Documentation menu

Documentation / Foundation / local

Local

Package
@wabbit/tome-local
Version
v0.7.0
npm install @wabbit/tome-local
First install from our registry?
  1. Add our registry to the .npmrc at the root of your project. Free packages install without a token.

    @wabbit:registry=https://npm.wabbit.com/
FoundationPreview

Tome local-business layer — the site's own business profile (a Payload global with hours, split shifts, dated overrides, named schedules, service areas, credentials and an expiring availability status), a cached public projection, a live-status source registry, a browser-safe open-state utility and a LocalBusiness JSON-LD builder.

Overview

A Tome site's record of itself as a place, and the time math every local-business surface needs. The package ships the local-business-profile global (who the business is, where it is, when it is open, where it works, what it is licensed for, and a short expiring availability status), a cached public projection of it that blocks, chrome and structured data read, a live-status source registry, a timezone-correct open-state utility that understands split shifts, dated overrides and named schedules, and a LocalBusiness JSON-LD builder that takes a neutral input so a site's own profile and a directory listing produce markup through one code path.

It also ships two opt-in collections. local-class-schedules is a shared timetable (classes, term, breaks, age bands and a level ladder) with an isomorphic @wabbit/tome-local/classes entry for the session arithmetic every class reader shares. local-locations is one record per place, for a business with more than one address, with an isomorphic @wabbit/tome-local/locations entry. A site that turns neither on sees no change. Not in this release: the local-testimonials and local-price-lists collections. They arrive once a site commits to consuming them.

Peer dependencies

PeerRangeOptional?
@wabbit/tome-core>=1.23.0 <2.0.0no — the profile global uses core's postal address group, field-shape vocabulary, capability check, layer registry and the shared unstable_cache loader.
payload>=3.67.0no — the global, its fields and hooks are Payload config.
next>=15.0.0yes — @wabbit/tome-local/server caches the profile with Next's unstable_cache, and the save hook revalidates through next/cache. Without Next, reads go straight to Payload and revalidation is skipped.

server-only is a runtime dependency, imported by @wabbit/tome-local/server alone.

Module surface

EntrySafe in a client bundleWhat it carries
@wabbit/tome-localno (Payload config)createLocalLayer, createLocalBusinessProfileGlobal, createLocalClassSchedulesCollection, createLocalLocationsCollection, localHoursField, localHoursOverridesField, localSchedulesField, validators, access helpers, constants, and every isomorphic subpath below re-exported
@wabbit/tome-local/hoursyescomputeOpenState, getOpenState, listWindows, formatOpenStateLabel, validateWeeklyHours, date-key helpers, hours types
@wabbit/tome-local/jsonldyesbuildLocalBusinessJsonLd, profileToLocalBusinessInput, serializeJsonLd, input types
@wabbit/tome-local/profileyesprojectLocalBusinessProfile, profileHoursSource, uncached readLocalBusinessProfile, findLocalProfileSlug, the LocalBusinessProfilePublic type, LOCAL_PROFILE_TAG
@wabbit/tome-local/classesyessessionsThisWeek, nextSessions, levelPosition, activeSpots, inAgeBand, the level helpers, normalizeLocalClassSchedule, uncached readLocalClassSchedule, findLocalClassSchedulesSlug, the schedule types
@wabbit/tome-local/live-statusyesresolveLiveStatus, the liveStatusSources registry, the built-in manual and rating sources
@wabbit/tome-local/locationsyeslocationHoursSource, locationPins, locationJsonLdInput, normalizeLocalLocation, finalizeLocalLocation, projectLocalLocations, uncached readLocalLocations and readLocalLocation, findLocalLocationsSlug, the location types
@wabbit/tome-local/serverno (server-only)getLocalBusinessProfile, getProfileHoursSource, getLiveStatus, getLocalClassSchedule, getLocalLocations, getLocalLocation, getLocationsStatus, resolvePrimaryHoursSource, cache tags

Server/client posture: @wabbit/tome-local/hours, @wabbit/tome-local/jsonld, @wabbit/tome-local/profile, @wabbit/tome-local/classes, @wabbit/tome-local/locations and @wabbit/tome-local/live-status import no payload, server-only, React or date library, so they run in a server component, a Payload field hook and a client island alike. Compute open state on the server for first paint, then recompute it in a client island, because a cached page otherwise tells visitors a shop is open when it closed an hour ago. @wabbit/tome-local/server is for server components and route handlers; code that runs inside Payload (hooks, jobs, the CLI) uses the uncached readers in @wabbit/tome-local/profile, because the server-only guard throws outside a React Server Components build.

Setting up the business profile

  1. Register the layer in payload.config.ts:
   import { createLocalLayer } from '@wabbit/tome-local'

   const local = createLocalLayer({
     schemaTypes: ['LocalBusiness', 'Organization'], // add your schema.org subtype, e.g. 'Restaurant' or 'Plumber'
   })

   export default buildConfig({
     // ...
     globals: [...otherGlobals, ...local.globals], // or plugins: [local.plugin]
   })

Then regenerate types and run your migration (Postgres) as for any new global.

  1. Fill it in the admin. The profile appears under Site → Business profile, in five tabs: Identity, Contact and location, Hours, Areas and credentials, Status and notices. The two fields every site needs are the trading name and the timezone (an IANA name such as America/Chicago); "open now" is computed there, never on the server or the visitor's device. Enter the phone in international form (+18165550100; spaces and brackets are stripped) and, optionally, the form customers see. Weekly hours take one row per opening window: two rows on one day are a split shift, and a close earlier than the open runs past midnight. Holidays go under Holidays and special hours; a second set of hours (a kitchen, a phone line) goes under Named schedules with a key such as kitchen.
  1. Who can edit it. Sessions holding local:edit-profile, which createLocalLayer grants to the admin and editor roles (grantRoles changes that), plus any legacy admin role. Saving goes live at once: there are no drafts, because hours waiting on a publish step are wrong on the site.
  1. Read it. The local blocks (@wabbit/tome-blocks-local-pack) pick the profile up on their own. Anywhere else, read the projection on the server:
   import { getLocalBusinessProfile } from '@wabbit/tome-local/server'
   import { buildLocalBusinessJsonLd, profileToLocalBusinessInput, serializeJsonLd } from '@wabbit/tome-local/jsonld'

   const profile = await getLocalBusinessProfile(payload)
   const ld = profile ? serializeJsonLd(buildLocalBusinessJsonLd(profileToLocalBusinessInput(profile, { siteUrl }))) : null
  1. Caching. Saving the profile revalidates LOCAL_PROFILE_TAG and the root layout. The local blocks embed profile data into page documents when they are read, so if your site caches its own page queries (with unstable_cache or tagged fetches), add LOCAL_PROFILE_TAG to their tags.

The profile

createLocalLayer(config) returns { globals, collections, plugin, slugs } (collections is empty unless classSchedules or locations is on). Its config speaks tome-core's LayerFactoryConfig vocabulary (adminGroup, slugs, and extraFields / fieldOverrides / omitFields / fieldOrder keyed by slug), with access and hooks in Payload's global shape, merged over the layer's own. Layer options: schemaTypes, credentialKinds, updateCapability (default local:edit-profile), grantRoles (default ['admin', 'editor'], false to grant none), mediaSlug (default media) dbName (default local_profile, short enough for Postgres's 63-character identifier limit once the versioned schedule tables nest) classSchedules (see below; default off) and locations (see below; default off).

GroupFields
Identityname (required), legalName, schemaType (from schemaTypes), description (≤300), logo, image, url, priceRange, foundingYear
Contact and locationphone { e164, display } (e164 validated as E.164; call links use it only), contactPageUrl (no public email field: contact goes through a form; a site that wants one adds it with extraFields), address (tome-core's postal group), addressVisibility (public / hidden), geo { lat, lng, source, precision }, timezone (required, validated as IANA), visitNotes { parking, transit, accessibility }
Hourshours, hoursOverrides (each row gets a server-written dateKey), schedules[] { key, label, hours, hoursOverrides }
Areas and credentialsserviceAreas[] { name, kind, postalCode?, center?, radiusMiles?, sameAs? } (radius needs a center and a radius), credentials[] { kind, label, issuer, number, showNumber, jurisdiction, validFrom, expiresOn, verifyUrl, sample } with a read-only status line (sample marks a demo or placeholder credential, projected so a block can label it "Sample"), socialProfiles[] { platform, url }
Status and noticesavailability { state, message, expiresAt, updatedAt } (expiresAt required unless state is none; updatedAt written by the server), responsePromise { value, unit, label }, ratingSummary { value, count, sourceLabel, sourceUrl, asOf }, footerNotice (rich text), urgentNotice { message, numbers[] { label, dial, display } } (see below)

Urgent notice. urgentNotice is the business's own wording and up to two labeled numbers for a visitor who may need help right away. It ships EMPTY: this package supplies no default wording, an empty notice renders nothing anywhere, and the projection then carries no urgentNotice key at all, so a profile that never fills it projects exactly as it did before the field existed. dial is digits with an optional leading plus, so a short service code is allowed (it is not held to the profile phone's E.164 rule). The wording is the site's to write and to have reviewed; it is available with or without locations.

The hours field factories are exported for reuse: localHoursField() and localHoursOverridesField() store exactly the shape of @wabbit/tome-directory's hours fields (same names, types, order and requiredness), plus the additive dateKey column, which { dateKey: false } leaves out. localHoursField({ validate: false }) drops the wrap-aware overlap validator for a caller that validates in its own hook.

Read access and redaction. The global is readable by anyone so the REST and GraphQL APIs can serve it, and every REST or GraphQL read by a session that cannot edit the profile is redacted in the document's own shape: a hidden address loses its street lines and coordinates, credentials past their expiry and numbers marked hidden are removed, and an expired availability status reads as none. Local API reads stay whole.

Class schedules (opt-in)

A row's enroll link and button text are enrollHref and enrollLabel; rows saved earlier hold them as enrolHref and enrolLabel, which stay in the schema (hidden in the admin) and are still projected until a save moves them to the new keys and empties them. Read the new key first. The default credential kinds list license next to the older licence, which is labeled "(legacy spelling)" in the admin. The old spelling is still accepted while stored data moves; writers store the new one.

A timetable that appears in more than one place (a finder, a pathway, a program page's next-step card, the phone bar) is one fact about the business, so it is stored once. createLocalLayer({ classSchedules: true }) builds the local-class-schedules collection (or pass an options object: access, hooks, dbName default local_cls, adminGroup, extraFields). The default is off and the returned config is then unchanged. Spread the collection into payload.config.ts next to the globals, or use the plugin, which appends both:

const local = createLocalLayer({ classSchedules: true })
export default buildConfig({ globals: [...local.globals], collections: [...local.collections] }) // or plugins: [local.plugin]

One document is one timetable (a site, or a location). Its term, breaks, timezone, weekStartsOn and classes[] are field for field what local-class-schedule stores inline, so a timetable moves between inline and collection without re-entry. It adds ageBands[] { key, label, sublabel?, pillLabel?, selectLabel?, saidLabel?, min?, max? } (the three optional labels word the band for the finder's pill, the timetable's filter and the finder's said line; each falls back to label) (the key goes in the URL, ?age=5-7) and levels[] { name, track, label?, ageBand, forWho?, movesUpWhen?, teaser?, blurb?, ageTag?, ratio?, href?, durationLabel? }, where a level's step and the ladder's length come from its order within its track. The three optional text fields word a level for the class pathway: teaser (one or two sentences, shown when the level is the next one up; empty falls back to forWho), blurb (one line on the level's card in place of "Who it's for" and "Moves up when"; empty keeps the pair) and ageTag (a short tag beside the name, "Walking–3"). All three are empty by default and change nothing until set. A class names its level in its level field. Saving checks that band keys are unique and URL-safe, level names are unique and name an existing band, a class's level (once levels exist) names a level, and a spots status carries an expiry.

Access and drafts. Published documents are readable by anyone; drafts and the versions endpoint need local:edit-schedules, as do create, update and delete. createLocalLayer grants it with the profile capability to grantRoles. Drafts are on (autosave off), so next term's timetable can be staged without going live. Saving or deleting revalidates localClassScheduleTag(id), LOCAL_CLASS_SCHEDULES_TAG and the root layout.

Not a booking engine. The document stores no capacity, attendee or payment. Spots are a hand-typed claim with a required expiry.

Locations (opt-in)

The profile is one global with one address, one set of hours and one status, and that fits nearly every site. A group practice with three offices, a restaurant with a second room or a trade with two yards needs one record per place. createLocalLayer({ locations: true }) builds the local-locations collection (or pass an options object: access, hooks, dbName default local_loc, adminGroup, editCapability default local:edit-locations, grantRoles, layoutBlocks for a per-location page layout, extraFields). The default is off: no collection, no new field, and the returned config is unchanged. LocalLayer.slugs.locations carries the resolved slug.

const local = createLocalLayer({ locations: true })
export default buildConfig({ globals: [...local.globals], collections: [...local.collections] }) // or plugins: [local.plugin]

The profile says who; a location says where. Name, logo, schema type, social profiles, footer notice and response promise stay on the profile. A location owns its address (and whether it is shown), coordinates, timezone (required), phone, visit notes, weekly hours and dated overrides, availability, and optionally its own credentials, service areas and rating citation. With locations on, the profile keeps the central desk's own phone and hours. Rating citation and service areas read the location's when set, otherwise the profile's. Credentials are the location's own: a credentials block pointed at a place reads that place.

FieldNotes
name, slugThe place's name and its unique page address (made from the name when empty).
primaryAt most one; saving a second refuses and names the location that holds it.
order, archived, sampleLower numbers first; archiving takes a place off the site and keeps it; sample marks a placeholder.
summary, photo, photoAlt, photoLabelOne line for cards, and a picture with its label ("Illustrative photo").
phone, contactPageUrl, address, addressVisibility, geo, timezone, visitNotesThe profile's own fields, from the same builders (fields/place).
hours, hoursOverrides, availabilityThe profile's hours builders and its availability group, with the same required expiry.
credentials, serviceAreas, ratingSummary, bookingOptional. booking { label, href, newTab } is the book action, often one scheduler URL per office.

Access. Editors (local:edit-locations, granted to admin and editor) read and write everything. Everyone else reads published, unarchived locations only, as a where-constraint, so a draft or an archived place is never served over REST or GraphQL; a REST or GraphQL read also blanks a hidden address's street lines and coordinates. Writes go through sessionHasCapabilityOrLegacyAdmin, never bare authenticated. Drafts are on (autosave off). Delete is refused while a record or a block points at the location (the hook reads the config for relationship fields to this collection, at any depth, and skips what it cannot query); archive it instead. Saving or deleting revalidates localLocationTag(id), LOCAL_LOCATIONS_TAG and the root layout, and a failure never fails a save.

import { getLiveStatus, getLocalLocations, getLocationsStatus, resolvePrimaryHoursSource } from '@wabbit/tome-local/server'
import { locationPins } from '@wabbit/tome-local/locations'

const locations = await getLocalLocations(payload) // published, unarchived, by order; [] when the collection does not exist
const all = await getLocationsStatus(payload) // every place's status, each in its own timezone
const here = await getLiveStatus(payload, { location: 'millbrook' }) // that place's line; without `location`, exactly as before
const hours = await resolvePrimaryHoursSource(payload) // the primary location's, else the profile's
const pins = locationPins(locations) // no pin for a place whose address is hidden
  • Open state across zones. Each location computes against its own timezone, so a list spanning two zones (and a clock-change night in either) shows each place's own "open until", never one shared answer. locationHoursSource(location) is a LocalHoursSource and an OpenStateSource over the same profileHoursSource.
  • `resolvePrimaryHoursSource` returns the location marked primary, falling back to the profile when none is marked, when no locations exist, or when the primary has no hours of its own. It is what chrome's callWhen and hours-aware actions read. A site that wants the central desk's hours reads getProfileHoursSource.
  • A location's status is its own: the profile's availability line is never shown as a place's. A status past its expiry does not render.
  • Hidden addresses stay hidden in every output. A hidden location's entry has no address, no geo and no street lines; locationPins emits no pin for it; locationJsonLdInput drops the street and the coordinates.
  • `locationPins(locations, { href })` returns pins in @wabbit/tome-maps' MapPin shape without importing that package.
  • `locationJsonLdInput(profile, location, { siteUrl, locationCount })` merges the profile's identity with the place and adds parentOrganization when locationCount is more than one. Wiring a route to emit it is the site's job.

@wabbit/tome-local/classes — the session arithmetic

import { nextSessions, sessionsThisWeek } from '@wabbit/tome-local/classes'
import { getLocalClassSchedule } from '@wabbit/tome-local/server'

const schedule = await getLocalClassSchedule(payload, id) // published, cached under its tags; null when absent or unpublished
const next = schedule && nextSessions(schedule, { level: 'Level 1', limit: 3, now: new Date(), fallbackTimezone: profile?.timezone })
  • sessionsThisWeek(schedule, { now }) is the current week's occurrences (week start from weekStartsOn), with breaks and dates outside the term removed. nextSessions(schedule, { now, level?, ageBand?, limit?, withRoom? }) walks forward across weeks, skips breaks and stops at the term's end; an unknown ageBand matches nothing, and withRoom skips a class whose live spots line says full (a waitlist still counts).
  • An occurrence is plain serializable data: uid, the class row, dateKey, start, end, startsAt and endsAt (ISO instants; null when the schedule has no timezone, in which case dates and times read as UTC), finished, spots and level { name, track, step, steps }. Times are wall clock in the schedule's timezone (the document's, else fallbackTimezone) and DST-correct; profileOverrides joins the profile's closed dates to the breaks unless breaksFromProfile is off.
  • activeSpots(row, now) is the spots rule: a status needs an unexpired expiry, a count below one is nothing, and nothing is ever inferred. On an occurrence the line speaks only for sessions that start before it expires.
  • levelPosition(levels, name), levelsOnTrack, levelsForBand, nextLevel and inAgeBand(row, band) are the ladder and band helpers.
  • This entry holds arithmetic only: labels, time text and calendar files stay with the block that renders them. readLocalClassSchedule and findLocalClassSchedulesSlug are the uncached readers for code inside Payload.

@wabbit/tome-local/profile — the public projection

import { profileHoursSource, readLocalBusinessProfile } from '@wabbit/tome-local/profile'
import { getOpenState } from '@wabbit/tome-local/hours'

const profile = await readLocalBusinessProfile(payload, { req }) // uncached; inside a Payload hook, pass req
if (profile) getOpenState(profileHoursSource(profile), new Date(), 'kitchen')

LocalBusinessProfilePublic is plain serializable data (no Date, no row ids) and is itself an OpenStateSource. The projection (projectLocalBusinessProfile(doc, { now })) drops admin-only sub-fields, removes credentials past their expiresOn (a credential is current through its expiry date in the business timezone), removes credential numbers marked hidden, resolves an availability status past its expiresAt (or without one) to { state: 'none' }, reduces a hidden address to locality, region, postal code and country with no coordinates, and reduces a populated upload to { url, alt, width, height }. An unsaved profile projects to null. The clock-independent half (normalizeLocalBusinessProfile) is what a cache may hold; finalizeLocalBusinessProfile(profile, now) applies the time rules on top. findLocalProfileSlug(payload) finds the global by a marker in its config, so a renamed slug works and a site without the layer is detected without a query.

profileHoursSource(profile) returns a LocalHoursSource (getWeeklyHours(key?), getOverrides(key?), getTimezone()) that is also an OpenStateSource; an unknown schedule key reads as no hours, never as the primary hours.

@wabbit/tome-local/server — cached reads

import { getLiveStatus, getLocalBusinessProfile, LOCAL_PROFILE_TAG } from '@wabbit/tome-local/server'

const profile = await getLocalBusinessProfile(payload) // LocalBusinessProfilePublic | null
const status = await getLiveStatus(payload, { mode: 'availability' })

getLocalBusinessProfile caches the clock-independent projection under LOCAL_PROFILE_TAG (and global:<slug>), which the profile's afterChange hook revalidates along with the root layout, and applies the time rules after the cache on every call. Outside a Next request it reads Payload directly. getProfileHoursSource(payload) and getLiveStatus(payload, opts) build on it. getLiveStatus(payload, { location }) answers for one place (a slug, or an entry already read) against that place's own timezone, hours and availability.

@wabbit/tome-local/live-status — one line of live proof

import { liveStatusSources, resolveLiveStatus } from '@wabbit/tome-local/live-status'

liveStatusSources.register('my-source', { id: 'my-source', priority: 10, resolve: ({ profile, now }) => null })
const status = await resolveLiveStatus('auto', { profile, now: new Date() })
// → { kind, text, tone, at?, expiresAt?, href?, sourceId } | null
  • open-state words the profile's hours (or a named schedule, scheduleKey) with formatOpenStateLabel; no hours, no status.
  • availability walks a chain, lowest priority first, and returns the first source with something to say: the built-in manual source (50) returns the profile's availability message while it is active, and rating (80) returns "4.9 on Google · 212 reviews" when the citation names a source and a count (ratingTemplate and locale reword it). A package such as a booking engine registers its own source at boot; a registered id replaces a built-in of the same id, and a source that throws is skipped.
  • auto is open-state when the profile has hours, else availability.
  • A LiveStatus carries expiresAt when it stops being true, so a client island can stop showing it on a cached page.

@wabbit/tome-local/hours — open now, closes at, opens next

import { computeOpenState, formatOpenStateLabel } from '@wabbit/tome-local/hours'

const state = computeOpenState({
  hours: [
    { dayOfWeek: '1', opens: '11:00', closes: '14:00' }, // lunch
    { dayOfWeek: '1', opens: '17:00', closes: '22:00' }, // dinner
  ],
  hoursOverrides: [{ date: '2026-12-25', closed: true, label: 'Christmas' }],
  timezone: 'America/Chicago',
})
// → { openNow, closesInMinutes?, opensAt?, closesAt?, current?, next?, closedLabel? }

formatOpenStateLabel(state, { timezone: 'America/Chicago', locale: 'en-US' })
// → "Open now · closes at 10 PM" | "Opens tomorrow at 11 AM" | "Closed today · Christmas" | null
  • Stored shape. Weekly rows are { dayOfWeek: '0'–'6', opens: 'HH:mm', closes: 'HH:mm', closed? } in the business's IANA timezone ('0' is Sunday). Several rows per day are split shifts, and every row counts. closes: '24:00' is end of day; a closes earlier than opens runs past midnight.
  • Overrides replace the weekly rows for their date. Several rows on one date give several windows; a closed row closes the date. date may be a bare YYYY-MM-DD or the ISO instant a database returns for a date-only field; an explicit dateKey wins when present. toDateOnlyKey reads a date-only value as its UTC calendar date, which is what both Payload's admin day picker (12:00 UTC) and an API write of a bare date (00:00 UTC) store; the profile's dateKey is written the same way.
  • DST. Wall-clock times resolve per date. A time inside a spring-forward gap moves forward past the gap, and an ambiguous fall-back time takes the first occurrence.
  • Merging. Touching or overlapping windows merge before current is chosen, so a business open through midnight reports its real closing time.
  • getOpenState(source, now?, scheduleKey?) reads any { timezone, hours, hoursOverrides, schedules? } record, the profile projection included; a scheduleKey selects a named schedule such as a kitchen or phone line.
  • listWindows({ ..., from, days }) lists every concrete window (one per row) for week views.
  • validateWeeklyHours(hours) is a wrap-aware save-time validator: it rejects bad times, opens === closes, and any overlap anywhere in the week, including an overnight row running into the next morning.
  • toLocalDateKey(instant, timezone) gives the calendar date there; isValidTimeZone(zone) checks an IANA name.

@wabbit/tome-local/jsonld — LocalBusiness structured data

import { buildLocalBusinessJsonLd, serializeJsonLd } from '@wabbit/tome-local/jsonld'

const ld = buildLocalBusinessJsonLd({
  schemaType: 'Plumber',
  name: 'Example Plumbing',
  telephone: '+18165550100',
  address: { city: 'Kansas City', region: 'MO', country: 'US', visibility: 'hidden' },
  timezone: 'America/Chicago',
  hours: [{ dayOfWeek: '1', opens: '08:00', closes: '17:00' }],
  areaServed: [{ name: 'Within 25 miles', kind: 'radius', center: { lat: 39.1, lng: -94.58 }, radiusMiles: 25 }],
})

// <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: serializeJsonLd(ld) }} />
  • Every property is conditional on data; nothing is defaulted, including addressCountry.
  • openingHoursSpecification has one entry per weekly row (split shifts give two for one day), 24:00 is written as 23:59, and overrides within overrideHorizonDays (default 30) carry validFrom / validThrough, with closed dates as 00:00–00:00.
  • areaServed maps city to City, county and region to AdministrativeArea, postal-code to a Place with a postal address, and radius to a GeoCircle in meters.
  • A hidden address emits locality, region, postal code and country only, and suppresses geo.
  • schemaType: 'Organization' drops hours, geo and priceRange.
  • profileToLocalBusinessInput(profile, { siteUrl }) maps the profile projection: telephone from phone.e164, url from the profile or the site, relative logo and image URLs made absolute against siteUrl, sameAs from the social profiles, areaServed from the service areas.
  • It never emits `aggregateRating` or `review`, and the profile mapper maps nothing rating-shaped: ratingSummary is a visible citation. A site with a verified third-party review integration emits its own.
  • serializeJsonLd escapes < and the U+2028/U+2029 separators, so an editor field containing </script> cannot break out of the tag.

What this package deliberately does not do

No booking, slots or appointments (a booking engine plugs into liveStatusSources and reads LocalHoursSource); no review collection or rating aggregation; no geocoding (a location's coordinates are typed); no multiple locations unless locations is on, and even then the profile stays one per site and the identity record; no "nearest office" by distance; no vertical policy. A consumer that lists other businesses keeps its own compliance rules (which subtypes, what to omit) in the adapter it writes from its record to LocalBusinessInput.

Exports

Import path
@wabbit/tome-local
@wabbit/tome-local/hours
@wabbit/tome-local/jsonld
@wabbit/tome-local/classes
@wabbit/tome-local/profile
@wabbit/tome-local/locations
@wabbit/tome-local/live-status
@wabbit/tome-local/server

Changelog

0.7.xMinor

  • A class row can now carry a price.

    The new price group holds a type (one price, from a price, a range, free, or price on request), the amounts in whole minor units, and an optional "per" text such as "per person". A schedule gets a currency field (an ISO 4217 code, USD when empty).

    An empty price type shows nothing, and "Free" is only ever something an editor chooses. normalizeLocalClassSchedule keeps the price and drops amounts a type doesn't use, and a type missing its amounts becomes no price rather than zero.

    New exports validateClassPrices, validateMinorUnits, validateCurrency and LOCAL_CLASS_PRICE_MODES, and the types LocalClassPrice and LocalClassPriceMode. The shared readers pass the price through on each occurrence.

    Rows without a price behave exactly as before.

0.6.xMinor

  • A save now moves renamed keys to their American names and empties the old ones.

    This is the second of three steps toward American spelling in stored values.

    On the class schedule block and collection, enrolLabel, enrolHref, enrol and labels.enrol move to enrollLabel, enrollHref, enroll and labels.enroll. On the event list board, labels.cancelled moves to labels.canceled.

    Anything that still writes an old key lands in the new one.

    This fixes clearing a field: a value sent for the new key, even a blank one, wins and the old value is emptied, so it no longer comes back on the next read or shows on the public page.

    The old group and label no longer have default values, so a new block stores nothing under them. Renderers still read the old keys, so a block that hasn't been saved or backfilled looks the same.

    The class schedule and event calendar demos use the new names.

    BREAKING: @wabbit/tome-blocks-local-pack now needs @wabbit/tome-local 0.6.0 or later, which exports these save hooks from @wabbit/tome-local/classes.

0.5.xMinor

  • New opt-in local-testimonials collection, which shows visitors only quotes with consent recorded.

    Neutral quotes (quote, name, role, company, image, publishedAt, order, complianceLabel) with a consent group (given, and the date it was given). The testimonial block reads it through its testimonialsCollection option.

    Turn it on with createLocalLayer({ testimonials: true }); off (the default), nothing changes: no collection, no capability, and slugs carries no testimonials key, held by a test. Visitors read only published quotes with consent recorded (a where-constraint, so a draft or an unconsented quote never leaves the server over REST or GraphQL); editors need local:edit-testimonials, granted to the layer's staff roles.

    Drafts are on, dbName defaults to local_tst. SQL sites that turn it on need a migration for the new tables; Mongo sites need none.

2 fixes (0.5.1 – 0.5.2)
  • 0.5.2
    The enrol names and two option values now accept their American spellings.

    This is the first of three steps, and nothing that gets written changes yet.

    Class schedule rows and the class schedule block gain enrollLabel, enrollHref, the enroll link group and the labels.enroll copy key. The renderer reads each new key first and falls back to the old enrol key, field by field.

    The old fields are hidden in the admin, not removed, so a save never drops a stored value, and the new fields show the stored value while the new key is empty.

    The credential kind license joins licence, and the price list tag house-favorite joins house-favourite. A credentials strip claim bound to either spelling of the kind matches both, and both tag values show the same label.

    The admin shows both options, because Payload cannot hide one select option; the old one is labeled "(legacy spelling)".

  • 0.5.1

    Admin labels, field descriptions, demo content and messages now use American spellings.

0.4.xMinor

  • New opt-in local-locations collection: one record per place, each with its own address, phone, hours and status, while the business profile stays the identity record.

    Turn it on with createLocalLayer({ locations: true }); off (the default), nothing changes, and a test holds the profile's schema against a snapshot taken before the change. The place-shaped fields are the profile's own builders, now shared with the collection without changing the profile's field order, names or types.

    Reads from @wabbit/tome-local/server: getLocalLocations, getLocalLocation, getLocationsStatus (every place's status, each in its own timezone) and resolvePrimaryHoursSource (the primary location's hours, else the profile's); getLiveStatus takes an optional location. New @wabbit/tome-local/locations entry: locationHoursSource, locationPins (no pin for a place whose address is hidden), locationJsonLdInput (with parentOrganization when there is more than one place) and uncached readers.

    At most one location is primary; a published, unarchived place is all a visitor can read; a place a record or block still points at is archived, not deleted.

    The profile gains an optional urgentNotice (wording and up to two labeled numbers). It ships empty with no default wording, an empty one renders nothing and projects no key, and it works with or without locations.

0.3.xMinor

  • Add an opt-in shared class timetable: the local-class-schedules collection and a ./classes entry for the session arithmetic.

    createLocalLayer({ classSchedules: true }) builds one timetable per site or location (amendment A3): classes, term, breaks, timezone, age bands (ageBands[]) and a level ladder (levels[], where order within a track is the step). Drafts are on, the public reads published documents only, and writes need the new local:edit-schedules capability, granted to the same roles as the profile capability.

    createLocalLayer now also returns collections (empty unless the option is on), and LocalSlugs gains classSchedules.

    The new isomorphic @wabbit/tome-local/classes exports sessionsThisWeek, nextSessions, levelPosition, activeSpots, inAgeBand and the schedule types. getLocalClassSchedule in ./server reads the cached document.

    A spots line on an occurrence speaks only for sessions that start before it expires.

    ageBands[] carries three optional wording fields, pillLabel, selectLabel and saidLabel (the finder's pill, the timetable's filter option and the finder's said line), each falling back to label when empty; the normalizer and the ./classes LocalAgeBand type carry them. Optional with no defaults: existing documents are unchanged, and the new fields add columns to the collection's tables, so a site with migrations generates one.

    Profile credentials gain an optional sample checkbox, projected so a block can label a demo credential "Sample".

    Purely additive: nothing changes for a site that does not turn the option on, and no peer is added or tightened.

  • A level in the shared class timetable can carry a teaser sentence, a one-line card blurb and a short age tag.

    Three optional text fields on levels[] in the local-class-schedules collection, all empty by default:

    • teaser: one or two sentences a class pathway shows when the level is the next one up. Empty falls back to forWho.
    • blurb: one line shown on the level's card in place of "Who it's for" and "Moves up when". Empty keeps the pair.
    • ageTag: a short tag beside the level's name, such as "Walking–3".

    The normalizer and the ./classes LocalLevel type carry them. Purely additive: existing documents are unchanged, and the new fields add columns to the collection's level table, so a site with migrations generates one.

    No peer is added or tightened.

1 fix (0.3.1)
  • 0.3.1

    README: subpath and file mentions are written package-qualified (for example @wabbit/tome-x/render) or as code text, so crawlers no longer resolve them as site URLs.

0.2.xMinor

  • New: the site's business profile, a Payload global that editors fill in once in the admin and that blocks and structured data read.

    It holds the name, contact details, address, timezone, hours (split shifts, holidays and named schedules), service areas, credentials, an expiring availability status, a response promise and a rating citation, and is read through a cached public projection.

    BREAKING: @wabbit/tome-core (>=1.17.0 <2.0.0) and payload (>=3.67.0) are now required peers, because the root entry is Payload config. next (>=15.0.0) is an optional peer.

    Sites that import only ./hours or ./jsonld already have both in any Tome install; nothing else changes for them.

    • `createLocalLayer(config)` returns { globals, plugin, slugs } and registers the local-business-profile global (admin group "Site", no drafts, so edits go live on save). It grants the local:edit-profile capability to admin and editor (grantRoles changes that). Options: schemaTypes, credentialKinds, updateCapability, mediaSlug, dbName, plus adminGroup, slugs, access, hooks, extraFields, fieldOverrides, omitFields and fieldOrder.
    • Validation on save: the phone is stored in E.164 (spaces and punctuation stripped), the timezone must be an IANA name, weekly hours may not overlap anywhere in the week (overnight windows included), schedule keys are unique, a service-area radius needs a center, and any availability status other than "none" needs an expiry. The server writes each override's dateKey and the availability updatedAt.
    • Privacy: the global is publicly readable over REST and GraphQL, but a visitor's read never shows a hidden street address or its coordinates, an expired credential, a credential number marked hidden, or an expired availability status.
    • `./profile` (new, isomorphic): projectLocalBusinessProfile, profileHoursSource (a LocalHoursSource that also works with getOpenState(profile, now, 'kitchen')), the uncached readLocalBusinessProfile for use inside Payload hooks, findLocalProfileSlug, and the LocalBusinessProfilePublic type.
    • `./server` (new): getLocalBusinessProfile(payload), cached under LOCAL_PROFILE_TAG and revalidated when the profile is saved, with expiry rules applied on every read; getProfileHoursSource and getLiveStatus.
    • `./live-status` (new, isomorphic): resolveLiveStatus('open-state' | 'availability' | 'auto', ctx) and the liveStatusSources registry. The availability chain runs registered sources by priority, then the built-in manual status, then the rating citation, and returns null rather than guess.
    • `./jsonld`: profileToLocalBusinessInput(profile, { siteUrl }) maps the profile to buildLocalBusinessJsonLd's input. A hidden address emits no street or coordinates, and no rating is ever emitted.
    • Field factories: localHoursField() and localHoursOverridesField() store the same shape as the directory's hours fields, with an additive dateKey column; localSchedulesField() adds named schedules.
1 fix (0.2.1)
  • 0.2.1
    The business-profile reader now uses tome-core's shared loadUnstableCache() instead of its own copy.

    The @wabbit/tome-core peer floor rises to 1.23.0, the release that adds it. No behavior change.

0.1.xMinor

  • New package: @wabbit/tome-local, a browser-safe open-state utility and a LocalBusiness JSON-LD builder for local-business sites.
    • `./hours`: computeOpenState returns openNow, closesInMinutes and opensAt, plus closesAt, the current and next windows, and a closedLabel for a closed-today override. It handles several windows per day (split shifts), several override windows per date, overrides stored as a bare YYYY-MM-DD or as the ISO instant a database returns for a date-only field, and daylight-saving transitions (a time inside a spring-forward gap moves past the gap; an ambiguous fall-back time takes its first occurrence). Touching windows merge, so a business open through midnight reports its real closing time. Also getOpenState (any record with hours, plus named schedules), listWindows, formatOpenStateLabel ("Open now · closes at 10 PM", "Opens tomorrow at 11 AM", "Closed today · Holiday", with "today" in the business timezone), a wrap-aware validateWeeklyHours, the toLocalDateKey / toDateOnlyKey helpers and the LocalHoursSource interface. No payload, server-only, React or date-library import.
    • `./jsonld`: buildLocalBusinessJsonLd builds schema.org LocalBusiness (or a subtype, or Organization) markup from a neutral input: conditional fields only, openingHoursSpecification per weekly row with dated overrides inside a horizon, areaServed as City / AdministrativeArea / Place / GeoCircle, a hidden-address mode that omits the street line and coordinates, and never aggregateRating or review. serializeJsonLd escapes the output for an inline script tag.
1 fix (0.1.1)
  • 0.1.1
    Published packages now contain compiled JavaScript and type declarations under a one-line license banner, and no longer include source maps.

    What you install: one compiled .js (ESM) and .cjs (CommonJS) file per source module, its .d.ts / .d.cts declarations, and the stylesheets, fonts and other assets a package already shipped. Every JavaScript module opens with a comment naming the package and its license: /*! @wabbit/<package> — © Wabbit, LLC. Wabbit Tome Commercial License (see LICENSE.md). Not for redistribution. */.

    The .map files and the sourceMappingURL comments that pointed at them are gone, which roughly halves the size of each tarball.

    Debugging: the code is still unbundled and unminified, one readable file per module, so a stack trace points at real code with real names. Line numbers in a stack trace are one higher than before, because of the banner line.

    A 'use client' directive stays the first statement of its module (the banner is a comment above it), so React Server Component boundaries are unchanged.

    No API change, no runtime behavior change, and nothing to do on upgrade.

    In @wabbit/tome-blocks-gallery, the source snapshots extractGallerySource writes from an installed pack leave out the license banner line, so a component or config snapshot starts at the code and a paid block's preview shows its first 15 lines of real code.

Full changelog across all packages