@tokenoftrust/storefront-runner 8.1.1 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "8.1.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 explicitFlavors = collectCatalogFlavorLabels(product, variant);
891
- const category = explicitCategory;
892
- const categoryClassified = Boolean(category) || merchantType.length > 0;
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 haystack = [
895
- merchantType,
896
- (category ?? "").toLowerCase(),
897
- typeof product.title === "string" ? product.title.toLowerCase() : "",
898
- ...(Array.isArray(product.tags) ? product.tags : []).map((t) => String(t ?? "").toLowerCase()),
899
- ].join(" ");
900
- const isAccessory =
901
- ((category ?? "").trim().toLowerCase() === "accessory" ||
902
- CATALOG_ACCESSORY_HINTS.some((n) => haystack.includes(n))) &&
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
  /**