@opengeni/artifact-tool 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +104 -0
  3. package/dist/bounded-zip.d.ts +28 -0
  4. package/dist/chunk-4BSENMAE.js +39 -0
  5. package/dist/chunk-4BSENMAE.js.map +1 -0
  6. package/dist/chunk-4FRFNNBM.js +276 -0
  7. package/dist/chunk-4FRFNNBM.js.map +1 -0
  8. package/dist/chunk-5XIA6KHZ.js +49 -0
  9. package/dist/chunk-5XIA6KHZ.js.map +1 -0
  10. package/dist/chunk-66CT2ZRP.js +2229 -0
  11. package/dist/chunk-66CT2ZRP.js.map +1 -0
  12. package/dist/chunk-72SYDU4O.js +319 -0
  13. package/dist/chunk-72SYDU4O.js.map +1 -0
  14. package/dist/chunk-B2ZJRZDA.js +279 -0
  15. package/dist/chunk-B2ZJRZDA.js.map +1 -0
  16. package/dist/chunk-DCTLTNPW.js +2458 -0
  17. package/dist/chunk-DCTLTNPW.js.map +1 -0
  18. package/dist/chunk-FGZM4FQ6.js +473 -0
  19. package/dist/chunk-FGZM4FQ6.js.map +1 -0
  20. package/dist/chunk-HTJBLBDE.js +591 -0
  21. package/dist/chunk-HTJBLBDE.js.map +1 -0
  22. package/dist/chunk-IYFXZQ34.js +5306 -0
  23. package/dist/chunk-IYFXZQ34.js.map +1 -0
  24. package/dist/chunk-J6N7IR44.js +172 -0
  25. package/dist/chunk-J6N7IR44.js.map +1 -0
  26. package/dist/chunk-N2IHNWBS.js +1002 -0
  27. package/dist/chunk-N2IHNWBS.js.map +1 -0
  28. package/dist/chunk-NAG44K67.js +549 -0
  29. package/dist/chunk-NAG44K67.js.map +1 -0
  30. package/dist/chunk-O24KTEGP.js +33 -0
  31. package/dist/chunk-O24KTEGP.js.map +1 -0
  32. package/dist/chunk-PI2AZVGK.js +2074 -0
  33. package/dist/chunk-PI2AZVGK.js.map +1 -0
  34. package/dist/chunk-Q2FFHEY7.js +40 -0
  35. package/dist/chunk-Q2FFHEY7.js.map +1 -0
  36. package/dist/chunk-RBGQADXA.js +57 -0
  37. package/dist/chunk-RBGQADXA.js.map +1 -0
  38. package/dist/chunk-U5G2BKM2.js +613 -0
  39. package/dist/chunk-U5G2BKM2.js.map +1 -0
  40. package/dist/chunk-VOJHMSM3.js +39 -0
  41. package/dist/chunk-VOJHMSM3.js.map +1 -0
  42. package/dist/chunk-VUNV25KB.js +16 -0
  43. package/dist/chunk-VUNV25KB.js.map +1 -0
  44. package/dist/chunk-XIFUNVBO.js +101 -0
  45. package/dist/chunk-XIFUNVBO.js.map +1 -0
  46. package/dist/chunk-ZCJYRJGB.js +489 -0
  47. package/dist/chunk-ZCJYRJGB.js.map +1 -0
  48. package/dist/chunk-ZZXPEE4S.js +2260 -0
  49. package/dist/chunk-ZZXPEE4S.js.map +1 -0
  50. package/dist/document-docx-api.d.ts +49 -0
  51. package/dist/document-docx-codec.d.ts +9 -0
  52. package/dist/document-docx-codec.js +4765 -0
  53. package/dist/document-docx-codec.js.map +1 -0
  54. package/dist/document-docx-import.d.ts +261 -0
  55. package/dist/document-docx-packer.d.ts +18 -0
  56. package/dist/document-docx-state.d.ts +12 -0
  57. package/dist/document-render.d.ts +3 -0
  58. package/dist/document-render.js +492 -0
  59. package/dist/document-render.js.map +1 -0
  60. package/dist/document.d.ts +432 -0
  61. package/dist/document.js +37 -0
  62. package/dist/document.js.map +1 -0
  63. package/dist/errors.d.ts +23 -0
  64. package/dist/file-blob.d.ts +11 -0
  65. package/dist/index.d.ts +4 -0
  66. package/dist/index.js +186 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/inspection.d.ts +12 -0
  69. package/dist/kernel.d.ts +101 -0
  70. package/dist/lib-GQLPACFK.js +9746 -0
  71. package/dist/lib-GQLPACFK.js.map +1 -0
  72. package/dist/materializer-cli-entry.d.ts +2 -0
  73. package/dist/materializer-cli-entry.js +29 -0
  74. package/dist/materializer-cli-entry.js.map +1 -0
  75. package/dist/materializer-cli.d.ts +24 -0
  76. package/dist/materializer-cli.js +24 -0
  77. package/dist/materializer-cli.js.map +1 -0
  78. package/dist/native-raster.d.ts +10 -0
  79. package/dist/native.d.ts +129 -0
  80. package/dist/native.js +31 -0
  81. package/dist/native.js.map +1 -0
  82. package/dist/office-import.d.ts +48 -0
  83. package/dist/office-import.js +154 -0
  84. package/dist/office-import.js.map +1 -0
  85. package/dist/presentation-pptx-api.d.ts +60 -0
  86. package/dist/presentation-pptx-import.d.ts +5 -0
  87. package/dist/presentation-pptx-state-digest-765CZZED.js +10 -0
  88. package/dist/presentation-pptx-state-digest-765CZZED.js.map +1 -0
  89. package/dist/presentation-pptx-state-digest.d.ts +3 -0
  90. package/dist/presentation-pptx-state.d.ts +4 -0
  91. package/dist/presentation-pptx-xml.d.ts +29 -0
  92. package/dist/presentation-pptx.d.ts +5 -0
  93. package/dist/presentation-pptx.js +2365 -0
  94. package/dist/presentation-pptx.js.map +1 -0
  95. package/dist/presentation-render.d.ts +29 -0
  96. package/dist/presentation-render.js +375 -0
  97. package/dist/presentation-render.js.map +1 -0
  98. package/dist/presentation.d.ts +565 -0
  99. package/dist/presentation.js +71 -0
  100. package/dist/presentation.js.map +1 -0
  101. package/dist/production-composite.d.ts +68 -0
  102. package/dist/production-document.d.ts +2 -0
  103. package/dist/production-document.js +176 -0
  104. package/dist/production-document.js.map +1 -0
  105. package/dist/production-native-codecs.d.ts +94 -0
  106. package/dist/production-presentation.d.ts +2 -0
  107. package/dist/production-presentation.js +176 -0
  108. package/dist/production-presentation.js.map +1 -0
  109. package/dist/production-sha256.d.ts +2 -0
  110. package/dist/production-spreadsheet-native.d.ts +12 -0
  111. package/dist/production-spreadsheet.d.ts +2 -0
  112. package/dist/production-spreadsheet.js +176 -0
  113. package/dist/production-spreadsheet.js.map +1 -0
  114. package/dist/production.d.ts +96 -0
  115. package/dist/raster-image.d.ts +34 -0
  116. package/dist/reference.d.ts +17 -0
  117. package/dist/reference.js +574 -0
  118. package/dist/reference.js.map +1 -0
  119. package/dist/runtime-cli-entry.d.ts +2 -0
  120. package/dist/runtime-cli-entry.js +21 -0
  121. package/dist/runtime-cli-entry.js.map +1 -0
  122. package/dist/runtime-cli.d.ts +76 -0
  123. package/dist/runtime-cli.js +26 -0
  124. package/dist/runtime-cli.js.map +1 -0
  125. package/dist/runtime-development.d.ts +73 -0
  126. package/dist/runtime-development.js +30 -0
  127. package/dist/runtime-development.js.map +1 -0
  128. package/dist/runtime-receipt.d.ts +19 -0
  129. package/dist/runtime.d.ts +355 -0
  130. package/dist/runtime.js +42 -0
  131. package/dist/runtime.js.map +1 -0
  132. package/dist/snapshot.d.ts +26 -0
  133. package/dist/snapshot.js +61 -0
  134. package/dist/snapshot.js.map +1 -0
  135. package/dist/spreadsheet-address.d.ts +18 -0
  136. package/dist/spreadsheet-file.d.ts +17 -0
  137. package/dist/spreadsheet-formula.d.ts +67 -0
  138. package/dist/spreadsheet-image.d.ts +17 -0
  139. package/dist/spreadsheet-render.d.ts +5 -0
  140. package/dist/spreadsheet-render.js +752 -0
  141. package/dist/spreadsheet-render.js.map +1 -0
  142. package/dist/spreadsheet-types.d.ts +155 -0
  143. package/dist/spreadsheet-xlsx-api.d.ts +88 -0
  144. package/dist/spreadsheet-xlsx-codec.d.ts +16 -0
  145. package/dist/spreadsheet-xlsx-codec.js +16 -0
  146. package/dist/spreadsheet-xlsx-codec.js.map +1 -0
  147. package/dist/spreadsheet-xlsx-state.d.ts +16 -0
  148. package/dist/spreadsheet.d.ts +724 -0
  149. package/dist/spreadsheet.js +67 -0
  150. package/dist/spreadsheet.js.map +1 -0
  151. package/package.json +129 -0
  152. package/src/bounded-zip.ts +450 -0
  153. package/src/document-docx-api.ts +64 -0
  154. package/src/document-docx-codec.ts +2253 -0
  155. package/src/document-docx-import.ts +3814 -0
  156. package/src/document-docx-packer.ts +72 -0
  157. package/src/document-docx-state.ts +59 -0
  158. package/src/document-render.ts +615 -0
  159. package/src/document.ts +2800 -0
  160. package/src/errors.ts +45 -0
  161. package/src/file-blob.ts +43 -0
  162. package/src/index.ts +4 -0
  163. package/src/inspection.ts +50 -0
  164. package/src/kernel.ts +525 -0
  165. package/src/materializer-cli-entry.ts +11 -0
  166. package/src/materializer-cli.ts +743 -0
  167. package/src/native-raster.ts +141 -0
  168. package/src/native.ts +390 -0
  169. package/src/office-import.ts +243 -0
  170. package/src/presentation-pptx-api.ts +107 -0
  171. package/src/presentation-pptx-import.ts +2065 -0
  172. package/src/presentation-pptx-state-digest.ts +46 -0
  173. package/src/presentation-pptx-state.ts +18 -0
  174. package/src/presentation-pptx-xml.ts +473 -0
  175. package/src/presentation-pptx.ts +447 -0
  176. package/src/presentation-render.ts +532 -0
  177. package/src/presentation.ts +2599 -0
  178. package/src/production-composite.ts +805 -0
  179. package/src/production-document.ts +2 -0
  180. package/src/production-native-codecs.ts +1141 -0
  181. package/src/production-presentation.ts +2 -0
  182. package/src/production-sha256.ts +150 -0
  183. package/src/production-spreadsheet-native.ts +686 -0
  184. package/src/production-spreadsheet.ts +2 -0
  185. package/src/production.ts +1022 -0
  186. package/src/raster-image.ts +586 -0
  187. package/src/reference.ts +17 -0
  188. package/src/runtime-cli-entry.ts +13 -0
  189. package/src/runtime-cli.ts +670 -0
  190. package/src/runtime-development.ts +689 -0
  191. package/src/runtime-receipt.ts +169 -0
  192. package/src/runtime.ts +1463 -0
  193. package/src/snapshot.ts +88 -0
  194. package/src/spreadsheet-address.ts +90 -0
  195. package/src/spreadsheet-file.ts +71 -0
  196. package/src/spreadsheet-formula.ts +1212 -0
  197. package/src/spreadsheet-image.ts +242 -0
  198. package/src/spreadsheet-render.ts +985 -0
  199. package/src/spreadsheet-types.ts +171 -0
  200. package/src/spreadsheet-xlsx-api.ts +123 -0
  201. package/src/spreadsheet-xlsx-codec.ts +3063 -0
  202. package/src/spreadsheet-xlsx-state.ts +191 -0
  203. package/src/spreadsheet.ts +5195 -0
@@ -0,0 +1,2260 @@
1
+ import {
2
+ SpreadsheetFile
3
+ } from "./chunk-VOJHMSM3.js";
4
+ import {
5
+ CompositeArtifactState,
6
+ requireCompositeState
7
+ } from "./chunk-HTJBLBDE.js";
8
+ import {
9
+ DOCUMENT_LOSS_PRESERVATION
10
+ } from "./chunk-RBGQADXA.js";
11
+ import {
12
+ NativeDocumentSession,
13
+ NativePresentationSession,
14
+ NativeSpreadsheetSession
15
+ } from "./chunk-B2ZJRZDA.js";
16
+ import {
17
+ Document,
18
+ DocumentBlockCollection,
19
+ DocumentCommentThread,
20
+ DocumentComments,
21
+ DocumentFile,
22
+ DocumentParagraph,
23
+ DocumentSection,
24
+ DocumentSections,
25
+ DocumentStory,
26
+ DocumentTable,
27
+ TrackedChanges
28
+ } from "./chunk-66CT2ZRP.js";
29
+ import {
30
+ LOSS_PRESERVATION
31
+ } from "./chunk-J6N7IR44.js";
32
+ import {
33
+ Workbook
34
+ } from "./chunk-IYFXZQ34.js";
35
+ import {
36
+ UnsupportedArtifactFeatureError
37
+ } from "./chunk-O24KTEGP.js";
38
+ import {
39
+ ArtifactRuntimeError
40
+ } from "./chunk-N2IHNWBS.js";
41
+ import {
42
+ Presentation,
43
+ PresentationChart,
44
+ PresentationChartCollection,
45
+ PresentationFile,
46
+ PresentationGroup,
47
+ PresentationGroupCollection,
48
+ PresentationImage,
49
+ PresentationImageCollection,
50
+ PresentationShape,
51
+ PresentationShapeCollection,
52
+ PresentationTable,
53
+ PresentationTableCollection,
54
+ PresentationText,
55
+ Slide,
56
+ SlideCollection,
57
+ colorValue,
58
+ presentationLossState,
59
+ setPresentationLossState
60
+ } from "./chunk-PI2AZVGK.js";
61
+ import {
62
+ decodeRasterBase64,
63
+ inspectRasterImage
64
+ } from "./chunk-FGZM4FQ6.js";
65
+
66
+ // src/production-sha256.ts
67
+ var ROUND_CONSTANTS = Uint32Array.of(
68
+ 1116352408,
69
+ 1899447441,
70
+ 3049323471,
71
+ 3921009573,
72
+ 961987163,
73
+ 1508970993,
74
+ 2453635748,
75
+ 2870763221,
76
+ 3624381080,
77
+ 310598401,
78
+ 607225278,
79
+ 1426881987,
80
+ 1925078388,
81
+ 2162078206,
82
+ 2614888103,
83
+ 3248222580,
84
+ 3835390401,
85
+ 4022224774,
86
+ 264347078,
87
+ 604807628,
88
+ 770255983,
89
+ 1249150122,
90
+ 1555081692,
91
+ 1996064986,
92
+ 2554220882,
93
+ 2821834349,
94
+ 2952996808,
95
+ 3210313671,
96
+ 3336571891,
97
+ 3584528711,
98
+ 113926993,
99
+ 338241895,
100
+ 666307205,
101
+ 773529912,
102
+ 1294757372,
103
+ 1396182291,
104
+ 1695183700,
105
+ 1986661051,
106
+ 2177026350,
107
+ 2456956037,
108
+ 2730485921,
109
+ 2820302411,
110
+ 3259730800,
111
+ 3345764771,
112
+ 3516065817,
113
+ 3600352804,
114
+ 4094571909,
115
+ 275423344,
116
+ 430227734,
117
+ 506948616,
118
+ 659060556,
119
+ 883997877,
120
+ 958139571,
121
+ 1322822218,
122
+ 1537002063,
123
+ 1747873779,
124
+ 1955562222,
125
+ 2024104815,
126
+ 2227730452,
127
+ 2361852424,
128
+ 2428436474,
129
+ 2756734187,
130
+ 3204031479,
131
+ 3329325298
132
+ );
133
+ var INITIAL_STATE = Uint32Array.of(
134
+ 1779033703,
135
+ 3144134277,
136
+ 1013904242,
137
+ 2773480762,
138
+ 1359893119,
139
+ 2600822924,
140
+ 528734635,
141
+ 1541459225
142
+ );
143
+ function sha256Bytes(input) {
144
+ const paddedLength = Math.ceil((input.byteLength + 9) / 64) * 64;
145
+ const padded = new Uint8Array(paddedLength);
146
+ padded.set(input);
147
+ padded[input.byteLength] = 128;
148
+ const bitLength = input.byteLength * 8;
149
+ const paddedView = new DataView(padded.buffer);
150
+ paddedView.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296), false);
151
+ paddedView.setUint32(paddedLength - 4, bitLength >>> 0, false);
152
+ const state = Uint32Array.from(INITIAL_STATE);
153
+ const schedule = new Uint32Array(64);
154
+ for (let offset = 0; offset < paddedLength; offset += 64) {
155
+ for (let index = 0; index < 16; index += 1) {
156
+ schedule[index] = paddedView.getUint32(offset + index * 4, false);
157
+ }
158
+ for (let index = 16; index < 64; index += 1) {
159
+ const previous15 = schedule[index - 15];
160
+ const previous2 = schedule[index - 2];
161
+ const sigma0 = (rotateRight(previous15, 7) ^ rotateRight(previous15, 18) ^ previous15 >>> 3) >>> 0;
162
+ const sigma1 = (rotateRight(previous2, 17) ^ rotateRight(previous2, 19) ^ previous2 >>> 10) >>> 0;
163
+ schedule[index] = schedule[index - 16] + sigma0 + schedule[index - 7] + sigma1 >>> 0;
164
+ }
165
+ let a = state[0];
166
+ let b = state[1];
167
+ let c = state[2];
168
+ let d = state[3];
169
+ let e = state[4];
170
+ let f = state[5];
171
+ let g = state[6];
172
+ let h = state[7];
173
+ for (let index = 0; index < 64; index += 1) {
174
+ const sum1 = (rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25)) >>> 0;
175
+ const choose = (e & f ^ ~e & g) >>> 0;
176
+ const temporary1 = h + sum1 + choose + ROUND_CONSTANTS[index] + schedule[index] >>> 0;
177
+ const sum0 = (rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22)) >>> 0;
178
+ const majority = (a & b ^ a & c ^ b & c) >>> 0;
179
+ const temporary2 = sum0 + majority >>> 0;
180
+ h = g;
181
+ g = f;
182
+ f = e;
183
+ e = d + temporary1 >>> 0;
184
+ d = c;
185
+ c = b;
186
+ b = a;
187
+ a = temporary1 + temporary2 >>> 0;
188
+ }
189
+ state[0] = state[0] + a >>> 0;
190
+ state[1] = state[1] + b >>> 0;
191
+ state[2] = state[2] + c >>> 0;
192
+ state[3] = state[3] + d >>> 0;
193
+ state[4] = state[4] + e >>> 0;
194
+ state[5] = state[5] + f >>> 0;
195
+ state[6] = state[6] + g >>> 0;
196
+ state[7] = state[7] + h >>> 0;
197
+ }
198
+ const output = new Uint8Array(32);
199
+ const outputView = new DataView(output.buffer);
200
+ for (let index = 0; index < state.length; index += 1) {
201
+ outputView.setUint32(index * 4, state[index], false);
202
+ }
203
+ return output;
204
+ }
205
+ function rotateRight(value, bits) {
206
+ return (value >>> bits | value << 32 - bits) >>> 0;
207
+ }
208
+
209
+ // src/production-native-codecs.ts
210
+ var textEncoder = new TextEncoder();
211
+ var DOCUMENT_COMMAND_MAX_BYTES = 64 * 1024 * 1024;
212
+ var DOCUMENT_COMMAND_MAX_COUNT = 4096;
213
+ var PRESENTATION_COMMAND_MAX_BYTES = 4 * 1024 * 1024;
214
+ var PRESENTATION_COMMAND_MAX_COUNT = 1e4;
215
+ var HEADER_BYTES = 24;
216
+ var CHECKSUM_BYTES = 8;
217
+ var EMU_PER_CSS_PIXEL = 9525;
218
+ var PRESENTATION_MAX_COORDINATE_EMU = 9525e9;
219
+ function encodeDocumentProjectionCommands(snapshot) {
220
+ const payload = new ByteWriter(DOCUMENT_COMMAND_MAX_BYTES - HEADER_BYTES - CHECKSUM_BYTES);
221
+ let commandCount = 0;
222
+ const command = (write) => {
223
+ commandCount += 1;
224
+ if (commandCount > DOCUMENT_COMMAND_MAX_COUNT) {
225
+ throw new RangeError("Document projection exceeds the native command-count limit");
226
+ }
227
+ write();
228
+ };
229
+ const firstSection = snapshot.sections[0];
230
+ if (!firstSection || firstSection.startBlockIndex !== 0) {
231
+ throw new Error("Document projection requires one initial section at body offset zero");
232
+ }
233
+ assertInitialDocumentSectionIds(firstSection, snapshot.idNamespace);
234
+ if (snapshot.evenAndOddHeaders !== void 0 || snapshot.trackRevisions !== void 0) {
235
+ command(() => {
236
+ payload.u8(0);
237
+ payload.u8(optionalOptionalBool(snapshot.evenAndOddHeaders));
238
+ payload.u8(optionalOptionalBool(snapshot.trackRevisions));
239
+ });
240
+ }
241
+ if (firstSection.titlePage !== void 0) {
242
+ command(() => {
243
+ payload.u8(9);
244
+ payload.documentId(firstSection.id, "sec");
245
+ payload.u8(optionalBool(firstSection.titlePage));
246
+ });
247
+ }
248
+ if (!isDefaultNativeDocumentPage(firstSection.page)) {
249
+ command(() => {
250
+ payload.u8(14);
251
+ payload.documentId(firstSection.id, "sec");
252
+ payload.pageWithExtras(firstSection.page);
253
+ });
254
+ }
255
+ const laterSections = /* @__PURE__ */ new Map();
256
+ for (const section of snapshot.sections.slice(1)) {
257
+ if (laterSections.has(section.startBlockIndex)) {
258
+ throw new Error("Document projection contains adjacent sections without a body block");
259
+ }
260
+ laterSections.set(section.startBlockIndex, section);
261
+ }
262
+ for (let index = 0; index <= snapshot.blocks.length; index += 1) {
263
+ const section = laterSections.get(index);
264
+ if (section) {
265
+ command(() => writeAddSection(payload, section));
266
+ if (hasNonDefaultDocumentPageExtras(section.page)) {
267
+ command(() => {
268
+ payload.u8(14);
269
+ payload.documentId(section.id, "sec");
270
+ payload.pageWithExtras(section.page);
271
+ });
272
+ }
273
+ }
274
+ const block = snapshot.blocks[index];
275
+ if (block) command(() => writeDocumentBlock(payload, block, { kind: "body" }));
276
+ }
277
+ if ([...laterSections.keys()].some((index) => index > snapshot.blocks.length)) {
278
+ throw new Error("Document section starts beyond the body block list");
279
+ }
280
+ for (const section of snapshot.sections) {
281
+ writeDocumentStoryCommands(
282
+ payload,
283
+ command,
284
+ section,
285
+ "header",
286
+ "default",
287
+ section.headers.default
288
+ );
289
+ writeDocumentStoryCommands(payload, command, section, "header", "first", section.headers.first);
290
+ writeDocumentStoryCommands(payload, command, section, "header", "even", section.headers.even);
291
+ writeDocumentStoryCommands(
292
+ payload,
293
+ command,
294
+ section,
295
+ "footer",
296
+ "default",
297
+ section.footers.default
298
+ );
299
+ writeDocumentStoryCommands(payload, command, section, "footer", "first", section.footers.first);
300
+ writeDocumentStoryCommands(payload, command, section, "footer", "even", section.footers.even);
301
+ }
302
+ for (const thread of snapshot.comments) {
303
+ const root = thread.replies[0];
304
+ if (!root) throw new Error(`Document comment ${thread.id} has no root reply`);
305
+ command(() => {
306
+ payload.u8(10);
307
+ payload.documentId(thread.id, "dc");
308
+ payload.documentId(thread.blockId, "p");
309
+ payload.u32(thread.start);
310
+ payload.u32(thread.end);
311
+ payload.bool(thread.resolved);
312
+ payload.commentReply(root);
313
+ });
314
+ for (const reply of thread.replies.slice(1)) {
315
+ command(() => {
316
+ payload.u8(11);
317
+ payload.documentId(thread.id, "dc");
318
+ payload.commentReply(reply);
319
+ });
320
+ }
321
+ }
322
+ for (const change of snapshot.changes) {
323
+ command(() => {
324
+ payload.u8(13);
325
+ payload.documentId(change.id, "chg");
326
+ payload.documentId(change.blockId, "p");
327
+ payload.u32(change.start);
328
+ payload.u32(change.end);
329
+ payload.u8(change.kind === "insert" ? 1 : 2);
330
+ payload.string(change.author);
331
+ payload.string(change.createdAt);
332
+ });
333
+ }
334
+ return envelope("OGADC001", commandCount, payload.finish(), DOCUMENT_COMMAND_MAX_BYTES);
335
+ }
336
+ function encodeDocumentIncrementalCommands(commands) {
337
+ const payload = new ByteWriter(DOCUMENT_COMMAND_MAX_BYTES - HEADER_BYTES - CHECKSUM_BYTES);
338
+ if (commands.length === 0 || commands.length > DOCUMENT_COMMAND_MAX_COUNT) {
339
+ throw new RangeError("Document incremental command count is outside its limit");
340
+ }
341
+ for (const command of commands) {
342
+ switch (command.kind) {
343
+ case "block.add":
344
+ writeDocumentBlock(payload, command.block, command.target);
345
+ break;
346
+ case "paragraph.edit":
347
+ payload.u8(2);
348
+ payload.documentId(command.id, "p");
349
+ payload.u32(command.start);
350
+ payload.u32(command.end);
351
+ payload.string(command.text);
352
+ payload.bool(command.style !== void 0);
353
+ if (command.style) payload.textStyle(command.style);
354
+ break;
355
+ case "paragraph.format":
356
+ payload.u8(3);
357
+ payload.documentId(command.id, "p");
358
+ payload.u32(command.format.start);
359
+ payload.u32(command.format.end);
360
+ payload.textStylePatch(command.format.style);
361
+ break;
362
+ case "paragraph.style":
363
+ payload.u8(4);
364
+ payload.documentId(command.id, "p");
365
+ payload.paragraphStyle(command.style);
366
+ break;
367
+ case "table.style":
368
+ payload.u8(6);
369
+ payload.documentId(command.id, "dt");
370
+ payload.tableStyle(command.style);
371
+ break;
372
+ case "document.flags":
373
+ payload.u8(0);
374
+ payload.u8(optionalOptionalBool(command.evenAndOddHeaders));
375
+ payload.u8(optionalOptionalBool(command.trackRevisions));
376
+ break;
377
+ case "section.add":
378
+ writeAddSection(payload, command.section);
379
+ if (hasNonDefaultDocumentPageExtras(command.section.page)) {
380
+ payload.u8(14);
381
+ payload.documentId(command.section.id, "sec");
382
+ payload.pageWithExtras(command.section.page);
383
+ }
384
+ break;
385
+ case "section.title":
386
+ payload.u8(9);
387
+ payload.documentId(command.id, "sec");
388
+ payload.u8(optionalBool(command.titlePage));
389
+ break;
390
+ case "comment.add": {
391
+ const root = command.comment.replies[0];
392
+ if (!root) throw new Error(`Document comment ${command.comment.id} has no root reply`);
393
+ payload.u8(10);
394
+ payload.documentId(command.comment.id, "dc");
395
+ payload.documentId(command.comment.blockId, "p");
396
+ payload.u32(command.comment.start);
397
+ payload.u32(command.comment.end);
398
+ payload.bool(command.comment.resolved);
399
+ payload.commentReply(root);
400
+ break;
401
+ }
402
+ case "comment.reply":
403
+ payload.u8(11);
404
+ payload.documentId(command.id, "dc");
405
+ payload.commentReply(command.reply);
406
+ break;
407
+ case "comment.resolved":
408
+ payload.u8(12);
409
+ payload.documentId(command.id, "dc");
410
+ payload.bool(command.resolved);
411
+ break;
412
+ case "tracked.add":
413
+ payload.u8(13);
414
+ payload.documentId(command.change.id, "chg");
415
+ payload.documentId(command.change.blockId, "p");
416
+ payload.u32(command.change.start);
417
+ payload.u32(command.change.end);
418
+ payload.u8(command.change.kind === "insert" ? 1 : 2);
419
+ payload.string(command.change.author);
420
+ payload.string(command.change.createdAt);
421
+ break;
422
+ }
423
+ }
424
+ const commandCount = commands.length + commands.filter(
425
+ (command) => command.kind === "section.add" && hasNonDefaultDocumentPageExtras(command.section.page)
426
+ ).length;
427
+ return envelope("OGADC001", commandCount, payload.finish(), DOCUMENT_COMMAND_MAX_BYTES);
428
+ }
429
+ function encodePresentationProjectionCommands(presentation, namespace) {
430
+ const hasCustomSlideSize = presentation.slideSize.width !== 1280 || presentation.slideSize.height !== 720;
431
+ if (hasCustomSlideSize) {
432
+ assertFinitePositive(presentation.slideSize.width, "presentation slide width");
433
+ assertFinitePositive(presentation.slideSize.height, "presentation slide height");
434
+ }
435
+ const payload = new ByteWriter(PRESENTATION_COMMAND_MAX_BYTES - HEADER_BYTES - CHECKSUM_BYTES);
436
+ let commandCount = 0;
437
+ const command = (write) => {
438
+ commandCount += 1;
439
+ if (commandCount > PRESENTATION_COMMAND_MAX_COUNT) {
440
+ throw new RangeError("Presentation projection exceeds the native command-count limit");
441
+ }
442
+ write();
443
+ };
444
+ if (hasCustomSlideSize) {
445
+ command(() => {
446
+ payload.u8(15);
447
+ payload.i64(presentationSizeEmu(presentation.slideSize.width, "presentation slide width"));
448
+ payload.i64(presentationSizeEmu(presentation.slideSize.height, "presentation slide height"));
449
+ });
450
+ }
451
+ let templateElementCounter = 0xffffffffffffffffn;
452
+ const nextTemplateElementId = () => {
453
+ if (templateElementCounter === 0n) {
454
+ throw new RangeError("Presentation template element id space is exhausted");
455
+ }
456
+ return `sh/${templateElementCounter--}`;
457
+ };
458
+ for (const master of presentation.masters.items) {
459
+ command(() => {
460
+ payload.u8(0);
461
+ payload.presentationId(master.id, namespace);
462
+ payload.string(master.name);
463
+ payload.fill(master.background);
464
+ });
465
+ for (const [index, template] of master.elements.entries()) {
466
+ const element = materializeTemplateElement(template);
467
+ writePresentationElement(
468
+ payload,
469
+ command,
470
+ element,
471
+ namespace,
472
+ { tag: 0, id: master.id },
473
+ void 0,
474
+ index,
475
+ nextTemplateElementId()
476
+ );
477
+ }
478
+ }
479
+ for (const layout of presentation.layouts.items) {
480
+ command(() => {
481
+ payload.u8(1);
482
+ payload.presentationId(layout.id, namespace);
483
+ payload.string(layout.name);
484
+ payload.optionalPresentationId(layout.masterId, namespace);
485
+ payload.fill(layout.background);
486
+ });
487
+ for (const [index, template] of layout.elements.entries()) {
488
+ const element = materializeTemplateElement(template);
489
+ writePresentationElement(
490
+ payload,
491
+ command,
492
+ element,
493
+ namespace,
494
+ { tag: 1, id: layout.id },
495
+ void 0,
496
+ index,
497
+ nextTemplateElementId()
498
+ );
499
+ }
500
+ }
501
+ for (const [slideIndex, slide] of presentation.slides.items.entries()) {
502
+ command(() => {
503
+ payload.u8(2);
504
+ payload.presentationId(slide.id, namespace);
505
+ payload.u32(slideIndex);
506
+ payload.string(slide.title);
507
+ payload.optionalPresentationId(slide.layout?.id, namespace);
508
+ payload.fill(slide.background.fill);
509
+ });
510
+ if (slide.notes.toString().length > 0) {
511
+ command(() => {
512
+ payload.u8(8);
513
+ payload.presentationId(slide.id, namespace);
514
+ payload.richText(slide.notes);
515
+ });
516
+ }
517
+ for (const [index, element] of slide.elements.entries()) {
518
+ writePresentationElement(
519
+ payload,
520
+ command,
521
+ element,
522
+ namespace,
523
+ { tag: 2, id: slide.id },
524
+ void 0,
525
+ index
526
+ );
527
+ }
528
+ }
529
+ return envelope("OGAPC001", commandCount, payload.finish(), PRESENTATION_COMMAND_MAX_BYTES);
530
+ }
531
+ function encodePresentationIncrementalCommands(commands, namespace) {
532
+ const payload = new ByteWriter(PRESENTATION_COMMAND_MAX_BYTES - HEADER_BYTES - CHECKSUM_BYTES);
533
+ let commandCount = 0;
534
+ const command = (write) => {
535
+ commandCount += 1;
536
+ if (commandCount > PRESENTATION_COMMAND_MAX_COUNT) {
537
+ throw new RangeError("Presentation incremental command count is outside its limit");
538
+ }
539
+ write();
540
+ };
541
+ for (const entry of commands) {
542
+ switch (entry.kind) {
543
+ case "slide.create":
544
+ command(() => {
545
+ payload.u8(2);
546
+ payload.presentationId(entry.slide.id, namespace);
547
+ payload.u32(entry.index);
548
+ payload.string(entry.slide.title);
549
+ payload.optionalPresentationId(entry.slide.layout?.id, namespace);
550
+ payload.fill(entry.slide.background.fill);
551
+ });
552
+ break;
553
+ case "slide.title":
554
+ command(() => {
555
+ payload.u8(6);
556
+ payload.presentationId(entry.id, namespace);
557
+ payload.string(entry.title);
558
+ });
559
+ break;
560
+ case "slide.layout":
561
+ command(() => {
562
+ payload.u8(7);
563
+ payload.presentationId(entry.id, namespace);
564
+ payload.optionalPresentationId(entry.layoutId, namespace);
565
+ });
566
+ break;
567
+ case "slide.notes":
568
+ command(() => {
569
+ payload.u8(8);
570
+ payload.presentationId(entry.id, namespace);
571
+ payload.richText(entry.notes);
572
+ });
573
+ break;
574
+ case "node.insert":
575
+ writePresentationElement(
576
+ payload,
577
+ command,
578
+ entry.element,
579
+ namespace,
580
+ { tag: 2, id: entry.slideId },
581
+ void 0,
582
+ entry.index
583
+ );
584
+ break;
585
+ case "node.update":
586
+ command(() => {
587
+ payload.u8(12);
588
+ payload.presentationId(entry.element.id, namespace);
589
+ payload.presentationRect(entry.element.position);
590
+ });
591
+ command(() => {
592
+ payload.u8(13);
593
+ payload.presentationId(entry.element.id, namespace);
594
+ payload.presentationTransform(
595
+ "rotation" in entry.element ? entry.element.rotation : 0,
596
+ "flipHorizontal" in entry.element ? entry.element.flipHorizontal : false,
597
+ "flipVertical" in entry.element ? entry.element.flipVertical : false
598
+ );
599
+ });
600
+ command(() => {
601
+ payload.u8(14);
602
+ payload.presentationId(entry.element.id, namespace);
603
+ payload.presentationNode(entry.element);
604
+ });
605
+ break;
606
+ case "presentation.size":
607
+ command(() => {
608
+ payload.u8(15);
609
+ payload.i64(presentationSizeEmu(entry.width, "presentation slide width"));
610
+ payload.i64(presentationSizeEmu(entry.height, "presentation slide height"));
611
+ });
612
+ break;
613
+ }
614
+ }
615
+ if (commandCount === 0) throw new RangeError("Presentation incremental command batch is empty");
616
+ return envelope("OGAPC001", commandCount, payload.finish(), PRESENTATION_COMMAND_MAX_BYTES);
617
+ }
618
+ function materializeTemplateElement(template) {
619
+ const scratch = Presentation.create();
620
+ const slide = scratch.slides.add();
621
+ switch (template.kind) {
622
+ case "shape":
623
+ return slide.shapes.add(template.config);
624
+ case "chart":
625
+ return slide.charts.add(template.type, template.config);
626
+ case "image":
627
+ return slide.images.add(template.config);
628
+ case "table":
629
+ return slide.tables.add(template.config);
630
+ }
631
+ }
632
+ function writeDocumentStoryCommands(writer, command, section, kind, variant, story) {
633
+ const expectedPrefix = kind === "header" ? "hdr" : "ftr";
634
+ writer.assertDocumentId(story.id, expectedPrefix);
635
+ for (const block of story.blocks) {
636
+ command(
637
+ () => writeDocumentBlock(writer, block, {
638
+ kind: "story",
639
+ sectionId: section.id,
640
+ storyKind: kind,
641
+ variant
642
+ })
643
+ );
644
+ }
645
+ }
646
+ function writeDocumentBlock(writer, block, target) {
647
+ if (block.kind === "paragraph") {
648
+ writer.u8(1);
649
+ writer.documentTarget(target);
650
+ writer.documentId(block.id, "p");
651
+ writer.textRuns(block.runs);
652
+ writer.paragraphStyle(block.style);
653
+ return;
654
+ }
655
+ if (block.kind === "table") {
656
+ writer.u8(5);
657
+ writer.documentTarget(target);
658
+ writer.documentId(block.id, "dt");
659
+ writer.u32(block.rows.length);
660
+ for (const row of block.rows) {
661
+ writer.u32(row.length);
662
+ for (const cell of row) writer.textRuns(cell);
663
+ }
664
+ writer.tableStyle(block.style);
665
+ return;
666
+ }
667
+ if (target.kind !== "body") {
668
+ throw new Error("Document story cannot contain a page break");
669
+ }
670
+ writer.u8(7);
671
+ writer.documentId(block.id, "pb");
672
+ }
673
+ function writeAddSection(writer, section) {
674
+ writer.u8(8);
675
+ writer.documentId(section.id, "sec");
676
+ writer.documentId(section.headers.default.id, "hdr");
677
+ writer.documentId(section.headers.first.id, "hdr");
678
+ writer.documentId(section.headers.even.id, "hdr");
679
+ writer.documentId(section.footers.default.id, "ftr");
680
+ writer.documentId(section.footers.first.id, "ftr");
681
+ writer.documentId(section.footers.even.id, "ftr");
682
+ writer.page(section.page);
683
+ writer.u8(optionalBool(section.titlePage));
684
+ }
685
+ function assertInitialDocumentSectionIds(section, namespace) {
686
+ const expected = [
687
+ [section.id, "sec", 1n],
688
+ [section.headers.default.id, "hdr", 2n],
689
+ [section.headers.first.id, "hdr", 3n],
690
+ [section.headers.even.id, "hdr", 4n],
691
+ [section.footers.default.id, "ftr", 5n],
692
+ [section.footers.first.id, "ftr", 6n],
693
+ [section.footers.even.id, "ftr", 7n]
694
+ ];
695
+ for (const [id, prefix, counter] of expected) {
696
+ const parsed = parseDocumentId(id, prefix);
697
+ if (parsed.namespace !== BigInt(`0x${namespace}`) || parsed.counter !== counter) {
698
+ throw new Error("Initial document structural ids do not match the native document allocator");
699
+ }
700
+ }
701
+ }
702
+ function isDefaultNativeDocumentPage(page) {
703
+ return page.widthPt === 612 && page.heightPt === 792 && page.marginTopPt === 72 && page.marginRightPt === 72 && page.marginBottomPt === 72 && page.marginLeftPt === 72 && !hasNonDefaultDocumentPageExtras(page);
704
+ }
705
+ function hasNonDefaultDocumentPageExtras(page) {
706
+ return (page.headerPt ?? 36) !== 36 || (page.footerPt ?? 36) !== 36 || (page.gutterPt ?? 0) !== 0;
707
+ }
708
+ function writePresentationElement(writer, command, element, namespace, owner, parentId, index, idOverride) {
709
+ const elementId = idOverride ?? element.id;
710
+ command(() => {
711
+ writer.u8(9);
712
+ writer.u8(owner.tag);
713
+ writer.presentationId(owner.id, namespace);
714
+ writer.optionalPresentationId(parentId, namespace);
715
+ writer.u32(index);
716
+ writer.presentationId(elementId, namespace);
717
+ writer.string(element.name);
718
+ writer.presentationRect(element.position);
719
+ writer.presentationTransform(
720
+ "rotation" in element ? element.rotation : 0,
721
+ "flipHorizontal" in element ? element.flipHorizontal : false,
722
+ "flipVertical" in element ? element.flipVertical : false
723
+ );
724
+ writer.presentationNode(element);
725
+ });
726
+ if (element instanceof PresentationGroup) {
727
+ for (const [childIndex, child] of element.children.entries()) {
728
+ writePresentationElement(writer, command, child, namespace, owner, elementId, childIndex);
729
+ }
730
+ }
731
+ }
732
+ function unsupportedPresentation(feature) {
733
+ throw new UnsupportedArtifactFeatureError("presentation", feature, "native Rust projection");
734
+ }
735
+ var ByteWriter = class {
736
+ constructor(maximum) {
737
+ this.maximum = maximum;
738
+ }
739
+ #bytes = [];
740
+ finish() {
741
+ return Uint8Array.from(this.#bytes);
742
+ }
743
+ bytes(value) {
744
+ if (this.#bytes.length + value.byteLength > this.maximum) {
745
+ throw new RangeError("Native projection command envelope exceeds its byte limit");
746
+ }
747
+ this.#bytes.push(...value);
748
+ }
749
+ u8(value) {
750
+ this.bytes(Uint8Array.of(value));
751
+ }
752
+ bool(value) {
753
+ this.u8(value ? 1 : 0);
754
+ }
755
+ u16(value) {
756
+ const bytes = new Uint8Array(2);
757
+ new DataView(bytes.buffer).setUint16(0, value, true);
758
+ this.bytes(bytes);
759
+ }
760
+ u32(value) {
761
+ if (!Number.isSafeInteger(value) || value < 0 || value > 4294967295) {
762
+ throw new RangeError("Native projection integer is outside u32");
763
+ }
764
+ const bytes = new Uint8Array(4);
765
+ new DataView(bytes.buffer).setUint32(0, value, true);
766
+ this.bytes(bytes);
767
+ }
768
+ i32(value) {
769
+ if (!Number.isSafeInteger(value) || value < -2147483648 || value > 2147483647) {
770
+ throw new RangeError("Native projection integer is outside i32");
771
+ }
772
+ const bytes = new Uint8Array(4);
773
+ new DataView(bytes.buffer).setInt32(0, value, true);
774
+ this.bytes(bytes);
775
+ }
776
+ u64(value) {
777
+ if (value < 0n || value > 0xffffffffffffffffn) {
778
+ throw new RangeError("Native projection integer is outside u64");
779
+ }
780
+ const bytes = new Uint8Array(8);
781
+ new DataView(bytes.buffer).setBigUint64(0, value, true);
782
+ this.bytes(bytes);
783
+ }
784
+ i64(value) {
785
+ const bytes = new Uint8Array(8);
786
+ new DataView(bytes.buffer).setBigInt64(0, value, true);
787
+ this.bytes(bytes);
788
+ }
789
+ f64(value) {
790
+ if (!Number.isFinite(value) || Object.is(value, -0)) {
791
+ throw new TypeError("Native projection numbers must be finite canonical doubles");
792
+ }
793
+ const bytes = new Uint8Array(8);
794
+ new DataView(bytes.buffer).setFloat64(0, value, true);
795
+ this.bytes(bytes);
796
+ }
797
+ string(value) {
798
+ const encoded = textEncoder.encode(value);
799
+ this.u32(encoded.byteLength);
800
+ this.bytes(encoded);
801
+ }
802
+ optionalString(value) {
803
+ this.bool(value !== void 0);
804
+ if (value !== void 0) this.string(value);
805
+ }
806
+ assertDocumentId(id, expectedPrefix) {
807
+ parseDocumentId(id, expectedPrefix);
808
+ }
809
+ documentId(id, expectedPrefix) {
810
+ const parsed = parseDocumentId(id, expectedPrefix);
811
+ this.u8(documentKindTag(expectedPrefix));
812
+ this.u64(parsed.namespace);
813
+ this.u64(parsed.counter);
814
+ }
815
+ documentTarget(target) {
816
+ if (target.kind === "body") {
817
+ this.u8(0);
818
+ return;
819
+ }
820
+ this.u8(1);
821
+ this.documentId(target.sectionId, "sec");
822
+ this.u8(target.storyKind === "header" ? 1 : 2);
823
+ this.u8(target.variant === "default" ? 1 : target.variant === "first" ? 2 : 3);
824
+ }
825
+ page(page) {
826
+ this.f64(page.widthPt);
827
+ this.f64(page.heightPt);
828
+ this.f64(page.marginTopPt);
829
+ this.f64(page.marginRightPt);
830
+ this.f64(page.marginBottomPt);
831
+ this.f64(page.marginLeftPt);
832
+ }
833
+ pageWithExtras(page) {
834
+ this.page(page);
835
+ this.f64(page.headerPt ?? 36);
836
+ this.f64(page.footerPt ?? 36);
837
+ this.f64(page.gutterPt ?? 0);
838
+ }
839
+ textRuns(runs) {
840
+ this.u32(runs.length);
841
+ for (const run of runs) {
842
+ this.string(run.text);
843
+ this.textStyle(run.style);
844
+ }
845
+ }
846
+ textStyle(style) {
847
+ const mask = Number(style.fontFamily !== void 0) | Number(style.fontSizePt !== void 0) << 1 | Number(style.color !== void 0) << 2 | Number(style.bold !== void 0) << 3 | Number(style.italic !== void 0) << 4 | Number(style.underline !== void 0) << 5 | Number(style.strike !== void 0) << 6;
848
+ this.u8(mask);
849
+ if (style.fontFamily !== void 0) this.string(style.fontFamily);
850
+ if (style.fontSizePt !== void 0) this.f64(style.fontSizePt);
851
+ if (style.color !== void 0) this.string(style.color);
852
+ for (const value of [style.bold, style.italic, style.underline, style.strike]) {
853
+ if (value !== void 0) this.bool(value);
854
+ }
855
+ }
856
+ textStylePatch(style) {
857
+ this.patchString(style.fontFamily);
858
+ this.patchF64(style.fontSizePt);
859
+ this.patchString(style.color);
860
+ this.patchBool(style.bold);
861
+ this.patchBool(style.italic);
862
+ this.patchBool(style.underline);
863
+ this.patchBool(style.strike);
864
+ }
865
+ patchString(value) {
866
+ this.u8(value === void 0 ? 0 : value === null ? 1 : 2);
867
+ if (typeof value === "string") this.string(value);
868
+ }
869
+ patchF64(value) {
870
+ this.u8(value === void 0 ? 0 : value === null ? 1 : 2);
871
+ if (typeof value === "number") this.f64(value);
872
+ }
873
+ patchBool(value) {
874
+ this.u8(value === void 0 ? 0 : value === null ? 1 : value ? 3 : 2);
875
+ }
876
+ paragraphStyle(style) {
877
+ const mask = Number(style.headingLevel !== void 0) | Number(style.alignment !== void 0) << 1 | Number(style.spaceBeforePt !== void 0) << 2 | Number(style.spaceAfterPt !== void 0) << 3 | Number(style.lineHeight !== void 0) << 4 | Number(style.keepNext !== void 0) << 5 | Number(style.pageBreakBefore !== void 0) << 6 | Number(style.list !== void 0) << 7;
878
+ this.u16(mask);
879
+ if (style.headingLevel !== void 0) this.u8(style.headingLevel);
880
+ if (style.alignment !== void 0) {
881
+ this.u8({ left: 1, center: 2, right: 3, justify: 4 }[style.alignment]);
882
+ }
883
+ for (const value of [style.spaceBeforePt, style.spaceAfterPt, style.lineHeight]) {
884
+ if (value !== void 0) this.f64(value);
885
+ }
886
+ for (const value of [style.keepNext, style.pageBreakBefore]) {
887
+ if (value !== void 0) this.bool(value);
888
+ }
889
+ if (style.list) {
890
+ this.u8(style.list.kind === "bullet" ? 1 : 2);
891
+ this.bool(style.list.level !== void 0);
892
+ if (style.list.level !== void 0) this.u8(style.list.level);
893
+ this.optionalString(style.list.instanceId);
894
+ }
895
+ }
896
+ tableStyle(style) {
897
+ const mask = Number(style.widthPt !== void 0) | Number(style.columnWidthsPt !== void 0) << 1 | Number(style.headerRows !== void 0) << 2 | Number(style.cellPaddingPt !== void 0) << 3 | Number(style.borderColor !== void 0) << 4 | Number(style.headerFill !== void 0) << 5 | Number(style.allowRowSplit !== void 0) << 6;
898
+ this.u8(mask);
899
+ if (style.widthPt !== void 0) this.f64(style.widthPt);
900
+ if (style.columnWidthsPt !== void 0) {
901
+ this.u32(style.columnWidthsPt.length);
902
+ for (const width of style.columnWidthsPt) this.f64(width);
903
+ }
904
+ if (style.headerRows !== void 0) this.u32(style.headerRows);
905
+ if (style.cellPaddingPt !== void 0) this.f64(style.cellPaddingPt);
906
+ if (style.borderColor !== void 0) this.string(style.borderColor);
907
+ if (style.headerFill !== void 0) this.string(style.headerFill);
908
+ if (style.allowRowSplit !== void 0) this.bool(style.allowRowSplit);
909
+ }
910
+ commentReply(reply) {
911
+ this.string(reply.author);
912
+ this.string(reply.text);
913
+ this.string(reply.createdAt);
914
+ }
915
+ presentationId(id, namespace) {
916
+ const counter = presentationCounter(id);
917
+ this.u64(counter);
918
+ this.u64(namespace);
919
+ }
920
+ optionalPresentationId(id, namespace) {
921
+ this.bool(id !== void 0);
922
+ if (id !== void 0) this.presentationId(id, namespace);
923
+ }
924
+ fill(fill) {
925
+ const value = colorValue(fill);
926
+ if (value === "none") {
927
+ this.u8(0);
928
+ return;
929
+ }
930
+ this.u8(1);
931
+ const rgb = Number.parseInt(value.slice(1), 16);
932
+ this.u32(rgb * 256 + 255 >>> 0);
933
+ }
934
+ line(line) {
935
+ this.fill(line.fill ?? "black");
936
+ this.i64(cssPixels(line.width ?? 1));
937
+ this.u8(line.style === "dash" ? 1 : line.style === "dot" ? 2 : 0);
938
+ }
939
+ presentationRect(position) {
940
+ this.i64(cssPixels(position.left));
941
+ this.i64(cssPixels(position.top));
942
+ this.i64(cssPixels(position.width));
943
+ this.i64(cssPixels(position.height));
944
+ }
945
+ presentationTransform(rotation, flipHorizontal, flipVertical) {
946
+ this.i32(Math.round(rotation * 6e4));
947
+ this.bool(flipHorizontal);
948
+ this.bool(flipVertical);
949
+ }
950
+ richText(text, fallbackStyle = {}) {
951
+ const style = { ...fallbackStyle, ...text.style };
952
+ this.u8(
953
+ style.verticalAlignment === "middle" ? 1 : style.verticalAlignment === "bottom" ? 2 : 0
954
+ );
955
+ this.u32(1);
956
+ this.u8(
957
+ style.alignment === "center" ? 1 : style.alignment === "right" ? 2 : style.alignment === "justify" ? 3 : 0
958
+ );
959
+ this.u32(1);
960
+ this.string(text.toString());
961
+ this.presentationTextStyle(style);
962
+ }
963
+ plainRichText(value, style = {}) {
964
+ this.u8(
965
+ style.verticalAlignment === "middle" ? 1 : style.verticalAlignment === "bottom" ? 2 : 0
966
+ );
967
+ this.u32(1);
968
+ this.u8(
969
+ style.alignment === "center" ? 1 : style.alignment === "right" ? 2 : style.alignment === "justify" ? 3 : 0
970
+ );
971
+ this.u32(1);
972
+ this.string(value);
973
+ this.presentationTextStyle(style);
974
+ }
975
+ presentationTextStyle(style) {
976
+ this.string(style.fontFamily ?? "Arial");
977
+ this.u32(Math.round((style.fontSize ?? 18) * 100));
978
+ const color = colorValue(style.color ?? "black");
979
+ const rgb = color === "none" ? 0 : Number.parseInt(color.slice(1), 16);
980
+ this.u32(rgb * 256 + (color === "none" ? 0 : 255) >>> 0);
981
+ this.bool(style.bold ?? false);
982
+ this.bool(style.italic ?? false);
983
+ this.bool(style.underline ?? false);
984
+ this.bool(false);
985
+ }
986
+ presentationNode(element) {
987
+ if (element instanceof PresentationShape) {
988
+ this.u8(0);
989
+ this.u8(
990
+ { textbox: 0, rect: 1, roundRect: 2, ellipse: 3, triangle: 4, rightArrow: 5, line: 6 }[element.geometry]
991
+ );
992
+ this.fill(element.fill);
993
+ this.line(element.line);
994
+ const hasText = element.text.toString().length > 0;
995
+ this.bool(hasText);
996
+ if (hasText) this.richText(element.text);
997
+ this.bool(element.placeholder !== void 0);
998
+ if (element.placeholder) {
999
+ this.string(element.placeholder.type);
1000
+ this.bool(element.placeholder.index !== void 0);
1001
+ if (element.placeholder.index !== void 0) this.u32(element.placeholder.index);
1002
+ }
1003
+ return;
1004
+ }
1005
+ if (element instanceof PresentationGroup) {
1006
+ this.u8(1);
1007
+ this.i64(cssPixels(element.childOffset.left));
1008
+ this.i64(cssPixels(element.childOffset.top));
1009
+ this.i64(cssPixels(element.childExtent.width));
1010
+ this.i64(cssPixels(element.childExtent.height));
1011
+ this.u32(0);
1012
+ return;
1013
+ }
1014
+ if (element instanceof PresentationChart) {
1015
+ this.u8(3);
1016
+ this.u8(
1017
+ { bar: 0, line: 1, area: 2, pie: 3, doughnut: 4, scatter: 5, bubble: 6, radar: 7 }[element.type]
1018
+ );
1019
+ this.plainRichText(element.title);
1020
+ this.u32(element.series.items.length);
1021
+ for (const series of element.series.items) {
1022
+ this.string(series.name);
1023
+ this.stringVector(series.categories.length > 0 ? series.categories : element.categories);
1024
+ this.numberVector(series.values);
1025
+ this.numberVector(series.xValues);
1026
+ this.numberVector(series.bubbleSizes);
1027
+ }
1028
+ this.bool(element.hasLegend);
1029
+ return;
1030
+ }
1031
+ if (element instanceof PresentationTable) {
1032
+ this.u8(4);
1033
+ this.u32(element.rows.length);
1034
+ this.u32(element.rows[0]?.length ?? 0);
1035
+ for (const row of element.rows) {
1036
+ for (const cell of row) {
1037
+ this.bool(cell !== null);
1038
+ if (cell) {
1039
+ this.richText(cell.text, element.textStyle);
1040
+ this.fill(cell.fill);
1041
+ this.u16(cell.rowSpan);
1042
+ this.u16(cell.colSpan);
1043
+ }
1044
+ }
1045
+ }
1046
+ this.u32(element.columnWidths.length);
1047
+ for (const width of element.columnWidths) this.i64(cssPixels(width));
1048
+ this.u32(element.rowHeights.length);
1049
+ for (const height of element.rowHeights) this.i64(cssPixels(height));
1050
+ this.line(element.line);
1051
+ return;
1052
+ }
1053
+ if (element instanceof PresentationImage) {
1054
+ const source = element.sourceForSvg();
1055
+ if (!source) {
1056
+ unsupportedPresentation("prompt-only raster image scene nodes");
1057
+ }
1058
+ const match = /^data:([^;,]+);base64,([A-Za-z0-9+/]*={0,2})$/u.exec(source);
1059
+ if (!match) throw new Error(`Presentation image ${element.id} has a non-canonical source`);
1060
+ const bytes = decodeRasterBase64(match[2]);
1061
+ const metadata = inspectRasterImage(bytes);
1062
+ if (metadata.contentType !== match[1] || metadata.contentType !== element.contentType) {
1063
+ throw new Error(`Presentation image ${element.id} MIME metadata diverged`);
1064
+ }
1065
+ this.u8(5);
1066
+ this.bytes(sha256Bytes(bytes));
1067
+ this.string(metadata.contentType);
1068
+ this.string(element.alt);
1069
+ this.u8(element.fit === "contain" ? 0 : 1);
1070
+ this.u32(metadata.width);
1071
+ this.u32(metadata.height);
1072
+ return;
1073
+ }
1074
+ unsupportedPresentation("unknown scene node");
1075
+ }
1076
+ stringVector(values) {
1077
+ this.u32(values.length);
1078
+ for (const value of values) this.string(value);
1079
+ }
1080
+ numberVector(values) {
1081
+ this.u32(values.length);
1082
+ for (const value of values) this.f64(value);
1083
+ }
1084
+ };
1085
+ function envelope(magic, count, payload, maximum) {
1086
+ const output = new Uint8Array(HEADER_BYTES + payload.byteLength + CHECKSUM_BYTES);
1087
+ if (output.byteLength > maximum) throw new RangeError(`${magic} envelope exceeds its byte limit`);
1088
+ output.set(textEncoder.encode(magic), 0);
1089
+ const view = new DataView(output.buffer);
1090
+ view.setUint16(8, 1, true);
1091
+ view.setUint32(12, count, true);
1092
+ view.setBigUint64(16, BigInt(payload.byteLength), true);
1093
+ output.set(payload, HEADER_BYTES);
1094
+ view.setBigUint64(HEADER_BYTES + payload.byteLength, fnv1a64(output.subarray(0, -8)), true);
1095
+ return output;
1096
+ }
1097
+ function parseDocumentId(id, expectedPrefix) {
1098
+ const match = /^([a-z]{1,8})\/([0-9a-f]{16})([0-9a-f]{16})$/u.exec(id);
1099
+ if (!match || match[1] !== expectedPrefix) {
1100
+ throw new Error(`Document id ${id} is not a canonical ${expectedPrefix} id`);
1101
+ }
1102
+ const counter = BigInt(`0x${match[3]}`);
1103
+ if (counter === 0n) throw new Error(`Document id ${id} uses the reserved zero counter`);
1104
+ return { namespace: BigInt(`0x${match[2]}`), counter };
1105
+ }
1106
+ function documentKindTag(prefix) {
1107
+ const tag = { p: 1, dt: 2, pb: 3, sec: 4, hdr: 5, ftr: 6, dc: 7, chg: 8 }[prefix];
1108
+ if (!tag) throw new Error(`Unknown document id prefix: ${prefix}`);
1109
+ return tag;
1110
+ }
1111
+ function presentationCounter(id) {
1112
+ const match = /^[a-z]{2}\/([1-9][0-9]*)$/u.exec(id);
1113
+ if (!match) throw new Error(`Presentation object id is not canonical: ${id}`);
1114
+ const counter = BigInt(match[1]);
1115
+ if (counter > 0xffffffffffffffffn) throw new RangeError("Presentation object id is exhausted");
1116
+ return counter;
1117
+ }
1118
+ function optionalBool(value) {
1119
+ return value === void 0 ? 0 : value ? 2 : 1;
1120
+ }
1121
+ function optionalOptionalBool(value) {
1122
+ return value === void 0 ? 0 : value ? 3 : 2;
1123
+ }
1124
+ function cssPixels(value) {
1125
+ if (!Number.isFinite(value) || Object.is(value, -0)) {
1126
+ throw new TypeError("Presentation geometry must contain finite canonical numbers");
1127
+ }
1128
+ return BigInt(Math.round(value * EMU_PER_CSS_PIXEL));
1129
+ }
1130
+ function assertFinitePositive(value, label) {
1131
+ if (!Number.isFinite(value) || value <= 0)
1132
+ throw new TypeError(`${label} must be positive and finite`);
1133
+ }
1134
+ function presentationSizeEmu(value, label) {
1135
+ assertFinitePositive(value, label);
1136
+ const rounded = Math.round(value * EMU_PER_CSS_PIXEL);
1137
+ if (!Number.isSafeInteger(rounded) || rounded <= 0 || rounded > PRESENTATION_MAX_COORDINATE_EMU) {
1138
+ throw new RangeError(`${label} exceeds the native presentation-coordinate bound`);
1139
+ }
1140
+ return BigInt(rounded);
1141
+ }
1142
+ function fnv1a64(bytes) {
1143
+ let hash = 0xcbf29ce484222325n;
1144
+ for (const byte of bytes) {
1145
+ hash ^= BigInt(byte);
1146
+ hash = BigInt.asUintN(64, hash * 0x100000001b3n);
1147
+ }
1148
+ return hash;
1149
+ }
1150
+
1151
+ // src/production-spreadsheet-native.ts
1152
+ import {
1153
+ SPREADSHEET_ARTIFACT_PROJECTION_MAX_BYTES,
1154
+ SPREADSHEET_ARTIFACT_VIEWPORT_MAX_CELLS,
1155
+ decodeSpreadsheetMetadataKernelProjection,
1156
+ decodeSpreadsheetViewportKernelProjection,
1157
+ editableArtifactStableId,
1158
+ encodeSpreadsheetMetadataKernelQuery,
1159
+ encodeSpreadsheetViewportKernelQuery,
1160
+ spreadsheetSheetId
1161
+ } from "@opengeni/contracts/editable-artifacts";
1162
+ var textEncoder2 = new TextEncoder();
1163
+ function reconcileSpreadsheetProjection(workbook, runtime, namespace) {
1164
+ const snapshot = workbook.toJSON();
1165
+ const session = NativeSpreadsheetSession.create(runtime, namespace);
1166
+ const sheetIds = /* @__PURE__ */ new Map();
1167
+ const generations = /* @__PURE__ */ new Map();
1168
+ const author = new SpreadsheetProjectionAuthor(session, namespace);
1169
+ try {
1170
+ let previous = null;
1171
+ let offset = 0;
1172
+ const maximumCommands = Math.max(1, Math.min(session.capabilities.maxCommands, 1024));
1173
+ while (offset < snapshot.worksheets.length) {
1174
+ const chunk = snapshot.worksheets.slice(offset, offset + maximumCommands);
1175
+ const commands = [];
1176
+ for (let relativeIndex = 0; relativeIndex < chunk.length; relativeIndex += 1) {
1177
+ const worksheet = chunk[relativeIndex];
1178
+ const sheetId = nativeSheetId(namespace, worksheet.id);
1179
+ sheetIds.set(worksheet.id, sheetId);
1180
+ const after = relativeIndex === 0 ? previous : {
1181
+ kind: "created-in-batch",
1182
+ sheetId: sheetIds.get(chunk[relativeIndex - 1].id),
1183
+ createCommandIndex: relativeIndex - 1
1184
+ };
1185
+ commands.push({ kind: "sheet.create", sheetId, name: worksheet.name, after });
1186
+ }
1187
+ author.author(commands);
1188
+ const metadata = querySpreadsheetMetadata(session, sheetIds.size);
1189
+ const metadataById = new Map(metadata.map((sheet) => [sheet.sheetId, sheet]));
1190
+ for (let index = 0; index < chunk.length; index += 1) {
1191
+ const worksheet = chunk[index];
1192
+ const sheetId = sheetIds.get(worksheet.id);
1193
+ const operationId = metadataById.get(sheetId)?.generationId;
1194
+ if (!operationId) throw new Error("Native kernel omitted a sheet generation id");
1195
+ const generation = Object.freeze({
1196
+ kind: "generation",
1197
+ sheetId,
1198
+ creationOperationId: editableArtifactStableId(operationId)
1199
+ });
1200
+ generations.set(worksheet.id, generation);
1201
+ previous = generation;
1202
+ }
1203
+ offset += chunk.length;
1204
+ }
1205
+ const batch = new SpreadsheetCommandBatcher(author, session);
1206
+ for (const worksheet of snapshot.worksheets) {
1207
+ const generation = generations.get(worksheet.id);
1208
+ if (!generation) throw new Error(`Missing native generation for worksheet ${worksheet.id}`);
1209
+ for (const command of cellCommands(worksheet, generation)) batch.add(command);
1210
+ }
1211
+ batch.finish();
1212
+ return {
1213
+ session,
1214
+ data: {
1215
+ sheetIds,
1216
+ generations,
1217
+ author,
1218
+ metadata: null
1219
+ }
1220
+ };
1221
+ } catch (cause) {
1222
+ session.dispose();
1223
+ throw cause;
1224
+ }
1225
+ }
1226
+ var prepareSpreadsheetMutation = (mutation, state) => {
1227
+ const data = spreadsheetData(state);
1228
+ const root = state.rawRoot();
1229
+ if (mutation.owner === root.worksheets && mutation.member === "add") {
1230
+ const previousHostId = root.worksheets.items.at(-1)?.id;
1231
+ const after = previousHostId ? data.generations.get(previousHostId) ?? null : null;
1232
+ return {
1233
+ commit(result) {
1234
+ if (!isWorksheet(result)) throw new Error("Worksheet add did not return a worksheet");
1235
+ const sheetId = nativeSheetId(state.namespace, result.id);
1236
+ data.author.author([{ kind: "sheet.create", sheetId, name: result.name, after }]);
1237
+ const operationId = querySpreadsheetMetadata(
1238
+ state.native,
1239
+ data.sheetIds.size + 1
1240
+ ).find((sheet) => sheet.sheetId === sheetId)?.generationId;
1241
+ if (!operationId) throw new Error("Native kernel omitted a sheet generation id");
1242
+ data.sheetIds.set(result.id, sheetId);
1243
+ data.generations.set(
1244
+ result.id,
1245
+ Object.freeze({
1246
+ kind: "generation",
1247
+ sheetId,
1248
+ creationOperationId: editableArtifactStableId(operationId)
1249
+ })
1250
+ );
1251
+ data.metadata = null;
1252
+ return true;
1253
+ }
1254
+ };
1255
+ }
1256
+ if (isWorksheet(mutation.owner) && mutation.member === "name") {
1257
+ const generation2 = requiredGeneration(data, mutation.owner.id);
1258
+ const name = normalizedSheetName(mutation.arguments?.[0]);
1259
+ return commitSpreadsheetCommands(data, [{ kind: "sheet.rename", sheet: generation2, name }]);
1260
+ }
1261
+ if (!isRange(mutation.owner)) return null;
1262
+ const range = mutation.owner;
1263
+ const generation = requiredGeneration(data, range.worksheet.id);
1264
+ if (mutation.member === "values" || mutation.member === "formulas") {
1265
+ return commitSpreadsheetCommands(data, [
1266
+ rectangularWriteCommand(generation, range.address, mutation.arguments?.[0], mutation.member)
1267
+ ]);
1268
+ }
1269
+ if (mutation.member === "writeValues") {
1270
+ const matrix = rectangularMatrix(mutation.arguments?.[0], "spreadsheet values");
1271
+ if (matrix.rows === 0 || matrix.columns === 0) return { commit: () => false };
1272
+ return commitSpreadsheetCommands(data, [
1273
+ rectangularWriteCommand(
1274
+ generation,
1275
+ { ...range.address, rowCount: matrix.rows, colCount: matrix.columns },
1276
+ matrix.values,
1277
+ "values"
1278
+ )
1279
+ ]);
1280
+ }
1281
+ if (mutation.member === "clear") {
1282
+ const options = mutation.arguments?.[0];
1283
+ if (options?.applyTo === "formats") {
1284
+ return { commit: () => true };
1285
+ }
1286
+ return commitSpreadsheetCommands(data, [
1287
+ {
1288
+ kind: "range.clear",
1289
+ sheet: generation,
1290
+ range: {
1291
+ start: { row: range.address.row, column: range.address.col },
1292
+ end: {
1293
+ row: range.address.row + range.address.rowCount - 1,
1294
+ column: range.address.col + range.address.colCount - 1
1295
+ }
1296
+ }
1297
+ }
1298
+ ]);
1299
+ }
1300
+ return null;
1301
+ };
1302
+ function commitSpreadsheetCommands(data, commands) {
1303
+ return {
1304
+ commit() {
1305
+ data.author.author(commands);
1306
+ data.metadata = null;
1307
+ return true;
1308
+ }
1309
+ };
1310
+ }
1311
+ function requiredGeneration(data, hostSheetId) {
1312
+ const generation = data.generations.get(hostSheetId);
1313
+ if (!generation) throw new Error(`Spreadsheet native generation is missing: ${hostSheetId}`);
1314
+ return generation;
1315
+ }
1316
+ function rectangularWriteCommand(sheet, address, input, kind) {
1317
+ const matrix = rectangularMatrix(input, `spreadsheet ${kind}`);
1318
+ if (matrix.rows !== address.rowCount || matrix.columns !== address.colCount) {
1319
+ throw new Error(
1320
+ `Matrix shape ${matrix.rows}x${matrix.columns} does not match range ${address.rowCount}x${address.colCount}`
1321
+ );
1322
+ }
1323
+ const cells = [];
1324
+ for (const row of matrix.values) {
1325
+ for (const value of row) {
1326
+ cells.push(kind === "values" ? nativeInputValue(value) : nativeFormula(value));
1327
+ }
1328
+ }
1329
+ return {
1330
+ kind: "cells.set",
1331
+ sheet,
1332
+ anchor: { row: address.row, column: address.col },
1333
+ rows: address.rowCount,
1334
+ columns: address.colCount,
1335
+ cells
1336
+ };
1337
+ }
1338
+ function rectangularMatrix(input, label) {
1339
+ if (!Array.isArray(input)) throw new TypeError(`${label} must be a matrix`);
1340
+ const columns = input[0]?.length ?? 0;
1341
+ if (!input.every((row) => Array.isArray(row) && row.length === columns)) {
1342
+ throw new Error(`${label} must be rectangular`);
1343
+ }
1344
+ return { values: input, rows: input.length, columns };
1345
+ }
1346
+ function nativeInputValue(value) {
1347
+ if (value instanceof Date) {
1348
+ const milliseconds = Date.prototype.getTime.call(value);
1349
+ if (!Number.isSafeInteger(milliseconds)) {
1350
+ throw new TypeError("Spreadsheet cell dates must be valid ECMAScript instants");
1351
+ }
1352
+ return { date: new Date(milliseconds).toISOString() };
1353
+ }
1354
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1355
+ if (typeof value === "number") {
1356
+ if (!Number.isFinite(value)) throw new TypeError("Spreadsheet cell numbers must be finite");
1357
+ return value;
1358
+ }
1359
+ throw new TypeError("Spreadsheet cell value is not supported by the native kernel");
1360
+ }
1361
+ function nativeFormula(value) {
1362
+ if (value === null) return null;
1363
+ if (typeof value !== "string")
1364
+ throw new TypeError("Spreadsheet formulas must be strings or null");
1365
+ const trimmed = value.trim();
1366
+ if (trimmed.length === 0) return null;
1367
+ return { formula: trimmed.startsWith("=") ? trimmed : `=${trimmed}`, cached: null };
1368
+ }
1369
+ function normalizedSheetName(value) {
1370
+ if (typeof value !== "string") throw new TypeError("Worksheet name must be a string");
1371
+ const name = value.trim();
1372
+ if (!name || name.length > 31 || /[\\/?*[\]:]/u.test(name)) {
1373
+ throw new Error(`Invalid worksheet name: ${value}`);
1374
+ }
1375
+ return name;
1376
+ }
1377
+ function installSpreadsheetProjection(workbook, state) {
1378
+ Object.defineProperty(workbook, "valueAt", {
1379
+ configurable: true,
1380
+ writable: true,
1381
+ value: (sheet, address) => {
1382
+ if (state.inMutation) {
1383
+ return Workbook.prototype.valueAt.call(workbook, sheet, address);
1384
+ }
1385
+ return readSpreadsheetMatrix(state, sheet.id, {
1386
+ row: address.row,
1387
+ col: address.col,
1388
+ rowCount: 1,
1389
+ colCount: 1
1390
+ }).values[0][0];
1391
+ }
1392
+ });
1393
+ }
1394
+ function readSpreadsheetProperty(owner, member, state) {
1395
+ if (state.inMutation) return { handled: false };
1396
+ if (member === "values" && isRange(owner)) {
1397
+ return {
1398
+ handled: true,
1399
+ value: readSpreadsheetMatrix(state, owner.worksheet.id, owner.address).values
1400
+ };
1401
+ }
1402
+ if (member === "formulas" && isRange(owner)) {
1403
+ return {
1404
+ handled: true,
1405
+ value: readSpreadsheetMatrix(state, owner.worksheet.id, owner.address).formulas
1406
+ };
1407
+ }
1408
+ if (member === "name" && isWorksheet(owner)) {
1409
+ const metadata = spreadsheetMetadata(state).get(owner.id);
1410
+ if (!metadata) throw new Error(`Native worksheet is missing: ${owner.id}`);
1411
+ return { handled: true, value: metadata.name };
1412
+ }
1413
+ return { handled: false };
1414
+ }
1415
+ function readSpreadsheetMatrix(state, hostSheetId, address) {
1416
+ const data = spreadsheetData(state);
1417
+ const nativeSheetIdValue = data.sheetIds.get(hostSheetId);
1418
+ if (!nativeSheetIdValue) throw new Error(`Native worksheet mapping is missing: ${hostSheetId}`);
1419
+ const cells = address.rowCount * address.colCount;
1420
+ if (!Number.isSafeInteger(cells) || cells > SPREADSHEET_ARTIFACT_VIEWPORT_MAX_CELLS) {
1421
+ throw new RangeError(
1422
+ `Spreadsheet read exceeds the native viewport limit (${SPREADSHEET_ARTIFACT_VIEWPORT_MAX_CELLS} cells)`
1423
+ );
1424
+ }
1425
+ const maxBytes = Math.min(
1426
+ state.native.capabilities.maxQueryResponseBytes,
1427
+ SPREADSHEET_ARTIFACT_PROJECTION_MAX_BYTES
1428
+ );
1429
+ const query = {
1430
+ sheetId: nativeSheetIdValue,
1431
+ startRow: address.row,
1432
+ startColumn: address.col,
1433
+ rowCount: address.rowCount,
1434
+ columnCount: address.colCount,
1435
+ maxCells: cells,
1436
+ maxBytes
1437
+ };
1438
+ const projection = decodeSpreadsheetViewportKernelProjection(
1439
+ state.native.query(encodeSpreadsheetViewportKernelQuery(query)),
1440
+ query
1441
+ );
1442
+ const values = Array.from(
1443
+ { length: address.rowCount },
1444
+ () => Array(address.colCount).fill(null)
1445
+ );
1446
+ const formulas = Array.from(
1447
+ { length: address.rowCount },
1448
+ () => Array(address.colCount).fill(null)
1449
+ );
1450
+ for (const cell of projection.cells) {
1451
+ const row = cell.row - address.row;
1452
+ const column = cell.column - address.col;
1453
+ values[row][column] = projectedCellValue(cell.value);
1454
+ formulas[row][column] = cell.formula;
1455
+ }
1456
+ return { values, formulas };
1457
+ }
1458
+ function spreadsheetMetadata(state) {
1459
+ const data = spreadsheetData(state);
1460
+ if (data.metadata) return data.metadata;
1461
+ const sheets = querySpreadsheetMetadata(
1462
+ state.native,
1463
+ data.sheetIds.size
1464
+ );
1465
+ const hostByNative = new Map([...data.sheetIds].map(([host, native]) => [native, host]));
1466
+ const metadata = /* @__PURE__ */ new Map();
1467
+ for (const sheet of sheets) {
1468
+ const host = hostByNative.get(sheet.sheetId);
1469
+ if (host) metadata.set(host, sheet);
1470
+ }
1471
+ data.metadata = metadata;
1472
+ return metadata;
1473
+ }
1474
+ function querySpreadsheetMetadata(session, maxSheets) {
1475
+ const query = {
1476
+ maxSheets: Math.max(1, maxSheets),
1477
+ maxBytes: Math.min(
1478
+ session.capabilities.maxQueryResponseBytes,
1479
+ SPREADSHEET_ARTIFACT_PROJECTION_MAX_BYTES
1480
+ )
1481
+ };
1482
+ return decodeSpreadsheetMetadataKernelProjection(
1483
+ session.query(encodeSpreadsheetMetadataKernelQuery(query)),
1484
+ query
1485
+ ).sheets;
1486
+ }
1487
+ function spreadsheetData(state) {
1488
+ if (state.native.modality !== "spreadsheet")
1489
+ throw new TypeError("Expected native spreadsheet session");
1490
+ const data = state.nativeData;
1491
+ if (!(data?.sheetIds instanceof Map) || !(data.generations instanceof Map) || !(data.author instanceof SpreadsheetProjectionAuthor)) {
1492
+ throw new Error("Spreadsheet native mapping is unavailable");
1493
+ }
1494
+ return data;
1495
+ }
1496
+ var SpreadsheetProjectionAuthor = class {
1497
+ #session;
1498
+ #replicaId;
1499
+ #artifactId;
1500
+ #transactionCounter = 0;
1501
+ #previousTransactionId = null;
1502
+ constructor(session, namespace) {
1503
+ this.#session = session;
1504
+ this.#replicaId = u64Hex(namespace);
1505
+ this.#artifactId = `${this.#replicaId}ffffffffffffffff`;
1506
+ }
1507
+ author(commands) {
1508
+ if (commands.length === 0) return;
1509
+ const counter = this.#transactionCounter + 1;
1510
+ const clientTransactionId = `projection.${this.#replicaId}.${counter}`;
1511
+ const revision = this.#session.revision();
1512
+ if (revision > BigInt(Number.MAX_SAFE_INTEGER)) {
1513
+ throw new RangeError("Native spreadsheet revision exceeds the JavaScript safe-integer range");
1514
+ }
1515
+ this.#session.authorCommands({
1516
+ intent: {
1517
+ artifactId: this.#artifactId,
1518
+ clientTransactionId,
1519
+ replicaId: this.#replicaId,
1520
+ replicaCounter: counter,
1521
+ previousLocalTransactionId: this.#previousTransactionId,
1522
+ observedHeadSequence: Number(revision),
1523
+ causalBase: this.#transactionCounter === 0 ? [] : [{ replicaId: this.#replicaId, counter: this.#transactionCounter }],
1524
+ selectiveUndoOperationIds: []
1525
+ },
1526
+ commands: { version: 1, commands },
1527
+ resolvedBaseBytes: this.#session.frontier()
1528
+ });
1529
+ this.#transactionCounter = counter;
1530
+ this.#previousTransactionId = clientTransactionId;
1531
+ }
1532
+ };
1533
+ var SpreadsheetCommandBatcher = class {
1534
+ #author;
1535
+ #maxCommands;
1536
+ #maxCells;
1537
+ #maxEstimatedBytes;
1538
+ #commands = [];
1539
+ #cells = 0;
1540
+ #estimatedBytes = 0;
1541
+ constructor(author, session) {
1542
+ this.#author = author;
1543
+ this.#maxCommands = Math.max(1, Math.min(session.capabilities.maxCommands, 1e3));
1544
+ this.#maxCells = Math.max(1, Math.min(session.capabilities.maxCellsPerBatch, 1e5));
1545
+ this.#maxEstimatedBytes = Math.max(
1546
+ 16384,
1547
+ Math.min(session.capabilities.maxSpreadsheetCommandBytes - 4096, 2 * 1024 * 1024)
1548
+ );
1549
+ }
1550
+ add(command) {
1551
+ const cells = command.kind === "cells.set" ? command.cells.length : 0;
1552
+ const estimatedBytes = estimateCommandBytes(command);
1553
+ if (this.#commands.length > 0 && (this.#commands.length + 1 > this.#maxCommands || this.#cells + cells > this.#maxCells || this.#estimatedBytes + estimatedBytes > this.#maxEstimatedBytes)) {
1554
+ this.flush();
1555
+ }
1556
+ this.#commands.push(command);
1557
+ this.#cells += cells;
1558
+ this.#estimatedBytes += estimatedBytes;
1559
+ if (estimatedBytes > this.#maxEstimatedBytes) this.flush();
1560
+ }
1561
+ finish() {
1562
+ this.flush();
1563
+ }
1564
+ flush() {
1565
+ if (this.#commands.length === 0) return;
1566
+ this.#author.author(this.#commands);
1567
+ this.#commands = [];
1568
+ this.#cells = 0;
1569
+ this.#estimatedBytes = 0;
1570
+ }
1571
+ };
1572
+ function* cellCommands(worksheet, generation) {
1573
+ const cells = [...worksheet.cells].sort(
1574
+ (left, right) => left.row - right.row || left.col - right.col
1575
+ );
1576
+ let index = 0;
1577
+ while (index < cells.length) {
1578
+ const first = cells[index];
1579
+ const rowCells = [nativeCell(first)];
1580
+ let nextColumn = first.col + 1;
1581
+ index += 1;
1582
+ while (index < cells.length && cells[index].row === first.row && cells[index].col === nextColumn && rowCells.length < 4096 && estimateCellsBytes(rowCells) < 512 * 1024) {
1583
+ rowCells.push(nativeCell(cells[index]));
1584
+ nextColumn += 1;
1585
+ index += 1;
1586
+ }
1587
+ yield {
1588
+ kind: "cells.set",
1589
+ sheet: generation,
1590
+ anchor: { row: first.row, column: first.col },
1591
+ rows: 1,
1592
+ columns: rowCells.length,
1593
+ cells: rowCells
1594
+ };
1595
+ }
1596
+ }
1597
+ function nativeCell(cell) {
1598
+ if (cell.formula !== null) return { formula: cell.formula, cached: null };
1599
+ const value = cell.value;
1600
+ if (typeof value === "object" && value !== null) {
1601
+ if ("type" in value && value.type === "date") {
1602
+ return { date: value.value };
1603
+ }
1604
+ throw new TypeError("Serialized spreadsheet cell value is not supported by the native kernel");
1605
+ }
1606
+ if (typeof value === "number" && !Number.isFinite(value)) {
1607
+ throw new TypeError("Spreadsheet cell numbers must be finite");
1608
+ }
1609
+ return value;
1610
+ }
1611
+ function nativeSheetId(namespace, hostId) {
1612
+ const match = /^ws\/(\d+)$/u.exec(hostId);
1613
+ if (!match) throw new Error(`Worksheet id cannot be mapped to the native kernel: ${hostId}`);
1614
+ const counter = BigInt(match[1]) + 1n;
1615
+ if (counter <= 1n || counter > 0xffffffffffffffffn) {
1616
+ throw new RangeError(`Worksheet id counter is outside the native range: ${hostId}`);
1617
+ }
1618
+ return spreadsheetSheetId(`${u64Hex(namespace)}${u64Hex(counter)}`);
1619
+ }
1620
+ function projectedCellValue(value) {
1621
+ switch (value.kind) {
1622
+ case "empty":
1623
+ return null;
1624
+ case "boolean":
1625
+ case "number":
1626
+ case "text":
1627
+ return value.value;
1628
+ case "date":
1629
+ return new Date(value.value);
1630
+ case "error": {
1631
+ if (typeof value.value === "object") return value.value.custom;
1632
+ const errors = {
1633
+ null: "#NULL!",
1634
+ divide_by_zero: "#DIV/0!",
1635
+ value: "#VALUE!",
1636
+ reference: "#REF!",
1637
+ name: "#NAME?",
1638
+ number: "#NUM!",
1639
+ not_available: "#N/A",
1640
+ spill: "#SPILL!",
1641
+ calculation: "#CALC!"
1642
+ };
1643
+ const projected = errors[value.value];
1644
+ if (!projected) throw new Error(`Unknown native formula error: ${value.value}`);
1645
+ return projected;
1646
+ }
1647
+ }
1648
+ throw new Error("Unknown native spreadsheet cell value");
1649
+ }
1650
+ function estimateCommandBytes(command) {
1651
+ if (command.kind !== "cells.set") return 256;
1652
+ return 256 + estimateCellsBytes(command.cells);
1653
+ }
1654
+ function estimateCellsBytes(cells) {
1655
+ let bytes = cells.length * 16;
1656
+ for (const cell of cells) {
1657
+ if (typeof cell === "string") bytes += textEncoder2.encode(cell).byteLength;
1658
+ else if (typeof cell === "object" && cell !== null) {
1659
+ if ("formula" in cell) bytes += textEncoder2.encode(cell.formula).byteLength;
1660
+ else if ("error" in cell) bytes += textEncoder2.encode(cell.error).byteLength;
1661
+ }
1662
+ }
1663
+ return bytes;
1664
+ }
1665
+ function isRange(value) {
1666
+ if (typeof value !== "object" || value === null) return false;
1667
+ const worksheet = Reflect.get(value, "worksheet");
1668
+ const address = Reflect.get(value, "address");
1669
+ return typeof worksheet === "object" && worksheet !== null && typeof Reflect.get(worksheet, "id") === "string" && typeof address === "object" && address !== null && Number.isInteger(Reflect.get(address, "row")) && Number.isInteger(Reflect.get(address, "col"));
1670
+ }
1671
+ function isWorksheet(value) {
1672
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "id") === "string" && typeof Reflect.get(value, "name") === "string" && String(Reflect.get(value, "id")).startsWith("ws/") && typeof Reflect.get(value, "getRangeByIndexes") === "function";
1673
+ }
1674
+ function u64Hex(value) {
1675
+ if (value <= 0n || value > 0xffffffffffffffffn) {
1676
+ throw new RangeError("Artifact namespace must be a nonzero u64");
1677
+ }
1678
+ return value.toString(16).padStart(16, "0");
1679
+ }
1680
+
1681
+ // src/production.ts
1682
+ var configuredRuntime = null;
1683
+ function configureArtifactRuntime(runtime) {
1684
+ if (runtime.kind !== "native" || runtime.target === "wasm-web") {
1685
+ throw new ArtifactRuntimeError(
1686
+ "ARTIFACT_RUNTIME_UNAVAILABLE",
1687
+ "The synchronous artifact facade requires an exact native N-API runtime"
1688
+ );
1689
+ }
1690
+ if (configuredRuntime && configuredRuntime !== runtime) {
1691
+ throw new ArtifactRuntimeError(
1692
+ "ARTIFACT_RUNTIME_INCOMPATIBLE",
1693
+ "A different artifact runtime is already configured in this process"
1694
+ );
1695
+ }
1696
+ configuredRuntime = runtime;
1697
+ }
1698
+ function getConfiguredArtifactRuntime() {
1699
+ return configuredRuntime;
1700
+ }
1701
+ var WorkbookFacade = createStaticFacade(Workbook, "Workbook", {
1702
+ create(options = {}) {
1703
+ return attachWorkbook(Workbook.create(options), randomNamespace());
1704
+ },
1705
+ async fromCSV(csvText, options = {}) {
1706
+ return attachWorkbook(await Workbook.fromCSV(csvText, options), randomNamespace());
1707
+ },
1708
+ fromJSON(input) {
1709
+ return attachWorkbook(Workbook.fromJSON(input), randomNamespace());
1710
+ }
1711
+ });
1712
+ var DocumentFacade = createStaticFacade(Document, "Document", {
1713
+ create(options = {}) {
1714
+ const document = Document.create(options);
1715
+ return attachDocument(document, BigInt(`0x${document.idNamespace}`));
1716
+ },
1717
+ fromJSON(input) {
1718
+ const document = Document.fromJSON(input);
1719
+ return attachDocument(document, BigInt(`0x${document.idNamespace}`));
1720
+ }
1721
+ });
1722
+ var PresentationFacade = createStaticFacade(Presentation, "Presentation", {
1723
+ create(options = {}) {
1724
+ return attachPresentation(Presentation.create(options), randomNamespace());
1725
+ }
1726
+ });
1727
+ var Workbook2 = WorkbookFacade;
1728
+ var Document2 = DocumentFacade;
1729
+ var Presentation2 = PresentationFacade;
1730
+ var SpreadsheetFile2 = class {
1731
+ static async importXlsx(...args) {
1732
+ requireConfiguredRuntime();
1733
+ const workbook = await SpreadsheetFile.importXlsx(...args);
1734
+ return attachWorkbook(workbook, randomNamespace());
1735
+ }
1736
+ static async exportXlsx(workbook, options = {}) {
1737
+ const raw = rawArtifact(workbook, "spreadsheet");
1738
+ return await SpreadsheetFile.exportXlsx(raw, options);
1739
+ }
1740
+ static fidelityReport(workbook) {
1741
+ return SpreadsheetFile.fidelityReport(rawArtifact(workbook, "spreadsheet"));
1742
+ }
1743
+ static lossPreservationEnvelope(workbook) {
1744
+ return SpreadsheetFile.lossPreservationEnvelope(rawArtifact(workbook, "spreadsheet"));
1745
+ }
1746
+ static async attachLossPreservationEnvelope(workbook, envelope2, options = {}) {
1747
+ const state = requireCompositeState(workbook, "spreadsheet");
1748
+ await state.mutate(
1749
+ () => SpreadsheetFile.attachLossPreservationEnvelope(
1750
+ state.rawRoot(),
1751
+ envelope2,
1752
+ options
1753
+ ),
1754
+ { member: "attachLossPreservationEnvelope", owner: state.rawRoot() }
1755
+ );
1756
+ }
1757
+ };
1758
+ var DocumentFile2 = class {
1759
+ static async importDocx(...args) {
1760
+ requireConfiguredRuntime();
1761
+ const document = await DocumentFile.importDocx(...args);
1762
+ return attachDocument(document, BigInt(`0x${document.idNamespace}`));
1763
+ }
1764
+ static async exportDocx(document) {
1765
+ return await DocumentFile.exportDocx(rawArtifact(document, "document"));
1766
+ }
1767
+ };
1768
+ var PresentationFile2 = class {
1769
+ static async importPptx(...args) {
1770
+ requireConfiguredRuntime();
1771
+ const presentation = await PresentationFile.importPptx(...args);
1772
+ return attachPresentation(presentation, randomNamespace());
1773
+ }
1774
+ static async exportPptx(presentation, options = {}) {
1775
+ return await PresentationFile.exportPptx(
1776
+ rawArtifact(presentation, "presentation"),
1777
+ options
1778
+ );
1779
+ }
1780
+ static fidelityReport(presentation) {
1781
+ return PresentationFile.fidelityReport(rawArtifact(presentation, "presentation"));
1782
+ }
1783
+ static lossPreservationEnvelope(presentation) {
1784
+ return PresentationFile.lossPreservationEnvelope(
1785
+ rawArtifact(presentation, "presentation")
1786
+ );
1787
+ }
1788
+ };
1789
+ function getArtifactCompositeDiagnostics(artifact) {
1790
+ const state = requireCompositeState(artifact);
1791
+ const root = state.rawRoot();
1792
+ const hostProjection = state.modality === "presentation" ? root.layoutSnapshot() : root.toJSON();
1793
+ return Object.freeze({
1794
+ version: 1,
1795
+ modality: state.modality,
1796
+ namespace: u64Hex2(state.namespace),
1797
+ runtimeTarget: state.native.target,
1798
+ runtimeBuildIdentity: state.native.buildIdentity,
1799
+ nativeRevision: state.native.revision(),
1800
+ nativeStateHash: state.native.stateHash(),
1801
+ nativeSnapshot: state.native.snapshot().slice(),
1802
+ hostProjection: structuredClone(hostProjection)
1803
+ });
1804
+ }
1805
+ function disposeArtifact(artifact) {
1806
+ requireCompositeState(artifact).dispose();
1807
+ }
1808
+ function attachWorkbook(workbook, namespace) {
1809
+ const runtime = requireConfiguredRuntime();
1810
+ const reconcile = (root) => reconcileSpreadsheetProjection(root, runtime, namespace);
1811
+ const reconciliation = reconcile(workbook);
1812
+ const state = new CompositeArtifactState({
1813
+ modality: "spreadsheet",
1814
+ namespace,
1815
+ root: workbook,
1816
+ reconciliation,
1817
+ reconcile,
1818
+ prepareMutation: prepareSpreadsheetMutation,
1819
+ installProjection: installSpreadsheetProjection,
1820
+ readProperty: readSpreadsheetProperty,
1821
+ captureAuxiliary: captureSpreadsheetAuxiliary,
1822
+ restoreAuxiliary: restoreSpreadsheetAuxiliary
1823
+ });
1824
+ return state.proxy();
1825
+ }
1826
+ function attachDocument(document, namespace) {
1827
+ const runtime = requireConfiguredRuntime();
1828
+ const reconcile = (root) => reconcileDocumentProjection(root, runtime, namespace);
1829
+ const reconciliation = reconcile(document);
1830
+ const state = new CompositeArtifactState({
1831
+ modality: "document",
1832
+ namespace,
1833
+ root: document,
1834
+ reconciliation,
1835
+ reconcile,
1836
+ prepareMutation: prepareDocumentMutation,
1837
+ captureAuxiliary: captureDocumentAuxiliary,
1838
+ restoreAuxiliary: restoreDocumentAuxiliary
1839
+ });
1840
+ return state.proxy();
1841
+ }
1842
+ function attachPresentation(presentation, namespace) {
1843
+ const runtime = requireConfiguredRuntime();
1844
+ const reconcile = (root) => reconcilePresentationProjection(root, runtime, namespace);
1845
+ const reconciliation = reconcile(presentation);
1846
+ const state = new CompositeArtifactState({
1847
+ modality: "presentation",
1848
+ namespace,
1849
+ root: presentation,
1850
+ reconciliation,
1851
+ reconcile,
1852
+ prepareMutation: preparePresentationMutation,
1853
+ captureAuxiliary: capturePresentationAuxiliary,
1854
+ restoreAuxiliary: restorePresentationAuxiliary
1855
+ });
1856
+ return state.proxy();
1857
+ }
1858
+ function reconcileDocumentProjection(document, runtime, namespace) {
1859
+ const session = NativeDocumentSession.create(runtime, namespace);
1860
+ try {
1861
+ const commands = encodeDocumentProjectionCommands(document.toJSON());
1862
+ if (envelopeCommandCount(commands) > 0) session.applyCommands(commands);
1863
+ return { session };
1864
+ } catch (cause) {
1865
+ session.dispose();
1866
+ throw cause;
1867
+ }
1868
+ }
1869
+ function prepareDocumentMutation(mutation, state) {
1870
+ const root = state.rawRoot();
1871
+ const owner = mutation.owner;
1872
+ const member = mutation.member;
1873
+ if (owner instanceof DocumentBlockCollection || owner instanceof DocumentStory) {
1874
+ if (member === "addParagraph" || member === "addHeading" || member === "addTable" || member === "addPageBreak") {
1875
+ const target = owner instanceof DocumentStory ? documentStoryTarget(root, owner) : { kind: "body" };
1876
+ return commitDocumentMutation(state, (result) => {
1877
+ if (!isSerializedDocumentBlock(result)) {
1878
+ throw new Error(`${String(member)} did not return a document block`);
1879
+ }
1880
+ return [{ kind: "block.add", target, block: result.serialize() }];
1881
+ });
1882
+ }
1883
+ }
1884
+ if (owner instanceof DocumentParagraph) {
1885
+ if (member === "setStyle") {
1886
+ const style = mutation.arguments?.[0];
1887
+ return commitDocumentMutation(state, () => [
1888
+ { kind: "paragraph.style", id: owner.id, style }
1889
+ ]);
1890
+ }
1891
+ if (member === "format") {
1892
+ const format = mutation.arguments?.[0];
1893
+ return commitDocumentMutation(state, () => [
1894
+ { kind: "paragraph.format", id: owner.id, format }
1895
+ ]);
1896
+ }
1897
+ if (member === "edit") {
1898
+ const edit = documentParagraphEdit(mutation.arguments ?? []);
1899
+ if (!edit) return null;
1900
+ return commitDocumentMutation(state, () => [
1901
+ { kind: "paragraph.edit", id: owner.id, ...edit }
1902
+ ]);
1903
+ }
1904
+ if (member === "append") {
1905
+ const text = mutation.arguments?.[0];
1906
+ const style = mutation.arguments?.[1] ?? {};
1907
+ if (typeof text !== "string" || typeof style !== "object" || style === null) return null;
1908
+ const start = owner.text.length;
1909
+ return commitDocumentMutation(state, () => [
1910
+ {
1911
+ kind: "paragraph.edit",
1912
+ id: owner.id,
1913
+ start,
1914
+ end: start,
1915
+ text,
1916
+ style
1917
+ }
1918
+ ]);
1919
+ }
1920
+ if (member === "text") {
1921
+ const before = owner.text;
1922
+ return commitDocumentMutation(state, () => {
1923
+ const edit = minimalDocumentTextEdit(before, owner.text);
1924
+ return edit ? [{ kind: "paragraph.edit", id: owner.id, ...edit }] : [];
1925
+ });
1926
+ }
1927
+ if (member === "replace") {
1928
+ const search = mutation.arguments?.[0];
1929
+ const before = owner.text;
1930
+ if (typeof search !== "string" || search.length === 0 || before.indexOf(search) !== before.lastIndexOf(search)) {
1931
+ return null;
1932
+ }
1933
+ return commitDocumentMutation(state, () => {
1934
+ const edit = minimalDocumentTextEdit(before, owner.text);
1935
+ return edit ? [{ kind: "paragraph.edit", id: owner.id, ...edit }] : [];
1936
+ });
1937
+ }
1938
+ }
1939
+ if (owner instanceof DocumentTable && member === "setStyle") {
1940
+ const style = mutation.arguments?.[0];
1941
+ return commitDocumentMutation(state, () => [{ kind: "table.style", id: owner.id, style }]);
1942
+ }
1943
+ if (owner === root && (member === "setEvenAndOddHeaders" || member === "setTrackRevisions")) {
1944
+ const enabled = mutation.arguments?.[0];
1945
+ if (typeof enabled !== "boolean") return null;
1946
+ return commitDocumentMutation(state, () => [
1947
+ {
1948
+ kind: "document.flags",
1949
+ ...member === "setEvenAndOddHeaders" ? { evenAndOddHeaders: enabled } : { trackRevisions: enabled }
1950
+ }
1951
+ ]);
1952
+ }
1953
+ if (owner instanceof DocumentSections && member === "add") {
1954
+ return commitDocumentMutation(state, (result) => {
1955
+ if (!(result instanceof DocumentSection))
1956
+ throw new Error("Section add did not return a section");
1957
+ return [{ kind: "section.add", section: result.serialize() }];
1958
+ });
1959
+ }
1960
+ if (owner instanceof DocumentSection && member === "setTitlePage") {
1961
+ const enabled = mutation.arguments?.[0];
1962
+ if (typeof enabled !== "boolean") return null;
1963
+ return commitDocumentMutation(state, () => [
1964
+ { kind: "section.title", id: owner.id, titlePage: enabled }
1965
+ ]);
1966
+ }
1967
+ if (owner instanceof DocumentComments) {
1968
+ if (member === "setSelf") return { commit: () => false };
1969
+ if (member === "addThread") {
1970
+ return commitDocumentMutation(state, (result) => {
1971
+ if (!(result instanceof DocumentCommentThread))
1972
+ throw new Error("Comment add did not return a thread");
1973
+ return [{ kind: "comment.add", comment: result.serialize() }];
1974
+ });
1975
+ }
1976
+ }
1977
+ if (owner instanceof DocumentCommentThread) {
1978
+ if (member === "addReply") {
1979
+ const before = owner.replies.length;
1980
+ return commitDocumentMutation(state, () => {
1981
+ const reply = owner.serialize().replies[before];
1982
+ return reply ? [{ kind: "comment.reply", id: owner.id, reply }] : [];
1983
+ });
1984
+ }
1985
+ if (member === "resolve" || member === "reopen") {
1986
+ const before = owner.resolved;
1987
+ return commitDocumentMutation(
1988
+ state,
1989
+ () => before === owner.resolved ? [] : [{ kind: "comment.resolved", id: owner.id, resolved: owner.resolved }]
1990
+ );
1991
+ }
1992
+ }
1993
+ if (owner instanceof TrackedChanges && member === "add") {
1994
+ return commitDocumentMutation(state, (result) => {
1995
+ if (!result || typeof result !== "object" || typeof Reflect.get(result, "serialize") !== "function") {
1996
+ throw new Error("Tracked-change add did not return a change");
1997
+ }
1998
+ return [
1999
+ {
2000
+ kind: "tracked.add",
2001
+ change: Reflect.get(result, "serialize").call(result)
2002
+ }
2003
+ ];
2004
+ });
2005
+ }
2006
+ return null;
2007
+ }
2008
+ function commitDocumentMutation(state, commands) {
2009
+ return {
2010
+ commit(result) {
2011
+ const batch = commands(result);
2012
+ if (batch.length === 0) return false;
2013
+ const session = state.native;
2014
+ if (!(session instanceof NativeDocumentSession))
2015
+ throw new TypeError("Expected native document session");
2016
+ const before = session.revision();
2017
+ session.applyCommands(encodeDocumentIncrementalCommands(batch));
2018
+ return session.revision() > before;
2019
+ }
2020
+ };
2021
+ }
2022
+ function documentStoryTarget(document, story) {
2023
+ for (const section of document.sections.items) {
2024
+ for (const storyKind of ["header", "footer"]) {
2025
+ const collection = storyKind === "header" ? section.headers : section.footers;
2026
+ for (const variant of ["default", "first", "even"]) {
2027
+ if (collection[variant] === story)
2028
+ return { kind: "story", sectionId: section.id, storyKind, variant };
2029
+ }
2030
+ }
2031
+ }
2032
+ throw new Error(`Document story is not attached: ${story.id}`);
2033
+ }
2034
+ function isSerializedDocumentBlock(value) {
2035
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "serialize") === "function";
2036
+ }
2037
+ function documentParagraphEdit(args) {
2038
+ if (typeof args[0] === "number") {
2039
+ if (typeof args[1] !== "number" || typeof args[2] !== "string") return null;
2040
+ return {
2041
+ start: args[0],
2042
+ end: args[1],
2043
+ text: args[2],
2044
+ ...args[3] && typeof args[3] === "object" ? { style: args[3] } : {}
2045
+ };
2046
+ }
2047
+ const edit = args[0];
2048
+ if (!edit || typeof edit.start !== "number" || typeof edit.end !== "number" || typeof edit.text !== "string") {
2049
+ return null;
2050
+ }
2051
+ return {
2052
+ start: edit.start,
2053
+ end: edit.end,
2054
+ text: edit.text,
2055
+ ...edit.style && typeof edit.style === "object" ? { style: edit.style } : {}
2056
+ };
2057
+ }
2058
+ function minimalDocumentTextEdit(before, after) {
2059
+ if (before === after) return null;
2060
+ let start = 0;
2061
+ while (start < before.length && start < after.length && before[start] === after[start])
2062
+ start += 1;
2063
+ let beforeEnd = before.length;
2064
+ let afterEnd = after.length;
2065
+ while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) {
2066
+ beforeEnd -= 1;
2067
+ afterEnd -= 1;
2068
+ }
2069
+ return { start, end: beforeEnd, text: after.slice(start, afterEnd) };
2070
+ }
2071
+ function reconcilePresentationProjection(presentation, runtime, namespace) {
2072
+ const session = NativePresentationSession.create(runtime, namespace);
2073
+ try {
2074
+ const commands = encodePresentationProjectionCommands(presentation, namespace);
2075
+ if (envelopeCommandCount(commands) > 0) session.applyCommands(commands);
2076
+ return { session };
2077
+ } catch (cause) {
2078
+ session.dispose();
2079
+ throw cause;
2080
+ }
2081
+ }
2082
+ function preparePresentationMutation(mutation, state) {
2083
+ const root = state.rawRoot();
2084
+ const owner = mutation.owner;
2085
+ const member = mutation.member;
2086
+ if (owner instanceof SlideCollection && member === "add") {
2087
+ const index = root.slides.items.length;
2088
+ return commitPresentationMutation(state, (result) => {
2089
+ if (!(result instanceof Slide)) throw new Error("Slide add did not return a slide");
2090
+ return [{ kind: "slide.create", slide: result, index }];
2091
+ });
2092
+ }
2093
+ if ((owner instanceof PresentationShapeCollection || owner instanceof PresentationChartCollection || owner instanceof PresentationImageCollection || owner instanceof PresentationTableCollection || owner instanceof PresentationGroupCollection) && member === "add") {
2094
+ return commitPresentationMutation(state, (result) => {
2095
+ if (!isPresentationElement(result))
2096
+ throw new Error("Presentation add did not return an element");
2097
+ const index = result.slide.elements.indexOf(result);
2098
+ if (index < 0) throw new Error("Presentation element was not attached to its slide");
2099
+ return [{ kind: "node.insert", slideId: result.slide.id, index, element: result }];
2100
+ });
2101
+ }
2102
+ if (owner instanceof Slide) {
2103
+ if (member === "title") {
2104
+ return commitPresentationMutation(state, () => [
2105
+ { kind: "slide.title", id: owner.id, title: owner.title }
2106
+ ]);
2107
+ }
2108
+ if (member === "setLayout") {
2109
+ return commitPresentationMutation(state, () => [
2110
+ {
2111
+ kind: "slide.layout",
2112
+ id: owner.id,
2113
+ ...owner.layout ? { layoutId: owner.layout.id } : {}
2114
+ }
2115
+ ]);
2116
+ }
2117
+ }
2118
+ if (owner === root.slideSize && (member === "width" || member === "height")) {
2119
+ return commitPresentationMutation(state, () => [
2120
+ {
2121
+ kind: "presentation.size",
2122
+ width: root.slideSize.width,
2123
+ height: root.slideSize.height
2124
+ }
2125
+ ]);
2126
+ }
2127
+ if (owner instanceof PresentationText) {
2128
+ const target = findPresentationTextOwner(root, owner);
2129
+ if (!target) return null;
2130
+ return commitPresentationMutation(
2131
+ state,
2132
+ () => target.kind === "notes" ? [{ kind: "slide.notes", id: target.slide.id, notes: owner }] : [{ kind: "node.update", element: target.element }]
2133
+ );
2134
+ }
2135
+ if (isPresentationElement(owner)) {
2136
+ return commitPresentationMutation(state, () => [{ kind: "node.update", element: owner }]);
2137
+ }
2138
+ return null;
2139
+ }
2140
+ function commitPresentationMutation(state, commands) {
2141
+ return {
2142
+ commit(result) {
2143
+ const batch = commands(result);
2144
+ if (batch.length === 0) return false;
2145
+ const session = state.native;
2146
+ if (!(session instanceof NativePresentationSession)) {
2147
+ throw new TypeError("Expected native presentation session");
2148
+ }
2149
+ const before = session.revision();
2150
+ session.applyCommands(encodePresentationIncrementalCommands(batch, state.namespace));
2151
+ return session.revision() > before;
2152
+ }
2153
+ };
2154
+ }
2155
+ function isPresentationElement(value) {
2156
+ return value instanceof PresentationShape || value instanceof PresentationChart || value instanceof PresentationImage || value instanceof PresentationTable || value instanceof PresentationGroup;
2157
+ }
2158
+ function findPresentationTextOwner(presentation, text) {
2159
+ const visit = (element) => {
2160
+ if (element instanceof PresentationShape && element.text === text) return element;
2161
+ if (element instanceof PresentationGroup) {
2162
+ for (const child of element.children) {
2163
+ const match = visit(child);
2164
+ if (match) return match;
2165
+ }
2166
+ }
2167
+ if (element instanceof PresentationTable) {
2168
+ if (element.rows.some((row) => row.some((cell) => cell?.text === text))) return element;
2169
+ }
2170
+ return null;
2171
+ };
2172
+ for (const slide of presentation.slides.items) {
2173
+ if (slide.notes === text) return { kind: "notes", slide };
2174
+ for (const element of slide.elements) {
2175
+ const match = visit(element);
2176
+ if (match) return { kind: "node", element: match };
2177
+ }
2178
+ }
2179
+ return null;
2180
+ }
2181
+ function captureSpreadsheetAuxiliary(workbook) {
2182
+ const value = LOSS_PRESERVATION.get(workbook);
2183
+ return value ? structuredClone(value) : void 0;
2184
+ }
2185
+ function restoreSpreadsheetAuxiliary(workbook, value) {
2186
+ if (value)
2187
+ LOSS_PRESERVATION.set(workbook, value);
2188
+ }
2189
+ function captureDocumentAuxiliary(document) {
2190
+ const value = DOCUMENT_LOSS_PRESERVATION.get(document);
2191
+ return value ? structuredClone(value) : void 0;
2192
+ }
2193
+ function restoreDocumentAuxiliary(document, value) {
2194
+ if (value) {
2195
+ DOCUMENT_LOSS_PRESERVATION.set(
2196
+ document,
2197
+ value
2198
+ );
2199
+ }
2200
+ }
2201
+ function capturePresentationAuxiliary(presentation) {
2202
+ const value = presentationLossState(presentation);
2203
+ return value ? structuredClone(value) : void 0;
2204
+ }
2205
+ function restorePresentationAuxiliary(presentation, value) {
2206
+ setPresentationLossState(presentation, value);
2207
+ }
2208
+ function rawArtifact(artifact, modality) {
2209
+ return requireCompositeState(artifact, modality).rawRoot();
2210
+ }
2211
+ function createStaticFacade(reference, name, statics) {
2212
+ const facade = function ArtifactFacade() {
2213
+ throw new TypeError(`${name} cannot be constructed directly; use ${name}.create()`);
2214
+ };
2215
+ Object.setPrototypeOf(facade, reference);
2216
+ Object.defineProperty(facade, "name", { configurable: true, value: name });
2217
+ Object.defineProperty(facade, "prototype", { value: reference.prototype });
2218
+ for (const [key, value] of Object.entries(statics)) {
2219
+ Object.defineProperty(facade, key, { configurable: false, enumerable: false, value });
2220
+ }
2221
+ return facade;
2222
+ }
2223
+ function requireConfiguredRuntime() {
2224
+ if (!configuredRuntime) {
2225
+ throw new ArtifactRuntimeError(
2226
+ "ARTIFACT_RUNTIME_UNAVAILABLE",
2227
+ "No exact artifact runtime is configured; host bootstrap must call configureArtifactRuntime()"
2228
+ );
2229
+ }
2230
+ return configuredRuntime;
2231
+ }
2232
+ function envelopeCommandCount(bytes) {
2233
+ if (bytes.byteLength < 16) throw new TypeError("Native command envelope is truncated");
2234
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(12, true);
2235
+ }
2236
+ function randomNamespace() {
2237
+ const words = crypto.getRandomValues(new Uint32Array(2));
2238
+ const namespace = BigInt(words[0]) << 32n | BigInt(words[1]);
2239
+ return namespace === 0n ? randomNamespace() : namespace;
2240
+ }
2241
+ function u64Hex2(value) {
2242
+ if (value <= 0n || value > 0xffffffffffffffffn) {
2243
+ throw new RangeError("Artifact namespace must be a nonzero u64");
2244
+ }
2245
+ return value.toString(16).padStart(16, "0");
2246
+ }
2247
+
2248
+ export {
2249
+ configureArtifactRuntime,
2250
+ getConfiguredArtifactRuntime,
2251
+ Workbook2 as Workbook,
2252
+ Document2 as Document,
2253
+ Presentation2 as Presentation,
2254
+ SpreadsheetFile2 as SpreadsheetFile,
2255
+ DocumentFile2 as DocumentFile,
2256
+ PresentationFile2 as PresentationFile,
2257
+ getArtifactCompositeDiagnostics,
2258
+ disposeArtifact
2259
+ };
2260
+ //# sourceMappingURL=chunk-ZZXPEE4S.js.map