duratom 0.0.0-stage → 0.1.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,824 @@
1
+ // src/core/equality.ts
2
+ var shallowEqual = (a, b) => {
3
+ if (Object.is(a, b)) return true;
4
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
5
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
6
+ const ka = Object.keys(a);
7
+ const kb = Object.keys(b);
8
+ return ka.length === kb.length && ka.every((k) => Object.hasOwn(b, k) && Object.is(a[k], b[k]));
9
+ };
10
+ var isPlainObject = (value) => {
11
+ if (value === null || typeof value !== "object") return false;
12
+ const proto = Object.getPrototypeOf(value);
13
+ return proto === Object.prototype || proto === null;
14
+ };
15
+ var deepEqual = (a, b) => {
16
+ if (Object.is(a, b)) return true;
17
+ if (a instanceof Uint8Array && b instanceof Uint8Array)
18
+ return a.length === b.length && a.every((byte, n) => byte === b[n]);
19
+ const arrays = Array.isArray(a) && Array.isArray(b);
20
+ if (!arrays && !(isPlainObject(a) && isPlainObject(b))) return false;
21
+ const ka = Object.keys(a);
22
+ return ka.length === Object.keys(b).length && ka.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
23
+ };
24
+
25
+ // src/core/locator.ts
26
+ import * as Y from "yjs";
27
+ var isMap = (node) => node instanceof Y.Map && !(node instanceof Y.XmlHook);
28
+ var Locator = class _Locator {
29
+ constructor(steps) {
30
+ this.steps = steps;
31
+ }
32
+ steps;
33
+ /** Descend into the Y type stored under `key` of a map. */
34
+ child(key) {
35
+ return new _Locator([...this.steps, { key }]);
36
+ }
37
+ resolve(doc) {
38
+ let node;
39
+ for (const step of this.steps) {
40
+ if ("root" in step)
41
+ node = step.kind === "map" ? doc.getMap(step.root) : doc.getArray(step.root);
42
+ else {
43
+ const next = isMap(node) ? node.get(step.key) : void 0;
44
+ node = next instanceof Y.AbstractType ? next : void 0;
45
+ }
46
+ if (!node) return void 0;
47
+ }
48
+ return node;
49
+ }
50
+ };
51
+ var at = {
52
+ map: (name) => new Locator([{ root: name, kind: "map" }]),
53
+ array: (name) => new Locator([{ root: name, kind: "array" }])
54
+ };
55
+
56
+ // src/core/observe.ts
57
+ import * as Y2 from "yjs";
58
+ function observeLocated(doc, locator, options, onChange) {
59
+ const { deep = false, keys, origin, event: accepted } = options;
60
+ let cleanups = [];
61
+ let node;
62
+ const accepts = (tr) => !origin || origin(tr.origin);
63
+ const touchesKeys = (event) => !keys || !(event instanceof Y2.YMapEvent) || deep && event.target === node || keys.some((k) => event.keysChanged.has(k));
64
+ const counts = (event) => touchesKeys(event) && (!accepted || accepted(event));
65
+ const unbind = () => {
66
+ for (const fn of cleanups) fn();
67
+ cleanups = [];
68
+ };
69
+ const bind = () => {
70
+ unbind();
71
+ let current;
72
+ node = void 0;
73
+ for (const step of locator.steps) {
74
+ if ("root" in step) {
75
+ current = step.kind === "map" ? doc.getMap(step.root) : doc.getArray(step.root);
76
+ continue;
77
+ }
78
+ if (!isMap(current)) return;
79
+ const parent = current;
80
+ const handler = (event, tr) => {
81
+ if (!event.keysChanged.has(step.key)) return;
82
+ bind();
83
+ if (accepts(tr)) onChange();
84
+ };
85
+ parent.observe(handler);
86
+ cleanups.push(() => parent.unobserve(handler));
87
+ const next = parent.get(step.key);
88
+ if (!(next instanceof Y2.AbstractType)) return;
89
+ current = next;
90
+ }
91
+ const target = current;
92
+ if (!target) return;
93
+ node = target;
94
+ if (deep) {
95
+ const handler = (events, tr) => {
96
+ if (accepts(tr) && events.some(counts)) onChange();
97
+ };
98
+ target.observeDeep(handler);
99
+ cleanups.push(() => target.unobserveDeep(handler));
100
+ } else {
101
+ const handler = (event, tr) => {
102
+ if (accepts(tr) && counts(event)) onChange();
103
+ };
104
+ target.observe(handler);
105
+ cleanups.push(() => target.unobserve(handler));
106
+ }
107
+ };
108
+ bind();
109
+ return unbind;
110
+ }
111
+
112
+ // src/core/live.ts
113
+ function live(doc, spec) {
114
+ const equals = spec.equals ?? shallowEqual;
115
+ const locator = spec.locate(at);
116
+ const listeners = /* @__PURE__ */ new Set();
117
+ let current;
118
+ let stop;
119
+ const refresh = () => {
120
+ const next = spec.project(locator.resolve(doc));
121
+ if (current && equals(current.value, next)) return false;
122
+ current = { value: next };
123
+ return true;
124
+ };
125
+ return {
126
+ get() {
127
+ if (!stop) refresh();
128
+ return current.value;
129
+ },
130
+ subscribe(listener) {
131
+ const entry = (value, prev) => listener(value, prev);
132
+ listeners.add(entry);
133
+ if (!stop) {
134
+ try {
135
+ stop = observeLocated(doc, locator, spec, () => {
136
+ const prev = current.value;
137
+ if (!refresh()) return;
138
+ const value = current.value;
139
+ for (const fn of [...listeners]) if (listeners.has(fn)) fn(value, prev);
140
+ });
141
+ refresh();
142
+ } catch (error) {
143
+ listeners.delete(entry);
144
+ stop?.();
145
+ stop = void 0;
146
+ throw error;
147
+ }
148
+ }
149
+ return () => {
150
+ if (!listeners.delete(entry) || listeners.size > 0) return;
151
+ stop?.();
152
+ stop = void 0;
153
+ };
154
+ },
155
+ resolve: () => locator.resolve(doc),
156
+ write: (fn, origin) => doc.transact(() => fn(locator.resolve(doc), doc), origin)
157
+ };
158
+ }
159
+
160
+ // src/core/select.ts
161
+ import * as Y3 from "yjs";
162
+ var selector = (locator, is, project2, options = {}) => ({
163
+ locate: () => locator,
164
+ project: (node) => project2(is(node) ? node : void 0),
165
+ ...options
166
+ });
167
+ var isText = (node) => node instanceof Y3.Text && !(node instanceof Y3.XmlText);
168
+ var asStored = (node) => true;
169
+ var kindOf = (value) => value === null ? "null" : Array.isArray(value) ? "array" : value instanceof Uint8Array ? "bytes" : isPlainObject(value) ? "object" : typeof value === "object" ? "other" : typeof value;
170
+ var sameKind = (value, fallback) => {
171
+ const kind = kindOf(value);
172
+ return kind !== "other" && kind === kindOf(fallback);
173
+ };
174
+ var frozen = (value) => Array.isArray(value) ? Object.freeze(value.map(frozen)) : isPlainObject(value) ? Object.freeze(
175
+ Object.fromEntries(Object.entries(value).map(([k, v]) => [k, frozen(v)]))
176
+ ) : value;
177
+ var orFallback = (value, fallback) => fallback === void 0 || sameKind(value, fallback) ? value : fallback instanceof Uint8Array ? fallback.slice() : fallback;
178
+ var observing = ({
179
+ equals = deepEqual,
180
+ keys,
181
+ deep = keys === void 0,
182
+ event
183
+ }) => ({ equals, deep, keys, event });
184
+ var Path = class {
185
+ constructor(locator) {
186
+ this.locator = locator;
187
+ }
188
+ locator;
189
+ selector(project2, options) {
190
+ return selector(this.locator, (node) => this.is(node), project2, options);
191
+ }
192
+ /** `toJSON()` of the node and everything under it, `empty` when missing. Observes deeply; compared deeply. */
193
+ json(empty) {
194
+ return this.selector((node) => node ? node.toJSON() : empty, observing({}));
195
+ }
196
+ project(projection, options = {}) {
197
+ if (typeof projection === "function") return this.selector(projection, observing(options));
198
+ return selector(this.locator, asStored, projection.project, observing(projection));
199
+ }
200
+ };
201
+ var MapPath = class _MapPath extends Path {
202
+ is(node) {
203
+ return isMap(node);
204
+ }
205
+ child(key, kind = "map") {
206
+ return kind === "array" ? new ArrayPath(this.locator.child(key)) : new _MapPath(this.locator.child(key));
207
+ }
208
+ get(key, fallback) {
209
+ const safe = frozen(fallback);
210
+ return this.selector((node) => orFallback(node?.get(key), safe), {
211
+ keys: [key]
212
+ });
213
+ }
214
+ /**
215
+ * An object with each key of `defaults`, read as `get(key, defaults[key])`
216
+ * reads it. Observes only those keys; compared shallowly.
217
+ */
218
+ pick(defaults) {
219
+ const safe = frozen(defaults);
220
+ const keys = Object.keys(safe);
221
+ return this.selector(
222
+ (node) => {
223
+ const out = {};
224
+ for (const k of keys) out[k] = orFallback(node?.get(k), safe[k]);
225
+ return out;
226
+ },
227
+ { keys }
228
+ );
229
+ }
230
+ /**
231
+ * The string of the `Y.Text` under `key`, `''` when it is missing or not a
232
+ * `Y.Text` (a `Y.XmlText` included). Follows edits to the text.
233
+ */
234
+ text(key) {
235
+ return selector(
236
+ this.locator.child(key),
237
+ isText,
238
+ (node) => node ? node.toString() : ""
239
+ );
240
+ }
241
+ /**
242
+ * The map's keys, sorted so every peer sees the same order. `[]` when the
243
+ * map is missing. Only a key added or deleted counts, not a value replaced.
244
+ * Its own `event` filter does that, so a spec that adds an `event` filter
245
+ * calls it from its own: `{ ...ids, event: (e) => ids.event!(e) && mine(e) }`.
246
+ */
247
+ keys() {
248
+ return this.selector((node) => node ? [...node.keys()].sort() : [], {
249
+ event: (event) => [...event.changes.keys.values()].some((c) => c.action !== "update")
250
+ });
251
+ }
252
+ /** `toJSON()` of the map and everything under it, `{}` when missing. Observes deeply; compared deeply. */
253
+ toJSON() {
254
+ return this.json({});
255
+ }
256
+ };
257
+ var ArrayPath = class extends Path {
258
+ is(node) {
259
+ return node instanceof Y3.Array;
260
+ }
261
+ /** The items as stored, `[]` when the array is missing. Compared shallowly. */
262
+ toArray() {
263
+ return this.selector((node) => node ? node.toArray() : []);
264
+ }
265
+ /** The number of items, 0 when the array is missing. */
266
+ length() {
267
+ return this.selector((node) => node?.length ?? 0);
268
+ }
269
+ /** `toJSON()` of the array and everything under it, `[]` when missing. Observes deeply; compared deeply. */
270
+ toJSON() {
271
+ return this.json([]);
272
+ }
273
+ };
274
+ var select = {
275
+ map: (name) => new MapPath(at.map(name)),
276
+ array: (name) => new ArrayPath(at.array(name))
277
+ };
278
+
279
+ // src/schema/read.ts
280
+ import * as Y6 from "yjs";
281
+
282
+ // src/schema/copy.ts
283
+ import * as Y4 from "yjs";
284
+ var setField = (target, key, value) => Object.defineProperty(target, key, {
285
+ value,
286
+ enumerable: true,
287
+ writable: true,
288
+ configurable: true
289
+ });
290
+ var pathOf = (at2) => {
291
+ const keys = [];
292
+ for (let link = at2; link; link = link.parent) keys.push(link.key);
293
+ return keys.reverse();
294
+ };
295
+ var isShared = (value) => value instanceof Y4.AbstractType || value instanceof Y4.Doc;
296
+ function copy(stored, report2) {
297
+ if (!isContainer(stored)) return stored;
298
+ if (stored instanceof Uint8Array) return new Uint8Array(stored);
299
+ const onPath = /* @__PURE__ */ new Map();
300
+ const root = {};
301
+ const steps = [
302
+ {
303
+ value: stored,
304
+ target: root,
305
+ key: "value",
306
+ pathKey: report2?.at.key ?? "value",
307
+ parent: report2?.at.parent
308
+ }
309
+ ];
310
+ for (let step = steps.pop(); step; step = steps.pop()) {
311
+ if ("leave" in step) {
312
+ onPath.delete(step.leave);
313
+ continue;
314
+ }
315
+ const { value, target, key, pathKey, parent } = step;
316
+ if (report2 && isShared(value)) report2.onShared(value, { key: pathKey, parent });
317
+ else if (!isContainer(value)) setField(target, key, value);
318
+ else if (onPath.has(value)) setField(target, key, onPath.get(value));
319
+ else if (value instanceof Uint8Array) setField(target, key, new Uint8Array(value));
320
+ else {
321
+ const here = report2 && { key: pathKey, parent };
322
+ const children = [];
323
+ let copied;
324
+ if (Array.isArray(value)) {
325
+ copied = new Array(value.length);
326
+ for (let n = 0; n < value.length; n++)
327
+ children.push({
328
+ value: value[n],
329
+ target: copied,
330
+ key: String(n),
331
+ pathKey: n,
332
+ parent: here
333
+ });
334
+ } else {
335
+ copied = {};
336
+ for (const [field, item] of Object.entries(value))
337
+ children.push({
338
+ value: item,
339
+ target: copied,
340
+ key: field,
341
+ pathKey: field,
342
+ parent: here
343
+ });
344
+ }
345
+ setField(target, key, copied);
346
+ onPath.set(value, copied);
347
+ steps.push({ leave: value });
348
+ for (let n = children.length - 1; n >= 0; n--) steps.push(children[n]);
349
+ }
350
+ }
351
+ return root.value;
352
+ }
353
+ var isContainer = (value) => value !== null && typeof value === "object" && !isShared(value);
354
+
355
+ // src/schema/equal.ts
356
+ function deepEqual2(a, b) {
357
+ const pairs = [[a, b]];
358
+ const seen = /* @__PURE__ */ new Map();
359
+ for (let pair = pairs.pop(); pair; pair = pairs.pop()) {
360
+ const [x, y] = pair;
361
+ if (Object.is(x, y)) continue;
362
+ if (x !== null && typeof x === "object" && y !== null && typeof y === "object") {
363
+ const partners = seen.get(x) ?? seen.set(x, /* @__PURE__ */ new Set()).get(x);
364
+ if (partners.has(y)) continue;
365
+ partners.add(y);
366
+ }
367
+ if (x instanceof Uint8Array && y instanceof Uint8Array) {
368
+ if (x.length !== y.length || x.some((byte, n) => byte !== y[n])) return false;
369
+ continue;
370
+ }
371
+ if (Array.isArray(x) && Array.isArray(y)) {
372
+ if (x.length !== y.length) return false;
373
+ for (let n = 0; n < x.length; n++) pairs.push([x[n], y[n]]);
374
+ continue;
375
+ }
376
+ if (!isPlainObject2(x) || !isPlainObject2(y)) return false;
377
+ const keys = Object.keys(x);
378
+ if (keys.length !== Object.keys(y).length) return false;
379
+ for (const key of keys) {
380
+ if (!Object.hasOwn(y, key)) return false;
381
+ pairs.push([x[key], y[key]]);
382
+ }
383
+ }
384
+ return true;
385
+ }
386
+ var isPlainObject2 = (value) => {
387
+ if (value === null || typeof value !== "object") return false;
388
+ const proto = Object.getPrototypeOf(value);
389
+ return proto === Object.prototype || proto === null;
390
+ };
391
+
392
+ // src/schema/shape.ts
393
+ import * as Y5 from "yjs";
394
+ var map = (shape) => Object.freeze({ kind: "map", shape });
395
+ var record = (itemShape) => Object.freeze({ kind: "record", shape: itemShape });
396
+ var arrayKind = Object.freeze({ kind: "array" });
397
+ var array = () => arrayKind;
398
+ var isText2 = (stored) => stored instanceof Y5.Text && !(stored instanceof Y5.XmlText);
399
+ var isMap2 = (value) => value instanceof Y5.Map && !(value instanceof Y5.XmlHook);
400
+ var isXml = (value) => value instanceof Y5.XmlFragment && !(value instanceof Y5.XmlElement);
401
+ function kindOf2(declared) {
402
+ if (declared === "text" || declared === "xml") return declared;
403
+ if (declared === null || typeof declared !== "object") return void 0;
404
+ const { kind, shape } = declared;
405
+ if (kind === "array") return declared;
406
+ if ((kind === "map" || kind === "record") && shape !== null && typeof shape === "object")
407
+ return declared;
408
+ return void 0;
409
+ }
410
+
411
+ // src/schema/errors.ts
412
+ var AsyncValidationUnsupportedError = class extends Error {
413
+ vendor;
414
+ constructor(vendor) {
415
+ super(
416
+ `The ${vendor} schema validated asynchronously, which duratom doesn't support. Use a schema with no async refinements or transforms.`
417
+ );
418
+ this.name = "AsyncValidationUnsupportedError";
419
+ this.vendor = vendor;
420
+ }
421
+ };
422
+ var UnsupportedValueError = class extends Error {
423
+ /** Where the value sits in the written value, starting at the field's key. */
424
+ path;
425
+ constructor(path) {
426
+ super(
427
+ `A Y.Map can't store the value written at ${path.map(String).join(".")} as written, so nothing was written. Use a schema that accepts only JSON values and bytes.`
428
+ );
429
+ this.name = "UnsupportedValueError";
430
+ this.path = path;
431
+ }
432
+ };
433
+
434
+ // src/schema/validate.ts
435
+ function validate(schema, value) {
436
+ const result = schema["~standard"].validate(value);
437
+ if (isThenable(result)) {
438
+ Promise.resolve(result).catch(() => {
439
+ });
440
+ throw new AsyncValidationUnsupportedError(schema["~standard"].vendor);
441
+ }
442
+ return result;
443
+ }
444
+ var isThenable = (value) => typeof value?.then === "function";
445
+
446
+ // src/schema/read.ts
447
+ function read(schema, shape, node) {
448
+ if (node === void 0) return void 0;
449
+ if (!isMap2(node)) return { issues: [mismatch(void 0, yMap, node)] };
450
+ if (!node.doc) throw new TypeError("read needs a Y.Map that is in a Y.Doc.");
451
+ const { value, issues } = project(shape, node);
452
+ if (issues.length > 0) return { issues };
453
+ return validate(schema, value);
454
+ }
455
+ function reader(schema, shape) {
456
+ return {
457
+ project: (node) => read(schema, shape, node),
458
+ deep: true,
459
+ event: (event) => !insideXml(shape, event.path),
460
+ equals: deepEqual2
461
+ };
462
+ }
463
+ function insideXml(shape, path) {
464
+ let current = shape;
465
+ for (let n = 0; n < path.length; n++) {
466
+ const key = path[n];
467
+ if (typeof key !== "string" || !Object.hasOwn(current, key)) return false;
468
+ const kind = kindOf2(current[key]);
469
+ if (kind === "xml") return true;
470
+ if (kind === void 0 || kind === "text" || kind.kind === "array") return false;
471
+ if (kind.kind === "record") n++;
472
+ current = kind.shape;
473
+ }
474
+ return false;
475
+ }
476
+ var maxIssues = 100;
477
+ var TooManyIssues = class extends Error {
478
+ };
479
+ var tooManyIssues = new TooManyIssues();
480
+ function report(issues, issue) {
481
+ if (issues.length < maxIssues) return void issues.push(issue);
482
+ issues.push({
483
+ message: `Shape mismatch: more than ${maxIssues} mismatches, the rest left out`
484
+ });
485
+ throw tooManyIssues;
486
+ }
487
+ var mismatch = (at2, expected, found) => ({
488
+ message: `Shape mismatch: expected ${expected}, found ${describeFound(found)}`,
489
+ path: pathOf(at2)
490
+ });
491
+ var plain = "a plain value";
492
+ var yText = "a Y.Text";
493
+ var yMap = "a Y.Map";
494
+ var yArray = "a Y.Array";
495
+ var yXmlFragment = "a Y.XmlFragment";
496
+ function describeFound(value) {
497
+ if (value instanceof Y6.Doc) return "a Y.Doc";
498
+ if (value instanceof Y6.XmlElement) return "a Y.XmlElement";
499
+ if (value instanceof Y6.XmlFragment) return yXmlFragment;
500
+ if (value instanceof Y6.XmlText) return "a Y.XmlText";
501
+ if (value instanceof Y6.XmlHook) return "a Y.XmlHook";
502
+ if (value instanceof Y6.Text) return yText;
503
+ if (value instanceof Y6.Map) return yMap;
504
+ if (value instanceof Y6.Array) return yArray;
505
+ if (value instanceof Y6.AbstractType) return "a shared type";
506
+ if (value === null) return "null";
507
+ if (Array.isArray(value)) return "an array";
508
+ if (value instanceof Uint8Array) return "bytes";
509
+ if (typeof value === "object") return "an object";
510
+ if (value === void 0) return "undefined";
511
+ return `a ${typeof value}`;
512
+ }
513
+ function project(shape, node) {
514
+ const root = {};
515
+ const issues = [];
516
+ const onShared = (found, at2) => report(issues, mismatch(at2, plain, found));
517
+ const reportAt = (at2) => ({ at: at2, onShared });
518
+ const steps = [{ shape, node, value: root, at: void 0, missing: [] }];
519
+ const later = (step, target, key) => {
520
+ const value = {};
521
+ setField(target, key, value);
522
+ steps.push({ ...step, value });
523
+ };
524
+ try {
525
+ for (let step = steps.pop(); step; step = steps.pop()) {
526
+ const { shape: shape2, node: node2, value, at: at2, missing } = step;
527
+ if (node2)
528
+ for (const [key, stored] of node2.entries()) {
529
+ const kind = Object.hasOwn(shape2, key) ? kindOf2(shape2[key]) : void 0;
530
+ const here = { key, parent: at2 };
531
+ if (kind === void 0) {
532
+ if (isShared(stored)) report(issues, mismatch(here, plain, stored));
533
+ else setField(value, key, copy(stored, reportAt(here)));
534
+ } else if (kind === "text") {
535
+ if (isText2(stored)) setField(value, key, stored.toString());
536
+ else report(issues, mismatch(here, yText, stored));
537
+ } else if (kind === "xml") {
538
+ if (isXml(stored)) setField(value, key, stored);
539
+ else report(issues, mismatch(here, yXmlFragment, stored));
540
+ } else if (kind.kind === "array") {
541
+ if (stored instanceof Y6.Array)
542
+ setField(value, key, copy(stored.toArray(), reportAt(here)));
543
+ else report(issues, mismatch(here, yArray, stored));
544
+ } else if (!isMap2(stored)) report(issues, mismatch(here, yMap, stored));
545
+ else if (kind.kind === "map")
546
+ later({ shape: kind.shape, node: stored, at: here, missing: [] }, value, key);
547
+ else {
548
+ const items = {};
549
+ setField(value, key, items);
550
+ for (const [id, item] of stored.entries()) {
551
+ const itemAt = { key: id, parent: here };
552
+ if (isMap2(item))
553
+ later({ shape: kind.shape, node: item, at: itemAt, missing: [] }, items, id);
554
+ else report(issues, mismatch(itemAt, yMap, item));
555
+ }
556
+ }
557
+ }
558
+ for (const [key, declared] of Object.entries(shape2)) {
559
+ const kind = kindOf2(declared);
560
+ if (kind === void 0 || kind === "xml" || node2?.has(key)) continue;
561
+ if (kind === "text") setField(value, key, "");
562
+ else if (kind.kind === "array") setField(value, key, []);
563
+ else if (kind.kind === "record" || missing.includes(kind.shape)) setField(value, key, {});
564
+ else
565
+ later(
566
+ {
567
+ shape: kind.shape,
568
+ node: void 0,
569
+ at: { key, parent: at2 },
570
+ missing: [...missing, kind.shape]
571
+ },
572
+ value,
573
+ key
574
+ );
575
+ }
576
+ }
577
+ } catch (error) {
578
+ if (error !== tooManyIssues) throw error;
579
+ }
580
+ return { value: root, issues };
581
+ }
582
+
583
+ // src/schema/write.ts
584
+ import * as Y7 from "yjs";
585
+ function write(schema, shape, node, value) {
586
+ if (!isMap2(node))
587
+ throw new TypeError(
588
+ node instanceof Y7.AbstractType ? "write needs a Y.Map, not another shared type (a Y.XmlHook is one); write its parent to repair it." : "write needs a located Y.Map; write its parent to create a missing one."
589
+ );
590
+ const doc = node.doc;
591
+ if (!doc) throw new TypeError("write needs a Y.Map that is in a Y.Doc.");
592
+ return apply(schema, shape, doc, new Target(node), value);
593
+ }
594
+ function create(schema, shape, parent, key, value) {
595
+ if (!isMap2(parent)) throw new TypeError("create needs a Y.Map to create the node in.");
596
+ const doc = parent.doc;
597
+ if (!doc) throw new TypeError("create needs a Y.Map that is in a Y.Doc.");
598
+ const root = new Target(void 0, new Target(parent), key);
599
+ return apply(schema, shape, doc, root, value);
600
+ }
601
+ function apply(schema, shape, doc, root, value) {
602
+ const result = validate(schema, value);
603
+ if (result.issues) return result;
604
+ if (!isPlainObject2(value))
605
+ throw new TypeError("write needs a field object as its value, since a Y.Map holds fields.");
606
+ const changes = plan(shape, root, value);
607
+ doc.transact(() => {
608
+ root.ensure();
609
+ for (const change of changes) change();
610
+ });
611
+ return result;
612
+ }
613
+ var Target = class {
614
+ constructor(stored, parent, key) {
615
+ this.stored = stored;
616
+ this.parent = parent;
617
+ this.key = key;
618
+ this.#map = stored;
619
+ }
620
+ stored;
621
+ parent;
622
+ key;
623
+ #map;
624
+ /** The `Y.Map`, created along with any missing parents, replacing whatever was stored there. */
625
+ ensure() {
626
+ const missing = [];
627
+ for (let target = this; !target.#map; target = target.parent) missing.push(target);
628
+ for (let n = missing.length - 1; n >= 0; n--) {
629
+ const target = missing[n];
630
+ target.#map = new Y7.Map();
631
+ target.parent.#map.set(target.key, target.#map);
632
+ }
633
+ return this.#map;
634
+ }
635
+ /** The `Y.Map` if it's stored or has been created, without creating it. */
636
+ get map() {
637
+ return this.#map;
638
+ }
639
+ };
640
+ function plan(shape, root, value) {
641
+ const changes = [];
642
+ const fragments = [];
643
+ const steps = [{ shape, target: root, value, at: void 0 }];
644
+ for (let step = steps.pop(); step; step = steps.pop()) {
645
+ const { shape: shape2, target, value: value2, at: at2 } = step;
646
+ const { stored } = target;
647
+ const kindAt = (key) => Object.hasOwn(shape2, key) ? kindOf2(shape2[key]) : void 0;
648
+ const absent = stored ? [...stored.keys()].filter((key) => !Object.hasOwn(value2, key) && kindAt(key) !== "xml") : [];
649
+ if (absent.length > 0) changes.push(() => absent.forEach((key) => stored.delete(key)));
650
+ for (const key of Object.keys(shape2))
651
+ if (kindAt(key) === "xml" && !isXml(stored?.get(key))) fragments.push([target, key]);
652
+ for (const [key, field] of Object.entries(value2)) {
653
+ const kind = kindAt(key);
654
+ const here = { key, parent: at2 };
655
+ const has = stored?.has(key) ?? false;
656
+ const current = stored?.get(key);
657
+ if (kind === void 0) {
658
+ if (has && deepEqual2(current, field)) continue;
659
+ if (field === void 0 && !stored) continue;
660
+ assertStorable(field, here);
661
+ changes.push(() => target.ensure().set(key, copy(field)));
662
+ } else if (kind === "xml") {
663
+ continue;
664
+ } else if (field === void 0 || field === null) {
665
+ if (has) changes.push(() => stored.delete(key));
666
+ } else if (kind === "text") {
667
+ if (typeof field !== "string") throw notStorable(here, "a string, null or undefined");
668
+ if (isText2(current)) changes.push(() => splice(current, field));
669
+ else if (field !== "" || has)
670
+ changes.push(() => target.ensure().set(key, new Y7.Text(field)));
671
+ } else if (kind.kind === "array") {
672
+ if (!Array.isArray(field)) throw notStorable(here, "an array, null or undefined");
673
+ const items = Array.from(field);
674
+ const array2 = current instanceof Y7.Array ? current : void 0;
675
+ const { start, removed, inserted } = diff(array2?.toArray() ?? [], items);
676
+ inserted.forEach((item, n) => {
677
+ const itemAt = { key: start + n, parent: here };
678
+ if (item === void 0) throw new UnsupportedValueError(pathOf(itemAt));
679
+ assertStorable(item, itemAt);
680
+ });
681
+ if (array2) {
682
+ if (removed > 0 || inserted.length > 0)
683
+ changes.push(() => {
684
+ if (removed > 0) array2.delete(start, removed);
685
+ if (inserted.length > 0) array2.insert(start, inserted.map(copyItem));
686
+ });
687
+ } else if (items.length > 0 || has)
688
+ changes.push(() => {
689
+ const created = new Y7.Array();
690
+ target.ensure().set(key, created);
691
+ created.insert(0, items.map(copyItem));
692
+ });
693
+ } else {
694
+ if (!isPlainObject2(field)) throw notStorable(here, "an object, null or undefined");
695
+ const child = new Target(isMap2(current) ? current : void 0, target, key);
696
+ if (has && !child.stored) changes.push(() => child.ensure());
697
+ if (kind.kind === "map") {
698
+ steps.push({ shape: kind.shape, target: child, value: field, at: here });
699
+ continue;
700
+ }
701
+ const items = child.stored;
702
+ const gone = items ? [...items.keys()].filter((id) => !Object.hasOwn(field, id)) : [];
703
+ if (gone.length > 0) changes.push(() => gone.forEach((id) => items.delete(id)));
704
+ for (const [id, item] of Object.entries(field)) {
705
+ const itemAt = { key: id, parent: here };
706
+ if (item === void 0 || item === null) {
707
+ if (items?.has(id)) changes.push(() => items.delete(id));
708
+ continue;
709
+ }
710
+ if (!isPlainObject2(item)) throw notStorable(itemAt, "an object");
711
+ const storedItem = items?.get(id);
712
+ const itemTarget = new Target(isMap2(storedItem) ? storedItem : void 0, child, id);
713
+ if (!itemTarget.stored) changes.push(() => itemTarget.ensure());
714
+ steps.push({ shape: kind.shape, target: itemTarget, value: item, at: itemAt });
715
+ }
716
+ }
717
+ }
718
+ }
719
+ changes.push(() => {
720
+ for (const [target, key] of fragments)
721
+ if (target.map && !isXml(target.map.get(key))) target.map.set(key, new Y7.XmlFragment());
722
+ });
723
+ return changes;
724
+ }
725
+ var copyItem = (item) => copy(item);
726
+ var notStorable = (at2, expected) => new TypeError(
727
+ `write can't store ${JSON.stringify(pathOf(at2))} as the shape declares it: only ${expected}.`
728
+ );
729
+ function diff(current, next) {
730
+ const end = Math.min(current.length, next.length);
731
+ let start = 0;
732
+ while (start < end && deepEqual2(current[start], next[start])) start++;
733
+ let suffix = 0;
734
+ while (suffix < end - start && deepEqual2(current[current.length - 1 - suffix], next[next.length - 1 - suffix]))
735
+ suffix++;
736
+ return {
737
+ start,
738
+ removed: current.length - start - suffix,
739
+ inserted: next.slice(start, next.length - suffix)
740
+ };
741
+ }
742
+ function assertStorable(field, root) {
743
+ const fail = (at2) => {
744
+ throw new UnsupportedValueError(pathOf(at2));
745
+ };
746
+ const onPath = /* @__PURE__ */ new Set();
747
+ const steps = [{ value: field, at: root }];
748
+ for (let step = steps.pop(); step; step = steps.pop()) {
749
+ if ("leave" in step) {
750
+ onPath.delete(step.leave);
751
+ continue;
752
+ }
753
+ const { value, at: at2 } = step;
754
+ if (value === null || value === void 0) continue;
755
+ if (["string", "number", "boolean"].includes(typeof value)) continue;
756
+ if (value instanceof Uint8Array) continue;
757
+ if (typeof value !== "object" || onPath.has(value)) fail(at2);
758
+ const items = Array.isArray(value) ? (
759
+ // Array.from reads a hole as undefined, as Yjs stores it.
760
+ Array.from(value, (item, n) => [n, item])
761
+ ) : isPlainObject2(value) ? Object.entries(value) : fail(at2);
762
+ onPath.add(value);
763
+ steps.push({ leave: value });
764
+ for (const [key, item] of items) {
765
+ const child = { key, parent: at2 };
766
+ if (key === "__proto__" || key === "constructor" && at2 === root) fail(child);
767
+ steps.push({ value: item, at: child });
768
+ }
769
+ }
770
+ }
771
+ function splice(text, next) {
772
+ const current = text.toString();
773
+ const end = Math.min(current.length, next.length);
774
+ let start = 0;
775
+ while (start < end && current[start] === next[start]) start++;
776
+ if (start > 0 && isHighSurrogate(current.charCodeAt(start - 1))) start--;
777
+ let suffix = 0;
778
+ while (suffix < end - start && current[current.length - 1 - suffix] === next[next.length - 1 - suffix])
779
+ suffix++;
780
+ if (suffix > 0 && isLowSurrogate(current.charCodeAt(current.length - suffix))) suffix--;
781
+ const removed = current.length - start - suffix;
782
+ const inserted = next.slice(start, next.length - suffix);
783
+ if (removed === 0 && !inserted) return;
784
+ const offsets = text.length === current.length ? void 0 : offsetsOf(text);
785
+ const at2 = (index) => offsets?.[index] ?? index;
786
+ const from = at2(start);
787
+ if (removed > 0) text.delete(from, at2(start + removed - 1) + 1 - from);
788
+ if (inserted) text.insert(from, inserted);
789
+ }
790
+ function offsetsOf(text) {
791
+ const offsets = [];
792
+ let offset = 0;
793
+ for (const { insert } of text.toDelta()) {
794
+ if (typeof insert === "string") for (let n = 0; n < insert.length; n++) offsets.push(offset++);
795
+ else offset++;
796
+ }
797
+ offsets.push(text.length);
798
+ return offsets;
799
+ }
800
+ var isHighSurrogate = (code) => code >= 55296 && code <= 56319;
801
+ var isLowSurrogate = (code) => code >= 56320 && code <= 57343;
802
+
803
+ export {
804
+ map,
805
+ record,
806
+ array,
807
+ isMap2 as isMap,
808
+ AsyncValidationUnsupportedError,
809
+ UnsupportedValueError,
810
+ validate,
811
+ read,
812
+ reader,
813
+ write,
814
+ create,
815
+ shallowEqual,
816
+ deepEqual,
817
+ Locator,
818
+ at,
819
+ observeLocated,
820
+ live,
821
+ MapPath,
822
+ ArrayPath,
823
+ select
824
+ };