@tokenoftrust/storefront-runner 7.10.0 → 7.11.0

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.
@@ -13,6 +13,7 @@
13
13
  * checkout store, and production, keep the full fail-closed contract regardless of what is saved here.
14
14
  */
15
15
  import { operationalSettingArtifactPath, readPublishedArtifact, type CustomizationEnv } from "@tot/public-runtime";
16
+ import { carrierRatePolicyProblem, quoteCarrierRate, type CarrierRatePolicy, type CarrierRateQuote, type LocationCarrierRate } from "@tot/public-runtime/shipping-rate-policy";
16
17
  import { readKv } from "@/lib/publication/shared/runtimeEnv";
17
18
  import { checkoutStoreHasExciseProducer } from "./sharedStoreAdmission";
18
19
 
@@ -38,6 +39,48 @@ export function checkoutStoreTaxBlocker(
38
39
 
39
40
  export const CHECKOUT_REQUIREMENT_KEYS = ["verification", "tax", "rules"] as const;
40
41
 
42
+ /** The artifact key carrying the carrier-rate + per-order markup policy (not a boolean switch). */
43
+ export const SHIPPING_RATE_POLICY_KEY = "shippingRatePolicy";
44
+
45
+ /**
46
+ * The carrier-rate policy declared in a `checkout-requirements.json` artifact, or `null` when none
47
+ * is declared or the declaration is invalid (a reader must then quote no carrier rate).
48
+ */
49
+ export function parseShippingRatePolicy(raw: string | null): CarrierRatePolicy | null {
50
+ if (raw === null) return null;
51
+ let parsed: unknown;
52
+ try {
53
+ parsed = JSON.parse(raw);
54
+ } catch (error) {
55
+ if (!(error instanceof SyntaxError)) throw error;
56
+ return null;
57
+ }
58
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
59
+ const declared = (parsed as Record<string, unknown>)[SHIPPING_RATE_POLICY_KEY];
60
+ if (!declared || typeof declared !== "object" || Array.isArray(declared)) return null;
61
+ const policy = declared as CarrierRatePolicy;
62
+ if (carrierRatePolicyProblem(policy) !== null) return null;
63
+ return { markupMinor: policy.markupMinor, signatureFeeMinor: policy.signatureFeeMinor, multiLocationPolicy: policy.multiLocationPolicy };
64
+ }
65
+
66
+ /**
67
+ * The artifact bytes a switches save writes: the validated switches plus the store's existing
68
+ * `shippingRatePolicy`, so an ordinary save never drops it.
69
+ */
70
+ export function serializeCheckoutRequirements(requirements: CheckoutRequirements, policy: CarrierRatePolicy | null): string {
71
+ return JSON.stringify(policy ? { ...requirements, [SHIPPING_RATE_POLICY_KEY]: policy } : requirements);
72
+ }
73
+
74
+ /**
75
+ * Quote an order's shipping from per-location carrier rates under the store's declared policy.
76
+ * Entry point for a rate hook: the markup and signature fee are charged once per order unless
77
+ * `per_location` is declared. `null` when the store declares no valid policy.
78
+ */
79
+ export function quoteOrderShipping(rawArtifact: string | null, rates: readonly LocationCarrierRate[]): CarrierRateQuote | null {
80
+ const policy = parseShippingRatePolicy(rawArtifact);
81
+ return policy ? quoteCarrierRate(policy, rates) : null;
82
+ }
83
+
41
84
  export const DEFAULT_CHECKOUT_REQUIREMENTS: Readonly<CheckoutRequirements> = Object.freeze({
42
85
  verification: false,
43
86
  tax: false,
@@ -63,7 +106,8 @@ export function parseCheckoutRequirements(raw: string | null): CheckoutRequireme
63
106
  }
64
107
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
65
108
  const value = parsed as Record<string, unknown>;
66
- if (Object.keys(value).some(key => !(CHECKOUT_REQUIREMENT_KEYS as readonly string[]).includes(key))) return null;
109
+ if (Object.keys(value).some(key => key !== SHIPPING_RATE_POLICY_KEY && !(CHECKOUT_REQUIREMENT_KEYS as readonly string[]).includes(key))) return null;
110
+ if (SHIPPING_RATE_POLICY_KEY in value && parseShippingRatePolicy(raw) === null) return null;
67
111
  const out = { ...DEFAULT_CHECKOUT_REQUIREMENTS };
68
112
  for (const key of CHECKOUT_REQUIREMENT_KEYS) {
69
113
  if (value[key] === undefined) continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.10.0",
3
+ "version": "7.11.0",
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",
@@ -12,6 +12,7 @@
12
12
  ".": "./src/index.ts",
13
13
  "./widget-postmessage": "./src/widget-postmessage.ts",
14
14
  "./compliance-obligations": "./src/compliance-obligations.ts",
15
+ "./shipping-rate-policy": "./src/shipping-rate-policy.ts",
15
16
  "./integration/consent-broker": "./src/integration/consent-broker.ts",
16
17
  "./integration/environment": "./src/integration/environment.ts",
17
18
  "./integration/render-phases": "./src/integration/render-phases.ts",
@@ -579,30 +579,39 @@ export function createCaptureArtifactRewriter(rewrites: readonly CaptureRewrite[
579
579
  // once, at each `/`, to find the only rewrites with a needle that can occur in it: wherever a needle
580
580
  // occurs, a `/` is followed by its anchor. A rewrite with a needle lacking an anchor (no slash, or
581
581
  // fewer characters after it) is always tried.
582
+ // A file name shorter than the anchor length is its own anchor (its whole text), so short names
583
+ // such as `2-4.avif` are indexed rather than always tried. `anchorLengths` records the distinct
584
+ // anchor lengths in use, and an artifact is probed once per length at each `/`.
582
585
  const anchored = new Map<string, number[]>();
586
+ const anchorLengths = new Set<number>();
583
587
  const always: number[] = [];
584
588
  prepared.forEach(({ needles }, index) => {
585
589
  const anchors = new Set<string>();
586
590
  for (const needle of needles) {
587
591
  const slash = needle.lastIndexOf("/");
588
- if (slash < 0 || needle.length - slash - 1 < REWRITE_ANCHOR_LENGTH) {
592
+ if (slash < 0 || slash === needle.length - 1) {
589
593
  always.push(index);
590
594
  return;
591
595
  }
592
- anchors.add(needle.substr(slash + 1, REWRITE_ANCHOR_LENGTH));
596
+ const anchor = needle.substr(slash + 1, REWRITE_ANCHOR_LENGTH);
597
+ anchors.add(anchor);
593
598
  }
594
599
  for (const anchor of anchors) {
600
+ anchorLengths.add(anchor.length);
595
601
  const list = anchored.get(anchor);
596
602
  if (list) list.push(index);
597
603
  else anchored.set(anchor, [index]);
598
604
  }
599
605
  });
606
+ const lengths = [...anchorLengths].sort((a, b) => a - b);
600
607
  const candidatesIn = (content: string): number[] => {
601
608
  if (anchored.size === 0) return always;
602
609
  const found = new Set<number>(always);
603
610
  for (let at = content.indexOf("/"); at !== -1; at = content.indexOf("/", at + 1)) {
604
- const list = anchored.get(content.substr(at + 1, REWRITE_ANCHOR_LENGTH));
605
- if (list) for (const index of list) found.add(index);
611
+ for (const length of lengths) {
612
+ const list = anchored.get(content.substr(at + 1, length));
613
+ if (list) for (const index of list) found.add(index);
614
+ }
606
615
  }
607
616
  return [...found].sort((a, b) => a - b);
608
617
  };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Carrier-calculated shipping: carrier rate + a per-order markup, charged once per order.
3
+ *
4
+ * A rate hook (a private app such as the ShipStation connector) returns one carrier rate per
5
+ * ship-from location the order splits across. The order pays the carrier rates plus
6
+ * `markupMinor` and `signatureFeeMinor` exactly once, never once per location.
7
+ * All amounts are integer minor units of one currency.
8
+ */
9
+
10
+ export type MultiLocationPolicy = "once_per_order" | "per_location";
11
+
12
+ export interface CarrierRatePolicy {
13
+ /** Fixed amount added to the order, minor units (200 = $2.00). */
14
+ markupMinor: number;
15
+ /** Order-level adult-signature fee, minor units. Defaults to 0. */
16
+ signatureFeeMinor?: number;
17
+ /** Defaults to `once_per_order`. */
18
+ multiLocationPolicy?: MultiLocationPolicy;
19
+ }
20
+
21
+ /** The carrier's rate for one ship-from location's parcel(s). */
22
+ export interface LocationCarrierRate {
23
+ locationId: string;
24
+ carrierRateMinor: number;
25
+ }
26
+
27
+ export interface CarrierRateQuote {
28
+ carrierRateMinor: number;
29
+ markupMinor: number;
30
+ signatureFeeMinor: number;
31
+ totalMinor: number;
32
+ locationCount: number;
33
+ }
34
+
35
+ export class CarrierRatePolicyError extends Error {
36
+ readonly code = "carrier-rate-policy" as const;
37
+ constructor(message: string) {
38
+ super(message);
39
+ this.name = "CarrierRatePolicyError";
40
+ }
41
+ }
42
+
43
+ function minor(value: unknown, what: string): number {
44
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
45
+ throw new CarrierRatePolicyError(`${what} must be a non-negative integer of minor units.`);
46
+ }
47
+ return value;
48
+ }
49
+
50
+ /** `null` when `policy` is a valid carrier-rate policy, else the reason it is not. */
51
+ export function carrierRatePolicyProblem(policy: CarrierRatePolicy): string | null {
52
+ const ok = (value: unknown, allowUndefined: boolean) =>
53
+ (allowUndefined && value === undefined) || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
54
+ if (!ok(policy.markupMinor, false)) return "markupMinor must be a non-negative integer of minor units.";
55
+ if (!ok(policy.signatureFeeMinor, true)) return "signatureFeeMinor must be a non-negative integer of minor units.";
56
+ const mode = policy.multiLocationPolicy;
57
+ if (mode !== undefined && mode !== "once_per_order" && mode !== "per_location") {
58
+ return "multiLocationPolicy must be once_per_order or per_location.";
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /**
64
+ * Price an order from per-location carrier rates. Throws `CarrierRatePolicyError` on an invalid
65
+ * policy, an empty or duplicate-location rate list, or a non-integer amount (fails closed).
66
+ */
67
+ export function quoteCarrierRate(policy: CarrierRatePolicy, rates: readonly LocationCarrierRate[]): CarrierRateQuote {
68
+ const markup = minor(policy.markupMinor, "markupMinor");
69
+ const signature = minor(policy.signatureFeeMinor ?? 0, "signatureFeeMinor");
70
+ const mode = policy.multiLocationPolicy ?? "once_per_order";
71
+ if (mode !== "once_per_order" && mode !== "per_location") {
72
+ throw new CarrierRatePolicyError("multiLocationPolicy must be once_per_order or per_location.");
73
+ }
74
+ if (rates.length === 0) throw new CarrierRatePolicyError("At least one location rate is required.");
75
+ const seen = new Set<string>();
76
+ let carrier = 0;
77
+ for (const rate of rates) {
78
+ if (!rate.locationId || seen.has(rate.locationId)) {
79
+ throw new CarrierRatePolicyError("Each location rate needs a unique locationId.");
80
+ }
81
+ seen.add(rate.locationId);
82
+ carrier += minor(rate.carrierRateMinor, "carrierRateMinor");
83
+ }
84
+ const multiplier = mode === "per_location" ? rates.length : 1;
85
+ const markupMinor = markup * multiplier;
86
+ const signatureFeeMinor = signature * multiplier;
87
+ return {
88
+ carrierRateMinor: carrier,
89
+ markupMinor,
90
+ signatureFeeMinor,
91
+ totalMinor: carrier + markupMinor + signatureFeeMinor,
92
+ locationCount: rates.length,
93
+ };
94
+ }