@tokenoftrust/storefront-runner 8.0.1 → 8.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +15 -7
  2. package/apps/storefront/src/components/publication/storefront/islands/CatalogQueryView.tsx +6 -1
  3. package/apps/storefront/src/layouts/Layout.astro +39 -1
  4. package/apps/storefront/src/lib/compliance/shopper/statePickerClient.ts +622 -67
  5. package/apps/storefront/src/lib/compliance/shopper/staticEligibilityArtifact.ts +182 -0
  6. package/apps/storefront/src/lib/compliance/shopper/staticEligibilityPointerGate.ts +13 -0
  7. package/apps/storefront/src/middleware/renderChain.ts +44 -25
  8. package/apps/storefront/src/middleware/routeBranch.ts +1 -0
  9. package/apps/storefront/src/middleware/staticBundle.ts +3 -0
  10. package/apps/storefront/src/pages/eligibility.json.ts +23 -0
  11. package/package.json +1 -1
  12. package/packages/cli/src/publication-spaces.mjs +1 -1
  13. package/packages/public-runtime/package.json +1 -0
  14. package/packages/public-runtime/schemas/publication-space/v1/manifest.schema.json +1 -1
  15. package/packages/public-runtime/schemas/publication-space/v1/normalized-mount.schema.json +1 -1
  16. package/packages/public-runtime/src/compliance/evaluate.ts +13 -0
  17. package/packages/public-runtime/src/compliance/state-directory.ts +16 -2
  18. package/packages/public-runtime/src/compliance/static-eligibility.d.mts +92 -0
  19. package/packages/public-runtime/src/compliance/static-eligibility.mjs +394 -0
  20. package/packages/public-runtime/src/declared-tenant-config.mjs +1 -1
  21. package/packages/public-runtime/src/publication-space.ts +1 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Worker-side producer of the static shopper-eligibility artifact
3
+ * (`@tot/public-runtime/compliance/static-eligibility`, ADR 0013 + ADR 0047).
4
+ *
5
+ * Projects the tenant's declarative rule pack (merged stricter-only with the tenant's overlays) and
6
+ * its catalog's product facts into the public-only artifact a published page filters on in the
7
+ * browser. The projection reads the rule pack's own data (regions, ZIP prefixes, registry
8
+ * predicates) and the engine's own subject matcher, so the static layer cannot drift from the
9
+ * authoritative checkout evaluation (`POST /api/compliance/preflight`), which stays the enforcement
10
+ * seam.
11
+ *
12
+ * Fail-closed projection: a declared-but-empty or malformed licensed footprint restricts every
13
+ * state, exactly as `evaluateCartCompliance` does; an allow-list that names no valid US state is
14
+ * encoded `[]` (ships nowhere), never dropped to "no restriction".
15
+ */
16
+ import type { CatalogProduct, ComplianceRule, ComplianceRuleset, TenantConfig } from "@tot/public-runtime";
17
+ import {
18
+ deriveProductProfile,
19
+ mergeTenantOverrides,
20
+ normalizeRegionCode,
21
+ ruleSubjectOutcome,
22
+ unconditionalProhibitedRegions,
23
+ } from "@tot/public-runtime";
24
+ import {
25
+ extractDirectoryStatesFromTags,
26
+ normalizeUsStateCode,
27
+ US_STATE_OPTIONS,
28
+ } from "@tot/public-runtime/compliance/state-directory";
29
+ import {
30
+ buildStaticEligibilityArtifact,
31
+ staticEligibilityRevisionSource,
32
+ type StaticEligibilityArtifact,
33
+ type StaticEligibilityZipScope,
34
+ } from "@tot/public-runtime/compliance/static-eligibility";
35
+ import { COMPLIANCE_RULE_PROFILES } from "@/config/compliance/rulesets";
36
+ import { resolveTenantRuleset } from "@/lib/compliance/enforcement";
37
+
38
+ type EligibilityTenant = Pick<TenantConfig, "tenant_id" | "compliance">;
39
+
40
+ /** Ruleset version used when a tenant declares state eligibility without a rule profile. */
41
+ export const DECLARED_ELIGIBILITY_RULESET_VERSION = "declared-state-eligibility:1";
42
+
43
+ /**
44
+ * The provenance `rulesetVersion` for a tenant, or `null` when the tenant has no eligibility
45
+ * surface at all (no rule profile and no declared state eligibility). Synchronous so the layout can
46
+ * decide whether to emit the page pointer without resolving the ruleset.
47
+ */
48
+ export function staticEligibilityRulesetVersion(tenant: EligibilityTenant): string | null {
49
+ const profile = tenant.compliance?.ruleProfile;
50
+ if (profile) {
51
+ const build = COMPLIANCE_RULE_PROFILES[profile];
52
+ if (!build) return null;
53
+ const pack = build(tenant.tenant_id).rulePack;
54
+ return `${pack.packId}:${pack.version}`;
55
+ }
56
+ return tenant.compliance?.stateEligibility ? DECLARED_ELIGIBILITY_RULESET_VERSION : null;
57
+ }
58
+
59
+ interface RegistryPredicateRule {
60
+ rule: ComplianceRule;
61
+ regions: string[];
62
+ jurisdiction: string;
63
+ zipPrefixes: string[];
64
+ }
65
+
66
+ /** The rules whose effect is a registry-listing requirement, with their destination and jurisdiction. */
67
+ function registryRules(rules: readonly ComplianceRule[]): RegistryPredicateRule[] {
68
+ const out: RegistryPredicateRule[] = [];
69
+ for (const rule of rules) {
70
+ const effect = rule.effect;
71
+ if (effect.kind !== "require_predicate") continue;
72
+ const predicate = effect.predicate as { field?: unknown; op?: unknown; value?: unknown };
73
+ if (predicate.field !== "catalog.registryListings" || predicate.op !== "registry_listed" ||
74
+ typeof predicate.value !== "string") continue;
75
+ const destination = rule.when?.destination;
76
+ const regions = (destination?.regions ?? []).map((r) => normalizeRegionCode(r)).filter(Boolean);
77
+ if (regions.length === 0) continue;
78
+ out.push({
79
+ rule,
80
+ regions,
81
+ jurisdiction: predicate.value,
82
+ zipPrefixes: [...(destination?.zipPrefixes ?? [])],
83
+ });
84
+ }
85
+ return out;
86
+ }
87
+
88
+ const ALL_STATE_CODES = US_STATE_OPTIONS.map((state) => state.code);
89
+
90
+ /**
91
+ * Build the artifact for `tenant` over its active `products`, or `null` when the tenant has no
92
+ * eligibility surface. `catalogRevision` is the content hash of the eligibility inputs.
93
+ */
94
+ export async function buildTenantStaticEligibility(
95
+ tenant: EligibilityTenant,
96
+ products: readonly CatalogProduct[],
97
+ ): Promise<StaticEligibilityArtifact | null> {
98
+ const rulesetVersion = staticEligibilityRulesetVersion(tenant);
99
+ if (!rulesetVersion) return null;
100
+
101
+ const declared = tenant.compliance?.stateEligibility;
102
+ const ruleset: ComplianceRuleset | null = tenant.compliance?.ruleProfile
103
+ ? await resolveTenantRuleset(tenant)
104
+ : null;
105
+ const merged = ruleset ? mergeTenantOverrides(ruleset.rulePack, ruleset.tenantOverrides) : null;
106
+ const rules = merged?.rules ?? [];
107
+
108
+ const restricted = new Set<string>();
109
+ for (const code of declared?.restrictedStates ?? []) {
110
+ const normalized = normalizeUsStateCode(code);
111
+ if (normalized) restricted.add(normalized);
112
+ }
113
+ if (ruleset) {
114
+ for (const code of unconditionalProhibitedRegions(ruleset)) {
115
+ const normalized = normalizeUsStateCode(code);
116
+ if (normalized) restricted.add(normalized);
117
+ }
118
+ }
119
+
120
+ // A footprint the engine fails closed on (declared but empty, or with a malformed entry) refuses
121
+ // every destination here too.
122
+ const footprintDeclared = merged ? merged.licensedStates !== null : Array.isArray(declared?.eligibleStates);
123
+ const licensed = merged?.licensedStates ?? declared?.eligibleStates ?? [];
124
+ const eligibleStates = licensed.map((code) => normalizeUsStateCode(code)).filter((code): code is string => code !== null);
125
+ if (footprintDeclared && (eligibleStates.length === 0 || merged?.licensedStatesInvalid)) {
126
+ for (const code of ALL_STATE_CODES) restricted.add(code);
127
+ }
128
+
129
+ const registry = registryRules(rules);
130
+ const zipScopes: StaticEligibilityZipScope[] = registry
131
+ .filter((entry) => entry.zipPrefixes.length > 0)
132
+ .flatMap((entry) => entry.regions.map((region) => ({
133
+ region,
134
+ jurisdiction: entry.jurisdiction,
135
+ zipPrefixes: entry.zipPrefixes,
136
+ })));
137
+ const stateRegistry = registry.filter((entry) => entry.zipPrefixes.length === 0);
138
+
139
+ const entries = products.map((product) => {
140
+ const profile = deriveProductProfile(product);
141
+ const reading = profile.catalogFacts.registryListings;
142
+ const registryStates = new Set<string>();
143
+ for (const entry of [...stateRegistry, ...registry.filter((e) => e.zipPrefixes.length > 0)]) {
144
+ // `indeterminate` (an unread fact) is held to the registry: fail closed.
145
+ if (ruleSubjectOutcome(entry.rule, profile) === "false") continue;
146
+ for (const region of entry.regions) {
147
+ const code = normalizeUsStateCode(region);
148
+ if (code) registryStates.add(code);
149
+ }
150
+ }
151
+ const allowed = profile.allowedRegions === null
152
+ ? null
153
+ : profile.allowedRegions.map((code) => normalizeUsStateCode(code)).filter((code): code is string => code !== null);
154
+ return {
155
+ handle: product.handle,
156
+ allowedStates: allowed,
157
+ restrictedStates: profile.restrictedRegions.map((code) => normalizeUsStateCode(code)).filter((code): code is string => code !== null),
158
+ directoryStates: extractDirectoryStatesFromTags(product.tags),
159
+ registryStates: [...registryStates],
160
+ registryListings: reading.state === "known" ? { ...reading.value } as Record<string, string> : null,
161
+ };
162
+ });
163
+
164
+ const body = buildStaticEligibilityArtifact({
165
+ provenance: { tenant: tenant.tenant_id, catalogRevision: "pending", rulesetVersion },
166
+ rules: {
167
+ directoryStates: declared?.directoryStates ?? [],
168
+ restrictedStates: [...restricted],
169
+ eligibleStates,
170
+ zipScopes,
171
+ },
172
+ products: entries,
173
+ });
174
+ const revision = (await sha256Hex(staticEligibilityRevisionSource(body))).slice(0, 32);
175
+ return { ...body, provenance: { ...body.provenance, catalogRevision: revision } };
176
+ }
177
+
178
+ /** sha256 hex over UTF-8 text with WebCrypto (the Worker and the browser both have it). */
179
+ async function sha256Hex(text: string): Promise<string> {
180
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
181
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
182
+ }
@@ -0,0 +1,13 @@
1
+ import { closedCatalogPath } from "@tot/public-runtime/declared-tenant-config";
2
+
3
+ /**
4
+ * Whether a page may carry the static-eligibility pointer, status shell and boot script.
5
+ *
6
+ * A closed store serves the artifact only to an admitted shopper (`closedCatalogPath` "admit"):
7
+ * an unadmitted visitor is redirected to sign-in. So its public "allow" routes (home, content
8
+ * pages) must not fetch it, or they would show the fail-closed unavailable banner. Every other
9
+ * store carries the pointer on every page.
10
+ */
11
+ export function staticEligibilityPointerAllowed(accessMode: string, path: string): boolean {
12
+ return accessMode !== "closed_store" || closedCatalogPath(path) === "admit";
13
+ }
@@ -462,6 +462,8 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
462
462
  ? input.managedIntegrationDeclarations
463
463
  : await readBakedManagedInstalls(request, tenant.tenant_id, readEnv);
464
464
 
465
+ const materializeMode = (await readEnv(MATERIALIZE_MODE_BINDING)) === "1";
466
+
465
467
  // Digest-addressed static-bundle serving. Deliberately before the edge page
466
468
  // cache/catalog/theme machinery. A selected publication bypasses this legacy
467
469
  // whole-site bundle until B1 can compose mounted spaces into it reproducibly.
@@ -492,6 +494,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
492
494
  hasCandidatePin: !!candidatePin,
493
495
  hasDraftCookie: !!draftCookie,
494
496
  hasManagedInstalls: managedIntegrationDeclarations.length > 0,
497
+ isMaterializeMode: materializeMode,
495
498
  ...(originalsBucket
496
499
  ? {
497
500
  capturedOriginal: {
@@ -575,7 +578,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
575
578
  // Either gate failing ⇒ fall through to the caller-supplied reader (control plane
576
579
  // only), never a caller-supplied snapshot.
577
580
  let bakedConsent: ReturnType<typeof parseConsentSnapshot> = null;
578
- if ((await readEnv(MATERIALIZE_MODE_BINDING)) === "1") {
581
+ if (materializeMode) {
579
582
  const consentInputHeader = request.headers.get(CONSENT_SNAPSHOT_INPUT_HEADER);
580
583
  const consentSig = request.headers.get(CONSENT_SNAPSHOT_SIG_HEADER);
581
584
  const hmacSecret = await readEnv(CONSENT_SNAPSHOT_HMAC_SECRET_BINDING);
@@ -613,8 +616,11 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
613
616
  // API in .wrangler/state, so a cached page would be served stale across edits AND
614
617
  // restarts — silently defeating hot-reload (edits look "lost"). Dev must always
615
618
  // re-render. import.meta.env.DEV statically drops this guard from the prod build.
619
+ // Materialize mode renders fresh pages with request-bound baked inputs and capture
620
+ // headers, so it bypasses the edge page cache completely.
616
621
  const pageCacheEligible =
617
622
  !import.meta.env.DEV &&
623
+ !materializeMode &&
618
624
  request.method.toUpperCase() === "GET" &&
619
625
  !isPreviewHost &&
620
626
  !preview.presented &&
@@ -644,10 +650,13 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
644
650
  const key = pageKey;
645
651
  const hit = await timed(timing, "page-cache", () => getCachedPage(cache, key));
646
652
  timing?.note("cache", hit ? "hit" : "miss");
647
- // The cached artifact is nonce-free (carries the placeholder). Stamp a fresh
648
- // per-response nonce into its body + CSP header so a warm hit is served with a
649
- // brand-new nonce, never the one an earlier response rendered with.
650
- if (hit) return await stampResponseNonce(hit, freshNonce());
653
+ // The cached artifact is nonce-free (carries the placeholder) and stored without
654
+ // materialize capture headers. Stamp any capture headers requested on this probe
655
+ // and a fresh per-response nonce so a warm hit matches a cold render.
656
+ if (hit) {
657
+ applyMaterializeCaptureHeaders(hit, request, tenant, shopperDelivery, materializeMode);
658
+ return await stampResponseNonce(hit, freshNonce());
659
+ }
651
660
  }
652
661
 
653
662
  const proto = url.protocol === "http:" ? "http" : "https";
@@ -927,7 +936,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
927
936
  pageBase: locals.basePath ?? basePath,
928
937
  apiBase: basePath,
929
938
  nonce: cspNonce,
930
- capture: isPublicationCapture(request.headers, await readEnv(MATERIALIZE_MODE_BINDING)),
939
+ capture: isPublicationCapture(request.headers, materializeMode ? "1" : null),
931
940
  cdnForwarded: locals.cdnForwarded === true,
932
941
  internalPublication: isInternalPublication,
933
942
  // Annotations and tours both identify the document; one KV read serves both.
@@ -1066,25 +1075,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
1066
1075
  // A preview-token (`test`) render is unpublished content shown to one viewer: no
1067
1076
  // browser, proxy, or CDN may keep it or hand it to the next visitor of this URL.
1068
1077
  if (customization.env === "test") response.headers.set("Cache-Control", "private, no-store");
1069
- // MATERIALIZE-ONLY capture (ADR 0013): expose the tenant's resolved route-document
1070
- // Cache-Control so the publish/materialize plane can bake it into the bundle
1071
- // manifest (the same capture pattern as CSP). Gated on the materialize probe
1072
- // request header, so it NEVER reaches a public client — the LIVE served header
1073
- // comes from the manifest via `static-bundle`, not from this signal.
1074
- if (request.headers.get(HTML_CACHE_POLICY_CAPTURE_PROBE)) {
1075
- response.headers.set(
1076
- HTML_CACHE_POLICY_CAPTURE_HEADER,
1077
- formatHtmlCacheControl(locals.tenant?.serving?.htmlCachePolicy),
1078
- );
1079
- // The tenant's declared origins — the same `domains` the Worker's own image scans use. The
1080
- // materializer ships images a page references absolutely on them (og:image is always
1081
- // absolute), and the publish scan classifies such references by path instead of as
1082
- // third-party hotlinks.
1083
- response.headers.set(TENANT_ORIGINS_CAPTURE_HEADER, declaredTenantOrigins(tenant).join(","));
1084
- if (await readEnv(MATERIALIZE_MODE_BINDING) === "1") {
1085
- response.headers.set("x-tot-shopper-delivery", JSON.stringify(shopperDelivery));
1086
- }
1087
- }
1078
+ applyMaterializeCaptureHeaders(response, request, locals.tenant ?? tenant, shopperDelivery, materializeMode);
1088
1079
  if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
1089
1080
  // Stamp a fresh per-response nonce into this cold response's body + CSP header
1090
1081
  // (the warm-hit path above stamps its own). Both paths therefore serve a fresh,
@@ -1093,6 +1084,34 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
1093
1084
  return await timed(timing, "nonce", () => stampResponseNonce(stamped, freshNonce()));
1094
1085
  }
1095
1086
 
1087
+ /**
1088
+ * Materialize-only capture headers (ADR 0013): expose the tenant's route-document
1089
+ * Cache-Control, declared origins, and (in materialize mode) shopper delivery policy
1090
+ * when requested by the materialize capture probe. Applied after page-cache writes
1091
+ * and on warm hits so cached artifacts never retain capture headers.
1092
+ */
1093
+ function applyMaterializeCaptureHeaders(
1094
+ response: Response,
1095
+ request: Request,
1096
+ tenant: TenantConfig,
1097
+ shopperDelivery: ReturnType<typeof shopperDeliveryPolicy>,
1098
+ materializeMode: boolean,
1099
+ ): void {
1100
+ if (!request.headers.get(HTML_CACHE_POLICY_CAPTURE_PROBE)) return;
1101
+ response.headers.set(
1102
+ HTML_CACHE_POLICY_CAPTURE_HEADER,
1103
+ formatHtmlCacheControl(tenant.serving?.htmlCachePolicy),
1104
+ );
1105
+ // The tenant's declared origins — the same `domains` the Worker's own image scans use. The
1106
+ // materializer ships images a page references absolutely on them (og:image is always
1107
+ // absolute), and the publish scan classifies such references by path instead of as
1108
+ // third-party hotlinks.
1109
+ response.headers.set(TENANT_ORIGINS_CAPTURE_HEADER, declaredTenantOrigins(tenant).join(","));
1110
+ if (materializeMode) {
1111
+ response.headers.set("x-tot-shopper-delivery", JSON.stringify(shopperDelivery));
1112
+ }
1113
+ }
1114
+
1096
1115
  /**
1097
1116
  * Inline a run of distinct tenant theme stylesheets into a preview document.
1098
1117
  * Bytes follow the `/tenants/<id>/` route: publication root, then the preview
@@ -84,6 +84,7 @@ export const PLATFORM_PUBLIC_DISCOVERY_PATHS = [
84
84
  */
85
85
  export const PLATFORM_PUBLIC_APP_ROUTE_PREFIXES = [
86
86
  "/catalog-index.json",
87
+ "/eligibility.json",
87
88
  "/collections",
88
89
  "/products",
89
90
  "/saved",
@@ -32,6 +32,8 @@ export interface StaticBundleAttemptInput {
32
32
  hasDraftCookie: boolean;
33
33
  /** Managed installs inject document markup, so a bundled DOCUMENT would be stale. */
34
34
  hasManagedInstalls: boolean;
35
+ /** Materialize mode renders fresh source documents, never a prior static bundle. */
36
+ isMaterializeMode?: boolean;
35
37
  /**
36
38
  * When set, a `/_a/<sha>` miss falls through to revision-bound captured
37
39
  * originals (hosted preview image capture) before returning 404.
@@ -151,6 +153,7 @@ export async function tryServeStaticBundle(
151
153
  !input.hasCandidatePin &&
152
154
  !input.hasDraftCookie &&
153
155
  !input.hasManagedInstalls &&
156
+ !input.isMaterializeMode &&
154
157
  !/^\/(?:api|account)(?:\/|$)/i.test(url.pathname);
155
158
  if (!eligible) return null;
156
159
 
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Static shopper-eligibility artifact (lib/compliance/shopper/staticEligibilityArtifact.ts,
3
+ * `@tot/public-runtime/compliance/static-eligibility`). The published pages filter their catalog
4
+ * cards and gate add-to-cart in the browser over this document, so it is rendered here once and the
5
+ * publish step pins it to a content address (`/_a/<sha256>.json`); a static host never calls this
6
+ * route. Public-only by schema: no prices, costs, B2B, draft or secret data.
7
+ */
8
+ import type { APIContext } from "astro";
9
+ import { serializeStaticEligibilityArtifact } from "@tot/public-runtime/compliance/static-eligibility";
10
+ import { buildTenantStaticEligibility } from "@/lib/compliance/shopper/staticEligibilityArtifact";
11
+
12
+ export async function GET(context: APIContext): Promise<Response> {
13
+ const { tot, tenant } = context.locals;
14
+ const products = await tot.getAllActiveProducts();
15
+ const artifact = await buildTenantStaticEligibility(tenant, products);
16
+ if (!artifact) return new Response(null, { status: 404 });
17
+ return new Response(serializeStaticEligibilityArtifact(artifact), {
18
+ headers: {
19
+ "content-type": "application/json; charset=utf-8",
20
+ "cache-control": "public, max-age=300, s-maxage=3600",
21
+ },
22
+ });
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "8.0.1",
3
+ "version": "8.1.1",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -36,7 +36,7 @@ export const PLATFORM_PATHS = Object.freeze([
36
36
  "/apps", "/assets", "/auth", "/brand", "/capabilities", "/cockpit", "/dashboard", "/dev",
37
37
  "/favicon.svg", "/health", "/js", "/feed.json", "/llms.txt", "/publication-discovery",
38
38
  "/search-index.json", "/sitemap.xml", "/platform", "/preview", "/products", "/collections",
39
- "/search", "/catalog-index.json", "/saved", "/robots.txt", "/shared", "/style-guide", "/tenants",
39
+ "/search", "/catalog-index.json", "/eligibility.json", "/saved", "/robots.txt", "/shared", "/style-guide", "/tenants",
40
40
  ]);
41
41
 
42
42
  const SPACE_ID = /^[a-z0-9](?:[a-z0-9._-]{0,126}[a-z0-9])?$/;
@@ -50,6 +50,7 @@
50
50
  "./theme-stylesheets": "./src/theme-stylesheets.mjs",
51
51
  "./compliance-coherence": "./src/compliance-coherence.mjs",
52
52
  "./compliance/state-directory": "./src/compliance/state-directory.ts",
53
+ "./compliance/static-eligibility": "./src/compliance/static-eligibility.mjs",
53
54
  "./integration/lifecycle-host-asset": "./src/integration/lifecycle-host-asset.mjs",
54
55
  "./integration/native-ga4-sandbox-asset": "./src/integration/native-ga4-sandbox-asset.mjs",
55
56
  "./integration/visitor-region": "./src/integration/visitor-region.mjs"
@@ -207,7 +207,7 @@
207
207
  "mountPath": {
208
208
  "allOf": [
209
209
  { "$ref": "#/$defs/path" },
210
- { "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][vV][aA][iI][lL][aA][bB][iI][lL][iI][tT][yY]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][cC][cC][oO][uU][nN][tT]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
210
+ { "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][vV][aA][iI][lL][aA][bB][iI][lL][iI][tT][yY]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][cC][cC][oO][uU][nN][tT]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[eE][lL][iI][gG][iI][bB][iI][lL][iI][tT][yY]\\.[jJ][sS][oO][nN]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
211
211
  ]
212
212
  },
213
213
  "aliasPath": {
@@ -67,7 +67,7 @@
67
67
  "mountPath": {
68
68
  "allOf": [
69
69
  { "$ref": "#/$defs/normalizedPath" },
70
- { "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][vV][aA][iI][lL][aA][bB][iI][lL][iI][tT][yY]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][cC][cC][oO][uU][nN][tT]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
70
+ { "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][vV][aA][iI][lL][aA][bB][iI][lL][iI][tT][yY]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][cC][cC][oO][uU][nN][tT]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[eE][lL][iI][gG][iI][bB][iI][lL][iI][tT][yY]\\.[jJ][sS][oO][nN]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
71
71
  ]
72
72
  },
73
73
  "aliasPath": {
@@ -327,6 +327,19 @@ function matchesSubject(
327
327
  return evalPredicate(rule.when.subjectMatch, line);
328
328
  }
329
329
 
330
+ /**
331
+ * Whether `rule`'s `subjectMatch` selects a product with this `profile`: `"true"` / `"false"`, or
332
+ * `"indeterminate"` when a fact it reads is unknown. A rule with no `subjectMatch` selects every
333
+ * product. Exposed so the static eligibility projection scopes a registry rule to the products the
334
+ * engine itself would hold to it, rather than restating the predicate.
335
+ */
336
+ export function ruleSubjectOutcome(
337
+ rule: ComplianceRule,
338
+ profile: ProductComplianceProfile,
339
+ ): "true" | "false" | "indeterminate" {
340
+ return matchesSubject(rule, { sku: "", quantity: 1, profile });
341
+ }
342
+
330
343
  export function evaluateCartCompliance(
331
344
  input: CartComplianceInput,
332
345
  ): CartComplianceDecision {
@@ -235,6 +235,11 @@ export interface StateDirectoryRule {
235
235
  export interface ProductStateEligibilityInput {
236
236
  /** Explicit per-product ship-to allow-list (when non-empty, only listed states are eligible). */
237
237
  allowedStates?: readonly string[] | null;
238
+ /**
239
+ * The product declares an allow-list that names no valid state (`allowedRegions === []`): it
240
+ * ships nowhere. Distinct from an absent allow-list, which restricts nothing.
241
+ */
242
+ shipsNowhere?: boolean;
238
243
  /** Explicit per-product no-ship list. */
239
244
  restrictedStates?: readonly string[] | null;
240
245
  /** Product tags; `directory:<ST>`, `state-directory:<ST>`, and `state:<ST>` grant directory eligibility. */
@@ -243,6 +248,11 @@ export interface ProductStateEligibilityInput {
243
248
  registryListings?: CatalogReading<RegistryListingMap> | null;
244
249
  /** City registries the ship-to falls under (e.g. `["SF"]`). */
245
250
  localJurisdictions?: readonly string[] | null;
251
+ /**
252
+ * States whose registry listing this product must hold, in addition to the store-wide
253
+ * `config.directoryStates` (a registry rule that selects this product, not every product).
254
+ */
255
+ registryStates?: readonly string[] | null;
246
256
  }
247
257
 
248
258
  export type ProductStateEligibilityReason =
@@ -280,6 +290,9 @@ export function evaluateProductStateEligibility(
280
290
  config?: StateDirectoryRule | null,
281
291
  ): ProductStateEligibilityDecision {
282
292
  const normalized = normalizeUsStateCode(stateCode);
293
+ if (product.shipsNowhere === true) {
294
+ return { eligible: false, reason: "state-restricted", stateCode: normalized };
295
+ }
283
296
  if (!normalized) {
284
297
  return { eligible: true, reason: "no-state-selected", stateCode: null };
285
298
  }
@@ -297,6 +310,7 @@ export function evaluateProductStateEligibility(
297
310
 
298
311
  const productAllowed = normalizeStateSet(product.allowedStates);
299
312
  const directoryStates = normalizeStateSet(config?.directoryStates);
313
+ for (const code of normalizeStateSet(product.registryStates)) directoryStates.add(code);
300
314
  if (directoryStates.has(normalized)) {
301
315
  const registry = resolveRegistryEligibility(product.registryListings, normalized, product.localJurisdictions);
302
316
  if (registry.refused) {
@@ -377,7 +391,7 @@ export function revalidateCartForState<TLine extends CartRevalidationLine>(
377
391
  config?: StateDirectoryRule | null,
378
392
  ): CartStateRevalidationResult<TLine> {
379
393
  const normalized = normalizeUsStateCode(stateCode);
380
- if (!normalized) {
394
+ if (!normalized && !lines.some((line) => resolveProduct(line)?.shipsNowhere === true)) {
381
395
  return {
382
396
  stateCode: null,
383
397
  kept: [...lines],
@@ -403,6 +417,6 @@ export function revalidateCartForState<TLine extends CartRevalidationLine>(
403
417
  stateCode: normalized,
404
418
  kept,
405
419
  removed,
406
- notice: formatRemovalNotice(removed, normalized),
420
+ notice: formatRemovalNotice(removed, normalized ?? "your destination"),
407
421
  };
408
422
  }
@@ -0,0 +1,92 @@
1
+ export const STATIC_ELIGIBILITY_SCHEMA: "tot.static-eligibility/v1";
2
+ export const STATIC_ELIGIBILITY_ROUTE: "/eligibility.json";
3
+ export const STATIC_ELIGIBILITY_META_NAME: "tot-static-eligibility";
4
+ export const STATIC_ELIGIBILITY_MAX_BYTES: number;
5
+
6
+ export interface StaticEligibilityProvenance {
7
+ tenant: string;
8
+ catalogRevision: string;
9
+ rulesetVersion: string;
10
+ }
11
+ export interface StaticEligibilityZipScope {
12
+ region: string;
13
+ jurisdiction: string | null;
14
+ zipPrefixes: string[];
15
+ }
16
+ export interface StaticEligibilityProduct {
17
+ /** `null` = no allow-list; `[]` = ships nowhere. */
18
+ allowedStates: string[] | null;
19
+ restrictedStates: string[];
20
+ directoryStates: string[];
21
+ /** States whose registry listing this product must hold (the rule pack's registry rules that select it). */
22
+ registryStates: string[];
23
+ registryListings: Record<string, string> | null;
24
+ }
25
+ export interface StaticEligibilityArtifact {
26
+ schema: "tot.static-eligibility/v1";
27
+ provenance: StaticEligibilityProvenance;
28
+ rules: {
29
+ directoryStates: string[];
30
+ restrictedStates: string[];
31
+ eligibleStates: string[];
32
+ zipScopes: StaticEligibilityZipScope[];
33
+ };
34
+ products: Record<string, StaticEligibilityProduct>;
35
+ }
36
+ export type StaticEligibilityVerdict =
37
+ | { ok: true; artifact: StaticEligibilityArtifact }
38
+ | { ok: false; reason: string };
39
+ export interface StaticEligibilityPointer {
40
+ url: string;
41
+ digest: string | null;
42
+ tenant: string;
43
+ rulesetVersion: string;
44
+ catalogRevision: string | null;
45
+ }
46
+
47
+ export function canonicalJson(value: unknown): string;
48
+ export function buildStaticEligibilityArtifact(input: {
49
+ provenance: StaticEligibilityProvenance;
50
+ rules?: {
51
+ directoryStates?: unknown;
52
+ restrictedStates?: unknown;
53
+ eligibleStates?: unknown;
54
+ zipScopes?: unknown;
55
+ };
56
+ products: ReadonlyArray<{
57
+ handle: string;
58
+ allowedStates?: readonly string[] | null;
59
+ restrictedStates?: readonly string[] | null;
60
+ directoryStates?: readonly string[] | null;
61
+ registryStates?: readonly string[] | null;
62
+ registryListings?: Record<string, string> | null;
63
+ }>;
64
+ }): StaticEligibilityArtifact;
65
+ export function staticEligibilityRevisionSource(
66
+ body: Pick<StaticEligibilityArtifact, "rules" | "products">,
67
+ ): string;
68
+ export function serializeStaticEligibilityArtifact(artifact: StaticEligibilityArtifact): string;
69
+ export function validateStaticEligibilityArtifact(
70
+ raw: unknown,
71
+ expected?: Partial<StaticEligibilityProvenance>,
72
+ ): StaticEligibilityVerdict;
73
+ export function parseStaticEligibilityArtifact(
74
+ bytes: string | Uint8Array,
75
+ expected?: Partial<StaticEligibilityProvenance>,
76
+ ): StaticEligibilityVerdict;
77
+ export function staticEligibilityAddress(digest: string): string;
78
+ export function isStaticEligibilityDigest(value: unknown): value is string;
79
+ export function findStaticEligibilityPointers(
80
+ html: string,
81
+ ): Array<{ tag: string; attrs: Record<string, string> }>;
82
+ export function staticEligibilityPointerTag(pointer: {
83
+ url: string;
84
+ tenant: string;
85
+ rulesetVersion: string;
86
+ catalogRevision?: string;
87
+ digest?: string;
88
+ }): string;
89
+ export function pinStaticEligibilityPointer(
90
+ html: string,
91
+ pin: { digest: string; provenance: StaticEligibilityProvenance },
92
+ ): { html: string; rewritten: number };