@tokenoftrust/storefront-runner 7.11.11 → 7.13.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.
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Per-state directory allow-list eligibility & cart revalidation.
3
+ *
4
+ * Pure, edge-safe decision core for:
5
+ * 1. Validating/normalizing 2-letter US state/DC codes (`normalizeUsStateCode`).
6
+ * 2. Evaluating whether a product is eligible to ship to a selected state under
7
+ * store-wide restrictions, per-state directory allow-lists (`directoryStates`),
8
+ * product-level `allowedStates` / `restrictedStates`, and directory tags
9
+ * (`directory:<ST>`, `state-directory:<ST>`, `state:<ST>`).
10
+ * 3. Revalidating a shopper's cart when their ship-to state changes, partitioning
11
+ * kept vs. removed lines and composing a clear shopper-facing notice.
12
+ */
13
+
14
+ /** US states and DC (50 states + District of Columbia) in alphabetical order by name. */
15
+ export const US_STATE_OPTIONS: ReadonlyArray<{ readonly code: string; readonly name: string }> = [
16
+ { code: "AL", name: "Alabama" },
17
+ { code: "AK", name: "Alaska" },
18
+ { code: "AZ", name: "Arizona" },
19
+ { code: "AR", name: "Arkansas" },
20
+ { code: "CA", name: "California" },
21
+ { code: "CO", name: "Colorado" },
22
+ { code: "CT", name: "Connecticut" },
23
+ { code: "DE", name: "Delaware" },
24
+ { code: "DC", name: "District of Columbia" },
25
+ { code: "FL", name: "Florida" },
26
+ { code: "GA", name: "Georgia" },
27
+ { code: "HI", name: "Hawaii" },
28
+ { code: "ID", name: "Idaho" },
29
+ { code: "IL", name: "Illinois" },
30
+ { code: "IN", name: "Indiana" },
31
+ { code: "IA", name: "Iowa" },
32
+ { code: "KS", name: "Kansas" },
33
+ { code: "KY", name: "Kentucky" },
34
+ { code: "LA", name: "Louisiana" },
35
+ { code: "ME", name: "Maine" },
36
+ { code: "MD", name: "Maryland" },
37
+ { code: "MA", name: "Massachusetts" },
38
+ { code: "MI", name: "Michigan" },
39
+ { code: "MN", name: "Minnesota" },
40
+ { code: "MS", name: "Mississippi" },
41
+ { code: "MO", name: "Missouri" },
42
+ { code: "MT", name: "Montana" },
43
+ { code: "NE", name: "Nebraska" },
44
+ { code: "NV", name: "Nevada" },
45
+ { code: "NH", name: "New Hampshire" },
46
+ { code: "NJ", name: "New Jersey" },
47
+ { code: "NM", name: "New Mexico" },
48
+ { code: "NY", name: "New York" },
49
+ { code: "NC", name: "North Carolina" },
50
+ { code: "ND", name: "North Dakota" },
51
+ { code: "OH", name: "Ohio" },
52
+ { code: "OK", name: "Oklahoma" },
53
+ { code: "OR", name: "Oregon" },
54
+ { code: "PA", name: "Pennsylvania" },
55
+ { code: "RI", name: "Rhode Island" },
56
+ { code: "SC", name: "South Carolina" },
57
+ { code: "SD", name: "South Dakota" },
58
+ { code: "TN", name: "Tennessee" },
59
+ { code: "TX", name: "Texas" },
60
+ { code: "UT", name: "Utah" },
61
+ { code: "VT", name: "Vermont" },
62
+ { code: "VA", name: "Virginia" },
63
+ { code: "WA", name: "Washington" },
64
+ { code: "WV", name: "West Virginia" },
65
+ { code: "WI", name: "Wisconsin" },
66
+ { code: "WY", name: "Wyoming" },
67
+ ];
68
+
69
+ const US_STATE_CODE_SET: ReadonlySet<string> = new Set(US_STATE_OPTIONS.map((s) => s.code));
70
+
71
+ const DIRECTORY_TAG_PATTERN = /^(?:directory|state-directory|state):\s*(.+)$/i;
72
+
73
+ /**
74
+ * Normalize a US state or DC code to its canonical 2-letter uppercase form.
75
+ * Accepts optional leading/trailing whitespace and an optional `US-` prefix.
76
+ * Returns `null` for nullish, empty, or unrecognized values.
77
+ */
78
+ export function normalizeUsStateCode(raw: string | null | undefined): string | null {
79
+ if (typeof raw !== "string") return null;
80
+ const trimmed = raw.trim().toUpperCase();
81
+ if (!trimmed) return null;
82
+ const code = trimmed.startsWith("US-") ? trimmed.slice(3) : trimmed;
83
+ return US_STATE_CODE_SET.has(code) ? code : null;
84
+ }
85
+
86
+ /** Normalize a list of raw state codes into a deduplicated set of valid US state/DC codes. */
87
+ function normalizeStateSet(codes: readonly string[] | null | undefined): Set<string> {
88
+ const out = new Set<string>();
89
+ if (!codes) return out;
90
+ for (const raw of codes) {
91
+ const code = normalizeUsStateCode(raw);
92
+ if (code) out.add(code);
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /**
98
+ * Extract valid 2-letter US state codes declared via product directory tags
99
+ * (`directory:<ST>`, `state-directory:<ST>`, or `state:<ST>`).
100
+ */
101
+ export function extractDirectoryStatesFromTags(
102
+ tags: readonly string[] | null | undefined,
103
+ ): string[] {
104
+ if (!tags || tags.length === 0) return [];
105
+ const seen = new Set<string>();
106
+ const out: string[] = [];
107
+ for (const tag of tags) {
108
+ if (typeof tag !== "string") continue;
109
+ const match = DIRECTORY_TAG_PATTERN.exec(tag.trim());
110
+ if (!match) continue;
111
+ const code = normalizeUsStateCode(match[1]);
112
+ if (code && !seen.has(code)) {
113
+ seen.add(code);
114
+ out.push(code);
115
+ }
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /** Store-level state eligibility & per-state directory allow-list configuration. */
121
+ export interface StateDirectoryRule {
122
+ /**
123
+ * States that maintain a regulated product directory / allow-list.
124
+ * Shipping to a state in this list fails closed unless the product explicitly
125
+ * allows that state (via `allowedStates` or a matching directory tag).
126
+ */
127
+ directoryStates?: readonly string[];
128
+ /** States where sale/shipment is prohibited store-wide. */
129
+ restrictedStates?: readonly string[];
130
+ /** Store-wide allow-list — when non-empty, states outside this list are restricted. */
131
+ eligibleStates?: readonly string[];
132
+ }
133
+
134
+ /** Product-level state eligibility inputs. */
135
+ export interface ProductStateEligibilityInput {
136
+ /** Explicit per-product ship-to allow-list (when non-empty, only listed states are eligible). */
137
+ allowedStates?: readonly string[] | null;
138
+ /** Explicit per-product no-ship list. */
139
+ restrictedStates?: readonly string[] | null;
140
+ /** Product tags; `directory:<ST>`, `state-directory:<ST>`, and `state:<ST>` grant directory eligibility. */
141
+ tags?: readonly string[] | null;
142
+ }
143
+
144
+ export type ProductStateEligibilityReason =
145
+ | "no-state-selected"
146
+ | "eligible"
147
+ | "state-restricted"
148
+ | "not-on-state-directory";
149
+
150
+ export interface ProductStateEligibilityDecision {
151
+ eligible: boolean;
152
+ reason: ProductStateEligibilityReason;
153
+ stateCode: string | null;
154
+ }
155
+
156
+ /**
157
+ * Evaluate whether a product may be sold/shipped to `stateCode` under `config`.
158
+ *
159
+ * Precedence:
160
+ * 1. Unset/invalid `stateCode` → `{ eligible: true, reason: "no-state-selected" }`.
161
+ * 2. `config.restrictedStates`, `product.restrictedStates`, or outside non-empty
162
+ * `config.eligibleStates` → `{ eligible: false, reason: "state-restricted" }`.
163
+ * 3. `config.directoryStates` includes `stateCode` → product MUST explicitly allow
164
+ * `stateCode` (via `product.allowedStates` or a directory tag for `stateCode`),
165
+ * otherwise fail closed with `{ eligible: false, reason: "not-on-state-directory" }`.
166
+ * 4. Non-empty `product.allowedStates` omitting `stateCode` →
167
+ * `{ eligible: false, reason: "not-on-state-directory" }`.
168
+ * 5. Otherwise → `{ eligible: true, reason: "eligible" }`.
169
+ */
170
+ export function evaluateProductStateEligibility(
171
+ product: ProductStateEligibilityInput,
172
+ stateCode: string | null | undefined,
173
+ config?: StateDirectoryRule | null,
174
+ ): ProductStateEligibilityDecision {
175
+ const normalized = normalizeUsStateCode(stateCode);
176
+ if (!normalized) {
177
+ return { eligible: true, reason: "no-state-selected", stateCode: null };
178
+ }
179
+
180
+ const configRestricted = normalizeStateSet(config?.restrictedStates);
181
+ const productRestricted = normalizeStateSet(product.restrictedStates);
182
+ if (configRestricted.has(normalized) || productRestricted.has(normalized)) {
183
+ return { eligible: false, reason: "state-restricted", stateCode: normalized };
184
+ }
185
+
186
+ const configEligible = normalizeStateSet(config?.eligibleStates);
187
+ if (configEligible.size > 0 && !configEligible.has(normalized)) {
188
+ return { eligible: false, reason: "state-restricted", stateCode: normalized };
189
+ }
190
+
191
+ const productAllowed = normalizeStateSet(product.allowedStates);
192
+ const directoryStates = normalizeStateSet(config?.directoryStates);
193
+ if (directoryStates.has(normalized)) {
194
+ const tagDirectoryStates = new Set(extractDirectoryStatesFromTags(product.tags));
195
+ if (!productAllowed.has(normalized) && !tagDirectoryStates.has(normalized)) {
196
+ return { eligible: false, reason: "not-on-state-directory", stateCode: normalized };
197
+ }
198
+ }
199
+
200
+ if (productAllowed.size > 0 && !productAllowed.has(normalized)) {
201
+ return { eligible: false, reason: "not-on-state-directory", stateCode: normalized };
202
+ }
203
+
204
+ return { eligible: true, reason: "eligible", stateCode: normalized };
205
+ }
206
+
207
+ export interface CartRevalidationLine {
208
+ sku?: string;
209
+ code?: string;
210
+ handle?: string;
211
+ title?: string;
212
+ name?: string;
213
+ quantity?: number;
214
+ }
215
+
216
+ export interface RemovedCartLine<TLine extends CartRevalidationLine = CartRevalidationLine> {
217
+ line: TLine;
218
+ reason: Exclude<ProductStateEligibilityReason, "eligible" | "no-state-selected">;
219
+ }
220
+
221
+ export interface CartStateRevalidationResult<TLine extends CartRevalidationLine = CartRevalidationLine> {
222
+ stateCode: string | null;
223
+ kept: TLine[];
224
+ removed: RemovedCartLine<TLine>[];
225
+ /** Clear shopper-facing summary when one or more items were removed; `null` otherwise. */
226
+ notice: string | null;
227
+ }
228
+
229
+ function lineDisplayName(line: CartRevalidationLine): string | null {
230
+ const candidate = (line.title ?? line.name ?? line.sku ?? line.code ?? line.handle ?? "").trim();
231
+ return candidate.length > 0 ? candidate : null;
232
+ }
233
+
234
+ function formatRemovalNotice<TLine extends CartRevalidationLine>(
235
+ removed: readonly RemovedCartLine<TLine>[],
236
+ stateCode: string,
237
+ ): string | null {
238
+ if (removed.length === 0) return null;
239
+ const names = removed
240
+ .map((entry) => lineDisplayName(entry.line))
241
+ .filter((n): n is string => n !== null);
242
+ const MAX_NAMED = 3;
243
+ const summaryNames =
244
+ names.length === 0
245
+ ? ""
246
+ : names.length <= MAX_NAMED
247
+ ? ` (${names.join(", ")})`
248
+ : ` (${names.slice(0, MAX_NAMED).join(", ")}, and ${names.length - MAX_NAMED} more)`;
249
+
250
+ if (removed.length === 1) {
251
+ return `1 item${summaryNames} was removed from your cart because it cannot be shipped to ${stateCode}.`;
252
+ }
253
+ return `${removed.length} items${summaryNames} were removed from your cart because they cannot be shipped to ${stateCode}.`;
254
+ }
255
+
256
+ /**
257
+ * Revalidate every cart line against `stateCode`, returning the kept lines,
258
+ * removed lines (with per-line reasons), and a shopper-facing notice string
259
+ * when any line is removed.
260
+ */
261
+ export function revalidateCartForState<TLine extends CartRevalidationLine>(
262
+ lines: readonly TLine[],
263
+ stateCode: string | null | undefined,
264
+ resolveProduct: (line: TLine) => ProductStateEligibilityInput | null | undefined,
265
+ config?: StateDirectoryRule | null,
266
+ ): CartStateRevalidationResult<TLine> {
267
+ const normalized = normalizeUsStateCode(stateCode);
268
+ if (!normalized) {
269
+ return {
270
+ stateCode: null,
271
+ kept: [...lines],
272
+ removed: [],
273
+ notice: null,
274
+ };
275
+ }
276
+
277
+ const kept: TLine[] = [];
278
+ const removed: RemovedCartLine<TLine>[] = [];
279
+
280
+ for (const line of lines) {
281
+ const product = resolveProduct(line) ?? {};
282
+ const decision = evaluateProductStateEligibility(product, normalized, config);
283
+ if (decision.eligible) {
284
+ kept.push(line);
285
+ } else if (decision.reason === "state-restricted" || decision.reason === "not-on-state-directory") {
286
+ removed.push({ line, reason: decision.reason });
287
+ }
288
+ }
289
+
290
+ return {
291
+ stateCode: normalized,
292
+ kept,
293
+ removed,
294
+ notice: formatRemovalNotice(removed, normalized),
295
+ };
296
+ }
@@ -252,6 +252,8 @@ export interface StateEligibilityConfig {
252
252
  restrictedStates?: string[];
253
253
  /** Allowlist — sale/shipment available ONLY in these. */
254
254
  eligibleStates?: string[];
255
+ /** States requiring products to appear on that state's directory/allow-list (fail-closed). */
256
+ directoryStates?: string[];
255
257
  /** Custom display message; when omitted a sentence is composed from the lists. */
256
258
  note?: string;
257
259
  }