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.
- package/README.md +4 -0
- package/dist/browser.cjs +4069 -350
- package/dist/browser.d.cts +2269 -50
- package/dist/browser.d.ts +2269 -50
- package/dist/browser.js +4070 -351
- package/dist/client.cjs +343 -2
- package/dist/client.d.cts +739 -12
- package/dist/client.d.ts +739 -12
- package/dist/client.js +340 -1
- package/dist/cloudflare-do.cjs +847 -6
- package/dist/cloudflare-do.d.cts +1085 -13
- package/dist/cloudflare-do.d.ts +1085 -13
- package/dist/cloudflare-do.js +845 -5
- package/dist/cloudflare.cjs +359 -10
- package/dist/cloudflare.d.cts +751 -13
- package/dist/cloudflare.d.ts +751 -13
- package/dist/cloudflare.js +356 -9
- package/dist/codegen-v2.cjs +319 -3
- package/dist/codegen.cjs +1 -1
- package/dist/index.cjs +4325 -501
- package/dist/index.d.cts +2253 -18
- package/dist/index.d.ts +2253 -18
- package/dist/index.js +4238 -470
- package/dist/node.cjs +4167 -359
- package/dist/node.d.cts +2280 -58
- package/dist/node.d.ts +2280 -58
- package/dist/node.js +4117 -361
- package/package.json +1 -1
package/dist/cloudflare-do.js
CHANGED
|
@@ -353,6 +353,9 @@ var init_patterns = __esm({
|
|
|
353
353
|
|
|
354
354
|
// src/utils/yjsValues.ts
|
|
355
355
|
import * as Y from "yjs";
|
|
356
|
+
function isYjsComposite(value) {
|
|
357
|
+
return value instanceof Y.Map || value instanceof Y.Array || value instanceof Y.Text;
|
|
358
|
+
}
|
|
356
359
|
function isStringSetYMap(value) {
|
|
357
360
|
if (!(value instanceof Y.Map)) return false;
|
|
358
361
|
for (const v of value.values()) {
|
|
@@ -570,8 +573,517 @@ var init_uniqueIndex = __esm({
|
|
|
570
573
|
}
|
|
571
574
|
});
|
|
572
575
|
|
|
573
|
-
// src/
|
|
576
|
+
// src/utils/largeDocuments.ts
|
|
574
577
|
import * as Y6 from "yjs";
|
|
578
|
+
function encodeOverlaySegment(segment) {
|
|
579
|
+
const escaped = segment.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
580
|
+
return escaped.startsWith("_") ? `~2${escaped.slice(1)}` : escaped;
|
|
581
|
+
}
|
|
582
|
+
function decodeOverlaySegment(segment) {
|
|
583
|
+
const withUnderscore = segment.startsWith("~2") ? `_${segment.slice(2)}` : segment;
|
|
584
|
+
return withUnderscore.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
585
|
+
}
|
|
586
|
+
function overlayFieldKey(recordId, field) {
|
|
587
|
+
return `${encodeOverlaySegment(recordId)}${OVERLAY_KEY_SEPARATOR}${encodeOverlaySegment(field)}`;
|
|
588
|
+
}
|
|
589
|
+
function overlayMemberKey(recordId, field, member) {
|
|
590
|
+
return `${overlayFieldKey(recordId, field)}${OVERLAY_KEY_SEPARATOR}${encodeOverlaySegment(member)}`;
|
|
591
|
+
}
|
|
592
|
+
function overlayMarkerKey(recordId, marker) {
|
|
593
|
+
return `${encodeOverlaySegment(recordId)}${OVERLAY_KEY_SEPARATOR}${marker}`;
|
|
594
|
+
}
|
|
595
|
+
function parseOverlayKey(key) {
|
|
596
|
+
const parts = key.split(OVERLAY_KEY_SEPARATOR);
|
|
597
|
+
if (parts.length === 2) {
|
|
598
|
+
const [rawId, rawSecond] = parts;
|
|
599
|
+
const recordId = decodeOverlaySegment(rawId);
|
|
600
|
+
if (OVERLAY_MARKERS.has(rawSecond)) return { recordId, marker: rawSecond };
|
|
601
|
+
return { recordId, field: decodeOverlaySegment(rawSecond) };
|
|
602
|
+
}
|
|
603
|
+
if (parts.length === 3) {
|
|
604
|
+
return {
|
|
605
|
+
recordId: decodeOverlaySegment(parts[0]),
|
|
606
|
+
field: decodeOverlaySegment(parts[1]),
|
|
607
|
+
member: decodeOverlaySegment(parts[2])
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
function emptyEntry(id) {
|
|
613
|
+
return { id, fields: {}, stringSets: {}, replace: false, deleted: false };
|
|
614
|
+
}
|
|
615
|
+
function groupOverlayEntries(entries) {
|
|
616
|
+
const out = /* @__PURE__ */ new Map();
|
|
617
|
+
for (const [key, value] of entries) {
|
|
618
|
+
const parsed = parseOverlayKey(key);
|
|
619
|
+
if (!parsed) continue;
|
|
620
|
+
let entry = out.get(parsed.recordId);
|
|
621
|
+
if (!entry) {
|
|
622
|
+
entry = emptyEntry(parsed.recordId);
|
|
623
|
+
out.set(parsed.recordId, entry);
|
|
624
|
+
}
|
|
625
|
+
if (parsed.marker === OVERLAY_MARKER_REPLACE) {
|
|
626
|
+
entry.replace = value === true;
|
|
627
|
+
} else if (parsed.marker === OVERLAY_MARKER_DELETED) {
|
|
628
|
+
entry.deleted = value === true;
|
|
629
|
+
} else if (parsed.member !== void 0) {
|
|
630
|
+
const field = parsed.field;
|
|
631
|
+
(entry.stringSets[field] ||= {})[parsed.member] = value === true;
|
|
632
|
+
} else if (parsed.field !== void 0) {
|
|
633
|
+
entry.fields[parsed.field] = value;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
return out;
|
|
637
|
+
}
|
|
638
|
+
function readOverlayRecord(modelMap, recordId) {
|
|
639
|
+
return collectOverlayRecords(modelMap, /* @__PURE__ */ new Set([recordId])).get(recordId);
|
|
640
|
+
}
|
|
641
|
+
function completeOverlayEntries(modelMap, entries) {
|
|
642
|
+
const rebuild = /* @__PURE__ */ new Set();
|
|
643
|
+
for (const [id, entry] of entries) {
|
|
644
|
+
if (!entry.replace || entry.deleted) continue;
|
|
645
|
+
rebuild.add(id);
|
|
646
|
+
}
|
|
647
|
+
if (rebuild.size === 0) return entries;
|
|
648
|
+
for (const [id, entry] of collectOverlayRecords(modelMap, rebuild)) {
|
|
649
|
+
entries.set(id, entry);
|
|
650
|
+
}
|
|
651
|
+
return entries;
|
|
652
|
+
}
|
|
653
|
+
function collectOverlayRecords(modelMap, recordIds) {
|
|
654
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
655
|
+
for (const id of recordIds) wanted.set(encodeOverlaySegment(id), id);
|
|
656
|
+
const own = /* @__PURE__ */ new Map();
|
|
657
|
+
for (const [key, value] of modelMap.entries()) {
|
|
658
|
+
if (typeof key !== "string") continue;
|
|
659
|
+
const separator = key.indexOf(OVERLAY_KEY_SEPARATOR);
|
|
660
|
+
if (separator <= 0) continue;
|
|
661
|
+
const id = wanted.get(key.slice(0, separator));
|
|
662
|
+
if (id === void 0) continue;
|
|
663
|
+
if (!parseOverlayKey(key)) continue;
|
|
664
|
+
const keys = own.get(id);
|
|
665
|
+
if (keys) keys.push([key, value]);
|
|
666
|
+
else own.set(id, [[key, value]]);
|
|
667
|
+
}
|
|
668
|
+
const out = /* @__PURE__ */ new Map();
|
|
669
|
+
for (const id of recordIds) {
|
|
670
|
+
out.set(id, groupOverlayEntries(own.get(id) ?? []).get(id) ?? emptyEntry(id));
|
|
671
|
+
}
|
|
672
|
+
return out;
|
|
673
|
+
}
|
|
674
|
+
function baseMembers(value) {
|
|
675
|
+
if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
|
|
676
|
+
if (value && typeof value === "object") {
|
|
677
|
+
return Object.entries(value).filter(([, present]) => Boolean(present)).map(([member]) => member);
|
|
678
|
+
}
|
|
679
|
+
return [];
|
|
680
|
+
}
|
|
681
|
+
function materializeOverlayRecord(base, overlay) {
|
|
682
|
+
if (overlay.deleted) return null;
|
|
683
|
+
const out = overlay.replace ? {} : { ...base ?? {} };
|
|
684
|
+
for (const [field, value] of Object.entries(overlay.fields)) {
|
|
685
|
+
if (value === null) delete out[field];
|
|
686
|
+
else out[field] = value;
|
|
687
|
+
}
|
|
688
|
+
for (const [field, members] of Object.entries(overlay.stringSets)) {
|
|
689
|
+
const current = overlay.replace ? [] : baseMembers(out[field]);
|
|
690
|
+
const next = current.slice();
|
|
691
|
+
for (const [member, present] of Object.entries(members)) {
|
|
692
|
+
const at = next.indexOf(member);
|
|
693
|
+
if (present && at === -1) next.push(member);
|
|
694
|
+
else if (!present && at !== -1) next.splice(at, 1);
|
|
695
|
+
}
|
|
696
|
+
out[field] = next;
|
|
697
|
+
}
|
|
698
|
+
out.id = overlay.id;
|
|
699
|
+
return out;
|
|
700
|
+
}
|
|
701
|
+
function encodeOverlayMutation(mutation) {
|
|
702
|
+
const { id, kind } = mutation;
|
|
703
|
+
const entries = [];
|
|
704
|
+
if (kind === "delete") {
|
|
705
|
+
entries.push([overlayMarkerKey(id, OVERLAY_MARKER_DELETED), true]);
|
|
706
|
+
return entries;
|
|
707
|
+
}
|
|
708
|
+
if (kind === "create") {
|
|
709
|
+
entries.push([overlayMarkerKey(id, OVERLAY_MARKER_REPLACE), true]);
|
|
710
|
+
entries.push([overlayMarkerKey(id, OVERLAY_MARKER_DELETED), false]);
|
|
711
|
+
}
|
|
712
|
+
for (const [field, value] of Object.entries(mutation.fields ?? {})) {
|
|
713
|
+
entries.push([overlayFieldKey(id, field), value === void 0 ? null : value]);
|
|
714
|
+
}
|
|
715
|
+
for (const [field, members] of Object.entries(mutation.stringSetDeltas ?? {})) {
|
|
716
|
+
for (const [member, present] of Object.entries(members)) {
|
|
717
|
+
entries.push([overlayMemberKey(id, field, member), present]);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
return entries;
|
|
721
|
+
}
|
|
722
|
+
function applyOverlayMutation(modelMap, mutation) {
|
|
723
|
+
if (mutation.kind === "create") {
|
|
724
|
+
clearStaleRecordOverlay(modelMap, mutation.id);
|
|
725
|
+
}
|
|
726
|
+
for (const [key, value] of encodeOverlayMutation(mutation)) {
|
|
727
|
+
modelMap.set(key, value);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function clearStaleRecordOverlay(modelMap, recordId) {
|
|
731
|
+
if (!modelMap.has(overlayMarkerKey(recordId, OVERLAY_MARKER_DELETED))) return;
|
|
732
|
+
const prefix = `${encodeOverlaySegment(recordId)}${OVERLAY_KEY_SEPARATOR}`;
|
|
733
|
+
const stale = [];
|
|
734
|
+
for (const key of modelMap.keys()) {
|
|
735
|
+
if (key.startsWith(prefix)) stale.push(key);
|
|
736
|
+
}
|
|
737
|
+
for (const key of stale) modelMap.delete(key);
|
|
738
|
+
}
|
|
739
|
+
function assertNoFormat2CompositeFields(modelName, recordId, fields) {
|
|
740
|
+
if (!fields) return;
|
|
741
|
+
for (const [field, value] of Object.entries(fields)) {
|
|
742
|
+
if (isYjsComposite(value)) {
|
|
743
|
+
throw new Format2CompositeFieldError(modelName, recordId, field);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
function isFormat2StringSetYMap(value) {
|
|
748
|
+
if (!(value instanceof Y6.Map)) return false;
|
|
749
|
+
for (const member of value.values()) {
|
|
750
|
+
if (member !== true && member !== false) return false;
|
|
751
|
+
}
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
function format2StringSetMembers(value) {
|
|
755
|
+
if (!(value instanceof Y6.Map)) return [];
|
|
756
|
+
return Array.from(value.entries()).filter(([, present]) => present === true).map(([member]) => member);
|
|
757
|
+
}
|
|
758
|
+
var OVERLAY_KEY_SEPARATOR, OVERLAY_MARKER_REPLACE, OVERLAY_MARKER_DELETED, OVERLAY_MARKERS, Format2CompositeFieldError;
|
|
759
|
+
var init_largeDocuments = __esm({
|
|
760
|
+
"src/utils/largeDocuments.ts"() {
|
|
761
|
+
"use strict";
|
|
762
|
+
init_yjsValues();
|
|
763
|
+
OVERLAY_KEY_SEPARATOR = "/";
|
|
764
|
+
OVERLAY_MARKER_REPLACE = "_replace";
|
|
765
|
+
OVERLAY_MARKER_DELETED = "_deleted";
|
|
766
|
+
OVERLAY_MARKERS = /* @__PURE__ */ new Set([
|
|
767
|
+
OVERLAY_MARKER_REPLACE,
|
|
768
|
+
OVERLAY_MARKER_DELETED
|
|
769
|
+
]);
|
|
770
|
+
Format2CompositeFieldError = class extends Error {
|
|
771
|
+
modelName;
|
|
772
|
+
recordId;
|
|
773
|
+
field;
|
|
774
|
+
constructor(modelName, recordId, field) {
|
|
775
|
+
super(
|
|
776
|
+
`Composite field values are not supported on large documents (format 2): ${modelName}.${field} (id=${recordId})`
|
|
777
|
+
);
|
|
778
|
+
this.name = "Format2CompositeFieldError";
|
|
779
|
+
this.modelName = modelName;
|
|
780
|
+
this.recordId = recordId;
|
|
781
|
+
this.field = field;
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
// src/models/OrmContext.ts
|
|
788
|
+
var OrmContext, defaultOrmContext, liveOrmContexts;
|
|
789
|
+
var init_OrmContext = __esm({
|
|
790
|
+
"src/models/OrmContext.ts"() {
|
|
791
|
+
"use strict";
|
|
792
|
+
OrmContext = class _OrmContext {
|
|
793
|
+
/** Declared before the field that reads it: static initialization is ordered. */
|
|
794
|
+
static instanceCounter = 0;
|
|
795
|
+
/**
|
|
796
|
+
* Which instance this is, for diagnostics. A process holding several clients
|
|
797
|
+
* needs a way to say WHICH one a warning is about, so every context takes the
|
|
798
|
+
* next number as it is created and keeps it for its lifetime.
|
|
799
|
+
*/
|
|
800
|
+
instanceId = ++_OrmContext.instanceCounter;
|
|
801
|
+
/** The engine this instance's models read and write through. */
|
|
802
|
+
dbEngine = null;
|
|
803
|
+
connectedDocuments = /* @__PURE__ */ new Map();
|
|
804
|
+
/** `docId_modelName` → the Y.Map that document holds for that model. */
|
|
805
|
+
documentYMaps = /* @__PURE__ */ new Map();
|
|
806
|
+
/** `subscribe()` callbacks, by model name. */
|
|
807
|
+
listenersMap = /* @__PURE__ */ new Map();
|
|
808
|
+
// Default-document resolution
|
|
809
|
+
modelNameToDefaultDocId = /* @__PURE__ */ new Map();
|
|
810
|
+
globalDefaultDocId = void 0;
|
|
811
|
+
defaultDocChangedListeners = /* @__PURE__ */ new Set();
|
|
812
|
+
modelDocMappingChangedListeners = /* @__PURE__ */ new Set();
|
|
813
|
+
/** Format-2 ("large document", #2816) record stores by document id. */
|
|
814
|
+
format2Documents = /* @__PURE__ */ new Map();
|
|
815
|
+
/** Format-2 epoch moves in flight (#2816). */
|
|
816
|
+
format2Transitions = /* @__PURE__ */ new Map();
|
|
817
|
+
/**
|
|
818
|
+
* Nested-Y.Map stringset fields this context has already observed. Per
|
|
819
|
+
* context, not global: a Y.Doc reconnected to a fresh instance has to be
|
|
820
|
+
* observed again by that instance, and a global guard would silently
|
|
821
|
+
* suppress it.
|
|
822
|
+
*/
|
|
823
|
+
observedStringSetMaps = /* @__PURE__ */ new WeakSet();
|
|
824
|
+
/**
|
|
825
|
+
* The registry this instance's schema lookups use. `null` on the standing
|
|
826
|
+
* default context, where callers fall back to the global singleton.
|
|
827
|
+
*/
|
|
828
|
+
modelRegistry = null;
|
|
829
|
+
/** Model classes routed to this context. */
|
|
830
|
+
boundModels = /* @__PURE__ */ new Set();
|
|
831
|
+
/** True once {@link destroy} has run; bound classes keep pointing here. */
|
|
832
|
+
destroyed = false;
|
|
833
|
+
/** Yjs `unobserve` thunks by owning document id. */
|
|
834
|
+
observerDisposers = /* @__PURE__ */ new Map();
|
|
835
|
+
/** Teardown the owner (the document manager) registers for `destroy()`. */
|
|
836
|
+
teardownHooks = /* @__PURE__ */ new Set();
|
|
837
|
+
static NO_DOCUMENT_KEY = "__no_document__";
|
|
838
|
+
/**
|
|
839
|
+
* Record how to remove an observer this context installed. Every `observe()`
|
|
840
|
+
* in the ORM pairs with one of these: without it a torn-down instance's
|
|
841
|
+
* callbacks keep firing on a Y.Doc that outlives it.
|
|
842
|
+
*/
|
|
843
|
+
registerObserverDisposer(docId, dispose) {
|
|
844
|
+
const key = docId ?? _OrmContext.NO_DOCUMENT_KEY;
|
|
845
|
+
const list = this.observerDisposers.get(key);
|
|
846
|
+
if (list) list.push(dispose);
|
|
847
|
+
else this.observerDisposers.set(key, [dispose]);
|
|
848
|
+
}
|
|
849
|
+
/** Remove every observer this context installed for `docId`. */
|
|
850
|
+
disposeObserversForDocument(docId) {
|
|
851
|
+
const list = this.observerDisposers.get(docId);
|
|
852
|
+
if (!list) return;
|
|
853
|
+
this.observerDisposers.delete(docId);
|
|
854
|
+
for (const dispose of list) {
|
|
855
|
+
try {
|
|
856
|
+
dispose();
|
|
857
|
+
} catch {
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
disposeAllObservers() {
|
|
862
|
+
const buckets = Array.from(this.observerDisposers.values());
|
|
863
|
+
this.observerDisposers.clear();
|
|
864
|
+
for (const list of buckets) {
|
|
865
|
+
for (const dispose of list) {
|
|
866
|
+
try {
|
|
867
|
+
dispose();
|
|
868
|
+
} catch {
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
/** Run `hook` as part of `destroy()` (the format-2 binding registers here). */
|
|
874
|
+
onDestroy(hook) {
|
|
875
|
+
this.teardownHooks.add(hook);
|
|
876
|
+
}
|
|
877
|
+
/** The record store for `docId`, or `null` when the document is format 1. */
|
|
878
|
+
getFormat2Store(docId) {
|
|
879
|
+
if (!docId) return null;
|
|
880
|
+
return this.format2Documents.get(docId) ?? null;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* The epoch move a write to `docId` has to wait out (#2816, behavior 10), or
|
|
884
|
+
* `null` when none is in flight.
|
|
885
|
+
*/
|
|
886
|
+
format2WritesHeld(docId) {
|
|
887
|
+
if (!docId) return null;
|
|
888
|
+
return this.format2Transitions.get(docId) ?? null;
|
|
889
|
+
}
|
|
890
|
+
/** Run an epoch move with `docId`'s local writes held back (#2816). */
|
|
891
|
+
async holdFormat2Writes(docId, run) {
|
|
892
|
+
const inFlight = this.format2Transitions.get(docId);
|
|
893
|
+
if (inFlight) await inFlight.catch(() => {
|
|
894
|
+
});
|
|
895
|
+
let release;
|
|
896
|
+
const held = new Promise((resolve) => {
|
|
897
|
+
release = resolve;
|
|
898
|
+
});
|
|
899
|
+
this.format2Transitions.set(docId, held);
|
|
900
|
+
try {
|
|
901
|
+
return await run();
|
|
902
|
+
} finally {
|
|
903
|
+
if (this.format2Transitions.get(docId) === held) {
|
|
904
|
+
this.format2Transitions.delete(docId);
|
|
905
|
+
}
|
|
906
|
+
release();
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
/** Notify `subscribe()` callbacks registered on this context for `modelName`. */
|
|
910
|
+
notifyListeners(modelName, log, onError) {
|
|
911
|
+
const listeners = this.listenersMap.get(modelName);
|
|
912
|
+
if (!listeners) return;
|
|
913
|
+
log?.(`Notifying ${listeners.size} listeners for ${modelName}`);
|
|
914
|
+
listeners.forEach((callback) => {
|
|
915
|
+
try {
|
|
916
|
+
callback();
|
|
917
|
+
} catch (e) {
|
|
918
|
+
onError?.(e);
|
|
919
|
+
}
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
// ---- Default-document resolution (the `BaseModel` statics delegate here) ----
|
|
923
|
+
setModelDefaultDocumentId(modelName, docId) {
|
|
924
|
+
const previous = this.modelNameToDefaultDocId.get(modelName);
|
|
925
|
+
this.modelNameToDefaultDocId.set(modelName, docId);
|
|
926
|
+
this.announceModelDocMapping(modelName, previous, docId);
|
|
927
|
+
}
|
|
928
|
+
removeModelDefaultDocumentId(modelName) {
|
|
929
|
+
const previous = this.modelNameToDefaultDocId.get(modelName);
|
|
930
|
+
this.modelNameToDefaultDocId.delete(modelName);
|
|
931
|
+
this.announceModelDocMapping(modelName, previous, void 0);
|
|
932
|
+
}
|
|
933
|
+
clearModelDefaultDocumentIds() {
|
|
934
|
+
const entries = Array.from(this.modelNameToDefaultDocId.entries());
|
|
935
|
+
this.modelNameToDefaultDocId.clear();
|
|
936
|
+
for (const [modelName, previous] of entries) {
|
|
937
|
+
this.announceModelDocMapping(modelName, previous, void 0);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
setGlobalDefaultDocumentId(docId) {
|
|
941
|
+
const previous = this.globalDefaultDocId;
|
|
942
|
+
this.globalDefaultDocId = docId;
|
|
943
|
+
this.announceDefaultDoc(previous, docId);
|
|
944
|
+
}
|
|
945
|
+
clearGlobalDefaultDocumentId() {
|
|
946
|
+
const previous = this.globalDefaultDocId;
|
|
947
|
+
this.globalDefaultDocId = void 0;
|
|
948
|
+
this.announceDefaultDoc(previous, void 0);
|
|
949
|
+
}
|
|
950
|
+
getModelDefaultDocumentMapping() {
|
|
951
|
+
return Object.fromEntries(this.modelNameToDefaultDocId.entries());
|
|
952
|
+
}
|
|
953
|
+
getDocumentIdForModel(modelName) {
|
|
954
|
+
return this.modelNameToDefaultDocId.get(modelName);
|
|
955
|
+
}
|
|
956
|
+
getGlobalDefaultDocumentId() {
|
|
957
|
+
return this.globalDefaultDocId;
|
|
958
|
+
}
|
|
959
|
+
onDefaultDocChanged(listener) {
|
|
960
|
+
this.defaultDocChangedListeners.add(listener);
|
|
961
|
+
return () => this.defaultDocChangedListeners.delete(listener);
|
|
962
|
+
}
|
|
963
|
+
onModelDocMappingChanged(listener) {
|
|
964
|
+
this.modelDocMappingChangedListeners.add(listener);
|
|
965
|
+
return () => this.modelDocMappingChangedListeners.delete(listener);
|
|
966
|
+
}
|
|
967
|
+
/** Drop the model→document defaults that point at a disconnected document. */
|
|
968
|
+
clearMappingsForDocId(docId) {
|
|
969
|
+
const toRemove = [];
|
|
970
|
+
for (const [modelName, mappedDocId] of this.modelNameToDefaultDocId) {
|
|
971
|
+
if (mappedDocId === docId) toRemove.push(modelName);
|
|
972
|
+
}
|
|
973
|
+
for (const modelName of toRemove) {
|
|
974
|
+
this.removeModelDefaultDocumentId(modelName);
|
|
975
|
+
}
|
|
976
|
+
if (this.globalDefaultDocId === docId) {
|
|
977
|
+
this.clearGlobalDefaultDocumentId();
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
announceDefaultDoc(previous, current) {
|
|
981
|
+
for (const listener of this.defaultDocChangedListeners) {
|
|
982
|
+
try {
|
|
983
|
+
listener({ previous, current });
|
|
984
|
+
} catch {
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
announceModelDocMapping(modelName, previous, current) {
|
|
989
|
+
for (const listener of this.modelDocMappingChangedListeners) {
|
|
990
|
+
try {
|
|
991
|
+
listener({ modelName, previous, current });
|
|
992
|
+
} catch {
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Tear this instance down: observers off, engine destroyed, state cleared.
|
|
998
|
+
*
|
|
999
|
+
* Deliberately does NOT unbind its model classes. They keep resolving this
|
|
1000
|
+
* context, whose engine is now null, so an operation through them throws the
|
|
1001
|
+
* ordinary not-initialized error instead of silently landing on whatever
|
|
1002
|
+
* other instance happens to be live (#3039, behavior 7). Only a later
|
|
1003
|
+
* `initJsBao` may rebind a class whose context is destroyed.
|
|
1004
|
+
*/
|
|
1005
|
+
async destroy() {
|
|
1006
|
+
if (this.destroyed) return;
|
|
1007
|
+
this.destroyed = true;
|
|
1008
|
+
this.disposeAllObservers();
|
|
1009
|
+
const hooks = Array.from(this.teardownHooks);
|
|
1010
|
+
this.teardownHooks.clear();
|
|
1011
|
+
for (const hook of hooks) {
|
|
1012
|
+
try {
|
|
1013
|
+
await hook();
|
|
1014
|
+
} catch {
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
const engine = this.dbEngine;
|
|
1018
|
+
this.dbEngine = null;
|
|
1019
|
+
if (engine) {
|
|
1020
|
+
try {
|
|
1021
|
+
await engine.destroy();
|
|
1022
|
+
} catch {
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
this.connectedDocuments.clear();
|
|
1026
|
+
this.documentYMaps.clear();
|
|
1027
|
+
this.listenersMap.clear();
|
|
1028
|
+
this.modelNameToDefaultDocId.clear();
|
|
1029
|
+
this.globalDefaultDocId = void 0;
|
|
1030
|
+
this.defaultDocChangedListeners.clear();
|
|
1031
|
+
this.modelDocMappingChangedListeners.clear();
|
|
1032
|
+
this.format2Documents.clear();
|
|
1033
|
+
this.format2Transitions.clear();
|
|
1034
|
+
this.observedStringSetMaps = /* @__PURE__ */ new WeakSet();
|
|
1035
|
+
liveOrmContexts.delete(this);
|
|
1036
|
+
if (defaultOrmContext === this) {
|
|
1037
|
+
defaultOrmContext = new _OrmContext();
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
defaultOrmContext = new OrmContext();
|
|
1042
|
+
liveOrmContexts = /* @__PURE__ */ new Set();
|
|
1043
|
+
}
|
|
1044
|
+
});
|
|
1045
|
+
|
|
1046
|
+
// src/models/format2QueryProjection.ts
|
|
1047
|
+
var FORMAT2_QUERY_PROJECTION_DDL;
|
|
1048
|
+
var init_format2QueryProjection = __esm({
|
|
1049
|
+
"src/models/format2QueryProjection.ts"() {
|
|
1050
|
+
"use strict";
|
|
1051
|
+
FORMAT2_QUERY_PROJECTION_DDL = `
|
|
1052
|
+
CREATE TABLE IF NOT EXISTS _query_projection (
|
|
1053
|
+
doc_id TEXT NOT NULL,
|
|
1054
|
+
model TEXT NOT NULL,
|
|
1055
|
+
PRIMARY KEY (doc_id, model)
|
|
1056
|
+
)`.trim();
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
|
|
1060
|
+
// src/models/format2Observer.ts
|
|
1061
|
+
import * as Y7 from "yjs";
|
|
1062
|
+
var init_format2Observer = __esm({
|
|
1063
|
+
"src/models/format2Observer.ts"() {
|
|
1064
|
+
"use strict";
|
|
1065
|
+
init_largeDocuments();
|
|
1066
|
+
}
|
|
1067
|
+
});
|
|
1068
|
+
|
|
1069
|
+
// src/models/format2ClientWrite.ts
|
|
1070
|
+
var init_format2ClientWrite = __esm({
|
|
1071
|
+
"src/models/format2ClientWrite.ts"() {
|
|
1072
|
+
"use strict";
|
|
1073
|
+
}
|
|
1074
|
+
});
|
|
1075
|
+
|
|
1076
|
+
// src/models/format2OfflineWindow.ts
|
|
1077
|
+
var DAY_MS;
|
|
1078
|
+
var init_format2OfflineWindow = __esm({
|
|
1079
|
+
"src/models/format2OfflineWindow.ts"() {
|
|
1080
|
+
"use strict";
|
|
1081
|
+
DAY_MS = 24 * 60 * 60 * 1e3;
|
|
1082
|
+
}
|
|
1083
|
+
});
|
|
1084
|
+
|
|
1085
|
+
// src/models/BaseModel.ts
|
|
1086
|
+
import * as Y8 from "yjs";
|
|
575
1087
|
import { ulid as ulid3 } from "ulid";
|
|
576
1088
|
function generateULID() {
|
|
577
1089
|
return ulid3();
|
|
@@ -588,6 +1100,12 @@ var init_BaseModel = __esm({
|
|
|
588
1100
|
init_writeLifecycle();
|
|
589
1101
|
init_yjsValues();
|
|
590
1102
|
init_uniqueIndex();
|
|
1103
|
+
init_largeDocuments();
|
|
1104
|
+
init_OrmContext();
|
|
1105
|
+
init_format2QueryProjection();
|
|
1106
|
+
init_format2Observer();
|
|
1107
|
+
init_format2ClientWrite();
|
|
1108
|
+
init_format2OfflineWindow();
|
|
591
1109
|
registerFunctionDefault(generateULID, "generate_ulid");
|
|
592
1110
|
}
|
|
593
1111
|
});
|
|
@@ -606,6 +1124,7 @@ var init_ModelRegistry = __esm({
|
|
|
606
1124
|
"use strict";
|
|
607
1125
|
init_BaseModel();
|
|
608
1126
|
init_relationshipManager();
|
|
1127
|
+
init_format2QueryProjection();
|
|
609
1128
|
}
|
|
610
1129
|
});
|
|
611
1130
|
|
|
@@ -641,6 +1160,32 @@ var DatabaseEngine = class {
|
|
|
641
1160
|
getTableName(_modelName) {
|
|
642
1161
|
throw new Error("Method not implemented.");
|
|
643
1162
|
}
|
|
1163
|
+
/**
|
|
1164
|
+
* A SYNCHRONOUS SQL executor over this engine's database, used by the
|
|
1165
|
+
* large-document (format 2) record store. That store commits a merged
|
|
1166
|
+
* record row and its pending-operation entry as one transaction — the
|
|
1167
|
+
* barrier a `save()` resolves behind — which the async `query()` API cannot
|
|
1168
|
+
* express. Engines whose underlying SQLite is synchronous (better-sqlite3,
|
|
1169
|
+
* SQL.js) provide it; anything else leaves it undefined and cannot host a
|
|
1170
|
+
* large document.
|
|
1171
|
+
*/
|
|
1172
|
+
createFormat2Sql;
|
|
1173
|
+
/**
|
|
1174
|
+
* Whether what {@link createFormat2Sql} writes survives this process.
|
|
1175
|
+
*
|
|
1176
|
+
* On a large document the merged record view IS the document: the Y.Doc
|
|
1177
|
+
* holds one epoch's overlay, and everything else — including a record a
|
|
1178
|
+
* `save()` has already resolved, and the pending write that still owes it to
|
|
1179
|
+
* the server — lives only in this store. An engine whose database is in
|
|
1180
|
+
* memory therefore cannot host one: a reload does not cost a cache, it costs
|
|
1181
|
+
* the document and the writes nobody has acknowledged yet.
|
|
1182
|
+
*
|
|
1183
|
+
* The platform is asked separately about its storage quota; this answers the
|
|
1184
|
+
* half only the engine knows. An engine that does not implement it is taken
|
|
1185
|
+
* at the platform's word, which is what keeps hosts with storage of their
|
|
1186
|
+
* own — a worker handed a file store, a test — working unchanged.
|
|
1187
|
+
*/
|
|
1188
|
+
format2StorageIsDurable;
|
|
644
1189
|
// Transaction support
|
|
645
1190
|
async withTransaction(_callback) {
|
|
646
1191
|
throw new Error("Method not implemented.");
|
|
@@ -1974,8 +2519,11 @@ var JsonQueryTranslator = class {
|
|
|
1974
2519
|
};
|
|
1975
2520
|
case "$ne":
|
|
1976
2521
|
this.validateFieldValue(fieldName, value);
|
|
2522
|
+
if (value === null || value === void 0) {
|
|
2523
|
+
return { sql: `${fieldSql} IS NOT NULL`, params: [] };
|
|
2524
|
+
}
|
|
1977
2525
|
return {
|
|
1978
|
-
sql:
|
|
2526
|
+
sql: `(${fieldSql} IS NULL OR ${fieldSql} != ?)`,
|
|
1979
2527
|
params: [this.convertValueForSQLite(value)]
|
|
1980
2528
|
};
|
|
1981
2529
|
case "$gt":
|
|
@@ -2058,12 +2606,23 @@ var JsonQueryTranslator = class {
|
|
|
2058
2606
|
if (value.length === 0) {
|
|
2059
2607
|
return { sql: "", params: [] };
|
|
2060
2608
|
}
|
|
2061
|
-
const
|
|
2062
|
-
const
|
|
2609
|
+
const ninHasNull = value.some((v) => v === null || v === void 0);
|
|
2610
|
+
const ninValues = value.filter((v) => v !== null && v !== void 0);
|
|
2611
|
+
const ninPlaceholders = ninValues.map(() => "?").join(",");
|
|
2612
|
+
const convertedNinValues = ninValues.map(
|
|
2063
2613
|
(v) => this.convertValueForSQLite(v)
|
|
2064
2614
|
);
|
|
2615
|
+
if (ninHasNull) {
|
|
2616
|
+
if (ninValues.length === 0) {
|
|
2617
|
+
return { sql: `${fieldSql} IS NOT NULL`, params: [] };
|
|
2618
|
+
}
|
|
2619
|
+
return {
|
|
2620
|
+
sql: `(${fieldSql} IS NOT NULL AND ${fieldSql} NOT IN (${ninPlaceholders}))`,
|
|
2621
|
+
params: convertedNinValues
|
|
2622
|
+
};
|
|
2623
|
+
}
|
|
2065
2624
|
return {
|
|
2066
|
-
sql:
|
|
2625
|
+
sql: `(${fieldSql} IS NULL OR ${fieldSql} NOT IN (${ninPlaceholders}))`,
|
|
2067
2626
|
params: convertedNinValues
|
|
2068
2627
|
};
|
|
2069
2628
|
case "$exists":
|
|
@@ -4396,6 +4955,12 @@ function discoverSchema(yDoc) {
|
|
|
4396
4955
|
}
|
|
4397
4956
|
return { models };
|
|
4398
4957
|
}
|
|
4958
|
+
function discoverDeclaredModel(yDoc, modelName) {
|
|
4959
|
+
const key = `_meta_${modelName}`;
|
|
4960
|
+
if (!yDoc.share.has(key)) return void 0;
|
|
4961
|
+
const map = materializeMap(yDoc, key);
|
|
4962
|
+
return map ? readModelMeta(map) : void 0;
|
|
4963
|
+
}
|
|
4399
4964
|
function discoverModelNames(yDoc) {
|
|
4400
4965
|
const names = [];
|
|
4401
4966
|
for (const key of yDoc.share.keys()) {
|
|
@@ -4874,27 +5439,302 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
|
|
|
4874
5439
|
// src/cloudflare-do.ts
|
|
4875
5440
|
init_metaSync();
|
|
4876
5441
|
init_sql();
|
|
5442
|
+
init_largeDocuments();
|
|
5443
|
+
|
|
5444
|
+
// src/utils/overlaySql.ts
|
|
5445
|
+
init_sql();
|
|
5446
|
+
var DEFAULT_OVERLAY_TABLES = {
|
|
5447
|
+
records: "records",
|
|
5448
|
+
stringSetIndex: "stringset_index"
|
|
5449
|
+
};
|
|
5450
|
+
var statementCache = /* @__PURE__ */ new Map();
|
|
5451
|
+
function statementsFor(tables) {
|
|
5452
|
+
const cacheKey = `${tables.records}\0${tables.stringSetIndex}`;
|
|
5453
|
+
const cached = statementCache.get(cacheKey);
|
|
5454
|
+
if (cached) return cached;
|
|
5455
|
+
assertValidIdentifier(tables.records, "overlay records table");
|
|
5456
|
+
assertValidIdentifier(tables.stringSetIndex, "overlay stringset table");
|
|
5457
|
+
const records = tables.records;
|
|
5458
|
+
const members = tables.stringSetIndex;
|
|
5459
|
+
const statements = {
|
|
5460
|
+
deleteRecord: `DELETE FROM ${records} WHERE _type = ? AND _id = ?`,
|
|
5461
|
+
deleteAllMembers: `DELETE FROM ${members} WHERE _type = ? AND _record_id = ?`,
|
|
5462
|
+
deleteMember: `DELETE FROM ${members} WHERE _type = ? AND _record_id = ? AND field = ? AND value = ?`,
|
|
5463
|
+
insertMember: `INSERT OR IGNORE INTO ${members} (_record_id, _type, field, value) VALUES (?, ?, ?, ?)`,
|
|
5464
|
+
selectMembers: `SELECT value FROM ${members} WHERE _type = ? AND _record_id = ? AND field = ? ORDER BY rowid`,
|
|
5465
|
+
mergeUpsert: `
|
|
5466
|
+
INSERT INTO ${records} (_id, _type, _data)
|
|
5467
|
+
VALUES (?, ?, json_patch('{}', ?))
|
|
5468
|
+
ON CONFLICT(_type, _id) DO UPDATE SET
|
|
5469
|
+
_data = json_patch(${records}._data, ?)`.trim(),
|
|
5470
|
+
replaceUpsert: `
|
|
5471
|
+
INSERT INTO ${records} (_id, _type, _data)
|
|
5472
|
+
VALUES (?, ?, json_patch('{}', ?))
|
|
5473
|
+
ON CONFLICT(_type, _id) DO UPDATE SET
|
|
5474
|
+
_data = json_patch('{}', ?)`.trim()
|
|
5475
|
+
};
|
|
5476
|
+
statementCache.set(cacheKey, statements);
|
|
5477
|
+
return statements;
|
|
5478
|
+
}
|
|
5479
|
+
function projectOverlayEntry(sql, modelName, entry, tables = DEFAULT_OVERLAY_TABLES) {
|
|
5480
|
+
const id = entry.id;
|
|
5481
|
+
const {
|
|
5482
|
+
deleteRecord: DELETE_RECORD,
|
|
5483
|
+
deleteAllMembers: DELETE_ALL_MEMBERS,
|
|
5484
|
+
deleteMember: DELETE_MEMBER,
|
|
5485
|
+
insertMember: INSERT_MEMBER,
|
|
5486
|
+
selectMembers: SELECT_MEMBERS,
|
|
5487
|
+
mergeUpsert: MERGE_UPSERT,
|
|
5488
|
+
replaceUpsert: REPLACE_UPSERT
|
|
5489
|
+
} = statementsFor(tables);
|
|
5490
|
+
if (entry.deleted) {
|
|
5491
|
+
sql.exec(DELETE_RECORD, modelName, id);
|
|
5492
|
+
sql.exec(DELETE_ALL_MEMBERS, modelName, id);
|
|
5493
|
+
return;
|
|
5494
|
+
}
|
|
5495
|
+
const touchedFields = Object.keys(entry.fields);
|
|
5496
|
+
const touchedSets = Object.keys(entry.stringSets);
|
|
5497
|
+
if (!entry.replace && touchedFields.length === 0 && touchedSets.length === 0) {
|
|
5498
|
+
return;
|
|
5499
|
+
}
|
|
5500
|
+
if (entry.replace) {
|
|
5501
|
+
sql.exec(DELETE_ALL_MEMBERS, modelName, id);
|
|
5502
|
+
}
|
|
5503
|
+
const patch = { ...entry.fields, id };
|
|
5504
|
+
for (const [field, members] of Object.entries(entry.stringSets)) {
|
|
5505
|
+
for (const [member, present] of Object.entries(members)) {
|
|
5506
|
+
if (present) sql.exec(INSERT_MEMBER, id, modelName, field, member);
|
|
5507
|
+
else sql.exec(DELETE_MEMBER, modelName, id, field, member);
|
|
5508
|
+
}
|
|
5509
|
+
const rows = Array.from(sql.exec(SELECT_MEMBERS, modelName, id, field));
|
|
5510
|
+
patch[field] = rows.map((row) => row.value);
|
|
5511
|
+
}
|
|
5512
|
+
const patchJson = JSON.stringify(patch);
|
|
5513
|
+
sql.exec(
|
|
5514
|
+
entry.replace ? REPLACE_UPSERT : MERGE_UPSERT,
|
|
5515
|
+
id,
|
|
5516
|
+
modelName,
|
|
5517
|
+
patchJson,
|
|
5518
|
+
patchJson
|
|
5519
|
+
);
|
|
5520
|
+
}
|
|
5521
|
+
|
|
5522
|
+
// src/utils/snapshotChunks.ts
|
|
5523
|
+
var SnapshotChunkIntegrityError = class extends Error {
|
|
5524
|
+
constructor(key, reason) {
|
|
5525
|
+
super(`Snapshot chunk ${key} does not match its manifest entry: ${reason}`);
|
|
5526
|
+
this.key = key;
|
|
5527
|
+
this.name = "SnapshotChunkIntegrityError";
|
|
5528
|
+
}
|
|
5529
|
+
};
|
|
5530
|
+
var SnapshotRowFormatError = class extends Error {
|
|
5531
|
+
constructor(model, id) {
|
|
5532
|
+
super(
|
|
5533
|
+
`Record ${model}/${id} cannot be written to a snapshot chunk: its id or data contains a newline or tab, which the line format reserves`
|
|
5534
|
+
);
|
|
5535
|
+
this.name = "SnapshotRowFormatError";
|
|
5536
|
+
}
|
|
5537
|
+
};
|
|
5538
|
+
function snapshotStringSetFields(manifest, model) {
|
|
5539
|
+
const declared = manifest.schema?.[model]?.stringSetFields;
|
|
5540
|
+
return new Set(Array.isArray(declared) ? declared.map(String) : []);
|
|
5541
|
+
}
|
|
5542
|
+
function snapshotDeclaredSchema(manifest, model) {
|
|
5543
|
+
const declared = manifest.schema?.[model] ?? {};
|
|
5544
|
+
const list = (value) => Array.isArray(value) ? value : [];
|
|
5545
|
+
const declaration = declared.declaration && typeof declared.declaration === "object" ? {
|
|
5546
|
+
fields: declared.declaration.fields ?? {},
|
|
5547
|
+
constraints: declared.declaration.constraints ?? {}
|
|
5548
|
+
} : void 0;
|
|
5549
|
+
return {
|
|
5550
|
+
...declaration ? { declaration } : {},
|
|
5551
|
+
stringSetFields: list(declared.stringSetFields).map(String),
|
|
5552
|
+
uniqueConstraints: list(declared.uniqueConstraints).filter(
|
|
5553
|
+
(constraint) => constraint?.name && Array.isArray(constraint.fields) && constraint.fields.length > 0
|
|
5554
|
+
).map((constraint) => ({
|
|
5555
|
+
name: String(constraint.name),
|
|
5556
|
+
fields: constraint.fields.map(String)
|
|
5557
|
+
})),
|
|
5558
|
+
indexedFields: list(declared.indexedFields).filter((index) => index?.field).map((index) => ({
|
|
5559
|
+
field: String(index.field),
|
|
5560
|
+
type: String(index.type || "string"),
|
|
5561
|
+
unique: !!index.unique
|
|
5562
|
+
}))
|
|
5563
|
+
};
|
|
5564
|
+
}
|
|
5565
|
+
function snapshotRowAsOverlayEntry(id, data, stringSetFields) {
|
|
5566
|
+
const fields = {};
|
|
5567
|
+
const stringSets = {};
|
|
5568
|
+
for (const [field, value] of Object.entries(data)) {
|
|
5569
|
+
if (field === "id") continue;
|
|
5570
|
+
if (stringSetFields.has(field) && Array.isArray(value)) {
|
|
5571
|
+
const members = {};
|
|
5572
|
+
for (const member of value) members[String(member)] = true;
|
|
5573
|
+
stringSets[field] = members;
|
|
5574
|
+
continue;
|
|
5575
|
+
}
|
|
5576
|
+
fields[field] = value;
|
|
5577
|
+
}
|
|
5578
|
+
return { id, fields, stringSets, replace: true, deleted: false };
|
|
5579
|
+
}
|
|
5580
|
+
var encoder = new TextEncoder();
|
|
5581
|
+
var decoder = new TextDecoder();
|
|
5582
|
+
function assertLineSafe(row) {
|
|
5583
|
+
if (/[\n\r\t]/.test(row._id) || /[\n\r\t]/.test(row._data)) {
|
|
5584
|
+
throw new SnapshotRowFormatError(row._type, row._id);
|
|
5585
|
+
}
|
|
5586
|
+
}
|
|
5587
|
+
function snapshotChunkLines(rows) {
|
|
5588
|
+
let body = "";
|
|
5589
|
+
for (const row of rows) {
|
|
5590
|
+
assertLineSafe(row);
|
|
5591
|
+
body += `${row._id} ${row._data}
|
|
5592
|
+
`;
|
|
5593
|
+
}
|
|
5594
|
+
return body;
|
|
5595
|
+
}
|
|
5596
|
+
async function gzip(bytes) {
|
|
5597
|
+
return await collect(
|
|
5598
|
+
new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip"))
|
|
5599
|
+
);
|
|
5600
|
+
}
|
|
5601
|
+
async function gunzip(bytes) {
|
|
5602
|
+
return await collect(
|
|
5603
|
+
new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"))
|
|
5604
|
+
);
|
|
5605
|
+
}
|
|
5606
|
+
async function collect(stream) {
|
|
5607
|
+
const parts = [];
|
|
5608
|
+
let total = 0;
|
|
5609
|
+
const reader = stream.getReader();
|
|
5610
|
+
for (; ; ) {
|
|
5611
|
+
const { done, value } = await reader.read();
|
|
5612
|
+
if (done) break;
|
|
5613
|
+
parts.push(value);
|
|
5614
|
+
total += value.byteLength;
|
|
5615
|
+
}
|
|
5616
|
+
const out = new Uint8Array(total);
|
|
5617
|
+
let at = 0;
|
|
5618
|
+
for (const part of parts) {
|
|
5619
|
+
out.set(part, at);
|
|
5620
|
+
at += part.byteLength;
|
|
5621
|
+
}
|
|
5622
|
+
return out;
|
|
5623
|
+
}
|
|
5624
|
+
async function sha256Hex(bytes) {
|
|
5625
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
5626
|
+
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
5627
|
+
}
|
|
5628
|
+
async function encodeSnapshotChunk(input) {
|
|
5629
|
+
const lines = encoder.encode(snapshotChunkLines(input.rows));
|
|
5630
|
+
const body = await gzip(lines);
|
|
5631
|
+
return {
|
|
5632
|
+
body,
|
|
5633
|
+
entry: {
|
|
5634
|
+
key: input.key,
|
|
5635
|
+
model: input.model,
|
|
5636
|
+
bytes: body.byteLength,
|
|
5637
|
+
rawBytes: lines.byteLength,
|
|
5638
|
+
rows: input.rows.length,
|
|
5639
|
+
firstId: input.rows.length > 0 ? input.rows[0]._id : "",
|
|
5640
|
+
lastId: input.rows.length > 0 ? input.rows[input.rows.length - 1]._id : "",
|
|
5641
|
+
sha256: await sha256Hex(body)
|
|
5642
|
+
}
|
|
5643
|
+
};
|
|
5644
|
+
}
|
|
5645
|
+
async function readSnapshotChunk(body, descriptor) {
|
|
5646
|
+
const entry = "sha256" in descriptor ? descriptor : null;
|
|
5647
|
+
if (entry) {
|
|
5648
|
+
if (body.byteLength !== entry.bytes) {
|
|
5649
|
+
throw new SnapshotChunkIntegrityError(
|
|
5650
|
+
entry.key,
|
|
5651
|
+
`expected ${entry.bytes} bytes, got ${body.byteLength}`
|
|
5652
|
+
);
|
|
5653
|
+
}
|
|
5654
|
+
const digest = await sha256Hex(body);
|
|
5655
|
+
if (digest !== entry.sha256) {
|
|
5656
|
+
throw new SnapshotChunkIntegrityError(
|
|
5657
|
+
entry.key,
|
|
5658
|
+
`expected sha256 ${entry.sha256}, got ${digest}`
|
|
5659
|
+
);
|
|
5660
|
+
}
|
|
5661
|
+
}
|
|
5662
|
+
const text = decoder.decode(await gunzip(body));
|
|
5663
|
+
const rows = [];
|
|
5664
|
+
for (const line of text.split("\n")) {
|
|
5665
|
+
if (line.length === 0) continue;
|
|
5666
|
+
const tab = line.indexOf(" ");
|
|
5667
|
+
if (tab < 0) {
|
|
5668
|
+
throw new SnapshotChunkIntegrityError(
|
|
5669
|
+
entry?.key ?? descriptor.model,
|
|
5670
|
+
"a line carries no id/data separator"
|
|
5671
|
+
);
|
|
5672
|
+
}
|
|
5673
|
+
rows.push({
|
|
5674
|
+
_type: descriptor.model,
|
|
5675
|
+
_id: line.slice(0, tab),
|
|
5676
|
+
_data: line.slice(tab + 1)
|
|
5677
|
+
});
|
|
5678
|
+
}
|
|
5679
|
+
if (entry && rows.length !== entry.rows) {
|
|
5680
|
+
throw new SnapshotChunkIntegrityError(
|
|
5681
|
+
entry.key,
|
|
5682
|
+
`expected ${entry.rows} rows, got ${rows.length}`
|
|
5683
|
+
);
|
|
5684
|
+
}
|
|
5685
|
+
return rows;
|
|
5686
|
+
}
|
|
4877
5687
|
export {
|
|
5688
|
+
DEFAULT_OVERLAY_TABLES,
|
|
4878
5689
|
DurableObjectEngine,
|
|
5690
|
+
Format2CompositeFieldError,
|
|
4879
5691
|
JsonQueryTranslator,
|
|
4880
5692
|
JsonSchemaDDL,
|
|
5693
|
+
OVERLAY_KEY_SEPARATOR,
|
|
5694
|
+
OVERLAY_MARKER_DELETED,
|
|
5695
|
+
OVERLAY_MARKER_REPLACE,
|
|
4881
5696
|
PROJECTED_JSON_ALIAS_PREFIX,
|
|
5697
|
+
SnapshotChunkIntegrityError,
|
|
5698
|
+
SnapshotRowFormatError,
|
|
5699
|
+
applyOverlayMutation,
|
|
5700
|
+
assertNoFormat2CompositeFields,
|
|
4882
5701
|
buildSafeAlias,
|
|
4883
5702
|
checkAutoStampsReservedFields,
|
|
4884
5703
|
checkReservedFieldName,
|
|
4885
5704
|
clearMetaSyncCache,
|
|
5705
|
+
completeOverlayEntries,
|
|
4886
5706
|
createDatabaseDO,
|
|
4887
5707
|
createDocumentDO,
|
|
5708
|
+
decodeOverlaySegment,
|
|
4888
5709
|
deterministicIdentifierHash,
|
|
5710
|
+
discoverDeclaredModel,
|
|
4889
5711
|
discoverModelNames,
|
|
4890
5712
|
discoverSchema,
|
|
5713
|
+
encodeOverlayMutation,
|
|
5714
|
+
encodeOverlaySegment,
|
|
5715
|
+
encodeSnapshotChunk,
|
|
5716
|
+
format2StringSetMembers,
|
|
5717
|
+
groupOverlayEntries,
|
|
4891
5718
|
handleRequest,
|
|
4892
5719
|
inferFieldType,
|
|
5720
|
+
isFormat2StringSetYMap,
|
|
4893
5721
|
loadSchemaFromTomlString,
|
|
5722
|
+
materializeOverlayRecord,
|
|
5723
|
+
overlayFieldKey,
|
|
5724
|
+
overlayMarkerKey,
|
|
5725
|
+
overlayMemberKey,
|
|
5726
|
+
parseOverlayKey,
|
|
4894
5727
|
parseRecordRow,
|
|
5728
|
+
projectOverlayEntry,
|
|
4895
5729
|
projectedJsonAlias,
|
|
5730
|
+
readOverlayRecord,
|
|
5731
|
+
readSnapshotChunk,
|
|
4896
5732
|
registerFunctionDefault,
|
|
4897
5733
|
schemaToToml,
|
|
5734
|
+
snapshotChunkLines,
|
|
5735
|
+
snapshotDeclaredSchema,
|
|
5736
|
+
snapshotRowAsOverlayEntry,
|
|
5737
|
+
snapshotStringSetFields,
|
|
4898
5738
|
syncInferredMeta,
|
|
4899
5739
|
syncModelMeta
|
|
4900
5740
|
};
|