@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
@@ -1,14 +1,21 @@
1
1
  /**
2
- * Shopper "Ship to" state picker client helper.
2
+ * Shopper "Ship to" state picker and static-eligibility enforcement (client).
3
3
  *
4
4
  * Responsibilities:
5
- * 1. Persist selected ship-to US state code in `localStorage` under `tot:ship-state`
6
- * and dispatch the `tot:ship-state-change` custom event on `window`.
7
- * 2. Filter rendered catalog cards (`[data-product-card]`) in place using
8
- * `data-eligible-states`, `data-restricted-states`, and `data-directory-states`
9
- * attributes, updating any `[data-state-filter-status]` status banner.
10
- * 3. Revalidate cart lines via `revalidateCartForState`, removing ineligible items
11
- * and rendering a shopper-facing notice into `[data-state-cart-notice]`.
5
+ * 1. Persist the shopper's ship-to US state (`tot:ship-state`) and optional ZIP
6
+ * (`tot:ship-zip`) in `localStorage` and dispatch `tot:ship-state-change` on `window`.
7
+ * 2. Load the release's static eligibility artifact (`@tot/public-runtime/compliance/static-eligibility`)
8
+ * from the same-origin address the page's `<meta name="tot-static-eligibility">` pointer
9
+ * names, verify its bytes (sha256 equals the pointer digest) and its provenance
10
+ * (`{tenant, catalogRevision, rulesetVersion}` equals the pointer's), and filter catalog cards,
11
+ * block add-to-cart forms and revalidate cart lines against it.
12
+ * 3. FAIL CLOSED. A missing, unreachable, oversized, corrupt, schema-invalid or
13
+ * provenance-mismatched artifact, a cross-origin pointer, a malformed picker config, and an
14
+ * invalid saved state or ZIP all leave every `form[data-managed-cart]` disabled and say so.
15
+ * There is no origin-compute fallback: the browser never asks a server to evaluate.
16
+ *
17
+ * Text is written with `textContent` only; nothing here parses markup or evaluates strings.
18
+ * Checkout (`POST /api/compliance/preflight`) stays the authoritative enforcement seam.
12
19
  */
13
20
  import {
14
21
  evaluateProductStateEligibility,
@@ -19,10 +26,24 @@ import {
19
26
  type ProductStateEligibilityInput,
20
27
  type StateDirectoryRule,
21
28
  } from "@tot/public-runtime/compliance/state-directory";
29
+ import {
30
+ STATIC_ELIGIBILITY_MAX_BYTES,
31
+ STATIC_ELIGIBILITY_META_NAME,
32
+ isStaticEligibilityDigest,
33
+ parseStaticEligibilityArtifact,
34
+ type StaticEligibilityArtifact,
35
+ } from "@tot/public-runtime/compliance/static-eligibility";
22
36
 
23
37
  export const SHIP_STATE_STORAGE_KEY = "tot:ship-state";
38
+ export const SHIP_ZIP_STORAGE_KEY = "tot:ship-zip";
24
39
  export const SHIP_STATE_CHANGE_EVENT = "tot:ship-state-change";
25
40
 
41
+ export const ELIGIBILITY_UNAVAILABLE_MESSAGE =
42
+ "Shipping availability could not be verified, so purchasing is unavailable on this page.";
43
+ export const ELIGIBILITY_PENDING_MESSAGE = "Checking shipping availability…";
44
+ export const ELIGIBILITY_INVALID_SHIP_TO_MESSAGE =
45
+ "Your saved ship-to location is not valid, so purchasing is unavailable. Choose a state to continue.";
46
+
26
47
  export interface ShipStateChangeDetail {
27
48
  stateCode: string | null;
28
49
  }
@@ -61,6 +82,26 @@ export interface SelectElementLike {
61
82
  removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void;
62
83
  }
63
84
 
85
+ export interface CartControlElement {
86
+ disabled: boolean;
87
+ getAttribute(name: string): string | null;
88
+ setAttribute(name: string, value: string): void;
89
+ removeAttribute(name: string): void;
90
+ }
91
+
92
+ /** A `form[data-managed-cart]`. */
93
+ export interface CartFormElement {
94
+ getAttribute(name: string): string | null;
95
+ setAttribute(name: string, value: string): void;
96
+ removeAttribute(name: string): void;
97
+ querySelectorAll(selector: string): Iterable<unknown>;
98
+ }
99
+
100
+ export interface CartLineElement {
101
+ getAttribute(name: string): string | null;
102
+ remove(): void;
103
+ }
104
+
64
105
  export interface CatalogFilterSummary {
65
106
  stateCode: string | null;
66
107
  total: number;
@@ -69,6 +110,13 @@ export interface CatalogFilterSummary {
69
110
  statusMessage: string | null;
70
111
  }
71
112
 
113
+ /** The shopper's saved ship-to. `valid: false` means a value is present but not a state / ZIP. */
114
+ export interface ShipSelection {
115
+ state: string | null;
116
+ zip: string | null;
117
+ valid: boolean;
118
+ }
119
+
72
120
  function defaultStorage(): StorageLike | null {
73
121
  try {
74
122
  if (typeof globalThis !== "undefined" && "localStorage" in globalThis && globalThis.localStorage) {
@@ -102,22 +150,61 @@ function parseStateListAttribute(raw: string | null): string[] {
102
150
  .filter(Boolean);
103
151
  }
104
152
 
105
- /** Read the persisted ship-to state code from `localStorage` (`tot:ship-state`). */
106
- export function readStoredShipState(storage: StorageLike | null = defaultStorage()): string | null {
153
+ function isStorageDenied(error: unknown): boolean {
154
+ return (
155
+ (typeof DOMException !== "undefined" && error instanceof DOMException) ||
156
+ (error instanceof Error && error.name === "SecurityError")
157
+ );
158
+ }
159
+
160
+ function readRaw(storage: StorageLike | null, key: string): string | null {
107
161
  if (!storage) return null;
108
- let raw: string | null = null;
109
162
  try {
110
- raw = storage.getItem(SHIP_STATE_STORAGE_KEY);
163
+ return storage.getItem(key);
111
164
  } catch (error) {
112
- if (
113
- (typeof DOMException !== "undefined" && error instanceof DOMException) ||
114
- (error instanceof Error && error.name === "SecurityError")
115
- ) {
116
- return null;
117
- }
165
+ if (isStorageDenied(error)) return null;
118
166
  throw error;
119
167
  }
120
- return normalizeUsStateCode(raw);
168
+ }
169
+
170
+ const ZIP5 = /^\d{5}$/;
171
+
172
+ /**
173
+ * Read the saved ship-to. An absent value is `null` and valid; a PRESENT value that is not a US
174
+ * state (or not a 5-digit ZIP) is `valid: false`, because a tampered value must not read as
175
+ * "no restriction".
176
+ */
177
+ export function readStoredShipSelection(storage: StorageLike | null = defaultStorage()): ShipSelection {
178
+ const rawState = readRaw(storage, SHIP_STATE_STORAGE_KEY);
179
+ const rawZip = readRaw(storage, SHIP_ZIP_STORAGE_KEY);
180
+ let valid = true;
181
+
182
+ let state: string | null = null;
183
+ if (rawState !== null && rawState.trim() !== "") {
184
+ state = normalizeUsStateCode(rawState);
185
+ if (state === null) valid = false;
186
+ }
187
+
188
+ let zip: string | null = null;
189
+ if (rawZip !== null && rawZip.trim() !== "") {
190
+ if (ZIP5.test(rawZip.trim())) zip = rawZip.trim();
191
+ else valid = false;
192
+ }
193
+
194
+ return { state, zip, valid };
195
+ }
196
+
197
+ /** Read the persisted ship-to state code (`tot:ship-state`); an invalid value reads as `null`. */
198
+ export function readStoredShipState(storage: StorageLike | null = defaultStorage()): string | null {
199
+ return readStoredShipSelection(storage).state;
200
+ }
201
+
202
+ function dispatchChange(eventTarget: EventTargetLike | null, stateCode: string | null): void {
203
+ if (eventTarget && typeof CustomEvent === "function") {
204
+ eventTarget.dispatchEvent(
205
+ new CustomEvent<ShipStateChangeDetail>(SHIP_STATE_CHANGE_EVENT, { detail: { stateCode } }),
206
+ );
207
+ }
121
208
  }
122
209
 
123
210
  /**
@@ -148,25 +235,47 @@ export function writeStoredShipState(
148
235
  }
149
236
  }
150
237
 
151
- if (eventTarget && typeof CustomEvent === "function") {
152
- eventTarget.dispatchEvent(
153
- new CustomEvent<ShipStateChangeDetail>(SHIP_STATE_CHANGE_EVENT, {
154
- detail: { stateCode: normalized },
155
- }),
156
- );
157
- }
158
-
238
+ dispatchChange(eventTarget, normalized);
159
239
  return normalized;
160
240
  }
161
241
 
162
- /** Extract product state-eligibility inputs from a `[data-product-card]` element. */
242
+ /** Persist the 5-digit ship-to ZIP (`tot:ship-zip`); anything else clears it. */
243
+ export function writeStoredShipZip(
244
+ rawZip: string | null | undefined,
245
+ options: { storage?: StorageLike | null; eventTarget?: EventTargetLike | null } = {},
246
+ ): string | null {
247
+ const storage = options.storage === undefined ? defaultStorage() : options.storage;
248
+ const eventTarget = options.eventTarget === undefined ? defaultEventTarget() : options.eventTarget;
249
+ const zip = typeof rawZip === "string" && ZIP5.test(rawZip.trim()) ? rawZip.trim() : null;
250
+ if (storage) {
251
+ try {
252
+ if (zip) storage.setItem(SHIP_ZIP_STORAGE_KEY, zip);
253
+ else storage.removeItem(SHIP_ZIP_STORAGE_KEY);
254
+ } catch {
255
+ // Ignore storage quota / privacy mode failures; still dispatch event.
256
+ }
257
+ }
258
+ dispatchChange(eventTarget, readStoredShipSelection(storage).state);
259
+ return zip;
260
+ }
261
+
262
+ /**
263
+ * Extract product state-eligibility inputs from a `[data-product-card]` element. An allow-list
264
+ * attribute that is present but names no valid state, and `data-ships-nowhere`, both mean the
265
+ * product ships nowhere; neither reads as "no allow-list".
266
+ */
163
267
  export function readProductCardEligibility(card: StateCardElement): ProductStateEligibilityInput {
164
- const eligible = parseStateListAttribute(card.getAttribute("data-eligible-states"));
268
+ const rawEligible = card.getAttribute("data-eligible-states");
269
+ const eligible = parseStateListAttribute(rawEligible);
165
270
  const restricted = parseStateListAttribute(card.getAttribute("data-restricted-states"));
166
271
  const directory = parseStateListAttribute(card.getAttribute("data-directory-states"));
272
+ const eligibleValid = eligible.filter((code) => normalizeUsStateCode(code) !== null);
273
+ const shipsNowhere =
274
+ card.getAttribute("data-ships-nowhere") === "true" || (rawEligible !== null && eligibleValid.length === 0);
167
275
 
168
276
  return {
169
277
  allowedStates: eligible.length > 0 ? eligible : null,
278
+ shipsNowhere,
170
279
  restrictedStates: restricted.length > 0 ? restricted : null,
171
280
  tags: directory.map((code) => `directory:${code}`),
172
281
  };
@@ -189,6 +298,52 @@ function formatFilterStatus(
189
298
  return `Showing ${visible} of ${total} products eligible to ship to ${stateCode} (${hidden} unavailable in ${stateCode}).`;
190
299
  }
191
300
 
301
+ function setBanners(root: StateFilterRoot, selector: string, message: string | null): void {
302
+ const banners = Array.from(root.querySelectorAll(selector)) as NoticeBannerElement[];
303
+ for (const banner of banners) {
304
+ const text = message ?? "";
305
+ if (banner.textContent !== text) banner.textContent = text;
306
+ banner.hidden = message === null;
307
+ }
308
+ }
309
+
310
+ /** Disable (never merely hide) every control of a managed-cart form, or restore the ones we disabled. */
311
+ export function setCartFormBlocked(form: CartFormElement, reason: string | null): void {
312
+ const controls = Array.from(form.querySelectorAll("button, input, select, textarea")) as CartControlElement[];
313
+ if (reason !== null) {
314
+ form.setAttribute("data-eligibility-blocked", reason);
315
+ form.setAttribute("aria-disabled", "true");
316
+ for (const control of controls) {
317
+ if (!control.disabled) {
318
+ control.disabled = true;
319
+ control.setAttribute("data-eligibility-disabled", "true");
320
+ }
321
+ }
322
+ return;
323
+ }
324
+ // A server-rendered "ships nowhere" form is never re-enabled by the client.
325
+ if (form.getAttribute("data-eligibility-blocked") === "ships-nowhere") return;
326
+ form.removeAttribute("data-eligibility-blocked");
327
+ form.removeAttribute("aria-disabled");
328
+ for (const control of controls) {
329
+ if (control.getAttribute("data-eligibility-disabled") === "true") {
330
+ control.disabled = false;
331
+ control.removeAttribute("data-eligibility-disabled");
332
+ }
333
+ }
334
+ }
335
+
336
+ function cartForms(root: StateFilterRoot): CartFormElement[] {
337
+ return Array.from(root.querySelectorAll("form[data-managed-cart]")) as CartFormElement[];
338
+ }
339
+
340
+ /** Block every managed-cart form under `root` for `reason` and say so in the status banner. */
341
+ export function failCloseCartForms(root: StateFilterRoot | null, reason: string, message: string): void {
342
+ if (!root) return;
343
+ for (const form of cartForms(root)) setCartFormBlocked(form, reason);
344
+ setBanners(root, "[data-state-filter-status]", message);
345
+ }
346
+
192
347
  /**
193
348
  * Filter `[data-product-card]` elements in `root` for `stateCode` and update
194
349
  * `[data-state-filter-status]` banner(s).
@@ -222,14 +377,7 @@ export function filterCatalogCardsForState(
222
377
 
223
378
  const total = cards.length;
224
379
  const statusMessage = formatFilterStatus(normalized, total, visible, hidden);
225
- const banners = Array.from(
226
- root.querySelectorAll("[data-state-filter-status]"),
227
- ) as NoticeBannerElement[];
228
-
229
- for (const banner of banners) {
230
- banner.textContent = statusMessage ?? "";
231
- banner.hidden = statusMessage === null;
232
- }
380
+ setBanners(root, "[data-state-filter-status]", statusMessage);
233
381
 
234
382
  return { stateCode: normalized, total, visible, hidden, statusMessage };
235
383
  }
@@ -263,19 +411,381 @@ export function revalidateShopperCartForState<TLine extends CartRevalidationLine
263
411
  options.writeLines(result.kept);
264
412
  }
265
413
 
266
- if (root) {
267
- const notices = Array.from(
268
- root.querySelectorAll("[data-state-cart-notice]"),
269
- ) as NoticeBannerElement[];
270
- for (const noticeEl of notices) {
271
- noticeEl.textContent = result.notice ?? "";
272
- noticeEl.hidden = result.notice === null;
414
+ if (root) setBanners(root, "[data-state-cart-notice]", result.notice);
415
+
416
+ return result;
417
+ }
418
+
419
+ interface DomCartLine extends CartRevalidationLine {
420
+ element: CartLineElement;
421
+ }
422
+
423
+ /** The cart lines the page renders (`[data-cart-line][data-product-handle]`); removal drops the node. */
424
+ export function domCartAdapter(root: StateFilterRoot | null): {
425
+ readLines: () => readonly DomCartLine[];
426
+ writeLines: (kept: DomCartLine[]) => void;
427
+ } {
428
+ const read = (): DomCartLine[] =>
429
+ root
430
+ ? (Array.from(root.querySelectorAll("[data-cart-line]")) as CartLineElement[]).map((element) => ({
431
+ element,
432
+ handle: element.getAttribute("data-product-handle") ?? undefined,
433
+ title: element.getAttribute("data-product-title") ?? undefined,
434
+ }))
435
+ : [];
436
+ return {
437
+ readLines: read,
438
+ writeLines: (kept) => {
439
+ const keptElements = new Set(kept.map((line) => line.element));
440
+ for (const line of read()) {
441
+ if (!keptElements.has(line.element)) line.element.remove();
442
+ }
443
+ },
444
+ };
445
+ }
446
+
447
+ /* ------------------------------------------------------------------------------------------ */
448
+ /* Static eligibility artifact: discovery, verification, enforcement */
449
+ /* ------------------------------------------------------------------------------------------ */
450
+
451
+ export interface StaticEligibilityPointerAttrs {
452
+ url: string;
453
+ tenant: string;
454
+ rulesetVersion: string;
455
+ catalogRevision: string;
456
+ digest: string;
457
+ }
458
+
459
+ export type StaticEligibilityLoad =
460
+ | { ok: true; artifact: StaticEligibilityArtifact }
461
+ | { ok: false; reason: string };
462
+
463
+ export interface StaticEligibilityEnv {
464
+ /** The pointer metas of the document, as attribute readers. */
465
+ pointers: () => Array<{ getAttribute(name: string): string | null }>;
466
+ /** `location.origin`. */
467
+ origin: string;
468
+ /** `location.href`, the base a relative pointer url resolves against. */
469
+ baseHref: string;
470
+ fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
471
+ sha256Hex: (bytes: Uint8Array) => Promise<string>;
472
+ }
473
+
474
+ function defaultEnv(): StaticEligibilityEnv | null {
475
+ if (typeof document === "undefined" || typeof location === "undefined") return null;
476
+ return {
477
+ pointers: () =>
478
+ Array.from(document.querySelectorAll(`meta[name="${STATIC_ELIGIBILITY_META_NAME}"]`)),
479
+ origin: location.origin,
480
+ baseHref: location.href,
481
+ fetchImpl: (url, init) => fetch(url, init),
482
+ sha256Hex: async (bytes) => {
483
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
484
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
485
+ },
486
+ };
487
+ }
488
+
489
+ function readPointer(env: StaticEligibilityEnv): StaticEligibilityPointerAttrs | string {
490
+ const metas = env.pointers();
491
+ if (metas.length === 0) return "pointer-missing";
492
+ if (metas.length > 1) return "pointer-ambiguous";
493
+ const meta = metas[0]!;
494
+ const url = meta.getAttribute("content") ?? "";
495
+ const tenant = meta.getAttribute("data-tenant") ?? "";
496
+ const rulesetVersion = meta.getAttribute("data-ruleset-version") ?? "";
497
+ const catalogRevision = meta.getAttribute("data-catalog-revision") ?? "";
498
+ const digest = meta.getAttribute("data-sha256") ?? "";
499
+ if (!url || !tenant || !rulesetVersion) return "pointer-incomplete";
500
+ return { url, tenant, rulesetVersion, catalogRevision, digest };
501
+ }
502
+
503
+ /**
504
+ * Fetch and verify the artifact the page's pointer names. A pinned (published) pointer carries
505
+ * the content digest and catalog revision, and both must match; an unpinned pointer (the live
506
+ * preview Worker) is verified on tenant and ruleset version alone.
507
+ */
508
+ export async function loadStaticEligibility(
509
+ env: StaticEligibilityEnv | null = defaultEnv(),
510
+ ): Promise<StaticEligibilityLoad> {
511
+ if (!env) return { ok: false, reason: "no-environment" };
512
+ const pointer = readPointer(env);
513
+ if (typeof pointer === "string") return { ok: false, reason: pointer };
514
+
515
+ let target: URL;
516
+ try {
517
+ target = new URL(pointer.url, env.baseHref);
518
+ } catch {
519
+ return { ok: false, reason: "pointer-url-invalid" };
520
+ }
521
+ if (target.origin !== env.origin) return { ok: false, reason: "pointer-cross-origin" };
522
+ const pinned = pointer.digest !== "";
523
+ if (pinned && !isStaticEligibilityDigest(pointer.digest)) return { ok: false, reason: "pointer-digest-invalid" };
524
+
525
+ let response: Response;
526
+ try {
527
+ response = await env.fetchImpl(target.toString(), { credentials: "same-origin", cache: "no-cache", redirect: "error" });
528
+ } catch {
529
+ return { ok: false, reason: "artifact-unreachable" };
530
+ }
531
+ if (!response.ok) return { ok: false, reason: `artifact-http-${response.status}` };
532
+ const declaredLength = Number(response.headers.get("content-length") ?? "0");
533
+ if (declaredLength > STATIC_ELIGIBILITY_MAX_BYTES) return { ok: false, reason: "artifact-too-large" };
534
+
535
+ let bytes: Uint8Array;
536
+ try {
537
+ bytes = new Uint8Array(await response.arrayBuffer());
538
+ } catch {
539
+ return { ok: false, reason: "artifact-unreadable" };
540
+ }
541
+ if (bytes.byteLength === 0 || bytes.byteLength > STATIC_ELIGIBILITY_MAX_BYTES) {
542
+ return { ok: false, reason: "artifact-size" };
543
+ }
544
+ if (pinned && (await env.sha256Hex(bytes)) !== pointer.digest) return { ok: false, reason: "artifact-digest-mismatch" };
545
+
546
+ const expected = {
547
+ tenant: pointer.tenant,
548
+ rulesetVersion: pointer.rulesetVersion,
549
+ ...(pointer.catalogRevision ? { catalogRevision: pointer.catalogRevision } : {}),
550
+ };
551
+ const verdict = parseStaticEligibilityArtifact(bytes, expected);
552
+ if (!verdict.ok) return { ok: false, reason: `artifact-${verdict.reason}` };
553
+ if (pinned && !pointer.catalogRevision) return { ok: false, reason: "pointer-revision-missing" };
554
+ return { ok: true, artifact: verdict.artifact };
555
+ }
556
+
557
+ /** City registries the saved ZIP falls under for `state`, from the artifact's ZIP scopes. */
558
+ function localJurisdictionsFor(artifact: StaticEligibilityArtifact, selection: ShipSelection): string[] {
559
+ if (!selection.state || !selection.zip) return [];
560
+ const out: string[] = [];
561
+ for (const scope of artifact.rules.zipScopes) {
562
+ if (scope.region !== selection.state || !scope.jurisdiction) continue;
563
+ if (scope.zipPrefixes.some((prefix) => selection.zip!.startsWith(prefix)) && !out.includes(scope.jurisdiction)) {
564
+ out.push(scope.jurisdiction);
273
565
  }
274
566
  }
567
+ return out;
568
+ }
275
569
 
276
- return result;
570
+ /** The store-wide rule an artifact carries, in the evaluator's own shape. */
571
+ export function staticEligibilityConfig(artifact: StaticEligibilityArtifact): StateDirectoryRule {
572
+ return {
573
+ directoryStates: artifact.rules.directoryStates,
574
+ restrictedStates: artifact.rules.restrictedStates,
575
+ eligibleStates: artifact.rules.eligibleStates,
576
+ };
577
+ }
578
+
579
+ /** One product's evaluator input from the artifact, or `null` for a handle the artifact does not carry. */
580
+ export function staticEligibilityProductInput(
581
+ artifact: StaticEligibilityArtifact,
582
+ handle: string | null,
583
+ selection: ShipSelection,
584
+ ): ProductStateEligibilityInput | null {
585
+ if (!handle || !Object.prototype.hasOwnProperty.call(artifact.products, handle)) return null;
586
+ const product = artifact.products[handle]!;
587
+ const allowed = product.allowedStates;
588
+ const shipsNowhere = allowed !== null && !allowed.some((code) => normalizeUsStateCode(code) !== null);
589
+ return {
590
+ allowedStates: allowed,
591
+ shipsNowhere,
592
+ restrictedStates: product.restrictedStates,
593
+ tags: product.directoryStates.map((code) => `directory:${code}`),
594
+ registryStates: product.registryStates,
595
+ registryListings: product.registryListings
596
+ ? { state: "known", value: product.registryListings as never }
597
+ : null,
598
+ localJurisdictions: localJurisdictionsFor(artifact, selection),
599
+ };
600
+ }
601
+
602
+ type EnforcementStatus = "pending" | "ready" | "failed";
603
+
604
+ interface Enforcement {
605
+ status: EnforcementStatus;
606
+ reason: string | null;
607
+ artifact: StaticEligibilityArtifact | null;
608
+ root: StateFilterRoot;
609
+ storage: StorageLike | null;
610
+ }
611
+
612
+ let active: Enforcement | null = null;
613
+
614
+ /** True once static-eligibility enforcement has started on this page. */
615
+ export function staticEnforcementActive(): boolean {
616
+ return active !== null;
617
+ }
618
+
619
+ /** Test seam: forget the page's enforcement state. */
620
+ export function resetStaticEnforcementForTests(): void {
621
+ active = null;
622
+ }
623
+
624
+ function blockReason(enforcement: Enforcement, selection: ShipSelection): string | null {
625
+ if (enforcement.status === "pending") return "eligibility-pending";
626
+ if (enforcement.status === "failed") return "eligibility-unavailable";
627
+ if (!selection.valid) return "invalid-ship-to";
628
+ return null;
629
+ }
630
+
631
+ function formHandle(form: CartFormElement): string | null {
632
+ const handle = form.getAttribute("data-product-handle");
633
+ return handle && handle.length > 0 ? handle : null;
277
634
  }
278
635
 
636
+ /** Whether a managed-cart form may submit right now. Evaluated at submit time, so a form rendered after the last apply is covered. */
637
+ export function staticCartFormAllowed(form: CartFormElement): boolean {
638
+ if (!active) return true;
639
+ const selection = readStoredShipSelection(active.storage);
640
+ if (blockReason(active, selection) !== null || !active.artifact) return false;
641
+ if (form.getAttribute("data-eligibility-blocked") === "ships-nowhere") return false;
642
+ const input = staticEligibilityProductInput(active.artifact, formHandle(form), selection);
643
+ if (!input) return false;
644
+ return evaluateProductStateEligibility(input, selection.state, staticEligibilityConfig(active.artifact)).eligible;
645
+ }
646
+
647
+ /** Evaluate every card, form and cart line under the page against the artifact and the saved ship-to. */
648
+ export function reapplyStaticEligibility(): void {
649
+ const enforcement = active;
650
+ if (!enforcement) return;
651
+ const { root } = enforcement;
652
+ const selection = readStoredShipSelection(enforcement.storage);
653
+ const reason = blockReason(enforcement, selection);
654
+ const cards = Array.from(root.querySelectorAll("[data-product-card]")) as StateCardElement[];
655
+
656
+ if (reason !== null || !enforcement.artifact) {
657
+ for (const form of cartForms(root)) setCartFormBlocked(form, reason ?? "eligibility-unavailable");
658
+ for (const card of cards) {
659
+ card.hidden = false;
660
+ card.setAttribute("data-state-ineligible", reason ?? "eligibility-unavailable");
661
+ }
662
+ setBanners(
663
+ root,
664
+ "[data-state-filter-status]",
665
+ reason === "invalid-ship-to"
666
+ ? ELIGIBILITY_INVALID_SHIP_TO_MESSAGE
667
+ : reason === "eligibility-pending"
668
+ ? ELIGIBILITY_PENDING_MESSAGE
669
+ : ELIGIBILITY_UNAVAILABLE_MESSAGE,
670
+ );
671
+ return;
672
+ }
673
+
674
+ const artifact = enforcement.artifact;
675
+ const config = staticEligibilityConfig(artifact);
676
+ let visible = 0;
677
+ let hidden = 0;
678
+ for (const card of cards) {
679
+ const input = staticEligibilityProductInput(artifact, card.getAttribute("data-product-handle"), selection);
680
+ const decision = input
681
+ ? evaluateProductStateEligibility(input, selection.state, config)
682
+ : { eligible: false, reason: "unknown-product" as const };
683
+ card.hidden = !decision.eligible;
684
+ if (decision.eligible) {
685
+ card.removeAttribute("data-state-ineligible");
686
+ visible += 1;
687
+ } else {
688
+ card.setAttribute("data-state-ineligible", decision.reason);
689
+ hidden += 1;
690
+ }
691
+ }
692
+ for (const form of cartForms(root)) {
693
+ const input = staticEligibilityProductInput(artifact, formHandle(form), selection);
694
+ const decision = input
695
+ ? evaluateProductStateEligibility(input, selection.state, config)
696
+ : { eligible: false, reason: "unknown-product" as const };
697
+ setCartFormBlocked(form, decision.eligible ? null : decision.reason);
698
+ }
699
+ setBanners(root, "[data-state-filter-status]", formatFilterStatus(selection.state, cards.length, visible, hidden));
700
+
701
+ const adapter = domCartAdapter(root);
702
+ revalidateShopperCartForState({
703
+ stateCode: selection.state,
704
+ config,
705
+ readLines: adapter.readLines,
706
+ writeLines: adapter.writeLines,
707
+ resolveProduct: (line) => staticEligibilityProductInput(artifact, line.handle ?? null, selection) ?? { shipsNowhere: true },
708
+ root,
709
+ });
710
+ }
711
+
712
+ export interface BootStaticEligibilityOptions {
713
+ root?: StateFilterRoot | null;
714
+ storage?: StorageLike | null;
715
+ eventTarget?: EventTargetLike | null;
716
+ env?: StaticEligibilityEnv | null;
717
+ }
718
+
719
+ function isElementLike(node: unknown): node is { matches?: (s: string) => boolean; querySelector?: (s: string) => unknown } {
720
+ return typeof node === "object" && node !== null && "nodeType" in node && (node as { nodeType: number }).nodeType === 1;
721
+ }
722
+
723
+ const CARD_OR_FORM = "[data-product-card], form[data-managed-cart]";
724
+
725
+ /**
726
+ * Start enforcing the page's static eligibility artifact. Every managed-cart form is blocked
727
+ * immediately and stays blocked until the artifact has been fetched and verified; a failure keeps
728
+ * it blocked. Cards and forms that appear later (islands) are enforced as they mount.
729
+ */
730
+ export async function bootStaticEligibilityFromDom(options: BootStaticEligibilityOptions = {}): Promise<void> {
731
+ const root = options.root === undefined ? defaultRoot() : options.root;
732
+ if (!root) return;
733
+ const storage = options.storage === undefined ? defaultStorage() : options.storage;
734
+ const eventTarget = options.eventTarget === undefined ? defaultEventTarget() : options.eventTarget;
735
+ const enforcement: Enforcement = { status: "pending", reason: null, artifact: null, root, storage };
736
+ active = enforcement;
737
+ reapplyStaticEligibility();
738
+
739
+ const doc = (typeof document !== "undefined" ? document : null) as Document | null;
740
+ if (doc && root === doc) {
741
+ // Capture phase, so the managed-cart handler never sees a blocked submission.
742
+ doc.addEventListener(
743
+ "submit",
744
+ (event) => {
745
+ const form = (event.target as Element | null)?.closest?.("[data-managed-cart]") as unknown as CartFormElement | null;
746
+ if (form && !staticCartFormAllowed(form)) {
747
+ event.preventDefault();
748
+ event.stopImmediatePropagation();
749
+ }
750
+ },
751
+ true,
752
+ );
753
+ if (typeof MutationObserver === "function" && doc.body) {
754
+ let queued = false;
755
+ new MutationObserver((records) => {
756
+ const relevant = records.some((record) =>
757
+ Array.from(record.addedNodes).some(
758
+ (node) => isElementLike(node) && (node.matches?.(CARD_OR_FORM) || node.querySelector?.(CARD_OR_FORM)),
759
+ ),
760
+ );
761
+ if (!relevant || queued) return;
762
+ queued = true;
763
+ queueMicrotask(() => {
764
+ queued = false;
765
+ reapplyStaticEligibility();
766
+ });
767
+ }).observe(doc.body, { childList: true, subtree: true });
768
+ }
769
+ }
770
+ const onChange: EventListener = () => reapplyStaticEligibility();
771
+ eventTarget?.addEventListener?.(SHIP_STATE_CHANGE_EVENT, onChange);
772
+ eventTarget?.addEventListener?.("storage", onChange);
773
+
774
+ const loaded = await loadStaticEligibility(options.env === undefined ? defaultEnv() : options.env);
775
+ if (loaded.ok) {
776
+ enforcement.status = "ready";
777
+ enforcement.artifact = loaded.artifact;
778
+ } else {
779
+ enforcement.status = "failed";
780
+ enforcement.reason = loaded.reason;
781
+ }
782
+ reapplyStaticEligibility();
783
+ }
784
+
785
+ /* ------------------------------------------------------------------------------------------ */
786
+ /* Picker */
787
+ /* ------------------------------------------------------------------------------------------ */
788
+
279
789
  export interface MountStatePickerOptions<TLine extends CartRevalidationLine = CartRevalidationLine> {
280
790
  select: SelectElementLike;
281
791
  config?: StateDirectoryRule | null;
@@ -291,7 +801,8 @@ export interface MountStatePickerOptions<TLine extends CartRevalidationLine = Ca
291
801
 
292
802
  /**
293
803
  * Wire a `<select>` state picker to `localStorage`, catalog filtering, and optional
294
- * cart revalidation. Returns a `dispose()` cleanup callback.
804
+ * cart revalidation. While static-eligibility enforcement is active the artifact decides
805
+ * (the picker only records the choice and asks it to re-apply). Returns a `dispose()` callback.
295
806
  */
296
807
  export function mountStatePicker<TLine extends CartRevalidationLine = CartRevalidationLine>(
297
808
  options: MountStatePickerOptions<TLine>,
@@ -300,12 +811,20 @@ export function mountStatePicker<TLine extends CartRevalidationLine = CartRevali
300
811
  const eventTarget = options.eventTarget === undefined ? defaultEventTarget() : options.eventTarget;
301
812
  const root = options.root === undefined ? defaultRoot() : options.root;
302
813
 
303
- const applyState = (stateCode: string | null) => {
304
- options.select.value = stateCode ?? "";
305
- filterCatalogCardsForState(stateCode, options.config, root);
814
+ const applySelection = (selection: ShipSelection) => {
815
+ options.select.value = selection.state ?? "";
816
+ if (staticEnforcementActive()) {
817
+ reapplyStaticEligibility();
818
+ return;
819
+ }
820
+ if (!selection.valid) {
821
+ failCloseCartForms(root, "invalid-ship-to", ELIGIBILITY_INVALID_SHIP_TO_MESSAGE);
822
+ return;
823
+ }
824
+ filterCatalogCardsForState(selection.state, options.config, root);
306
825
  if (options.cart) {
307
826
  revalidateShopperCartForState({
308
- stateCode,
827
+ stateCode: selection.state,
309
828
  config: options.config,
310
829
  readLines: options.cart.readLines,
311
830
  writeLines: options.cart.writeLines,
@@ -315,19 +834,20 @@ export function mountStatePicker<TLine extends CartRevalidationLine = CartRevali
315
834
  }
316
835
  };
317
836
 
318
- const initial = readStoredShipState(storage);
319
- applyState(initial);
837
+ applySelection(readStoredShipSelection(storage));
320
838
 
321
839
  const onSelectChange: EventListener = () => {
322
- const next = writeStoredShipState(options.select.value, { storage, eventTarget });
323
- applyState(next);
840
+ writeStoredShipState(options.select.value, { storage, eventTarget });
841
+ applySelection(readStoredShipSelection(storage));
324
842
  };
325
843
 
326
844
  const onExternalStateChange: EventListener = (event) => {
327
845
  const detail = (event as CustomEvent<ShipStateChangeDetail>).detail;
328
- const next = normalizeUsStateCode(detail?.stateCode);
329
- if (options.select.value !== (next ?? "")) {
330
- applyState(next);
846
+ const next = storage
847
+ ? readStoredShipSelection(storage)
848
+ : { state: normalizeUsStateCode(detail?.stateCode), zip: null, valid: true };
849
+ if (options.select.value !== (next.state ?? "")) {
850
+ applySelection(next);
331
851
  }
332
852
  };
333
853
 
@@ -340,32 +860,67 @@ export function mountStatePicker<TLine extends CartRevalidationLine = CartRevali
340
860
  };
341
861
  }
342
862
 
863
+ /** A picker config is an object whose list fields (when present) are string arrays; anything else is malformed. */
864
+ export function parseStatePickerConfig(raw: string | null): StateDirectoryRule | "malformed" | null {
865
+ if (raw === null || raw.trim() === "") return null;
866
+ let parsed: unknown;
867
+ try {
868
+ parsed = JSON.parse(raw);
869
+ } catch {
870
+ return "malformed";
871
+ }
872
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "malformed";
873
+ const out: Record<string, string[]> = {};
874
+ for (const key of ["directoryStates", "restrictedStates", "eligibleStates"]) {
875
+ const value = (parsed as Record<string, unknown>)[key];
876
+ if (value === undefined) continue;
877
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) return "malformed";
878
+ out[key] = value as string[];
879
+ }
880
+ return out as StateDirectoryRule;
881
+ }
882
+
343
883
  /**
344
884
  * Boot every unmounted `[data-state-picker]` widget in the document.
345
- * Reads its `StateDirectoryRule` JSON from `data-state-picker-config`.
885
+ * Reads its `StateDirectoryRule` JSON from `data-state-picker-config`; a malformed config
886
+ * fails the page closed instead of mounting with no rules. Cart lines the page renders are
887
+ * revalidated against the saved ship-to on every state change.
346
888
  */
347
889
  export function bootStatePickersFromDom(): Array<() => void> {
348
890
  if (typeof document === "undefined") return [];
349
891
  const containers = Array.from(document.querySelectorAll<HTMLElement>("[data-state-picker]"));
350
892
  const disposers: Array<() => void> = [];
893
+ const cart = domCartAdapter(document);
351
894
 
352
895
  for (const container of containers) {
353
896
  if (container.dataset.statePickerMounted === "true") continue;
354
897
  const select = container.querySelector<HTMLSelectElement>("[data-state-picker-select]");
355
898
  if (!select) continue;
356
899
 
357
- let config: StateDirectoryRule | null = null;
358
- const rawConfig = container.getAttribute("data-state-picker-config");
359
- if (rawConfig) {
360
- try {
361
- config = JSON.parse(rawConfig) as StateDirectoryRule;
362
- } catch {
363
- config = null;
364
- }
900
+ const config = parseStatePickerConfig(container.getAttribute("data-state-picker-config"));
901
+ if (config === "malformed") {
902
+ failCloseCartForms(document, "invalid-picker-config", ELIGIBILITY_UNAVAILABLE_MESSAGE);
903
+ select.disabled = true;
904
+ continue;
365
905
  }
366
906
 
367
907
  container.dataset.statePickerMounted = "true";
368
- disposers.push(mountStatePicker({ select, config }));
908
+ disposers.push(
909
+ mountStatePicker({
910
+ select,
911
+ config,
912
+ cart: {
913
+ readLines: cart.readLines,
914
+ writeLines: cart.writeLines,
915
+ resolveProduct: (line) => {
916
+ const card = line.handle
917
+ ? (document.querySelector(`[data-product-card][data-product-handle="${CSS.escape(line.handle)}"]`) as StateCardElement | null)
918
+ : null;
919
+ return card ? readProductCardEligibility(card) : undefined;
920
+ },
921
+ },
922
+ }),
923
+ );
369
924
  }
370
925
 
371
926
  return disposers;