@tangle-network/agent-app 0.45.21 → 0.45.22

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 (110) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +21 -4
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/chunk-CCVG2TL6.js +327 -0
  16. package/dist/chunk-CCVG2TL6.js.map +1 -0
  17. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  18. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  19. package/dist/chunk-F7VH4G5C.js +283 -0
  20. package/dist/chunk-F7VH4G5C.js.map +1 -0
  21. package/dist/chunk-I24YIKHO.js +183 -0
  22. package/dist/chunk-I24YIKHO.js.map +1 -0
  23. package/dist/{chunk-AH3IOSWF.js → chunk-NZVBJM73.js} +1432 -187
  24. package/dist/chunk-NZVBJM73.js.map +1 -0
  25. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  26. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  27. package/dist/chunk-PC2WYTK7.js +405 -0
  28. package/dist/chunk-PC2WYTK7.js.map +1 -0
  29. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  30. package/dist/chunk-TX6S7XXU.js.map +1 -0
  31. package/dist/chunk-UGWQLQDS.js +35 -0
  32. package/dist/chunk-UGWQLQDS.js.map +1 -0
  33. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  34. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  35. package/dist/design-canvas/index.d.ts +3 -3
  36. package/dist/design-canvas/index.js +2 -2
  37. package/dist/design-canvas-react/engine.js +4 -4
  38. package/dist/design-canvas-react/index.js +7 -7
  39. package/dist/design-canvas-react/lazy.js +1 -1
  40. package/dist/documents/index.d.ts +233 -0
  41. package/dist/documents/index.js +495 -0
  42. package/dist/documents/index.js.map +1 -0
  43. package/dist/documents/pdf-inspector.d.ts +60 -0
  44. package/dist/documents/pdf-inspector.js +100 -0
  45. package/dist/documents/pdf-inspector.js.map +1 -0
  46. package/dist/eval/index.d.ts +1 -1
  47. package/dist/fold-DACU7gtf.d.ts +320 -0
  48. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  49. package/dist/openui/index.d.ts +208 -0
  50. package/dist/openui/index.js +350 -0
  51. package/dist/openui/index.js.map +1 -0
  52. package/dist/openui-react/index.d.ts +119 -0
  53. package/dist/openui-react/index.js +149 -0
  54. package/dist/openui-react/index.js.map +1 -0
  55. package/dist/platform/index.js +2 -2
  56. package/dist/preset-cloudflare/index.d.ts +2 -2
  57. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  58. package/dist/record/drizzle.d.ts +682 -0
  59. package/dist/record/drizzle.js +579 -0
  60. package/dist/record/drizzle.js.map +1 -0
  61. package/dist/record/index.d.ts +16 -0
  62. package/dist/record/index.js +35 -0
  63. package/dist/record/index.js.map +1 -0
  64. package/dist/runtime/index.d.ts +3 -3
  65. package/dist/sandbox/index.d.ts +2 -2
  66. package/dist/sandbox/index.js +3 -2
  67. package/dist/sequences/index.d.ts +3 -3
  68. package/dist/sequences/index.js +1 -1
  69. package/dist/session-shell/index.d.ts +173 -1
  70. package/dist/session-shell/index.js +13 -1
  71. package/dist/teams/index.js +9 -9
  72. package/dist/teams/invitations-api.js +3 -3
  73. package/dist/tools/index.d.ts +5 -5
  74. package/dist/tools/index.js +3 -2
  75. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  76. package/dist/types-DrBidf3O.d.ts +123 -0
  77. package/dist/values-C7RidJuI.d.ts +156 -0
  78. package/dist/web/index.d.ts +197 -31
  79. package/dist/web/index.js +15 -3
  80. package/dist/web-react/async/index.d.ts +309 -0
  81. package/dist/web-react/async/index.js +327 -0
  82. package/dist/web-react/async/index.js.map +1 -0
  83. package/dist/web-react/index.d.ts +338 -2
  84. package/dist/web-react/index.js +52 -6
  85. package/dist/work-product/index.d.ts +1 -1
  86. package/dist/work-product/index.js +2 -1
  87. package/dist/work-product/index.js.map +1 -1
  88. package/dist/workspace-react/index.js +1 -1
  89. package/package.json +43 -3
  90. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  91. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  92. package/dist/chunk-AH3IOSWF.js.map +0 -1
  93. package/dist/chunk-GINKOZFD.js +0 -214
  94. package/dist/chunk-GINKOZFD.js.map +0 -1
  95. package/dist/chunk-J25RST7G.js +0 -126
  96. package/dist/chunk-J25RST7G.js.map +0 -1
  97. package/dist/chunk-WBHPN5DY.js +0 -158
  98. package/dist/chunk-WBHPN5DY.js.map +0 -1
  99. package/dist/chunk-YEFFHORB.js.map +0 -1
  100. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  101. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  102. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  103. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  104. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  105. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  106. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  107. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  108. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  109. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  110. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1,283 @@
1
+ // src/web/rate-limit.ts
2
+ async function checkRateLimit(kv, key, limit, windowSeconds) {
3
+ const now = Math.floor(Date.now() / 1e3);
4
+ const windowStart = now - windowSeconds;
5
+ const kvKey = `rl:${key}`;
6
+ const raw = await kv.get(kvKey);
7
+ const parsed = parseRateLimitState(raw);
8
+ if (parsed === POISONED_STATE) {
9
+ return { allowed: false, remaining: 0, resetAt: now + windowSeconds };
10
+ }
11
+ const valid = parsed.filter((t) => t > windowStart);
12
+ if (valid.length >= limit) return { allowed: false, remaining: 0, resetAt: (valid[0] ?? now) + windowSeconds };
13
+ valid.push(now);
14
+ await kv.put(kvKey, JSON.stringify(valid), { expirationTtl: windowSeconds * 2 });
15
+ return { allowed: true, remaining: limit - valid.length, resetAt: now + windowSeconds };
16
+ }
17
+ var POISONED_STATE = /* @__PURE__ */ Symbol("rate-limit-poisoned-state");
18
+ function parseRateLimitState(raw) {
19
+ if (raw === null) return [];
20
+ let parsed;
21
+ try {
22
+ parsed = JSON.parse(raw);
23
+ } catch {
24
+ return POISONED_STATE;
25
+ }
26
+ if (!Array.isArray(parsed)) return POISONED_STATE;
27
+ return parsed.filter((t) => typeof t === "number" && Number.isFinite(t));
28
+ }
29
+
30
+ // src/web/free-route-limit.ts
31
+ var FREE_ROUTE_BUDGETS = Object.freeze({
32
+ interactive: Object.freeze({ limit: 120, windowSeconds: 60 }),
33
+ compute: Object.freeze({ limit: 30, windowSeconds: 60 }),
34
+ heavy: Object.freeze({ limit: 10, windowSeconds: 300 })
35
+ });
36
+ var WORKSPACE_BUDGET_MULTIPLIER = 5;
37
+ var FreeRouteLimitError = class extends Error {
38
+ reason;
39
+ status;
40
+ retryAfterSeconds;
41
+ dimension;
42
+ route;
43
+ constructor(init) {
44
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
45
+ this.name = "FreeRouteLimitError";
46
+ this.reason = init.reason;
47
+ this.status = init.status;
48
+ this.retryAfterSeconds = init.retryAfterSeconds;
49
+ this.dimension = init.dimension;
50
+ this.route = init.route;
51
+ }
52
+ };
53
+ function limitKey(route, dimension, id) {
54
+ return `free:${encodeURIComponent(route)}:${dimension}:${encodeURIComponent(id)}`;
55
+ }
56
+ function assertBudget(budget, label) {
57
+ const valid = Number.isInteger(budget.limit) && budget.limit >= 1 && Number.isInteger(budget.windowSeconds) && budget.windowSeconds >= 1;
58
+ if (!valid) {
59
+ throw new Error(
60
+ `${label} must be positive integers (got limit=${budget.limit}, windowSeconds=${budget.windowSeconds})`
61
+ );
62
+ }
63
+ }
64
+ function secondsUntil(resetAt) {
65
+ return Math.max(1, resetAt - Math.floor(Date.now() / 1e3));
66
+ }
67
+ async function runWindow(kv, route, dimension, id, budget) {
68
+ try {
69
+ const value = await checkRateLimit(kv, limitKey(route, dimension, id), budget.limit, budget.windowSeconds);
70
+ return { succeeded: true, value };
71
+ } catch (cause) {
72
+ return {
73
+ succeeded: false,
74
+ error: new FreeRouteLimitError({
75
+ reason: "limiter-unavailable",
76
+ status: 503,
77
+ retryAfterSeconds: Math.min(budget.windowSeconds, 30),
78
+ dimension,
79
+ route,
80
+ message: `Rate limiter unavailable for route '${route}' \u2014 the request is refused rather than admitted unmetered`,
81
+ cause
82
+ })
83
+ };
84
+ }
85
+ }
86
+ async function checkFreeRouteLimit(input) {
87
+ const budget = input.budget ?? FREE_ROUTE_BUDGETS[input.costClass ?? "compute"];
88
+ assertBudget(budget, `Free-route budget for '${input.route}'`);
89
+ const workspaceBudget = input.workspaceBudget ?? { limit: budget.limit * WORKSPACE_BUDGET_MULTIPLIER, windowSeconds: budget.windowSeconds };
90
+ if (input.workspace) assertBudget(workspaceBudget, `Free-route workspace budget for '${input.route}'`);
91
+ const subject = input.subject?.trim();
92
+ if (!subject) {
93
+ return {
94
+ succeeded: false,
95
+ error: new FreeRouteLimitError({
96
+ reason: "unidentified",
97
+ status: 401,
98
+ // Not correctable by waiting: the caller must authenticate.
99
+ retryAfterSeconds: 0,
100
+ dimension: null,
101
+ route: input.route,
102
+ message: `Route '${input.route}' is authenticated-only \u2014 an unidentified caller cannot be rate limited, so it is refused`
103
+ })
104
+ };
105
+ }
106
+ const subjectWindow = await runWindow(input.kv, input.route, "subject", subject, budget);
107
+ if (!subjectWindow.succeeded) return subjectWindow;
108
+ if (!subjectWindow.value.allowed) {
109
+ return { succeeded: false, error: rateLimited(input.route, "subject", subjectWindow.value) };
110
+ }
111
+ let tightest = {
112
+ result: subjectWindow.value,
113
+ budget,
114
+ dimension: "subject"
115
+ };
116
+ if (input.workspace) {
117
+ const workspaceWindow = await runWindow(input.kv, input.route, "workspace", input.workspace, workspaceBudget);
118
+ if (!workspaceWindow.succeeded) return workspaceWindow;
119
+ if (!workspaceWindow.value.allowed) {
120
+ return { succeeded: false, error: rateLimited(input.route, "workspace", workspaceWindow.value) };
121
+ }
122
+ if (workspaceWindow.value.remaining < tightest.result.remaining) {
123
+ tightest = { result: workspaceWindow.value, budget: workspaceBudget, dimension: "workspace" };
124
+ }
125
+ }
126
+ return {
127
+ succeeded: true,
128
+ value: {
129
+ remaining: tightest.result.remaining,
130
+ resetAt: tightest.result.resetAt,
131
+ budget: tightest.budget,
132
+ dimension: tightest.dimension
133
+ }
134
+ };
135
+ }
136
+ function rateLimited(route, dimension, result) {
137
+ const retryAfterSeconds = secondsUntil(result.resetAt);
138
+ return new FreeRouteLimitError({
139
+ reason: "rate-limited",
140
+ status: 429,
141
+ retryAfterSeconds,
142
+ dimension,
143
+ route,
144
+ message: `Route '${route}' rate limit reached for this ${dimension}; retry in ${retryAfterSeconds}s`
145
+ });
146
+ }
147
+ function freeRouteLimitResponse(error, options = {}) {
148
+ const headers = new Headers(options.headers);
149
+ headers.set("Content-Type", "application/json");
150
+ if (error.retryAfterSeconds > 0) headers.set("Retry-After", String(error.retryAfterSeconds));
151
+ return new Response(
152
+ JSON.stringify({
153
+ error: options.message ?? error.message,
154
+ reason: error.reason,
155
+ retryAfterSeconds: error.retryAfterSeconds
156
+ }),
157
+ { status: error.status, headers }
158
+ );
159
+ }
160
+ function withFreeRouteLimit(options, handler) {
161
+ return async (args) => {
162
+ const identity = await options.identify(args);
163
+ const outcome = await checkFreeRouteLimit({
164
+ kv: options.kv(args),
165
+ route: options.route,
166
+ subject: identity?.subject,
167
+ workspace: identity?.workspace,
168
+ costClass: options.costClass,
169
+ budget: options.budget,
170
+ workspaceBudget: options.workspaceBudget
171
+ });
172
+ if (!outcome.succeeded) {
173
+ return options.onDenied ? await options.onDenied(outcome.error, args) : freeRouteLimitResponse(outcome.error);
174
+ }
175
+ return await handler(args);
176
+ };
177
+ }
178
+
179
+ // src/web/index.ts
180
+ async function parseJsonObjectBody(request) {
181
+ let raw;
182
+ try {
183
+ raw = await request.json();
184
+ } catch {
185
+ return [null, Response.json({ error: "Invalid JSON body" }, { status: 400 })];
186
+ }
187
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
188
+ return [null, Response.json({ error: "Body must be a JSON object" }, { status: 400 })];
189
+ }
190
+ return [raw, null];
191
+ }
192
+ function requireString(body, field) {
193
+ const v = body[field];
194
+ if (typeof v !== "string" || v.length === 0) {
195
+ return Response.json({ error: `Missing or non-string field: ${field}` }, { status: 400 });
196
+ }
197
+ return v;
198
+ }
199
+ function extractRequestContext(request) {
200
+ const ipAddress = request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Forwarded-For")?.split(",")[0]?.trim() ?? "0.0.0.0";
201
+ return {
202
+ ipAddress,
203
+ userAgent: request.headers.get("User-Agent") ?? "",
204
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
205
+ requestId: crypto.randomUUID()
206
+ };
207
+ }
208
+ function serializeCookie(value, opts) {
209
+ if (opts.sameSite === "None" && !opts.secure) {
210
+ throw new Error("SameSite=None cookies require secure: true (browsers reject them otherwise)");
211
+ }
212
+ const parts = [`${opts.name}=${encodeURIComponent(value)}`, `Path=${opts.path ?? "/"}`];
213
+ if (opts.httpOnly !== false) parts.push("HttpOnly");
214
+ parts.push(`SameSite=${opts.sameSite ?? "Lax"}`);
215
+ if (opts.maxAgeSeconds !== void 0) parts.push(`Max-Age=${opts.maxAgeSeconds}`);
216
+ if (opts.secure) parts.push("Secure");
217
+ return parts.join("; ");
218
+ }
219
+ function clearCookieHeader(opts) {
220
+ return serializeCookie("", { ...opts, maxAgeSeconds: 0 });
221
+ }
222
+ function readCookieValue(cookieHeader, name) {
223
+ if (!cookieHeader) return null;
224
+ for (const part of cookieHeader.split(/;\s*/)) {
225
+ const [cookieName, ...rest] = part.split("=");
226
+ if (cookieName === name) {
227
+ try {
228
+ return decodeURIComponent(rest.join("="));
229
+ } catch {
230
+ return null;
231
+ }
232
+ }
233
+ }
234
+ return null;
235
+ }
236
+ var STANDARD_SECURITY_HEADERS = Object.freeze({
237
+ "Strict-Transport-Security": "max-age=31536000; includeSubDomains; preload",
238
+ "X-Content-Type-Options": "nosniff",
239
+ "X-Frame-Options": "SAMEORIGIN",
240
+ "Referrer-Policy": "same-origin",
241
+ "X-XSS-Protection": "1; mode=block"
242
+ });
243
+ function addSecurityHeaders(response, opts = {}) {
244
+ for (const [name, value] of Object.entries(STANDARD_SECURITY_HEADERS)) {
245
+ response.headers.set(name, value);
246
+ }
247
+ if (opts.disclaimer) response.headers.set("X-AI-Disclaimer", opts.disclaimer);
248
+ if (opts.retention) response.headers.set("X-Data-Retention", opts.retention);
249
+ for (const [k, v] of Object.entries(opts.extra ?? {})) response.headers.set(k, v);
250
+ return response;
251
+ }
252
+ var REJECTED_MEDIA_SCHEMES = ["file:", "data:", "blob:", "javascript:", "vbscript:"];
253
+ function assertMediaUrl(url, what = "media url") {
254
+ const trimmed = url.trim();
255
+ if (/^https?:\/\//i.test(trimmed)) return;
256
+ if (trimmed.startsWith("/api/")) return;
257
+ const shown = trimmed.length > 96 ? `${trimmed.slice(0, 96)}\u2026` : trimmed;
258
+ const lower = trimmed.toLowerCase();
259
+ if (REJECTED_MEDIA_SCHEMES.some((scheme) => lower.startsWith(scheme)) || lower.startsWith("/tmp/") || lower.startsWith("/home/")) {
260
+ throw new Error(`${what} must reference a provider http(s) URL or a rooted /api/ path, not a local sandbox file (${shown})`);
261
+ }
262
+ throw new Error(`${what} must be http(s) or a rooted /api/ path (${shown})`);
263
+ }
264
+
265
+ export {
266
+ checkRateLimit,
267
+ FREE_ROUTE_BUDGETS,
268
+ WORKSPACE_BUDGET_MULTIPLIER,
269
+ FreeRouteLimitError,
270
+ checkFreeRouteLimit,
271
+ freeRouteLimitResponse,
272
+ withFreeRouteLimit,
273
+ parseJsonObjectBody,
274
+ requireString,
275
+ extractRequestContext,
276
+ serializeCookie,
277
+ clearCookieHeader,
278
+ readCookieValue,
279
+ STANDARD_SECURITY_HEADERS,
280
+ addSecurityHeaders,
281
+ assertMediaUrl
282
+ };
283
+ //# sourceMappingURL=chunk-F7VH4G5C.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/rate-limit.ts","../src/web/free-route-limit.ts","../src/web/index.ts"],"sourcesContent":["/**\n * The KV-backed sliding-window rate limiter. Lives in its own leaf so policy\n * layers (`./free-route-limit`) can build on it without importing the web\n * barrel and creating an import cycle. Re-exported from `./index`, which is the\n * published surface.\n */\n\n/** Minimal KV contract (Cloudflare `KVNamespace` satisfies it structurally). */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n}\n\n/** Describe the outcome of a rate limit check including allowance, remaining count, and reset time */\nexport interface RateLimitResult {\n allowed: boolean\n remaining: number\n resetAt: number\n}\n\n/** KV-backed sliding-window rate limit. Stores recent timestamps per key,\n * prunes the window, allows until `limit` is hit.\n *\n * Read-modify-write is best-effort, NOT atomic: KV has no compare-and-swap, so\n * two requests racing on the same key can each read the same pre-state and both\n * write — a concurrent burst can momentarily admit up to one extra request per\n * racing writer. This is acceptable for coarse abuse limiting; it is NOT a hard\n * quota gate.\n *\n * Fail-CLOSED on unreadable state: corrupt/non-array KV (a poisoned or\n * truncated value) is treated as a full window, so a tampered key cannot reset\n * the count and bypass the limiter. A bare `JSON.parse` here would throw and\n * abort the request handler, silently disabling the limit (fail-open). */\nexport async function checkRateLimit(kv: KvLike, key: string, limit: number, windowSeconds: number): Promise<RateLimitResult> {\n const now = Math.floor(Date.now() / 1000)\n const windowStart = now - windowSeconds\n const kvKey = `rl:${key}`\n const raw = await kv.get(kvKey)\n const parsed = parseRateLimitState(raw)\n if (parsed === POISONED_STATE) {\n // Unreadable state (parse threw or value is not a JSON array): deny rather\n // than reset the window to empty. A poisoned key must not become a bypass.\n return { allowed: false, remaining: 0, resetAt: now + windowSeconds }\n }\n const valid = parsed.filter((t) => t > windowStart)\n if (valid.length >= limit) return { allowed: false, remaining: 0, resetAt: (valid[0] ?? now) + windowSeconds }\n valid.push(now)\n await kv.put(kvKey, JSON.stringify(valid), { expirationTtl: windowSeconds * 2 })\n return { allowed: true, remaining: limit - valid.length, resetAt: now + windowSeconds }\n}\n\n/** Sentinel returned by `parseRateLimitState` when the stored value cannot be\n * read as a timestamp array — distinct from an empty window so the limiter can\n * fail closed instead of treating corruption as a fresh window. */\nconst POISONED_STATE = Symbol('rate-limit-poisoned-state')\n\n/** Parse stored rate-limit state into a timestamp array. Absent state is a\n * fresh (empty) window. A value that fails to parse, or parses to a non-array,\n * returns `POISONED_STATE`; numeric junk inside a valid array is dropped. */\nfunction parseRateLimitState(raw: string | null): number[] | typeof POISONED_STATE {\n if (raw === null) return []\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return POISONED_STATE\n }\n if (!Array.isArray(parsed)) return POISONED_STATE\n return parsed.filter((t): t is number => typeof t === 'number' && Number.isFinite(t))\n}\n","/**\n * Rate-limit policy for FREE routes: authenticated, unmetered, compute-bearing\n * endpoints.\n *\n * Billing meters the chat turn. Everything deterministic a product adds beside\n * it — a planning recompute fired on every slider drag, a redline diff, a\n * deadline computation — runs unmetered, so nothing bounds how much worker CPU\n * one authenticated caller can spend. `checkRateLimit` is the primitive; this\n * is the policy around it, so a route declares a cost class instead of each one\n * inventing a key format, a budget, and a denial response.\n *\n * Three rules this enforces that a hand-rolled call site usually does not:\n *\n * 1. **Identity is required.** A missing subject is denied, never pooled into a\n * shared bucket and never quietly keyed by IP — a shared bucket makes one\n * heavy user throttle everyone, and an IP key makes one NAT do the same.\n * 2. **A limiter that throws denies.** KV `get`/`put` failures are transport\n * failures; treating them as \"allowed\" converts a KV outage into an\n * unbounded-compute hole, which is exactly when the limiter matters most.\n * 3. **The denial is a typed, correctable outcome** — reason, HTTP status and\n * `Retry-After` — so the caller answers the client rather than failing\n * opaquely or, worse, continuing.\n *\n * ```ts\n * export const action = withFreeRouteLimit(\n * {\n * route: 'tax.plan.recompute',\n * costClass: 'interactive',\n * kv: ({ context }) => context.cloudflare.env.RATE_LIMIT_KV,\n * identify: async ({ request }) => {\n * const session = await requireSession(request)\n * return { subject: session.userId, workspace: session.workspaceId }\n * },\n * },\n * async ({ request }) => Response.json(recompute(await request.json())),\n * )\n * ```\n */\n\nimport { checkRateLimit, type KvLike, type RateLimitResult } from './rate-limit'\n\n/** Requests allowed per identity inside a sliding window. */\nexport interface RateLimitBudget {\n limit: number\n windowSeconds: number\n}\n\n/**\n * How expensive one call is, which is what picks the default budget.\n *\n * - `interactive` — a control the user drags or types into, recomputed per\n * tick. Sized for sustained two-per-second interaction, so a real slider\n * never trips it and a script still stops.\n * - `compute` — a derivation the user triggers deliberately (recalculate a\n * plan, diff a document, compute a deadline set). The default.\n * - `heavy` — whole-document or whole-matter work measured in seconds of CPU.\n */\nexport type FreeRouteClass = 'interactive' | 'compute' | 'heavy'\n\n/** Default budget per cost class. A product overrides with an explicit\n * `budget` when it has measured its own route. */\nexport const FREE_ROUTE_BUDGETS: Readonly<Record<FreeRouteClass, RateLimitBudget>> = Object.freeze({\n interactive: Object.freeze({ limit: 120, windowSeconds: 60 }),\n compute: Object.freeze({ limit: 30, windowSeconds: 60 }),\n heavy: Object.freeze({ limit: 10, windowSeconds: 300 }),\n})\n\n/** A workspace's shared ceiling defaults to this many times one member's, so a\n * multi-seat tenant is bounded without a single active member tripping it. */\nexport const WORKSPACE_BUDGET_MULTIPLIER = 5\n\n/** Why a call was refused. Every value is a REFUSAL — there is no reason code\n * that lets the handler run. */\nexport type FreeRouteDenialReason =\n /** No authenticated subject. Not correctable by waiting. */\n | 'unidentified'\n /** The window is full for this subject or workspace. */\n | 'rate-limited'\n /** The limiter itself failed (KV read/write threw). Denied, not passed. */\n | 'limiter-unavailable'\n\n/** Which window refused the call. `null` when no window was consulted. */\nexport type FreeRouteDimension = 'subject' | 'workspace' | null\n\n/**\n * A correctable refusal: the caller maps `status` + `retryAfterSeconds` onto a\n * response (see {@link freeRouteLimitResponse}) so the client learns what to do\n * next. Carrying the limiter's own failure in `cause` keeps a KV outage\n * diagnosable instead of collapsing into a generic 429.\n */\nexport class FreeRouteLimitError extends Error {\n readonly reason: FreeRouteDenialReason\n readonly status: 401 | 429 | 503\n readonly retryAfterSeconds: number\n readonly dimension: FreeRouteDimension\n readonly route: string\n\n constructor(init: {\n reason: FreeRouteDenialReason\n status: 401 | 429 | 503\n retryAfterSeconds: number\n dimension: FreeRouteDimension\n route: string\n message: string\n cause?: unknown\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause })\n this.name = 'FreeRouteLimitError'\n this.reason = init.reason\n this.status = init.status\n this.retryAfterSeconds = init.retryAfterSeconds\n this.dimension = init.dimension\n this.route = init.route\n }\n}\n\n/** What remains of the binding window after an allowed call. */\nexport interface FreeRouteAllowance {\n /** Remaining calls in whichever window is tightest. */\n remaining: number\n /** Unix seconds at which that window resets. */\n resetAt: number\n /** The budget that window enforces. */\n budget: RateLimitBudget\n /** Which window is tightest — `subject` unless a workspace ceiling binds. */\n dimension: Exclude<FreeRouteDimension, null>\n}\n\n/** Typed outcome at the route boundary: an allowance, or a refusal that says\n * how to correct it. There is no third state and no silent pass. */\nexport type FreeRouteLimitOutcome =\n | { succeeded: true; value: FreeRouteAllowance }\n | { succeeded: false; error: FreeRouteLimitError }\n\nexport interface FreeRouteLimitInput {\n kv: KvLike\n /** Stable route name. Part of the key, so two routes never share a window. */\n route: string\n /** The authenticated subject (user id). Absent or blank ⇒ denied. */\n subject: string | null | undefined\n /** Tenant the call belongs to. When present, a second, wider window bounds\n * the workspace as a whole. */\n workspace?: string | null\n /** Cost class picking the default budget. Ignored when `budget` is given.\n * Default `'compute'`. */\n costClass?: FreeRouteClass\n budget?: RateLimitBudget\n /** Workspace ceiling. Defaults to the subject budget's limit multiplied by\n * {@link WORKSPACE_BUDGET_MULTIPLIER} over the same window. */\n workspaceBudget?: RateLimitBudget\n}\n\n/** Key components are percent-encoded so a route name or subject containing the\n * separator cannot be crafted to collide with another caller's window. */\nfunction limitKey(route: string, dimension: string, id: string): string {\n return `free:${encodeURIComponent(route)}:${dimension}:${encodeURIComponent(id)}`\n}\n\nfunction assertBudget(budget: RateLimitBudget, label: string): void {\n const valid =\n Number.isInteger(budget.limit) &&\n budget.limit >= 1 &&\n Number.isInteger(budget.windowSeconds) &&\n budget.windowSeconds >= 1\n if (!valid) {\n throw new Error(\n `${label} must be positive integers (got limit=${budget.limit}, windowSeconds=${budget.windowSeconds})`,\n )\n }\n}\n\nfunction secondsUntil(resetAt: number): number {\n return Math.max(1, resetAt - Math.floor(Date.now() / 1000))\n}\n\n/**\n * Run one window. A throw from KV becomes a `limiter-unavailable` refusal\n * rather than propagating — the caller must be able to answer 503 with a\n * `Retry-After` instead of the handler running or the route 500ing opaquely.\n */\nasync function runWindow(\n kv: KvLike,\n route: string,\n dimension: Exclude<FreeRouteDimension, null>,\n id: string,\n budget: RateLimitBudget,\n): Promise<{ succeeded: true; value: RateLimitResult } | { succeeded: false; error: FreeRouteLimitError }> {\n try {\n const value = await checkRateLimit(kv, limitKey(route, dimension, id), budget.limit, budget.windowSeconds)\n return { succeeded: true, value }\n } catch (cause) {\n return {\n succeeded: false,\n error: new FreeRouteLimitError({\n reason: 'limiter-unavailable',\n status: 503,\n retryAfterSeconds: Math.min(budget.windowSeconds, 30),\n dimension,\n route,\n message: `Rate limiter unavailable for route '${route}' — the request is refused rather than admitted unmetered`,\n cause,\n }),\n }\n }\n}\n\n/**\n * Decide whether one authenticated, unmetered call may run.\n *\n * Checks the subject's window first, then the workspace ceiling when a\n * workspace is supplied; the tighter of the two is what the allowance reports.\n * Every failure path returns a refusal — none returns an allowance.\n */\nexport async function checkFreeRouteLimit(input: FreeRouteLimitInput): Promise<FreeRouteLimitOutcome> {\n const budget = input.budget ?? FREE_ROUTE_BUDGETS[input.costClass ?? 'compute']\n assertBudget(budget, `Free-route budget for '${input.route}'`)\n const workspaceBudget =\n input.workspaceBudget ?? { limit: budget.limit * WORKSPACE_BUDGET_MULTIPLIER, windowSeconds: budget.windowSeconds }\n if (input.workspace) assertBudget(workspaceBudget, `Free-route workspace budget for '${input.route}'`)\n\n const subject = input.subject?.trim()\n if (!subject) {\n return {\n succeeded: false,\n error: new FreeRouteLimitError({\n reason: 'unidentified',\n status: 401,\n // Not correctable by waiting: the caller must authenticate.\n retryAfterSeconds: 0,\n dimension: null,\n route: input.route,\n message: `Route '${input.route}' is authenticated-only — an unidentified caller cannot be rate limited, so it is refused`,\n }),\n }\n }\n\n const subjectWindow = await runWindow(input.kv, input.route, 'subject', subject, budget)\n if (!subjectWindow.succeeded) return subjectWindow\n if (!subjectWindow.value.allowed) {\n return { succeeded: false, error: rateLimited(input.route, 'subject', subjectWindow.value) }\n }\n\n let tightest: { result: RateLimitResult; budget: RateLimitBudget; dimension: Exclude<FreeRouteDimension, null> } = {\n result: subjectWindow.value,\n budget,\n dimension: 'subject',\n }\n\n if (input.workspace) {\n const workspaceWindow = await runWindow(input.kv, input.route, 'workspace', input.workspace, workspaceBudget)\n if (!workspaceWindow.succeeded) return workspaceWindow\n if (!workspaceWindow.value.allowed) {\n return { succeeded: false, error: rateLimited(input.route, 'workspace', workspaceWindow.value) }\n }\n if (workspaceWindow.value.remaining < tightest.result.remaining) {\n tightest = { result: workspaceWindow.value, budget: workspaceBudget, dimension: 'workspace' }\n }\n }\n\n return {\n succeeded: true,\n value: {\n remaining: tightest.result.remaining,\n resetAt: tightest.result.resetAt,\n budget: tightest.budget,\n dimension: tightest.dimension,\n },\n }\n}\n\nfunction rateLimited(\n route: string,\n dimension: Exclude<FreeRouteDimension, null>,\n result: RateLimitResult,\n): FreeRouteLimitError {\n const retryAfterSeconds = secondsUntil(result.resetAt)\n return new FreeRouteLimitError({\n reason: 'rate-limited',\n status: 429,\n retryAfterSeconds,\n dimension,\n route,\n message: `Route '${route}' rate limit reached for this ${dimension}; retry in ${retryAfterSeconds}s`,\n })\n}\n\nexport interface FreeRouteLimitResponseOptions {\n /** Extra response headers (a product's security headers, CORS). */\n headers?: Record<string, string>\n /** Client-facing message. Defaults to the error's own message. */\n message?: string\n}\n\n/** The refusal as an HTTP response: the error's status, a JSON body carrying\n * the machine-readable `reason`, and `Retry-After` when waiting can fix it. */\nexport function freeRouteLimitResponse(\n error: FreeRouteLimitError,\n options: FreeRouteLimitResponseOptions = {},\n): Response {\n const headers = new Headers(options.headers)\n headers.set('Content-Type', 'application/json')\n if (error.retryAfterSeconds > 0) headers.set('Retry-After', String(error.retryAfterSeconds))\n return new Response(\n JSON.stringify({\n error: options.message ?? error.message,\n reason: error.reason,\n retryAfterSeconds: error.retryAfterSeconds,\n }),\n { status: error.status, headers },\n )\n}\n\n/** The authenticated caller behind one request. */\nexport interface FreeRouteIdentity {\n subject: string\n workspace?: string | null\n}\n\nexport interface WithFreeRouteLimitOptions<TArgs> {\n /** Stable route name; part of the key. */\n route: string\n costClass?: FreeRouteClass\n budget?: RateLimitBudget\n workspaceBudget?: RateLimitBudget\n /** The KV binding for this request. */\n kv: (args: TArgs) => KvLike\n /**\n * Resolve the authenticated caller. Return `null` for an unauthenticated\n * request — the wrapper then refuses with 401 and the handler never runs.\n *\n * A THROW here propagates: an auth lookup that failed is not the same as an\n * absent session, and the wrapper will not invent a status for it. The\n * handler still does not run, so the failure stays closed.\n */\n identify: (args: TArgs) => Promise<FreeRouteIdentity | null> | FreeRouteIdentity | null\n /** Build the refusal response. Defaults to {@link freeRouteLimitResponse}. */\n onDenied?: (error: FreeRouteLimitError, args: TArgs) => Response | Promise<Response>\n}\n\n/**\n * Wrap an authenticated, unmetered, compute-bearing route handler in its\n * budget. The limit is applied BEFORE the handler is entered — including\n * before the request body is read — so a refused call costs a KV read, not the\n * compute the route exists to do.\n *\n * The handler's own response is returned untouched: this never rewrites status,\n * body or headers on the success path, so it cannot break a streaming or\n * pre-built response.\n *\n * `TArgs` is the router's handler-argument object (react-router's\n * `ActionFunctionArgs`, or any single-object shape a product uses).\n */\nexport function withFreeRouteLimit<TArgs>(\n options: WithFreeRouteLimitOptions<TArgs>,\n handler: (args: TArgs) => Response | Promise<Response>,\n): (args: TArgs) => Promise<Response> {\n return async (args: TArgs): Promise<Response> => {\n const identity = await options.identify(args)\n const outcome = await checkFreeRouteLimit({\n kv: options.kv(args),\n route: options.route,\n subject: identity?.subject,\n workspace: identity?.workspace,\n costClass: options.costClass,\n budget: options.budget,\n workspaceBudget: options.workspaceBudget,\n })\n if (!outcome.succeeded) {\n return options.onDenied ? await options.onDenied(outcome.error, args) : freeRouteLimitResponse(outcome.error)\n }\n return await handler(args)\n }\n}\n","/**\n * Web-boundary utilities every agent app's routes hand-roll: JSON body parsing\n * + narrowing, request-context extraction (real client IP behind Cloudflare),\n * a KV-backed sliding-window rate limiter, the free-route budget policy built\n * on it, and security response headers. Pure mechanism — no DB, no domain. The\n * KV is a structural interface so this needs no `@cloudflare/workers-types`\n * dependency.\n */\n\nexport * from './rate-limit'\nexport * from './free-route-limit'\n\nexport type JsonObject = Record<string, unknown>\n\n/** Parse + object-narrow a Request body. `[body, null]` on success, `[null,\n * errorResponse]` on a non-object body (callers `if (err) return err`). */\nexport async function parseJsonObjectBody(request: Request): Promise<[JsonObject, null] | [null, Response]> {\n let raw: unknown\n try {\n raw = await request.json()\n } catch {\n return [null, Response.json({ error: 'Invalid JSON body' }, { status: 400 })]\n }\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return [null, Response.json({ error: 'Body must be a JSON object' }, { status: 400 })]\n }\n return [raw as JsonObject, null]\n}\n\n/** Narrow one required string field, 400 if missing/empty. */\nexport function requireString(body: JsonObject, field: string): string | Response {\n const v = body[field]\n if (typeof v !== 'string' || v.length === 0) {\n return Response.json({ error: `Missing or non-string field: ${field}` }, { status: 400 })\n }\n return v\n}\n\n/** Define the context of a request including IP address, user agent, timestamp, and request ID */\nexport interface RequestContext {\n ipAddress: string\n userAgent: string\n timestamp: string\n requestId: string\n}\n\n/** Extract request context for audit trails. Uses `CF-Connecting-IP` for the\n * real client IP behind Cloudflare. */\nexport function extractRequestContext(request: Request): RequestContext {\n const ipAddress =\n request.headers.get('CF-Connecting-IP') ??\n request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ??\n '0.0.0.0'\n return {\n ipAddress,\n userAgent: request.headers.get('User-Agent') ?? '',\n timestamp: new Date().toISOString(),\n requestId: crypto.randomUUID(),\n }\n}\n\n/** Define options for configuring cookie attributes and behavior */\nexport interface CookieOptions {\n name: string\n /** Default '/'. */\n path?: string\n /** Default true. */\n httpOnly?: boolean\n /** Adds the `Secure` attribute. Default false. */\n secure?: boolean\n /** Default 'Lax'. */\n sameSite?: 'Lax' | 'Strict' | 'None'\n maxAgeSeconds?: number\n}\n\n/** Serialize a Set-Cookie header value: `name=encodeURIComponent(value)` plus\n * attributes in Path / HttpOnly / SameSite / Max-Age / Secure order.\n * Throws on `SameSite=None` without `secure` — browsers silently drop that\n * combination, which would otherwise fail invisibly. */\nexport function serializeCookie(value: string, opts: CookieOptions): string {\n if (opts.sameSite === 'None' && !opts.secure) {\n throw new Error('SameSite=None cookies require secure: true (browsers reject them otherwise)')\n }\n const parts = [`${opts.name}=${encodeURIComponent(value)}`, `Path=${opts.path ?? '/'}`]\n if (opts.httpOnly !== false) parts.push('HttpOnly')\n parts.push(`SameSite=${opts.sameSite ?? 'Lax'}`)\n if (opts.maxAgeSeconds !== undefined) parts.push(`Max-Age=${opts.maxAgeSeconds}`)\n if (opts.secure) parts.push('Secure')\n return parts.join('; ')\n}\n\n/** Set-Cookie header value that deletes the cookie (empty value, Max-Age=0). */\nexport function clearCookieHeader(opts: Omit<CookieOptions, 'maxAgeSeconds'>): string {\n return serializeCookie('', { ...opts, maxAgeSeconds: 0 })\n}\n\n/** Read + decode one cookie from a Cookie request header; null when absent. */\nexport function readCookieValue(cookieHeader: string | null, name: string): string | null {\n if (!cookieHeader) return null\n for (const part of cookieHeader.split(/;\\s*/)) {\n const [cookieName, ...rest] = part.split('=')\n if (cookieName === name) {\n try {\n return decodeURIComponent(rest.join('='))\n } catch {\n return null\n }\n }\n }\n return null\n}\n\n/** Define options for configuring security-related HTTP headers including disclaimers and retention labels */\nexport interface SecurityHeaderOptions {\n /** Product disclaimer (e.g. \"AI-powered tool. Not legal advice.\"). Omitted if absent. */\n disclaimer?: string\n /** Data-retention label (e.g. \"7-years\"). Omitted if absent. */\n retention?: string\n /** Extra headers to set. */\n extra?: Record<string, string>\n}\n\n/** Canonical generic response headers used by {@link addSecurityHeaders}.\n * Exported so static-asset hosts can apply the same policy without copying\n * values that silently drift from Worker/API responses. */\nexport const STANDARD_SECURITY_HEADERS = Object.freeze({\n 'Strict-Transport-Security':\n 'max-age=31536000; includeSubDomains; preload',\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'SAMEORIGIN',\n 'Referrer-Policy': 'same-origin',\n 'X-XSS-Protection': '1; mode=block',\n} as const)\n\n/** Set standard security headers on a response (HSTS, nosniff, frame-options,\n * referrer-policy, XSS) + optional product disclaimer/retention. The security\n * set is generic; the disclaimer/retention are the product's. */\nexport function addSecurityHeaders(response: Response, opts: SecurityHeaderOptions = {}): Response {\n for (const [name, value] of Object.entries(STANDARD_SECURITY_HEADERS)) {\n response.headers.set(name, value)\n }\n if (opts.disclaimer) response.headers.set('X-AI-Disclaimer', opts.disclaimer)\n if (opts.retention) response.headers.set('X-Data-Retention', opts.retention)\n for (const [k, v] of Object.entries(opts.extra ?? {})) response.headers.set(k, v)\n return response\n}\n\n/** Local-sandbox / inline schemes a stored media reference must never use.\n * Reachable from neither a browser nor the product worker, and a `file:`/`data:`\n * url is the tell of an agent substituting local ffmpeg output for a real\n * provider artifact. `blob:` and `javascript:` are inert/active client schemes\n * with no server reachability. */\nconst REJECTED_MEDIA_SCHEMES = ['file:', 'data:', 'blob:', 'javascript:', 'vbscript:'] as const\n\n/**\n * Canonical media-reference boundary shared by every surface that persists a\n * media url (sequences clips, design-canvas image/video src). The ONE rule:\n * remote `http(s)` or a rooted `/api/` path are allowed; everything else is\n * rejected, with a named reason for known-bad local/inline schemes so the\n * thrown message is actionable for an LLM planner. The url is trimmed before\n * the scheme check so leading whitespace cannot smuggle a rejected scheme past\n * a naive `startsWith`.\n *\n * @param what - noun for the error message (e.g. 'media url', 'src').\n */\nexport function assertMediaUrl(url: string, what = 'media url'): void {\n const trimmed = url.trim()\n if (/^https?:\\/\\//i.test(trimmed)) return\n if (trimmed.startsWith('/api/')) return\n const shown = trimmed.length > 96 ? `${trimmed.slice(0, 96)}…` : trimmed\n const lower = trimmed.toLowerCase()\n if (\n REJECTED_MEDIA_SCHEMES.some((scheme) => lower.startsWith(scheme)) ||\n lower.startsWith('/tmp/') ||\n lower.startsWith('/home/')\n ) {\n throw new Error(`${what} must reference a provider http(s) URL or a rooted /api/ path, not a local sandbox file (${shown})`)\n }\n throw new Error(`${what} must be http(s) or a rooted /api/ path (${shown})`)\n}\n"],"mappings":";AAiCA,eAAsB,eAAe,IAAY,KAAa,OAAe,eAAiD;AAC5H,QAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACxC,QAAM,cAAc,MAAM;AAC1B,QAAM,QAAQ,MAAM,GAAG;AACvB,QAAM,MAAM,MAAM,GAAG,IAAI,KAAK;AAC9B,QAAM,SAAS,oBAAoB,GAAG;AACtC,MAAI,WAAW,gBAAgB;AAG7B,WAAO,EAAE,SAAS,OAAO,WAAW,GAAG,SAAS,MAAM,cAAc;AAAA,EACtE;AACA,QAAM,QAAQ,OAAO,OAAO,CAAC,MAAM,IAAI,WAAW;AAClD,MAAI,MAAM,UAAU,MAAO,QAAO,EAAE,SAAS,OAAO,WAAW,GAAG,UAAU,MAAM,CAAC,KAAK,OAAO,cAAc;AAC7G,QAAM,KAAK,GAAG;AACd,QAAM,GAAG,IAAI,OAAO,KAAK,UAAU,KAAK,GAAG,EAAE,eAAe,gBAAgB,EAAE,CAAC;AAC/E,SAAO,EAAE,SAAS,MAAM,WAAW,QAAQ,MAAM,QAAQ,SAAS,MAAM,cAAc;AACxF;AAKA,IAAM,iBAAiB,uBAAO,2BAA2B;AAKzD,SAAS,oBAAoB,KAAsD;AACjF,MAAI,QAAQ,KAAM,QAAO,CAAC;AAC1B,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,MAAM,QAAQ,MAAM,EAAG,QAAO;AACnC,SAAO,OAAO,OAAO,CAAC,MAAmB,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,CAAC;AACtF;;;ACRO,IAAM,qB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return { succeeded: false, error, code };
7
+ }
8
+ var RECORD_KEY_SENTINEL = "";
9
+ var RECORD_PERIOD_SENTINEL = 0;
10
+ var RECORD_REVIEW_STATES = ["proposed", "accepted", "rejected"];
11
+ var KEY_SEPARATOR = "\0";
12
+ function recordKeyString(key) {
13
+ return [key.dimension, key.path, key.itemKey, String(key.period)].join(KEY_SEPARATOR);
14
+ }
15
+ function canonicalRecordJson(value) {
16
+ const encoded = JSON.stringify(sortKeysDeep(value));
17
+ return encoded === void 0 ? "null" : encoded;
18
+ }
19
+ function sortKeysDeep(value) {
20
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
21
+ if (value !== null && typeof value === "object") {
22
+ const source = value;
23
+ const out = {};
24
+ for (const key of Object.keys(source).sort()) out[key] = sortKeysDeep(source[key]);
25
+ return out;
26
+ }
27
+ return value;
28
+ }
29
+ function validateRecordValue(validator, value) {
30
+ if (typeof validator === "function") return validator(value);
31
+ const parsed = validator.safeParse(value);
32
+ if (parsed.success) return recordOk(parsed.data);
33
+ return recordFail("invalid-value", describeParseError(parsed.error));
34
+ }
35
+ function describeParseError(error) {
36
+ if (error !== null && typeof error === "object") {
37
+ const issues = error.issues;
38
+ if (Array.isArray(issues)) {
39
+ const messages = issues.map((issue) => issue !== null && typeof issue === "object" ? String(issue.message ?? "") : "").filter((message2) => message2.length > 0);
40
+ if (messages.length > 0) return messages.join("; ");
41
+ }
42
+ const message = error.message;
43
+ if (typeof message === "string" && message.length > 0) return message;
44
+ }
45
+ return String(error);
46
+ }
47
+ var defaultRecordMaterialDifference = (head, incoming) => head.sourceKind !== incoming.sourceKind && (head.valueJson !== incoming.valueJson || head.affirmedEmpty !== incoming.affirmedEmpty);
48
+ function resolveWriteReviewState(policy, sourceKind) {
49
+ const state = policy.reviewStateOnWrite[sourceKind];
50
+ if (state === void 0) {
51
+ const known = Object.keys(policy.reviewStateOnWrite).sort().join(", ");
52
+ return recordFail(
53
+ "unknown-source-kind",
54
+ `source kind '${sourceKind}' is not declared in reviewStateOnWrite (declared: ${known || "none"})`
55
+ );
56
+ }
57
+ return recordOk(state);
58
+ }
59
+ function detectRecordConflict(policy, head, incoming) {
60
+ if (head === void 0) return false;
61
+ return (policy.isMateriallyDifferent ?? defaultRecordMaterialDifference)(head, incoming);
62
+ }
63
+
64
+ // src/record/fold.ts
65
+ var defaultRecordPeriodScope = () => "exact";
66
+ function recordEntryVisibleInPeriod(scope, entryPeriod, requestedPeriod) {
67
+ return scope === "carry-forward" ? entryPeriod <= requestedPeriod : entryPeriod === requestedPeriod;
68
+ }
69
+ function foldRecordEntries(entries, options) {
70
+ const { rules } = options;
71
+ const periodScope = rules.periodScope ?? defaultRecordPeriodScope;
72
+ const period = options.period ?? RECORD_PERIOD_SENTINEL;
73
+ if (!Number.isInteger(period)) {
74
+ return recordFail("invalid-input", `foldRecordEntries: period must be an integer, got ${String(period)}`);
75
+ }
76
+ const carryHeads = /* @__PURE__ */ new Map();
77
+ for (const entry of entries) {
78
+ const scope = periodScope(entry.path);
79
+ if (!recordEntryVisibleInPeriod(scope, entry.period, period)) continue;
80
+ if (scope !== "carry-forward") continue;
81
+ const key = carryKey(entry);
82
+ const best = carryHeads.get(key);
83
+ if (best === void 0 || entry.period > best) carryHeads.set(key, entry.period);
84
+ }
85
+ const resolved = entries.filter((entry) => {
86
+ const scope = periodScope(entry.path);
87
+ if (!recordEntryVisibleInPeriod(scope, entry.period, period)) return false;
88
+ if (scope !== "carry-forward") return true;
89
+ return carryHeads.get(carryKey(entry)) === entry.period;
90
+ }).sort((a, b) => a.seq - b.seq || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
91
+ const draft = rules.init();
92
+ for (const entry of resolved) {
93
+ let value = null;
94
+ if (!entry.affirmedEmpty) {
95
+ try {
96
+ value = JSON.parse(entry.valueJson);
97
+ } catch {
98
+ return recordFail("fold-failed", `foldRecordEntries: entry '${entry.id}' has unparseable valueJson`);
99
+ }
100
+ }
101
+ const decoded = { ...entry, value };
102
+ if (entry.affirmedEmpty) {
103
+ if (!rules.retract) {
104
+ return recordFail(
105
+ "fold-failed",
106
+ `foldRecordEntries: entry '${entry.id}' ('${entry.path}') is affirmedEmpty but the rules define no retract`
107
+ );
108
+ }
109
+ const retracted = rules.retract(draft, decoded);
110
+ if (!retracted.succeeded) {
111
+ return recordFail("fold-failed", `foldRecordEntries: entry '${entry.id}' ('${entry.path}') \u2014 ${retracted.error}`);
112
+ }
113
+ continue;
114
+ }
115
+ const applied = rules.apply(draft, decoded);
116
+ if (!applied.succeeded) {
117
+ return recordFail("fold-failed", `foldRecordEntries: entry '${entry.id}' ('${entry.path}') \u2014 ${applied.error}`);
118
+ }
119
+ }
120
+ if (rules.finalize) {
121
+ const finalized = rules.finalize(draft);
122
+ if (!finalized.succeeded) {
123
+ return recordFail("fold-failed", `foldRecordEntries: finalize \u2014 ${finalized.error}`);
124
+ }
125
+ }
126
+ return recordOk({ value: draft, entryCount: resolved.length });
127
+ }
128
+ function carryKey(entry) {
129
+ return recordKeyString({
130
+ dimension: entry.dimension,
131
+ path: entry.path,
132
+ itemKey: entry.itemKey,
133
+ period: RECORD_PERIOD_SENTINEL
134
+ });
135
+ }
136
+
137
+ // src/record/ulid.ts
138
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
139
+ var MAX_TIMESTAMP = 2 ** 48 - 1;
140
+ function recordUlid(now = Date.now()) {
141
+ if (!Number.isInteger(now) || now < 0 || now > MAX_TIMESTAMP) {
142
+ throw new Error(`recordUlid: timestamp out of range: ${now}`);
143
+ }
144
+ let time = now;
145
+ const chars = new Array(26);
146
+ for (let i = 9; i >= 0; i--) {
147
+ chars[i] = ENCODING[time % 32];
148
+ time = Math.floor(time / 32);
149
+ }
150
+ const bytes = new Uint8Array(10);
151
+ crypto.getRandomValues(bytes);
152
+ let buffer = 0;
153
+ let bits = 0;
154
+ let out = 10;
155
+ for (const byte of bytes) {
156
+ buffer = buffer << 8 | byte;
157
+ bits += 8;
158
+ while (bits >= 5) {
159
+ chars[out++] = ENCODING[buffer >>> bits - 5 & 31];
160
+ bits -= 5;
161
+ }
162
+ }
163
+ return chars.join("");
164
+ }
165
+
166
+ export {
167
+ recordOk,
168
+ recordFail,
169
+ RECORD_KEY_SENTINEL,
170
+ RECORD_PERIOD_SENTINEL,
171
+ RECORD_REVIEW_STATES,
172
+ recordKeyString,
173
+ canonicalRecordJson,
174
+ validateRecordValue,
175
+ defaultRecordMaterialDifference,
176
+ resolveWriteReviewState,
177
+ detectRecordConflict,
178
+ defaultRecordPeriodScope,
179
+ recordEntryVisibleInPeriod,
180
+ foldRecordEntries,
181
+ recordUlid
182
+ };
183
+ //# sourceMappingURL=chunk-I24YIKHO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/record/model.ts","../src/record/fold.ts","../src/record/ulid.ts"],"sourcesContent":["/**\n * The pure core of the record module: the entry vocabulary, the key sentinels,\n * canonical value encoding, consumer-supplied validation, and the conflict\n * rule. Zero imports — a product can fold and validate entries in a browser,\n * an eval process, or a worker without touching a database driver.\n *\n * A record entry is one source-cited assertion: \"at `path` (optionally for\n * `itemKey`, in `dimension`, for `period`), the value is X, and here is where\n * that came from\". Entries are append-only. An entry becomes the live head of\n * its key by being `accepted` with no `supersededById`; the previous head is\n * marked superseded in the same atomic write, so the history stays readable.\n *\n * Every domain word — what a path means, what an item key identifies, what a\n * dimension or period is, which source kinds exist — is a parameter supplied\n * by the consumer. This module knows none of them.\n */\n\n/** Error classes a caller maps to a status code or a retry decision. */\nexport type RecordErrorCode =\n /** The path is not a key of the consumer's schema map. */\n | 'unknown-path'\n /** The value failed the consumer's schema for its path. */\n | 'invalid-value'\n /** The input is structurally wrong (bad period, missing source ref, …). */\n | 'invalid-input'\n /** The source kind is not a key of the consumer's review policy. */\n | 'unknown-source-kind'\n /** No such entry in this scope. */\n | 'not-found'\n /** The entry is not in a state this operation accepts. */\n | 'not-reviewable'\n /** A competing writer took the live head; the caller may re-read and retry. */\n | 'supersede-race'\n /** The fold rejected an entry — the record cannot be materialized. */\n | 'fold-failed'\n /** The driver raised. */\n | 'storage-failed'\n /** The driver exposes no atomic multi-statement primitive. */\n | 'unsupported-driver'\n\n/**\n * Typed outcome for every record operation. Callers MUST inspect `succeeded`\n * before reading `value`; nothing here throws past its own boundary except a\n * programming error in the consumer's own callbacks.\n */\nexport type RecordOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: string; code: RecordErrorCode }\n\n/** Build a success outcome. */\nexport function recordOk<T>(value: T): RecordOutcome<T> {\n return { succeeded: true, value }\n}\n\n/** Build a failure outcome carrying its error class. */\nexport function recordFail(code: RecordErrorCode, error: string): RecordOutcome<never> {\n return { succeeded: false, error, code }\n}\n\n/**\n * Sentinel for an unused key column.\n *\n * SQLite treats NULLs as distinct in a unique index, so a nullable key column\n * would let two live heads coexist on the same logical key. Every key column\n * is therefore NOT NULL with a sentinel, and this is the sentinel for the two\n * text ones (`dimension`, `itemKey`).\n */\nexport const RECORD_KEY_SENTINEL = ''\n\n/**\n * Sentinel period for a record with no time dimension. Same reason as\n * {@link RECORD_KEY_SENTINEL}: the column is NOT NULL so the unique index over\n * the live head actually dedupes. A consumer with no period concept writes\n * every entry at `0` and materializes at `0`.\n */\nexport const RECORD_PERIOD_SENTINEL = 0\n\n/** Lifecycle of one entry. `accepted` requires a structured act — a source\n * kind the policy trusts, or an explicit review. */\nexport type RecordReviewState = 'proposed' | 'accepted' | 'rejected'\n\n/** Every review state, for iteration and validation. */\nexport const RECORD_REVIEW_STATES: readonly RecordReviewState[] = ['proposed', 'accepted', 'rejected']\n\n/** Position of the assertion inside its source. All fields optional — a chat\n * message has no page, a scraped row has no character span. */\nexport interface RecordSourceLocator {\n page?: number\n charStart?: number\n charEnd?: number\n}\n\n/** The columns that identify which assertion an entry supersedes. Two entries\n * with the same key compete for the same live head. */\nexport interface RecordEntryKey {\n /** Consumer-defined partition inside a scope — whatever second axis the\n * product folds along. {@link RECORD_KEY_SENTINEL} when unused. */\n dimension: string\n /** The field this entry asserts. Must be a key of the schema map. */\n path: string\n /** Identifies which element of a collection the path belongs to, when the\n * path addresses a repeated thing. {@link RECORD_KEY_SENTINEL} when unused. */\n itemKey: string\n /** The period the assertion became true in. {@link RECORD_PERIOD_SENTINEL}\n * when the consumer has no time dimension. */\n period: number\n}\n\n/** Separator for the joined fold key. NUL cannot appear in a SQLite text\n * value, so the join is unambiguous for any key content. */\nconst KEY_SEPARATOR = '\\u0000'\n\n/** Join an entry key into one comparable string, for grouping in memory. */\nexport function recordKeyString(key: RecordEntryKey): string {\n return [key.dimension, key.path, key.itemKey, String(key.period)].join(KEY_SEPARATOR)\n}\n\n/**\n * Deterministic JSON with object keys sorted at every depth. Two values that\n * differ only in key order encode identically, so the conflict rule never\n * fires on serialization noise and the fold's stored value is stable.\n */\nexport function canonicalRecordJson(value: unknown): string {\n const encoded = JSON.stringify(sortKeysDeep(value))\n return encoded === undefined ? 'null' : encoded\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeysDeep)\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(source).sort()) out[key] = sortKeysDeep(source[key])\n return out\n }\n return value\n}\n\n/** The result shape a `safeParse`-style validator returns. `zod`'s schemas\n * satisfy this structurally, so a consumer passes its zod schema directly and\n * this module takes no schema-library dependency. */\nexport type RecordParseResult =\n | { success: true; data: unknown }\n | { success: false; error: unknown }\n\n/** Something that can validate one value for one path: a `safeParse` object\n * (zod and friends) or a plain function returning a typed outcome. */\nexport type RecordValueValidator =\n | { safeParse(value: unknown): RecordParseResult }\n | ((value: unknown) => RecordOutcome<unknown>)\n\n/**\n * Path → validator. The KEY SET is the write allowlist: a path absent from the\n * map is rejected with `unknown-path`, so nothing the consumer's fold cannot\n * type-check ever reaches storage.\n */\nexport type RecordSchemaMap = Readonly<Record<string, RecordValueValidator>>\n\n/** Run one validator, normalizing both forms to a typed outcome and flattening\n * a `safeParse` error into a readable message. */\nexport function validateRecordValue(\n validator: RecordValueValidator,\n value: unknown,\n): RecordOutcome<unknown> {\n if (typeof validator === 'function') return validator(value)\n const parsed = validator.safeParse(value)\n if (parsed.success) return recordOk(parsed.data)\n return recordFail('invalid-value', describeParseError(parsed.error))\n}\n\nfunction describeParseError(error: unknown): string {\n if (error !== null && typeof error === 'object') {\n const issues = (error as { issues?: unknown }).issues\n if (Array.isArray(issues)) {\n const messages = issues\n .map((issue) => (issue !== null && typeof issue === 'object' ? String((issue as { message?: unknown }).message ?? '') : ''))\n .filter((message) => message.length > 0)\n if (messages.length > 0) return messages.join('; ')\n }\n const message = (error as { message?: unknown }).message\n if (typeof message === 'string' && message.length > 0) return message\n }\n return String(error)\n}\n\n/**\n * How a live accepted head at the same key is compared against an incoming\n * write. Returning `true` means the two assertions genuinely disagree.\n */\nexport type RecordMaterialDifference = (\n head: { sourceKind: string; valueJson: string; affirmedEmpty: boolean },\n incoming: { sourceKind: string; valueJson: string; affirmedEmpty: boolean },\n) => boolean\n\n/**\n * The default rule, and the one all three hand-rolled stores converged on:\n * two assertions materially differ when they come from DIFFERENT source kinds\n * and encode to different canonical JSON. A restatement from the same source\n * kind is a refresh, not a disagreement; an identical value from another\n * source kind is corroboration.\n */\nexport const defaultRecordMaterialDifference: RecordMaterialDifference = (head, incoming) =>\n head.sourceKind !== incoming.sourceKind &&\n (head.valueJson !== incoming.valueJson || head.affirmedEmpty !== incoming.affirmedEmpty)\n\n/** Canonicalize a key column before it enters the fold key (upper-casing a\n * region code, trimming an identifier). Rejecting is fail-loud, never a\n * silent rewrite to a sentinel. */\nexport type RecordKeyCanonicalizer = (path: string, raw: string) => RecordOutcome<string>\n\n/**\n * Everything domain-specific about writing an entry, supplied by the consumer.\n * The store holds no defaults for any of it except the conflict rule.\n */\nexport interface RecordWritePolicy {\n /** Path → validator; the key set is the write allowlist. */\n schemas: RecordSchemaMap\n /**\n * Paths that accept a negative assertion (`affirmedEmpty`) — \"there are none\n * of these\". These are typically COLLECTION paths that carry no value of\n * their own, so they are deliberately separate from {@link schemas}.\n */\n affirmablePaths?: readonly string[]\n /**\n * Source kind → the review state a write from it lands in. The key set is\n * the source-kind allowlist: an unlisted kind is rejected. This is where a\n * product says \"a value the user typed is accepted; anything a model\n * extracted is proposed\".\n */\n reviewStateOnWrite: Readonly<Record<string, RecordReviewState>>\n /** Source kinds whose writes must carry a `sourceRef`. A citation store\n * makes every extracting kind require one. */\n requireSourceRef?: readonly string[]\n /** Source kinds whose writes must carry a `sourceQuote`. */\n requireSourceQuote?: readonly string[]\n /**\n * Source kind → product columns (declared through the table factory's\n * `extraColumns`) whose value a write from that kind must supply.\n *\n * `requireSourceRef` can only require THE one built-in ref, which is not\n * enough for a store whose kinds point at different tables — a chat-sourced\n * row cites a message and a document-sourced row cites a document, each with\n * its own foreign key. Declaring one column per kind and requiring it per\n * kind is how that shape is expressed without the store learning either\n * word.\n */\n requireExtras?: Readonly<Record<string, readonly string[]>>\n /** Canonicalize `itemKey` before it becomes part of the fold key. */\n canonicalizeItemKey?: RecordKeyCanonicalizer\n /** Canonicalize `dimension` before it becomes part of the fold key. */\n canonicalizeDimension?: RecordKeyCanonicalizer\n /** Override the conflict rule. Defaults to\n * {@link defaultRecordMaterialDifference}. */\n isMateriallyDifferent?: RecordMaterialDifference\n /** Lowest accepted period. Defaults to {@link RECORD_PERIOD_SENTINEL}. */\n minPeriod?: number\n /** Highest accepted period. Defaults to `Number.MAX_SAFE_INTEGER`. */\n maxPeriod?: number\n}\n\n/** Resolve the review state a write from `sourceKind` lands in, failing loud\n * on a kind the policy never declared. */\nexport function resolveWriteReviewState(\n policy: RecordWritePolicy,\n sourceKind: string,\n): RecordOutcome<RecordReviewState> {\n const state = policy.reviewStateOnWrite[sourceKind]\n if (state === undefined) {\n const known = Object.keys(policy.reviewStateOnWrite).sort().join(', ')\n return recordFail(\n 'unknown-source-kind',\n `source kind '${sourceKind}' is not declared in reviewStateOnWrite (declared: ${known || 'none'})`,\n )\n }\n return recordOk(state)\n}\n\n/** True when the incoming write disagrees with the live head under the\n * policy's rule (or the default). */\nexport function detectRecordConflict(\n policy: RecordWritePolicy,\n head: { sourceKind: string; valueJson: string; affirmedEmpty: boolean } | undefined,\n incoming: { sourceKind: string; valueJson: string; affirmedEmpty: boolean },\n): boolean {\n if (head === undefined) return false\n return (policy.isMateriallyDifferent ?? defaultRecordMaterialDifference)(head, incoming)\n}\n","/**\n * The fold: live entries in, one consumer-shaped object out.\n *\n * Pure and driver-free — the store loads rows and hands them here, and a test\n * or an eval harness can call it with literals. Determinism is the contract:\n * the result depends only on the CONTENT of the entries, never on the order\n * they arrive in, because ordering is `seq` alone (with `id` as an unreachable\n * tie-break — `(scope, seq)` is unique in storage). Nothing here reads a clock\n * or a timestamp column, so two entries written in the same second still fold\n * in a defined order.\n *\n * The consumer supplies the grouping rules: which paths carry forward across\n * periods, how one entry applies to the accumulator, what a negative assertion\n * retracts, and any derived values computed after the last entry.\n */\n\nimport {\n recordFail,\n recordKeyString,\n recordOk,\n RECORD_PERIOD_SENTINEL,\n type RecordOutcome,\n} from './model'\n\n/**\n * How a path's entries resolve against the period being materialized.\n *\n * - `exact` — visible only at their own period. A value that was true for one\n * period is structurally invisible to every other one.\n * - `carry-forward` — visible at any period at or after their own, and only\n * the newest such entry per key wins. Asserting a new value at a later\n * period changes that period onward and can never rewrite an earlier one.\n */\nexport type RecordPeriodScope = 'exact' | 'carry-forward'\n\n/** Resolves the period scope of one path. */\nexport type RecordPeriodScopeResolver = (path: string) => RecordPeriodScope\n\n/** The scope assumed for every path when a consumer supplies no resolver. */\nexport const defaultRecordPeriodScope: RecordPeriodScopeResolver = () => 'exact'\n\n/** The slice of a stored row the fold reads. */\nexport interface FoldableRecordEntry {\n id: string\n /** Per-scope monotonic write counter — the ONLY ordering key. */\n seq: number\n dimension: string\n period: number\n path: string\n itemKey: string\n /** Canonical JSON produced by `canonicalRecordJson` on write. */\n valueJson: string\n /** True when the entry asserts \"there are none of these\" at `path`. */\n affirmedEmpty: boolean\n}\n\n/** A resolved entry with its value already parsed, handed to the rules. */\nexport interface DecodedRecordEntry extends FoldableRecordEntry {\n /** `JSON.parse(valueJson)`; `null` on an `affirmedEmpty` entry. */\n value: unknown\n}\n\n/**\n * The consumer's grouping rules. `T` is whatever shape the product folds into\n * — a typed profile object, a keyed map, a list.\n */\nexport interface RecordFoldRules<T> {\n /** Fresh accumulator for one fold. Must return a NEW object each call. */\n init(): T\n /**\n * Period scope for a path. Called for every entry, including paths that only\n * ever appear as `affirmedEmpty` targets. Defaults to `'exact'` for every\n * path when omitted, which is the narrower rule: an entry never leaks into a\n * period it was not asserted for.\n */\n periodScope?: RecordPeriodScopeResolver\n /** Apply one entry to the accumulator. Fail loud: an entry the rules cannot\n * place must reject the whole fold, never be skipped — a silently dropped\n * entry shows a wrong number with a straight face. */\n apply(draft: T, entry: DecodedRecordEntry): RecordOutcome<void>\n /** Apply a negative assertion. Runs at the entry's `seq`, so later entries\n * at the same path repopulate. Omit it to reject `affirmedEmpty` entries. */\n retract?(draft: T, entry: DecodedRecordEntry): RecordOutcome<void>\n /** Compute derived values after the last entry. */\n finalize?(draft: T): RecordOutcome<void>\n}\n\n/** Options for one fold. */\nexport interface FoldRecordEntriesOptions<T> {\n rules: RecordFoldRules<T>\n /** The period being materialized. Defaults to\n * {@link RECORD_PERIOD_SENTINEL} for a record with no time dimension. */\n period?: number\n}\n\n/** What a fold produced. */\nexport interface RecordFoldResult<T> {\n value: T\n /** Entries that survived period resolution and were applied. */\n entryCount: number\n}\n\n/**\n * True when an entry at `entryPeriod` is a candidate at `requestedPeriod`\n * under `scope`. Carry-forward candidacy is necessary, not sufficient — only\n * the newest candidate per key survives {@link foldRecordEntries}.\n */\nexport function recordEntryVisibleInPeriod(\n scope: RecordPeriodScope,\n entryPeriod: number,\n requestedPeriod: number,\n): boolean {\n return scope === 'carry-forward' ? entryPeriod <= requestedPeriod : entryPeriod === requestedPeriod\n}\n\n/**\n * Resolve entries against the requested period, then fold them in `seq` order.\n *\n * Callers may pass entries in any order and any mix of periods; the result is\n * a function of their content alone.\n */\nexport function foldRecordEntries<T>(\n entries: readonly FoldableRecordEntry[],\n options: FoldRecordEntriesOptions<T>,\n): RecordOutcome<RecordFoldResult<T>> {\n const { rules } = options\n const periodScope = rules.periodScope ?? defaultRecordPeriodScope\n const period = options.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `foldRecordEntries: period must be an integer, got ${String(period)}`)\n }\n\n // Newest candidate period per carry-forward key; `exact` keys need no head.\n const carryHeads = new Map<string, number>()\n for (const entry of entries) {\n const scope = periodScope(entry.path)\n if (!recordEntryVisibleInPeriod(scope, entry.period, period)) continue\n if (scope !== 'carry-forward') continue\n const key = carryKey(entry)\n const best = carryHeads.get(key)\n if (best === undefined || entry.period > best) carryHeads.set(key, entry.period)\n }\n\n const resolved = entries\n .filter((entry) => {\n const scope = periodScope(entry.path)\n if (!recordEntryVisibleInPeriod(scope, entry.period, period)) return false\n if (scope !== 'carry-forward') return true\n return carryHeads.get(carryKey(entry)) === entry.period\n })\n // `(scope, seq)` is unique in storage, so the `id` tie-break is unreachable\n // for stored rows; it keeps a hand-built entry list deterministic too.\n .sort((a, b) => (a.seq - b.seq) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n\n const draft = rules.init()\n for (const entry of resolved) {\n let value: unknown = null\n if (!entry.affirmedEmpty) {\n try {\n value = JSON.parse(entry.valueJson)\n } catch {\n return recordFail('fold-failed', `foldRecordEntries: entry '${entry.id}' has unparseable valueJson`)\n }\n }\n const decoded: DecodedRecordEntry = { ...entry, value }\n\n if (entry.affirmedEmpty) {\n if (!rules.retract) {\n return recordFail(\n 'fold-failed',\n `foldRecordEntries: entry '${entry.id}' ('${entry.path}') is affirmedEmpty but the rules define no retract`,\n )\n }\n const retracted = rules.retract(draft, decoded)\n if (!retracted.succeeded) {\n return recordFail('fold-failed', `foldRecordEntries: entry '${entry.id}' ('${entry.path}') — ${retracted.error}`)\n }\n continue\n }\n\n const applied = rules.apply(draft, decoded)\n if (!applied.succeeded) {\n return recordFail('fold-failed', `foldRecordEntries: entry '${entry.id}' ('${entry.path}') — ${applied.error}`)\n }\n }\n\n if (rules.finalize) {\n const finalized = rules.finalize(draft)\n if (!finalized.succeeded) {\n return recordFail('fold-failed', `foldRecordEntries: finalize — ${finalized.error}`)\n }\n }\n\n return recordOk({ value: draft, entryCount: resolved.length })\n}\n\n/** Carry-forward candidacy is per (dimension, path, itemKey) — the entry key\n * WITHOUT its period, since the period is what is being resolved. */\nfunction carryKey(entry: FoldableRecordEntry): string {\n return recordKeyString({\n dimension: entry.dimension,\n path: entry.path,\n itemKey: entry.itemKey,\n period: RECORD_PERIOD_SENTINEL,\n })\n}\n","/**\n * ULID — a 26-character Crockford-base32 id: a 48-bit millisecond timestamp\n * followed by 80 bits from `crypto.getRandomValues`.\n *\n * The record store mints ids in application code rather than taking a column\n * default, because an atomic supersede stamps the REPLACEMENT's id onto the\n * outgoing head in the same write — the id has to exist before the insert.\n * Lexicographic order approximates creation order, which keeps a raw table\n * scan readable; strict fold ordering comes from `seq`, never from the id.\n */\n\nconst ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\nconst MAX_TIMESTAMP = 2 ** 48 - 1\n\n/** Mint a ULID. `now` is exposed so a caller can pin time in a test. */\nexport function recordUlid(now: number = Date.now()): string {\n if (!Number.isInteger(now) || now < 0 || now > MAX_TIMESTAMP) {\n throw new Error(`recordUlid: timestamp out of range: ${now}`)\n }\n let time = now\n const chars = new Array<string>(26)\n for (let i = 9; i >= 0; i--) {\n chars[i] = ENCODING[time % 32] as string\n time = Math.floor(time / 32)\n }\n const bytes = new Uint8Array(10)\n crypto.getRandomValues(bytes)\n // 80 random bits → 16 base-32 characters through a rolling bit buffer.\n let buffer = 0\n let bits = 0\n let out = 10\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte\n bits += 8\n while (bits >= 5) {\n chars[out++] = ENCODING[(buffer >>> (b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