@valerypopoff/rivet2-core 2.3.0 → 2.5.0

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 (105) hide show
  1. package/dist/cjs/bundle.cjs +1947 -765
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +1578 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +7 -0
  5. package/dist/cjs/interpolationSyntax.cjs +186 -0
  6. package/dist/cjs/interpolationSyntax.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +1537 -121
  8. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  9. package/dist/esm/api/createProcessor.js +2 -0
  10. package/dist/esm/exports.js +4 -1
  11. package/dist/esm/integrations/CodeRunner.js +5 -0
  12. package/dist/esm/integrations/mcp/MCPBase.js +16 -6
  13. package/dist/esm/interpolationRuntime.js +5 -0
  14. package/dist/esm/model/AgentResponseTrace.js +16 -0
  15. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  16. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  17. package/dist/esm/model/GraphOutputSelection.js +34 -0
  18. package/dist/esm/model/GraphProcessor.js +150 -44
  19. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  20. package/dist/esm/model/ProcessContextBuilder.js +4 -1
  21. package/dist/esm/model/RecordingPlayer.js +19 -6
  22. package/dist/esm/model/StoredValueStore.js +4 -3
  23. package/dist/esm/model/SubprocessorBridge.js +1 -0
  24. package/dist/esm/model/UiGraphActionProtocol.js +46 -4
  25. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  26. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  27. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  28. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  29. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  30. package/dist/esm/model/chat-v2/chatV2CallObserver.js +1 -0
  31. package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -33
  32. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +1 -0
  33. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  34. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  35. package/dist/esm/model/chat-v2/llmProfile.js +17 -1
  36. package/dist/esm/model/chat-v2/llmProfileFallback.js +17 -5
  37. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +2 -0
  38. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +4 -0
  39. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  40. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  41. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  42. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  43. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  44. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  45. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  46. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +21 -2
  48. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  49. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  50. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  51. package/dist/esm/model/nodes/PromptNode.js +10 -11
  52. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  53. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  54. package/dist/esm/model/nodes/TextNode.js +11 -32
  55. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  56. package/dist/esm/model/nodes/ToolNode.js +33 -16
  57. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  58. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  59. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  60. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  61. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  62. package/dist/esm/utils/index.js +2 -0
  63. package/dist/esm/utils/interpolation.js +478 -221
  64. package/dist/esm/utils/interpolationSyntax.js +175 -0
  65. package/dist/esm/utils/jsonPath.js +129 -0
  66. package/dist/esm/webAppRuntime.js +5 -2
  67. package/dist/types/api/createProcessor.d.ts +2 -0
  68. package/dist/types/exports.d.ts +5 -1
  69. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  70. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  71. package/dist/types/interpolationRuntime.d.ts +5 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +1 -0
  73. package/dist/types/model/ExecutorProtocol.d.ts +9 -1
  74. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  75. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  76. package/dist/types/model/GraphProcessor.d.ts +7 -4
  77. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  78. package/dist/types/model/ProcessContext.d.ts +36 -2
  79. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  80. package/dist/types/model/UiGraphActionProtocol.d.ts +8 -3
  81. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  82. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  84. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  85. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  86. package/dist/types/model/chat-v2/chatV2Types.d.ts +3 -1
  87. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  88. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  89. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +4 -0
  90. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +10 -0
  91. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +6 -0
  92. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  93. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  94. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  95. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  96. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  97. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  98. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  99. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  100. package/dist/types/utils/index.d.ts +2 -0
  101. package/dist/types/utils/interpolation.d.ts +93 -8
  102. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  103. package/dist/types/utils/jsonPath.d.ts +15 -0
  104. package/dist/types/webAppRuntime.d.ts +8 -2
  105. package/package.json +11 -1
@@ -20,9 +20,26 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/webAppRuntime.ts
21
21
  var webAppRuntime_exports = {};
22
22
  __export(webAppRuntime_exports, {
23
+ IndexedDbWebAppBrowserStorage: () => IndexedDbWebAppBrowserStorage,
23
24
  RIVET_WEB_APP_ACTION_PROTOCOL_VERSION: () => RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
25
+ RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES,
26
+ RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES,
27
+ RIVET_WEB_APP_BROWSER_STORAGE_DATABASE: () => RIVET_WEB_APP_BROWSER_STORAGE_DATABASE,
28
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES,
29
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES,
30
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES,
31
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS: () => RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS,
32
+ RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY: () => RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY,
33
+ RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION: () => RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION,
34
+ RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES,
35
+ RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION: () => RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION,
36
+ RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES: () => RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES,
37
+ RIVET_WEB_APP_LEGACY_RETENTION_MS: () => RIVET_WEB_APP_LEGACY_RETENTION_MS,
38
+ UiGraphBrowserPersistence: () => UiGraphBrowserPersistence,
39
+ WebAppBrowserStoragePersistenceError: () => WebAppBrowserStoragePersistenceError,
24
40
  applyUiGraphStatePatch: () => applyUiGraphStatePatch,
25
41
  applyUiGraphWebAppStorageActionPatch: () => applyUiGraphWebAppStorageActionPatch,
42
+ applyUiGraphWebAppStorageActionPatchAsync: () => applyUiGraphWebAppStorageActionPatchAsync,
26
43
  applyUiGraphWebAppStoragePatch: () => applyUiGraphWebAppStoragePatch,
27
44
  clearUiGraphChatSearchMatches: () => clearUiGraphChatSearchMatches,
28
45
  copyUiGraphText: () => copyUiGraphText,
@@ -32,17 +49,23 @@ __export(webAppRuntime_exports, {
32
49
  createUiGraphChatPinStatePatch: () => createUiGraphChatPinStatePatch,
33
50
  createUiGraphChatSubmissionStatePatch: () => createUiGraphChatSubmissionStatePatch,
34
51
  createUiGraphInteractionController: () => createUiGraphInteractionController,
52
+ decodeRivetWebAppStorageBinaryFrame: () => decodeRivetWebAppStorageBinaryFrame,
53
+ deserializeRivetWebAppStoredValue: () => deserializeRivetWebAppStoredValue,
54
+ deserializeRivetWebAppStoredValuePatch: () => deserializeRivetWebAppStoredValuePatch,
35
55
  downloadUiGraphJsonOutput: () => downloadUiGraphJsonOutput,
56
+ encodeRivetWebAppStorageBinaryFrame: () => encodeRivetWebAppStorageBinaryFrame,
36
57
  enhanceUiGraphChatJsonCodeBlocks: () => enhanceUiGraphChatJsonCodeBlocks,
37
58
  getUiGraphActionState: () => getUiGraphActionState,
38
59
  getUiGraphChatDraftStateKey: () => getUiGraphChatDraftStateKey,
39
60
  getUiGraphChatMessagePresentations: () => getUiGraphChatMessagePresentations,
40
61
  getUiGraphChatMessagesStateKey: () => getUiGraphChatMessagesStateKey,
41
62
  getUiGraphChatPersistentState: () => getUiGraphChatPersistentState,
63
+ getUiGraphChatPinsStateKey: () => getUiGraphChatPinsStateKey,
42
64
  getUiGraphChatStorageKey: () => getUiGraphChatStorageKey,
43
65
  getUiGraphComponentRenderModel: () => getUiGraphComponentRenderModel,
44
66
  getUiGraphJsonOutputFilename: () => getUiGraphJsonOutputFilename,
45
67
  getUiGraphProgressiveJsonOutputChunks: () => getUiGraphProgressiveJsonOutputChunks,
68
+ getUiGraphResponseTraceStorageKey: () => getUiGraphResponseTraceStorageKey,
46
69
  getUiGraphWebAppStorageKey: () => getUiGraphWebAppStorageKey,
47
70
  hasUiGraphChatPersistentStateChanged: () => hasUiGraphChatPersistentStateChanged,
48
71
  highlightUiGraphChatSearchMatches: () => highlightUiGraphChatSearchMatches,
@@ -51,13 +74,18 @@ __export(webAppRuntime_exports, {
51
74
  loadUiGraphResponseTrace: () => loadUiGraphResponseTrace,
52
75
  loadUiGraphWebAppStorage: () => loadUiGraphWebAppStorage,
53
76
  observeUiGraphOutputResizeBounds: () => observeUiGraphOutputResizeBounds,
77
+ parseRivetWebAppBrowserStorageClientMessage: () => parseRivetWebAppBrowserStorageClientMessage,
78
+ parseRivetWebAppBrowserStorageServerMessage: () => parseRivetWebAppBrowserStorageServerMessage,
54
79
  parseRivetWebAppClientMessage: () => parseRivetWebAppClientMessage,
55
80
  parseRivetWebAppServerMessage: () => parseRivetWebAppServerMessage,
56
81
  pruneUiGraphResponseTraces: () => pruneUiGraphResponseTraces,
57
82
  revealUiGraphChatElement: () => revealUiGraphChatElement,
58
83
  revealUiGraphChatSearchMatch: () => revealUiGraphChatSearchMatch,
59
84
  saveUiGraphChatPersistentState: () => saveUiGraphChatPersistentState,
60
- saveUiGraphResponseTrace: () => saveUiGraphResponseTrace
85
+ saveUiGraphResponseTrace: () => saveUiGraphResponseTrace,
86
+ serializeRivetWebAppStoredValue: () => serializeRivetWebAppStoredValue,
87
+ serializeRivetWebAppStoredValuePatch: () => serializeRivetWebAppStoredValuePatch,
88
+ splitRivetWebAppStorageTransfer: () => splitRivetWebAppStorageTransfer
61
89
  });
62
90
  module.exports = __toCommonJS(webAppRuntime_exports);
63
91
 
@@ -114,6 +142,7 @@ function isAgentModelCallTrace(value) {
114
142
  "outcome",
115
143
  "attemptIndex",
116
144
  "profileIndex",
145
+ "profileName",
117
146
  "profileHealthKey",
118
147
  "profileHealthState",
119
148
  "roundIndex",
@@ -122,13 +151,14 @@ function isAgentModelCallTrace(value) {
122
151
  "finishReason",
123
152
  "usage",
124
153
  "pricing"
125
- ]) && typeof value.callId === "string" && typeof value.nodeId === "string" && typeof value.processId === "string" && typeof value.provider === "string" && typeof value.model === "string" && (value.customProviderApi === void 0 || value.customProviderApi === "completions" || value.customProviderApi === "responses") && (value.outcome === "success" || value.outcome === "provider-failure" || value.outcome === "aborted") && isNonNegativeInteger(value.attemptIndex) && isOptionalNonNegativeInteger(value.profileIndex) && isOptionalString(value.profileHealthKey) && (value.profileHealthState === void 0 || value.profileHealthState === "closed" || value.profileHealthState === "open" || value.profileHealthState === "half-open") && isOptionalNonNegativeInteger(value.roundIndex) && isOptionalNonNegativeFiniteNumber(value.startedAt) && isOptionalNonNegativeFiniteNumber(value.durationMs) && isOptionalString(value.finishReason) && (value.usage === void 0 || isAgentTraceUsage(value.usage)) && isAgentTracePricing(value.pricing);
154
+ ]) && typeof value.callId === "string" && typeof value.nodeId === "string" && typeof value.processId === "string" && typeof value.provider === "string" && typeof value.model === "string" && (value.customProviderApi === void 0 || value.customProviderApi === "completions" || value.customProviderApi === "responses") && (value.outcome === "success" || value.outcome === "provider-failure" || value.outcome === "aborted") && isNonNegativeInteger(value.attemptIndex) && isOptionalNonNegativeInteger(value.profileIndex) && isOptionalString(value.profileName) && isOptionalString(value.profileHealthKey) && (value.profileHealthState === void 0 || value.profileHealthState === "closed" || value.profileHealthState === "open" || value.profileHealthState === "half-open") && isOptionalNonNegativeInteger(value.roundIndex) && isOptionalNonNegativeFiniteNumber(value.startedAt) && isOptionalNonNegativeFiniteNumber(value.durationMs) && isOptionalString(value.finishReason) && (value.usage === void 0 || isAgentTraceUsage(value.usage)) && isAgentTracePricing(value.pricing);
126
155
  }
127
156
  function isAgentLLMProfileAttemptTrace(value) {
128
157
  return isRecord(value) && hasOnlyKeys(value, [
129
158
  "eventId",
130
159
  "roundIndex",
131
160
  "profileIndex",
161
+ "profileName",
132
162
  "nodeId",
133
163
  "processId",
134
164
  "provider",
@@ -145,7 +175,7 @@ function isAgentLLMProfileAttemptTrace(value) {
145
175
  "healthOutcome",
146
176
  "retryAt",
147
177
  "timeoutKind"
148
- ]) && typeof value.eventId === "string" && isNonNegativeInteger(value.roundIndex) && isOptionalNonNegativeInteger(value.profileIndex) && typeof value.nodeId === "string" && typeof value.processId === "string" && typeof value.provider === "string" && typeof value.model === "string" && (value.customProviderApi === void 0 || value.customProviderApi === "completions" || value.customProviderApi === "responses") && ["configuration", "request", "response-validation", "health-gate", "health-update"].includes(
178
+ ]) && typeof value.eventId === "string" && isNonNegativeInteger(value.roundIndex) && isOptionalNonNegativeInteger(value.profileIndex) && isOptionalString(value.profileName) && typeof value.nodeId === "string" && typeof value.processId === "string" && typeof value.provider === "string" && typeof value.model === "string" && (value.customProviderApi === void 0 || value.customProviderApi === "completions" || value.customProviderApi === "responses") && ["configuration", "request", "response-validation", "health-gate", "health-update"].includes(
149
179
  String(value.stage)
150
180
  ) && ["success", "failure", "aborted", "skipped"].includes(String(value.outcome)) && isOptionalNonNegativeInteger(value.attemptIndex) && isOptionalNonNegativeFiniteNumber(value.status) && isOptionalString(value.error) && isOptionalString(value.profileHealthKey) && (value.healthState === void 0 || value.healthState === "closed" || value.healthState === "open" || value.healthState === "half-open") && (value.healthDisposition === void 0 || value.healthDisposition === "allow" || value.healthDisposition === "deny" || value.healthDisposition === "fail-open") && (value.healthOutcome === void 0 || value.healthOutcome === "healthy" || value.healthOutcome === "unhealthy" || value.healthOutcome === "ignored") && isOptionalNonNegativeFiniteNumber(value.retryAt) && (value.timeoutKind === void 0 || value.timeoutKind === "first-output" || value.timeoutKind === "stream-inactivity");
151
181
  }
@@ -221,6 +251,826 @@ function isRecord(value) {
221
251
  return typeof value === "object" && value != null && !Array.isArray(value);
222
252
  }
223
253
 
254
+ // src/model/StoredValueStore.ts
255
+ function normalizeRivetStoredValueKey(value) {
256
+ if (typeof value !== "string" || !value.trim()) {
257
+ throw new Error("Stored value key must be a non-empty string.");
258
+ }
259
+ return value;
260
+ }
261
+ function cloneRivetStoredValue(value, label = "Stored value") {
262
+ return clonePortableValue(value, label, /* @__PURE__ */ new Set());
263
+ }
264
+ function cloneRivetStoredValueRecord(value, label = "Stored value record") {
265
+ const cloned = cloneRivetStoredValue(value, label);
266
+ if (!isPlainRecord(cloned)) throw new Error(`${label} must be a JSON object.`);
267
+ for (const key of Object.keys(cloned)) normalizeRivetStoredValueKey(key);
268
+ return cloned;
269
+ }
270
+ function clonePortableValue(value, label, ancestors) {
271
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
272
+ if (typeof value === "number") {
273
+ if (!Number.isFinite(value)) throw new Error(`${label} must contain only finite numbers.`);
274
+ return value;
275
+ }
276
+ if (typeof value !== "object") {
277
+ throw new Error(`${label} must contain only portable JSON values.`);
278
+ }
279
+ if (ancestors.has(value)) throw new Error(`${label} must not contain cycles.`);
280
+ ancestors.add(value);
281
+ try {
282
+ if (Array.isArray(value)) {
283
+ const cloned = [];
284
+ for (let index = 0; index < value.length; index += 1) {
285
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
286
+ throw new Error(`${label} must not contain sparse arrays.`);
287
+ }
288
+ cloned.push(clonePortableValue(value[index], label, ancestors));
289
+ }
290
+ return cloned;
291
+ }
292
+ if (!isPlainRecord(value)) {
293
+ throw new Error(`${label} must contain only plain JSON objects and arrays.`);
294
+ }
295
+ return Object.fromEntries(
296
+ Object.entries(value).map(([key, item]) => [key, clonePortableValue(item, label, ancestors)])
297
+ );
298
+ } finally {
299
+ ancestors.delete(value);
300
+ }
301
+ }
302
+ function isPlainRecord(value) {
303
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
304
+ const prototype = Object.getPrototypeOf(value);
305
+ return prototype === Object.prototype || prototype === null;
306
+ }
307
+
308
+ // src/model/WebAppBrowserStorage.ts
309
+ var RIVET_WEB_APP_BROWSER_STORAGE_DATABASE = "rivet-web-app-browser-storage";
310
+ var RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION = 1;
311
+ var RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES = 256 * 1024;
312
+ var RIVET_WEB_APP_LEGACY_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
313
+ var METADATA_STORE = "metadata";
314
+ var CHUNKS_STORE = "chunks";
315
+ var MIGRATIONS_STORE = "migrations";
316
+ var STAGING_STORE = "staging";
317
+ var RECORD_GENERATION_INDEX = "record-generation";
318
+ var SCHEMA_METADATA_ID = "__rivet_schema__";
319
+ var BROADCAST_CHANNEL_NAME = "rivet-web-app-browser-storage:v1";
320
+ var IndexedDbWebAppBrowserStorage = class {
321
+ #databaseName;
322
+ #factory;
323
+ #now;
324
+ #storageManager;
325
+ #broadcastChannelFactory;
326
+ #listeners = /* @__PURE__ */ new Set();
327
+ #memory = /* @__PURE__ */ new Map();
328
+ #memoryDeleted = /* @__PURE__ */ new Set();
329
+ #memoryOnly = /* @__PURE__ */ new Set();
330
+ #instanceId = createGeneration();
331
+ #knownRevisions = /* @__PURE__ */ new Map();
332
+ #focusListener = () => void this.#recheckRevisions();
333
+ #channel;
334
+ #database;
335
+ #openPromise;
336
+ #scope;
337
+ #scopeId;
338
+ #status = { durable: false, reason: "indexeddb-unavailable" };
339
+ #writeQueue = Promise.resolve();
340
+ #lastRevision = 0;
341
+ constructor(options = {}) {
342
+ this.#databaseName = options.databaseName ?? RIVET_WEB_APP_BROWSER_STORAGE_DATABASE;
343
+ this.#factory = options.indexedDB === void 0 ? getDefaultIndexedDbFactory() : options.indexedDB ?? void 0;
344
+ this.#now = options.now ?? Date.now;
345
+ this.#storageManager = options.storageManager ?? getDefaultStorageManager();
346
+ this.#broadcastChannelFactory = options.broadcastChannelFactory ?? getDefaultBroadcastChannelFactory();
347
+ }
348
+ async initialize(scope) {
349
+ var _a;
350
+ const normalized = normalizeScope(scope);
351
+ const nextScopeId = serializeScope(normalized);
352
+ if (this.#scopeId && this.#scopeId !== nextScopeId) {
353
+ throw new Error("A browser storage instance cannot be reused for another web app scope.");
354
+ }
355
+ this.#scope = normalized;
356
+ this.#scopeId = nextScopeId;
357
+ this.#ensureBroadcastChannel();
358
+ if (!this.#factory) return this.#status;
359
+ try {
360
+ this.#database = await this.#openDatabase();
361
+ await this.#ensureSchemaMetadata();
362
+ this.#status = { durable: true };
363
+ await this.#removeAbandonedStaging();
364
+ (_a = globalThis.addEventListener) == null ? void 0 : _a.call(globalThis, "focus", this.#focusListener);
365
+ } catch {
366
+ this.#status = { durable: false, reason: "open-failed" };
367
+ }
368
+ return this.#status;
369
+ }
370
+ async get(namespace, key) {
371
+ const id = this.#recordId(namespace, key);
372
+ if (this.#memoryDeleted.has(id)) return void 0;
373
+ const memoryValue = this.#memory.get(id);
374
+ if (memoryValue !== void 0) return cloneRivetStoredValue(memoryValue, "Browser stored value");
375
+ if (!this.#database) return void 0;
376
+ const transaction = this.#database.transaction([METADATA_STORE, CHUNKS_STORE], "readonly");
377
+ const metadata = await requestResult(
378
+ transaction.objectStore(METADATA_STORE).get(id)
379
+ );
380
+ if (!metadata) {
381
+ await transactionDone(transaction);
382
+ this.#knownRevisions.set(id, 0);
383
+ return void 0;
384
+ }
385
+ if (metadata.deleted) {
386
+ await transactionDone(transaction);
387
+ this.#memory.delete(id);
388
+ this.#memoryDeleted.add(id);
389
+ this.#knownRevisions.set(id, metadata.revision);
390
+ return void 0;
391
+ }
392
+ const chunks = await requestResult(
393
+ transaction.objectStore(CHUNKS_STORE).index(RECORD_GENERATION_INDEX).getAll(IDBKeyRange.only([id, metadata.generation]))
394
+ );
395
+ await transactionDone(transaction);
396
+ const value = decodeChunks(metadata, chunks);
397
+ this.#memory.set(id, value);
398
+ this.#knownRevisions.set(id, metadata.revision);
399
+ return cloneRivetStoredValue(value, "Browser stored value");
400
+ }
401
+ async list(namespace) {
402
+ const scopeId = this.#requireScope();
403
+ const entries = /* @__PURE__ */ new Map();
404
+ const database = this.#database;
405
+ if (database) {
406
+ const transaction = database.transaction([METADATA_STORE, CHUNKS_STORE], "readonly");
407
+ const records = (await requestResult(transaction.objectStore(METADATA_STORE).getAll())).filter(isStoredRecordMetadata).filter((metadata) => metadata.scopeId === scopeId && metadata.namespace === namespace && !metadata.deleted).sort((left, right) => left.key.localeCompare(right.key));
408
+ for (const metadata of records) {
409
+ if (this.#memoryDeleted.has(metadata.id)) continue;
410
+ const memoryValue = this.#memory.get(metadata.id);
411
+ if (memoryValue !== void 0) {
412
+ entries.set(metadata.key, cloneRivetStoredValue(memoryValue, "Browser stored value"));
413
+ continue;
414
+ }
415
+ const chunks = await requestResult(
416
+ transaction.objectStore(CHUNKS_STORE).index(RECORD_GENERATION_INDEX).getAll(IDBKeyRange.only([metadata.id, metadata.generation]))
417
+ );
418
+ const value = decodeChunks(metadata, chunks);
419
+ this.#memory.set(metadata.id, value);
420
+ this.#knownRevisions.set(metadata.id, metadata.revision);
421
+ entries.set(metadata.key, cloneRivetStoredValue(value, "Browser stored value"));
422
+ }
423
+ await transactionDone(transaction);
424
+ }
425
+ const prefix = `${scopeId}\0${namespace}\0`;
426
+ for (const [id, value] of this.#memory) {
427
+ if (!id.startsWith(prefix) || this.#memoryDeleted.has(id)) continue;
428
+ entries.set(id.slice(prefix.length), cloneRivetStoredValue(value, "Browser stored value"));
429
+ }
430
+ return [...entries].sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => ({ key, value }));
431
+ }
432
+ async set(namespace, key, value) {
433
+ return await this.commitBatch([{ key, namespace, value }]);
434
+ }
435
+ async delete(namespace, key) {
436
+ return await this.commitBatch([{ key, namespace }]);
437
+ }
438
+ async commitBatch(changes) {
439
+ this.#requireScope();
440
+ if (changes.length === 0) return { ...this.#status, revision: this.#now() };
441
+ const prepared = changes.map((change) => prepareChange(this.#recordId(change.namespace, change.key), change));
442
+ if (new Set(prepared.map((change) => change.id)).size !== prepared.length) {
443
+ throw new Error("A browser storage batch cannot change the same scoped key more than once.");
444
+ }
445
+ for (const change of prepared) {
446
+ if (change.serialized) {
447
+ const parsed = cloneRivetStoredValue(
448
+ JSON.parse(new TextDecoder().decode(change.serialized)),
449
+ "Browser stored value"
450
+ );
451
+ this.#memory.set(change.id, parsed);
452
+ this.#memoryDeleted.delete(change.id);
453
+ } else {
454
+ this.#memory.delete(change.id);
455
+ this.#memoryDeleted.add(change.id);
456
+ }
457
+ }
458
+ const revision = this.#nextRevision();
459
+ try {
460
+ let committedRevision = revision;
461
+ await this.#enqueueWrite(async () => {
462
+ if (!this.#database) throw new Error("IndexedDB is unavailable.");
463
+ committedRevision = await this.#commitPreparedChanges(prepared, revision);
464
+ });
465
+ this.#lastRevision = Math.max(this.#lastRevision, committedRevision);
466
+ for (const change of prepared) {
467
+ this.#memoryOnly.delete(change.id);
468
+ this.#knownRevisions.set(change.id, committedRevision);
469
+ this.#publishChange(change.namespace, change.key, committedRevision);
470
+ }
471
+ this.#status = this.#memoryOnly.size === 0 ? { durable: true } : { durable: false, reason: "write-failed" };
472
+ return {
473
+ durable: true,
474
+ ...this.#memoryOnly.size > 0 ? { hasMemoryOnlyRecords: true } : {},
475
+ revision: committedRevision
476
+ };
477
+ } catch (error) {
478
+ for (const change of prepared) this.#memoryOnly.add(change.id);
479
+ this.#status = { durable: false, reason: "write-failed" };
480
+ throw new WebAppBrowserStoragePersistenceError(
481
+ "Browser data could not be saved. Changes will last only until this page is closed.",
482
+ { cause: error, revision }
483
+ );
484
+ }
485
+ }
486
+ subscribe(listener) {
487
+ this.#listeners.add(listener);
488
+ return () => this.#listeners.delete(listener);
489
+ }
490
+ hasMemoryOnlyRecord(namespace, key) {
491
+ return this.#memoryOnly.has(this.#recordId(namespace, key));
492
+ }
493
+ async estimateUsage() {
494
+ if (!this.#storageManager) return {};
495
+ try {
496
+ const estimate = await this.#storageManager.estimate();
497
+ return {
498
+ ...typeof estimate.quota === "number" ? { quota: estimate.quota } : {},
499
+ ...typeof estimate.usage === "number" ? { usage: estimate.usage } : {}
500
+ };
501
+ } catch {
502
+ return {};
503
+ }
504
+ }
505
+ dispose() {
506
+ var _a, _b, _c;
507
+ (_a = this.#channel) == null ? void 0 : _a.close();
508
+ (_b = globalThis.removeEventListener) == null ? void 0 : _b.call(globalThis, "focus", this.#focusListener);
509
+ this.#channel = void 0;
510
+ (_c = this.#database) == null ? void 0 : _c.close();
511
+ this.#database = void 0;
512
+ this.#openPromise = void 0;
513
+ this.#listeners.clear();
514
+ this.#knownRevisions.clear();
515
+ this.#memoryDeleted.clear();
516
+ this.#memoryOnly.clear();
517
+ }
518
+ async getMigration(legacyKey) {
519
+ const scopeId = this.#requireScope();
520
+ if (!this.#database) return void 0;
521
+ const id = migrationId(scopeId, legacyKey);
522
+ const transaction = this.#database.transaction(MIGRATIONS_STORE, "readonly");
523
+ const migration = await requestResult(
524
+ transaction.objectStore(MIGRATIONS_STORE).get(id)
525
+ );
526
+ await transactionDone(transaction);
527
+ if (!migration) return void 0;
528
+ return {
529
+ cleanupAfter: migration.cleanupAfter,
530
+ completedAt: migration.completedAt,
531
+ key: migration.key,
532
+ legacyKey: migration.legacyKey,
533
+ namespace: migration.namespace
534
+ };
535
+ }
536
+ async recordMigration(migration) {
537
+ const scopeId = this.#requireScope();
538
+ if (!this.#database) throw new Error("IndexedDB is unavailable.");
539
+ const transaction = this.#database.transaction(MIGRATIONS_STORE, "readwrite");
540
+ transaction.objectStore(MIGRATIONS_STORE).put({
541
+ ...migration,
542
+ id: migrationId(scopeId, migration.legacyKey),
543
+ scopeId
544
+ });
545
+ await transactionDone(transaction);
546
+ }
547
+ async listMigrations() {
548
+ const scopeId = this.#requireScope();
549
+ if (!this.#database) return [];
550
+ const transaction = this.#database.transaction(MIGRATIONS_STORE, "readonly");
551
+ const migrations = await requestResult(transaction.objectStore(MIGRATIONS_STORE).getAll());
552
+ await transactionDone(transaction);
553
+ return migrations.filter((migration) => migration.scopeId === scopeId).map(({ cleanupAfter, completedAt, key, legacyKey, namespace }) => ({
554
+ cleanupAfter,
555
+ completedAt,
556
+ key,
557
+ legacyKey,
558
+ namespace
559
+ }));
560
+ }
561
+ #recordId(namespace, key) {
562
+ const scopeId = this.#requireScope();
563
+ if (!key) throw new Error("Browser storage key cannot be empty.");
564
+ return `${scopeId}\0${namespace}\0${key}`;
565
+ }
566
+ #requireScope() {
567
+ if (!this.#scopeId || !this.#scope) throw new Error("Browser storage must be initialized before use.");
568
+ return this.#scopeId;
569
+ }
570
+ async #openDatabase() {
571
+ if (this.#database) return this.#database;
572
+ if (this.#openPromise) return await this.#openPromise;
573
+ if (!this.#factory) throw new Error("IndexedDB is unavailable.");
574
+ this.#openPromise = new Promise((resolve, reject) => {
575
+ const request = this.#factory.open(this.#databaseName, RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION);
576
+ request.onupgradeneeded = () => {
577
+ const database = request.result;
578
+ if (!database.objectStoreNames.contains(METADATA_STORE)) {
579
+ database.createObjectStore(METADATA_STORE, { keyPath: "id" });
580
+ }
581
+ if (!database.objectStoreNames.contains(CHUNKS_STORE)) {
582
+ const chunks = database.createObjectStore(CHUNKS_STORE, {
583
+ keyPath: ["recordId", "generation", "index"]
584
+ });
585
+ chunks.createIndex(RECORD_GENERATION_INDEX, ["recordId", "generation"]);
586
+ }
587
+ if (!database.objectStoreNames.contains(MIGRATIONS_STORE)) {
588
+ database.createObjectStore(MIGRATIONS_STORE, { keyPath: "id" });
589
+ }
590
+ if (!database.objectStoreNames.contains(STAGING_STORE)) {
591
+ database.createObjectStore(STAGING_STORE, { keyPath: "id" });
592
+ }
593
+ };
594
+ request.onerror = () => reject(request.error ?? new Error("Failed to open IndexedDB."));
595
+ request.onblocked = () => reject(new Error("IndexedDB upgrade was blocked by another page."));
596
+ request.onsuccess = () => {
597
+ const database = request.result;
598
+ database.onversionchange = () => database.close();
599
+ resolve(database);
600
+ };
601
+ });
602
+ try {
603
+ return await this.#openPromise;
604
+ } finally {
605
+ this.#openPromise = void 0;
606
+ }
607
+ }
608
+ async #ensureSchemaMetadata() {
609
+ if (!this.#database) return;
610
+ const transaction = this.#database.transaction(METADATA_STORE, "readwrite");
611
+ transaction.objectStore(METADATA_STORE).put({
612
+ id: SCHEMA_METADATA_ID,
613
+ schemaVersion: RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION,
614
+ updatedAt: this.#now()
615
+ });
616
+ await transactionDone(transaction);
617
+ }
618
+ async #commitPreparedChanges(prepared, revision) {
619
+ var _a, _b;
620
+ const database = this.#database;
621
+ const generation = createGeneration();
622
+ const staged = prepared.filter((change) => change.serialized != null);
623
+ if (staged.length > 0) {
624
+ const stageTransaction = database.transaction([CHUNKS_STORE, STAGING_STORE], "readwrite");
625
+ const chunksStore = stageTransaction.objectStore(CHUNKS_STORE);
626
+ const stagingStore2 = stageTransaction.objectStore(STAGING_STORE);
627
+ for (const change of staged) {
628
+ const stagingId = `${change.id}\0${generation}`;
629
+ stagingStore2.put({
630
+ createdAt: this.#now(),
631
+ generation,
632
+ id: stagingId,
633
+ recordId: change.id
634
+ });
635
+ change.chunks.forEach((bytes, index2) => {
636
+ chunksStore.put({ bytes, generation, index: index2, recordId: change.id });
637
+ });
638
+ }
639
+ await transactionDone(stageTransaction);
640
+ const validationTransaction = database.transaction(CHUNKS_STORE, "readonly");
641
+ const index = validationTransaction.objectStore(CHUNKS_STORE).index(RECORD_GENERATION_INDEX);
642
+ for (const change of staged) {
643
+ const chunks = await requestResult(index.getAll(IDBKeyRange.only([change.id, generation])));
644
+ decodeChunks(
645
+ {
646
+ byteLength: change.serialized.byteLength,
647
+ chunkCount: change.chunks.length,
648
+ generation,
649
+ id: change.id,
650
+ key: change.key,
651
+ namespace: change.namespace,
652
+ revision,
653
+ scopeId: this.#scopeId,
654
+ updatedAt: this.#now()
655
+ },
656
+ chunks
657
+ );
658
+ }
659
+ await transactionDone(validationTransaction);
660
+ }
661
+ const switchTransaction = database.transaction([METADATA_STORE, STAGING_STORE], "readwrite");
662
+ const metadataStore = switchTransaction.objectStore(METADATA_STORE);
663
+ const stagingStore = switchTransaction.objectStore(STAGING_STORE);
664
+ const previous = [];
665
+ const priorRecords = [];
666
+ for (const change of prepared) {
667
+ const prior = await requestResult(metadataStore.get(change.id));
668
+ if (prior) {
669
+ priorRecords.push(prior);
670
+ if (!prior.deleted) previous.push(prior);
671
+ }
672
+ }
673
+ const committedRevision = Math.max(revision, ...priorRecords.map((prior) => prior.revision + 1));
674
+ for (const change of prepared) {
675
+ const base = {
676
+ byteLength: ((_a = change.serialized) == null ? void 0 : _a.byteLength) ?? 0,
677
+ chunkCount: ((_b = change.serialized) == null ? void 0 : _b.byteLength) == null ? 0 : change.chunks.length,
678
+ deleted: change.serialized == null,
679
+ generation,
680
+ id: change.id,
681
+ key: change.key,
682
+ namespace: change.namespace,
683
+ revision: committedRevision,
684
+ scopeId: this.#scopeId,
685
+ updatedAt: this.#now()
686
+ };
687
+ metadataStore.put(base);
688
+ if (change.serialized) stagingStore.delete(`${change.id}\0${generation}`);
689
+ }
690
+ await transactionDone(switchTransaction);
691
+ void Promise.all(previous.map((metadata) => this.#deleteGeneration(metadata.id, metadata.generation))).catch(
692
+ () => void 0
693
+ );
694
+ return committedRevision;
695
+ }
696
+ async #deleteGeneration(recordId, generation) {
697
+ if (!this.#database) return;
698
+ const transaction = this.#database.transaction(CHUNKS_STORE, "readwrite");
699
+ const index = transaction.objectStore(CHUNKS_STORE).index(RECORD_GENERATION_INDEX);
700
+ const keys = await requestResult(index.getAllKeys(IDBKeyRange.only([recordId, generation])));
701
+ const store = transaction.objectStore(CHUNKS_STORE);
702
+ for (const key of keys) store.delete(key);
703
+ await transactionDone(transaction);
704
+ }
705
+ async #removeAbandonedStaging() {
706
+ if (!this.#database) return;
707
+ const transaction = this.#database.transaction(STAGING_STORE, "readwrite");
708
+ const staging = await requestResult(transaction.objectStore(STAGING_STORE).getAll());
709
+ const store = transaction.objectStore(STAGING_STORE);
710
+ const abandoned = staging.filter((record) => this.#now() - record.createdAt >= 5 * 60 * 1e3);
711
+ for (const record of abandoned) store.delete(record.id);
712
+ await transactionDone(transaction);
713
+ await Promise.all(abandoned.map((record) => this.#deleteGeneration(record.recordId, record.generation)));
714
+ }
715
+ #ensureBroadcastChannel() {
716
+ if (this.#channel || !this.#broadcastChannelFactory) return;
717
+ try {
718
+ this.#channel = this.#broadcastChannelFactory(BROADCAST_CHANNEL_NAME);
719
+ this.#channel.onmessage = (event) => {
720
+ const message = parseBroadcastMessage(event.data);
721
+ if (!message || message.sourceId === this.#instanceId || message.scopeId !== this.#scopeId) return;
722
+ void this.#enqueueWrite(async () => {
723
+ const id = this.#recordId(message.namespace, message.key);
724
+ if (this.#memoryOnly.has(id)) return;
725
+ const knownRevision = this.#knownRevisions.get(id);
726
+ if (knownRevision !== void 0 && message.revision <= knownRevision) return;
727
+ this.#memory.delete(id);
728
+ this.#memoryDeleted.delete(id);
729
+ this.#knownRevisions.set(id, message.revision);
730
+ const change = { key: message.key, namespace: message.namespace, revision: message.revision };
731
+ for (const listener of this.#listeners) listener(change);
732
+ });
733
+ };
734
+ } catch {
735
+ this.#channel = void 0;
736
+ }
737
+ }
738
+ #publishChange(namespace, key, revision) {
739
+ var _a;
740
+ const change = { key, namespace, revision };
741
+ try {
742
+ (_a = this.#channel) == null ? void 0 : _a.postMessage({
743
+ ...change,
744
+ scopeId: this.#scopeId,
745
+ sourceId: this.#instanceId,
746
+ type: "record-changed"
747
+ });
748
+ } catch {
749
+ }
750
+ }
751
+ async #enqueueWrite(operation) {
752
+ const result = this.#writeQueue.catch(() => void 0).then(operation);
753
+ this.#writeQueue = result.catch(() => void 0);
754
+ await result;
755
+ }
756
+ #nextRevision() {
757
+ this.#lastRevision = Math.max(this.#lastRevision + 1, this.#now());
758
+ return this.#lastRevision;
759
+ }
760
+ async #recheckRevisions() {
761
+ if (!this.#database || !this.#scopeId) return;
762
+ await this.#enqueueWrite(async () => {
763
+ if (!this.#database || !this.#scopeId) return;
764
+ const transaction = this.#database.transaction(METADATA_STORE, "readonly");
765
+ const records = (await requestResult(transaction.objectStore(METADATA_STORE).getAll())).filter(
766
+ isStoredRecordMetadata
767
+ );
768
+ await transactionDone(transaction);
769
+ for (const metadata of records) {
770
+ if (metadata.scopeId !== this.#scopeId) continue;
771
+ if (this.#memoryOnly.has(metadata.id)) continue;
772
+ const knownRevision = this.#knownRevisions.get(metadata.id);
773
+ if (knownRevision !== void 0 && metadata.revision <= knownRevision) continue;
774
+ this.#memory.delete(metadata.id);
775
+ this.#memoryDeleted.delete(metadata.id);
776
+ this.#knownRevisions.set(metadata.id, metadata.revision);
777
+ const change = {
778
+ key: metadata.key,
779
+ namespace: metadata.namespace,
780
+ revision: metadata.revision
781
+ };
782
+ for (const listener of this.#listeners) listener(change);
783
+ }
784
+ }).catch(() => void 0);
785
+ }
786
+ };
787
+ var WebAppBrowserStoragePersistenceError = class extends Error {
788
+ revision;
789
+ constructor(message, options) {
790
+ super(message, options);
791
+ this.name = "WebAppBrowserStoragePersistenceError";
792
+ this.revision = options.revision;
793
+ }
794
+ };
795
+ function prepareChange(id, change) {
796
+ if (!change.key) throw new Error("Browser storage key cannot be empty.");
797
+ if (change.value === void 0) {
798
+ return { chunks: [], id, key: change.key, namespace: change.namespace };
799
+ }
800
+ const portable = cloneRivetStoredValue(change.value, "Browser stored value");
801
+ const serialized = new TextEncoder().encode(JSON.stringify(portable));
802
+ const chunks = [];
803
+ for (let offset = 0; offset < serialized.byteLength; offset += RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES) {
804
+ const chunk = serialized.slice(
805
+ offset,
806
+ Math.min(serialized.byteLength, offset + RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES)
807
+ );
808
+ chunks.push(chunk.buffer);
809
+ }
810
+ if (chunks.length === 0) chunks.push(new ArrayBuffer(0));
811
+ return { chunks, id, key: change.key, namespace: change.namespace, serialized };
812
+ }
813
+ function decodeChunks(metadata, chunks) {
814
+ if (chunks.length !== metadata.chunkCount) throw new Error("Browser storage record is incomplete.");
815
+ chunks.sort((left, right) => left.index - right.index);
816
+ const bytes = new Uint8Array(metadata.byteLength);
817
+ let offset = 0;
818
+ for (let index = 0; index < chunks.length; index += 1) {
819
+ const chunk = chunks[index];
820
+ if (chunk.index !== index) throw new Error("Browser storage record has invalid chunk ordering.");
821
+ const source = new Uint8Array(chunk.bytes);
822
+ if (offset + source.byteLength > bytes.byteLength) throw new Error("Browser storage record exceeds its metadata.");
823
+ bytes.set(source, offset);
824
+ offset += source.byteLength;
825
+ }
826
+ if (offset !== metadata.byteLength)
827
+ throw new Error("Browser storage record byte length does not match its metadata.");
828
+ return cloneRivetStoredValue(JSON.parse(new TextDecoder().decode(bytes)), "Browser stored value");
829
+ }
830
+ function isStoredRecordMetadata(value) {
831
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
832
+ const metadata = value;
833
+ return typeof metadata.id === "string" && metadata.id !== SCHEMA_METADATA_ID && typeof metadata.scopeId === "string" && typeof metadata.key === "string" && (metadata.namespace === "chat-state" || metadata.namespace === "response-traces" || metadata.namespace === "stored-values") && typeof metadata.revision === "number" && typeof metadata.generation === "string" && typeof metadata.byteLength === "number" && typeof metadata.chunkCount === "number";
834
+ }
835
+ function normalizeScope(scope) {
836
+ if (!scope.origin) throw new Error("Browser storage origin cannot be empty.");
837
+ if (!scope.uiGraphId) throw new Error("Browser storage UI graph id cannot be empty.");
838
+ const pathname = scope.pathname.replace(/\/+$/, "") || "/";
839
+ return { origin: scope.origin, pathname, uiGraphId: scope.uiGraphId };
840
+ }
841
+ function serializeScope(scope) {
842
+ return [
843
+ encodeURIComponent(scope.origin),
844
+ encodeURIComponent(scope.pathname),
845
+ encodeURIComponent(scope.uiGraphId)
846
+ ].join(":");
847
+ }
848
+ function migrationId(scopeId, legacyKey) {
849
+ return `${scopeId}\0${legacyKey}`;
850
+ }
851
+ function createGeneration() {
852
+ var _a, _b;
853
+ return ((_b = (_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) == null ? void 0 : _b.call(_a)) ?? `rivet-${Date.now()}-${Math.random().toString(36).slice(2)}`;
854
+ }
855
+ function getDefaultIndexedDbFactory() {
856
+ var _a;
857
+ try {
858
+ return globalThis.indexedDB ?? ((_a = globalThis.window) == null ? void 0 : _a.indexedDB);
859
+ } catch {
860
+ return void 0;
861
+ }
862
+ }
863
+ function getDefaultStorageManager() {
864
+ var _a;
865
+ try {
866
+ return (_a = globalThis.navigator) == null ? void 0 : _a.storage;
867
+ } catch {
868
+ return void 0;
869
+ }
870
+ }
871
+ function getDefaultBroadcastChannelFactory() {
872
+ try {
873
+ return typeof globalThis.BroadcastChannel === "function" ? (name) => new BroadcastChannel(name) : void 0;
874
+ } catch {
875
+ return void 0;
876
+ }
877
+ }
878
+ function parseBroadcastMessage(value) {
879
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
880
+ const message = value;
881
+ return message.type === "record-changed" && typeof message.scopeId === "string" && typeof message.sourceId === "string" && typeof message.key === "string" && (message.namespace === "chat-state" || message.namespace === "response-traces" || message.namespace === "stored-values") && Number.isSafeInteger(message.revision) && Number(message.revision) > 0 ? message : void 0;
882
+ }
883
+ function requestResult(request) {
884
+ return new Promise((resolve, reject) => {
885
+ request.onsuccess = () => resolve(request.result);
886
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed."));
887
+ });
888
+ }
889
+ function transactionDone(transaction) {
890
+ return new Promise((resolve, reject) => {
891
+ transaction.oncomplete = () => resolve();
892
+ transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB transaction failed."));
893
+ transaction.onabort = () => reject(transaction.error ?? new Error("IndexedDB transaction was aborted."));
894
+ });
895
+ }
896
+
897
+ // src/model/WebAppBrowserStorageRpc.ts
898
+ var RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY = "browser-storage-rpc-v2";
899
+ var RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION = 2;
900
+ var RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES = 4 * 1024 * 1024;
901
+ var RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES = 256 * 1024 * 1024;
902
+ var RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES = 512 * 1024 * 1024;
903
+ var RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES = 512 * 1024 * 1024;
904
+ var RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS = 6e4;
905
+ var RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES = 256 * 1024;
906
+ var RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES = 40;
907
+ var FRAME_MAGIC = new Uint8Array([82, 86, 66, 83]);
908
+ function parseRivetWebAppBrowserStorageClientMessage(value) {
909
+ if (!isRecord2(value) || !hasActionIds(value) || typeof value.type !== "string") return void 0;
910
+ if (!isUuid(value.storageSessionId)) return void 0;
911
+ if (value.type === "storage.transfer.start") {
912
+ return isNonEmptyString(value.storageRequestId) && isUuid(value.transferId) && isSafeByteLength(value.byteLength) && isSafeChunkCount(value.chunkCount) && typeof value.found === "boolean" ? {
913
+ type: value.type,
914
+ requestId: value.requestId,
915
+ runId: value.runId,
916
+ storageSessionId: value.storageSessionId,
917
+ storageRequestId: value.storageRequestId,
918
+ transferId: value.transferId,
919
+ byteLength: value.byteLength,
920
+ chunkCount: value.chunkCount,
921
+ found: value.found
922
+ } : void 0;
923
+ }
924
+ if (value.type === "storage.commit.ack") {
925
+ return isUuid(value.transferId) ? {
926
+ type: value.type,
927
+ requestId: value.requestId,
928
+ runId: value.runId,
929
+ storageSessionId: value.storageSessionId,
930
+ transferId: value.transferId
931
+ } : void 0;
932
+ }
933
+ if (value.type === "storage.error") return parseStorageError(value);
934
+ return void 0;
935
+ }
936
+ function parseRivetWebAppBrowserStorageServerMessage(value) {
937
+ if (!isRecord2(value) || !hasActionIds(value) || typeof value.type !== "string") return void 0;
938
+ if (!isUuid(value.storageSessionId)) return void 0;
939
+ if (value.type === "storage.get") {
940
+ return isNonEmptyString(value.storageRequestId) && typeof value.key === "string" && value.key.length > 0 ? {
941
+ type: value.type,
942
+ requestId: value.requestId,
943
+ runId: value.runId,
944
+ storageSessionId: value.storageSessionId,
945
+ storageRequestId: value.storageRequestId,
946
+ key: value.key
947
+ } : void 0;
948
+ }
949
+ if (value.type === "storage.transfer.ack") {
950
+ return isNonEmptyString(value.storageRequestId) && isUuid(value.transferId) ? {
951
+ type: value.type,
952
+ requestId: value.requestId,
953
+ runId: value.runId,
954
+ storageSessionId: value.storageSessionId,
955
+ storageRequestId: value.storageRequestId,
956
+ transferId: value.transferId
957
+ } : void 0;
958
+ }
959
+ if (value.type === "storage.commit.start") {
960
+ return isUuid(value.transferId) && isSafeByteLength(value.byteLength) && isSafeChunkCount(value.chunkCount) ? {
961
+ type: value.type,
962
+ requestId: value.requestId,
963
+ runId: value.runId,
964
+ storageSessionId: value.storageSessionId,
965
+ transferId: value.transferId,
966
+ byteLength: value.byteLength,
967
+ chunkCount: value.chunkCount
968
+ } : void 0;
969
+ }
970
+ if (value.type === "storage.error") return parseStorageError(value);
971
+ return void 0;
972
+ }
973
+ function serializeRivetWebAppStoredValue(value) {
974
+ return new TextEncoder().encode(JSON.stringify(value));
975
+ }
976
+ function deserializeRivetWebAppStoredValue(bytes) {
977
+ return cloneRivetStoredValue(JSON.parse(new TextDecoder().decode(bytes)), "Browser Stored Value transfer");
978
+ }
979
+ function serializeRivetWebAppStoredValuePatch(patch) {
980
+ return new TextEncoder().encode(JSON.stringify(patch));
981
+ }
982
+ function deserializeRivetWebAppStoredValuePatch(bytes) {
983
+ return cloneRivetStoredValueRecord(
984
+ JSON.parse(new TextDecoder().decode(bytes)),
985
+ "Browser Stored Value commit"
986
+ );
987
+ }
988
+ function splitRivetWebAppStorageTransfer(bytes) {
989
+ if (bytes.byteLength === 0) return [];
990
+ const chunks = [];
991
+ for (let offset = 0; offset < bytes.byteLength; offset += RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES) {
992
+ chunks.push(
993
+ bytes.slice(offset, Math.min(bytes.byteLength, offset + RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES))
994
+ );
995
+ }
996
+ return chunks;
997
+ }
998
+ function encodeRivetWebAppStorageBinaryFrame(storageSessionId, transferId, chunkIndex, bytes) {
999
+ const sessionUuid = uuidToBytes(storageSessionId);
1000
+ const transferUuid = uuidToBytes(transferId);
1001
+ if (!Number.isSafeInteger(chunkIndex) || chunkIndex < 0 || chunkIndex > 4294967295) {
1002
+ throw new RangeError("Storage transfer chunk index is invalid.");
1003
+ }
1004
+ const frame = new Uint8Array(RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES + bytes.byteLength);
1005
+ frame.set(FRAME_MAGIC, 0);
1006
+ frame.set(sessionUuid, 4);
1007
+ frame.set(transferUuid, 20);
1008
+ new DataView(frame.buffer).setUint32(36, chunkIndex, false);
1009
+ frame.set(bytes, RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES);
1010
+ return frame;
1011
+ }
1012
+ function decodeRivetWebAppStorageBinaryFrame(frame) {
1013
+ const source = frame instanceof ArrayBuffer ? new Uint8Array(frame) : new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);
1014
+ if (source.byteLength < RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES) return void 0;
1015
+ for (let index = 0; index < FRAME_MAGIC.length; index += 1) {
1016
+ if (source[index] !== FRAME_MAGIC[index]) return void 0;
1017
+ }
1018
+ return {
1019
+ storageSessionId: bytesToUuid(source.slice(4, 20)),
1020
+ transferId: bytesToUuid(source.slice(20, 36)),
1021
+ chunkIndex: new DataView(
1022
+ source.buffer,
1023
+ source.byteOffset,
1024
+ RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES
1025
+ ).getUint32(36, false),
1026
+ bytes: source.slice(RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES)
1027
+ };
1028
+ }
1029
+ function parseStorageError(value) {
1030
+ return isStorageErrorCode(value.code) && typeof value.error === "string" && typeof value.retryable === "boolean" ? {
1031
+ type: "storage.error",
1032
+ requestId: value.requestId,
1033
+ runId: value.runId,
1034
+ storageSessionId: value.storageSessionId,
1035
+ code: value.code,
1036
+ error: value.error,
1037
+ retryable: value.retryable,
1038
+ ...isNonEmptyString(value.storageRequestId) ? { storageRequestId: value.storageRequestId } : {},
1039
+ ...isUuid(value.transferId) ? { transferId: value.transferId } : {}
1040
+ } : void 0;
1041
+ }
1042
+ function hasActionIds(value) {
1043
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.runId);
1044
+ }
1045
+ function isStorageErrorCode(value) {
1046
+ return value === "storage_unavailable" || value === "storage_invalid" || value === "storage_too_large" || value === "storage_capacity";
1047
+ }
1048
+ function isSafeByteLength(value) {
1049
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1050
+ }
1051
+ function isSafeChunkCount(value) {
1052
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1053
+ }
1054
+ function isUuid(value) {
1055
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
1056
+ }
1057
+ function uuidToBytes(value) {
1058
+ if (!isUuid(value)) throw new Error("Storage transfer ID must be a UUID.");
1059
+ return Uint8Array.from(
1060
+ value.replaceAll("-", "").match(/.{2}/g).map((part) => Number.parseInt(part, 16))
1061
+ );
1062
+ }
1063
+ function bytesToUuid(value) {
1064
+ const hex = [...value].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1065
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1066
+ }
1067
+ function isRecord2(value) {
1068
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1069
+ }
1070
+ function isNonEmptyString(value) {
1071
+ return typeof value === "string" && value.length > 0;
1072
+ }
1073
+
224
1074
  // src/utils/newId.ts
225
1075
  var import_non_secure = require("nanoid/non-secure");
226
1076
 
@@ -973,123 +1823,27 @@ function applyUiGraphStatePatch(state, statePatch) {
973
1823
  return statePatch ? { ...state, ...statePatch } : state;
974
1824
  }
975
1825
 
976
- // src/model/UiGraphActionProtocol.ts
977
- var RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1;
978
- function parseRivetWebAppClientMessage(value) {
979
- if (!isRecord2(value) || typeof value.type !== "string") return void 0;
980
- switch (value.type) {
981
- case "client.hello":
982
- return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? { type: value.type, protocolVersion: value.protocolVersion } : void 0;
983
- case "action.start":
984
- return isNonEmptyString(value.requestId) && isNonEmptyString(value.componentId) && isRecord2(value.state) && (value.storage == null || isRecord2(value.storage)) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
985
- type: value.type,
986
- requestId: value.requestId,
987
- componentId: value.componentId,
988
- state: value.state,
989
- ...isRecord2(value.storage) ? { storage: value.storage } : {},
990
- ...typeof value.revisionKey === "string" ? { revisionKey: value.revisionKey } : {}
991
- } : void 0;
992
- case "action.cancel":
993
- return isNonEmptyString(value.runId) ? { type: value.type, runId: value.runId } : void 0;
994
- case "run.resume":
995
- return isNonEmptyString(value.runId) && typeof value.lastSequence === "number" && Number.isSafeInteger(value.lastSequence) && value.lastSequence >= 0 ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence } : void 0;
996
- default:
997
- return void 0;
998
- }
999
- }
1000
- function parseRivetWebAppServerMessage(value) {
1001
- if (!isRecord2(value) || typeof value.type !== "string") return void 0;
1002
- if (value.type === "server.ready") {
1003
- return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? { type: value.type, protocolVersion: value.protocolVersion } : void 0;
1004
- }
1005
- if (value.type === "server.draining") return { type: value.type };
1006
- if (value.type === "action.rejected") {
1007
- return isNonEmptyString(value.requestId) && isNonEmptyString(value.error) ? {
1008
- type: value.type,
1009
- requestId: value.requestId,
1010
- error: value.error,
1011
- ...typeof value.code === "string" ? { code: value.code } : {}
1012
- } : void 0;
1013
- }
1014
- if (value.type === "run.rejected") {
1015
- return isNonEmptyString(value.runId) && isNonEmptyString(value.error) ? {
1016
- type: value.type,
1017
- runId: value.runId,
1018
- error: value.error,
1019
- ...typeof value.code === "string" ? { code: value.code } : {}
1020
- } : void 0;
1021
- }
1022
- if (!hasRunEventBase(value)) return void 0;
1023
- const base = {
1024
- requestId: value.requestId,
1025
- runId: value.runId,
1026
- sequence: value.sequence
1027
- };
1028
- switch (value.type) {
1029
- case "action.accepted":
1030
- case "action.cancelled":
1031
- return { type: value.type, ...base };
1032
- case "action.progress": {
1033
- if (!isRecord2(value.progress)) return void 0;
1034
- const progress = normalizeGraphProgress({
1035
- message: typeof value.progress.message === "string" ? value.progress.message : void 0,
1036
- percent: typeof value.progress.percent === "number" ? value.progress.percent : void 0
1037
- });
1038
- return progress ? { type: value.type, ...base, progress } : void 0;
1039
- }
1040
- case "action.completed":
1041
- return isRecord2(value.statePatch) && (value.storagePatch == null || isRecord2(value.storagePatch)) ? {
1042
- type: value.type,
1043
- ...base,
1044
- statePatch: value.statePatch,
1045
- ...isRecord2(value.storagePatch) ? { storagePatch: value.storagePatch } : {},
1046
- ...isAgentResponseTrace(value.responseTrace) ? { responseTrace: value.responseTrace } : {}
1047
- } : void 0;
1048
- case "action.failed":
1049
- return isNonEmptyString(value.error) ? {
1050
- type: value.type,
1051
- ...base,
1052
- error: value.error,
1053
- ...typeof value.code === "string" ? { code: value.code } : {},
1054
- ...isAgentResponseTrace(value.responseTrace) ? { responseTrace: value.responseTrace } : {}
1055
- } : void 0;
1056
- case "action.interrupted":
1057
- return isNonEmptyString(value.error) ? { type: value.type, ...base, error: value.error } : void 0;
1058
- default:
1059
- return void 0;
1060
- }
1061
- }
1062
- function hasRunEventBase(value) {
1063
- return isNonEmptyString(value.requestId) && isNonEmptyString(value.runId) && typeof value.sequence === "number" && Number.isSafeInteger(value.sequence) && value.sequence > 0;
1064
- }
1065
- function isRecord2(value) {
1066
- return typeof value === "object" && value != null && !Array.isArray(value);
1067
- }
1068
- function isNonEmptyString(value) {
1069
- return typeof value === "string" && value.length > 0;
1070
- }
1071
-
1072
- // src/model/UiGraphBrowserRuntime.ts
1073
- var OUTPUT_MAX_HEIGHT_PX = 800;
1074
- var OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
1075
- var OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-min-height";
1076
- var OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-max-height";
1077
- var CHAT_SEARCH_MATCH_CLASS = "rivet-web-app-chat-search-match";
1078
- var CHAT_SEARCH_ACTIVE_MATCH_CLASS = "rivet-web-app-chat-search-match-active";
1079
- var UI_GRAPH_CHAT_STORAGE_PREFIX = "rivet-web-app-chat-state:v1";
1080
- var UI_GRAPH_APP_STORAGE_PREFIX = "rivet-web-app-storage:v1";
1081
- var UI_GRAPH_RESPONSE_TRACE_STORAGE_PREFIX = "rivet-web-app-response-traces:v1";
1082
- var UI_GRAPH_RESPONSE_TRACE_LIMIT = 100;
1083
- var responseTraceMemoryFallback = /* @__PURE__ */ new Map();
1084
- var unsyncedResponseTraceKeysByStorage = /* @__PURE__ */ new WeakMap();
1085
- var escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1086
- var getPixelValue = (value, fallback) => {
1087
- const parsed = Number.parseFloat(value);
1088
- return Number.isFinite(parsed) ? parsed : fallback;
1089
- };
1090
- var setStyleProperty = (element, property, value) => {
1091
- if (element.style.getPropertyValue(property) !== value) {
1092
- element.style.setProperty(property, value);
1826
+ // src/model/UiGraphBrowserRuntime.ts
1827
+ var OUTPUT_MAX_HEIGHT_PX = 800;
1828
+ var OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
1829
+ var OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-min-height";
1830
+ var OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = "--rivet-web-app-output-resize-max-height";
1831
+ var CHAT_SEARCH_MATCH_CLASS = "rivet-web-app-chat-search-match";
1832
+ var CHAT_SEARCH_ACTIVE_MATCH_CLASS = "rivet-web-app-chat-search-match-active";
1833
+ var UI_GRAPH_CHAT_STORAGE_PREFIX = "rivet-web-app-chat-state:v1";
1834
+ var UI_GRAPH_APP_STORAGE_PREFIX = "rivet-web-app-storage:v1";
1835
+ var UI_GRAPH_RESPONSE_TRACE_STORAGE_PREFIX = "rivet-web-app-response-traces:v1";
1836
+ var UI_GRAPH_RESPONSE_TRACE_LIMIT = 100;
1837
+ var responseTraceMemoryFallback = /* @__PURE__ */ new Map();
1838
+ var unsyncedResponseTraceKeysByStorage = /* @__PURE__ */ new WeakMap();
1839
+ var escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1840
+ var getPixelValue = (value, fallback) => {
1841
+ const parsed = Number.parseFloat(value);
1842
+ return Number.isFinite(parsed) ? parsed : fallback;
1843
+ };
1844
+ var setStyleProperty = (element, property, value) => {
1845
+ if (element.style.getPropertyValue(property) !== value) {
1846
+ element.style.setProperty(property, value);
1093
1847
  }
1094
1848
  };
1095
1849
  var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1332,6 +2086,16 @@ function applyUiGraphWebAppStorageActionPatch(patch, actionNumber, appliedAction
1332
2086
  for (const key of applicableKeys) appliedActionByKey.set(key, actionNumber);
1333
2087
  return applicablePatch;
1334
2088
  }
2089
+ async function applyUiGraphWebAppStorageActionPatchAsync(patch, actionNumber, appliedActionByKey, persist) {
2090
+ const applicablePatch = Object.fromEntries(
2091
+ Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0))
2092
+ );
2093
+ const applicableKeys = Object.keys(applicablePatch);
2094
+ if (applicableKeys.length === 0) return applicablePatch;
2095
+ await persist(applicablePatch);
2096
+ for (const key of applicableKeys) appliedActionByKey.set(key, actionNumber);
2097
+ return applicablePatch;
2098
+ }
1335
2099
  function getUiGraphChatPersistentState(uiGraph, state) {
1336
2100
  const persistentState = {};
1337
2101
  for (const component of uiGraph.components) {
@@ -1606,11 +2370,652 @@ function revealUiGraphChatElement(messagesElement, element, alignment = "center"
1606
2370
  messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));
1607
2371
  }
1608
2372
  var revealUiGraphChatSearchMatch = revealUiGraphChatElement;
2373
+
2374
+ // src/model/UiGraphIndexedDbPersistence.ts
2375
+ var CHAT_STATE_RECORD_KEY = "state";
2376
+ var RESPONSE_TRACE_LIMIT = 100;
2377
+ var UiGraphBrowserPersistence = class {
2378
+ #store;
2379
+ #uiGraph;
2380
+ #legacyStorage;
2381
+ #location;
2382
+ #now;
2383
+ #onDiagnostic;
2384
+ #listeners = /* @__PURE__ */ new Set();
2385
+ #warningListeners = /* @__PURE__ */ new Set();
2386
+ #status = { durable: false, reason: "indexeddb-unavailable" };
2387
+ #warning;
2388
+ #disposeStoreSubscription;
2389
+ #responseTraceMutationQueue = Promise.resolve();
2390
+ #useLegacyStorage = true;
2391
+ constructor(uiGraph, options = {}) {
2392
+ this.#uiGraph = uiGraph;
2393
+ this.#legacyStorage = options.legacyStorage ?? getDefaultLegacyStorage();
2394
+ this.#now = options.now ?? Date.now;
2395
+ this.#onDiagnostic = options.onDiagnostic ?? defaultBrowserStorageDiagnostic;
2396
+ this.#location = options.location ?? getDefaultLocation();
2397
+ this.#store = new IndexedDbWebAppBrowserStorage(options);
2398
+ }
2399
+ async initialize() {
2400
+ const location = this.#location;
2401
+ if (!(location == null ? void 0 : location.origin)) {
2402
+ this.#reportDiagnostic({ operation: "open", outcome: "fallback" });
2403
+ this.#setWarning({
2404
+ code: "indexeddb-unavailable",
2405
+ message: "Saved browser data is unavailable. Changes will last only until this page is closed."
2406
+ });
2407
+ return this.#status;
2408
+ }
2409
+ this.#status = await this.#store.initialize({
2410
+ origin: location.origin,
2411
+ pathname: location.pathname,
2412
+ uiGraphId: String(this.#uiGraph.id)
2413
+ });
2414
+ this.#reportDiagnostic({ operation: "open", outcome: this.#status.durable ? "success" : "fallback" });
2415
+ this.#disposeStoreSubscription = this.#store.subscribe((change) => {
2416
+ for (const listener of this.#listeners) listener(change);
2417
+ });
2418
+ if (!this.#status.durable) {
2419
+ this.#setWarning({
2420
+ code: "indexeddb-unavailable",
2421
+ message: "Saved browser data is unavailable. Changes will use limited legacy storage for this page."
2422
+ });
2423
+ return this.#status;
2424
+ }
2425
+ this.#useLegacyStorage = false;
2426
+ const migratedLegacyRecords = await this.#tryMigrateLegacyRecords();
2427
+ if (migratedLegacyRecords) {
2428
+ try {
2429
+ await this.#cleanupExpiredLegacyRecords();
2430
+ this.#reportDiagnostic({ operation: "cleanup", outcome: "success" });
2431
+ } catch {
2432
+ this.#reportDiagnostic({ operation: "cleanup", outcome: "failure" });
2433
+ }
2434
+ this.#setWarning(void 0);
2435
+ }
2436
+ return this.#status;
2437
+ }
2438
+ get status() {
2439
+ return this.#status;
2440
+ }
2441
+ get warning() {
2442
+ return this.#warning;
2443
+ }
2444
+ subscribe(listener) {
2445
+ this.#listeners.add(listener);
2446
+ return () => this.#listeners.delete(listener);
2447
+ }
2448
+ subscribeWarning(listener) {
2449
+ this.#warningListeners.add(listener);
2450
+ return () => this.#warningListeners.delete(listener);
2451
+ }
2452
+ async loadChatState() {
2453
+ if (this.#useLegacyStorage) {
2454
+ return loadUiGraphChatPersistentState(this.#uiGraph, this.#legacyStorage, this.#location);
2455
+ }
2456
+ const value = await this.#store.get("chat-state", CHAT_STATE_RECORD_KEY);
2457
+ if (isRecord4(value)) return getUiGraphChatPersistentState(this.#uiGraph, value);
2458
+ return await this.#loadLegacyChatStateIfUnmigrated();
2459
+ }
2460
+ async saveChatState(state) {
2461
+ if (this.#useLegacyStorage) {
2462
+ saveUiGraphChatPersistentState(this.#uiGraph, state, this.#legacyStorage, this.#location);
2463
+ return;
2464
+ }
2465
+ await this.#tryMigrateLegacyRecords();
2466
+ const persistentState = getUiGraphChatPersistentState(this.#uiGraph, state);
2467
+ await this.#persist(
2468
+ () => Object.keys(persistentState).length === 0 ? this.#store.delete("chat-state", CHAT_STATE_RECORD_KEY) : this.#store.set("chat-state", CHAT_STATE_RECORD_KEY, cloneRivetStoredValue(persistentState))
2469
+ );
2470
+ }
2471
+ async loadStoredValues() {
2472
+ if (this.#useLegacyStorage) {
2473
+ return cloneRivetStoredValueRecord(
2474
+ loadUiGraphWebAppStorage(this.#uiGraph, this.#legacyStorage, this.#location),
2475
+ "Stored Value browser snapshot"
2476
+ );
2477
+ }
2478
+ const indexedDbValues = Object.fromEntries(
2479
+ (await this.#store.list("stored-values")).map(({ key, value }) => [key, value])
2480
+ );
2481
+ const legacyValues = await this.#loadLegacyStoredValuesIfUnmigrated();
2482
+ return cloneRivetStoredValueRecord({ ...legacyValues, ...indexedDbValues }, "Stored Value browser snapshot");
2483
+ }
2484
+ async loadStoredValue(key) {
2485
+ if (this.#useLegacyStorage) {
2486
+ const values = await this.loadStoredValues();
2487
+ return Object.prototype.hasOwnProperty.call(values, key) ? cloneRivetStoredValue(values[key], "Stored Value browser value") : void 0;
2488
+ }
2489
+ const value = await this.#store.get("stored-values", key);
2490
+ if (value !== void 0) return cloneRivetStoredValue(value, "Stored Value browser value");
2491
+ const legacyValues = await this.#loadLegacyStoredValuesIfUnmigrated();
2492
+ return Object.prototype.hasOwnProperty.call(legacyValues, key) ? cloneRivetStoredValue(legacyValues[key], "Stored Value browser value") : void 0;
2493
+ }
2494
+ async applyStoredValuePatch(patch, options = {}) {
2495
+ const portablePatch = cloneRivetStoredValueRecord(patch, "Stored Value browser patch");
2496
+ if (this.#useLegacyStorage) {
2497
+ const legacyKey = getUiGraphWebAppStorageKey(this.#uiGraph, this.#location);
2498
+ if (!legacyKey || !this.#legacyStorage) throw new Error("Browser storage is unavailable for this web app.");
2499
+ const current = await this.loadStoredValues();
2500
+ const next = cloneRivetStoredValueRecord({ ...current, ...portablePatch }, "Stored Value browser snapshot");
2501
+ this.#legacyStorage.setItem(legacyKey, JSON.stringify(next));
2502
+ return;
2503
+ }
2504
+ await this.#tryMigrateLegacyRecords();
2505
+ await this.#persist(
2506
+ () => this.#store.commitBatch(
2507
+ Object.entries(portablePatch).map(([key, value]) => ({ key, namespace: "stored-values", value }))
2508
+ ),
2509
+ options.requireDurable === true
2510
+ );
2511
+ }
2512
+ async loadResponseTrace(componentId, traceId) {
2513
+ const traces = await this.#loadResponseTraces(componentId);
2514
+ return traces.find((trace) => trace.traceId === traceId);
2515
+ }
2516
+ async saveResponseTrace(componentId, trace) {
2517
+ if (!isAgentResponseTrace(trace) || !this.#isResponseInspectionEnabled(componentId)) return;
2518
+ await this.#enqueueResponseTraceMutation(async () => {
2519
+ const traces = (await this.#loadResponseTraces(componentId)).filter(
2520
+ (candidate) => candidate.traceId !== trace.traceId
2521
+ );
2522
+ traces.push(trace);
2523
+ await this.#saveResponseTraces(componentId, traces.slice(-RESPONSE_TRACE_LIMIT));
2524
+ });
2525
+ }
2526
+ async pruneResponseTraces(state) {
2527
+ await this.#enqueueResponseTraceMutation(async () => {
2528
+ for (const component of this.#uiGraph.components) {
2529
+ if (component.type !== "chat") continue;
2530
+ const referenced = component.allowResponseInspection === true ? new Set(
2531
+ getUiGraphChatMessages(component.id, state).flatMap(
2532
+ (message) => typeof message.responseTraceId === "string" ? [message.responseTraceId] : []
2533
+ )
2534
+ ) : /* @__PURE__ */ new Set();
2535
+ const retained = (await this.#loadResponseTraces(String(component.id))).filter(
2536
+ (trace) => referenced.has(trace.traceId)
2537
+ );
2538
+ await this.#saveResponseTraces(String(component.id), retained);
2539
+ }
2540
+ });
2541
+ }
2542
+ reportTransportIncompatibility(message) {
2543
+ this.#reportDiagnostic({ operation: "transport", outcome: "failure" });
2544
+ if (this.#warning && this.#warning.code !== "transport-incompatible") return;
2545
+ this.#setWarning({ code: "transport-incompatible", message });
2546
+ }
2547
+ clearTransportIncompatibility() {
2548
+ var _a;
2549
+ if (((_a = this.#warning) == null ? void 0 : _a.code) === "transport-incompatible") {
2550
+ this.#setWarning(void 0);
2551
+ }
2552
+ }
2553
+ async estimateUsage() {
2554
+ return await this.#store.estimateUsage();
2555
+ }
2556
+ dispose() {
2557
+ var _a;
2558
+ (_a = this.#disposeStoreSubscription) == null ? void 0 : _a.call(this);
2559
+ this.#disposeStoreSubscription = void 0;
2560
+ this.#listeners.clear();
2561
+ this.#warningListeners.clear();
2562
+ this.#store.dispose();
2563
+ }
2564
+ async #loadResponseTraces(componentId) {
2565
+ if (!this.#isResponseInspectionEnabled(componentId)) return [];
2566
+ if (this.#useLegacyStorage) return this.#loadLegacyResponseTraces(componentId);
2567
+ const value = await this.#store.get("response-traces", componentId);
2568
+ return Array.isArray(value) ? value.filter(isAgentResponseTrace).slice(-RESPONSE_TRACE_LIMIT) : [];
2569
+ }
2570
+ async #saveResponseTraces(componentId, traces) {
2571
+ if (this.#useLegacyStorage) {
2572
+ const legacyKey = getUiGraphResponseTraceStorageKey(this.#uiGraph, componentId, this.#location);
2573
+ if (!legacyKey || !this.#legacyStorage) return;
2574
+ if (traces.length === 0) this.#legacyStorage.removeItem(legacyKey);
2575
+ else this.#legacyStorage.setItem(legacyKey, JSON.stringify(traces));
2576
+ return;
2577
+ }
2578
+ await this.#persist(
2579
+ () => traces.length === 0 ? this.#store.delete("response-traces", componentId) : this.#store.set("response-traces", componentId, cloneRivetStoredValue(traces))
2580
+ );
2581
+ }
2582
+ #loadLegacyResponseTraces(componentId) {
2583
+ const legacyKey = getUiGraphResponseTraceStorageKey(this.#uiGraph, componentId, this.#location);
2584
+ if (!legacyKey || !this.#legacyStorage) return [];
2585
+ try {
2586
+ const raw = this.#legacyStorage.getItem(legacyKey);
2587
+ const value = raw ? JSON.parse(raw) : void 0;
2588
+ return Array.isArray(value) ? value.filter(isAgentResponseTrace).slice(-RESPONSE_TRACE_LIMIT) : [];
2589
+ } catch {
2590
+ return [];
2591
+ }
2592
+ }
2593
+ #isResponseInspectionEnabled(componentId) {
2594
+ return this.#uiGraph.components.some(
2595
+ (component) => component.type === "chat" && String(component.id) === componentId && component.allowResponseInspection === true
2596
+ );
2597
+ }
2598
+ async #enqueueResponseTraceMutation(operation) {
2599
+ const result = this.#responseTraceMutationQueue.catch(() => void 0).then(operation);
2600
+ this.#responseTraceMutationQueue = result.then(
2601
+ () => void 0,
2602
+ () => void 0
2603
+ );
2604
+ return await result;
2605
+ }
2606
+ async #tryMigrateLegacyRecords() {
2607
+ var _a;
2608
+ try {
2609
+ if (!await this.#migrateLegacyRecords()) {
2610
+ this.#reportDiagnostic({ operation: "migration", outcome: "success" });
2611
+ if (((_a = this.#warning) == null ? void 0 : _a.code) === "migration-failed") this.#setWarning(void 0);
2612
+ return true;
2613
+ }
2614
+ } catch {
2615
+ }
2616
+ this.#reportMigrationFailure(
2617
+ "Existing browser data could not be migrated safely. Rivet kept the original copy and will try again later."
2618
+ );
2619
+ return false;
2620
+ }
2621
+ #reportMigrationFailure(message) {
2622
+ this.#reportDiagnostic({ operation: "migration", outcome: "failure" });
2623
+ this.#setWarning({ code: "migration-failed", message });
2624
+ }
2625
+ async #loadLegacyChatStateIfUnmigrated() {
2626
+ var _a;
2627
+ const legacyKey = getUiGraphChatStorageKey(this.#uiGraph, this.#location);
2628
+ if (!legacyKey || await this.#store.getMigration(legacyKey)) return {};
2629
+ const raw = (_a = this.#legacyStorage) == null ? void 0 : _a.getItem(legacyKey);
2630
+ if (raw == null) return {};
2631
+ try {
2632
+ const value = JSON.parse(raw);
2633
+ assertValidLegacyChatState(this.#uiGraph, value);
2634
+ const state = getUiGraphChatPersistentState(this.#uiGraph, value);
2635
+ await this.#tryMigrateLegacyRecords();
2636
+ return state;
2637
+ } catch {
2638
+ this.#reportMigrationFailure(
2639
+ "Some existing browser data was invalid and could not be migrated. Rivet kept its original copy."
2640
+ );
2641
+ return {};
2642
+ }
2643
+ }
2644
+ async #loadLegacyStoredValuesIfUnmigrated() {
2645
+ var _a;
2646
+ const legacyKey = getUiGraphWebAppStorageKey(this.#uiGraph, this.#location);
2647
+ if (!legacyKey || await this.#store.getMigration(legacyKey)) return {};
2648
+ const raw = (_a = this.#legacyStorage) == null ? void 0 : _a.getItem(legacyKey);
2649
+ if (raw == null) return {};
2650
+ try {
2651
+ const values = cloneRivetStoredValueRecord(
2652
+ JSON.parse(raw),
2653
+ "Legacy Stored Value snapshot"
2654
+ );
2655
+ await this.#tryMigrateLegacyRecords();
2656
+ return values;
2657
+ } catch {
2658
+ this.#reportMigrationFailure(
2659
+ "Some existing browser data was invalid and could not be migrated. Rivet kept its original copy."
2660
+ );
2661
+ return {};
2662
+ }
2663
+ }
2664
+ async #migrateLegacyRecords() {
2665
+ const legacyStorage = this.#legacyStorage;
2666
+ if (!legacyStorage) return false;
2667
+ let hasUnmigratedLegacyRecords = false;
2668
+ const now = this.#now();
2669
+ const migrations = [
2670
+ {
2671
+ key: CHAT_STATE_RECORD_KEY,
2672
+ legacyKey: getUiGraphChatStorageKey(this.#uiGraph, this.#location),
2673
+ namespace: "chat-state",
2674
+ parse: (raw) => {
2675
+ const value = JSON.parse(raw);
2676
+ assertValidLegacyChatState(this.#uiGraph, value);
2677
+ const state = getUiGraphChatPersistentState(this.#uiGraph, value);
2678
+ return Object.keys(state).length > 0 ? [{ key: CHAT_STATE_RECORD_KEY, namespace: "chat-state", value: cloneRivetStoredValue(state) }] : [];
2679
+ }
2680
+ },
2681
+ {
2682
+ key: "legacy-snapshot",
2683
+ legacyKey: getUiGraphWebAppStorageKey(this.#uiGraph, this.#location),
2684
+ namespace: "stored-values",
2685
+ parse: (raw) => Object.entries(
2686
+ cloneRivetStoredValueRecord(JSON.parse(raw), "Legacy Stored Value snapshot")
2687
+ ).map(([key, value]) => ({ key, namespace: "stored-values", value }))
2688
+ },
2689
+ ...this.#uiGraph.components.flatMap(
2690
+ (component) => component.type !== "chat" ? [] : [
2691
+ {
2692
+ key: String(component.id),
2693
+ legacyKey: getUiGraphResponseTraceStorageKey(this.#uiGraph, String(component.id), this.#location),
2694
+ namespace: "response-traces",
2695
+ parse: (raw) => {
2696
+ const value = JSON.parse(raw);
2697
+ if (!Array.isArray(value) || !value.every(isAgentResponseTrace)) {
2698
+ throw new Error("Legacy Chat response traces are invalid.");
2699
+ }
2700
+ const traces = value.slice(-RESPONSE_TRACE_LIMIT);
2701
+ return traces.length > 0 ? [
2702
+ {
2703
+ key: String(component.id),
2704
+ namespace: "response-traces",
2705
+ value: cloneRivetStoredValue(traces)
2706
+ }
2707
+ ] : [];
2708
+ }
2709
+ }
2710
+ ]
2711
+ )
2712
+ ];
2713
+ for (const migration of migrations) {
2714
+ if (!migration.legacyKey || await this.#store.getMigration(migration.legacyKey)) continue;
2715
+ const raw = legacyStorage.getItem(migration.legacyKey);
2716
+ if (raw == null) continue;
2717
+ let parsed;
2718
+ try {
2719
+ parsed = migration.parse(raw);
2720
+ } catch {
2721
+ hasUnmigratedLegacyRecords = true;
2722
+ continue;
2723
+ }
2724
+ const missing = [];
2725
+ let hasMemoryOnlyRecord = false;
2726
+ for (const change of parsed) {
2727
+ if (this.#store.hasMemoryOnlyRecord(change.namespace, change.key)) {
2728
+ hasMemoryOnlyRecord = true;
2729
+ break;
2730
+ }
2731
+ if (await this.#store.get(change.namespace, change.key) === void 0) missing.push(change);
2732
+ }
2733
+ if (hasMemoryOnlyRecord) {
2734
+ hasUnmigratedLegacyRecords = true;
2735
+ continue;
2736
+ }
2737
+ if (missing.length > 0) await this.#store.commitBatch(missing);
2738
+ await this.#store.recordMigration({
2739
+ cleanupAfter: now + RIVET_WEB_APP_LEGACY_RETENTION_MS,
2740
+ completedAt: now,
2741
+ key: migration.key,
2742
+ legacyKey: migration.legacyKey,
2743
+ namespace: migration.namespace
2744
+ });
2745
+ }
2746
+ return hasUnmigratedLegacyRecords;
2747
+ }
2748
+ async #cleanupExpiredLegacyRecords() {
2749
+ if (!this.#legacyStorage) return;
2750
+ const now = this.#now();
2751
+ for (const migration of await this.#store.listMigrations()) {
2752
+ if (migration.cleanupAfter <= now) this.#legacyStorage.removeItem(migration.legacyKey);
2753
+ }
2754
+ }
2755
+ async #persist(operation, requireDurable = false) {
2756
+ var _a;
2757
+ try {
2758
+ const result = await operation();
2759
+ if (isStorageStatus(result) && !result.durable) {
2760
+ this.#reportDiagnostic({ operation: "write", outcome: "failure" });
2761
+ this.#status = result;
2762
+ const warning = {
2763
+ code: "persistence-failed",
2764
+ message: "Some browser data exists only in memory and will not survive a reload."
2765
+ };
2766
+ this.#setWarning(warning);
2767
+ if (requireDurable) throw new Error(warning.message);
2768
+ } else if (isStorageCommitResult(result) && result.hasMemoryOnlyRecords) {
2769
+ this.#reportDiagnostic({ operation: "write", outcome: "failure" });
2770
+ this.#status = { durable: false, reason: "write-failed" };
2771
+ this.#setWarning({
2772
+ code: "persistence-failed",
2773
+ message: "Some browser data exists only in memory and will not survive a reload."
2774
+ });
2775
+ } else {
2776
+ this.#status = { durable: true };
2777
+ if (((_a = this.#warning) == null ? void 0 : _a.code) === "persistence-failed") this.#setWarning(void 0);
2778
+ }
2779
+ } catch (error) {
2780
+ if (error instanceof WebAppBrowserStoragePersistenceError) {
2781
+ this.#reportDiagnostic({ operation: "write", outcome: "failure" });
2782
+ this.#status = { durable: false, reason: "write-failed" };
2783
+ const warning = isQuotaExceededError(error) ? {
2784
+ code: "quota-exhausted",
2785
+ message: "Browser storage is full. Changes will last only until this page is closed."
2786
+ } : { code: "persistence-failed", message: error.message };
2787
+ this.#setWarning(warning);
2788
+ if (requireDurable) throw new Error(warning.message, { cause: error });
2789
+ return;
2790
+ }
2791
+ throw error;
2792
+ }
2793
+ }
2794
+ #reportDiagnostic(diagnostic) {
2795
+ try {
2796
+ this.#onDiagnostic(diagnostic);
2797
+ } catch {
2798
+ }
2799
+ }
2800
+ #setWarning(warning) {
2801
+ var _a, _b;
2802
+ if (((_a = this.#warning) == null ? void 0 : _a.code) === (warning == null ? void 0 : warning.code) && ((_b = this.#warning) == null ? void 0 : _b.message) === (warning == null ? void 0 : warning.message)) return;
2803
+ this.#warning = warning;
2804
+ for (const listener of this.#warningListeners) listener(warning);
2805
+ }
2806
+ };
2807
+ function defaultBrowserStorageDiagnostic(diagnostic) {
2808
+ var _a, _b;
2809
+ (_b = (_a = globalThis.console) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, "[rivet-web-app-storage]", diagnostic);
2810
+ }
2811
+ function isQuotaExceededError(error) {
2812
+ let current = error;
2813
+ for (let depth = 0; depth < 4 && current instanceof Error; depth += 1) {
2814
+ if (current.name === "QuotaExceededError") return true;
2815
+ current = current.cause;
2816
+ }
2817
+ return false;
2818
+ }
2819
+ function isStorageStatus(value) {
2820
+ return isRecord4(value) && typeof value.durable === "boolean";
2821
+ }
2822
+ function isStorageCommitResult(value) {
2823
+ return isStorageStatus(value) && ("revision" in value || "hasMemoryOnlyRecords" in value);
2824
+ }
2825
+ function getDefaultLegacyStorage() {
2826
+ var _a;
2827
+ try {
2828
+ return globalThis.localStorage ?? ((_a = globalThis.window) == null ? void 0 : _a.localStorage);
2829
+ } catch {
2830
+ return void 0;
2831
+ }
2832
+ }
2833
+ function getDefaultLocation() {
2834
+ var _a;
2835
+ try {
2836
+ return globalThis.location ?? ((_a = globalThis.window) == null ? void 0 : _a.location);
2837
+ } catch {
2838
+ return void 0;
2839
+ }
2840
+ }
2841
+ function isRecord4(value) {
2842
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2843
+ }
2844
+ function assertValidLegacyChatState(uiGraph, value) {
2845
+ if (!isRecord4(value)) throw new Error("Legacy Chat state must be a JSON object.");
2846
+ for (const component of uiGraph.components) {
2847
+ if (component.type !== "chat") continue;
2848
+ const draft = value[`__rivet_chat_${component.id}_draft`];
2849
+ const messages = value[`__rivet_chat_${component.id}_messages`];
2850
+ const pins = value[`__rivet_chat_${component.id}_pins`];
2851
+ if (draft !== void 0 && typeof draft !== "string") {
2852
+ throw new Error("Legacy Chat draft is invalid.");
2853
+ }
2854
+ if (messages !== void 0 && (!Array.isArray(messages) || !messages.every(isValidLegacyChatMessage))) {
2855
+ throw new Error("Legacy Chat messages are invalid.");
2856
+ }
2857
+ if (pins !== void 0 && (!Array.isArray(pins) || !pins.every((pin) => typeof pin === "number" && Number.isSafeInteger(pin) && pin >= 0))) {
2858
+ throw new Error("Legacy Chat pins are invalid.");
2859
+ }
2860
+ }
2861
+ }
2862
+ function isValidLegacyChatMessage(value) {
2863
+ if (!isRecord4(value)) return false;
2864
+ return (value.role === "user" || value.role === "assistant") && typeof value.content === "string" && (value.timestamp === void 0 || typeof value.timestamp === "string") && (value.responseTraceId === void 0 || typeof value.responseTraceId === "string");
2865
+ }
2866
+
2867
+ // src/model/UiGraphActionProtocol.ts
2868
+ var RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1;
2869
+ function parseRivetWebAppClientMessage(value) {
2870
+ if (!isRecord5(value) || typeof value.type !== "string") return void 0;
2871
+ const storageMessage = parseRivetWebAppBrowserStorageClientMessage(value);
2872
+ if (storageMessage) return storageMessage;
2873
+ switch (value.type) {
2874
+ case "client.hello":
2875
+ return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION ? {
2876
+ type: value.type,
2877
+ protocolVersion: value.protocolVersion,
2878
+ ...isStringArray(value.capabilities) ? { capabilities: value.capabilities } : {}
2879
+ } : void 0;
2880
+ case "action.start":
2881
+ return isNonEmptyString2(value.requestId) && isNonEmptyString2(value.componentId) && isRecord5(value.state) && (value.storage == null || isRecord5(value.storage)) && (value.revisionKey == null || typeof value.revisionKey === "string") ? {
2882
+ type: value.type,
2883
+ requestId: value.requestId,
2884
+ componentId: value.componentId,
2885
+ state: value.state,
2886
+ ...isRecord5(value.storage) ? { storage: value.storage } : {},
2887
+ ...typeof value.revisionKey === "string" ? { revisionKey: value.revisionKey } : {},
2888
+ ...value.storageRpcVersion === 2 ? { storageRpcVersion: 2 } : {}
2889
+ } : void 0;
2890
+ case "action.cancel":
2891
+ return isNonEmptyString2(value.runId) ? { type: value.type, runId: value.runId } : void 0;
2892
+ case "run.resume":
2893
+ return isNonEmptyString2(value.runId) && typeof value.lastSequence === "number" && Number.isSafeInteger(value.lastSequence) && value.lastSequence >= 0 ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence } : void 0;
2894
+ default:
2895
+ return void 0;
2896
+ }
2897
+ }
2898
+ function parseRivetWebAppServerMessage(value) {
2899
+ if (!isRecord5(value) || typeof value.type !== "string") return void 0;
2900
+ const storageMessage = parseRivetWebAppBrowserStorageServerMessage(value);
2901
+ if (storageMessage) return storageMessage;
2902
+ if (value.type === "server.ready") {
2903
+ if (value.protocolVersion !== RIVET_WEB_APP_ACTION_PROTOCOL_VERSION) return void 0;
2904
+ const browserStorageRpcLimits = parseBrowserStorageRpcLimits(value.browserStorageRpcLimits);
2905
+ if (value.browserStorageRpcLimits != null && !browserStorageRpcLimits) return void 0;
2906
+ return {
2907
+ type: value.type,
2908
+ protocolVersion: value.protocolVersion,
2909
+ ...isStringArray(value.capabilities) ? { capabilities: value.capabilities } : {},
2910
+ ...browserStorageRpcLimits ? { browserStorageRpcLimits } : {}
2911
+ };
2912
+ }
2913
+ if (value.type === "server.draining") return { type: value.type };
2914
+ if (value.type === "action.rejected") {
2915
+ return isNonEmptyString2(value.requestId) && isNonEmptyString2(value.error) ? {
2916
+ type: value.type,
2917
+ requestId: value.requestId,
2918
+ error: value.error,
2919
+ ...typeof value.code === "string" ? { code: value.code } : {}
2920
+ } : void 0;
2921
+ }
2922
+ if (value.type === "run.rejected") {
2923
+ return isNonEmptyString2(value.runId) && isNonEmptyString2(value.error) ? {
2924
+ type: value.type,
2925
+ runId: value.runId,
2926
+ error: value.error,
2927
+ ...typeof value.code === "string" ? { code: value.code } : {}
2928
+ } : void 0;
2929
+ }
2930
+ if (!hasRunEventBase(value)) return void 0;
2931
+ const base = {
2932
+ requestId: value.requestId,
2933
+ runId: value.runId,
2934
+ sequence: value.sequence
2935
+ };
2936
+ switch (value.type) {
2937
+ case "action.accepted":
2938
+ case "action.cancelled":
2939
+ return { type: value.type, ...base };
2940
+ case "action.progress": {
2941
+ if (!isRecord5(value.progress)) return void 0;
2942
+ const progress = normalizeGraphProgress({
2943
+ message: typeof value.progress.message === "string" ? value.progress.message : void 0,
2944
+ percent: typeof value.progress.percent === "number" ? value.progress.percent : void 0
2945
+ });
2946
+ return progress ? { type: value.type, ...base, progress } : void 0;
2947
+ }
2948
+ case "action.completed":
2949
+ return isRecord5(value.statePatch) && (value.storagePatch == null || isRecord5(value.storagePatch)) ? {
2950
+ type: value.type,
2951
+ ...base,
2952
+ statePatch: value.statePatch,
2953
+ ...isRecord5(value.storagePatch) ? { storagePatch: value.storagePatch } : {},
2954
+ ...isAgentResponseTrace(value.responseTrace) ? { responseTrace: value.responseTrace } : {}
2955
+ } : void 0;
2956
+ case "action.failed":
2957
+ return isNonEmptyString2(value.error) ? {
2958
+ type: value.type,
2959
+ ...base,
2960
+ error: value.error,
2961
+ ...typeof value.code === "string" ? { code: value.code } : {},
2962
+ ...isAgentResponseTrace(value.responseTrace) ? { responseTrace: value.responseTrace } : {}
2963
+ } : void 0;
2964
+ case "action.interrupted":
2965
+ return isNonEmptyString2(value.error) ? { type: value.type, ...base, error: value.error } : void 0;
2966
+ default:
2967
+ return void 0;
2968
+ }
2969
+ }
2970
+ function hasRunEventBase(value) {
2971
+ return isNonEmptyString2(value.requestId) && isNonEmptyString2(value.runId) && typeof value.sequence === "number" && Number.isSafeInteger(value.sequence) && value.sequence > 0;
2972
+ }
2973
+ function isRecord5(value) {
2974
+ return typeof value === "object" && value != null && !Array.isArray(value);
2975
+ }
2976
+ function parseBrowserStorageRpcLimits(value) {
2977
+ if (!isRecord5(value)) return void 0;
2978
+ if (!isPositiveSafeInteger(value.maxActionBytes) || !isPositiveSafeInteger(value.maxValueBytes) || value.maxValueBytes > value.maxActionBytes) {
2979
+ return void 0;
2980
+ }
2981
+ if (value.transferTimeoutMs != null && !isPositiveSafeInteger(value.transferTimeoutMs)) return void 0;
2982
+ return {
2983
+ maxActionBytes: value.maxActionBytes,
2984
+ maxValueBytes: value.maxValueBytes,
2985
+ transferTimeoutMs: value.transferTimeoutMs ?? RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS
2986
+ };
2987
+ }
2988
+ function isPositiveSafeInteger(value) {
2989
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2990
+ }
2991
+ function isNonEmptyString2(value) {
2992
+ return typeof value === "string" && value.length > 0;
2993
+ }
2994
+ function isStringArray(value) {
2995
+ return Array.isArray(value) && value.length <= 16 && value.every((item) => typeof item === "string" && item.length <= 100);
2996
+ }
1609
2997
  // Annotate the CommonJS export names for ESM import in node:
1610
2998
  0 && (module.exports = {
2999
+ IndexedDbWebAppBrowserStorage,
1611
3000
  RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,
3001
+ RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES,
3002
+ RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES,
3003
+ RIVET_WEB_APP_BROWSER_STORAGE_DATABASE,
3004
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES,
3005
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES,
3006
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES,
3007
+ RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS,
3008
+ RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY,
3009
+ RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION,
3010
+ RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES,
3011
+ RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION,
3012
+ RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES,
3013
+ RIVET_WEB_APP_LEGACY_RETENTION_MS,
3014
+ UiGraphBrowserPersistence,
3015
+ WebAppBrowserStoragePersistenceError,
1612
3016
  applyUiGraphStatePatch,
1613
3017
  applyUiGraphWebAppStorageActionPatch,
3018
+ applyUiGraphWebAppStorageActionPatchAsync,
1614
3019
  applyUiGraphWebAppStoragePatch,
1615
3020
  clearUiGraphChatSearchMatches,
1616
3021
  copyUiGraphText,
@@ -1620,17 +3025,23 @@ var revealUiGraphChatSearchMatch = revealUiGraphChatElement;
1620
3025
  createUiGraphChatPinStatePatch,
1621
3026
  createUiGraphChatSubmissionStatePatch,
1622
3027
  createUiGraphInteractionController,
3028
+ decodeRivetWebAppStorageBinaryFrame,
3029
+ deserializeRivetWebAppStoredValue,
3030
+ deserializeRivetWebAppStoredValuePatch,
1623
3031
  downloadUiGraphJsonOutput,
3032
+ encodeRivetWebAppStorageBinaryFrame,
1624
3033
  enhanceUiGraphChatJsonCodeBlocks,
1625
3034
  getUiGraphActionState,
1626
3035
  getUiGraphChatDraftStateKey,
1627
3036
  getUiGraphChatMessagePresentations,
1628
3037
  getUiGraphChatMessagesStateKey,
1629
3038
  getUiGraphChatPersistentState,
3039
+ getUiGraphChatPinsStateKey,
1630
3040
  getUiGraphChatStorageKey,
1631
3041
  getUiGraphComponentRenderModel,
1632
3042
  getUiGraphJsonOutputFilename,
1633
3043
  getUiGraphProgressiveJsonOutputChunks,
3044
+ getUiGraphResponseTraceStorageKey,
1634
3045
  getUiGraphWebAppStorageKey,
1635
3046
  hasUiGraphChatPersistentStateChanged,
1636
3047
  highlightUiGraphChatSearchMatches,
@@ -1639,12 +3050,17 @@ var revealUiGraphChatSearchMatch = revealUiGraphChatElement;
1639
3050
  loadUiGraphResponseTrace,
1640
3051
  loadUiGraphWebAppStorage,
1641
3052
  observeUiGraphOutputResizeBounds,
3053
+ parseRivetWebAppBrowserStorageClientMessage,
3054
+ parseRivetWebAppBrowserStorageServerMessage,
1642
3055
  parseRivetWebAppClientMessage,
1643
3056
  parseRivetWebAppServerMessage,
1644
3057
  pruneUiGraphResponseTraces,
1645
3058
  revealUiGraphChatElement,
1646
3059
  revealUiGraphChatSearchMatch,
1647
3060
  saveUiGraphChatPersistentState,
1648
- saveUiGraphResponseTrace
3061
+ saveUiGraphResponseTrace,
3062
+ serializeRivetWebAppStoredValue,
3063
+ serializeRivetWebAppStoredValuePatch,
3064
+ splitRivetWebAppStorageTransfer
1649
3065
  });
1650
3066
  //# sourceMappingURL=webAppRuntime.cjs.map