@simpleapps-com/augur-server 2.4.0 → 2026.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/EXPORTS.md +30 -73
  2. package/README.md +29 -198
  3. package/dist/actions/agr-info.d.ts +44 -0
  4. package/dist/actions/agr-info.d.ts.map +1 -0
  5. package/dist/actions/agr-site.d.ts +38 -0
  6. package/dist/actions/agr-site.d.ts.map +1 -0
  7. package/dist/actions/agr-work.d.ts +29 -0
  8. package/dist/actions/agr-work.d.ts.map +1 -0
  9. package/dist/actions/avalara.d.ts +38 -0
  10. package/dist/actions/avalara.d.ts.map +1 -0
  11. package/dist/actions/basecamp2.d.ts +48 -0
  12. package/dist/actions/basecamp2.d.ts.map +1 -0
  13. package/dist/actions/brand-folder.d.ts +39 -0
  14. package/dist/actions/brand-folder.d.ts.map +1 -0
  15. package/dist/actions/commerce.d.ts +58 -0
  16. package/dist/actions/commerce.d.ts.map +1 -0
  17. package/dist/actions/customers.d.ts +45 -0
  18. package/dist/actions/customers.d.ts.map +1 -0
  19. package/dist/actions/favorites.d.ts +21 -0
  20. package/dist/actions/favorites.d.ts.map +1 -0
  21. package/dist/actions/gregorovich.d.ts +35 -0
  22. package/dist/actions/gregorovich.d.ts.map +1 -0
  23. package/dist/actions/items.d.ts +81 -0
  24. package/dist/actions/items.d.ts.map +1 -0
  25. package/dist/actions/joomla.d.ts +60 -0
  26. package/dist/actions/joomla.d.ts.map +1 -0
  27. package/dist/actions/legacy.d.ts +46 -0
  28. package/dist/actions/legacy.d.ts.map +1 -0
  29. package/dist/actions/logistics.d.ts +41 -0
  30. package/dist/actions/logistics.d.ts.map +1 -0
  31. package/dist/actions/orders.d.ts +37 -0
  32. package/dist/actions/orders.d.ts.map +1 -0
  33. package/dist/actions/p21-apis.d.ts +34 -0
  34. package/dist/actions/p21-apis.d.ts.map +1 -0
  35. package/dist/actions/p21-core.d.ts +47 -0
  36. package/dist/actions/p21-core.d.ts.map +1 -0
  37. package/dist/actions/p21-pim.d.ts +37 -0
  38. package/dist/actions/p21-pim.d.ts.map +1 -0
  39. package/dist/actions/p21-sism.d.ts +38 -0
  40. package/dist/actions/p21-sism.d.ts.map +1 -0
  41. package/dist/actions/payments.d.ts +39 -0
  42. package/dist/actions/payments.d.ts.map +1 -0
  43. package/dist/actions/pricing.d.ts +46 -0
  44. package/dist/actions/pricing.d.ts.map +1 -0
  45. package/dist/actions/search.d.ts +62 -0
  46. package/dist/actions/search.d.ts.map +1 -0
  47. package/dist/actions/shipping.d.ts +57 -0
  48. package/dist/actions/shipping.d.ts.map +1 -0
  49. package/dist/actions/site.d.ts +142 -0
  50. package/dist/actions/site.d.ts.map +1 -0
  51. package/dist/actions/smarty-streets.d.ts +45 -0
  52. package/dist/actions/smarty-streets.d.ts.map +1 -0
  53. package/dist/actions/vmi.d.ts +45 -0
  54. package/dist/actions/vmi.d.ts.map +1 -0
  55. package/dist/actions/wishlists.d.ts +29 -0
  56. package/dist/actions/wishlists.d.ts.map +1 -0
  57. package/dist/api-handler.d.ts +25 -0
  58. package/dist/api-handler.d.ts.map +1 -0
  59. package/dist/api.d.ts +2 -26
  60. package/dist/api.d.ts.map +1 -0
  61. package/dist/api.js +19 -14
  62. package/dist/api.js.map +1 -1
  63. package/dist/auth.d.ts +10 -12
  64. package/dist/auth.d.ts.map +1 -0
  65. package/dist/auth.js +2 -2
  66. package/dist/cache/redis-client.d.ts +18 -0
  67. package/dist/cache/redis-client.d.ts.map +1 -0
  68. package/dist/cache/with-cache.d.ts +17 -0
  69. package/dist/cache/with-cache.d.ts.map +1 -0
  70. package/dist/{chunk-PIYHMA6F.js → chunk-6CSVIBHQ.js} +15 -18
  71. package/dist/chunk-6CSVIBHQ.js.map +1 -0
  72. package/dist/{chunk-ALTIINP6.js → chunk-A4IVBK6P.js} +30 -6
  73. package/dist/chunk-A4IVBK6P.js.map +1 -0
  74. package/dist/{chunk-KHFEDL47.js → chunk-INVDQQ7T.js} +18 -12
  75. package/dist/chunk-INVDQQ7T.js.map +1 -0
  76. package/dist/{chunk-26WZBC4F.js → chunk-LX7SJJOU.js} +275 -667
  77. package/dist/chunk-LX7SJJOU.js.map +1 -0
  78. package/dist/chunk-OBWQSGB6.js +205 -0
  79. package/dist/chunk-OBWQSGB6.js.map +1 -0
  80. package/dist/{chunk-2NL4QKJN.js → chunk-UVGG74FO.js} +31 -30
  81. package/dist/chunk-UVGG74FO.js.map +1 -0
  82. package/dist/duration.d.ts +16 -0
  83. package/dist/duration.d.ts.map +1 -0
  84. package/dist/environment.d.ts +10 -0
  85. package/dist/environment.d.ts.map +1 -0
  86. package/dist/hooks.d.ts +8 -10
  87. package/dist/hooks.d.ts.map +1 -0
  88. package/dist/hooks.js +3 -3
  89. package/dist/hooks.js.map +1 -1
  90. package/dist/index.d.ts +16 -125
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +9 -7
  93. package/dist/index.js.map +1 -1
  94. package/dist/pagination.d.ts +32 -0
  95. package/dist/pagination.d.ts.map +1 -0
  96. package/dist/query-action.d.ts +15 -117
  97. package/dist/query-action.d.ts.map +1 -0
  98. package/dist/query-action.js +3 -3
  99. package/dist/query-options-helper.d.ts +34 -0
  100. package/dist/query-options-helper.d.ts.map +1 -0
  101. package/dist/query.js +1 -2
  102. package/dist/recaptcha.d.ts +6 -0
  103. package/dist/recaptcha.d.ts.map +1 -0
  104. package/dist/rules.d.ts +230 -0
  105. package/dist/rules.d.ts.map +1 -0
  106. package/dist/scoped-client-key.d.ts +9 -0
  107. package/dist/scoped-client-key.d.ts.map +1 -0
  108. package/dist/sdk-call.d.ts +66 -0
  109. package/dist/sdk-call.d.ts.map +1 -0
  110. package/dist/sdk-client-store.d.ts +250 -0
  111. package/dist/sdk-client-store.d.ts.map +1 -0
  112. package/dist/server-actions.d.ts +2 -0
  113. package/dist/server-actions.d.ts.map +1 -0
  114. package/dist/server-query-client.d.ts +19 -0
  115. package/dist/server-query-client.d.ts.map +1 -0
  116. package/dist/{server-site-registry-CdBfczOj.d.ts → server-site-registry.d.ts} +7 -9
  117. package/dist/server-site-registry.d.ts.map +1 -0
  118. package/dist/{site.d.ts → server-site.d.ts} +11 -16
  119. package/dist/server-site.d.ts.map +1 -0
  120. package/dist/site-actions-store.d.ts +27 -0
  121. package/dist/site-actions-store.d.ts.map +1 -0
  122. package/dist/site.js +15 -14
  123. package/dist/site.js.map +1 -1
  124. package/dist/testing.d.ts +9 -12
  125. package/dist/testing.d.ts.map +1 -0
  126. package/dist/testing.js +7 -27
  127. package/dist/testing.js.map +1 -1
  128. package/dist/utils/batch-fetch.d.ts +7 -0
  129. package/dist/utils/batch-fetch.d.ts.map +1 -0
  130. package/llms.txt +72 -51
  131. package/package.json +30 -20
  132. package/dist/actions.d.ts +0 -2
  133. package/dist/chunk-26WZBC4F.js.map +0 -1
  134. package/dist/chunk-2NL4QKJN.js.map +0 -1
  135. package/dist/chunk-ALTIINP6.js.map +0 -1
  136. package/dist/chunk-DGUM43GV.js +0 -11
  137. package/dist/chunk-DGUM43GV.js.map +0 -1
  138. package/dist/chunk-KHFEDL47.js.map +0 -1
  139. package/dist/chunk-PIYHMA6F.js.map +0 -1
  140. package/dist/query.d.ts +0 -35
  141. package/dist/site-BjSFqufX.d.ts +0 -469
@@ -0,0 +1,205 @@
1
+ // ../foundation/src/duration.ts
2
+ function seconds(n) {
3
+ return n;
4
+ }
5
+ function minutes(n) {
6
+ return n * 60;
7
+ }
8
+ function hours(n) {
9
+ return n * 3600;
10
+ }
11
+ function millis(n) {
12
+ return n;
13
+ }
14
+ function toMillis(d) {
15
+ return d * 1e3;
16
+ }
17
+ function addMillis(a, b) {
18
+ return a + b;
19
+ }
20
+
21
+ // ../utils/src/strings.ts
22
+ function codeAt(s, i) {
23
+ return i >= 0 && i < s.length ? s.charCodeAt(i) : -1;
24
+ }
25
+ function indexOfCode(s, code, from) {
26
+ const c = codeAt(s, from);
27
+ if (c === code) return from;
28
+ if (c === -1) return -1;
29
+ return indexOfCode(s, code, from + 1);
30
+ }
31
+ function startsWithAt(s, x, pos) {
32
+ const at = Math.min(pos, s.length);
33
+ return s.slice(at, Math.min(at + x.length, s.length)) === x;
34
+ }
35
+
36
+ // ../utils/src/includes.ts
37
+ function includesFrom(s, x, i) {
38
+ for (let k = i; k !== s.length + 1; k++) {
39
+ if (startsWithAt(s, x, k)) return true;
40
+ }
41
+ return false;
42
+ }
43
+
44
+ // src/rules.ts
45
+ function clientIdSiteIdOf(clientId) {
46
+ const k = indexOfCode(clientId, 124, 0);
47
+ if (k < 0) return null;
48
+ if (k + 1 >= clientId.length) return null;
49
+ return clientId.slice(k + 1);
50
+ }
51
+ function mintedCredentials(siteIdOk, targetSiteId, token, bearerSiteId) {
52
+ if (!siteIdOk || token === "" || bearerSiteId === "" || bearerSiteId !== targetSiteId) {
53
+ return { kind: "refused" };
54
+ }
55
+ return { kind: "minted", siteId: targetSiteId, token };
56
+ }
57
+ function hasMoreOf(page, limit, total, itemCount) {
58
+ if (total !== void 0) return (page + 1) * limit < total;
59
+ return itemCount === limit;
60
+ }
61
+ function nextCursorOf(hasMore, page) {
62
+ if (hasMore) return page + 1;
63
+ return void 0;
64
+ }
65
+ function envOf(deploymentEnv, isServer, nodeEnv, host) {
66
+ if (deploymentEnv === "dev") return "staging";
67
+ if (deploymentEnv === "live") return "production";
68
+ if (isServer) return serverEnvOf(nodeEnv);
69
+ return hostEnvOf(host);
70
+ }
71
+ function serverEnvOf(nodeEnv) {
72
+ return nodeEnv === "development" ? "development" : "production";
73
+ }
74
+ function hostEnvOf(host) {
75
+ if (includesFrom(host, "localhost", 0) || includesFrom(host, "127.0.0.1", 0))
76
+ return "development";
77
+ if (includesFrom(host, "agr-hosting.dev", 0)) return "staging";
78
+ return "production";
79
+ }
80
+ function isCrossOrigin(fetchSite) {
81
+ return fetchSite !== "" && fetchSite !== "same-origin";
82
+ }
83
+ function bodyOutcomeOf(jsonOk, methodPathOk, argsIsArray) {
84
+ if (!jsonOk) return "bad-json";
85
+ if (!methodPathOk) return "bad-method-path";
86
+ if (!argsIsArray) return "bad-args";
87
+ return "run";
88
+ }
89
+ function apiStatusOf(o) {
90
+ if (o === "forbidden") return 403;
91
+ if (o === "run") return 200;
92
+ return 400;
93
+ }
94
+ function apiMessageOf(o) {
95
+ if (o === "forbidden") return "Forbidden: cross-origin requests not allowed";
96
+ if (o === "bad-json") return "Invalid JSON body";
97
+ if (o === "bad-method-path") return "Missing or invalid methodPath";
98
+ if (o === "bad-args") return "Missing or invalid args array";
99
+ return "";
100
+ }
101
+ function ttlFor(staleTime, redisTtl, longRedisTtl) {
102
+ if (staleTime === 0) return null;
103
+ if (staleTime >= toMillis(hours(1))) return longRedisTtl;
104
+ return redisTtl;
105
+ }
106
+ function circuitCheck(c, now) {
107
+ if (c.openUntil === 0) return { open: false, next: c };
108
+ if (now >= c.openUntil) return { open: false, next: { failures: 0, openUntil: millis(0) } };
109
+ return { open: true, next: c };
110
+ }
111
+ function opensAt(failures) {
112
+ return failures >= 5;
113
+ }
114
+ function recordFailureOf(c, now) {
115
+ const failures = c.failures + 1;
116
+ if (opensAt(failures)) return { failures, openUntil: addMillis(now, toMillis(minutes(1))) };
117
+ return { failures, openUntil: c.openUntil };
118
+ }
119
+ function recordSuccessOf(c) {
120
+ return { failures: 0, openUntil: c.openUntil };
121
+ }
122
+ function verifiedFlag(s) {
123
+ return s === "true";
124
+ }
125
+ function recaptchaOk(hasSecret, httpOk, success) {
126
+ return hasSecret && httpOk && success === true;
127
+ }
128
+ function positiveOrZero(n) {
129
+ return n > 0 ? n : 0;
130
+ }
131
+ function itemsLimitOf(limit) {
132
+ if (limit === void 0) return 24;
133
+ if (limit === 0) return 24;
134
+ return limit;
135
+ }
136
+ function resolutionOf(minted, scopedMade, hasGlobal) {
137
+ if (minted && scopedMade) return "scoped";
138
+ return hasGlobal ? "global" : "uninit";
139
+ }
140
+ function slotDecisionOf(slotKey, key, hasFactory) {
141
+ if (slotKey === key) return "hit";
142
+ return hasFactory ? "mint" : "no-client";
143
+ }
144
+ function approvePath(path, hasAllowlist, listed) {
145
+ return path !== "" && (!hasAllowlist || listed);
146
+ }
147
+ function usesCache(hasWrapper, isRead) {
148
+ return hasWrapper && isRead;
149
+ }
150
+ function scopedPrefix(siteId) {
151
+ return siteId + ":";
152
+ }
153
+ function shouldCache(ttl) {
154
+ return ttl !== 0;
155
+ }
156
+ function cacheTtlOf(missing, ttl) {
157
+ return missing ? seconds(0) : ttl;
158
+ }
159
+ function docUidOf(uid) {
160
+ if (uid > 0) return uid;
161
+ return void 0;
162
+ }
163
+ function takesItemId(uid, itemId) {
164
+ return uid === 0 && itemId !== "";
165
+ }
166
+ function hasDocKey(uidSet, itemId) {
167
+ return uidSet || itemId !== "";
168
+ }
169
+ function configuredModeOf(configured) {
170
+ if (configured === void 0) return "live";
171
+ return configured;
172
+ }
173
+
174
+ export {
175
+ clientIdSiteIdOf,
176
+ mintedCredentials,
177
+ hasMoreOf,
178
+ nextCursorOf,
179
+ envOf,
180
+ isCrossOrigin,
181
+ bodyOutcomeOf,
182
+ apiStatusOf,
183
+ apiMessageOf,
184
+ ttlFor,
185
+ circuitCheck,
186
+ opensAt,
187
+ recordFailureOf,
188
+ recordSuccessOf,
189
+ verifiedFlag,
190
+ recaptchaOk,
191
+ positiveOrZero,
192
+ itemsLimitOf,
193
+ resolutionOf,
194
+ slotDecisionOf,
195
+ approvePath,
196
+ usesCache,
197
+ scopedPrefix,
198
+ shouldCache,
199
+ cacheTtlOf,
200
+ docUidOf,
201
+ takesItemId,
202
+ hasDocKey,
203
+ configuredModeOf
204
+ };
205
+ //# sourceMappingURL=chunk-OBWQSGB6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../foundation/src/duration.ts","../../utils/src/strings.ts","../../utils/src/includes.ts","../src/rules.ts"],"sourcesContent":["//@ 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 {\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 { startsWithAt } from \"./strings\";\n\n/* Substring search from an index, verified with LemmaScript → Dafny (model: models/Utils.dfy\n IncludesFrom; link: models/links/utils-includes.dfy). Its own file (moved out of strings.ts,\n 2026-11-06) so its contract can name `startsWithAt`: lsc gives an importer a helper from\n another file with that helper's contract, never one from the same file (models/LSC-GAPS.md). */\n\n/**\n * Whether `x` occurs in `s` at some index ≥ `i` (JS `s.includes(x, i)`). `i` MUST be at most\n * |s|: past the end JS clamps it to |s| (Fable review 2026-11-06), so a start there is the end.\n *\n * A loop, so its depth doesn't grow with `s` (agr-entity-graphql runs it on a whole schema's JSON).\n *\n * @requires i ≤ |s|\n * @ensures result ⟺ ∃ k. i ≤ k ≤ |s| ∧ startsWithAt(s, x, k) — exactly the model's IncludesFrom\n */\nexport function includesFrom(s: string, x: string, i: number): boolean {\n //@ verify\n //@ type i nat\n //@ requires i >= 0 && i <= s.length\n //@ ensures \\result <==> exists(k: nat, i <= k && k <= s.length && startsWithAt(s, x, k))\n for (let k = i; k !== s.length + 1; k++) {\n //@ invariant i <= k && k <= s.length + 1\n //@ invariant forall(j: nat, (i <= j && j < k) ==> !startsWithAt(s, x, j))\n //@ decreases s.length + 1 - k\n if (startsWithAt(s, x, k)) return true;\n }\n return false;\n}\n","//@ backend dafny\nimport { addMillis, hours, millis, minutes, seconds, toMillis } from \"@atlas/foundation/duration\";\nimport { includesFrom } from \"@atlas/utils/includes\";\nimport { indexOfCode } from \"@atlas/utils/strings\";\nimport type { Millis, Seconds } from \"./duration\";\n\n/* The server's decisions, as pure functions verified with LemmaScript → Dafny (model:\n models/AugurServer.dfy; link: models/links/augur-server-rules.dfy). Cookies, JWT decoding,\n fetch, Redis and process.env stay in the callers, which hand over plain values. */\n\n/**\n * The siteId of a bearer's client_id claim (`<n>|<siteId>`): the text after the first \"|\", when\n * there is one and it is non-empty. The prefix is not checked.\n *\n * @ensures exactly the model's ClientIdSiteId on a string claim\n */\nexport function clientIdSiteIdOf(clientId: string): string | null {\n //@ verify\n //@ ensures indexOfCode(clientId, 124, 0) < 0 ==> \\result === null\n //@ ensures indexOfCode(clientId, 124, 0) >= 0 && indexOfCode(clientId, 124, 0) + 1 >= clientId.length ==> \\result === null\n //@ ensures indexOfCode(clientId, 124, 0) >= 0 && indexOfCode(clientId, 124, 0) + 1 < clientId.length ==> \\result === clientId.slice(indexOfCode(clientId, 124, 0) + 1)\n const k = indexOfCode(clientId, 124, 0);\n if (k < 0) return null;\n if (k + 1 >= clientId.length) return null;\n return clientId.slice(k + 1);\n}\n\n/** A session's siteId and bearer token, as minted, or refused. */\nexport type Mint = { kind: \"minted\"; siteId: string; token: string } | { kind: \"refused\" };\n\n/**\n * getSessionCredentials' mint, once the secret and the decoded session are in hand: a valid\n * siteId (augur-api's `isSiteId`, checked by the caller), a non-empty token, and the bearer's\n * client_id siteId (`\"\"` for none: `clientIdSiteIdOf` never gives `\"\"`) equal to it.\n *\n * @ensures exactly the model's MintCredentials with a secret and a decoded session\n */\nexport function mintedCredentials(\n siteIdOk: boolean,\n targetSiteId: string,\n token: string,\n bearerSiteId: string,\n): Mint {\n //@ verify\n //@ ensures siteIdOk && token !== \"\" && bearerSiteId !== \"\" && bearerSiteId === targetSiteId ==> \\result.kind === \"minted\" && \\result.siteId === targetSiteId && \\result.token === token\n //@ ensures !(siteIdOk && token !== \"\" && bearerSiteId !== \"\" && bearerSiteId === targetSiteId) ==> \\result.kind === \"refused\"\n if (!siteIdOk || token === \"\" || bearerSiteId === \"\" || bearerSiteId !== targetSiteId) {\n return { kind: \"refused\" };\n }\n return { kind: \"minted\", siteId: targetSiteId, token };\n}\n\n/**\n * Whether there is another page: from the total when one is given, else a full page.\n *\n * @ensures exactly the model's HasMore\n */\nexport function hasMoreOf(\n page: number,\n limit: number,\n total: number | undefined,\n itemCount: number,\n): boolean {\n //@ verify\n //@ ensures total !== undefined ==> \\result === ((page + 1) * limit < total)\n //@ ensures total === undefined ==> \\result === (itemCount === limit)\n if (total !== undefined) return (page + 1) * limit < total;\n return itemCount === limit;\n}\n\n/**\n * The next page's cursor: page + 1 while there is more.\n *\n * @ensures exactly the model's NextCursor given HasMore\n */\nexport function nextCursorOf(hasMore: boolean, page: number): number | undefined {\n //@ verify\n //@ ensures hasMore ==> \\result === page + 1\n //@ ensures !hasMore ==> \\result === undefined\n if (hasMore) return page + 1;\n return undefined;\n}\n\n/** The deployment environment. */\nexport type Env = \"development\" | \"staging\" | \"production\";\n\n/**\n * DEPLOYMENT_ENV first; then the server's NODE_ENV; then the browser's host (substring). A missing\n * variable is \"\".\n *\n * @ensures exactly the model's EnvOf\n */\nexport function envOf(\n deploymentEnv: string,\n isServer: boolean,\n nodeEnv: string,\n host: string,\n): Env {\n //@ verify\n //@ ensures deploymentEnv === \"dev\" ==> \\result === \"staging\"\n //@ ensures deploymentEnv !== \"dev\" && deploymentEnv === \"live\" ==> \\result === \"production\"\n //@ ensures deploymentEnv !== \"dev\" && deploymentEnv !== \"live\" && isServer ==> \\result === serverEnvOf(nodeEnv)\n //@ ensures deploymentEnv !== \"dev\" && deploymentEnv !== \"live\" && !isServer ==> \\result === hostEnvOf(host)\n if (deploymentEnv === \"dev\") return \"staging\";\n if (deploymentEnv === \"live\") return \"production\";\n if (isServer) return serverEnvOf(nodeEnv);\n return hostEnvOf(host);\n}\n\n/**\n * On the server: development only for NODE_ENV \"development\".\n *\n * @ensures result = development ⟺ nodeEnv = \"development\", else production\n */\nexport function serverEnvOf(nodeEnv: string): Env {\n //@ verify\n //@ ensures nodeEnv === \"development\" ==> \\result === \"development\"\n //@ ensures nodeEnv !== \"development\" ==> \\result === \"production\"\n return nodeEnv === \"development\" ? \"development\" : \"production\";\n}\n\n/**\n * In the browser: localhost or 127.0.0.1 anywhere in the host is development, agr-hosting.dev\n * staging, anything else production.\n *\n * @ensures exactly the model's host rule\n */\nexport function hostEnvOf(host: string): Env {\n //@ verify\n //@ ensures (includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0)) ==> \\result === \"development\"\n //@ ensures !(includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0)) && includesFrom(host, \"agr-hosting.dev\", 0) ==> \\result === \"staging\"\n //@ ensures !(includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0)) && !includesFrom(host, \"agr-hosting.dev\", 0) ==> \\result === \"production\"\n if (includesFrom(host, \"localhost\", 0) || includesFrom(host, \"127.0.0.1\", 0))\n return \"development\";\n if (includesFrom(host, \"agr-hosting.dev\", 0)) return \"staging\";\n return \"production\";\n}\n\n/** The API route's outcome for a request. */\nexport type ApiOutcome = \"forbidden\" | \"bad-json\" | \"bad-method-path\" | \"bad-args\" | \"run\";\n\n/**\n * A present, non-empty Sec-Fetch-Site other than same-origin is refused (a missing one, `\"\"`\n * from the caller, passes).\n *\n * @ensures result ⟺ fetchSite ∉ {\"\", \"same-origin\"}\n */\nexport function isCrossOrigin(fetchSite: string): boolean {\n //@ verify\n //@ ensures \\result === (fetchSite !== \"\" && fetchSite !== \"same-origin\")\n return fetchSite !== \"\" && fetchSite !== \"same-origin\";\n}\n\n/**\n * The body's outcome: JSON, then a non-empty methodPath string, then an args array.\n *\n * @ensures exactly the model's ApiOutcomeOf past the origin check\n */\nexport function bodyOutcomeOf(\n jsonOk: boolean,\n methodPathOk: boolean,\n argsIsArray: boolean,\n): ApiOutcome {\n //@ verify\n //@ ensures !jsonOk ==> \\result === \"bad-json\"\n //@ ensures jsonOk && !methodPathOk ==> \\result === \"bad-method-path\"\n //@ ensures jsonOk && methodPathOk && !argsIsArray ==> \\result === \"bad-args\"\n //@ ensures jsonOk && methodPathOk && argsIsArray ==> \\result === \"run\"\n if (!jsonOk) return \"bad-json\";\n if (!methodPathOk) return \"bad-method-path\";\n if (!argsIsArray) return \"bad-args\";\n return \"run\";\n}\n\n/**\n * An outcome's HTTP status: 403, 400 for a bad body, 200 to run.\n *\n * @ensures exactly the model's ApiStatus\n */\nexport function apiStatusOf(o: ApiOutcome): number {\n //@ verify\n //@ ensures o === \"forbidden\" ==> \\result === 403\n //@ ensures (o === \"bad-json\" || o === \"bad-method-path\" || o === \"bad-args\") ==> \\result === 400\n //@ ensures o === \"run\" ==> \\result === 200\n if (o === \"forbidden\") return 403;\n if (o === \"run\") return 200;\n return 400;\n}\n\n/**\n * A refusal's response text (\"\" to run).\n *\n * @ensures each refusal has its fixed text\n */\nexport function apiMessageOf(o: ApiOutcome): string {\n //@ verify\n //@ ensures o === \"forbidden\" ==> \\result === \"Forbidden: cross-origin requests not allowed\"\n //@ ensures o === \"bad-json\" ==> \\result === \"Invalid JSON body\"\n //@ ensures o === \"bad-method-path\" ==> \\result === \"Missing or invalid methodPath\"\n //@ ensures o === \"bad-args\" ==> \\result === \"Missing or invalid args array\"\n //@ ensures o === \"run\" ==> \\result === \"\"\n if (o === \"forbidden\") return \"Forbidden: cross-origin requests not allowed\";\n if (o === \"bad-json\") return \"Invalid JSON body\";\n if (o === \"bad-method-path\") return \"Missing or invalid methodPath\";\n if (o === \"bad-args\") return \"Missing or invalid args array\";\n return \"\";\n}\n\n/**\n * The Redis TTL for a cache tier: none for staleTime 0, the long TTL from an hour up, else the\n * standard one. `staleTime` is React Query's `Millis`, the TTLs Redis's `Seconds`; the hour is\n * compared in milliseconds.\n *\n * @ensures exactly the model's TtlFor\n */\nexport function ttlFor(\n staleTime: Millis,\n redisTtl: Seconds,\n longRedisTtl: Seconds,\n): Seconds | null {\n //@ verify\n //@ ensures staleTime === 0 ==> \\result === null\n //@ ensures staleTime !== 0 && staleTime >= 3600000 ==> \\result === longRedisTtl\n //@ ensures staleTime !== 0 && staleTime < 3600000 ==> \\result === redisTtl\n if (staleTime === 0) return null;\n if (staleTime >= toMillis(hours(1))) return longRedisTtl;\n return redisTtl;\n}\n\n/** The Redis circuit breaker's state: consecutive failures, and when it closes (0 = closed). */\nexport interface Circuit {\n failures: number;\n openUntil: Millis;\n}\n\n/** The circuit's answer at a time: whether it is open, and its state after the check. */\nexport interface CircuitAnswer {\n open: boolean;\n next: Circuit;\n}\n\n/**\n * isCircuitOpen at `now`: closed at openUntil 0; past it, reset and closed; else open.\n *\n * @ensures exactly the model's CircuitCheck\n */\nexport function circuitCheck(c: Circuit, now: Millis): CircuitAnswer {\n //@ verify\n //@ ensures c.openUntil === 0 ==> !\\result.open && \\result.next === c\n //@ ensures c.openUntil !== 0 && now >= c.openUntil ==> !\\result.open && \\result.next.failures === 0 && \\result.next.openUntil === 0\n //@ ensures c.openUntil !== 0 && now < c.openUntil ==> \\result.open && \\result.next === c\n if (c.openUntil === 0) return { open: false, next: c };\n if (now >= c.openUntil) return { open: false, next: { failures: 0, openUntil: millis(0) } };\n return { open: true, next: c };\n}\n\n/**\n * Whether a failure count opens the circuit: five in a row.\n *\n * @ensures result ⟺ failures ≥ 5\n */\nexport function opensAt(failures: number): boolean {\n //@ verify\n //@ ensures \\result === (failures >= 5)\n return failures >= 5;\n}\n\n/**\n * A failure counts; from the threshold on the circuit opens for a minute from now.\n *\n * @ensures exactly the model's RecordFailure\n */\nexport function recordFailureOf(c: Circuit, now: Millis): Circuit {\n //@ verify\n //@ ensures \\result.failures === c.failures + 1\n //@ ensures opensAt(c.failures + 1) ==> \\result.openUntil === now + 60000\n //@ ensures !opensAt(c.failures + 1) ==> \\result.openUntil === c.openUntil\n const failures = c.failures + 1;\n if (opensAt(failures)) return { failures, openUntil: addMillis(now, toMillis(minutes(1))) };\n return { failures, openUntil: c.openUntil };\n}\n\n/**\n * A success clears the failure count and leaves openUntil.\n *\n * @ensures exactly the model's RecordSuccess\n */\nexport function recordSuccessOf(c: Circuit): Circuit {\n //@ verify\n //@ ensures \\result.failures === 0 && \\result.openUntil === c.openUntil\n return { failures: 0, openUntil: c.openUntil };\n}\n\n/**\n * authorize's verified flag: exactly the text \"true\".\n *\n * @ensures result ⟺ s = \"true\"\n */\nexport function verifiedFlag(s: string): boolean {\n //@ verify\n //@ ensures \\result === (s === \"true\")\n return s === \"true\";\n}\n\n/**\n * reCAPTCHA passes only with a secret, an ok response and the reply's optional `success` exactly\n * true (the score is not read).\n *\n * @ensures exactly the model's RecaptchaOk, success read as `=== true`\n */\nexport function recaptchaOk(\n hasSecret: boolean,\n httpOk: boolean,\n success: boolean | undefined,\n): boolean {\n //@ verify\n //@ ensures \\result === (hasSecret && httpOk && success === true)\n return hasSecret && httpOk && success === true;\n}\n\n/**\n * A customer id is used only above 0; anything else (NaN included, at the caller) is 0.\n *\n * @ensures result = n when n > 0, else 0\n */\nexport function positiveOrZero(n: number): number {\n //@ verify\n //@ ensures n > 0 ==> \\result === n\n //@ ensures n <= 0 ==> \\result === 0\n return n > 0 ? n : 0;\n}\n\n/**\n * The category page size: 24 when none (or 0) is given.\n *\n * @ensures exactly the model's ItemsLimit, a missing limit as 0\n */\nexport function itemsLimitOf(limit: number | undefined): number {\n //@ verify\n //@ ensures (limit === undefined || limit === 0) ==> \\result === 24\n //@ ensures limit !== undefined && limit !== 0 ==> \\result === limit\n if (limit === undefined) return 24;\n if (limit === 0) return 24;\n return limit;\n}\n\n/** How queryAction resolves its client. */\nexport type Resolution = \"scoped\" | \"global\" | \"uninit\";\n\n/**\n * resolveClient: scoped when credentials minted and a scoped client was made; else the global\n * client when one is registered (also for a valid session without a factory); else none.\n *\n * @ensures exactly the model's ResolveClient\n */\nexport function resolutionOf(minted: boolean, scopedMade: boolean, hasGlobal: boolean): Resolution {\n //@ verify\n //@ ensures minted && scopedMade ==> \\result === \"scoped\"\n //@ ensures !(minted && scopedMade) && hasGlobal ==> \\result === \"global\"\n //@ ensures !(minted && scopedMade) && !hasGlobal ==> \\result === \"uninit\"\n if (minted && scopedMade) return \"scoped\";\n return hasGlobal ? \"global\" : \"uninit\";\n}\n\n/** The scoped-client slot's decision. */\nexport type SlotDecision = \"hit\" | \"mint\" | \"no-client\";\n\n/**\n * getOrCreateScopedClient's single slot: a hit when it holds this key; else a new client when a\n * factory is registered; else none. An empty slot is \"\" at the caller, which no key equals (a\n * key holds a NUL).\n *\n * @ensures exactly the model's SlotDecisionOf\n */\nexport function slotDecisionOf(slotKey: string, key: string, hasFactory: boolean): SlotDecision {\n //@ verify\n //@ ensures slotKey === key ==> \\result === \"hit\"\n //@ ensures slotKey !== key && hasFactory ==> \\result === \"mint\"\n //@ ensures slotKey !== key && !hasFactory ==> \\result === \"no-client\"\n if (slotKey === key) return \"hit\";\n return hasFactory ? \"mint\" : \"no-client\";\n}\n\n/**\n * parseMethodPath: a non-empty path, in the allowlist when one is registered (permissive by\n * default); `listed` is the caller's Set lookup.\n *\n * @ensures exactly the model's ApprovePath\n */\nexport function approvePath(path: string, hasAllowlist: boolean, listed: boolean): boolean {\n //@ verify\n //@ ensures \\result === (path !== \"\" && (!hasAllowlist || listed))\n return path !== \"\" && (!hasAllowlist || listed);\n}\n\n/**\n * queryAction caches a call only through a wrapper, and only for a read leaf (augur-core's\n * `isReadMethod`, checked by the caller).\n *\n * @ensures exactly the model's UsesCache\n */\nexport function usesCache(hasWrapper: boolean, isRead: boolean): boolean {\n //@ verify\n //@ ensures \\result === (hasWrapper && isRead)\n return hasWrapper && isRead;\n}\n\n/**\n * The scoped cache prefix: the session's siteId and \":\".\n *\n * @ensures exactly the model's ScopedPrefix\n */\nexport function scopedPrefix(siteId: string): string {\n //@ verify\n //@ ensures \\result === siteId + \":\"\n return siteId + \":\";\n}\n\n/**\n * withServerCache caches when the TTL is not 0 (missing or NaN is 0 at the caller; a `Seconds`\n * is never negative).\n *\n * @ensures exactly the model's ShouldCache\n */\nexport function shouldCache(ttl: Seconds): boolean {\n //@ verify\n //@ ensures \\result === (ttl !== 0)\n return ttl !== 0;\n}\n\n/**\n * The TTL a server cache call uses: a missing one (undefined or NaN, which the caller reads) is 0,\n * as `!redisTtl` had it.\n *\n * @ensures exactly the model's CacheTtl\n */\nexport function cacheTtlOf(missing: boolean, ttl: Seconds): Seconds {\n //@ verify\n //@ ensures \\result === (missing ? 0 : ttl)\n return missing ? seconds(0) : ttl;\n}\n\n/**\n * getInvMastDoc's positional uid: kept above 0, else none.\n *\n * @ensures result = uid when uid > 0, else undefined\n */\nexport function docUidOf(uid: number): number | undefined {\n //@ verify\n //@ ensures uid > 0 ==> \\result === uid\n //@ ensures uid <= 0 ==> \\result === undefined\n if (uid > 0) return uid;\n return undefined;\n}\n\n/**\n * The positional itemId is used only at uid 0 and when non-empty (\"\" for none, at the caller).\n *\n * @ensures result ⟺ uid = 0 ∧ itemId ≠ \"\"\n */\nexport function takesItemId(uid: number, itemId: string): boolean {\n //@ verify\n //@ ensures \\result === (uid === 0 && itemId !== \"\")\n return uid === 0 && itemId !== \"\";\n}\n\n/**\n * A doc call needs a uid (truthy at the caller) or a non-empty itemId.\n *\n * @ensures result ⟺ uidSet ∨ itemId ≠ \"\"\n */\nexport function hasDocKey(uidSet: boolean, itemId: string): boolean {\n //@ verify\n //@ ensures \\result === (uidSet || itemId !== \"\")\n return uidSet || itemId !== \"\";\n}\n\n/**\n * The configured payments mode, \"live\" by default.\n *\n * @ensures result = configured ?? \"live\"\n */\nexport function configuredModeOf(configured: string | undefined): string {\n //@ verify\n //@ ensures configured === undefined ==> \\result === \"live\"\n //@ ensures configured !== undefined ==> \\result === configured\n if (configured === undefined) return \"live\";\n return configured;\n}\n"],"mappings":"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","names":[]}
@@ -5,10 +5,22 @@ import {
5
5
  getSdkCallWrapper,
6
6
  getSdkClientOrNull,
7
7
  parseMethodPath
8
- } from "./chunk-ALTIINP6.js";
8
+ } from "./chunk-A4IVBK6P.js";
9
+ import {
10
+ clientIdSiteIdOf,
11
+ mintedCredentials,
12
+ resolutionOf,
13
+ scopedPrefix,
14
+ usesCache
15
+ } from "./chunk-OBWQSGB6.js";
9
16
 
10
17
  // src/query-action.ts
11
- import { isReadMethod, stripEdgeCacheForNoCachePaths } from "@simpleapps-com/augur-core";
18
+ import {
19
+ isReadMethod,
20
+ stripEdgeCacheForNoCachePaths,
21
+ unwrapBaseResponse
22
+ } from "@simpleapps-com/augur-core";
23
+ import { isSiteId } from "@simpleapps-com/augur-api";
12
24
  var SECURE_COOKIE = "__Secure-authjs.session-token";
13
25
  var PLAIN_COOKIE = "authjs.session-token";
14
26
  var _decode;
@@ -55,10 +67,7 @@ function parseBearerClientSiteId(bearer) {
55
67
  const payload = _decodeJwt(bearer);
56
68
  const clientId = payload["client_id"];
57
69
  if (typeof clientId !== "string") return null;
58
- const pipeIndex = clientId.indexOf("|");
59
- if (pipeIndex < 0) return null;
60
- const siteId = clientId.slice(pipeIndex + 1);
61
- return siteId.length > 0 ? siteId : null;
70
+ return clientIdSiteIdOf(clientId);
62
71
  } catch {
63
72
  return null;
64
73
  }
@@ -72,34 +81,26 @@ async function getSessionCredentials() {
72
81
  if (!decoded) return null;
73
82
  const targetSiteId = decoded["targetSiteId"];
74
83
  const token = decoded["token"];
75
- if (typeof targetSiteId !== "string" || targetSiteId.length === 0) return null;
76
- if (typeof token !== "string" || token.length === 0) return null;
77
- const bearerSiteId = parseBearerClientSiteId(token);
78
- if (bearerSiteId !== targetSiteId) return null;
79
- return { siteId: targetSiteId, token };
84
+ if (typeof targetSiteId !== "string" || typeof token !== "string") return null;
85
+ const bearerSiteId = parseBearerClientSiteId(token) ?? "";
86
+ const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);
87
+ if (mint.kind === "refused") return null;
88
+ return { siteId: mint.siteId, token: mint.token };
80
89
  } catch {
81
90
  }
82
91
  return null;
83
92
  }
84
93
  async function resolveClient() {
85
94
  const creds = await getSessionCredentials();
86
- if (creds) {
87
- const scoped = getOrCreateScopedClient(creds);
88
- if (scoped !== null && typeof scoped === "object") {
89
- return { kind: "scoped", client: scoped, credentials: creds };
90
- }
91
- }
95
+ const scoped = creds ? getOrCreateScopedClient(creds) : null;
92
96
  const globalClient = getSdkClientOrNull();
93
- if (globalClient !== null && typeof globalClient === "object") {
94
- return { kind: "global", client: globalClient };
95
- }
96
- return { kind: "uninit" };
97
+ const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));
98
+ if (kind === "scoped") return { kind, client: scoped, credentials: creds };
99
+ if (kind === "global") return { kind, client: globalClient };
100
+ return { kind };
97
101
  }
98
- function unwrapBaseResponse(raw) {
99
- if (raw != null && typeof raw === "object" && "data" in raw && "status" in raw && "message" in raw) {
100
- return raw.data;
101
- }
102
- return raw;
102
+ function isObject(value) {
103
+ return value !== null && typeof value === "object";
103
104
  }
104
105
  function resolveMethod(client, methodPath) {
105
106
  const segments = methodPath.split(".");
@@ -137,8 +138,8 @@ async function queryAction(methodPath, ...args) {
137
138
  const resolvedMethod = resolveMethod(resolution.client, approvedPath);
138
139
  const leafName = approvedPath.split(".").pop();
139
140
  const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);
140
- const wrapper = resolution.kind === "scoped" ? bindScopedPrefix(getScopedCacheWrapper(), `${resolution.credentials.siteId}:`) : getSdkCallWrapper();
141
- if (wrapper && isReadMethod(leafName)) {
141
+ const wrapper = resolution.kind === "scoped" ? bindScopedPrefix(getScopedCacheWrapper(), scopedPrefix(resolution.credentials.siteId)) : getSdkCallWrapper();
142
+ if (usesCache(wrapper !== null, isReadMethod(leafName))) {
142
143
  const result2 = await wrapper(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);
143
144
  return unwrapBaseResponse(result2);
144
145
  }
@@ -152,10 +153,10 @@ function resetSessionImports() {
152
153
  }
153
154
 
154
155
  export {
155
- getSessionCredentials,
156
156
  unwrapBaseResponse,
157
+ getSessionCredentials,
157
158
  resolveMethod,
158
159
  queryAction,
159
160
  resetSessionImports
160
161
  };
161
- //# sourceMappingURL=chunk-2NL4QKJN.js.map
162
+ //# sourceMappingURL=chunk-UVGG74FO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query-action.ts"],"sourcesContent":["// \"use server\" banner is injected by tsup at build time.\n// Isolated server action for the proxy pattern.\n// This file MUST NOT import from server-actions.ts, server-site-registry.ts,\n// cache/, or any factory. It imports only from lightweight stores with zero\n// deps, the proved pure `rules` (with @atlas/utils' string scans, bundled), plus augur-core\n// and augur-api's `isSiteId` (both external in tsup — not bundled into chunks; every site\n// already loads the SDK on the server).\n// Dynamic imports of next/headers and next-auth/jwt are used for session\n// credential resolution (both are external in tsup).\n\nimport {\n getSdkClientOrNull,\n getSdkCallWrapper,\n getAuthSecret,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport {\n isReadMethod,\n stripEdgeCacheForNoCachePaths,\n unwrapBaseResponse,\n} from \"@simpleapps-com/augur-core\";\nimport { isSiteId } from \"@simpleapps-com/augur-api\";\nimport {\n clientIdSiteIdOf,\n mintedCredentials,\n resolutionOf,\n scopedPrefix,\n usesCache,\n} from \"./rules\";\n\n/** Auth.js v5 session cookie names (HTTPS secure prefix + HTTP fallback). */\nconst SECURE_COOKIE = \"__Secure-authjs.session-token\";\nconst PLAIN_COOKIE = \"authjs.session-token\";\n\n/** Simplified function types for lazy-loaded external deps. */\ntype DecodeFn = (params: {\n token?: string;\n secret: string | string[];\n salt: string;\n}) => Promise<Record<string, unknown> | null>;\ntype CookiesFn = () => Promise<{ get: (name: string) => { value: string } | undefined }>;\ntype DecodeJwtFn = (token: string) => Record<string, unknown>;\n\n/** Cached dynamic imports for next-auth/jwt decode, next/headers cookies, and jose decodeJwt. */\nlet _decode: DecodeFn | null | undefined;\nlet _cookies: CookiesFn | null | undefined;\nlet _decodeJwt: DecodeJwtFn | null | undefined;\n\n/** Lazy-load decode, cookies, and decodeJwt functions from external deps. Cached after first call. */\nasync function ensureImports(): Promise<boolean> {\n if (_decode === undefined) {\n try {\n const mod = await import(\"next-auth/jwt\");\n _decode = mod.decode as unknown as DecodeFn;\n } catch {\n // next-auth is an optional peer: without it there are no session credentials\n _decode = null;\n }\n }\n if (_cookies === undefined) {\n try {\n const mod = await import(\"next/headers\");\n _cookies = mod.cookies as unknown as CookiesFn;\n } catch {\n // outside Next.js there is no request cookie store\n _cookies = null;\n }\n }\n if (_decodeJwt === undefined) {\n try {\n const mod = await import(\"jose\");\n _decodeJwt = mod.decodeJwt as unknown as DecodeJwtFn;\n } catch {\n // jose is an optional peer: without it the bearer cannot be cross-checked\n _decodeJwt = null;\n }\n }\n return !!_decode && !!_cookies && !!_decodeJwt;\n}\n\n/** Read and decode the Auth.js session JWT from request cookies. */\nasync function decodeSessionJwt(secret: string): Promise<Record<string, unknown> | null> {\n const cookieStore = await _cookies!();\n const secureCookie = cookieStore.get(SECURE_COOKIE);\n const plainCookie = secureCookie ? undefined : cookieStore.get(PLAIN_COOKIE);\n const cookie = secureCookie ?? plainCookie;\n if (!cookie?.value) return null;\n\n const salt = secureCookie ? SECURE_COOKIE : PLAIN_COOKIE;\n return _decode!({ token: cookie.value, secret, salt });\n}\n\n/**\n * Extract the siteId portion of an Augur bearer token's `client_id` claim.\n * Bearer tokens are JWTs whose payload contains `client_id: \"<numeric>|<siteId>\"`.\n * Returns null on any parse failure or unexpected shape.\n *\n * Uses jose.decodeJwt (no signature verification) — we trust the bearer\n * because the *outer* Auth.js cookie's signature was just verified upstream,\n * so the bearer's contents are trusted as session-issued. This check guards\n * against internal inconsistency between the session's `targetSiteId` and the\n * bearer's scope, not against a forged bearer (the auth provider's signature\n * does that).\n */\nfunction parseBearerClientSiteId(bearer: string): string | null {\n try {\n const payload = _decodeJwt!(bearer);\n const clientId = payload[\"client_id\"];\n if (typeof clientId !== \"string\") return null;\n return clientIdSiteIdOf(clientId);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve session credentials from the Auth.js JWT cookie.\n *\n * Trust-boundary mint point: this is the only function in the package that\n * produces {@link SessionCredentials} values. Bytes from a cookie become\n * typed, paired credentials here and only here. No other production code\n * constructs the branded pair, so a `SessionCredentials` that came through\n * this mint is JWT-validated and internally consistent. The brand is not\n * enforced by the compiler: an `as SessionCredentials` cast compiles (tests\n * do it), so audit casts (see \"Brand strength\" below).\n *\n * Returns null when:\n * - no AUTH_SECRET is configured\n * - next-auth/jwt, next/headers, or jose cannot be loaded\n * - no session cookie is present\n * - the JWT decode fails or returns null\n * - the decoded payload is missing `targetSiteId` or `token`, or either is\n * not a non-empty string (refuse to mint partial credentials)\n * - `targetSiteId` fails augur-api's `isSiteId` (`[a-z0-9_-]+`): siteIds are\n * lowercase by convention, and the scoped-client key's injectivity proof\n * (`scoped-client-key.ts`) needs a NUL-free siteId\n * - the bearer token's `client_id` siteId portion does not match\n * `targetSiteId` (defense-in-depth: refuses internally inconsistent sessions\n * before they reach the augur-api authority check)\n *\n * ## Verified preconditions for `result = some c`\n *\n * AUTH_SECRET configured\n * next-auth/jwt, next/headers, jose all loadable\n * session cookie present and decodable with the secret\n * typeof jwt.targetSiteId === \"string\" ∧ isSiteId(jwt.targetSiteId) // implies non-empty\n * typeof jwt.token === \"string\" ∧ jwt.token.length > 0\n * bearerClientSiteId(jwt.token) = some jwt.targetSiteId\n *\n * Lean equivalent: each clause becomes a `requires` on the function;\n * `result = none` is the disjunction of any failing.\n * F* equivalent: refinement on the option payload covering the\n * conjunction of these clauses.\n *\n * The bearer cross-check (`bearerClientSiteId(jwt.token) = some jwt.targetSiteId`)\n * is the substantive runtime invariant: it refuses sessions where the bearer's\n * encoded `client_id` siteId disagrees with the session's targetSiteId,\n * catching internal-inconsistency bugs before the call reaches augur-api.\n *\n * ## By construction (not independently verified)\n *\n * c.siteId === jwt.targetSiteId (assigned, not checked)\n * c.token === jwt.token (assigned, not checked)\n *\n * ## Brand strength\n *\n * `SessionCredentials` is a TS-level brand: there is no runtime tag on the\n * value. `value as SessionCredentials` casts compile, so the brand is a\n * code-review signal (audit `as SessionCredentials` usages — there should be\n * exactly one, in this function), not a hard type-system gate.\n */\nasync function getSessionCredentials(): Promise<SessionCredentials | null> {\n const secret = getAuthSecret();\n if (!secret) return null;\n if (!(await ensureImports())) return null;\n\n try {\n const decoded = await decodeSessionJwt(secret);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || typeof token !== \"string\") return null;\n\n // An empty or undecodable token has no client_id siteId (\"\").\n const bearerSiteId = parseBearerClientSiteId(token) ?? \"\";\n const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);\n if (mint.kind === \"refused\") return null;\n\n return { siteId: mint.siteId, token: mint.token } as unknown as SessionCredentials;\n } catch {\n // Not in a request context (build time, tests), or decode failed\n }\n\n return null;\n}\n\n/**\n * Discriminated result of client resolution.\n *\n * Encodes two structural invariants at the type level:\n *\n * 1. session credentials exist iff this is the scoped path\n * (only `kind: \"scoped\"` carries `credentials`)\n * 2. a usable client exists iff this is NOT the uninit path\n * (`kind: \"scoped\" | \"global\"` always carry `client: object`)\n *\n * The `client: object` constraint replaces the previous `client: unknown` +\n * runtime null check. Anything narrowed to `kind: \"scoped\"` or `kind: \"global\"`\n * is guaranteed by the type system to have a non-null, traversable client —\n * downstream code that walks the SDK namespace path cannot accidentally\n * dereference null. The runtime check moves into `resolveClient` itself, where\n * `kind: \"uninit\"` is constructed when neither a scoped nor a global client is\n * available.\n *\n * Downstream code that wants to derive a cache prefix can only do so on the\n * scoped variant, and only from the credentials carried by that variant —\n * there is no way to construct a cache prefix from a different source without\n * crossing into the type.\n */\ntype ClientResolution =\n | { kind: \"scoped\"; client: object; credentials: SessionCredentials }\n | { kind: \"global\"; client: object }\n | { kind: \"uninit\" };\n\n/**\n * Resolve the SDK client for this request.\n *\n * - If the session JWT validates and a scoped client can be minted, returns\n * the scoped variant carrying the {@link SessionCredentials} that produced\n * the client. The cache prefix is derived at the use site from\n * `credentials.siteId`, structurally guaranteeing it matches the credentials\n * under which the SDK call is made.\n * - Otherwise returns the global variant. No credentials, no cache prefix.\n *\n * The previous return shape `{ client, cachePrefix: string | null }` made\n * \"cachePrefix exists iff scoped\" a runtime invariant; the tagged union\n * promotes it to a type-level one.\n */\nasync function resolveClient(): Promise<ClientResolution> {\n const creds = await getSessionCredentials();\n const scoped = creds ? getOrCreateScopedClient(creds) : null;\n const globalClient = getSdkClientOrNull();\n const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));\n if (kind === \"scoped\") return { kind, client: scoped as object, credentials: creds! };\n if (kind === \"global\") return { kind, client: globalClient as object };\n return { kind };\n}\n\n/** A usable client: a non-null object. */\nfunction isObject(value: unknown): boolean {\n return value !== null && typeof value === \"object\";\n}\n\n/**\n * Resolve a dot-separated method path on an object, returning the leaf function.\n *\n * Demands {@link ApprovedMethodPath} so callers must have run the path through\n * `parseMethodPath` first — passing an unvalidated string is a compile error.\n */\nfunction resolveMethod(\n client: unknown,\n methodPath: ApprovedMethodPath,\n): (...a: unknown[]) => Promise<unknown> {\n const segments = methodPath.split(\".\");\n\n let current: unknown = client;\n for (const segment of segments) {\n if (current == null || (typeof current !== \"object\" && typeof current !== \"function\")) {\n throw new Error(\n `Cannot resolve \"${methodPath}\": \"${segment}\" is not accessible on ${typeof current}`,\n );\n }\n current = (current as Record<string, unknown>)[segment];\n }\n\n if (typeof current !== \"function\") {\n throw new Error(`\"${methodPath}\" does not resolve to a function (got ${typeof current})`);\n }\n\n return current as (...a: unknown[]) => Promise<unknown>;\n}\n\n/**\n * Bind a scoped cache wrapper to a fixed prefix, producing an `SdkCallWrapper`\n * with the same signature as the global wrapper.\n *\n * On the scoped queryAction path, the cache prefix is derived structurally\n * from the `SessionCredentials` that minted the client (`${credentials.siteId}:`).\n * Capturing that prefix in a closure here lets queryAction's call site treat\n * scoped and global wrappers uniformly — the only thing that differs between\n * them is which prefix gets baked in, and that decision happens in exactly one\n * place per request.\n *\n * Returns null when no scoped wrapper is registered, so the caller falls\n * through to the unwrapped SDK call. The closure preserves the cross-tenant\n * invariant: prefix is captured at bind time from the same credentials value\n * used to mint the scoped client, and cannot be replaced or re-sourced later.\n *\n * ## Property\n *\n * bindScopedPrefix(null, _) = null\n * bindScopedPrefix(w, p)(methodPath, fn, ...args) = w(p, methodPath, fn, ...args)\n *\n * The bound wrapper forwards faithfully — it adds nothing, drops nothing,\n * and reorders nothing. Every effect (cache read, cache write, SDK call)\n * happens inside the underlying scopedWrapper exactly as if queryAction had\n * called it directly with the prefix as the first argument.\n */\nfunction bindScopedPrefix(\n scopedWrapper: ScopedCacheWrapper | null,\n prefix: string,\n): SdkCallWrapper | null {\n if (!scopedWrapper) return null;\n return (methodPath, sdkCall, ...keyArgs) =>\n scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);\n}\n\n/**\n * Generic server action that routes any SDK method call through the raw\n * SDK client with optional Redis caching. Used internally by\n * `createServerQueryProxy()` to bridge client-side React Query hooks\n * to server-side API calls.\n *\n * For read methods (get, list, lookup, search, suggest), the call is\n * wrapped in the registered cache wrapper (Redis) if one was registered\n * by createServerSite(). Write methods bypass caching.\n *\n * When the request has an active session with targetSiteId + token\n * (from cross-site auth), the call uses a scoped SDK client with those\n * credentials. Redis caching uses targetSiteId as the cache prefix so\n * users managing the same site share cached data.\n *\n * SDK responses wrapped in BaseResponse are automatically unwrapped --\n * consumers receive `T` instead of `{ data: T, status, message }`.\n *\n * This is the chokepoint: every B2B site without a client-side SDK\n * routes EVERY data access through this one function. The invariants\n * below are load-bearing across every site, every request, every user.\n *\n * ## Preconditions (enforced at runtime via thrown Error)\n *\n * parseMethodPath(methodPath) ≠ null\n * resolveClient().client ≠ null\n *\n * First clause: methodPath is a non-empty string AND — if an allowlist\n * has been registered via `registerAllowedMethodPaths` — methodPath is\n * in the allowlist. Assumes the site opted into surface restriction\n * when narrower-than-augur-api authority is desired; otherwise any\n * non-empty string passes (transparent forwarder default).\n *\n * Second clause: createServerSite() ran during bootstrap OR\n * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can\n * auto-init. Assumes the caller has bootstrapped one of the two paths.\n *\n * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.\n *\n * ## Cross-tenant cache-prefix invariant (load-bearing)\n *\n * resolution.kind = \"scoped\" ⟹ cachePrefix = `${resolution.credentials.siteId}:`\n *\n * On the scoped path the cache prefix is derived structurally from the\n * same `SessionCredentials` value that minted the scoped client — they\n * cannot be sourced separately. This makes \"siteId from session A\n * combined with token from session B\" or \"siteId X with cache prefix Y\"\n * unrepresentable here. Assumes `getSessionCredentials` performed the\n * bearer/session siteId cross-check at mint time; see the brand-strength\n * caveat on `SessionCredentials`.\n *\n * A regression here would silently leak cached data across tenants.\n * The structural derivation is the only thing standing between the\n * request and that leak — do not reintroduce a separate `cachePrefix`\n * parameter or compute it from anything other than `resolution.credentials`.\n *\n * ### Sibling assumption — bearer is NOT in the cache key\n *\n * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover\n * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`\n * and the bearer token is intentionally absent. Two users with different\n * bearers on the same site share cached data for cacheable namespaces.\n *\n * This is a deliberate design choice. The assumption is:\n *\n * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.\n * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)\n *\n * i.e. for cacheable namespaces, augur-api's response is bearer-independent\n * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`\n * (commerce.*, payments.*) is the carve-out for namespaces whose responses\n * ARE bearer-coupled. If a future namespace produces bearer-dependent\n * responses (e.g. user-specific permissions affecting query results), it\n * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the\n * cache key — otherwise this assumption silently produces a permission leak.\n *\n * ## No-edge-cache defense-in-depth (load-bearing)\n *\n * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ \"edgeCache\" ∉ keys(a)\n *\n * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every\n * first-level object arg when methodPath belongs to a no-cache namespace\n * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms\n * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing\n * it here guarantees no CDN edge-caching of identity-bound responses\n * even if a caller passed one explicitly or a legacy factory injected\n * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose\n * responses must not cross identity boundaries.\n *\n * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)\n *\n * result = unwrapBaseResponse(raw)\n * = raw.data when raw is { data, status, message }\n * = raw otherwise\n *\n * Consumers receive `T` directly when the SDK returns\n * `{ data: T, status, message }`, and the original value otherwise.\n * Assumes upstream cache wrappers do NOT themselves unwrap — they\n * return whatever the SDK returned, so unwrapping happens exactly\n * once, here. Double-unwrap (caller + queryAction) would silently\n * strip a layer of legitimate `{data, status, message}` user data\n * when that shape happens to round-trip through the API.\n *\n * ## Effects\n *\n * @mutates Redis (write-through on read methods when a wrapper is registered)\n * @io augur-api SDK (network request)\n * @throws Error when the allowlist gate fails or no client is initialised\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"items.invMast.doc.get\")\n * @param args Arguments to pass to the resolved method\n * @returns The unwrapped result from the SDK method (possibly from Redis cache)\n */\nexport async function queryAction(methodPath: string, ...args: unknown[]): Promise<unknown> {\n const approvedPath = parseMethodPath(methodPath);\n if (approvedPath === null) {\n throw new Error(\n `queryAction: methodPath ${JSON.stringify(methodPath)} is not in the registered allowlist. ` +\n `Register it via registerAllowedMethodPaths() in createServerSite() config.`,\n );\n }\n\n const resolution = await resolveClient();\n if (resolution.kind === \"uninit\") {\n throw new Error(\n \"SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars.\",\n );\n }\n\n const resolvedMethod = resolveMethod(resolution.client, approvedPath);\n const leafName = approvedPath.split(\".\").pop()!;\n // Defense in depth: strip `edgeCache` from no-cache paths before the SDK\n // sees it. The augur-api SDK transforms `edgeCache` into a Cloudflare\n // `cacheSiteId{N}` query param; removing it here guarantees no CDN edge\n // caching of identity-bound responses even if a caller explicitly passed\n // one. Also keeps cache keys consistent with what is actually sent.\n const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);\n\n // Pick the wrapper for this resolution's prefix policy. On the scoped path,\n // the prefix is structurally derived from `credentials.siteId` and bound into\n // a closure here — bindScopedPrefix is the only call site that builds it,\n // and the prefix cannot be re-sourced after binding. On the global path, the\n // prefix is closed over by the SdkCallWrapper that createServerSite registered.\n // Both paths now produce a uniform `SdkCallWrapper | null`, so the caching\n // and uncached branches collapse into a single shape below.\n const wrapper: SdkCallWrapper | null =\n resolution.kind === \"scoped\"\n ? bindScopedPrefix(getScopedCacheWrapper(), scopedPrefix(resolution.credentials.siteId))\n : getSdkCallWrapper();\n\n if (usesCache(wrapper !== null, isReadMethod(leafName))) {\n const result = await wrapper!(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);\n return unwrapBaseResponse(result);\n }\n\n const result = await resolvedMethod(...safeArgs);\n return unwrapBaseResponse(result);\n}\n\n/** Reset lazy-loaded imports. Used in tests only. @internal */\nexport function resetSessionImports(): void {\n _decode = undefined;\n _cookies = undefined;\n _decodeJwt = undefined;\n}\n\nexport { unwrapBaseResponse, getSessionCredentials, resolveMethod };\n"],"mappings":"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","names":["result"]}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * augur-server's `Seconds` and `Millis`: the same brands as augur-utils' (and `@atlas/utils`'),
3
+ * so each is the others' type; `test/duration.test.ts` pins that. Declared here, not imported,
4
+ * because lsc reads a type from another package out of its built `.d.ts`, where the `//@ type`
5
+ * line is gone (models/LSC-GAPS.md); the proved `rules.ts` imports these. Build values with
6
+ * augur-utils' `hours`, `toMillis` and the rest.
7
+ */
8
+ /** A whole number of seconds (a Redis TTL). */
9
+ export type Seconds = number & {
10
+ readonly __seconds: true;
11
+ };
12
+ /** A whole number of milliseconds (React Query's `staleTime` / `gcTime`). */
13
+ export type Millis = number & {
14
+ readonly __millis: true;
15
+ };
16
+ //# sourceMappingURL=duration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duration.d.ts","sourceRoot":"","sources":["../src/duration.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,+CAA+C;AAE/C,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG;IAAE,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAA;CAAE,CAAC;AAE5D,6EAA6E;AAE7E,MAAM,MAAM,MAAM,GAAG,MAAM,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAA;CAAE,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { type Env } from "./rules";
2
+ /** Resolved environment: `"development"`, `"staging"`, or `"production"`. */
3
+ export declare const env: Env;
4
+ /** `true` when running locally (localhost / NODE_ENV=development). */
5
+ export declare const isDev: boolean;
6
+ /** `true` when running on the staging/dev deployment. */
7
+ export declare const isStaging: boolean;
8
+ /** `true` when running on the production deployment. */
9
+ export declare const isProduction: boolean;
10
+ //# sourceMappingURL=environment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../src/environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,GAAG,EAAE,MAAM,SAAS,CAAC;AAqB1C,6EAA6E;AAC7E,eAAO,MAAM,GAAG,KAAmB,CAAC;AACpC,sEAAsE;AACtE,eAAO,MAAM,KAAK,SAAwB,CAAC;AAC3C,yDAAyD;AACzD,eAAO,MAAM,SAAS,SAAoB,CAAC;AAC3C,wDAAwD;AACxD,eAAO,MAAM,YAAY,SAAuB,CAAC"}
package/dist/hooks.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { QueryActionFn, OptionsProxyConfig, DeepQueryOptions } from '@simpleapps-com/augur-core';
2
- export { QueryActionFn } from '@simpleapps-com/augur-core';
3
- import { AugurAPI } from '@simpleapps-com/augur-api';
4
-
1
+ import type { DeepQueryOptions, OptionsProxyConfig, QueryActionFn } from "@simpleapps-com/augur-core";
2
+ import type { AugurAPI } from "@simpleapps-com/augur-api";
3
+ export type { QueryActionFn };
5
4
  /**
6
5
  * Creates a client-side proxy that mirrors the SDK namespace and routes
7
6
  * every method call through a server action function.
@@ -17,12 +16,12 @@ import { AugurAPI } from '@simpleapps-com/augur-api';
17
16
  *
18
17
  * // Reads — any SDK method, routed through server actions
19
18
  * const { data: item } = useQuery(q.items.invMast.doc.get(42));
20
- * const { data: price } = useQuery(q.pricing.priceEngine.get({ itemId, customerId }));
19
+ * const { data: price } = useQuery(q.pricing.priceEngine.list({ itemId, customerId }));
21
20
  *
22
21
  * // Infinite queries — spread and add infinite-specific options
23
22
  * const { data, fetchNextPage } = useInfiniteQuery({
24
- * ...q.items.itemCategory.categoryItems.get(uid, filters),
25
- * getNextPageParam: (lastPage) => lastPage.nextCursor,
23
+ * ...q.items.categories.items.list(itemCategoryUid, filters),
24
+ * getNextPageParam: (lastPage, pages) => nextOffset(lastPage, pages), // the site's paging rule
26
25
  * initialPageParam: 0,
27
26
  * });
28
27
  *
@@ -30,6 +29,5 @@ import { AugurAPI } from '@simpleapps-com/augur-api';
30
29
  * const addToCart = useMutation(q.commerce.cartLine.add.create());
31
30
  * ```
32
31
  */
33
- declare function createServerQueryProxy<TApi extends object = AugurAPI>(queryActionOrConfig?: QueryActionFn | OptionsProxyConfig, config?: OptionsProxyConfig): DeepQueryOptions<TApi>;
34
-
35
- export { createServerQueryProxy };
32
+ export declare function createServerQueryProxy<TApi extends object = AugurAPI>(queryActionOrConfig?: QueryActionFn | OptionsProxyConfig, config?: OptionsProxyConfig): DeepQueryOptions<TApi>;
33
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,gBAAgB,EAChB,kBAAkB,EAClB,aAAa,EACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAS1D,YAAY,EAAE,aAAa,EAAE,CAAC;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,SAAS,MAAM,GAAG,QAAQ,EACnE,mBAAmB,CAAC,EAAE,aAAa,GAAG,kBAAkB,EACxD,MAAM,CAAC,EAAE,kBAAkB,GAC1B,gBAAgB,CAAC,IAAI,CAAC,CAMxB"}