js-bao 0.5.2 → 0.6.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.
@@ -464,15 +464,324 @@ var init_uniqueIndex = __esm({
464
464
  }
465
465
  });
466
466
 
467
+ // src/utils/largeDocuments.ts
468
+ var Y5;
469
+ var init_largeDocuments = __esm({
470
+ "src/utils/largeDocuments.ts"() {
471
+ "use strict";
472
+ Y5 = __toESM(require("yjs"), 1);
473
+ init_yjsValues();
474
+ }
475
+ });
476
+
477
+ // src/models/OrmContext.ts
478
+ var OrmContext, defaultOrmContext, liveOrmContexts;
479
+ var init_OrmContext = __esm({
480
+ "src/models/OrmContext.ts"() {
481
+ "use strict";
482
+ OrmContext = class _OrmContext {
483
+ /** Declared before the field that reads it: static initialization is ordered. */
484
+ static instanceCounter = 0;
485
+ /**
486
+ * Which instance this is, for diagnostics. A process holding several clients
487
+ * needs a way to say WHICH one a warning is about, so every context takes the
488
+ * next number as it is created and keeps it for its lifetime.
489
+ */
490
+ instanceId = ++_OrmContext.instanceCounter;
491
+ /** The engine this instance's models read and write through. */
492
+ dbEngine = null;
493
+ connectedDocuments = /* @__PURE__ */ new Map();
494
+ /** `docId_modelName` → the Y.Map that document holds for that model. */
495
+ documentYMaps = /* @__PURE__ */ new Map();
496
+ /** `subscribe()` callbacks, by model name. */
497
+ listenersMap = /* @__PURE__ */ new Map();
498
+ // Default-document resolution
499
+ modelNameToDefaultDocId = /* @__PURE__ */ new Map();
500
+ globalDefaultDocId = void 0;
501
+ defaultDocChangedListeners = /* @__PURE__ */ new Set();
502
+ modelDocMappingChangedListeners = /* @__PURE__ */ new Set();
503
+ /** Format-2 ("large document", #2816) record stores by document id. */
504
+ format2Documents = /* @__PURE__ */ new Map();
505
+ /** Format-2 epoch moves in flight (#2816). */
506
+ format2Transitions = /* @__PURE__ */ new Map();
507
+ /**
508
+ * Nested-Y.Map stringset fields this context has already observed. Per
509
+ * context, not global: a Y.Doc reconnected to a fresh instance has to be
510
+ * observed again by that instance, and a global guard would silently
511
+ * suppress it.
512
+ */
513
+ observedStringSetMaps = /* @__PURE__ */ new WeakSet();
514
+ /**
515
+ * The registry this instance's schema lookups use. `null` on the standing
516
+ * default context, where callers fall back to the global singleton.
517
+ */
518
+ modelRegistry = null;
519
+ /** Model classes routed to this context. */
520
+ boundModels = /* @__PURE__ */ new Set();
521
+ /** True once {@link destroy} has run; bound classes keep pointing here. */
522
+ destroyed = false;
523
+ /** Yjs `unobserve` thunks by owning document id. */
524
+ observerDisposers = /* @__PURE__ */ new Map();
525
+ /** Teardown the owner (the document manager) registers for `destroy()`. */
526
+ teardownHooks = /* @__PURE__ */ new Set();
527
+ static NO_DOCUMENT_KEY = "__no_document__";
528
+ /**
529
+ * Record how to remove an observer this context installed. Every `observe()`
530
+ * in the ORM pairs with one of these: without it a torn-down instance's
531
+ * callbacks keep firing on a Y.Doc that outlives it.
532
+ */
533
+ registerObserverDisposer(docId, dispose) {
534
+ const key = docId ?? _OrmContext.NO_DOCUMENT_KEY;
535
+ const list = this.observerDisposers.get(key);
536
+ if (list) list.push(dispose);
537
+ else this.observerDisposers.set(key, [dispose]);
538
+ }
539
+ /** Remove every observer this context installed for `docId`. */
540
+ disposeObserversForDocument(docId) {
541
+ const list = this.observerDisposers.get(docId);
542
+ if (!list) return;
543
+ this.observerDisposers.delete(docId);
544
+ for (const dispose of list) {
545
+ try {
546
+ dispose();
547
+ } catch {
548
+ }
549
+ }
550
+ }
551
+ disposeAllObservers() {
552
+ const buckets = Array.from(this.observerDisposers.values());
553
+ this.observerDisposers.clear();
554
+ for (const list of buckets) {
555
+ for (const dispose of list) {
556
+ try {
557
+ dispose();
558
+ } catch {
559
+ }
560
+ }
561
+ }
562
+ }
563
+ /** Run `hook` as part of `destroy()` (the format-2 binding registers here). */
564
+ onDestroy(hook) {
565
+ this.teardownHooks.add(hook);
566
+ }
567
+ /** The record store for `docId`, or `null` when the document is format 1. */
568
+ getFormat2Store(docId) {
569
+ if (!docId) return null;
570
+ return this.format2Documents.get(docId) ?? null;
571
+ }
572
+ /**
573
+ * The epoch move a write to `docId` has to wait out (#2816, behavior 10), or
574
+ * `null` when none is in flight.
575
+ */
576
+ format2WritesHeld(docId) {
577
+ if (!docId) return null;
578
+ return this.format2Transitions.get(docId) ?? null;
579
+ }
580
+ /** Run an epoch move with `docId`'s local writes held back (#2816). */
581
+ async holdFormat2Writes(docId, run) {
582
+ const inFlight = this.format2Transitions.get(docId);
583
+ if (inFlight) await inFlight.catch(() => {
584
+ });
585
+ let release;
586
+ const held = new Promise((resolve) => {
587
+ release = resolve;
588
+ });
589
+ this.format2Transitions.set(docId, held);
590
+ try {
591
+ return await run();
592
+ } finally {
593
+ if (this.format2Transitions.get(docId) === held) {
594
+ this.format2Transitions.delete(docId);
595
+ }
596
+ release();
597
+ }
598
+ }
599
+ /** Notify `subscribe()` callbacks registered on this context for `modelName`. */
600
+ notifyListeners(modelName, log, onError) {
601
+ const listeners = this.listenersMap.get(modelName);
602
+ if (!listeners) return;
603
+ log?.(`Notifying ${listeners.size} listeners for ${modelName}`);
604
+ listeners.forEach((callback) => {
605
+ try {
606
+ callback();
607
+ } catch (e) {
608
+ onError?.(e);
609
+ }
610
+ });
611
+ }
612
+ // ---- Default-document resolution (the `BaseModel` statics delegate here) ----
613
+ setModelDefaultDocumentId(modelName, docId) {
614
+ const previous = this.modelNameToDefaultDocId.get(modelName);
615
+ this.modelNameToDefaultDocId.set(modelName, docId);
616
+ this.announceModelDocMapping(modelName, previous, docId);
617
+ }
618
+ removeModelDefaultDocumentId(modelName) {
619
+ const previous = this.modelNameToDefaultDocId.get(modelName);
620
+ this.modelNameToDefaultDocId.delete(modelName);
621
+ this.announceModelDocMapping(modelName, previous, void 0);
622
+ }
623
+ clearModelDefaultDocumentIds() {
624
+ const entries = Array.from(this.modelNameToDefaultDocId.entries());
625
+ this.modelNameToDefaultDocId.clear();
626
+ for (const [modelName, previous] of entries) {
627
+ this.announceModelDocMapping(modelName, previous, void 0);
628
+ }
629
+ }
630
+ setGlobalDefaultDocumentId(docId) {
631
+ const previous = this.globalDefaultDocId;
632
+ this.globalDefaultDocId = docId;
633
+ this.announceDefaultDoc(previous, docId);
634
+ }
635
+ clearGlobalDefaultDocumentId() {
636
+ const previous = this.globalDefaultDocId;
637
+ this.globalDefaultDocId = void 0;
638
+ this.announceDefaultDoc(previous, void 0);
639
+ }
640
+ getModelDefaultDocumentMapping() {
641
+ return Object.fromEntries(this.modelNameToDefaultDocId.entries());
642
+ }
643
+ getDocumentIdForModel(modelName) {
644
+ return this.modelNameToDefaultDocId.get(modelName);
645
+ }
646
+ getGlobalDefaultDocumentId() {
647
+ return this.globalDefaultDocId;
648
+ }
649
+ onDefaultDocChanged(listener) {
650
+ this.defaultDocChangedListeners.add(listener);
651
+ return () => this.defaultDocChangedListeners.delete(listener);
652
+ }
653
+ onModelDocMappingChanged(listener) {
654
+ this.modelDocMappingChangedListeners.add(listener);
655
+ return () => this.modelDocMappingChangedListeners.delete(listener);
656
+ }
657
+ /** Drop the model→document defaults that point at a disconnected document. */
658
+ clearMappingsForDocId(docId) {
659
+ const toRemove = [];
660
+ for (const [modelName, mappedDocId] of this.modelNameToDefaultDocId) {
661
+ if (mappedDocId === docId) toRemove.push(modelName);
662
+ }
663
+ for (const modelName of toRemove) {
664
+ this.removeModelDefaultDocumentId(modelName);
665
+ }
666
+ if (this.globalDefaultDocId === docId) {
667
+ this.clearGlobalDefaultDocumentId();
668
+ }
669
+ }
670
+ announceDefaultDoc(previous, current) {
671
+ for (const listener of this.defaultDocChangedListeners) {
672
+ try {
673
+ listener({ previous, current });
674
+ } catch {
675
+ }
676
+ }
677
+ }
678
+ announceModelDocMapping(modelName, previous, current) {
679
+ for (const listener of this.modelDocMappingChangedListeners) {
680
+ try {
681
+ listener({ modelName, previous, current });
682
+ } catch {
683
+ }
684
+ }
685
+ }
686
+ /**
687
+ * Tear this instance down: observers off, engine destroyed, state cleared.
688
+ *
689
+ * Deliberately does NOT unbind its model classes. They keep resolving this
690
+ * context, whose engine is now null, so an operation through them throws the
691
+ * ordinary not-initialized error instead of silently landing on whatever
692
+ * other instance happens to be live (#3039, behavior 7). Only a later
693
+ * `initJsBao` may rebind a class whose context is destroyed.
694
+ */
695
+ async destroy() {
696
+ if (this.destroyed) return;
697
+ this.destroyed = true;
698
+ this.disposeAllObservers();
699
+ const hooks = Array.from(this.teardownHooks);
700
+ this.teardownHooks.clear();
701
+ for (const hook of hooks) {
702
+ try {
703
+ await hook();
704
+ } catch {
705
+ }
706
+ }
707
+ const engine = this.dbEngine;
708
+ this.dbEngine = null;
709
+ if (engine) {
710
+ try {
711
+ await engine.destroy();
712
+ } catch {
713
+ }
714
+ }
715
+ this.connectedDocuments.clear();
716
+ this.documentYMaps.clear();
717
+ this.listenersMap.clear();
718
+ this.modelNameToDefaultDocId.clear();
719
+ this.globalDefaultDocId = void 0;
720
+ this.defaultDocChangedListeners.clear();
721
+ this.modelDocMappingChangedListeners.clear();
722
+ this.format2Documents.clear();
723
+ this.format2Transitions.clear();
724
+ this.observedStringSetMaps = /* @__PURE__ */ new WeakSet();
725
+ liveOrmContexts.delete(this);
726
+ if (defaultOrmContext === this) {
727
+ defaultOrmContext = new _OrmContext();
728
+ }
729
+ }
730
+ };
731
+ defaultOrmContext = new OrmContext();
732
+ liveOrmContexts = /* @__PURE__ */ new Set();
733
+ }
734
+ });
735
+
736
+ // src/models/format2QueryProjection.ts
737
+ var FORMAT2_QUERY_PROJECTION_DDL;
738
+ var init_format2QueryProjection = __esm({
739
+ "src/models/format2QueryProjection.ts"() {
740
+ "use strict";
741
+ FORMAT2_QUERY_PROJECTION_DDL = `
742
+ CREATE TABLE IF NOT EXISTS _query_projection (
743
+ doc_id TEXT NOT NULL,
744
+ model TEXT NOT NULL,
745
+ PRIMARY KEY (doc_id, model)
746
+ )`.trim();
747
+ }
748
+ });
749
+
750
+ // src/models/format2Observer.ts
751
+ var Y6;
752
+ var init_format2Observer = __esm({
753
+ "src/models/format2Observer.ts"() {
754
+ "use strict";
755
+ Y6 = __toESM(require("yjs"), 1);
756
+ init_largeDocuments();
757
+ }
758
+ });
759
+
760
+ // src/models/format2ClientWrite.ts
761
+ var init_format2ClientWrite = __esm({
762
+ "src/models/format2ClientWrite.ts"() {
763
+ "use strict";
764
+ }
765
+ });
766
+
767
+ // src/models/format2OfflineWindow.ts
768
+ var DAY_MS;
769
+ var init_format2OfflineWindow = __esm({
770
+ "src/models/format2OfflineWindow.ts"() {
771
+ "use strict";
772
+ DAY_MS = 24 * 60 * 60 * 1e3;
773
+ }
774
+ });
775
+
467
776
  // src/models/BaseModel.ts
468
777
  function generateULID() {
469
778
  return (0, import_ulid2.ulid)();
470
779
  }
471
- var Y5, import_ulid2, Logger;
780
+ var Y7, import_ulid2, Logger;
472
781
  var init_BaseModel = __esm({
473
782
  "src/models/BaseModel.ts"() {
474
783
  "use strict";
475
- Y5 = __toESM(require("yjs"), 1);
784
+ Y7 = __toESM(require("yjs"), 1);
476
785
  import_ulid2 = require("ulid");
477
786
  init_StringSet();
478
787
  init_documentTypes();
@@ -483,6 +792,12 @@ var init_BaseModel = __esm({
483
792
  init_writeLifecycle();
484
793
  init_yjsValues();
485
794
  init_uniqueIndex();
795
+ init_largeDocuments();
796
+ init_OrmContext();
797
+ init_format2QueryProjection();
798
+ init_format2Observer();
799
+ init_format2ClientWrite();
800
+ init_format2OfflineWindow();
486
801
  Logger = class {
487
802
  static _logLevel = 1 /* ERROR */;
488
803
  static _logCallback = null;
@@ -569,6 +884,7 @@ var init_ModelRegistry = __esm({
569
884
  "use strict";
570
885
  init_BaseModel();
571
886
  init_relationshipManager();
887
+ init_format2QueryProjection();
572
888
  }
573
889
  });
574
890
 
@@ -585,6 +901,7 @@ __export(cloudflare_exports, {
585
901
  clearMetaSyncCache: () => clearMetaSyncCache,
586
902
  connectDoDb: () => connectDoDb,
587
903
  decodeFunctionDefault: () => decodeFunctionDefault,
904
+ discoverDeclaredModel: () => discoverDeclaredModel,
588
905
  discoverModelNames: () => discoverModelNames,
589
906
  discoverSchema: () => discoverSchema,
590
907
  ensureStringSetYMap: () => ensureStringSetYMap,
@@ -644,6 +961,32 @@ var DatabaseEngine = class {
644
961
  getTableName(_modelName) {
645
962
  throw new Error("Method not implemented.");
646
963
  }
964
+ /**
965
+ * A SYNCHRONOUS SQL executor over this engine's database, used by the
966
+ * large-document (format 2) record store. That store commits a merged
967
+ * record row and its pending-operation entry as one transaction — the
968
+ * barrier a `save()` resolves behind — which the async `query()` API cannot
969
+ * express. Engines whose underlying SQLite is synchronous (better-sqlite3,
970
+ * SQL.js) provide it; anything else leaves it undefined and cannot host a
971
+ * large document.
972
+ */
973
+ createFormat2Sql;
974
+ /**
975
+ * Whether what {@link createFormat2Sql} writes survives this process.
976
+ *
977
+ * On a large document the merged record view IS the document: the Y.Doc
978
+ * holds one epoch's overlay, and everything else — including a record a
979
+ * `save()` has already resolved, and the pending write that still owes it to
980
+ * the server — lives only in this store. An engine whose database is in
981
+ * memory therefore cannot host one: a reload does not cost a cache, it costs
982
+ * the document and the writes nobody has acknowledged yet.
983
+ *
984
+ * The platform is asked separately about its storage quota; this answers the
985
+ * half only the engine knows. An engine that does not implement it is taken
986
+ * at the platform's word, which is what keeps hosts with storage of their
987
+ * own — a worker handed a file store, a test — working unchanged.
988
+ */
989
+ format2StorageIsDurable;
647
990
  // Transaction support
648
991
  async withTransaction(_callback) {
649
992
  throw new Error("Method not implemented.");
@@ -1486,7 +1829,7 @@ function connectDoDb(options) {
1486
1829
  }
1487
1830
 
1488
1831
  // src/utils/yDocSchema.ts
1489
- var Y6 = __toESM(require("yjs"), 1);
1832
+ var Y8 = __toESM(require("yjs"), 1);
1490
1833
  init_yjsValues();
1491
1834
  function discoverSchema(yDoc) {
1492
1835
  const models = {};
@@ -1509,6 +1852,12 @@ function discoverSchema(yDoc) {
1509
1852
  }
1510
1853
  return { models };
1511
1854
  }
1855
+ function discoverDeclaredModel(yDoc, modelName) {
1856
+ const key = `_meta_${modelName}`;
1857
+ if (!yDoc.share.has(key)) return void 0;
1858
+ const map = materializeMap(yDoc, key);
1859
+ return map ? readModelMeta(map) : void 0;
1860
+ }
1512
1861
  function discoverModelNames(yDoc) {
1513
1862
  const names = [];
1514
1863
  for (const key of yDoc.share.keys()) {
@@ -1521,7 +1870,7 @@ function discoverModelNames(yDoc) {
1521
1870
  function materializeMap(yDoc, key) {
1522
1871
  try {
1523
1872
  const map = yDoc.getMap(key);
1524
- return map instanceof Y6.Map ? map : null;
1873
+ return map instanceof Y8.Map ? map : null;
1525
1874
  } catch {
1526
1875
  return null;
1527
1876
  }
@@ -1531,11 +1880,11 @@ function readModelMeta(metaMap) {
1531
1880
  let constraints;
1532
1881
  let relationships;
1533
1882
  for (const [key, value] of metaMap.entries()) {
1534
- if (key === "_constraints" && value instanceof Y6.Map) {
1883
+ if (key === "_constraints" && value instanceof Y8.Map) {
1535
1884
  constraints = readConstraints(value);
1536
- } else if (key === "_relationships" && value instanceof Y6.Map) {
1885
+ } else if (key === "_relationships" && value instanceof Y8.Map) {
1537
1886
  relationships = readRelationships(value);
1538
- } else if (value instanceof Y6.Map) {
1887
+ } else if (value instanceof Y8.Map) {
1539
1888
  fields[key] = readFieldMeta(value);
1540
1889
  }
1541
1890
  }
@@ -1570,7 +1919,7 @@ function inferModelFromData(dataMap) {
1570
1919
  const fields = {};
1571
1920
  let sampled = 0;
1572
1921
  for (const [_recordId, recordValue] of dataMap.entries()) {
1573
- if (!(recordValue instanceof Y6.Map)) continue;
1922
+ if (!(recordValue instanceof Y8.Map)) continue;
1574
1923
  if (++sampled > 5) break;
1575
1924
  for (const [fieldName, value] of recordValue.entries()) {
1576
1925
  if (fieldName.startsWith("_")) continue;
@@ -1598,7 +1947,7 @@ function inferTypeFromValue(value) {
1598
1947
  function readConstraints(constraintsMap) {
1599
1948
  const out = {};
1600
1949
  for (const [name, value] of constraintsMap.entries()) {
1601
- if (!(value instanceof Y6.Map)) continue;
1950
+ if (!(value instanceof Y8.Map)) continue;
1602
1951
  let fields = [];
1603
1952
  const rawFields = value.get("fields");
1604
1953
  if (typeof rawFields === "string") {
@@ -1617,7 +1966,7 @@ function readConstraints(constraintsMap) {
1617
1966
  function readRelationships(relsMap) {
1618
1967
  const out = {};
1619
1968
  for (const [name, value] of relsMap.entries()) {
1620
- if (!(value instanceof Y6.Map)) continue;
1969
+ if (!(value instanceof Y8.Map)) continue;
1621
1970
  const rel = {};
1622
1971
  for (const [k, v] of value.entries()) {
1623
1972
  rel[k] = v;