@ember-lattice/server 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1542 @@
1
+ import { createRefContext, shrinkDeleted } from '@ember-lattice/formula';
2
+
3
+ // ../../node_modules/.pnpm/@sindresorhus+is@8.1.0/node_modules/@sindresorhus/is/distribution/utilities.js
4
+
5
+ // ../../node_modules/.pnpm/@sindresorhus+is@8.1.0/node_modules/@sindresorhus/is/distribution/index.js
6
+ var typedArrayTypeNames = [
7
+ "Int8Array",
8
+ "Uint8Array",
9
+ "Uint8ClampedArray",
10
+ "Int16Array",
11
+ "Uint16Array",
12
+ "Int32Array",
13
+ "Uint32Array",
14
+ "Float32Array",
15
+ "Float64Array",
16
+ "BigInt64Array",
17
+ "BigUint64Array"
18
+ ];
19
+ function isTypedArrayName(name) {
20
+ return typedArrayTypeNames.includes(name);
21
+ }
22
+ var objectTypeNames = [
23
+ "Function",
24
+ "Generator",
25
+ "AsyncGenerator",
26
+ "GeneratorFunction",
27
+ "AsyncGeneratorFunction",
28
+ "AsyncFunction",
29
+ "Observable",
30
+ "Array",
31
+ "Buffer",
32
+ "Blob",
33
+ "Object",
34
+ "RegExp",
35
+ "Date",
36
+ "Error",
37
+ "Map",
38
+ "Set",
39
+ "WeakMap",
40
+ "WeakSet",
41
+ "WeakRef",
42
+ "ArrayBuffer",
43
+ "SharedArrayBuffer",
44
+ "DataView",
45
+ "Promise",
46
+ "URL",
47
+ "FormData",
48
+ "URLSearchParams",
49
+ "HTMLElement",
50
+ "NaN",
51
+ ...typedArrayTypeNames
52
+ ];
53
+ function isObjectTypeName(name) {
54
+ return objectTypeNames.includes(name);
55
+ }
56
+ var primitiveTypeNames = [
57
+ "null",
58
+ "undefined",
59
+ "string",
60
+ "number",
61
+ "bigint",
62
+ "boolean",
63
+ "symbol"
64
+ ];
65
+ function isPrimitiveTypeName(name) {
66
+ return primitiveTypeNames.includes(name);
67
+ }
68
+ var getObjectType = (value2) => {
69
+ const objectTypeName = Object.prototype.toString.call(value2).slice(8, -1);
70
+ if (new RegExp("HTML\\w+Element", "v").test(objectTypeName) && isHtmlElement(value2)) {
71
+ return "HTMLElement";
72
+ }
73
+ if (isObjectTypeName(objectTypeName)) {
74
+ return objectTypeName;
75
+ }
76
+ return void 0;
77
+ };
78
+ function detect(value2) {
79
+ if (value2 === null) {
80
+ return "null";
81
+ }
82
+ switch (typeof value2) {
83
+ case "undefined": {
84
+ return "undefined";
85
+ }
86
+ case "string": {
87
+ return "string";
88
+ }
89
+ case "number": {
90
+ return Number.isNaN(value2) ? "NaN" : "number";
91
+ }
92
+ case "boolean": {
93
+ return "boolean";
94
+ }
95
+ case "function": {
96
+ return "Function";
97
+ }
98
+ case "bigint": {
99
+ return "bigint";
100
+ }
101
+ case "symbol": {
102
+ return "symbol";
103
+ }
104
+ }
105
+ if (isObservable(value2)) {
106
+ return "Observable";
107
+ }
108
+ if (isArray(value2)) {
109
+ return "Array";
110
+ }
111
+ if (isBuffer(value2)) {
112
+ return "Buffer";
113
+ }
114
+ const tagType = getObjectType(value2);
115
+ if (tagType !== void 0 && tagType !== "Object") {
116
+ return tagType;
117
+ }
118
+ if (hasPromiseApi(value2)) {
119
+ return "Promise";
120
+ }
121
+ if (isBoxedPrimitiveObject(value2)) {
122
+ throw new TypeError("Please don't use object wrappers for primitive types");
123
+ }
124
+ return "Object";
125
+ }
126
+ function hasPromiseApi(value2) {
127
+ return isFunction(value2?.then) && isFunction(value2?.catch);
128
+ }
129
+ function hasBoxedPrimitiveBrand(value2, valueOf) {
130
+ try {
131
+ Reflect.apply(valueOf, value2, []);
132
+ return true;
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+ function isBoxedPrimitiveObject(value2) {
138
+ return hasBoxedPrimitiveBrand(value2, String.prototype.valueOf) || hasBoxedPrimitiveBrand(value2, Boolean.prototype.valueOf) || hasBoxedPrimitiveBrand(value2, Number.prototype.valueOf);
139
+ }
140
+ var is = Object.assign(detect, {
141
+ all: isAll,
142
+ any: isAny,
143
+ array: isArray,
144
+ arrayBuffer: isArrayBuffer,
145
+ arrayLike: isArrayLike,
146
+ arrayOf: isArrayOf,
147
+ asyncFunction: isAsyncFunction,
148
+ asyncGenerator: isAsyncGenerator,
149
+ asyncGeneratorFunction: isAsyncGeneratorFunction,
150
+ asyncIterable: isAsyncIterable,
151
+ bigint: isBigint,
152
+ bigInt64Array: isBigInt64Array,
153
+ bigUint64Array: isBigUint64Array,
154
+ blob: isBlob,
155
+ boolean: isBoolean,
156
+ boundFunction: isBoundFunction,
157
+ buffer: isBuffer,
158
+ class: isClass,
159
+ dataView: isDataView,
160
+ date: isDate,
161
+ detect,
162
+ directInstanceOf: isDirectInstanceOf,
163
+ emptyArray: isEmptyArray,
164
+ emptyMap: isEmptyMap,
165
+ emptyObject: isEmptyObject,
166
+ emptySet: isEmptySet,
167
+ emptyString: isEmptyString,
168
+ emptyStringOrWhitespace: isEmptyStringOrWhitespace,
169
+ enumCase: isEnumCase,
170
+ error: isError,
171
+ evenInteger: isEvenInteger,
172
+ falsy: isFalsy,
173
+ finiteNumber: isFiniteNumber,
174
+ float32Array: isFloat32Array,
175
+ float64Array: isFloat64Array,
176
+ formData: isFormData,
177
+ function: isFunction,
178
+ generator: isGenerator,
179
+ generatorFunction: isGeneratorFunction,
180
+ htmlElement: isHtmlElement,
181
+ infinite: isInfinite,
182
+ inRange: isInRange,
183
+ int16Array: isInt16Array,
184
+ int32Array: isInt32Array,
185
+ int8Array: isInt8Array,
186
+ integer: isInteger,
187
+ iterable: isIterable,
188
+ map: isMap,
189
+ nan: isNan,
190
+ nativePromise: isNativePromise,
191
+ negativeInteger: isNegativeInteger,
192
+ negativeNumber: isNegativeNumber,
193
+ nodeStream: isNodeStream,
194
+ nonEmptyArray: isNonEmptyArray,
195
+ nonEmptyMap: isNonEmptyMap,
196
+ nonEmptyObject: isNonEmptyObject,
197
+ nonEmptySet: isNonEmptySet,
198
+ nonEmptyString: isNonEmptyString,
199
+ nonEmptyStringAndNotWhitespace: isNonEmptyStringAndNotWhitespace,
200
+ nonNegativeInteger: isNonNegativeInteger,
201
+ nonNegativeNumber: isNonNegativeNumber,
202
+ null: isNull,
203
+ nullOrUndefined: isNullOrUndefined,
204
+ number: isNumber,
205
+ numericString: isNumericString,
206
+ object: isObject,
207
+ observable: isObservable,
208
+ oddInteger: isOddInteger,
209
+ oneOf: isOneOf,
210
+ plainObject: isPlainObject,
211
+ positiveInteger: isPositiveInteger,
212
+ positiveNumber: isPositiveNumber,
213
+ primitive: isPrimitive,
214
+ promise: isPromise,
215
+ propertyKey: isPropertyKey,
216
+ regExp: isRegExp,
217
+ safeInteger: isSafeInteger,
218
+ set: isSet,
219
+ sharedArrayBuffer: isSharedArrayBuffer,
220
+ string: isString,
221
+ symbol: isSymbol,
222
+ truthy: isTruthy,
223
+ tupleLike: isTupleLike,
224
+ typedArray: isTypedArray,
225
+ uint16Array: isUint16Array,
226
+ uint32Array: isUint32Array,
227
+ uint8Array: isUint8Array,
228
+ uint8ClampedArray: isUint8ClampedArray,
229
+ undefined: isUndefined,
230
+ urlInstance: isUrlInstance,
231
+ urlSearchParams: isUrlSearchParams,
232
+ urlString: isUrlString,
233
+ optional: isOptional,
234
+ validDate: isValidDate,
235
+ validLength: isValidLength,
236
+ weakMap: isWeakMap,
237
+ weakRef: isWeakRef,
238
+ weakSet: isWeakSet,
239
+ whitespaceString: isWhitespaceString
240
+ });
241
+ function isAbsoluteModule2(remainder) {
242
+ return (value2) => isInteger(value2) && Math.abs(value2 % 2) === remainder;
243
+ }
244
+ function validatePredicateArray(predicateArray, allowEmpty) {
245
+ if (predicateArray.length === 0) {
246
+ if (allowEmpty) ; else {
247
+ throw new TypeError("Invalid predicate array");
248
+ }
249
+ return;
250
+ }
251
+ for (const predicate of predicateArray) {
252
+ validatePredicate(predicate);
253
+ }
254
+ }
255
+ function validatePredicate(predicate) {
256
+ if (!isFunction(predicate)) {
257
+ throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
258
+ }
259
+ }
260
+ function isAll(predicate, ...values) {
261
+ if (Array.isArray(predicate)) {
262
+ const predicateArray = predicate;
263
+ validatePredicateArray(predicateArray, values.length === 0);
264
+ const combinedPredicate = (value2) => predicateArray.every((singlePredicate) => singlePredicate(value2));
265
+ if (values.length === 0) {
266
+ return combinedPredicate;
267
+ }
268
+ return predicateOnArray(Array.prototype.every, combinedPredicate, values);
269
+ }
270
+ return predicateOnArray(Array.prototype.every, predicate, values);
271
+ }
272
+ function isAny(predicate, ...values) {
273
+ if (Array.isArray(predicate)) {
274
+ const predicateArray = predicate;
275
+ validatePredicateArray(predicateArray, values.length === 0);
276
+ const combinedPredicate = (value2) => predicateArray.some((singlePredicate) => singlePredicate(value2));
277
+ if (values.length === 0) {
278
+ return combinedPredicate;
279
+ }
280
+ return predicateOnArray(Array.prototype.some, combinedPredicate, values);
281
+ }
282
+ return predicateOnArray(Array.prototype.some, predicate, values);
283
+ }
284
+ function isOptional(value2, predicate) {
285
+ return isUndefined(value2) || predicate(value2);
286
+ }
287
+ function isArray(value2, assertion) {
288
+ if (!Array.isArray(value2)) {
289
+ return false;
290
+ }
291
+ if (!isFunction(assertion)) {
292
+ return true;
293
+ }
294
+ return value2.every((element) => assertion(element));
295
+ }
296
+ function isArrayBuffer(value2) {
297
+ return getObjectType(value2) === "ArrayBuffer";
298
+ }
299
+ function isArrayLike(value2) {
300
+ return !isNullOrUndefined(value2) && !isFunction(value2) && isValidLength(value2.length);
301
+ }
302
+ function isArrayOf(predicate) {
303
+ return (value2) => isArray(value2) && value2.every((element) => predicate(element));
304
+ }
305
+ function isAsyncFunction(value2) {
306
+ return getObjectType(value2) === "AsyncFunction";
307
+ }
308
+ function isAsyncGenerator(value2) {
309
+ return isAsyncIterable(value2) && isFunction(value2.next) && isFunction(value2.throw);
310
+ }
311
+ function isAsyncGeneratorFunction(value2) {
312
+ return getObjectType(value2) === "AsyncGeneratorFunction";
313
+ }
314
+ function isAsyncIterable(value2) {
315
+ return isFunction(value2?.[Symbol.asyncIterator]);
316
+ }
317
+ function isBigint(value2) {
318
+ return typeof value2 === "bigint";
319
+ }
320
+ function isBigInt64Array(value2) {
321
+ return getObjectType(value2) === "BigInt64Array";
322
+ }
323
+ function isBigUint64Array(value2) {
324
+ return getObjectType(value2) === "BigUint64Array";
325
+ }
326
+ function isBlob(value2) {
327
+ return getObjectType(value2) === "Blob";
328
+ }
329
+ function isBoolean(value2) {
330
+ return value2 === true || value2 === false;
331
+ }
332
+ function isBoundFunction(value2) {
333
+ return isFunction(value2) && !Object.hasOwn(value2, "prototype");
334
+ }
335
+ function isBuffer(value2) {
336
+ return value2?.constructor?.isBuffer?.(value2) ?? false;
337
+ }
338
+ function isClass(value2) {
339
+ return isFunction(value2) && new RegExp("^class(?:\\s+|\\{)", "v").test(value2.toString());
340
+ }
341
+ function isDataView(value2) {
342
+ return getObjectType(value2) === "DataView";
343
+ }
344
+ function isDate(value2) {
345
+ return getObjectType(value2) === "Date";
346
+ }
347
+ function isDirectInstanceOf(instance, class_) {
348
+ if (instance === void 0 || instance === null) {
349
+ return false;
350
+ }
351
+ return Object.getPrototypeOf(instance) === class_.prototype;
352
+ }
353
+ function isEmptyArray(value2) {
354
+ return isArray(value2) && value2.length === 0;
355
+ }
356
+ function isEmptyMap(value2) {
357
+ return isMap(value2) && value2.size === 0;
358
+ }
359
+ function isEmptyObject(value2) {
360
+ return isObject(value2) && !isFunction(value2) && !isArray(value2) && !isMap(value2) && !isSet(value2) && Object.keys(value2).length === 0;
361
+ }
362
+ function isEmptySet(value2) {
363
+ return isSet(value2) && value2.size === 0;
364
+ }
365
+ function isEmptyString(value2) {
366
+ return isString(value2) && value2.length === 0;
367
+ }
368
+ function isEmptyStringOrWhitespace(value2) {
369
+ return isEmptyString(value2) || isWhitespaceString(value2);
370
+ }
371
+ function isEnumCase(value2, targetEnum) {
372
+ const enumObject = targetEnum;
373
+ return Object.entries(enumObject).some(([key2, enumValue]) => {
374
+ if (!isString(enumValue)) {
375
+ return enumValue === value2;
376
+ }
377
+ const numericKey = Number(key2);
378
+ if (Number.isNaN(numericKey) || String(numericKey) !== key2) {
379
+ return enumValue === value2;
380
+ }
381
+ return enumValue === value2 && !(Object.hasOwn(enumObject, enumValue) && enumObject[enumValue] === numericKey);
382
+ });
383
+ }
384
+ function isError(value2) {
385
+ return getObjectType(value2) === "Error";
386
+ }
387
+ function isEvenInteger(value2) {
388
+ return isAbsoluteModule2(0)(value2);
389
+ }
390
+ function isFalsy(value2) {
391
+ return !value2;
392
+ }
393
+ function isFiniteNumber(value2) {
394
+ return Number.isFinite(value2);
395
+ }
396
+ function isFloat32Array(value2) {
397
+ return getObjectType(value2) === "Float32Array";
398
+ }
399
+ function isFloat64Array(value2) {
400
+ return getObjectType(value2) === "Float64Array";
401
+ }
402
+ function isFormData(value2) {
403
+ return getObjectType(value2) === "FormData";
404
+ }
405
+ function isFunction(value2) {
406
+ return typeof value2 === "function";
407
+ }
408
+ function isGenerator(value2) {
409
+ return isIterable(value2) && isFunction(value2?.next) && isFunction(value2?.throw);
410
+ }
411
+ function isGeneratorFunction(value2) {
412
+ return getObjectType(value2) === "GeneratorFunction";
413
+ }
414
+ var NODE_TYPE_ELEMENT = 1;
415
+ var DOM_PROPERTIES_TO_CHECK = [
416
+ "innerHTML",
417
+ "ownerDocument",
418
+ "style",
419
+ "attributes",
420
+ "nodeValue"
421
+ ];
422
+ function isHtmlElement(value2) {
423
+ return isObject(value2) && value2.nodeType === NODE_TYPE_ELEMENT && isString(value2.nodeName) && !isPlainObject(value2) && DOM_PROPERTIES_TO_CHECK.every((property) => property in value2);
424
+ }
425
+ function isInfinite(value2) {
426
+ return value2 === Number.POSITIVE_INFINITY || value2 === Number.NEGATIVE_INFINITY;
427
+ }
428
+ function isInRange(value2, range2) {
429
+ if (isNumber(range2)) {
430
+ return value2 >= Math.min(0, range2) && value2 <= Math.max(range2, 0);
431
+ }
432
+ if (isArray(range2) && range2.length === 2) {
433
+ if (Number.isNaN(range2[0]) || Number.isNaN(range2[1])) {
434
+ throw new TypeError(`Invalid range: ${JSON.stringify(range2)}`);
435
+ }
436
+ return value2 >= Math.min(...range2) && value2 <= Math.max(...range2);
437
+ }
438
+ throw new TypeError(`Invalid range: ${JSON.stringify(range2)}`);
439
+ }
440
+ function isInt16Array(value2) {
441
+ return getObjectType(value2) === "Int16Array";
442
+ }
443
+ function isInt32Array(value2) {
444
+ return getObjectType(value2) === "Int32Array";
445
+ }
446
+ function isInt8Array(value2) {
447
+ return getObjectType(value2) === "Int8Array";
448
+ }
449
+ function isInteger(value2) {
450
+ return Number.isInteger(value2);
451
+ }
452
+ function isIterable(value2) {
453
+ return isFunction(value2?.[Symbol.iterator]);
454
+ }
455
+ function isMap(value2) {
456
+ return getObjectType(value2) === "Map";
457
+ }
458
+ function isNan(value2) {
459
+ return Number.isNaN(value2);
460
+ }
461
+ function isNativePromise(value2) {
462
+ return getObjectType(value2) === "Promise";
463
+ }
464
+ function isNegativeInteger(value2) {
465
+ return isInteger(value2) && value2 < 0;
466
+ }
467
+ function isNegativeNumber(value2) {
468
+ return isNumber(value2) && value2 < 0;
469
+ }
470
+ function isNodeStream(value2) {
471
+ return isObject(value2) && isFunction(value2.pipe) && !isObservable(value2);
472
+ }
473
+ function isNonEmptyArray(value2) {
474
+ return isArray(value2) && value2.length > 0;
475
+ }
476
+ function isNonEmptyMap(value2) {
477
+ return isMap(value2) && value2.size > 0;
478
+ }
479
+ function isNonEmptyObject(value2) {
480
+ return isObject(value2) && !isFunction(value2) && !isArray(value2) && !isMap(value2) && !isSet(value2) && Object.keys(value2).length > 0;
481
+ }
482
+ function isNonEmptySet(value2) {
483
+ return isSet(value2) && value2.size > 0;
484
+ }
485
+ function isNonEmptyString(value2) {
486
+ return isString(value2) && value2.length > 0;
487
+ }
488
+ function isNonEmptyStringAndNotWhitespace(value2) {
489
+ return isString(value2) && !isEmptyStringOrWhitespace(value2);
490
+ }
491
+ function isNonNegativeInteger(value2) {
492
+ return isInteger(value2) && value2 >= 0;
493
+ }
494
+ function isNonNegativeNumber(value2) {
495
+ return isNumber(value2) && value2 >= 0;
496
+ }
497
+ function isNull(value2) {
498
+ return value2 === null;
499
+ }
500
+ function isNullOrUndefined(value2) {
501
+ return isNull(value2) || isUndefined(value2);
502
+ }
503
+ function isNumber(value2) {
504
+ return typeof value2 === "number" && !Number.isNaN(value2);
505
+ }
506
+ function isNumericString(value2) {
507
+ return isString(value2) && !isEmptyStringOrWhitespace(value2) && value2 === value2.trim() && !Number.isNaN(Number(value2));
508
+ }
509
+ function isObject(value2) {
510
+ return !isNull(value2) && (typeof value2 === "object" || isFunction(value2));
511
+ }
512
+ function isObservable(value2) {
513
+ if (!value2) {
514
+ return false;
515
+ }
516
+ if (Symbol.observable !== void 0 && value2 === value2[Symbol.observable]?.()) {
517
+ return true;
518
+ }
519
+ if (value2 === value2["@@observable"]?.()) {
520
+ return true;
521
+ }
522
+ return false;
523
+ }
524
+ function isOddInteger(value2) {
525
+ return isAbsoluteModule2(1)(value2);
526
+ }
527
+ function isOneOf(values) {
528
+ return (value2) => values.includes(value2);
529
+ }
530
+ function isPlainObject(value2) {
531
+ if (typeof value2 !== "object" || value2 === null) {
532
+ return false;
533
+ }
534
+ const prototype = Object.getPrototypeOf(value2);
535
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value2) && !(Symbol.iterator in value2);
536
+ }
537
+ function isPositiveInteger(value2) {
538
+ return isInteger(value2) && value2 > 0;
539
+ }
540
+ function isPositiveNumber(value2) {
541
+ return isNumber(value2) && value2 > 0;
542
+ }
543
+ function isPrimitive(value2) {
544
+ return isNull(value2) || isPrimitiveTypeName(typeof value2);
545
+ }
546
+ function isPromise(value2) {
547
+ return isNativePromise(value2) || hasPromiseApi(value2);
548
+ }
549
+ function isPropertyKey(value2) {
550
+ return isAny([isString, isNumber, isSymbol], value2);
551
+ }
552
+ function isRegExp(value2) {
553
+ return getObjectType(value2) === "RegExp";
554
+ }
555
+ function isSafeInteger(value2) {
556
+ return Number.isSafeInteger(value2);
557
+ }
558
+ function isSet(value2) {
559
+ return getObjectType(value2) === "Set";
560
+ }
561
+ function isSharedArrayBuffer(value2) {
562
+ return getObjectType(value2) === "SharedArrayBuffer";
563
+ }
564
+ function isString(value2) {
565
+ return typeof value2 === "string";
566
+ }
567
+ function isSymbol(value2) {
568
+ return typeof value2 === "symbol";
569
+ }
570
+ function isTruthy(value2) {
571
+ return Boolean(value2);
572
+ }
573
+ function isTupleLike(value2, guards) {
574
+ if (isArray(guards) && isArray(value2) && guards.length === value2.length) {
575
+ return guards.every((guard, index) => guard(value2[index]));
576
+ }
577
+ return false;
578
+ }
579
+ function isTypedArray(value2) {
580
+ return isTypedArrayName(getObjectType(value2));
581
+ }
582
+ function isUint16Array(value2) {
583
+ return getObjectType(value2) === "Uint16Array";
584
+ }
585
+ function isUint32Array(value2) {
586
+ return getObjectType(value2) === "Uint32Array";
587
+ }
588
+ function isUint8Array(value2) {
589
+ return getObjectType(value2) === "Uint8Array";
590
+ }
591
+ function isUint8ClampedArray(value2) {
592
+ return getObjectType(value2) === "Uint8ClampedArray";
593
+ }
594
+ function isUndefined(value2) {
595
+ return value2 === void 0;
596
+ }
597
+ function isUrlInstance(value2) {
598
+ return getObjectType(value2) === "URL";
599
+ }
600
+ function isUrlSearchParams(value2) {
601
+ return getObjectType(value2) === "URLSearchParams";
602
+ }
603
+ function isUrlString(value2) {
604
+ if (!isString(value2)) {
605
+ return false;
606
+ }
607
+ try {
608
+ new URL(value2);
609
+ return true;
610
+ } catch {
611
+ return false;
612
+ }
613
+ }
614
+ function isValidDate(value2) {
615
+ return isDate(value2) && !isNan(Number(value2));
616
+ }
617
+ function isValidLength(value2) {
618
+ return isSafeInteger(value2) && value2 >= 0;
619
+ }
620
+ function isWeakMap(value2) {
621
+ return getObjectType(value2) === "WeakMap";
622
+ }
623
+ function isWeakRef(value2) {
624
+ return getObjectType(value2) === "WeakRef";
625
+ }
626
+ function isWeakSet(value2) {
627
+ return getObjectType(value2) === "WeakSet";
628
+ }
629
+ function isWhitespaceString(value2) {
630
+ return isString(value2) && new RegExp("^\\s+$", "v").test(value2);
631
+ }
632
+ function predicateOnArray(method, predicate, values) {
633
+ validatePredicate(predicate);
634
+ if (values.length === 0) {
635
+ throw new TypeError("Invalid number of values");
636
+ }
637
+ return method.call(values, predicate);
638
+ }
639
+ var distribution_default = is;
640
+
641
+ // src/collab/wire.ts
642
+ var COLLAB_VERSION = 1;
643
+ var COLLAB_LIMITS = {
644
+ /** Ops in one submit. */
645
+ maxOps: 1e3,
646
+ /** IDs in one insert or delete. */
647
+ maxIds: 1e4,
648
+ /** Characters in a text value, a formula or a name ref (the Excel cell limit). */
649
+ maxText: 32767,
650
+ /** Characters in a number format, a style color or a user name. */
651
+ maxShort: 256,
652
+ /** Characters in an ID (doc, client, op, sheet, row or column). */
653
+ maxId: 64
654
+ };
655
+ var ID = /^[\w.-]+$/;
656
+ var SHEET_NAME = /^[^[\]:*?/\\']{1,31}$/;
657
+ var NAME = /^[A-Za-z_\\][\w.]{0,254}$/;
658
+ var ERRORS = /* @__PURE__ */ new Set(["#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"]);
659
+ var STYLE_FLAGS = ["bold", "italic", "underline", "strike", "wrap"];
660
+ var ALIGN = /* @__PURE__ */ new Set(["left", "center", "right"]);
661
+ var VALIGN = /* @__PURE__ */ new Set(["top", "middle", "bottom"]);
662
+ var SIDES = /* @__PURE__ */ new Set(["top", "right", "bottom", "left"]);
663
+ var badString = (s) => s.includes("\0") || /\p{Cs}/u.test(s);
664
+ var Bad = class extends Error {
665
+ };
666
+ function fail(message2) {
667
+ throw new Bad(message2);
668
+ }
669
+ function obj(input, path, required, optional = []) {
670
+ if (!distribution_default.plainObject(input)) fail(`${path} must be an object`);
671
+ const known = /* @__PURE__ */ new Set([...required, ...optional]);
672
+ for (const key2 of Object.keys(input)) if (!known.has(key2)) fail(`${path}.${key2} is not known`);
673
+ for (const key2 of required) if (!Object.hasOwn(input, key2)) fail(`${path}.${key2} is missing`);
674
+ return input;
675
+ }
676
+ function text(input, path, max) {
677
+ if (!distribution_default.string(input)) fail(`${path} must be a string`);
678
+ if (input.length > max) fail(`${path} has more than ${max} characters`);
679
+ if (badString(input)) fail(`${path} has U+0000 or a lone surrogate`);
680
+ return input;
681
+ }
682
+ function id(input, path) {
683
+ const s = text(input, path, COLLAB_LIMITS.maxId);
684
+ if (!ID.test(s)) fail(`${path} must match ${ID}`);
685
+ return s;
686
+ }
687
+ function ids(input, path) {
688
+ if (!distribution_default.array(input)) fail(`${path} must be a list`);
689
+ if (input.length === 0 || input.length > COLLAB_LIMITS.maxIds) {
690
+ fail(`${path} must have 1 to ${COLLAB_LIMITS.maxIds} IDs`);
691
+ }
692
+ return input.map((x, i) => id(x, `${path}[${i}]`));
693
+ }
694
+ function seq(input, path) {
695
+ if (!distribution_default.safeInteger(input) || input < 0) fail(`${path} must be an integer >= 0`);
696
+ return input;
697
+ }
698
+ function value(input, path) {
699
+ if (input === null || distribution_default.boolean(input)) return input;
700
+ if (distribution_default.number(input)) {
701
+ if (!Number.isFinite(input)) fail(`${path} must be finite`);
702
+ return input;
703
+ }
704
+ if (distribution_default.string(input)) return text(input, path, COLLAB_LIMITS.maxText);
705
+ const o = obj(input, path, ["error"]);
706
+ if (!distribution_default.string(o["error"]) || !ERRORS.has(o["error"])) fail(`${path}.error is not known`);
707
+ return { error: o["error"] };
708
+ }
709
+ function cell(input, path) {
710
+ const o = obj(input, path, ["sheet", "row", "col"]);
711
+ return {
712
+ sheet: id(o["sheet"], `${path}.sheet`),
713
+ row: id(o["row"], `${path}.row`),
714
+ col: id(o["col"], `${path}.col`)
715
+ };
716
+ }
717
+ function corner(input, path) {
718
+ const o = obj(input, path, ["row", "col"]);
719
+ return { row: id(o["row"], `${path}.row`), col: id(o["col"], `${path}.col`) };
720
+ }
721
+ function range(input, path) {
722
+ const o = obj(input, path, ["sheet", "start", "end"]);
723
+ return {
724
+ sheet: id(o["sheet"], `${path}.sheet`),
725
+ start: corner(o["start"], `${path}.start`),
726
+ end: corner(o["end"], `${path}.end`)
727
+ };
728
+ }
729
+ function short(input, path) {
730
+ return text(input, path, COLLAB_LIMITS.maxShort);
731
+ }
732
+ function style(input, path) {
733
+ const keys = [...STYLE_FLAGS, "color", "fill", "align", "valign", "border"];
734
+ const o = obj(input, path, [], keys);
735
+ const out = {};
736
+ for (const flag of STYLE_FLAGS) {
737
+ if (!Object.hasOwn(o, flag)) continue;
738
+ if (!distribution_default.boolean(o[flag])) fail(`${path}.${flag} must be a boolean`);
739
+ out[flag] = o[flag];
740
+ }
741
+ if (Object.hasOwn(o, "color")) out.color = short(o["color"], `${path}.color`);
742
+ if (Object.hasOwn(o, "fill")) out.fill = short(o["fill"], `${path}.fill`);
743
+ if (Object.hasOwn(o, "align")) {
744
+ if (!ALIGN.has(o["align"])) fail(`${path}.align is not known`);
745
+ out.align = o["align"];
746
+ }
747
+ if (Object.hasOwn(o, "valign")) {
748
+ if (!VALIGN.has(o["valign"])) fail(`${path}.valign is not known`);
749
+ out.valign = o["valign"];
750
+ }
751
+ if (Object.hasOwn(o, "border")) {
752
+ const b = obj(o["border"], `${path}.border`, [], [...SIDES]);
753
+ out.border = Object.fromEntries(
754
+ Object.entries(b).map(([side, v]) => [side, short(v, `${path}.border.${side}`)])
755
+ );
756
+ }
757
+ return out;
758
+ }
759
+ function sheetName(input, path) {
760
+ const s = text(input, path, 31);
761
+ if (!SHEET_NAME.test(s)) fail(`${path} is not a valid sheet name`);
762
+ return s;
763
+ }
764
+ function count(input, path) {
765
+ if (!distribution_default.safeInteger(input) || input < 0 || input > COLLAB_LIMITS.maxIds) {
766
+ fail(`${path} must be an integer from 0 to ${COLLAB_LIMITS.maxIds}`);
767
+ }
768
+ return input;
769
+ }
770
+ function op(input, path) {
771
+ if (!distribution_default.plainObject(input)) fail(`${path} must be an object`);
772
+ const p = (key2) => `${path}.${key2}`;
773
+ switch (input["type"]) {
774
+ case "setCell": {
775
+ const o = obj(input, path, ["type", "sheet", "row", "col"], ["value", "formula"]);
776
+ const out = {
777
+ type: "setCell",
778
+ ...cell({ sheet: o["sheet"], row: o["row"], col: o["col"] }, path)
779
+ };
780
+ if (Object.hasOwn(o, "value")) out.value = value(o["value"], p("value"));
781
+ if (Object.hasOwn(o, "formula")) {
782
+ const f = text(o["formula"], p("formula"), COLLAB_LIMITS.maxText);
783
+ if (!f.startsWith("=") || f.length < 2) fail(`${p("formula")} must start with =`);
784
+ out.formula = f;
785
+ }
786
+ return out;
787
+ }
788
+ case "insertRows":
789
+ case "insertCols": {
790
+ const o = obj(input, path, ["type", "sheet", "ids", "before"]);
791
+ return {
792
+ type: input["type"],
793
+ sheet: id(o["sheet"], p("sheet")),
794
+ ids: ids(o["ids"], p("ids")),
795
+ before: o["before"] === null ? null : id(o["before"], p("before"))
796
+ };
797
+ }
798
+ case "deleteRows":
799
+ case "deleteCols": {
800
+ const o = obj(input, path, ["type", "sheet", "ids"]);
801
+ return {
802
+ type: input["type"],
803
+ sheet: id(o["sheet"], p("sheet")),
804
+ ids: ids(o["ids"], p("ids"))
805
+ };
806
+ }
807
+ case "setFormat": {
808
+ const o = obj(input, path, ["type", "range", "format"]);
809
+ const format = o["format"] === null ? null : short(o["format"], p("format"));
810
+ return { type: "setFormat", range: range(o["range"], p("range")), format };
811
+ }
812
+ case "setStyle": {
813
+ const o = obj(input, path, ["type", "range", "style"]);
814
+ const s = o["style"] === null ? null : style(o["style"], p("style"));
815
+ return { type: "setStyle", range: range(o["range"], p("range")), style: s };
816
+ }
817
+ case "merge":
818
+ case "unmerge": {
819
+ const o = obj(input, path, ["type", "range"]);
820
+ return { type: input["type"], range: range(o["range"], p("range")) };
821
+ }
822
+ case "setName": {
823
+ const o = obj(input, path, ["type", "name", "ref"]);
824
+ const name = text(o["name"], p("name"), 255);
825
+ if (!NAME.test(name)) fail(`${p("name")} is not a valid name`);
826
+ const ref = o["ref"] === null ? null : text(o["ref"], p("ref"), COLLAB_LIMITS.maxText);
827
+ return { type: "setName", name, ref };
828
+ }
829
+ case "addSheet": {
830
+ const o = obj(input, path, ["type", "id", "name", "rows", "cols"]);
831
+ return {
832
+ type: "addSheet",
833
+ id: id(o["id"], p("id")),
834
+ name: sheetName(o["name"], p("name")),
835
+ rows: ids(o["rows"], p("rows")),
836
+ cols: ids(o["cols"], p("cols"))
837
+ };
838
+ }
839
+ case "removeSheet": {
840
+ const o = obj(input, path, ["type", "id"]);
841
+ return { type: "removeSheet", id: id(o["id"], p("id")) };
842
+ }
843
+ case "renameSheet": {
844
+ const o = obj(input, path, ["type", "id", "name"]);
845
+ return {
846
+ type: "renameSheet",
847
+ id: id(o["id"], p("id")),
848
+ name: sheetName(o["name"], p("name"))
849
+ };
850
+ }
851
+ case "setNote": {
852
+ const o = obj(input, path, ["type", "sheet", "row", "col", "note"]);
853
+ const note = o["note"] === null ? null : text(o["note"], p("note"), COLLAB_LIMITS.maxText);
854
+ return {
855
+ type: "setNote",
856
+ ...cell({ sheet: o["sheet"], row: o["row"], col: o["col"] }, path),
857
+ note
858
+ };
859
+ }
860
+ case "freeze": {
861
+ const o = obj(input, path, ["type", "sheet", "rows", "cols"]);
862
+ return {
863
+ type: "freeze",
864
+ sheet: id(o["sheet"], p("sheet")),
865
+ rows: count(o["rows"], p("rows")),
866
+ cols: count(o["cols"], p("cols"))
867
+ };
868
+ }
869
+ default:
870
+ fail(`${p("type")} is not a known op`);
871
+ }
872
+ }
873
+ function nullable(input, path, read) {
874
+ return input === null ? null : read(input, path);
875
+ }
876
+ function message(input) {
877
+ if (!distribution_default.plainObject(input)) fail("the message must be an object");
878
+ if (input["v"] !== COLLAB_VERSION) fail(`v must be ${COLLAB_VERSION}`);
879
+ switch (input["type"]) {
880
+ case "join": {
881
+ const o = obj(input, "join", ["v", "type", "docId", "clientId", "sinceSeq"], ["name"]);
882
+ const out = {
883
+ v: 1,
884
+ type: "join",
885
+ docId: id(o["docId"], "docId"),
886
+ clientId: id(o["clientId"], "clientId"),
887
+ sinceSeq: nullable(o["sinceSeq"], "sinceSeq", seq)
888
+ };
889
+ if (Object.hasOwn(o, "name")) out.name = short(o["name"], "name");
890
+ return out;
891
+ }
892
+ case "submit": {
893
+ const o = obj(input, "submit", ["v", "type", "docId", "clientId", "opId", "baseSeq", "ops"]);
894
+ if (!distribution_default.array(o["ops"])) fail("ops must be a list");
895
+ if (o["ops"].length > COLLAB_LIMITS.maxOps)
896
+ fail(`ops has more than ${COLLAB_LIMITS.maxOps} items`);
897
+ return {
898
+ v: 1,
899
+ type: "submit",
900
+ docId: id(o["docId"], "docId"),
901
+ clientId: id(o["clientId"], "clientId"),
902
+ opId: id(o["opId"], "opId"),
903
+ baseSeq: seq(o["baseSeq"], "baseSeq"),
904
+ ops: o["ops"].map((x, i) => op(x, `ops[${i}]`))
905
+ };
906
+ }
907
+ case "presence": {
908
+ const o = obj(input, "presence", ["v", "type", "docId", "cursor", "selection", "editing"]);
909
+ return {
910
+ v: 1,
911
+ type: "presence",
912
+ docId: id(o["docId"], "docId"),
913
+ cursor: nullable(o["cursor"], "cursor", cell),
914
+ selection: nullable(o["selection"], "selection", range),
915
+ editing: nullable(o["editing"], "editing", cell)
916
+ };
917
+ }
918
+ default:
919
+ fail("type is not a known message type");
920
+ }
921
+ }
922
+ function parseClientMessage(input) {
923
+ try {
924
+ return { ok: true, message: message(input) };
925
+ } catch (e) {
926
+ if (e instanceof Bad) return { ok: false, error: e.message };
927
+ return { ok: false, error: "the message is not valid" };
928
+ }
929
+ }
930
+ var Axis = class {
931
+ live;
932
+ all;
933
+ dead = /* @__PURE__ */ new Set();
934
+ #known;
935
+ constructor(live, all = live) {
936
+ this.live = [...live];
937
+ this.all = [...all];
938
+ this.#known = new Set(this.all);
939
+ const alive = new Set(live);
940
+ for (const id2 of this.all) if (!alive.has(id2)) this.dead.add(id2);
941
+ }
942
+ has(id2) {
943
+ return this.#known.has(id2) && !this.dead.has(id2);
944
+ }
945
+ known(id2) {
946
+ return this.#known.has(id2);
947
+ }
948
+ /** The first live ID at or after `id` in the full order, or null for the end. */
949
+ nextLive(id2) {
950
+ const all = this.all;
951
+ for (let i = all.indexOf(id2); i < all.length; i++) if (!this.dead.has(all[i])) return all[i];
952
+ return null;
953
+ }
954
+ insert(ids2, before) {
955
+ const at = (list) => before === null ? list.length : list.indexOf(before);
956
+ this.live.splice(at(this.live), 0, ...ids2);
957
+ this.all.splice(at(this.all), 0, ...ids2);
958
+ for (const id2 of ids2) this.#known.add(id2);
959
+ }
960
+ remove(ids2) {
961
+ this.live = this.live.filter((id2) => !ids2.has(id2));
962
+ for (const id2 of ids2) this.dead.add(id2);
963
+ }
964
+ };
965
+ var isEmpty = (cell2) => Object.values(cell2).every((v) => v === void 0);
966
+ var sameArea = (a, b) => a.start.row === b.start.row && a.start.col === b.start.col && a.end.row === b.end.row && a.end.col === b.end.col;
967
+ var DocModel = class {
968
+ sheets = [];
969
+ names = /* @__PURE__ */ new Map();
970
+ #removedSheets = /* @__PURE__ */ new Set();
971
+ constructor(doc, axes = {}) {
972
+ const styles = doc.styles ?? {};
973
+ for (const s of doc.sheets) {
974
+ const sheet = {
975
+ id: s.id,
976
+ name: s.name,
977
+ rows: new Axis(s.rows, axes[s.id]?.rows),
978
+ cols: new Axis(s.cols, axes[s.id]?.cols),
979
+ cells: /* @__PURE__ */ new Map(),
980
+ merges: (s.merges ?? []).map((m) => structuredClone(m)),
981
+ frozen: { rows: s.frozen?.rows ?? 0, cols: s.frozen?.cols ?? 0 }
982
+ };
983
+ for (const { row, col, style: style2, ...rest } of s.cells) {
984
+ const cell2 = { ...rest };
985
+ if (!cell2.formula && cell2.computed === void 0) cell2.computed = cell2.value;
986
+ if (style2 !== void 0 && styles[style2]) cell2.style = styles[style2];
987
+ this.#put(sheet, row, col, cell2);
988
+ }
989
+ this.sheets.push(sheet);
990
+ }
991
+ for (const { name, ref } of doc.names ?? []) this.names.set(name, ref);
992
+ }
993
+ sheet(id2) {
994
+ return this.sheets.find((s) => s.id === id2);
995
+ }
996
+ cell(sheetId, row, col) {
997
+ const sheet = this.sheet(sheetId);
998
+ return sheet && this.#cell(sheet, row, col);
999
+ }
1000
+ #cell(sheet, row, col) {
1001
+ return sheet.cells.get(row)?.get(col);
1002
+ }
1003
+ #put(sheet, row, col, cell2) {
1004
+ let cols = sheet.cells.get(row);
1005
+ if (isEmpty(cell2)) {
1006
+ cols?.delete(col);
1007
+ return;
1008
+ }
1009
+ if (!cols) sheet.cells.set(row, cols = /* @__PURE__ */ new Map());
1010
+ cols.set(col, cell2);
1011
+ }
1012
+ #update(sheet, row, col, change) {
1013
+ this.#put(sheet, row, col, { ...this.#cell(sheet, row, col), ...change });
1014
+ }
1015
+ #ctx(full) {
1016
+ return createRefContext({
1017
+ sheets: this.sheets.map((s) => ({
1018
+ id: s.id,
1019
+ name: s.name,
1020
+ rows: full ? s.rows.all : s.rows.live,
1021
+ cols: full ? s.cols.all : s.cols.live
1022
+ }))
1023
+ });
1024
+ }
1025
+ /** Moves the range ends of a late formula off deleted rows and columns. */
1026
+ #lateFormula(formula, sheetId) {
1027
+ const withDead = this.sheets.filter((s) => s.rows.dead.size || s.cols.dead.size);
1028
+ if (withDead.length === 0) return formula;
1029
+ const ctx = this.#ctx(true);
1030
+ for (const s of withDead) {
1031
+ formula = shrinkDeleted(formula, sheetId, ctx, {
1032
+ sheet: s.id,
1033
+ rows: [...s.rows.dead],
1034
+ cols: [...s.cols.dead]
1035
+ });
1036
+ }
1037
+ return formula;
1038
+ }
1039
+ /** Moves dead range ends inward in the full order; null when no live row or column is left. */
1040
+ #lateArea(sheet, range2) {
1041
+ const out = structuredClone(range2);
1042
+ for (const [key2, axis] of [
1043
+ ["row", sheet.rows],
1044
+ ["col", sheet.cols]
1045
+ ]) {
1046
+ const from = axis.all.indexOf(range2.start[key2]);
1047
+ const to = axis.all.indexOf(range2.end[key2]);
1048
+ if (from < 0 || to < 0) return null;
1049
+ const live = axis.all.slice(from, to + 1).filter((id2) => !axis.dead.has(id2));
1050
+ if (live.length === 0) return null;
1051
+ if (axis.dead.has(range2.start[key2])) out.start[key2] = live[0];
1052
+ if (axis.dead.has(range2.end[key2])) out.end[key2] = live[live.length - 1];
1053
+ }
1054
+ return out;
1055
+ }
1056
+ #nameUsed(name, except) {
1057
+ const n = name.toLowerCase();
1058
+ return this.sheets.some((s) => s.id !== except && s.name.toLowerCase() === n);
1059
+ }
1060
+ /**
1061
+ * The op as the server applies it now, or null when it must drop. This is the only
1062
+ * transform: every op names IDs, so the server checks it against the current state.
1063
+ */
1064
+ normalize(op2) {
1065
+ switch (op2.type) {
1066
+ case "setNote": {
1067
+ const sheet = this.sheet(op2.sheet);
1068
+ return sheet?.rows.has(op2.row) && sheet.cols.has(op2.col) ? op2 : null;
1069
+ }
1070
+ case "freeze":
1071
+ return this.sheet(op2.sheet) ? op2 : null;
1072
+ case "setCell": {
1073
+ const sheet = this.sheet(op2.sheet);
1074
+ if (!sheet?.rows.has(op2.row) || !sheet.cols.has(op2.col)) return null;
1075
+ return op2.formula ? { ...op2, formula: this.#lateFormula(op2.formula, op2.sheet) } : op2;
1076
+ }
1077
+ case "insertRows":
1078
+ case "insertCols": {
1079
+ const sheet = this.sheet(op2.sheet);
1080
+ const axis = op2.type === "insertRows" ? sheet?.rows : sheet?.cols;
1081
+ if (!axis || new Set(op2.ids).size !== op2.ids.length) return null;
1082
+ if (op2.ids.some((id2) => axis.known(id2))) return null;
1083
+ if (op2.before === null) return op2;
1084
+ if (!axis.known(op2.before)) return null;
1085
+ return { ...op2, before: axis.nextLive(op2.before) };
1086
+ }
1087
+ case "deleteRows":
1088
+ case "deleteCols": {
1089
+ const sheet = this.sheet(op2.sheet);
1090
+ const axis = op2.type === "deleteRows" ? sheet?.rows : sheet?.cols;
1091
+ const ids2 = [...new Set(op2.ids)].filter((id2) => axis?.has(id2));
1092
+ if (ids2.length === 0) return null;
1093
+ return ids2.length === op2.ids.length ? op2 : { ...op2, ids: ids2 };
1094
+ }
1095
+ case "setFormat":
1096
+ case "setStyle":
1097
+ case "merge":
1098
+ case "unmerge": {
1099
+ const sheet = this.sheet(op2.range.sheet);
1100
+ const range2 = sheet && this.#lateArea(sheet, op2.range);
1101
+ return range2 ? { ...op2, range: range2 } : null;
1102
+ }
1103
+ case "setName":
1104
+ return op2;
1105
+ case "addSheet": {
1106
+ if (this.sheet(op2.id) || this.#removedSheets.has(op2.id) || this.#nameUsed(op2.name)) {
1107
+ return null;
1108
+ }
1109
+ const unique = (ids2) => new Set(ids2).size === ids2.length;
1110
+ return unique(op2.rows) && unique(op2.cols) ? op2 : null;
1111
+ }
1112
+ case "removeSheet":
1113
+ return this.sheet(op2.id) && this.sheets.length > 1 ? op2 : null;
1114
+ case "renameSheet":
1115
+ return this.sheet(op2.id) && !this.#nameUsed(op2.name, op2.id) ? op2 : null;
1116
+ }
1117
+ }
1118
+ /**
1119
+ * Applies a normalized op, with the same rules as `Workbook.apply`. Give one `read` map to all
1120
+ * ops of a batch: it keeps the computed value of each cell before the batch, the last value the
1121
+ * engine read, and a formula keeps that value until the engine reports a change.
1122
+ */
1123
+ apply(op2, read = /* @__PURE__ */ new Map()) {
1124
+ switch (op2.type) {
1125
+ case "setNote":
1126
+ this.#update(this.sheet(op2.sheet), op2.row, op2.col, { note: op2.note ?? void 0 });
1127
+ return;
1128
+ case "freeze":
1129
+ this.sheet(op2.sheet).frozen = { rows: op2.rows, cols: op2.cols };
1130
+ return;
1131
+ case "setCell": {
1132
+ const sheet = this.sheet(op2.sheet);
1133
+ const at = `${op2.sheet} ${op2.row} ${op2.col}`;
1134
+ if (!read.has(at)) read.set(at, this.#cell(sheet, op2.row, op2.col)?.computed);
1135
+ this.#update(sheet, op2.row, op2.col, {
1136
+ value: op2.formula ? void 0 : op2.value,
1137
+ formula: op2.formula,
1138
+ computed: op2.formula ? read.get(at) : op2.value
1139
+ });
1140
+ return;
1141
+ }
1142
+ case "insertRows":
1143
+ case "insertCols": {
1144
+ const sheet = this.sheet(op2.sheet);
1145
+ (op2.type === "insertRows" ? sheet.rows : sheet.cols).insert(op2.ids, op2.before);
1146
+ return;
1147
+ }
1148
+ case "deleteRows":
1149
+ case "deleteCols":
1150
+ return this.#delete(op2);
1151
+ case "setFormat":
1152
+ case "setStyle": {
1153
+ const sheet = this.sheet(op2.range.sheet);
1154
+ const change = op2.type === "setFormat" ? { format: op2.format ?? void 0 } : { style: op2.style ?? void 0 };
1155
+ for (const [row, col] of this.#cellsOf(sheet, op2.range)) {
1156
+ this.#update(sheet, row, col, change);
1157
+ }
1158
+ return;
1159
+ }
1160
+ case "merge": {
1161
+ const sheet = this.sheet(op2.range.sheet);
1162
+ sheet.merges = [...sheet.merges, { start: op2.range.start, end: op2.range.end }];
1163
+ return;
1164
+ }
1165
+ case "unmerge": {
1166
+ const sheet = this.sheet(op2.range.sheet);
1167
+ sheet.merges = sheet.merges.filter((m) => !sameArea(m, op2.range));
1168
+ return;
1169
+ }
1170
+ case "setName":
1171
+ if (op2.ref === null) this.names.delete(op2.name);
1172
+ else this.names.set(op2.name, op2.ref);
1173
+ return;
1174
+ case "addSheet":
1175
+ this.sheets.push({
1176
+ id: op2.id,
1177
+ name: op2.name,
1178
+ rows: new Axis(op2.rows),
1179
+ cols: new Axis(op2.cols),
1180
+ cells: /* @__PURE__ */ new Map(),
1181
+ merges: [],
1182
+ frozen: { rows: 0, cols: 0 }
1183
+ });
1184
+ return;
1185
+ case "removeSheet":
1186
+ this.sheets = this.sheets.filter((s) => s.id !== op2.id);
1187
+ this.#removedSheets.add(op2.id);
1188
+ return;
1189
+ case "renameSheet":
1190
+ this.sheet(op2.id).name = op2.name;
1191
+ }
1192
+ }
1193
+ *#cellsOf(sheet, area) {
1194
+ const rows = sheet.rows.live;
1195
+ const cols = sheet.cols.live;
1196
+ const r0 = rows.indexOf(area.start.row);
1197
+ const r1 = rows.indexOf(area.end.row);
1198
+ const c0 = cols.indexOf(area.start.col);
1199
+ const c1 = cols.indexOf(area.end.col);
1200
+ if (r0 < 0 || r1 < 0 || c0 < 0 || c1 < 0) return;
1201
+ for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) yield [rows[r], cols[c]];
1202
+ }
1203
+ #delete(op2) {
1204
+ const sheet = this.sheet(op2.sheet);
1205
+ const rows = op2.type === "deleteRows";
1206
+ const deletion = { sheet: op2.sheet, [rows ? "rows" : "cols"]: op2.ids };
1207
+ const ctx = this.#ctx(false);
1208
+ for (const s of this.sheets) {
1209
+ for (const cols of s.cells.values()) {
1210
+ for (const [col, cell2] of cols) {
1211
+ if (!cell2.formula) continue;
1212
+ const formula = shrinkDeleted(cell2.formula, s.id, ctx, deletion);
1213
+ if (formula !== cell2.formula) cols.set(col, { ...cell2, formula });
1214
+ }
1215
+ }
1216
+ }
1217
+ for (const [name, ref] of this.names) {
1218
+ this.names.set(name, shrinkDeleted(ref, op2.sheet, ctx, deletion));
1219
+ }
1220
+ const gone = new Set(op2.ids);
1221
+ const key2 = rows ? "row" : "col";
1222
+ const ids2 = rows ? sheet.rows.live : sheet.cols.live;
1223
+ sheet.merges = sheet.merges.flatMap((area) => {
1224
+ const from = ids2.indexOf(area.start[key2]);
1225
+ const to = ids2.indexOf(area.end[key2]);
1226
+ const keep = ids2.slice(from, to + 1).filter((id2) => !gone.has(id2));
1227
+ if (keep.length === 0) return [];
1228
+ return [
1229
+ {
1230
+ start: { ...area.start, [key2]: keep[0] },
1231
+ end: { ...area.end, [key2]: keep[keep.length - 1] }
1232
+ }
1233
+ ];
1234
+ });
1235
+ if (rows) for (const id2 of gone) sheet.cells.delete(id2);
1236
+ else for (const cols of sheet.cells.values()) for (const id2 of gone) cols.delete(id2);
1237
+ (rows ? sheet.rows : sheet.cols).remove(gone);
1238
+ }
1239
+ /** Sets the computed values that the engine gives. A change for an empty cell is skipped. */
1240
+ take(changes) {
1241
+ for (const { sheet: id2, row, col, value: value2 } of changes) {
1242
+ const sheet = this.sheet(id2);
1243
+ const cell2 = sheet && this.#cell(sheet, row, col);
1244
+ if (sheet && cell2) this.#put(sheet, row, col, { ...cell2, computed: value2 });
1245
+ }
1246
+ }
1247
+ /** The doc for the engine. */
1248
+ sheetDoc() {
1249
+ const doc = this.toDoc();
1250
+ return {
1251
+ sheets: doc.sheets.map(({ id: id2, name, rows, cols, cells }) => ({
1252
+ id: id2,
1253
+ name,
1254
+ rows,
1255
+ cols,
1256
+ cells: cells.flatMap(
1257
+ ({ row, col, value: value2, formula }) => value2 === void 0 && formula === void 0 ? [] : [{ row, col, value: value2, formula }]
1258
+ )
1259
+ })),
1260
+ names: doc.names ?? []
1261
+ };
1262
+ }
1263
+ /** The doc for the clients, with the computed values. Equal styles share one ID. */
1264
+ toDoc() {
1265
+ const styles = {};
1266
+ const styleIds = /* @__PURE__ */ new Map();
1267
+ const styleId = (style2) => {
1268
+ const key2 = JSON.stringify(style2);
1269
+ let sid = styleIds.get(key2);
1270
+ if (!sid) {
1271
+ sid = `st${styleIds.size + 1}`;
1272
+ styleIds.set(key2, sid);
1273
+ styles[sid] = style2;
1274
+ }
1275
+ return sid;
1276
+ };
1277
+ const sheets = this.sheets.map((s) => {
1278
+ const cells = [];
1279
+ for (const [row, cols] of s.cells) {
1280
+ for (const [col, { style: style2, ...rest }] of cols) {
1281
+ const cell2 = { row, col };
1282
+ for (const [k, v] of Object.entries(rest)) {
1283
+ if (v !== void 0) cell2[k] = v;
1284
+ }
1285
+ if (style2) cell2.style = styleId(style2);
1286
+ cells.push(cell2);
1287
+ }
1288
+ }
1289
+ const sheet = {
1290
+ id: s.id,
1291
+ name: s.name,
1292
+ rows: [...s.rows.live],
1293
+ cols: [...s.cols.live],
1294
+ cells,
1295
+ merges: s.merges.map((m) => structuredClone(m))
1296
+ };
1297
+ if (s.frozen.rows || s.frozen.cols) sheet.frozen = { ...s.frozen };
1298
+ return sheet;
1299
+ });
1300
+ const names = [...this.names].map(([name, ref]) => ({ name, ref }));
1301
+ return { sheets, names, styles };
1302
+ }
1303
+ axes() {
1304
+ return Object.fromEntries(
1305
+ this.sheets.map((s) => [s.id, { rows: [...s.rows.all], cols: [...s.cols.all] }])
1306
+ );
1307
+ }
1308
+ };
1309
+
1310
+ // src/collab/server.ts
1311
+ var key = (clientId, opId) => `${clientId} ${opId}`;
1312
+ function createDocServer(options) {
1313
+ const { store, snapshotEvery = 100 } = options;
1314
+ const docs = /* @__PURE__ */ new Map();
1315
+ async function rebuild(docId, upTo) {
1316
+ const snap = await store.snapshot(docId, upTo);
1317
+ if (!snap) return void 0;
1318
+ const model = new DocModel(snap.doc, snap.axes);
1319
+ const entries = await store.entries(docId, snap.seq, upTo);
1320
+ for (const entry of entries) {
1321
+ const read = /* @__PURE__ */ new Map();
1322
+ for (const op2 of entry.ops) model.apply(op2, read);
1323
+ model.take(entry.changes);
1324
+ }
1325
+ return { model, seq: entries.at(-1)?.seq ?? snap.seq, entries };
1326
+ }
1327
+ async function open(docId) {
1328
+ const built = await rebuild(docId);
1329
+ if (!built) return void 0;
1330
+ const engine = await options.engine();
1331
+ await engine.load(built.model.sheetDoc());
1332
+ if (engine.watch) built.model.take(await engine.watch(null));
1333
+ const all = await store.entries(docId, 0);
1334
+ const done = new Map(all.map((e) => [key(e.clientId, e.opId), e.seq]));
1335
+ return {
1336
+ id: docId,
1337
+ seq: built.seq,
1338
+ model: built.model,
1339
+ engine,
1340
+ done,
1341
+ conns: /* @__PURE__ */ new Set(),
1342
+ presence: /* @__PURE__ */ new Map(),
1343
+ queue: Promise.resolve()
1344
+ };
1345
+ }
1346
+ function get(docId) {
1347
+ let doc = docs.get(docId);
1348
+ if (!doc) {
1349
+ doc = open(docId);
1350
+ docs.set(docId, doc);
1351
+ void doc.then((d) => d ?? docs.delete(docId));
1352
+ }
1353
+ return doc;
1354
+ }
1355
+ function serial(doc, fn) {
1356
+ const next = doc.queue.then(fn);
1357
+ doc.queue = next.catch(() => void 0);
1358
+ return next;
1359
+ }
1360
+ async function join(conn, doc, m) {
1361
+ conn.doc = doc;
1362
+ conn.clientId = m.clientId;
1363
+ conn.name = m.name ?? m.clientId;
1364
+ doc.conns.add(conn);
1365
+ const v = 1;
1366
+ const since = m.sinceSeq;
1367
+ const missed = since === null || since > doc.seq ? [] : await store.entries(doc.id, since);
1368
+ if (since === null || missed.length !== doc.seq - since) {
1369
+ conn.send({ v, type: "snapshot", docId: doc.id, seq: doc.seq, doc: doc.model.toDoc() });
1370
+ } else {
1371
+ for (const e of missed) conn.send({ v, type: "ops", docId: doc.id, ...e });
1372
+ }
1373
+ for (const [clientId, p] of doc.presence) {
1374
+ if (clientId !== m.clientId) {
1375
+ conn.send({ v, type: "presence", docId: doc.id, clientId, name: p.name, ...p.state });
1376
+ }
1377
+ }
1378
+ }
1379
+ async function submit(conn, doc, m) {
1380
+ const v = 1;
1381
+ const seen = doc.done.get(key(m.clientId, m.opId));
1382
+ if (seen !== void 0) {
1383
+ conn.send({ v, type: "ack", docId: doc.id, opId: m.opId, seq: seen });
1384
+ return;
1385
+ }
1386
+ const ops = [];
1387
+ const read = /* @__PURE__ */ new Map();
1388
+ for (const op2 of m.ops) {
1389
+ const fit = doc.model.normalize(op2);
1390
+ if (!fit) continue;
1391
+ doc.model.apply(fit, read);
1392
+ ops.push(fit);
1393
+ }
1394
+ if (ops.length === 0) {
1395
+ conn.send({ v, type: "reject", docId: doc.id, opId: m.opId, reason: "conflict" });
1396
+ return;
1397
+ }
1398
+ let changes;
1399
+ try {
1400
+ const engineOps = ops.filter((o) => o.type !== "setNote" && o.type !== "freeze");
1401
+ changes = engineOps.length ? await doc.engine.apply(engineOps) : [];
1402
+ } catch {
1403
+ doc.model = (await rebuild(doc.id)).model;
1404
+ await doc.engine.load(doc.model.sheetDoc());
1405
+ if (doc.engine.watch) doc.model.take(await doc.engine.watch(null));
1406
+ conn.send({ v, type: "reject", docId: doc.id, opId: m.opId, reason: "invalid" });
1407
+ return;
1408
+ }
1409
+ doc.model.take(changes);
1410
+ const entry = { seq: ++doc.seq, clientId: m.clientId, opId: m.opId, ops, changes };
1411
+ doc.done.set(key(m.clientId, m.opId), entry.seq);
1412
+ await store.append(doc.id, entry);
1413
+ for (const c of doc.conns) c.send({ v, type: "ops", docId: doc.id, ...entry });
1414
+ if (entry.seq % snapshotEvery === 0) {
1415
+ await store.saveSnapshot(doc.id, {
1416
+ seq: entry.seq,
1417
+ doc: doc.model.toDoc(),
1418
+ axes: doc.model.axes()
1419
+ });
1420
+ }
1421
+ }
1422
+ function presence(conn, doc, m) {
1423
+ const clientId = conn.clientId;
1424
+ const name = conn.name ?? clientId;
1425
+ const state = { cursor: m.cursor, selection: m.selection, editing: m.editing };
1426
+ doc.presence.set(clientId, { name, state, conn });
1427
+ for (const c of doc.conns) {
1428
+ if (c.clientId !== clientId) {
1429
+ c.send({ v: 1, type: "presence", docId: doc.id, clientId, name, ...state });
1430
+ }
1431
+ }
1432
+ }
1433
+ return {
1434
+ async create(docId, doc) {
1435
+ const model = new DocModel(doc);
1436
+ await store.saveSnapshot(docId, { seq: 0, doc: model.toDoc(), axes: model.axes() });
1437
+ },
1438
+ connect(send) {
1439
+ const conn = { send };
1440
+ const reject = (docId, opId, reason) => send({ v: 1, type: "reject", docId, opId, reason });
1441
+ async function handle(input) {
1442
+ const parsed = parseClientMessage(input);
1443
+ if (!parsed.ok) {
1444
+ const docId = distribution_default.plainObject(input) && distribution_default.string(input["docId"]) ? input["docId"] : "";
1445
+ return reject(docId, null, "bad_message");
1446
+ }
1447
+ const m = parsed.message;
1448
+ const opId = m.type === "submit" ? m.opId : null;
1449
+ try {
1450
+ const doc = await get(m.docId);
1451
+ if (!doc) return reject(m.docId, opId, "unknown_doc");
1452
+ if (m.type === "join") return await serial(doc, () => join(conn, doc, m));
1453
+ const joined = conn.doc === doc;
1454
+ if (!joined || m.type === "submit" && m.clientId !== conn.clientId) {
1455
+ return reject(m.docId, opId, "not_joined");
1456
+ }
1457
+ if (m.type === "submit") return await serial(doc, () => submit(conn, doc, m));
1458
+ return presence(conn, doc, m);
1459
+ } catch {
1460
+ return reject(m.docId, opId, "server_error");
1461
+ }
1462
+ }
1463
+ let chain = Promise.resolve();
1464
+ return {
1465
+ receive(input) {
1466
+ const run = chain.then(() => handle(input));
1467
+ chain = run;
1468
+ return run;
1469
+ },
1470
+ close() {
1471
+ const { doc, clientId } = conn;
1472
+ if (!doc || clientId === void 0) return;
1473
+ doc.conns.delete(conn);
1474
+ conn.doc = void 0;
1475
+ if (doc.presence.get(clientId)?.conn === conn) doc.presence.delete(clientId);
1476
+ for (const c of doc.conns) c.send({ v: 1, type: "leave", docId: doc.id, clientId });
1477
+ }
1478
+ };
1479
+ },
1480
+ async snapshot(docId) {
1481
+ const doc = await get(docId);
1482
+ if (!doc) throw new Error(`Lattice: no doc "${docId}"`);
1483
+ return serial(doc, () => ({ seq: doc.seq, doc: doc.model.toDoc() }));
1484
+ },
1485
+ history: (docId) => store.entries(docId, 0),
1486
+ async docAt(docId, seq2) {
1487
+ const built = await rebuild(docId, seq2);
1488
+ if (!built) throw new Error(`Lattice: no doc "${docId}" at seq ${seq2}`);
1489
+ return built.model.toDoc();
1490
+ }
1491
+ };
1492
+ }
1493
+
1494
+ // src/collab/store.ts
1495
+ function createMemoryStore() {
1496
+ const logs = /* @__PURE__ */ new Map();
1497
+ const snapshots = /* @__PURE__ */ new Map();
1498
+ return {
1499
+ async append(docId, entry) {
1500
+ const log = logs.get(docId) ?? [];
1501
+ log.push(structuredClone(entry));
1502
+ logs.set(docId, log);
1503
+ },
1504
+ async entries(docId, afterSeq, upToSeq = Infinity) {
1505
+ const log = logs.get(docId) ?? [];
1506
+ return structuredClone(log.filter((e) => e.seq > afterSeq && e.seq <= upToSeq));
1507
+ },
1508
+ async saveSnapshot(docId, snapshot) {
1509
+ const list = snapshots.get(docId) ?? [];
1510
+ list.push(structuredClone(snapshot));
1511
+ list.sort((a, b) => a.seq - b.seq);
1512
+ snapshots.set(docId, list);
1513
+ },
1514
+ async snapshot(docId, atOrBefore = Infinity) {
1515
+ const found = (snapshots.get(docId) ?? []).filter((s) => s.seq <= atOrBefore).at(-1);
1516
+ return found && structuredClone(found);
1517
+ }
1518
+ };
1519
+ }
1520
+
1521
+ // src/collab/socket.ts
1522
+ function attachSocket(server, socket, options = {}) {
1523
+ const { maxBytes = 1e6 } = options;
1524
+ const conn = server.connect((message2) => socket.send(JSON.stringify(message2)));
1525
+ const reject = (reason) => socket.send(JSON.stringify({ v: 1, type: "reject", docId: "", opId: null, reason }));
1526
+ socket.on("message", (data) => {
1527
+ const raw = String(data);
1528
+ if (raw.length > maxBytes) return reject("too_large");
1529
+ let input;
1530
+ try {
1531
+ input = JSON.parse(raw);
1532
+ } catch {
1533
+ return reject("bad_message");
1534
+ }
1535
+ void conn.receive(input);
1536
+ });
1537
+ socket.on("close", () => conn.close());
1538
+ }
1539
+
1540
+ export { COLLAB_LIMITS, COLLAB_VERSION, attachSocket, createDocServer, createMemoryStore, isArray, isBoolean, isNull, isNumber, isSafeInteger, isString, parseClientMessage };
1541
+ //# sourceMappingURL=chunk-WHFTIPTN.js.map
1542
+ //# sourceMappingURL=chunk-WHFTIPTN.js.map