Documentation menu
Documentation / Directory engine / directory
Directory
npm install @wabbit/tome-directoryFirst install from our registry?
Get a registry token from your credentials page. You need a purchase that includes this package, or a Craft Library membership.
Add the registry and your token to the
.npmrcat the root of your project, with your token in place ofYOUR_TOKEN:@wabbit:registry=https://npm.wabbit.com/ //npm.wabbit.com/:_authToken=YOUR_TOKEN
Tome local-directory layer — markets, listings, claims, reviews, favorites, promotions, and an inbound menu-item seam, plus a defineListingType registry and a DirectoryTenantPolicy contract so vertical rules live in the consuming site, never in the layer.
Overview
Tome local-directory layer — markets, listings, claims, reviews, favorites, promotions, and an inbound menu-item seam, plus a defineListingType registry so a consumer site adds real per-type schema without touching the layer, and a DirectoryTenantPolicy contract so vertical rules live in the consuming site, never in the layer. Description copied verbatim from package.json.
Layer: domain (per the repo's ARCHITECTURE.md § The Layer Model), family directory, tier pro. Depends on @wabbit/tome-core (identity, auth, fields/address, fields/slug), @wabbit/tome-accounts (the claimed-owner tenant), @wabbit/tome-workflow (claimTransition drives claim/review/promotion state), @wabbit/tome-local (the open-state utility); optional @wabbit/tome-economy (tier subscriptions — paid listing tiers require the Commerce engine), optional @wabbit/tome-forms / @wabbit/tome-intake for a guided claim-submission front end.
Peer dependencies
Peer ranges, copied from package.json:
| Peer | Range | Optional? |
|---|---|---|
payload | >=3.67.0 | no |
@wabbit/tome-core | >=1.17.0 <2.0.0 | no |
@wabbit/tome-local | >=0.1.0 <1.0.0 | no — computeOpenState is @wabbit/tome-local/hours' open-state utility, re-exported from @wabbit/tome-directory/server. |
@wabbit/tome-maps | >=0.1.0 <1.0.0 | no — type-only. @wabbit/tome-directory/maps extends the neutral provider types in @wabbit/tome-maps/types; no runtime code imports it. |
@wabbit/tome-accounts | >=0.3.0 <1.0.0 | no |
@wabbit/tome-economy | >=0.18.0 <1.0.0 | yes — needed for paid listing tiers, which require the Commerce engine. Only the @wabbit/tome-directory/economy subpath imports it; the root entry and every other subpath load without it. |
@wabbit/tome-workflow | >=0.3.0 <1.0.0 | no |
@wabbit/tome-forms | >=0.3.0 <1.0.0 | yes |
@wabbit/tome-intake | >=0.3.0 <1.0.0 | yes |
react | >=19.0.0 | yes — type-only (DirectoryMapProvider.MapView's ComponentType). The layer renders nothing itself; concrete map providers ship in @wabbit/tome-blocks-directory-pack. |
60-second quickstart
The example below is a generic trades directory (plumbers, electricians, HVAC — no licensing or age-gate compliance weight) on purpose. A regulated vertical (cannabis, medical, alcohol) supplies its own DirectoryTenantPolicy with the age gate turned on and its real registry and content rules.
import { buildConfig } from 'payload'
import {
createDirectoryLayer,
defineListingType,
defineDirectoryTenantPolicy,
} from '@wabbit/tome-directory'
// Paid listing tiers only — requires the Commerce engine (@wabbit/tome-economy
// installed). A directory with no paid tiers drops this import and the
// registerEconomySubscriptionHandlers call below.
import { registerDirectorySubscriptionHandlers } from '@wabbit/tome-directory/economy'
const tradesShop = defineListingType({
value: 'trades-shop',
label: 'Trades Shop',
labelPlural: 'Trades Shops',
typeFields: [
{ name: 'trade', type: 'select', options: ['plumbing', 'electrical', 'hvac'], required: true },
{ name: 'licensedInsured', type: 'checkbox' },
],
requiredRegistry: false,
detailRoute: '/trades-shop/[slug]',
})
const tenantPolicy = defineDirectoryTenantPolicy({
// sponsoredLabel defaults to 'Sponsored'
ageGate: { enabled: false, minAge: 18, mode: 'dob', logResultNotDob: true },
registry: {
name: 'State Contractor License Board',
sourceUrl: 'https://example.gov/contractor-lookup',
requireVerifiedLicenseForTypes: ['trades-shop'],
reverifyEveryDays: 180,
},
content: { prohibitedPatterns: [], requiredDisclaimers: [], allowPriceDisplay: true, imageReviewQueue: false },
reviews: {
requireLogin: true,
requireVerifiedVisitForBadge: false,
insiderDisclosureRequired: true,
moderation: 'post',
maxPerAuthorPerListingPerDays: 30,
},
promotions: { requireEndDate: true, paidSurfacesOwnerSourceOnly: true },
privacy: { storeDob: false, preciseGeolocation: false, adPixelsOnListingPages: false },
dataRetention: { menuItemTtlHours: 24, gateEventRetentionDays: 90 },
// billing.graceDays defaults to 7
})
const directory = createDirectoryLayer({
membersSlug: 'members',
accountsSlug: 'accounts',
membershipsSlug: 'memberships',
listingTypes: [tradesShop],
tenantPolicy,
// REQUIRED — the version `claimBeforeValidate`/the claim-submission flow
// requires acceptedTerms.version to equal exactly.
currentTermsVersion: '1',
// REQUIRED only when tenantPolicy.ageGate.enabled is true — this trades
// example leaves the gate off, so it is omitted here. A regulated vertical
// supplies a real secret from server env, never a literal in source.
// ageGateSecret: process.env.DIRECTORY_AGE_GATE_SECRET,
})
directory.registerHandlers.onListingClaimed(async (event) => {
// send a welcome email, unlock upsell copy, etc.
})
export default buildConfig({
// db, secret, editor, admin: as in any Payload config
collections: [...existingCollections, ...directory.collections],
endpoints: [...existingEndpoints, ...directory.endpoints],
onInit: async (payload) => {
// Paid listing tiers: wires the four economy subscription-lifecycle
// handlers so a checkout/renewal/cancel/payment-failed event stamps
// `tier` on the right listing. See "Subscription checkout contract"
// below for the `metadata` shape a directory checkout MUST pass.
directory.registerHandlers.registerEconomySubscriptionHandlers(payload, registerDirectorySubscriptionHandlers)
},
})Server-side data access comes from the @wabbit/tome-directory/server subpath:
import { findListingsNear, resolveListingEntitlements } from '@wabbit/tome-directory/server'API surface
Seven export subpaths: . (config-time — factory, access, claims, moderation, age-gate, event bus, hooks context/geohash, jobs, fields, photo attestation, tenant-policy registry, types), @wabbit/tome-directory/server (server-only data access, marked with server-only), @wabbit/tome-directory/maps (map/geocoder provider types only — no runtime code), @wabbit/tome-directory/listing-types (the listing-type registry alone, with no Payload in its import graph, for client-reachable code; the root re-exports the same functions), @wabbit/tome-directory/menu (the inbound menu-publish HMAC seam), @wabbit/tome-directory/endpoints (one factory, createDirectoryEndpoints, which returns the layer's four Payload endpoints), @wabbit/tome-directory/economy (subscription-lifecycle tier stamping — the only subpath that imports the optional @wabbit/tome-economy peer; it is not re-exported from the root).
| Group | Exports |
|---|---|
| Layer factory | createDirectoryLayer, composeTypeGroups |
| Collection factories | createMarketsCollection, createListingsCollection, createClaimsCollection, createReviewsCollection, createFavoritesCollection, createPromotionsCollection, createMenuItemsCollection, createListingStatsCollection, createPhotoAttestationsCollection (+ their *CollectionConfig types). Called without an access bundle, every factory fails closed: each operation is staff-only (directoryStaff). Public reads (status-filtered listings, markets, reviews, promotions) come from the real bundle — pass access (e.g. from createDirectoryAccess) or use createDirectoryLayer, which always does. |
| Listing-type registry | defineListingType, listingTypeRegistry, registerListingType, getListingType, hasListingType, getAllListingTypes, resetListingTypeRegistry |
| Tenant policy | defineDirectoryTenantPolicy, DEFAULT_ENTITLEMENTS, pickEntitlementTable (the per-listing-type ladder lookup) (+ DirectoryTenantPolicyInput, DirectoryEntitlementTable) |
| Tenant-policy registry | setActiveTenantPolicy, getActiveTenantPolicy, resetActiveTenantPolicy — createDirectoryLayer calls setActiveTenantPolicy once; server query functions that omit their own tenantPolicy argument fall back to it |
| Event bus | onListingClaimed/dispatchListingClaimed, onTierChanged/dispatchTierChanged, onReviewApproved/dispatchReviewApproved, onPromotionPublished/dispatchPromotionPublished, onListingSuspended/dispatchListingSuspended, resetDirectoryEventBus |
| Access | directoryStaff, directoryStaffFieldLevel, directoryStaffAccess(ctx?) and lockedFieldAccessFor(ctx?) (the context-aware factories that honor a custom staffPredicate), isStaffUser, isSystemWrite, listingOwnerAccess, lockedFieldAccess, publicStatusOrStaff, createDirectoryAccess, DIRECTORY_LOCKED_LISTING_FIELDS, buildListingFieldLocks, publicListingProjection, ownership resolvers (resolveCallerMember, resolveOwnedAccountIds, resolveOwnedListingIds, resolvePublishedListingIds), helpers relId(value) (a relationship's id from a raw id, { id } or populated doc; null when absent) and sha256Hex(input), types DirectoryLayerContext, DirectoryLockedListingField, DirectoryPublicListing, DirectoryAccessBundle, DirectoryAccessBundles |
| Claims | submitClaim, verifyClaim, approveClaim, rejectClaim, revokeClaim, requestOwnershipTransfer (+ their arg/result types) |
| Moderation | approveReview, rejectReview, removeReview, respondToReview, reportReview, plus the takedown shape/transitions/stores — see "Takedown store" below |
| Age gate | verifyAgeGate, createAgeGateCookie/readAgeGateCookie, createAgeGateVerifyHandler, isAgeGatePassed |
| Hooks (context + geohash only) | resolveHookContext, isStaffOrAdmin (async — delegates to isStaffUser, so super-admin, un-populated role ids and a custom staffPredicate all count; await it), isHookSystemWrite (aliased — @wabbit/tome-directory/access's isSystemWrite is canonical), FALLBACK_TENANT_POLICY, encodeGeohashLocal. Everything else under src/hooks/** (fieldLock, hours, contentScan, counters, the per-collection hook factories) is internal collection-schema plumbing, not part of the public surface. |
| Jobs | createDirectoryJobs (the one-call factory; see Scheduled jobs for which jobs are conditional) + each individual create*Job/build*Handler, incl. createPruneListingStatsJob/buildPruneListingStatsHandler/computeRetentionCutoff |
| Fields | directoryHoursField, directoryHoursOverridesField, directoryGeoField, directoryRegistryRefField, directoryMenuPublishField |
| Photo attestation | attachListingPhoto, detachListingPhoto, approveListingPhoto, rejectListingPhoto (+ their arg/result types) |
| Content scanner | scanForProhibitedContent, assertNoProhibitedContent |
| Version | DIRECTORY_LAYER_VERSION |
| Slugs | DIRECTORY_DEFAULT_SLUGS, DirectorySlugs (incl. listingStats, photoAttestations) |
| Types | DirectoryListingType, DirectoryMarket, DirectoryMarketSeed, DirectoryListing, DirectoryClaim, DirectoryReview, DirectoryFavorite, DirectoryPromotion, DirectoryMenuItem, DirectoryEntitlements, DirectoryTenantPolicy (+ nested policy shapes, incl. advertiserTermsVersion), DirectoryLayerConfig (incl. currentTermsVersion, ageGateSecret, isVerifiedCrawler, registryVerify), DirectoryLayer, JobConfig, event payload types, DirectoryEventHandlers (incl. registerEconomySubscriptionHandlers), DirectoryEconomySubscriptionRegistrar, DirectoryEventType, DirectoryEventSource, DirectoryEventSurface, DirectoryAnalyticsConfig, DirectoryListingStats, DirectoryPhotoAttestation, and every literal-union alias (DirectoryTier, DirectoryClaimStatus, etc.) |
@wabbit/tome-directory/server | Queries: findListingsNear, getListingBySlug, getOpenNowCount (both read in bounded pages through core's findPaged, never one limit: 0 scan; findListingsNear also narrows each query to a lat/lng bounding box around the radius, and its haversine post-filter still decides membership, so results are unchanged), getLivePromotions, getListingReviews, toggleFavorite, submitReview, submitClaim, publishMenu, getListingStats, getListingPlacement, getRotationShare. Entitlements: resolveListingEntitlements (reads the listing and subscription) and computeListingEntitlements (the same decision as a pure function, for a caller that already holds the listing and a batch-resolved subscription). Geo: encodeGeohash, decodeGeohashBounds, geohashNeighbors, geohashPrefixesForRadius (the center cell plus its eight neighbors at a radius-appropriate precision, local math only), haversineDistanceMiles, DIRECTORY_GEOHASH_PRECISION. Hours: computeOpenState (re-exported from @wabbit/tome-local/hours: every weekly row for a day counts, so split shifts work, and an override matches its date whether stored as YYYY-MM-DD or as the ISO instant Payload persists; the result adds closesAt, current, next and closedLabel to openNow / closesInMinutes / opensAt). Browser code imports @wabbit/tome-local/hours directly. Ranking: rankListings, rotationKey ((dayOfYear + hash(listingId)) % bandSize), hashListingId (FNV-1a 32-bit), dayOfYearUTC, assertPremierSlotAvailable (throws PremierSlotUnavailableError when the market already has another premier listing; call it before stamping premier), assertTierSlotAvailable, assertTierCapsForListing, capsForTier, TierSlotUnavailableError, TierSlotScopeMissingError, TierScopeTooSmallError. Each query's *Args/*Result types are exported alongside, plus LatLng, GeohashBounds, OpenState, OpenWindow, RankableListing, ListingBillingSnapshot, SubscriptionStatusSnapshot. |
@wabbit/tome-directory/maps | DirectoryMapProvider, DirectoryGeocoder, DirectoryMapPin (the neutral MapPin from @wabbit/tome-maps/types plus tier, sponsored and openState; incl. slug/href — the listing's detail route, for a map provider's default click-to-navigate), DirectoryMapViewProps (+ their supporting arg/result types) |
@wabbit/tome-directory/listing-types | defineListingType, listingTypeRegistry, registerListingType, getListingType, hasListingType, getAllListingTypes, resetListingTypeRegistry, DirectoryListingType (payload-free; shares one store with the root) |
@wabbit/tome-directory/menu | mintMenuPublishKey, revokeMenuPublishKey, fingerprintMenuPublishKey, verifyMenuSignature, validatePublishMenuItems, rateLimit, createInMemoryRateLimitStore |
@wabbit/tome-directory/endpoints | createDirectoryEndpoints (now four endpoints — see below) |
@wabbit/tome-directory/economy | registerDirectorySubscriptionHandlers — requires @wabbit/tome-economy (the Commerce engine) |
Endpoints
createDirectoryEndpoints returns four Payload Endpoints, spread into DirectoryLayer.endpoints:
| Endpoint | Purpose |
|---|---|
POST /directory/menus/:listingId/publish | inbound menu push — per-listing HMAC key |
Menu-publish hardening. Pass DirectoryLayerConfig.menuPublish (all options optional; omitted, the endpoint behaves as before) to harden the inbound push. entitlementGate(entitlements, listing) refuses a push with a public 403 (menu-publish-not-entitled) unless it returns true; it runs after the signature is verified. validateItem(item, { listingId, index }) runs per item after the structural checks and may return a reason string, a string array, or false to reject that item, for example from a prohibited-content scan. maxItemsPerPush and maxBodyBytes refuse oversized pushes with a 413. itemLimits adds maxNameLength, maxVariantsPerItem and integerPrices. mode: 'replace' makes a push a snapshot: that listing's push-sourced rows (source: 'api') absent from the push are deleted by id, owner-sourced rows are never touched, and a push whose every item was rejected deletes nothing. One bad item no longer aborts a push: invalid items come back in a rejected list ({ externalId, index, reasons }) beside accepted and skipped, and the rest are written. rejected appears in the response only when non-empty, removed only in replace mode. revokeMenuPublishKey({ payload, listingId }) is the counterpart to mintMenuPublishKey: it disables publishing and clears the key and secret. menuPublish.ttlSources limits the purge job to rows whose source carries a TTL (for example ['api']), so owner-typed rows are never purged; omitted, the job purges every expired row as before. | POST /directory/age-gate/verify | server-side DOB check → signed directory_ag cookie | | POST /directory/claims | claim submission — requires a signed-in session (see below) | | POST /directory/events | analytics event ingestion — { events: [{ listing, type, source?, surface?, kind? }] } (kind is required for the outbound type), max 20 events, always 204. Bot user-agent deny-list plus the optional DirectoryLayerConfig.isVerifiedCrawler(req) hook; drops sponsored events for a listing that isn't currently sponsored; per-IP in-memory rate limit (the IP is never persisted). |
Claims auth. POST /directory/claims resolves the claimant from the session, never from the body: req.user → the members row whose user points at it (core's resolveMemberFromSession, against DirectoryLayerConfig.membersSlug — createDirectoryEndpoints takes it as membersSlug, default 'members'). No session user → 401. A signed-in user with no member row → 403. The body may still carry claimantMember, but it must equal the resolved member id; anything else is refused with 403, never silently rewritten. The body supplies listing, verificationMethod, optional licenseNumberSubmitted/evidence, and acceptedTerms.version. The rest of acceptedTerms is server-derived: acceptedAt is stamped at submission and ip is read from x-forwarded-for (first hop), then x-real-ip, else 'unknown'. Body-supplied acceptedAt/ip are ignored. A caller that posts from the server on a visitor's behalf (a Next server action, say) must forward the visitor's cookie and x-forwarded-for, or the claim records the server's own address. The other three endpoints are deliberately session-free: menu publish is HMAC-authenticated, while the age gate and the events beacon are anonymous by design. Each one says so in a // public-endpoint: comment, which pnpm assert:endpoint-auth enforces.
Scheduled jobs
createDirectoryJobs returns the jobs below as JobConfig[], ready to spread into DirectoryLayer.jobs; each is also available individually as create*Job. It returns four jobs unconditionally (expirePromotions, purgeExpiredMenuItems, recomputeRatingAggregates, expireTierGrace), adds reverifyRegistry only when you pass a registryVerify lookup, and adds pruneListingStats only when you pass listingStatsSlug. createDirectoryLayer always passes listingStatsSlug and passes registryVerify through from DirectoryLayerConfig.registryVerify, so DirectoryLayer.jobs has five jobs, or six when you supply a verifier. Every endpoint.path is mounted under Payload's config-root endpoints, which Payload itself serves under /api — so the path below is relative to that, e.g. expirePromotions's default resolves to POST /api/directory/jobs/expire-promotions, never /api/api/directory/jobs/expire-promotions. Pass path to override any one of them.
| Job | Default endpoint.path | Default schedule |
|---|---|---|
createExpirePromotionsJob | /directory/jobs/expire-promotions | hourly |
createExpireTierGraceJob | /directory/jobs/expire-tier-grace | daily at 04:00 |
createPurgeExpiredMenuItemsJob | /directory/jobs/purge-expired-menu-items | hourly |
createRecomputeRatingAggregatesJob | /directory/jobs/recompute-rating-aggregates | nightly at 02:00 |
createReverifyRegistryJob | /directory/jobs/reverify-registry | daily at 03:00; re-checks each listing every tenantPolicy.registry.reverifyEveryDays days. Included only when DirectoryLayerConfig.registryVerify (your license-register lookup) is supplied — see below |
createPruneListingStatsJob | /directory/jobs/prune-listing-stats | daily — deletes directory-listing-stats rows older than 400 days |
Each endpoint is CRON_SECRET-guarded (@wabbit/tome-core/jobs's asCronEndpoint) for an external scheduler; a consumer on Payload's own jobs framework instead wraps that job module's build*Handler with asPayloadTask. The schedules are the intended cadence; nothing registers them for you.
Registry re-verification needs a verifier. The reverify-registry job checks licenses through a registryVerify lookup (your call to the licensing register). Pass it as DirectoryLayerConfig.registryVerify (or createDirectoryJobs({ ..., registryVerify })); without one the job is omitted from DirectoryLayer.jobs entirely rather than shipped as a job that scans nothing, and createDirectoryLayer logs a one-time warning when tenantPolicy.registry.requireVerifiedLicenseForTypes is non-empty, because licenses would then never be re-verified. requireVerifiedLicenseForTypes still gates claims at submission time either way; only the periodic re-check depends on the verifier.
Per-type ladders, scoped caps, analytics keys and photo pre-review
Five opt-in options for a directory that lists more than one kind of listing. Every one is optional; omit them and a layer behaves exactly as before.
A separate entitlement ladder per listing type. tenantPolicy.entitlementsByListingType maps a listing type value to its own complete tier table (all five tiers; defineDirectoryTenantPolicy rejects a partial one, and createDirectoryLayer rejects a key that is not a registered type). A listing resolves against the table for its type, else tenantPolicy.entitlements, else DEFAULT_ENTITLEMENTS. Every internal caller reads the listing's listingType off the listing document, so pass the whole document to computeListingEntitlements (the listing argument now carries an optional listingType). When a per-type ladder is configured and a lookup is handed a listing with no listingType, it falls back to the default ladder and logs a one-time development warning. respondToReview takes tenantPolicy (or entitlementsByListingType) for the same reason.
tenantPolicy: defineDirectoryTenantPolicy({
// ...
entitlementsByListingType: { maker: makerLadder }, // every tier defined
})Type-scoped, multiple caps per tier. A tierCaps value may be one cap or a list, and a cap may name listingTypes. A cap with listingTypes applies only to listings of those types and counts only listings of those types, so featured listings of another type never use up its slots. Every cap that applies to the listing being written is enforced, on both write paths (the listings hook for staff and manual stamps, and the subscription handlers). assertTierCapsForListing runs them in one place and assertTierSlotAvailable takes a listingTypes filter.
tierCaps: {
premier: [
{ listingTypes: ['venue'], scope: { field: 'address.city' }, max: 1 },
{ listingTypes: ['maker'], scope: { field: 'makerDetails.category' }, max: 1 },
],
featured: [{ listingTypes: ['venue'], scope: { field: 'address.city' }, max: 6 }],
}A field-scoped cap fails closed: when the listing has no value at the scope's field, the write throws TierSlotScopeMissingError (code: 'tier-slot-scope-missing') instead of counting listings that also have no value. A cap with no listingTypes still applies to, and counts, every type, so existing configs are unchanged.
A minimum population per scope. Give a cap minInScope to sell its tier only where the scope is big enough: the tier can be newly taken only when the scope holds at least that many published listings (status: 'published'), counting only the cap's listingTypes when set and counting the listing being written when it is itself published. Below the minimum the write throws TierScopeTooSmallError (code: 'tier-scope-too-small', carrying tier, scope, min and count). The check is for acquisition only: a renewal or re-stamp of a tier the listing already holds skips it (the max check still runs), so a sitting holder is never evicted when its scope shrinks. Both write paths pass the listing's stored tier as currentTier to assertTierCapsForListing.
tierCaps: {
premier: { scope: { field: 'address.city' }, max: 1, minInScope: 2 },
}Analytics keys. DirectoryLayerConfig.analytics adds to the built-in vocabulary: extraViewSources (accepted as a view event's source), extraSponsoredSurfaces (accepted as a sponsored event's surface) and outboundKinds (accepted as an outbound event's kind, each counted in an outboundClicks.<kind> group). Keys must be plain identifiers because they become stored field names. directory-listing-stats builds its groups from the built-ins plus your extras, and outboundClicks exists only when you set outboundKinds. getListingStats returns the extras, plus sponsoredImpressions, sponsoredClicks and outboundClicks; pass it the same analytics object to get zeroed entries for keys with no traffic. getListingPlacement and getRotationShare keep reporting the four built-in surfaces. Because the stored groups change, a SQL-backed consumer needs a migration when it first adds keys.
Listing-photo pre-review. tenantPolicy.content.listingPhotoReview: { listingTypes: string[] | 'all' } holds new photos for staff review on those listing types. attachListingPhoto then writes the media to a locked pendingPhotos field (an upload field the layer adds only when this option is set) and marks the attestation reviewStatus: 'pending'; the photo is not public. approveListingPhoto moves it into photos and rejectListingPhoto drops it, each stamping the attestation approved or rejected and keeping the row. maxPhotos counts live and pending photos together, and for a reviewed type an owner's direct write to photos can only remove photos. attachListingPhoto accepts bypassReview for a trusted staff or system caller. Pass req and ctx to the review functions to require a staff caller.
The prohibited-content scan the layer's own hooks use is exported as scanForProhibitedContent and assertNoProhibitedContent, so a server action can apply the same tenantPolicy.content rules to text the layer's collections never see.
Owner analytics, placement reporting, and photo attestation
Three collections' worth of surface, additive to v1:
- `directory-listing-stats` — one row per listing per LOCAL calendar day (market timezone), counts only (no IP/UA/cookie/member/session id ever stored). Written exclusively via
POST /directory/events; read = staff, or the owning membership whenresolveListingEntitlements().analyticsis true (Listed tier and up). - `directory-photo-attestations` — the license record for a claim-time photo grant:
{ listing, media, member, termsVersion, attestedAt }. Create-only viaattachListingPhoto, which checks ownership, themaxPhotosentitlement, and thatattestation.termsVersionmatchestenantPolicy.advertiserTermsVersion.detachListingPhotoremoves the photo fromlisting.photosbut keeps the attestation row. - `getListingStats`/`getListingPlacement`/`getRotationShare` (
@wabbit/tome-directory/server) — the owner dashboard's Analytics and Placement panels.getListingStatsandgetListingPlacementare entitlement-checked and returnnull(not an error) when the listing's plan doesn't include the relevant capability.getRotationSharenever returnsnull: it reports{ tier: 'premier', exclusive: true }for Premier (capped at one live subscription per market),{ tier, sharedWith: 0, share: 0 }for any listing that is not a sponsored Featured listing, and otherwise the listing's share of sponsored impressions against its Featured siblings.
A tenant wiring this in must: (1) set tenantPolicy.advertiserTermsVersion before any photo attachment is possible; (2) optionally supply DirectoryLayerConfig.isVerifiedCrawler for a stronger crawler signal than the built-in UA deny-list; (3) mount @wabbit/tome-blocks-directory-pack/track's beacon on any custom listing-detail/grid page not built from this pack's own blocks; (4) describe the counters (aggregate, no identifiers, GPC honored) in the site's privacy policy.
Listing types are schema contributions, not dropdown labels
defineListingType + the registry (Symbol.for('@wabbit/tome-directory/listing-type-registry')) close the gap @wabbit/tome-catalog's ProductTypeRegistry leaves open: a registered type there is a label; here, typeFields is composed into a real ${value}Details group on directory-listings (composeTypeGroups, called by createDirectoryLayer). The layer ships zero built-in types — registering a bare delivery type is a modeling error, because delivery is a tags attribute, never a listing type.
Tenant policy is where vertical rules live
Every cannabis-specific (or alcohol-, or firearms-, or any regulated-vertical-specific) rule is data on a DirectoryTenantPolicy object the CONSUMING SITE builds with defineDirectoryTenantPolicy — never an if (vertical === 'x') branch in this layer. A handful of fields carry literal-typed compliance invariants the type system will not let a tenant relax: ageGate.mode: 'dob', ageGate.logResultNotDob: true, promotions.requireEndDate: true, promotions.paidSurfacesOwnerSourceOnly: true, privacy.storeDob: false, privacy.preciseGeolocation: false, privacy.adPixelsOnListingPages: false. defineDirectoryTenantPolicy adds the runtime checks TypeScript cannot express (ageGate.minAge integer ≥ 13, ageGate.alternateClass.minAge ≤ minAge, ageGate.rememberDays in 1–365, billing.graceDays ≥ 0) and fills the documented defaults (sponsoredLabel: 'Sponsored', ageGate.rememberDays: 30, billing.graceDays: 7, entitlements: DEFAULT_ENTITLEMENTS).
createDirectoryLayer also publishes the resolved policy to a globalThis-anchored singleton (setActiveTenantPolicy) — any server query function that omits its own tenantPolicy argument (a route handler that only has payload/listingId in hand) still resolves the REAL policy via getActiveTenantPolicy(), falling back to DEFAULT_ENTITLEMENTS/'Sponsored' only when no layer has been constructed in that module instance at all.
Fail-secure entitlements
resolveListingEntitlements resolves in a fixed order — tier → subscription/manual confirmation → tenantPolicy.entitlements[tier] (or DEFAULT_ENTITLEMENTS) → fail-secure to the unpaid floor (tier: 'unpaid') on anything missing, expired, or suspended. A lapsed subscription silently keeping a "Sponsored" placement is treated as a compliance failure, not just a billing one.
unpaid is the ONLY tier this ever fails secure to. claimed used to BE that floor (hardcoded free, exempt from the billing check) — since 1.0.0, claimed is a real paid tier, resolved through the exact same active-subscription/manual-billing gate as listed/featured/premier. Ownership (ownerAccount) is a separate axis entirely and is NOT billing-gated: an owner can always correct factual fields (address, phone, hours, license number) with no subscription, even at tier: 'unpaid' — only the MARKETING surface (photos, promotions, owner review responses, rank boost, menu sync, sponsored placement) is entitlement-gated. See ../server/entitlements.ts's module header and ../claims/approveClaim.ts's "THE CLAIM-PAYMENT SEAM" header for the full design.
A tenant with free claiming (the only mode before 1.0.0) is unaffected: approveClaim still grants claimed in the same call that establishes ownership, by stamping a brand-new owner account billing.provider: 'manual' — the same staff-stamped bypass this module already had for a comped account. Nothing changes for that tenant unless it opts into approveClaim({ requirePayment: true }).
Subscription checkout contract
registerDirectorySubscriptionHandlers (import it from @wabbit/tome-directory/economy and pass it to registerHandlers.registerEconomySubscriptionHandlers(payload, registerDirectorySubscriptionHandlers) once from your Payload onInit, see the quickstart; that call binds your listings slug, economy.subscriptionsSlug and tenantPolicy.billing.graceDays. Called without it, paid-tier stamping is disabled with a one-time console warning, never a crash) resolves the listing and tier being purchased off the economy Subscriptions row's own metadata field, not off the event object. A directory checkout must pass:
createSubscriptionCheckoutAction({
// ...price/customer args per @wabbit/tome-economy
metadata: {
userId, // required by economy
productId, // required by economy
productType, // required by economy
listingId, // REQUIRED by this layer — the listing being upgraded
tier, // REQUIRED — 'claimed' | 'listed' | 'featured' | 'premier', never 'unpaid'
},
})Missing metadata.listingId/tier, or tier: 'unpaid', means the lifecycle handler silently no-ops (it cannot stamp a listing it cannot resolve) — verify this contract in an integration test before wiring a real checkout. claimed is sellable since 1.0.0 — a tenant that charges for its entry tier (e.g. a $49/mo cannabis-directory claim fee) configures economy.tierPriceMap.claimed and calls approveClaim({ requirePayment: true }); the owner then completes checkout with metadata.tier: 'claimed' exactly like any other tier, and this handler's subscription.complete branch stamps it.
Takedown store
The moderation takedown shape has no eighth collection backing it — the layer ships the TakedownStore interface plus two implementations:
createInMemoryTakedownStore()— a plain-Map-backed store, for tests or a single-process demo. Not persisted.createPayloadTakedownStore({ payload, slug })— persists to a consumer-supplied Payload collection. That collection needs fields matchingDirectoryTakedownNotice:noticeId(text, unique),listingId(relationship or text),accountId(relationship or text, optional),claimant(text),status(select:received | actioned | counter-noticed | reinstated | rejected),receivedAt(date),actionedAt(date, optional).
import { createPayloadTakedownStore, recordTakedownNotice } from '@wabbit/tome-directory'
const store = createPayloadTakedownStore({ payload, slug: 'directory-takedown-notices' })
await recordTakedownNotice({ store, payload, listingsSlug: 'directory-listings', listingId, claimant: 'Rights Holder LLC' })No vertical-specific code
Nothing in src/ references cannabis, THC, or dispensaries by name — the examples above use a generic trades directory on purpose. A regulated tenant supplies its whole policy through DirectoryTenantPolicy in its own repo.
Exports
| Import path |
|---|
@wabbit/tome-directory |
@wabbit/tome-directory/server |
@wabbit/tome-directory/maps |
@wabbit/tome-directory/listing-types |
@wabbit/tome-directory/menu |
@wabbit/tome-directory/endpoints |
@wabbit/tome-directory/economy |
Changelog
2.0.xMajor
BREAKING: these packages now require
@wabbit/tome-economy0.18.0 or later, because they use its renamedSubscriptionCanceledEvent,OrderCanceledEventandsubscription.cancelednames.Update
@wabbit/tome-economyin the same change as these packages.Admin labels, field descriptions, demo content and messages now use American spellings.
1 fix (2.0.1)
- 2.0.1
A soft cancel no longer drops a paid listing to
unpaidon the day the owner cancels.When an owner cancels at period end (Stripe's customer portal default), economy sends a cancel event whose
accessEndsAtis in the future; the listing now keeps its tier until the provider's final cancel event at the end of the paid period, which downgrades it as before. Authorize.net's single terminal cancel still downgrades immediately.
1.10.xMinor
BREAKING:
@wabbit/tome-directory/mapsnow extends the neutral types in@wabbit/tome-maps, a new required peer.Migration: install
@wabbit/tome-mapsalongside@wabbit/tome-directory. The peer is type-only, so there is no runtime change; everyDirectory*map type keeps its name and shape, andDirectoryMapPinis now the neutralMapPinplustier,sponsoredandopenState.
1.9.xMinor
New payload-free
@wabbit/tome-directory/listing-typessubpath for client-reachable code that only needs the listing-type registry.It exports
defineListingType,listingTypeRegistry,registerListingType,getListingType,hasListingType,getAllListingTypes,resetListingTypeRegistryand theDirectoryListingTypetype, and shares one store with the package root, which still exports them all.DirectoryListingLinkgains an optionalid(the Payload array-row id) for renderers to key on.
2 fixes (1.9.1 – 1.9.2)
- 1.9.2
A listing type with no extra fields no longer adds an empty details group, which broke the GraphQL API.
- 1.9.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.
1.8.xMinor
Tier caps can now require a minimum population: give a
tierCapsentryminInScopeand the tier can only be newly taken where the cap's scope holds at least that many published listings.The count covers published listings (
status: 'published') in the same market and, for a field-scoped cap, the same field value; it counts only the cap'slistingTypeswhen set, and includes the listing being written when it is itself published. Below the minimum the write throws the newTierScopeTooSmallError(code: 'tier-scope-too-small', HTTP 409, carryingtier,scope,minandcount), exported from@wabbit/tome-directory/server.The rule applies to acquisition only:
assertTierCapsForListingtakes an optionalcurrentTier, and when it equals the tier being written (a renewal or a re-stamp) the minimum is skipped while themaxcheck still runs, so a sitting holder is never evicted when its scope shrinks. Both write paths (the listings hook and the subscription handlers) pass the listing's stored tier.Caps without
minInScopebehave exactly as before.
1.7.xMinor
A menu push can now be hardened without breaking existing integrations: one bad item no longer aborts the push, and a site can gate, validate, size-limit and snapshot-replace what a store publishes.
Every addition is optional, so an existing config behaves identically; the response only gains a
rejectedlist when something was rejected.- Per-item validation. Each pushed item is checked on its own, and the response lists rejected items with reasons (
{ externalId, index, reasons }) besideacceptedandskipped. The newvalidatePublishMenuItemsis exported from./menu. DirectoryLayerConfig.menuPublishtakesentitlementGate(a public 403 unless it returns true),validateItem(a per-item callback, e.g. a content scan),maxItemsPerPushandmaxBodyBytes(413),itemLimits, andmode: 'replace', where a push replaces that listing's push-sourced rows and never touches owner-sourced ones.revokeMenuPublishKeydisables publishing and clears the key, the counterpart tomintMenuPublishKey.publishMenuthrows a publicAPIError(403,menu-publish-disabled) when publishing is off, and the endpoint now returns public errors with their own status and code.menuPublish.ttlSourceslimits the hourly purge to rows whosesourcecarries a TTL, so owner-typed rows with a consumer-managed retention date are never purged. Omitted, the job still purges every expired row.- An unchanged re-pushed item now refreshes its
publishedAtandexpiresAt(still counted asskipped), so a store pushing the same menu daily no longer has it age out at the TTL. - Security: the client address can no longer be spoofed through
x-forwarded-for. The events rate limit and the claims terms-acceptance IP used the leftmost entry, which the caller chooses. They now usetrustedProxyHopsentries from the right (default 1, the rightmost, which the nearest proxy appended). NewDirectoryLayerConfig.clientIp(req)lets a site supply the address from a header its edge guarantees, and takes precedence;trustedProxyHops: 0ignores forwarding headers. Behavior change: behind a CDN plus a load balancer the default now sees the CDN-side address, so settrustedProxyHops: 2or aclientIpcallback to keep per-client rate limiting and an accurate terms-acceptance IP. The default is 1 hop because it is the only value that is safe without knowing the deployment, and a wrong guess towards too few hops only coarsens the limiter, while too many would trust client input. - Security: the menu-publish body is now capped before it is buffered.
Content-Lengthis checked first, then the body is read as a stream and aborted with a 413 the moment it passes the cap. WhenmenuPublish.maxBodyBytesis unset the endpoint now applies a built-in 5 MB ceiling instead of being unbounded; a site that pushes larger menus must raisemaxBodyBytes. - Security: the menu-publish endpoint no longer reveals which authentication check failed. An unknown listing (was 404), publishing disabled or no key set, a wrong key id (was 403) and a bad or stale signature (was 401 with a
reason) all return the same 401{ "error": "authentication failed" }, and the early exits do the same HMAC work so timing does not differ either. The reason is logged server-side. The entitlement gate stays a 403 (it runs after authentication), and 413 and 429 are unchanged. Publishers that branched on the old 404 or 403 must treat 401 as "check the listing id, key and signature".
- Per-item validation. Each pushed item is checked on its own, and the response lists rejected items with reasons (
Tier-cap, entitlement and content-scan refusals now reach the person who triggered them instead of a generic 500 "Something went wrong".
These refusals threw plain
Errors, which Payload masks. They are now PayloadAPIErrors withisPublic: trueand a status: 409 for a full tier slot, a taken slug, or a photo or live-promotion cap; 403 for a tier that is not eligible for Deal of the Day; 400 for a missing end date, an unscoped cap field, or prohibited content.Each carries a machine-readable
data.code:photo-cap-exceeded,promotion-cap-exceeded,deal-of-day-ineligible,promotion-end-date-required,prohibited-content,slug-taken.TierSlotUnavailableError,TierSlotScopeMissingErrorandPremierSlotUnavailableErrornow extendAPIError. They keep their names,codes, fields andinstanceofbehavior, and every message is unchanged.No exports or signatures change.
1 fix (1.7.1)
- 1.7.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.ctsdeclarations, 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
.mapfiles and thesourceMappingURLcomments 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 snapshotsextractGallerySourcewrites 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.
1.6.xMinor
A directory with several listing types can now give each type its own entitlement ladder and its own, type-scoped slot caps, and can hold listing photos for staff review.
Every addition is optional, so an existing config behaves identically.
- Per-type ladders.
tenantPolicy.entitlementsByListingTypemaps a listing type to its own complete tier table. A listing resolves against its type's table, thenentitlements, thenDEFAULT_ENTITLEMENTS.ListingBillingSnapshotgains an optionallistingType; every internal caller passes it, and a lookup that is handed a listing without one logs a one-time development warning when per-type ladders are configured.respondToReviewacceptstenantPolicyorentitlementsByListingType. - Type-scoped, multiple caps.
DirectoryTierCapgainslistingTypes, and atierCapsvalue may be one cap or a list. A scoped cap applies to, and counts, only its own listing types. This also fixes a latent over-count: featured listings of one type no longer used up another type's slots once the cap is scoped. New exports:assertTierCapsForListing,capsForTier, and alistingTypesfilter onassertTierSlotAvailable. - Fail-closed field scope. A field-scoped cap whose field is empty on the listing now throws
TierSlotScopeMissingError(code: 'tier-slot-scope-missing') instead of querying for a missing value. - Analytics keys.
DirectoryLayerConfig.analyticsacceptsextraViewSources,extraSponsoredSurfacesandoutboundKinds. The events endpoint accepts them and a newoutboundevent type with a validatedkind;directory-listing-statsbuilds its groups from the built-ins plus your keys and addsoutboundClicksonly when you setoutboundKinds.getListingStatsreturns the extra keys plussponsoredImpressions,sponsoredClicksandoutboundClicks. - Photo pre-review.
tenantPolicy.content.listingPhotoReviewholds new photos for the named listing types in a lockedpendingPhotosfield until staff call the newapproveListingPhotoorrejectListingPhoto.maxPhotoscounts both fields, and an owner's direct write tophotoscan only remove photos for a reviewed type.attachListingPhotogainsbypassReviewand aplacementresult. - Content scanner.
scanForProhibitedContentandassertNoProhibitedContentare now exported.
Type note:
DirectoryTierCapsvalues widen fromDirectoryTierCaptoDirectoryTierCap | readonly DirectoryTierCap[]. Config literals still compile; code that reads a cap's fields straight offtierCaps[tier]must now handle the list form (usecapsForTier).The
viewSourcestype on stats rows and results widens to include any registered key.Storage note: the new
pendingPhotos, review andoutboundClicksfields exist only when you opt in, so an existing schema is unchanged. A SQL-backed consumer needs a migration when it first adds them.- Per-type ladders.
1.5.xMinor
BREAKING:
@wabbit/tome-localis a new required peer.computeOpenStatenow comes from@wabbit/tome-local/hours, the shared open-state utility.Migration: install
@wabbit/tome-local(>=0.1.0 <1.0.0) alongside@wabbit/tome-directory. No code change is needed:computeOpenState,ComputeOpenStateArgs,OpenStateandnormalizeOverrideDateare still exported.- Every call site keeps its signature.
- The stored
hours/hoursOverridesshape is unchanged. - Relation to 1.4.1: the split-shift and override-date fixes shipped in 1.4.1 carry over unchanged. All of 1.4.1's open-state tests pass against the shared utility.
- Fix — DST spring-forward gap. A window that crossed the spring-forward gap (for example 18:00–02:00 on the change night) closed an hour early. It now resolves by checking the offsets on both sides of the change. Ambiguous fall-back times resolve as before.
- Fix — touching windows. Windows that meet at midnight merge, so a place open through midnight reports its real closing time.
- Additive:
OpenStategainsclosesAt,current,nextandclosedLabel.OpenWindowis exported from./server.DirectoryDayOfWeekis now an alias of the identicalLocalDayOfWeekunion.- Unchanged: save-time hours validation keeps its current lenient semantics. The stricter wrap-aware
validateWeeklyHoursin@wabbit/tome-local/hoursis opt-in.
1.4.xMinor
BREAKING: promotion cap/eligibility now apply to every actor, including staff.
New
DirectoryLayerConfig.tierCapsgeneralizes the Premier-only slot cap to any tier and scope.assertTierSlotAvailable(new export,@wabbit/tome-directory/server) generalizes the previously-uncalledassertPremierSlotAvailable(kept, unchanged, as a thin wrapper) to any tier, scoped to a market or to one dot-path field within a market (e.g. one Featured slot per city), with any max.DirectoryLayerConfig.tierCapsconfigures it — default when omitted:{ premier: { scope: 'market', max: 1 } }, matching today's documented intent.The check now actually runs, in two write paths:
registerDirectorySubscriptionHandlers(before stamping a subscription-driven tier change) and the listingsbeforeChangehook (whenevertierchanges to a capped tier — staff admin stamps, manual billing). Both paths enforce the sametierCapsobject;createDirectoryLayerforwards it to both automatically.BREAKING:
createPromotionBeforeValidateHook's live-count cap (maxLivePromotions) anddealOfDayeligibility check used to be skipped outright for a staff or system-authored write. They now apply to every actor — a staff admin approving or publishing an owner's promotion must respect the owner's own tier cap.The only bypass is an explicit
req.context.bypassPromotionCap === true, set on purpose (a migration or one-off internal script), never inferred fromsystemWriteor a staff role. Migration: a consumer with a staff/admin flow that publishes promotions on an owner's behalf and relies on it skipping the cap must now setcontext: { bypassPromotionCap: true }on that specific write if bypassing is still wanted; otherwise the cap now applies as it always should have.Promotion-cap/eligibility and review-response entitlement checks are now billing-resolved: both
createPromotionBeforeValidateHookandrespondToReviewresolve entitlements throughresolveListingEntitlements(the same billing-aware path photos/analytics already used), instead of a static lookup keyed by the storedtierfield. A lapsed subscription now loses these perks immediately, even though the listing's storedtieris still stamped high, rather than waiting for the grace-expiry job to catch up.findListingsNear's decorated listings (and@wabbit/tome-blocks-directory-pack's map pins, viaresolveDirectoryMapPins) now carry an additiveresolvedTierfield — the billing-resolved tier, which can differ from the storedtier. A consumer reading a decorated listing's tier for display should preferresolvedTier ?? tier.
1 fix (1.4.1)
- 1.4.1
Fixes split-shift hours and holiday-override date matching in listing open/closed status.
A listing with split-shift hours (e.g. a lunch break) now correctly shows open during EVERY window for the day, not just the first one. Holiday/exception overrides now correctly match the calendar day the admin UI's date picker actually stores, instead of silently never matching.
Both bugs were in
computeOpenState(server/openNow.ts), which every open-now computation in this package funnels through —findListingsNear,getListingBySlug, andgetOpenNowCount. No API or field-shape change; existinghours/hoursOverridesdata does not need to be migrated.A new exported helper,
normalizeOverrideDate, handles the override-date normalization and is documented for anyone matchinghoursOverridesdates directly. The admin UI'shoursOverrides.datefield now also hides its time picker (pickerAppearance: 'dayOnly'), since the stored value was never meant to carry a time of day.
1.3.xMinor
@wabbit/tome-economyis now an optional peer, so you can install the directory without the Commerce engine; paid listing tiers require it.If you sell paid listing tiers (one-line change on upgrade): install
@wabbit/tome-economyyourself, importregisterDirectorySubscriptionHandlers(and itsRegisterDirectorySubscriptionHandlersArgs/RegisterDirectorySubscriptionHandlersResulttypes) from@wabbit/tome-directory/economyinstead of the package root, and pass it as the second argument:directory.registerHandlers.registerEconomySubscriptionHandlers(payload, registerDirectorySubscriptionHandlers). If you don't sell paid tiers, remove that call.- The package root no longer re-exports
registerDirectorySubscriptionHandlersor its types, and nothing reachable from the root (or from./server,./maps,./menu,./endpoints) imports@wabbit/tome-economy. Only./economydoes. registerEconomySubscriptionHandlersnow takes the registrar as a required second argument (typed as the newDirectoryEconomySubscriptionRegistrar). Called without one, it logs a one-time warning that paid listing tiers are disabled and returns a no-opunsubscribe, rather than throwing.- Manually stamped tiers and fail-secure entitlement resolution are unchanged.
- The package root no longer re-exports
1 fix (1.3.1)
- 1.3.1
Directory listing pages work on a site without the Commerce engine.
getListingBySlug,findListingsNear,getLivePromotionsandresolveListingEntitlementsread economy'ssubscriptionscollection to decide whether a paid tier is live. Economy has been an optional peer since 1.3.0, so that collection may not exist, and the three queries threw on any listing with a paid tier.They now skip the lookup when the collection isn't registered. A paid tier then resolves as it does with no subscription row: the unpaid floor, unless the owner account's billing provider is
manual, which keeps the tier.
1.2.xMinor
BREAKING for anonymous callers:
POST /directory/claimsnow requires a signed-in session and takes the claimant from it, never from the request body.The defect (P0): the handler never read
req.user. It tookclaimantMemberandacceptedTerms.ipfrom the JSON body and passed them tosubmitClaim, which writes withoverrideAccess: true.createDirectoryLayermounts the route by default, so any anonymous caller could file a pending claim on any listing in any member's name. Only one pending claim is allowed per listing, so that fake claim then locked the real owner out.The fix:
- The claimant is resolved with
resolveCallerMember(src/access/context.ts), the same wrapper over@wabbit/tome-core/identity'sresolveMemberFromSessionthat every directory access rule uses. It looks up themembersrow whoseuserisreq.user.id.createDirectoryEndpointsgains an optionalmembersSlug, default'members'(core's default), andcreateDirectoryLayerpassesDirectoryLayerConfig.membersSlug. - No session user →
401. A session user with no member row →403. A bodyclaimantMemberthat is not the resolved member id →403. The endpoint refuses the mismatch and never rewrites it. OmittingclaimantMemberis fine. acceptedTerms.ipcomes fromx-forwarded-for(first hop), thenx-real-ip, else'unknown'.acceptedTerms.acceptedAtis now stamped by the server at submission. The submission is the moment of acceptance, and a client clock can be backdated, so the stamp is better evidence. Body-suppliedacceptedAtandipare ignored. OnlyacceptedTerms.versionstill comes from the caller, and it is still checked against the current agreement version.
Why minor, not patch: the request contract changes for one class of caller. Anonymous requests that used to get
201now get401.acceptedTerms.ip/acceptedAtare no longer honored from the body. The endpoint also sends403in cases where it used to write.The package's own history flags runtime-contract changes (
1.0.0forclaimed/unpaid), so shipping this silently as a patch would understate it. It is notmajor, because no legitimate caller loses anything.An authenticated caller that sends its own member id, like the first consumer tenant's
submitClaimAction, keeps working unchanged. The only TypeScript change is the new optionalmembersSlug.Consumer action: a server-side caller that posts to this endpoint on a visitor's behalf must forward the visitor's
cookieheader, as it already had to for the claim to belong to anyone. It should also forwardx-forwarded-for, oracceptedTerms.iprecords the server's own egress address.Also in this change: the other three directory endpoints (menu publish, age gate, events) are marked
// public-endpoint: <reason>, and a new repo gate,pnpm assert:endpoint-auth, fails any endpoint underpackages/*/src/**/endpoints/that neither reads the session nor declares itself public.- The claimant is resolved with
BREAKING:
DEFAULT_DIRECTORY_ACCESS— what every directory collection factory falls back to when called withoutaccess— now fails closed: every operation is staff-only (directoryStaff:super-admin/admin/staff).It was all
() => true, so a consumer who composed the exported factories withoutcreateDirectoryLayershipped an open CRUD surface.createDirectoryLayeris unaffected (it always passes the real bundle with its status-filtered public reads).A standalone factory caller that relied on the open default must now pass
access.BREAKING:
isStaffOrAdmin(req, context?)is now async (Promise<boolean>) and delegates toisStaffUser— the same staff definition access control uses.It previously used the deprecated sync
checkRole(['staff','admin']), which excludedsuper-admin(a super-admin's edits to locked listing fields were silently stripped, and super-admins hit owner photo caps and content scans), ignoredstaffPredicate, and returnedfalsewhenever roles were not already populated.DirectoryHookContext,ResolveHookContextArgs, and the listings/promotions collection configs gain an optionalstaffPredicate, whichcreateDirectoryLayerthreads through so hook-side decisions honor the consumer override.Callers of the exported
isStaffOrAdminmustawaitit.BREAKING: license re-verification is now wired through the layer, and the job is omitted rather than silently no-opping.
Decision:
DirectoryLayerConfiggains an optionalregistryVerify(the site's license-register lookup, typeDirectoryRegistryVerifier), whichcreateDirectoryLayerthreads tocreateDirectoryJobs. When it is absent,createDirectoryJobs(and therefore the layer) no longer includes thereverifyRegistryjob at all — previously the layer always shipped it with no verifier, so every run skipped while the job list implied licenses were being re-verified — andcreateDirectoryLayerwarns once at creation iftenantPolicy.registry.requireVerifiedLicenseForTypesis non-empty.A consumer that mounted the
reverifyRegistryendpoint fromlayer.jobsmust supplyregistryVerifyto keep it.Relationship ids are now read with core's
relationId/relationIdRaw(@wabbit/tome-core/utilities/relationId) instead of seven local copies; each site keeps its return shape, and the publicrelIdexport stays as a thin alias ofrelationIdRaw.The
@wabbit/tome-corepeer floor rises to>=1.17.0(the release that addsrelationIdRaw).findListingsNearandgetOpenNowCountno longer issue unboundedlimit: 0reads on public request paths.findListingsNearadds a portable lat/lng bounding-box pre-filter (newboundingBoxForRadiusinserver/geo) on every path and pages the listings read with core'sfindPaged(200 rows per query, capped and logged);getOpenNowCountpages the same way. Results are unchanged — the box strictly contains the search circle and the haversine post-filter still decides membership.
2 fixes (1.2.1)
- 1.2.1
Nearby-listing search and the live-promotions query no longer issue unbounded reads; results are unchanged.
Promotions and subscriptions are read in bounded pages, and the listing fallback lookup is capped at the number of ids requested. Internal: collection slugs are typed through the shared
typedSlug()helper instead of inline casts. - 1.2.1
customer-facing wording: internal references removed from admin descriptions, error messages and block metadata.
1.1.xMinor
Add owner analytics, placement reporting, and photo attestation.
New public API:
directory-listing-statsanddirectory-photo-attestationscollections;POST /directory/eventsingestion endpoint (bot deny-list, a consumer-pluggableDirectoryLayerConfig.isVerifiedCrawlerhook, per-IP in-memory rate limiting, always 204); server queriesgetListingStats,getListingPlacement, andgetRotationShare(all entitlement-checked,nullwhen the listing's plan lacks the relevant entitlement);attachListingPhoto/detachListingPhotofor the claim-time photo license grant; a dailypruneListingStatsjob (400-day retention).Privacy by construction: no IP, user-agent, cookie id, member id, or session id is ever stored with an event — counts only, keyed on
[listing, day]in the listing's local timezone. A sponsored impression/click can only be recorded for a listing that is currentlysponsoredper its resolved entitlements, so the counters can never say a surface was labeled Sponsored when it wasn't.This makes the
analyticsentitlement (declared since v1 but previously unbacked by any data) real for the first time.
1.0.xMajor
Introduce
unpaidas a real unpaid floor tier beneathclaimed, and makeclaimedsellable.This is a breaking behavioral change flagged
majorfor review — the public API surface is purely additive, but the RUNTIME semantics of theclaimedtier change.The problem:
claimedwas hardcoded as the layer's free floor in several billing-blind places —resolveListingEntitlementsshort-circuited ontier === 'claimed'and returned its entitlements BEFORE any subscription/billing check, the fail-securecatchreturned fullclaimedentitlements on any error, andSELLABLE_TIERSexcludedclaimedentirely so nothing could ever stamp it via checkout. That made a paid entry tier (e.g. a $49/mo cannabis-directory claim fee) impossible to sell, and worse, meant every fail-secure path handed outclaimed's entitlements for free, forever.The fix:
- New
DirectoryTiermember'unpaid'— zero marketing entitlements (maxPhotos: 0,maxLivePromotions: 0,rankBoost: 0,ownerResponses: false, etc.). It is the ONLY tier every fail-secure path (resolveListingEntitlements's error catch and no-active-billing branch,registerDirectorySubscriptionHandlers's cancel handler,revokeClaim,expireTierGrace) now lands on — neverclaimed. claimedis added toSELLABLE_TIERSand its short-circuit inresolveListingEntitlementsis removed — it now resolves through the EXACT same active-subscription/manual-billing gate aslisted/featured/premier.directory-listings.tier's schema default changes from'claimed'to'unpaid'— a brand-new listing starts with zero entitlements until claimed and/or subscribed.- Ownership vs. entitlements is now an explicit split:
ownerAccount(established byapproveClaim) grants the right to correct FACTUAL fields (address, phone, hours, license number) with NO billing check, ever. Entitlements (photos, promotions, owner review responses, rank boost, menu sync, sponsored placement) are billing-gated. NewDirectoryEntitlements.ownerResponses: booleanfield —moderation/respondToReviewnow checks it (statically, off the listing's storedtier, mirroring the existing photo-cap pattern) before allowing a response write;unpaidisfalse,claimedand above aretrue. - New claim-payment seam:
approveClaim({ requirePayment }). Defaultfalsepreserves EVERY existing tenant's behavior byte-for-byte — the listing is stampedtier: 'claimed'in the same call that establishes ownership, and a brand-new owner account is stampedbilling.provider: 'manual'soclaimed's entitlements actually resolve (reusing the pre-existing manual-billing bypass rather than inventing a parallel "free tier" concept).requirePayment: trueleaves the listing at its existing tier (normallyunpaid) and defers promotion toclaimedto a subsequentcreateSubscriptionCheckoutAction+ the (now claimed-aware) subscription-complete handler — no new economy wiring required, since addingclaimedtoSELLABLE_TIERSwas the only change the checkout path needed.
Backward compatibility: A tenant that never passes
requirePaymentand never configureseconomy.tierPriceMap.claimedsees IDENTICAL behavior to before this change — free claiming still grantsclaimed's entitlements immediately, with no code changes required on the consumer side.Migration flag for any tenant with PRE-EXISTING `claimed` listings from before this change ships: those listings' owner accounts were never stamped
billing.provider: 'manual'(the old code never checked it). After this deploy,resolveListingEntitlementswill fail those listings secure to theunpaidfloor until either (a) a backfill stampsbilling.provider: 'manual'on their owner accounts, or (b) they're re-approved through the newapproveClaimpath.Flagging for the operator/consumer sites to run a one-time backfill before/alongside this deploy if any tenant already has claimed listings in production.
Also updated
@wabbit/tome-blocks-directory-pack'smaps/shared/pins.ts(TIER_BACKGROUND/TIER_FOREGROUNDRecord<DirectoryTier, string>) to add anunpaidentry so it keeps compiling against the widenedDirectoryTierunion — same muted stylingclaimedalready had, since a pin's fill is a rank cue, not a claim-status cue.- New
Fix a compliance defect in the age gate: the alternate age class (e.g. an 18+ medical-patient exception under a 21+
minAge) was granted to any visitor whose DOB fell in the alternate age band, with no assertion that they actually qualify for it — a plain "Enter" submission from an 18-20-year-old silently passed asclass: "alternate", making a 21+ gate behave as an 18+ gate for anyone who didn't notice the second button.verifyAgeGatenow requires the caller to passclaimAlternateClass: true(asserted only when the visitor pressed the dedicated alternate-class control) in addition to meetingpolicy.alternateClass.minAge; an unclaimed under-minAgeDOB is denied, never silently admitted.createAgeGateVerifyHandler's request body gained an optionalclaimAlternateClassfield (strict=== true, so a truthy-but-non-boolean value is never mistaken for a claim) — additive, so any pre-existing caller that omits it keeps getting{ ok: false, class: null }for an unclaimed under-minAgeDOB, same as after this fix (they were never able to reach the alternate class via that path anyway, since the old code inferred it from age alone with no per-request signal at all).Also fixes the "Remember me on this device" checkbox being silently ignored: the handler's request body gained an optional
rememberfield (defaulttrue, matching the prior always-persistent behavior) —falsenow issues a session cookie (noMax-Age/Expires) instead of always issuing apolicy.rememberDays-lifetime cookie regardless of the visitor's choice.Both new fields are additive to the endpoint's request body — no existing caller's request shape needs to change, and the response shape (
{ ok, class }) anddirectory_agcookie payload shape are unchanged.verifyAgeGate'sVerifyAgeGateArgsgained an optionalclaimAlternateClassfield — also additive.Tenants that configure no
ageGate.alternateClassat all (a straight 21+ gate) are unaffected either way: the alternate-class branch has always been (and remains) a no-op whenpolicy.alternateClassis undefined, claim or no claim — covered by dedicated tests since this is the exact configuration a production consumer is shipping.SECURITY: fix
directory-reviewsletting a review's own author self-approve their own pending review, and the same-shape gap indirectory-promotions.The vulnerability:
buildReviewsAccess()(access/createDirectoryAccess.ts) declares field-level locks for FOUR fields —status,moderation,reports,ownerResponse— butcreateReviewsCollection(collections/reviews.ts) only ever wired ONE of them (moderation) onto a real Payload field. The other three carried noaccessat all and fell through to the collection-levelupdateaccess, which a review's own author legitimately holds on their OWN pending review (so they can edittitle/bodybefore moderation).Concretely:
PATCH /api/directory-reviews/<id> { status: 'approved' }succeeded for the review's own author, publishing it unmoderated.directory-promotionshad the identical shape:buildPromotionsAccess()declares afields.statuslock, butcreatePromotionsCollectionnever calledresolveDirectoryFieldAccessfor it at all — an owner updating their owndraftpromotion (access they legitimately hold) could setstatus: 'live'in the same PATCH, bypassing the staff/system-only publish transition.The fix: every key each bundle's
fieldsmap declares is now wired viaresolveDirectoryFieldAccess, exactly asmoderationalready was.ownerResponseis wired to the bundle's existing (correct) predicate — system write, staff, OR the caller holding an owner seat on the review's own listing — deliberately NOT staff-only, since owner responses are a paid-tier product feature.Also fixed, same class, opposite direction:
directory-listings'ownerAccountfield has always calledresolveDirectoryFieldAccess(config.access, 'ownerAccount'), butDIRECTORY_LOCKED_LISTING_FIELDS(access/fieldLock.ts) — the bundle's only source for itsfieldskeys — never included'ownerAccount', so that call always silently resolved to the permissive default. An owner could rewrite their own listing'sownerAccountdirectly (silent ownership/billing reassignment), with neither a field lock nor thebeforeChangestrip hook (which shares the same list) catching it.Now locked, same as every other server-stamped listing field.
Made the whole class loud, not just these four fields:
resolveDirectoryFieldAccessnow THROWS at construction time if it's asked for a field key against a bundle whosefieldsmap is populated but doesn't declare that key — the exact shape of theownerAccountgap. A new generic test suite (tests/collections/fieldLockWiring.test.ts) builds every collection this package ships against its real access bundle and asserts, by function reference, that every key the bundle declares infieldsis actually wired onto a real field — the exact shape of thestatus/reports/ownerResponsegap.Together these make "a bundle declares a field lock the collection never applies" and "a collection asks for a lock the bundle never declares" both fail immediately, for every current and future locked field, instead of silently doing nothing.
Backward compatibility — read carefully: any consumer whose code was directly PATCHing
directory-reviews.status/.reports/.ownerResponseordirectory-promotions.statusas an ordinary authenticated caller will now be denied where it previously succeeded. That is the point — those are exactly the unintended-write paths this closes.A consumer whose OWN code writes these fields via
overrideAccess: truewithcontext: { systemWrite: true }(the pattern this package's ownreportReview/respondToReview/approveReview/rejectReview/removeReviewalready use) is unaffected; verified by reading each of those functions and by a spy-based test asserting every write they make carries both flags.draft -> live/live -> expiredpromotion transitions andpending -> approved/rejectedreview transitions go through@wabbit/tome-workflow'sclaimTransition, which writes via the DB adapter's raw atomic primitive (bypassing Payload access entirely) oroverrideAccess: trueon its non-Mongo fallback — neither path is gated by Payload field access, so cron jobs (expirePromotions) and moderation helpers are unaffected either way.Fix the staff access gate (
isStaffUser/directoryStaffinaccess/context.ts), which was dead for every user of every role on every consumer.The problem: the gate read
req.user.role— SINGULAR — via the deprecated@wabbit/tome-core/access/checkRole. Tome's real Users shape has no such field; roles live onroles, a relationship ARRAY resolved by BetterAuth's customSession enricher, never eagerly populated onto a flatrolestring.Every call resolved to
checkRole(undefined, [...]), unconditionallyfalse. Proven live in a consumer: anadmin-role account still gottotalDocs: 0and "Nothing found" against a six-document directory collection.Every collection's staff bypass, and every locked-field staff override (
tier,registryRef, review moderation fields, promotionstatus, etc.), was silently inert — staff could not moderate, could not hand-correct a listing, could not bypass a scoping WHERE, regardless of role.The fix:
isStaffUsernow delegates role resolution to@wabbit/tome-core/auth/rbac'scheckRoleAsync— the same helper core's own async admin gates (auth/guards.ts) use. It reads_populatedRoleswhen already request-cached, elseroles(handling both bare relationship ids and already-populated role docs), fetching and caching on a miss. This makes the gateasync; every call site was already inside anasyncAccess/FieldAccessfunction, so nothing further up needed to change.- The default vocabulary no longer hardcodes
['staff', 'admin']— that excludedsuper-admin, the platform's most privileged role, independent of the field-name bug. The default is nowsuper-adminoradmin(core'sROLESconstants) plus a role literally sluggedstaff(kept only for a consumer who already defined one — never assumed to exist). - New
DirectoryLayerConfig.staffPredicate?: (req) => boolean | Promise<boolean>lets a consumer replace the staff gate outright (a different vocabulary, an org-scoped check, whatever) — threaded throughcreateDirectoryLayerinto everyDirectoryAccessBundlecreateDirectoryAccessbuilds, including the field-level locks. New exportsdirectoryStaffAccess(ctx)/lockedFieldAccessFor(ctx)are the ctx-aware factories that honor it; the existing ctx-freedirectoryStaff/directoryStaffFieldLevel/lockedFieldAccessexports are unchanged in shape and always use the corrected default.
Backward compatibility: essentially none of today's consumers are affected in practice, because the broken gate matched nobody — there is no live behavior to regress. Any consumer whose staff/admin/super-admin accounts start correctly bypassing scoping WHEREs and correctly editing locked fields is receiving the FIX, not a regression.
A consumer that happens to have defined a role literally slugged
staffcontinues to work unchanged (still in the default vocabulary).Field-level lock behavior for
directory-listingslocked fields (buildListingFieldLocks) is threaded through the samectx/staffPredicateseam. Hook-side gating inhooks/context.ts'sisStaffOrAdmin(used bybeforeChangefield-strip enforcement) is a SEPARATE, already-correct implementation (it readsroles/_populatedRolesvia core's synccheckRole, not a singularrolefield) — untouched here since it lives in files another in-flight PR (feat/directory-unclaimed-floor-tier) owns; it still hardcodes['staff', 'admin'](missingsuper-admin) and is flagged as a follow-up, not fixed in this change.
1 fix (1.0.1)
- 1.0.1
Fix the five scheduled jobs' (
createDirectoryJobs/ eachcreate*Job) defaultendpoint.pathbeing double-prefixed with/apiat request time.Root cause: every job defaulted its
endpoint.pathto/api/directory/jobs/<job>, but Payload mounts config-rootendpointsunder/apiitself — the layer's other endpoints (/directory/claims,/directory/age-gate/verify,/directory/menus/:listingId/publish) never included the/apiprefix themselves. Verified empirically on tome-starter (next start, 2026-09-13):POST /api/directory/jobs/expire-promotions→ "Route not found";POST /api/api/directory/jobs/expire-promotions→ 401 without the bearer, 200 with it.Every consumer spreading
directoryLayer.jobs.map(j => j.endpoint)into a cron/scheduler config (a production consumer does exactly this) got double-prefixed cron URLs.The fix:
expirePromotions,expireTierGrace,purgeExpiredMenuItems,recomputeRatingAggregates, andreverifyRegistrynow default to/directory/jobs/<job>— matching every other endpoint this layer mounts.createDirectoryJobs's aggregate output changes accordingly; a caller who already set an explicitpathoverride is unaffected.Consumer-visible change: the default cron endpoint URLs move from
/api/api/directory/jobs/*(broken) to/api/directory/jobs/*(working). A consumer that had already worked around the double-prefix (e.g. by pointing its scheduler at the broken/api/api/...URL, or by passing an explicitpath) should update its scheduler config to the corrected URL, or keep its explicitpathoverride — either continues to work.
0.1.xMinor
New package:
@wabbit/tome-directory— a reusable, market-agnostic, vertical-agnostic local-directory layer (markets, listings, claims, reviews, favorites, promotions, an inbound menu-item seam).Wave 1 (W1-INFRA) ships the full public type surface, the
defineListingTyperegistry,defineDirectoryTenantPolicy+DEFAULT_ENTITLEMENTS, the five-channel event bus,createDirectoryLayer's config validation/slug resolution/listing-type-group composition/layer registration, and the./server+./mapsexport subpaths. The seven collection factories and every./serverdata-access function are typed stubs pending W1-COLL/W1-SERVER (Wave 1 continues in parallel).First tenant: a production consumer, via its own
DirectoryTenantPolicy— no vertical-specific code ships in this package.
1 fix (0.1.1)
- 0.1.1
Fix
validateAndNormalizeHoursrejectingcloses: '24:00': ISO 8601 permits24:00as an end-of-day value, and real register data closes stores at midnight this way, so the consumer import aborted on the first such listing.24:00is now accepted as aclosesvalue only (neveropens, and never any other value past23:59) and is treated as 1440 minutes — the day's final instant — for ordering and overlap validation.computeOpenState(server/openNow.ts) already resolved genuinely overnight windows (closesearlier thanopens, e.g.20:00-02:00) correctly across the midnight wrap; it now also carries explicit documentation and test coverage for the24:00case, which resolves correctly via the sameDate.UTChour-24 overflow used for overnight wraps.The stored
hoursvalues are unchanged by this fix — no migration needed.