@tokenoftrust/storefront-runner 6.8.2 → 6.9.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.
@@ -0,0 +1,39 @@
1
+ /** Browser wiring for the /admin "Excise tax" form: collect the switch, POST, report. */
2
+
3
+ import { saveResultStatus } from "./checkoutRequirementsForm";
4
+ import { announceSettingChanged } from "./settingDraftActions";
5
+
6
+ export function mountCheckoutExciseForm(form: HTMLElement): void {
7
+ const endpoint = form.dataset.endpoint || "/api/preview/checkout-excise";
8
+ const targetTenant = form.dataset.targetTenant || "";
9
+ const field = form.querySelector<HTMLInputElement>("[data-excise-field]");
10
+ const status = form.querySelector<HTMLElement>("[data-excise-status]");
11
+ const saveBtn = form.querySelector<HTMLButtonElement>("[data-excise-save]");
12
+ const setStatus = (message: string, state?: "ok" | "err") => {
13
+ if (!status) return;
14
+ status.textContent = message;
15
+ if (state) status.dataset.state = state;
16
+ else delete status.dataset.state;
17
+ };
18
+ saveBtn?.addEventListener("click", async () => {
19
+ const body: Record<string, unknown> = { excise: field?.checked ?? false, ...(targetTenant ? { targetTenant } : {}) };
20
+ setStatus("Saving…");
21
+ saveBtn.disabled = true;
22
+ try {
23
+ const res = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
24
+ let data: Parameters<typeof saveResultStatus>[2] = {};
25
+ try {
26
+ data = await res.json();
27
+ } catch {
28
+ // non-JSON error body
29
+ }
30
+ const result = saveResultStatus(res.ok, res.status, data);
31
+ setStatus(result.message, result.state);
32
+ if (res.ok) announceSettingChanged("checkout-excise");
33
+ } catch {
34
+ setStatus("Save failed — network error", "err");
35
+ } finally {
36
+ saveBtn.disabled = false;
37
+ }
38
+ });
39
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * A store's excise setting: whether its checkout collects excise tax. It is a merchant-operated
3
+ * commerce setting (ADR 0035 "operational"), saved as the tenant-owned artifact
4
+ * `tenants/<id>/checkout-excise.json` exactly like the checkout requirements: a save writes the
5
+ * draft (`test`) the preview reads, the live store reads the published value (`live`) until the
6
+ * owner publishes the draft, and every reader resolves it through `readPublishedArtifact` for its
7
+ * own env. The setting is served by the Worker on both CDN providers, because the checkout handoff
8
+ * that signs it into the cart is a Worker route for Cloudflare and CloudFront stores alike.
9
+ *
10
+ * An absent artifact means the capability default (`capabilities.exciseTax`, on for a store whose
11
+ * compliance rules owe excise). A store whose compliance rules require excise keeps it on whatever
12
+ * is saved: the save refuses off and a reader ignores a stored off.
13
+ */
14
+ import {
15
+ operationalSettingArtifactPath,
16
+ readPublishedArtifact,
17
+ resolveComplianceObligations,
18
+ type CapabilityConfig,
19
+ type CustomizationEnv,
20
+ type TenantConfig,
21
+ } from "@tot/public-runtime";
22
+ import { readKv } from "@/lib/publication/shared/runtimeEnv";
23
+
24
+ export interface CheckoutExcise {
25
+ /** Collect excise tax at checkout. */
26
+ excise: boolean;
27
+ }
28
+
29
+ /**
30
+ * What a read found: `unset` (nothing saved, so the capability default), `set`, or `unreadable`
31
+ * (corrupt or unavailable, so a reader must fail closed, never treat it as off).
32
+ */
33
+ export type SavedExcise = { state: "unset" } | { state: "set"; excise: boolean } | { state: "unreadable" };
34
+
35
+ const UNREADABLE: SavedExcise = { state: "unreadable" };
36
+
37
+ export const REQUIRED_EXCISE_REFUSAL = "This store's compliance rules require excise tax collection, so it can't be turned off.";
38
+
39
+ export function checkoutExciseArtifactPath(tenantId: string): string {
40
+ return operationalSettingArtifactPath(tenantId, "checkout-excise.json");
41
+ }
42
+
43
+ /** Whether the store's compliance rules require excise collection. */
44
+ export function exciseRequired(tenant: Pick<TenantConfig, "compliance" | "siteType">): boolean {
45
+ return resolveComplianceObligations(tenant).exciseTax.required;
46
+ }
47
+
48
+ /** Parse a published artifact: absent is `unset`; anything but an object holding exactly a boolean `excise` is `unreadable`. */
49
+ export function parseCheckoutExcise(raw: string | null): SavedExcise {
50
+ if (raw === null) return { state: "unset" };
51
+ const parsed = parseJson(raw);
52
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return UNREADABLE;
53
+ const value = parsed as Record<string, unknown>;
54
+ if (Object.keys(value).some((key) => key !== "excise")) return UNREADABLE;
55
+ if (typeof value.excise !== "boolean") return UNREADABLE;
56
+ return { state: "set", excise: value.excise };
57
+ }
58
+
59
+ function parseJson(raw: string): unknown {
60
+ try {
61
+ return JSON.parse(raw);
62
+ } catch (err) {
63
+ if (err instanceof SyntaxError) return undefined;
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ export type CheckoutExciseInput = { ok: true; setting: CheckoutExcise } | { ok: false; errors: string[] };
69
+
70
+ /** Validate a save from /admin. A store whose compliance rules require excise cannot save it off. */
71
+ export function validateCheckoutExciseInput(raw: unknown, required: boolean): CheckoutExciseInput {
72
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, errors: ["body must be a JSON object"] };
73
+ const excise = (raw as Record<string, unknown>).excise;
74
+ if (typeof excise !== "boolean") return { ok: false, errors: ["excise must be true or false"] };
75
+ if (required && !excise) return { ok: false, errors: [REQUIRED_EXCISE_REFUSAL] };
76
+ return { ok: true, setting: { excise } };
77
+ }
78
+
79
+ /**
80
+ * The effective setting from what is saved: a required store is always on, otherwise the saved
81
+ * value, otherwise the capability default. An unreadable save is on: collecting tax is the stricter
82
+ * outcome, so a corrupt or unavailable store never switches it off.
83
+ */
84
+ export function resolveExcise(saved: SavedExcise, input: { required: boolean; capabilities: Pick<CapabilityConfig, "exciseTax"> }): boolean {
85
+ if (input.required || saved.state === "unreadable") return true;
86
+ return saved.state === "set" ? saved.excise : input.capabilities.exciseTax.enabled;
87
+ }
88
+
89
+ /** The store's saved setting for `env`. */
90
+ export async function readCheckoutExcise(tenantId: string, env: CustomizationEnv): Promise<SavedExcise> {
91
+ const kv = await readKv("TENANT_CACHE");
92
+ if (!kv) return UNREADABLE;
93
+ let raw: string | null;
94
+ try {
95
+ raw = await readPublishedArtifact((key) => kv.get(key), tenantId, env, checkoutExciseArtifactPath(tenantId));
96
+ } catch (err) {
97
+ console.warn(`[checkout-excise] unreadable ${JSON.stringify({ tenant: tenantId, env, error: err instanceof Error ? err.name : "unknown" })}`);
98
+ return UNREADABLE;
99
+ }
100
+ return parseCheckoutExcise(raw);
101
+ }
102
+
103
+ /** Whether checkout collects excise for `env`. */
104
+ export async function effectiveExcise(
105
+ tenant: Pick<TenantConfig, "tenant_id" | "compliance" | "siteType">,
106
+ capabilities: Pick<CapabilityConfig, "exciseTax">,
107
+ env: CustomizationEnv,
108
+ ): Promise<boolean> {
109
+ return resolveExcise(await readCheckoutExcise(tenant.tenant_id, env), { required: exciseRequired(tenant), capabilities });
110
+ }
@@ -31,6 +31,7 @@ import {
31
31
  withVerificationRef,
32
32
  withShippingPolicy,
33
33
  withReturnUrl,
34
+ withExcise,
34
35
  trustedCartReturnUrl,
35
36
  tenantPublicOrigin,
36
37
  CHECKOUT_NAVIGATION_REFERRER_POLICY,
@@ -45,6 +46,7 @@ import {
45
46
  import { resolveCheckoutHandoffCorrelation } from "@/lib/checkout/commerce/checkoutHandoffCorrelation";
46
47
  import { bindCartSession, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
47
48
  import { resolveCartSigning, shopperCartDenialMessage } from "@/lib/checkout/shared/checkoutCommerce";
49
+ import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
48
50
  import { fromD1 } from "@/lib/catalog/d1/catalog";
49
51
  import { readD1 } from "@/lib/publication/shared/env";
50
52
  import { handoffStockFinding, MIRROR_LOCATION_UNSPECIFIED, readMirrorBalance } from "@/lib/inventory/mirrorStock";
@@ -230,7 +232,12 @@ async function cartFormPost(context: APIContext): Promise<Response> {
230
232
  const verified = await withVerificationRef(result.fields, { mode: commerce.mode, secret: signing.secret, ref });
231
233
  const shippable = await boundShippingPolicy(verified, tenant, commerce.mode, signing.secret);
232
234
  if (!shippable) return cartDenial("shipping", SHIPPING_UNAVAILABLE_CART_MESSAGE, 409);
233
- const returned = await withReturnUrl(shippable, {
235
+ const excised = await withExcise(shippable, {
236
+ mode: commerce.mode,
237
+ secret: signing.secret,
238
+ excise: await effectiveExcise(tenant, context.locals.capabilities, context.locals.customizationEnv ?? "test"),
239
+ });
240
+ const returned = await withReturnUrl(excised, {
234
241
  mode: commerce.mode, secret: signing.secret, returnUrl: submittedFromUrl(context.request, tenant),
235
242
  });
236
243
  const location = await sessionedCartLocation(context, commerce, tenant, returned);
@@ -12,8 +12,8 @@
12
12
  * cart_include[drawer] / receipt / email), set and refreshed
13
13
  * through the commerce service.
14
14
  * The colors/fonts/logo live INSIDE the hosted template file.
15
- * 3. `store` — storeSubDomain + loader feature toggles (excise tax, age/ID
16
- * verification). Non-visual; no theme default.
15
+ * 3. `store` — storeSubDomain + the age/ID verification loader toggle.
16
+ * Non-visual; no theme default.
17
17
  *
18
18
  * Prepopulation lands on the parts with a theme default — the brand colors and
19
19
  * the template pointers (defaulted to a ToT-hosted, theme-derived template URL).
@@ -67,7 +67,6 @@ export interface CheckoutTemplatePointer {
67
67
  /** Store + loader feature config. Non-visual. */
68
68
  export interface CheckoutStoreConfig {
69
69
  storeSubDomain: string;
70
- exciseTaxCollectionEnabled: boolean;
71
70
  verificationEnabled: boolean;
72
71
  }
73
72
 
@@ -132,7 +131,6 @@ export function deriveCheckoutSettings(
132
131
  store: {
133
132
  storeSubDomain: commerce?.storeSubDomain ?? "",
134
133
  // Feature toggles have no theme default — start off; not prepopulatable.
135
- exciseTaxCollectionEnabled: false,
136
134
  verificationEnabled: false,
137
135
  },
138
136
  };
@@ -238,10 +236,6 @@ export function buildCheckoutSettingsFields(
238
236
  resettable: false,
239
237
  help: "Internal checkout store identifier for this tenant.",
240
238
  }),
241
- field("store", "store.exciseTaxCollectionEnabled", "Collect excise tax", "boolean", {
242
- resettable: false,
243
- help: "Managed pre-cart excise tax collection.",
244
- }),
245
239
  field("store", "store.verificationEnabled", "Age / identity verification", "boolean", {
246
240
  resettable: false,
247
241
  help: "Token of Trust verification at checkout.",
@@ -34,6 +34,7 @@ export const INTERNAL_CART_OPTIONS: readonly string[] = [
34
34
  "shipping_policy",
35
35
  "return_url",
36
36
  "content_version",
37
+ "excise",
37
38
  ];
38
39
 
39
40
  const MANAGED_CART_FORM = "form[data-managed-cart]";
@@ -16,7 +16,7 @@
16
16
  * idempotency key, `actorId` the authenticated install.
17
17
  */
18
18
  import { isStoredSku, parseSku, skuKey } from "@tot/public-runtime/sku";
19
- import type { CommerceStage } from "@tot/public-runtime";
19
+ import type { CatalogProduct, CommerceStage } from "@tot/public-runtime";
20
20
  import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
21
21
  import {
22
22
  guardedCorrectionStatement,
@@ -282,6 +282,11 @@ async function classifyRefused(
282
282
  return inventoryRefusal("balance-out-of-range");
283
283
  }
284
284
 
285
+ /** Every stored sku of the catalog's variants: the skus an app may write for this tenant. */
286
+ export function catalogSkus(products: readonly CatalogProduct[]): string[] {
287
+ return products.flatMap((product) => product.variants.flatMap((variant) => (variant.sku ? [variant.sku] : [])));
288
+ }
289
+
285
290
  /** The stored catalog sku matching `sku` under the platform sku comparison, or null. */
286
291
  export function matchCatalogSku(catalogSkus: Iterable<string>, sku: string): string | null {
287
292
  const wanted = skuKey(sku);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.8.2",
3
+ "version": "6.9.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",
@@ -338,6 +338,13 @@ export const ACTION_CATALOG = {
338
338
  argsAllow: ["versionId", "scope", ...OPERATIONAL_READ_BACK_ARGS], renderedAllow: [],
339
339
  desc: "A store's checkout requirements were saved to a version.",
340
340
  },
341
+ "content.checkout_excise.saved": {
342
+ // A store's excise setting (Settings → Checkout requirements) was saved to the store's
343
+ // operational selection. Same actors, spine and read-back args as the checkout requirements.
344
+ actors: ["merchant", "admin"], source: "server", sinks: LIFECYCLE,
345
+ argsAllow: ["versionId", "scope", ...OPERATIONAL_READ_BACK_ARGS], renderedAllow: [],
346
+ desc: "A store's excise setting was saved to a version.",
347
+ },
341
348
  "content.operational_setting.published": {
342
349
  // An operational setting's saved draft (checkout requirements or styling) was made the live
343
350
  // store's value (/api/preview/settings-live). `scope` names the setting.
@@ -239,9 +239,10 @@ export class CartSigningUnavailableError extends Error {
239
239
  * ref when the gate produced one (`withVerificationRef`). `shipping_policy` carries the
240
240
  * store's declared shipping charge (`withShippingPolicy`). `return_url` carries the page the
241
241
  * shopper submitted from (`withReturnUrl`). `content_version` carries the candidate
242
- * content pin the page rendered, and only then.
242
+ * content pin the page rendered, and only then. `excise` carries the store's excise setting
243
+ * (`withExcise`), `on` or `off`.
243
244
  */
244
- export const INTERNAL_CART_FIELDS = ["currency", "tenant", "verification", "shipping_policy", "return_url", "content_version"] as const;
245
+ export const INTERNAL_CART_FIELDS = ["currency", "tenant", "verification", "shipping_policy", "return_url", "content_version", "excise"] as const;
245
246
 
246
247
  /** Signed cart option naming the content version the preview page rendered. */
247
248
  export const CONTENT_VERSION_CART_FIELD = "content_version";
@@ -265,6 +266,9 @@ export const RETURN_URL_CART_FIELD = "return_url";
265
266
  */
266
267
  export const CHECKOUT_NAVIGATION_REFERRER_POLICY = "no-referrer-when-downgrade";
267
268
 
269
+ /** The signed cart option the checkout store reads the store's excise setting from. */
270
+ export const EXCISE_CART_FIELD = "excise";
271
+
268
272
  /** The signed cart option the checkout store reads the shipping charge from. */
269
273
  export const SHIPPING_POLICY_CART_FIELD = "shipping_policy";
270
274
 
@@ -1048,6 +1052,25 @@ export async function withShippingPolicy(
1048
1052
  return [...kept, await signField(opts.secret, code, field)];
1049
1053
  }
1050
1054
 
1055
+ /**
1056
+ * Bind the store's excise setting into an enforced cart as the internal `excise` option (`on` or
1057
+ * `off`), signed against the cart's product code. Any `excise` the shopper submitted is dropped
1058
+ * first, so only the store's own setting reaches the cart. A cart with no product code is
1059
+ * returned without one.
1060
+ */
1061
+ export async function withExcise(
1062
+ fields: readonly CartSubmissionField[],
1063
+ opts: { mode: ManagedCheckoutConfig["mode"]; secret?: string; excise: boolean },
1064
+ ): Promise<CartSubmissionField[]> {
1065
+ const kept = fields.filter((field) => field.name.split("||")[0] !== EXCISE_CART_FIELD);
1066
+ const code = kept.find((field) => field.name.split("||")[0] === "code")?.value;
1067
+ if (!code) return kept;
1068
+ const field: CartField = { name: EXCISE_CART_FIELD, value: opts.excise ? "on" : "off" };
1069
+ if (opts.mode !== "signed") return [...kept, unsignedField(field)];
1070
+ if (!opts.secret) throw new CartSigningUnavailableError();
1071
+ return [...kept, await signField(opts.secret, code, field)];
1072
+ }
1073
+
1051
1074
  const MAX_RETURN_URL_LENGTH = 1500;
1052
1075
 
1053
1076
  /**
@@ -87,7 +87,7 @@ export const CATALOG_LISTING_ARTIFACT = "catalog-listing.json";
87
87
  * or carried by a preview→live promotion. A store with no live site yet saves to both. A path not
88
88
  * listed here is repo-authored content: a channel pointer, when engaged, owns it.
89
89
  */
90
- export const OPERATIONAL_SETTING_FILES = Object.freeze(["checkout-requirements.json", "checkout-style.json"] as const);
90
+ export const OPERATIONAL_SETTING_FILES = Object.freeze(["checkout-requirements.json", "checkout-style.json", "checkout-excise.json"] as const);
91
91
  export type OperationalSettingFile = (typeof OPERATIONAL_SETTING_FILES)[number];
92
92
 
93
93
  export function operationalSettingArtifactPath(tenantId: string, file: OperationalSettingFile): string {