npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@openlup/platform

v1.4.0

Published

Runnable server substrate: Node HTTP runtime, BFF dispatch, scheduler, storage, data gateways and bundle composition.

Downloads

18,595

Readme

@openlup/platform

@openlup/platform provides the server substrate an application composes: Node HTTP and BFF dispatch, scheduling and leases, blob storage, data gateways, PostgreSQL migrations and optional commerce services. Ports and contracts live in @openlup/core/platform-runtime. Pin exact versions and upgrade the @openlup/* set together after reading every changelog. Follow the stable API contract: unions and literal sets are open, additions are minor, and consumers must keep a default branch for unknown values. The generated maturity reference identifies stable, experimental and testing subpaths.

npm install --save-exact @openlup/core @openlup/platform
import { createScheduledJobRegistry } from "@openlup/platform/scheduler";

export const jobs = createScheduledJobRegistry([
  { id: "app-cleanup", schedule: "0 * * * *", run: async () => {} },
]);

This example declares a job registry; bind a scheduler and implement the job before running it. Node 24 or newer is required. Read AGENTS.md for installed agent context, subpath maturity and application ownership.

Start with the OpenLup guide. Use the self-host recipe for runtime composition, database upgrade guide for installation, and application-file upgrades for managed files. The openlup command exposes upgrade and diagnosis; read openlup --help from your installed version for its syntax.

Repository-source links below navigate to current public main, outside this tarball. They may describe a different revision. For installed behavior, use this package's declarations and changelogs and source at the matching release tag. A current-main link establishes no compatibility or support guarantee. See CHANGELOG.md for release changes and migration precautions.

The published 1.1.0 set is the first qualified stable npm set and image (qualification run). It includes the required owned-file migration, cadence widening and native forward 151. It supersedes 1.0.0, which later passed qualification as an npm set without an image (requalification run).

The subscriptions entry also exposes createPostgresSubscriptionAutoResume: bind its run(limit, now) method to the host scheduler and job ledger after installing the complete selected catalogue. Due finite pauses resume only when eligible; graceful skips leave their window open for re-evaluation. The host owns enablement and cadence. Trusted native retry bindings accept retryCadence: { backoffHours }; defaults remain [24,72,168] and timing cannot alter terminating failure classes or an already accepted receipt.

Declaration maps connect dist/ declarations to shipped src/; JavaScript source maps are not shipped. Directory publishing refuses; the authorized release workflow owns publication.

Install the portable PostgreSQL schema

See selecting, inspecting and applying the complete catalogue.

@openlup/platform/migrations exports createPlatformPostgresMigrationRunner. It uses the existing executor with the complete packaged catalogue, canonical ledger paths, SHA-256 hashes, order and host-admission checks. No source checkout is required. Install the optional pg peer in the application. Call status(), apply({ dryRun: true }) or apply() explicitly; imports install nothing.

// Fragment: the application supplies directUrl, its direct PostgreSQL connection string.
import { createPlatformPostgresMigrationRunner } from "@openlup/platform/migrations";

const migrations = createPlatformPostgresMigrationRunner({ connectionString: directUrl }, {
  installation: {
    generation: "qualified-admin", roleMode: "installer-managed",
    migrationLogin: "app_migrator", bootstrapLogin: "postgres",
    runtimeLogin: "app_runtime", restoreLogin: "app_restore",
  },
});
await migrations.apply();
const status = await migrations.status();

Provision the selected PostgreSQL 16 host profile first. qualified-v2 retains its privileged migration principal; qualified-admin uses the restricted principal. Both retain installer-managed and operator-provisioned role modes; qualified-admin in operator-provisioned mode also requires a distinct operatorLogin. These options observe and admit the existing profiles; they do not create host logins, qualify a provider or authorize access. Follow the source data and migration owner for the exact provisioning boundary and use the matching installed release.

The package factory requires an explicit installation; omitting it refuses before catalogue or pool work. Select a qualified generation for a fresh qualified installation. legacy is a separate history; histories cannot be switched in place. The repository facade retains its legacy default. SQL resolves relative to the installed module, independent of the application's working directory. Missing or tampered units are refused by their canonical path before connection. A completed chain reports every selected unit applied; another apply is a no-op. createPostgresMigrationRunner keeps its original explicit source/options API. The convenience factory also retains poolFactory, root and catalogProjectionPayload, and accepts a catalog reader for repository-layout compatibility. Supplying a pool factory retains responsibility for startup options and pool lifetime. These are trusted host seams, not sandbox boundaries.

The selection/validator in src/migrations/catalog.ts is a generated copy with one generated-from header line followed by the source tooling owner's exact bytes, checked by the same gate: source policy tools run before workspace build output exists. Do not edit the copy. sql/manifest.json is generated from the canonical source manifest and its issued SQL, following the outbox asset pattern. Do not edit it or its SQL copies. The required installed-consumer gate refuses drift. In a source checkout, run node --experimental-strip-types --input-type=module -e "import { checkPlatformMigrationProjection } from './scripts/packages/platform-migration-projection.ts'; const errors = checkPlatformMigrationProjection(process.cwd(), true); if (errors.length) throw new Error(errors.join('\n'));" to regenerate exact copies after an authorized canonical change. This packaging change adds no migration and changes no SQL bytes.

Customer pause and bundle commands share the generic principal-scoped command: hash namespace after 20261106050000_customer_command_key_isolation.sql. Apply the complete selected catalogue with the matching runtime. These actor entries reject supplied command: keys, including historical raw keys with that prefix. Derived lookups require principal-bound provenance; an unmarked row at the hash refuses as ambiguous. Non-reserved raw history replays only for the same owner/action, with accepted quote proof for bundles; other customer actions refuse, while system rows are bypassed without replacement. See the native command owner.

Installed agent context

Core's installed openlup-context command searches its reader guide under docs/guide/ alongside the installed packages' AGENTS.md, README.md, declarations and exports. Upgrade questions also search CHANGELOG.md. Results cite local files and line ranges offline. Read the version from the installed package.json before relying on this guidance. Lookup grants no application policy or execution authority and establishes no runtime activation or compatibility with another version.

Package surface

The experimental Node-only ./lifecycle entry plans and applies explicit application-file snapshots. It preserves unmanaged files and local edits in upstream-unchanged files, refuses divergent changed files before writes, and resumes exact completed replacements after interruption. The caller holds an exclusive maintenance window and supplies schema-range evidence; this entry runs no database migration, npm install or deployment. Read the file-ownership boundary and disposable app recipe.

The same entry exports inspectLegacyPostgresInstallRoles, a read-only query through a caller-owned PostgreSQL handle. Its legacy-fresh-bootstrap-role-prerequisites report observes finite immutable legacy bootstrap role conditions; rolePrerequisitesMet does not establish install readiness, schema/ACL correctness or provider support. See the legacy role boundary.

The experimental Node-only ./portability entry copies a bounded, explicitly complete immutable/quiesced object inventory and captures/restores selected compatible PostgreSQL rows through injected transaction handles. Private filesystem objects publish bytes and metadata together, bind an explicit access label to the filesystem owner's private policy and resume by verified readback. Row replay preserves exact JSON/numeric/time values, refuses conflicts and every enabled user INSERT trigger, and copies no schema, migration ledger or grants. With the complete 0.35.0 catalogue, outbox_events also needs the owner path, so the generic utility refuses it; that owner path is reference-source only. The host qualifies the canonical catalogue, credentials and source completeness. These helpers activate no executor and do not supply managed identity mapping, live changed-row catch-up or hosted old-worker fencing. Read the transfer boundary and the retained M14 obligations. The provider-owned HTTP counterexample exercises an existing adapter's cached bearer; its local fixture establishes no hosted revocation guarantee.

release-gates.json declares kind rail: this foundation provides runtime infrastructure over core ports, matching the architecture's rail responsibility. Its entries each bind a declaration snapshot and package-owned smoke tests. The API checker reads this same inventory.

| Export | Contents | | --- | --- | | ./lifecycle | Experimental Node file-snapshot planning/apply, read-only legacy PostgreSQL role prerequisites, and storefront verdict and proof-file contracts; no install-readiness claim, optional SDK or activation | | ./portability | Experimental server object copy/resume, private filesystem transfer store and compatible PostgreSQL row capture/restore; injected handles, explicit refusal and no activation | | ./http | Generic capped raw-body reader, hex HMAC and constant-time token comparison; Node request adaptation, deadlines, security headers and static documents, and createNodeHttpRuntime with its fixed request order | | ./bff | createBffDispatcher, lazyBffRoute, the hosted router URL rewrite, the response envelope (createBffResponder), the observed request context and the health route | | ./scheduler | Transport-neutral scheduled jobs (ScheduledJob, the job registry, the lease-aware runner and the authenticated HTTP cron entry), path-declared jobs from configuration, the node-cron scheduler with per-job advisory locks, hosted cron verification, the cron entrypoint guard (it compares the presented bearer token with CRON_SECRET in constant time) and direct job bindings | | ./blob | Filesystem, S3-compatible, Supabase Storage and Vercel Blob adapters, and bindBlobPort | | ./data | Supabase and node-postgres data gateways, the role-free transaction lane, the query builder and the data bindings | | ./migrations | The node-postgres MigrationRunnerPort | | ./job-ledger | The job-run ledger port, its PostgreSQL and managed (Supabase) adapters, the managed v2/v3 compatibility calls and the location of its SQL | | ./kernel | The bundle identifiers, descriptors and readiness | | ./composition | createBundleComposer, the Node HTTP binding helpers and createNodeHost | | ./identity | Identity engine, authorization, profile readers, session adapters and BFF factories | | ./identity/contracts | Experimental capability: browser-safe customer auth port, value types and provider parser | | ./communications | Existing public consent/status, newsletter sync, Auth email hook, transport contracts/capture, observation/polling orchestration, standard webhook verification and delivery receipts; host-selected rendering, egress, protocol mapping and control policy | | ./communications/contracts | Pure renderer, block builders, copy-injected commerce/subscription factories and email/newsletter/Auth/intake/receipt types; no Zod, Node or provider runtime imports | | ./payments/stripe | Opt-in Node payment example with an injected structural client, verified observations and purpose-sensitive readback; no SDK dependency or default activation. | | ./payments/tpay | Opt-in Node payment example with injected HTTP/certificate I/O, Model O aliases and verified observations; no default activation. | | ./fulfillment/omnipack | Opt-in Node fulfillment example with injected I/O; default-off. | | ./payments/testing | Testing-only offline adapter conformance runner and scripted transport fake. | | ./payments | Prepared-attempt ordering with injected persistence, execution and failure policy; contracts at ./payments/contracts. | | ./fulfillment, ./fulfillment/contracts | Fulfillment services, capability declarations/refusals and status canon. | | ./fulfillment/native | createNativeFulfillmentBinding with selected nativeDispatch or explicit host preparation; requires a capability-local transaction lane and contribution composition. Optional shadowCommandFingerprint preserves actual adapter command identity. | | ./fulfillment/native (operator transactions) | createPostgresFulfillmentOperatorPort for replacement and complete cancellation, with authenticated actor and explicit provider/stock-source binding; createPostgresParcelReservationConsumption supplies exact parcel stock consumption. Install the complete catalogue and retain the legacy cancellation limits. | | ./fulfillment/native (shipment commands) | createPostgresFulfillmentShipmentCommandPort records label evidence, handoff and tracking atomically with server actor and durable replay evidence. Handoff consumes only frozen parcel reservation IDs. Compose withAccountingInvoiceShadowTrigger from ./invoicing after the committed command, using host channel policy and fail-soft accounting. Historical limits. | | ./fulfillment/native (local commerce) | createPostgresFulfillmentCommerceMutationPort composes local creation, private operator-attempt audit and cancellation. createPostgresFulfillmentDispatchComposition supplies recorded native candidate/preparation reads. Install the complete catalogue through the dispatch-outcome forward; authenticate operators in the host. | | ./fulfillment/native (provider intake) | createPostgresFulfillmentProviderIntake composes verified ingress, first-envelope replay, recorded correlation, exact stock, scoped exception recovery and leased reconciliation over existing workers and commands. Supply committed SQL calls, declared channels, durable keys and accounting policy. A verified delivery with no incoming tracking can commit arrival from an existing exact parcel reference and a proven occurrence time. See the native recipe; offline evidence only. | | ./fulfillment/native (customer alignment) | createPostgresCustomerAlignmentRowsReader feeds readFulfillmentDelay with protected/aligned rows ordered by update time. Supply authorized subscription IDs and current schedules. Replacement creation queues only; selected native dispatch submits the new parcel independently, and actual arrival settles alignment. Overview remains host-bound. | | ./fulfillment/native (commerce projection) | Reduced createPostgresFulfillmentCommerceReadPort; requires the existing eligibility policy and explicit order-mode mapping. Its default destination reader calls the nonmutating shipment view through the supplied executor; an optional injected reader wins. Select nativeFulfillmentCommerceResponseSchemas explicitly when composing served commerce handlers; managed schemas remain the default. The preparation reader does not supply that boundary. Limits. | | ./subscriptions, ./subscriptions/contracts | Default-off, incomplete; subscription contracts and renewal port. | | ./invoicing, ./invoicing/contracts | Default-off invoicing contracts and independent duty collection; no provider activation. | | ./inventory | Schemas/ports, handlers, native stores, projection, injected forecast and SQL descriptor; ./inventory/contracts DTOs. | | ./catalog | Neutral catalog schemas, drafts, reads, media source packs and publication ports | | ./catalog/contracts | Dependency-free catalog DTOs, media resolver, authority and canonicalization helpers | | ./marketing/server | Node-only acquisition handlers, direct read/evidence factories and research orchestration without pg; host responder, authorization, binding and notification copy | | ./commerce/server/postgres | Existing native OMS control, reduced control-plane, delivered system-hold recovery and return lifecycle stores; host executor | | ./account-support/postgres | Existing native support journey factory; host runtime connection and operator context | | ./account-support/read-contracts | Browser-safe portable-client and Customer 360 read schemas, preserving validation and defaults | | ./marketing/server/postgres | Tester acquisition, partner inquiry and research evidence PostgreSQL port factories; requires the existing optional pg peer | | ./marketing/server (analytics context) | Injected analytics context handler with host persistence, capability and identity bindings | | ./marketing, ./marketing/contracts | Browser-safe tester history, partner inquiry lifecycle, portable prelaunch, survey evidence and newsletter consent schemas; type-only DTOs and tester/partner/research ports | | ./marketing, ./marketing/contracts (analytics) | Browser-safe acquisition and research schemas, injected analytics, paid purchase and consent-time facts; type-only DTOs and ports | | ./marketing, ./marketing/contracts (SEO and content slots) | Browser-safe JSON-LD serialization and graph builders, URL/hreflang helpers, ordered head data and contact/legal projections; type-only organization, contact, legal-document and privacy-processor content slots | | ./commerce, ./commerce/contracts | Browser-safe neutral commerce schema cores, generic ports and pure contract helpers | | ./commerce/server | Node-only OMS, returns, native reviews/media and hosted-feedback handlers/adapters and order-detail composition, email consumers, dispatch registry, paid-fulfillment binding and checkout compensation, checkout handlers, runtime and shared paid-order saga | | ./pricing | Price authority, quote computation/handlers, offer projection/cache, readiness and policy tokens | | ./pricing/browser | Existing quote primitives, acquisition validators, shipping-terms validator and the deriveSubscriptionUnitPrice display estimate, browser-safe | | ./pricing/contracts | Dependency-free authority, money, quote and offer DTOs and version constants | | ./promotions | Promotion application, admin handlers, native read/sweep, SQL projections and acceptance | | ./promotions/contracts | Dependency-free preview and admin DTOs | | ./tax, ./tax/contracts | Experimental tax contracts, local calculation and offline adapter conformance | | ./shipping | Delivery ports, injected-schema handlers, summary/evidence; native flat-rate port + Core schema readiness | | ./shipping/contracts | Type-only address, customer-address, delivery, pickup-point, shipping-rate and threshold contracts, plus selection summary and evidence DTOs | | ./storefront | Experimental, browser-safe purchase continuation: identity roles and their constructors, the continuation record and its recovery functions, an experimental continuation controller, host bindings and declarations, and the markup anchor names; storage, requests and provider facts only through host bindings | | ./storefront/testing | Test support for storefront proofs, Node only: the scenario, adapter, observer and page-handle contracts, createPageHandle over a Playwright page, the verdict serializer, the scenario runner and a PostgreSQL observer over the platform's tables; never in a buyer's bundle |

HTTP runtime and security contract

See HTTP admission and request handling.

The Node-only ./http entry builds a request handler around host-supplied route tables, dispatch, entrypoint loaders, deadlines, security-header policy, robots content and static-asset reader. Its request order is fixed: apply security headers, handle canonical trailing-slash redirects and declared entrypoints, dispatch the BFF and scheduled routes, refuse unknown API paths, then apply host-declared redirects and static-document rules. The package does not infer which application routes are authorized or supply deployment-specific header policy.

Buffered requests retain the exact raw bytes for signature verification while also exposing parsed JSON to handlers; the platform CSP-report entrypoint and explicitly marked stream-first handlers retain their live stream instead. Body size/deadline boundaries remain explicit. Static serving returns 404 for a missing asset, serves only declared route documents or an enabled SPA fallback, and leaves route admission to the host. These helpers define the HTTP adapter contract; they do not certify a deployed route or security policy.

Marketing contracts

See marketing handlers, analytics and consent.

The browser data-layer factory defaults to analytics-consent-only admission. Hosts may opt in with consentPolicy: "independent" to admit events with either stored analytics or marketing cookie consent. The explicit consentPolicy: "host-authorized" mode also admits observations when no purpose is granted, solely for hosts that authorize limited consent-aware transmission and enforce route and per-tag gates. Both nondefault modes keep consent updates tied to each stored category; pushAnalyticsConsentUpdate(false) denies both. The host must gate every tag by its own purpose, and may allow denied-state transmission only for explicitly authorized consent-aware tags. The factory does not inspect tag behavior or minimize event payloads; the host must authorize every admitted event and its data. Queue admission never authorizes storage or grants a purpose. In nondefault modes update(true) publishes stored flags and update(false) publishes all denial; neither switches the admission policy or fences routes. Queue admission does not prove delivery or attribution.

./marketing provides acquisition address references, historical case projections, list/count reads, portable prelaunch list/detail schemas, idempotency keys, survey submission/evidence/list schemas and newsletter consent events/responses. Reference compatibility shims forward the same schema objects and load the reference validation wrapper before package schemas. The marketing runtime entry configures the shared Zod instance in jitless mode before constructing schemas, preserving CSP-safe initialization for direct imports as well as reference facades, like the pricing, catalog and communications entries. The type-only ./marketing/contracts entry has no runtime initialization. The rich prelaunch DTO and case submit/transition schemas remain application-owned and are excluded from the browser entries. The shared acquisitionOpaqueReferenceSchema lets those retained contracts reuse the exact reference syntax. No entry registers a route automatically.

./marketing/contracts exports only types. Explicit acquisition DTO shapes are checked against the runtime schema inference by an executed TypeScript equality witness. The tester case port exposes list, get, active count and close; the app uses the server-only compatibility port for its retired methods. Evidence ports retain survey submission, survey listing and consent application. Port types are also forwarded through the runtime entry, following the commerce boundary. Both entries forward research schemas or types from the compatibility owner, @openlup/core/marketing/research; runtime schemas retain object identity. Tester case locale remains en|pl, matching its persisted constraint; partner inquiry SQL retains und. Widening it requires a separate migration. Historical wire values remain unchanged.

The source and built entries have browser graph proofs. The root test runner selects test/marketing/; the installed consumer checks both public entries, compiles typed usage and refuses deep imports. Kiosk and research reference contracts/ports continue to consume the core export. The app owns its admin response client and host composition.

./marketing/server owns acquisition case handlers, list/count and prelaunch list/detail factories, survey evidence submit/list and consent application, research submit/admin handlers and managed survey orchestration without loading pg. Select ./marketing/server/postgres for the three PostgreSQL port factories after installing the existing optional pg peer. Hosts inject the BFF responder, authorization and binding resolvers. Direct case reads receive the host bundle predicate at their original guard; prelaunch and evidence dispatch stays in the host. Notification HTML and subject are injected separately, preserving HTML rendering before the subject clock read. The reference owns retired route refusals, raw signed consent ingress and notification copy. PostgreSQL SQL, role selection and transaction/pool handling remain unchanged. The server-only compatibility command types do not expose retired admission schemas.

The partner lifecycle uses these same entries: ./marketing exports the strict partner_acquisition_v1 case/list/transition and inquiry submit schemas; ./marketing/contracts exports their DTOs and PartnerAcquisitionPort; ./marketing/server/postgres exports createPostgresPartnerAcquisitionPort. Partners retains domain and data ownership. The factory accepts an explicit connectionString, opens its pool lazily, and runs submit/list/transition through BEGIN → SET LOCAL ROLE platform_acquisition_runtime → routine → COMMIT. It preserves normalization, original command receipts, quota effects, descending cursor tuples and version fences. The host validates wire input, selects the neutral list view and authorizes operators before binding. The direct adapter does not enforce administrator membership; its SQL checks actor UUID presence.

Install the complete selected source catalogue before using the factory. The four existing partner SQL units are present in all three source plans; the npm package's sparse SQL assets do not constitute a complete partner installer. R1 adds no SQL, grants, route activation or host binding. The reference catch-all router has an empty route table; source BFF leaves alone do not establish serving endpoints. Host routing, authorization, legacy drain, environment selection, connection cache and pool disposal remain application-owned.

closed_won is a partner pipeline fact. It creates neither a customer identity nor marketing consent, provider notification or managed CRM transition. Rich managed inquiry/admin contracts stay separate. The strict submit schema accepts openlupInternalCheck; a host using another sentinel must map it explicitly at its compatibility seam. Current forms admit country OTHER and leading-zero phones that direct SQL refuses; this contribution preserves those refusals.

Partner personal-data export/erasure is unavailable, with resource duties recorded by the Partners owner. Existing marketing privacy-contributor coverage must not be read as partner coverage. Append-only receipts and audit are retained; nonempty acquisition state remains outside supported store transfer. The package contract, public counterpart/producer and real PostgreSQL witnesses freeze these limits. The PostgreSQL witness packs the current artifact, compiles both declaration modes, and executes its default factory against a disposable full native catalogue; it establishes no provider or hosted qualification.

Analytics facts share these browser-safe entries. createNoopAnalytics implements Core's existing analytics port; deployment and advertising defaults remain inert. AnalyticsEventMap<StepName> retains the host's literal step vocabulary, with string as the neutral default. Private transport ownership fields and envelopes remain host extensions. Types are forwarded type-only by ./marketing/contracts.

createAnalyticsDataLayer owns loader readiness per instance and accepts the host's browser/storage access, consent key and change event, consentSignalNames, event prefix, container reader and deployment callback. consentSignalNames supplies one analytics wire name and the ordered advertising wire names. Without it, no consent command is pushed and optional event admission returns false, even with browser access, a container and stored consent; deployment attempts remain independent. Consent commands seed default before update and use array-like arguments; advertising grants read marketing consent at push time. By default, update commands carry the caller-supplied analytics decision and optional events require the stored analytics flag. With consentPolicy: "independent", updates additionally require each purpose’s stored flag, and optional events accept either stored analytics or marketing consent. With consentPolicy: "host-authorized", optional events are admitted even before choice or after refusal, while updates still require each purpose’s stored flag. Optional event admission in every mode requires a configured container and configured signals. Hosts must independently fence private routes and unauthorized tags. The host owns authorization and must not use this helper to create consent; stored flags are admission inputs, not consent authority. An explicit all-denial update denies every signal. Sinks are attempted independently with failure isolation and no replay of observations made before consent. Admission booleans mean synchronous local acceptance only, never delivery or business acknowledgement.

createAnalyticsRoutePolicy requires public paths, redirect sources and all sensitive-path sets. Its optional-route predicate preserves broad eligibility; deployment URL sanitization admits exact public paths and safe campaign values. projectPaidPurchase consumes only structural paid-recap facts, preserving allocation/grouping, the item cap and ordered suppression reasons without an ambient currency policy. selectMarketingHistoricalConsentTime selects exact native chronology only after host authorization, without changing the local grant. The reference retains its narrower checkout-kind admission and all wire names. Purchase equivalence and the package analytics witnesses pin these boundaries.

createAnalyticsContextHandler in ./marketing/server accepts a required BFF responder, enable reader, persistence resolver, access-token reader, trusted-subject resolver, capability mint/hash functions, historical cookie name and clientIdField. The host supplies the client-id wire field name through clientIdField; the strict request also keeps granted and explicitGrant. Grants require a client id and existing revoked contexts require an explicit new grant for replacement. Only token hashes reach persistence. Enrollment uses only the server-verified subject, and invalid bearer grants refuse before writes. Cookie attributes and method/flag/origin/schema refusal order are preserved. The host owns flag and RPC names, gateway authority, route mounting and observability. Persistence operations must reject on failure; null persistence refuses as unavailable. There is no default persistence, portable SQL or reference route for this handler. An active result is a local context fact, never delivery, and telemetry context failure never gates commerce. The context witness exercises the factory through synthetic host bindings.

./marketing also provides browser-safe JSON-LD serialization and graph builders, route URL/hreflang helpers, an ordered head descriptor and plain contact/legal projections. Applications supply identity, origin, routes, locales, images and content; the descriptor is plain data for a host head manager. The type-only ./marketing/contracts entry exports shared organization facts and contact, legal-document and privacy-processor shapes, also forwarded as types by the runtime entry. The package supplies no document wording, processor inventory or content policy. The marketing recipe owns the mechanics and installed-artifact proof.

Marketing composition

See selecting marketing operations and privacy owners.

./composition exports createMarketingContribution, an inert descriptor for the marketing capability's ./marketing, ./marketing/contracts and ./marketing/server entries, with a runtime dependency on identity/contracts for obligation validation. Supply already-bound operations and host schema requirements. Ports, routes and triggers share the supplied functions; null ports remain required for Core readiness, and handlers retain only registration descriptors. Duplicate handler, schedule or route identities refuse. Construction invokes no callable and installs no worker, route or schedule. See the composition contract for the host admission boundary.

./marketing/server also exports createMarketingPrivacyContributor and createMarketingPrivacyBindings. Explicit enablement and both complete owner ports select one contributor; its exportPersonalData, assessErasure and eraseOrRetain callables can be passed directly to createMarketingContribution. Missing ownership makes coverage unavailable and erasure unresolved. Identity owns assessment ordering, subscription vetoes, receipt replay and transaction rollback; the marketing fence runs only during eraseOrRetain. Provider request acceptance never proves deletion. The reference leaves marketing unselected, so its marketing privacy coverage remains an open gap. See the privacy composition recipe.

The contributor and binding declarations use identity contract types and local structural interfaces compatible with identity's PersonalDataContributor. They do not reference identity's main entry; ./marketing/server compiles without pg or @types/pg. Select ./marketing/server/postgres explicitly for those ports.

Provider wiring recipes

For transactional email, email provider setup, marketing automation and ecommerce events, start with these offline examples from the application root. Save each complete TypeScript block as a separate .mts file and run it with Node 24. The examples use the installed package exports, synthetic data and injected HTTP only.

The captured delivery and protocol observation recipe is in Architecture and extensions; it is not shipped in this package.

Unqualified marketing integration

A host issues an opaque subject reference backed by its current subject registry. The type assertion below is the host's explicit TypeScript branding boundary; it grants no authorization. Never derive that reference from an email or treat a serialized branded string as trusted evidence.

import assert from "node:assert/strict";
import type { SyncRequest } from "@openlup/platform/communications/contracts";
import { createKlaviyoMarketingAdapter } from "@openlup/platform/communications/klaviyo";

const binding = { account: "synthetic", environment: "local",
  namespace: "example", mappingVersion: "1" };
const audience = { kind: "account-wide" } as const;
const subjectReference = "subject:example" as SyncRequest["subjectReference"];
const subject = { binding, subjectReference, generation: 1, erased: false,
  email: "[email protected]", externalReference: "local:example",
  ownedFields: [], ownedProperties: [] };
const values = new Map<string, string>();
let httpCalls = 0, credentialReads = 0, writes = 0;
const adapter = createKlaviyoMarketingAdapter({
  binding, audience,
  subjectMapper: reference => reference === subjectReference ? subject : undefined,
  resolveCredential: () => { credentialReads++; return undefined; },
  authorizations: new Map(), localEvidence: new Map(),
  storage: {
    availability: { account: binding.account, environment: binding.environment,
      busy: false, quarantined: true },
    get: async key => values.get(key) ?? null,
    compareAndSwap: async (key, expected, next) => {
      writes++;
      if ((values.get(key) ?? null) !== expected) return false;
      values.set(key, next); return true;
    },
  },
  fetch: async () => { httpCalls++; throw new Error("Unexpected HTTP"); },
  // Deliberately omit verification: no account qualification is claimed.
});
const result = await adapter.consent.read({
  binding, audience, subjectReference, requestId: "read:example", generation: 1,
  deadlineMs: Date.now() + 60000, authorizationReference: "unissued:example",
  operation: "consent.read", payload: {},
});
assert.equal(adapter.capabilities.operations["consent.read"].state, "verification_pending");
assert.equal(result.kind, "refused");
if (result.kind === "refused") assert.equal(result.reason, "verification_pending");
assert.deepEqual({ httpCalls, credentialReads, writes },
  { httpCalls: 0, credentialReads: 0, writes: 0 });
console.log({ result, httpCalls, credentialReads, writes });

The Map is an offline fixture, not durable application storage. A real host supplies current local authorization/consent evidence and exact-byte durable CAS, shares one availability record per account/environment and starts quarantined after restart. Quiesce old work, reconcile stored uncertainty, then reconstruct the adapters. Account qualification binds actual scopes, mappings and safe effects; copying verification flags from tests cannot establish it. The newsletter compatibility port remains unsupported. See the canonical construction/recovery contract at the source revision matching the installed package.

Retained ecommerce events with a fake endpoint

This separate fixture qualifies only its injected endpoint, which simulates deduplication by existing profile, metric and source identity. It creates no profile, sends no live request and proves no provider account qualification. The retained request carries integer JPY money and the currency owner's exponent provenance; retries reuse those exact bytes. The current local authority check still runs on every dispatch.

import assert from "node:assert/strict";
import type { EcommerceEventExportRequest } from "@openlup/platform/communications/contracts";
import { createKlaviyoMarketingAdapter } from "@openlup/platform/communications/klaviyo";
import { currencyExponent } from "@openlup/platform/market-packs";

const binding = Object.freeze({ account: "fake-account", environment: "local",
  namespace: "fake-events", mappingVersion: "ecommerce-v1" });
const subject = { binding, subjectReference: "subject:example", generation: 1,
  erased: false, id: "existing-profile-1", email: "[email protected]",
  externalReference: "local:example", ownedFields: [], ownedProperties: [] };
const request = Object.freeze<EcommerceEventExportRequest>({
  binding, subjectReference: subject.subjectReference, profileId: subject.id,
  generation: subject.generation, authorityReference: "local-authority:example",
  classification: "live", currencyExponent: currencyExponent("JPY"),
  currencyExponentSource: "market-packs.currencyExponent:JPY",
  event: { schemaVersion: 1, sourceId: "paid:example", sourceType: "order.paid",
    occurredAt: "2026-01-01T00:00:30.000Z",
    subject: { clientId: "00000000-0000-4000-8000-000000000001" },
    data: { orderId: "00000000-0000-4000-8000-000000000002",
      settlementIntentId: "00000000-0000-4000-8000-000000000003",
      purchaseKind: "one_time", amountMinor: 1000, currency: "JPY",
      lines: [{ sku: "example-sku", quantity: 1, amountMinor: 1000 }] } },
});
assert.equal(request.currencyExponent, 0);
const retainedDuty = JSON.stringify(request);
let currentAuthority = true, attempts = 0;
let clock = Date.parse("2026-01-01T00:01:00.000Z");
const values = new Map<string, string>(), fakeEffects = new Set<string>();
const adapter = createKlaviyoMarketingAdapter({
  binding, audience: { kind: "account-wide" }, now: () => clock,
  subjectMapper: reference => reference === subject.subjectReference ? subject : undefined,
  resolveCredential: () => ({ binding, key: "synthetic-not-a-real-key" }),
  authorizations: new Map(), localEvidence: new Map(),
  storage: {
    // Fresh empty fake fixture only; a real restart requires quarantined recovery.
    availability: { account: binding.account, environment: binding.environment,
      busy: false, quarantined: false },
    get: async key => values.get(key) ?? null,
    compareAndSwap: async (key, expected, next) => {
      if ((values.get(key) ?? null) !== expected) return false;
      values.set(key, next); return true;
    },
  },
  events: {
    liveSinceMs: Date.parse("2026-01-01T00:00:00.000Z"),
    authorize: candidate => currentAuthority && JSON.stringify(candidate) === retainedDuty,
    // Evidence belongs exclusively to the fake endpoint below. Never copy to a live account.
    verification: { binding, revision: "2026-07-15", evidenceReference: "fake-endpoint-only",
      scopes: ["events:write"], sourceTypes: ["order.paid"],
      accountEffectsVerified: true, messageOwnershipVerified: true },
  },
  fetch: async (url, init) => {
    assert.equal(url, "https://a.klaviyo.com/api/events");
    assert.equal(init?.method, "POST");
    const { data: { attributes } } = JSON.parse(String(init?.body)) as {
      data: { attributes: { profile: { data: { id: string } };
        metric: { data: { attributes: { name: string } } }; unique_id: string;
        value: number; value_currency: string } } };
    assert.equal(attributes.value, 1000);
    assert.equal(attributes.value_currency, "JPY");
    attempts++;
    const identity = [attributes.profile.data.id,
      attributes.metric.data.attributes.name, attributes.unique_id];
    assert.deepEqual(identity, [subject.id, "Placed Order", request.event.sourceId]);
    fakeEffects.add(JSON.stringify(identity));
    return new Response(null, { status: 202 });
  },
});
assert.equal((await adapter.events.exportEvent(request)).kind, "accepted");
clock += 1000;
assert.equal((await adapter.events.exportEvent(request)).kind, "accepted");
assert.deepEqual({ attempts, fakeEffects: fakeEffects.size }, { attempts: 2, fakeEffects: 1 });
currentAuthority = false;
assert.deepEqual(await adapter.events.exportEvent(request), { kind: "refused", reason: "restricted" });
assert.equal(attempts, 2);
console.log({ attempts, fakeEffects: fakeEffects.size, acceptance: "not ingestion evidence" });

The Map and Set model only local fixture storage and fake endpoint effects. A real host retains the exact projected duty, current authority and currency provenance durably; shares account availability; and reconciles uncertainty before clearing startup quarantine. Keep the live cutoff and mapping version fixed on retry. HTTP acceptance does not prove ingestion, flow execution or message delivery, and this fixture does not establish real receiver deduplication.

For the native PostgreSQL composition, install the complete migration chain and use createPostgresEcommerceEventProjection from the public communications entry. Supply one binding, immutable liveSince, now, local resolveTarget, and withTransaction that commits or rolls back the entire callback on one database connection. Supply currency: { code, exponent, provenance } from the host's selected settlement profile and currency owner. Call initialize with the approved new-fact cutoff, then project(limit) in a bounded postcommit job. Do not call it as a new prerequisite of payment commit.

Bind createPostgresEcommerceEventHandler to the same binding/transaction owner, the selected adapter's events port, clock and current authorize callback. Register that handler in its own outbox invocation with only ECOMMERCE_EXPORT_EVENT_TYPE; run commerce handlers in a separate invocation and lease. The worker owns dispatch/claim retries; the projector owns source handoff. Supply the selected finite platform vocabulary as knownEventTypes; known unclaimed facts do not become handlers, and an unknown type still refuses. The adapter's synchronous authority callback must also check the exact retained duty and current subject immediately before HTTP. A missing target records a visible refusal and cannot block unrelated subjects.

An unknown/dispatching receipt stays retained. Stop and quiesce the export lane, inspect the privileged matching receipt/digest, obtain provider evidence, then call reconcilePostgresEcommerceEvent with that exact digest, binding, evidence reference and explicit resolution. An identical retry additionally requires qualified deduplication and current authority; it preserves the original request. The helper refuses live claims and mismatched evidence. Keep raw projections and recovery snapshots out of logs. This operator action needs application-owned authentication and never fabricates account qualification.

Commerce contracts

./commerce/server also exports createPostgresCheckoutRecoveryTokenPort for a trusted host's already admitted order. Inject a dedicated transaction lane with effective service-role privileges. The port supports contacts without a principal, stores only token hashes and computes expiry as order creation plus 24 hours; the shared expiresAt argument cannot choose a deadline. New checkout links preserve earlier links of the same order until expiry or payment. Pending renewal-cycle orders are refused. Inspection preserves initial subscription mode and cadence from stored quote/activation facts, normalizes consumed links for paid confirmation, and grants payment continuation only through validation of an active pending order. It sends no mail and performs no settlement. See the recovery recipe.

./commerce/server exports createPostgresCheckoutRecoveryWaves. ./composition supplies createCheckoutRecoveryWaveJob and createCheckoutRecoveryWaveHttpEntry; ./communications supplies withCheckoutRecoverySendEvidence. Apply the complete migration chain before selecting them. Reminder waves atomically mint distinct links without revoking older checkout links. Pending initial purchases remain eligible; renewal-cycle orders refuse. Successful or recent active payment evidence suppresses nudges. A final wave that follows a first wave requires a confirmed first-wave receipt bound to its event, template and selected delivery profile, independently of outbox completion. Skipped, disabled, ambiguous and failed sends do not create that evidence. The existing recovery email handler remains the consumer.

./commerce/server exports createAdminCheckoutPaymentLinkHandler and createPostgresOperatorCheckoutLinkStore. The host supplies the verified active human administrator session, order snapshot/commercial validation, responder and positive operatorLifetimeMs / recoveryWindowMs configuration. The session supplies identity; request identity fields refuse. Native SQL checks the existing active operator authority and refuses machine principals and renewal-cycle orders.

The operator command commits admission, revokes every prior same-order checkout link, inserts its token, optionally queues the existing transactional recovery email, then records its outcome. Separate writes retain the acknowledged failure stage. Customer/service issuance remains nonrevoking, so a later such link coexists with the operator link. Concurrent operator revocations can both finish before either insert; both resulting links then remain live. Payment-case recovery is separate. Copy returns the token without email; email returns an explicit queued result only after durable per-token handoff. Expiry is the earlier configured deadline; an elapsed deadline returns order_not_recoverable without issuing a token. The operator UI and expired-checkout recreation require separate host composition. See the operator recipe.

./commerce/server/postgres also exports createPostgresCommercePriceAuthorityReadPort(executor). Allocate it once per request and pass it to createConcurrentCommercePriceAuthorityPort from ./pricing. It reads complete active price-list and exact unit-entry histories, plus the selected context's complete subscription-policy history. UUID demand waves are deduplicated and chunked at 500; result rows are never truncated. Matching keys use canonical UUID values; query arguments and returned identifiers keep their original spelling. Raw histories and failed promises are shared only within that request, with caller-owned copies. The existing authority selects half-open effective windows, validates policy digests and refuses ambiguity; the reader never chooses a newest winner or substitutes a fallback after a failed read. Supply the restricted runtime executor; the reader changes no role, grants, configuration or data.

./commerce/server/postgres exposes the existing native createPostgresCommerceOmsPort, createPostgresCommerceOmsControlPlane, createPostgresProviderExceptionHealPort and createPostgresCommerceReturnsPort. Supply an executor using the installation's restricted runtime login. These are store bindings: holds, exact release, unpaid cancellation, completed external-refund marking and return request/approve/reject. Control-plane reads remain the reduced control_plane_v1 projection. Rich OMS reads, notes, address correction retain their existing refusal. Replacement requests use the optional explicit replacement binding, which can be supplied by createPostgresFulfillmentOperatorPort from ./fulfillment/native. Returns allow one line per order item per request, with quantity capped at the ordered quantity. Returns record intent; they do not receive, restock or execute a refund. The host authenticates and authorizes each operation. The native operator resolver accepts an existing Commerce operator whose UUID is either an active control principal or an active human admin membership with no control row of any state. A human distributor, revoked member or admin without a Commerce row does not resolve. No authority is provisioned by the resolver. Human hosts must enforce admin-only admission and resolve again before every command and replay; the existing machine path is unchanged. The owner provisions a Commerce row for each human admin and never deletes it; withdraw human access by revoking membership. Deletion would set commerce_order_holds.created_by to NULL, making a human fulfillment-exception hold eligible for automatic release. This existing FK hazard is not changed. See the composition recipe.

With the complete catalogue through 20261110200000_operator_order_commands.sql, unpaid cancellation locks the current payment aggregate and refuses in-flight, captured or indeterminate payment before writing one operator audit and releasing the order's held purchase reservations. Late captures remain review-required. Manual external-refund marking accepts paid orders only and records status without a payment-provider call, refund notification or accounting reversal event. Existing object metadata keeps its keys; other metadata is retained under previousMetadata before the command writes its top-level source. Genuine refund sources retain their event duties. Neither operation changes an active subscription's lifecycle or schedule. With the complete catalogue through 20261110210000_return_request_decisions.sql, fresh return requests accept paid or fulfilled orders owned by the authenticated customer. Replay normalizes key/note whitespace, UUIDs, line order and defaults. Hosts declare a subset of the database's stored reason set. Codes outside the stored set receive a clean command refusal. New line SKUs use a trimmed supplied value, then the order-item snapshot SKU, then unknown. Historical NULL SKUs mean not recorded; historical receipts replay against their stored fingerprints. Trimmed key aliases are resolved before creation; a unique matching receipt replays its own ID, and ambiguous matches receive the uniform refusal without changing historical rows. Partial approval requires an amount. Approved/rejected decisions each emit one intent event; requests emit none. These commands do not receive goods, restock or execute refunds.

For native v1 destinations, use ./commerce/server/destinations with the complete native SQL installation. Authorize parent reads, use opaque references and bind checkout and dispatch explicitly. Share a transaction between the shipment reader and dispatch enqueue. Addresses, phone numbers and identifying references persist. Address-change events retain optional reasons in their top-level and nested payloads. The port provides no destination-row export or erasure. Use the separate saved-address port for the mutable book. The confirmation outbox is durable and native mail dispatch needs a host binding.

For experimental v2 ingress, discover native readiness with destinationV2Capabilities, then parse and apply the host address policy. Managed hosts support v1 checkout and saved addresses. Fresh v2 destination issuance requires an installed native writer. Use the v1 address book for saved addresses. Follow the destination validation guide.

./composition exports the inert createCommerceContribution for the installed commerce entries and selected callables. Duplicate descriptor identities refuse; the composition recipe and reference binding describe host readiness, one executor per operation and native recovery limits.

./commerce stays browser-safe. ./commerce/server is the separate Node-only entry for checkout engines, handlers, stores and adapters. It exports tryCompensate and CheckoutCompensationPort: release the selected order's reservations, attempt unstarted-promotion cancellation, then cancel the abandoned order only when promotion cleanup did not succeed. Existing keys, reasons, warning messages and swallowed cleanup failures are preserved. The reference facade delegates to the same function; composition still owns the cleanup ports. The package boundary test bundles the browser entry without Node built-ins or the server subtree, and the cold consumer exercises installed compensation. Starter declaration types are inferred from the createStarterOfferGuard binding signature; the declaration interface stays internal to the engine.

The Node-only entry owns the checkout admission/quote/resume/failure sequence, neutral command adapter, runtime and one paid-order saga. Composition injects HTTP schemas/responder, quote and persistence ports, subject/metadata projections and the existing prepared-payment execution callables. Provider roles, flow selection and trusted provider-evidence classification are reference inputs. Saved-method alias and recurring-mode strings are host-defined generics passed unchanged through resolver, saga and runtime; the evidence schema owns its internal JSON-length bound. The reference retains locale, fiscal, profile, starter-policy, request observation and status-link bindings. Acquisition expectations and accepted shipping terms require quote acceptance; offer asks require a bound policy. A matching owned saved epoch can resume; edited or incomplete state re-quotes. Stock refusal compensates only a proved pre-dispatch draft; scoped contention and uncertain dispatch carry no cleanup capability. A synchronous decline stays failed and is never auto-settled. Neutral finalize and one-time reservation conformance tests use recording ports; atomic acquisition/finalize SQL still requires integration with its migration chain.

The server entry also owns generic order-draft, runtime-finalize, intent-persistence and resume stores, cancellation adapters and reservation sweeps. Structural clients retain the incumbent RPC/table calls; composition supplies frozen snapshot schemas, ordered finalize arguments, response decoders and fail-open phone normalization. Use createCommerceOrderDraftRpcPort, createCheckoutCompensationRpcAdapter, createCommerceCheckoutResumeQueryPort and createConfiguratorIntentPersistenceRpcPort with structural clients, including ConfiguratorIntentRpcQueryClient for intent persistence. Reference bindings retain their incumbent exported factory names. Verified identity overwrites submitted identity after normalization. Draft retries supersede only once after an idempotency conflict; catalog refusals do not supersede. Recovery classifiers inject subject admission, compare shipping terms as well as money, and separate continuation, expiry policy and refused token states. Application recovery projection, routes and destinations stay in the host. SQL atomicity and active-subscription guards require real PostgreSQL integration; the C2 handoff release check is to be released.

./commerce/server/native-checkout exports createPostgresNativeCheckoutPersistence for the qualified-v2 draft rail. Bind a restricted runtime executor, pass a server-produced quoteSnapshot, and supply the route-authorized clientId through the separate options argument. The port validates quote money, derives the draft snapshot, and calls the existing guarded native draft routine with explicitly encoded JSON. It retains metadata.quoteSnapshot and metadata.orderDraftSnapshot, including line tax, totals and host context, for order-detail readers. A matching replay returns the durable draft receipt; changed input conflicts without superseding the order. The receipt's not_started field describes draft creation, not current payment truth. Neither creating nor replaying it settles an order or dispatches payment. Browser return handling and authenticated quote production belong to the host. Existing native refusals for line discounts and zero-payable orders still apply. Catalogue and prices are install-time seed data on this rail; this port adds no price writer or managed-rail behavior. The installed PostgreSQL witness checks snapshot retention, refusal, concurrent replay and fresh-process recovery.

createPostgresAcquisitionCheckoutPersistence adds final acquisition admission over that persistence port. Supply a restricted runtime pool with exclusive checked-out connections, the region, the existing financial policy and a host classifier for acquisition discount semantics. It owns one READ COMMITTED transaction: serialize the normalized native idempotency key, lock the existing scoped definitions, re-read the current promise and paid-family facts, check the quote's capability and pricing policy, then persist and commit the draft on that connection. Changed second-delivery promises refuse even when initial money is unchanged. Missing standalone capability raises AcquisitionTermsError with acquisition_terms_capability_required; incompatible engines raise acquisition_terms_v2_required. A changed promise raises acquisition_terms_changed. Existing matching receipts replay before current offer checks; the lower writer still validates replay ownership and input. An ordinary returning subscription may omit acquisition terms only with complete discount evidence, no acquisition grant or marker, and paid-family evidence. Admission re-checks paid-family eligibility for the ordinary-returning path; a quote issued before the family's first payment stays admissible until it expires, as in the reference implementation. The host must pass only a quote produced on the server, authorize the buyer and verify quote acceptance before calling this boundary. A host that mounts acquisition routing must route every acquisition caller through this adapter; the mounting integration supplies its own no-bypass witness. The lower persistence factory remains available for trusted composition and does not enforce acquisition admission. No route is mounted by either factory. Definition writers must share the same row-lock protocol; this adapter adds no schedule-insertion protocol or writer.

./commerce/contracts is a type-only, browser-safe entry for commerce-owned records and generic persistence, checkout/runtime, availability, recovery and offer-policy ports. It imports no pricing module. Consume pricing DTOs from ./pricing/contracts directly. Commerce does not re-export pricing DTOs; its runtime reuses the version constant through ./pricing/contracts. Quote ports take the host request, response and existing options as type parameters; the reference binds the existing pricing definitions, adding only the server-bound offer.

./commerce/server supplies the Node-only O