@dabble/patches 0.5.6 → 0.5.8

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.
@@ -142,7 +142,10 @@ function breakTextOp(origChange, textOp, maxBytes, startRev, sizeCalculator) {
142
142
  testBatchOps.push({ retain: retainToPrefixCurrentPiece });
143
143
  }
144
144
  testBatchOps.push(op);
145
- const testBatchSize = getSizeForStorage({ ...origChange, ops: [{ ...textOp, value: testBatchOps }] }, sizeCalculator);
145
+ const testBatchSize = getSizeForStorage(
146
+ { ...origChange, ops: [{ ...textOp, value: testBatchOps }] },
147
+ sizeCalculator
148
+ );
146
149
  if (currentOpsForNextChangePiece.length > 0 && testBatchSize > maxBytes) {
147
150
  flushCurrentChangePiece();
148
151
  }
@@ -88,7 +88,13 @@ class PatchesDoc {
88
88
  * @returns The generated Change objects.
89
89
  */
90
90
  change(mutator) {
91
- const changes = makeChange(this._snapshot, mutator, this._changeMetadata, this._maxStorageBytes, this._sizeCalculator);
91
+ const changes = makeChange(
92
+ this._snapshot,
93
+ mutator,
94
+ this._changeMetadata,
95
+ this._maxStorageBytes,
96
+ this._sizeCalculator
97
+ );
92
98
  if (changes.length === 0) {
93
99
  return changes;
94
100
  }
@@ -11,6 +11,7 @@ import '../json-patch/JSONPatch.js';
11
11
  import '@dabble/delta';
12
12
  import '../json-patch/types.js';
13
13
  import './PatchesClient.js';
14
+ import '../utils/deferred.js';
14
15
  import '../client/PatchesDoc.js';
15
16
 
16
17
  interface PatchesSyncState {
@@ -53,6 +54,14 @@ declare class PatchesSync {
53
54
  docId?: string;
54
55
  }) => void>;
55
56
  constructor(patches: Patches, url: string, options?: PatchesSyncOptions | undefined);
57
+ /**
58
+ * Gets the URL of the WebSocket connection.
59
+ */
60
+ get url(): string;
61
+ /**
62
+ * Sets the URL of the WebSocket connection.
63
+ */
64
+ set url(url: string);
56
65
  /**
57
66
  * Gets the current sync state.
58
67
  */
@@ -50,6 +50,22 @@ class PatchesSync {
50
50
  patches.onUntrackDocs(this._handleDocsUntracked.bind(this));
51
51
  patches.onDeleteDoc(this._handleDocDeleted.bind(this));
52
52
  }
53
+ /**
54
+ * Gets the URL of the WebSocket connection.
55
+ */
56
+ get url() {
57
+ return this.ws.transport.url;
58
+ }
59
+ /**
60
+ * Sets the URL of the WebSocket connection.
61
+ */
62
+ set url(url) {
63
+ this.ws.transport.url = url;
64
+ if (this.state.connected) {
65
+ this.ws.disconnect();
66
+ this.ws.connect();
67
+ }
68
+ }
53
69
  /**
54
70
  * Gets the current sync state.
55
71
  */
@@ -26,5 +26,6 @@ import '../compression/index.js';
26
26
  import '../algorithms/shared/lz.js';
27
27
  import '../json-patch/types.js';
28
28
  import '../server/PatchesHistoryManager.js';
29
+ import '../utils/deferred.js';
29
30
  import '../json-patch/JSONPatch.js';
30
31
  import '@dabble/delta';
@@ -7,6 +7,7 @@ import '@dabble/delta';
7
7
  import '../../json-patch/types.js';
8
8
  import 'simple-peer';
9
9
  import '../websocket/WebSocketTransport.js';
10
+ import '../../utils/deferred.js';
10
11
 
11
12
  /**
12
13
  * Base type for awareness states, representing arbitrary structured data
@@ -6,6 +6,7 @@ import '../../types.js';
6
6
  import '../../json-patch/JSONPatch.js';
7
7
  import '@dabble/delta';
8
8
  import '../../json-patch/types.js';
9
+ import '../../utils/deferred.js';
9
10
 
10
11
  /**
11
12
  * WebRTC-based transport implementation that enables direct peer-to-peer communication.
@@ -8,3 +8,4 @@ import '@dabble/delta';
8
8
  import '../../json-patch/types.js';
9
9
  import 'simple-peer';
10
10
  import '../websocket/WebSocketTransport.js';
11
+ import '../../utils/deferred.js';
@@ -7,6 +7,7 @@ import '../../json-patch/JSONPatch.js';
7
7
  import '@dabble/delta';
8
8
  import '../../json-patch/types.js';
9
9
  import '../protocol/JSONRPCClient.js';
10
+ import '../../utils/deferred.js';
10
11
 
11
12
  /**
12
13
  * High-level client for the Patches real-time collaboration service.
@@ -1,4 +1,5 @@
1
- import { Signal } from '../../event-signal.js';
1
+ import { Unsubscriber, Signal } from '../../event-signal.js';
2
+ import { Deferred } from '../../utils/deferred.js';
2
3
  import { ClientTransport, ConnectionState } from '../protocol/types.js';
3
4
  import '../../types.js';
4
5
  import '../../json-patch/JSONPatch.js';
@@ -14,17 +15,17 @@ interface WebSocketOptions {
14
15
  * Includes automatic reconnection with exponential backoff.
15
16
  */
16
17
  declare class WebSocketTransport implements ClientTransport {
17
- private url;
18
- private wsOptions?;
19
- private _state;
20
- private ws;
21
- private reconnectTimer;
22
- private backoff;
23
- private connecting;
24
- private connectionDeferred;
25
- private onlineUnsubscriber;
18
+ url: string;
19
+ wsOptions?: WebSocketOptions | undefined;
20
+ protected _state: ConnectionState;
21
+ protected ws: WebSocket | null;
22
+ protected reconnectTimer: any;
23
+ protected backoff: number;
24
+ protected connecting: boolean;
25
+ protected connectionDeferred: Deferred | null;
26
+ protected onlineUnsubscriber: Unsubscriber | null;
26
27
  /** Flag representing the *intent* to be connected. It is set by `connect()` and cleared by `disconnect()`. */
27
- private shouldBeConnected;
28
+ protected shouldBeConnected: boolean;
28
29
  /**
29
30
  * Signal that emits when the connection state changes.
30
31
  * Subscribers will receive the new connection state as an argument.
@@ -72,17 +73,17 @@ declare class WebSocketTransport implements ClientTransport {
72
73
  /**
73
74
  * Schedules a reconnection attempt using exponential backoff.
74
75
  * The backoff time increases with each failed attempt, up to a maximum of 30 seconds.
75
- * @private
76
+ * @protected
76
77
  */
77
- private _scheduleReconnect;
78
+ protected _scheduleReconnect(): void;
78
79
  /**
79
80
  * Internal helper that adds (once) listeners for the browser's online/offline
80
81
  * events so we can automatically attempt to connect when the network comes
81
82
  * back and forcibly close when it goes away.
82
83
  */
83
- private _ensureOnlineOfflineListeners;
84
+ protected _ensureOnlineOfflineListeners(): void;
84
85
  /** Removes previously registered online/offline listeners (if any) */
85
- private _removeOnlineOfflineListeners;
86
+ protected _removeOnlineOfflineListeners(): void;
86
87
  }
87
88
 
88
89
  export { type WebSocketOptions, WebSocketTransport };
@@ -143,7 +143,7 @@ class WebSocketTransport {
143
143
  /**
144
144
  * Schedules a reconnection attempt using exponential backoff.
145
145
  * The backoff time increases with each failed attempt, up to a maximum of 30 seconds.
146
- * @private
146
+ * @protected
147
147
  */
148
148
  _scheduleReconnect() {
149
149
  if (!this.shouldBeConnected || onlineState.isOffline) {
@@ -0,0 +1,68 @@
1
+ import { JSX } from 'solid-js';
2
+ import { Patches } from '../client/Patches.js';
3
+ import { PatchesSync } from '../net/PatchesSync.js';
4
+ import '../event-signal.js';
5
+ import '../types.js';
6
+ import '../json-patch/JSONPatch.js';
7
+ import '@dabble/delta';
8
+ import '../json-patch/types.js';
9
+ import '../client/PatchesDoc.js';
10
+ import '../algorithms/shared/changeBatching.js';
11
+ import '../client/PatchesStore.js';
12
+ import '../net/protocol/types.js';
13
+ import '../net/protocol/JSONRPCClient.js';
14
+ import '../net/websocket/PatchesWebSocket.js';
15
+ import '../net/PatchesClient.js';
16
+ import '../net/websocket/WebSocketTransport.js';
17
+ import '../utils/deferred.js';
18
+
19
+ /**
20
+ * Context value containing Patches and optional PatchesSync instances.
21
+ */
22
+ interface PatchesContextValue {
23
+ patches: Patches;
24
+ sync?: PatchesSync;
25
+ }
26
+ /**
27
+ * Props for the PatchesProvider component.
28
+ */
29
+ interface PatchesProviderProps {
30
+ patches: Patches;
31
+ sync?: PatchesSync;
32
+ children: JSX.Element;
33
+ }
34
+ /**
35
+ * Provider component for making Patches and PatchesSync available to child components.
36
+ *
37
+ * @example
38
+ * ```tsx
39
+ * import { PatchesProvider } from '@dabble/patches/solid';
40
+ * import { Patches, InMemoryStore } from '@dabble/patches/client';
41
+ *
42
+ * const patches = new Patches({ store: new InMemoryStore() });
43
+ *
44
+ * <PatchesProvider patches={patches}>
45
+ * <App />
46
+ * </PatchesProvider>
47
+ * ```
48
+ */
49
+ declare function PatchesProvider(props: PatchesProviderProps): any;
50
+ /**
51
+ * Hook to access the Patches context.
52
+ *
53
+ * @throws Error if called outside of a PatchesProvider
54
+ * @returns PatchesContextValue containing patches and optional sync instances
55
+ *
56
+ * @example
57
+ * ```tsx
58
+ * import { usePatchesContext } from '@dabble/patches/solid';
59
+ *
60
+ * function MyComponent() {
61
+ * const { patches, sync } = usePatchesContext();
62
+ * // Use patches and sync...
63
+ * }
64
+ * ```
65
+ */
66
+ declare function usePatchesContext(): PatchesContextValue;
67
+
68
+ export { type PatchesContextValue, PatchesProvider, type PatchesProviderProps, usePatchesContext };
@@ -0,0 +1,20 @@
1
+ import "../chunk-IZ2YBCUP.js";
2
+ import { createContext, useContext } from "solid-js";
3
+ const PatchesContext = createContext();
4
+ function PatchesProvider(props) {
5
+ const value = { patches: props.patches, sync: props.sync };
6
+ return /* @__PURE__ */ React.createElement(PatchesContext.Provider, { value, children: props.children });
7
+ }
8
+ function usePatchesContext() {
9
+ const context = useContext(PatchesContext);
10
+ if (!context) {
11
+ throw new Error(
12
+ "usePatchesContext must be called within a PatchesProvider. Make sure your component is wrapped with <PatchesProvider>."
13
+ );
14
+ }
15
+ return context;
16
+ }
17
+ export {
18
+ PatchesProvider,
19
+ usePatchesContext
20
+ };
@@ -0,0 +1,88 @@
1
+ import { Patches } from '../client/Patches.js';
2
+ import { PatchesDoc } from '../client/PatchesDoc.js';
3
+ import '../event-signal.js';
4
+ import '../types.js';
5
+ import '../json-patch/JSONPatch.js';
6
+ import '@dabble/delta';
7
+ import '../json-patch/types.js';
8
+ import '../client/PatchesStore.js';
9
+ import '../algorithms/shared/changeBatching.js';
10
+
11
+ /**
12
+ * Reference counting manager for PatchesDoc instances.
13
+ *
14
+ * Tracks how many Solid components are using each document and only opens/closes
15
+ * documents when the reference count goes to/from zero.
16
+ *
17
+ * This prevents the footgun where multiple components open the same doc but the
18
+ * first one to unmount closes it for everyone else.
19
+ */
20
+ declare class DocManager {
21
+ private refCounts;
22
+ private pendingOps;
23
+ /**
24
+ * Opens a document with reference counting.
25
+ *
26
+ * - If this is the first reference, calls patches.openDoc()
27
+ * - If doc is already open, returns existing instance and increments count
28
+ * - Handles concurrent opens to the same doc safely
29
+ *
30
+ * @param patches - Patches instance
31
+ * @param docId - Document ID to open
32
+ * @returns Promise resolving to PatchesDoc instance
33
+ */
34
+ openDoc<T extends object>(patches: Patches, docId: string): Promise<PatchesDoc<T>>;
35
+ /**
36
+ * Closes a document with reference counting.
37
+ *
38
+ * - Decrements the reference count
39
+ * - Only calls patches.closeDoc() when count reaches zero
40
+ * - Safe to call even if doc was never opened
41
+ *
42
+ * @param patches - Patches instance
43
+ * @param docId - Document ID to close
44
+ */
45
+ closeDoc(patches: Patches, docId: string): Promise<void>;
46
+ /**
47
+ * Increments the reference count for a document without opening it.
48
+ *
49
+ * Used in explicit mode to track usage and prevent premature closes
50
+ * from autoClose mode.
51
+ *
52
+ * @param docId - Document ID
53
+ */
54
+ incrementRefCount(docId: string): void;
55
+ /**
56
+ * Decrements the reference count for a document without closing it.
57
+ *
58
+ * Used in explicit mode to release usage tracking.
59
+ *
60
+ * @param docId - Document ID
61
+ */
62
+ decrementRefCount(docId: string): void;
63
+ /**
64
+ * Gets the current reference count for a document.
65
+ *
66
+ * Useful for debugging or advanced use cases.
67
+ *
68
+ * @param docId - Document ID
69
+ * @returns Current reference count (0 if not tracked)
70
+ */
71
+ getRefCount(docId: string): number;
72
+ /**
73
+ * Clears all reference counts without closing documents.
74
+ *
75
+ * Use with caution - this is mainly for testing or cleanup scenarios
76
+ * where you want to reset the manager state.
77
+ */
78
+ reset(): void;
79
+ }
80
+ /**
81
+ * Gets or creates a DocManager for a Patches instance.
82
+ *
83
+ * @param patches - Patches instance
84
+ * @returns DocManager for this Patches instance
85
+ */
86
+ declare function getDocManager(patches: Patches): DocManager;
87
+
88
+ export { DocManager, getDocManager };
@@ -0,0 +1,125 @@
1
+ import "../chunk-IZ2YBCUP.js";
2
+ class DocManager {
3
+ refCounts = /* @__PURE__ */ new Map();
4
+ pendingOps = /* @__PURE__ */ new Map();
5
+ /**
6
+ * Opens a document with reference counting.
7
+ *
8
+ * - If this is the first reference, calls patches.openDoc()
9
+ * - If doc is already open, returns existing instance and increments count
10
+ * - Handles concurrent opens to the same doc safely
11
+ *
12
+ * @param patches - Patches instance
13
+ * @param docId - Document ID to open
14
+ * @returns Promise resolving to PatchesDoc instance
15
+ */
16
+ async openDoc(patches, docId) {
17
+ const currentCount = this.refCounts.get(docId) || 0;
18
+ if (currentCount === 0 && this.pendingOps.has(docId)) {
19
+ const doc = await this.pendingOps.get(docId);
20
+ this.refCounts.set(docId, (this.refCounts.get(docId) || 0) + 1);
21
+ return doc;
22
+ }
23
+ if (currentCount > 0) {
24
+ this.refCounts.set(docId, currentCount + 1);
25
+ const doc = patches.getOpenDoc(docId);
26
+ if (!doc) {
27
+ throw new Error(`Document ${docId} has ref count ${currentCount} but is not open in Patches`);
28
+ }
29
+ return doc;
30
+ }
31
+ const openPromise = patches.openDoc(docId);
32
+ this.pendingOps.set(docId, openPromise);
33
+ try {
34
+ const doc = await openPromise;
35
+ this.refCounts.set(docId, 1);
36
+ return doc;
37
+ } catch (error) {
38
+ this.refCounts.delete(docId);
39
+ throw error;
40
+ } finally {
41
+ this.pendingOps.delete(docId);
42
+ }
43
+ }
44
+ /**
45
+ * Closes a document with reference counting.
46
+ *
47
+ * - Decrements the reference count
48
+ * - Only calls patches.closeDoc() when count reaches zero
49
+ * - Safe to call even if doc was never opened
50
+ *
51
+ * @param patches - Patches instance
52
+ * @param docId - Document ID to close
53
+ */
54
+ async closeDoc(patches, docId) {
55
+ const currentCount = this.refCounts.get(docId) || 0;
56
+ if (currentCount === 0) {
57
+ return;
58
+ }
59
+ if (currentCount === 1) {
60
+ this.refCounts.delete(docId);
61
+ await patches.closeDoc(docId);
62
+ } else {
63
+ this.refCounts.set(docId, currentCount - 1);
64
+ }
65
+ }
66
+ /**
67
+ * Increments the reference count for a document without opening it.
68
+ *
69
+ * Used in explicit mode to track usage and prevent premature closes
70
+ * from autoClose mode.
71
+ *
72
+ * @param docId - Document ID
73
+ */
74
+ incrementRefCount(docId) {
75
+ const currentCount = this.refCounts.get(docId) || 0;
76
+ this.refCounts.set(docId, currentCount + 1);
77
+ }
78
+ /**
79
+ * Decrements the reference count for a document without closing it.
80
+ *
81
+ * Used in explicit mode to release usage tracking.
82
+ *
83
+ * @param docId - Document ID
84
+ */
85
+ decrementRefCount(docId) {
86
+ const currentCount = this.refCounts.get(docId) || 0;
87
+ if (currentCount > 0) {
88
+ this.refCounts.set(docId, currentCount - 1);
89
+ }
90
+ }
91
+ /**
92
+ * Gets the current reference count for a document.
93
+ *
94
+ * Useful for debugging or advanced use cases.
95
+ *
96
+ * @param docId - Document ID
97
+ * @returns Current reference count (0 if not tracked)
98
+ */
99
+ getRefCount(docId) {
100
+ return this.refCounts.get(docId) || 0;
101
+ }
102
+ /**
103
+ * Clears all reference counts without closing documents.
104
+ *
105
+ * Use with caution - this is mainly for testing or cleanup scenarios
106
+ * where you want to reset the manager state.
107
+ */
108
+ reset() {
109
+ this.refCounts.clear();
110
+ this.pendingOps.clear();
111
+ }
112
+ }
113
+ const managers = /* @__PURE__ */ new WeakMap();
114
+ function getDocManager(patches) {
115
+ let manager = managers.get(patches);
116
+ if (!manager) {
117
+ manager = new DocManager();
118
+ managers.set(patches, manager);
119
+ }
120
+ return manager;
121
+ }
122
+ export {
123
+ DocManager,
124
+ getDocManager
125
+ };
@@ -0,0 +1,20 @@
1
+ export { PatchesContextValue, PatchesProvider, PatchesProviderProps, usePatchesContext } from './context.js';
2
+ export { MaybeAccessor, UsePatchesDocOptions, UsePatchesDocReturn, UsePatchesSyncReturn, createPatchesDoc, usePatchesDoc, usePatchesSync } from './primitives.js';
3
+ export { DocManager, getDocManager } from './doc-manager.js';
4
+ import 'solid-js';
5
+ import '../client/Patches.js';
6
+ import '../event-signal.js';
7
+ import '../types.js';
8
+ import '../json-patch/JSONPatch.js';
9
+ import '@dabble/delta';
10
+ import '../json-patch/types.js';
11
+ import '../client/PatchesDoc.js';
12
+ import '../algorithms/shared/changeBatching.js';
13
+ import '../client/PatchesStore.js';
14
+ import '../net/PatchesSync.js';
15
+ import '../net/protocol/types.js';
16
+ import '../net/protocol/JSONRPCClient.js';
17
+ import '../net/websocket/PatchesWebSocket.js';
18
+ import '../net/PatchesClient.js';
19
+ import '../net/websocket/WebSocketTransport.js';
20
+ import '../utils/deferred.js';
@@ -0,0 +1,17 @@
1
+ import "../chunk-IZ2YBCUP.js";
2
+ import { PatchesProvider, usePatchesContext } from "./context.js";
3
+ import {
4
+ usePatchesDoc,
5
+ usePatchesSync,
6
+ createPatchesDoc
7
+ } from "./primitives.js";
8
+ import { getDocManager, DocManager } from "./doc-manager.js";
9
+ export {
10
+ DocManager,
11
+ PatchesProvider,
12
+ createPatchesDoc,
13
+ getDocManager,
14
+ usePatchesContext,
15
+ usePatchesDoc,
16
+ usePatchesSync
17
+ };