@tokenoftrust/storefront-runner 8.1.0 → 8.1.2
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.
|
@@ -462,6 +462,8 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
462
462
|
? input.managedIntegrationDeclarations
|
|
463
463
|
: await readBakedManagedInstalls(request, tenant.tenant_id, readEnv);
|
|
464
464
|
|
|
465
|
+
const materializeMode = (await readEnv(MATERIALIZE_MODE_BINDING)) === "1";
|
|
466
|
+
|
|
465
467
|
// Digest-addressed static-bundle serving. Deliberately before the edge page
|
|
466
468
|
// cache/catalog/theme machinery. A selected publication bypasses this legacy
|
|
467
469
|
// whole-site bundle until B1 can compose mounted spaces into it reproducibly.
|
|
@@ -492,6 +494,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
492
494
|
hasCandidatePin: !!candidatePin,
|
|
493
495
|
hasDraftCookie: !!draftCookie,
|
|
494
496
|
hasManagedInstalls: managedIntegrationDeclarations.length > 0,
|
|
497
|
+
isMaterializeMode: materializeMode,
|
|
495
498
|
...(originalsBucket
|
|
496
499
|
? {
|
|
497
500
|
capturedOriginal: {
|
|
@@ -575,7 +578,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
575
578
|
// Either gate failing ⇒ fall through to the caller-supplied reader (control plane
|
|
576
579
|
// only), never a caller-supplied snapshot.
|
|
577
580
|
let bakedConsent: ReturnType<typeof parseConsentSnapshot> = null;
|
|
578
|
-
if (
|
|
581
|
+
if (materializeMode) {
|
|
579
582
|
const consentInputHeader = request.headers.get(CONSENT_SNAPSHOT_INPUT_HEADER);
|
|
580
583
|
const consentSig = request.headers.get(CONSENT_SNAPSHOT_SIG_HEADER);
|
|
581
584
|
const hmacSecret = await readEnv(CONSENT_SNAPSHOT_HMAC_SECRET_BINDING);
|
|
@@ -613,8 +616,11 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
613
616
|
// API in .wrangler/state, so a cached page would be served stale across edits AND
|
|
614
617
|
// restarts — silently defeating hot-reload (edits look "lost"). Dev must always
|
|
615
618
|
// re-render. import.meta.env.DEV statically drops this guard from the prod build.
|
|
619
|
+
// Materialize mode renders fresh pages with request-bound baked inputs and capture
|
|
620
|
+
// headers, so it bypasses the edge page cache completely.
|
|
616
621
|
const pageCacheEligible =
|
|
617
622
|
!import.meta.env.DEV &&
|
|
623
|
+
!materializeMode &&
|
|
618
624
|
request.method.toUpperCase() === "GET" &&
|
|
619
625
|
!isPreviewHost &&
|
|
620
626
|
!preview.presented &&
|
|
@@ -644,10 +650,13 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
644
650
|
const key = pageKey;
|
|
645
651
|
const hit = await timed(timing, "page-cache", () => getCachedPage(cache, key));
|
|
646
652
|
timing?.note("cache", hit ? "hit" : "miss");
|
|
647
|
-
// The cached artifact is nonce-free (carries the placeholder)
|
|
648
|
-
//
|
|
649
|
-
//
|
|
650
|
-
if (hit)
|
|
653
|
+
// The cached artifact is nonce-free (carries the placeholder) and stored without
|
|
654
|
+
// materialize capture headers. Stamp any capture headers requested on this probe
|
|
655
|
+
// and a fresh per-response nonce so a warm hit matches a cold render.
|
|
656
|
+
if (hit) {
|
|
657
|
+
applyMaterializeCaptureHeaders(hit, request, tenant, shopperDelivery, materializeMode);
|
|
658
|
+
return await stampResponseNonce(hit, freshNonce());
|
|
659
|
+
}
|
|
651
660
|
}
|
|
652
661
|
|
|
653
662
|
const proto = url.protocol === "http:" ? "http" : "https";
|
|
@@ -927,7 +936,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
927
936
|
pageBase: locals.basePath ?? basePath,
|
|
928
937
|
apiBase: basePath,
|
|
929
938
|
nonce: cspNonce,
|
|
930
|
-
capture: isPublicationCapture(request.headers,
|
|
939
|
+
capture: isPublicationCapture(request.headers, materializeMode ? "1" : null),
|
|
931
940
|
cdnForwarded: locals.cdnForwarded === true,
|
|
932
941
|
internalPublication: isInternalPublication,
|
|
933
942
|
// Annotations and tours both identify the document; one KV read serves both.
|
|
@@ -1066,25 +1075,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
1066
1075
|
// A preview-token (`test`) render is unpublished content shown to one viewer: no
|
|
1067
1076
|
// browser, proxy, or CDN may keep it or hand it to the next visitor of this URL.
|
|
1068
1077
|
if (customization.env === "test") response.headers.set("Cache-Control", "private, no-store");
|
|
1069
|
-
|
|
1070
|
-
// Cache-Control so the publish/materialize plane can bake it into the bundle
|
|
1071
|
-
// manifest (the same capture pattern as CSP). Gated on the materialize probe
|
|
1072
|
-
// request header, so it NEVER reaches a public client — the LIVE served header
|
|
1073
|
-
// comes from the manifest via `static-bundle`, not from this signal.
|
|
1074
|
-
if (request.headers.get(HTML_CACHE_POLICY_CAPTURE_PROBE)) {
|
|
1075
|
-
response.headers.set(
|
|
1076
|
-
HTML_CACHE_POLICY_CAPTURE_HEADER,
|
|
1077
|
-
formatHtmlCacheControl(locals.tenant?.serving?.htmlCachePolicy),
|
|
1078
|
-
);
|
|
1079
|
-
// The tenant's declared origins — the same `domains` the Worker's own image scans use. The
|
|
1080
|
-
// materializer ships images a page references absolutely on them (og:image is always
|
|
1081
|
-
// absolute), and the publish scan classifies such references by path instead of as
|
|
1082
|
-
// third-party hotlinks.
|
|
1083
|
-
response.headers.set(TENANT_ORIGINS_CAPTURE_HEADER, declaredTenantOrigins(tenant).join(","));
|
|
1084
|
-
if (await readEnv(MATERIALIZE_MODE_BINDING) === "1") {
|
|
1085
|
-
response.headers.set("x-tot-shopper-delivery", JSON.stringify(shopperDelivery));
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1078
|
+
applyMaterializeCaptureHeaders(response, request, locals.tenant ?? tenant, shopperDelivery, materializeMode);
|
|
1088
1079
|
if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
|
|
1089
1080
|
// Stamp a fresh per-response nonce into this cold response's body + CSP header
|
|
1090
1081
|
// (the warm-hit path above stamps its own). Both paths therefore serve a fresh,
|
|
@@ -1093,6 +1084,34 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
|
|
|
1093
1084
|
return await timed(timing, "nonce", () => stampResponseNonce(stamped, freshNonce()));
|
|
1094
1085
|
}
|
|
1095
1086
|
|
|
1087
|
+
/**
|
|
1088
|
+
* Materialize-only capture headers (ADR 0013): expose the tenant's route-document
|
|
1089
|
+
* Cache-Control, declared origins, and (in materialize mode) shopper delivery policy
|
|
1090
|
+
* when requested by the materialize capture probe. Applied after page-cache writes
|
|
1091
|
+
* and on warm hits so cached artifacts never retain capture headers.
|
|
1092
|
+
*/
|
|
1093
|
+
function applyMaterializeCaptureHeaders(
|
|
1094
|
+
response: Response,
|
|
1095
|
+
request: Request,
|
|
1096
|
+
tenant: TenantConfig,
|
|
1097
|
+
shopperDelivery: ReturnType<typeof shopperDeliveryPolicy>,
|
|
1098
|
+
materializeMode: boolean,
|
|
1099
|
+
): void {
|
|
1100
|
+
if (!request.headers.get(HTML_CACHE_POLICY_CAPTURE_PROBE)) return;
|
|
1101
|
+
response.headers.set(
|
|
1102
|
+
HTML_CACHE_POLICY_CAPTURE_HEADER,
|
|
1103
|
+
formatHtmlCacheControl(tenant.serving?.htmlCachePolicy),
|
|
1104
|
+
);
|
|
1105
|
+
// The tenant's declared origins — the same `domains` the Worker's own image scans use. The
|
|
1106
|
+
// materializer ships images a page references absolutely on them (og:image is always
|
|
1107
|
+
// absolute), and the publish scan classifies such references by path instead of as
|
|
1108
|
+
// third-party hotlinks.
|
|
1109
|
+
response.headers.set(TENANT_ORIGINS_CAPTURE_HEADER, declaredTenantOrigins(tenant).join(","));
|
|
1110
|
+
if (materializeMode) {
|
|
1111
|
+
response.headers.set("x-tot-shopper-delivery", JSON.stringify(shopperDelivery));
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1096
1115
|
/**
|
|
1097
1116
|
* Inline a run of distinct tenant theme stylesheets into a preview document.
|
|
1098
1117
|
* Bytes follow the `/tenants/<id>/` route: publication root, then the preview
|
|
@@ -32,6 +32,8 @@ export interface StaticBundleAttemptInput {
|
|
|
32
32
|
hasDraftCookie: boolean;
|
|
33
33
|
/** Managed installs inject document markup, so a bundled DOCUMENT would be stale. */
|
|
34
34
|
hasManagedInstalls: boolean;
|
|
35
|
+
/** Materialize mode renders fresh source documents, never a prior static bundle. */
|
|
36
|
+
isMaterializeMode?: boolean;
|
|
35
37
|
/**
|
|
36
38
|
* When set, a `/_a/<sha>` miss falls through to revision-bound captured
|
|
37
39
|
* originals (hosted preview image capture) before returning 404.
|
|
@@ -151,6 +153,7 @@ export async function tryServeStaticBundle(
|
|
|
151
153
|
!input.hasCandidatePin &&
|
|
152
154
|
!input.hasDraftCookie &&
|
|
153
155
|
!input.hasManagedInstalls &&
|
|
156
|
+
!input.isMaterializeMode &&
|
|
154
157
|
!/^\/(?:api|account)(?:\/|$)/i.test(url.pathname);
|
|
155
158
|
if (!eligible) return null;
|
|
156
159
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "8.1.
|
|
3
|
+
"version": "8.1.2",
|
|
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",
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Eligibility-config validation for `tot validate`: the tenant's `compliance` restriction block
|
|
3
|
+
* against the platform's rules-engine contract (ADR 0047).
|
|
4
|
+
*
|
|
5
|
+
* - `compliance.ruleProfile` names a shipped rule pack.
|
|
6
|
+
* - `compliance.stateEligibility` footprints are lists of 2-letter state codes, nothing else.
|
|
7
|
+
* - Tenant overrides are stricter-only: a key that would allow a rule-pack-prohibited destination,
|
|
8
|
+
* disable a rule, or raise a unit cap is refused, because the engine ignores it and the merchant
|
|
9
|
+
* would believe it took effect.
|
|
10
|
+
*
|
|
11
|
+
* Pure and dependency-free. Findings are plain `{ level, rule, file, message, fix }` objects; every
|
|
12
|
+
* one is an error, so `tot validate` exits non-zero.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Rule packs the platform ships (apps/storefront/src/config/compliance/rulesets.ts). */
|
|
16
|
+
export const KNOWN_RULE_PROFILES = Object.freeze(["vape-nicotine-us", "vape-nicotine-us-ovs"]);
|
|
17
|
+
|
|
18
|
+
/** Keys the engine never honors: each one relaxes the rule pack. */
|
|
19
|
+
export const PERMISSIVE_OVERRIDE_KEYS = Object.freeze(["allowRegions", "allowRules", "relaxedUnitLimit"]);
|
|
20
|
+
|
|
21
|
+
const STATE_ELIGIBILITY_KEYS = new Set(["restrictedStates", "eligibleStates", "directoryStates", "note"]);
|
|
22
|
+
const STATE_LIST_KEYS = ["restrictedStates", "eligibleStates", "directoryStates"];
|
|
23
|
+
const STATE_CODE = /^[A-Z]{2}$/;
|
|
24
|
+
|
|
25
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {Record<string, any>} config the parsed `.tot/config.json`
|
|
29
|
+
* @param {string} [file]
|
|
30
|
+
* @returns {Array<{level: "error", rule: string, file: string, message: string, fix?: string}>}
|
|
31
|
+
*/
|
|
32
|
+
export function eligibilityConfigFindings(config, file = ".tot/config.json") {
|
|
33
|
+
const compliance = config?.compliance;
|
|
34
|
+
if (compliance === undefined || !isObject(compliance)) return [];
|
|
35
|
+
const out = [];
|
|
36
|
+
const err = (rule, at, message, fix) => out.push({ level: "error", rule, file: `${file} ${at}`, message, fix });
|
|
37
|
+
|
|
38
|
+
if (compliance.ruleProfile !== undefined && !KNOWN_RULE_PROFILES.includes(compliance.ruleProfile)) {
|
|
39
|
+
err(
|
|
40
|
+
"compliance-rule-profile-unknown",
|
|
41
|
+
"compliance.ruleProfile",
|
|
42
|
+
`\`compliance.ruleProfile\` is ${JSON.stringify(compliance.ruleProfile)}, which is not a shipped rule pack — no checkout rules resolve and checkout blocks.`,
|
|
43
|
+
`Use one of: ${KNOWN_RULE_PROFILES.map((p) => `"${p}"`).join(", ")}.`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
for (const key of PERMISSIVE_OVERRIDE_KEYS) {
|
|
48
|
+
if (key in compliance) refusePermissive(err, key, "compliance");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const elig = compliance.stateEligibility;
|
|
52
|
+
if (elig === undefined || typeof elig === "boolean") return out;
|
|
53
|
+
if (!isObject(elig)) {
|
|
54
|
+
err("compliance-state-eligibility-shape", "compliance.stateEligibility", "`compliance.stateEligibility` must be an object.",
|
|
55
|
+
"Use { restrictedStates?: [...], eligibleStates?: [...], directoryStates?: [...], note?: string }.");
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
for (const key of Object.keys(elig)) {
|
|
59
|
+
if (PERMISSIVE_OVERRIDE_KEYS.includes(key)) refusePermissive(err, key, "compliance.stateEligibility");
|
|
60
|
+
else if (!STATE_ELIGIBILITY_KEYS.has(key)) {
|
|
61
|
+
err("compliance-state-eligibility-unknown-key", `compliance.stateEligibility.${key}`,
|
|
62
|
+
`\`compliance.stateEligibility.${key}\` is not a recognised key, so it is ignored.`,
|
|
63
|
+
`Use only ${[...STATE_ELIGIBILITY_KEYS].map((k) => `\`${k}\``).join(", ")}.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
for (const key of STATE_LIST_KEYS) {
|
|
67
|
+
const list = elig[key];
|
|
68
|
+
if (list === undefined) continue;
|
|
69
|
+
const at = `compliance.stateEligibility.${key}`;
|
|
70
|
+
if (!Array.isArray(list)) {
|
|
71
|
+
err("compliance-state-code", at, `\`${at}\` must be an array of 2-letter state codes.`, 'e.g. ["UT", "CA"].');
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
for (const [i, code] of list.entries()) {
|
|
75
|
+
if (typeof code !== "string" || !STATE_CODE.test(code)) {
|
|
76
|
+
err("compliance-state-code", `${at}[${i}]`,
|
|
77
|
+
`${JSON.stringify(code)} is not a 2-letter uppercase state code; the engine ignores it.`,
|
|
78
|
+
'Use the USPS code, e.g. "UT".');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (key === "eligibleStates" && list.length === 0) {
|
|
82
|
+
err("compliance-state-footprint-empty", at,
|
|
83
|
+
"`eligibleStates` is empty, which fails closed: no destination is licensed.",
|
|
84
|
+
"List the licensed states, or remove `eligibleStates`.");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function refusePermissive(err, key, parent) {
|
|
91
|
+
err(
|
|
92
|
+
"compliance-permissive-override",
|
|
93
|
+
`${parent}.${key}`,
|
|
94
|
+
`\`${parent}.${key}\` would loosen the rule pack (allow a prohibited destination, disable a rule, or raise a unit cap). Tenant overrides are stricter-only and the engine ignores it.`,
|
|
95
|
+
`Remove \`${key}\`. To narrow the footprint use \`restrictedStates\` or \`eligibleStates\`.`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const FACT_STATES = new Set(["known", "unknown", "invalid", "conflict", "not_applicable"]);
|
|
100
|
+
const BOOLEAN_FACTS = new Set(["has_nicotine", "cooling_agent", "contains_lithium_battery", "child_resistant_packaging"]);
|
|
101
|
+
const NUMBER_FACTS = new Set(["unit_weight_grams", "liquid_volume_ml"]);
|
|
102
|
+
const STRING_FACTS = new Set([
|
|
103
|
+
"compliance_category", "flavor_classification", "fda_authorization", "nicotine_origin", "manufacturer_legal_name", "system_type",
|
|
104
|
+
]);
|
|
105
|
+
const STRING_LIST_FACTS = new Set(["flavor_labels", "registry_listings"]);
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Regulatory fact declarations on catalog products (`variants[].catalog_link.facts`, storefront-catalog
|
|
109
|
+
* v2.1.0): a known fact carries a value of its key's type, any other state carries none, and a key is
|
|
110
|
+
* declared once per variant. Errors, because checkout reads these as the primary eligibility truth.
|
|
111
|
+
* @param {Array<{ file: string, record: any }>} products
|
|
112
|
+
*/
|
|
113
|
+
export function catalogFactFindings(products) {
|
|
114
|
+
const out = [];
|
|
115
|
+
for (const { file, record } of products) {
|
|
116
|
+
const variants = Array.isArray(record?.variants) ? record.variants : [];
|
|
117
|
+
variants.forEach((variant, vi) => {
|
|
118
|
+
const facts = variant?.catalog_link?.facts;
|
|
119
|
+
if (facts === undefined) return;
|
|
120
|
+
const at = `variants[${vi}].catalog_link.facts`;
|
|
121
|
+
const err = (rule, i, message, fix) => out.push({ level: "error", rule, file: `${file} ${at}[${i}]`, message, fix });
|
|
122
|
+
if (!Array.isArray(facts)) {
|
|
123
|
+
out.push({ level: "error", rule: "catalog-fact-shape", file: `${file} ${at}`, message: "`catalog_link.facts` must be an array.", fix: "Re-accept the catalog item to rewrite its facts." });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const seen = new Set();
|
|
127
|
+
facts.forEach((fact, i) => {
|
|
128
|
+
if (!isObject(fact) || typeof fact.key !== "string" || !fact.key) {
|
|
129
|
+
err("catalog-fact-shape", i, "a fact must be an object with a string `key`.");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (seen.has(fact.key)) err("catalog-fact-duplicate", i, `fact \`${fact.key}\` is declared more than once; checkout cannot tell which is true.`, "Keep one entry per key.");
|
|
133
|
+
seen.add(fact.key);
|
|
134
|
+
if (!FACT_STATES.has(fact.state)) {
|
|
135
|
+
err("catalog-fact-state", i, `fact \`${fact.key}\` has state ${JSON.stringify(fact.state)}; it must be one of ${[...FACT_STATES].join(", ")}.`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (fact.state !== "known") {
|
|
139
|
+
if (fact.value !== undefined) err("catalog-fact-value", i, `fact \`${fact.key}\` is ${fact.state} but carries a value; a value is never read from a fact that is not known.`, "Remove `value` or mark the fact known.");
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const v = fact.value;
|
|
143
|
+
const ok = BOOLEAN_FACTS.has(fact.key) ? typeof v === "boolean"
|
|
144
|
+
: NUMBER_FACTS.has(fact.key) ? typeof v === "number" && Number.isFinite(v)
|
|
145
|
+
: STRING_FACTS.has(fact.key) ? typeof v === "string" && v.trim().length > 0
|
|
146
|
+
: STRING_LIST_FACTS.has(fact.key) ? Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string")
|
|
147
|
+
: v !== undefined;
|
|
148
|
+
if (!ok) {
|
|
149
|
+
err("catalog-fact-value", i, `known fact \`${fact.key}\` has ${v === undefined ? "no value" : `an unusable value ${JSON.stringify(v)}`}; checkout reads it as invalid.`,
|
|
150
|
+
"Give it a value of the fact's type, or mark the fact unknown.");
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
@@ -51,6 +51,9 @@ import { pageSlugFindings } from "../../agency-kit/tools/lib/page-slugs.mjs";
|
|
|
51
51
|
import { ANALYTICS_DECLARATION_FILE, analyticsDeclarationFindings } from "../../agency-kit/tools/lib/analytics-declaration.mjs";
|
|
52
52
|
import { validateVisualParityClosure } from "../../packages/cli/src/visual-parity.mjs";
|
|
53
53
|
import { contrastRatio, declaredObligations, isRegulatedCompliance, validateDeclaredConfig } from "../../packages/cli/src/declared-config.mjs";
|
|
54
|
+
import { catalogFactFindings, eligibilityConfigFindings } from "../../packages/cli/src/eligibility-config.mjs";
|
|
55
|
+
|
|
56
|
+
export { catalogFactFindings, eligibilityConfigFindings };
|
|
54
57
|
|
|
55
58
|
/** Catalogued embed slugs a tenant may opt into (mirror of EMBED_PROVIDERS). */
|
|
56
59
|
const KNOWN_EMBED_SLUGS = new Set(KNOWN_EMBEDS.map((p) => p.slug));
|
|
@@ -124,6 +127,7 @@ export function validateConfigShape(config, file = ".tot/config.json") {
|
|
|
124
127
|
}
|
|
125
128
|
// The same refusal `tot validate` applies: a key no surface reads never passes.
|
|
126
129
|
out.push(...validateDeclaredConfig(config, file));
|
|
130
|
+
out.push(...eligibilityConfigFindings(config, file));
|
|
127
131
|
if (!Array.isArray(config.mappings)) {
|
|
128
132
|
out.push(mk(ERROR, "config-mappings", file, "`mappings` must be an array", "seed shape: [{workspace,repo,kind}]"));
|
|
129
133
|
return out; // nothing more to check without the array
|
|
@@ -832,7 +836,6 @@ export const LOUD_ADVISORY_RULES = [
|
|
|
832
836
|
],
|
|
833
837
|
];
|
|
834
838
|
|
|
835
|
-
const GENERIC_PRODUCT_TYPES = new Set(["physical", "digital", "gift_certificate"]);
|
|
836
839
|
const CATALOG_FLAVOR_FIELDS = new Set(["flavor", "flavour", "flavors", "flavours"]);
|
|
837
840
|
const CATALOG_CATEGORY_FIELDS = new Set(["compliance category", "product category", "product_category"]);
|
|
838
841
|
const CATALOG_NICOTINE_FORMAT_LABELS = new Set([
|
|
@@ -840,11 +843,6 @@ const CATALOG_NICOTINE_FORMAT_LABELS = new Set([
|
|
|
840
843
|
"freebase", "free base", "freebase nicotine", "free base nicotine", "synthetic", "synthetic nicotine",
|
|
841
844
|
"tfn", "tobacco free nicotine", "tobacco-free nicotine",
|
|
842
845
|
]);
|
|
843
|
-
const CATALOG_NICOTINE_HINTS = [
|
|
844
|
-
"nicotine", "vape", "vapor", "vaping", "e-liquid", "eliquid", "e-juice", "ejuice",
|
|
845
|
-
"e liquid", "salt nic", "nic salt", "pod", "disposable", "ends", "cig",
|
|
846
|
-
];
|
|
847
|
-
const CATALOG_ACCESSORY_HINTS = ["battery", "coil", "charger", "case", "lanyard"];
|
|
848
846
|
|
|
849
847
|
function readCatalogMetafield(product, namespace, keys) {
|
|
850
848
|
const mfs = Array.isArray(product?.metafields) ? product.metafields : [];
|
|
@@ -877,39 +875,39 @@ function collectCatalogFlavorLabels(product, variant) {
|
|
|
877
875
|
return [...labels];
|
|
878
876
|
}
|
|
879
877
|
|
|
878
|
+
const catalogFactOf = (variant, key) =>
|
|
879
|
+
(Array.isArray(variant?.catalog_link?.facts) ? variant.catalog_link.facts : []).find((f) => f?.key === key);
|
|
880
|
+
|
|
881
|
+
/** A catalog fact settles a field unless it is unknown; conflicting/invalid facts settle it restrictively. */
|
|
882
|
+
const factDecides = (fact) => fact !== undefined && fact.state !== "unknown";
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* The classification a product still lacks. The accepted catalog facts
|
|
886
|
+
* (`variants[].catalog_link.facts`) are the primary truth; merchant fields are the secondary
|
|
887
|
+
* declaration. Nothing is inferred from a title, tag or product type: a product whose category is
|
|
888
|
+
* not recorded is unclassified, and a nicotine-bearing one needs a flavour reading.
|
|
889
|
+
*/
|
|
880
890
|
function productClassificationGaps(product) {
|
|
881
891
|
if (!product || typeof product !== "object") return [];
|
|
882
892
|
const explicitCategory =
|
|
883
893
|
readCatalogMetafield(product, "compliance", new Set(["product_category"])) ??
|
|
884
894
|
readCatalogMetafield(product, "bigcommerce_custom", CATALOG_CATEGORY_FIELDS);
|
|
885
|
-
const productType = typeof product.product_type === "string" ? product.product_type.trim().toLowerCase() : "";
|
|
886
|
-
const merchantType = GENERIC_PRODUCT_TYPES.has(productType) ? "" : productType;
|
|
887
895
|
const variants = Array.isArray(product.variants) && product.variants.length > 0 ? product.variants : [null];
|
|
888
896
|
const gaps = new Set();
|
|
889
897
|
for (const variant of variants) {
|
|
890
|
-
const
|
|
891
|
-
const category = explicitCategory;
|
|
892
|
-
const categoryClassified =
|
|
898
|
+
const categoryFact = catalogFactOf(variant, "compliance_category");
|
|
899
|
+
const category = categoryFact?.state === "known" && typeof categoryFact.value === "string" ? categoryFact.value : explicitCategory;
|
|
900
|
+
const categoryClassified = factDecides(categoryFact) || Boolean(category);
|
|
893
901
|
if (!categoryClassified) gaps.add("category");
|
|
894
|
-
const
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
(
|
|
902
|
-
|
|
903
|
-
!["e-liquid", "eliquid", "juice", "salt"].some((n) => haystack.includes(n));
|
|
904
|
-
const nicStrength = typeof variant?.option_values?.["Nicotine strength"] === "string"
|
|
905
|
-
? variant.option_values["Nicotine strength"].toLowerCase()
|
|
906
|
-
: undefined;
|
|
907
|
-
const nicOptionSaysZero = nicStrength !== undefined && /^0\s*mg\b/.test(nicStrength);
|
|
908
|
-
const nicOptionSaysNonZero = nicStrength !== undefined && /\d/.test(nicStrength) && !nicOptionSaysZero;
|
|
909
|
-
const containsNicotine =
|
|
910
|
-
!isAccessory &&
|
|
911
|
-
(nicOptionSaysNonZero || (!nicOptionSaysZero && CATALOG_NICOTINE_HINTS.some((n) => haystack.includes(n))));
|
|
912
|
-
const flavorClassified = explicitFlavors.length > 0;
|
|
902
|
+
const nicotineFact = catalogFactOf(variant, "has_nicotine");
|
|
903
|
+
const hardware = ["accessory", "none"].includes((category ?? "").trim().toLowerCase());
|
|
904
|
+
const containsNicotine = nicotineFact?.state === "known" && nicotineFact.value === false ? false : !hardware;
|
|
905
|
+
const flavorFact = catalogFactOf(variant, "flavor_classification");
|
|
906
|
+
const labelsFact = catalogFactOf(variant, "flavor_labels");
|
|
907
|
+
const flavorClassified =
|
|
908
|
+
factDecides(flavorFact) ||
|
|
909
|
+
(labelsFact?.state === "known" && Array.isArray(labelsFact.value) && labelsFact.value.length > 0) ||
|
|
910
|
+
collectCatalogFlavorLabels(product, variant).length > 0;
|
|
913
911
|
if ((containsNicotine || !categoryClassified) && !flavorClassified) gaps.add("flavor");
|
|
914
912
|
}
|
|
915
913
|
return ["category", "flavor"].filter((g) => gaps.has(g));
|
|
@@ -950,7 +948,7 @@ function validateCatalogCompliance(contentDir, rel, config = null) {
|
|
|
950
948
|
const { value, error } = readJsonSafe(path);
|
|
951
949
|
if (!error) products.push({ file: rel(path), record: value });
|
|
952
950
|
}
|
|
953
|
-
return catalogComplianceFindings(products, config);
|
|
951
|
+
return [...catalogFactFindings(products), ...catalogComplianceFindings(products, config)];
|
|
954
952
|
}
|
|
955
953
|
|
|
956
954
|
/**
|