@simpleapps-com/augur-utils 2026.11.3 → 2026.11.5
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/EXPORTS.md +15 -4
- package/README.md +31 -2
- package/dist/address-id.d.ts +41 -0
- package/dist/address-id.d.ts.map +1 -0
- package/dist/analytics.d.ts +8 -3
- package/dist/analytics.d.ts.map +1 -1
- package/dist/build-checkout-payload.d.ts +9 -3
- package/dist/build-checkout-payload.d.ts.map +1 -1
- package/dist/cart-line-rules.d.ts +43 -0
- package/dist/cart-line-rules.d.ts.map +1 -0
- package/dist/date-helpers.d.ts.map +1 -1
- package/dist/image-rules.d.ts +72 -10
- package/dist/image-rules.d.ts.map +1 -1
- package/dist/image.d.ts +22 -7
- package/dist/image.d.ts.map +1 -1
- package/dist/index.cjs +228 -54
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +222 -48
- package/dist/index.js.map +1 -1
- package/dist/rules.d.ts +14 -0
- package/dist/rules.d.ts.map +1 -1
- package/dist/transform-ship-to-address.d.ts.map +1 -1
- package/llms.txt +16 -3
- package/package.json +3 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-utils/dist/index.cjs","../src/price-breaks.ts","../../foundation/src/duration.ts","../src/rules.ts","../src/runtime.ts","../src/cache-config.ts","../src/duration.ts","../src/format-price.ts","../src/address-comparison.ts","../src/get-payment-status.ts","../src/transform-ship-to-address.ts","../src/build-checkout-payload.ts","../src/money.ts","../src/price-outcome.ts","../src/derive-price.ts","../src/resolve-stock.ts","../src/schema-availability.ts","../../utils/src/strings.ts","../../utils/src/lists.ts","../../utils/src/replace.ts","../../utils/src/json.ts","../../foundation/src/decimal.ts","../../utils/src/json-ld-items.ts","../../utils/src/json-ld.ts","../src/json-ld-rules.ts","../src/json-ld.ts","../src/result.ts","../src/image-rules.ts","../src/image.ts","../src/validation-patterns.ts","../src/address-schemas.ts","../src/us-states.ts","../src/date-helpers.ts","../src/transforms.ts","../src/analytics.ts"],"names":["days","seconds","minutes","hours","millis","toMillis","addMillis","minusMillis","floorSeconds","secondsOf","wholeSeconds","millisOf","breadcrumbLd","transform"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACWO,SAAS,cAAA,CACd,gBAAA,EACuC;AACvC,EAAA,OAAO,iBAAA,IAAqB,KAAA,GAAQ,KAAA,CAAM,OAAA,CAAQ,gBAAA,CAAiB,MAAM,CAAA;AAC3E;ADXA;AACA;AEmBO,SAAS,OAAA,CAAQ,CAAA,EAAoB;AAK1C,EAAA,OAAO,CAAA;AACT;AAOO,SAAS,OAAA,CAAQ,CAAA,EAAoB;AAK1C,EAAA,OAAQ,EAAA,EAAI,EAAA;AACd;AAOO,SAAS,KAAA,CAAM,CAAA,EAAoB;AAKxC,EAAA,OAAQ,EAAA,EAAI,IAAA;AACd;AAOO,SAAS,IAAA,CAAK,CAAA,EAAoB;AAKvC,EAAA,OAAQ,EAAA,EAAI,KAAA;AACd;AAOO,SAAS,MAAA,CAAO,CAAA,EAAmB;AAKxC,EAAA,OAAO,CAAA;AACT;AAOO,SAAS,QAAA,CAAS,CAAA,EAAoB;AAI3C,EAAA,OAAQ,EAAA,EAAI,GAAA;AACd;AAOO,SAAS,YAAA,CAAa,CAAA,EAAoB;AAK/C,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,EAAA,EAAI,GAAI,CAAA;AAC5B;AAQO,SAAS,SAAA,CAAU,CAAA,EAAW,CAAA,EAAmB;AAItD,EAAA,OAAQ,EAAA,EAAI,CAAA;AACd;AASO,SAAS,WAAA,CAAY,CAAA,EAAW,CAAA,EAAmB;AAIxD,EAAA,OAAO,EAAA,GAAK,EAAA,EAAM,EAAA,EAAI,EAAA,EAAgB,MAAA,CAAO,CAAC,CAAA;AAChD;AAQO,SAAS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A;AACO,UAAA;AACP,UAAA;AACA,UAAA;AACA,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AACD,EAAA;AACH;AAYgB;AACd,EAAA;AACA,EAAA;AACA,EAAA;AACW,EAAA;AACiB;AACjB,EAAA;AAEC,EAAA;AACA,IAAA;AACH,IAAA;AACA,IAAA;AACL,MAAA;AACW,QAAA;AACT,QAAA;AACA,QAAA;AACO,QAAA;AACP,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACD,EAAA;AACH;AAiCgB;AACd,EAAA;AACA,EAAA;AACA,EAAA;AACW,EAAA;AAC4B;AAC3B,EAAA;AACkB,EAAA;AACtB,IAAA;AACA,IAAA;AACE,IAAA;AACD,IAAA;AACI,MAAA;AACE,MAAA;AACX,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACU,MAAA;AACZ,IAAA;AACD,EAAA;AAEM,EAAA;AACE,IAAA;AACP,IAAA;AAAA;AAEO,IAAA;AACP,IAAA;AACF,EAAA;AACF;AAKgB;AACH,EAAA;AAEJ,EAAA;AACA,EAAA;AACO,IAAA;AACD,IAAA;AACC,MAAA;AACH,MAAA;AACA,MAAA;AACT,IAAA;AACD,EAAA;AACH;AlC09BiB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-utils/dist/index.cjs","sourcesContent":[null,"import type { TLibraryPriceData, TPriceData } from \"./types/pricing\";\n\n/**\n * Type guard: true when `libraryPriceData` is the price-page shape with quantity `breaks`.\n *\n * `\"breaks\" in libraryPriceData` does not narrow, because both SDK shapes allow\n * arbitrary extra keys.\n *\n * @example\n * ```ts\n * if (hasPriceBreaks(priceData.libraryPriceData)) {\n * priceData.libraryPriceData.breaks.map((tier) => tier.startQuantity);\n * }\n * ```\n */\nexport function hasPriceBreaks(\n libraryPriceData: TPriceData[\"libraryPriceData\"],\n): libraryPriceData is TLibraryPriceData {\n return libraryPriceData !== null && Array.isArray(libraryPriceData.breaks);\n}\n","//@ backend dafny\n\n/* Seconds and milliseconds as two types (2026-11-08). Verified with LemmaScript → Dafny\n (`pnpm proofs`; model: models/Durations.dfy, where they are two datatypes; link:\n models/links/foundation-duration.dfy).\n\n Both are branded: a plain `number` is neither, and a `Seconds` is not a `Millis`, so a TTL in\n seconds can't be passed where milliseconds are meant (augur-core's `staleTime` vs\n `redisTtl`), and a JWT `exp` can't be compared with `Date.now()` unconverted. Write a\n duration in the unit people think in (`minutes(15)`) and convert with `toMillis`; read a\n clock or a millisecond count back with `floorSeconds`. Values enter through the guards\n `secondsOf` / `millisOf` (an env value, a JSON `expires_in`); the clock is `millis(Date.now())`\n (the platform's time value is a whole, non-negative number of milliseconds).\n lsc writes both aliases as `nat` (no refinement, models/LSC-GAPS.md). */\n\n/** A whole number of seconds, made only by the builders and guards below. */\n//@ type nat\nexport type Seconds = number & { readonly __seconds: true };\n\n/** A whole number of milliseconds, made only by the builders and guards below. */\n//@ type nat\nexport type Millis = number & { readonly __millis: true };\n\n/**\n * `n` seconds.\n *\n * @ensures exactly the model's Seconds(n)\n */\nexport function seconds(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n\n return n as Seconds;\n}\n\n/**\n * `n` minutes, in seconds.\n *\n * @ensures exactly the model's Minutes\n */\nexport function minutes(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 60\n return (n * 60) as Seconds;\n}\n\n/**\n * `n` hours, in seconds.\n *\n * @ensures exactly the model's Hours\n */\nexport function hours(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 3600\n return (n * 3600) as Seconds;\n}\n\n/**\n * `n` days, in seconds.\n *\n * @ensures exactly the model's Days\n */\nexport function days(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 86400\n return (n * 86400) as Seconds;\n}\n\n/**\n * `n` milliseconds: for a duration under a second (a retry backoff, a debounce).\n *\n * @ensures exactly the model's Millis(n)\n */\nexport function millis(n: number): Millis {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n\n return n as Millis;\n}\n\n/**\n * Seconds as milliseconds, exactly.\n *\n * @ensures exactly the model's ToMillis\n */\nexport function toMillis(d: Seconds): Millis {\n //@ verify\n //@ requires d >= 0\n //@ ensures \\result === d * 1000\n return (d * 1000) as Millis;\n}\n\n/**\n * Milliseconds as whole seconds, rounded down (a JWT `exp` or `iat` from a clock).\n *\n * @ensures exactly the model's FloorSeconds\n */\nexport function floorSeconds(m: Millis): Seconds {\n //@ verify\n //@ type m nat\n //@ requires m >= 0\n //@ ensures \\result === Math.floor(m / 1000)\n return Math.floor(m / 1000) as Seconds;\n}\n\n/**\n * A clock reading plus a duration, both `Millis`: when something expires (`addMillis(now,\n * toMillis(minutes(15)))`).\n *\n * @ensures exactly the model's AddMillis\n */\nexport function addMillis(a: Millis, b: Millis): Millis {\n //@ verify\n //@ requires a >= 0 && b >= 0\n //@ ensures \\result === a + b\n return (a + b) as Millis;\n}\n\n/**\n * A reading less a duration, never below 0 (a token used until a minute before it expires). An\n * expiry clamped to 0 is no more live than the negative one it stands for (the model's\n * MinusMillisKeepsLiveness).\n *\n * @ensures exactly the model's MinusMillis\n */\nexport function minusMillis(a: Millis, b: Millis): Millis {\n //@ verify\n //@ requires a >= 0 && b >= 0\n //@ ensures \\result === (a >= b ? a - b : 0)\n return a >= b ? ((a - b) as Millis) : millis(0);\n}\n\n/**\n * `n` as `Seconds`, or null when it is not a safe integer at least 0: a fraction, NaN, a\n * negative, an infinity, or past `Number.MAX_SAFE_INTEGER`. Where a number of seconds enters.\n *\n * @ensures exactly the model's AcceptedAsDuration, and the value is kept\n */\nexport function secondsOf(n: number): Seconds | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 0 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 0 && n <= 9007199254740991 ? (n as Seconds) : null;\n}\n\n/**\n * An outside count of seconds (a token's `expires_in`, a JWT's `exp`) as `Seconds`: rounded\n * down, and 0 when it is then no safe integer at least 0 (a negative, NaN, an infinity), so a\n * bad lifetime is no lifetime and a bad expiry is already past.\n *\n * @ensures exactly the model's WholeSeconds (the proof reads a number as an integer)\n */\nexport function wholeSeconds(n: number): Seconds {\n //@ verify\n //@ ensures (n >= 0 && n <= 9007199254740991) ==> \\result === n\n //@ ensures !(n >= 0 && n <= 9007199254740991) ==> \\result === 0\n const whole = secondsOf(Math.floor(n));\n return whole === null ? seconds(0) : whole;\n}\n\n/**\n * `n` as `Millis`, or null when it is not a safe integer at least 0 (the same rule as\n * `secondsOf`). Where a number of milliseconds enters.\n *\n * @ensures exactly the model's AcceptedAsDuration, and the value is kept\n */\nexport function millisOf(n: number): Millis | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 0 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 0 && n <= 9007199254740991 ? (n as Millis) : null;\n}\n","//@ backend dafny\nimport { hours, millis, minutes, toMillis } from \"@atlas/foundation/duration\";\nimport type { Millis } from \"./duration\";\n\n/* Small decisions the utils use, pulled out so they are proved. Verified with LemmaScript →\n Dafny (`pnpm proofs`; model: models/AugurUtils.dfy; link: models/links/augur-utils-rules.dfy).\n Each caller turns its record into these plain arguments; that mapping is tested. */\n\n/** An invoice's payment status, from its flag and amounts. */\nexport type PaymentStatus = \"Paid\" | \"Partially Paid\" | \"Unpaid\";\n\n/**\n * \"Paid\" when the invoice is flagged paid in full; else \"Partially Paid\" when both amounts are\n * present and something was paid; else \"Unpaid\". The total is never compared with the amount\n * (a finding: a full payment without the flag reads \"Partially Paid\").\n */\nexport function paymentStatusOf(\n paidInFull: boolean,\n hasAmounts: boolean,\n amountPaid: number,\n): PaymentStatus {\n //@ verify\n //@ ensures paidInFull ==> \\result === \"Paid\"\n //@ ensures !paidInFull && hasAmounts && amountPaid > 0 ==> \\result === \"Partially Paid\"\n //@ ensures !paidInFull && !(hasAmounts && amountPaid > 0) ==> \\result === \"Unpaid\"\n if (paidInFull) return \"Paid\";\n if (hasAmounts && amountPaid > 0) return \"Partially Paid\";\n return \"Unpaid\";\n}\n\n/** Low stock: in stock, a threshold set (above 0), and the quantity at or under it. */\nexport function isLowStockOf(quantity: number, threshold: number): boolean {\n //@ verify\n //@ ensures \\result === (quantity > 0 && threshold > 0 && quantity <= threshold)\n return quantity > 0 && threshold > 0 && quantity <= threshold;\n}\n\n/** Every flag from `i` on is \"Y\" (vacuously when there are none). */\nexport function allYesFrom(flags: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ decreases flags.length - i\n //@ ensures \\result === (forall(k: nat, i <= k && k < flags.length ==> flags[k] === \"Y\"))\n if (i >= flags.length) return true;\n return flags[i] === \"Y\" && allYesFrom(flags, i + 1);\n}\n\n/** Discontinued: there are stock rows, and every one says \"Y\". */\nexport function isDiscontinuedOf(flags: string[]): boolean {\n //@ verify\n //@ ensures \\result === (flags.length > 0 && allYesFrom(flags, 0))\n return flags.length > 0 && allYesFrom(flags, 0);\n}\n\n/** serializeCategoryFilters' sortBy: the prefix applied only when both are non-empty. */\nexport function categorySortBy(prefix: string, sortBy: string): string {\n //@ verify\n //@ ensures prefix !== \"\" && sortBy !== \"\" ==> \\result === prefix + sortBy\n //@ ensures !(prefix !== \"\" && sortBy !== \"\") ==> \\result === sortBy\n return prefix !== \"\" && sortBy !== \"\" ? prefix + sortBy : sortBy;\n}\n\n/** serializeSearchParams' sortBy: an empty one is left out. */\nexport function searchSortBy(sortBy: string): string | undefined {\n //@ verify\n //@ ensures sortBy !== \"\" ==> \\result === sortBy\n //@ ensures sortBy === \"\" ==> \\result === undefined\n return sortBy !== \"\" ? sortBy : undefined;\n}\n\n/** A page's first item. */\nexport function pageOffset(page: number, limit: number): number {\n //@ verify\n //@ ensures \\result === page * limit\n return page * limit;\n}\n\n/** unwrap's error message: the action's, or \"Action failed\" when it is empty. */\nexport function unwrapMessage(error: string): string {\n //@ verify\n //@ ensures error !== \"\" ==> \\result === error\n //@ ensures error === \"\" ==> \\result === \"Action failed\"\n return error !== \"\" ? error : \"Action failed\";\n}\n\n/** A shipping lead's business-day range; `to` is 0 for a single day. */\nexport interface ShippingLead {\n from: number;\n to: number;\n}\n\n/** The shipping-lead table: a days key's business-day range, or null for any other key. */\nexport function shippingLeadOf(days: string): ShippingLead | null {\n //@ verify\n //@ ensures days === \"1-2\" ==> \\result === { from: 1, to: 4 }\n //@ ensures days === \"2\" ==> \\result === { from: 4, to: 0 }\n //@ ensures days === \"2-3\" ==> \\result === { from: 2, to: 5 }\n //@ ensures days === \"3\" ==> \\result === { from: 5, to: 0 }\n //@ ensures days === \"3-4\" ==> \\result === { from: 3, to: 6 }\n //@ ensures days === \"4\" ==> \\result === { from: 6, to: 0 }\n //@ ensures days === \"5\" ==> \\result === { from: 7, to: 0 }\n //@ ensures !(days === \"1-2\" || days === \"2\" || days === \"2-3\" || days === \"3\" || days === \"3-4\" || days === \"4\" || days === \"5\") ==> \\result === null\n if (days === \"1-2\") return { from: 1, to: 4 };\n if (days === \"2\") return { from: 4, to: 0 };\n if (days === \"2-3\") return { from: 2, to: 5 };\n if (days === \"3\") return { from: 5, to: 0 };\n if (days === \"3-4\") return { from: 3, to: 6 };\n if (days === \"4\") return { from: 6, to: 0 };\n if (days === \"5\") return { from: 7, to: 0 };\n return null;\n}\n\n/** A business day is any day but Saturday and Sunday (by its en-US weekday name). */\nexport function isBusinessDayName(dayName: string): boolean {\n //@ verify\n //@ ensures \\result === (dayName !== \"Sunday\" && dayName !== \"Saturday\")\n return dayName !== \"Sunday\" && dayName !== \"Saturday\";\n}\n\n/** Schema.org availability, by the resolved stock's flags. */\nexport type Availability = \"InStock\" | \"OutOfStock\" | \"BackOrder\";\n\n/** In stock, else discontinued is out of stock, else back order (also with no stock record). */\nexport function availabilityOf(isInStock: boolean, isDiscontinued: boolean): Availability {\n //@ verify\n //@ ensures isInStock ==> \\result === \"InStock\"\n //@ ensures !isInStock && isDiscontinued ==> \\result === \"OutOfStock\"\n //@ ensures !isInStock && !isDiscontinued ==> \\result === \"BackOrder\"\n if (isInStock) return \"InStock\";\n if (isDiscontinued) return \"OutOfStock\";\n return \"BackOrder\";\n}\n\n/** The order taker: the caller's, else \"ESTORE\". */\nexport function takerOf(taker: string | undefined): string {\n //@ verify\n //@ ensures taker !== undefined ==> \\result === taker\n //@ ensures taker === undefined ==> \\result === \"ESTORE\"\n return taker ?? \"ESTORE\";\n}\n\n/**\n * An address differs from its validated form when line 1 or the city differ after lower-casing\n * (compared by the caller with JS `toLowerCase`), or the state or zip differ exactly.\n *\n * @ensures exactly the model's AddressDifferent\n */\nexport function addressDifferentOf(\n line1Same: boolean,\n citySame: boolean,\n stateSame: boolean,\n zipSame: boolean,\n): boolean {\n //@ verify\n //@ ensures \\result === (!line1Same || !citySame || !stateSame || !zipSame)\n return !line1Same || !citySame || !stateSame || !zipSame;\n}\n\n/**\n * The gcTime a query gets: none on the server (`null`, which the caller turns into `Infinity`,\n * so query-core schedules no GC timer and a per-request cache is freed with the request), the\n * client's value in the browser. Moved from augur-core (#94) so the CACHE_CONFIG tiers use it.\n *\n * @ensures exactly the model's GcTime\n */\nexport function gcTimeFor(isServer: boolean, clientGcTime: Millis): Millis | null {\n //@ verify\n //@ ensures isServer ==> \\result === null\n //@ ensures !isServer ==> \\result === clientGcTime\n return isServer ? null : clientGcTime;\n}\n\n/** A CACHE_CONFIG tier's name. */\nexport type TierName = \"STATIC\" | \"SEMI_STATIC\" | \"DYNAMIC\" | \"CART\" | \"REALTIME\";\n\n/**\n * A tier's staleTime: STATIC 1 h, SEMI_STATIC 10 min, DYNAMIC 5 min, CART 2 min, REALTIME 0.\n *\n * @ensures exactly the model's TierStaleTime\n */\nexport function tierStaleTime(t: TierName): Millis {\n //@ verify\n //@ ensures t === \"STATIC\" ==> \\result === 3600000\n //@ ensures t === \"SEMI_STATIC\" ==> \\result === 600000\n //@ ensures t === \"DYNAMIC\" ==> \\result === 300000\n //@ ensures t === \"CART\" ==> \\result === 120000\n //@ ensures t === \"REALTIME\" ==> \\result === 0\n if (t === \"STATIC\") return toMillis(hours(1));\n if (t === \"SEMI_STATIC\") return toMillis(minutes(10));\n if (t === \"DYNAMIC\") return toMillis(minutes(5));\n if (t === \"CART\") return toMillis(minutes(2));\n return millis(0);\n}\n\n/**\n * A tier's gcTime in the browser: STATIC 24 h, SEMI_STATIC 4 h, DYNAMIC and CART 30 min,\n * REALTIME 5 min; never shorter than its staleTime. On the server the tier's gcTime is\n * `gcTimeFor(true, …)`: none.\n *\n * @ensures exactly the model's TierBrowserGcTime; result ≥ tierStaleTime(t)\n */\nexport function tierBrowserGcTime(t: TierName): Millis {\n //@ verify\n //@ ensures t === \"STATIC\" ==> \\result === 86400000\n //@ ensures t === \"SEMI_STATIC\" ==> \\result === 14400000\n //@ ensures (t === \"DYNAMIC\" || t === \"CART\") ==> \\result === 1800000\n //@ ensures t === \"REALTIME\" ==> \\result === 300000\n //@ ensures \\result >= tierStaleTime(t)\n if (t === \"STATIC\") return toMillis(hours(24));\n if (t === \"SEMI_STATIC\") return toMillis(hours(4));\n if (t === \"DYNAMIC\") return toMillis(minutes(30));\n if (t === \"CART\") return toMillis(minutes(30));\n return toMillis(minutes(5));\n}\n\n/**\n * Outside a browser (Node SSR, edge, Deno): no `window`, or Deno (which has one). Mirrors\n * query-core's `isServer`; runtime.ts reads the two facts per call.\n *\n * @ensures exactly the model's ServerRuntime\n */\nexport function serverRuntimeOf(hasWindow: boolean, hasDeno: boolean): boolean {\n //@ verify\n //@ ensures \\result <==> (!hasWindow || hasDeno)\n return !hasWindow || hasDeno;\n}\n","/**\n * Which runtime a query is built in, and the gcTime it gets there. The decision is the proved\n * `gcTimeFor` (rules.ts, model `AugurUtils.GcTime`); this file only reads the runtime. Moved\n * from augur-core (#94, 2026-11-07), which re-exports both, so the CACHE_CONFIG tiers can use\n * them: augur-core depends on augur-utils, never the other way.\n */\n\nimport type { Millis } from \"./duration\";\nimport { gcTimeFor, serverRuntimeOf } from \"./rules\";\n\n/**\n * Returns true when running outside a browser (Node SSR, edge, Deno).\n * Mirrors `isServer` in `@tanstack/query-core` (`build/modern/utils.js`).\n * Evaluated per call, not at module scope, so `\"use client\"` modules that\n * also run during SSR resolve correctly on each pass.\n */\nexport function isServerRuntime(): boolean {\n // augur-utils is cross-platform with no DOM lib, so read `window` off globalThis.\n const hasWindow = typeof (globalThis as { window?: unknown }).window !== \"undefined\";\n return serverRuntimeOf(hasWindow, \"Deno\" in globalThis);\n}\n\n/**\n * Returns the React Query `gcTime` to use for a query built in this runtime.\n * On the server returns `Infinity`, which query-core treats as \"schedule no\n * GC timer\", so a per-request QueryClient is freed when the request ends.\n * A finite value would start a timer that pins the whole request cache.\n * In the browser returns `clientGcTime` unchanged. The result is a `number`, not `Millis`:\n * `Infinity` is no whole number of milliseconds.\n */\nexport function resolveGcTime(clientGcTime: Millis): number {\n return gcTimeFor(isServerRuntime(), clientGcTime) ?? Infinity;\n}\n","import { tierBrowserGcTime, tierStaleTime, type TierName } from \"./rules\";\nimport { resolveGcTime } from \"./runtime\";\n\n/**\n * A tier: its staleTime and its gcTime in this runtime (a getter, read when the tier is). The\n * values are the proved `tierStaleTime` / `tierBrowserGcTime` (model `AugurUtils.Tier…`), the\n * runtime's choice the proved `gcTimeFor`; this only builds the object.\n */\nfunction tier(name: TierName) {\n return {\n staleTime: tierStaleTime(name),\n get gcTime(): number {\n return resolveGcTime(tierBrowserGcTime(name));\n },\n } as const;\n}\n\n/**\n * Centralized cache configuration for React Query (TanStack Query)\n *\n * staleTime -- How long cached data is considered \"fresh\". While fresh,\n * React Query serves the cache instantly and does NOT refetch in the\n * background. After staleTime expires the data is \"stale\" and will be\n * refetched on the next access (mount, window focus, etc.).\n *\n * gcTime (garbage collection time) -- How long UNUSED cached data stays in\n * memory after all components using it unmount. Once gcTime expires the\n * cache entry is deleted entirely. Server-safe (#94): each tier's gcTime is\n * read through `resolveGcTime`, so on the server it is `Infinity` (no GC\n * timer, the per-request cache is freed with the request) and in the browser\n * the value below, never shorter than the tier's staleTime (proved). It is\n * decided each time the tier is read, so spreading a tier after the proxy's\n * options (`{ ...q.items.get(id), ...CACHE_CONFIG.STATIC }`) is safe in a\n * `\"use client\"` module rendered on the server too.\n *\n * STATIC (1h, gc 24h): categories, menus, item details\n * SEMI_STATIC (10m, gc 4h): pricing, stock, search results\n * DYNAMIC (5m, gc 30m): infinite scroll data\n * CART (2m, gc 30m): cart lines, cart header\n * REALTIME (0, gc 5m): active orders, checkout state\n */\nexport const CACHE_CONFIG = {\n STATIC: tier(\"STATIC\"),\n SEMI_STATIC: tier(\"SEMI_STATIC\"),\n DYNAMIC: tier(\"DYNAMIC\"),\n CART: tier(\"CART\"),\n REALTIME: tier(\"REALTIME\"),\n} as const;\n\nexport type CacheTier = keyof typeof CACHE_CONFIG;\n","import * as duration from \"@atlas/foundation/duration\";\n\n/**\n * Seconds and milliseconds for the published augur-* packages (2026-11-08): the same two types\n * as `@atlas/utils/duration`, which is private (its code is bundled in, its types can't be\n * named in a published `.d.ts`). The brands are the same, so a `Seconds` from either package is\n * the other's (as the SDK's `SiteId` is auth-core's); the builders are the proved ones, passed\n * through (model `Utils` \"durations\", link `models/links/utils-duration.dfy`).\n *\n * A TTL in seconds can't go where milliseconds are meant: React Query's `staleTime` / `gcTime`\n * are `Millis`, a Redis TTL is `Seconds`. Write `toMillis(minutes(5))`, not `300000`.\n */\n\n/** A whole number of seconds (a Redis TTL, a JWT `exp`). */\n//@ type nat\nexport type Seconds = number & { readonly __seconds: true };\n\n/** A whole number of milliseconds (React Query's `staleTime` / `gcTime`, `Date.now()`). */\n//@ type nat\nexport type Millis = number & { readonly __millis: true };\n\n/** `n` seconds. */\nexport const seconds: (n: number) => Seconds = duration.seconds;\n/** `n` minutes, in seconds. */\nexport const minutes: (n: number) => Seconds = duration.minutes;\n/** `n` hours, in seconds. */\nexport const hours: (n: number) => Seconds = duration.hours;\n/** `n` days, in seconds. */\nexport const days: (n: number) => Seconds = duration.days;\n/** `n` milliseconds, for a duration under a second. */\nexport const millis: (n: number) => Millis = duration.millis;\n/** Seconds as milliseconds, exactly. */\nexport const toMillis: (d: Seconds) => Millis = duration.toMillis;\n/** A clock reading plus a duration, both milliseconds: when something expires. */\nexport const addMillis: (a: Millis, b: Millis) => Millis = duration.addMillis;\n/** A reading less a duration, never below 0. */\nexport const minusMillis: (a: Millis, b: Millis) => Millis = duration.minusMillis;\n/** Milliseconds as whole seconds, rounded down. */\nexport const floorSeconds: (m: Millis) => Seconds = duration.floorSeconds;\n/** `n` as `Seconds`, or null unless it is a safe integer at least 0. */\nexport const secondsOf: (n: number) => Seconds | null = duration.secondsOf;\n/** An outside count of seconds, rounded down; 0 when it is then no safe integer at least 0. */\nexport const wholeSeconds: (n: number) => Seconds = duration.wholeSeconds;\n/** `n` as `Millis`, or null unless it is a safe integer at least 0. */\nexport const millisOf: (n: number) => Millis | null = duration.millisOf;\n","/**\n * Locale-aware currency formatting.\n * Defaults to USD -- consumers can override locale and currency.\n */\nexport function formatPrice(\n price: number,\n locale: string = \"en-US\",\n currency: string = \"USD\",\n): string {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: 2,\n }).format(price);\n}\n","import { addressDifferentOf } from \"./rules\";\nimport type { TSmartyStreets } from \"./types/smarty-streets\";\n\n/** User-entered address fields for comparison. */\nexport interface UserAddress {\n address1: string;\n city: string;\n state: string;\n postalCode: string;\n}\n\n/**\n * Compares a user-entered address with a SmartyStreets-validated address.\n * Returns true if any field differs (case-insensitive for address/city,\n * exact match for state abbreviation and zip code).\n *\n * Used in checkout to prompt users when their input differs from the\n * USPS-validated address.\n */\nexport function isAddressDifferent(\n userAddress: UserAddress,\n smartyAddress: TSmartyStreets,\n): boolean {\n return addressDifferentOf(\n (smartyAddress.deliveryLine1 ?? \"\").toLowerCase() === userAddress.address1.toLowerCase(),\n (smartyAddress.cityName ?? \"\").toLowerCase() === userAddress.city.toLowerCase(),\n smartyAddress.stateAbbreviation === userAddress.state,\n smartyAddress.zipCode === userAddress.postalCode,\n );\n}\n","export type PaymentStatusInvoice = {\n paidInFullFlag?: string | null;\n amountPaid?: number;\n totalAmount?: number;\n};\n\nimport { paymentStatusOf, type PaymentStatus } from \"./rules\";\n\nexport type { PaymentStatus } from \"./rules\";\n\n/** Returns \"Paid\", \"Partially Paid\", or \"Unpaid\" based on invoice payment flags and amounts. */\nexport function getPaymentStatus(invoice: PaymentStatusInvoice): PaymentStatus {\n return paymentStatusOf(\n invoice.paidInFullFlag === \"Y\",\n invoice.amountPaid != null && invoice.totalAmount != null,\n invoice.amountPaid ?? 0,\n );\n}\n","export type ShipToAddress = {\n shipToId: string | number;\n name: string;\n address1: string;\n address2?: string;\n city: string;\n state: string;\n zip: string;\n country?: string;\n};\n\ntype RawShipTo = Record<string, unknown>;\n\nfunction str(value: unknown): string {\n return String(value).trim();\n}\n\n/** The value of the first key that is neither null nor undefined, else \"\". */\nfunction firstPresent(raw: RawShipTo, keys: readonly string[]): unknown {\n for (const k of keys) {\n if (raw[k] != null) return raw[k];\n }\n return \"\";\n}\n\nfunction pick(raw: RawShipTo, keys: readonly string[]): string {\n return str(firstPresent(raw, keys));\n}\n\n// Physical records are detected by camelCase OR snake_case keys. Checking only the\n// camelCase variants misclassified snake_case-only physical records as mailing,\n// which then matched no MAIL_FIELDS key and returned empty fields.\nconst PHYS_MARKERS = [\n \"physAddress1\",\n \"phys_address1\",\n \"physCity\",\n \"phys_city\",\n \"physState\",\n \"phys_state\",\n] as const;\n\nconst PHYS_FIELDS = {\n address1: [\"physAddress1\", \"phys_address1\"],\n address2: [\"physAddress2\", \"phys_address2\"],\n city: [\"physCity\", \"phys_city\"],\n state: [\"physState\", \"phys_state\"],\n zip: [\"physPostalCode\", \"phys_postal_code\"],\n country: [\"physCountry\", \"phys_country\"],\n} as const;\n\nconst MAIL_FIELDS = {\n address1: [\"mailAddress1\", \"mail_address1\", \"address1\"],\n address2: [\"mailAddress2\", \"mail_address2\", \"address2\"],\n city: [\"mailCity\", \"mail_city\", \"city\"],\n state: [\"mailState\", \"mail_state\", \"state\"],\n zip: [\"mailPostalCode\", \"mail_postal_code\", \"postalCode\", \"zip\"],\n country: [\"mailCountry\", \"mail_country\", \"country\"],\n} as const;\n\n/** Normalizes a raw ship-to address object (camelCase or snake_case, physical or mailing) into a consistent ShipToAddress shape. */\nexport function transformShipToAddress(raw: RawShipTo): ShipToAddress {\n const isPhys = PHYS_MARKERS.some((k) => raw[k] != null);\n\n const f = isPhys ? PHYS_FIELDS : MAIL_FIELDS;\n\n const address: ShipToAddress = {\n shipToId: firstPresent(raw, [\"shipToId\", \"ship_to_id\", \"id\"]) as string | number,\n name: pick(raw, [\"shipToName\", \"ship_to_name\", \"name\"]),\n address1: pick(raw, f.address1),\n city: pick(raw, f.city),\n state: pick(raw, f.state),\n zip: pick(raw, f.zip),\n };\n\n const address2 = pick(raw, f.address2);\n if (address2) address.address2 = address2;\n\n const country = pick(raw, f.country);\n if (country) address.country = country;\n\n return address;\n}\n","import { takerOf } from \"./rules\";\nimport type { TCartLine } from \"./types/cart\";\n\nexport type OeHdr = {\n customer_id: number;\n company_id: string;\n sales_location_id: number;\n user_id: number;\n user_email: string;\n taker: string;\n customer_po_no?: string;\n ship_to_id?: string | number;\n delivery_instructions?: string;\n};\n\nexport type OeLine = {\n item_id: string;\n unit_quantity: number | null;\n unit_of_measure: string | null;\n inv_mast_uid: number;\n unit_price?: number;\n};\n\nexport type CheckoutInput = {\n customerId: number;\n companyId: string;\n salesLocationId: number;\n userId: number;\n userEmail: string;\n taker?: string;\n cartLines: TCartLine[];\n poNumber?: string;\n shipToId?: string | number;\n deliveryInstructions?: string;\n};\n\n/** Builds the oe_hdr + oe_line payload required by the commerce checkout API from cart data. */\nexport function buildCheckoutPayload(input: CheckoutInput): {\n oe_hdr: OeHdr;\n oe_line: OeLine[];\n} {\n const oe_hdr: OeHdr = {\n customer_id: input.customerId,\n company_id: input.companyId,\n sales_location_id: input.salesLocationId,\n user_id: input.userId,\n user_email: input.userEmail,\n taker: takerOf(input.taker),\n };\n\n if (input.poNumber != null) oe_hdr.customer_po_no = input.poNumber;\n if (input.shipToId != null) oe_hdr.ship_to_id = input.shipToId;\n if (input.deliveryInstructions != null) oe_hdr.delivery_instructions = input.deliveryInstructions;\n\n const oe_line: OeLine[] = input.cartLines.map((line) => {\n const oeLine: OeLine = {\n item_id: line.itemId,\n unit_quantity: line.quantity,\n unit_of_measure: line.unitOfMeasure,\n inv_mast_uid: line.invMastUid,\n };\n if (line.unitPrice != null) oeLine.unit_price = line.unitPrice;\n return oeLine;\n });\n\n return { oe_hdr, oe_line };\n}\n","/**\n * Decimal places kept by `cleanMoney`. Prices carry at most 4 decimals and\n * quantities about as many, so a product needs at most 8. Float64 holds about\n * 15 significant digits, so on real 4-decimal prices 8 decimals stayed\n * noise-free for line totals up to about 2×10^7; 10 decimals left noise from\n * about 2×10^5 (measured in the GH #496 review).\n */\nconst MONEY_DECIMALS = 8;\n\n/**\n * Largest shifted magnitude that is rounded. From 2^51 up, adjacent doubles are\n * 0.5 or more apart, so rounding to `decimals` places cannot be represented and\n * the value is returned unchanged (this also keeps a shift that overflows to\n * Infinity from becoming NaN).\n */\nconst MAX_SHIFTED = 2 ** 51;\n\n/**\n * Shift a finite, non-negative number's decimal point by `places` through its\n * exponent string. The result is the correctly rounded double of the shifted\n * decimal, not a binary `value * 10^places` product.\n */\nfunction shiftDecimal(value: number, places: number): number {\n const [mantissa, exponent = \"0\"] = String(value).split(\"e\");\n return Number(`${mantissa}e${Number(exponent) + places}`);\n}\n\n/**\n * Round half away from zero to `decimals` places.\n *\n * Shifts the decimal point through the exponent string instead of multiplying,\n * so float noise in `value * 10^decimals` cannot flip a tie\n * (`Math.round(1.005 * 100) / 100` is 1; this returns 1.01).\n *\n * @requires decimals ∈ ℕ // whole, non-negative; otherwise RangeError\n * @ensures ¬isFinite(value) → result = value // NaN and ±Infinity pass through unchanged\n * @ensures |value| · 10^decimals ≥ 2^51 → result = value // too large to round at that precision\n * @ensures |value| · 10^decimals < 2^51 → result = sign(value) · round½↑(|value| · 10^decimals) · 10^−decimals\n * // half away from zero on the value's shortest decimal string; a 17-significant-digit input whose\n * // shifted fraction falls within one float spacing of .5 can still double-round (not observed for\n * // real price × quantity products)\n * @ensures result = 0 → result is +0 // a small negative rounds to 0, never −0 (\"-$0.00\")\n *\n * @param value Number to round\n * @param decimals Decimal places to keep\n * @returns `value` rounded half away from zero\n */\nexport function roundHalfAway(value: number, decimals: number): number {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new RangeError(\n `roundHalfAway: decimals must be a non-negative integer, got ${String(decimals)}`,\n );\n }\n if (!Number.isFinite(value)) return value;\n const shifted = shiftDecimal(Math.abs(value), decimals);\n if (!(shifted < MAX_SHIFTED)) return value;\n const rounded = Math.round(shifted);\n if (rounded === 0) return 0;\n return Math.sign(value) * shiftDecimal(rounded, -decimals);\n}\n\n/**\n * Remove JS float noise from a money product or sum.\n *\n * `38.0714 * 3` is 114.21419999999999; this returns 114.2142. Rounds half away\n * from zero to 8 decimals: enough to represent real prices and quantities, not\n * exact decimal arithmetic. Apply it to every product and running sum of money.\n *\n * @ensures cleanMoney(cleanMoney(value)) = cleanMoney(value)\n * // idempotent: an in-range result is k · 10^−8 with integer k < 2^51, whose shortest\n * // decimal string shifts back to k exactly; out-of-range values pass through unchanged\n *\n * @param value Result of a money product or sum\n * @returns `value` without float noise\n */\nexport function cleanMoney(value: number): number {\n return roundHalfAway(value, MONEY_DECIMALS);\n}\n","//@ backend dafny\n\n/* The decision behind `derivePrice`: which of its five outcomes a price input gets. Verified\n with LemmaScript → Dafny (`pnpm proofs`; model: models/AugurUtils.dfy `PriceOutcomeOf`; link:\n models/links/augur-utils-price-outcome.dfy). What is proved is the whole decision table, with\n no gap: every input gets exactly the outcome its clause names, whatever order the checks run\n in. Not proved: that `derivePrice` computes the three flags correctly from the price record\n (`Number.isFinite` and IEEE-754 are invisible to the prover, whose `number` is a mathematical\n integer, so `unitPrice` is reasoned about as an integer here), or the money math (`total`),\n which is tested in test/derive-price.test.ts and test/money.test.ts. */\n\n/**\n * - `badQuantity`: the quantity is negative or not finite (derivePrice throws).\n * - `loading`: no price record, or the record has no `unitPrice` yet (GH #454).\n * - `badPrice`: the record's `unitPrice` is negative or not finite (derivePrice throws).\n * - `callForPrice`: the record's `unitPrice` is 0.\n * - `priced`: the record's `unitPrice` is greater than 0.\n */\nexport type PriceOutcome = \"badQuantity\" | \"loading\" | \"badPrice\" | \"callForPrice\" | \"priced\";\n\n/**\n * Decide the outcome. `quantityOk` is \"finite and ≥ 0\"; `hasPrice` is \"a record with a\n * `unitPrice`\"; `priceFinite` is `Number.isFinite(unitPrice)`; `unitPrice` is the record's price\n * (any value when `hasPrice` is false).\n *\n * Proven: each outcome holds exactly when its condition does, so the five are exhaustive and\n * mutually exclusive. A bad quantity wins over everything (a negative quantity throws even while\n * loading), and loading wins over a bad price (a missing price is never reported as bad).\n */\nexport function priceOutcome(\n quantityOk: boolean,\n hasPrice: boolean,\n priceFinite: boolean,\n unitPrice: number,\n): PriceOutcome {\n //@ verify\n //@ ensures (\\result === \"badQuantity\") === !quantityOk\n //@ ensures (\\result === \"loading\") === (quantityOk && !hasPrice)\n //@ ensures (\\result === \"badPrice\") === (quantityOk && hasPrice && !(priceFinite && unitPrice >= 0))\n //@ ensures (\\result === \"callForPrice\") === (quantityOk && hasPrice && priceFinite && unitPrice === 0)\n //@ ensures (\\result === \"priced\") === (quantityOk && hasPrice && priceFinite && unitPrice > 0)\n if (!quantityOk) return \"badQuantity\";\n if (!hasPrice) return \"loading\";\n if (!priceFinite || unitPrice < 0) return \"badPrice\";\n if (unitPrice === 0) return \"callForPrice\";\n return \"priced\";\n}\n","import { cleanMoney } from \"./money\";\nimport { priceOutcome, type PriceOutcome } from \"./price-outcome\";\nimport type { TPriceData } from \"./types/pricing\";\n\n/**\n * Result of price derivation as a discriminated union over the three real\n * domain states. The `state` tag lifts the previously-overloaded `0` sentinel\n * into the type system: \"loading\" (no price record yet) is now distinct from\n * \"callForPrice\" (a genuine zero price). See GH #454.\n */\nexport type DerivedPrice =\n | { state: \"loading\" }\n | { state: \"priced\"; unitPrice: number; total: number; unitOfMeasure: string }\n | { state: \"callForPrice\"; unitOfMeasure: string };\n\nexport interface DerivePriceInput {\n priceData: TPriceData | null | undefined;\n /**\n * Quantity in the priced unit. Fractional values come from UOM conversion (ft, sqft, lb).\n * Omit it to price one unit. Null is not accepted: an unknown quantity cannot be priced,\n * so the caller decides how to handle it.\n */\n quantity?: number;\n}\n\n/** The RangeError for the two refused outcomes, null for the rest (the outcomes are exclusive). */\nfunction outcomeError(\n outcome: PriceOutcome,\n quantity: number,\n unitPrice: number | undefined,\n): RangeError | null {\n if (outcome === \"badQuantity\") {\n return new RangeError(\n `derivePrice: quantity must be a non-negative finite number, got ${String(quantity)}`,\n );\n }\n if (outcome === \"badPrice\") {\n return new RangeError(\n `derivePrice: unitPrice must be a non-negative finite number, got ${String(unitPrice)}`,\n );\n }\n return null;\n}\n\n/** `priceOutcome` over the input's three flags. */\nfunction outcomeFor(\n priceData: TPriceData | null | undefined,\n unitPrice: number | undefined,\n quantity: number,\n): PriceOutcome {\n const hasPrice = priceData != null && unitPrice != null;\n return priceOutcome(\n Number.isFinite(quantity) && quantity >= 0,\n hasPrice,\n Number.isFinite(unitPrice),\n // Read only when hasPrice is true; the 0 is never compared then.\n unitPrice ?? 0,\n );\n}\n\n/**\n * Pure price derivation — usable in hooks AND server components.\n *\n * @requires quantity = undefined ∨ (quantity ∈ ℝ ∧ quantity ≥ 0 ∧ Number.isFinite(quantity))\n * // omitted → 1 (a one-unit price); fractional quantities (UOM conversion, e.g. 2023.5 ft) are valid;\n * // negative, NaN, ±Infinity, or a null passed at runtime → RangeError. -0 passes (-0 ≥ 0).\n * @requires unitPrice ≥ 0 ∧ Number.isFinite(unitPrice) (when a price record is present)\n * // violated → RangeError\n * @ensures result.state = \"loading\" ⟺ priceData == null ∨ priceData.unitPrice == null (given the quantity @requires; a bad quantity throws even while loading)\n * // a missing price record (undefined/null) is loading, NOT a zero price — the distinction GH #454 restores\n * @ensures result.state = \"callForPrice\" ⟺ priceData.unitPrice = 0\n * // a genuine zero price is call-for-price, distinct from loading\n * @ensures result.state = \"priced\" ⟺ priceData.unitPrice > 0\n * // total = cleanMoney(unitPrice · quantity): the product rounded half away from zero to\n * // 8 decimals, which removes float noise (38.0714 · 3 → 114.2142, not 114.21419999999999)\n *\n * The state decision (which branch, including the two RangeErrors) is `priceOutcome`, proved\n * with LemmaScript (`price-outcome.ts`, linked to `models/AugurUtils.dfy`). This function computes\n * its three flags and does the money math; both are tested, not proved.\n */\nexport function derivePrice(input: DerivePriceInput): DerivedPrice {\n const { priceData, quantity = 1 } = input;\n\n // TPriceData types unitPrice as `number`, but the payload omits it while the\n // price record is still loading. Widen to capture that runtime reality.\n const unitPrice: number | undefined = priceData?.unitPrice;\n const outcome = outcomeFor(priceData, unitPrice, quantity);\n\n const error = outcomeError(outcome, quantity, unitPrice);\n if (error) throw error;\n if (outcome === \"loading\") return { state: \"loading\" };\n\n // Every outcome after \"loading\" has hasPrice (priceOutcome's loading clause), so both are set.\n const record = priceData as TPriceData;\n const price = unitPrice as number;\n const unitOfMeasure = record.item?.unitOfMeasure ?? \"\";\n\n if (outcome === \"callForPrice\") return { state: \"callForPrice\", unitOfMeasure };\n\n return { state: \"priced\", unitPrice: price, total: cleanMoney(price * quantity), unitOfMeasure };\n}\n","import { isDiscontinuedOf, isLowStockOf } from \"./rules\";\nimport type { TStock } from \"./types/inventory\";\n\nexport interface ResolveStockInput {\n stock: TStock | null | undefined;\n companyKey?: string;\n round?: boolean;\n lowStockThreshold?: number;\n showQuantity?: boolean;\n}\n\nexport interface ResolvedStock {\n quantity: number;\n isInStock: boolean;\n isLowStock: boolean;\n isDiscontinued: boolean;\n displayQuantity: number | null;\n}\n\n/** One company's quantity when `companyKey` names one in the summary, else the sum over every company. */\nfunction summaryQuantity(\n companySummary: TStock[\"companySummary\"],\n companyKey: string | undefined,\n): number {\n if (companyKey && companyKey in companySummary) {\n return companySummary[companyKey] ?? 0;\n }\n return Object.values(companySummary).reduce((sum: number, val: number) => sum + val, 0);\n}\n\n/** Discontinued when there is stock data and every row says \"Y\". */\nfunction allDiscontinued(stockData: TStock[\"stockData\"]): boolean {\n return isDiscontinuedOf(stockData.map((d) => d.discontinued));\n}\n\n/**\n * Pure stock resolution -- usable in hooks AND server components.\n *\n * Returns `null` when `stock` is missing (loading / error state).\n */\nexport function resolveStock(input: ResolveStockInput): ResolvedStock | null {\n const { stock, companyKey, round = false, lowStockThreshold = 0, showQuantity = false } = input;\n\n if (!stock) return null;\n\n const summed = summaryQuantity(stock.companySummary, companyKey);\n const qty = round ? Math.round(summed) : summed;\n\n const isInStock = qty > 0;\n const isLowStock = isLowStockOf(qty, lowStockThreshold);\n const isDiscontinued = allDiscontinued(stock.stockData);\n\n return {\n quantity: qty,\n isInStock,\n isLowStock,\n isDiscontinued,\n displayQuantity: showQuantity ? qty : null,\n };\n}\n","import type { ResolvedStock } from \"./resolve-stock\";\nimport { availabilityOf, type Availability } from \"./rules\";\n\nexport type SchemaAvailability =\n | \"https://schema.org/InStock\"\n | \"https://schema.org/OutOfStock\"\n | \"https://schema.org/LimitedAvailability\"\n | \"https://schema.org/BackOrder\"\n | \"https://schema.org/Discontinued\";\n\n/**\n * Maps resolved stock to a Schema.org availability URL.\n *\n * - InStock: quantity > 0\n * - OutOfStock: discontinued at all locations with zero inventory\n * - BackOrder: zero stock but not discontinued (accepts backorders)\n */\nexport function getSchemaAvailability(\n resolved: ResolvedStock | null | undefined,\n): SchemaAvailability {\n return SCHEMA_URLS[availabilityOf(!!resolved?.isInStock, !!resolved?.isDiscontinued)];\n}\n\nconst SCHEMA_URLS: Record<Availability, SchemaAvailability> = {\n InStock: \"https://schema.org/InStock\",\n OutOfStock: \"https://schema.org/OutOfStock\",\n BackOrder: \"https://schema.org/BackOrder\",\n};\n","//@ backend dafny\nimport {\n isAlnumChar,\n isBase64UrlChar,\n isDigit,\n isHexChar,\n isJsSpace,\n isLineTerminator,\n isLowerHexChar,\n isSnakeChar,\n isWordChar,\n lowerCode,\n} from \"@atlas/foundation/chars\";\n\n/* String scans and slices, verified with LemmaScript → Dafny (hand lemmas in strings.dfy;\n model: models/Utils.dfy; link: models/links/utils-strings.dfy). Recursive and\n expression-bodied so specs can use them, and each contract pins the result exactly, so\n an importer (which sees only the contract) knows what it returns. Two of them stand in\n for constructs lsc mistranslates: `prefix` for an unclamped `slice`, and the code-unit\n scans for \"\\r\" / \"\\n\" literals. */\n\n/**\n * The code unit at `i`, or -1 when `i` is outside `s`. JS `charCodeAt` gives NaN there,\n * which no code equals, so a scan's own bounds test would change no result and no test\n * could tell it from none (an equivalent mutant); with the bound here once, the boundary is\n * observable (tests pin -1) and the scans that use it carry no bound of their own. A code\n * unit is never negative, so -1 matches no `code` a caller passes (`requires code >= 0`).\n *\n * @ensures 0 ≤ i < |s| ⟹ result = s[i]; otherwise result = -1\n */\nexport function codeAt(s: string, i: number): number {\n //@ verify\n //@ ensures (i >= 0 && i < s.length) ==> \\result === s.charCodeAt(i)\n //@ ensures !(i >= 0 && i < s.length) ==> \\result === -1\n return i >= 0 && i < s.length ? s.charCodeAt(i) : -1;\n}\n\n/**\n * Every character of `s` from index `i` on is base64url.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isBase64UrlChar(s[k])\n */\nexport function base64UrlFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isBase64UrlChar(s.charCodeAt(k)))\n return i >= s.length || (isBase64UrlChar(s.charCodeAt(i)) && base64UrlFrom(s, i + 1));\n}\n\n/**\n * The base64url digit for `v` (RFC 4648 §5): A-Z a-z 0-9 - _.\n *\n * @ensures exactly the model's Base64UrlDigit\n */\nexport function base64UrlDigit(v: number): string {\n //@ verify\n //@ type v nat\n //@ requires v >= 0 && v < 64\n //@ ensures \\result === \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\".slice(v, v + 1)\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\".slice(v, v + 1);\n}\n\n/**\n * Bytes from `i` on as unpadded base64url: each three as four digits, a last one or two as two or\n * three (JS `btoa` with `+/` as `-_` and the `=` dropped). One frame per three bytes: a JWT part\n * is a few hundred.\n *\n * @ensures exactly the model's Base64UrlFrom (links/utils-strings.dfy)\n */\nexport function encodeBase64UrlFrom(b: number[], i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && forall(k: nat, k < b.length ==> (b[k] >= 0 && b[k] < 256))\n //@ decreases b.length - i\n //@ ensures i >= b.length ==> \\result === \"\"\n if (i >= b.length) return \"\";\n const x = b[i] as number;\n const first = base64UrlDigit(Math.floor(x / 4));\n if (i + 1 === b.length) return first + base64UrlDigit((x % 4) * 16);\n const y = b[i + 1] as number;\n const second = base64UrlDigit((x % 4) * 16 + Math.floor(y / 16));\n if (i + 2 === b.length) return first + second + base64UrlDigit((y % 16) * 4);\n const z = b[i + 2] as number;\n return (\n first +\n second +\n base64UrlDigit((y % 16) * 4 + Math.floor(z / 64)) +\n base64UrlDigit(z % 64) +\n encodeBase64UrlFrom(b, i + 3)\n );\n}\n\n/**\n * Every character of `s` from index `i` on is lowercase hex.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isLowerHexChar(s[k])\n */\nexport function lowerHexFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isLowerHexChar(s.charCodeAt(k)))\n return i >= s.length || (isLowerHexChar(s.charCodeAt(i)) && lowerHexFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is hex, either case.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isHexChar(s[k])\n */\nexport function hexFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isHexChar(s.charCodeAt(k)))\n return i >= s.length || (isHexChar(s.charCodeAt(i)) && hexFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII digit (`\\d` without the `u` flag).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isDigit(s[k])\n */\nexport function digitsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isDigit(s.charCodeAt(k)))\n return i >= s.length || (isDigit(s.charCodeAt(i)) && digitsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is a word character (`\\w`: `[A-Za-z0-9_]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isWordChar(s[k])\n */\nexport function wordCharsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isWordChar(s.charCodeAt(k)))\n return i >= s.length || (isWordChar(s.charCodeAt(i)) && wordCharsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is a snake_case character (`[a-z0-9_]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isSnakeChar(s[k])\n */\nexport function snakeCharsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isSnakeChar(s.charCodeAt(k)))\n return i >= s.length || (isSnakeChar(s.charCodeAt(i)) && snakeCharsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII letter or digit (`[A-Za-z0-9]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isAlnumChar(s[k])\n */\nexport function alnumFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isAlnumChar(s.charCodeAt(k)))\n return i >= s.length || (isAlnumChar(s.charCodeAt(i)) && alnumFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII letter, digit or `-` (`[A-Za-z0-9-]`):\n * a domain label's tail, a service name's tail.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isAlnumChar(s[k]) ∨ s[k] = \"-\" — the model's AlnumDashFrom\n */\nexport function alnumDashFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> (isAlnumChar(s.charCodeAt(k)) || s.charCodeAt(k) === 45))\n if (i >= s.length) return true;\n const c = s.charCodeAt(i);\n return (isAlnumChar(c) || c === 45) && alnumDashFrom(s, i + 1);\n}\n\n/**\n * The last index before `end` holding `code`, or -1 (JS `s.lastIndexOf(c)` at end = |s|).\n *\n * @ensures result = -1 ∨ (0 ≤ result < end ∧ s[result] = code ∧ no `code` in (result, end))\n */\nexport function lastIndexOfCode(s: string, code: number, end: number): number {\n //@ verify\n //@ type end nat\n //@ requires 0 <= end && end <= s.length\n //@ decreases end\n //@ ensures \\result === -1 || (0 <= \\result && \\result < end)\n //@ ensures \\result >= 0 ==> s.charCodeAt(\\result) === code\n //@ ensures \\result >= 0 ==> forall(k: nat, (\\result < k && k < end) ==> s.charCodeAt(k) !== code)\n //@ ensures \\result === -1 ==> forall(k: nat, k < end ==> s.charCodeAt(k) !== code)\n if (end === 0) return -1;\n if (s.charCodeAt(end - 1) === code) return end - 1;\n return lastIndexOfCode(s, code, end - 1);\n}\n\n/**\n * No character of `s` from index `i` on is `code`.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). s[k] ≠ code\n */\nexport function lacksCode(s: string, code: number, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> s.charCodeAt(k) !== code)\n // `===`, not `>=`: past the end a read is NaN !== code, so `>=` vs `>` would be equivalent\n return i === s.length || (s.charCodeAt(i) !== code && lacksCode(s, code, i + 1));\n}\n\n/**\n * The end of the run of `code` starting at `i`: the first index ≥ i that isn't `code`\n * (skip spaces: `codeRunEnd(header, 32, i)`).\n *\n * @requires i ≤ |s|\n * @ensures i ≤ result ≤ |s| ∧ ∀ k ∈ [i, result). s[k] = code ∧ (result < |s| ⟹ s[result] ≠ code)\n * — exactly the run's end\n */\nexport function codeRunEnd(s: string, code: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ requires code >= 0\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> s.charCodeAt(k) === code)\n //@ ensures \\result < s.length ==> s.charCodeAt(\\result) !== code\n return codeAt(s, i) === code ? codeRunEnd(s, code, i + 1) : i;\n}\n\n/**\n * The first index ≥ `from` holding `code`, or -1 (`indexOf` for one code unit, so \"\\n\" is\n * passed as 10, never as a literal).\n *\n * @ensures result = -1 ∨ (from ≤ result < |s| ∧ s[result] = code), with no `code` in\n * [from, result) — the first one; result = -1 ⟹ none from `from` on\n */\nexport function indexOfCode(s: string, code: number, from: number): number {\n //@ verify\n //@ type from nat\n //@ requires code >= 0 && from >= 0\n //@ decreases s.length - from\n //@ ensures \\result === -1 || (from <= \\result && \\result < s.length)\n //@ ensures \\result >= 0 ==> s.charCodeAt(\\result) === code\n //@ ensures \\result >= 0 ==> forall(k: nat, (from <= k && k < \\result) ==> s.charCodeAt(k) !== code)\n //@ ensures \\result === -1 ==> forall(k: nat, (from <= k && k < s.length) ==> s.charCodeAt(k) !== code)\n const c = codeAt(s, from);\n if (c === code) return from;\n if (c === -1) return -1;\n return indexOfCode(s, code, from + 1);\n}\n\n/**\n * The first index ≥ `i` holding `a` or `b`, or |s| (a run either code ends: a path segment's\n * run to \"/\" or \"?\"). One scan: the lesser of two `indexOfCode` ends is the same index, but\n * its two sides are equal only when both are |s|, a boundary no test can observe.\n *\n * @requires i ≤ |s|\n * @ensures i ≤ result ≤ |s| ∧ ∀ k ∈ [i, result). s[k] ∉ {a, b} ∧ (result < |s| ⟹ s[result] ∈ {a, b})\n * — exactly the first such index\n */\nexport function eitherCodeEnd(s: string, a: number, b: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ requires a >= 0 && b >= 0\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> (s.charCodeAt(k) !== a && s.charCodeAt(k) !== b))\n //@ ensures \\result < s.length ==> (s.charCodeAt(\\result) === a || s.charCodeAt(\\result) === b)\n const c = codeAt(s, i);\n if (c === -1 || c === a || c === b) return i;\n return eitherCodeEnd(s, a, b, i + 1);\n}\n\n/**\n * `s` without one trailing `code` (\"\\r\" before a \"\\n\", say); unchanged otherwise.\n *\n * @ensures s ends with code ⟹ result = s[0, |s| − 1)\n * @ensures otherwise result = s\n */\nexport function dropLast(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures (s.length > 0 && s.charCodeAt(s.length - 1) === code) ==> \\result === s.slice(0, s.length - 1)\n //@ ensures !(s.length > 0 && s.charCodeAt(s.length - 1) === code) ==> \\result === s\n return codeAt(s, s.length - 1) === code ? s.slice(0, s.length - 1) : s;\n}\n\n/**\n * `s` without its leading `code` units (every one of them).\n *\n * @ensures exactly the model's LStripCode\n */\nexport function lStripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ decreases s.length\n //@ ensures \\result.length <= s.length\n if (codeAt(s, 0) === code) return lStripCode(s.slice(1), code);\n return s;\n}\n\n/**\n * `s` without its trailing `code` units (every one of them).\n *\n * @ensures exactly the model's RStripCode\n */\nexport function rStripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ decreases s.length\n //@ ensures \\result.length <= s.length\n if (codeAt(s, s.length - 1) === code) {\n return rStripCode(s.slice(0, s.length - 1), code);\n }\n return s;\n}\n\n/**\n * `s` without its leading and trailing `code` units, the middle kept (`/a/b/` with `/` →\n * `a/b`).\n *\n * @ensures exactly the model's StripCode — neither end is `code` (StripCodeTrims)\n */\nexport function stripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures \\result === rStripCode(lStripCode(s, code), code)\n return rStripCode(lStripCode(s, code), code);\n}\n\n/**\n * JS `s.startsWith(x, pos)`, which lsc mistranslates (it drops `pos`). Like JS, a `pos`\n * past the end counts as the end, so the empty string matches anywhere.\n *\n * @ensures pos ≤ |s| ⟹ (result ⟺ pos + |x| ≤ |s| ∧ s[pos, pos + |x|) = x) — so a true\n * result also gives the bounds for slicing after the match\n * @ensures pos > |s| ⟹ (result ⟺ x = \"\")\n */\nexport function startsWithAt(s: string, x: string, pos: number): boolean {\n //@ verify\n //@ type pos nat\n //@ requires pos >= 0\n //@ ensures pos <= s.length ==> (\\result <==> (pos + x.length <= s.length && s.slice(pos, pos + x.length) === x))\n //@ ensures pos > s.length ==> (\\result <==> x.length === 0)\n // Math.min, not a ternary: at pos = |s| both branches agree, so `<` vs `<=` is equivalent\n const at = Math.min(pos, s.length);\n // The slice is clamped to the end, so a too-long x differs by length: no separate fit test\n // (JS slice clamps too, which made one unobservable)\n return s.slice(at, Math.min(at + x.length, s.length)) === x;\n}\n\n/**\n * `s` with A-Z lowercased and every other character kept: what lsc's proofs take\n * `toLowerCase()` to be. JS's `toLowerCase()` also maps non-ASCII letters, some onto ASCII\n * (the Kelvin sign K, U+212A, becomes \"k\") or onto two characters (İ, U+0130), so a proved\n * function that lowercases MUST use this, or the runtime does what the proof says it\n * doesn't.\n *\n * @ensures |result| = |s| ∧ ∀ k < |s|. result[k] = (s[k] ∈ A-Z ? s[k] + 32 : s[k]) — A-Z\n * lowered, every other code unit unchanged; true in JS (a contract `=== s.toLowerCase()` held\n * only in lsc's ASCII model of the built-in, Fable review 2026-11-06). Helper-free, since an\n * importer is given only the helpers its own body calls; exactly the model's LowerAscii in\n * the link\n */\nexport function lowerAscii(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures \\result.length === s.length\n //@ ensures forall(k: nat, k < s.length ==> \\result.charCodeAt(k) === ((s.charCodeAt(k) >= 65 && s.charCodeAt(k) <= 90) ? s.charCodeAt(k) + 32 : s.charCodeAt(k)))\n if (s.length === 0) return \"\";\n const c = s.charCodeAt(0);\n const head =\n c >= 65 && c <= 90 ? \"abcdefghijklmnopqrstuvwxyz\".slice(c - 65, c - 64) : s.slice(0, 1);\n return head + lowerAscii(s.slice(1));\n}\n\n/**\n * `lowerAscii` as a loop: a constant stack depth (and linear time) on long text, where the\n * recursive spec takes a frame and a slice per character.\n *\n * @ensures result = lowerAscii(s)\n */\nexport function lowerAsciiText(s: string): string {\n //@ verify\n //@ ensures \\result === lowerAscii(s)\n let out = \"\";\n let i = 0;\n while (i !== s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + lowerAscii(s.slice(i)) === lowerAscii(s)\n //@ decreases s.length - i\n const c = s.charCodeAt(i);\n out =\n out +\n (c >= 65 && c <= 90 ? \"abcdefghijklmnopqrstuvwxyz\".slice(c - 65, c - 64) : s.slice(i, i + 1));\n i = i + 1;\n }\n return out;\n}\n\n/**\n * Whether `x` from index `k` matches `s` from `pos + k`, code by code, ASCII-lowered. A code\n * past the end of `s` is -1 (`codeAt`), which no code of `x` is, so there is no bound to\n * check (a `pos + |x| ≤ |s|` guard before a slice never changed the answer at runtime, where\n * `slice` clamps: an equivalent mutant, 2026-11-02).\n *\n * @ensures exactly the model's CaselessFrom\n */\nexport function caselessFrom(s: string, x: string, pos: number, k: number): boolean {\n //@ verify\n //@ type pos nat\n //@ type k nat\n //@ requires pos >= 0 && k >= 0 && k <= x.length\n //@ decreases x.length - k\n //@ ensures k === x.length ==> \\result\n if (k === x.length) return true;\n return lowerCode(codeAt(s, pos + k)) === x.charCodeAt(k) && caselessFrom(s, x, pos, k + 1);\n}\n\n/**\n * Whether the text of `s` at `pos`, ASCII-lowered, is `x` (`x` given lowercase): a case-free\n * `startsWith`; callers carry no length guard of their own. Only `pos ≤ |s|` is checked: it\n * decides an empty `x` past the end, the one case the code-by-code test can't see.\n *\n * @ensures result ⟺ pos + |x| ≤ |s| ∧ ∀ j < |x|. lowered(s[pos + j]) = x[j] — the text at pos,\n * ASCII-lowered (A-Z + 32), is x; helper-free; exactly the model's StartsWithCaseless in the link\n */\nexport function startsWithCaseless(s: string, x: string, pos: number): boolean {\n //@ verify\n //@ type pos nat\n //@ requires pos >= 0\n //@ ensures \\result <==> (pos + x.length <= s.length && forall(j: nat, j < x.length ==> ((s.charCodeAt(pos + j) >= 65 && s.charCodeAt(pos + j) <= 90) ? s.charCodeAt(pos + j) + 32 : s.charCodeAt(pos + j)) === x.charCodeAt(j)))\n return pos <= s.length && caselessFrom(s, x, pos, 0);\n}\n\n/**\n * Whether `s` ends with `suffix` (JS one-argument `endsWith`, which lsc reads as its\n * two-argument form; moved from the augur-api generator 2026-11-01).\n *\n * @ensures result ⟺ |s| ≥ |suffix| ∧ s[|s| − |suffix|, |s|) = suffix — exactly the model's EndsWith\n */\nexport function endsWith(s: string, suffix: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s.length >= suffix.length && s.slice(s.length - suffix.length) === suffix)\n // No length test: from max(|s| − |suffix|, 0), a too-long suffix compares unequal by length\n return s.slice(Math.max(s.length - suffix.length, 0)) === suffix;\n}\n\n/**\n * The order of `a` and `b` by UTF-16 code unit from index `i`, as a recursive spec: -1, 0\n * or 1 (JS `<` on strings; a proper prefix comes first). Locale-free, unlike `localeCompare`.\n *\n * @ensures result ∈ {-1, 0, 1} — exactly the model's CompareFrom\n */\nexport function compareFrom(a: string, b: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases a.length - i\n //@ ensures \\result === -1 || \\result === 0 || \\result === 1\n if (i >= a.length) return i >= b.length ? 0 : -1;\n if (i >= b.length) return 1;\n const x = a.charCodeAt(i);\n const y = b.charCodeAt(i);\n if (x < y) return -1;\n if (x > y) return 1;\n return compareFrom(a, b, i + 1);\n}\n\n/**\n * The order of two strings by UTF-16 code unit, for `sort` (what the default `sort` uses on\n * strings), so sorted output never depends on locale.\n *\n * @ensures result = compareFrom(a, b, 0)\n */\nexport function compareCodeUnits(a: string, b: string): number {\n //@ verify\n //@ ensures \\result === compareFrom(a, b, 0)\n return compareFrom(a, b, 0);\n}\n\n/**\n * JS `s.slice(0, n)`: at most `n` characters, clamped to the length. lsc reads a bare\n * `slice(0, n)` without JS's clamp, so use this instead.\n *\n * @ensures result = s[0, min(n, |s|))\n */\nexport function prefix(s: string, n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures n < s.length ==> \\result === s.slice(0, n)\n //@ ensures n >= s.length ==> \\result === s\n // Math.min, not a ternary: JS slice already clamps, so a ternary's branch is unobservable\n return s.slice(0, Math.min(n, s.length));\n}\n\n/**\n * The end of the JS-whitespace (`\\s`) run starting at `i`: the first index ≥ i that is not\n * whitespace, or |s|.\n *\n * @ensures i ≤ result ≤ |s| ∧ s[i, result) all whitespace ∧ (result = |s| ∨ ¬space(s[result]))\n */\nexport function spaceRunEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> isJsSpace(s.charCodeAt(k)))\n //@ ensures \\result < s.length ==> !isJsSpace(s.charCodeAt(\\result))\n // codeAt is -1 at the end, which is no space: the bound needs no test of its own here\n if (!isJsSpace(codeAt(s, i))) return i;\n return spaceRunEnd(s, i + 1);\n}\n\n/**\n * The end of the ASCII-digit run starting at `i` (a regex's `\\d+`, from `i`): the first index\n * ≥ i that is not 0-9, or |s|.\n *\n * @ensures i ≤ result ≤ |s| ∧ s[i, result) all digits ∧ (result = |s| ∨ ¬digit(s[result])) —\n * exactly the model's DigitRunEnd\n */\nexport function digitRunEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))\n //@ ensures \\result < s.length ==> !(s.charCodeAt(\\result) >= 48 && s.charCodeAt(\\result) <= 57)\n // codeAt is -1 at the end, which is no digit\n if (!isDigit(codeAt(s, i))) return i;\n return digitRunEnd(s, i + 1);\n}\n\n/**\n * A natural number written canonically (`^(0|[1-9][0-9]*)$`): the keys JS objects move\n * first, ahead of their source order.\n *\n * @ensures exactly the model's CanonicalNat, stated over the codes themselves so an importer\n * can use it (a contract naming `digitsFrom` can't be resolved there, models/LSC-GAPS.md)\n */\nexport function isCanonicalNat(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s === \"0\" || (s.length > 0 && s.charCodeAt(0) >= 49 && s.charCodeAt(0) <= 57 && forall(k: nat, (1 <= k && k < s.length) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))))\n if (s === \"0\") return true;\n const first = codeAt(s, 0);\n return first >= 49 && first <= 57 && digitsFrom(s, 1);\n}\n\n/**\n * The value of a run of decimal digits, most significant first (\"\" is 0).\n *\n * @requires ∀ k ∈ [0, |s|). isDigit(s[k])\n * @ensures exactly the model's DigitsValue (proved in links/utils-strings.dfy)\n */\nexport function digitsValue(s: string): number {\n //@ verify\n //@ requires forall(k: nat, k < s.length ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))\n //@ decreases s.length\n //@ ensures \\result >= 0\n if (s.length === 0) return 0;\n return digitsValue(s.slice(0, s.length - 1)) * 10 + (s.charCodeAt(s.length - 1) - 48);\n}\n\n/**\n * What a number from the environment means (owner 2026-11-04: a bad one fails at start):\n * \"default\" when unset (\"\": the wrapper reads a missing variable as \"\"), \"value\" when it is\n * a canonical natural number at least `min` (its value is `digitsValue(raw)`), and \"bad\"\n * otherwise: a sign, a space, a fraction, an exponent, hex, text, or below `min`.\n *\n * @ensures exactly the model's EnvNumberOf (proved in links/utils-strings.dfy)\n */\nexport function envNumberKind(raw: string, min: number): string {\n //@ verify\n //@ type min nat\n //@ ensures raw === \"\" ==> \\result === \"default\"\n //@ ensures (raw !== \"\" && !isCanonicalNat(raw)) ==> \\result === \"bad\"\n if (raw === \"\") return \"default\";\n if (!isCanonicalNat(raw)) return \"bad\";\n return digitsValue(raw) < min ? \"bad\" : \"value\";\n}\n\n/**\n * A canonical natural number's value, 0 for any other text (a count written as JSON).\n *\n * @ensures exactly the model's CanonicalNatValue (in the link: `digitsValue` needs the digits\n * isCanonicalNat's contract gives, which a contract can't call for); 0 for other text\n */\nexport function canonicalNatValue(s: string): number {\n //@ verify\n //@ ensures \\result >= 0\n //@ ensures !isCanonicalNat(s) ==> \\result === 0\n if (!isCanonicalNat(s)) return 0;\n return digitsValue(s);\n}\n\n/**\n * The first index ≥ `i` holding a line terminator, or |s|: where a regex `.+` started at `i`\n * stops.\n *\n * @ensures i ≤ result ≤ |s| ∧ no terminator in s[i, result) ∧ (result = |s| ∨ terminator at result)\n */\nexport function lineEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> !isLineTerminator(s.charCodeAt(k)))\n //@ ensures \\result < s.length ==> isLineTerminator(s.charCodeAt(\\result))\n if (i === s.length || isLineTerminator(s.charCodeAt(i))) return i;\n return lineEnd(s, i + 1);\n}\n\n/**\n * The largest p with lo ≤ p < hi whose character is not a line terminator, or -1: where a\n * backtracking regex `.` can start.\n *\n * @ensures result = -1 ∨ (lo ≤ result < hi ∧ ¬terminator(s[result]) ∧ only terminators in (result, hi))\n */\nexport function lastLineCharBelow(s: string, hi: number, lo: number): number {\n //@ verify\n //@ type hi nat\n //@ type lo nat\n //@ requires 0 <= lo && 0 <= hi && hi <= s.length\n //@ decreases hi\n //@ ensures \\result === -1 || (lo <= \\result && \\result < hi)\n //@ ensures \\result >= 0 ==> !isLineTerminator(s.charCodeAt(\\result))\n //@ ensures \\result >= 0 ==> forall(k: nat, (\\result < k && k < hi) ==> isLineTerminator(s.charCodeAt(k)))\n //@ ensures \\result === -1 ==> forall(k: nat, (lo <= k && k < hi) ==> isLineTerminator(s.charCodeAt(k)))\n if (hi <= lo) return -1;\n if (!isLineTerminator(s.charCodeAt(hi - 1))) return hi - 1;\n return lastLineCharBelow(s, hi - 1, lo);\n}\n\n/**\n * Nothing but JS whitespace (`s.trim() === \"\"`).\n *\n * @ensures exactly the model's Blank\n */\nexport function isBlank(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> s.trim() === \"\"\n return s.trim() === \"\";\n}\n\n/**\n * The first index ≥ `i` where `x` occurs in `s`, or -1 (JS `s.indexOf(x, i)` for i ≤ |s|).\n *\n * @ensures result = -1 ∨ (i ≤ result ∧ s[result, result + |x|) = x) — and the first such\n * index: links/utils-strings.dfy proves it is exactly the model's IndexOfFrom (lsc can't\n * give the \"no earlier match\" quantifier a trigger)\n */\nexport function indexOfFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result + x.length <= s.length)\n //@ ensures \\result >= 0 ==> s.slice(\\result, \\result + x.length) === x\n // A match here, else the end, else the next index: stopping at `i === |s|` (not \"x no\n // longer fits\") leaves no bound whose slip a later, harmless step would hide\n if (startsWithAt(s, x, i)) return i;\n if (i === s.length) return -1;\n return indexOfFrom(s, x, i + 1);\n}\n\n/**\n * `indexOfFrom` as a loop: the same answer at a constant stack depth, for text long enough that\n * one frame per character would overflow the stack (a rendered page, 50–60 KB with its inlined\n * stylesheet). Specs and links use `indexOfFrom`; runtime scans over long text use this.\n *\n * @ensures result = indexOfFrom(s, x, i)\n */\nexport function findFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ ensures \\result === indexOfFrom(s, x, i)\n let k = i;\n while (k !== s.length) {\n //@ invariant i <= k && k <= s.length\n //@ invariant indexOfFrom(s, x, k) === indexOfFrom(s, x, i)\n //@ decreases s.length - k\n if (startsWithAt(s, x, k)) return k;\n k = k + 1;\n }\n return startsWithAt(s, x, k) ? k : -1;\n}\n\n/**\n * `indexOfCode` as a loop: the same answer at a constant stack depth (see `findFrom`).\n *\n * @ensures result = indexOfCode(s, code, from)\n */\nexport function findCodeFrom(s: string, code: number, from: number): number {\n //@ verify\n //@ type from nat\n //@ requires code >= 0 && from >= 0\n //@ ensures \\result === indexOfCode(s, code, from)\n let k = from;\n while (k < s.length) {\n //@ invariant from <= k\n //@ invariant indexOfCode(s, code, k) === indexOfCode(s, code, from)\n //@ decreases s.length - k\n if (s.charCodeAt(k) === code) return k;\n k = k + 1;\n }\n return -1;\n}\n\n/**\n * How many times `x` occurs in `s` from `i` on, left to right without overlaps (repeated JS\n * `s.indexOf(x, at + x.length)`).\n *\n * @requires |x| > 0\n * @ensures result ≥ 0 — exactly the model's CountFrom (links/utils-strings.dfy)\n */\nexport function countFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires x.length > 0 && i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result >= 0\n const at = indexOfFrom(s, x, i);\n if (at === -1) return 0;\n return 1 + countFrom(s, x, at + x.length);\n}\n\n/**\n * `countFrom(s, x, 0)` as a loop: a constant stack depth on long text (see `findFrom`).\n *\n * @requires |x| > 0\n * @ensures result = countFrom(s, x, 0)\n */\nexport function countOf(s: string, x: string): number {\n //@ verify\n //@ requires x.length > 0\n //@ ensures \\result === countFrom(s, x, 0)\n let n = 0;\n let i = 0;\n let at = findFrom(s, x, 0);\n while (at !== -1) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant at === indexOfFrom(s, x, i)\n //@ invariant n + countFrom(s, x, i) === countFrom(s, x, 0)\n //@ decreases s.length - i\n n = n + 1;\n i = at + x.length;\n at = findFrom(s, x, i);\n }\n return n;\n}\n\n/**\n * The text before the first `code`, or all of it when there is none (JS `s.split(c)[0]`).\n *\n * @ensures result = s[0, first code) when s holds one, else s — the model's UntilCode\n */\nexport function untilCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures \\result === (indexOfCode(s, code, 0) >= 0 && indexOfCode(s, code, 0) <= s.length ? s.slice(0, indexOfCode(s, code, 0)) : s)\n const k = indexOfCode(s, code, 0);\n return k >= 0 ? s.slice(0, k) : s;\n}\n\n/**\n * `s` from `i` on split at every `code` (JS `s.split(c)` at i = 0, for a one-character\n * separator): always at least one part.\n *\n * @ensures |result| ≥ 1 — exactly the model's SplitCodeFrom (links/utils-strings.dfy)\n */\nexport function splitCodeFrom(s: string, code: number, i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires code >= 0 && i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result.length > 0\n const k = indexOfCode(s, code, i);\n if (k === -1) return [s.slice(i)];\n return [s.slice(i, k), ...splitCodeFrom(s, code, k + 1)];\n}\n\n/**\n * Every run of JS whitespace in `s` from `i` on as one space (JS `s.replace(/\\s+/g, \" \")` at\n * i = 0).\n *\n * @ensures |result| ≤ |s| − i — exactly the model's CollapseSpacesFrom (links/utils-strings.dfy)\n */\nexport function collapseSpacesFrom(s: string, i: number): string {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result.length <= s.length - i\n if (i === s.length) return \"\";\n if (isJsSpace(s.charCodeAt(i))) return \" \" + collapseSpacesFrom(s, spaceRunEnd(s, i));\n return s.slice(i, i + 1) + collapseSpacesFrom(s, i + 1);\n}\n\n/**\n * `collapseSpacesFrom(s, 0)` at a constant stack depth (a page's text is tens of KB).\n *\n * @ensures result = collapseSpacesFrom(s, 0)\n */\nexport function collapseSpaces(s: string): string {\n //@ verify\n //@ ensures \\result === collapseSpacesFrom(s, 0)\n let out = \"\";\n let i = 0;\n while (i < s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + collapseSpacesFrom(s, i) === collapseSpacesFrom(s, 0)\n //@ decreases s.length - i\n if (isJsSpace(s.charCodeAt(i))) {\n out = out + \" \";\n // the run's end as a loop too: spaceRunEnd takes a frame per space (Fable review 2026-11-06)\n let e = i + 1;\n while (e !== s.length && isJsSpace(s.charCodeAt(e))) {\n //@ invariant i < e && e <= s.length\n //@ invariant forall(k: nat, (i <= k && k < e) ==> isJsSpace(s.charCodeAt(k)))\n //@ decreases s.length - e\n e = e + 1;\n }\n i = e;\n } else {\n out = out + s.slice(i, i + 1);\n i = i + 1;\n }\n }\n return out;\n}\n\n/**\n * `n` spaces.\n *\n * @ensures result = \" \" repeated n times — the model's Spaces\n */\nexport function spaces(n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ decreases n\n //@ ensures \\result.length === n\n //@ ensures forall(k: nat, k < n ==> \\result.charCodeAt(k) === 32)\n // `<= 0`, not `=== 0`: the same for a nat, and a fraction a caller slips in (outside the\n // contract) ends instead of recursing forever (Fable review 2026-11-06: spaces(0.5))\n if (n <= 0) return \"\";\n return \" \" + spaces(n - 1);\n}\n\n/**\n * A line feed, `\"\\n\"`, for proved text that spans lines: lsc emits a `\"\\n\"` escape raw, which\n * Dafny cannot parse (models/LSC-GAPS.md), so the contract pins it by code unit and the body is\n * a template literal holding the line break itself.\n *\n * @ensures result = \"\\n\" — one code unit, 10\n */\nexport function lineFeed(): string {\n //@ verify\n //@ ensures \\result.length === 1 && \\result.charCodeAt(0) === 10\n return `\n`;\n}\n\n/**\n * `s` padded on the left with spaces to `width` (JS `s.padStart(width)`).\n *\n * @ensures result = Spaces(width − |s|) + s when width > |s|, else s\n */\nexport function padLeft(s: string, width: number): string {\n //@ verify\n //@ ensures width <= s.length ==> \\result === s\n // width > |s| ⟹ spaces(width − |s|) + s: a hand ensures in strings.dfy, so importers'\n // axioms name no helper (models/LSC-GAPS.md). Math.max, not a ternary: at width = |s|\n // both branches agree (spaces(0) is \"\"), so `>` vs `>=` would be equivalent.\n return spaces(Math.max(width - s.length, 0)) + s;\n}\n\n/**\n * `s` padded on the right with spaces to `width` (JS `s.padEnd(width)`).\n *\n * @ensures result = s + Spaces(width − |s|) when width > |s|, else s\n */\nexport function padRight(s: string, width: number): string {\n //@ verify\n //@ ensures width <= s.length ==> \\result === s\n // width > |s| ⟹ s + spaces(width − |s|): a hand ensures in strings.dfy, as padLeft's.\n return s + spaces(Math.max(width - s.length, 0));\n}\n\n/**\n * An optional part of a key: `tag` then `text`, or nothing when `text` is empty, so an absent\n * part never leaves a bare tag.\n *\n * @ensures result = \"\" when text = \"\", else tag + text — exactly the model's KeyPart\n */\nexport function keyPart(tag: string, text: string): string {\n //@ verify\n //@ ensures \\result === (text === \"\" ? \"\" : tag + text)\n return text === \"\" ? \"\" : tag + text;\n}\n\n/**\n * Two texts joined by one space: the one rule behind a loader key's `<column> <direction>`, a\n * sync line's `METHOD /path` and a field's description then note.\n *\n * @ensures result = a + \" \" + b — exactly the model's SpaceJoined\n */\nexport function spaceJoined(a: string, b: string): string {\n //@ verify\n //@ ensures \\result === a + \" \" + b\n return a + \" \" + b;\n}\n\n/**\n * The first code point of `w` as text: a surrogate pair whole, else the first code unit, or \"\"\n * (Fable review 2026-11-06: an astral initial was a lone surrogate).\n *\n * @ensures exactly the model's FirstChar\n */\nexport function firstCodePoint(w: string): string {\n //@ verify\n //@ ensures \\result === ((w.length >= 2 && w.charCodeAt(0) >= 55296 && w.charCodeAt(0) <= 56319 && w.charCodeAt(1) >= 56320 && w.charCodeAt(1) <= 57343) ? w.slice(0, 2) : (w.length > 0 ? w.slice(0, 1) : \"\"))\n if (w.length >= 2) {\n const hi = w.charCodeAt(0);\n const lo = w.charCodeAt(1);\n if (hi >= 55296 && hi <= 56319 && lo >= 56320 && lo <= 57343) return w.slice(0, 2);\n }\n return w.length > 0 ? w.slice(0, 1) : \"\";\n}\n\n/**\n * An ASCII letter (A-Z, a-z) somewhere in `w` from `i` on (moved from readability.ts\n * 2026-11-06, so `readableWords`' contract can name it and importers resolve it).\n *\n * @ensures result ⟺ ∃ k ∈ [i, |w|). w[k] ∈ A-Z ∪ a-z — at i = 0 exactly the model's HasAsciiLetter\n */\nexport function hasAsciiLetterFrom(w: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases w.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < w.length && ((w.charCodeAt(k) >= 65 && w.charCodeAt(k) <= 90) || (w.charCodeAt(k) >= 97 && w.charCodeAt(k) <= 122)))\n if (i >= w.length) return false;\n const c = w.charCodeAt(i);\n if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) return true;\n return hasAsciiLetterFrom(w, i + 1);\n}\n\n/**\n * `s` with a-z uppercased and every other character kept, the mirror of `lowerAscii`: JS's\n * `toUpperCase()` also maps non-ASCII letters (ß becomes \"SS\").\n *\n * @ensures |result| = |s| ∧ ∀ k < |s|. result[k] = (s[k] ∈ a-z ? s[k] − 32 : s[k]) — a-z\n * raised, every other code unit unchanged; exactly the model's UpperAscii in the link\n */\nexport function upperAscii(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures \\result.length === s.length\n //@ ensures forall(k: nat, k < s.length ==> \\result.charCodeAt(k) === ((s.charCodeAt(k) >= 97 && s.charCodeAt(k) <= 122) ? s.charCodeAt(k) - 32 : s.charCodeAt(k)))\n if (s.length === 0) return \"\";\n const c = s.charCodeAt(0);\n const head =\n c >= 97 && c <= 122 ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".slice(c - 97, c - 96) : s.slice(0, 1);\n return head + upperAscii(s.slice(1));\n}\n","//@ backend dafny\nimport { includesFrom } from \"./includes\";\nimport { compareFrom, endsWith } from \"./strings\";\n\n/* Pure list helpers, verified with LemmaScript → Dafny (model: models/Utils.dfy; link:\n models/links/utils-lists.dfy). */\n\n/**\n * The items from index `i` joined by `sep` (JS `xs.join(sep)` at i = 0).\n *\n * @ensures exactly the model's JoinFrom\n */\nexport function joinFrom(xs: string[], sep: string, i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result === \"\"\n //@ ensures i + 1 === xs.length ==> \\result === xs[i]\n //@ ensures i + 1 < xs.length ==> (\\result.length >= xs[i].length + sep.length && \\result.slice(0, xs[i].length + sep.length) === xs[i] + sep)\n if (i >= xs.length) return \"\";\n return joinRange(xs, sep, i, xs.length);\n}\n\n/**\n * The items from `lo` up to `hi` (at least one) joined by `sep`, by halves: a list of n items\n * recurses log n deep, so a generated file of many thousand lines fits the stack.\n *\n * @ensures = the model's JoinFrom(xs[..hi], sep, lo) (links/utils-lists.dfy, by JoinFromSplits)\n */\nfunction joinRange(xs: string[], sep: string, lo: number, hi: number): string {\n //@ verify\n //@ type lo nat\n //@ type hi nat\n //@ requires lo < hi && hi <= xs.length\n //@ decreases hi - lo\n //@ ensures hi === lo + 1 ==> \\result === xs[lo]\n if (hi - lo === 1) return xs[lo] as string;\n const mid = lo + Math.floor((hi - lo) / 2);\n return joinRange(xs, sep, lo, mid) + sep + joinRange(xs, sep, mid, hi);\n}\n\n/**\n * The first index ≥ `i` holding `x`, or -1 (JS `xs.indexOf(x, i)`): how a table of parallel\n * lists is read.\n *\n * @ensures result = -1 ∨ (i ≤ result < |xs| ∧ xs[result] = x) — and the first such index: the\n * model's ItemIndexFrom (links/utils-lists.dfy)\n */\nexport function itemIndexFrom(xs: string[], x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result < xs.length && xs[\\result] === x)\n //@ ensures \\result === -1 ==> forall(k: nat, (i <= k && k < xs.length) ==> xs[k] !== x)\n //@ ensures \\result >= 0 ==> forall(k: nat, (i <= k && k < \\result) ==> xs[k] !== x)\n if (i >= xs.length) return -1;\n return (xs[i] as string) === x ? i : itemIndexFrom(xs, x, i + 1);\n}\n\n/**\n * The sum of `xs[i..]`, 0 past the end (JS `xs.slice(i).reduce((a, b) => a + b, 0)`).\n *\n * @ensures result = Σ xs[i..] — exactly the model's SumFrom\n */\nexport function sumFrom(xs: number[], i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures \\result === (i >= xs.length ? 0 : xs[i] + sumFrom(xs, i + 1))\n if (i >= xs.length) return 0;\n return (xs[i] as number) + sumFrom(xs, i + 1);\n}\n\n/**\n * Whether `x` is one of `xs` from index `i` on (JS `xs.includes(x)` at i = 0).\n *\n * @ensures result ⟺ ∃ k. i ≤ k < |xs| ∧ xs[k] = x — exactly the model's HasItemFrom\n */\nexport function hasItemFrom(xs: string[], x: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && xs[k] === x)\n // `===`, not `>=`: past the end xs[i] is undefined, never x, so `>=` vs `>` is equivalent\n if (i === xs.length) return false;\n if ((xs[i] as string) === x) return true;\n return hasItemFrom(xs, x, i + 1);\n}\n\n/**\n * Whether the number `x` is one of `xs` from index `i` on (JS `xs.includes(x)` at i = 0, for\n * numbers).\n *\n * @ensures result ⟺ ∃ k. i ≤ k < |xs| ∧ xs[k] = x — exactly the model's HasNumberFrom\n */\nexport function hasNumberFrom(xs: number[], x: number, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && xs[k] === x)\n if (i === xs.length) return false;\n if ((xs[i] as number) === x) return true;\n return hasNumberFrom(xs, x, i + 1);\n}\n\n/**\n * Whether `s` ends with one of `xs` from index `i` on (a regex `(a|b|…)$` at i = 0).\n *\n * @ensures exactly the model's EndsWithAnyFrom\n */\nexport function endsWithAnyFrom(s: string, xs: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && endsWith(s, xs[k]))\n if (i === xs.length) return false;\n if (endsWith(s, xs[i] as string)) return true;\n return endsWithAnyFrom(s, xs, i + 1);\n}\n\n/**\n * Whether one of `xs` from index `i` on occurs in `s` (a regex `(a|b|…)` at i = 0).\n *\n * @ensures exactly the model's IncludesAnyFrom\n */\nexport function includesAnyFrom(s: string, xs: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && includesFrom(s, xs[k], 0))\n if (i === xs.length) return false;\n if (includesFrom(s, xs[i] as string, 0)) return true;\n return includesAnyFrom(s, xs, i + 1);\n}\n\n/**\n * The items of `xs` from index `i` that `allowed` doesn't hold, in order (JS\n * `xs.filter((x) => !allowed.includes(x))` at i = 0).\n *\n * @ensures exactly the model's NotInFrom (NotInFromIsTheUnknown: the unknown ones, all of them)\n */\nexport function notInFrom(xs: string[], allowed: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result.length === 0\n if (i >= xs.length) return [];\n const rest = notInFrom(xs, allowed, i + 1);\n return hasItemFrom(allowed, xs[i] as string, 0) ? rest : [xs[i] as string, ...rest];\n}\n\n/**\n * Whether `x` is one of the first `k` items of `xs` (JS `xs.slice(0, k).includes(x)`).\n *\n * @ensures result ⟺ ∃ j < k. xs[j] = x — exactly the model's HasItemBelow\n */\nexport function hasItemBelow(xs: string[], x: string, k: number): boolean {\n //@ verify\n //@ type k nat\n //@ requires k >= 0 && k <= xs.length\n //@ decreases k\n //@ ensures \\result <==> exists(j: nat, j < k && xs[j] === x)\n if (k === 0) return false;\n if ((xs[k - 1] as string) === x) return true;\n return hasItemBelow(xs, x, k - 1);\n}\n\n/**\n * The items of `xs` from index `i` that repeat an earlier item, in order (at i = 0, every\n * duplicate after its first; none ⟺ the items are unique).\n *\n * @ensures exactly the model's RepeatsFrom (RepeatsFromEmpty: none exactly when unique)\n */\nexport function repeatsFrom(xs: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result.length === 0\n if (i >= xs.length) return [];\n const rest = repeatsFrom(xs, i + 1);\n return hasItemBelow(xs, xs[i] as string, i) ? [xs[i] as string, ...rest] : rest;\n}\n\n/**\n * The items of `xs` from index `i` that no earlier item repeats, in order (at i = 0, JS\n * `[...new Set(xs)]`: each item once, first occurrence kept).\n *\n * @ensures exactly the model's FirstsFrom\n */\nexport function firstsFrom(xs: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result.length === 0\n //@ ensures forall(j: nat, forall(k: nat, (j < k && k < \\result.length) ==> \\result[j] !== \\result[k]))\n if (i >= xs.length) return [];\n const rest = firstsFrom(xs, i + 1);\n return hasItemBelow(xs, xs[i] as string, i) ? rest : [xs[i] as string, ...rest];\n}\n\n/**\n * At most the first `n` items (JS `xs.slice(0, n)` for n ≥ 0).\n *\n * @ensures exactly the model's TakeAtMost\n */\nexport function takeAtMost(xs: string[], n: number): string[] {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === (n < xs.length ? xs.slice(0, n) : xs)\n return n < xs.length ? xs.slice(0, n) : xs;\n}\n\n/**\n * Whether two number lists are equal from index `i` on (the whole lists at i = 0).\n *\n * @ensures result ⟺ |a| = |b| ∧ ∀ k ∈ [i, |a|). a[k] = b[k] — exactly the model's\n * SameNumbersFrom\n */\nexport function sameNumbersFrom(a: number[], b: number[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= a.length\n //@ decreases a.length - i\n //@ ensures \\result <==> (a.length === b.length && forall(k: nat, i <= k && k < a.length ==> a[k] === b[k]))\n if (a.length !== b.length) return false;\n if (i === a.length) return true;\n return (a[i] as number) === (b[i] as number) && sameNumbersFrom(a, b, i + 1);\n}\n\n/**\n * Whether two text lists are equal from index `i` on (the whole lists at i = 0, as their\n * `JSON.stringify` texts compare).\n *\n * @ensures result ⟺ |a| = |b| ∧ ∀ k ∈ [i, |a|). a[k] = b[k] — exactly the model's\n * SameTextsFrom\n */\nexport function sameTextsFrom(a: string[], b: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= a.length\n //@ decreases a.length - i\n //@ ensures \\result <==> (a.length === b.length && forall(k: nat, i <= k && k < a.length ==> a[k] === b[k]))\n if (a.length !== b.length) return false;\n if (i === a.length) return true;\n return (a[i] as string) === (b[i] as string) && sameTextsFrom(a, b, i + 1);\n}\n\n/**\n * The texts in code-unit order (JS's default `sort`, stable: of two equal texts the earlier\n * stays first).\n *\n * @ensures exactly the model's SortedTexts (in the link); the same length\n */\nexport function sortedTexts(xs: string[]): string[] {\n //@ verify\n //@ ensures \\result.length === xs.length\n if (xs.length === 0) return [];\n return insertText(xs[0] as string, sortedTexts(xs.slice(1)));\n}\n\n/**\n * `x` placed into sorted texts before the first it doesn't sort after.\n *\n * @ensures exactly the model's InsertText (in the link); one longer\n */\nexport function insertText(x: string, sorted: string[]): string[] {\n //@ verify\n //@ ensures \\result.length === sorted.length + 1\n if (sorted.length === 0) return [x];\n const first = sorted[0] as string;\n if (compareFrom(x, first, 0) <= 0) return [x, ...sorted];\n return [first, ...insertText(x, sorted.slice(1))];\n}\n","//@ backend dafny\nimport { codeAt, indexOfFrom } from \"./strings\";\n\n/* Whole-string rewrites, verified with LemmaScript → Dafny (model: models/Utils.dfy \"text\n replacement\"; link: models/links/utils-replace.dfy). Each has a recursive spec (for\n proofs and tests) and a loop proved to build exactly it (for callers: its depth doesn't\n grow with the input). The `\\result === spec(s)` clause of each loop is a hand `ensures`\n in replace.dfy, as utils `escapeHtml`'s is: lsc would put it in every importer's axiom,\n where this file's own spec isn't emitted. */\n\n// --- One substitution rule (model `Utils.Substituted`, 2026-11-03): each code unit found in a\n// table is replaced by its text, every other kept. replaceCode, pointerToken, escapeHtml and\n// the generator's look-alike fold are this rule, each with its own table.\n\n/**\n * The first index ≥ `i` holding `c` in `codes`, or -1.\n *\n * @ensures result = -1 ∨ (i ≤ result < |codes| ∧ codes[result] = c) — the model's CodeIndex\n */\nexport function codeIndex(codes: number[], c: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i <= codes.length\n //@ decreases codes.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result < codes.length && codes[\\result] === c)\n // `===`, not `>=`: past the end codes[i] is undefined, never c, so `>=` vs `>` is equivalent\n if (i === codes.length) return -1;\n return (codes[i] as number) === c ? i : codeIndex(codes, c, i + 1);\n}\n\n/** `s` with each code unit in `codes` replaced by its text, recursively: the spec `substitute` builds. */\nexport function substitutedText(s: string, codes: number[], texts: string[]): string {\n //@ verify\n //@ decreases s.length\n //@ ensures s.length === 0 ==> \\result === \"\"\n //@ ensures codes.length === 0 ==> \\result === s\n if (s.length === 0) return \"\";\n const k = codeIndex(codes, s.charCodeAt(0), 0);\n const head = k >= 0 && k < texts.length ? (texts[k] as string) : s.slice(0, 1);\n return head + substitutedText(s.slice(1), codes, texts);\n}\n\n/**\n * `s` with each code unit in `codes` replaced by the text at its first index there, every\n * other kept. A loop, so its depth doesn't grow with the input.\n *\n * @ensures result = substitutedText(s, codes, texts) — the model's Substituted (a hand\n * ensures in replace.dfy: importers can't resolve substitutedText)\n * @ensures |s| = 0 ⟹ result = \"\" ∧ |codes| = 0 ⟹ result = s — no table, no change\n */\nexport function substitute(s: string, codes: number[], texts: string[]): string {\n //@ verify\n //@ ensures s.length === 0 ==> \\result === \"\"\n //@ ensures codes.length === 0 ==> \\result === s\n let out = \"\";\n // `!==`, not `<`: one step past the end reads NaN and adds \"\", so `<=` would be equivalent\n for (let i = 0; i !== s.length; i++) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + substitutedText(s.slice(i), codes, texts) === substitutedText(s, codes, texts)\n //@ decreases s.length - i\n const k = codeIndex(codes, s.charCodeAt(i), 0);\n out = k >= 0 && k < texts.length ? out + (texts[k] as string) : out + s.slice(i, i + 1);\n }\n return out;\n}\n\n/**\n * `s` with every `from` code unit replaced by `to`, recursively: the one-entry table.\n *\n * @ensures no `from` survives when `to` holds none — exactly the model's ReplaceCode in the link\n */\nexport function replacedCode(s: string, from: number, to: string): string {\n //@ verify\n //@ ensures forall(j: nat, j < to.length ==> to.charCodeAt(j) !== from) ==> forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== from)\n return substitutedText(s, [from], [to]);\n}\n\n/**\n * `s` with every `from` code unit replaced by `to` (`replaceAll` of one character).\n *\n * @ensures no `from` survives when `to` holds none (ReplaceCodeRemoves) — = replacedCode(s,\n * from, to), the model's ReplaceCode, as a hand ensures in replace.dfy\n */\nexport function replaceCode(s: string, from: number, to: string): string {\n //@ verify\n //@ ensures forall(j: nat, j < to.length ==> to.charCodeAt(j) !== from) ==> forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== from)\n return substitute(s, [from], [to]);\n}\n\n/**\n * `s` with its first `find` replaced by `put`; no match leaves it: JS `s.replace(find, put)` for\n * a string `find`, when `put` holds no `$` (JS reads `$&`, `$1` there as a pattern).\n *\n * @ensures exactly the model's ReplaceFirst\n */\nexport function replaceFirst(s: string, find: string, put: string): string {\n //@ verify\n //@ ensures \\result === (indexOfFrom(s, find, 0) < 0 ? s : s.slice(0, indexOfFrom(s, find, 0)) + put + s.slice(indexOfFrom(s, find, 0) + find.length))\n const i = indexOfFrom(s, find, 0);\n if (i < 0) return s;\n return s.slice(0, i) + put + s.slice(i + find.length);\n}\n\n/**\n * `s` with every `find` replaced by `put`, left to right without overlaps: JS\n * `s.split(find).join(put)` for a non-empty `find` (tests pin the two). Recursive, with no\n * loop twin: its callers fill short templates (the SDK's registry paths), so the depth stays\n * small; a long-input caller would need one.\n *\n * @requires |find| > 0 — split(\"\") splits into characters, a different rule\n * @ensures text shorter than `find` is unchanged, and so is any text when `put` = `find` —\n * exactly the model's ReplaceText in the link\n */\nexport function replaceText(s: string, find: string, put: string): string {\n //@ verify\n //@ requires find.length > 0\n //@ decreases s.length\n //@ ensures s.length < find.length ==> \\result === s\n //@ ensures put === find ==> \\result === s\n if (s.length < find.length) return s;\n if (s.slice(0, find.length) === find) {\n return put + replaceText(s.slice(find.length), find, put);\n }\n return s.slice(0, 1) + replaceText(s.slice(1), find, put);\n}\n\n/**\n * A JSON Pointer token of `s`, recursively: `~` → `~0`, `/` → `~1`.\n *\n * @ensures never holds \"/\" — exactly the model's PointerToken in the link\n */\nexport function pointerTokenOf(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== 47)\n return substitutedText(s, [126, 47], [\"~0\", \"~1\"]);\n}\n\n/**\n * `s` as a JSON Pointer reference token (RFC 6901 §3): `~` as `~0`, `/` as `~1`.\n *\n * @ensures never holds \"/\" (PointerTokenHasNoSlash) — = pointerTokenOf(s), the model's\n * PointerToken, as a hand ensures in replace.dfy\n */\nexport function pointerToken(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== 47)\n return substitute(s, [126, 47], [\"~0\", \"~1\"]);\n}\n\n/**\n * The escape of `s`, recursively: each `&` `<` `>` `\"` `'` as its entity.\n *\n * @ensures no `<` `>` `\"` `'` in result — exactly the model's EscapeHtml in the link\n */\nexport function escapedText(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n return substitutedText(s, [38, 60, 62, 34, 39], [\"&\", \"<\", \">\", \""\", \"'\"]);\n}\n\n/**\n * Escape text for an HTML body or a double-quoted attribute.\n *\n * @ensures result = escapedText(value) — exactly the model's EscapeHtml (a hand ensures in\n * replace.dfy, since importers can't see escapedText)\n * @ensures ∀ k < |result|. result[k] ∉ {\"<\", \">\", \"\\\"\", \"'\"} — nothing in the output can\n * open a tag or close the attribute; \"&\" appears only as the start of an entity\n */\nexport function escapeHtml(value: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n return substitute(value, [38, 60, 62, 34, 39], [\"&\", \"<\", \">\", \""\", \"'\"]);\n}\n\n/**\n * The code units a JSON string escapes: `\"`, `\\`, then the control characters with short\n * escapes (\\b \\t \\n \\f \\r), then the other code units below 0x20.\n *\n * @ensures exactly the model's JsonCodes\n */\nexport function jsonCodes(): number[] {\n //@ verify\n //@ ensures \\result === [34, 92, 8, 9, 10, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]\n return [\n 34, 92, 8, 9, 10, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31,\n ];\n}\n\n/**\n * Each `jsonCodes` entry's escape (ECMA-262 QuoteJSONString; lowercase hex, as JSON.stringify).\n *\n * @ensures exactly the model's JsonTexts\n */\nexport function jsonTexts(): string[] {\n //@ verify\n //@ ensures \\result === [\"\\\\\\\"\", \"\\\\\\\\\", \"\\\\b\", \"\\\\t\", \"\\\\n\", \"\\\\f\", \"\\\\r\", \"\\\\u0000\", \"\\\\u0001\", \"\\\\u0002\", \"\\\\u0003\", \"\\\\u0004\", \"\\\\u0005\", \"\\\\u0006\", \"\\\\u0007\", \"\\\\u000b\", \"\\\\u000e\", \"\\\\u000f\", \"\\\\u0010\", \"\\\\u0011\", \"\\\\u0012\", \"\\\\u0013\", \"\\\\u0014\", \"\\\\u0015\", \"\\\\u0016\", \"\\\\u0017\", \"\\\\u0018\", \"\\\\u0019\", \"\\\\u001a\", \"\\\\u001b\", \"\\\\u001c\", \"\\\\u001d\", \"\\\\u001e\", \"\\\\u001f\"]\n return [\n '\\\\\"',\n \"\\\\\\\\\",\n \"\\\\b\",\n \"\\\\t\",\n \"\\\\n\",\n \"\\\\f\",\n \"\\\\r\",\n \"\\\\u0000\",\n \"\\\\u0001\",\n \"\\\\u0002\",\n \"\\\\u0003\",\n \"\\\\u0004\",\n \"\\\\u0005\",\n \"\\\\u0006\",\n \"\\\\u0007\",\n \"\\\\u000b\",\n \"\\\\u000e\",\n \"\\\\u000f\",\n \"\\\\u0010\",\n \"\\\\u0011\",\n \"\\\\u0012\",\n \"\\\\u0013\",\n \"\\\\u0014\",\n \"\\\\u0015\",\n \"\\\\u0016\",\n \"\\\\u0017\",\n \"\\\\u0018\",\n \"\\\\u0019\",\n \"\\\\u001a\",\n \"\\\\u001b\",\n \"\\\\u001c\",\n \"\\\\u001d\",\n \"\\\\u001e\",\n \"\\\\u001f\",\n ];\n}\n\n/**\n * A string as JSON text, as `JSON.stringify(s)` writes it for well-formed text: quoted, `\"`\n * and `\\` backslashed, control characters escaped. A lone surrogate is kept as it is\n * (JSON.stringify writes `\\udxxx`); callers pass well-formed text. Built by the `substitute`\n * loop, so its depth doesn't grow with the text (an FAQ answer can be long; Fable review\n * 2026-11-06); importers still see a function (its contract as an axiom), so their premise\n * `jsonString(s) == Utils.JsonString(s)` stands.\n *\n * @ensures result = `\"` + substitutedText(s, jsonCodes(), jsonTexts()) + `\"` — a hand ensures in\n * replace.dfy; the model's JsonString (proved in links/utils-replace.dfy)\n * @ensures result starts and ends with `\"`\n */\nexport function jsonString(s: string): string {\n //@ verify\n //@ ensures \\result.length >= 2 && \\result.charCodeAt(0) === 34 && \\result.charCodeAt(\\result.length - 1) === 34\n return '\"' + substitute(s, jsonCodes(), jsonTexts()) + '\"';\n}\n\n/**\n * `s` with every `*` `/` pair written `* /`, recursively: the spec `commentSafe` builds.\n *\n * @ensures no \"*\" \"/\" pair in result — exactly the model's CommentSafe in the link\n */\nexport function commentSafeOf(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures forall(k: nat, k + 1 < \\result.length ==> !(\\result.charCodeAt(k) === 42 && \\result.charCodeAt(k + 1) === 47))\n if (s.length === 0) return \"\";\n if (codeAt(s, 0) === 42 && codeAt(s, 1) === 47) {\n return \"* /\" + commentSafeOf(s.slice(2));\n }\n return s.slice(0, 1) + commentSafeOf(s.slice(1));\n}\n\n/**\n * Text safe inside a `/* … *\\/` comment: every `*` `/` pair written `* /`.\n *\n * @ensures no \"*\" \"/\" pair in result: nothing can close the comment — = commentSafeOf(s), the\n * model's CommentSafe, as a hand ensures in replace.dfy\n */\nexport function commentSafe(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k + 1 < \\result.length ==> !(\\result.charCodeAt(k) === 42 && \\result.charCodeAt(k + 1) === 47))\n let out = \"\";\n let i = 0;\n while (i !== s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + commentSafeOf(s.slice(i)) === commentSafeOf(s)\n //@ decreases s.length - i\n if (codeAt(s, i) === 42 && codeAt(s, i + 1) === 47) {\n out = out + \"* /\";\n i = i + 2;\n } else {\n out = out + s.slice(i, i + 1);\n i = i + 1;\n }\n }\n return out;\n}\n","//@ backend dafny\nimport { joinFrom } from \"./lists\";\nimport { jsonString } from \"./replace\";\n\n/* JSON text written by hand (`jsonPair`, `jsonObject`, `jsonArray`, with `jsonString` in\n replace.ts; model \"JSON text\") and `parseJsonSafe`'s refusal (`unsafeJsonInteger`,\n `unsafeIntegerText`; model \"JSON values\"), proved and linked (models/links/utils-json.dfy).\n The helpers over parsed values (`unknown`) are @atlas/json-values' (moved 2026-11-06, so\n every function here is proved). */\n\n/**\n * An object member: the key as a JSON string, then the value's own JSON text.\n *\n * @ensures exactly the model's JsonPair\n */\nexport function jsonPair(key: string, value: string): string {\n //@ verify\n //@ ensures \\result === jsonString(key) + \":\" + value\n return jsonString(key) + \":\" + value;\n}\n\n/**\n * An object member whose value is a string.\n *\n * @ensures exactly the model's JsonTextPair\n */\nexport function jsonTextPair(key: string, value: string): string {\n //@ verify\n //@ ensures \\result === jsonString(key) + \":\" + jsonString(value)\n return jsonString(key) + \":\" + jsonString(value);\n}\n\n/**\n * An object of members already written as JSON text (`jsonPair`), in order.\n *\n * @ensures exactly the model's JsonObject — proved in links/utils-json.dfy\n */\nexport function jsonObject(pairs: string[]): string {\n //@ verify\n //@ ensures \\result === \"{\" + joinFrom(pairs, \",\", 0) + \"}\"\n return \"{\" + joinFrom(pairs, \",\", 0) + \"}\";\n}\n\n/**\n * An array of items already written as JSON text, in order.\n *\n * @ensures exactly the model's JsonArray — proved in links/utils-json.dfy\n */\nexport function jsonArray(items: string[]): string {\n //@ verify\n //@ ensures \\result === \"[\" + joinFrom(items, \",\", 0) + \"]\"\n return \"[\" + joinFrom(items, \",\", 0) + \"]\";\n}\n\n/**\n * The refusal `parseJsonSafe` (`@atlas/json-values`) makes: an integer that isn't a safe one (above 2^53 − 1).\n *\n * @ensures result ⟺ isInteger ∧ ¬isSafe — the model's UnsafeJsonInteger\n */\nexport function unsafeJsonInteger(isInteger: boolean, isSafe: boolean): boolean {\n //@ verify\n //@ ensures \\result <==> (isInteger && !isSafe)\n return isInteger && !isSafe;\n}\n\n/** The refusal's text, naming the value. */\nexport function unsafeIntegerText(value: string): string {\n //@ verify\n //@ ensures \\result === \"JSON integer \" + value + \" is not exact in JavaScript\"\n return \"JSON integer \" + value + \" is not exact in JavaScript\";\n}\n","//@ backend dafny\n\n/* Verified with LemmaScript → Dafny (`pnpm proofs`; hand lemmas in decimal.dfy; model:\n models/Platform.dfy Decimal; link: models/links/foundation-decimal.dfy): how every app\n writes an id as text. Used by services/agr-int-mcp (customer grant ids `<site>|<usersUid>`) and\n packages/joomla-auth (staff grant ids `staff-<Joomla user id>`), so both are one-to-one\n by the same proof. */\n\n/**\n * The decimal digits of `n`, exactly what `String(n)` gives for a non-negative integer\n * (tests pin the two together). Recursive so specs can use it. Injective: different numbers\n * are written differently (lemma DecimalInjective, decimal.dfy; Platform.DecimalInjective).\n *\n * @ensures |result| ≥ 1 ∧ ∀ k < |result|. result[k] ∈ '0'..'9'\n */\nexport function decimal(n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ decreases n\n //@ ensures \\result.length > 0\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57))\n const last = \"0123456789\".slice(n % 10, (n % 10) + 1);\n return n < 10 ? last : decimal(Math.floor(n / 10)) + last;\n}\n\n/**\n * Any integer as `String(n)` writes it: a minus for a negative, then `decimal`'s digits\n * (tests pin it to `String` for safe integers). An id written this way can't change a path.\n *\n * @ensures result is digits, after a \"-\" exactly when n < 0 — never empty, so an id written\n * this way can't change a path; exactly the model's Platform.IntText in the link (a contract\n * naming `decimal` couldn't be resolved by an importer, models/LSC-GAPS.md, so importers that\n * need the exact text take the link's equality as a premise)\n */\nexport function intText(n: number): string {\n //@ verify\n //@ type n int\n //@ ensures \\result.length > 0\n //@ ensures n >= 0 ==> forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57))\n //@ ensures n < 0 ==> (\\result.length > 1 && \\result.charCodeAt(0) === 45 && forall(k: nat, (1 <= k && k < \\result.length) ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57)))\n return n < 0 ? \"-\" + decimal(-n) : decimal(n);\n}\n","//@ backend dafny\nimport { decimal } from \"@atlas/foundation/decimal\";\nimport { jsonObject, jsonPair, jsonTextPair } from \"./json\";\n\n/* The pieces `./json-ld`'s nodes are built from, verified with LemmaScript → Dafny and linked to\n models/Utils.dfy \"structured data\" (models/links/utils-json-ld-items.dfy). They sit in their own\n file so a proved importer of `breadcrumbLd` or `faqLd` gets their contracts too: a contract\n naming a helper of its own file leaves it unresolved in the importer, one from another file\n the body calls comes along (models/LSC-GAPS.md, 2026-11-06). `./json-ld` re-exports them. */\n\n/**\n * The schema.org context every node starts with, then its type: the first two members of a node.\n *\n * @ensures exactly the model's NodeHead\n */\nexport function nodeHead(type: string): string[] {\n //@ verify\n //@ ensures \\result === [jsonTextPair(\"@context\", \"https://schema.org\"), jsonTextPair(\"@type\", type)]\n return [jsonTextPair(\"@context\", \"https://schema.org\"), jsonTextPair(\"@type\", type)];\n}\n\n/** A breadcrumb: its visible name and the absolute URL of its page (the site's canonical). */\nexport interface LdCrumb {\n name: string;\n url: string;\n}\n\n/**\n * A breadcrumb, built here so a proved importer can make one (an object literal of an imported\n * interface is mistranslated; models/LSC-GAPS.md).\n *\n * @ensures the crumb holds exactly name and url\n */\nexport function ldCrumb(name: string, url: string): LdCrumb {\n //@ verify\n //@ ensures \\result.name === name && \\result.url === url\n return { name, url };\n}\n\n/**\n * The trail's ListItems from index `i`, numbered from 1.\n *\n * @ensures exactly the model's CrumbItemsFrom (in the link; a recursive equation can't be an\n * export's contract, models/LSC-GAPS.md)\n */\nexport function crumbItemsFrom(crumbs: LdCrumb[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases crumbs.length - i\n //@ ensures i >= crumbs.length ==> \\result.length === 0\n if (i >= crumbs.length) return [];\n const crumb = crumbs[i] as LdCrumb;\n return [\n jsonObject([\n jsonTextPair(\"@type\", \"ListItem\"),\n jsonPair(\"position\", decimal(i + 1)),\n jsonTextPair(\"name\", crumb.name),\n jsonTextPair(\"item\", crumb.url),\n ]),\n ...crumbItemsFrom(crumbs, i + 1),\n ];\n}\n\n/** A FAQ entry: the question and its plain-text answer, as the page shows them. */\nexport interface Faq {\n question: string;\n answer: string;\n}\n\n/**\n * The FAQ's Questions from index `i`.\n *\n * @ensures exactly the model's FaqItemsFrom (in the link, as for crumbItemsFrom)\n */\nexport function faqItemsFrom(faqs: Faq[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases faqs.length - i\n //@ ensures i >= faqs.length ==> \\result.length === 0\n if (i >= faqs.length) return [];\n const faq = faqs[i] as Faq;\n return [\n jsonObject([\n jsonTextPair(\"@type\", \"Question\"),\n jsonTextPair(\"name\", faq.question),\n jsonPair(\n \"acceptedAnswer\",\n jsonObject([jsonTextPair(\"@type\", \"Answer\"), jsonTextPair(\"text\", faq.answer)]),\n ),\n ]),\n ...faqItemsFrom(faqs, i + 1),\n ];\n}\n","//@ backend dafny\nimport { jsonArray, jsonObject, jsonPair, jsonTextPair } from \"./json\";\nimport { crumbItemsFrom, faqItemsFrom, nodeHead, type Faq, type LdCrumb } from \"./json-ld-items\";\n\nexport { ldCrumb, nodeHead } from \"./json-ld-items\";\nexport type { Faq, LdCrumb } from \"./json-ld-items\";\n\n/* Structured data (JSON-LD): schema.org nodes written with the proved JSON text (`./json`,\n `jsonString`), the bytes JSON.stringify gives for the same object literal (keys in its order).\n Verified with LemmaScript → Dafny and linked to models/Utils.dfy \"structured data\"\n (models/links/utils-json-ld.dfy). The pieces are `./json-ld-items` (re-exported here), so a\n proved importer resolves every name these contracts use. @simpleapps-com/augur-hono and\n @simpleapps-com/augur-utils re-export these; a site builds its own nodes from the pieces and\n passes its own values, and a page puts the text in a `<script type=\"application/ld+json\">`. */\n\n/**\n * A reference to another node by its @id (`{\"@id\": id}`).\n *\n * @ensures exactly the model's IdRef\n */\nexport function idRef(id: string): string {\n //@ verify\n //@ ensures \\result === jsonObject([jsonTextPair(\"@id\", id)])\n return jsonObject([jsonTextPair(\"@id\", id)]);\n}\n\n/**\n * A breadcrumb trail's BreadcrumbList. Build the visible trail from the same crumbs, so the two\n * can't drift.\n *\n * @ensures exactly the model's BreadcrumbLd\n */\nexport function breadcrumbLd(crumbs: LdCrumb[]): string {\n //@ verify\n //@ ensures \\result === jsonObject(nodeHead(\"BreadcrumbList\").concat([jsonPair(\"itemListElement\", jsonArray(crumbItemsFrom(crumbs, 0)))]))\n return jsonObject([\n ...nodeHead(\"BreadcrumbList\"),\n jsonPair(\"itemListElement\", jsonArray(crumbItemsFrom(crumbs, 0))),\n ]);\n}\n\n/**\n * A FAQ page's FAQPage markup: one Question per entry, its answer the plain text. Render the\n * page's FAQ section from the same entries, so the two can't drift.\n *\n * @ensures exactly the model's FaqLd\n */\nexport function faqLd(faqs: Faq[]): string {\n //@ verify\n //@ ensures \\result === jsonObject(nodeHead(\"FAQPage\").concat([jsonPair(\"mainEntity\", jsonArray(faqItemsFrom(faqs, 0)))]))\n return jsonObject([\n ...nodeHead(\"FAQPage\"),\n jsonPair(\"mainEntity\", jsonArray(faqItemsFrom(faqs, 0))),\n ]);\n}\n","//@ backend dafny\n\n/* The JSON-LD builders' decisions (json-ld.ts), verified with LemmaScript → Dafny (model:\n models/AugurUtils.dfy; link: models/links/augur-utils-json-ld-rules.dfy). The callers apply\n JS `trim` and `toUpperCase` (Unicode, no lsc form) before these. */\n\n/**\n * A breadcrumb's position: its index plus one.\n *\n * @ensures exactly the model's BreadcrumbPosition\n */\nexport function breadcrumbPosition(i: number): number {\n //@ verify\n //@ ensures \\result === i + 1\n return i + 1;\n}\n\n/**\n * The GTIN field name for a UPC/EAN type, already uppercased by the caller.\n *\n * @ensures exactly the model's GtinField\n */\nexport function gtinFieldOf(upper: string): string {\n //@ verify\n //@ ensures upper === \"UPC\" ==> \\result === \"gtin12\"\n //@ ensures upper === \"EAN\" ==> \\result === \"gtin13\"\n //@ ensures upper !== \"UPC\" && upper !== \"EAN\" ==> \\result === \"gtin\"\n if (upper === \"UPC\") return \"gtin12\";\n if (upper === \"EAN\") return \"gtin13\";\n return \"gtin\";\n}\n\n/**\n * An item is kept out of JSON-LD when deleted, offline or inactive.\n *\n * @ensures exactly the model's IsSuppressed\n */\nexport function isSuppressedOf(deleteFlag: string, onlineCd: number, statusCd: number): boolean {\n //@ verify\n //@ ensures \\result === (deleteFlag === \"Y\" || onlineCd === 0 || statusCd === 0)\n return deleteFlag === \"Y\" || onlineCd === 0 || statusCd === 0;\n}\n\n/**\n * The product's name when it gets a Product JSON-LD: not suppressed, named (`name` trimmed by the\n * caller) and priced above 0; null otherwise.\n *\n * @ensures result ≠ null ⟺ the model's EmitsProduct, and then result = name\n */\nexport function productNameOf(suppressed: boolean, name: string, unitPrice: number): string | null {\n //@ verify\n //@ ensures suppressed ==> \\result === null\n //@ ensures !suppressed && (name === \"\" || unitPrice <= 0) ==> \\result === null\n //@ ensures !suppressed && name !== \"\" && unitPrice > 0 ==> \\result === name\n if (suppressed) return null;\n if (name === \"\" || unitPrice <= 0) return null;\n return name;\n}\n\n/**\n * The first non-blank of two texts (each trimmed by the caller), or undefined.\n *\n * @ensures exactly the model's FirstNonBlank\n */\nexport function firstNonBlankOf(a: string, b: string): string | undefined {\n //@ verify\n //@ ensures a !== \"\" ==> \\result === a\n //@ ensures a === \"\" && b !== \"\" ==> \\result === b\n //@ ensures a === \"\" && b === \"\" ==> \\result === undefined\n if (a !== \"\") return a;\n if (b !== \"\") return b;\n return undefined;\n}\n\n/**\n * The first primary (\"Y\") supplier from index `i`, or −1.\n *\n * @ensures exactly the model's PrimarySupplierFrom\n */\nexport function primarySupplierFrom(flags: string[], i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases flags.length - i\n //@ ensures i >= flags.length ==> \\result === -1\n //@ ensures i < flags.length && flags[i] === \"Y\" ==> \\result === i\n //@ ensures i < flags.length && flags[i] !== \"Y\" ==> \\result === primarySupplierFrom(flags, i + 1)\n if (i >= flags.length) return -1;\n if ((flags[i] as string) === \"Y\") return i;\n return primarySupplierFrom(flags, i + 1);\n}\n\n/**\n * The supplier whose part number goes in: the first primary, else the first, else none (−1).\n *\n * @ensures exactly the model's SupplierIndex\n */\nexport function supplierIndexOf(flags: string[]): number {\n //@ verify\n //@ ensures primarySupplierFrom(flags, 0) >= 0 ==> \\result === primarySupplierFrom(flags, 0)\n //@ ensures primarySupplierFrom(flags, 0) < 0 && flags.length > 0 ==> \\result === 0\n //@ ensures primarySupplierFrom(flags, 0) < 0 && flags.length === 0 ==> \\result === -1\n const primary = primarySupplierFrom(flags, 0);\n if (primary >= 0) return primary;\n return flags.length > 0 ? 0 : -1;\n}\n\n/**\n * The offer's URL only when a site URL is configured.\n *\n * @ensures exactly the model's OfferUrl\n */\nexport function offerUrlOf(siteUrl: string, itemPath: string, itemId: string): string | undefined {\n //@ verify\n //@ ensures siteUrl !== \"\" ==> \\result === siteUrl + itemPath + \"/\" + itemId\n //@ ensures siteUrl === \"\" ==> \\result === undefined\n if (siteUrl === \"\") return undefined;\n return siteUrl + itemPath + \"/\" + itemId;\n}\n","import * as ld from \"@atlas/utils/json-ld\";\nimport type { TInvMastDoc } from \"./types/inventory\";\nimport type { TInventorySupplier } from \"./types/supplier\";\nimport { resolveStock } from \"./resolve-stock\";\nimport { getSchemaAvailability } from \"./schema-availability\";\nimport {\n breadcrumbPosition,\n firstNonBlankOf,\n gtinFieldOf,\n isSuppressedOf,\n offerUrlOf,\n productNameOf,\n supplierIndexOf,\n} from \"./json-ld-rules\";\n\n// ---------------------------------------------------------------------------\n// Breadcrumb JSON-LD\n// ---------------------------------------------------------------------------\n\nexport interface BreadcrumbJsonLdItem {\n name: string;\n url: string;\n}\n\n/** Generates a Schema.org BreadcrumbList JSON-LD object from an array of breadcrumb items. */\nexport function generateBreadcrumbJsonLd(items: BreadcrumbJsonLdItem[]): Record<string, unknown> {\n return {\n \"@context\": \"https://schema.org\",\n \"@type\": \"BreadcrumbList\",\n itemListElement: items.map((item, index) => ({\n \"@type\": \"ListItem\",\n position: breadcrumbPosition(index),\n name: item.name,\n item: item.url,\n })),\n };\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD as text: the proved builders of @atlas/utils `json-ld` (bundled), the bytes\n// JSON.stringify gives. Typed here so the published declarations name nothing private.\n// `breadcrumbLd(items)` is `JSON.stringify(generateBreadcrumbJsonLd(items))` for the same items.\n// The same builders, by the same names, as @simpleapps-com/augur-hono.\n// ---------------------------------------------------------------------------\n\n/** A FAQ entry: the question and its plain-text answer, as the page shows them. */\nexport interface Faq {\n question: string;\n answer: string;\n}\n\n/** A breadcrumb trail's BreadcrumbList as text. */\nexport const breadcrumbLd: (items: BreadcrumbJsonLdItem[]) => string = ld.breadcrumbLd;\n\n/** A FAQ page's FAQPage markup as text: one Question per entry. */\nexport const faqLd: (faqs: Faq[]) => string = ld.faqLd;\n\n/** The schema.org context and a node's type: its first two members, as JSON text. */\nexport const nodeHead: (type: string) => string[] = ld.nodeHead;\n\n/** A reference to another node by its @id, as JSON text. */\nexport const idRef: (id: string) => string = ld.idRef;\n\n// ---------------------------------------------------------------------------\n// Product JSON-LD — types\n// ---------------------------------------------------------------------------\n\nexport interface ProductJsonLdAggregateRating {\n ratingValue: number;\n reviewCount: number;\n}\n\nexport interface ProductJsonLdSeller {\n name: string;\n url?: string;\n}\n\nexport interface ProductJsonLdOptions {\n unitPrice: number;\n currency?: string;\n siteUrl?: string;\n itemPath?: string;\n seller?: ProductJsonLdSeller;\n priceValidDays?: number;\n imageUrlTransform?: (path: string) => string;\n returnPolicy?: Record<string, unknown>;\n shippingDetails?: Record<string, unknown>;\n aggregateRating?: ProductJsonLdAggregateRating;\n companyKey?: string;\n weightUnit?: string;\n dimensionUnit?: string;\n overrides?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Product JSON-LD — helpers\n// ---------------------------------------------------------------------------\n\nfunction getGtinField(upcOrEan: string | null | undefined): string {\n return gtinFieldOf(upcOrEan?.toUpperCase() ?? \"\");\n}\n\nfunction getPrimarySupplierPartNo(suppliers: TInventorySupplier[]): string | undefined {\n // A null flag is no \"Y\"; index -1 (no suppliers) reads undefined.\n const supplier = suppliers[supplierIndexOf(suppliers.map((s) => s.primarySupplierFlag ?? \"\"))];\n const partNo = supplier?.supplierPartNo?.trim();\n return partNo || undefined;\n}\n\nfunction buildQuantitativeValue(\n value: number | null | undefined,\n unitCode: string,\n): Record<string, unknown> | undefined {\n if (value == null || value === 0) return undefined;\n return { \"@type\": \"QuantitativeValue\", value: Math.round(value * 100) / 100, unitCode };\n}\n\nfunction omitEmpty(obj: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value) && value.length === 0) continue;\n if (typeof value === \"object\" && !Array.isArray(value)) {\n const cleaned = omitEmpty(value as Record<string, unknown>);\n if (Object.keys(cleaned).length > 0) {\n result[key] = cleaned;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction resolveBrand(doc: TInvMastDoc): Record<string, unknown> | undefined {\n const name = firstNonBlankOf(doc.brandName?.trim() ?? \"\", doc.parkerProductCd?.trim() ?? \"\");\n if (name === undefined) return undefined;\n return { \"@type\": \"Brand\", name };\n}\n\nfunction resolveDescription(doc: TInvMastDoc): string | undefined {\n return firstNonBlankOf(doc.displayDesc?.trim() ?? \"\", doc.extendedDesc?.trim() ?? \"\");\n}\n\nfunction resolveImages(\n doc: TInvMastDoc,\n transform?: (path: string) => string,\n): string[] | undefined {\n if (doc.images.length === 0) return undefined;\n return transform ? doc.images.map(transform) : [...doc.images];\n}\n\nfunction buildOffers(doc: TInvMastDoc, options: ProductJsonLdOptions): Record<string, unknown> {\n const currency = options.currency ?? \"USD\";\n const itemPath = options.itemPath ?? \"/items\";\n const priceValidDays = options.priceValidDays ?? 360;\n\n const resolved = resolveStock({ stock: doc.stock, companyKey: options.companyKey });\n const availability = getSchemaAvailability(resolved);\n\n const validUntil = new Date();\n validUntil.setDate(validUntil.getDate() + priceValidDays);\n\n const url = offerUrlOf(options.siteUrl ?? \"\", itemPath, doc.itemId);\n\n const eligibleQuantity = doc.defaultSellingUnit?.trim()\n ? { \"@type\": \"QuantitativeValue\", unitCode: doc.defaultSellingUnit.trim() }\n : undefined;\n\n const seller = options.seller\n ? { \"@type\": \"Organization\", name: options.seller.name, url: options.seller.url }\n : undefined;\n\n return {\n \"@type\": \"Offer\",\n price: options.unitPrice,\n priceCurrency: currency,\n availability,\n itemCondition: \"https://schema.org/NewCondition\",\n priceValidUntil: validUntil.toISOString().split(\"T\")[0],\n url,\n eligibleQuantity,\n seller,\n hasMerchantReturnPolicy: options.returnPolicy,\n shippingDetails: options.shippingDetails,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Product JSON-LD — main\n// ---------------------------------------------------------------------------\n\n/** The product's name when it gets a Product JSON-LD: not suppressed, named, and priced above 0; null otherwise. */\nfunction productName(doc: TInvMastDoc, unitPrice: number): string | null {\n const suppressed = isSuppressedOf(doc.deleteFlag, doc.onlineCd, doc.statusCd);\n return productNameOf(suppressed, (doc.itemDesc || \"\").trim(), unitPrice);\n}\n\nfunction buildAggregateRating(\n rating: ProductJsonLdAggregateRating | undefined,\n): Record<string, unknown> | undefined {\n if (!rating) return undefined;\n return {\n \"@type\": \"AggregateRating\",\n ratingValue: rating.ratingValue,\n reviewCount: rating.reviewCount,\n };\n}\n\n/** Generates a Schema.org Product JSON-LD string from an inventory document. Returns null if the item is suppressed, unnamed, or has no price. */\nexport function generateProductJsonLd(\n doc: TInvMastDoc,\n options: ProductJsonLdOptions,\n): string | null {\n const name = productName(doc, options.unitPrice);\n if (name === null) return null;\n\n const weightUnit = options.weightUnit ?? \"LBR\";\n const dimensionUnit = options.dimensionUnit ?? \"INH\";\n\n const gtinId = doc.upcOrEanId?.trim() || undefined;\n\n const aggregateRating = buildAggregateRating(options.aggregateRating);\n\n const product: Record<string, unknown> = {\n \"@context\": \"https://schema.org\",\n \"@type\": \"Product\",\n name,\n description: resolveDescription(doc),\n brand: resolveBrand(doc),\n sku: doc.itemId,\n image: resolveImages(doc, options.imageUrlTransform),\n ...(gtinId ? { [getGtinField(doc.upcOrEan)]: gtinId } : {}),\n mpn: getPrimarySupplierPartNo(doc.inventorySupplier),\n weight: buildQuantitativeValue(doc.weight, weightUnit),\n width: buildQuantitativeValue(doc.width, dimensionUnit),\n height: buildQuantitativeValue(doc.height, dimensionUnit),\n depth: buildQuantitativeValue(doc.length, dimensionUnit),\n offers: buildOffers(doc, options),\n aggregateRating,\n };\n\n const merged = options.overrides ? { ...product, ...options.overrides } : product;\n return JSON.stringify(omitEmpty(merged));\n}\n","import { unwrapMessage } from \"./rules\";\n\n/** Result type for safe action wrappers. */\nexport type SafeActionResult<T> = { ok: true; data: T } | { ok: false; error: string };\n\n/**\n * Extracts the data from a `SafeActionResult`, throwing on error.\n *\n * Ideal for React Query `queryFn` where errors should propagate\n * to the error boundary.\n *\n * @example\n * ```ts\n * const cart = unwrap(await getCartLines(cartId));\n * ```\n */\nexport function unwrap<T>(result: SafeActionResult<T>): T {\n if (!result.ok) throw new Error(unwrapMessage(result.error));\n return result.data;\n}\n\n/**\n * Extracts the data from a `SafeActionResult`, returning `null` on error.\n *\n * For direct calls that prefer `null` over thrown errors.\n *\n * @example\n * ```ts\n * const cart = unwrapOr(await getCartLines(cartId));\n * if (!cart) { /* handle missing data *\\/ }\n * ```\n */\nexport function unwrapOr<T>(result: SafeActionResult<T>): T | null {\n return result.ok ? (result.data ?? null) : null;\n}\n","//@ backend dafny\nimport { joinFrom } from \"@atlas/utils/lists\";\nimport { codeAt, indexOfCode, startsWithAt } from \"@atlas/utils/strings\";\n\n/* The image CDN's decisions (image.ts), verified with LemmaScript → Dafny (model:\n models/AugurUtils.dfy; link: models/links/augur-utils-image-rules.dfy). The callers trim the\n path (JS `trim`) and list the transforms in object-key order. */\n\n/**\n * A transform field's CDN key, or \"\" when it has none.\n *\n * @ensures exactly the model's TransformKey\n */\nexport function transformKeyOf(field: string): string {\n //@ verify\n //@ ensures field === \"width\" ==> \\result === \"w\"\n //@ ensures field === \"height\" ==> \\result === \"h\"\n //@ ensures field === \"format\" ==> \\result === \"f\"\n //@ ensures field === \"quality\" ==> \\result === \"q\"\n //@ ensures field === \"fit\" ==> \\result === \"fit\"\n //@ ensures field !== \"width\" && field !== \"height\" && field !== \"format\" && field !== \"quality\" && field !== \"fit\" ==> \\result === \"\"\n if (field === \"width\") return \"w\";\n if (field === \"height\") return \"h\";\n if (field === \"format\") return \"f\";\n if (field === \"quality\") return \"q\";\n if (field === \"fit\") return \"fit\";\n return \"\";\n}\n\n/**\n * A transform value's text: \"jpg\" is sent as \"jpeg\" for the format field.\n *\n * @ensures exactly the model's TransformValue\n */\nexport function transformValueOf(field: string, value: string): string {\n //@ verify\n //@ ensures field === \"format\" && value === \"jpg\" ==> \\result === \"jpeg\"\n //@ ensures !(field === \"format\" && value === \"jpg\") ==> \\result === value\n if (field === \"format\" && value === \"jpg\") return \"jpeg\";\n return value;\n}\n\n/**\n * The `k_v` parts from index `i`: one for each known field with a value (`present`), in order.\n *\n * @ensures exactly the model's TransformParts\n */\nexport function transformPartsFrom(\n fields: string[],\n present: boolean[],\n texts: string[],\n i: number,\n): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && fields.length === present.length && fields.length === texts.length\n //@ decreases fields.length - i\n //@ ensures i >= fields.length ==> \\result.length === 0\n if (i >= fields.length) return [];\n const field = fields[i] as string;\n const key = transformKeyOf(field);\n const rest = transformPartsFrom(fields, present, texts, i + 1);\n if ((present[i] as boolean) && key !== \"\") {\n return [key + \"_\" + transformValueOf(field, texts[i] as string), ...rest];\n }\n return rest;\n}\n\n/**\n * serializeTransforms: the parts joined by \",\".\n *\n * @ensures exactly the model's SerializeTransforms\n */\nexport function serializedTransforms(\n fields: string[],\n present: boolean[],\n texts: string[],\n): string {\n //@ verify\n //@ requires fields.length === present.length && fields.length === texts.length\n //@ ensures \\result === joinFrom(transformPartsFrom(fields, present, texts, 0), \",\", 0)\n return joinFrom(transformPartsFrom(fields, present, texts, 0), \",\", 0);\n}\n\n/**\n * An external URL: the path starts with \"http\".\n *\n * @ensures exactly the model's IsExternal\n */\nexport function isExternal(path: string): boolean {\n //@ verify\n //@ ensures \\result === startsWithAt(path, \"http\", 0)\n return startsWithAt(path, \"http\", 0);\n}\n\n/**\n * The path with the first prefix (from index `i`) it starts with stripped once.\n *\n * @ensures exactly the model's StripFirstPrefix\n */\nexport function stripFirstPrefixFrom(path: string, prefixes: string[], i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases prefixes.length - i\n //@ ensures i >= prefixes.length ==> \\result === path\n if (i >= prefixes.length) return path;\n const prefix = prefixes[i] as string;\n if (startsWithAt(path, prefix, 0)) return path.slice(prefix.length);\n return stripFirstPrefixFrom(path, prefixes, i + 1);\n}\n\n/**\n * Every leading \"/\" removed (`replace(/^\\/+/, \"\")`).\n *\n * @ensures exactly the model's StripLeadingSlashes\n */\nexport function stripLeadingSlashes(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures codeAt(s, 0) !== 47 ==> \\result === s\n if (codeAt(s, 0) !== 47) return s;\n return stripLeadingSlashes(s.slice(1));\n}\n\n/**\n * normalizePath: an external URL as is; else the first matching prefix stripped once, then the\n * leading slashes, then defaultPath + \"/\" before a bare file name when a defaultPath (\"\" for\n * none) is set.\n *\n * @ensures exactly the model's NormalizePath\n */\nexport function normalizedPath(raw: string, prefixes: string[], defaultPath: string): string {\n //@ verify\n //@ ensures isExternal(raw) ==> \\result === raw\n if (isExternal(raw)) return raw;\n const cleaned = stripLeadingSlashes(stripFirstPrefixFrom(raw, prefixes, 0));\n if (defaultPath !== \"\" && indexOfCode(cleaned, 47, 0) < 0) return defaultPath + \"/\" + cleaned;\n return cleaned;\n}\n\n/**\n * The CDN URL for a normalized path, with the transform segment only when there is one.\n *\n * @ensures exactly the model's CdnUrl\n */\nexport function cdnUrlOf(clientDomain: string, serialized: string, normalized: string): string {\n //@ verify\n //@ ensures serialized !== \"\" ==> \\result === \"https://agr.media/\" + clientDomain + \"/images/\" + serialized + \"/\" + normalized\n //@ ensures serialized === \"\" ==> \\result === \"https://agr.media/\" + clientDomain + \"/images/\" + normalized\n const segment = serialized !== \"\" ? \"/\" + serialized : \"\";\n return \"https://agr.media/\" + clientDomain + \"/images\" + segment + \"/\" + normalized;\n}\n\n/**\n * getDefaultImageUrl over the chosen fallback (\"\" for none).\n *\n * @ensures exactly the model's DefaultImageUrl\n */\nexport function defaultImageUrlOf(\n clientDomain: string,\n fallback: string,\n prefixes: string[],\n defaultPath: string,\n): string {\n //@ verify\n //@ ensures fallback === \"\" ==> \\result === \"\"\n if (fallback === \"\") return \"\";\n const normalized = normalizedPath(fallback, prefixes, defaultPath);\n if (isExternal(normalized)) return normalized;\n return \"https://agr.media/\" + clientDomain + \"/images/\" + normalized;\n}\n\n/**\n * getImageUrl on a trimmed path: a blank one gives the default; an external one passes; else the\n * CDN URL.\n *\n * @ensures exactly the model's ImageUrl on the trimmed path\n */\nexport function imageUrlOf(\n clientDomain: string,\n path: string,\n serialized: string,\n fallback: string,\n prefixes: string[],\n defaultPath: string,\n): string {\n //@ verify\n //@ ensures path === \"\" ==> \\result === defaultImageUrlOf(clientDomain, fallback, prefixes, defaultPath)\n if (path === \"\") return defaultImageUrlOf(clientDomain, fallback, prefixes, defaultPath);\n const normalized = normalizedPath(path, prefixes, defaultPath);\n if (isExternal(normalized)) return normalized;\n return cdnUrlOf(clientDomain, serialized, normalized);\n}\n","/**\n * Image CDN utilities for agr.media.\n * Pure functions -- no DOM or React dependencies. Safe for server, web, and mobile.\n * The decisions are proved in image-rules.ts.\n */\n\nimport { defaultImageUrlOf, imageUrlOf, normalizedPath, serializedTransforms } from \"./image-rules\";\n\n/** 1x1 transparent PNG for Next.js `<Image blurDataURL={...}>` placeholders. */\nexport const BLUR_DATA_URL =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mN88P/BfwYABQoBfqVKzQAAAABJRU5ErkJggg==\";\n\nexport interface ImageTransforms {\n width?: number;\n height?: number;\n format?: \"auto\" | \"webp\" | \"avif\" | \"jpeg\" | \"jpg\" | \"png\";\n quality?: number;\n fit?: \"cover\" | \"contain\" | \"fill\" | \"inside\" | \"outside\";\n}\n\nexport interface ImageConfig {\n readonly clientDomain: string;\n readonly defaultImage?: string;\n readonly defaultTransforms?: ImageTransforms;\n readonly stripPrefixes?: string[];\n readonly defaultPath?: string;\n}\n\nexport interface ImageUrlOptions {\n defaultImage?: string;\n}\n\nconst DEFAULT_STRIP_PREFIXES = [\"/images\", \"images\"];\n\n/**\n * Creates a frozen ImageConfig object.\n *\n * `stripPrefixes` defaults to `[\"/images\", \"images\"]` — set to `[]` to disable.\n */\nexport function createImageConfig(\n clientDomain: string,\n opts?: {\n defaultImage?: string;\n defaultTransforms?: ImageTransforms;\n stripPrefixes?: string[];\n defaultPath?: string;\n },\n): ImageConfig {\n return Object.freeze({\n clientDomain,\n defaultImage: opts?.defaultImage,\n defaultTransforms: opts?.defaultTransforms,\n stripPrefixes: opts?.stripPrefixes ?? DEFAULT_STRIP_PREFIXES,\n defaultPath: opts?.defaultPath,\n });\n}\n\n/**\n * Serializes transform options into the CDN path segment.\n * Example: `{ width: 400, format: \"webp\" }` → `\"w_400,f_webp\"`\n */\nexport function serializeTransforms(transforms: ImageTransforms): string {\n // The fields in object-key order; `serializedTransforms` keeps the known ones with a value.\n const entries = Object.entries(transforms);\n return serializedTransforms(\n entries.map(([key]) => key),\n entries.map(([, value]) => value !== undefined),\n entries.map(([, value]) => String(value)),\n );\n}\n\n/**\n * Normalizes an image path by:\n * 1. Returning it as-is if it starts with `http` (external URL).\n * 2. Stripping configured prefixes (defaults: `/images`, `images`).\n * 3. Prepending `defaultPath` for bare filenames (no `/`).\n * 4. Stripping leading slashes.\n */\nexport function normalizePath(config: ImageConfig, raw: string): string {\n return normalizedPath(raw, prefixesOf(config), config.defaultPath ?? \"\");\n}\n\n/** The config's strip prefixes, the defaults when unset. */\nfunction prefixesOf(config: ImageConfig): string[] {\n return config.stripPrefixes ?? DEFAULT_STRIP_PREFIXES;\n}\n\n/**\n * Builds a full agr.media URL for the given image path and transforms.\n *\n * - Empty/nullish paths return the default image URL.\n * - Paths starting with `http` are returned as-is (external CDN).\n * - Configured prefixes (default: `/images`) are stripped automatically.\n * - Bare filenames are prepended with `config.defaultPath` if set.\n */\nexport function getImageUrl(\n config: ImageConfig,\n imagePath: string | undefined | null,\n transforms?: ImageTransforms,\n options?: ImageUrlOptions,\n): string {\n const merged: ImageTransforms = {\n ...config.defaultTransforms,\n ...transforms,\n };\n return imageUrlOf(\n config.clientDomain,\n imagePath?.trim() ?? \"\",\n serializeTransforms(merged),\n fallbackOf(config, options),\n prefixesOf(config),\n config.defaultPath ?? \"\",\n );\n}\n\n/**\n * Returns the default/placeholder image URL.\n * Per-call `options.defaultImage` overrides `config.defaultImage`.\n */\nexport function getDefaultImageUrl(config: ImageConfig, options?: ImageUrlOptions): string {\n return defaultImageUrlOf(\n config.clientDomain,\n fallbackOf(config, options),\n prefixesOf(config),\n config.defaultPath ?? \"\",\n );\n}\n\n/** The fallback image: the call's, else the config's (\"\" for none). */\nfunction fallbackOf(config: ImageConfig, options?: ImageUrlOptions): string {\n return options?.defaultImage ?? config.defaultImage ?? \"\";\n}\n\n/**\n * Generates a `srcset` string for responsive images.\n */\nexport function getImageSrcSet(\n config: ImageConfig,\n imagePath: string,\n widths: number[],\n transforms?: ImageTransforms,\n): string {\n return widths\n .map((w) => {\n const url = getImageUrl(config, imagePath, { ...transforms, width: w });\n return `${url} ${w}w`;\n })\n .join(\", \");\n}\n\n/**\n * Returns a loader function compatible with Next.js `<Image loader={...}>`.\n */\nexport function buildImageLoader(\n config: ImageConfig,\n transforms?: ImageTransforms,\n): (props: { src: string; width: number; quality?: number }) => string {\n return ({ src, width, quality }) => {\n const merged: ImageTransforms = { ...transforms, width };\n if (quality !== undefined) {\n merged.quality = quality;\n }\n return getImageUrl(config, src, merged);\n };\n}\n\n/**\n * Rewrites `<img src=\"...\">` attributes in an HTML string to use agr.media URLs.\n * Useful for CMS/Joomla content that contains raw image references.\n */\nexport function sanitizeHtmlImages(\n config: ImageConfig,\n html: string,\n transforms?: ImageTransforms,\n): string {\n return html.replace(\n /<img\\s([^>]*?)src=[\"']([^\"']+)[\"']/gi,\n (_match, before: string, src: string) => {\n const cdnUrl = getImageUrl(config, src, transforms);\n return `<img ${before}src=\"${cdnUrl}\"`;\n },\n );\n}\n","/**\n * Common regex patterns used for form validation across augur-hosted sites.\n */\nexport const VALIDATION_PATTERNS = {\n /** Phone number format: (123) 456-7890 or 123-456-7890 or 123.456.7890 */\n phoneNumber: /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,\n\n /** Name format: Must start with non-hyphen/space, allow word chars, spaces, hyphens */\n nameFormat: /^[^-\\s][\\w\\s-]+$/,\n\n /** Name must not contain numbers */\n nameNoNumbers: /^([^0-9]*)$/,\n\n /** Address format: Allow word chars, spaces, hyphens, slashes, periods, hash, commas */\n addressFormat: /^[^-\\s][\\w\\s\\-\\/.#,]+$/,\n\n /** No PO Box pattern - prevents PO Box addresses */\n noPOBox:\n /^(?!.*(P\\.?\\s*O\\.?\\s*BOX|POST\\s*OFFICE\\s*BOX|PO\\s*BOX|P\\s*O\\s*B\\s*O\\s*X|POBOX|P\\.O\\.B\\.)).*$/i,\n\n /** Zip code: Exactly 5 digits */\n zipCode: /^\\d{5}$/,\n\n /** City: Letters, spaces, periods, hyphens, apostrophes only */\n cityFormat: /^[a-zA-Z\\s.\\-']+$/,\n\n /** Address must contain at least one number */\n hasNumber: /\\d/,\n} as const;\n","import * as v from \"valibot\";\nimport { VALIDATION_PATTERNS } from \"./validation-patterns\";\nimport { US_STATES } from \"./us-states\";\n\nconst validStateCodes = US_STATES.map((state) => state.code) as [string, ...string[]];\n\n/** A required person name: name characters only, no digits. */\nfunction personName(requiredMessage: string, invalidMessage: string) {\n return v.pipe(\n v.string(),\n v.minLength(1, requiredMessage),\n v.regex(VALIDATION_PATTERNS.nameFormat, invalidMessage),\n v.regex(VALIDATION_PATTERNS.nameNoNumbers, invalidMessage),\n );\n}\n\nconst firstName = personName(\"First name is required\", \"Invalid first name\");\nconst lastName = personName(\"Last name is required\", \"Invalid last name\");\n\n/**\n * Valibot schema for shipping address validation.\n * Enforces no PO Box, requires street number, formats phone number.\n */\nexport const ShippingAddressSchema = v.object({\n companyName: v.optional(v.string()),\n firstName,\n lastName,\n address1: v.pipe(\n v.string(),\n v.minLength(1, \"Address 1 is required\"),\n v.regex(VALIDATION_PATTERNS.addressFormat, \"Invalid address\"),\n v.regex(VALIDATION_PATTERNS.noPOBox, \"PO Box addresses are not allowed for shipping\"),\n v.regex(VALIDATION_PATTERNS.hasNumber, \"Address must contain at least one number\"),\n ),\n address2: v.optional(\n v.pipe(\n v.string(),\n v.check(\n (val) => !val || VALIDATION_PATTERNS.addressFormat.test(val),\n \"Invalid address format\",\n ),\n v.check(\n (val) => !val || VALIDATION_PATTERNS.noPOBox.test(val),\n \"PO Box addresses are not allowed for shipping\",\n ),\n ),\n ),\n postalCode: v.pipe(\n v.string(),\n v.minLength(1, \"Zip code is required\"),\n v.regex(VALIDATION_PATTERNS.zipCode, \"Zip code must be exactly 5 digits\"),\n ),\n city: v.pipe(\n v.string(),\n v.minLength(2, \"City is required\"),\n v.regex(\n VALIDATION_PATTERNS.cityFormat,\n \"City must contain only letters, spaces, periods, hyphens, or apostrophes\",\n ),\n ),\n state: v.pipe(\n v.string(),\n v.minLength(1, \"State is required\"),\n v.picklist(validStateCodes, \"Please select a valid US state\"),\n ),\n country: v.pipe(v.string(), v.minLength(1, \"Country is required\")),\n email: v.pipe(v.string(), v.minLength(1, \"Email is required\"), v.email(\"Invalid email\")),\n phoneNumber: v.pipe(\n v.string(),\n v.minLength(1, \"Phone number is required\"),\n v.regex(VALIDATION_PATTERNS.phoneNumber, \"Invalid phone number\"),\n v.transform((val) => {\n const digits = val.replace(/\\D/g, \"\");\n return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;\n }),\n ),\n notes: v.optional(v.string()),\n plus4Code: v.optional(v.string()),\n});\n\n/**\n * Valibot schema for billing address validation.\n * Less strict than shipping: allows PO Box, no email/phone required.\n */\nexport const BillingAddressSchema = v.object({\n poNumber: v.optional(v.string()),\n firstName,\n lastName,\n address1: v.pipe(\n v.string(),\n v.minLength(1, \"Address 1 is required\"),\n v.regex(VALIDATION_PATTERNS.addressFormat, \"Invalid address\"),\n ),\n address2: v.optional(v.string()),\n postalCode: v.pipe(v.string(), v.minLength(1, \"Zip code is required\")),\n city: v.pipe(v.string(), v.minLength(1, \"City is required\")),\n state: v.pipe(v.string(), v.minLength(1, \"State is required\")),\n country: v.pipe(v.string(), v.minLength(1, \"Country is required\")),\n plus4Code: v.optional(v.string()),\n});\n\n/**\n * Valibot schema for billing address with required PO number (invoice payments).\n */\nexport const BillingAddressInvoiceSchema = v.object({\n poNumber: v.pipe(v.string(), v.minLength(2, \"PO number is required\")),\n});\n\nexport type ShippingAddress = v.InferOutput<typeof ShippingAddressSchema>;\nexport type BillingAddress = v.InferOutput<typeof BillingAddressSchema>;\n","import { states } from \"states-us\";\nimport type { State } from \"states-us\";\n\nexport type { State as USState };\n\n/** All US states and territories — full data from states-us. */\nexport const US_STATES_FULL = states;\n\n/** All US states and territories — backward-compatible {code, name} shape. */\nexport const US_STATES = states.map((s) => ({\n code: s.abbreviation,\n name: s.name,\n}));\n\n/** Lower 48 contiguous states. */\nexport const CONTIGUOUS_STATES = states.filter((s) => s.contiguous);\n\n/** US territories (PR, GU, VI, AS, MP). */\nexport const US_TERRITORIES = states.filter((s) => s.territory);\n\nexport type USStateCode = (typeof US_STATES)[number][\"code\"];\n","/**\n * Date utility functions for shipping calculations.\n */\n\nimport { isBusinessDayName, shippingLeadOf } from \"./rules\";\n\nconst DATE_FORMAT_OPTIONS: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"short\",\n day: \"numeric\",\n};\n\n/**\n * Get the Nth business day from today (skipping weekends).\n * @param businessDaysFromNow - Number of business days to add\n * @returns Formatted date string\n */\nexport function getBusinessDay(businessDaysFromNow: number): string {\n const businessDays: string[] = [];\n let i = 1;\n\n while (businessDays.length < businessDaysFromNow) {\n const date = new Date();\n date.setDate(date.getDate() + i);\n const dayName = date.toLocaleDateString(\"en-US\", { weekday: \"long\" });\n\n if (isBusinessDayName(dayName)) {\n businessDays.push(date.toLocaleDateString(\"en-US\", DATE_FORMAT_OPTIONS));\n }\n i++;\n }\n\n return businessDays[businessDays.length - 1] || \"\";\n}\n\n/**\n * Get shipping lead date estimate based on days string (the table is `shippingLeadOf`).\n * @param days - Shipping days string (e.g., \"1-2\", \"2-3\", \"3\")\n * @returns Formatted date range or single date\n */\nexport function getShippingLeadDate(days: string): string {\n const config = shippingLeadOf(days);\n if (!config) return \"\";\n\n const fromDate = getBusinessDay(config.from);\n\n if (config.to) {\n const toDate = getBusinessDay(config.to);\n return `${fromDate} - ${toDate}`;\n }\n\n return fromDate;\n}\n","import { categorySortBy, pageOffset, searchSortBy } from \"./rules\";\nimport type { TItemsFilters } from \"./types/filter\";\n\n/**\n * Options for category item filter serialization.\n * All fields optional — omit what you don't need.\n */\nexport interface CategoryFilterOptions {\n /** Prefix prepended to non-empty sortBy values (e.g. \"item_category_sequence_no_min|\"). */\n sortByPrefix?: string;\n /** Whether to include stock data in results. Default: true. */\n includeStock?: boolean;\n}\n\n/**\n * Options for search param serialization.\n * All fields optional — omit what you don't need.\n */\nexport interface SearchParamOptions {\n /** Category UID to scope search results. Converted to classId5List string. */\n categoryUid?: number | string;\n /** Source fields for search results. Default: \"display_desc\". */\n sourceFields?: string;\n}\n\n/**\n * Converts TItemsFilters to the SDK params shape for category item endpoints.\n *\n * Pure function. Idempotent. Produces params ready to spread into\n * `q.items.itemCategory.categoryItems.list(uid, params)`.\n *\n * Transforms applied:\n * - filters: [string, string][] -> JSON string\n * - sortBy: prefixed with sortByPrefix if configured and non-empty\n * - includeStock: \"Y\" added by default\n * - page field: stripped (SDK uses limit/offset, not page)\n */\nexport function serializeCategoryFilters(\n filters: TItemsFilters,\n options?: CategoryFilterOptions,\n): Record<string, unknown> {\n const { sortByPrefix, includeStock = true } = options ?? {};\n\n // A sortBy missing at runtime (the type says string) stays as it came.\n const sortBy: string = filters.sortBy\n ? categorySortBy(sortByPrefix ?? \"\", filters.sortBy)\n : filters.sortBy;\n\n const params: Record<string, unknown> = {\n filters: JSON.stringify(filters.filters),\n limit: filters.limit,\n offset: filters.offset,\n q: filters.q,\n sortBy,\n };\n\n if (includeStock) {\n params[\"includeStock\"] = \"Y\";\n }\n\n return params;\n}\n\n/**\n * Converts TItemsFilters to the SDK params shape for search endpoints.\n *\n * Pure function. Idempotent. Produces params ready to spread into\n * `q.openSearch.itemSearch.list(params)`.\n *\n * Transforms applied:\n * - limit -> size, offset -> from (field rename)\n * - searchType: \"query\" injected\n * - categoryUid -> classId5List (string conversion)\n * - filters: [string, string][] -> JSON string (or undefined if empty)\n * - sourceFieldsList: injected from options or default \"display_desc\"\n * - page field: stripped\n */\nexport function serializeSearchParams(\n filters: TItemsFilters,\n options?: SearchParamOptions,\n): Record<string, unknown> {\n const { categoryUid, sourceFields = \"display_desc\" } = options ?? {};\n\n return {\n q: filters.q,\n searchType: \"query\",\n size: filters.limit,\n from: filters.offset,\n sortBy: searchSortBy(filters.sortBy),\n classId5List: categoryUid ? String(categoryUid) : undefined,\n filters: filters.filters?.length ? JSON.stringify(filters.filters) : undefined,\n sourceFieldsList: sourceFields,\n };\n}\n\n/**\n * Returns a copy of filters with offset adjusted for the given page.\n *\n * Pure function. Idempotent. Use with useInfiniteQuery's pageParam\n * to compute the correct offset for each page.\n *\n * @example\n * ```tsx\n * useInfiniteQuery({\n * ...q.items.itemCategory.categoryItems.list(\n * uid,\n * serializeCategoryFilters(paginateOffset(filters, pageParam), site)\n * ),\n * initialPageParam: 0,\n * getNextPageParam: (last, _all, lastPage) =>\n * (lastPage + 1) * filters.limit < last.total ? lastPage + 1 : undefined,\n * });\n * ```\n */\nexport function paginateOffset(filters: TItemsFilters, pageParam: number): TItemsFilters {\n return {\n ...filters,\n offset: pageOffset(pageParam, filters.limit),\n };\n}\n","/**\n * Analytics utility functions for tracking ecommerce events via Google Analytics.\n */\n\nimport { cleanMoney, roundHalfAway } from \"./money\";\n\ndeclare global {\n interface Window {\n dataLayer?: Record<string, unknown>[];\n gtag?: (...args: unknown[]) => void;\n }\n}\n\nexport interface AddToCartEventParams {\n itemId: string;\n itemName: string;\n price: number;\n quantity: number;\n estimatedCost: number;\n}\n\n/**\n * Track add_to_cart event to Google Analytics dataLayer.\n */\nexport function trackAddToCart({\n itemId,\n itemName,\n price,\n quantity,\n estimatedCost,\n}: AddToCartEventParams): void {\n if (typeof window === \"undefined\" || !window.dataLayer) return;\n\n // Clear previous ecommerce data\n window.dataLayer.push({ ecommerce: null });\n\n window.dataLayer.push({\n event: \"add_to_cart\",\n ecommerce: {\n currency: \"USD\",\n value: roundHalfAway(estimatedCost, 2),\n items: [\n {\n item_id: itemId,\n item_name: itemName,\n currency: \"USD\",\n index: 0,\n item_category: \"\",\n price,\n quantity,\n },\n ],\n },\n });\n}\n\nexport interface ViewItemEventParams {\n itemId: string;\n itemName: string;\n price: number;\n category?: string;\n}\n\n/**\n * Track view_item event to Google Analytics dataLayer.\n */\nexport function trackViewItem({\n itemId,\n itemName,\n price,\n category = \"\",\n}: ViewItemEventParams): void {\n if (typeof window === \"undefined\" || !window.gtag) return;\n\n window.gtag(\"event\", \"view_item\", {\n currency: \"USD\",\n value: price,\n items: [\n {\n item_id: itemId,\n item_name: itemName,\n currency: \"USD\",\n index: 0,\n item_category: category,\n price,\n quantity: 1,\n },\n ],\n });\n}\n\n// ---------------------------------------------------------------------------\n// GA4 begin_checkout tracking\n// ---------------------------------------------------------------------------\n\nexport interface TrackingItem {\n item_id: string;\n item_name: string;\n currency: string;\n index: number;\n item_category: string;\n price: number;\n quantity: number;\n}\n\nexport interface TrackingData {\n event: string;\n currency: string;\n value: number;\n items: TrackingItem[];\n}\n\nexport interface BuildTrackingDataInput {\n cartLines: { itemId: string; quantity: number }[];\n itemDetails: Record<string, { itemDesc?: string; classId5?: string }>;\n getUnitPrice: (itemId: string) => number;\n currency?: string;\n}\n\n/**\n * Build a GA4 begin_checkout ecommerce payload from cart lines, item details, and prices.\n */\nexport function buildTrackingData({\n cartLines,\n itemDetails,\n getUnitPrice,\n currency = \"USD\",\n}: BuildTrackingDataInput): TrackingData {\n let total = 0;\n const items: TrackingItem[] = cartLines.map((line, index) => {\n const details = itemDetails[line.itemId];\n const price = getUnitPrice(line.itemId);\n total = cleanMoney(total + cleanMoney(price * line.quantity));\n return {\n item_id: line.itemId,\n item_name: details?.itemDesc ?? \"\",\n currency,\n index,\n item_category: details?.classId5 ?? \"\",\n price,\n quantity: line.quantity,\n };\n });\n\n return {\n event: \"begin_checkout\",\n currency,\n // toFixed(2) rounds ties wrong (1.005 → \"1.00\"); roundHalfAway gives 1.01.\n value: roundHalfAway(total, 2),\n items,\n };\n}\n\n/**\n * Push ecommerce tracking data to window.dataLayer using the GA4 clear-then-push pattern.\n */\nexport function pushTrackingData(data: TrackingData): void {\n if (typeof window === \"undefined\" || !window.dataLayer) return;\n\n window.dataLayer.push({ ecommerce: null });\n window.dataLayer.push({\n event: data.event,\n ecommerce: {\n currency: data.currency,\n value: data.value,\n items: data.items,\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-utils/dist/index.cjs","../src/price-breaks.ts","../../foundation/src/duration.ts","../src/rules.ts","../src/runtime.ts","../src/cache-config.ts","../src/duration.ts","../src/format-price.ts","../src/address-comparison.ts","../src/get-payment-status.ts","../src/transform-ship-to-address.ts","../../foundation/src/chars.ts","../../utils/src/strings.ts","../src/cart-line-rules.ts","../../foundation/src/pos-digits.ts","../../foundation/src/pos-int.ts","../src/address-id.ts","../src/build-checkout-payload.ts","../src/money.ts","../src/price-outcome.ts","../src/derive-price.ts","../src/resolve-stock.ts","../src/schema-availability.ts","../../utils/src/lists.ts","../../utils/src/replace.ts","../../utils/src/json.ts","../../foundation/src/decimal.ts","../../utils/src/json-ld-items.ts","../../utils/src/json-ld.ts","../src/json-ld-rules.ts","../src/json-ld.ts","../src/result.ts","../src/image-rules.ts","../src/image.ts","../src/validation-patterns.ts","../src/address-schemas.ts","../src/us-states.ts","../src/date-helpers.ts","../src/transforms.ts","../src/analytics.ts"],"names":["days","seconds","minutes","hours","millis","toMillis","addMillis","minusMillis","floorSeconds","secondsOf","wholeSeconds","millisOf","v","breadcrumbLd","transform"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACWO,SAAS,cAAA,CACd,gBAAA,EACuC;AACvC,EAAA,OAAO,iBAAA,IAAqB,KAAA,GAAQ,KAAA,CAAM,OAAA,CAAQ,gBAAA,CAAiB,MAAM,CAAA;AAC3E;ADXA;AACA;AEmBO,SAAS,OAAA,CAAQ,CAAA,EAAoB;AAK1C,EAAA,OAAO,CAAA;AACT;AAOO,SAAS,OAAA,CAAQ,CAAA,EAAoB;AAK1C,EAAA,OAAQ,EAAA,EAAI,EAAA;AACd;AAOO,SAAS,KAAA,CAAM,CAAA,EAAoB;AAKxC,EAAA,OAAQ,EAAA,EAAI,IAAA;AACd;AAOO,SAAS,IAAA,CAAK,CAAA,EAAoB;AAK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AA;AACW,EAAA;AACiB;AACjB,EAAA;AAEC,EAAA;AACA,IAAA;AACH,IAAA;AACA,IAAA;AACL,MAAA;AACW,QAAA;AACT,QAAA;AACA,QAAA;AACO,QAAA;AACP,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACD,EAAA;AACH;AAsCgB;AACd,EAAA;AACA,EAAA;AACA,EAAA;AACW,EAAA;AAC4B;AAC3B,EAAA;AACkB,EAAA;AACtB,IAAA;AACA,IAAA;AACE,IAAA;AACD,IAAA;AACI,MAAA;AACE,MAAA;AACX,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACU,MAAA;AACZ,IAAA;AACD,EAAA;AAEM,EAAA;AACE,IAAA;AACP,IAAA;AAAA;AAEO,IAAA;AACP,IAAA;AACF,EAAA;AACF;AAKgB;AACH,EAAA;AAEJ,EAAA;AACA,EAAA;AACO,IAAA;AACD,IAAA;AACC,MAAA;AACH,MAAA;AACA,MAAA;AACT,IAAA;AACD,EAAA;AACH;AvCwnCiB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/stuartjackson/Projects/simpleapps/atlas/repo/packages/augur-utils/dist/index.cjs","sourcesContent":[null,"import type { TLibraryPriceData, TPriceData } from \"./types/pricing\";\n\n/**\n * Type guard: true when `libraryPriceData` is the price-page shape with quantity `breaks`.\n *\n * `\"breaks\" in libraryPriceData` does not narrow, because both SDK shapes allow\n * arbitrary extra keys.\n *\n * @example\n * ```ts\n * if (hasPriceBreaks(priceData.libraryPriceData)) {\n * priceData.libraryPriceData.breaks.map((tier) => tier.startQuantity);\n * }\n * ```\n */\nexport function hasPriceBreaks(\n libraryPriceData: TPriceData[\"libraryPriceData\"],\n): libraryPriceData is TLibraryPriceData {\n return libraryPriceData !== null && Array.isArray(libraryPriceData.breaks);\n}\n","//@ backend dafny\n\n/* Seconds and milliseconds as two types (2026-11-08). Verified with LemmaScript → Dafny\n (`pnpm proofs`; model: models/Durations.dfy, where they are two datatypes; link:\n models/links/foundation-duration.dfy).\n\n Both are branded: a plain `number` is neither, and a `Seconds` is not a `Millis`, so a TTL in\n seconds can't be passed where milliseconds are meant (augur-core's `staleTime` vs\n `redisTtl`), and a JWT `exp` can't be compared with `Date.now()` unconverted. Write a\n duration in the unit people think in (`minutes(15)`) and convert with `toMillis`; read a\n clock or a millisecond count back with `floorSeconds`. Values enter through the guards\n `secondsOf` / `millisOf` (an env value, a JSON `expires_in`); the clock is `millis(Date.now())`\n (the platform's time value is a whole, non-negative number of milliseconds).\n lsc writes both aliases as `nat` (no refinement, models/LSC-GAPS.md). */\n\n/** A whole number of seconds, made only by the builders and guards below. */\n//@ type nat\nexport type Seconds = number & { readonly __seconds: true };\n\n/** A whole number of milliseconds, made only by the builders and guards below. */\n//@ type nat\nexport type Millis = number & { readonly __millis: true };\n\n/**\n * `n` seconds.\n *\n * @ensures exactly the model's Seconds(n)\n */\nexport function seconds(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n\n return n as Seconds;\n}\n\n/**\n * `n` minutes, in seconds.\n *\n * @ensures exactly the model's Minutes\n */\nexport function minutes(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 60\n return (n * 60) as Seconds;\n}\n\n/**\n * `n` hours, in seconds.\n *\n * @ensures exactly the model's Hours\n */\nexport function hours(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 3600\n return (n * 3600) as Seconds;\n}\n\n/**\n * `n` days, in seconds.\n *\n * @ensures exactly the model's Days\n */\nexport function days(n: number): Seconds {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n * 86400\n return (n * 86400) as Seconds;\n}\n\n/**\n * `n` milliseconds: for a duration under a second (a retry backoff, a debounce).\n *\n * @ensures exactly the model's Millis(n)\n */\nexport function millis(n: number): Millis {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n\n return n as Millis;\n}\n\n/**\n * Seconds as milliseconds, exactly.\n *\n * @ensures exactly the model's ToMillis\n */\nexport function toMillis(d: Seconds): Millis {\n //@ verify\n //@ requires d >= 0\n //@ ensures \\result === d * 1000\n return (d * 1000) as Millis;\n}\n\n/**\n * Milliseconds as whole seconds, rounded down (a JWT `exp` or `iat` from a clock).\n *\n * @ensures exactly the model's FloorSeconds\n */\nexport function floorSeconds(m: Millis): Seconds {\n //@ verify\n //@ type m nat\n //@ requires m >= 0\n //@ ensures \\result === Math.floor(m / 1000)\n return Math.floor(m / 1000) as Seconds;\n}\n\n/**\n * A clock reading plus a duration, both `Millis`: when something expires (`addMillis(now,\n * toMillis(minutes(15)))`).\n *\n * @ensures exactly the model's AddMillis\n */\nexport function addMillis(a: Millis, b: Millis): Millis {\n //@ verify\n //@ requires a >= 0 && b >= 0\n //@ ensures \\result === a + b\n return (a + b) as Millis;\n}\n\n/**\n * A reading less a duration, never below 0 (a token used until a minute before it expires). An\n * expiry clamped to 0 is no more live than the negative one it stands for (the model's\n * MinusMillisKeepsLiveness).\n *\n * @ensures exactly the model's MinusMillis\n */\nexport function minusMillis(a: Millis, b: Millis): Millis {\n //@ verify\n //@ requires a >= 0 && b >= 0\n //@ ensures \\result === (a >= b ? a - b : 0)\n return a >= b ? ((a - b) as Millis) : millis(0);\n}\n\n/**\n * `n` as `Seconds`, or null when it is not a safe integer at least 0: a fraction, NaN, a\n * negative, an infinity, or past `Number.MAX_SAFE_INTEGER`. Where a number of seconds enters.\n *\n * @ensures exactly the model's AcceptedAsDuration, and the value is kept\n */\nexport function secondsOf(n: number): Seconds | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 0 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 0 && n <= 9007199254740991 ? (n as Seconds) : null;\n}\n\n/**\n * An outside count of seconds (a token's `expires_in`, a JWT's `exp`) as `Seconds`: rounded\n * down, and 0 when it is then no safe integer at least 0 (a negative, NaN, an infinity), so a\n * bad lifetime is no lifetime and a bad expiry is already past.\n *\n * @ensures exactly the model's WholeSeconds (the proof reads a number as an integer)\n */\nexport function wholeSeconds(n: number): Seconds {\n //@ verify\n //@ ensures (n >= 0 && n <= 9007199254740991) ==> \\result === n\n //@ ensures !(n >= 0 && n <= 9007199254740991) ==> \\result === 0\n const whole = secondsOf(Math.floor(n));\n return whole === null ? seconds(0) : whole;\n}\n\n/**\n * `n` as `Millis`, or null when it is not a safe integer at least 0 (the same rule as\n * `secondsOf`). Where a number of milliseconds enters.\n *\n * @ensures exactly the model's AcceptedAsDuration, and the value is kept\n */\nexport function millisOf(n: number): Millis | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 0 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 0 && n <= 9007199254740991 ? (n as Millis) : null;\n}\n","//@ backend dafny\nimport { hours, millis, minutes, toMillis } from \"@atlas/foundation/duration\";\nimport type { Millis } from \"./duration\";\n\n/* Small decisions the utils use, pulled out so they are proved. Verified with LemmaScript →\n Dafny (`pnpm proofs`; model: models/AugurUtils.dfy; link: models/links/augur-utils-rules.dfy).\n Each caller turns its record into these plain arguments; that mapping is tested. */\n\n/** An invoice's payment status, from its flag and amounts. */\nexport type PaymentStatus = \"Paid\" | \"Partially Paid\" | \"Unpaid\";\n\n/**\n * \"Paid\" when the invoice is flagged paid in full; else \"Partially Paid\" when both amounts are\n * present and something was paid; else \"Unpaid\". The total is never compared with the amount\n * (a finding: a full payment without the flag reads \"Partially Paid\").\n */\nexport function paymentStatusOf(\n paidInFull: boolean,\n hasAmounts: boolean,\n amountPaid: number,\n): PaymentStatus {\n //@ verify\n //@ ensures paidInFull ==> \\result === \"Paid\"\n //@ ensures !paidInFull && hasAmounts && amountPaid > 0 ==> \\result === \"Partially Paid\"\n //@ ensures !paidInFull && !(hasAmounts && amountPaid > 0) ==> \\result === \"Unpaid\"\n if (paidInFull) return \"Paid\";\n if (hasAmounts && amountPaid > 0) return \"Partially Paid\";\n return \"Unpaid\";\n}\n\n/** Low stock: in stock, a threshold set (above 0), and the quantity at or under it. */\nexport function isLowStockOf(quantity: number, threshold: number): boolean {\n //@ verify\n //@ ensures \\result === (quantity > 0 && threshold > 0 && quantity <= threshold)\n return quantity > 0 && threshold > 0 && quantity <= threshold;\n}\n\n/** Every flag from `i` on is \"Y\" (vacuously when there are none). */\nexport function allYesFrom(flags: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ decreases flags.length - i\n //@ ensures \\result === (forall(k: nat, i <= k && k < flags.length ==> flags[k] === \"Y\"))\n if (i >= flags.length) return true;\n return flags[i] === \"Y\" && allYesFrom(flags, i + 1);\n}\n\n/** Discontinued: there are stock rows, and every one says \"Y\". */\nexport function isDiscontinuedOf(flags: string[]): boolean {\n //@ verify\n //@ ensures \\result === (flags.length > 0 && allYesFrom(flags, 0))\n return flags.length > 0 && allYesFrom(flags, 0);\n}\n\n/** serializeCategoryFilters' sortBy: the prefix applied only when both are non-empty. */\nexport function categorySortBy(prefix: string, sortBy: string): string {\n //@ verify\n //@ ensures prefix !== \"\" && sortBy !== \"\" ==> \\result === prefix + sortBy\n //@ ensures !(prefix !== \"\" && sortBy !== \"\") ==> \\result === sortBy\n return prefix !== \"\" && sortBy !== \"\" ? prefix + sortBy : sortBy;\n}\n\n/** serializeSearchParams' sortBy: an empty one is left out. */\nexport function searchSortBy(sortBy: string): string | undefined {\n //@ verify\n //@ ensures sortBy !== \"\" ==> \\result === sortBy\n //@ ensures sortBy === \"\" ==> \\result === undefined\n return sortBy !== \"\" ? sortBy : undefined;\n}\n\n/** A page's first item. */\nexport function pageOffset(page: number, limit: number): number {\n //@ verify\n //@ ensures \\result === page * limit\n return page * limit;\n}\n\n/** unwrap's error message: the action's, or \"Action failed\" when it is empty. */\nexport function unwrapMessage(error: string): string {\n //@ verify\n //@ ensures error !== \"\" ==> \\result === error\n //@ ensures error === \"\" ==> \\result === \"Action failed\"\n return error !== \"\" ? error : \"Action failed\";\n}\n\n/** A shipping lead's business-day range; `to` is 0 for a single day. */\nexport interface ShippingLead {\n from: number;\n to: number;\n}\n\n/** The shipping-lead table: a days key's business-day range, or null for any other key. */\nexport function shippingLeadOf(days: string): ShippingLead | null {\n //@ verify\n //@ ensures days === \"1-2\" ==> \\result === { from: 1, to: 4 }\n //@ ensures days === \"2\" ==> \\result === { from: 4, to: 0 }\n //@ ensures days === \"2-3\" ==> \\result === { from: 2, to: 5 }\n //@ ensures days === \"3\" ==> \\result === { from: 5, to: 0 }\n //@ ensures days === \"3-4\" ==> \\result === { from: 3, to: 6 }\n //@ ensures days === \"4\" ==> \\result === { from: 6, to: 0 }\n //@ ensures days === \"5\" ==> \\result === { from: 7, to: 0 }\n //@ ensures !(days === \"1-2\" || days === \"2\" || days === \"2-3\" || days === \"3\" || days === \"3-4\" || days === \"4\" || days === \"5\") ==> \\result === null\n if (days === \"1-2\") return { from: 1, to: 4 };\n if (days === \"2\") return { from: 4, to: 0 };\n if (days === \"2-3\") return { from: 2, to: 5 };\n if (days === \"3\") return { from: 5, to: 0 };\n if (days === \"3-4\") return { from: 3, to: 6 };\n if (days === \"4\") return { from: 6, to: 0 };\n if (days === \"5\") return { from: 7, to: 0 };\n return null;\n}\n\n/** A business day is any day but Saturday and Sunday (by its en-US weekday name). */\nexport function isBusinessDayName(dayName: string): boolean {\n //@ verify\n //@ ensures \\result === (dayName !== \"Sunday\" && dayName !== \"Saturday\")\n return dayName !== \"Sunday\" && dayName !== \"Saturday\";\n}\n\n/** Schema.org availability, by the resolved stock's flags. */\nexport type Availability = \"InStock\" | \"OutOfStock\" | \"BackOrder\";\n\n/** In stock, else discontinued is out of stock, else back order (also with no stock record). */\nexport function availabilityOf(isInStock: boolean, isDiscontinued: boolean): Availability {\n //@ verify\n //@ ensures isInStock ==> \\result === \"InStock\"\n //@ ensures !isInStock && isDiscontinued ==> \\result === \"OutOfStock\"\n //@ ensures !isInStock && !isDiscontinued ==> \\result === \"BackOrder\"\n if (isInStock) return \"InStock\";\n if (isDiscontinued) return \"OutOfStock\";\n return \"BackOrder\";\n}\n\n/**\n * The first key from `i` whose value is present (neither null nor undefined), or −1:\n * `transformShipToAddress` reads that key (\"\" for −1), and a record is physical when any physical\n * marker is present.\n *\n * @ensures exactly the model's PresentIndexFrom (PresentIndexIsFirst: present, none before it)\n */\nexport function presentIndexFrom(present: boolean[], i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= present.length\n //@ decreases present.length - i\n //@ ensures i === present.length ==> \\result === -1\n //@ ensures i < present.length && present[i] ==> \\result === i\n //@ ensures i < present.length && !present[i] ==> \\result === presentIndexFrom(present, i + 1)\n if (i === present.length) return -1;\n if (present[i] === true) return i;\n return presentIndexFrom(present, i + 1);\n}\n\n/**\n * `getShippingLeadDate`'s text: \"from - to\" when the lead has a second day, else the one date.\n *\n * @ensures result = from + \" - \" + to when hasTo, else from: the model's LeadDateText\n */\nexport function leadDateText(from: string, hasTo: boolean, to: string): string {\n //@ verify\n //@ ensures \\result === (hasTo ? from + \" - \" + to : from)\n return hasTo ? from + \" - \" + to : from;\n}\n\n/** The order taker: the caller's, else \"ESTORE\". */\nexport function takerOf(taker: string | undefined): string {\n //@ verify\n //@ ensures taker !== undefined ==> \\result === taker\n //@ ensures taker === undefined ==> \\result === \"ESTORE\"\n return taker ?? \"ESTORE\";\n}\n\n/**\n * An address differs from its validated form when line 1 or the city differ after lower-casing\n * (compared by the caller with JS `toLowerCase`), or the state or zip differ exactly.\n *\n * @ensures exactly the model's AddressDifferent\n */\nexport function addressDifferentOf(\n line1Same: boolean,\n citySame: boolean,\n stateSame: boolean,\n zipSame: boolean,\n): boolean {\n //@ verify\n //@ ensures \\result === (!line1Same || !citySame || !stateSame || !zipSame)\n return !line1Same || !citySame || !stateSame || !zipSame;\n}\n\n/**\n * The gcTime a query gets: none on the server (`null`, which the caller turns into `Infinity`,\n * so query-core schedules no GC timer and a per-request cache is freed with the request), the\n * client's value in the browser. Moved from augur-core (#94) so the CACHE_CONFIG tiers use it.\n *\n * @ensures exactly the model's GcTime\n */\nexport function gcTimeFor(isServer: boolean, clientGcTime: Millis): Millis | null {\n //@ verify\n //@ ensures isServer ==> \\result === null\n //@ ensures !isServer ==> \\result === clientGcTime\n return isServer ? null : clientGcTime;\n}\n\n/** A CACHE_CONFIG tier's name. */\nexport type TierName = \"STATIC\" | \"SEMI_STATIC\" | \"DYNAMIC\" | \"CART\" | \"REALTIME\";\n\n/**\n * A tier's staleTime: STATIC 1 h, SEMI_STATIC 10 min, DYNAMIC 5 min, CART 2 min, REALTIME 0.\n *\n * @ensures exactly the model's TierStaleTime\n */\nexport function tierStaleTime(t: TierName): Millis {\n //@ verify\n //@ ensures t === \"STATIC\" ==> \\result === 3600000\n //@ ensures t === \"SEMI_STATIC\" ==> \\result === 600000\n //@ ensures t === \"DYNAMIC\" ==> \\result === 300000\n //@ ensures t === \"CART\" ==> \\result === 120000\n //@ ensures t === \"REALTIME\" ==> \\result === 0\n if (t === \"STATIC\") return toMillis(hours(1));\n if (t === \"SEMI_STATIC\") return toMillis(minutes(10));\n if (t === \"DYNAMIC\") return toMillis(minutes(5));\n if (t === \"CART\") return toMillis(minutes(2));\n return millis(0);\n}\n\n/**\n * A tier's gcTime in the browser: STATIC 24 h, SEMI_STATIC 4 h, DYNAMIC and CART 30 min,\n * REALTIME 5 min; never shorter than its staleTime. On the server the tier's gcTime is\n * `gcTimeFor(true, …)`: none.\n *\n * @ensures exactly the model's TierBrowserGcTime; result ≥ tierStaleTime(t)\n */\nexport function tierBrowserGcTime(t: TierName): Millis {\n //@ verify\n //@ ensures t === \"STATIC\" ==> \\result === 86400000\n //@ ensures t === \"SEMI_STATIC\" ==> \\result === 14400000\n //@ ensures (t === \"DYNAMIC\" || t === \"CART\") ==> \\result === 1800000\n //@ ensures t === \"REALTIME\" ==> \\result === 300000\n //@ ensures \\result >= tierStaleTime(t)\n if (t === \"STATIC\") return toMillis(hours(24));\n if (t === \"SEMI_STATIC\") return toMillis(hours(4));\n if (t === \"DYNAMIC\") return toMillis(minutes(30));\n if (t === \"CART\") return toMillis(minutes(30));\n return toMillis(minutes(5));\n}\n\n/**\n * Outside a browser (Node SSR, edge, Deno): no `window`, or Deno (which has one). Mirrors\n * query-core's `isServer`; runtime.ts reads the two facts per call.\n *\n * @ensures exactly the model's ServerRuntime\n */\nexport function serverRuntimeOf(hasWindow: boolean, hasDeno: boolean): boolean {\n //@ verify\n //@ ensures \\result <==> (!hasWindow || hasDeno)\n return !hasWindow || hasDeno;\n}\n","/**\n * Which runtime a query is built in, and the gcTime it gets there. The decision is the proved\n * `gcTimeFor` (rules.ts, model `AugurUtils.GcTime`); this file only reads the runtime. Moved\n * from augur-core (#94, 2026-11-07), which re-exports both, so the CACHE_CONFIG tiers can use\n * them: augur-core depends on augur-utils, never the other way.\n */\n\nimport type { Millis } from \"./duration\";\nimport { gcTimeFor, serverRuntimeOf } from \"./rules\";\n\n/**\n * Returns true when running outside a browser (Node SSR, edge, Deno).\n * Mirrors `isServer` in `@tanstack/query-core` (`build/modern/utils.js`).\n * Evaluated per call, not at module scope, so `\"use client\"` modules that\n * also run during SSR resolve correctly on each pass.\n */\nexport function isServerRuntime(): boolean {\n // augur-utils is cross-platform with no DOM lib, so read `window` off globalThis.\n const hasWindow = typeof (globalThis as { window?: unknown }).window !== \"undefined\";\n return serverRuntimeOf(hasWindow, \"Deno\" in globalThis);\n}\n\n/**\n * Returns the React Query `gcTime` to use for a query built in this runtime.\n * On the server returns `Infinity`, which query-core treats as \"schedule no\n * GC timer\", so a per-request QueryClient is freed when the request ends.\n * A finite value would start a timer that pins the whole request cache.\n * In the browser returns `clientGcTime` unchanged. The result is a `number`, not `Millis`:\n * `Infinity` is no whole number of milliseconds.\n */\nexport function resolveGcTime(clientGcTime: Millis): number {\n return gcTimeFor(isServerRuntime(), clientGcTime) ?? Infinity;\n}\n","import { tierBrowserGcTime, tierStaleTime, type TierName } from \"./rules\";\nimport { resolveGcTime } from \"./runtime\";\n\n/**\n * A tier: its staleTime and its gcTime in this runtime (a getter, read when the tier is). The\n * values are the proved `tierStaleTime` / `tierBrowserGcTime` (model `AugurUtils.Tier…`), the\n * runtime's choice the proved `gcTimeFor`; this only builds the object.\n */\nfunction tier(name: TierName) {\n return {\n staleTime: tierStaleTime(name),\n get gcTime(): number {\n return resolveGcTime(tierBrowserGcTime(name));\n },\n } as const;\n}\n\n/**\n * Centralized cache configuration for React Query (TanStack Query)\n *\n * staleTime -- How long cached data is considered \"fresh\". While fresh,\n * React Query serves the cache instantly and does NOT refetch in the\n * background. After staleTime expires the data is \"stale\" and will be\n * refetched on the next access (mount, window focus, etc.).\n *\n * gcTime (garbage collection time) -- How long UNUSED cached data stays in\n * memory after all components using it unmount. Once gcTime expires the\n * cache entry is deleted entirely. Server-safe (#94): each tier's gcTime is\n * read through `resolveGcTime`, so on the server it is `Infinity` (no GC\n * timer, the per-request cache is freed with the request) and in the browser\n * the value below, never shorter than the tier's staleTime (proved). It is\n * decided each time the tier is read, so spreading a tier after the proxy's\n * options (`{ ...q.items.get(id), ...CACHE_CONFIG.STATIC }`) is safe in a\n * `\"use client\"` module rendered on the server too.\n *\n * STATIC (1h, gc 24h): categories, menus, item details\n * SEMI_STATIC (10m, gc 4h): pricing, stock, search results\n * DYNAMIC (5m, gc 30m): infinite scroll data\n * CART (2m, gc 30m): cart lines, cart header\n * REALTIME (0, gc 5m): active orders, checkout state\n */\nexport const CACHE_CONFIG = {\n STATIC: tier(\"STATIC\"),\n SEMI_STATIC: tier(\"SEMI_STATIC\"),\n DYNAMIC: tier(\"DYNAMIC\"),\n CART: tier(\"CART\"),\n REALTIME: tier(\"REALTIME\"),\n} as const;\n\nexport type CacheTier = keyof typeof CACHE_CONFIG;\n","import * as duration from \"@atlas/foundation/duration\";\n\n/**\n * Seconds and milliseconds for the published augur-* packages (2026-11-08): the same two types\n * as `@atlas/utils/duration`, which is private (its code is bundled in, its types can't be\n * named in a published `.d.ts`). The brands are the same, so a `Seconds` from either package is\n * the other's (as the SDK's `SiteId` is auth-core's); the builders are the proved ones, passed\n * through (model `Utils` \"durations\", link `models/links/utils-duration.dfy`).\n *\n * A TTL in seconds can't go where milliseconds are meant: React Query's `staleTime` / `gcTime`\n * are `Millis`, a Redis TTL is `Seconds`. Write `toMillis(minutes(5))`, not `300000`.\n */\n\n/** A whole number of seconds (a Redis TTL, a JWT `exp`). */\n//@ type nat\nexport type Seconds = number & { readonly __seconds: true };\n\n/** A whole number of milliseconds (React Query's `staleTime` / `gcTime`, `Date.now()`). */\n//@ type nat\nexport type Millis = number & { readonly __millis: true };\n\n/** `n` seconds. */\nexport const seconds: (n: number) => Seconds = duration.seconds;\n/** `n` minutes, in seconds. */\nexport const minutes: (n: number) => Seconds = duration.minutes;\n/** `n` hours, in seconds. */\nexport const hours: (n: number) => Seconds = duration.hours;\n/** `n` days, in seconds. */\nexport const days: (n: number) => Seconds = duration.days;\n/** `n` milliseconds, for a duration under a second. */\nexport const millis: (n: number) => Millis = duration.millis;\n/** Seconds as milliseconds, exactly. */\nexport const toMillis: (d: Seconds) => Millis = duration.toMillis;\n/** A clock reading plus a duration, both milliseconds: when something expires. */\nexport const addMillis: (a: Millis, b: Millis) => Millis = duration.addMillis;\n/** A reading less a duration, never below 0. */\nexport const minusMillis: (a: Millis, b: Millis) => Millis = duration.minusMillis;\n/** Milliseconds as whole seconds, rounded down. */\nexport const floorSeconds: (m: Millis) => Seconds = duration.floorSeconds;\n/** `n` as `Seconds`, or null unless it is a safe integer at least 0. */\nexport const secondsOf: (n: number) => Seconds | null = duration.secondsOf;\n/** An outside count of seconds, rounded down; 0 when it is then no safe integer at least 0. */\nexport const wholeSeconds: (n: number) => Seconds = duration.wholeSeconds;\n/** `n` as `Millis`, or null unless it is a safe integer at least 0. */\nexport const millisOf: (n: number) => Millis | null = duration.millisOf;\n","/**\n * Locale-aware currency formatting.\n * Defaults to USD -- consumers can override locale and currency.\n */\nexport function formatPrice(\n price: number,\n locale: string = \"en-US\",\n currency: string = \"USD\",\n): string {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: 2,\n }).format(price);\n}\n","import { addressDifferentOf } from \"./rules\";\nimport type { TSmartyStreets } from \"./types/smarty-streets\";\n\n/** User-entered address fields for comparison. */\nexport interface UserAddress {\n address1: string;\n city: string;\n state: string;\n postalCode: string;\n}\n\n/**\n * Compares a user-entered address with a SmartyStreets-validated address.\n * Returns true if any field differs (case-insensitive for address/city,\n * exact match for state abbreviation and zip code).\n *\n * Used in checkout to prompt users when their input differs from the\n * USPS-validated address.\n */\nexport function isAddressDifferent(\n userAddress: UserAddress,\n smartyAddress: TSmartyStreets,\n): boolean {\n return addressDifferentOf(\n (smartyAddress.deliveryLine1 ?? \"\").toLowerCase() === userAddress.address1.toLowerCase(),\n (smartyAddress.cityName ?? \"\").toLowerCase() === userAddress.city.toLowerCase(),\n smartyAddress.stateAbbreviation === userAddress.state,\n smartyAddress.zipCode === userAddress.postalCode,\n );\n}\n","export type PaymentStatusInvoice = {\n paidInFullFlag?: string | null;\n amountPaid?: number;\n totalAmount?: number;\n};\n\nimport { paymentStatusOf, type PaymentStatus } from \"./rules\";\n\nexport type { PaymentStatus } from \"./rules\";\n\n/** Returns \"Paid\", \"Partially Paid\", or \"Unpaid\" based on invoice payment flags and amounts. */\nexport function getPaymentStatus(invoice: PaymentStatusInvoice): PaymentStatus {\n return paymentStatusOf(\n invoice.paidInFullFlag === \"Y\",\n invoice.amountPaid != null && invoice.totalAmount != null,\n invoice.amountPaid ?? 0,\n );\n}\n","export type ShipToAddress = {\n shipToId: string | number;\n name: string;\n address1: string;\n address2?: string;\n city: string;\n state: string;\n zip: string;\n country?: string;\n};\n\nimport { presentIndexFrom } from \"./rules\";\n\ntype RawShipTo = Record<string, unknown>;\n\nfunction str(value: unknown): string {\n return String(value).trim();\n}\n\n/** Whether each key's value is present (neither null nor undefined). */\nfunction presence(raw: RawShipTo, keys: readonly string[]): boolean[] {\n return keys.map((k) => raw[k] != null);\n}\n\n/** The value of the first key that is neither null nor undefined (the proved presentIndexFrom), else \"\". */\nfunction firstPresent(raw: RawShipTo, keys: readonly string[]): unknown {\n const index = presentIndexFrom(presence(raw, keys), 0);\n return index < 0 ? \"\" : raw[keys[index] as string];\n}\n\nfunction pick(raw: RawShipTo, keys: readonly string[]): string {\n return str(firstPresent(raw, keys));\n}\n\n// Physical records are detected by camelCase OR snake_case keys. Checking only the\n// camelCase variants misclassified snake_case-only physical records as mailing,\n// which then matched no MAIL_FIELDS key and returned empty fields.\nconst PHYS_MARKERS = [\n \"physAddress1\",\n \"phys_address1\",\n \"physCity\",\n \"phys_city\",\n \"physState\",\n \"phys_state\",\n] as const;\n\nconst PHYS_FIELDS = {\n address1: [\"physAddress1\", \"phys_address1\"],\n address2: [\"physAddress2\", \"phys_address2\"],\n city: [\"physCity\", \"phys_city\"],\n state: [\"physState\", \"phys_state\"],\n zip: [\"physPostalCode\", \"phys_postal_code\"],\n country: [\"physCountry\", \"phys_country\"],\n} as const;\n\nconst MAIL_FIELDS = {\n address1: [\"mailAddress1\", \"mail_address1\", \"address1\"],\n address2: [\"mailAddress2\", \"mail_address2\", \"address2\"],\n city: [\"mailCity\", \"mail_city\", \"city\"],\n state: [\"mailState\", \"mail_state\", \"state\"],\n zip: [\"mailPostalCode\", \"mail_postal_code\", \"postalCode\", \"zip\"],\n country: [\"mailCountry\", \"mail_country\", \"country\"],\n} as const;\n\n/** Normalizes a raw ship-to address object (camelCase or snake_case, physical or mailing) into a consistent ShipToAddress shape. */\nexport function transformShipToAddress(raw: RawShipTo): ShipToAddress {\n const isPhys = presentIndexFrom(presence(raw, PHYS_MARKERS), 0) >= 0;\n\n const f = isPhys ? PHYS_FIELDS : MAIL_FIELDS;\n\n const address: ShipToAddress = {\n shipToId: firstPresent(raw, [\"shipToId\", \"ship_to_id\", \"id\"]) as string | number,\n name: pick(raw, [\"shipToName\", \"ship_to_name\", \"name\"]),\n address1: pick(raw, f.address1),\n city: pick(raw, f.city),\n state: pick(raw, f.state),\n zip: pick(raw, f.zip),\n };\n\n const address2 = pick(raw, f.address2);\n if (address2) address.address2 = address2;\n\n const country = pick(raw, f.country);\n if (country) address.country = country;\n\n return address;\n}\n","//@ backend dafny\n\n/* Character classes over UTF-16 code units (what charCodeAt returns), verified with\n LemmaScript → Dafny (model: models/Foundation.dfy; link: models/links/foundation-chars.dfy).\n Every contract is an iff, so an importer, which sees only the contract, knows each class\n exactly. */\n\n/**\n * A decimal digit: 0-9.\n *\n * @ensures result ⟺ c ∈ [48, 57]\n */\nexport function isDigit(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> (c >= 48 && c <= 57)\n return c >= 48 && c <= 57;\n}\n\n/**\n * A JS line terminator (what regex `.` doesn't match): LF, CR, LS, PS.\n *\n * @ensures result ⟺ c ∈ {10, 13, 8232, 8233}\n */\nexport function isLineTerminator(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> (c === 10 || c === 13 || c === 8232 || c === 8233)\n return c === 10 || c === 13 || c === 8232 || c === 8233;\n}\n\n/**\n * The code ASCII-lowered: A-Z to a-z, any other value (-1 from `codeAt` included) unchanged.\n *\n * @ensures exactly the model's LowerCode\n */\nexport function lowerCode(c: number): number {\n //@ verify\n //@ ensures \\result === (c >= 65 && c <= 90 ? c + 32 : c)\n return c >= 65 && c <= 90 ? c + 32 : c;\n}\n/**\n * A lowercase ASCII letter: a-z.\n *\n * @ensures result ⟺ c ∈ [97, 122]\n */\nexport function isLowerAlphaChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> (c >= 97 && c <= 122)\n return c >= 97 && c <= 122;\n}\n\n/**\n * An ASCII letter or digit: A-Z a-z 0-9.\n *\n * @ensures result ⟺ c ∈ [A-Z] ∪ [a-z] ∪ [0-9]\n */\nexport function isAlnumChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57))\n return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57);\n}\n\n/**\n * A lowercase hex digit: 0-9 a-f.\n *\n * @ensures result ⟺ c ∈ [0-9] ∪ [a-f]\n */\nexport function isLowerHexChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 48 && c <= 57) || (c >= 97 && c <= 102))\n return (c >= 48 && c <= 57) || (c >= 97 && c <= 102);\n}\n\n/**\n * A hex digit in either case: 0-9 a-f A-F.\n *\n * @ensures result ⟺ c ∈ [0-9] ∪ [a-f] ∪ [A-F]\n */\nexport function isHexChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70))\n return (c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70);\n}\n\n/**\n * A base64url character (RFC 4648 §5): A-Z a-z 0-9 - _.\n *\n * @ensures result ⟺ c ∈ [A-Z] ∪ [a-z] ∪ [0-9] ∪ {\"-\", \"_\"} — never \".\" or \"=\"\n */\nexport function isBase64UrlChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 45 || c === 95)\n return (\n (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 45 || c === 95\n );\n}\n\n/**\n * JS whitespace, the regex `\\s` and what `trim()` strips: tab, LF, VT, FF, CR, space, NBSP,\n * U+1680, U+2000-U+200A, LS, PS, U+202F, U+205F, U+3000 and the BOM.\n *\n * @ensures result ⟺ c ∈ {9..13, 32, 160, 5760, 8192..8202, 8232, 8233, 8239, 8287, 12288, 65279}\n */\nexport function isJsSpace(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 9 && c <= 13) || c === 32 || c === 160 || c === 5760 || (c >= 8192 && c <= 8202) || c === 8232 || c === 8233 || c === 8239 || c === 8287 || c === 12288 || c === 65279)\n return isAsciiSpace(c) || isGeneralPunctuationSpace(c) || isOtherSpace(c);\n}\n\n/**\n * ASCII whitespace: tab, LF, VT, FF, CR and space.\n *\n * @ensures result ⟺ c ∈ [9, 13] ∪ {32}\n */\nfunction isAsciiSpace(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 9 && c <= 13) || c === 32)\n return (c >= 9 && c <= 13) || c === 32;\n}\n\n/**\n * The spaces in the General Punctuation block: U+2000-U+200A, LS, PS, U+202F, U+205F.\n *\n * @ensures result ⟺ c ∈ [8192, 8202] ∪ {8232, 8233, 8239, 8287}\n */\nfunction isGeneralPunctuationSpace(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 8192 && c <= 8202) || c === 8232 || c === 8233 || c === 8239 || c === 8287)\n return (c >= 8192 && c <= 8202) || c === 8232 || c === 8233 || c === 8239 || c === 8287;\n}\n\n/**\n * The other spaces: NBSP, U+1680 (Ogham), U+3000 (ideographic) and the BOM.\n *\n * @ensures result ⟺ c ∈ {160, 5760, 12288, 65279}\n */\nfunction isOtherSpace(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> (c === 160 || c === 5760 || c === 12288 || c === 65279)\n return c === 160 || c === 5760 || c === 12288 || c === 65279;\n}\n\n/**\n * A word character, the regex `\\w`: A-Z a-z 0-9 _.\n *\n * @ensures result ⟺ c ∈ [A-Z] ∪ [a-z] ∪ [0-9] ∪ {\"_\"}\n */\nexport function isWordChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95)\n return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95;\n}\n\n/**\n * A snake_case character: a-z 0-9 _.\n *\n * @ensures result ⟺ c ∈ [a-z] ∪ [0-9] ∪ {\"_\"}\n */\nexport function isSnakeChar(c: number): boolean {\n //@ verify\n //@ ensures \\result <==> ((c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95)\n return (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95;\n}\n","//@ backend dafny\nimport {\n isAlnumChar,\n isBase64UrlChar,\n isDigit,\n isHexChar,\n isJsSpace,\n isLineTerminator,\n isLowerHexChar,\n isSnakeChar,\n isWordChar,\n lowerCode,\n} from \"@atlas/foundation/chars\";\n\n/* String scans and slices, verified with LemmaScript → Dafny (hand lemmas in strings.dfy;\n model: models/Utils.dfy; link: models/links/utils-strings.dfy). Recursive and\n expression-bodied so specs can use them, and each contract pins the result exactly, so\n an importer (which sees only the contract) knows what it returns. Two of them stand in\n for constructs lsc mistranslates: `prefix` for an unclamped `slice`, and the code-unit\n scans for \"\\r\" / \"\\n\" literals. */\n\n/**\n * The code unit at `i`, or -1 when `i` is outside `s`. JS `charCodeAt` gives NaN there,\n * which no code equals, so a scan's own bounds test would change no result and no test\n * could tell it from none (an equivalent mutant); with the bound here once, the boundary is\n * observable (tests pin -1) and the scans that use it carry no bound of their own. A code\n * unit is never negative, so -1 matches no `code` a caller passes (`requires code >= 0`).\n *\n * @ensures 0 ≤ i < |s| ⟹ result = s[i]; otherwise result = -1\n */\nexport function codeAt(s: string, i: number): number {\n //@ verify\n //@ ensures (i >= 0 && i < s.length) ==> \\result === s.charCodeAt(i)\n //@ ensures !(i >= 0 && i < s.length) ==> \\result === -1\n return i >= 0 && i < s.length ? s.charCodeAt(i) : -1;\n}\n\n/**\n * Every character of `s` from index `i` on is base64url.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isBase64UrlChar(s[k])\n */\nexport function base64UrlFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isBase64UrlChar(s.charCodeAt(k)))\n return i >= s.length || (isBase64UrlChar(s.charCodeAt(i)) && base64UrlFrom(s, i + 1));\n}\n\n/**\n * The base64url digit for `v` (RFC 4648 §5): A-Z a-z 0-9 - _.\n *\n * @ensures exactly the model's Base64UrlDigit\n */\nexport function base64UrlDigit(v: number): string {\n //@ verify\n //@ type v nat\n //@ requires v >= 0 && v < 64\n //@ ensures \\result === \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\".slice(v, v + 1)\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\".slice(v, v + 1);\n}\n\n/**\n * Bytes from `i` on as unpadded base64url: each three as four digits, a last one or two as two or\n * three (JS `btoa` with `+/` as `-_` and the `=` dropped). One frame per three bytes: a JWT part\n * is a few hundred.\n *\n * @ensures exactly the model's Base64UrlFrom (links/utils-strings.dfy)\n */\nexport function encodeBase64UrlFrom(b: number[], i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && forall(k: nat, k < b.length ==> (b[k] >= 0 && b[k] < 256))\n //@ decreases b.length - i\n //@ ensures i >= b.length ==> \\result === \"\"\n if (i >= b.length) return \"\";\n const x = b[i] as number;\n const first = base64UrlDigit(Math.floor(x / 4));\n if (i + 1 === b.length) return first + base64UrlDigit((x % 4) * 16);\n const y = b[i + 1] as number;\n const second = base64UrlDigit((x % 4) * 16 + Math.floor(y / 16));\n if (i + 2 === b.length) return first + second + base64UrlDigit((y % 16) * 4);\n const z = b[i + 2] as number;\n return (\n first +\n second +\n base64UrlDigit((y % 16) * 4 + Math.floor(z / 64)) +\n base64UrlDigit(z % 64) +\n encodeBase64UrlFrom(b, i + 3)\n );\n}\n\n/**\n * Every character of `s` from index `i` on is lowercase hex.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isLowerHexChar(s[k])\n */\nexport function lowerHexFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isLowerHexChar(s.charCodeAt(k)))\n return i >= s.length || (isLowerHexChar(s.charCodeAt(i)) && lowerHexFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is hex, either case.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isHexChar(s[k])\n */\nexport function hexFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isHexChar(s.charCodeAt(k)))\n return i >= s.length || (isHexChar(s.charCodeAt(i)) && hexFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII digit (`\\d` without the `u` flag).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isDigit(s[k])\n */\nexport function digitsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isDigit(s.charCodeAt(k)))\n return i >= s.length || (isDigit(s.charCodeAt(i)) && digitsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is a word character (`\\w`: `[A-Za-z0-9_]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isWordChar(s[k])\n */\nexport function wordCharsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isWordChar(s.charCodeAt(k)))\n return i >= s.length || (isWordChar(s.charCodeAt(i)) && wordCharsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is a snake_case character (`[a-z0-9_]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isSnakeChar(s[k])\n */\nexport function snakeCharsFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isSnakeChar(s.charCodeAt(k)))\n return i >= s.length || (isSnakeChar(s.charCodeAt(i)) && snakeCharsFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII letter or digit (`[A-Za-z0-9]`).\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isAlnumChar(s[k])\n */\nexport function alnumFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> isAlnumChar(s.charCodeAt(k)))\n return i >= s.length || (isAlnumChar(s.charCodeAt(i)) && alnumFrom(s, i + 1));\n}\n\n/**\n * Every character of `s` from index `i` on is an ASCII letter, digit or `-` (`[A-Za-z0-9-]`):\n * a domain label's tail, a service name's tail.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). isAlnumChar(s[k]) ∨ s[k] = \"-\" — the model's AlnumDashFrom\n */\nexport function alnumDashFrom(s: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> (isAlnumChar(s.charCodeAt(k)) || s.charCodeAt(k) === 45))\n if (i >= s.length) return true;\n const c = s.charCodeAt(i);\n return (isAlnumChar(c) || c === 45) && alnumDashFrom(s, i + 1);\n}\n\n/**\n * The last index before `end` holding `code`, or -1 (JS `s.lastIndexOf(c)` at end = |s|).\n *\n * @ensures result = -1 ∨ (0 ≤ result < end ∧ s[result] = code ∧ no `code` in (result, end))\n */\nexport function lastIndexOfCode(s: string, code: number, end: number): number {\n //@ verify\n //@ type end nat\n //@ requires 0 <= end && end <= s.length\n //@ decreases end\n //@ ensures \\result === -1 || (0 <= \\result && \\result < end)\n //@ ensures \\result >= 0 ==> s.charCodeAt(\\result) === code\n //@ ensures \\result >= 0 ==> forall(k: nat, (\\result < k && k < end) ==> s.charCodeAt(k) !== code)\n //@ ensures \\result === -1 ==> forall(k: nat, k < end ==> s.charCodeAt(k) !== code)\n if (end === 0) return -1;\n if (s.charCodeAt(end - 1) === code) return end - 1;\n return lastIndexOfCode(s, code, end - 1);\n}\n\n/**\n * No character of `s` from index `i` on is `code`.\n *\n * @ensures result ⟺ ∀ k ∈ [i, |s|). s[k] ≠ code\n */\nexport function lacksCode(s: string, code: number, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result <==> forall(k: nat, (i <= k && k < s.length) ==> s.charCodeAt(k) !== code)\n // `===`, not `>=`: past the end a read is NaN !== code, so `>=` vs `>` would be equivalent\n return i === s.length || (s.charCodeAt(i) !== code && lacksCode(s, code, i + 1));\n}\n\n/**\n * The end of the run of `code` starting at `i`: the first index ≥ i that isn't `code`\n * (skip spaces: `codeRunEnd(header, 32, i)`).\n *\n * @requires i ≤ |s|\n * @ensures i ≤ result ≤ |s| ∧ ∀ k ∈ [i, result). s[k] = code ∧ (result < |s| ⟹ s[result] ≠ code)\n * — exactly the run's end\n */\nexport function codeRunEnd(s: string, code: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ requires code >= 0\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> s.charCodeAt(k) === code)\n //@ ensures \\result < s.length ==> s.charCodeAt(\\result) !== code\n return codeAt(s, i) === code ? codeRunEnd(s, code, i + 1) : i;\n}\n\n/**\n * The first index ≥ `from` holding `code`, or -1 (`indexOf` for one code unit, so \"\\n\" is\n * passed as 10, never as a literal).\n *\n * @ensures result = -1 ∨ (from ≤ result < |s| ∧ s[result] = code), with no `code` in\n * [from, result) — the first one; result = -1 ⟹ none from `from` on\n */\nexport function indexOfCode(s: string, code: number, from: number): number {\n //@ verify\n //@ type from nat\n //@ requires code >= 0 && from >= 0\n //@ decreases s.length - from\n //@ ensures \\result === -1 || (from <= \\result && \\result < s.length)\n //@ ensures \\result >= 0 ==> s.charCodeAt(\\result) === code\n //@ ensures \\result >= 0 ==> forall(k: nat, (from <= k && k < \\result) ==> s.charCodeAt(k) !== code)\n //@ ensures \\result === -1 ==> forall(k: nat, (from <= k && k < s.length) ==> s.charCodeAt(k) !== code)\n const c = codeAt(s, from);\n if (c === code) return from;\n if (c === -1) return -1;\n return indexOfCode(s, code, from + 1);\n}\n\n/**\n * The first index ≥ `i` holding `a` or `b`, or |s| (a run either code ends: a path segment's\n * run to \"/\" or \"?\"). One scan: the lesser of two `indexOfCode` ends is the same index, but\n * its two sides are equal only when both are |s|, a boundary no test can observe.\n *\n * @requires i ≤ |s|\n * @ensures i ≤ result ≤ |s| ∧ ∀ k ∈ [i, result). s[k] ∉ {a, b} ∧ (result < |s| ⟹ s[result] ∈ {a, b})\n * — exactly the first such index\n */\nexport function eitherCodeEnd(s: string, a: number, b: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ requires a >= 0 && b >= 0\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> (s.charCodeAt(k) !== a && s.charCodeAt(k) !== b))\n //@ ensures \\result < s.length ==> (s.charCodeAt(\\result) === a || s.charCodeAt(\\result) === b)\n const c = codeAt(s, i);\n if (c === -1 || c === a || c === b) return i;\n return eitherCodeEnd(s, a, b, i + 1);\n}\n\n/**\n * `s` without one trailing `code` (\"\\r\" before a \"\\n\", say); unchanged otherwise.\n *\n * @ensures s ends with code ⟹ result = s[0, |s| − 1)\n * @ensures otherwise result = s\n */\nexport function dropLast(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures (s.length > 0 && s.charCodeAt(s.length - 1) === code) ==> \\result === s.slice(0, s.length - 1)\n //@ ensures !(s.length > 0 && s.charCodeAt(s.length - 1) === code) ==> \\result === s\n return codeAt(s, s.length - 1) === code ? s.slice(0, s.length - 1) : s;\n}\n\n/**\n * `s` without its leading `code` units (every one of them).\n *\n * @ensures exactly the model's LStripCode\n */\nexport function lStripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ decreases s.length\n //@ ensures \\result.length <= s.length\n if (codeAt(s, 0) === code) return lStripCode(s.slice(1), code);\n return s;\n}\n\n/**\n * `s` without its trailing `code` units (every one of them).\n *\n * @ensures exactly the model's RStripCode\n */\nexport function rStripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ decreases s.length\n //@ ensures \\result.length <= s.length\n if (codeAt(s, s.length - 1) === code) {\n return rStripCode(s.slice(0, s.length - 1), code);\n }\n return s;\n}\n\n/**\n * `s` without its leading and trailing `code` units, the middle kept (`/a/b/` with `/` →\n * `a/b`).\n *\n * @ensures exactly the model's StripCode — neither end is `code` (StripCodeTrims)\n */\nexport function stripCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures \\result === rStripCode(lStripCode(s, code), code)\n return rStripCode(lStripCode(s, code), code);\n}\n\n/**\n * JS `s.startsWith(x, pos)`, which lsc mistranslates (it drops `pos`). Like JS, a `pos`\n * past the end counts as the end, so the empty string matches anywhere.\n *\n * @ensures pos ≤ |s| ⟹ (result ⟺ pos + |x| ≤ |s| ∧ s[pos, pos + |x|) = x) — so a true\n * result also gives the bounds for slicing after the match\n * @ensures pos > |s| ⟹ (result ⟺ x = \"\")\n */\nexport function startsWithAt(s: string, x: string, pos: number): boolean {\n //@ verify\n //@ type pos nat\n //@ requires pos >= 0\n //@ ensures pos <= s.length ==> (\\result <==> (pos + x.length <= s.length && s.slice(pos, pos + x.length) === x))\n //@ ensures pos > s.length ==> (\\result <==> x.length === 0)\n // Math.min, not a ternary: at pos = |s| both branches agree, so `<` vs `<=` is equivalent\n const at = Math.min(pos, s.length);\n // The slice is clamped to the end, so a too-long x differs by length: no separate fit test\n // (JS slice clamps too, which made one unobservable)\n return s.slice(at, Math.min(at + x.length, s.length)) === x;\n}\n\n/**\n * `s` with A-Z lowercased and every other character kept: what lsc's proofs take\n * `toLowerCase()` to be. JS's `toLowerCase()` also maps non-ASCII letters, some onto ASCII\n * (the Kelvin sign K, U+212A, becomes \"k\") or onto two characters (İ, U+0130), so a proved\n * function that lowercases MUST use this, or the runtime does what the proof says it\n * doesn't.\n *\n * @ensures |result| = |s| ∧ ∀ k < |s|. result[k] = (s[k] ∈ A-Z ? s[k] + 32 : s[k]) — A-Z\n * lowered, every other code unit unchanged; true in JS (a contract `=== s.toLowerCase()` held\n * only in lsc's ASCII model of the built-in, Fable review 2026-11-06). Helper-free, since an\n * importer is given only the helpers its own body calls; exactly the model's LowerAscii in\n * the link\n */\nexport function lowerAscii(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures \\result.length === s.length\n //@ ensures forall(k: nat, k < s.length ==> \\result.charCodeAt(k) === ((s.charCodeAt(k) >= 65 && s.charCodeAt(k) <= 90) ? s.charCodeAt(k) + 32 : s.charCodeAt(k)))\n if (s.length === 0) return \"\";\n const c = s.charCodeAt(0);\n const head =\n c >= 65 && c <= 90 ? \"abcdefghijklmnopqrstuvwxyz\".slice(c - 65, c - 64) : s.slice(0, 1);\n return head + lowerAscii(s.slice(1));\n}\n\n/**\n * `lowerAscii` as a loop: a constant stack depth (and linear time) on long text, where the\n * recursive spec takes a frame and a slice per character.\n *\n * @ensures result = lowerAscii(s)\n */\nexport function lowerAsciiText(s: string): string {\n //@ verify\n //@ ensures \\result === lowerAscii(s)\n let out = \"\";\n let i = 0;\n while (i !== s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + lowerAscii(s.slice(i)) === lowerAscii(s)\n //@ decreases s.length - i\n const c = s.charCodeAt(i);\n out =\n out +\n (c >= 65 && c <= 90 ? \"abcdefghijklmnopqrstuvwxyz\".slice(c - 65, c - 64) : s.slice(i, i + 1));\n i = i + 1;\n }\n return out;\n}\n\n/**\n * Whether `x` from index `k` matches `s` from `pos + k`, code by code, ASCII-lowered. A code\n * past the end of `s` is -1 (`codeAt`), which no code of `x` is, so there is no bound to\n * check (a `pos + |x| ≤ |s|` guard before a slice never changed the answer at runtime, where\n * `slice` clamps: an equivalent mutant, 2026-11-02).\n *\n * @ensures exactly the model's CaselessFrom\n */\nexport function caselessFrom(s: string, x: string, pos: number, k: number): boolean {\n //@ verify\n //@ type pos nat\n //@ type k nat\n //@ requires pos >= 0 && k >= 0 && k <= x.length\n //@ decreases x.length - k\n //@ ensures k === x.length ==> \\result\n if (k === x.length) return true;\n return lowerCode(codeAt(s, pos + k)) === x.charCodeAt(k) && caselessFrom(s, x, pos, k + 1);\n}\n\n/**\n * Whether the text of `s` at `pos`, ASCII-lowered, is `x` (`x` given lowercase): a case-free\n * `startsWith`; callers carry no length guard of their own. Only `pos ≤ |s|` is checked: it\n * decides an empty `x` past the end, the one case the code-by-code test can't see.\n *\n * @ensures result ⟺ pos + |x| ≤ |s| ∧ ∀ j < |x|. lowered(s[pos + j]) = x[j] — the text at pos,\n * ASCII-lowered (A-Z + 32), is x; helper-free; exactly the model's StartsWithCaseless in the link\n */\nexport function startsWithCaseless(s: string, x: string, pos: number): boolean {\n //@ verify\n //@ type pos nat\n //@ requires pos >= 0\n //@ ensures \\result <==> (pos + x.length <= s.length && forall(j: nat, j < x.length ==> ((s.charCodeAt(pos + j) >= 65 && s.charCodeAt(pos + j) <= 90) ? s.charCodeAt(pos + j) + 32 : s.charCodeAt(pos + j)) === x.charCodeAt(j)))\n return pos <= s.length && caselessFrom(s, x, pos, 0);\n}\n\n/**\n * Whether `s` ends with `suffix` (JS one-argument `endsWith`, which lsc reads as its\n * two-argument form; moved from the augur-api generator 2026-11-01).\n *\n * @ensures result ⟺ |s| ≥ |suffix| ∧ s[|s| − |suffix|, |s|) = suffix — exactly the model's EndsWith\n */\nexport function endsWith(s: string, suffix: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s.length >= suffix.length && s.slice(s.length - suffix.length) === suffix)\n // No length test: from max(|s| − |suffix|, 0), a too-long suffix compares unequal by length\n return s.slice(Math.max(s.length - suffix.length, 0)) === suffix;\n}\n\n/**\n * The order of `a` and `b` by UTF-16 code unit from index `i`, as a recursive spec: -1, 0\n * or 1 (JS `<` on strings; a proper prefix comes first). Locale-free, unlike `localeCompare`.\n *\n * @ensures result ∈ {-1, 0, 1} — exactly the model's CompareFrom\n */\nexport function compareFrom(a: string, b: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases a.length - i\n //@ ensures \\result === -1 || \\result === 0 || \\result === 1\n if (i >= a.length) return i >= b.length ? 0 : -1;\n if (i >= b.length) return 1;\n const x = a.charCodeAt(i);\n const y = b.charCodeAt(i);\n if (x < y) return -1;\n if (x > y) return 1;\n return compareFrom(a, b, i + 1);\n}\n\n/**\n * The order of two strings by UTF-16 code unit, for `sort` (what the default `sort` uses on\n * strings), so sorted output never depends on locale.\n *\n * @ensures result = compareFrom(a, b, 0)\n */\nexport function compareCodeUnits(a: string, b: string): number {\n //@ verify\n //@ ensures \\result === compareFrom(a, b, 0)\n return compareFrom(a, b, 0);\n}\n\n/**\n * JS `s.slice(0, n)`: at most `n` characters, clamped to the length. lsc reads a bare\n * `slice(0, n)` without JS's clamp, so use this instead.\n *\n * @ensures result = s[0, min(n, |s|))\n */\nexport function prefix(s: string, n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures n < s.length ==> \\result === s.slice(0, n)\n //@ ensures n >= s.length ==> \\result === s\n // Math.min, not a ternary: JS slice already clamps, so a ternary's branch is unobservable\n return s.slice(0, Math.min(n, s.length));\n}\n\n/**\n * The end of the JS-whitespace (`\\s`) run starting at `i`: the first index ≥ i that is not\n * whitespace, or |s|.\n *\n * @ensures i ≤ result ≤ |s| ∧ s[i, result) all whitespace ∧ (result = |s| ∨ ¬space(s[result]))\n */\nexport function spaceRunEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> isJsSpace(s.charCodeAt(k)))\n //@ ensures \\result < s.length ==> !isJsSpace(s.charCodeAt(\\result))\n // codeAt is -1 at the end, which is no space: the bound needs no test of its own here\n if (!isJsSpace(codeAt(s, i))) return i;\n return spaceRunEnd(s, i + 1);\n}\n\n/**\n * The end of the ASCII-digit run starting at `i` (a regex's `\\d+`, from `i`): the first index\n * ≥ i that is not 0-9, or |s|.\n *\n * @ensures i ≤ result ≤ |s| ∧ s[i, result) all digits ∧ (result = |s| ∨ ¬digit(s[result])) —\n * exactly the model's DigitRunEnd\n */\nexport function digitRunEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))\n //@ ensures \\result < s.length ==> !(s.charCodeAt(\\result) >= 48 && s.charCodeAt(\\result) <= 57)\n // codeAt is -1 at the end, which is no digit\n if (!isDigit(codeAt(s, i))) return i;\n return digitRunEnd(s, i + 1);\n}\n\n/**\n * A natural number written canonically (`^(0|[1-9][0-9]*)$`): the keys JS objects move\n * first, ahead of their source order.\n *\n * @ensures exactly the model's CanonicalNat, stated over the codes themselves so an importer\n * can use it (a contract naming `digitsFrom` can't be resolved there, models/LSC-GAPS.md)\n */\nexport function isCanonicalNat(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s === \"0\" || (s.length > 0 && s.charCodeAt(0) >= 49 && s.charCodeAt(0) <= 57 && forall(k: nat, (1 <= k && k < s.length) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))))\n if (s === \"0\") return true;\n const first = codeAt(s, 0);\n return first >= 49 && first <= 57 && digitsFrom(s, 1);\n}\n\n/**\n * The value of a run of decimal digits, most significant first (\"\" is 0).\n *\n * @requires ∀ k ∈ [0, |s|). isDigit(s[k])\n * @ensures exactly the model's DigitsValue (proved in links/utils-strings.dfy)\n */\nexport function digitsValue(s: string): number {\n //@ verify\n //@ requires forall(k: nat, k < s.length ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57))\n //@ decreases s.length\n //@ ensures \\result >= 0\n if (s.length === 0) return 0;\n return digitsValue(s.slice(0, s.length - 1)) * 10 + (s.charCodeAt(s.length - 1) - 48);\n}\n\n/**\n * What a number from the environment means (owner 2026-11-04: a bad one fails at start):\n * \"default\" when unset (\"\": the wrapper reads a missing variable as \"\"), \"value\" when it is\n * a canonical natural number at least `min` (its value is `digitsValue(raw)`), and \"bad\"\n * otherwise: a sign, a space, a fraction, an exponent, hex, text, or below `min`.\n *\n * @ensures exactly the model's EnvNumberOf (proved in links/utils-strings.dfy)\n */\nexport function envNumberKind(raw: string, min: number): string {\n //@ verify\n //@ type min nat\n //@ ensures raw === \"\" ==> \\result === \"default\"\n //@ ensures (raw !== \"\" && !isCanonicalNat(raw)) ==> \\result === \"bad\"\n if (raw === \"\") return \"default\";\n if (!isCanonicalNat(raw)) return \"bad\";\n return digitsValue(raw) < min ? \"bad\" : \"value\";\n}\n\n/**\n * A canonical natural number's value, 0 for any other text (a count written as JSON).\n *\n * @ensures exactly the model's CanonicalNatValue (in the link: `digitsValue` needs the digits\n * isCanonicalNat's contract gives, which a contract can't call for); 0 for other text\n */\nexport function canonicalNatValue(s: string): number {\n //@ verify\n //@ ensures \\result >= 0\n //@ ensures !isCanonicalNat(s) ==> \\result === 0\n if (!isCanonicalNat(s)) return 0;\n return digitsValue(s);\n}\n\n/**\n * The first index ≥ `i` holding a line terminator, or |s|: where a regex `.+` started at `i`\n * stops.\n *\n * @ensures i ≤ result ≤ |s| ∧ no terminator in s[i, result) ∧ (result = |s| ∨ terminator at result)\n */\nexport function lineEnd(s: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures i <= \\result && \\result <= s.length\n //@ ensures forall(k: nat, (i <= k && k < \\result) ==> !isLineTerminator(s.charCodeAt(k)))\n //@ ensures \\result < s.length ==> isLineTerminator(s.charCodeAt(\\result))\n if (i === s.length || isLineTerminator(s.charCodeAt(i))) return i;\n return lineEnd(s, i + 1);\n}\n\n/**\n * The largest p with lo ≤ p < hi whose character is not a line terminator, or -1: where a\n * backtracking regex `.` can start.\n *\n * @ensures result = -1 ∨ (lo ≤ result < hi ∧ ¬terminator(s[result]) ∧ only terminators in (result, hi))\n */\nexport function lastLineCharBelow(s: string, hi: number, lo: number): number {\n //@ verify\n //@ type hi nat\n //@ type lo nat\n //@ requires 0 <= lo && 0 <= hi && hi <= s.length\n //@ decreases hi\n //@ ensures \\result === -1 || (lo <= \\result && \\result < hi)\n //@ ensures \\result >= 0 ==> !isLineTerminator(s.charCodeAt(\\result))\n //@ ensures \\result >= 0 ==> forall(k: nat, (\\result < k && k < hi) ==> isLineTerminator(s.charCodeAt(k)))\n //@ ensures \\result === -1 ==> forall(k: nat, (lo <= k && k < hi) ==> isLineTerminator(s.charCodeAt(k)))\n if (hi <= lo) return -1;\n if (!isLineTerminator(s.charCodeAt(hi - 1))) return hi - 1;\n return lastLineCharBelow(s, hi - 1, lo);\n}\n\n/**\n * Nothing but JS whitespace (`s.trim() === \"\"`).\n *\n * @ensures exactly the model's Blank\n */\nexport function isBlank(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> s.trim() === \"\"\n return s.trim() === \"\";\n}\n\n/**\n * The first index ≥ `i` where `x` occurs in `s`, or -1 (JS `s.indexOf(x, i)` for i ≤ |s|).\n *\n * @ensures result = -1 ∨ (i ≤ result ∧ s[result, result + |x|) = x) — and the first such\n * index: links/utils-strings.dfy proves it is exactly the model's IndexOfFrom (lsc can't\n * give the \"no earlier match\" quantifier a trigger)\n */\nexport function indexOfFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result + x.length <= s.length)\n //@ ensures \\result >= 0 ==> s.slice(\\result, \\result + x.length) === x\n // A match here, else the end, else the next index: stopping at `i === |s|` (not \"x no\n // longer fits\") leaves no bound whose slip a later, harmless step would hide\n if (startsWithAt(s, x, i)) return i;\n if (i === s.length) return -1;\n return indexOfFrom(s, x, i + 1);\n}\n\n/**\n * `indexOfFrom` as a loop: the same answer at a constant stack depth, for text long enough that\n * one frame per character would overflow the stack (a rendered page, 50–60 KB with its inlined\n * stylesheet). Specs and links use `indexOfFrom`; runtime scans over long text use this.\n *\n * @ensures result = indexOfFrom(s, x, i)\n */\nexport function findFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ ensures \\result === indexOfFrom(s, x, i)\n let k = i;\n while (k !== s.length) {\n //@ invariant i <= k && k <= s.length\n //@ invariant indexOfFrom(s, x, k) === indexOfFrom(s, x, i)\n //@ decreases s.length - k\n if (startsWithAt(s, x, k)) return k;\n k = k + 1;\n }\n return startsWithAt(s, x, k) ? k : -1;\n}\n\n/**\n * `indexOfCode` as a loop: the same answer at a constant stack depth (see `findFrom`).\n *\n * @ensures result = indexOfCode(s, code, from)\n */\nexport function findCodeFrom(s: string, code: number, from: number): number {\n //@ verify\n //@ type from nat\n //@ requires code >= 0 && from >= 0\n //@ ensures \\result === indexOfCode(s, code, from)\n let k = from;\n while (k < s.length) {\n //@ invariant from <= k\n //@ invariant indexOfCode(s, code, k) === indexOfCode(s, code, from)\n //@ decreases s.length - k\n if (s.charCodeAt(k) === code) return k;\n k = k + 1;\n }\n return -1;\n}\n\n/**\n * How many times `x` occurs in `s` from `i` on, left to right without overlaps (repeated JS\n * `s.indexOf(x, at + x.length)`).\n *\n * @requires |x| > 0\n * @ensures result ≥ 0 — exactly the model's CountFrom (links/utils-strings.dfy)\n */\nexport function countFrom(s: string, x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires x.length > 0 && i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result >= 0\n const at = indexOfFrom(s, x, i);\n if (at === -1) return 0;\n return 1 + countFrom(s, x, at + x.length);\n}\n\n/**\n * `countFrom(s, x, 0)` as a loop: a constant stack depth on long text (see `findFrom`).\n *\n * @requires |x| > 0\n * @ensures result = countFrom(s, x, 0)\n */\nexport function countOf(s: string, x: string): number {\n //@ verify\n //@ requires x.length > 0\n //@ ensures \\result === countFrom(s, x, 0)\n let n = 0;\n let i = 0;\n let at = findFrom(s, x, 0);\n while (at !== -1) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant at === indexOfFrom(s, x, i)\n //@ invariant n + countFrom(s, x, i) === countFrom(s, x, 0)\n //@ decreases s.length - i\n n = n + 1;\n i = at + x.length;\n at = findFrom(s, x, i);\n }\n return n;\n}\n\n/**\n * The text before the first `code`, or all of it when there is none (JS `s.split(c)[0]`).\n *\n * @ensures result = s[0, first code) when s holds one, else s — the model's UntilCode\n */\nexport function untilCode(s: string, code: number): string {\n //@ verify\n //@ requires code >= 0\n //@ ensures \\result === (indexOfCode(s, code, 0) >= 0 && indexOfCode(s, code, 0) <= s.length ? s.slice(0, indexOfCode(s, code, 0)) : s)\n const k = indexOfCode(s, code, 0);\n return k >= 0 ? s.slice(0, k) : s;\n}\n\n/**\n * `s` from `i` on split at every `code` (JS `s.split(c)` at i = 0, for a one-character\n * separator): always at least one part.\n *\n * @ensures |result| ≥ 1 — exactly the model's SplitCodeFrom (links/utils-strings.dfy)\n */\nexport function splitCodeFrom(s: string, code: number, i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires code >= 0 && i >= 0 && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result.length > 0\n const k = indexOfCode(s, code, i);\n if (k === -1) return [s.slice(i)];\n return [s.slice(i, k), ...splitCodeFrom(s, code, k + 1)];\n}\n\n/**\n * Every run of JS whitespace in `s` from `i` on as one space (JS `s.replace(/\\s+/g, \" \")` at\n * i = 0).\n *\n * @ensures |result| ≤ |s| − i — exactly the model's CollapseSpacesFrom (links/utils-strings.dfy)\n */\nexport function collapseSpacesFrom(s: string, i: number): string {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result.length <= s.length - i\n if (i === s.length) return \"\";\n if (isJsSpace(s.charCodeAt(i))) return \" \" + collapseSpacesFrom(s, spaceRunEnd(s, i));\n return s.slice(i, i + 1) + collapseSpacesFrom(s, i + 1);\n}\n\n/**\n * `collapseSpacesFrom(s, 0)` at a constant stack depth (a page's text is tens of KB).\n *\n * @ensures result = collapseSpacesFrom(s, 0)\n */\nexport function collapseSpaces(s: string): string {\n //@ verify\n //@ ensures \\result === collapseSpacesFrom(s, 0)\n let out = \"\";\n let i = 0;\n while (i < s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + collapseSpacesFrom(s, i) === collapseSpacesFrom(s, 0)\n //@ decreases s.length - i\n if (isJsSpace(s.charCodeAt(i))) {\n out = out + \" \";\n // the run's end as a loop too: spaceRunEnd takes a frame per space (Fable review 2026-11-06)\n let e = i + 1;\n while (e !== s.length && isJsSpace(s.charCodeAt(e))) {\n //@ invariant i < e && e <= s.length\n //@ invariant forall(k: nat, (i <= k && k < e) ==> isJsSpace(s.charCodeAt(k)))\n //@ decreases s.length - e\n e = e + 1;\n }\n i = e;\n } else {\n out = out + s.slice(i, i + 1);\n i = i + 1;\n }\n }\n return out;\n}\n\n/**\n * `n` spaces.\n *\n * @ensures result = \" \" repeated n times — the model's Spaces\n */\nexport function spaces(n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ decreases n\n //@ ensures \\result.length === n\n //@ ensures forall(k: nat, k < n ==> \\result.charCodeAt(k) === 32)\n // `<= 0`, not `=== 0`: the same for a nat, and a fraction a caller slips in (outside the\n // contract) ends instead of recursing forever (Fable review 2026-11-06: spaces(0.5))\n if (n <= 0) return \"\";\n return \" \" + spaces(n - 1);\n}\n\n/**\n * A line feed, `\"\\n\"`, for proved text that spans lines: lsc emits a `\"\\n\"` escape raw, which\n * Dafny cannot parse (models/LSC-GAPS.md), so the contract pins it by code unit and the body is\n * a template literal holding the line break itself.\n *\n * @ensures result = \"\\n\" — one code unit, 10\n */\nexport function lineFeed(): string {\n //@ verify\n //@ ensures \\result.length === 1 && \\result.charCodeAt(0) === 10\n return `\n`;\n}\n\n/**\n * `s` padded on the left with spaces to `width` (JS `s.padStart(width)`).\n *\n * @ensures result = Spaces(width − |s|) + s when width > |s|, else s\n */\nexport function padLeft(s: string, width: number): string {\n //@ verify\n //@ ensures width <= s.length ==> \\result === s\n // width > |s| ⟹ spaces(width − |s|) + s: a hand ensures in strings.dfy, so importers'\n // axioms name no helper (models/LSC-GAPS.md). Math.max, not a ternary: at width = |s|\n // both branches agree (spaces(0) is \"\"), so `>` vs `>=` would be equivalent.\n return spaces(Math.max(width - s.length, 0)) + s;\n}\n\n/**\n * `s` padded on the right with spaces to `width` (JS `s.padEnd(width)`).\n *\n * @ensures result = s + Spaces(width − |s|) when width > |s|, else s\n */\nexport function padRight(s: string, width: number): string {\n //@ verify\n //@ ensures width <= s.length ==> \\result === s\n // width > |s| ⟹ s + spaces(width − |s|): a hand ensures in strings.dfy, as padLeft's.\n return s + spaces(Math.max(width - s.length, 0));\n}\n\n/**\n * An optional part of a key: `tag` then `text`, or nothing when `text` is empty, so an absent\n * part never leaves a bare tag.\n *\n * @ensures result = \"\" when text = \"\", else tag + text — exactly the model's KeyPart\n */\nexport function keyPart(tag: string, text: string): string {\n //@ verify\n //@ ensures \\result === (text === \"\" ? \"\" : tag + text)\n return text === \"\" ? \"\" : tag + text;\n}\n\n/**\n * Two texts joined by one space: the one rule behind a loader key's `<column> <direction>`, a\n * sync line's `METHOD /path` and a field's description then note.\n *\n * @ensures result = a + \" \" + b — exactly the model's SpaceJoined\n */\nexport function spaceJoined(a: string, b: string): string {\n //@ verify\n //@ ensures \\result === a + \" \" + b\n return a + \" \" + b;\n}\n\n/**\n * The first code point of `w` as text: a surrogate pair whole, else the first code unit, or \"\"\n * (Fable review 2026-11-06: an astral initial was a lone surrogate).\n *\n * @ensures exactly the model's FirstChar\n */\nexport function firstCodePoint(w: string): string {\n //@ verify\n //@ ensures \\result === ((w.length >= 2 && w.charCodeAt(0) >= 55296 && w.charCodeAt(0) <= 56319 && w.charCodeAt(1) >= 56320 && w.charCodeAt(1) <= 57343) ? w.slice(0, 2) : (w.length > 0 ? w.slice(0, 1) : \"\"))\n if (w.length >= 2) {\n const hi = w.charCodeAt(0);\n const lo = w.charCodeAt(1);\n if (hi >= 55296 && hi <= 56319 && lo >= 56320 && lo <= 57343) return w.slice(0, 2);\n }\n return w.length > 0 ? w.slice(0, 1) : \"\";\n}\n\n/**\n * An ASCII letter (A-Z, a-z) somewhere in `w` from `i` on (moved from readability.ts\n * 2026-11-06, so `readableWords`' contract can name it and importers resolve it).\n *\n * @ensures result ⟺ ∃ k ∈ [i, |w|). w[k] ∈ A-Z ∪ a-z — at i = 0 exactly the model's HasAsciiLetter\n */\nexport function hasAsciiLetterFrom(w: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases w.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < w.length && ((w.charCodeAt(k) >= 65 && w.charCodeAt(k) <= 90) || (w.charCodeAt(k) >= 97 && w.charCodeAt(k) <= 122)))\n if (i >= w.length) return false;\n const c = w.charCodeAt(i);\n if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) return true;\n return hasAsciiLetterFrom(w, i + 1);\n}\n\n/**\n * `s` with a-z uppercased and every other character kept, the mirror of `lowerAscii`: JS's\n * `toUpperCase()` also maps non-ASCII letters (ß becomes \"SS\").\n *\n * @ensures |result| = |s| ∧ ∀ k < |s|. result[k] = (s[k] ∈ a-z ? s[k] − 32 : s[k]) — a-z\n * raised, every other code unit unchanged; exactly the model's UpperAscii in the link\n */\nexport function upperAscii(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures \\result.length === s.length\n //@ ensures forall(k: nat, k < s.length ==> \\result.charCodeAt(k) === ((s.charCodeAt(k) >= 97 && s.charCodeAt(k) <= 122) ? s.charCodeAt(k) - 32 : s.charCodeAt(k)))\n if (s.length === 0) return \"\";\n const c = s.charCodeAt(0);\n const head =\n c >= 97 && c <= 122 ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".slice(c - 97, c - 96) : s.slice(0, 1);\n return head + upperAscii(s.slice(1));\n}\n","//@ backend dafny\nimport { isBlank } from \"@atlas/utils/strings\";\n\n/* A cart line and its price (atlas#93). The owner's rule (2026-11-12): a cart line has its item\n and its quantity, and needs no price. augur never stores a null quantity (its routes write 0 for\n a sent null: models/AugurCommerceCartLine.dfy RoutesWriteQuantity); the column, and so the type,\n still allows one, and such a line is simply not priced. Verified with LemmaScript → Dafny (`pnpm proofs`;\n model: models/AugurUtils.dfy, section \"a cart line with no quantity\"; link:\n models/links/augur-utils-cart-line-rules.dfy). The prover's `number` is an integer; only\n null-ness and booleans are decided here, never a quantity's value. */\n\n/**\n * Whether a cart line has a quantity (augur always stores one; the type allows null).\n *\n * @ensures result ⟺ quantity ≠ null, the model's LineHasQuantity\n */\nexport function lineHasQuantity(quantity: number | null): boolean {\n //@ verify\n //@ ensures \\result === (quantity !== null)\n return quantity !== null;\n}\n\n/**\n * Whether a line's price query runs: a customer, an itemId, and a quantity (the price engine is\n * never asked for a quantity nobody entered).\n *\n * @ensures result ⟺ hasCustomer ∧ hasItemId ∧ quantity ≠ null, the model's PriceQueryRuns over\n * LineHasQuantity\n */\nexport function priceQueryRuns(\n hasCustomer: boolean,\n hasItemId: boolean,\n quantity: number | null,\n): boolean {\n //@ verify\n //@ ensures \\result === (hasCustomer && hasItemId && quantity !== null)\n return hasCustomer && hasItemId && lineHasQuantity(quantity);\n}\n\n/**\n * The unit of measure a line's price query asks for: the line's own, so a CASE/6 line is priced per\n * case, not as one EACH (the price engine prices a query without a unit in the item's default\n * selling unit); null for a missing or blank unit (a line saved before the client required one).\n *\n * @ensures result = unitOfMeasure when it is set and not blank, else null: the model's QueryUnit\n */\nexport function priceQueryUnit(unitOfMeasure: string | null): string | null {\n //@ verify\n //@ ensures \\result === (unitOfMeasure !== null && !isBlank(unitOfMeasure) ? unitOfMeasure : null)\n return unitOfMeasure !== null && !isBlank(unitOfMeasure) ? unitOfMeasure : null;\n}\n\n/**\n * Cart pricing is settled when every query that runs has succeeded: a line whose query never runs\n * (no quantity, no itemId, no customer) can't hold it back (its query stays pending and idle).\n *\n * @ensures exactly the model's PricingSettledFrom\n */\nexport function pricingSettledFrom(succeeded: boolean[], runs: boolean[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires succeeded.length === runs.length\n //@ requires i >= 0 && i <= succeeded.length\n //@ decreases succeeded.length - i\n //@ ensures i === succeeded.length ==> \\result === true\n //@ ensures i < succeeded.length ==> \\result === ((!runs[i] || succeeded[i]) && pricingSettledFrom(succeeded, runs, i + 1))\n if (i === succeeded.length) return true;\n if (runs[i] === true && succeeded[i] !== true) return false;\n return pricingSettledFrom(succeeded, runs, i + 1);\n}\n\n/**\n * Cart pricing is loading when any query that runs is loading.\n *\n * @ensures exactly the model's PricingLoadingFrom\n */\nexport function pricingLoadingFrom(loading: boolean[], runs: boolean[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires loading.length === runs.length\n //@ requires i >= 0 && i <= loading.length\n //@ decreases loading.length - i\n //@ ensures i === loading.length ==> \\result === false\n //@ ensures i < loading.length ==> \\result === ((runs[i] && loading[i]) || pricingLoadingFrom(loading, runs, i + 1))\n if (i === loading.length) return false;\n if (runs[i] === true && loading[i] === true) return true;\n return pricingLoadingFrom(loading, runs, i + 1);\n}\n\n/**\n * Line `i`'s unit price from the per-line list (cart order): its own, fetched at its own quantity,\n * so one item on two lines (two units of measure) keeps two prices; 0 past the end.\n *\n * @ensures result = unitPrices[i] when i < |unitPrices|, else 0, the model's LinePriceAt\n */\nexport function linePriceAt(unitPrices: number[], i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ ensures \\result === (i < unitPrices.length ? unitPrices[i] : 0)\n return i < unitPrices.length ? (unitPrices[i] as number) : 0;\n}\n","//@ backend dafny\nimport { isDigit } from \"./chars.js\";\n\n/* PosDigits: a positive whole number written as text, the text form of `PosInt` (owner\n 2026-11-08: \"I know we have a posint, is there a posdigit?\"). Verified with LemmaScript →\n Dafny (`pnpm proofs`; model: models/Digits.dfy; link: models/links/foundation-pos-digits.dfy).\n\n Decimal digits only, at least one, and at least one that is not 0, so its value is at least\n 1: \"1\", \"007\" and \"4096\" are; \"\", \"0\", \"00\", \"-1\", \"+1\" and \"1.0\" are not. Leading zeros\n are kept (P21 sends some keys padded). The type is branded: a plain `string` is not a\n `PosDigits`, so the only way to get one is the guard `posDigitsOf`, where the value enters.\n lsc writes the alias as `string` (no refinement, models/LSC-GAPS.md). */\n\n/** Text that is a positive whole number, made only by `posDigitsOf`. */\n//@ type string\nexport type PosDigits = string & { readonly __posDigits: true };\n\n/**\n * Every character from `i` on is a digit, and some digit from `i` on is not 0 (or one before\n * `i` was, `nonZero`).\n */\nfunction posDigitsFrom(s: string, i: number, nonZero: boolean): boolean {\n //@ verify\n //@ type i nat\n //@ requires 0 <= i && i <= s.length\n //@ decreases s.length - i\n //@ ensures \\result <==> (forall(k: nat, (i <= k && k < s.length) ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57)) && (nonZero || exists(k: nat, i <= k && k < s.length && s.charCodeAt(k) !== 48)))\n if (i === s.length) return nonZero;\n const c = s.charCodeAt(i);\n if (!isDigit(c)) return false;\n return posDigitsFrom(s, i + 1, nonZero || c !== 48);\n}\n\n/**\n * `s` is a positive whole number written in decimal digits.\n *\n * @ensures result ⟺ |s| > 0 ∧ ∀ k. s[k] ∈ 0-9 ∧ ∃ k. s[k] ≠ 0 — exactly the model's\n * IsPosDigits, stated over the codes so an importer can use it\n */\nexport function isPosDigits(s: string): boolean {\n //@ verify\n //@ ensures \\result <==> (s.length > 0 && forall(k: nat, k < s.length ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57)) && exists(k: nat, k < s.length && s.charCodeAt(k) !== 48))\n return posDigitsFrom(s, 0, false);\n}\n\n/**\n * `s` as a `PosDigits`, or null when it is not one. The one place a `string` becomes one.\n *\n * @ensures exactly the model's IsPosDigits (stated over the codes, as isPosDigits', so an\n * importer can resolve it); the value is `s` itself\n */\nexport function posDigitsOf(s: string): PosDigits | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (s.length > 0 && forall(k: nat, k < s.length ==> (s.charCodeAt(k) >= 48 && s.charCodeAt(k) <= 57)) && exists(k: nat, k < s.length && s.charCodeAt(k) !== 48))\n //@ ensures \\result !== null ==> \\result === s\n return isPosDigits(s) ? (s as PosDigits) : null;\n}\n","//@ backend dafny\n\n/* PosInt: an integer at least 1 (an id such as a Joomla user id or a P21 usersUid, a count that\n is never empty, a page size). Verified with LemmaScript → Dafny (`pnpm proofs`; model:\n models/Foundation.dfy \"positive integers\", where the bound is a subset type; link:\n models/links/foundation-pos-int.dfy).\n\n The type is branded: a plain `number` is not a `PosInt`, so the only ways to get one are the\n guard `posIntOf` (where a value enters) and the proved building blocks below. A function that\n takes a `PosInt` therefore never sees 0, a negative or a fraction. lsc writes the alias as\n `nat` (it carries no refinement, models/LSC-GAPS.md), so a proved function taking one also\n states `//@ requires x >= 1`, which every caller holding a `PosInt` meets. */\n\n/** An integer at least 1, made only by `posIntOf` or the building blocks below. */\n//@ type nat\nexport type PosInt = number & { readonly __posInt: true };\n\n/**\n * `n` as a `PosInt`, or null when it is not a safe integer at least 1: a fraction\n * (`Math.floor(n) !== n`), NaN (never equal to itself), 0, a negative, an infinity or an\n * integer past `Number.MAX_SAFE_INTEGER` (2^53 - 1, past which a JS number is no exact\n * integer). The one place a `number` becomes a `PosInt`.\n *\n * @ensures exactly the model's PosIntOf: n when 1 ≤ n ≤ 2^53 - 1, else null (the proof reads\n * `number` as an integer, where `Math.floor(n) === n` always holds; at runtime it is what\n * refuses a fraction and NaN)\n */\nexport function posIntOf(n: number): PosInt | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (n >= 1 && n <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === n\n return Math.floor(n) === n && n >= 1 && n <= 9007199254740991 ? (n as PosInt) : null;\n}\n\n/**\n * The next integer after a non-negative integer: a count plus one, a 0-based index made 1-based.\n *\n * @ensures exactly the model's PosSucc\n */\nexport function posSucc(n: number): PosInt {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === n + 1\n //@ ensures \\result >= 1\n return (n + 1) as PosInt;\n}\n\n/**\n * A `PosInt` plus a non-negative integer.\n *\n * @ensures exactly the model's PosAdd\n */\nexport function posAdd(a: PosInt, b: number): PosInt {\n //@ verify\n //@ type b nat\n //@ requires a >= 1 && b >= 0\n //@ ensures \\result === a + b\n //@ ensures \\result >= 1 && \\result >= a\n return (a + b) as PosInt;\n}\n\n/**\n * Two `PosInt`s multiplied (a page count times a page size).\n *\n * @ensures exactly the model's PosMul\n */\nexport function posMul(a: PosInt, b: PosInt): PosInt {\n //@ verify\n //@ requires a >= 1 && b >= 1\n //@ ensures \\result === a * b\n //@ ensures \\result >= 1 && \\result >= a && \\result >= b\n return (a * b) as PosInt;\n}\n\n/**\n * The larger of a `PosInt` and any integer (a lower bound of 1 or more applied to a count).\n *\n * @ensures exactly the model's PosMax\n */\nexport function posMax(a: PosInt, b: number): PosInt {\n //@ verify\n //@ type b int\n //@ requires a >= 1\n //@ ensures \\result === (a >= b ? a : b)\n //@ ensures \\result >= 1\n return (a >= b ? a : b) as PosInt;\n}\n\n/**\n * The smaller of two `PosInt`s (a page size capped by a limit).\n *\n * @ensures exactly the model's PosMin\n */\nexport function posMin(a: PosInt, b: PosInt): PosInt {\n //@ verify\n //@ requires a >= 1 && b >= 1\n //@ ensures \\result === (a <= b ? a : b)\n //@ ensures \\result >= 1\n return a <= b ? a : b;\n}\n","//@ backend dafny\nimport { isPosDigits } from \"@atlas/foundation/pos-digits\";\nimport { posIntOf } from \"@atlas/foundation/pos-int\";\nimport { digitsValue } from \"@atlas/utils/strings\";\n\n/* A P21 address id (atlas#95): a customer, ship-to, supplier or vendor id is that party's\n `address.id`, decimal(19,0), not null (augur's definitions/prophet21 address, customer,\n ship_to, supplier and vendor), never 0 (owner 2026-11-13), so a whole number at least 1. Sites\n carry \"no customer\" as undefined, \"\" or \"0\" (Joomla's profile holds the id as text), and a `??`\n fallback or `Number()` read let \"\" and \"0\" through as party 0; every place that takes one of\n these ids resolves it here instead (owner 2026-11-13: \"A customerId should be fixed on the\n entire system\", then the same rule for shipToId, supplierId and vendorId). An id may be left\n out, but one that is sent MUST pass. Verified with LemmaScript → Dafny (`pnpm proofs`; model:\n models/AugurUtils.dfy, section \"address id\"; link: models/links/augur-utils-address-id.dfy). */\n\n/**\n * A usable address id: a whole number at least 1 that a JS number holds exactly. The brand is\n * foundation's `PosInt` (private, so it can't be named in a published `.d.ts`), so the two are\n * the same type.\n */\n//@ type nat\nexport type AddressId = number & { readonly __posInt: true };\n\n/** A value an address id arrives as: a session or profile field, a site default, a param. */\nexport type AddressIdInput = string | number | null | undefined;\n\n/**\n * A text as an address id: trimmed, decimal digits with at least one that is not 0, and a safe\n * integer; null for \"\", \" \", \"0\", \"000\", \"-1\", \"1.0\", \"1e3\", \"0x10\", \"abc\" and past 2^53 - 1.\n *\n * @ensures exactly the model's AddressIdOfText: the trimmed digits' value when they are\n * PosDigits and that value is a safe integer at least 1, else null\n */\nexport function addressIdOfText(s: string): AddressId | null {\n //@ verify\n //@ ensures (\\result !== null) <==> (isPosDigits(s.trim()) && digitsValue(s.trim()) >= 1 && digitsValue(s.trim()) <= 9007199254740991)\n //@ ensures \\result !== null ==> \\result === digitsValue(s.trim())\n const t = s.trim();\n if (!isPosDigits(t)) return null;\n // A digit run's value is whole, so the bounds are posIntOf's whole check (its imported\n // contract doesn't translate: models/LSC-GAPS.md).\n const v = digitsValue(t);\n return v >= 1 && v <= 9007199254740991 ? (v as AddressId) : null;\n}\n\n/**\n * The first id in `ids` from `i` on, null when none is (each already read by `addressIdOf`).\n *\n * @ensures exactly the model's FirstAddressIdFrom\n */\nexport function firstAddressIdFrom(ids: (AddressId | null)[], i: number): AddressId | null {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= ids.length\n //@ decreases ids.length - i\n //@ ensures i === ids.length ==> \\result === null\n //@ ensures i < ids.length && ids[i] !== null ==> \\result === ids[i]\n //@ ensures i < ids.length && ids[i] === null ==> \\result === firstAddressIdFrom(ids, i + 1)\n if (i === ids.length) return null;\n const id = ids[i] as AddressId | null;\n if (id !== null) return id;\n return firstAddressIdFrom(ids, i + 1);\n}\n\n/**\n * Any value as an address id, null when it isn't one: absent, a number that is not a safe integer\n * at least 1 (0, -5, 1.5, NaN, Infinity), or a text `addressIdOfText` refuses. Only reads the\n * value's kind; the decisions are the proved `posIntOf` and `addressIdOfText`.\n */\nexport function addressIdOf(value: AddressIdInput): AddressId | null {\n if (typeof value === \"number\") return posIntOf(value) as AddressId | null;\n if (typeof value === \"string\") return addressIdOfText(value);\n return null;\n}\n\n/**\n * Whether `value` is a usable address id (`addressIdOf` gives one). A plain boolean, not a type\n * guard: \"0\" is a string that is no id, so a false MUST NOT narrow it away from `string`.\n */\nexport function isUsableAddressId(value: AddressIdInput): boolean {\n return addressIdOf(value) !== null;\n}\n\n/**\n * The first usable address id among `candidates`, in order, or null when none is: a caller's id,\n * then the session's, then the site's default. \"\" and \"0\" are passed over, never read as 0.\n */\nexport function resolveAddressId(...candidates: AddressIdInput[]): AddressId | null {\n return firstAddressIdFrom(candidates.map(addressIdOf), 0);\n}\n","import type { AddressId } from \"./address-id\";\nimport { takerOf } from \"./rules\";\nimport type { TCartLine } from \"./types/cart\";\n\nexport type OeHdr = {\n customer_id: number;\n company_id: string;\n sales_location_id: number;\n user_id: number;\n user_email: string;\n taker: string;\n customer_po_no?: string;\n ship_to_id?: number;\n delivery_instructions?: string;\n};\n\nexport type OeLine = {\n item_id: string;\n unit_quantity: number | null;\n unit_of_measure: string | null;\n inv_mast_uid: number;\n unit_price?: number;\n};\n\nexport type CheckoutInput = {\n /** A usable P21 customer (`resolveAddressId` / `addressIdOf`): an order is never placed for 0 (atlas#95). */\n customerId: AddressId;\n companyId: string;\n salesLocationId: number;\n userId: number;\n userEmail: string;\n taker?: string;\n cartLines: TCartLine[];\n poNumber?: string;\n /**\n * The order's ship-to, optional; when given, a usable P21 ship-to id (`addressIdOf` /\n * `resolveAddressId`): it is the ship-to's `address.id`, never \"\" or 0 (atlas#95).\n */\n shipToId?: AddressId;\n deliveryInstructions?: string;\n};\n\n/** Builds the oe_hdr + oe_line payload required by the commerce checkout API from cart data. */\nexport function buildCheckoutPayload(input: CheckoutInput): {\n oe_hdr: OeHdr;\n oe_line: OeLine[];\n} {\n const oe_hdr: OeHdr = {\n customer_id: input.customerId,\n company_id: input.companyId,\n sales_location_id: input.salesLocationId,\n user_id: input.userId,\n user_email: input.userEmail,\n taker: takerOf(input.taker),\n };\n\n if (input.poNumber != null) oe_hdr.customer_po_no = input.poNumber;\n if (input.shipToId != null) oe_hdr.ship_to_id = input.shipToId;\n if (input.deliveryInstructions != null) oe_hdr.delivery_instructions = input.deliveryInstructions;\n\n const oe_line: OeLine[] = input.cartLines.map((line) => {\n const oeLine: OeLine = {\n item_id: line.itemId,\n unit_quantity: line.quantity,\n unit_of_measure: line.unitOfMeasure,\n inv_mast_uid: line.invMastUid,\n };\n if (line.unitPrice != null) oeLine.unit_price = line.unitPrice;\n return oeLine;\n });\n\n return { oe_hdr, oe_line };\n}\n","/**\n * Decimal places kept by `cleanMoney`. Prices carry at most 4 decimals and\n * quantities about as many, so a product needs at most 8. Float64 holds about\n * 15 significant digits, so on real 4-decimal prices 8 decimals stayed\n * noise-free for line totals up to about 2×10^7; 10 decimals left noise from\n * about 2×10^5 (measured in the GH #496 review).\n */\nconst MONEY_DECIMALS = 8;\n\n/**\n * Largest shifted magnitude that is rounded. From 2^51 up, adjacent doubles are\n * 0.5 or more apart, so rounding to `decimals` places cannot be represented and\n * the value is returned unchanged (this also keeps a shift that overflows to\n * Infinity from becoming NaN).\n */\nconst MAX_SHIFTED = 2 ** 51;\n\n/**\n * Shift a finite, non-negative number's decimal point by `places` through its\n * exponent string. The result is the correctly rounded double of the shifted\n * decimal, not a binary `value * 10^places` product.\n */\nfunction shiftDecimal(value: number, places: number): number {\n const [mantissa, exponent = \"0\"] = String(value).split(\"e\");\n return Number(`${mantissa}e${Number(exponent) + places}`);\n}\n\n/**\n * Round half away from zero to `decimals` places.\n *\n * Shifts the decimal point through the exponent string instead of multiplying,\n * so float noise in `value * 10^decimals` cannot flip a tie\n * (`Math.round(1.005 * 100) / 100` is 1; this returns 1.01).\n *\n * @requires decimals ∈ ℕ // whole, non-negative; otherwise RangeError\n * @ensures ¬isFinite(value) → result = value // NaN and ±Infinity pass through unchanged\n * @ensures |value| · 10^decimals ≥ 2^51 → result = value // too large to round at that precision\n * @ensures |value| · 10^decimals < 2^51 → result = sign(value) · round½↑(|value| · 10^decimals) · 10^−decimals\n * // half away from zero on the value's shortest decimal string; a 17-significant-digit input whose\n * // shifted fraction falls within one float spacing of .5 can still double-round (not observed for\n * // real price × quantity products)\n * @ensures result = 0 → result is +0 // a small negative rounds to 0, never −0 (\"-$0.00\")\n *\n * @param value Number to round\n * @param decimals Decimal places to keep\n * @returns `value` rounded half away from zero\n */\nexport function roundHalfAway(value: number, decimals: number): number {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new RangeError(\n `roundHalfAway: decimals must be a non-negative integer, got ${String(decimals)}`,\n );\n }\n if (!Number.isFinite(value)) return value;\n const shifted = shiftDecimal(Math.abs(value), decimals);\n if (!(shifted < MAX_SHIFTED)) return value;\n const rounded = Math.round(shifted);\n if (rounded === 0) return 0;\n return Math.sign(value) * shiftDecimal(rounded, -decimals);\n}\n\n/**\n * Remove JS float noise from a money product or sum.\n *\n * `38.0714 * 3` is 114.21419999999999; this returns 114.2142. Rounds half away\n * from zero to 8 decimals: enough to represent real prices and quantities, not\n * exact decimal arithmetic. Apply it to every product and running sum of money.\n *\n * @ensures cleanMoney(cleanMoney(value)) = cleanMoney(value)\n * // idempotent: an in-range result is k · 10^−8 with integer k < 2^51, whose shortest\n * // decimal string shifts back to k exactly; out-of-range values pass through unchanged\n *\n * @param value Result of a money product or sum\n * @returns `value` without float noise\n */\nexport function cleanMoney(value: number): number {\n return roundHalfAway(value, MONEY_DECIMALS);\n}\n","//@ backend dafny\n\n/* The decision behind `derivePrice`: which of its five outcomes a price input gets. Verified\n with LemmaScript → Dafny (`pnpm proofs`; model: models/AugurUtils.dfy `PriceOutcomeOf`; link:\n models/links/augur-utils-price-outcome.dfy). What is proved is the whole decision table, with\n no gap: every input gets exactly the outcome its clause names, whatever order the checks run\n in. Not proved: that `derivePrice` computes the three flags correctly from the price record\n (`Number.isFinite` and IEEE-754 are invisible to the prover, whose `number` is a mathematical\n integer, so `unitPrice` is reasoned about as an integer here), or the money math (`total`),\n which is tested in test/derive-price.test.ts and test/money.test.ts. */\n\n/**\n * - `badQuantity`: the quantity is negative or not finite (derivePrice throws).\n * - `loading`: no price record, or the record has no `unitPrice` yet (GH #454).\n * - `badPrice`: the record's `unitPrice` is negative or not finite (derivePrice throws).\n * - `callForPrice`: the record's `unitPrice` is 0.\n * - `priced`: the record's `unitPrice` is greater than 0.\n */\nexport type PriceOutcome = \"badQuantity\" | \"loading\" | \"badPrice\" | \"callForPrice\" | \"priced\";\n\n/**\n * Decide the outcome. `quantityOk` is \"finite and ≥ 0\"; `hasPrice` is \"a record with a\n * `unitPrice`\"; `priceFinite` is `Number.isFinite(unitPrice)`; `unitPrice` is the record's price\n * (any value when `hasPrice` is false).\n *\n * Proven: each outcome holds exactly when its condition does, so the five are exhaustive and\n * mutually exclusive. A bad quantity wins over everything (a negative quantity throws even while\n * loading), and loading wins over a bad price (a missing price is never reported as bad).\n */\nexport function priceOutcome(\n quantityOk: boolean,\n hasPrice: boolean,\n priceFinite: boolean,\n unitPrice: number,\n): PriceOutcome {\n //@ verify\n //@ ensures (\\result === \"badQuantity\") === !quantityOk\n //@ ensures (\\result === \"loading\") === (quantityOk && !hasPrice)\n //@ ensures (\\result === \"badPrice\") === (quantityOk && hasPrice && !(priceFinite && unitPrice >= 0))\n //@ ensures (\\result === \"callForPrice\") === (quantityOk && hasPrice && priceFinite && unitPrice === 0)\n //@ ensures (\\result === \"priced\") === (quantityOk && hasPrice && priceFinite && unitPrice > 0)\n if (!quantityOk) return \"badQuantity\";\n if (!hasPrice) return \"loading\";\n if (!priceFinite || unitPrice < 0) return \"badPrice\";\n if (unitPrice === 0) return \"callForPrice\";\n return \"priced\";\n}\n","import { cleanMoney } from \"./money\";\nimport { priceOutcome, type PriceOutcome } from \"./price-outcome\";\nimport type { TPriceData } from \"./types/pricing\";\n\n/**\n * Result of price derivation as a discriminated union over the three real\n * domain states. The `state` tag lifts the previously-overloaded `0` sentinel\n * into the type system: \"loading\" (no price record yet) is now distinct from\n * \"callForPrice\" (a genuine zero price). See GH #454.\n */\nexport type DerivedPrice =\n | { state: \"loading\" }\n | { state: \"priced\"; unitPrice: number; total: number; unitOfMeasure: string }\n | { state: \"callForPrice\"; unitOfMeasure: string };\n\nexport interface DerivePriceInput {\n priceData: TPriceData | null | undefined;\n /**\n * Quantity in the priced unit. Fractional values come from UOM conversion (ft, sqft, lb).\n * Omit it to price one unit. Null is not accepted: an unknown quantity cannot be priced,\n * so the caller decides how to handle it.\n */\n quantity?: number;\n}\n\n/** The RangeError for the two refused outcomes, null for the rest (the outcomes are exclusive). */\nfunction outcomeError(\n outcome: PriceOutcome,\n quantity: number,\n unitPrice: number | undefined,\n): RangeError | null {\n if (outcome === \"badQuantity\") {\n return new RangeError(\n `derivePrice: quantity must be a non-negative finite number, got ${String(quantity)}`,\n );\n }\n if (outcome === \"badPrice\") {\n return new RangeError(\n `derivePrice: unitPrice must be a non-negative finite number, got ${String(unitPrice)}`,\n );\n }\n return null;\n}\n\n/** `priceOutcome` over the input's three flags. */\nfunction outcomeFor(\n priceData: TPriceData | null | undefined,\n unitPrice: number | undefined,\n quantity: number,\n): PriceOutcome {\n const hasPrice = priceData != null && unitPrice != null;\n return priceOutcome(\n Number.isFinite(quantity) && quantity >= 0,\n hasPrice,\n Number.isFinite(unitPrice),\n // Read only when hasPrice is true; the 0 is never compared then.\n unitPrice ?? 0,\n );\n}\n\n/**\n * Pure price derivation — usable in hooks AND server components.\n *\n * @requires quantity = undefined ∨ (quantity ∈ ℝ ∧ quantity ≥ 0 ∧ Number.isFinite(quantity))\n * // omitted → 1 (a one-unit price); fractional quantities (UOM conversion, e.g. 2023.5 ft) are valid;\n * // negative, NaN, ±Infinity, or a null passed at runtime → RangeError. -0 passes (-0 ≥ 0).\n * @requires unitPrice ≥ 0 ∧ Number.isFinite(unitPrice) (when a price record is present)\n * // violated → RangeError\n * @ensures result.state = \"loading\" ⟺ priceData == null ∨ priceData.unitPrice == null (given the quantity @requires; a bad quantity throws even while loading)\n * // a missing price record (undefined/null) is loading, NOT a zero price — the distinction GH #454 restores\n * @ensures result.state = \"callForPrice\" ⟺ priceData.unitPrice = 0\n * // a genuine zero price is call-for-price, distinct from loading\n * @ensures result.state = \"priced\" ⟺ priceData.unitPrice > 0\n * // total = cleanMoney(unitPrice · quantity): the product rounded half away from zero to\n * // 8 decimals, which removes float noise (38.0714 · 3 → 114.2142, not 114.21419999999999)\n *\n * The state decision (which branch, including the two RangeErrors) is `priceOutcome`, proved\n * with LemmaScript (`price-outcome.ts`, linked to `models/AugurUtils.dfy`). This function computes\n * its three flags and does the money math; both are tested, not proved.\n */\nexport function derivePrice(input: DerivePriceInput): DerivedPrice {\n const { priceData, quantity = 1 } = input;\n\n // TPriceData types unitPrice as `number`, but the payload omits it while the\n // price record is still loading. Widen to capture that runtime reality.\n const unitPrice: number | undefined = priceData?.unitPrice;\n const outcome = outcomeFor(priceData, unitPrice, quantity);\n\n const error = outcomeError(outcome, quantity, unitPrice);\n if (error) throw error;\n if (outcome === \"loading\") return { state: \"loading\" };\n\n // Every outcome after \"loading\" has hasPrice (priceOutcome's loading clause), so both are set.\n const record = priceData as TPriceData;\n const price = unitPrice as number;\n const unitOfMeasure = record.item?.unitOfMeasure ?? \"\";\n\n if (outcome === \"callForPrice\") return { state: \"callForPrice\", unitOfMeasure };\n\n return { state: \"priced\", unitPrice: price, total: cleanMoney(price * quantity), unitOfMeasure };\n}\n","import { isDiscontinuedOf, isLowStockOf } from \"./rules\";\nimport type { TStock } from \"./types/inventory\";\n\nexport interface ResolveStockInput {\n stock: TStock | null | undefined;\n companyKey?: string;\n round?: boolean;\n lowStockThreshold?: number;\n showQuantity?: boolean;\n}\n\nexport interface ResolvedStock {\n quantity: number;\n isInStock: boolean;\n isLowStock: boolean;\n isDiscontinued: boolean;\n displayQuantity: number | null;\n}\n\n/** One company's quantity when `companyKey` names one in the summary, else the sum over every company. */\nfunction summaryQuantity(\n companySummary: TStock[\"companySummary\"],\n companyKey: string | undefined,\n): number {\n if (companyKey && companyKey in companySummary) {\n return companySummary[companyKey] ?? 0;\n }\n return Object.values(companySummary).reduce((sum: number, val: number) => sum + val, 0);\n}\n\n/** Discontinued when there is stock data and every row says \"Y\". */\nfunction allDiscontinued(stockData: TStock[\"stockData\"]): boolean {\n return isDiscontinuedOf(stockData.map((d) => d.discontinued));\n}\n\n/**\n * Pure stock resolution -- usable in hooks AND server components.\n *\n * Returns `null` when `stock` is missing (loading / error state).\n */\nexport function resolveStock(input: ResolveStockInput): ResolvedStock | null {\n const { stock, companyKey, round = false, lowStockThreshold = 0, showQuantity = false } = input;\n\n if (!stock) return null;\n\n const summed = summaryQuantity(stock.companySummary, companyKey);\n const qty = round ? Math.round(summed) : summed;\n\n const isInStock = qty > 0;\n const isLowStock = isLowStockOf(qty, lowStockThreshold);\n const isDiscontinued = allDiscontinued(stock.stockData);\n\n return {\n quantity: qty,\n isInStock,\n isLowStock,\n isDiscontinued,\n displayQuantity: showQuantity ? qty : null,\n };\n}\n","import type { ResolvedStock } from \"./resolve-stock\";\nimport { availabilityOf, type Availability } from \"./rules\";\n\nexport type SchemaAvailability =\n | \"https://schema.org/InStock\"\n | \"https://schema.org/OutOfStock\"\n | \"https://schema.org/LimitedAvailability\"\n | \"https://schema.org/BackOrder\"\n | \"https://schema.org/Discontinued\";\n\n/**\n * Maps resolved stock to a Schema.org availability URL.\n *\n * - InStock: quantity > 0\n * - OutOfStock: discontinued at all locations with zero inventory\n * - BackOrder: zero stock but not discontinued (accepts backorders)\n */\nexport function getSchemaAvailability(\n resolved: ResolvedStock | null | undefined,\n): SchemaAvailability {\n return SCHEMA_URLS[availabilityOf(!!resolved?.isInStock, !!resolved?.isDiscontinued)];\n}\n\nconst SCHEMA_URLS: Record<Availability, SchemaAvailability> = {\n InStock: \"https://schema.org/InStock\",\n OutOfStock: \"https://schema.org/OutOfStock\",\n BackOrder: \"https://schema.org/BackOrder\",\n};\n","//@ backend dafny\nimport { includesFrom } from \"./includes\";\nimport { compareFrom, endsWith } from \"./strings\";\n\n/* Pure list helpers, verified with LemmaScript → Dafny (model: models/Utils.dfy; link:\n models/links/utils-lists.dfy). */\n\n/**\n * The items from index `i` joined by `sep` (JS `xs.join(sep)` at i = 0).\n *\n * @ensures exactly the model's JoinFrom\n */\nexport function joinFrom(xs: string[], sep: string, i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result === \"\"\n //@ ensures i + 1 === xs.length ==> \\result === xs[i]\n //@ ensures i + 1 < xs.length ==> (\\result.length >= xs[i].length + sep.length && \\result.slice(0, xs[i].length + sep.length) === xs[i] + sep)\n if (i >= xs.length) return \"\";\n return joinRange(xs, sep, i, xs.length);\n}\n\n/**\n * The items joined by `sep`, or `fallback` when there are none (a validation issue's path in\n * augur-api: its segments joined by \".\", or \"root\"; lifted 2026-11-10).\n *\n * @ensures exactly the model's JoinOr\n */\nexport function joinOr(xs: string[], sep: string, fallback: string): string {\n //@ verify\n //@ ensures xs.length === 0 ==> \\result === fallback\n //@ ensures xs.length > 0 ==> \\result === joinFrom(xs, sep, 0)\n return xs.length === 0 ? fallback : joinFrom(xs, sep, 0);\n}\n\n/**\n * The items from `lo` up to `hi` (at least one) joined by `sep`, by halves: a list of n items\n * recurses log n deep, so a generated file of many thousand lines fits the stack.\n *\n * @ensures = the model's JoinFrom(xs[..hi], sep, lo) (links/utils-lists.dfy, by JoinFromSplits)\n */\nfunction joinRange(xs: string[], sep: string, lo: number, hi: number): string {\n //@ verify\n //@ type lo nat\n //@ type hi nat\n //@ requires lo < hi && hi <= xs.length\n //@ decreases hi - lo\n //@ ensures hi === lo + 1 ==> \\result === xs[lo]\n if (hi - lo === 1) return xs[lo] as string;\n const mid = lo + Math.floor((hi - lo) / 2);\n return joinRange(xs, sep, lo, mid) + sep + joinRange(xs, sep, mid, hi);\n}\n\n/**\n * The first index ≥ `i` holding `x`, or -1 (JS `xs.indexOf(x, i)`): how a table of parallel\n * lists is read.\n *\n * @ensures result = -1 ∨ (i ≤ result < |xs| ∧ xs[result] = x) — and the first such index: the\n * model's ItemIndexFrom (links/utils-lists.dfy)\n */\nexport function itemIndexFrom(xs: string[], x: string, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result < xs.length && xs[\\result] === x)\n //@ ensures \\result === -1 ==> forall(k: nat, (i <= k && k < xs.length) ==> xs[k] !== x)\n //@ ensures \\result >= 0 ==> forall(k: nat, (i <= k && k < \\result) ==> xs[k] !== x)\n if (i >= xs.length) return -1;\n return (xs[i] as string) === x ? i : itemIndexFrom(xs, x, i + 1);\n}\n\n/**\n * The sum of `xs[i..]`, 0 past the end (JS `xs.slice(i).reduce((a, b) => a + b, 0)`).\n *\n * @ensures result = Σ xs[i..] — exactly the model's SumFrom\n */\nexport function sumFrom(xs: number[], i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures \\result === (i >= xs.length ? 0 : xs[i] + sumFrom(xs, i + 1))\n if (i >= xs.length) return 0;\n return (xs[i] as number) + sumFrom(xs, i + 1);\n}\n\n/**\n * Whether `x` is one of `xs` from index `i` on (JS `xs.includes(x)` at i = 0).\n *\n * @ensures result ⟺ ∃ k. i ≤ k < |xs| ∧ xs[k] = x — exactly the model's HasItemFrom\n */\nexport function hasItemFrom(xs: string[], x: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && xs[k] === x)\n // `===`, not `>=`: past the end xs[i] is undefined, never x, so `>=` vs `>` is equivalent\n if (i === xs.length) return false;\n if ((xs[i] as string) === x) return true;\n return hasItemFrom(xs, x, i + 1);\n}\n\n/**\n * Whether the number `x` is one of `xs` from index `i` on (JS `xs.includes(x)` at i = 0, for\n * numbers).\n *\n * @ensures result ⟺ ∃ k. i ≤ k < |xs| ∧ xs[k] = x — exactly the model's HasNumberFrom\n */\nexport function hasNumberFrom(xs: number[], x: number, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && xs[k] === x)\n if (i === xs.length) return false;\n if ((xs[i] as number) === x) return true;\n return hasNumberFrom(xs, x, i + 1);\n}\n\n/**\n * Whether `s` ends with one of `xs` from index `i` on (a regex `(a|b|…)$` at i = 0).\n *\n * @ensures exactly the model's EndsWithAnyFrom\n */\nexport function endsWithAnyFrom(s: string, xs: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && endsWith(s, xs[k]))\n if (i === xs.length) return false;\n if (endsWith(s, xs[i] as string)) return true;\n return endsWithAnyFrom(s, xs, i + 1);\n}\n\n/**\n * Whether one of `xs` from index `i` on occurs in `s` (a regex `(a|b|…)` at i = 0).\n *\n * @ensures exactly the model's IncludesAnyFrom\n */\nexport function includesAnyFrom(s: string, xs: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= xs.length\n //@ decreases xs.length - i\n //@ ensures \\result <==> exists(k: nat, i <= k && k < xs.length && includesFrom(s, xs[k], 0))\n if (i === xs.length) return false;\n if (includesFrom(s, xs[i] as string, 0)) return true;\n return includesAnyFrom(s, xs, i + 1);\n}\n\n/**\n * The items of `xs` from index `i` that `allowed` doesn't hold, in order (JS\n * `xs.filter((x) => !allowed.includes(x))` at i = 0).\n *\n * @ensures exactly the model's NotInFrom (NotInFromIsTheUnknown: the unknown ones, all of them)\n */\nexport function notInFrom(xs: string[], allowed: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result.length === 0\n if (i >= xs.length) return [];\n const rest = notInFrom(xs, allowed, i + 1);\n return hasItemFrom(allowed, xs[i] as string, 0) ? rest : [xs[i] as string, ...rest];\n}\n\n/**\n * Whether `x` is one of the first `k` items of `xs` (JS `xs.slice(0, k).includes(x)`).\n *\n * @ensures result ⟺ ∃ j < k. xs[j] = x — exactly the model's HasItemBelow\n */\nexport function hasItemBelow(xs: string[], x: string, k: number): boolean {\n //@ verify\n //@ type k nat\n //@ requires k >= 0 && k <= xs.length\n //@ decreases k\n //@ ensures \\result <==> exists(j: nat, j < k && xs[j] === x)\n if (k === 0) return false;\n if ((xs[k - 1] as string) === x) return true;\n return hasItemBelow(xs, x, k - 1);\n}\n\n/**\n * The items of `xs` from index `i` that repeat an earlier item, in order (at i = 0, every\n * duplicate after its first; none ⟺ the items are unique).\n *\n * @ensures exactly the model's RepeatsFrom (RepeatsFromEmpty: none exactly when unique)\n */\nexport function repeatsFrom(xs: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result.length === 0\n if (i >= xs.length) return [];\n const rest = repeatsFrom(xs, i + 1);\n return hasItemBelow(xs, xs[i] as string, i) ? [xs[i] as string, ...rest] : rest;\n}\n\n/**\n * The items of `xs` from index `i` that no earlier item repeats, in order (at i = 0, JS\n * `[...new Set(xs)]`: each item once, first occurrence kept).\n *\n * @ensures exactly the model's FirstsFrom\n */\nexport function firstsFrom(xs: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases xs.length - i\n //@ ensures i >= xs.length ==> \\result.length === 0\n //@ ensures forall(j: nat, forall(k: nat, (j < k && k < \\result.length) ==> \\result[j] !== \\result[k]))\n if (i >= xs.length) return [];\n const rest = firstsFrom(xs, i + 1);\n return hasItemBelow(xs, xs[i] as string, i) ? rest : [xs[i] as string, ...rest];\n}\n\n/**\n * At most the first `n` items (JS `xs.slice(0, n)` for n ≥ 0).\n *\n * @ensures exactly the model's TakeAtMost\n */\nexport function takeAtMost(xs: string[], n: number): string[] {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ ensures \\result === (n < xs.length ? xs.slice(0, n) : xs)\n return n < xs.length ? xs.slice(0, n) : xs;\n}\n\n/**\n * Whether two number lists are equal from index `i` on (the whole lists at i = 0).\n *\n * @ensures result ⟺ |a| = |b| ∧ ∀ k ∈ [i, |a|). a[k] = b[k] — exactly the model's\n * SameNumbersFrom\n */\nexport function sameNumbersFrom(a: number[], b: number[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= a.length\n //@ decreases a.length - i\n //@ ensures \\result <==> (a.length === b.length && forall(k: nat, i <= k && k < a.length ==> a[k] === b[k]))\n if (a.length !== b.length) return false;\n if (i === a.length) return true;\n return (a[i] as number) === (b[i] as number) && sameNumbersFrom(a, b, i + 1);\n}\n\n/**\n * Whether two text lists are equal from index `i` on (the whole lists at i = 0, as their\n * `JSON.stringify` texts compare).\n *\n * @ensures result ⟺ |a| = |b| ∧ ∀ k ∈ [i, |a|). a[k] = b[k] — exactly the model's\n * SameTextsFrom\n */\nexport function sameTextsFrom(a: string[], b: string[], i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= a.length\n //@ decreases a.length - i\n //@ ensures \\result <==> (a.length === b.length && forall(k: nat, i <= k && k < a.length ==> a[k] === b[k]))\n if (a.length !== b.length) return false;\n if (i === a.length) return true;\n return (a[i] as string) === (b[i] as string) && sameTextsFrom(a, b, i + 1);\n}\n\n/**\n * The texts in code-unit order (JS's default `sort`, stable: of two equal texts the earlier\n * stays first).\n *\n * @ensures exactly the model's SortedTexts (in the link); the same length\n */\nexport function sortedTexts(xs: string[]): string[] {\n //@ verify\n //@ ensures \\result.length === xs.length\n if (xs.length === 0) return [];\n return insertText(xs[0] as string, sortedTexts(xs.slice(1)));\n}\n\n/**\n * `x` placed into sorted texts before the first it doesn't sort after.\n *\n * @ensures exactly the model's InsertText (in the link); one longer\n */\nexport function insertText(x: string, sorted: string[]): string[] {\n //@ verify\n //@ ensures \\result.length === sorted.length + 1\n if (sorted.length === 0) return [x];\n const first = sorted[0] as string;\n if (compareFrom(x, first, 0) <= 0) return [x, ...sorted];\n return [first, ...insertText(x, sorted.slice(1))];\n}\n","//@ backend dafny\nimport { codeAt, indexOfFrom } from \"./strings\";\n\n/* Whole-string rewrites, verified with LemmaScript → Dafny (model: models/Utils.dfy \"text\n replacement\"; link: models/links/utils-replace.dfy). Each has a recursive spec (for\n proofs and tests) and a loop proved to build exactly it (for callers: its depth doesn't\n grow with the input). The `\\result === spec(s)` clause of each loop is a hand `ensures`\n in replace.dfy, as utils `escapeHtml`'s is: lsc would put it in every importer's axiom,\n where this file's own spec isn't emitted. */\n\n// --- One substitution rule (model `Utils.Substituted`, 2026-11-03): each code unit found in a\n// table is replaced by its text, every other kept. replaceCode, pointerToken, escapeHtml and\n// the generator's look-alike fold are this rule, each with its own table.\n\n/**\n * The first index ≥ `i` holding `c` in `codes`, or -1.\n *\n * @ensures result = -1 ∨ (i ≤ result < |codes| ∧ codes[result] = c) — the model's CodeIndex\n */\nexport function codeIndex(codes: number[], c: number, i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i <= codes.length\n //@ decreases codes.length - i\n //@ ensures \\result === -1 || (i <= \\result && \\result < codes.length && codes[\\result] === c)\n // `===`, not `>=`: past the end codes[i] is undefined, never c, so `>=` vs `>` is equivalent\n if (i === codes.length) return -1;\n return (codes[i] as number) === c ? i : codeIndex(codes, c, i + 1);\n}\n\n/** `s` with each code unit in `codes` replaced by its text, recursively: the spec `substitute` builds. */\nexport function substitutedText(s: string, codes: number[], texts: string[]): string {\n //@ verify\n //@ decreases s.length\n //@ ensures s.length === 0 ==> \\result === \"\"\n //@ ensures codes.length === 0 ==> \\result === s\n if (s.length === 0) return \"\";\n const k = codeIndex(codes, s.charCodeAt(0), 0);\n const head = k >= 0 && k < texts.length ? (texts[k] as string) : s.slice(0, 1);\n return head + substitutedText(s.slice(1), codes, texts);\n}\n\n/**\n * `s` with each code unit in `codes` replaced by the text at its first index there, every\n * other kept. A loop, so its depth doesn't grow with the input.\n *\n * @ensures result = substitutedText(s, codes, texts) — the model's Substituted (a hand\n * ensures in replace.dfy: importers can't resolve substitutedText)\n * @ensures |s| = 0 ⟹ result = \"\" ∧ |codes| = 0 ⟹ result = s — no table, no change\n */\nexport function substitute(s: string, codes: number[], texts: string[]): string {\n //@ verify\n //@ ensures s.length === 0 ==> \\result === \"\"\n //@ ensures codes.length === 0 ==> \\result === s\n let out = \"\";\n // `!==`, not `<`: one step past the end reads NaN and adds \"\", so `<=` would be equivalent\n for (let i = 0; i !== s.length; i++) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + substitutedText(s.slice(i), codes, texts) === substitutedText(s, codes, texts)\n //@ decreases s.length - i\n const k = codeIndex(codes, s.charCodeAt(i), 0);\n out = k >= 0 && k < texts.length ? out + (texts[k] as string) : out + s.slice(i, i + 1);\n }\n return out;\n}\n\n/**\n * `s` with every `from` code unit replaced by `to`, recursively: the one-entry table.\n *\n * @ensures no `from` survives when `to` holds none — exactly the model's ReplaceCode in the link\n */\nexport function replacedCode(s: string, from: number, to: string): string {\n //@ verify\n //@ ensures forall(j: nat, j < to.length ==> to.charCodeAt(j) !== from) ==> forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== from)\n return substitutedText(s, [from], [to]);\n}\n\n/**\n * `s` with every `from` code unit replaced by `to` (`replaceAll` of one character).\n *\n * @ensures no `from` survives when `to` holds none (ReplaceCodeRemoves) — = replacedCode(s,\n * from, to), the model's ReplaceCode, as a hand ensures in replace.dfy\n */\nexport function replaceCode(s: string, from: number, to: string): string {\n //@ verify\n //@ ensures forall(j: nat, j < to.length ==> to.charCodeAt(j) !== from) ==> forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== from)\n return substitute(s, [from], [to]);\n}\n\n/**\n * `s` with its first `find` replaced by `put`; no match leaves it: JS `s.replace(find, put)` for\n * a string `find`, when `put` holds no `$` (JS reads `$&`, `$1` there as a pattern).\n *\n * @ensures exactly the model's ReplaceFirst\n */\nexport function replaceFirst(s: string, find: string, put: string): string {\n //@ verify\n //@ ensures \\result === (indexOfFrom(s, find, 0) < 0 ? s : s.slice(0, indexOfFrom(s, find, 0)) + put + s.slice(indexOfFrom(s, find, 0) + find.length))\n const i = indexOfFrom(s, find, 0);\n if (i < 0) return s;\n return s.slice(0, i) + put + s.slice(i + find.length);\n}\n\n/**\n * `s` with every `find` replaced by `put`, left to right without overlaps: JS\n * `s.split(find).join(put)` for a non-empty `find` (tests pin the two). Recursive, with no\n * loop twin: its callers fill short templates (the SDK's registry paths), so the depth stays\n * small; a long-input caller would need one.\n *\n * @requires |find| > 0 — split(\"\") splits into characters, a different rule\n * @ensures text shorter than `find` is unchanged, and so is any text when `put` = `find` —\n * exactly the model's ReplaceText in the link\n */\nexport function replaceText(s: string, find: string, put: string): string {\n //@ verify\n //@ requires find.length > 0\n //@ decreases s.length\n //@ ensures s.length < find.length ==> \\result === s\n //@ ensures put === find ==> \\result === s\n if (s.length < find.length) return s;\n if (s.slice(0, find.length) === find) {\n return put + replaceText(s.slice(find.length), find, put);\n }\n return s.slice(0, 1) + replaceText(s.slice(1), find, put);\n}\n\n/**\n * A JSON Pointer token of `s`, recursively: `~` → `~0`, `/` → `~1`.\n *\n * @ensures never holds \"/\" — exactly the model's PointerToken in the link\n */\nexport function pointerTokenOf(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== 47)\n return substitutedText(s, [126, 47], [\"~0\", \"~1\"]);\n}\n\n/**\n * `s` as a JSON Pointer reference token (RFC 6901 §3): `~` as `~0`, `/` as `~1`.\n *\n * @ensures never holds \"/\" (PointerTokenHasNoSlash) — = pointerTokenOf(s), the model's\n * PointerToken, as a hand ensures in replace.dfy\n */\nexport function pointerToken(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> \\result.charCodeAt(k) !== 47)\n return substitute(s, [126, 47], [\"~0\", \"~1\"]);\n}\n\n/**\n * The escape of `s`, recursively: each `&` `<` `>` `\"` `'` as its entity.\n *\n * @ensures no `<` `>` `\"` `'` in result — exactly the model's EscapeHtml in the link\n */\nexport function escapedText(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n return substitutedText(s, [38, 60, 62, 34, 39], [\"&\", \"<\", \">\", \""\", \"'\"]);\n}\n\n/**\n * Escape text for an HTML body or a double-quoted attribute.\n *\n * @ensures result = escapedText(value) — exactly the model's EscapeHtml (a hand ensures in\n * replace.dfy, since importers can't see escapedText)\n * @ensures ∀ k < |result|. result[k] ∉ {\"<\", \">\", \"\\\"\", \"'\"} — nothing in the output can\n * open a tag or close the attribute; \"&\" appears only as the start of an entity\n */\nexport function escapeHtml(value: string): string {\n //@ verify\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) !== 60 && \\result.charCodeAt(k) !== 62 && \\result.charCodeAt(k) !== 34 && \\result.charCodeAt(k) !== 39))\n return substitute(value, [38, 60, 62, 34, 39], [\"&\", \"<\", \">\", \""\", \"'\"]);\n}\n\n/**\n * The code units a JSON string escapes: `\"`, `\\`, then the control characters with short\n * escapes (\\b \\t \\n \\f \\r), then the other code units below 0x20.\n *\n * @ensures exactly the model's JsonCodes\n */\nexport function jsonCodes(): number[] {\n //@ verify\n //@ ensures \\result === [34, 92, 8, 9, 10, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]\n return [\n 34, 92, 8, 9, 10, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31,\n ];\n}\n\n/**\n * Each `jsonCodes` entry's escape (ECMA-262 QuoteJSONString; lowercase hex, as JSON.stringify).\n *\n * @ensures exactly the model's JsonTexts\n */\nexport function jsonTexts(): string[] {\n //@ verify\n //@ ensures \\result === [\"\\\\\\\"\", \"\\\\\\\\\", \"\\\\b\", \"\\\\t\", \"\\\\n\", \"\\\\f\", \"\\\\r\", \"\\\\u0000\", \"\\\\u0001\", \"\\\\u0002\", \"\\\\u0003\", \"\\\\u0004\", \"\\\\u0005\", \"\\\\u0006\", \"\\\\u0007\", \"\\\\u000b\", \"\\\\u000e\", \"\\\\u000f\", \"\\\\u0010\", \"\\\\u0011\", \"\\\\u0012\", \"\\\\u0013\", \"\\\\u0014\", \"\\\\u0015\", \"\\\\u0016\", \"\\\\u0017\", \"\\\\u0018\", \"\\\\u0019\", \"\\\\u001a\", \"\\\\u001b\", \"\\\\u001c\", \"\\\\u001d\", \"\\\\u001e\", \"\\\\u001f\"]\n return [\n '\\\\\"',\n \"\\\\\\\\\",\n \"\\\\b\",\n \"\\\\t\",\n \"\\\\n\",\n \"\\\\f\",\n \"\\\\r\",\n \"\\\\u0000\",\n \"\\\\u0001\",\n \"\\\\u0002\",\n \"\\\\u0003\",\n \"\\\\u0004\",\n \"\\\\u0005\",\n \"\\\\u0006\",\n \"\\\\u0007\",\n \"\\\\u000b\",\n \"\\\\u000e\",\n \"\\\\u000f\",\n \"\\\\u0010\",\n \"\\\\u0011\",\n \"\\\\u0012\",\n \"\\\\u0013\",\n \"\\\\u0014\",\n \"\\\\u0015\",\n \"\\\\u0016\",\n \"\\\\u0017\",\n \"\\\\u0018\",\n \"\\\\u0019\",\n \"\\\\u001a\",\n \"\\\\u001b\",\n \"\\\\u001c\",\n \"\\\\u001d\",\n \"\\\\u001e\",\n \"\\\\u001f\",\n ];\n}\n\n/**\n * A string as JSON text, as `JSON.stringify(s)` writes it for well-formed text: quoted, `\"`\n * and `\\` backslashed, control characters escaped. A lone surrogate is kept as it is\n * (JSON.stringify writes `\\udxxx`); callers pass well-formed text. Built by the `substitute`\n * loop, so its depth doesn't grow with the text (an FAQ answer can be long; Fable review\n * 2026-11-06); importers still see a function (its contract as an axiom), so their premise\n * `jsonString(s) == Utils.JsonString(s)` stands.\n *\n * @ensures result = `\"` + substitutedText(s, jsonCodes(), jsonTexts()) + `\"` — a hand ensures in\n * replace.dfy; the model's JsonString (proved in links/utils-replace.dfy)\n * @ensures result starts and ends with `\"`\n */\nexport function jsonString(s: string): string {\n //@ verify\n //@ ensures \\result.length >= 2 && \\result.charCodeAt(0) === 34 && \\result.charCodeAt(\\result.length - 1) === 34\n return '\"' + substitute(s, jsonCodes(), jsonTexts()) + '\"';\n}\n\n/**\n * `s` with every `*` `/` pair written `* /`, recursively: the spec `commentSafe` builds.\n *\n * @ensures no \"*\" \"/\" pair in result — exactly the model's CommentSafe in the link\n */\nexport function commentSafeOf(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures forall(k: nat, k + 1 < \\result.length ==> !(\\result.charCodeAt(k) === 42 && \\result.charCodeAt(k + 1) === 47))\n if (s.length === 0) return \"\";\n if (codeAt(s, 0) === 42 && codeAt(s, 1) === 47) {\n return \"* /\" + commentSafeOf(s.slice(2));\n }\n return s.slice(0, 1) + commentSafeOf(s.slice(1));\n}\n\n/**\n * Text safe inside a `/* … *\\/` comment: every `*` `/` pair written `* /`.\n *\n * @ensures no \"*\" \"/\" pair in result: nothing can close the comment — = commentSafeOf(s), the\n * model's CommentSafe, as a hand ensures in replace.dfy\n */\nexport function commentSafe(s: string): string {\n //@ verify\n //@ ensures forall(k: nat, k + 1 < \\result.length ==> !(\\result.charCodeAt(k) === 42 && \\result.charCodeAt(k + 1) === 47))\n let out = \"\";\n let i = 0;\n while (i !== s.length) {\n //@ invariant 0 <= i && i <= s.length\n //@ invariant out + commentSafeOf(s.slice(i)) === commentSafeOf(s)\n //@ decreases s.length - i\n if (codeAt(s, i) === 42 && codeAt(s, i + 1) === 47) {\n out = out + \"* /\";\n i = i + 2;\n } else {\n out = out + s.slice(i, i + 1);\n i = i + 1;\n }\n }\n return out;\n}\n","//@ backend dafny\nimport { joinFrom } from \"./lists\";\nimport { jsonString } from \"./replace\";\n\n/* JSON text written by hand (`jsonPair`, `jsonObject`, `jsonArray`, with `jsonString` in\n replace.ts; model \"JSON text\") and `parseJsonSafe`'s refusal (`unsafeJsonInteger`,\n `unsafeIntegerText`; model \"JSON values\"), proved and linked (models/links/utils-json.dfy).\n The helpers over parsed values (`unknown`) are @atlas/json-values' (moved 2026-11-06, so\n every function here is proved). */\n\n/**\n * An object member: the key as a JSON string, then the value's own JSON text.\n *\n * @ensures exactly the model's JsonPair\n */\nexport function jsonPair(key: string, value: string): string {\n //@ verify\n //@ ensures \\result === jsonString(key) + \":\" + value\n return jsonString(key) + \":\" + value;\n}\n\n/**\n * An object member whose value is a string.\n *\n * @ensures exactly the model's JsonTextPair\n */\nexport function jsonTextPair(key: string, value: string): string {\n //@ verify\n //@ ensures \\result === jsonString(key) + \":\" + jsonString(value)\n return jsonString(key) + \":\" + jsonString(value);\n}\n\n/**\n * An object of members already written as JSON text (`jsonPair`), in order.\n *\n * @ensures exactly the model's JsonObject — proved in links/utils-json.dfy\n */\nexport function jsonObject(pairs: string[]): string {\n //@ verify\n //@ ensures \\result === \"{\" + joinFrom(pairs, \",\", 0) + \"}\"\n return \"{\" + joinFrom(pairs, \",\", 0) + \"}\";\n}\n\n/**\n * An array of items already written as JSON text, in order.\n *\n * @ensures exactly the model's JsonArray — proved in links/utils-json.dfy\n */\nexport function jsonArray(items: string[]): string {\n //@ verify\n //@ ensures \\result === \"[\" + joinFrom(items, \",\", 0) + \"]\"\n return \"[\" + joinFrom(items, \",\", 0) + \"]\";\n}\n\n/**\n * The refusal `parseJsonSafe` (`@atlas/json-values`) makes: an integer that isn't a safe one (above 2^53 − 1).\n *\n * @ensures result ⟺ isInteger ∧ ¬isSafe — the model's UnsafeJsonInteger\n */\nexport function unsafeJsonInteger(isInteger: boolean, isSafe: boolean): boolean {\n //@ verify\n //@ ensures \\result <==> (isInteger && !isSafe)\n return isInteger && !isSafe;\n}\n\n/** The refusal's text, naming the value. */\nexport function unsafeIntegerText(value: string): string {\n //@ verify\n //@ ensures \\result === \"JSON integer \" + value + \" is not exact in JavaScript\"\n return \"JSON integer \" + value + \" is not exact in JavaScript\";\n}\n","//@ backend dafny\n\n/* Verified with LemmaScript → Dafny (`pnpm proofs`; hand lemmas in decimal.dfy; model:\n models/Platform.dfy Decimal; link: models/links/foundation-decimal.dfy): how every app\n writes an id as text. Used by services/agr-int-mcp (customer grant ids `<site>|<usersUid>`) and\n packages/joomla-auth (staff grant ids `staff-<Joomla user id>`), so both are one-to-one\n by the same proof. */\n\n/**\n * The decimal digits of `n`, exactly what `String(n)` gives for a non-negative integer\n * (tests pin the two together). Recursive so specs can use it. Injective: different numbers\n * are written differently (lemma DecimalInjective, decimal.dfy; Platform.DecimalInjective).\n *\n * @ensures |result| ≥ 1 ∧ ∀ k < |result|. result[k] ∈ '0'..'9'\n */\nexport function decimal(n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ decreases n\n //@ ensures \\result.length > 0\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57))\n const last = \"0123456789\".slice(n % 10, (n % 10) + 1);\n return n < 10 ? last : decimal(Math.floor(n / 10)) + last;\n}\n\n/**\n * Any integer as `String(n)` writes it: a minus for a negative, then `decimal`'s digits\n * (tests pin it to `String` for safe integers). An id written this way can't change a path.\n *\n * @ensures result is digits, after a \"-\" exactly when n < 0 — never empty, so an id written\n * this way can't change a path; exactly the model's Platform.IntText in the link (a contract\n * naming `decimal` couldn't be resolved by an importer, models/LSC-GAPS.md, so importers that\n * need the exact text take the link's equality as a premise)\n */\nexport function intText(n: number): string {\n //@ verify\n //@ type n int\n //@ ensures \\result.length > 0\n //@ ensures n >= 0 ==> forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57))\n //@ ensures n < 0 ==> (\\result.length > 1 && \\result.charCodeAt(0) === 45 && forall(k: nat, (1 <= k && k < \\result.length) ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57)))\n return n < 0 ? \"-\" + decimal(-n) : decimal(n);\n}\n","//@ backend dafny\nimport { decimal } from \"@atlas/foundation/decimal\";\nimport { jsonObject, jsonPair, jsonTextPair } from \"./json\";\n\n/* The pieces `./json-ld`'s nodes are built from, verified with LemmaScript → Dafny and linked to\n models/Utils.dfy \"structured data\" (models/links/utils-json-ld-items.dfy). They sit in their own\n file so a proved importer of `breadcrumbLd` or `faqLd` gets their contracts too: a contract\n naming a helper of its own file leaves it unresolved in the importer, one from another file\n the body calls comes along (models/LSC-GAPS.md, 2026-11-06). `./json-ld` re-exports them. */\n\n/**\n * The schema.org context every node starts with, then its type: the first two members of a node.\n *\n * @ensures exactly the model's NodeHead\n */\nexport function nodeHead(type: string): string[] {\n //@ verify\n //@ ensures \\result === [jsonTextPair(\"@context\", \"https://schema.org\"), jsonTextPair(\"@type\", type)]\n return [jsonTextPair(\"@context\", \"https://schema.org\"), jsonTextPair(\"@type\", type)];\n}\n\n/** A breadcrumb: its visible name and the absolute URL of its page (the site's canonical). */\nexport interface LdCrumb {\n name: string;\n url: string;\n}\n\n/**\n * A breadcrumb, built here so a proved importer can make one (an object literal of an imported\n * interface is mistranslated; models/LSC-GAPS.md).\n *\n * @ensures the crumb holds exactly name and url\n */\nexport function ldCrumb(name: string, url: string): LdCrumb {\n //@ verify\n //@ ensures \\result.name === name && \\result.url === url\n return { name, url };\n}\n\n/**\n * The trail's ListItems from index `i`, numbered from 1.\n *\n * @ensures exactly the model's CrumbItemsFrom (in the link; a recursive equation can't be an\n * export's contract, models/LSC-GAPS.md)\n */\nexport function crumbItemsFrom(crumbs: LdCrumb[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases crumbs.length - i\n //@ ensures i >= crumbs.length ==> \\result.length === 0\n if (i >= crumbs.length) return [];\n const crumb = crumbs[i] as LdCrumb;\n return [\n jsonObject([\n jsonTextPair(\"@type\", \"ListItem\"),\n jsonPair(\"position\", decimal(i + 1)),\n jsonTextPair(\"name\", crumb.name),\n jsonTextPair(\"item\", crumb.url),\n ]),\n ...crumbItemsFrom(crumbs, i + 1),\n ];\n}\n\n/** A FAQ entry: the question and its plain-text answer, as the page shows them. */\nexport interface Faq {\n question: string;\n answer: string;\n}\n\n/**\n * The FAQ's Questions from index `i`.\n *\n * @ensures exactly the model's FaqItemsFrom (in the link, as for crumbItemsFrom)\n */\nexport function faqItemsFrom(faqs: Faq[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases faqs.length - i\n //@ ensures i >= faqs.length ==> \\result.length === 0\n if (i >= faqs.length) return [];\n const faq = faqs[i] as Faq;\n return [\n jsonObject([\n jsonTextPair(\"@type\", \"Question\"),\n jsonTextPair(\"name\", faq.question),\n jsonPair(\n \"acceptedAnswer\",\n jsonObject([jsonTextPair(\"@type\", \"Answer\"), jsonTextPair(\"text\", faq.answer)]),\n ),\n ]),\n ...faqItemsFrom(faqs, i + 1),\n ];\n}\n","//@ backend dafny\nimport { jsonArray, jsonObject, jsonPair, jsonTextPair } from \"./json\";\nimport { crumbItemsFrom, faqItemsFrom, nodeHead, type Faq, type LdCrumb } from \"./json-ld-items\";\n\nexport { ldCrumb, nodeHead } from \"./json-ld-items\";\nexport type { Faq, LdCrumb } from \"./json-ld-items\";\n\n/* Structured data (JSON-LD): schema.org nodes written with the proved JSON text (`./json`,\n `jsonString`), the bytes JSON.stringify gives for the same object literal (keys in its order).\n Verified with LemmaScript → Dafny and linked to models/Utils.dfy \"structured data\"\n (models/links/utils-json-ld.dfy). The pieces are `./json-ld-items` (re-exported here), so a\n proved importer resolves every name these contracts use. @simpleapps-com/augur-hono and\n @simpleapps-com/augur-utils re-export these; a site builds its own nodes from the pieces and\n passes its own values, and a page puts the text in a `<script type=\"application/ld+json\">`. */\n\n/**\n * A reference to another node by its @id (`{\"@id\": id}`).\n *\n * @ensures exactly the model's IdRef\n */\nexport function idRef(id: string): string {\n //@ verify\n //@ ensures \\result === jsonObject([jsonTextPair(\"@id\", id)])\n return jsonObject([jsonTextPair(\"@id\", id)]);\n}\n\n/**\n * A breadcrumb trail's BreadcrumbList. Build the visible trail from the same crumbs, so the two\n * can't drift.\n *\n * @ensures exactly the model's BreadcrumbLd\n */\nexport function breadcrumbLd(crumbs: LdCrumb[]): string {\n //@ verify\n //@ ensures \\result === jsonObject(nodeHead(\"BreadcrumbList\").concat([jsonPair(\"itemListElement\", jsonArray(crumbItemsFrom(crumbs, 0)))]))\n return jsonObject([\n ...nodeHead(\"BreadcrumbList\"),\n jsonPair(\"itemListElement\", jsonArray(crumbItemsFrom(crumbs, 0))),\n ]);\n}\n\n/**\n * A FAQ page's FAQPage markup: one Question per entry, its answer the plain text. Render the\n * page's FAQ section from the same entries, so the two can't drift.\n *\n * @ensures exactly the model's FaqLd\n */\nexport function faqLd(faqs: Faq[]): string {\n //@ verify\n //@ ensures \\result === jsonObject(nodeHead(\"FAQPage\").concat([jsonPair(\"mainEntity\", jsonArray(faqItemsFrom(faqs, 0)))]))\n return jsonObject([\n ...nodeHead(\"FAQPage\"),\n jsonPair(\"mainEntity\", jsonArray(faqItemsFrom(faqs, 0))),\n ]);\n}\n","//@ backend dafny\n\n/* The JSON-LD builders' decisions (json-ld.ts), verified with LemmaScript → Dafny (model:\n models/AugurUtils.dfy; link: models/links/augur-utils-json-ld-rules.dfy). The callers apply\n JS `trim` and `toUpperCase` (Unicode, no lsc form) before these. */\n\n/**\n * A breadcrumb's position: its index plus one.\n *\n * @ensures exactly the model's BreadcrumbPosition\n */\nexport function breadcrumbPosition(i: number): number {\n //@ verify\n //@ ensures \\result === i + 1\n return i + 1;\n}\n\n/**\n * The GTIN field name for a UPC/EAN type, already uppercased by the caller.\n *\n * @ensures exactly the model's GtinField\n */\nexport function gtinFieldOf(upper: string): string {\n //@ verify\n //@ ensures upper === \"UPC\" ==> \\result === \"gtin12\"\n //@ ensures upper === \"EAN\" ==> \\result === \"gtin13\"\n //@ ensures upper !== \"UPC\" && upper !== \"EAN\" ==> \\result === \"gtin\"\n if (upper === \"UPC\") return \"gtin12\";\n if (upper === \"EAN\") return \"gtin13\";\n return \"gtin\";\n}\n\n/**\n * An item is kept out of JSON-LD when deleted, offline or inactive.\n *\n * @ensures exactly the model's IsSuppressed\n */\nexport function isSuppressedOf(deleteFlag: string, onlineCd: number, statusCd: number): boolean {\n //@ verify\n //@ ensures \\result === (deleteFlag === \"Y\" || onlineCd === 0 || statusCd === 0)\n return deleteFlag === \"Y\" || onlineCd === 0 || statusCd === 0;\n}\n\n/**\n * The product's name when it gets a Product JSON-LD: not suppressed, named (`name` trimmed by the\n * caller) and priced above 0; null otherwise.\n *\n * @ensures result ≠ null ⟺ the model's EmitsProduct, and then result = name\n */\nexport function productNameOf(suppressed: boolean, name: string, unitPrice: number): string | null {\n //@ verify\n //@ ensures suppressed ==> \\result === null\n //@ ensures !suppressed && (name === \"\" || unitPrice <= 0) ==> \\result === null\n //@ ensures !suppressed && name !== \"\" && unitPrice > 0 ==> \\result === name\n if (suppressed) return null;\n if (name === \"\" || unitPrice <= 0) return null;\n return name;\n}\n\n/**\n * The first non-blank of two texts (each trimmed by the caller), or undefined.\n *\n * @ensures exactly the model's FirstNonBlank\n */\nexport function firstNonBlankOf(a: string, b: string): string | undefined {\n //@ verify\n //@ ensures a !== \"\" ==> \\result === a\n //@ ensures a === \"\" && b !== \"\" ==> \\result === b\n //@ ensures a === \"\" && b === \"\" ==> \\result === undefined\n if (a !== \"\") return a;\n if (b !== \"\") return b;\n return undefined;\n}\n\n/**\n * The first primary (\"Y\") supplier from index `i`, or −1.\n *\n * @ensures exactly the model's PrimarySupplierFrom\n */\nexport function primarySupplierFrom(flags: string[], i: number): number {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases flags.length - i\n //@ ensures i >= flags.length ==> \\result === -1\n //@ ensures i < flags.length && flags[i] === \"Y\" ==> \\result === i\n //@ ensures i < flags.length && flags[i] !== \"Y\" ==> \\result === primarySupplierFrom(flags, i + 1)\n if (i >= flags.length) return -1;\n if ((flags[i] as string) === \"Y\") return i;\n return primarySupplierFrom(flags, i + 1);\n}\n\n/**\n * The supplier whose part number goes in: the first primary, else the first, else none (−1).\n *\n * @ensures exactly the model's SupplierIndex\n */\nexport function supplierIndexOf(flags: string[]): number {\n //@ verify\n //@ ensures primarySupplierFrom(flags, 0) >= 0 ==> \\result === primarySupplierFrom(flags, 0)\n //@ ensures primarySupplierFrom(flags, 0) < 0 && flags.length > 0 ==> \\result === 0\n //@ ensures primarySupplierFrom(flags, 0) < 0 && flags.length === 0 ==> \\result === -1\n const primary = primarySupplierFrom(flags, 0);\n if (primary >= 0) return primary;\n return flags.length > 0 ? 0 : -1;\n}\n\n/**\n * The offer's URL only when a site URL is configured.\n *\n * @ensures exactly the model's OfferUrl\n */\nexport function offerUrlOf(siteUrl: string, itemPath: string, itemId: string): string | undefined {\n //@ verify\n //@ ensures siteUrl !== \"\" ==> \\result === siteUrl + itemPath + \"/\" + itemId\n //@ ensures siteUrl === \"\" ==> \\result === undefined\n if (siteUrl === \"\") return undefined;\n return siteUrl + itemPath + \"/\" + itemId;\n}\n","import * as ld from \"@atlas/utils/json-ld\";\nimport type { TInvMastDoc } from \"./types/inventory\";\nimport type { TInventorySupplier } from \"./types/supplier\";\nimport { resolveStock } from \"./resolve-stock\";\nimport { getSchemaAvailability } from \"./schema-availability\";\nimport {\n breadcrumbPosition,\n firstNonBlankOf,\n gtinFieldOf,\n isSuppressedOf,\n offerUrlOf,\n productNameOf,\n supplierIndexOf,\n} from \"./json-ld-rules\";\n\n// ---------------------------------------------------------------------------\n// Breadcrumb JSON-LD\n// ---------------------------------------------------------------------------\n\nexport interface BreadcrumbJsonLdItem {\n name: string;\n url: string;\n}\n\n/** Generates a Schema.org BreadcrumbList JSON-LD object from an array of breadcrumb items. */\nexport function generateBreadcrumbJsonLd(items: BreadcrumbJsonLdItem[]): Record<string, unknown> {\n return {\n \"@context\": \"https://schema.org\",\n \"@type\": \"BreadcrumbList\",\n itemListElement: items.map((item, index) => ({\n \"@type\": \"ListItem\",\n position: breadcrumbPosition(index),\n name: item.name,\n item: item.url,\n })),\n };\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD as text: the proved builders of @atlas/utils `json-ld` (bundled), the bytes\n// JSON.stringify gives. Typed here so the published declarations name nothing private.\n// `breadcrumbLd(items)` is `JSON.stringify(generateBreadcrumbJsonLd(items))` for the same items.\n// The same builders, by the same names, as @simpleapps-com/augur-hono.\n// ---------------------------------------------------------------------------\n\n/** A FAQ entry: the question and its plain-text answer, as the page shows them. */\nexport interface Faq {\n question: string;\n answer: string;\n}\n\n/** A breadcrumb trail's BreadcrumbList as text. */\nexport const breadcrumbLd: (items: BreadcrumbJsonLdItem[]) => string = ld.breadcrumbLd;\n\n/** A FAQ page's FAQPage markup as text: one Question per entry. */\nexport const faqLd: (faqs: Faq[]) => string = ld.faqLd;\n\n/** The schema.org context and a node's type: its first two members, as JSON text. */\nexport const nodeHead: (type: string) => string[] = ld.nodeHead;\n\n/** A reference to another node by its @id, as JSON text. */\nexport const idRef: (id: string) => string = ld.idRef;\n\n// ---------------------------------------------------------------------------\n// Product JSON-LD — types\n// ---------------------------------------------------------------------------\n\nexport interface ProductJsonLdAggregateRating {\n ratingValue: number;\n reviewCount: number;\n}\n\nexport interface ProductJsonLdSeller {\n name: string;\n url?: string;\n}\n\nexport interface ProductJsonLdOptions {\n unitPrice: number;\n currency?: string;\n siteUrl?: string;\n itemPath?: string;\n seller?: ProductJsonLdSeller;\n priceValidDays?: number;\n imageUrlTransform?: (path: string) => string;\n returnPolicy?: Record<string, unknown>;\n shippingDetails?: Record<string, unknown>;\n aggregateRating?: ProductJsonLdAggregateRating;\n companyKey?: string;\n weightUnit?: string;\n dimensionUnit?: string;\n overrides?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Product JSON-LD — helpers\n// ---------------------------------------------------------------------------\n\nfunction getGtinField(upcOrEan: string | null | undefined): string {\n return gtinFieldOf(upcOrEan?.toUpperCase() ?? \"\");\n}\n\nfunction getPrimarySupplierPartNo(suppliers: TInventorySupplier[]): string | undefined {\n // A null flag is no \"Y\"; index -1 (no suppliers) reads undefined.\n const supplier = suppliers[supplierIndexOf(suppliers.map((s) => s.primarySupplierFlag ?? \"\"))];\n const partNo = supplier?.supplierPartNo?.trim();\n return partNo || undefined;\n}\n\nfunction buildQuantitativeValue(\n value: number | null | undefined,\n unitCode: string,\n): Record<string, unknown> | undefined {\n if (value == null || value === 0) return undefined;\n return { \"@type\": \"QuantitativeValue\", value: Math.round(value * 100) / 100, unitCode };\n}\n\nfunction omitEmpty(obj: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value) && value.length === 0) continue;\n if (typeof value === \"object\" && !Array.isArray(value)) {\n const cleaned = omitEmpty(value as Record<string, unknown>);\n if (Object.keys(cleaned).length > 0) {\n result[key] = cleaned;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction resolveBrand(doc: TInvMastDoc): Record<string, unknown> | undefined {\n const name = firstNonBlankOf(doc.brandName?.trim() ?? \"\", doc.parkerProductCd?.trim() ?? \"\");\n if (name === undefined) return undefined;\n return { \"@type\": \"Brand\", name };\n}\n\nfunction resolveDescription(doc: TInvMastDoc): string | undefined {\n return firstNonBlankOf(doc.displayDesc?.trim() ?? \"\", doc.extendedDesc?.trim() ?? \"\");\n}\n\nfunction resolveImages(\n doc: TInvMastDoc,\n transform?: (path: string) => string,\n): string[] | undefined {\n if (doc.images.length === 0) return undefined;\n return transform ? doc.images.map(transform) : [...doc.images];\n}\n\nfunction buildOffers(doc: TInvMastDoc, options: ProductJsonLdOptions): Record<string, unknown> {\n const currency = options.currency ?? \"USD\";\n const itemPath = options.itemPath ?? \"/items\";\n const priceValidDays = options.priceValidDays ?? 360;\n\n const resolved = resolveStock({ stock: doc.stock, companyKey: options.companyKey });\n const availability = getSchemaAvailability(resolved);\n\n const validUntil = new Date();\n validUntil.setDate(validUntil.getDate() + priceValidDays);\n\n const url = offerUrlOf(options.siteUrl ?? \"\", itemPath, doc.itemId);\n\n const eligibleQuantity = doc.defaultSellingUnit?.trim()\n ? { \"@type\": \"QuantitativeValue\", unitCode: doc.defaultSellingUnit.trim() }\n : undefined;\n\n const seller = options.seller\n ? { \"@type\": \"Organization\", name: options.seller.name, url: options.seller.url }\n : undefined;\n\n return {\n \"@type\": \"Offer\",\n price: options.unitPrice,\n priceCurrency: currency,\n availability,\n itemCondition: \"https://schema.org/NewCondition\",\n priceValidUntil: validUntil.toISOString().split(\"T\")[0],\n url,\n eligibleQuantity,\n seller,\n hasMerchantReturnPolicy: options.returnPolicy,\n shippingDetails: options.shippingDetails,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Product JSON-LD — main\n// ---------------------------------------------------------------------------\n\n/** The product's name when it gets a Product JSON-LD: not suppressed, named, and priced above 0; null otherwise. */\nfunction productName(doc: TInvMastDoc, unitPrice: number): string | null {\n const suppressed = isSuppressedOf(doc.deleteFlag, doc.onlineCd, doc.statusCd);\n return productNameOf(suppressed, (doc.itemDesc || \"\").trim(), unitPrice);\n}\n\nfunction buildAggregateRating(\n rating: ProductJsonLdAggregateRating | undefined,\n): Record<string, unknown> | undefined {\n if (!rating) return undefined;\n return {\n \"@type\": \"AggregateRating\",\n ratingValue: rating.ratingValue,\n reviewCount: rating.reviewCount,\n };\n}\n\n/** Generates a Schema.org Product JSON-LD string from an inventory document. Returns null if the item is suppressed, unnamed, or has no price. */\nexport function generateProductJsonLd(\n doc: TInvMastDoc,\n options: ProductJsonLdOptions,\n): string | null {\n const name = productName(doc, options.unitPrice);\n if (name === null) return null;\n\n const weightUnit = options.weightUnit ?? \"LBR\";\n const dimensionUnit = options.dimensionUnit ?? \"INH\";\n\n const gtinId = doc.upcOrEanId?.trim() || undefined;\n\n const aggregateRating = buildAggregateRating(options.aggregateRating);\n\n const product: Record<string, unknown> = {\n \"@context\": \"https://schema.org\",\n \"@type\": \"Product\",\n name,\n description: resolveDescription(doc),\n brand: resolveBrand(doc),\n sku: doc.itemId,\n image: resolveImages(doc, options.imageUrlTransform),\n ...(gtinId ? { [getGtinField(doc.upcOrEan)]: gtinId } : {}),\n mpn: getPrimarySupplierPartNo(doc.inventorySupplier),\n weight: buildQuantitativeValue(doc.weight, weightUnit),\n width: buildQuantitativeValue(doc.width, dimensionUnit),\n height: buildQuantitativeValue(doc.height, dimensionUnit),\n depth: buildQuantitativeValue(doc.length, dimensionUnit),\n offers: buildOffers(doc, options),\n aggregateRating,\n };\n\n const merged = options.overrides ? { ...product, ...options.overrides } : product;\n return JSON.stringify(omitEmpty(merged));\n}\n","import { unwrapMessage } from \"./rules\";\n\n/** Result type for safe action wrappers. */\nexport type SafeActionResult<T> = { ok: true; data: T } | { ok: false; error: string };\n\n/**\n * Extracts the data from a `SafeActionResult`, throwing on error.\n *\n * Ideal for React Query `queryFn` where errors should propagate\n * to the error boundary.\n *\n * @example\n * ```ts\n * const cart = unwrap(await getCartLines(cartId));\n * ```\n */\nexport function unwrap<T>(result: SafeActionResult<T>): T {\n if (!result.ok) throw new Error(unwrapMessage(result.error));\n return result.data;\n}\n\n/**\n * Extracts the data from a `SafeActionResult`, returning `null` on error.\n *\n * For direct calls that prefer `null` over thrown errors.\n *\n * @example\n * ```ts\n * const cart = unwrapOr(await getCartLines(cartId));\n * if (!cart) { /* handle missing data *\\/ }\n * ```\n */\nexport function unwrapOr<T>(result: SafeActionResult<T>): T | null {\n return result.ok ? (result.data ?? null) : null;\n}\n","//@ backend dafny\nimport { joinFrom } from \"@atlas/utils/lists\";\nimport {\n codeAt,\n indexOfCode,\n lowerAscii,\n startsWithAt,\n startsWithCaseless,\n} from \"@atlas/utils/strings\";\n\n/* The image CDN's decisions (image.ts), verified with LemmaScript → Dafny (model:\n models/AugurUtils.dfy; link: models/links/augur-utils-image-rules.dfy). The callers trim the\n path (JS `trim`) and list the transforms in object-key order. */\n\n/**\n * A transform field's CDN key, or \"\" when it has none.\n *\n * @ensures exactly the model's TransformKey\n */\nexport function transformKeyOf(field: string): string {\n //@ verify\n //@ ensures field === \"width\" ==> \\result === \"w\"\n //@ ensures field === \"height\" ==> \\result === \"h\"\n //@ ensures field === \"format\" ==> \\result === \"f\"\n //@ ensures field === \"quality\" ==> \\result === \"q\"\n //@ ensures field === \"fit\" ==> \\result === \"fit\"\n //@ ensures field !== \"width\" && field !== \"height\" && field !== \"format\" && field !== \"quality\" && field !== \"fit\" ==> \\result === \"\"\n if (field === \"width\") return \"w\";\n if (field === \"height\") return \"h\";\n if (field === \"format\") return \"f\";\n if (field === \"quality\") return \"q\";\n if (field === \"fit\") return \"fit\";\n return \"\";\n}\n\n/**\n * A transform value's text: \"jpg\" is sent as \"jpeg\" for the format field.\n *\n * @ensures exactly the model's TransformValue\n */\nexport function transformValueOf(field: string, value: string): string {\n //@ verify\n //@ ensures field === \"format\" && value === \"jpg\" ==> \\result === \"jpeg\"\n //@ ensures !(field === \"format\" && value === \"jpg\") ==> \\result === value\n if (field === \"format\" && value === \"jpg\") return \"jpeg\";\n return value;\n}\n\n/**\n * The `k_v` parts from index `i`: one for each known field with a value (`present`), in order.\n *\n * @ensures exactly the model's TransformParts\n */\nexport function transformPartsFrom(\n fields: string[],\n present: boolean[],\n texts: string[],\n i: number,\n): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && fields.length === present.length && fields.length === texts.length\n //@ decreases fields.length - i\n //@ ensures i >= fields.length ==> \\result.length === 0\n if (i >= fields.length) return [];\n const field = fields[i] as string;\n const key = transformKeyOf(field);\n const rest = transformPartsFrom(fields, present, texts, i + 1);\n if ((present[i] as boolean) && key !== \"\") {\n return [key + \"_\" + transformValueOf(field, texts[i] as string), ...rest];\n }\n return rest;\n}\n\n/**\n * serializeTransforms: the parts joined by \",\".\n *\n * @ensures exactly the model's SerializeTransforms\n */\nexport function serializedTransforms(\n fields: string[],\n present: boolean[],\n texts: string[],\n): string {\n //@ verify\n //@ requires fields.length === present.length && fields.length === texts.length\n //@ ensures \\result === joinFrom(transformPartsFrom(fields, present, texts, 0), \",\", 0)\n return joinFrom(transformPartsFrom(fields, present, texts, 0), \",\", 0);\n}\n\n/**\n * A URL, not a site path: \"https://\" in any case, or protocol-relative \"//host/…\". A plain\n * http:// URL is denied before this is asked (isInsecure). Was `startsWith(\"http\")`, which\n * mangled \"HTTPS://host/x\" into an agr.media path and passed a file named \"http-x.png\" as a URL.\n *\n * @ensures exactly the model's IsExternal\n */\nexport function isExternal(path: string): boolean {\n //@ verify\n //@ ensures \\result === (startsWithCaseless(path, \"https://\", 0) || startsWithAt(path, \"//\", 0))\n if (startsWithCaseless(path, \"https://\", 0)) return true;\n return startsWithAt(path, \"//\", 0);\n}\n\n/**\n * The path with the first prefix (from index `i`) it starts with stripped once.\n *\n * @ensures exactly the model's StripFirstPrefix\n */\nexport function stripFirstPrefixFrom(path: string, prefixes: string[], i: number): string {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases prefixes.length - i\n //@ ensures i >= prefixes.length ==> \\result === path\n if (i >= prefixes.length) return path;\n const prefix = prefixes[i] as string;\n if (startsWithAt(path, prefix, 0)) return path.slice(prefix.length);\n return stripFirstPrefixFrom(path, prefixes, i + 1);\n}\n\n/**\n * Every leading \"/\" removed (`replace(/^\\/+/, \"\")`).\n *\n * @ensures exactly the model's StripLeadingSlashes\n */\nexport function stripLeadingSlashes(s: string): string {\n //@ verify\n //@ decreases s.length\n //@ ensures codeAt(s, 0) !== 47 ==> \\result === s\n if (codeAt(s, 0) !== 47) return s;\n return stripLeadingSlashes(s.slice(1));\n}\n\n/**\n * A path relative to the site: the first matching prefix stripped once, then the leading\n * slashes, then defaultPath + \"/\" before a bare file name when a defaultPath (\"\" for none) is\n * set.\n *\n * @ensures exactly the model's LocalPath\n */\nexport function localPath(raw: string, prefixes: string[], defaultPath: string): string {\n //@ verify\n //@ ensures defaultPath === \"\" ==> \\result === stripLeadingSlashes(stripFirstPrefixFrom(raw, prefixes, 0))\n const cleaned = stripLeadingSlashes(stripFirstPrefixFrom(raw, prefixes, 0));\n if (defaultPath !== \"\" && indexOfCode(cleaned, 47, 0) < 0) return defaultPath + \"/\" + cleaned;\n return cleaned;\n}\n\n/* Own origins (atlas#175). A CMS stores many images as absolute URLs on the site's own image\n host, which agr.media mirrors: images.<d>/X, www.<d>/images/X and <d>/images/X are all the\n file X under agr.media/<d>/images (owner 2026-11-14). An origin is a host, optionally with a\n path (\"www.example.com/images\"); it matches after \"https://\" (either case), the host\n ASCII-caseless, the path exactly, and only with a \"/\" right after it. What follows is a path\n from the images root: no strip prefixes, no defaultPath.\n\n A plain http:// URL, in any case, is denied (owner 2026-11-14: \"all http:// without the s\n MUST be denied\"): it is no image, so getImageUrl gives the default image (\"\" without one) and\n normalizePath \"\". No http:// URL is ever returned (model NeverInsecure). */\n\n/**\n * A plain http:// URL, in any case: denied.\n *\n * @ensures exactly the model's IsInsecure\n */\nexport function isInsecure(s: string): boolean {\n //@ verify\n //@ ensures \\result === startsWithCaseless(s, \"http://\", 0)\n return startsWithCaseless(s, \"http://\", 0);\n}\n\n/**\n * Where the host starts: after \"https://\" (8, either case) or a protocol-relative \"//\" (2);\n * 0 otherwise.\n *\n * @ensures exactly the model's SchemeEnd\n */\nexport function schemeEnd(raw: string): number {\n //@ verify\n //@ ensures startsWithCaseless(raw, \"https://\", 0) ==> \\result === 8\n //@ ensures !startsWithCaseless(raw, \"https://\", 0) && startsWithAt(raw, \"//\", 0) ==> \\result === 2\n //@ ensures !startsWithCaseless(raw, \"https://\", 0) && !startsWithAt(raw, \"//\", 0) ==> \\result === 0\n if (startsWithCaseless(raw, \"https://\", 0)) return 8;\n return startsWithAt(raw, \"//\", 0) ? 2 : 0;\n}\n\n/**\n * The index of an origin's first \"/\", its length when it has none: where its host ends.\n *\n * @ensures exactly the model's SlashAt\n */\nexport function slashAt(o: string): number {\n //@ verify\n //@ ensures 0 <= \\result && \\result <= o.length\n //@ ensures forall(k: nat, k < \\result ==> o.charCodeAt(k) !== 47)\n //@ ensures \\result < o.length ==> o.charCodeAt(\\result) === 47\n const k = indexOfCode(o, 47, 0);\n return k < 0 ? o.length : k;\n}\n\n/**\n * Origin `o` sits at `at` in `raw` (its host caselessly, its path exactly), and a \"/\" follows.\n *\n * @ensures exactly the model's OwnOriginAt\n */\nexport function ownOriginAt(raw: string, o: string, at: number): boolean {\n //@ verify\n //@ type at nat\n //@ requires at >= 0\n //@ ensures \\result === (slashAt(o) > 0 && startsWithCaseless(raw, lowerAscii(o.slice(0, slashAt(o))), at) && startsWithAt(raw, o.slice(slashAt(o)), at + slashAt(o)) && codeAt(raw, at + o.length) === 47)\n const cut = slashAt(o);\n if (cut === 0) return false;\n if (!startsWithCaseless(raw, lowerAscii(o.slice(0, cut)), at)) return false;\n if (!startsWithAt(raw, o.slice(cut), at + cut)) return false;\n return codeAt(raw, at + o.length) === 47;\n}\n\n/**\n * The path after the first own origin (from index `i`) the URL starts with; null for any other\n * string, or when nothing follows the origin.\n *\n * @ensures exactly the model's OwnOriginRest\n */\nexport function ownOriginRestFrom(raw: string, origins: string[], i: number): string | null {\n //@ verify\n //@ type i nat\n //@ requires i >= 0\n //@ decreases origins.length - i\n //@ ensures (schemeEnd(raw) === 0 || i >= origins.length) ==> \\result === null\n const at = schemeEnd(raw);\n if (at === 0 || i >= origins.length) return null;\n const o = origins[i] as string;\n if (ownOriginAt(raw, o, at)) {\n const path = stripLeadingSlashes(raw.slice(at + o.length));\n return path === \"\" ? null : path;\n }\n return ownOriginRestFrom(raw, origins, i + 1);\n}\n\n/**\n * createImageConfig's default origins for a clientDomain (a bare domain, \"example.com\").\n *\n * @ensures exactly the model's DefaultOwnOrigins\n */\nexport function defaultOwnOrigins(clientDomain: string): string[] {\n //@ verify\n //@ ensures \\result.length === 3\n //@ ensures \\result[0] === \"images.\" + clientDomain\n //@ ensures \\result[1] === \"www.\" + clientDomain + \"/images\"\n //@ ensures \\result[2] === clientDomain + \"/images\"\n return [\"images.\" + clientDomain, \"www.\" + clientDomain + \"/images\", clientDomain + \"/images\"];\n}\n\n/**\n * normalizePath: \"\" for a denied http:// URL; an own-origin URL is its path from the images\n * root; any other external URL as is; else the local path (\"\" when it reads as http://).\n *\n * @ensures exactly the model's NormalizePath\n */\nexport function normalizedPath(\n raw: string,\n prefixes: string[],\n origins: string[],\n defaultPath: string,\n): string {\n //@ verify\n //@ ensures isInsecure(raw) ==> \\result === \"\"\n //@ ensures !isInsecure(raw) && ownOriginRestFrom(raw, origins, 0) === null && isExternal(raw) ==> \\result === raw\n if (isInsecure(raw)) return \"\";\n const own = ownOriginRestFrom(raw, origins, 0);\n if (own !== null) return own;\n if (isExternal(raw)) return raw;\n const local = localPath(raw, prefixes, defaultPath);\n return isInsecure(local) ? \"\" : local;\n}\n\n/**\n * The CDN URL for a normalized path, with the transform segment only when there is one.\n *\n * @ensures exactly the model's CdnUrl\n */\nexport function cdnUrlOf(clientDomain: string, serialized: string, normalized: string): string {\n //@ verify\n //@ ensures serialized !== \"\" ==> \\result === \"https://agr.media/\" + clientDomain + \"/images/\" + serialized + \"/\" + normalized\n //@ ensures serialized === \"\" ==> \\result === \"https://agr.media/\" + clientDomain + \"/images/\" + normalized\n const segment = serialized !== \"\" ? \"/\" + serialized : \"\";\n return \"https://agr.media/\" + clientDomain + \"/images\" + segment + \"/\" + normalized;\n}\n\n/**\n * A srcset's entries from index `i`: \"<url> <width>w\" for each width whose URL is not \"\" (a\n * blank or denied image with no default has none, and an entry without a URL is unreadable).\n *\n * @ensures exactly the model's SrcSetParts\n */\nexport function srcSetPartsFrom(urls: string[], widths: string[], i: number): string[] {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && urls.length === widths.length\n //@ decreases urls.length - i\n //@ ensures i >= urls.length ==> \\result.length === 0\n if (i >= urls.length) return [];\n const url = urls[i] as string;\n const rest = srcSetPartsFrom(urls, widths, i + 1);\n return url === \"\" ? rest : [url + \" \" + (widths[i] as string) + \"w\", ...rest];\n}\n\n/**\n * getImageSrcSet: the entries joined by \", \".\n *\n * @ensures exactly the model's SrcSet\n */\nexport function srcSetOf(urls: string[], widths: string[]): string {\n //@ verify\n //@ requires urls.length === widths.length\n //@ ensures \\result === joinFrom(srcSetPartsFrom(urls, widths, 0), \", \", 0)\n return joinFrom(srcSetPartsFrom(urls, widths, 0), \", \", 0);\n}\n\n/**\n * getDefaultImageUrl over the chosen fallback: \"\" for none or a denied http:// one; an\n * own-origin fallback goes to the CDN at its path, any other external one as is, else the CDN\n * URL of its local path.\n *\n * @ensures exactly the model's DefaultImageUrl\n */\nexport function defaultImageUrlOf(\n clientDomain: string,\n fallback: string,\n prefixes: string[],\n origins: string[],\n defaultPath: string,\n): string {\n //@ verify\n //@ ensures fallback === \"\" ==> \\result === \"\"\n //@ ensures isInsecure(fallback) ==> \\result === \"\"\n if (fallback === \"\" || isInsecure(fallback)) return \"\";\n const own = ownOriginRestFrom(fallback, origins, 0);\n if (own !== null) return \"https://agr.media/\" + clientDomain + \"/images/\" + own;\n if (isExternal(fallback)) return fallback;\n const local = localPath(fallback, prefixes, defaultPath);\n if (isInsecure(local)) return \"\";\n if (isExternal(local)) return local;\n return \"https://agr.media/\" + clientDomain + \"/images/\" + local;\n}\n\n/**\n * getImageUrl on a trimmed path: a blank or denied http:// one gives the default; an own-origin\n * URL the CDN URL of its path; any other external one passes; else the CDN URL of its local path.\n *\n * @ensures exactly the model's ImageUrl on the trimmed path\n */\nexport function imageUrlOf(\n clientDomain: string,\n path: string,\n serialized: string,\n fallback: string,\n prefixes: string[],\n origins: string[],\n defaultPath: string,\n): string {\n //@ verify\n //@ ensures (path === \"\" || isInsecure(path)) ==> \\result === defaultImageUrlOf(clientDomain, fallback, prefixes, origins, defaultPath)\n //@ ensures path !== \"\" && !isInsecure(path) && ownOriginRestFrom(path, origins, 0) === null && isExternal(path) ==> \\result === path\n if (path === \"\" || isInsecure(path)) {\n return defaultImageUrlOf(clientDomain, fallback, prefixes, origins, defaultPath);\n }\n const own = ownOriginRestFrom(path, origins, 0);\n if (own !== null) return cdnUrlOf(clientDomain, serialized, own);\n if (isExternal(path)) return path;\n const local = localPath(path, prefixes, defaultPath);\n if (isInsecure(local))\n return defaultImageUrlOf(clientDomain, fallback, prefixes, origins, defaultPath);\n if (isExternal(local)) return local;\n return cdnUrlOf(clientDomain, serialized, local);\n}\n","/**\n * Image CDN utilities for agr.media.\n * Pure functions -- no DOM or React dependencies. Safe for server, web, and mobile.\n * The decisions are proved in image-rules.ts.\n */\n\nimport {\n defaultImageUrlOf,\n defaultOwnOrigins,\n imageUrlOf,\n normalizedPath,\n serializedTransforms,\n srcSetOf,\n} from \"./image-rules\";\n\n/** 1x1 transparent PNG for Next.js `<Image blurDataURL={...}>` placeholders. */\nexport const BLUR_DATA_URL =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mN88P/BfwYABQoBfqVKzQAAAABJRU5ErkJggg==\";\n\nexport interface ImageTransforms {\n width?: number;\n height?: number;\n format?: \"auto\" | \"webp\" | \"avif\" | \"jpeg\" | \"jpg\" | \"png\";\n quality?: number;\n fit?: \"cover\" | \"contain\" | \"fill\" | \"inside\" | \"outside\";\n}\n\nexport interface ImageConfig {\n readonly clientDomain: string;\n readonly defaultImage?: string;\n readonly defaultTransforms?: ImageTransforms;\n readonly stripPrefixes?: string[];\n readonly defaultPath?: string;\n /**\n * The site's own image hosts, which agr.media mirrors: an absolute URL on one of them is\n * rewritten to agr.media like a relative path. Each is a host, optionally with a path\n * (`\"www.example.com/images\"`), no scheme. Defaults to `images.<clientDomain>`,\n * `www.<clientDomain>/images` and `<clientDomain>/images`.\n */\n readonly ownOrigins?: string[];\n}\n\nexport interface ImageUrlOptions {\n defaultImage?: string;\n}\n\nconst DEFAULT_STRIP_PREFIXES = [\"/images\", \"images\"];\n\n/**\n * Creates a frozen ImageConfig object.\n *\n * `stripPrefixes` defaults to `[\"/images\", \"images\"]` — set to `[]` to disable.\n * `ownOrigins` defaults to `images.<clientDomain>`, `www.<clientDomain>/images` and\n * `<clientDomain>/images`; a list replaces them, `[]` disables the rewrite.\n */\nexport function createImageConfig(\n clientDomain: string,\n opts?: {\n defaultImage?: string;\n defaultTransforms?: ImageTransforms;\n stripPrefixes?: string[];\n defaultPath?: string;\n ownOrigins?: string[];\n },\n): ImageConfig {\n return Object.freeze({\n clientDomain,\n defaultImage: opts?.defaultImage,\n defaultTransforms: opts?.defaultTransforms,\n stripPrefixes: opts?.stripPrefixes ?? DEFAULT_STRIP_PREFIXES,\n defaultPath: opts?.defaultPath,\n ownOrigins: opts?.ownOrigins ?? defaultOwnOrigins(clientDomain),\n });\n}\n\n/**\n * Serializes transform options into the CDN path segment.\n * Example: `{ width: 400, format: \"webp\" }` → `\"w_400,f_webp\"`\n */\nexport function serializeTransforms(transforms: ImageTransforms): string {\n // The fields in object-key order; `serializedTransforms` keeps the known ones with a value.\n const entries = Object.entries(transforms);\n return serializedTransforms(\n entries.map(([key]) => key),\n entries.map(([, value]) => value !== undefined),\n entries.map(([, value]) => String(value)),\n );\n}\n\n/**\n * Normalizes an image path by:\n * 1. Returning the path after the origin for a URL on one of `ownOrigins` (the site's own image\n * host: `https://images.<clientDomain>/a/b.jpg` → `a/b.jpg`).\n * 2. Returning `\"\"` for a plain `http://` URL (denied), and any other URL (`https://` in any\n * case, or protocol-relative `//host/…`) as-is (external).\n * 3. Stripping configured prefixes (defaults: `/images`, `images`).\n * 4. Prepending `defaultPath` for bare filenames (no `/`).\n * 5. Stripping leading slashes.\n */\nexport function normalizePath(config: ImageConfig, raw: string): string {\n return normalizedPath(raw, prefixesOf(config), originsOf(config), config.defaultPath ?? \"\");\n}\n\n/** The config's strip prefixes, the defaults when unset. */\nfunction prefixesOf(config: ImageConfig): string[] {\n return config.stripPrefixes ?? DEFAULT_STRIP_PREFIXES;\n}\n\n/** The config's own origins, the clientDomain's defaults when unset. */\nfunction originsOf(config: ImageConfig): string[] {\n return config.ownOrigins ?? defaultOwnOrigins(config.clientDomain);\n}\n\n/**\n * Builds a full agr.media URL for the given image path and transforms.\n *\n * - Empty/nullish paths and plain `http://` URLs (denied) return the default image URL.\n * - URLs on the site's own image host (`ownOrigins`) go to agr.media like relative paths.\n * - Other URLs (`https://` in any case, or protocol-relative `//host/…`) are returned as-is.\n * - Configured prefixes (default: `/images`) are stripped automatically.\n * - Bare filenames are prepended with `config.defaultPath` if set.\n */\nexport function getImageUrl(\n config: ImageConfig,\n imagePath: string | undefined | null,\n transforms?: ImageTransforms,\n options?: ImageUrlOptions,\n): string {\n const merged: ImageTransforms = {\n ...config.defaultTransforms,\n ...transforms,\n };\n return imageUrlOf(\n config.clientDomain,\n imagePath?.trim() ?? \"\",\n serializeTransforms(merged),\n fallbackOf(config, options),\n prefixesOf(config),\n originsOf(config),\n config.defaultPath ?? \"\",\n );\n}\n\n/**\n * Returns the default/placeholder image URL.\n * Per-call `options.defaultImage` overrides `config.defaultImage`.\n */\nexport function getDefaultImageUrl(config: ImageConfig, options?: ImageUrlOptions): string {\n return defaultImageUrlOf(\n config.clientDomain,\n fallbackOf(config, options),\n prefixesOf(config),\n originsOf(config),\n config.defaultPath ?? \"\",\n );\n}\n\n/** The fallback image: the call's, else the config's (\"\" for none). */\nfunction fallbackOf(config: ImageConfig, options?: ImageUrlOptions): string {\n return options?.defaultImage ?? config.defaultImage ?? \"\";\n}\n\n/**\n * Generates a `srcset` string for responsive images: one entry per width with a URL, so a\n * blank or denied image with no default gives `\"\"`.\n */\nexport function getImageSrcSet(\n config: ImageConfig,\n imagePath: string,\n widths: number[],\n transforms?: ImageTransforms,\n): string {\n return srcSetOf(\n widths.map((width) => getImageUrl(config, imagePath, { ...transforms, width })),\n widths.map(String),\n );\n}\n\n/**\n * Returns a loader function compatible with Next.js `<Image loader={...}>`.\n */\nexport function buildImageLoader(\n config: ImageConfig,\n transforms?: ImageTransforms,\n): (props: { src: string; width: number; quality?: number }) => string {\n return ({ src, width, quality }) => {\n const merged: ImageTransforms = { ...transforms, width };\n if (quality !== undefined) {\n merged.quality = quality;\n }\n return getImageUrl(config, src, merged);\n };\n}\n\n/**\n * Rewrites `<img src=\"...\">` attributes in an HTML string to use agr.media URLs.\n * Useful for CMS/Joomla content that contains raw image references.\n */\nexport function sanitizeHtmlImages(\n config: ImageConfig,\n html: string,\n transforms?: ImageTransforms,\n): string {\n return html.replace(\n /<img\\s([^>]*?)src=[\"']([^\"']+)[\"']/gi,\n (_match, before: string, src: string) => {\n const cdnUrl = getImageUrl(config, src, transforms);\n return `<img ${before}src=\"${cdnUrl}\"`;\n },\n );\n}\n","/**\n * Common regex patterns used for form validation across augur-hosted sites.\n */\nexport const VALIDATION_PATTERNS = {\n /** Phone number format: (123) 456-7890 or 123-456-7890 or 123.456.7890 */\n phoneNumber: /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,\n\n /** Name format: Must start with non-hyphen/space, allow word chars, spaces, hyphens */\n nameFormat: /^[^-\\s][\\w\\s-]+$/,\n\n /** Name must not contain numbers */\n nameNoNumbers: /^([^0-9]*)$/,\n\n /** Address format: Allow word chars, spaces, hyphens, slashes, periods, hash, commas */\n addressFormat: /^[^-\\s][\\w\\s\\-\\/.#,]+$/,\n\n /** No PO Box pattern - prevents PO Box addresses */\n noPOBox:\n /^(?!.*(P\\.?\\s*O\\.?\\s*BOX|POST\\s*OFFICE\\s*BOX|PO\\s*BOX|P\\s*O\\s*B\\s*O\\s*X|POBOX|P\\.O\\.B\\.)).*$/i,\n\n /** Zip code: Exactly 5 digits */\n zipCode: /^\\d{5}$/,\n\n /** City: Letters, spaces, periods, hyphens, apostrophes only */\n cityFormat: /^[a-zA-Z\\s.\\-']+$/,\n\n /** Address must contain at least one number */\n hasNumber: /\\d/,\n} as const;\n","import * as v from \"valibot\";\nimport { VALIDATION_PATTERNS } from \"./validation-patterns\";\nimport { US_STATES } from \"./us-states\";\n\nconst validStateCodes = US_STATES.map((state) => state.code) as [string, ...string[]];\n\n/** A required person name: name characters only, no digits. */\nfunction personName(requiredMessage: string, invalidMessage: string) {\n return v.pipe(\n v.string(),\n v.minLength(1, requiredMessage),\n v.regex(VALIDATION_PATTERNS.nameFormat, invalidMessage),\n v.regex(VALIDATION_PATTERNS.nameNoNumbers, invalidMessage),\n );\n}\n\nconst firstName = personName(\"First name is required\", \"Invalid first name\");\nconst lastName = personName(\"Last name is required\", \"Invalid last name\");\n\n/**\n * Valibot schema for shipping address validation.\n * Enforces no PO Box, requires street number, formats phone number.\n */\nexport const ShippingAddressSchema = v.object({\n companyName: v.optional(v.string()),\n firstName,\n lastName,\n address1: v.pipe(\n v.string(),\n v.minLength(1, \"Address 1 is required\"),\n v.regex(VALIDATION_PATTERNS.addressFormat, \"Invalid address\"),\n v.regex(VALIDATION_PATTERNS.noPOBox, \"PO Box addresses are not allowed for shipping\"),\n v.regex(VALIDATION_PATTERNS.hasNumber, \"Address must contain at least one number\"),\n ),\n address2: v.optional(\n v.pipe(\n v.string(),\n v.check(\n (val) => !val || VALIDATION_PATTERNS.addressFormat.test(val),\n \"Invalid address format\",\n ),\n v.check(\n (val) => !val || VALIDATION_PATTERNS.noPOBox.test(val),\n \"PO Box addresses are not allowed for shipping\",\n ),\n ),\n ),\n postalCode: v.pipe(\n v.string(),\n v.minLength(1, \"Zip code is required\"),\n v.regex(VALIDATION_PATTERNS.zipCode, \"Zip code must be exactly 5 digits\"),\n ),\n city: v.pipe(\n v.string(),\n v.minLength(2, \"City is required\"),\n v.regex(\n VALIDATION_PATTERNS.cityFormat,\n \"City must contain only letters, spaces, periods, hyphens, or apostrophes\",\n ),\n ),\n state: v.pipe(\n v.string(),\n v.minLength(1, \"State is required\"),\n v.picklist(validStateCodes, \"Please select a valid US state\"),\n ),\n country: v.pipe(v.string(), v.minLength(1, \"Country is required\")),\n email: v.pipe(v.string(), v.minLength(1, \"Email is required\"), v.email(\"Invalid email\")),\n phoneNumber: v.pipe(\n v.string(),\n v.minLength(1, \"Phone number is required\"),\n v.regex(VALIDATION_PATTERNS.phoneNumber, \"Invalid phone number\"),\n v.transform((val) => {\n const digits = val.replace(/\\D/g, \"\");\n return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;\n }),\n ),\n notes: v.optional(v.string()),\n plus4Code: v.optional(v.string()),\n});\n\n/**\n * Valibot schema for billing address validation.\n * Less strict than shipping: allows PO Box, no email/phone required.\n */\nexport const BillingAddressSchema = v.object({\n poNumber: v.optional(v.string()),\n firstName,\n lastName,\n address1: v.pipe(\n v.string(),\n v.minLength(1, \"Address 1 is required\"),\n v.regex(VALIDATION_PATTERNS.addressFormat, \"Invalid address\"),\n ),\n address2: v.optional(v.string()),\n postalCode: v.pipe(v.string(), v.minLength(1, \"Zip code is required\")),\n city: v.pipe(v.string(), v.minLength(1, \"City is required\")),\n state: v.pipe(v.string(), v.minLength(1, \"State is required\")),\n country: v.pipe(v.string(), v.minLength(1, \"Country is required\")),\n plus4Code: v.optional(v.string()),\n});\n\n/**\n * Valibot schema for billing address with required PO number (invoice payments).\n */\nexport const BillingAddressInvoiceSchema = v.object({\n poNumber: v.pipe(v.string(), v.minLength(2, \"PO number is required\")),\n});\n\nexport type ShippingAddress = v.InferOutput<typeof ShippingAddressSchema>;\nexport type BillingAddress = v.InferOutput<typeof BillingAddressSchema>;\n","import { states } from \"states-us\";\nimport type { State } from \"states-us\";\n\nexport type { State as USState };\n\n/** All US states and territories — full data from states-us. */\nexport const US_STATES_FULL = states;\n\n/** All US states and territories — backward-compatible {code, name} shape. */\nexport const US_STATES = states.map((s) => ({\n code: s.abbreviation,\n name: s.name,\n}));\n\n/** Lower 48 contiguous states. */\nexport const CONTIGUOUS_STATES = states.filter((s) => s.contiguous);\n\n/** US territories (PR, GU, VI, AS, MP). */\nexport const US_TERRITORIES = states.filter((s) => s.territory);\n\nexport type USStateCode = (typeof US_STATES)[number][\"code\"];\n","/**\n * Date utility functions for shipping calculations.\n */\n\nimport { isBusinessDayName, leadDateText, shippingLeadOf } from \"./rules\";\n\nconst DATE_FORMAT_OPTIONS: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"short\",\n day: \"numeric\",\n};\n\n/**\n * Get the Nth business day from today (skipping weekends).\n * @param businessDaysFromNow - Number of business days to add\n * @returns Formatted date string\n */\nexport function getBusinessDay(businessDaysFromNow: number): string {\n const businessDays: string[] = [];\n let i = 1;\n\n while (businessDays.length < businessDaysFromNow) {\n const date = new Date();\n date.setDate(date.getDate() + i);\n const dayName = date.toLocaleDateString(\"en-US\", { weekday: \"long\" });\n\n if (isBusinessDayName(dayName)) {\n businessDays.push(date.toLocaleDateString(\"en-US\", DATE_FORMAT_OPTIONS));\n }\n i++;\n }\n\n return businessDays[businessDays.length - 1] || \"\";\n}\n\n/**\n * Get shipping lead date estimate based on days string (the table is `shippingLeadOf`).\n * @param days - Shipping days string (e.g., \"1-2\", \"2-3\", \"3\")\n * @returns Formatted date range or single date\n */\nexport function getShippingLeadDate(days: string): string {\n const config = shippingLeadOf(days);\n if (!config) return \"\";\n\n const hasTo = config.to !== 0;\n return leadDateText(getBusinessDay(config.from), hasTo, hasTo ? getBusinessDay(config.to) : \"\");\n}\n","import { categorySortBy, pageOffset, searchSortBy } from \"./rules\";\nimport type { TItemsFilters } from \"./types/filter\";\n\n/**\n * Options for category item filter serialization.\n * All fields optional — omit what you don't need.\n */\nexport interface CategoryFilterOptions {\n /** Prefix prepended to non-empty sortBy values (e.g. \"item_category_sequence_no_min|\"). */\n sortByPrefix?: string;\n /** Whether to include stock data in results. Default: true. */\n includeStock?: boolean;\n}\n\n/**\n * Options for search param serialization.\n * All fields optional — omit what you don't need.\n */\nexport interface SearchParamOptions {\n /** Category UID to scope search results. Converted to classId5List string. */\n categoryUid?: number | string;\n /** Source fields for search results. Default: \"display_desc\". */\n sourceFields?: string;\n}\n\n/**\n * Converts TItemsFilters to the SDK params shape for category item endpoints.\n *\n * Pure function. Idempotent. Produces params ready to spread into\n * `q.items.itemCategory.categoryItems.list(uid, params)`.\n *\n * Transforms applied:\n * - filters: [string, string][] -> JSON string\n * - sortBy: prefixed with sortByPrefix if configured and non-empty\n * - includeStock: \"Y\" added by default\n * - page field: stripped (SDK uses limit/offset, not page)\n */\nexport function serializeCategoryFilters(\n filters: TItemsFilters,\n options?: CategoryFilterOptions,\n): Record<string, unknown> {\n const { sortByPrefix, includeStock = true } = options ?? {};\n\n // A sortBy missing at runtime (the type says string) stays as it came.\n const sortBy: string = filters.sortBy\n ? categorySortBy(sortByPrefix ?? \"\", filters.sortBy)\n : filters.sortBy;\n\n const params: Record<string, unknown> = {\n filters: JSON.stringify(filters.filters),\n limit: filters.limit,\n offset: filters.offset,\n q: filters.q,\n sortBy,\n };\n\n if (includeStock) {\n params[\"includeStock\"] = \"Y\";\n }\n\n return params;\n}\n\n/**\n * Converts TItemsFilters to the SDK params shape for search endpoints.\n *\n * Pure function. Idempotent. Produces params ready to spread into\n * `q.openSearch.itemSearch.list(params)`.\n *\n * Transforms applied:\n * - limit -> size, offset -> from (field rename)\n * - searchType: \"query\" injected\n * - categoryUid -> classId5List (string conversion)\n * - filters: [string, string][] -> JSON string (or undefined if empty)\n * - sourceFieldsList: injected from options or default \"display_desc\"\n * - page field: stripped\n */\nexport function serializeSearchParams(\n filters: TItemsFilters,\n options?: SearchParamOptions,\n): Record<string, unknown> {\n const { categoryUid, sourceFields = \"display_desc\" } = options ?? {};\n\n return {\n q: filters.q,\n searchType: \"query\",\n size: filters.limit,\n from: filters.offset,\n sortBy: searchSortBy(filters.sortBy),\n classId5List: categoryUid ? String(categoryUid) : undefined,\n filters: filters.filters?.length ? JSON.stringify(filters.filters) : undefined,\n sourceFieldsList: sourceFields,\n };\n}\n\n/**\n * Returns a copy of filters with offset adjusted for the given page.\n *\n * Pure function. Idempotent. Use with useInfiniteQuery's pageParam\n * to compute the correct offset for each page.\n *\n * @example\n * ```tsx\n * useInfiniteQuery({\n * ...q.items.itemCategory.categoryItems.list(\n * uid,\n * serializeCategoryFilters(paginateOffset(filters, pageParam), site)\n * ),\n * initialPageParam: 0,\n * getNextPageParam: (last, _all, lastPage) =>\n * (lastPage + 1) * filters.limit < last.total ? lastPage + 1 : undefined,\n * });\n * ```\n */\nexport function paginateOffset(filters: TItemsFilters, pageParam: number): TItemsFilters {\n return {\n ...filters,\n offset: pageOffset(pageParam, filters.limit),\n };\n}\n","/**\n * Analytics utility functions for tracking ecommerce events via Google Analytics.\n */\n\nimport { cleanMoney, roundHalfAway } from \"./money\";\n\ndeclare global {\n interface Window {\n dataLayer?: Record<string, unknown>[];\n gtag?: (...args: unknown[]) => void;\n }\n}\n\nexport interface AddToCartEventParams {\n itemId: string;\n itemName: string;\n price: number;\n quantity: number;\n estimatedCost: number;\n}\n\n/**\n * Track add_to_cart event to Google Analytics dataLayer.\n */\nexport function trackAddToCart({\n itemId,\n itemName,\n price,\n quantity,\n estimatedCost,\n}: AddToCartEventParams): void {\n if (typeof window === \"undefined\" || !window.dataLayer) return;\n\n // Clear previous ecommerce data\n window.dataLayer.push({ ecommerce: null });\n\n window.dataLayer.push({\n event: \"add_to_cart\",\n ecommerce: {\n currency: \"USD\",\n value: roundHalfAway(estimatedCost, 2),\n items: [\n {\n item_id: itemId,\n item_name: itemName,\n currency: \"USD\",\n index: 0,\n item_category: \"\",\n price,\n quantity,\n },\n ],\n },\n });\n}\n\nexport interface ViewItemEventParams {\n itemId: string;\n itemName: string;\n price: number;\n category?: string;\n}\n\n/**\n * Track view_item event to Google Analytics dataLayer.\n */\nexport function trackViewItem({\n itemId,\n itemName,\n price,\n category = \"\",\n}: ViewItemEventParams): void {\n if (typeof window === \"undefined\" || !window.gtag) return;\n\n window.gtag(\"event\", \"view_item\", {\n currency: \"USD\",\n value: price,\n items: [\n {\n item_id: itemId,\n item_name: itemName,\n currency: \"USD\",\n index: 0,\n item_category: category,\n price,\n quantity: 1,\n },\n ],\n });\n}\n\n// ---------------------------------------------------------------------------\n// GA4 begin_checkout tracking\n// ---------------------------------------------------------------------------\n\nexport interface TrackingItem {\n item_id: string;\n item_name: string;\n currency: string;\n index: number;\n item_category: string;\n price: number;\n quantity: number;\n}\n\nexport interface TrackingData {\n event: string;\n currency: string;\n value: number;\n items: TrackingItem[];\n}\n\nexport interface BuildTrackingDataInput {\n cartLines: { itemId: string; quantity: number }[];\n itemDetails: Record<string, { itemDesc?: string; classId5?: string }>;\n /**\n * Unit price of the line at `index` in `cartLines` (useCartPricing's `getLineUnitPrice`). Per\n * line, not per item: one item on two lines (two units of measure) has two prices.\n */\n getLineUnitPrice: (index: number) => number;\n currency?: string;\n}\n\n/**\n * Build a GA4 begin_checkout ecommerce payload from cart lines, item details, and each line's own\n * price.\n */\nexport function buildTrackingData({\n cartLines,\n itemDetails,\n getLineUnitPrice,\n currency = \"USD\",\n}: BuildTrackingDataInput): TrackingData {\n let total = 0;\n const items: TrackingItem[] = cartLines.map((line, index) => {\n const details = itemDetails[line.itemId];\n const price = getLineUnitPrice(index);\n total = cleanMoney(total + cleanMoney(price * line.quantity));\n return {\n item_id: line.itemId,\n item_name: details?.itemDesc ?? \"\",\n currency,\n index,\n item_category: details?.classId5 ?? \"\",\n price,\n quantity: line.quantity,\n };\n });\n\n return {\n event: \"begin_checkout\",\n currency,\n // toFixed(2) rounds ties wrong (1.005 → \"1.00\"); roundHalfAway gives 1.01.\n value: roundHalfAway(total, 2),\n items,\n };\n}\n\n/**\n * Push ecommerce tracking data to window.dataLayer using the GA4 clear-then-push pattern.\n */\nexport function pushTrackingData(data: TrackingData): void {\n if (typeof window === \"undefined\" || !window.dataLayer) return;\n\n window.dataLayer.push({ ecommerce: null });\n window.dataLayer.push({\n event: data.event,\n ecommerce: {\n currency: data.currency,\n value: data.value,\n items: data.items,\n },\n });\n}\n"]}
|