@opengeni/sdk 0.48.0 → 0.57.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 (122) hide show
  1. package/README.md +147 -1
  2. package/dist/artifact-client.d.ts +20 -2
  3. package/dist/artifacts.d.ts +4 -0
  4. package/dist/artifacts.js +11 -0
  5. package/dist/artifacts.js.map +1 -0
  6. package/dist/{chunk-V5F253OG.js → chunk-GU6JF75T.js} +6 -3
  7. package/dist/chunk-GU6JF75T.js.map +1 -0
  8. package/dist/chunk-HJ3HHUT5.js +222 -0
  9. package/dist/chunk-HJ3HHUT5.js.map +1 -0
  10. package/dist/{chunk-KIHGPM7H.js → chunk-JDLDDRNE.js} +20 -14
  11. package/dist/chunk-JDLDDRNE.js.map +1 -0
  12. package/dist/chunk-JRPFWI6T.js +128 -0
  13. package/dist/chunk-JRPFWI6T.js.map +1 -0
  14. package/dist/{chunk-MBGBLVUV.js → chunk-PKQ377ED.js} +1725 -555
  15. package/dist/chunk-PKQ377ED.js.map +1 -0
  16. package/dist/chunk-ST5DDKJP.js +987 -0
  17. package/dist/chunk-ST5DDKJP.js.map +1 -0
  18. package/dist/chunk-VWE2QIVO.js +1162 -0
  19. package/dist/chunk-VWE2QIVO.js.map +1 -0
  20. package/dist/chunk-VYCTL62C.js +230 -0
  21. package/dist/chunk-VYCTL62C.js.map +1 -0
  22. package/dist/{chunk-DXDL7EEW.js → chunk-YKZME56C.js} +197 -113
  23. package/dist/chunk-YKZME56C.js.map +1 -0
  24. package/dist/client.d.ts +240 -16
  25. package/dist/codex-realtime-controller.d.ts +9 -6
  26. package/dist/codex-realtime-controller.js +2 -2
  27. package/dist/codex-realtime-lifecycle.d.ts +1 -1
  28. package/dist/codex-realtime-v3.d.ts +3 -3
  29. package/dist/codex-realtime.d.ts +1 -1
  30. package/dist/company-profile.d.ts +100 -0
  31. package/dist/core.d.ts +5 -5
  32. package/dist/core.js +10 -5
  33. package/dist/desktop.d.ts +9 -1
  34. package/dist/editable-artifact-resources.d.ts +96 -0
  35. package/dist/editable-artifacts/browser-session.d.ts +35 -0
  36. package/dist/editable-artifacts/controller.d.ts +60 -0
  37. package/dist/editable-artifacts/errors.d.ts +23 -0
  38. package/dist/editable-artifacts/http-live-transport.d.ts +46 -0
  39. package/dist/editable-artifacts/index.d.ts +19 -0
  40. package/dist/editable-artifacts/pool.d.ts +15 -0
  41. package/dist/editable-artifacts/session.d.ts +96 -0
  42. package/dist/editable-artifacts/storage.d.ts +72 -0
  43. package/dist/editable-artifacts/types.d.ts +416 -0
  44. package/dist/editable-artifacts/worker/browser-client.d.ts +80 -0
  45. package/dist/editable-artifacts/worker/browser-entry.d.ts +6 -0
  46. package/dist/editable-artifacts/worker/kernel-adapter.d.ts +45 -0
  47. package/dist/editable-artifacts/worker/rpc-protocol.d.ts +92 -0
  48. package/dist/editable-artifacts/worker/runtime.d.ts +66 -0
  49. package/dist/editable-artifacts/worker/wire-codec.d.ts +52 -0
  50. package/dist/editable-artifacts-worker.d.ts +8 -0
  51. package/dist/editable-artifacts-worker.js +1708 -0
  52. package/dist/editable-artifacts-worker.js.map +1 -0
  53. package/dist/editable-artifacts.d.ts +6 -0
  54. package/dist/editable-artifacts.js +5954 -0
  55. package/dist/editable-artifacts.js.map +1 -0
  56. package/dist/gateway-realtime-transport.d.ts +2 -1
  57. package/dist/gateway-realtime-transport.js +5 -3
  58. package/dist/index.d.ts +45 -35
  59. package/dist/index.js +134 -64
  60. package/dist/index.js.map +1 -1
  61. package/dist/interaction-revision-stream.d.ts +11 -0
  62. package/dist/interaction.d.ts +1484 -0
  63. package/dist/interaction.js +81 -0
  64. package/dist/interaction.js.map +1 -0
  65. package/dist/memory-slack-client.d.ts +13 -0
  66. package/dist/memory-slack-delivery.d.ts +99 -0
  67. package/dist/memory-slack.d.ts +4 -0
  68. package/dist/memory-slack.js +44 -0
  69. package/dist/memory-slack.js.map +1 -0
  70. package/dist/proxy.d.ts +3 -3
  71. package/dist/realtime.d.ts +14 -14
  72. package/dist/realtime.js +11 -7
  73. package/dist/realtime.js.map +1 -1
  74. package/dist/retained-artifacts.d.ts +12 -0
  75. package/dist/stream.d.ts +1 -1
  76. package/dist/terminal.d.ts +1 -1
  77. package/dist/types.d.ts +1347 -34
  78. package/dist/workspace-control-stream.d.ts +2 -2
  79. package/dist/workspace-live-stream.d.ts +14 -0
  80. package/dist/workspace-state.d.ts +1 -1
  81. package/package.json +29 -3
  82. package/src/artifact-client.ts +129 -0
  83. package/src/artifacts.ts +17 -0
  84. package/src/client.ts +3022 -910
  85. package/src/codex-realtime-controller.ts +25 -7
  86. package/src/codex-realtime-lifecycle.ts +1 -0
  87. package/src/company-profile.ts +92 -0
  88. package/src/desktop.ts +11 -1
  89. package/src/editable-artifact-resources.ts +119 -0
  90. package/src/editable-artifacts/browser-session.ts +176 -0
  91. package/src/editable-artifacts/controller.ts +2632 -0
  92. package/src/editable-artifacts/errors.ts +52 -0
  93. package/src/editable-artifacts/http-live-transport.ts +1449 -0
  94. package/src/editable-artifacts/index.ts +175 -0
  95. package/src/editable-artifacts/pool.ts +81 -0
  96. package/src/editable-artifacts/session.ts +778 -0
  97. package/src/editable-artifacts/storage.ts +1718 -0
  98. package/src/editable-artifacts/types.ts +499 -0
  99. package/src/editable-artifacts/worker/browser-client.ts +1167 -0
  100. package/src/editable-artifacts/worker/browser-entry.ts +57 -0
  101. package/src/editable-artifacts/worker/kernel-adapter.ts +1039 -0
  102. package/src/editable-artifacts/worker/rpc-protocol.ts +622 -0
  103. package/src/editable-artifacts/worker/runtime.ts +1204 -0
  104. package/src/editable-artifacts/worker/wire-codec.ts +852 -0
  105. package/src/editable-artifacts-worker.ts +8 -0
  106. package/src/editable-artifacts.ts +6 -0
  107. package/src/errors.ts +16 -2
  108. package/src/gateway-realtime-transport.ts +252 -109
  109. package/src/index.ts +215 -1
  110. package/src/interaction-revision-stream.ts +117 -0
  111. package/src/interaction.ts +2874 -0
  112. package/src/memory-slack-client.ts +71 -0
  113. package/src/memory-slack-delivery.ts +128 -0
  114. package/src/memory-slack.ts +19 -0
  115. package/src/realtime.ts +14 -4
  116. package/src/retained-artifacts.ts +326 -0
  117. package/src/types.ts +1636 -52
  118. package/src/workspace-live-stream.ts +137 -0
  119. package/dist/chunk-DXDL7EEW.js.map +0 -1
  120. package/dist/chunk-KIHGPM7H.js.map +0 -1
  121. package/dist/chunk-MBGBLVUV.js.map +0 -1
  122. package/dist/chunk-V5F253OG.js.map +0 -1
@@ -0,0 +1,1162 @@
1
+ // src/editable-artifacts/worker/rpc-protocol.ts
2
+ var FRAME_MAGIC = new Uint8Array([79, 71, 65, 87, 82, 80, 67, 49]);
3
+ var FRAME_HEADER_BYTES = 36;
4
+ var FRAME_VERSION = 1;
5
+ var DEFAULT_MAX_METADATA_BYTES = 1024 * 1024;
6
+ var DEFAULT_MAX_SEGMENT_BYTES = 128 * 1024 * 1024;
7
+ var DEFAULT_MAX_TOTAL_SEGMENT_BYTES = 512 * 1024 * 1024;
8
+ var DEFAULT_MAX_SEGMENTS = 4096;
9
+ var DEFAULT_ARTIFACT_WORKER_RPC_LIMITS = Object.freeze({
10
+ maxMetadataBytes: DEFAULT_MAX_METADATA_BYTES,
11
+ maxSegmentBytes: DEFAULT_MAX_SEGMENT_BYTES,
12
+ maxTotalSegmentBytes: DEFAULT_MAX_TOTAL_SEGMENT_BYTES,
13
+ maxSegments: DEFAULT_MAX_SEGMENTS
14
+ });
15
+ var ArtifactWorkerProtocolError = class extends Error {
16
+ code;
17
+ constructor(code, message, options) {
18
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
19
+ this.name = "ArtifactWorkerProtocolError";
20
+ this.code = code;
21
+ }
22
+ };
23
+ function encodeArtifactWorkerRpcMessage(input) {
24
+ const limits = validateLimits(input.limits ?? DEFAULT_ARTIFACT_WORKER_RPC_LIMITS);
25
+ const generation = unsignedInt(input.generation, "generation");
26
+ const requestId = unsignedInt(input.requestId, "requestId");
27
+ if (generation === 0 || requestId === 0) {
28
+ throw protocolError("invalid_number", "generation and requestId must be nonzero");
29
+ }
30
+ const flags = unsignedInt(input.flags ?? 0, "flags");
31
+ const kind = unsignedShort(input.kind, "kind");
32
+ if (!isKnownKind(kind)) throw protocolError("unknown_kind", `unknown RPC kind ${kind}`);
33
+ const metadata = input.metadata ?? new Uint8Array();
34
+ if (!(metadata instanceof Uint8Array))
35
+ throw protocolError("invalid_frame", "metadata must be bytes");
36
+ if (metadata.byteLength > limits.maxMetadataBytes) {
37
+ throw protocolError("metadata_too_large", "RPC metadata exceeds its configured byte limit");
38
+ }
39
+ const segments = input.segments ?? [];
40
+ if (!Array.isArray(segments) || segments.length > limits.maxSegments || segments.length > 65535) {
41
+ throw protocolError("segments_too_large", "RPC segment count exceeds its configured limit");
42
+ }
43
+ let totalSegmentBytes = 0;
44
+ const uniqueSegments = /* @__PURE__ */ new Set();
45
+ for (const segment of segments) {
46
+ if (!(segment instanceof ArrayBuffer)) {
47
+ throw protocolError("invalid_segment", "RPC segments must be transferable ArrayBuffers");
48
+ }
49
+ if (segment.byteLength > limits.maxSegmentBytes) {
50
+ throw protocolError("segment_too_large", "RPC segment exceeds its configured byte limit");
51
+ }
52
+ if (uniqueSegments.has(segment)) {
53
+ throw protocolError("invalid_segment", "RPC segments must not alias one transferable buffer");
54
+ }
55
+ uniqueSegments.add(segment);
56
+ totalSegmentBytes = checkedAdd(totalSegmentBytes, segment.byteLength, "RPC segment bytes");
57
+ if (totalSegmentBytes > limits.maxTotalSegmentBytes) {
58
+ throw protocolError("segments_too_large", "RPC segments exceed their aggregate byte limit");
59
+ }
60
+ }
61
+ const segmentTableBytes = checkedMultiply(segments.length, 4, "RPC segment table");
62
+ const frameBytes = checkedAdd(
63
+ checkedAdd(FRAME_HEADER_BYTES, metadata.byteLength, "RPC frame"),
64
+ segmentTableBytes,
65
+ "RPC frame"
66
+ );
67
+ const frame = new Uint8Array(frameBytes);
68
+ const view = new DataView(frame.buffer);
69
+ frame.set(FRAME_MAGIC, 0);
70
+ view.setUint16(8, FRAME_VERSION, true);
71
+ view.setUint16(10, kind, true);
72
+ view.setUint32(12, generation, true);
73
+ view.setUint32(16, requestId, true);
74
+ view.setUint32(20, flags, true);
75
+ view.setUint32(24, metadata.byteLength, true);
76
+ view.setUint16(28, segments.length, true);
77
+ view.setUint16(30, 0, true);
78
+ view.setUint32(32, 0, true);
79
+ frame.set(metadata, FRAME_HEADER_BYTES);
80
+ let offset = FRAME_HEADER_BYTES + metadata.byteLength;
81
+ for (const segment of segments) {
82
+ view.setUint32(offset, segment.byteLength, true);
83
+ offset += 4;
84
+ }
85
+ view.setUint32(32, checksum32(frame), true);
86
+ return { frame: frame.buffer, segments };
87
+ }
88
+ function decodeArtifactWorkerRpcMessage(input, limitsInput = DEFAULT_ARTIFACT_WORKER_RPC_LIMITS) {
89
+ const limits = validateLimits(limitsInput);
90
+ if (!isPlainRecord(input)) throw protocolError("invalid_frame", "RPC message must be a record");
91
+ const keys = Object.keys(input);
92
+ if (keys.length !== 2 || !keys.includes("frame") || !keys.includes("segments")) {
93
+ throw protocolError("invalid_frame", "RPC message contains unknown or missing fields");
94
+ }
95
+ const frameBuffer = dataProperty(input, "frame");
96
+ const rawSegments = dataProperty(input, "segments");
97
+ if (!(frameBuffer instanceof ArrayBuffer)) {
98
+ throw protocolError("invalid_frame", "RPC frame must be a transferable ArrayBuffer");
99
+ }
100
+ if (!Array.isArray(rawSegments))
101
+ throw protocolError("invalid_frame", "RPC segments must be an array");
102
+ if (frameBuffer.byteLength < FRAME_HEADER_BYTES)
103
+ throw protocolError("truncated", "RPC frame is truncated");
104
+ if (frameBuffer.byteLength > FRAME_HEADER_BYTES + limits.maxMetadataBytes + limits.maxSegments * 4) {
105
+ throw protocolError("metadata_too_large", "RPC frame exceeds its configured byte limit");
106
+ }
107
+ const frame = new Uint8Array(frameBuffer);
108
+ for (let index = 0; index < FRAME_MAGIC.length; index += 1) {
109
+ if (frame[index] !== FRAME_MAGIC[index])
110
+ throw protocolError("bad_magic", "invalid RPC frame magic");
111
+ }
112
+ const view = new DataView(frameBuffer);
113
+ const version = view.getUint16(8, true);
114
+ if (version !== FRAME_VERSION) {
115
+ throw protocolError("unsupported_version", `unsupported RPC frame version ${version}`);
116
+ }
117
+ const kind = view.getUint16(10, true);
118
+ if (!isKnownKind(kind)) throw protocolError("unknown_kind", `unknown RPC kind ${kind}`);
119
+ const generation = view.getUint32(12, true);
120
+ const requestId = view.getUint32(16, true);
121
+ if (generation === 0 || requestId === 0) {
122
+ throw protocolError("noncanonical", "generation and requestId must be nonzero");
123
+ }
124
+ const flags = view.getUint32(20, true);
125
+ const metadataBytes = view.getUint32(24, true);
126
+ const segmentCount = view.getUint16(28, true);
127
+ if (view.getUint16(30, true) !== 0) {
128
+ throw protocolError("noncanonical", "reserved RPC frame bits are set");
129
+ }
130
+ if (metadataBytes > limits.maxMetadataBytes) {
131
+ throw protocolError("metadata_too_large", "RPC metadata exceeds its configured byte limit");
132
+ }
133
+ if (segmentCount > limits.maxSegments || rawSegments.length !== segmentCount) {
134
+ throw protocolError("invalid_segment", "RPC segment count does not match its frame");
135
+ }
136
+ const expectedFrameBytes = checkedAdd(
137
+ checkedAdd(FRAME_HEADER_BYTES, metadataBytes, "RPC frame"),
138
+ checkedMultiply(segmentCount, 4, "RPC segment table"),
139
+ "RPC frame"
140
+ );
141
+ if (frame.byteLength !== expectedFrameBytes) {
142
+ throw protocolError("trailing_bytes", "RPC frame has a truncated or trailing payload");
143
+ }
144
+ const expectedChecksum = view.getUint32(32, true);
145
+ view.setUint32(32, 0, true);
146
+ const actualChecksum = checksum32(frame);
147
+ view.setUint32(32, expectedChecksum, true);
148
+ if (expectedChecksum !== actualChecksum) {
149
+ throw protocolError("checksum_mismatch", "RPC frame checksum does not match");
150
+ }
151
+ const segments = [];
152
+ const uniqueBuffers = /* @__PURE__ */ new Set([frameBuffer]);
153
+ let totalSegmentBytes = 0;
154
+ let tableOffset = FRAME_HEADER_BYTES + metadataBytes;
155
+ for (let index = 0; index < segmentCount; index += 1) {
156
+ const expectedBytes = view.getUint32(tableOffset, true);
157
+ tableOffset += 4;
158
+ const segment = rawSegments[index];
159
+ if (!(segment instanceof ArrayBuffer) || segment.byteLength !== expectedBytes) {
160
+ throw protocolError(
161
+ "invalid_segment",
162
+ `RPC segment ${index} does not match its declared length`
163
+ );
164
+ }
165
+ if (uniqueBuffers.has(segment)) {
166
+ throw protocolError("invalid_segment", "RPC frame and segments must use distinct buffers");
167
+ }
168
+ uniqueBuffers.add(segment);
169
+ if (segment.byteLength > limits.maxSegmentBytes) {
170
+ throw protocolError("segment_too_large", `RPC segment ${index} exceeds its configured limit`);
171
+ }
172
+ totalSegmentBytes = checkedAdd(totalSegmentBytes, segment.byteLength, "RPC segment bytes");
173
+ if (totalSegmentBytes > limits.maxTotalSegmentBytes) {
174
+ throw protocolError("segments_too_large", "RPC segments exceed their aggregate byte limit");
175
+ }
176
+ segments.push(new Uint8Array(segment));
177
+ }
178
+ return {
179
+ kind,
180
+ generation,
181
+ requestId,
182
+ flags,
183
+ metadata: frame.slice(FRAME_HEADER_BYTES, FRAME_HEADER_BYTES + metadataBytes),
184
+ segments
185
+ };
186
+ }
187
+ function transferListForArtifactWorkerRpcMessage(message) {
188
+ return [message.frame, ...message.segments];
189
+ }
190
+ function ownedTransferBuffer(bytes) {
191
+ if (!(bytes instanceof Uint8Array))
192
+ throw protocolError("invalid_segment", "expected byte segment");
193
+ return bytes.slice().buffer;
194
+ }
195
+ var ArtifactWorkerBinaryWriter = class {
196
+ constructor(maximumBytes = DEFAULT_MAX_METADATA_BYTES) {
197
+ this.maximumBytes = maximumBytes;
198
+ positiveSafeInteger(maximumBytes, "maximumBytes");
199
+ }
200
+ chunks = [];
201
+ size = 0;
202
+ u8(value) {
203
+ unsignedByte(value, "u8");
204
+ return this.append(new Uint8Array([value]));
205
+ }
206
+ u16(value) {
207
+ unsignedShort(value, "u16");
208
+ const bytes = new Uint8Array(2);
209
+ new DataView(bytes.buffer).setUint16(0, value, true);
210
+ return this.append(bytes);
211
+ }
212
+ u32(value) {
213
+ unsignedInt(value, "u32");
214
+ const bytes = new Uint8Array(4);
215
+ new DataView(bytes.buffer).setUint32(0, value, true);
216
+ return this.append(bytes);
217
+ }
218
+ safeUint(value) {
219
+ nonNegativeSafeInteger(value, "safeUint");
220
+ const bytes = new Uint8Array(8);
221
+ new DataView(bytes.buffer).setBigUint64(0, BigInt(value), true);
222
+ return this.append(bytes);
223
+ }
224
+ f64(value) {
225
+ if (!Number.isFinite(value)) throw protocolError("invalid_number", "f64 must be finite");
226
+ const bytes = new Uint8Array(8);
227
+ new DataView(bytes.buffer).setFloat64(0, value, true);
228
+ return this.append(bytes);
229
+ }
230
+ string(value, maximumBytes = 256 * 1024) {
231
+ if (typeof value !== "string") throw protocolError("invalid_string", "expected a string");
232
+ if (!isWellFormedUnicode(value)) {
233
+ throw protocolError("invalid_string", "string contains an unpaired UTF-16 surrogate");
234
+ }
235
+ const bytes = new TextEncoder().encode(value);
236
+ if (bytes.byteLength > maximumBytes)
237
+ throw protocolError("string_too_large", "string exceeds its byte limit");
238
+ this.u32(bytes.byteLength);
239
+ return this.append(bytes);
240
+ }
241
+ optionalString(value, maximumBytes = 256 * 1024) {
242
+ this.u8(value === null ? 0 : 1);
243
+ if (value !== null) this.string(value, maximumBytes);
244
+ return this;
245
+ }
246
+ frontier(value, maximumActors = 1024) {
247
+ const entries = validateFrontier(value, maximumActors);
248
+ this.u32(entries.length);
249
+ for (const [actor, counter] of entries) {
250
+ this.string(actor, 256);
251
+ this.safeUint(counter);
252
+ }
253
+ return this;
254
+ }
255
+ finish() {
256
+ const output = new Uint8Array(this.size);
257
+ let offset = 0;
258
+ for (const chunk of this.chunks) {
259
+ output.set(chunk, offset);
260
+ offset += chunk.byteLength;
261
+ }
262
+ return output;
263
+ }
264
+ append(bytes) {
265
+ this.size = checkedAdd(this.size, bytes.byteLength, "binary metadata");
266
+ if (this.size > this.maximumBytes) {
267
+ throw protocolError("metadata_too_large", "binary metadata exceeds its configured limit");
268
+ }
269
+ this.chunks.push(bytes);
270
+ return this;
271
+ }
272
+ };
273
+ var ArtifactWorkerBinaryReader = class {
274
+ constructor(bytes) {
275
+ this.bytes = bytes;
276
+ if (!(bytes instanceof Uint8Array))
277
+ throw protocolError("invalid_frame", "metadata must be bytes");
278
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
279
+ }
280
+ view;
281
+ offset = 0;
282
+ u8() {
283
+ this.require(1);
284
+ const value = this.view.getUint8(this.offset);
285
+ this.offset += 1;
286
+ return value;
287
+ }
288
+ u16() {
289
+ this.require(2);
290
+ const value = this.view.getUint16(this.offset, true);
291
+ this.offset += 2;
292
+ return value;
293
+ }
294
+ u32() {
295
+ this.require(4);
296
+ const value = this.view.getUint32(this.offset, true);
297
+ this.offset += 4;
298
+ return value;
299
+ }
300
+ safeUint() {
301
+ this.require(8);
302
+ const value = this.view.getBigUint64(this.offset, true);
303
+ this.offset += 8;
304
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
305
+ throw protocolError("invalid_number", "RPC unsigned integer exceeds JavaScript safe range");
306
+ }
307
+ return Number(value);
308
+ }
309
+ f64() {
310
+ this.require(8);
311
+ const value = this.view.getFloat64(this.offset, true);
312
+ this.offset += 8;
313
+ if (!Number.isFinite(value)) throw protocolError("invalid_number", "non-finite RPC number");
314
+ return value;
315
+ }
316
+ string(maximumBytes = 256 * 1024) {
317
+ const length = this.u32();
318
+ if (length > maximumBytes)
319
+ throw protocolError("string_too_large", "RPC string exceeds its byte limit");
320
+ this.require(length);
321
+ const bytes = this.bytes.subarray(this.offset, this.offset + length);
322
+ this.offset += length;
323
+ try {
324
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
325
+ } catch (error) {
326
+ throw protocolError("invalid_utf8", "RPC string is not valid UTF-8", error);
327
+ }
328
+ }
329
+ optionalString(maximumBytes = 256 * 1024) {
330
+ const present = this.u8();
331
+ if (present === 0) return null;
332
+ if (present !== 1) throw protocolError("noncanonical", "invalid optional-string tag");
333
+ return this.string(maximumBytes);
334
+ }
335
+ frontier(maximumActors = 1024) {
336
+ const count = this.u32();
337
+ if (count > maximumActors)
338
+ throw protocolError("frontier_too_large", "causal frontier exceeds its actor limit");
339
+ const entries = [];
340
+ let previous = "";
341
+ for (let index = 0; index < count; index += 1) {
342
+ const actor = this.string(256);
343
+ if (!actor || index > 0 && compareCodeUnits(previous, actor) >= 0) {
344
+ throw protocolError(
345
+ "noncanonical",
346
+ "causal frontier actors must be unique and code-unit sorted"
347
+ );
348
+ }
349
+ const counter = this.safeUint();
350
+ entries.push(Object.freeze({ replicaId: actor, counter }));
351
+ previous = actor;
352
+ }
353
+ return Object.freeze(entries);
354
+ }
355
+ done() {
356
+ if (this.offset !== this.bytes.byteLength) {
357
+ throw protocolError("trailing_bytes", "RPC metadata contains trailing bytes");
358
+ }
359
+ }
360
+ remaining() {
361
+ return this.bytes.byteLength - this.offset;
362
+ }
363
+ require(length) {
364
+ if (length < 0 || this.offset + length > this.bytes.byteLength) {
365
+ throw protocolError("truncated", "RPC metadata is truncated");
366
+ }
367
+ }
368
+ };
369
+ function validateFrontier(value, maximumActors) {
370
+ if (!Array.isArray(value))
371
+ throw protocolError("invalid_frontier", "causal frontier must be an array");
372
+ const entries = [];
373
+ for (const entry of value) {
374
+ if (!isPlainRecord(entry))
375
+ throw protocolError("invalid_frontier", "causal frontier entry is invalid");
376
+ const keys = Object.keys(entry);
377
+ if (keys.length !== 2 || !keys.includes("replicaId") || !keys.includes("counter")) {
378
+ throw protocolError("invalid_frontier", "causal frontier entry has unknown fields");
379
+ }
380
+ const actor = dataProperty(entry, "replicaId");
381
+ const counter = dataProperty(entry, "counter");
382
+ if (typeof actor !== "string" || typeof counter !== "number") {
383
+ throw protocolError("invalid_frontier", "causal frontier entry has invalid fields");
384
+ }
385
+ entries.push([actor, counter]);
386
+ }
387
+ if (entries.length > maximumActors) {
388
+ throw protocolError("frontier_too_large", "causal frontier exceeds its actor limit");
389
+ }
390
+ for (const [actor, counter] of entries) {
391
+ if (!actor || new TextEncoder().encode(actor).byteLength > 256) {
392
+ throw protocolError("invalid_frontier", "causal frontier actor is invalid");
393
+ }
394
+ nonNegativeSafeInteger(counter, `causal frontier counter for ${actor}`);
395
+ }
396
+ const sorted = entries.slice().sort(([left], [right]) => compareCodeUnits(left, right));
397
+ for (let index = 0; index < entries.length; index += 1) {
398
+ if (entries[index][0] !== sorted[index][0]) {
399
+ throw protocolError("noncanonical", "causal frontier must already be code-unit sorted");
400
+ }
401
+ if (index > 0 && entries[index - 1][0] === entries[index][0]) {
402
+ throw protocolError("noncanonical", "causal frontier contains a duplicate replica");
403
+ }
404
+ }
405
+ return entries;
406
+ }
407
+ function validateLimits(input) {
408
+ const limits = {
409
+ maxMetadataBytes: positiveSafeInteger(input.maxMetadataBytes, "maxMetadataBytes"),
410
+ maxSegmentBytes: positiveSafeInteger(input.maxSegmentBytes, "maxSegmentBytes"),
411
+ maxTotalSegmentBytes: positiveSafeInteger(input.maxTotalSegmentBytes, "maxTotalSegmentBytes"),
412
+ maxSegments: positiveSafeInteger(input.maxSegments, "maxSegments")
413
+ };
414
+ if (limits.maxSegments > 65535) {
415
+ throw protocolError("invalid_limit", "maxSegments exceeds the frame encoding limit");
416
+ }
417
+ return limits;
418
+ }
419
+ function isKnownKind(kind) {
420
+ return kind >= 1 /* Initialize */ && kind <= 10 /* QuerySpreadsheet */ || kind === 128 /* Response */ || kind === 129 /* Error */;
421
+ }
422
+ function checksum32(bytes) {
423
+ let hash = 2166136261;
424
+ for (const byte of bytes) {
425
+ hash ^= byte;
426
+ hash = Math.imul(hash, 16777619) >>> 0;
427
+ }
428
+ return hash;
429
+ }
430
+ function compareCodeUnits(left, right) {
431
+ return left < right ? -1 : left > right ? 1 : 0;
432
+ }
433
+ function isWellFormedUnicode(value) {
434
+ for (let index = 0; index < value.length; index += 1) {
435
+ const code = value.charCodeAt(index);
436
+ if (code >= 55296 && code <= 56319) {
437
+ const following = value.charCodeAt(index + 1);
438
+ if (!(following >= 56320 && following <= 57343)) return false;
439
+ index += 1;
440
+ } else if (code >= 56320 && code <= 57343) {
441
+ return false;
442
+ }
443
+ }
444
+ return true;
445
+ }
446
+ function isPlainRecord(value) {
447
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
448
+ const prototype = Object.getPrototypeOf(value);
449
+ return prototype === Object.prototype || prototype === null;
450
+ }
451
+ function dataProperty(record, key) {
452
+ const descriptor = Object.getOwnPropertyDescriptor(record, key);
453
+ if (!descriptor || !("value" in descriptor)) {
454
+ throw protocolError("invalid_frame", `RPC ${key} must be a data property`);
455
+ }
456
+ return descriptor.value;
457
+ }
458
+ function unsignedByte(value, label) {
459
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
460
+ throw protocolError("invalid_number", `${label} must be an unsigned byte`);
461
+ }
462
+ return value;
463
+ }
464
+ function unsignedShort(value, label) {
465
+ if (!Number.isInteger(value) || value < 0 || value > 65535) {
466
+ throw protocolError("invalid_number", `${label} must be an unsigned 16-bit integer`);
467
+ }
468
+ return value;
469
+ }
470
+ function unsignedInt(value, label) {
471
+ if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
472
+ throw protocolError("invalid_number", `${label} must be an unsigned 32-bit integer`);
473
+ }
474
+ return value;
475
+ }
476
+ function positiveSafeInteger(value, label) {
477
+ if (!Number.isSafeInteger(value) || value <= 0) {
478
+ throw protocolError("invalid_limit", `${label} must be a positive safe integer`);
479
+ }
480
+ return value;
481
+ }
482
+ function nonNegativeSafeInteger(value, label) {
483
+ if (!Number.isSafeInteger(value) || value < 0) {
484
+ throw protocolError("invalid_number", `${label} must be a non-negative safe integer`);
485
+ }
486
+ return value;
487
+ }
488
+ function checkedAdd(left, right, label) {
489
+ const result = left + right;
490
+ if (!Number.isSafeInteger(result)) throw protocolError("size_overflow", `${label} overflow`);
491
+ return result;
492
+ }
493
+ function checkedMultiply(left, right, label) {
494
+ const result = left * right;
495
+ if (!Number.isSafeInteger(result)) throw protocolError("size_overflow", `${label} overflow`);
496
+ return result;
497
+ }
498
+ function protocolError(code, message, cause) {
499
+ return new ArtifactWorkerProtocolError(
500
+ code,
501
+ message,
502
+ cause === void 0 ? void 0 : { cause }
503
+ );
504
+ }
505
+
506
+ // src/editable-artifacts/worker/wire-codec.ts
507
+ import {
508
+ EDITABLE_ARTIFACT_COMMAND_MAX_BYTES,
509
+ EDITABLE_ARTIFACT_INTENT_MAX_BYTES,
510
+ EDITABLE_ARTIFACT_PRODUCT_MAX_SNAPSHOT_BYTES
511
+ } from "@opengeni/contracts/editable-artifacts";
512
+ import { MAX_COMMITTED_TRANSACTION_BYTES } from "@opengeni/contracts/editable-artifact-committed-transaction";
513
+ var MAX_ID_BYTES = 256;
514
+ var MAX_VERSION_BYTES = 512;
515
+ var MAX_ERROR_BYTES = 8 * 1024;
516
+ var MAX_URL_BYTES = 8 * 1024;
517
+ var SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/;
518
+ var HARD_MAX_SNAPSHOT_BYTES = EDITABLE_ARTIFACT_PRODUCT_MAX_SNAPSHOT_BYTES;
519
+ var HARD_MAX_COMMAND_BYTES = EDITABLE_ARTIFACT_COMMAND_MAX_BYTES;
520
+ var HARD_MAX_INTENT_BYTES = EDITABLE_ARTIFACT_INTENT_MAX_BYTES;
521
+ var HARD_MAX_COMMITTED_TRANSACTION_BYTES = MAX_COMMITTED_TRANSACTION_BYTES;
522
+ var HARD_MAX_QUERY_BYTES = 256;
523
+ var HARD_MAX_QUERY_RESPONSE_BYTES = 8 * 1024 * 1024;
524
+ var HARD_MAX_PENDING_TRANSACTIONS = 1024;
525
+ function encodeInitialize(input) {
526
+ validateInitializeLimits(input);
527
+ const writer = new ArtifactWorkerBinaryWriter();
528
+ writer.u8(modalityTag(input.modality)).string(requireVersion(input.kernelVersion, "kernelVersion"), MAX_VERSION_BYTES).u32(positiveSafeInteger2(input.protocolVersion, "protocolVersion")).u32(positiveSafeInteger2(input.modelSchemaVersion, "modelSchemaVersion")).u32(positiveSafeInteger2(input.commandVersion, "commandVersion")).string(requireUrl(input.wasmGlueUrl, "wasmGlueUrl"), MAX_URL_BYTES).string(requireUrl(input.wasmBinaryUrl, "wasmBinaryUrl"), MAX_URL_BYTES).safeUint(positiveSafeInteger2(input.maximumSnapshotBytes, "maximumSnapshotBytes")).safeUint(positiveSafeInteger2(input.maximumCommandBytes, "maximumCommandBytes")).safeUint(positiveSafeInteger2(input.maximumIntentBytes, "maximumIntentBytes")).safeUint(
529
+ positiveSafeInteger2(
530
+ input.maximumCommittedTransactionBytes,
531
+ "maximumCommittedTransactionBytes"
532
+ )
533
+ ).safeUint(positiveSafeInteger2(input.maximumQueryBytes, "maximumQueryBytes")).safeUint(positiveSafeInteger2(input.maximumQueryResponseBytes, "maximumQueryResponseBytes")).safeUint(positiveSafeInteger2(input.maximumPendingTransactions, "maximumPendingTransactions"));
534
+ return writer.finish();
535
+ }
536
+ function decodeInitialize(bytes) {
537
+ const reader = new ArtifactWorkerBinaryReader(bytes);
538
+ const value = {
539
+ modality: decodeModality(reader.u8()),
540
+ kernelVersion: requireVersion(reader.string(MAX_VERSION_BYTES), "kernelVersion"),
541
+ protocolVersion: positiveSafeInteger2(reader.u32(), "protocolVersion"),
542
+ modelSchemaVersion: positiveSafeInteger2(reader.u32(), "modelSchemaVersion"),
543
+ commandVersion: positiveSafeInteger2(reader.u32(), "commandVersion"),
544
+ wasmGlueUrl: requireUrl(reader.string(MAX_URL_BYTES), "wasmGlueUrl"),
545
+ wasmBinaryUrl: requireUrl(reader.string(MAX_URL_BYTES), "wasmBinaryUrl"),
546
+ maximumSnapshotBytes: positiveSafeInteger2(reader.safeUint(), "maximumSnapshotBytes"),
547
+ maximumCommandBytes: positiveSafeInteger2(reader.safeUint(), "maximumCommandBytes"),
548
+ maximumIntentBytes: positiveSafeInteger2(reader.safeUint(), "maximumIntentBytes"),
549
+ maximumCommittedTransactionBytes: positiveSafeInteger2(
550
+ reader.safeUint(),
551
+ "maximumCommittedTransactionBytes"
552
+ ),
553
+ maximumQueryBytes: positiveSafeInteger2(reader.safeUint(), "maximumQueryBytes"),
554
+ maximumQueryResponseBytes: positiveSafeInteger2(reader.safeUint(), "maximumQueryResponseBytes"),
555
+ maximumPendingTransactions: positiveSafeInteger2(
556
+ reader.safeUint(),
557
+ "maximumPendingTransactions"
558
+ )
559
+ };
560
+ reader.done();
561
+ validateInitializeLimits(value);
562
+ return value;
563
+ }
564
+ function encodeSnapshotMetadata(snapshot) {
565
+ const writer = new ArtifactWorkerBinaryWriter();
566
+ writer.u8(modalityTag(snapshot.modality)).string(requireIdentifier(snapshot.artifactId, "snapshot.artifactId"), MAX_ID_BYTES).safeUint(nonNegativeSafeInteger2(snapshot.sequence, "snapshot.sequence")).string(requireSha256(snapshot.stateHash, "snapshot.stateHash"), 71).string(requireSha256(snapshot.digest, "snapshot.digest"), 71).string(requireVersion(snapshot.kernelVersion, "snapshot.kernelVersion"), MAX_VERSION_BYTES).u32(positiveSafeInteger2(snapshot.modelSchemaVersion, "snapshot.modelSchemaVersion"));
567
+ if (snapshot.modality === "spreadsheet") {
568
+ writer.frontier(snapshot.causalFrontier).u32(positiveSafeInteger2(snapshot.protocolVersion, "snapshot.protocolVersion"));
569
+ } else {
570
+ writer.safeUint(nonNegativeSafeInteger2(snapshot.nativeRevision, "snapshot.nativeRevision"));
571
+ }
572
+ return writer.finish();
573
+ }
574
+ function decodeSnapshotMetadata(bytes, snapshotBytes) {
575
+ const reader = new ArtifactWorkerBinaryReader(bytes);
576
+ const modality = decodeModality(reader.u8());
577
+ const common = {
578
+ artifactId: requireIdentifier(reader.string(MAX_ID_BYTES), "snapshot.artifactId"),
579
+ sequence: nonNegativeSafeInteger2(reader.safeUint(), "snapshot.sequence"),
580
+ stateHash: requireSha256(reader.string(71), "snapshot.stateHash"),
581
+ digest: requireSha256(reader.string(71), "snapshot.digest"),
582
+ kernelVersion: requireVersion(reader.string(MAX_VERSION_BYTES), "snapshot.kernelVersion"),
583
+ modelSchemaVersion: positiveSafeInteger2(reader.u32(), "snapshot.modelSchemaVersion"),
584
+ bytes: snapshotBytes
585
+ };
586
+ const value = modality === "spreadsheet" ? {
587
+ ...common,
588
+ modality,
589
+ causalFrontier: reader.frontier(),
590
+ protocolVersion: positiveSafeInteger2(reader.u32(), "snapshot.protocolVersion")
591
+ } : {
592
+ ...common,
593
+ modality,
594
+ nativeRevision: nonNegativeSafeInteger2(reader.safeUint(), "snapshot.nativeRevision")
595
+ };
596
+ reader.done();
597
+ return Object.freeze(value);
598
+ }
599
+ function encodeCommittedMetadata(transaction) {
600
+ const writer = new ArtifactWorkerBinaryWriter();
601
+ encodeCommittedFields(writer, transaction);
602
+ return writer.finish();
603
+ }
604
+ function decodeCommittedMetadata(bytes, committedTransactionBytes) {
605
+ const reader = new ArtifactWorkerBinaryReader(bytes);
606
+ const modality = decodeModality(reader.u8());
607
+ const common = {
608
+ artifactId: requireIdentifier(reader.string(MAX_ID_BYTES), "transaction.artifactId"),
609
+ transactionId: requireIdentifier(reader.string(MAX_ID_BYTES), "transaction.transactionId"),
610
+ requestHash: requireSha256(reader.string(71), "transaction.requestHash"),
611
+ startSequence: positiveSafeInteger2(reader.safeUint(), "transaction.startSequence"),
612
+ endSequence: positiveSafeInteger2(reader.safeUint(), "transaction.endSequence"),
613
+ priorStateHash: requireSha256(reader.string(71), "transaction.priorStateHash"),
614
+ stateHash: requireSha256(reader.string(71), "transaction.stateHash"),
615
+ committedTransactionBytes
616
+ };
617
+ const value = modality === "spreadsheet" ? {
618
+ ...common,
619
+ modality,
620
+ causalFrontier: reader.frontier(),
621
+ protocolVersion: positiveSafeInteger2(reader.u32(), "transaction.protocolVersion")
622
+ } : {
623
+ ...common,
624
+ modality,
625
+ priorNativeRevision: nonNegativeSafeInteger2(
626
+ reader.safeUint(),
627
+ "transaction.priorNativeRevision"
628
+ ),
629
+ nativeRevision: nonNegativeSafeInteger2(reader.safeUint(), "transaction.nativeRevision"),
630
+ commitProtocolVersion: positiveSafeInteger2(
631
+ reader.u32(),
632
+ "transaction.commitProtocolVersion"
633
+ )
634
+ };
635
+ reader.done();
636
+ if (value.endSequence < value.startSequence) {
637
+ throw wireError("invalid_sequence", "transaction endSequence precedes startSequence");
638
+ }
639
+ return Object.freeze(value);
640
+ }
641
+ function encodePendingListMetadata(transactions) {
642
+ const writer = new ArtifactWorkerBinaryWriter();
643
+ if (!Array.isArray(transactions))
644
+ throw wireError("invalid_pending", "pending transactions must be an array");
645
+ writer.u32(transactions.length);
646
+ for (const transaction of transactions) encodePendingFields(writer, transaction);
647
+ return writer.finish();
648
+ }
649
+ function decodePendingListMetadata(bytes, segments, maximumTransactions) {
650
+ const reader = new ArtifactWorkerBinaryReader(bytes);
651
+ const count = reader.u32();
652
+ if (count > maximumTransactions || count * 2 !== segments.length) {
653
+ throw wireError("invalid_pending", "pending metadata and command segments do not match");
654
+ }
655
+ const transactions = [];
656
+ for (let index = 0; index < count; index += 1) {
657
+ transactions.push(decodePendingFields(reader, segments[index * 2], segments[index * 2 + 1]));
658
+ }
659
+ reader.done();
660
+ return Object.freeze(transactions);
661
+ }
662
+ function encodeReconcileMetadata(committed, pending) {
663
+ const writer = new ArtifactWorkerBinaryWriter();
664
+ encodeCommittedFields(writer, committed);
665
+ writer.u32(pending.length);
666
+ for (const transaction of pending) encodePendingFields(writer, transaction);
667
+ return writer.finish();
668
+ }
669
+ function decodeReconcileMetadata(bytes, segments, maximumPendingTransactions) {
670
+ if (segments.length < 1) throw wireError("invalid_segment", "reconcile requires operation bytes");
671
+ const reader = new ArtifactWorkerBinaryReader(bytes);
672
+ const committed = decodeCommittedFields(reader, segments[0]);
673
+ if (committed.endSequence < committed.startSequence) {
674
+ throw wireError("invalid_sequence", "transaction endSequence precedes startSequence");
675
+ }
676
+ const count = reader.u32();
677
+ if (count > maximumPendingTransactions || segments.length !== count * 2 + 1) {
678
+ throw wireError("invalid_pending", "reconcile pending metadata and segments do not match");
679
+ }
680
+ const pending = [];
681
+ for (let index = 0; index < count; index += 1) {
682
+ pending.push(decodePendingFields(reader, segments[index * 2 + 1], segments[index * 2 + 2]));
683
+ }
684
+ reader.done();
685
+ return { committed, pending: Object.freeze(pending) };
686
+ }
687
+ function encodeAuthorPendingMetadata(input) {
688
+ const writer = new ArtifactWorkerBinaryWriter();
689
+ encodeAuthorPendingFields(writer, input);
690
+ return writer.finish();
691
+ }
692
+ function decodeAuthorPendingMetadata(bytes, commandBytes) {
693
+ const reader = new ArtifactWorkerBinaryReader(bytes);
694
+ const value = decodeAuthorPendingFields(reader, commandBytes);
695
+ reader.done();
696
+ return value;
697
+ }
698
+ function encodeStateResponse(stateHash, digest) {
699
+ const writer = new ArtifactWorkerBinaryWriter(256);
700
+ writer.string(requireSha256(stateHash, "stateHash"), 71).optionalString(digest === void 0 ? null : requireSha256(digest, "digest"), 71);
701
+ return writer.finish();
702
+ }
703
+ function decodeStateResponse(bytes) {
704
+ const reader = new ArtifactWorkerBinaryReader(bytes);
705
+ const stateHash = requireSha256(reader.string(71), "stateHash");
706
+ const digest = reader.optionalString(71);
707
+ reader.done();
708
+ return digest === null ? { stateHash } : { stateHash, digest: requireSha256(digest, "digest") };
709
+ }
710
+ function encodeProjectionResponse(blockedPending, stateHash) {
711
+ if (!Array.isArray(blockedPending) || blockedPending.length > HARD_MAX_PENDING_TRANSACTIONS) {
712
+ throw wireError("invalid_pending", "blocked pending result exceeds its item limit");
713
+ }
714
+ const writer = new ArtifactWorkerBinaryWriter();
715
+ writer.optionalString(stateHash === void 0 ? null : requireSha256(stateHash, "stateHash"), 71);
716
+ writer.u32(blockedPending.length);
717
+ const seen = /* @__PURE__ */ new Set();
718
+ for (const blocked of blockedPending) {
719
+ const clientTransactionId = requireIdentifier(
720
+ blocked.clientTransactionId,
721
+ "blocked.clientTransactionId"
722
+ );
723
+ if (seen.has(clientTransactionId))
724
+ throw wireError("noncanonical", "blocked transaction is duplicated");
725
+ seen.add(clientTransactionId);
726
+ writer.string(clientTransactionId, MAX_ID_BYTES).string(requireErrorCode(blocked.code), 128);
727
+ }
728
+ return writer.finish();
729
+ }
730
+ function decodeProjectionResponse(bytes) {
731
+ const reader = new ArtifactWorkerBinaryReader(bytes);
732
+ const stateHash = reader.optionalString(71);
733
+ const count = reader.u32();
734
+ if (count > HARD_MAX_PENDING_TRANSACTIONS) {
735
+ throw wireError("invalid_pending", "blocked pending result exceeds its item limit");
736
+ }
737
+ const blockedPending = [];
738
+ const seen = /* @__PURE__ */ new Set();
739
+ for (let index = 0; index < count; index += 1) {
740
+ const clientTransactionId = requireIdentifier(
741
+ reader.string(MAX_ID_BYTES),
742
+ "blocked.clientTransactionId"
743
+ );
744
+ if (seen.has(clientTransactionId))
745
+ throw wireError("noncanonical", "blocked transaction is duplicated");
746
+ seen.add(clientTransactionId);
747
+ blockedPending.push(
748
+ Object.freeze({ clientTransactionId, code: requireErrorCode(reader.string(128)) })
749
+ );
750
+ }
751
+ reader.done();
752
+ return {
753
+ ...stateHash === null ? {} : { stateHash: requireSha256(stateHash, "stateHash") },
754
+ blockedPending: Object.freeze(blockedPending)
755
+ };
756
+ }
757
+ function encodeErrorPayload(error) {
758
+ const writer = new ArtifactWorkerBinaryWriter(MAX_ERROR_BYTES * 2 + 32);
759
+ writer.string(requireErrorCode(error.code), 128).string(requireBoundedString(error.message, "error.message", MAX_ERROR_BYTES), MAX_ERROR_BYTES).u8(error.retryable ? 1 : 0);
760
+ return writer.finish();
761
+ }
762
+ function decodeErrorPayload(bytes) {
763
+ const reader = new ArtifactWorkerBinaryReader(bytes);
764
+ const value = {
765
+ code: requireErrorCode(reader.string(128)),
766
+ message: requireBoundedString(reader.string(MAX_ERROR_BYTES), "error.message", MAX_ERROR_BYTES),
767
+ retryable: decodeBoolean(reader.u8(), "error.retryable")
768
+ };
769
+ reader.done();
770
+ return value;
771
+ }
772
+ function sha256Hex(bytes) {
773
+ if (!(bytes instanceof Uint8Array))
774
+ throw wireError("invalid_bytes", "SHA-256 input must be bytes");
775
+ const owned = new Uint8Array(bytes);
776
+ return globalThis.crypto.subtle.digest("SHA-256", owned).then(
777
+ (digest) => `sha256:${[...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("")}`
778
+ );
779
+ }
780
+ function requireMatchingHash(actual, expected, label) {
781
+ requireSha256(actual, `${label}.actual`);
782
+ requireSha256(expected, `${label}.expected`);
783
+ if (actual !== expected)
784
+ throw wireError("kernel_diverged", `${label} hash does not match authority`);
785
+ }
786
+ function encodeCommittedFields(writer, transaction) {
787
+ writer.u8(modalityTag(transaction.modality)).string(requireIdentifier(transaction.artifactId, "transaction.artifactId"), MAX_ID_BYTES).string(requireIdentifier(transaction.transactionId, "transaction.transactionId"), MAX_ID_BYTES).string(requireSha256(transaction.requestHash, "transaction.requestHash"), 71).safeUint(positiveSafeInteger2(transaction.startSequence, "transaction.startSequence")).safeUint(positiveSafeInteger2(transaction.endSequence, "transaction.endSequence")).string(requireSha256(transaction.priorStateHash, "transaction.priorStateHash"), 71).string(requireSha256(transaction.stateHash, "transaction.stateHash"), 71);
788
+ if (transaction.modality === "spreadsheet") {
789
+ writer.frontier(transaction.causalFrontier).u32(positiveSafeInteger2(transaction.protocolVersion, "transaction.protocolVersion"));
790
+ } else {
791
+ writer.safeUint(
792
+ nonNegativeSafeInteger2(transaction.priorNativeRevision, "transaction.priorNativeRevision")
793
+ ).safeUint(nonNegativeSafeInteger2(transaction.nativeRevision, "transaction.nativeRevision")).u32(
794
+ positiveSafeInteger2(transaction.commitProtocolVersion, "transaction.commitProtocolVersion")
795
+ );
796
+ }
797
+ }
798
+ function decodeCommittedFields(reader, committedTransactionBytes) {
799
+ const modality = decodeModality(reader.u8());
800
+ const common = {
801
+ artifactId: requireIdentifier(reader.string(MAX_ID_BYTES), "transaction.artifactId"),
802
+ transactionId: requireIdentifier(reader.string(MAX_ID_BYTES), "transaction.transactionId"),
803
+ requestHash: requireSha256(reader.string(71), "transaction.requestHash"),
804
+ startSequence: positiveSafeInteger2(reader.safeUint(), "transaction.startSequence"),
805
+ endSequence: positiveSafeInteger2(reader.safeUint(), "transaction.endSequence"),
806
+ priorStateHash: requireSha256(reader.string(71), "transaction.priorStateHash"),
807
+ stateHash: requireSha256(reader.string(71), "transaction.stateHash"),
808
+ committedTransactionBytes
809
+ };
810
+ return Object.freeze(
811
+ modality === "spreadsheet" ? {
812
+ ...common,
813
+ modality,
814
+ causalFrontier: reader.frontier(),
815
+ protocolVersion: positiveSafeInteger2(reader.u32(), "transaction.protocolVersion")
816
+ } : {
817
+ ...common,
818
+ modality,
819
+ priorNativeRevision: nonNegativeSafeInteger2(
820
+ reader.safeUint(),
821
+ "transaction.priorNativeRevision"
822
+ ),
823
+ nativeRevision: nonNegativeSafeInteger2(reader.safeUint(), "transaction.nativeRevision"),
824
+ commitProtocolVersion: positiveSafeInteger2(
825
+ reader.u32(),
826
+ "transaction.commitProtocolVersion"
827
+ )
828
+ }
829
+ );
830
+ }
831
+ function modalityTag(modality) {
832
+ switch (modality) {
833
+ case "document":
834
+ return 1;
835
+ case "spreadsheet":
836
+ return 2;
837
+ case "presentation":
838
+ return 3;
839
+ }
840
+ }
841
+ function decodeModality(tag) {
842
+ if (tag === 1) return "document";
843
+ if (tag === 2) return "spreadsheet";
844
+ if (tag === 3) return "presentation";
845
+ throw wireError("invalid_modality", "artifact modality tag is invalid");
846
+ }
847
+ function encodePendingFields(writer, transaction) {
848
+ writer.u8(modalityTag(transaction.modality)).string(requireIdentifier(transaction.artifactId, "pending.artifactId"), MAX_ID_BYTES).string(
849
+ requireIdentifier(transaction.clientTransactionId, "pending.clientTransactionId"),
850
+ MAX_ID_BYTES
851
+ ).string(requireSha256(transaction.requestHash, "pending.requestHash"), 71).u32(positiveSafeInteger2(transaction.protocolVersion, "pending.protocolVersion")).u32(positiveSafeInteger2(transaction.modelSchemaVersion, "pending.modelSchemaVersion")).u32(positiveSafeInteger2(transaction.commandVersion, "pending.commandVersion")).string(requireReplicaId(transaction.replicaId, "pending.replicaId"), 16).safeUint(positiveSafeInteger2(transaction.replicaCounter, "pending.replicaCounter")).optionalString(
852
+ transaction.previousLocalTransactionId === null ? null : requireIdentifier(
853
+ transaction.previousLocalTransactionId,
854
+ "pending.previousLocalTransactionId"
855
+ ),
856
+ MAX_ID_BYTES
857
+ ).safeUint(
858
+ nonNegativeSafeInteger2(transaction.observedHeadSequence, "pending.observedHeadSequence")
859
+ );
860
+ if (transaction.modality === "spreadsheet") {
861
+ writer.frontier(transaction.causalBase).u32(transaction.selectiveUndoTargets.length);
862
+ encodeSortedIdentifiers(
863
+ writer,
864
+ transaction.selectiveUndoTargets,
865
+ "pending.selectiveUndoTargets"
866
+ );
867
+ } else {
868
+ writer.safeUint(
869
+ nonNegativeSafeInteger2(transaction.observedNativeRevision, "pending.observedNativeRevision")
870
+ );
871
+ }
872
+ writer.safeUint(nonNegativeSafeInteger2(transaction.createdAt, "pending.createdAt"));
873
+ }
874
+ function decodePendingFields(reader, commandBytes, intentBytes) {
875
+ const modality = decodeModality(reader.u8());
876
+ const artifactId = requireIdentifier(reader.string(MAX_ID_BYTES), "pending.artifactId");
877
+ const clientTransactionId = requireIdentifier(
878
+ reader.string(MAX_ID_BYTES),
879
+ "pending.clientTransactionId"
880
+ );
881
+ const requestHash = requireSha256(reader.string(71), "pending.requestHash");
882
+ const protocolVersion = positiveSafeInteger2(reader.u32(), "pending.protocolVersion");
883
+ const modelSchemaVersion = positiveSafeInteger2(reader.u32(), "pending.modelSchemaVersion");
884
+ const commandVersion = positiveSafeInteger2(reader.u32(), "pending.commandVersion");
885
+ const replicaId = requireReplicaId(reader.string(16), "pending.replicaId");
886
+ const replicaCounter = positiveSafeInteger2(reader.safeUint(), "pending.replicaCounter");
887
+ const previousLocalTransactionId = optionalIdentifier(
888
+ reader.optionalString(MAX_ID_BYTES),
889
+ "pending.previousLocalTransactionId"
890
+ );
891
+ const observedHeadSequence = nonNegativeSafeInteger2(
892
+ reader.safeUint(),
893
+ "pending.observedHeadSequence"
894
+ );
895
+ const common = {
896
+ artifactId,
897
+ clientTransactionId,
898
+ requestHash,
899
+ protocolVersion,
900
+ modelSchemaVersion,
901
+ commandVersion,
902
+ replicaId,
903
+ replicaCounter,
904
+ previousLocalTransactionId,
905
+ observedHeadSequence,
906
+ commandBytes,
907
+ intentBytes
908
+ };
909
+ if (modality === "spreadsheet") {
910
+ const causalBase = reader.frontier();
911
+ const selectiveUndoTargets = decodeSortedIdentifiers(
912
+ reader,
913
+ reader.u32(),
914
+ "pending.selectiveUndoTargets"
915
+ );
916
+ return Object.freeze({
917
+ ...common,
918
+ modality,
919
+ causalBase,
920
+ selectiveUndoTargets,
921
+ createdAt: nonNegativeSafeInteger2(reader.safeUint(), "pending.createdAt")
922
+ });
923
+ }
924
+ const observedNativeRevision = nonNegativeSafeInteger2(
925
+ reader.safeUint(),
926
+ "pending.observedNativeRevision"
927
+ );
928
+ return Object.freeze({
929
+ ...common,
930
+ modality,
931
+ observedNativeRevision,
932
+ createdAt: nonNegativeSafeInteger2(reader.safeUint(), "pending.createdAt")
933
+ });
934
+ }
935
+ function encodeAuthorPendingFields(writer, input) {
936
+ writer.u8(modalityTag(input.modality)).u32(positiveSafeInteger2(input.protocolVersion, "author.protocolVersion")).string(requireVersion(input.kernelVersion, "author.kernelVersion"), MAX_VERSION_BYTES).u32(positiveSafeInteger2(input.modelSchemaVersion, "author.modelSchemaVersion")).u32(positiveSafeInteger2(input.commandVersion, "author.commandVersion")).string(requireIdentifier(input.artifactId, "author.artifactId"), MAX_ID_BYTES).string(
937
+ requireIdentifier(input.clientTransactionId, "author.clientTransactionId"),
938
+ MAX_ID_BYTES
939
+ ).string(requireReplicaId(input.replicaId, "author.replicaId"), 16).safeUint(positiveSafeInteger2(input.replicaCounter, "author.replicaCounter")).optionalString(
940
+ input.previousLocalTransactionId === null ? null : requireIdentifier(input.previousLocalTransactionId, "author.previousLocalTransactionId"),
941
+ MAX_ID_BYTES
942
+ ).safeUint(nonNegativeSafeInteger2(input.observedHeadSequence, "author.observedHeadSequence"));
943
+ if (input.modality === "spreadsheet") {
944
+ const causalBase = input.causalBase ?? [];
945
+ const selectiveUndoTargets = input.selectiveUndoTargets ?? [];
946
+ writer.frontier(causalBase).u32(selectiveUndoTargets.length);
947
+ encodeSortedIdentifiers(writer, selectiveUndoTargets, "author.selectiveUndoTargets");
948
+ }
949
+ writer.safeUint(input.commandBytes.byteLength);
950
+ writer.safeUint(nonNegativeSafeInteger2(input.createdAt, "author.createdAt"));
951
+ }
952
+ function decodeAuthorPendingFields(reader, commandBytes) {
953
+ const modality = decodeModality(reader.u8());
954
+ const value = {
955
+ modality,
956
+ protocolVersion: positiveSafeInteger2(reader.u32(), "author.protocolVersion"),
957
+ kernelVersion: requireVersion(reader.string(MAX_VERSION_BYTES), "author.kernelVersion"),
958
+ modelSchemaVersion: positiveSafeInteger2(reader.u32(), "author.modelSchemaVersion"),
959
+ commandVersion: positiveSafeInteger2(reader.u32(), "author.commandVersion"),
960
+ artifactId: requireIdentifier(reader.string(MAX_ID_BYTES), "author.artifactId"),
961
+ clientTransactionId: requireIdentifier(
962
+ reader.string(MAX_ID_BYTES),
963
+ "author.clientTransactionId"
964
+ ),
965
+ replicaId: requireReplicaId(reader.string(16), "author.replicaId"),
966
+ replicaCounter: positiveSafeInteger2(reader.safeUint(), "author.replicaCounter"),
967
+ previousLocalTransactionId: optionalIdentifier(
968
+ reader.optionalString(MAX_ID_BYTES),
969
+ "author.previousLocalTransactionId"
970
+ ),
971
+ observedHeadSequence: nonNegativeSafeInteger2(reader.safeUint(), "author.observedHeadSequence"),
972
+ ...modality === "spreadsheet" ? {
973
+ causalBase: reader.frontier(),
974
+ selectiveUndoTargets: decodeSortedIdentifiers(
975
+ reader,
976
+ reader.u32(),
977
+ "author.selectiveUndoTargets"
978
+ )
979
+ } : {},
980
+ commandBytes,
981
+ createdAt: 0
982
+ };
983
+ const declaredCommandBytes = reader.safeUint();
984
+ if (declaredCommandBytes !== commandBytes.byteLength) {
985
+ throw wireError("invalid_segment", "author command length does not match its segment");
986
+ }
987
+ value.createdAt = nonNegativeSafeInteger2(reader.safeUint(), "author.createdAt");
988
+ return Object.freeze(value);
989
+ }
990
+ function requireUrl(value, label) {
991
+ const bounded = requireBoundedString(value, label, MAX_URL_BYTES);
992
+ let url;
993
+ try {
994
+ url = new URL(bounded);
995
+ } catch (error) {
996
+ throw wireError("invalid_url", `${label} must be an absolute URL`, error);
997
+ }
998
+ if (!(/* @__PURE__ */ new Set(["https:", "http:", "file:"])).has(url.protocol)) {
999
+ throw wireError("invalid_url", `${label} uses an unsupported URL scheme`);
1000
+ }
1001
+ if (url.username || url.password || url.hash) {
1002
+ throw wireError("invalid_url", `${label} must not contain credentials or a fragment`);
1003
+ }
1004
+ url.username = "";
1005
+ url.password = "";
1006
+ if (url.href !== bounded) {
1007
+ throw wireError("noncanonical", `${label} must be a canonical URL without credentials`);
1008
+ }
1009
+ return bounded;
1010
+ }
1011
+ function requireIdentifier(value, label) {
1012
+ const bounded = requireBoundedString(value, label, MAX_ID_BYTES);
1013
+ if (/\p{Cc}/u.test(bounded))
1014
+ throw wireError("invalid_identifier", `${label} contains control characters`);
1015
+ return bounded;
1016
+ }
1017
+ function requireVersion(value, label) {
1018
+ const bounded = requireBoundedString(value, label, MAX_VERSION_BYTES);
1019
+ if (/\p{Cc}/u.test(bounded))
1020
+ throw wireError("invalid_identifier", `${label} contains control characters`);
1021
+ return bounded;
1022
+ }
1023
+ function optionalIdentifier(value, label) {
1024
+ return value === null ? null : requireIdentifier(value, label);
1025
+ }
1026
+ function requireReplicaId(value, label) {
1027
+ if (!/^(?!0{16}$)[0-9a-f]{16}$/.test(value)) {
1028
+ throw wireError(
1029
+ "invalid_identifier",
1030
+ `${label} must be 16 lowercase nonzero hexadecimal digits`
1031
+ );
1032
+ }
1033
+ return value;
1034
+ }
1035
+ function requireSha256(value, label) {
1036
+ if (!SHA256_PATTERN.test(value))
1037
+ throw wireError("invalid_hash", `${label} must be 64 lowercase hex characters`);
1038
+ return value;
1039
+ }
1040
+ function requireErrorCode(value) {
1041
+ if (!/^[a-z][a-z0-9_]{0,127}$/.test(value))
1042
+ throw wireError("invalid_error", "invalid worker error code");
1043
+ return value;
1044
+ }
1045
+ function requireBoundedString(value, label, maximumBytes) {
1046
+ if (typeof value !== "string" || value.length === 0)
1047
+ throw wireError("invalid_string", `${label} is empty`);
1048
+ if (new TextEncoder().encode(value).byteLength > maximumBytes) {
1049
+ throw wireError("string_too_large", `${label} exceeds its byte limit`);
1050
+ }
1051
+ return value;
1052
+ }
1053
+ function positiveSafeInteger2(value, label) {
1054
+ if (!Number.isSafeInteger(value) || value <= 0)
1055
+ throw wireError("invalid_number", `${label} must be positive`);
1056
+ return value;
1057
+ }
1058
+ function nonNegativeSafeInteger2(value, label) {
1059
+ if (!Number.isSafeInteger(value) || value < 0) {
1060
+ throw wireError("invalid_number", `${label} must be a non-negative safe integer`);
1061
+ }
1062
+ return value;
1063
+ }
1064
+ function decodeBoolean(value, label) {
1065
+ if (value === 0) return false;
1066
+ if (value === 1) return true;
1067
+ throw wireError("noncanonical", `${label} has an invalid boolean tag`);
1068
+ }
1069
+ function encodeSortedIdentifiers(writer, values, label) {
1070
+ if (!Array.isArray(values) || values.length > 1e4) {
1071
+ throw wireError("invalid_identifiers", `${label} exceeds its item limit`);
1072
+ }
1073
+ let previous = "";
1074
+ for (let index = 0; index < values.length; index += 1) {
1075
+ const value = requireIdentifier(values[index], `${label}[${index}]`);
1076
+ if (index > 0 && previous >= value) {
1077
+ throw wireError("noncanonical", `${label} must be unique and code-unit sorted`);
1078
+ }
1079
+ writer.string(value, MAX_ID_BYTES);
1080
+ previous = value;
1081
+ }
1082
+ }
1083
+ function decodeSortedIdentifiers(reader, count, label) {
1084
+ if (count > 1e4) throw wireError("invalid_identifiers", `${label} exceeds its item limit`);
1085
+ const values = [];
1086
+ let previous = "";
1087
+ for (let index = 0; index < count; index += 1) {
1088
+ const value = requireIdentifier(reader.string(MAX_ID_BYTES), `${label}[${index}]`);
1089
+ if (index > 0 && previous >= value) {
1090
+ throw wireError("noncanonical", `${label} must be unique and code-unit sorted`);
1091
+ }
1092
+ values.push(value);
1093
+ previous = value;
1094
+ }
1095
+ return Object.freeze(values);
1096
+ }
1097
+ function wireError(code, message, cause) {
1098
+ return new ArtifactWorkerProtocolError(
1099
+ code,
1100
+ message,
1101
+ cause === void 0 ? void 0 : { cause }
1102
+ );
1103
+ }
1104
+ function validateInitializeLimits(input) {
1105
+ requireVersion(input.kernelVersion, "kernelVersion");
1106
+ for (const [value, label] of [
1107
+ [input.protocolVersion, "protocolVersion"],
1108
+ [input.modelSchemaVersion, "modelSchemaVersion"],
1109
+ [input.commandVersion, "commandVersion"]
1110
+ ]) {
1111
+ positiveSafeInteger2(value, label);
1112
+ if (value > 65535) throw wireError("invalid_version", `${label} exceeds uint16`);
1113
+ }
1114
+ const limits = [
1115
+ [input.maximumSnapshotBytes, HARD_MAX_SNAPSHOT_BYTES, "maximumSnapshotBytes"],
1116
+ [input.maximumCommandBytes, HARD_MAX_COMMAND_BYTES, "maximumCommandBytes"],
1117
+ [input.maximumIntentBytes, HARD_MAX_INTENT_BYTES, "maximumIntentBytes"],
1118
+ [
1119
+ input.maximumCommittedTransactionBytes,
1120
+ HARD_MAX_COMMITTED_TRANSACTION_BYTES,
1121
+ "maximumCommittedTransactionBytes"
1122
+ ],
1123
+ [input.maximumQueryBytes, HARD_MAX_QUERY_BYTES, "maximumQueryBytes"],
1124
+ [input.maximumQueryResponseBytes, HARD_MAX_QUERY_RESPONSE_BYTES, "maximumQueryResponseBytes"],
1125
+ [input.maximumPendingTransactions, HARD_MAX_PENDING_TRANSACTIONS, "maximumPendingTransactions"]
1126
+ ];
1127
+ for (const [value, maximum, label] of limits) {
1128
+ positiveSafeInteger2(value, label);
1129
+ if (value > maximum)
1130
+ throw wireError("invalid_limit", `${label} exceeds the hard safety ceiling`);
1131
+ }
1132
+ }
1133
+
1134
+ export {
1135
+ DEFAULT_ARTIFACT_WORKER_RPC_LIMITS,
1136
+ ArtifactWorkerProtocolError,
1137
+ encodeArtifactWorkerRpcMessage,
1138
+ decodeArtifactWorkerRpcMessage,
1139
+ transferListForArtifactWorkerRpcMessage,
1140
+ ownedTransferBuffer,
1141
+ encodeInitialize,
1142
+ decodeInitialize,
1143
+ encodeSnapshotMetadata,
1144
+ decodeSnapshotMetadata,
1145
+ encodeCommittedMetadata,
1146
+ decodeCommittedMetadata,
1147
+ encodePendingListMetadata,
1148
+ decodePendingListMetadata,
1149
+ encodeReconcileMetadata,
1150
+ decodeReconcileMetadata,
1151
+ encodeAuthorPendingMetadata,
1152
+ decodeAuthorPendingMetadata,
1153
+ encodeStateResponse,
1154
+ decodeStateResponse,
1155
+ encodeProjectionResponse,
1156
+ decodeProjectionResponse,
1157
+ encodeErrorPayload,
1158
+ decodeErrorPayload,
1159
+ sha256Hex,
1160
+ requireMatchingHash
1161
+ };
1162
+ //# sourceMappingURL=chunk-VWE2QIVO.js.map