@pixerate/editor 0.277.0 → 0.279.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.
@@ -11892,6 +11892,141 @@ var isViewport = (value) => {
11892
11892
  const v = value;
11893
11893
  return !!v && typeof v === "object" && [v.x, v.y, v.zoom].every((n3) => typeof n3 === "number" && Number.isFinite(n3)) && v.zoom > 0;
11894
11894
  };
11895
+ function sanitizeCanvasDocument(raw, options = {}) {
11896
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
11897
+ return { nodes: [], edges: [] };
11898
+ }
11899
+ const doc = raw;
11900
+ const keys = omitKeys(options);
11901
+ const rawNodes = Array.isArray(doc.nodes) ? doc.nodes : [];
11902
+ const rawEdges = Array.isArray(doc.edges) ? doc.edges : [];
11903
+ const nodeMap = /* @__PURE__ */ new Map();
11904
+ for (const candidate of rawNodes) {
11905
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue;
11906
+ const item = candidate;
11907
+ if (typeof item.id !== "string" || item.id.length === 0) continue;
11908
+ const pos = item.position;
11909
+ const position = {
11910
+ x: typeof pos?.x === "number" && Number.isFinite(pos.x) ? pos.x : 0,
11911
+ y: typeof pos?.y === "number" && Number.isFinite(pos.y) ? pos.y : 0
11912
+ };
11913
+ const data = item.data && typeof item.data === "object" && !Array.isArray(item.data) ? { ...item.data } : {};
11914
+ const cleaned = omit({ ...item, position, data }, keys.node);
11915
+ nodeMap.set(item.id, options.normalizeNode ? options.normalizeNode(cleaned) : cleaned);
11916
+ }
11917
+ const hasCycle = (nodeId, parentId) => {
11918
+ let cur = parentId;
11919
+ const seen = /* @__PURE__ */ new Set([nodeId]);
11920
+ while (cur) {
11921
+ if (seen.has(cur)) return true;
11922
+ seen.add(cur);
11923
+ cur = nodeMap.get(cur)?.parentId;
11924
+ }
11925
+ return false;
11926
+ };
11927
+ const sanitizedNodes = [];
11928
+ for (const node of nodeMap.values()) {
11929
+ if (node.parentId !== void 0 && (typeof node.parentId !== "string" || !nodeMap.has(node.parentId) || hasCycle(node.id, node.parentId))) {
11930
+ const copy = { ...node };
11931
+ delete copy.parentId;
11932
+ delete copy.extent;
11933
+ nodeMap.set(node.id, copy);
11934
+ sanitizedNodes.push(copy);
11935
+ } else {
11936
+ sanitizedNodes.push(node);
11937
+ }
11938
+ }
11939
+ const orderedNodes = [];
11940
+ const placedIds = /* @__PURE__ */ new Set();
11941
+ const byId = new Map(sanitizedNodes.map((n3) => [n3.id, n3]));
11942
+ const place2 = (node) => {
11943
+ if (placedIds.has(node.id)) return;
11944
+ if (node.parentId && byId.has(node.parentId)) {
11945
+ place2(byId.get(node.parentId));
11946
+ }
11947
+ placedIds.add(node.id);
11948
+ orderedNodes.push(node);
11949
+ };
11950
+ for (const node of sanitizedNodes) place2(node);
11951
+ const edgeMap = /* @__PURE__ */ new Map();
11952
+ for (const candidate of rawEdges) {
11953
+ if (!isValidCanvasEdge(candidate)) continue;
11954
+ if (!placedIds.has(candidate.source) || !placedIds.has(candidate.target)) continue;
11955
+ edgeMap.set(candidate.id, omit({ ...candidate }, keys.edge));
11956
+ }
11957
+ const extraEntries = Object.entries(doc).filter(
11958
+ ([k, v]) => k !== "nodes" && k !== "edges" && k !== "scenes" && k !== "viewport" && v !== void 0
11959
+ );
11960
+ return {
11961
+ ...Object.fromEntries(extraEntries),
11962
+ nodes: orderedNodes,
11963
+ edges: [...edgeMap.values()],
11964
+ ...Array.isArray(doc.scenes) ? { scenes: doc.scenes } : {},
11965
+ ...isViewport(doc.viewport) ? { viewport: { ...doc.viewport } } : {}
11966
+ };
11967
+ }
11968
+ function calculateGraphDifferences(currentState, baselineState, options) {
11969
+ const currentNodes = currentState.nodes ?? [];
11970
+ const currentEdges = currentState.edges ?? [];
11971
+ const baselineNodes = baselineState.nodes ?? [];
11972
+ const baselineEdges = baselineState.edges ?? [];
11973
+ const keys = omitKeys(options);
11974
+ const baselineNodeMap = new Map(baselineNodes.map((n3) => [n3.id, n3]));
11975
+ const baselineEdgeMap = new Map(baselineEdges.map((e) => [e.id, e]));
11976
+ const currentNodeMap = new Map(currentNodes.map((n3) => [n3.id, n3]));
11977
+ const currentEdgeMap = new Map(currentEdges.map((e) => [e.id, e]));
11978
+ const removedNodes = baselineNodes.filter((oldNode) => !currentNodeMap.has(oldNode.id));
11979
+ const removedEdges = baselineEdges.filter((oldEdge) => !currentEdgeMap.has(oldEdge.id));
11980
+ const changedNodes = currentNodes.filter((newNode) => {
11981
+ const oldNode = baselineNodeMap.get(newNode.id);
11982
+ if (!oldNode) return true;
11983
+ return JSON.stringify(omit(newNode, keys.node)) !== JSON.stringify(omit(oldNode, keys.node));
11984
+ });
11985
+ const changedEdges = currentEdges.filter((newEdge) => {
11986
+ const oldEdge = baselineEdgeMap.get(newEdge.id);
11987
+ if (!oldEdge) return true;
11988
+ return JSON.stringify(omit(newEdge, keys.edge)) !== JSON.stringify(omit(oldEdge, keys.edge));
11989
+ });
11990
+ return { changedNodes, changedEdges, removedNodes, removedEdges };
11991
+ }
11992
+ function applyGraphDifferences(state, diff) {
11993
+ const removedNodeIds = new Set((diff.removedNodes ?? []).map((n3) => n3.id));
11994
+ const removedEdgeIds = new Set((diff.removedEdges ?? []).map((e) => e.id));
11995
+ const changedNodeMap = new Map((diff.changedNodes ?? []).map((n3) => [n3.id, n3]));
11996
+ const changedEdgeMap = new Map((diff.changedEdges ?? []).map((e) => [e.id, e]));
11997
+ const existingNodeIds = /* @__PURE__ */ new Set();
11998
+ const nextNodes = state.nodes.filter((n3) => !removedNodeIds.has(n3.id)).map((n3) => {
11999
+ existingNodeIds.add(n3.id);
12000
+ const updated = changedNodeMap.get(n3.id);
12001
+ if (!updated) return n3;
12002
+ return {
12003
+ ...updated,
12004
+ ...n3.selected !== void 0 ? { selected: n3.selected } : {},
12005
+ ...n3.measured !== void 0 && updated.measured === void 0 ? { measured: n3.measured } : {}
12006
+ };
12007
+ });
12008
+ for (const [id, node] of changedNodeMap) {
12009
+ if (!existingNodeIds.has(id) && !removedNodeIds.has(id)) {
12010
+ nextNodes.push({ ...node, selected: false });
12011
+ }
12012
+ }
12013
+ const existingEdgeIds = /* @__PURE__ */ new Set();
12014
+ const nextEdges = state.edges.filter((e) => !removedEdgeIds.has(e.id)).map((e) => {
12015
+ existingEdgeIds.add(e.id);
12016
+ const updated = changedEdgeMap.get(e.id);
12017
+ if (!updated) return e;
12018
+ return {
12019
+ ...updated,
12020
+ ...e.selected !== void 0 ? { selected: e.selected } : {}
12021
+ };
12022
+ });
12023
+ for (const [id, edge] of changedEdgeMap) {
12024
+ if (!existingEdgeIds.has(id) && !removedEdgeIds.has(id)) {
12025
+ nextEdges.push({ ...edge, selected: false });
12026
+ }
12027
+ }
12028
+ return { nodes: nextNodes, edges: nextEdges };
12029
+ }
11895
12030
  function checkCanvasDocument(document2) {
11896
12031
  const hint = "A canvas document is { nodes: [{ id, position: { x, y }, data }], edges: [{ id, source, target }], scenes?, viewport? } as get_canvas_document returns it.";
11897
12032
  const value = document2;
@@ -11919,9 +12054,16 @@ function checkCanvasDocument(document2) {
11919
12054
  if (value.viewport !== void 0 && !isViewport(value.viewport)) throw new Error(`viewport must be { x, y, zoom } with finite numbers and a zoom above 0. ${hint}`);
11920
12055
  }
11921
12056
  function createCanvasEditorDocument(options) {
11922
- const { history, scenes: scenes2 } = options;
12057
+ const { history, scenes: scenes2, extras } = options;
11923
12058
  const keys = omitKeys(options);
12059
+ const snapshotExtras = () => {
12060
+ if (!extras) return {};
12061
+ const raw = extras.get();
12062
+ if (!raw || typeof raw !== "object") return {};
12063
+ return Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== void 0));
12064
+ };
11924
12065
  const snapshot = () => ({
12066
+ ...snapshotExtras(),
11925
12067
  nodes: options.getNodes().map((n3) => omit(n3, keys.node)),
11926
12068
  edges: options.getEdges().map((e) => omit(e, keys.edge)),
11927
12069
  ...scenes2 ? { scenes: scenes2.toJSON().scenes } : {},
@@ -11932,6 +12074,7 @@ function createCanvasEditorDocument(options) {
11932
12074
  options.setEdges(doc.edges.map((e) => ({ ...e })));
11933
12075
  if (scenes2) scenes2.load(doc.scenes ?? []);
11934
12076
  if (doc.viewport) options.setViewport?.({ ...doc.viewport });
12077
+ extras?.load?.(doc);
11935
12078
  };
11936
12079
  const check = (document2) => {
11937
12080
  checkCanvasDocument(document2);
@@ -11963,6 +12106,7 @@ function createCanvasEditorDocument(options) {
11963
12106
  subscribe: (listener) => {
11964
12107
  const offs = [history.subscribe(() => listener())];
11965
12108
  if (scenes2) offs.push(scenes2.subscribe(() => listener()));
12109
+ if (extras?.subscribe) offs.push(extras.subscribe(() => listener()));
11966
12110
  if (options.subscribe) offs.push(options.subscribe(listener));
11967
12111
  return () => offs.forEach((off) => off());
11968
12112
  },
@@ -12895,6 +13039,7 @@ export {
12895
13039
  applyAnimation,
12896
13040
  applyAnimationOverrides,
12897
13041
  applyConstraints,
13042
+ applyGraphDifferences,
12898
13043
  applyNodeUpdates,
12899
13044
  applyShapeCombination,
12900
13045
  applyShapeReplacement,
@@ -12921,6 +13066,7 @@ export {
12921
13066
  calculateCurvedPath,
12922
13067
  calculateDagreReflowDisplacement,
12923
13068
  calculateDirectionalDisplacement,
13069
+ calculateGraphDifferences,
12924
13070
  calculateReflowDisplacement,
12925
13071
  canCombineShapeNodes,
12926
13072
  canOffsetShapeNodes,
@@ -13273,6 +13419,7 @@ export {
13273
13419
  runCanvasNodeEffect,
13274
13420
  runMultiNodeTransition,
13275
13421
  sampleAnimationFrames,
13422
+ sanitizeCanvasDocument,
13276
13423
  scaleKeyframes,
13277
13424
  sceneColor,
13278
13425
  segmentBounds,
@@ -6,7 +6,7 @@ require('../chunk-QEUI6OGE.cjs');
6
6
 
7
7
 
8
8
  var _chunkKIJIONZFcjs = require('../chunk-KIJIONZF.cjs');
9
- require('../chunk-T2HUQBRC.cjs');
9
+ require('../chunk-DK33HLA2.cjs');
10
10
 
11
11
 
12
12
 
@@ -6,7 +6,7 @@ import {
6
6
  CommandRegistry,
7
7
  createCommandToolProvider
8
8
  } from "../chunk-HAEB3MZD.js";
9
- import "../chunk-JV7DKLMX.js";
9
+ import "../chunk-KBH6CM3U.js";
10
10
  import {
11
11
  CATEGORY_REF,
12
12
  CHART_UPDATE_PROPERTIES,
@@ -473,6 +473,10 @@ function createAutosaveController(options) {
473
473
  return rev;
474
474
  };
475
475
  const docName = () => typeof options.name === "function" ? options.name() : options.name;
476
+ const readBaseVersion = () => {
477
+ const v = typeof options.baseVersion === "function" ? options.baseVersion() : options.baseVersion;
478
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
479
+ };
476
480
  const run = (action, rev) => {
477
481
  if (action.type === "writeSnapshot") {
478
482
  setInfo({ status: "saving", nextAttemptAt: null });
@@ -482,11 +486,13 @@ function createAutosaveController(options) {
482
486
  try {
483
487
  const text = serialize(getSnapshot());
484
488
  await storage.set(key, text);
489
+ const baseVersion = readBaseVersion();
485
490
  const meta = {
486
491
  dirty: true,
487
492
  revision: action.revision,
488
493
  time: wallClock(),
489
- name: docName()
494
+ name: docName(),
495
+ ...baseVersion !== void 0 ? { baseVersion } : {}
490
496
  };
491
497
  await storage.set(metaKey, JSON.stringify(meta));
492
498
  ok = true;
@@ -607,7 +613,7 @@ function createAutosaveController(options) {
607
613
  tick();
608
614
  await whenIdle();
609
615
  },
610
- async checkRecovery() {
616
+ async checkRecovery(checkOptions) {
611
617
  if (policy.ownsSnapshot) return null;
612
618
  let meta;
613
619
  try {
@@ -618,6 +624,12 @@ function createAutosaveController(options) {
618
624
  return null;
619
625
  }
620
626
  if (!meta || meta.dirty !== true) return null;
627
+ const required = _nullishCoalesce(_optionalChain([checkOptions, 'optionalAccess', _6 => _6.minimumBaseVersion]), () => ( readBaseVersion()));
628
+ if (required !== void 0 && (typeof meta.baseVersion === "number" ? meta.baseVersion : 0) < required) {
629
+ await storage.remove(metaKey).catch(() => void 0);
630
+ await storage.remove(key).catch(() => void 0);
631
+ return null;
632
+ }
621
633
  const text = await storage.get(key).catch(() => null);
622
634
  if (text === null) return null;
623
635
  try {
@@ -726,10 +738,36 @@ function createEditorAutosave(doc, options) {
726
738
  savedRevision: revisions.savedRevision
727
739
  });
728
740
  const unsubscribe = revisions.subscribe(() => controller.notify());
741
+ const retireRecovery = async () => {
742
+ await controller.discardRecovery();
743
+ controller.ready();
744
+ await collect();
745
+ };
729
746
  return {
730
747
  controller,
731
748
  revisions,
732
749
  checkRecovery: () => controller.checkRecovery(),
750
+ async recoverIfNewer(minimumBaseVersion) {
751
+ const recovery = await controller.checkRecovery(
752
+ minimumBaseVersion !== void 0 ? { minimumBaseVersion } : void 0
753
+ );
754
+ if (!recovery) {
755
+ controller.ready();
756
+ return null;
757
+ }
758
+ if (!recovery.snapshot) {
759
+ await retireRecovery();
760
+ return null;
761
+ }
762
+ try {
763
+ const report = doc.loadDocument(recovery.snapshot, { history: "reset" });
764
+ controller.ready();
765
+ return report;
766
+ } catch (e7) {
767
+ await retireRecovery();
768
+ return null;
769
+ }
770
+ },
733
771
  restore(recovery) {
734
772
  if (!recovery.snapshot) throw _nullishCoalesce(recovery.error, () => ( new Error("The recovered snapshot could not be read.")));
735
773
  const report = doc.loadDocument(recovery.snapshot, { history: "reset" });
@@ -737,9 +775,7 @@ function createEditorAutosave(doc, options) {
737
775
  return report;
738
776
  },
739
777
  async discard() {
740
- await controller.discardRecovery();
741
- controller.ready();
742
- await collect();
778
+ await retireRecovery();
743
779
  },
744
780
  async markClean() {
745
781
  revisions.markSaved();
@@ -754,6 +790,289 @@ function createEditorAutosave(doc, options) {
754
790
  };
755
791
  }
756
792
 
793
+ // src/persistence/remoteSync.ts
794
+ var EditorRemoteConflictError = class extends Error {
795
+ constructor(serverVersion) {
796
+ super(
797
+ serverVersion === void 0 ? "The document changed on the server since it was loaded; local edits were not saved." : `The document is at version ${serverVersion} on the server; local edits were not saved.`
798
+ );
799
+ this.serverVersion = serverVersion;
800
+ this.name = "EditorRemoteConflictError";
801
+ }
802
+
803
+ };
804
+ var cloneSnapshot = (value) => {
805
+ try {
806
+ return JSON.parse(JSON.stringify(value));
807
+ } catch (e8) {
808
+ return value;
809
+ }
810
+ };
811
+ function createEditorRemoteSync(doc, options) {
812
+ const debounceMs = _nullishCoalesce(options.debounceMs, () => ( 500));
813
+ const now = _nullishCoalesce(options.now, () => ( Date.now));
814
+ let localVersion = _nullishCoalesce(options.initialVersion, () => ( 0));
815
+ let confirmedVersion = localVersion;
816
+ let localSequence = 0;
817
+ let savedSequence = 0;
818
+ let baselineSnapshot = cloneSnapshot(doc.getDocument());
819
+ let savedSnapshot = baselineSnapshot;
820
+ let state = "idle";
821
+ let lastSavedAt = null;
822
+ let lastError = void 0;
823
+ let isApplyingRemote = false;
824
+ let conflictRetries = 0;
825
+ let destroyed = false;
826
+ let debounceTimer = null;
827
+ let inFlightPromise = null;
828
+ const listeners = /* @__PURE__ */ new Set();
829
+ const getStatus = () => ({
830
+ status: state,
831
+ version: localVersion,
832
+ savedVersion: confirmedVersion,
833
+ dirty: localSequence > savedSequence,
834
+ lastSavedAt,
835
+ ...lastError !== void 0 ? { error: lastError } : {}
836
+ });
837
+ const emit = () => {
838
+ const currentStatus = getStatus();
839
+ listeners.forEach((listener) => {
840
+ try {
841
+ listener(currentStatus);
842
+ } catch (error) {
843
+ console.error("[remoteSync] Error in status listener:", error);
844
+ }
845
+ });
846
+ };
847
+ const clearTimer = () => {
848
+ if (debounceTimer !== null) {
849
+ clearTimeout(debounceTimer);
850
+ debounceTimer = null;
851
+ }
852
+ };
853
+ const hasChanged = (current, baseline) => {
854
+ if (options.diff) {
855
+ const diff = options.diff(current, baseline);
856
+ const empty = options.isEmptyDiff ? options.isEmptyDiff(diff, current, baseline) : JSON.stringify(current) === JSON.stringify(baseline);
857
+ return { changed: !empty, diff };
858
+ }
859
+ return { changed: JSON.stringify(current) !== JSON.stringify(baseline) };
860
+ };
861
+ const suppressed = (fn) => {
862
+ const wasApplying = isApplyingRemote;
863
+ isApplyingRemote = true;
864
+ try {
865
+ return fn();
866
+ } finally {
867
+ isApplyingRemote = wasApplying;
868
+ }
869
+ };
870
+ const executeSave = async () => {
871
+ if (inFlightPromise) {
872
+ await inFlightPromise;
873
+ if (localSequence > savedSequence) {
874
+ return executeSave();
875
+ }
876
+ return true;
877
+ }
878
+ if (localSequence <= savedSequence) {
879
+ return true;
880
+ }
881
+ clearTimer();
882
+ const targetSequence = localSequence;
883
+ const snapshotToSave = cloneSnapshot(baselineSnapshot);
884
+ const diffToSave = options.diff ? options.diff(snapshotToSave, savedSnapshot) : void 0;
885
+ const versionToSave = Math.max(localVersion, confirmedVersion + 1);
886
+ localVersion = versionToSave;
887
+ state = "saving";
888
+ lastError = void 0;
889
+ emit();
890
+ const run = (async () => {
891
+ try {
892
+ const result = await options.save({
893
+ document: snapshotToSave,
894
+ version: versionToSave,
895
+ baseVersion: confirmedVersion,
896
+ diff: diffToSave
897
+ });
898
+ if (result && typeof result === "object" && result.conflict) {
899
+ const serverVersion = typeof result.version === "number" ? result.version : void 0;
900
+ if (!options.onConflict || conflictRetries >= (_nullishCoalesce(options.maxConflictRetries, () => ( 3)))) {
901
+ conflictRetries = 0;
902
+ throw new EditorRemoteConflictError(serverVersion);
903
+ }
904
+ conflictRetries++;
905
+ const resolution = await options.onConflict({
906
+ document: snapshotToSave,
907
+ base: savedSnapshot,
908
+ serverVersion,
909
+ apply: (fn) => suppressed(fn)
910
+ });
911
+ confirmedVersion = resolution.serverVersion;
912
+ localVersion = Math.max(localVersion, confirmedVersion);
913
+ if (resolution.serverDocument !== void 0) savedSnapshot = cloneSnapshot(resolution.serverDocument);
914
+ baselineSnapshot = cloneSnapshot(doc.getDocument());
915
+ localSequence++;
916
+ state = "pending";
917
+ emit();
918
+ return true;
919
+ }
920
+ conflictRetries = 0;
921
+ const returnedVersion = typeof result === "number" ? result : result && typeof result === "object" && typeof result.version === "number" ? result.version : versionToSave;
922
+ confirmedVersion = Math.max(confirmedVersion, versionToSave, returnedVersion);
923
+ if (returnedVersion > localVersion) {
924
+ localVersion = returnedVersion;
925
+ }
926
+ savedSequence = Math.max(savedSequence, targetSequence);
927
+ savedSnapshot = snapshotToSave;
928
+ lastSavedAt = now();
929
+ lastError = void 0;
930
+ if (localSequence <= savedSequence) {
931
+ state = "saved";
932
+ try {
933
+ await _optionalChain([options, 'access', _7 => _7.autosave, 'optionalAccess', _8 => _8.markClean, 'call', _9 => _9()]);
934
+ } catch (error) {
935
+ console.error("[remoteSync] autosave.markClean failed:", error);
936
+ }
937
+ } else {
938
+ state = "pending";
939
+ }
940
+ _optionalChain([options, 'access', _10 => _10.onSaved, 'optionalCall', _11 => _11({ document: snapshotToSave, version: confirmedVersion })]);
941
+ emit();
942
+ return true;
943
+ } catch (error) {
944
+ lastError = error;
945
+ state = "error";
946
+ _optionalChain([options, 'access', _12 => _12.onError, 'optionalCall', _13 => _13(error)]);
947
+ emit();
948
+ return false;
949
+ }
950
+ })();
951
+ inFlightPromise = run;
952
+ let ok;
953
+ try {
954
+ ok = await run;
955
+ } finally {
956
+ if (inFlightPromise === run) inFlightPromise = null;
957
+ }
958
+ if (ok && localSequence > savedSequence && debounceTimer === null) {
959
+ return executeSave();
960
+ }
961
+ return ok;
962
+ };
963
+ const scheduleSave = () => {
964
+ clearTimer();
965
+ if (debounceMs <= 0) {
966
+ void executeSave();
967
+ return;
968
+ }
969
+ debounceTimer = setTimeout(() => {
970
+ debounceTimer = null;
971
+ if (!destroyed) {
972
+ void executeSave();
973
+ }
974
+ }, debounceMs);
975
+ };
976
+ const notify = () => {
977
+ if (isApplyingRemote || destroyed) return false;
978
+ const current = cloneSnapshot(doc.getDocument());
979
+ const { changed, diff } = hasChanged(current, baselineSnapshot);
980
+ if (!changed) return false;
981
+ const previousBaseline = baselineSnapshot;
982
+ baselineSnapshot = current;
983
+ localSequence++;
984
+ localVersion = Math.max(localVersion, confirmedVersion) + 1;
985
+ if (state !== "saving") {
986
+ state = "pending";
987
+ }
988
+ emit();
989
+ _optionalChain([options, 'access', _14 => _14.onLocalChange, 'optionalCall', _15 => _15({
990
+ document: current,
991
+ baseline: previousBaseline,
992
+ diff,
993
+ version: localVersion
994
+ })]);
995
+ scheduleSave();
996
+ return true;
997
+ };
998
+ const flush = async () => {
999
+ clearTimer();
1000
+ notify();
1001
+ if (localSequence <= savedSequence && !inFlightPromise) {
1002
+ return true;
1003
+ }
1004
+ return executeSave();
1005
+ };
1006
+ const unsubscribeDoc = doc.subscribe(() => {
1007
+ notify();
1008
+ });
1009
+ return {
1010
+ version: () => localVersion,
1011
+ savedVersion: () => confirmedVersion,
1012
+ dirty: () => localSequence > savedSequence,
1013
+ status: getStatus,
1014
+ baseline: () => baselineSnapshot,
1015
+ notify,
1016
+ applyRemote(fn, remoteVersion) {
1017
+ const wasApplying = isApplyingRemote;
1018
+ const wasDirty = localSequence > savedSequence;
1019
+ isApplyingRemote = true;
1020
+ try {
1021
+ const result = fn();
1022
+ baselineSnapshot = cloneSnapshot(doc.getDocument());
1023
+ if (typeof remoteVersion === "number" && Number.isFinite(remoteVersion)) {
1024
+ confirmedVersion = Math.max(confirmedVersion, remoteVersion);
1025
+ localVersion = Math.max(localVersion, remoteVersion);
1026
+ }
1027
+ if (!wasDirty) {
1028
+ savedSequence = localSequence;
1029
+ savedSnapshot = baselineSnapshot;
1030
+ }
1031
+ emit();
1032
+ return result;
1033
+ } finally {
1034
+ isApplyingRemote = wasApplying;
1035
+ }
1036
+ },
1037
+ resetBaseline(remoteVersion) {
1038
+ clearTimer();
1039
+ baselineSnapshot = cloneSnapshot(doc.getDocument());
1040
+ savedSnapshot = baselineSnapshot;
1041
+ if (typeof remoteVersion === "number" && Number.isFinite(remoteVersion)) {
1042
+ localVersion = remoteVersion;
1043
+ confirmedVersion = remoteVersion;
1044
+ }
1045
+ savedSequence = localSequence;
1046
+ lastError = void 0;
1047
+ state = "idle";
1048
+ emit();
1049
+ },
1050
+ flush,
1051
+ async whenIdle() {
1052
+ while (debounceTimer !== null || inFlightPromise) {
1053
+ if (debounceTimer !== null) {
1054
+ await flush();
1055
+ } else if (inFlightPromise) {
1056
+ await inFlightPromise.catch(() => false);
1057
+ }
1058
+ }
1059
+ },
1060
+ subscribe(listener) {
1061
+ listeners.add(listener);
1062
+ listener(getStatus());
1063
+ return () => {
1064
+ listeners.delete(listener);
1065
+ };
1066
+ },
1067
+ destroy() {
1068
+ destroyed = true;
1069
+ clearTimer();
1070
+ unsubscribeDoc();
1071
+ listeners.clear();
1072
+ }
1073
+ };
1074
+ }
1075
+
757
1076
  // src/persistence/documentStore.ts
758
1077
  function slugifyDocumentName(name) {
759
1078
  const slug = name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
@@ -783,7 +1102,7 @@ function createEditorDocumentStore(options) {
783
1102
  if (data && Array.isArray(data.items)) {
784
1103
  items = data.items.filter((item) => item && typeof item.key === "string" && typeof item.kind === "string");
785
1104
  }
786
- } catch (e7) {
1105
+ } catch (e9) {
787
1106
  items = [];
788
1107
  }
789
1108
  }
@@ -892,7 +1211,7 @@ function createDocumentToolProvider(doc, options = {}) {
892
1211
  annotations: { title: `Get the ${noun} document`, ...READ },
893
1212
  handler: () => {
894
1213
  const document = doc.getDocument();
895
- const size = _nullishCoalesce(_optionalChain([JSON, 'access', _6 => _6.stringify, 'call', _7 => _7(document), 'optionalAccess', _8 => _8.length]), () => ( 0));
1214
+ const size = _nullishCoalesce(_optionalChain([JSON, 'access', _16 => _16.stringify, 'call', _17 => _17(document), 'optionalAccess', _18 => _18.length]), () => ( 0));
896
1215
  if (size > maxChars) {
897
1216
  throw new Error(`The ${noun} document is ${size} characters of JSON, over the ${maxChars} limit for this tool. Use the editor's read tools to look at parts of it.`);
898
1217
  }
@@ -959,7 +1278,7 @@ function createDocumentToolProvider(doc, options = {}) {
959
1278
  }),
960
1279
  annotations: { title: `Save the ${noun}`, ...OVERWRITE },
961
1280
  handler: async ({ name }) => {
962
- const entry = await s.save(doc, _nullishCoalesce(_nullishCoalesce(name, () => ( _optionalChain([options, 'access', _9 => _9.name, 'optionalCall', _10 => _10()]))), () => ( `Untitled ${noun}`)));
1281
+ const entry = await s.save(doc, _nullishCoalesce(_nullishCoalesce(name, () => ( _optionalChain([options, 'access', _19 => _19.name, 'optionalCall', _20 => _20()]))), () => ( `Untitled ${noun}`)));
963
1282
  return { key: entry.key, name: entry.name, savedAt: entry.savedAt, revision: doc.revision() };
964
1283
  }
965
1284
  },
@@ -1044,7 +1363,7 @@ function createDocumentToolProvider(doc, options = {}) {
1044
1363
  load,
1045
1364
  ...options.history === false ? [] : [undo, redo],
1046
1365
  ...store ? storeTools(store) : [],
1047
- ..._optionalChain([store, 'optionalAccess', _11 => _11.collectAssetGarbage]) && doc.assets ? assetTools(store) : []
1366
+ ..._optionalChain([store, 'optionalAccess', _21 => _21.collectAssetGarbage]) && doc.assets ? assetTools(store) : []
1048
1367
  ]
1049
1368
  };
1050
1369
  }
@@ -1070,4 +1389,6 @@ function createDocumentToolProvider(doc, options = {}) {
1070
1389
 
1071
1390
 
1072
1391
 
1073
- exports.exponentialBackoff = exponentialBackoff; exports.createRecoveryPolicy = createRecoveryPolicy; exports.StorageUnavailableError = StorageUnavailableError; exports.InjectedStorageError = InjectedStorageError; exports.withStorageFailures = withStorageFailures; exports.createMemoryStorage = createMemoryStorage; exports.isLocalStorageAvailable = isLocalStorageAvailable; exports.createLocalStorageAdapter = createLocalStorageAdapter; exports.isIndexedDbAvailable = isIndexedDbAvailable; exports.createIndexedDbAdapter = createIndexedDbAdapter; exports.isOpfsAvailable = isOpfsAvailable; exports.createOpfsAdapter = createOpfsAdapter; exports.recoveryMetaKey = recoveryMetaKey; exports.formatRecoveryMessage = formatRecoveryMessage; exports.createAutosaveController = createAutosaveController; exports.createRevisionTracker = createRevisionTracker; exports.createEditorAutosave = createEditorAutosave; exports.slugifyDocumentName = slugifyDocumentName; exports.createEditorDocumentStore = createEditorDocumentStore; exports.createDocumentToolProvider = createDocumentToolProvider;
1392
+
1393
+
1394
+ exports.exponentialBackoff = exponentialBackoff; exports.createRecoveryPolicy = createRecoveryPolicy; exports.StorageUnavailableError = StorageUnavailableError; exports.InjectedStorageError = InjectedStorageError; exports.withStorageFailures = withStorageFailures; exports.createMemoryStorage = createMemoryStorage; exports.isLocalStorageAvailable = isLocalStorageAvailable; exports.createLocalStorageAdapter = createLocalStorageAdapter; exports.isIndexedDbAvailable = isIndexedDbAvailable; exports.createIndexedDbAdapter = createIndexedDbAdapter; exports.isOpfsAvailable = isOpfsAvailable; exports.createOpfsAdapter = createOpfsAdapter; exports.recoveryMetaKey = recoveryMetaKey; exports.formatRecoveryMessage = formatRecoveryMessage; exports.createAutosaveController = createAutosaveController; exports.createRevisionTracker = createRevisionTracker; exports.createEditorAutosave = createEditorAutosave; exports.EditorRemoteConflictError = EditorRemoteConflictError; exports.createEditorRemoteSync = createEditorRemoteSync; exports.slugifyDocumentName = slugifyDocumentName; exports.createEditorDocumentStore = createEditorDocumentStore; exports.createDocumentToolProvider = createDocumentToolProvider;