@tokenoftrust/storefront-runner 7.15.1 → 8.0.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.
- package/apps/storefront/src/config/compliance/rulesets.ts +475 -50
- package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +10 -4
- package/apps/storefront/src/lib/compliance/enforcement.ts +29 -0
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +45 -22
- package/apps/storefront/src/pages/api/compliance/preflight.ts +162 -66
- package/package.json +1 -1
- package/packages/public-runtime/src/compliance/evaluate.ts +600 -126
- package/packages/public-runtime/src/compliance/evidence-signals.ts +3 -1
- package/packages/public-runtime/src/compliance/profile.ts +184 -166
- package/packages/public-runtime/src/compliance/ruleset.ts +743 -78
- package/packages/public-runtime/src/compliance/state-directory.ts +116 -4
- package/packages/public-runtime/src/tenant.ts +1 -1
- package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +100 -38
|
@@ -1,93 +1,213 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Compliance RULESET — the data-driven jurisdiction
|
|
3
|
-
*
|
|
4
|
-
* branches: a tenant's regulated obligations (state flavor/no-ship bans, per-order
|
|
5
|
-
* limits, PACT Act, verification, excise) are expressed as a serializable record
|
|
6
|
-
* so the rules can be reviewed, versioned, and updated without touching the
|
|
7
|
-
* evaluator. The concrete per-tenant data literals live in the app
|
|
8
|
-
* (`apps/storefront/src/config/compliance/rulesets.ts`); this module owns the
|
|
9
|
-
* SHAPE + resolution helpers.
|
|
2
|
+
* Compliance RULESET — the data-driven declarative jurisdiction, channel,
|
|
3
|
+
* product-fact, and tenant-footprint rule model evaluated by `evaluate.ts`.
|
|
10
4
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
5
|
+
* All rules are inert serializable data (no `eval`, no callbacks, closed operator
|
|
6
|
+
* vocabulary). Rule pack data lives in `apps/storefront/src/config/compliance/rulesets.ts`;
|
|
7
|
+
* this module owns the schema, validator, stricter-only override merger, and pure
|
|
8
|
+
* resolution helpers.
|
|
9
|
+
*
|
|
10
|
+
* Under `counsel-coverage-decision`, platform rule packs capture best-effort
|
|
11
|
+
* compliance declarations without external legal counsel; merchants and their
|
|
12
|
+
* counsel own authoritative rule review and statutory filings. Every rule pack
|
|
13
|
+
* stamps `source` and `updatedAt` to make that boundary explicit.
|
|
16
14
|
*
|
|
17
15
|
* Pure + edge-safe (no node, no I/O).
|
|
18
16
|
*/
|
|
17
|
+
import { REGISTRY_JURISDICTIONS } from "./state-directory.js";
|
|
18
|
+
|
|
19
|
+
/** Checkout sales channel. Unspecified defaults fail-closed to `"b2c"`. */
|
|
20
|
+
export type SalesChannel = "b2b" | "b2c";
|
|
21
|
+
|
|
22
|
+
export const SALES_CHANNELS: readonly SalesChannel[] = ["b2c", "b2b"] as const;
|
|
23
|
+
|
|
24
|
+
const SALES_CHANNEL_SET: ReadonlySet<string> = new Set(SALES_CHANNELS);
|
|
25
|
+
|
|
26
|
+
/** Closed structured block codes emitted by `evaluateCartCompliance`. */
|
|
27
|
+
export type ComplianceBlockCode =
|
|
28
|
+
| "ruleset_unavailable"
|
|
29
|
+
| "invalid_ruleset"
|
|
30
|
+
| "verification_unconfigured"
|
|
31
|
+
| "verification_required"
|
|
32
|
+
| "verification_failed"
|
|
33
|
+
| "destination_required"
|
|
34
|
+
| "postal_code_required"
|
|
35
|
+
| "region_prohibited"
|
|
36
|
+
| "flavored_prohibited"
|
|
37
|
+
| "cooling_agent_prohibited"
|
|
38
|
+
| "registry_prohibited"
|
|
39
|
+
| "fact_prohibited"
|
|
40
|
+
| "pact_requirement_failed"
|
|
41
|
+
| "sku_limit_exceeded"
|
|
42
|
+
| "purchase_limit_exceeded"
|
|
43
|
+
| "excise_unavailable";
|
|
44
|
+
|
|
45
|
+
/** Closed set of declarative predicate operators — never executable expressions. */
|
|
46
|
+
export type DeclarativeOperator =
|
|
47
|
+
| "eq"
|
|
48
|
+
| "neq"
|
|
49
|
+
| "in"
|
|
50
|
+
| "not_in"
|
|
51
|
+
| "gt"
|
|
52
|
+
| "gte"
|
|
53
|
+
| "lt"
|
|
54
|
+
| "lte"
|
|
55
|
+
| "prefix"
|
|
56
|
+
| "is_true"
|
|
57
|
+
| "is_false"
|
|
58
|
+
| "is_known"
|
|
59
|
+
| "registry_listed";
|
|
60
|
+
|
|
61
|
+
export const DECLARATIVE_OPERATORS: ReadonlySet<string> = new Set<DeclarativeOperator>([
|
|
62
|
+
"eq",
|
|
63
|
+
"neq",
|
|
64
|
+
"in",
|
|
65
|
+
"not_in",
|
|
66
|
+
"gt",
|
|
67
|
+
"gte",
|
|
68
|
+
"lt",
|
|
69
|
+
"lte",
|
|
70
|
+
"prefix",
|
|
71
|
+
"is_true",
|
|
72
|
+
"is_false",
|
|
73
|
+
"is_known",
|
|
74
|
+
"registry_listed",
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
export type RuleFactScalar = string | number | boolean;
|
|
78
|
+
export type RuleFactValue = RuleFactScalar | readonly (string | number)[];
|
|
79
|
+
|
|
80
|
+
export interface FieldPredicate {
|
|
81
|
+
/** Field path resolved against the evaluated line, catalog facts, or `facts.<key>`. */
|
|
82
|
+
field: string;
|
|
83
|
+
op: DeclarativeOperator;
|
|
84
|
+
value?: RuleFactValue;
|
|
85
|
+
/** Explicit override allowing `not_applicable` catalog readings (defaults false = fail closed). */
|
|
86
|
+
allowNotApplicable?: boolean;
|
|
87
|
+
}
|
|
19
88
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
|
|
41
|
-
/**
|
|
89
|
+
export type RulePredicate =
|
|
90
|
+
| FieldPredicate
|
|
91
|
+
| { all: readonly RulePredicate[] }
|
|
92
|
+
| { any: readonly RulePredicate[] }
|
|
93
|
+
| { not: RulePredicate };
|
|
94
|
+
|
|
95
|
+
export interface RuleDestinationMatch {
|
|
96
|
+
/** ISO 2-letter uppercase country code (e.g. `"US"`). Omitted matches any country. */
|
|
97
|
+
country?: string;
|
|
98
|
+
/** Uppercase 2-letter region/state codes (e.g. `["CA"]`). Omitted matches all regions. */
|
|
99
|
+
regions?: readonly string[];
|
|
100
|
+
/** US 1-to-5-digit ZIP prefixes (e.g. `["941"]` for San Francisco `941xx`). */
|
|
101
|
+
zipPrefixes?: readonly string[];
|
|
102
|
+
/** Optional ZIP prefix exclusions. */
|
|
103
|
+
excludeZipPrefixes?: readonly string[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface RuleWhen {
|
|
107
|
+
destination?: RuleDestinationMatch;
|
|
108
|
+
/** Channels this rule governs; omitted applies to all channels. */
|
|
109
|
+
channels?: readonly SalesChannel[];
|
|
110
|
+
/** Declarative line/fact filter selecting which cart lines this rule targets. */
|
|
111
|
+
subjectMatch?: RulePredicate;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export type ComplianceRuleEffect =
|
|
115
|
+
| {
|
|
116
|
+
kind: "ban_shipment";
|
|
117
|
+
code?: ComplianceBlockCode;
|
|
118
|
+
message?: string;
|
|
119
|
+
}
|
|
120
|
+
| {
|
|
121
|
+
kind: "ban_flavored";
|
|
122
|
+
}
|
|
123
|
+
| {
|
|
124
|
+
kind: "ban_cooling_agent";
|
|
125
|
+
}
|
|
126
|
+
| {
|
|
127
|
+
kind: "require_predicate";
|
|
128
|
+
code: ComplianceBlockCode;
|
|
129
|
+
predicate: RulePredicate;
|
|
130
|
+
message: string;
|
|
131
|
+
failClosedMessage?: string;
|
|
132
|
+
/** When true, unclassified items on a regulated tenant fail closed on this rule. */
|
|
133
|
+
blockOnUnclassified?: boolean;
|
|
134
|
+
}
|
|
135
|
+
| {
|
|
136
|
+
kind: "per_sku_limit";
|
|
137
|
+
limit: number;
|
|
138
|
+
code?: ComplianceBlockCode;
|
|
139
|
+
message?: string;
|
|
140
|
+
}
|
|
141
|
+
| {
|
|
142
|
+
kind: "per_order_limit";
|
|
143
|
+
limit: number;
|
|
144
|
+
code?: ComplianceBlockCode;
|
|
145
|
+
message?: string;
|
|
146
|
+
}
|
|
147
|
+
| {
|
|
148
|
+
kind: "require_adult_signature";
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export interface ComplianceRule {
|
|
152
|
+
id: string;
|
|
42
153
|
note?: string;
|
|
154
|
+
when?: RuleWhen;
|
|
155
|
+
effect: ComplianceRuleEffect;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Pure declarative, versioned rule pack consumed by the compliance engine. */
|
|
159
|
+
export interface ComplianceRulePack {
|
|
160
|
+
packId: string;
|
|
161
|
+
/** Semver version (`MAJOR.MINOR.PATCH`). */
|
|
162
|
+
version: string;
|
|
163
|
+
/** ISO date the rule data was last reviewed. */
|
|
164
|
+
updatedAt: string;
|
|
165
|
+
/** Provenance / governance disclaimer note. */
|
|
166
|
+
source: string;
|
|
167
|
+
/** Fail-closed default channel (`"b2c"`). */
|
|
168
|
+
defaultChannel?: SalesChannel;
|
|
169
|
+
rules: readonly ComplianceRule[];
|
|
43
170
|
}
|
|
44
171
|
|
|
45
172
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
173
|
+
* Stricter-only tenant configuration overrides layered over the active rule pack.
|
|
174
|
+
* Any attempt to waive a base rule-pack ban or raise a cap is rejected/ignored.
|
|
175
|
+
*/
|
|
176
|
+
export interface TenantComplianceOverrides {
|
|
177
|
+
/** Licensed ship-to state footprint (2-letter codes). Destinations outside are blocked. */
|
|
178
|
+
licensedStates?: readonly string[];
|
|
179
|
+
/** Additional stricter-only overlay rules. */
|
|
180
|
+
extraRules?: readonly ComplianceRule[];
|
|
181
|
+
/** Relaxation fields below are never honored; rejected/ignored during evaluation and merge. */
|
|
182
|
+
allowRegions?: readonly string[];
|
|
183
|
+
allowRules?: readonly string[];
|
|
184
|
+
relaxedUnitLimit?: number;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Age/identity verification requirement. `provider` is populated only when a
|
|
189
|
+
* verification provider is configured in operational config; absent fails closed.
|
|
51
190
|
*/
|
|
52
191
|
export interface VerificationRequirement {
|
|
53
|
-
/** Verification must pass before checkout can complete. */
|
|
54
192
|
required: boolean;
|
|
55
|
-
/** Minimum age enforced (e.g. 21 for nicotine). */
|
|
56
193
|
minAge: number;
|
|
57
|
-
/**
|
|
58
|
-
* Live provider id once wired (e.g. "tot"). Absent ⇒ no provider configured;
|
|
59
|
-
* `resolveVerificationDecision` then blocks (safe default). Set by
|
|
60
|
-
* `resolveTenantRuleset` from operational config, never hardcoded in the data.
|
|
61
|
-
*/
|
|
62
194
|
provider?: string;
|
|
63
195
|
}
|
|
64
196
|
|
|
65
197
|
/**
|
|
66
|
-
* Excise-tax obligation +
|
|
67
|
-
* obligation with `handling: "unavailable"` BLOCKS checkout rather than silently
|
|
68
|
-
* shipping untaxed.
|
|
198
|
+
* Excise-tax obligation + handling path. `unavailable` fails closed.
|
|
69
199
|
*/
|
|
70
200
|
export interface ExciseRequirement {
|
|
71
201
|
required: boolean;
|
|
72
|
-
/**
|
|
73
|
-
* - "managed-cart" — materialized in the managed cart via the pre-cart webhook +
|
|
74
|
-
* `tot_excise_tax` coupon (Track B).
|
|
75
|
-
* - "provider" — external excise calc/handoff (contract in `note`).
|
|
76
|
-
* - "unavailable" — no excise path wired; enforcement fails closed.
|
|
77
|
-
*/
|
|
78
202
|
handling: "managed-cart" | "provider" | "unavailable";
|
|
79
|
-
/** External excise-provider handoff contract note. */
|
|
80
203
|
note?: string;
|
|
81
204
|
}
|
|
82
205
|
|
|
83
|
-
/** PACT Act
|
|
206
|
+
/** PACT Act shipping and reporting obligations. */
|
|
84
207
|
export interface PactActRule {
|
|
85
208
|
enabled: boolean;
|
|
86
|
-
/** Adult signature (21+) on delivery — PACT baseline for ENDS. */
|
|
87
209
|
adultSignatureRequired: boolean;
|
|
88
|
-
/** Carriers that must NOT carry ENDS (PACT: USPS won't). Documents the carrier contract. */
|
|
89
210
|
prohibitedCarriers: string[];
|
|
90
|
-
/** Per-order data must be captured for the PACT Act monthly state report. */
|
|
91
211
|
reportingRequired: boolean;
|
|
92
212
|
}
|
|
93
213
|
|
|
@@ -97,11 +217,13 @@ export interface ComplianceRuleset {
|
|
|
97
217
|
verification: VerificationRequirement;
|
|
98
218
|
excise: ExciseRequirement;
|
|
99
219
|
pactAct: PactActRule;
|
|
100
|
-
/**
|
|
101
|
-
|
|
102
|
-
/**
|
|
220
|
+
/** Pure declarative versioned rule pack evaluated by `evaluateCartCompliance`. */
|
|
221
|
+
rulePack: ComplianceRulePack;
|
|
222
|
+
/** Optional merchant licensed footprint & stricter-only overlays. */
|
|
223
|
+
tenantOverrides?: TenantComplianceOverrides;
|
|
224
|
+
/** ISO date the rule data was last reviewed (provenance). */
|
|
103
225
|
updatedAt: string;
|
|
104
|
-
/** Provenance / disclaimer note
|
|
226
|
+
/** Provenance / disclaimer note. */
|
|
105
227
|
source: string;
|
|
106
228
|
}
|
|
107
229
|
|
|
@@ -135,26 +257,569 @@ export const US_REGIONS: ReadonlyArray<{ code: string; name: string }> = [
|
|
|
135
257
|
{ code: "WY", name: "Wyoming" },
|
|
136
258
|
];
|
|
137
259
|
|
|
260
|
+
const STATIC_FIELDS: ReadonlySet<string> = new Set([
|
|
261
|
+
"subject.regulated",
|
|
262
|
+
"subject.containsNicotine",
|
|
263
|
+
"subject.category",
|
|
264
|
+
"subject.categoryClassified",
|
|
265
|
+
"subject.flavorStatus",
|
|
266
|
+
"subject.flavorClassified",
|
|
267
|
+
"subject.coolingAgent",
|
|
268
|
+
"subject.productClass",
|
|
269
|
+
"catalog.registryListings",
|
|
270
|
+
"catalog.fdaAuthorization",
|
|
271
|
+
"catalog.nicotineOrigin",
|
|
272
|
+
"catalog.containsLithiumBattery",
|
|
273
|
+
"catalog.unitWeightGrams",
|
|
274
|
+
"catalog.childResistantPackaging",
|
|
275
|
+
"catalog.manufacturerLegalName",
|
|
276
|
+
"catalog.liquidVolumeMl",
|
|
277
|
+
"catalog.systemType",
|
|
278
|
+
]);
|
|
279
|
+
|
|
280
|
+
const CUSTOM_FACT_FIELD = /^facts\.[A-Za-z0-9_.-]+$/;
|
|
281
|
+
const SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/;
|
|
282
|
+
const ZIP_PREFIX_PATTERN = /^\d{1,5}$/;
|
|
283
|
+
const US_ZIP_PATTERN = /^(\d{5})(?:-\d{4})?$/;
|
|
284
|
+
const REGION_CODE_PATTERN = /^[A-Z]{2}$/;
|
|
285
|
+
const REGISTRY_JURISDICTION_SET: ReadonlySet<string> = new Set(REGISTRY_JURISDICTIONS);
|
|
286
|
+
const EFFECT_KINDS: ReadonlySet<string> = new Set([
|
|
287
|
+
"ban_shipment",
|
|
288
|
+
"ban_flavored",
|
|
289
|
+
"ban_cooling_agent",
|
|
290
|
+
"require_predicate",
|
|
291
|
+
"per_sku_limit",
|
|
292
|
+
"per_order_limit",
|
|
293
|
+
"require_adult_signature",
|
|
294
|
+
]);
|
|
295
|
+
const BLOCK_CODE_SET: ReadonlySet<string> = new Set<ComplianceBlockCode>([
|
|
296
|
+
"ruleset_unavailable",
|
|
297
|
+
"invalid_ruleset",
|
|
298
|
+
"verification_unconfigured",
|
|
299
|
+
"verification_required",
|
|
300
|
+
"verification_failed",
|
|
301
|
+
"destination_required",
|
|
302
|
+
"postal_code_required",
|
|
303
|
+
"region_prohibited",
|
|
304
|
+
"flavored_prohibited",
|
|
305
|
+
"cooling_agent_prohibited",
|
|
306
|
+
"registry_prohibited",
|
|
307
|
+
"fact_prohibited",
|
|
308
|
+
"pact_requirement_failed",
|
|
309
|
+
"sku_limit_exceeded",
|
|
310
|
+
"purchase_limit_exceeded",
|
|
311
|
+
"excise_unavailable",
|
|
312
|
+
]);
|
|
313
|
+
|
|
138
314
|
/** The display name for a region code (`CA` ⇒ `California`), or the code itself when unknown. */
|
|
139
315
|
export function regionDisplayName(code: string): string {
|
|
140
|
-
const key = code.trim().toUpperCase();
|
|
316
|
+
const key = code.trim().toUpperCase().replace(/^US-/, "");
|
|
141
317
|
return US_REGIONS.find((r) => r.code === key)?.name ?? key;
|
|
142
318
|
}
|
|
143
319
|
|
|
144
|
-
/**
|
|
145
|
-
export function
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
320
|
+
/** Normalize a US postal code into its 5-digit ZIP, or `null` when missing/malformed. */
|
|
321
|
+
export function normalizeZip5(postalCode: string | null | undefined): string | null {
|
|
322
|
+
if (typeof postalCode !== "string") return null;
|
|
323
|
+
const match = US_ZIP_PATTERN.exec(postalCode.trim());
|
|
324
|
+
return match ? match[1]! : null;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Normalize region code (`"us-ca"` ⇒ `"CA"`). */
|
|
328
|
+
export function normalizeRegionCode(region: string | null | undefined): string {
|
|
329
|
+
return (region ?? "").trim().toUpperCase().replace(/^US-/, "");
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Normalize checkout sales channel. Undefined/null defaults fail-closed to `"b2c"`;
|
|
334
|
+
* any unrecognized non-empty value returns `null` so enforcement fails closed.
|
|
335
|
+
*/
|
|
336
|
+
export function normalizeSalesChannel(raw: unknown): SalesChannel | null {
|
|
337
|
+
if (raw === undefined || raw === null) return "b2c";
|
|
338
|
+
if (typeof raw !== "string") return null;
|
|
339
|
+
const normalized = raw.trim().toLowerCase();
|
|
340
|
+
return SALES_CHANNEL_SET.has(normalized) ? (normalized as SalesChannel) : null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
344
|
+
return !!v && typeof v === "object" && !Array.isArray(v);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function isValidFieldPath(field: unknown): field is string {
|
|
348
|
+
return typeof field === "string" && (STATIC_FIELDS.has(field) || CUSTOM_FACT_FIELD.test(field));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function validatePredicate(pred: unknown, path: string, errors: string[]): void {
|
|
352
|
+
if (!isPlainObject(pred)) {
|
|
353
|
+
errors.push(`${path}: predicate must be an object`);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if ("all" in pred) {
|
|
357
|
+
if (!Array.isArray(pred.all) || pred.all.length === 0) {
|
|
358
|
+
errors.push(`${path}.all: must be a non-empty array`);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
pred.all.forEach((child, i) => validatePredicate(child, `${path}.all[${i}]`, errors));
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if ("any" in pred) {
|
|
365
|
+
if (!Array.isArray(pred.any) || pred.any.length === 0) {
|
|
366
|
+
errors.push(`${path}.any: must be a non-empty array`);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
pred.any.forEach((child, i) => validatePredicate(child, `${path}.any[${i}]`, errors));
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if ("not" in pred) {
|
|
373
|
+
validatePredicate(pred.not, `${path}.not`, errors);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (!isValidFieldPath(pred.field)) {
|
|
377
|
+
errors.push(`${path}.field: unsupported or malformed field path`);
|
|
378
|
+
}
|
|
379
|
+
if (typeof pred.op !== "string" || !DECLARATIVE_OPERATORS.has(pred.op)) {
|
|
380
|
+
errors.push(`${path}.op: unsupported operator`);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const op = pred.op as DeclarativeOperator;
|
|
384
|
+
if (op === "eq" || op === "neq") {
|
|
385
|
+
const t = typeof pred.value;
|
|
386
|
+
if (t !== "string" && t !== "number" && t !== "boolean") {
|
|
387
|
+
errors.push(`${path}.value: ${op} requires a scalar value`);
|
|
388
|
+
} else if (t === "number" && !Number.isFinite(pred.value)) {
|
|
389
|
+
errors.push(`${path}.value: numeric scalar must be finite`);
|
|
390
|
+
}
|
|
391
|
+
} else if (op === "in" || op === "not_in") {
|
|
392
|
+
if (
|
|
393
|
+
!Array.isArray(pred.value) ||
|
|
394
|
+
pred.value.length === 0 ||
|
|
395
|
+
!pred.value.every((item) => typeof item === "string" || (typeof item === "number" && Number.isFinite(item)))
|
|
396
|
+
) {
|
|
397
|
+
errors.push(`${path}.value: ${op} requires a non-empty array of strings or numbers`);
|
|
398
|
+
}
|
|
399
|
+
} else if (op === "gt" || op === "gte" || op === "lt" || op === "lte") {
|
|
400
|
+
if (typeof pred.value !== "number" || !Number.isFinite(pred.value)) {
|
|
401
|
+
errors.push(`${path}.value: ${op} requires a finite number`);
|
|
402
|
+
}
|
|
403
|
+
} else if (op === "prefix") {
|
|
404
|
+
if (typeof pred.value !== "string" || pred.value.length === 0) {
|
|
405
|
+
errors.push(`${path}.value: prefix requires a non-empty string`);
|
|
406
|
+
}
|
|
407
|
+
} else if (op === "registry_listed") {
|
|
408
|
+
if (typeof pred.value !== "string" || !REGISTRY_JURISDICTION_SET.has(pred.value)) {
|
|
409
|
+
errors.push(`${path}.value: registry_listed requires a valid registry jurisdiction`);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
152
412
|
}
|
|
153
413
|
|
|
154
|
-
|
|
414
|
+
export function validateRule(rule: unknown, index: number): string[] {
|
|
415
|
+
const errors: string[] = [];
|
|
416
|
+
const prefix = `rules[${index}]`;
|
|
417
|
+
if (!isPlainObject(rule)) {
|
|
418
|
+
return [`${prefix}: rule must be an object`];
|
|
419
|
+
}
|
|
420
|
+
if (typeof rule.id !== "string" || rule.id.trim().length === 0) {
|
|
421
|
+
errors.push(`${prefix}.id: non-empty string required`);
|
|
422
|
+
}
|
|
423
|
+
if (rule.when !== undefined) {
|
|
424
|
+
if (!isPlainObject(rule.when)) {
|
|
425
|
+
errors.push(`${prefix}.when: must be an object`);
|
|
426
|
+
} else {
|
|
427
|
+
if (rule.when.channels !== undefined) {
|
|
428
|
+
if (
|
|
429
|
+
!Array.isArray(rule.when.channels) ||
|
|
430
|
+
rule.when.channels.length === 0 ||
|
|
431
|
+
!rule.when.channels.every((c) => typeof c === "string" && SALES_CHANNEL_SET.has(c))
|
|
432
|
+
) {
|
|
433
|
+
errors.push(`${prefix}.when.channels: must be a non-empty array of "b2b" | "b2c"`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (rule.when.destination !== undefined) {
|
|
437
|
+
if (!isPlainObject(rule.when.destination)) {
|
|
438
|
+
errors.push(`${prefix}.when.destination: must be an object`);
|
|
439
|
+
} else {
|
|
440
|
+
const dest = rule.when.destination;
|
|
441
|
+
if (dest.country !== undefined && (typeof dest.country !== "string" || !/^[A-Z]{2}$/.test(dest.country.trim().toUpperCase()))) {
|
|
442
|
+
errors.push(`${prefix}.when.destination.country: must be a 2-letter country code`);
|
|
443
|
+
}
|
|
444
|
+
if (dest.regions !== undefined) {
|
|
445
|
+
if (
|
|
446
|
+
!Array.isArray(dest.regions) ||
|
|
447
|
+
dest.regions.length === 0 ||
|
|
448
|
+
!dest.regions.every((r) => typeof r === "string" && REGION_CODE_PATTERN.test(normalizeRegionCode(r)))
|
|
449
|
+
) {
|
|
450
|
+
errors.push(`${prefix}.when.destination.regions: must be non-empty array of 2-letter region codes`);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
for (const zipKey of ["zipPrefixes", "excludeZipPrefixes"] as const) {
|
|
454
|
+
const arr = dest[zipKey];
|
|
455
|
+
if (arr !== undefined) {
|
|
456
|
+
if (!Array.isArray(arr) || arr.length === 0 || !arr.every((z) => typeof z === "string" && ZIP_PREFIX_PATTERN.test(z))) {
|
|
457
|
+
errors.push(`${prefix}.when.destination.${zipKey}: must be non-empty array of 1-5 digit strings`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (rule.when.subjectMatch !== undefined) {
|
|
464
|
+
validatePredicate(rule.when.subjectMatch, `${prefix}.when.subjectMatch`, errors);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (!isPlainObject(rule.effect)) {
|
|
469
|
+
errors.push(`${prefix}.effect: must be an object`);
|
|
470
|
+
return errors;
|
|
471
|
+
}
|
|
472
|
+
const kind = rule.effect.kind;
|
|
473
|
+
if (typeof kind !== "string" || !EFFECT_KINDS.has(kind)) {
|
|
474
|
+
errors.push(`${prefix}.effect.kind: unsupported rule effect`);
|
|
475
|
+
return errors;
|
|
476
|
+
}
|
|
477
|
+
if (kind === "require_predicate") {
|
|
478
|
+
if (typeof rule.effect.code !== "string" || !BLOCK_CODE_SET.has(rule.effect.code)) {
|
|
479
|
+
errors.push(`${prefix}.effect.code: valid ComplianceBlockCode required`);
|
|
480
|
+
}
|
|
481
|
+
if (typeof rule.effect.message !== "string" || rule.effect.message.trim().length === 0) {
|
|
482
|
+
errors.push(`${prefix}.effect.message: non-empty message required`);
|
|
483
|
+
}
|
|
484
|
+
validatePredicate(rule.effect.predicate, `${prefix}.effect.predicate`, errors);
|
|
485
|
+
} else if (kind === "per_sku_limit" || kind === "per_order_limit") {
|
|
486
|
+
if (typeof rule.effect.limit !== "number" || !Number.isInteger(rule.effect.limit) || rule.effect.limit < 0) {
|
|
487
|
+
errors.push(`${prefix}.effect.limit: non-negative integer required`);
|
|
488
|
+
}
|
|
489
|
+
} else if (kind === "ban_shipment") {
|
|
490
|
+
if (rule.effect.code !== undefined && (typeof rule.effect.code !== "string" || !BLOCK_CODE_SET.has(rule.effect.code))) {
|
|
491
|
+
errors.push(`${prefix}.effect.code: valid ComplianceBlockCode required`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return errors;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Validate an entire `ComplianceRulePack` before evaluation or promotion; fails closed on any defect. */
|
|
498
|
+
export function validateRulePack(
|
|
499
|
+
pack: unknown,
|
|
500
|
+
): { ok: true } | { ok: false; errors: string[] } {
|
|
501
|
+
if (!isPlainObject(pack)) {
|
|
502
|
+
return { ok: false, errors: ["rulePack must be an object"] };
|
|
503
|
+
}
|
|
504
|
+
const errors: string[] = [];
|
|
505
|
+
if (typeof pack.packId !== "string" || pack.packId.trim().length === 0) {
|
|
506
|
+
errors.push("rulePack.packId must be a non-empty string");
|
|
507
|
+
}
|
|
508
|
+
if (typeof pack.version !== "string" || !SEMVER_PATTERN.test(pack.version)) {
|
|
509
|
+
errors.push("rulePack.version must be a valid semver string");
|
|
510
|
+
}
|
|
511
|
+
if (pack.defaultChannel !== undefined && pack.defaultChannel !== "b2c") {
|
|
512
|
+
errors.push('rulePack.defaultChannel must be omitted or "b2c" (fail-closed retail default)');
|
|
513
|
+
}
|
|
514
|
+
if (!Array.isArray(pack.rules)) {
|
|
515
|
+
errors.push("rulePack.rules must be an array");
|
|
516
|
+
return { ok: false, errors };
|
|
517
|
+
}
|
|
518
|
+
pack.rules.forEach((rule, index) => {
|
|
519
|
+
errors.push(...validateRule(rule, index));
|
|
520
|
+
});
|
|
521
|
+
return errors.length === 0 ? { ok: true } : { ok: false, errors };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export interface MergedTenantRulesResult {
|
|
525
|
+
/** Base pack rules combined with stricter-only validated overlay rules. */
|
|
526
|
+
rules: ComplianceRule[];
|
|
527
|
+
/** Overlay rules contributed by tenant config (already included in `rules`, tracked for attribution). */
|
|
528
|
+
overlayRuleIds: ReadonlySet<string>;
|
|
529
|
+
/** Normalized licensed state codes, or `null` when tenant declares no footprint allowlist. */
|
|
530
|
+
licensedStates: string[] | null;
|
|
531
|
+
/** True when a declared `licensedStates` contained non-2-letter or malformed entries. */
|
|
532
|
+
licensedStatesInvalid: boolean;
|
|
533
|
+
/** Human-readable notes describing relaxation attempts that were rejected/ignored. */
|
|
534
|
+
rejectedRelaxations: string[];
|
|
535
|
+
/** Validation errors on `extraRules` (causes evaluation to fail closed). */
|
|
536
|
+
invalidOverlayErrors: string[];
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function sameOrNarrowerDestination(
|
|
540
|
+
base: RuleDestinationMatch | undefined,
|
|
541
|
+
extra: RuleDestinationMatch | undefined,
|
|
542
|
+
): boolean {
|
|
543
|
+
if (!base) return true;
|
|
544
|
+
if (!extra) return false;
|
|
545
|
+
if (base.country && normalizeRegionCode(extra.country) !== normalizeRegionCode(base.country)) {
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
if (base.regions && base.regions.length > 0) {
|
|
549
|
+
if (!extra.regions || extra.regions.length === 0) return false;
|
|
550
|
+
const baseSet = new Set(base.regions.map(normalizeRegionCode));
|
|
551
|
+
if (!extra.regions.every((r) => baseSet.has(normalizeRegionCode(r)))) return false;
|
|
552
|
+
}
|
|
553
|
+
if (base.zipPrefixes && base.zipPrefixes.length > 0) {
|
|
554
|
+
if (!extra.zipPrefixes || extra.zipPrefixes.length === 0) return false;
|
|
555
|
+
if (!extra.zipPrefixes.every((ez) => base.zipPrefixes!.some((bz) => ez.startsWith(bz)))) return false;
|
|
556
|
+
}
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function channelsOverlap(
|
|
561
|
+
a: readonly SalesChannel[] | undefined,
|
|
562
|
+
b: readonly SalesChannel[] | undefined,
|
|
563
|
+
): boolean {
|
|
564
|
+
const left = a ?? SALES_CHANNELS;
|
|
565
|
+
const right = b ?? SALES_CHANNELS;
|
|
566
|
+
return left.some((c) => right.includes(c));
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Combine two optional override layers into one stricter-only configuration. */
|
|
570
|
+
export function combineTenantOverrides(
|
|
571
|
+
first?: TenantComplianceOverrides | null,
|
|
572
|
+
second?: TenantComplianceOverrides | null,
|
|
573
|
+
): TenantComplianceOverrides | undefined {
|
|
574
|
+
if (!first && !second) return undefined;
|
|
575
|
+
if (!first) return second ?? undefined;
|
|
576
|
+
if (!second) return first;
|
|
577
|
+
|
|
578
|
+
let licensedStates: string[] | undefined;
|
|
579
|
+
if (first.licensedStates !== undefined && second.licensedStates !== undefined) {
|
|
580
|
+
const secondSet = new Set(second.licensedStates.map(normalizeRegionCode));
|
|
581
|
+
licensedStates = first.licensedStates.map(normalizeRegionCode).filter((s) => secondSet.has(s));
|
|
582
|
+
} else {
|
|
583
|
+
const chosen = first.licensedStates ?? second.licensedStates;
|
|
584
|
+
licensedStates = chosen ? [...chosen] : undefined;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
return {
|
|
588
|
+
...(licensedStates !== undefined ? { licensedStates } : {}),
|
|
589
|
+
extraRules: [...(first.extraRules ?? []), ...(second.extraRules ?? [])],
|
|
590
|
+
allowRegions: [...(first.allowRegions ?? []), ...(second.allowRegions ?? [])],
|
|
591
|
+
allowRules: [...(first.allowRules ?? []), ...(second.allowRules ?? [])],
|
|
592
|
+
...(first.relaxedUnitLimit !== undefined || second.relaxedUnitLimit !== undefined
|
|
593
|
+
? { relaxedUnitLimit: first.relaxedUnitLimit ?? second.relaxedUnitLimit }
|
|
594
|
+
: {}),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Merge merchant `TenantComplianceOverrides` over a `ComplianceRulePack` using stricter-only
|
|
600
|
+
* semantics: any relaxation attempt (`allowRegions`, `allowRules`, `relaxedUnitLimit`, or an
|
|
601
|
+
* overlay cap above a base rule's limit) is rejected/ignored without weakening base enforcement.
|
|
602
|
+
*/
|
|
603
|
+
export function mergeTenantOverrides(
|
|
604
|
+
pack: Pick<ComplianceRulePack, "rules">,
|
|
605
|
+
overrides?: TenantComplianceOverrides | null,
|
|
606
|
+
): MergedTenantRulesResult {
|
|
607
|
+
const rejectedRelaxations: string[] = [];
|
|
608
|
+
const invalidOverlayErrors: string[] = [];
|
|
609
|
+
const overlayRuleIds = new Set<string>();
|
|
610
|
+
const admittedOverlay: ComplianceRule[] = [];
|
|
611
|
+
|
|
612
|
+
if (!overrides) {
|
|
613
|
+
return {
|
|
614
|
+
rules: [...pack.rules],
|
|
615
|
+
overlayRuleIds,
|
|
616
|
+
licensedStates: null,
|
|
617
|
+
licensedStatesInvalid: false,
|
|
618
|
+
rejectedRelaxations,
|
|
619
|
+
invalidOverlayErrors,
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if (overrides.allowRegions && overrides.allowRegions.length > 0) {
|
|
624
|
+
rejectedRelaxations.push("Rejected tenant override `allowRegions`: merchants cannot permit rule-pack prohibited regions.");
|
|
625
|
+
}
|
|
626
|
+
if (overrides.allowRules && overrides.allowRules.length > 0) {
|
|
627
|
+
rejectedRelaxations.push("Rejected tenant override `allowRules`: merchants cannot disable rule-pack rules.");
|
|
628
|
+
}
|
|
629
|
+
if (overrides.relaxedUnitLimit !== undefined) {
|
|
630
|
+
rejectedRelaxations.push("Rejected tenant override `relaxedUnitLimit`: merchants cannot raise rule-pack unit caps.");
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
let licensedStates: string[] | null = null;
|
|
634
|
+
let licensedStatesInvalid = false;
|
|
635
|
+
if (overrides.licensedStates !== undefined) {
|
|
636
|
+
if (!Array.isArray(overrides.licensedStates)) {
|
|
637
|
+
licensedStatesInvalid = true;
|
|
638
|
+
} else {
|
|
639
|
+
const normalized: string[] = [];
|
|
640
|
+
for (const raw of overrides.licensedStates) {
|
|
641
|
+
if (typeof raw !== "string") {
|
|
642
|
+
licensedStatesInvalid = true;
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
const code = normalizeRegionCode(raw);
|
|
646
|
+
if (!REGION_CODE_PATTERN.test(code)) {
|
|
647
|
+
licensedStatesInvalid = true;
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
if (!normalized.includes(code)) normalized.push(code);
|
|
651
|
+
}
|
|
652
|
+
licensedStates = licensedStatesInvalid ? [] : normalized;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
if (overrides.extraRules !== undefined) {
|
|
657
|
+
if (!Array.isArray(overrides.extraRules)) {
|
|
658
|
+
invalidOverlayErrors.push("tenantOverrides.extraRules must be an array");
|
|
659
|
+
} else {
|
|
660
|
+
overrides.extraRules.forEach((rule, index) => {
|
|
661
|
+
const errs = validateRule(rule, index);
|
|
662
|
+
if (errs.length > 0) {
|
|
663
|
+
invalidOverlayErrors.push(...errs.map((e) => `tenantOverrides.${e}`));
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
// Reject/ignore any limit rule that attempts to raise an applicable base pack limit.
|
|
667
|
+
if (rule.effect.kind === "per_order_limit" || rule.effect.kind === "per_sku_limit") {
|
|
668
|
+
const effectKind = rule.effect.kind;
|
|
669
|
+
const extraLimit = rule.effect.limit;
|
|
670
|
+
const baseStrictest = pack.rules
|
|
671
|
+
.filter(
|
|
672
|
+
(base) =>
|
|
673
|
+
base.effect.kind === effectKind &&
|
|
674
|
+
channelsOverlap(base.when?.channels, rule.when?.channels) &&
|
|
675
|
+
sameOrNarrowerDestination(base.when?.destination, rule.when?.destination),
|
|
676
|
+
)
|
|
677
|
+
.map((base) => (base.effect as { limit: number }).limit);
|
|
678
|
+
if (baseStrictest.length > 0 && extraLimit > Math.min(...baseStrictest)) {
|
|
679
|
+
rejectedRelaxations.push(
|
|
680
|
+
`Rejected tenant override rule "${rule.id}": limit ${extraLimit} exceeds base pack limit.`,
|
|
681
|
+
);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
overlayRuleIds.add(rule.id);
|
|
686
|
+
admittedOverlay.push(rule);
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
return {
|
|
692
|
+
rules: [...pack.rules, ...admittedOverlay],
|
|
693
|
+
overlayRuleIds,
|
|
694
|
+
licensedStates,
|
|
695
|
+
licensedStatesInvalid,
|
|
696
|
+
rejectedRelaxations,
|
|
697
|
+
invalidOverlayErrors,
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
export function ruleMatchesDestinationAndChannel(
|
|
702
|
+
rule: ComplianceRule,
|
|
703
|
+
destination: { country?: string; region?: string | null; zip5?: string | null },
|
|
704
|
+
channel: SalesChannel,
|
|
705
|
+
): boolean {
|
|
706
|
+
const when = rule.when;
|
|
707
|
+
if (when?.channels && !when.channels.includes(channel)) return false;
|
|
708
|
+
const dest = when?.destination;
|
|
709
|
+
if (!dest) return true;
|
|
710
|
+
if (dest.country) {
|
|
711
|
+
const c = (destination.country ?? "").trim().toUpperCase();
|
|
712
|
+
if (c !== dest.country.trim().toUpperCase()) return false;
|
|
713
|
+
}
|
|
714
|
+
if (dest.regions && dest.regions.length > 0) {
|
|
715
|
+
const r = normalizeRegionCode(destination.region);
|
|
716
|
+
if (!r || !dest.regions.some((candidate) => normalizeRegionCode(candidate) === r)) return false;
|
|
717
|
+
}
|
|
718
|
+
if (dest.zipPrefixes && dest.zipPrefixes.length > 0) {
|
|
719
|
+
if (!destination.zip5 || !dest.zipPrefixes.some((prefix) => destination.zip5!.startsWith(prefix))) {
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
if (dest.excludeZipPrefixes && dest.excludeZipPrefixes.length > 0 && destination.zip5) {
|
|
724
|
+
if (dest.excludeZipPrefixes.some((prefix) => destination.zip5!.startsWith(prefix))) {
|
|
725
|
+
return false;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* True when any active rule in the pack (or tenant overlays) matching `(country, region, channel)`
|
|
733
|
+
* declares ZIP-prefix or excluded-ZIP matching — meaning postal code cannot be omitted safely.
|
|
734
|
+
*/
|
|
735
|
+
export function stateHasZipScopedRules(
|
|
736
|
+
ruleset: Pick<ComplianceRuleset, "rulePack" | "tenantOverrides">,
|
|
737
|
+
destination: { country?: string; region: string },
|
|
738
|
+
channel: SalesChannel = "b2c",
|
|
739
|
+
extraOverrides?: TenantComplianceOverrides | null,
|
|
740
|
+
): boolean {
|
|
741
|
+
const combined = combineTenantOverrides(ruleset.tenantOverrides, extraOverrides);
|
|
742
|
+
const { rules } = mergeTenantOverrides(ruleset.rulePack, combined);
|
|
743
|
+
const country = (destination.country ?? "US").trim().toUpperCase();
|
|
744
|
+
const region = normalizeRegionCode(destination.region);
|
|
745
|
+
return rules.some((rule) => {
|
|
746
|
+
const when = rule.when;
|
|
747
|
+
if (when?.channels && !when.channels.includes(channel)) return false;
|
|
748
|
+
const d = when?.destination;
|
|
749
|
+
if (!d) return false;
|
|
750
|
+
if (d.country && d.country.trim().toUpperCase() !== country) return false;
|
|
751
|
+
if (d.regions && d.regions.length > 0 && !d.regions.some((r) => normalizeRegionCode(r) === region)) {
|
|
752
|
+
return false;
|
|
753
|
+
}
|
|
754
|
+
return Boolean((d.zipPrefixes && d.zipPrefixes.length > 0) || (d.excludeZipPrefixes && d.excludeZipPrefixes.length > 0));
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** All distinct uppercased region codes named in a rule pack, in declaration order. */
|
|
759
|
+
export function rulePackRegions(rulePack: Pick<ComplianceRulePack, "rules">): string[] {
|
|
760
|
+
const seen = new Set<string>();
|
|
761
|
+
const out: string[] = [];
|
|
762
|
+
for (const rule of rulePack.rules) {
|
|
763
|
+
for (const region of rule.when?.destination?.regions ?? []) {
|
|
764
|
+
const code = normalizeRegionCode(region);
|
|
765
|
+
if (code && !seen.has(code)) {
|
|
766
|
+
seen.add(code);
|
|
767
|
+
out.push(code);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return out;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Sorted 2-letter region codes that are unconditionally prohibited for B2C regulated sales
|
|
776
|
+
* (rules declaring `ban_shipment` with no `subjectMatch` and no `zipPrefixes`).
|
|
777
|
+
*/
|
|
778
|
+
export function unconditionalProhibitedRegions(
|
|
779
|
+
ruleset: Pick<ComplianceRuleset, "rulePack" | "tenantOverrides">,
|
|
780
|
+
): string[] {
|
|
781
|
+
const { rules } = mergeTenantOverrides(ruleset.rulePack, ruleset.tenantOverrides);
|
|
782
|
+
const out = new Set<string>();
|
|
783
|
+
for (const rule of rules) {
|
|
784
|
+
if (rule.effect.kind !== "ban_shipment") continue;
|
|
785
|
+
if (rule.when?.subjectMatch) continue;
|
|
786
|
+
const d = rule.when?.destination;
|
|
787
|
+
if (d?.zipPrefixes && d.zipPrefixes.length > 0) continue;
|
|
788
|
+
if (rule.when?.channels && !rule.when.channels.includes("b2c")) continue;
|
|
789
|
+
for (const r of d?.regions ?? []) {
|
|
790
|
+
const code = normalizeRegionCode(r);
|
|
791
|
+
if (REGION_CODE_PATTERN.test(code)) out.add(code);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return [...out].sort();
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* The effective per-order unit limit for a destination + channel, taking the strictest
|
|
799
|
+
* matching unscoped `per_order_limit` across the rule pack and stricter tenant overrides.
|
|
800
|
+
*/
|
|
155
801
|
export function effectivePerOrderLimit(
|
|
156
|
-
ruleset: Pick<ComplianceRuleset, "
|
|
157
|
-
|
|
802
|
+
ruleset: Pick<ComplianceRuleset, "rulePack" | "tenantOverrides">,
|
|
803
|
+
target: string | { country?: string; region?: string | null; postalCode?: string | null } | undefined | null,
|
|
804
|
+
opts?: { channel?: SalesChannel; tenantOverrides?: TenantComplianceOverrides },
|
|
158
805
|
): number | undefined {
|
|
159
|
-
|
|
806
|
+
if (!target) return undefined;
|
|
807
|
+
const dest = typeof target === "string"
|
|
808
|
+
? { country: "US", region: target, postalCode: undefined }
|
|
809
|
+
: { country: target.country ?? "US", region: target.region, postalCode: target.postalCode };
|
|
810
|
+
const region = normalizeRegionCode(dest.region);
|
|
811
|
+
if (!region) return undefined;
|
|
812
|
+
const channel = opts?.channel ?? "b2c";
|
|
813
|
+
const zip5 = normalizeZip5(dest.postalCode);
|
|
814
|
+
const combined = combineTenantOverrides(ruleset.tenantOverrides, opts?.tenantOverrides);
|
|
815
|
+
const { rules } = mergeTenantOverrides(ruleset.rulePack, combined);
|
|
816
|
+
|
|
817
|
+
let minLimit: number | undefined;
|
|
818
|
+
for (const rule of rules) {
|
|
819
|
+
if (rule.effect.kind !== "per_order_limit") continue;
|
|
820
|
+
if (rule.when?.subjectMatch) continue;
|
|
821
|
+
if (!ruleMatchesDestinationAndChannel(rule, { country: dest.country, region, zip5 }, channel)) continue;
|
|
822
|
+
minLimit = minLimit === undefined ? rule.effect.limit : Math.min(minLimit, rule.effect.limit);
|
|
823
|
+
}
|
|
824
|
+
return minLimit;
|
|
160
825
|
}
|