@tldraw/sync 5.5.0-next.f9308d324e1c → 5.6.0-canary.5bfc37740468
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/dist-cjs/index.js +1 -1
- package/dist-cjs/useSync.js +38 -64
- package/dist-cjs/useSync.js.map +2 -2
- package/dist-cjs/useSyncDemo.js +31 -45
- package/dist-cjs/useSyncDemo.js.map +2 -2
- package/dist-esm/index.mjs +1 -1
- package/dist-esm/useSync.mjs +38 -64
- package/dist-esm/useSync.mjs.map +2 -2
- package/dist-esm/useSyncDemo.mjs +31 -45
- package/dist-esm/useSyncDemo.mjs.map +2 -2
- package/package.json +17 -18
- package/src/useSync.test.tsx +95 -0
- package/src/useSync.ts +62 -81
- package/src/useSyncDemo.ts +32 -54
package/dist-cjs/index.js
CHANGED
|
@@ -29,7 +29,7 @@ var import_useSync = require("./useSync");
|
|
|
29
29
|
var import_useSyncDemo = require("./useSyncDemo");
|
|
30
30
|
(0, import_utils.registerTldrawLibraryVersion)(
|
|
31
31
|
"@tldraw/sync",
|
|
32
|
-
"5.
|
|
32
|
+
"5.6.0-canary.5bfc37740468",
|
|
33
33
|
"cjs"
|
|
34
34
|
);
|
|
35
35
|
//# sourceMappingURL=index.js.map
|
package/dist-cjs/useSync.js
CHANGED
|
@@ -28,6 +28,15 @@ var import_tldraw = require("tldraw");
|
|
|
28
28
|
const MULTIPLAYER_EVENT_NAME = "multiplayer.client";
|
|
29
29
|
const defaultCustomMessageHandler = () => {
|
|
30
30
|
};
|
|
31
|
+
const SYNC_ERROR_EVENT_NAMES = /* @__PURE__ */ new Map([
|
|
32
|
+
[import_sync_core.TLSyncErrorCloseEventReason.NOT_FOUND, "room-not-found"],
|
|
33
|
+
[import_sync_core.TLSyncErrorCloseEventReason.FORBIDDEN, "forbidden"],
|
|
34
|
+
[import_sync_core.TLSyncErrorCloseEventReason.NOT_AUTHENTICATED, "not-authenticated"],
|
|
35
|
+
[import_sync_core.TLSyncErrorCloseEventReason.RATE_LIMITED, "rate-limited"]
|
|
36
|
+
]);
|
|
37
|
+
function toCollaborationStatus(status) {
|
|
38
|
+
return status === "error" ? "offline" : status;
|
|
39
|
+
}
|
|
31
40
|
function useSync(opts) {
|
|
32
41
|
const [state, setState] = (0, import_tldraw.useRefState)(null);
|
|
33
42
|
const {
|
|
@@ -54,27 +63,16 @@ function useSync(opts) {
|
|
|
54
63
|
const onCustomMessageReceived = (0, import_tldraw.useEvent)(_onCustomMessageReceived ?? defaultCustomMessageHandler);
|
|
55
64
|
(0, import_react.useEffect)(() => {
|
|
56
65
|
const storeId = (0, import_tldraw.uniqueId)();
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
if (current && current.id === (0, import_tldraw.createUserId)(userId)) return current;
|
|
68
|
-
const presences = store.query.records("instance_presence").get();
|
|
69
|
-
const match = presences.find((p) => p.userId === (0, import_tldraw.createUserId)(userId));
|
|
70
|
-
if (match) {
|
|
71
|
-
return import_tldraw.UserRecordType.create({
|
|
72
|
-
id: (0, import_tldraw.createUserId)(userId),
|
|
73
|
-
name: match.userName,
|
|
74
|
-
color: match.color
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
return null;
|
|
66
|
+
const currentUserSignal = _users?.currentUser ?? import_tldraw.defaultUserStore.currentUser;
|
|
67
|
+
const users = {
|
|
68
|
+
currentUser: currentUserSignal,
|
|
69
|
+
resolve: _users?.resolve ?? (0, import_tldraw.createCachedUserResolve)((userId) => {
|
|
70
|
+
const id = (0, import_tldraw.createUserId)(userId);
|
|
71
|
+
const current = currentUserSignal.get();
|
|
72
|
+
if (current && current.id === id) return current;
|
|
73
|
+
if (_users) return null;
|
|
74
|
+
const match = store.query.records("instance_presence").get().find((p) => p.userId === id);
|
|
75
|
+
return match ? import_tldraw.UserRecordType.create({ id, name: match.userName, color: match.color }) : null;
|
|
78
76
|
})
|
|
79
77
|
};
|
|
80
78
|
const currentUser = (0, import_tldraw.computed)("currentUser", () => {
|
|
@@ -92,26 +90,16 @@ function useSync(opts) {
|
|
|
92
90
|
if (uri) {
|
|
93
91
|
throw new Error("uri and connect cannot be used together");
|
|
94
92
|
}
|
|
95
|
-
socket = connect({
|
|
96
|
-
sessionId: import_tldraw.TAB_ID,
|
|
97
|
-
storeId
|
|
98
|
-
});
|
|
93
|
+
socket = connect({ sessionId: import_tldraw.TAB_ID, storeId });
|
|
99
94
|
} else if (uri) {
|
|
100
|
-
if (connect) {
|
|
101
|
-
throw new Error("uri and connect cannot be used together");
|
|
102
|
-
}
|
|
103
95
|
socket = new import_sync_core.ClientWebSocketAdapter(async () => {
|
|
104
|
-
const
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (withParams.searchParams.has("storeId")) {
|
|
112
|
-
throw new Error(
|
|
113
|
-
'useSync. "storeId" is a reserved query param name. Please use a different name'
|
|
114
|
-
);
|
|
96
|
+
const withParams = new URL(typeof uri === "string" ? uri : await uri());
|
|
97
|
+
for (const param of ["sessionId", "storeId"]) {
|
|
98
|
+
if (withParams.searchParams.has(param)) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
`useSync. "${param}" is a reserved query param name. Please use a different name`
|
|
101
|
+
);
|
|
102
|
+
}
|
|
115
103
|
}
|
|
116
104
|
withParams.searchParams.set("sessionId", import_tldraw.TAB_ID);
|
|
117
105
|
withParams.searchParams.set("storeId", storeId);
|
|
@@ -121,12 +109,12 @@ function useSync(opts) {
|
|
|
121
109
|
throw new Error("uri or connect must be provided");
|
|
122
110
|
}
|
|
123
111
|
let didCancel = false;
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
112
|
+
const collaborationStatusSignal = (0, import_state.atom)(
|
|
113
|
+
"collaboration status",
|
|
114
|
+
toCollaborationStatus(socket.connectionStatus)
|
|
115
|
+
);
|
|
128
116
|
const unsubscribeFromConnectionStatus = socket.onStatusChange(() => {
|
|
129
|
-
collaborationStatusSignal.set(
|
|
117
|
+
collaborationStatusSignal.set(toCollaborationStatus(socket.connectionStatus));
|
|
130
118
|
});
|
|
131
119
|
const syncMode = (0, import_state.atom)("sync mode", "readwrite");
|
|
132
120
|
const store = (0, import_tldraw.createTLStore)({
|
|
@@ -153,27 +141,14 @@ function useSync(opts) {
|
|
|
153
141
|
didCancel: () => didCancel,
|
|
154
142
|
onLoad(client2) {
|
|
155
143
|
track?.(MULTIPLAYER_EVENT_NAME, { name: "load", roomId });
|
|
156
|
-
setState((prev) => ({
|
|
144
|
+
setState((prev) => ({ readyClient: client2, objectAccess: prev?.objectAccess }));
|
|
157
145
|
},
|
|
158
146
|
onSyncError(reason) {
|
|
159
147
|
console.error("sync error", reason);
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
case import_sync_core.TLSyncErrorCloseEventReason.FORBIDDEN:
|
|
165
|
-
track?.(MULTIPLAYER_EVENT_NAME, { name: "forbidden", roomId });
|
|
166
|
-
break;
|
|
167
|
-
case import_sync_core.TLSyncErrorCloseEventReason.NOT_AUTHENTICATED:
|
|
168
|
-
track?.(MULTIPLAYER_EVENT_NAME, { name: "not-authenticated", roomId });
|
|
169
|
-
break;
|
|
170
|
-
case import_sync_core.TLSyncErrorCloseEventReason.RATE_LIMITED:
|
|
171
|
-
track?.(MULTIPLAYER_EVENT_NAME, { name: "rate-limited", roomId });
|
|
172
|
-
break;
|
|
173
|
-
default:
|
|
174
|
-
track?.(MULTIPLAYER_EVENT_NAME, { name: "sync-error:" + reason, roomId });
|
|
175
|
-
break;
|
|
176
|
-
}
|
|
148
|
+
track?.(MULTIPLAYER_EVENT_NAME, {
|
|
149
|
+
name: SYNC_ERROR_EVENT_NAMES.get(reason) ?? "sync-error:" + reason,
|
|
150
|
+
roomId
|
|
151
|
+
});
|
|
177
152
|
setState({ error: new import_sync_core.TLRemoteSyncError(reason) });
|
|
178
153
|
socket.close();
|
|
179
154
|
},
|
|
@@ -213,10 +188,9 @@ function useSync(opts) {
|
|
|
213
188
|
if (!state) return { status: "loading" };
|
|
214
189
|
if (state.error) return { status: "error", error: state.error };
|
|
215
190
|
if (!state.readyClient) return { status: "loading" };
|
|
216
|
-
const connectionStatus = state.readyClient.socket.connectionStatus;
|
|
217
191
|
return {
|
|
218
192
|
status: "synced-remote",
|
|
219
|
-
connectionStatus: connectionStatus
|
|
193
|
+
connectionStatus: toCollaborationStatus(state.readyClient.socket.connectionStatus),
|
|
220
194
|
store: state.readyClient.store,
|
|
221
195
|
objectAccess: state.objectAccess ?? "write"
|
|
222
196
|
};
|
package/dist-cjs/useSync.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/useSync.ts"],
|
|
4
|
-
"sourcesContent": ["import { atom, transact } from '@tldraw/state'\nimport {\n\tClientWebSocketAdapter,\n\tTLCustomMessageHandler,\n\tTLObjectStoreAccess,\n\tTLPersistentClientSocket,\n\tTLPresenceMode,\n\tTLRemoteSyncError,\n\tTLSocketClientSentEvent,\n\tTLSocketServerSentEvent,\n\tTLSyncClient,\n\tTLSyncErrorCloseEventReason,\n} from '@tldraw/sync-core'\nimport { useEffect } from 'react'\nimport {\n\tEditor,\n\tTAB_ID,\n\tTLAssetStore,\n\tTLPresenceStateInfo,\n\tTLRecord,\n\tTLStore,\n\tTLStoreSchemaOptions,\n\tTLStoreWithStatus,\n\tTLThemes,\n\tTLUser,\n\tTLUserStore,\n\tUserRecordType,\n\tcomputed,\n\tcreateCachedUserResolve,\n\tcreatePresenceStateDerivation,\n\tregisterColorsFromThemes,\n\tregisterFontsFromThemes,\n\tresolveThemes,\n\tcreateTLStore,\n\tcreateUserId,\n\tdefaultUserPreferences,\n\tdefaultUserStore,\n\tgetDefaultUserPresence,\n\tgetUserPreferences,\n\tuniqueId,\n\tuseEvent,\n\tuseReactiveEvent,\n\tuseRefState,\n\tuseTLSchemaFromUtils,\n\tuseValue,\n} from 'tldraw'\n\nconst MULTIPLAYER_EVENT_NAME = 'multiplayer.client'\n\nconst defaultCustomMessageHandler: TLCustomMessageHandler = () => {}\n\n/**\n * A store wrapper specifically for remote collaboration that excludes local-only states.\n * This type represents a tldraw store that is synchronized with a remote multiplayer server.\n *\n * Unlike the base TLStoreWithStatus, this excludes 'synced-local' and 'not-synced' states\n * since remote stores are always either loading, connected to a server, or in an error state.\n *\n * @example\n * ```tsx\n * function MyCollaborativeApp() {\n * const store: RemoteTLStoreWithStatus = useSync({\n * uri: 'wss://myserver.com/sync/room-123',\n * assets: myAssetStore\n * })\n *\n * if (store.status === 'loading') {\n * return <div>Connecting to multiplayer session...</div>\n * }\n *\n * if (store.status === 'error') {\n * return <div>Connection failed: {store.error.message}</div>\n * }\n *\n * // store.status === 'synced-remote'\n * return <Tldraw store={store.store} />\n * }\n * ```\n *\n * @public\n */\nexport type RemoteTLStoreWithStatus =\n\t| Exclude<\n\t\t\tTLStoreWithStatus,\n\t\t\t{ status: 'synced-local' } | { status: 'not-synced' } | { status: 'synced-remote' }\n\t >\n\t| (Extract<TLStoreWithStatus, { status: 'synced-remote' }> & {\n\t\t\t/**\n\t\t\t * Write access for object-store lane record types (e.g. comments), as granted by the\n\t\t\t * server for this session. Independent of the canvas read-only state, so a session can\n\t\t\t * be allowed to comment without being allowed to edit. Defaults to `'write'`.\n\t\t\t */\n\t\t\treadonly objectAccess: TLObjectStoreAccess\n\t })\n\n/**\n * Creates a reactive store synchronized with a multiplayer server for real-time collaboration.\n *\n * This hook manages the complete lifecycle of a collaborative tldraw session, including\n * WebSocket connection establishment, state synchronization, user presence, and error handling.\n * The returned store can be passed directly to the Tldraw component to enable multiplayer features.\n *\n * The store progresses through multiple states:\n * - `loading`: Establishing connection and synchronizing initial state\n * - `synced-remote`: Successfully connected and actively synchronizing changes\n * - `error`: Connection failed or synchronization error occurred\n *\n * For optimal performance with media assets, provide an `assets` store that implements\n * external blob storage. Without this, large images and videos will be stored inline\n * as base64, causing performance issues during serialization.\n *\n * @param opts - Configuration options for multiplayer synchronization\n * - `uri` - WebSocket server URI (string or async function returning URI)\n * - `assets` - Asset store for blob storage (required for production use)\n * - `users` - User store for identity, presence and attribution\n * - `getUserPresence` - Optional function to customize presence data\n * - `onCustomMessageReceived` - Handler for custom socket messages\n * - `roomId` - Room identifier for analytics (internal use)\n * - `onMount` - Callback when editor mounts (internal use)\n * - `trackAnalyticsEvent` - Analytics event tracker (internal use)\n *\n * @returns A reactive store wrapper with connection status and synchronized store\n *\n * @example\n * ```tsx\n * // Basic multiplayer setup\n * function CollaborativeApp() {\n * const store = useSync({\n * uri: 'wss://myserver.com/sync/room-123',\n * assets: myAssetStore,\n * users: {\n * currentUser: computed('current-user', () => ({\n * id: createUserId('user-1'),\n * name: 'Alice',\n * color: '#ff0000',\n * meta: {},\n * })),\n * }\n * })\n *\n * if (store.status === 'loading') {\n * return <div>Connecting to collaboration session...</div>\n * }\n *\n * if (store.status === 'error') {\n * return <div>Failed to connect: {store.error.message}</div>\n * }\n *\n * return <Tldraw store={store.store} />\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Dynamic authentication with user store\n * function AuthenticatedApp() {\n * const store = useSync({\n * uri: async () => {\n * const token = await getAuthToken()\n * return `wss://myserver.com/sync/room-123?token=${token}`\n * },\n * assets: authenticatedAssetStore,\n * users: myUserStore,\n * getUserPresence: (store, user) => {\n * return {\n * userId: user.id,\n * userName: user.name,\n * cursor: getCurrentCursor(store)\n * }\n * }\n * })\n *\n * return <Tldraw store={store.store} />\n * }\n * ```\n *\n * @public\n */\nexport function useSync(opts: UseSyncOptions & TLStoreSchemaOptions): RemoteTLStoreWithStatus {\n\tconst [state, setState] = useRefState<{\n\t\treadyClient?: TLSyncClient<TLRecord, TLStore>\n\t\terror?: Error\n\t\tobjectAccess?: TLObjectStoreAccess\n\t} | null>(null)\n\tconst {\n\t\turi,\n\t\troomId = 'default',\n\t\tassets,\n\t\tusers: _users,\n\t\tonMount,\n\t\tconnect,\n\t\ttrackAnalyticsEvent: track,\n\t\tgetUserPresence: _getUserPresence,\n\t\tonCustomMessageReceived: _onCustomMessageReceived,\n\t\tthemes,\n\t\t...schemaOpts\n\t} = opts\n\n\t// This line will throw a type error if we add any new options to the useSync hook but we don't destructure them\n\t// This is required because otherwise the useTLSchemaFromUtils might return a new schema on every render if the newly-added option\n\t// is allowed to be unstable\n\tconst __never__: never = 0 as any as keyof Omit<typeof schemaOpts, keyof TLStoreSchemaOptions>\n\n\tconst resolvedThemes = resolveThemes(themes)\n\tregisterColorsFromThemes(resolvedThemes)\n\tregisterFontsFromThemes(resolvedThemes)\n\tconst schema = useTLSchemaFromUtils(schemaOpts)\n\n\tconst getUserPresence = useReactiveEvent(\n\t\t(_getUserPresence ?? getDefaultUserPresence) as typeof getDefaultUserPresence\n\t)\n\tconst onCustomMessageReceived = useEvent(_onCustomMessageReceived ?? defaultCustomMessageHandler)\n\n\tuseEffect(() => {\n\t\tconst storeId = uniqueId()\n\n\t\tconst users: Required<TLUserStore> = _users\n\t\t\t? {\n\t\t\t\t\tcurrentUser: _users.currentUser,\n\t\t\t\t\tresolve:\n\t\t\t\t\t\t_users.resolve ??\n\t\t\t\t\t\tcreateCachedUserResolve((userId) => {\n\t\t\t\t\t\t\tconst current = _users.currentUser.get()\n\t\t\t\t\t\t\treturn current && current.id === createUserId(userId) ? current : null\n\t\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tcurrentUser: defaultUserStore.currentUser,\n\t\t\t\t\tresolve: createCachedUserResolve((userId) => {\n\t\t\t\t\t\tconst current = defaultUserStore.currentUser.get()\n\t\t\t\t\t\tif (current && current.id === createUserId(userId)) return current\n\t\t\t\t\t\tconst presences = store.query.records('instance_presence').get()\n\t\t\t\t\t\tconst match = presences.find((p) => p.userId === createUserId(userId))\n\t\t\t\t\t\tif (match) {\n\t\t\t\t\t\t\treturn UserRecordType.create({\n\t\t\t\t\t\t\t\tid: createUserId(userId),\n\t\t\t\t\t\t\t\tname: match.userName,\n\t\t\t\t\t\t\t\tcolor: match.color,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn null\n\t\t\t\t\t}),\n\t\t\t\t}\n\n\t\t// This always returns a non-null user for presence display, falling back\n\t\t// to anonymous user preferences. The store receives the raw `users` object\n\t\t// (where currentUser may return null), so attribution via\n\t\t// getAttributionUserId() correctly returns null for anonymous sessions.\n\t\tconst currentUser = computed<TLUser>('currentUser', () => {\n\t\t\tconst user = users.currentUser.get()\n\t\t\tif (user) return user\n\t\t\tconst prefs = getUserPreferences()\n\t\t\treturn UserRecordType.create({\n\t\t\t\tid: createUserId(prefs.id),\n\t\t\t\tname: prefs.name ?? '',\n\t\t\t\tcolor: prefs.color ?? defaultUserPreferences.color,\n\t\t\t})\n\t\t})\n\n\t\tlet socket: TLPersistentClientSocket<\n\t\t\tTLSocketClientSentEvent<TLRecord>,\n\t\t\tTLSocketServerSentEvent<TLRecord>\n\t\t>\n\t\tif (connect) {\n\t\t\tif (uri) {\n\t\t\t\tthrow new Error('uri and connect cannot be used together')\n\t\t\t}\n\n\t\t\tsocket = connect({\n\t\t\t\tsessionId: TAB_ID,\n\t\t\t\tstoreId,\n\t\t\t}) as TLPersistentClientSocket<\n\t\t\t\tTLSocketClientSentEvent<TLRecord>,\n\t\t\t\tTLSocketServerSentEvent<TLRecord>\n\t\t\t>\n\t\t} else if (uri) {\n\t\t\tif (connect) {\n\t\t\t\tthrow new Error('uri and connect cannot be used together')\n\t\t\t}\n\n\t\t\tsocket = new ClientWebSocketAdapter(async () => {\n\t\t\t\tconst uriString = typeof uri === 'string' ? uri : await uri()\n\n\t\t\t\t// set sessionId as a query param on the uri\n\t\t\t\tconst withParams = new URL(uriString)\n\t\t\t\tif (withParams.searchParams.has('sessionId')) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'useSync. \"sessionId\" is a reserved query param name. Please use a different name'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (withParams.searchParams.has('storeId')) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'useSync. \"storeId\" is a reserved query param name. Please use a different name'\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\twithParams.searchParams.set('sessionId', TAB_ID)\n\t\t\t\twithParams.searchParams.set('storeId', storeId)\n\t\t\t\treturn withParams.toString()\n\t\t\t})\n\t\t} else {\n\t\t\tthrow new Error('uri or connect must be provided')\n\t\t}\n\n\t\tlet didCancel = false\n\n\t\tfunction getConnectionStatus() {\n\t\t\treturn socket.connectionStatus === 'error' ? 'offline' : socket.connectionStatus\n\t\t}\n\t\tconst collaborationStatusSignal = atom('collaboration status', getConnectionStatus())\n\t\tconst unsubscribeFromConnectionStatus = socket.onStatusChange(() => {\n\t\t\tcollaborationStatusSignal.set(getConnectionStatus())\n\t\t})\n\n\t\tconst syncMode = atom('sync mode', 'readwrite' as 'readonly' | 'readwrite')\n\n\t\tconst store = createTLStore({\n\t\t\tid: storeId,\n\t\t\tschema,\n\t\t\tassets,\n\t\t\tusers,\n\t\t\tonMount,\n\t\t\tcollaboration: {\n\t\t\t\tstatus: collaborationStatusSignal,\n\t\t\t\tmode: syncMode,\n\t\t\t},\n\t\t})\n\n\t\tconst presence = createPresenceStateDerivation(currentUser, {\n\t\t\tgetUserPresence,\n\t\t})(store)\n\n\t\t// Every connected session \u2014 each tab, window, or device \u2014 pushes its\n\t\t// presence on connect, so the store holds one instance_presence record per\n\t\t// *other* session in the room, including the user's own other tabs. (The\n\t\t// server never echoes a session its own record.) So an empty set means\n\t\t// we're genuinely the only session and can throttle to solo; any other\n\t\t// session \u2014 another user, or just another tab of our own \u2014 keeps us at the\n\t\t// full sync rate so edits propagate without the solo-mode lag.\n\t\tconst otherSessions = store.query.ids('instance_presence')\n\n\t\tconst presenceMode = computed<TLPresenceMode>('presenceMode', () => {\n\t\t\treturn otherSessions.get().size === 0 ? 'solo' : 'full'\n\t\t})\n\n\t\tconst client = new TLSyncClient<TLRecord, TLStore>({\n\t\t\tstore,\n\t\t\tsocket,\n\t\t\tdidCancel: () => didCancel,\n\t\t\tonLoad(client) {\n\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'load', roomId })\n\t\t\t\t// Merge so we don't clobber objectAccess if onAfterConnect ran first.\n\t\t\t\tsetState((prev) => ({ ...prev, readyClient: client }))\n\t\t\t},\n\t\t\tonSyncError(reason) {\n\t\t\t\tconsole.error('sync error', reason)\n\n\t\t\t\tswitch (reason) {\n\t\t\t\t\tcase TLSyncErrorCloseEventReason.NOT_FOUND:\n\t\t\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'room-not-found', roomId })\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase TLSyncErrorCloseEventReason.FORBIDDEN:\n\t\t\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'forbidden', roomId })\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase TLSyncErrorCloseEventReason.NOT_AUTHENTICATED:\n\t\t\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'not-authenticated', roomId })\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase TLSyncErrorCloseEventReason.RATE_LIMITED:\n\t\t\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'rate-limited', roomId })\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'sync-error:' + reason, roomId })\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tsetState({ error: new TLRemoteSyncError(reason) })\n\t\t\t\tsocket.close()\n\t\t\t},\n\t\t\tonAfterConnect(_, { isReadonly, objectAccess }) {\n\t\t\t\t// Object-lane (comment) write access is decided per session by the server and can\n\t\t\t\t// change on reconnect (e.g. when the file's share tier changes), so surface it on\n\t\t\t\t// the returned status for consumers that gate comment UI. This fires before the\n\t\t\t\t// first onLoad, hence the merge in both directions.\n\t\t\t\tsetState((prev) => ({ ...prev, objectAccess }))\n\t\t\t\ttransact(() => {\n\t\t\t\t\tsyncMode.set(isReadonly ? 'readonly' : 'readwrite')\n\t\t\t\t\t// if the server crashes and loses all data it can return an empty document\n\t\t\t\t\t// when it comes back up. This is a safety check to make sure that if something like\n\t\t\t\t\t// that happens, it won't render the app broken and require a restart. The user will\n\t\t\t\t\t// most likely lose all their changes though since they'll have been working with pages\n\t\t\t\t\t// that won't exist. There's certainly something we can do to make this better.\n\t\t\t\t\t// but the likelihood of this happening is very low and maybe not worth caring about beyond this.\n\t\t\t\t\tstore.ensureStoreIsUsable()\n\t\t\t\t})\n\t\t\t},\n\t\t\tonCustomMessageReceived,\n\t\t\tpresence,\n\t\t\tpresenceMode,\n\t\t})\n\n\t\treturn () => {\n\t\t\tdidCancel = true\n\t\t\tunsubscribeFromConnectionStatus()\n\t\t\tclient.close()\n\t\t\tsocket.close()\n\t\t}\n\t}, [\n\t\tassets,\n\t\tonMount,\n\t\tconnect,\n\t\t_users,\n\t\troomId,\n\t\tschema,\n\t\tsetState,\n\t\ttrack,\n\t\turi,\n\t\tgetUserPresence,\n\t\tonCustomMessageReceived,\n\t])\n\n\treturn useValue<RemoteTLStoreWithStatus>(\n\t\t'remote synced store',\n\t\t() => {\n\t\t\tif (!state) return { status: 'loading' }\n\t\t\tif (state.error) return { status: 'error', error: state.error }\n\t\t\tif (!state.readyClient) return { status: 'loading' }\n\t\t\tconst connectionStatus = state.readyClient.socket.connectionStatus\n\t\t\treturn {\n\t\t\t\tstatus: 'synced-remote',\n\t\t\t\tconnectionStatus: connectionStatus === 'error' ? 'offline' : connectionStatus,\n\t\t\t\tstore: state.readyClient.store,\n\t\t\t\tobjectAccess: state.objectAccess ?? 'write',\n\t\t\t}\n\t\t},\n\t\t[state]\n\t)\n}\n\n/**\n * Configuration options for the {@link useSync} hook to establish multiplayer collaboration.\n *\n * This interface defines the required and optional settings for connecting to a multiplayer\n * server, managing user presence, handling assets, and customizing the collaboration experience.\n *\n * @example\n * ```tsx\n * const syncOptions: UseSyncOptions = {\n * uri: 'wss://myserver.com/sync/room-123',\n * assets: myAssetStore,\n * users: {\n * currentUser: myCurrentUserSignal,\n * },\n * getUserPresence: (store, user) => ({\n * userId: user.id,\n * userName: user.name,\n * cursor: getCursorPosition()\n * })\n * }\n * ```\n *\n * @public\n */\nexport interface UseSyncOptionsBase {\n\t/**\n\t * Named theme definitions. When provided, custom color names are automatically\n\t * registered before the store is constructed so persisted data with those\n\t * colors passes validation on load.\n\t */\n\tthemes?: Partial<TLThemes>\n\n\t/**\n\t * Asset store implementation for handling file uploads and storage.\n\t *\n\t * Required for production applications to handle images, videos, and other\n\t * media efficiently. Without an asset store, files are stored inline as\n\t * base64, which causes performance issues with large files.\n\t *\n\t * The asset store must implement upload (for new files) and resolve\n\t * (for displaying existing files) methods. For prototyping, you can use\n\t * {@link @tldraw/editor#inlineBase64AssetStore} but this is not recommended for production.\n\t *\n\t * @example\n\t * ```ts\n\t * const myAssetStore: TLAssetStore = {\n\t * upload: async (asset, file) => {\n\t * const url = await uploadToCloudStorage(file)\n\t * return { src: url }\n\t * },\n\t * resolve: (asset, context) => {\n\t * return getOptimizedUrl(asset.src, context)\n\t * }\n\t * }\n\t * ```\n\t */\n\tassets: TLAssetStore\n\n\t/**\n\t * User store for identity, presence and attribution.\n\t *\n\t * Both methods return reactive {@link @tldraw/state#Signal | Signals}.\n\t * `currentUser` provides the current user's identity (used for\n\t * both presence broadcasting and shape attribution) and optionally\n\t * `resolve(userId)` looks up other users by ID. If not provided,\n\t * a default implementation backed by localStorage user preferences is\n\t * used, with `resolve` falling back to presence records in the store.\n\t */\n\tusers?: TLUserStore\n\n\t/**\n\t * Handler for receiving custom messages sent through the multiplayer connection.\n\t *\n\t * Use this to implement custom communication channels between clients beyond\n\t * the standard shape and presence synchronization. Messages are sent using\n\t * the TLSyncClient's sendMessage method.\n\t *\n\t * @param data - The custom message data received from another client\n\t *\n\t * @example\n\t * ```ts\n\t * onCustomMessageReceived: (data) => {\n\t * if (data.type === 'chat') {\n\t * displayChatMessage(data.message, data.userId)\n\t * }\n\t * }\n\t * ```\n\t */\n\tonCustomMessageReceived?(data: any): void\n\n\t/** @internal */\n\tonMount?(editor: Editor): void\n\t/** @internal used for analytics only, we should refactor this away */\n\troomId?: string\n\t/** @internal */\n\ttrackAnalyticsEvent?(name: string, data: { [key: string]: any }): void\n\n\t/**\n\t * A reactive function that returns a {@link @tldraw/tlschema#TLInstancePresence} object.\n\t *\n\t * This function is called reactively whenever the store state changes and\n\t * determines what presence information to broadcast to other clients. The\n\t * result is synchronized across all connected clients for displaying cursors,\n\t * selections, and other collaborative indicators.\n\t *\n\t * If not provided, uses the default implementation which includes standard\n\t * cursor position and selection state. Custom implementations allow you to\n\t * add additional presence data like current tool, view state, or custom status.\n\t *\n\t * See {@link @tldraw/tlschema#getDefaultUserPresence} for\n\t * the default implementation of this function.\n\t *\n\t * @param store - The current TLStore\n\t * @param user - The current user information\n\t * @returns Presence state to broadcast to other clients, or null to hide presence\n\t *\n\t * @example\n\t * ```ts\n\t * getUserPresence: (store, user) => {\n\t * return {\n\t * userId: user.id,\n\t * userName: user.name,\n\t * cursor: { x: 100, y: 200 },\n\t * currentTool: 'select',\n\t * isActive: true\n\t * }\n\t * }\n\t * ```\n\t */\n\tgetUserPresence?(store: TLStore, user: TLUser): TLPresenceStateInfo | null\n}\n\n/** @public */\nexport interface UseSyncOptionsWithUri extends UseSyncOptionsBase {\n\t/**\n\t * The WebSocket URI of the multiplayer server for real-time synchronization.\n\t *\n\t * Must include the protocol (wss:// for secure, ws:// for local development).\n\t * HTTP/HTTPS URLs will be automatically upgraded to WebSocket connections.\n\t *\n\t * Can be a static string or a function that returns a URI (useful for dynamic\n\t * authentication tokens or room routing). The function is called on each\n\t * connection attempt, allowing for token refresh and dynamic routing.\n\t *\n\t * Reserved query parameters `sessionId` and `storeId` are automatically added\n\t * by the sync system and should not be included in your URI.\n\t *\n\t * @example\n\t * ```ts\n\t * // Static URI\n\t * uri: 'wss://myserver.com/sync/room-123'\n\t *\n\t * // Dynamic URI with authentication\n\t * uri: async () => {\n\t * const token = await getAuthToken()\n\t * return `wss://myserver.com/sync/room-123?token=${token}`\n\t * }\n\t * ```\n\t */\n\turi: string | (() => string | Promise<string>)\n\tconnect?: never\n}\n\n/** @public */\nexport interface UseSyncOptionsWithConnectFn extends UseSyncOptionsBase {\n\t/**\n\t * Create a connection to the server. Mostly you should use {@link UseSyncOptionsWithUri.uri}\n\t * instead, but this is useful if you want to use a custom transport to connect to the server,\n\t * instead of our default websocket-based transport.\n\t */\n\tconnect: UseSyncConnectFn\n\turi?: never\n}\n\n/** @public */\nexport type UseSyncConnectFn = (query: {\n\tsessionId: string\n\tstoreId: string\n}) => TLPersistentClientSocket\n\n/**\n * Options for the {@link useSync} hook.\n * @public\n */\nexport type UseSyncOptions = UseSyncOptionsWithUri | UseSyncOptionsWithConnectFn\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA+B;AAC/B,uBAWO;AACP,mBAA0B;AAC1B,oBA+BO;AAEP,MAAM,yBAAyB;AAE/B,MAAM,8BAAsD,MAAM;AAAC;
|
|
4
|
+
"sourcesContent": ["import { atom, transact } from '@tldraw/state'\nimport {\n\tClientWebSocketAdapter,\n\tTLCustomMessageHandler,\n\tTLObjectStoreAccess,\n\tTLPersistentClientSocket,\n\tTLPresenceMode,\n\tTLRemoteSyncError,\n\tTLSocketClientSentEvent,\n\tTLSocketServerSentEvent,\n\tTLSyncClient,\n\tTLSyncErrorCloseEventReason,\n} from '@tldraw/sync-core'\nimport { useEffect } from 'react'\nimport {\n\tEditor,\n\tTAB_ID,\n\tTLAssetStore,\n\tTLPresenceStateInfo,\n\tTLRecord,\n\tTLStore,\n\tTLStoreSchemaOptions,\n\tTLStoreWithStatus,\n\tTLThemes,\n\tTLUser,\n\tTLUserStore,\n\tUserRecordType,\n\tcomputed,\n\tcreateCachedUserResolve,\n\tcreatePresenceStateDerivation,\n\tregisterColorsFromThemes,\n\tregisterFontsFromThemes,\n\tresolveThemes,\n\tcreateTLStore,\n\tcreateUserId,\n\tdefaultUserPreferences,\n\tdefaultUserStore,\n\tgetDefaultUserPresence,\n\tgetUserPreferences,\n\tuniqueId,\n\tuseEvent,\n\tuseReactiveEvent,\n\tuseRefState,\n\tuseTLSchemaFromUtils,\n\tuseValue,\n} from 'tldraw'\n\nconst MULTIPLAYER_EVENT_NAME = 'multiplayer.client'\n\nconst defaultCustomMessageHandler: TLCustomMessageHandler = () => {}\n\n// Keyed by `reason`, which is an arbitrary string off the server's close event, so a Map rather\n// than an object literal: a reason of 'constructor' or '__proto__' would find a prototype member.\nconst SYNC_ERROR_EVENT_NAMES = new Map<string, string>([\n\t[TLSyncErrorCloseEventReason.NOT_FOUND, 'room-not-found'],\n\t[TLSyncErrorCloseEventReason.FORBIDDEN, 'forbidden'],\n\t[TLSyncErrorCloseEventReason.NOT_AUTHENTICATED, 'not-authenticated'],\n\t[TLSyncErrorCloseEventReason.RATE_LIMITED, 'rate-limited'],\n])\n\ntype SyncSocket = TLPersistentClientSocket<\n\tTLSocketClientSentEvent<TLRecord>,\n\tTLSocketServerSentEvent<TLRecord>\n>\n\n// The socket reports 'error' but the collaboration status only knows 'offline'.\nfunction toCollaborationStatus(status: SyncSocket['connectionStatus']) {\n\treturn status === 'error' ? 'offline' : status\n}\n\n/**\n * A store wrapper specifically for remote collaboration that excludes local-only states.\n * This type represents a tldraw store that is synchronized with a remote multiplayer server.\n *\n * Unlike the base TLStoreWithStatus, this excludes 'synced-local' and 'not-synced' states\n * since remote stores are always either loading, connected to a server, or in an error state.\n *\n * @example\n * ```tsx\n * function MyCollaborativeApp() {\n * const store: RemoteTLStoreWithStatus = useSync({\n * uri: 'wss://myserver.com/sync/room-123',\n * assets: myAssetStore\n * })\n *\n * if (store.status === 'loading') {\n * return <div>Connecting to multiplayer session...</div>\n * }\n *\n * if (store.status === 'error') {\n * return <div>Connection failed: {store.error.message}</div>\n * }\n *\n * // store.status === 'synced-remote'\n * return <Tldraw store={store.store} />\n * }\n * ```\n *\n * @public\n */\nexport type RemoteTLStoreWithStatus =\n\t| Exclude<\n\t\t\tTLStoreWithStatus,\n\t\t\t{ status: 'synced-local' } | { status: 'not-synced' } | { status: 'synced-remote' }\n\t >\n\t| (Extract<TLStoreWithStatus, { status: 'synced-remote' }> & {\n\t\t\t/**\n\t\t\t * Write access for object-store lane record types (e.g. comments), as granted by the\n\t\t\t * server for this session. Independent of the canvas read-only state, so a session can\n\t\t\t * be allowed to comment without being allowed to edit. Defaults to `'write'`.\n\t\t\t */\n\t\t\treadonly objectAccess: TLObjectStoreAccess\n\t })\n\n/**\n * Creates a reactive store synchronized with a multiplayer server for real-time collaboration.\n *\n * This hook manages the complete lifecycle of a collaborative tldraw session, including\n * WebSocket connection establishment, state synchronization, user presence, and error handling.\n * The returned store can be passed directly to the Tldraw component to enable multiplayer features.\n *\n * The store progresses through multiple states:\n * - `loading`: Establishing connection and synchronizing initial state\n * - `synced-remote`: Successfully connected and actively synchronizing changes\n * - `error`: Connection failed or synchronization error occurred\n *\n * For optimal performance with media assets, provide an `assets` store that implements\n * external blob storage. Without this, large images and videos will be stored inline\n * as base64, causing performance issues during serialization.\n *\n * @param opts - Configuration options for multiplayer synchronization\n * - `uri` - WebSocket server URI (string or async function returning URI)\n * - `assets` - Asset store for blob storage (required for production use)\n * - `users` - User store for identity, presence and attribution\n * - `getUserPresence` - Optional function to customize presence data\n * - `onCustomMessageReceived` - Handler for custom socket messages\n * - `roomId` - Room identifier for analytics (internal use)\n * - `onMount` - Callback when editor mounts (internal use)\n * - `trackAnalyticsEvent` - Analytics event tracker (internal use)\n *\n * @returns A reactive store wrapper with connection status and synchronized store\n *\n * @example\n * ```tsx\n * // Basic multiplayer setup\n * function CollaborativeApp() {\n * const store = useSync({\n * uri: 'wss://myserver.com/sync/room-123',\n * assets: myAssetStore,\n * users: {\n * currentUser: computed('current-user', () => ({\n * id: createUserId('user-1'),\n * name: 'Alice',\n * color: '#ff0000',\n * meta: {},\n * })),\n * }\n * })\n *\n * if (store.status === 'loading') {\n * return <div>Connecting to collaboration session...</div>\n * }\n *\n * if (store.status === 'error') {\n * return <div>Failed to connect: {store.error.message}</div>\n * }\n *\n * return <Tldraw store={store.store} />\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Dynamic authentication with user store\n * function AuthenticatedApp() {\n * const store = useSync({\n * uri: async () => {\n * const token = await getAuthToken()\n * return `wss://myserver.com/sync/room-123?token=${token}`\n * },\n * assets: authenticatedAssetStore,\n * users: myUserStore,\n * getUserPresence: (store, user) => {\n * return {\n * userId: user.id,\n * userName: user.name,\n * cursor: getCurrentCursor(store)\n * }\n * }\n * })\n *\n * return <Tldraw store={store.store} />\n * }\n * ```\n *\n * @public\n */\nexport function useSync(opts: UseSyncOptions & TLStoreSchemaOptions): RemoteTLStoreWithStatus {\n\tconst [state, setState] = useRefState<{\n\t\treadyClient?: TLSyncClient<TLRecord, TLStore>\n\t\terror?: Error\n\t\tobjectAccess?: TLObjectStoreAccess\n\t} | null>(null)\n\tconst {\n\t\turi,\n\t\troomId = 'default',\n\t\tassets,\n\t\tusers: _users,\n\t\tonMount,\n\t\tconnect,\n\t\ttrackAnalyticsEvent: track,\n\t\tgetUserPresence: _getUserPresence,\n\t\tonCustomMessageReceived: _onCustomMessageReceived,\n\t\tthemes,\n\t\t...schemaOpts\n\t} = opts\n\n\t// This line will throw a type error if we add any new options to the useSync hook but we don't destructure them\n\t// This is required because otherwise the useTLSchemaFromUtils might return a new schema on every render if the newly-added option\n\t// is allowed to be unstable\n\tconst __never__: never = 0 as any as keyof Omit<typeof schemaOpts, keyof TLStoreSchemaOptions>\n\n\tconst resolvedThemes = resolveThemes(themes)\n\tregisterColorsFromThemes(resolvedThemes)\n\tregisterFontsFromThemes(resolvedThemes)\n\tconst schema = useTLSchemaFromUtils(schemaOpts)\n\n\tconst getUserPresence = useReactiveEvent(\n\t\t(_getUserPresence ?? getDefaultUserPresence) as typeof getDefaultUserPresence\n\t)\n\tconst onCustomMessageReceived = useEvent(_onCustomMessageReceived ?? defaultCustomMessageHandler)\n\n\tuseEffect(() => {\n\t\tconst storeId = uniqueId()\n\n\t\tconst currentUserSignal = _users?.currentUser ?? defaultUserStore.currentUser\n\t\tconst users: Required<TLUserStore> = {\n\t\t\tcurrentUser: currentUserSignal,\n\t\t\tresolve:\n\t\t\t\t_users?.resolve ??\n\t\t\t\tcreateCachedUserResolve((userId) => {\n\t\t\t\t\tconst id = createUserId(userId)\n\t\t\t\t\tconst current = currentUserSignal.get()\n\t\t\t\t\tif (current && current.id === id) return current\n\t\t\t\t\t// Only the default user store falls back to presence records for other users.\n\t\t\t\t\tif (_users) return null\n\t\t\t\t\tconst match = store.query\n\t\t\t\t\t\t.records('instance_presence')\n\t\t\t\t\t\t.get()\n\t\t\t\t\t\t.find((p) => p.userId === id)\n\t\t\t\t\treturn match\n\t\t\t\t\t\t? UserRecordType.create({ id, name: match.userName, color: match.color })\n\t\t\t\t\t\t: null\n\t\t\t\t}),\n\t\t}\n\n\t\t// This always returns a non-null user for presence display, falling back\n\t\t// to anonymous user preferences. The store receives the raw `users` object\n\t\t// (where currentUser may return null), so attribution via\n\t\t// getAttributionUserId() correctly returns null for anonymous sessions.\n\t\tconst currentUser = computed<TLUser>('currentUser', () => {\n\t\t\tconst user = users.currentUser.get()\n\t\t\tif (user) return user\n\t\t\tconst prefs = getUserPreferences()\n\t\t\treturn UserRecordType.create({\n\t\t\t\tid: createUserId(prefs.id),\n\t\t\t\tname: prefs.name ?? '',\n\t\t\t\tcolor: prefs.color ?? defaultUserPreferences.color,\n\t\t\t})\n\t\t})\n\n\t\tlet socket: SyncSocket\n\t\tif (connect) {\n\t\t\tif (uri) {\n\t\t\t\tthrow new Error('uri and connect cannot be used together')\n\t\t\t}\n\n\t\t\tsocket = connect({ sessionId: TAB_ID, storeId }) as SyncSocket\n\t\t} else if (uri) {\n\t\t\tsocket = new ClientWebSocketAdapter(async () => {\n\t\t\t\t// set sessionId as a query param on the uri\n\t\t\t\tconst withParams = new URL(typeof uri === 'string' ? uri : await uri())\n\t\t\t\tfor (const param of ['sessionId', 'storeId']) {\n\t\t\t\t\tif (withParams.searchParams.has(param)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`useSync. \"${param}\" is a reserved query param name. Please use a different name`\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\twithParams.searchParams.set('sessionId', TAB_ID)\n\t\t\t\twithParams.searchParams.set('storeId', storeId)\n\t\t\t\treturn withParams.toString()\n\t\t\t})\n\t\t} else {\n\t\t\tthrow new Error('uri or connect must be provided')\n\t\t}\n\n\t\tlet didCancel = false\n\n\t\tconst collaborationStatusSignal = atom(\n\t\t\t'collaboration status',\n\t\t\ttoCollaborationStatus(socket.connectionStatus)\n\t\t)\n\t\tconst unsubscribeFromConnectionStatus = socket.onStatusChange(() => {\n\t\t\tcollaborationStatusSignal.set(toCollaborationStatus(socket.connectionStatus))\n\t\t})\n\n\t\tconst syncMode = atom('sync mode', 'readwrite' as 'readonly' | 'readwrite')\n\n\t\tconst store = createTLStore({\n\t\t\tid: storeId,\n\t\t\tschema,\n\t\t\tassets,\n\t\t\tusers,\n\t\t\tonMount,\n\t\t\tcollaboration: {\n\t\t\t\tstatus: collaborationStatusSignal,\n\t\t\t\tmode: syncMode,\n\t\t\t},\n\t\t})\n\n\t\tconst presence = createPresenceStateDerivation(currentUser, {\n\t\t\tgetUserPresence,\n\t\t})(store)\n\n\t\t// Every connected session \u2014 each tab, window, or device \u2014 pushes its\n\t\t// presence on connect, so the store holds one instance_presence record per\n\t\t// *other* session in the room, including the user's own other tabs. (The\n\t\t// server never echoes a session its own record.) So an empty set means\n\t\t// we're genuinely the only session and can throttle to solo; any other\n\t\t// session \u2014 another user, or just another tab of our own \u2014 keeps us at the\n\t\t// full sync rate so edits propagate without the solo-mode lag.\n\t\tconst otherSessions = store.query.ids('instance_presence')\n\n\t\tconst presenceMode = computed<TLPresenceMode>('presenceMode', () => {\n\t\t\treturn otherSessions.get().size === 0 ? 'solo' : 'full'\n\t\t})\n\n\t\tconst client = new TLSyncClient<TLRecord, TLStore>({\n\t\t\tstore,\n\t\t\tsocket,\n\t\t\tdidCancel: () => didCancel,\n\t\t\tonLoad(client) {\n\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, { name: 'load', roomId })\n\t\t\t\t// Keep objectAccess (onAfterConnect always runs first for this client) but drop the\n\t\t\t\t// rest: an `error` left behind by a previous client (e.g. NOT_FOUND on the old uri)\n\t\t\t\t// would otherwise keep the hook reporting status 'error' for the new, healthy room.\n\t\t\t\tsetState((prev) => ({ readyClient: client, objectAccess: prev?.objectAccess }))\n\t\t\t},\n\t\t\tonSyncError(reason) {\n\t\t\t\tconsole.error('sync error', reason)\n\n\t\t\t\ttrack?.(MULTIPLAYER_EVENT_NAME, {\n\t\t\t\t\tname: SYNC_ERROR_EVENT_NAMES.get(reason) ?? 'sync-error:' + reason,\n\t\t\t\t\troomId,\n\t\t\t\t})\n\t\t\t\tsetState({ error: new TLRemoteSyncError(reason) })\n\t\t\t\tsocket.close()\n\t\t\t},\n\t\t\tonAfterConnect(_, { isReadonly, objectAccess }) {\n\t\t\t\t// Object-lane (comment) write access is decided per session by the server and can\n\t\t\t\t// change on reconnect (e.g. when the file's share tier changes), so surface it on\n\t\t\t\t// the returned status for consumers that gate comment UI. This fires before the\n\t\t\t\t// first onLoad, hence the merge in both directions.\n\t\t\t\tsetState((prev) => ({ ...prev, objectAccess }))\n\t\t\t\ttransact(() => {\n\t\t\t\t\tsyncMode.set(isReadonly ? 'readonly' : 'readwrite')\n\t\t\t\t\t// if the server crashes and loses all data it can return an empty document\n\t\t\t\t\t// when it comes back up. This is a safety check to make sure that if something like\n\t\t\t\t\t// that happens, it won't render the app broken and require a restart. The user will\n\t\t\t\t\t// most likely lose all their changes though since they'll have been working with pages\n\t\t\t\t\t// that won't exist. There's certainly something we can do to make this better.\n\t\t\t\t\t// but the likelihood of this happening is very low and maybe not worth caring about beyond this.\n\t\t\t\t\tstore.ensureStoreIsUsable()\n\t\t\t\t})\n\t\t\t},\n\t\t\tonCustomMessageReceived,\n\t\t\tpresence,\n\t\t\tpresenceMode,\n\t\t})\n\n\t\treturn () => {\n\t\t\tdidCancel = true\n\t\t\tunsubscribeFromConnectionStatus()\n\t\t\tclient.close()\n\t\t\tsocket.close()\n\t\t}\n\t}, [\n\t\tassets,\n\t\tonMount,\n\t\tconnect,\n\t\t_users,\n\t\troomId,\n\t\tschema,\n\t\tsetState,\n\t\ttrack,\n\t\turi,\n\t\tgetUserPresence,\n\t\tonCustomMessageReceived,\n\t])\n\n\treturn useValue<RemoteTLStoreWithStatus>(\n\t\t'remote synced store',\n\t\t() => {\n\t\t\tif (!state) return { status: 'loading' }\n\t\t\tif (state.error) return { status: 'error', error: state.error }\n\t\t\tif (!state.readyClient) return { status: 'loading' }\n\t\t\treturn {\n\t\t\t\tstatus: 'synced-remote',\n\t\t\t\tconnectionStatus: toCollaborationStatus(state.readyClient.socket.connectionStatus),\n\t\t\t\tstore: state.readyClient.store,\n\t\t\t\tobjectAccess: state.objectAccess ?? 'write',\n\t\t\t}\n\t\t},\n\t\t[state]\n\t)\n}\n\n/**\n * Configuration options for the {@link useSync} hook to establish multiplayer collaboration.\n *\n * This interface defines the required and optional settings for connecting to a multiplayer\n * server, managing user presence, handling assets, and customizing the collaboration experience.\n *\n * @example\n * ```tsx\n * const syncOptions: UseSyncOptions = {\n * uri: 'wss://myserver.com/sync/room-123',\n * assets: myAssetStore,\n * users: {\n * currentUser: myCurrentUserSignal,\n * },\n * getUserPresence: (store, user) => ({\n * userId: user.id,\n * userName: user.name,\n * cursor: getCursorPosition()\n * })\n * }\n * ```\n *\n * @public\n */\nexport interface UseSyncOptionsBase {\n\t/**\n\t * Named theme definitions. When provided, custom color names are automatically\n\t * registered before the store is constructed so persisted data with those\n\t * colors passes validation on load.\n\t */\n\tthemes?: Partial<TLThemes>\n\n\t/**\n\t * Asset store implementation for handling file uploads and storage.\n\t *\n\t * Required for production applications to handle images, videos, and other\n\t * media efficiently. Without an asset store, files are stored inline as\n\t * base64, which causes performance issues with large files.\n\t *\n\t * The asset store must implement upload (for new files) and resolve\n\t * (for displaying existing files) methods. For prototyping, you can use\n\t * {@link @tldraw/editor#inlineBase64AssetStore} but this is not recommended for production.\n\t *\n\t * @example\n\t * ```ts\n\t * const myAssetStore: TLAssetStore = {\n\t * upload: async (asset, file) => {\n\t * const url = await uploadToCloudStorage(file)\n\t * return { src: url }\n\t * },\n\t * resolve: (asset, context) => {\n\t * return getOptimizedUrl(asset.src, context)\n\t * }\n\t * }\n\t * ```\n\t */\n\tassets: TLAssetStore\n\n\t/**\n\t * User store for identity, presence and attribution.\n\t *\n\t * Both methods return reactive {@link @tldraw/state#Signal | Signals}.\n\t * `currentUser` provides the current user's identity (used for\n\t * both presence broadcasting and shape attribution) and optionally\n\t * `resolve(userId)` looks up other users by ID. If not provided,\n\t * a default implementation backed by localStorage user preferences is\n\t * used, with `resolve` falling back to presence records in the store.\n\t */\n\tusers?: TLUserStore\n\n\t/**\n\t * Handler for receiving custom messages sent through the multiplayer connection.\n\t *\n\t * Use this to implement custom communication channels between clients beyond\n\t * the standard shape and presence synchronization. Messages are sent using\n\t * the TLSyncClient's sendMessage method.\n\t *\n\t * @param data - The custom message data received from another client\n\t *\n\t * @example\n\t * ```ts\n\t * onCustomMessageReceived: (data) => {\n\t * if (data.type === 'chat') {\n\t * displayChatMessage(data.message, data.userId)\n\t * }\n\t * }\n\t * ```\n\t */\n\tonCustomMessageReceived?(data: any): void\n\n\t/** @internal */\n\tonMount?(editor: Editor): void\n\t/** @internal used for analytics only, we should refactor this away */\n\troomId?: string\n\t/** @internal */\n\ttrackAnalyticsEvent?(name: string, data: { [key: string]: any }): void\n\n\t/**\n\t * A reactive function that returns a {@link @tldraw/tlschema#TLInstancePresence} object.\n\t *\n\t * This function is called reactively whenever the store state changes and\n\t * determines what presence information to broadcast to other clients. The\n\t * result is synchronized across all connected clients for displaying cursors,\n\t * selections, and other collaborative indicators.\n\t *\n\t * If not provided, uses the default implementation which includes standard\n\t * cursor position and selection state. Custom implementations allow you to\n\t * add additional presence data like current tool, view state, or custom status.\n\t *\n\t * See {@link @tldraw/tlschema#getDefaultUserPresence} for\n\t * the default implementation of this function.\n\t *\n\t * @param store - The current TLStore\n\t * @param user - The current user information\n\t * @returns Presence state to broadcast to other clients, or null to hide presence\n\t *\n\t * @example\n\t * ```ts\n\t * getUserPresence: (store, user) => {\n\t * return {\n\t * userId: user.id,\n\t * userName: user.name,\n\t * cursor: { x: 100, y: 200 },\n\t * currentTool: 'select',\n\t * isActive: true\n\t * }\n\t * }\n\t * ```\n\t */\n\tgetUserPresence?(store: TLStore, user: TLUser): TLPresenceStateInfo | null\n}\n\n/** @public */\nexport interface UseSyncOptionsWithUri extends UseSyncOptionsBase {\n\t/**\n\t * The WebSocket URI of the multiplayer server for real-time synchronization.\n\t *\n\t * Must include the protocol (wss:// for secure, ws:// for local development).\n\t * HTTP/HTTPS URLs will be automatically upgraded to WebSocket connections.\n\t *\n\t * Can be a static string or a function that returns a URI (useful for dynamic\n\t * authentication tokens or room routing). The function is called on each\n\t * connection attempt, allowing for token refresh and dynamic routing.\n\t *\n\t * Reserved query parameters `sessionId` and `storeId` are automatically added\n\t * by the sync system and should not be included in your URI.\n\t *\n\t * @example\n\t * ```ts\n\t * // Static URI\n\t * uri: 'wss://myserver.com/sync/room-123'\n\t *\n\t * // Dynamic URI with authentication\n\t * uri: async () => {\n\t * const token = await getAuthToken()\n\t * return `wss://myserver.com/sync/room-123?token=${token}`\n\t * }\n\t * ```\n\t */\n\turi: string | (() => string | Promise<string>)\n\tconnect?: never\n}\n\n/** @public */\nexport interface UseSyncOptionsWithConnectFn extends UseSyncOptionsBase {\n\t/**\n\t * Create a connection to the server. Mostly you should use {@link UseSyncOptionsWithUri.uri}\n\t * instead, but this is useful if you want to use a custom transport to connect to the server,\n\t * instead of our default websocket-based transport.\n\t */\n\tconnect: UseSyncConnectFn\n\turi?: never\n}\n\n/** @public */\nexport type UseSyncConnectFn = (query: {\n\tsessionId: string\n\tstoreId: string\n}) => TLPersistentClientSocket\n\n/**\n * Options for the {@link useSync} hook.\n * @public\n */\nexport type UseSyncOptions = UseSyncOptionsWithUri | UseSyncOptionsWithConnectFn\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA+B;AAC/B,uBAWO;AACP,mBAA0B;AAC1B,oBA+BO;AAEP,MAAM,yBAAyB;AAE/B,MAAM,8BAAsD,MAAM;AAAC;AAInE,MAAM,yBAAyB,oBAAI,IAAoB;AAAA,EACtD,CAAC,6CAA4B,WAAW,gBAAgB;AAAA,EACxD,CAAC,6CAA4B,WAAW,WAAW;AAAA,EACnD,CAAC,6CAA4B,mBAAmB,mBAAmB;AAAA,EACnE,CAAC,6CAA4B,cAAc,cAAc;AAC1D,CAAC;AAQD,SAAS,sBAAsB,QAAwC;AACtE,SAAO,WAAW,UAAU,YAAY;AACzC;AAiIO,SAAS,QAAQ,MAAsE;AAC7F,QAAM,CAAC,OAAO,QAAQ,QAAI,2BAIhB,IAAI;AACd,QAAM;AAAA,IACL;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA,qBAAqB;AAAA,IACrB,iBAAiB;AAAA,IACjB,yBAAyB;AAAA,IACzB;AAAA,IACA,GAAG;AAAA,EACJ,IAAI;AAKJ,QAAM,YAAmB;AAEzB,QAAM,qBAAiB,6BAAc,MAAM;AAC3C,8CAAyB,cAAc;AACvC,6CAAwB,cAAc;AACtC,QAAM,aAAS,oCAAqB,UAAU;AAE9C,Q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options) {
|
|
|
51
51
|
assets,
|
|
52
52
|
onMount: (0, import_react.useCallback)(
|
|
53
53
|
(editor) => {
|
|
54
|
-
editor.registerExternalAssetHandler(
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
editor.registerExternalAssetHandler(
|
|
55
|
+
"url",
|
|
56
|
+
({ url }) => createAssetFromUrlUsingDemoServer(host, url)
|
|
57
|
+
);
|
|
57
58
|
},
|
|
58
59
|
[host]
|
|
59
60
|
),
|
|
@@ -73,8 +74,7 @@ function createDemoAssetStore(host) {
|
|
|
73
74
|
alert("Uploading images is disabled in this demo.");
|
|
74
75
|
throw new Error("Uploading images is disabled in this demo.");
|
|
75
76
|
}
|
|
76
|
-
const
|
|
77
|
-
const objectName = `${id}-${file.name}`.replace(/\W/g, "-");
|
|
77
|
+
const objectName = `${(0, import_tldraw.uniqueId)()}-${file.name}`.replace(/\W/g, "-");
|
|
78
78
|
const url = `${host}/uploads/${objectName}`;
|
|
79
79
|
const response = await fetch(url, {
|
|
80
80
|
method: "POST",
|
|
@@ -86,18 +86,18 @@ function createDemoAssetStore(host) {
|
|
|
86
86
|
return { src: url };
|
|
87
87
|
},
|
|
88
88
|
resolve(asset, context) {
|
|
89
|
-
|
|
90
|
-
if (
|
|
89
|
+
const { src } = asset.props;
|
|
90
|
+
if (!src) return null;
|
|
91
|
+
if (asset.type === "video") return src;
|
|
91
92
|
if (asset.type !== "image") return null;
|
|
92
|
-
if (!
|
|
93
|
-
|
|
94
|
-
if (
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const url = new URL(asset.props.src);
|
|
93
|
+
if (!src.startsWith("http:") && !src.startsWith("https:")) return src;
|
|
94
|
+
if (context.shouldResolveToOriginal) return src;
|
|
95
|
+
if (import_tldraw.MediaHelpers.isAnimatedImageType(asset.props.mimeType) || asset.props.isAnimated)
|
|
96
|
+
return src;
|
|
97
|
+
if (import_tldraw.MediaHelpers.isVectorImageType(asset.props.mimeType)) return src;
|
|
98
|
+
const url = new URL(src);
|
|
99
99
|
const isTldrawImage = url.origin === host || /\.tldraw\.(?:com|xyz|dev|workers\.dev)$/.test(url.host);
|
|
100
|
-
if (!isTldrawImage) return
|
|
100
|
+
if (!isTldrawImage) return src;
|
|
101
101
|
const { fileSize = 0 } = asset.props;
|
|
102
102
|
const isWorthResizing = fileSize >= 1024 * 1024 * 1.5;
|
|
103
103
|
if (isWorthResizing) {
|
|
@@ -112,45 +112,31 @@ function createDemoAssetStore(host) {
|
|
|
112
112
|
);
|
|
113
113
|
url.searchParams.set("w", width.toString());
|
|
114
114
|
}
|
|
115
|
-
|
|
116
|
-
return newUrl;
|
|
115
|
+
return `${IMAGE_WORKER}/${url.host}/${url.toString().slice(url.origin.length + 1)}`;
|
|
117
116
|
}
|
|
118
117
|
};
|
|
119
118
|
}
|
|
120
119
|
async function createAssetFromUrlUsingDemoServer(host, url) {
|
|
121
|
-
|
|
120
|
+
let meta = null;
|
|
122
121
|
try {
|
|
123
122
|
const fetchUrl = new URL(`${host}/bookmarks/unfurl`);
|
|
124
123
|
fetchUrl.searchParams.set("url", url);
|
|
125
|
-
|
|
126
|
-
return {
|
|
127
|
-
id: import_tldraw.AssetRecordType.createId(urlHash),
|
|
128
|
-
typeName: "asset",
|
|
129
|
-
type: "bookmark",
|
|
130
|
-
props: {
|
|
131
|
-
src: url,
|
|
132
|
-
description: meta?.description ?? "",
|
|
133
|
-
image: meta?.image ?? "",
|
|
134
|
-
favicon: meta?.favicon ?? "",
|
|
135
|
-
title: meta?.title ?? ""
|
|
136
|
-
},
|
|
137
|
-
meta: {}
|
|
138
|
-
};
|
|
124
|
+
meta = await (await fetch(fetchUrl, { method: "POST" })).json();
|
|
139
125
|
} catch (error) {
|
|
140
126
|
console.error(error);
|
|
141
|
-
return {
|
|
142
|
-
id: import_tldraw.AssetRecordType.createId(urlHash),
|
|
143
|
-
typeName: "asset",
|
|
144
|
-
type: "bookmark",
|
|
145
|
-
props: {
|
|
146
|
-
src: url,
|
|
147
|
-
description: "",
|
|
148
|
-
image: "",
|
|
149
|
-
favicon: "",
|
|
150
|
-
title: ""
|
|
151
|
-
},
|
|
152
|
-
meta: {}
|
|
153
|
-
};
|
|
154
127
|
}
|
|
128
|
+
return {
|
|
129
|
+
id: import_tldraw.AssetRecordType.createId((0, import_tldraw.getHashForString)(url)),
|
|
130
|
+
typeName: "asset",
|
|
131
|
+
type: "bookmark",
|
|
132
|
+
props: {
|
|
133
|
+
src: url,
|
|
134
|
+
description: meta?.description ?? "",
|
|
135
|
+
image: meta?.image ?? "",
|
|
136
|
+
favicon: meta?.favicon ?? "",
|
|
137
|
+
title: meta?.title ?? ""
|
|
138
|
+
},
|
|
139
|
+
meta: {}
|
|
140
|
+
};
|
|
155
141
|
}
|
|
156
142
|
//# sourceMappingURL=useSyncDemo.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/useSyncDemo.ts"],
|
|
4
|
-
"sourcesContent": ["import { useCallback, useMemo } from 'react'\nimport {\n\tAssetRecordType,\n\tEditor,\n\tMediaHelpers,\n\tTLAsset,\n\tTLAssetStore,\n\tTLPresenceStateInfo,\n\tTLStore,\n\tTLStoreSchemaOptions,\n\tTLUser,\n\tTLUserStore,\n\tclamp,\n\tdefaultBindingUtils,\n\tdefaultShapeUtils,\n\tgetHashForString,\n\tuniqueId,\n\tuseShallowObjectIdentity,\n} from 'tldraw'\nimport { RemoteTLStoreWithStatus, useSync } from './useSync'\n\n/** @public */\nexport interface UseSyncDemoOptions {\n\t/**\n\t * The room ID to sync with. Make sure the room ID is unique. The namespace is shared by\n\t * everyone using the demo server. Consider prefixing it with your company or project name.\n\t */\n\troomId: string\n\n\t/**\n\t * User store for identity, presence and attribution.\n\t * If not provided, a default implementation based on localStorage will be used.\n\t */\n\tusers?: TLUserStore\n\n\t/** @internal */\n\thost?: string\n\n\t/**\n\t * {@inheritdoc UseSyncOptions.getUserPresence}\n\t * @public\n\t */\n\tgetUserPresence?(store: TLStore, user: TLUser): TLPresenceStateInfo | null\n}\n\n/**\n * Safely accesses environment variables across different bundling environments.\n *\n * Depending on the environment this package is used in, process.env may not be available. This function\n * wraps `process.env` accesses in a try/catch to prevent runtime errors in environments where process\n * is not defined.\n *\n * The reason that this is just a try/catch and not a dynamic check e.g. `process &&\n * process.env[key]` is that many bundlers implement `process.env.WHATEVER` using compile-time\n * string replacement, rather than actually creating a runtime implementation of a `process` object.\n *\n * @param cb - Callback function that accesses an environment variable\n * @returns The environment variable value if available, otherwise undefined\n * @internal\n */\nfunction getEnv(cb: () => string | undefined): string | undefined {\n\ttry {\n\t\treturn cb()\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nconst DEMO_WORKER = getEnv(() => process.env.TLDRAW_BEMO_URL) ?? 'https://demo.tldraw.xyz'\nconst IMAGE_WORKER = getEnv(() => process.env.TLDRAW_IMAGE_URL) ?? 'https://images.tldraw.xyz'\n\n/**\n * Creates a tldraw store synced with a multiplayer room hosted on tldraw's demo server `https://demo.tldraw.xyz`.\n *\n * The store can be passed directly into the `<Tldraw />` component to enable multiplayer features.\n * It will handle loading states, and enable multiplayer UX like user cursors and following.\n *\n * All data on the demo server is\n *\n * - Deleted after a day or so.\n * - Publicly accessible to anyone who knows the room ID. Use your company name as a prefix to help avoid collisions, or generate UUIDs for maximum privacy.\n *\n * @example\n * ```tsx\n * function MyApp() {\n * const store = useSyncDemo({roomId: 'my-app-test-room'})\n * return <Tldraw store={store} />\n * }\n * ```\n *\n * @param options - Options for the multiplayer demo sync store. See {@link UseSyncDemoOptions} and {@link @tldraw/editor#TLStoreSchemaOptions}.\n *\n * @public\n */\nexport function useSyncDemo(\n\toptions: UseSyncDemoOptions & TLStoreSchemaOptions\n): RemoteTLStoreWithStatus {\n\tconst { roomId, host = DEMO_WORKER, ..._syncOpts } = options\n\tconst assets = useMemo(() => createDemoAssetStore(host), [host])\n\n\tconst syncOpts = useShallowObjectIdentity(_syncOpts)\n\tconst syncOptsWithDefaults = useMemo(() => {\n\t\tif ('schema' in syncOpts && syncOpts.schema) return syncOpts\n\n\t\treturn {\n\t\t\t...syncOpts,\n\t\t\tshapeUtils:\n\t\t\t\t'shapeUtils' in syncOpts\n\t\t\t\t\t? [...defaultShapeUtils, ...(syncOpts.shapeUtils ?? [])]\n\t\t\t\t\t: defaultShapeUtils,\n\t\t\tbindingUtils:\n\t\t\t\t'bindingUtils' in syncOpts\n\t\t\t\t\t? [...defaultBindingUtils, ...(syncOpts.bindingUtils ?? [])]\n\t\t\t\t\t: defaultBindingUtils,\n\t\t}\n\t}, [syncOpts])\n\n\treturn useSync({\n\t\turi: `${host}/connect/${encodeURIComponent(roomId)}`,\n\t\troomId,\n\t\tassets,\n\t\tonMount: useCallback(\n\t\t\t(editor: Editor) => {\n\t\t\t\teditor.registerExternalAssetHandler('url', async ({ url }) => {\n\t\t\t\t\treturn await createAssetFromUrlUsingDemoServer(host, url)\n\t\t\t\t})\n\t\t\t},\n\t\t\t[host]\n\t\t),\n\t\t...syncOptsWithDefaults,\n\t})\n}\n\n/**\n * Determines whether file uploads should be disabled for a given host.\n *\n * Uploads are disabled for production tldraw domains to prevent abuse of the demo server\n * infrastructure. This includes tldraw.com and tldraw.xyz domains and their subdomains.\n *\n * @param host - The host URL to check for upload restrictions\n * @returns True if uploads should be disabled, false otherwise\n * @internal\n */\nfunction shouldDisallowUploads(host: string) {\n\tconst disallowedHosts = ['tldraw.com', 'tldraw.xyz']\n\treturn disallowedHosts.some(\n\t\t(disallowedHost) => host === disallowedHost || host.endsWith(`.${disallowedHost}`)\n\t)\n}\n\n/**\n * Creates an asset store implementation optimized for the tldraw demo server.\n *\n * This asset store handles file uploads to the demo server and provides intelligent\n * asset resolution with automatic image optimization based on network conditions,\n * screen density, and display size. It includes safeguards to prevent uploads to\n * production domains and optimizes images through the tldraw image processing service.\n *\n * @param host - The demo server host URL for file uploads and asset resolution\n * @returns A TLAssetStore implementation with upload and resolve capabilities\n * @example\n * ```ts\n * const assetStore = createDemoAssetStore('https://demo.tldraw.xyz')\n *\n * // Upload a file\n * const result = await assetStore.upload(asset, file)\n * console.log('Uploaded to:', result.src)\n *\n * // Resolve optimized asset URL\n * const optimizedUrl = assetStore.resolve(imageAsset, {\n * steppedScreenScale: 1.5,\n * dpr: 2,\n * networkEffectiveType: '4g'\n * })\n * ```\n * @internal\n */\nfunction createDemoAssetStore(host: string): TLAssetStore {\n\treturn {\n\t\tupload: async (_asset, file) => {\n\t\t\tif (shouldDisallowUploads(host)) {\n\t\t\t\talert('Uploading images is disabled in this demo.')\n\t\t\t\tthrow new Error('Uploading images is disabled in this demo.')\n\t\t\t}\n\t\t\tconst id = uniqueId()\n\n\t\t\tconst objectName = `${id}-${file.name}`.replace(/\\W/g, '-')\n\t\t\tconst url = `${host}/uploads/${objectName}`\n\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: file,\n\t\t\t})\n\t\t\t// a rejected upload (invalid name, duplicate, server error) resolves the fetch; without\n\t\t\t// this the asset would point at a URL that was never stored\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`Failed to upload asset (${response.status})`)\n\t\t\t}\n\n\t\t\treturn { src: url }\n\t\t},\n\n\t\tresolve(asset, context) {\n\t\t\tif (!asset.props.src) return null\n\n\t\t\t// We don't deal with videos at the moment.\n\t\t\tif (asset.type === 'video') return asset.props.src\n\n\t\t\t// Assert it's an image to make TS happy.\n\t\t\tif (asset.type !== 'image') return null\n\n\t\t\t// Don't try to transform data: URLs, yikes.\n\t\t\tif (!asset.props.src.startsWith('http:') && !asset.props.src.startsWith('https:'))\n\t\t\t\treturn asset.props.src\n\n\t\t\tif (context.shouldResolveToOriginal) return asset.props.src\n\n\t\t\t// Don't try to transform animated images.\n\t\t\tif (MediaHelpers.isAnimatedImageType(asset?.props.mimeType) || asset.props.isAnimated)\n\t\t\t\treturn asset.props.src\n\n\t\t\t// Don't try to transform vector images.\n\t\t\tif (MediaHelpers.isVectorImageType(asset?.props.mimeType)) return asset.props.src\n\n\t\t\tconst url = new URL(asset.props.src)\n\n\t\t\t// we only transform images that are hosted on domains we control\n\t\t\tconst isTldrawImage =\n\t\t\t\turl.origin === host || /\\.tldraw\\.(?:com|xyz|dev|workers\\.dev)$/.test(url.host)\n\n\t\t\tif (!isTldrawImage) return asset.props.src\n\n\t\t\t// Assets that are under a certain file size aren't worth transforming (and incurring cost).\n\t\t\t// We still send them through the image worker to get them optimized though.\n\t\t\tconst { fileSize = 0 } = asset.props\n\t\t\tconst isWorthResizing = fileSize >= 1024 * 1024 * 1.5\n\n\t\t\tif (isWorthResizing) {\n\t\t\t\t// N.B. navigator.connection is only available in certain browsers (mainly Blink-based browsers)\n\t\t\t\t// 4g is as high the 'effectiveType' goes and we can pick a lower effective image quality for slower connections.\n\t\t\t\tconst networkCompensation =\n\t\t\t\t\t!context.networkEffectiveType || context.networkEffectiveType === '4g' ? 1 : 0.5\n\n\t\t\t\tconst pixelRatio = asset.props.pixelRatio ?? 1\n\t\t\t\tconst trueWidth = asset.props.w * pixelRatio\n\t\t\t\tconst width = Math.ceil(\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\ttrueWidth *\n\t\t\t\t\t\t\tclamp(context.steppedScreenScale, 1 / 32, 1) *\n\t\t\t\t\t\t\tnetworkCompensation *\n\t\t\t\t\t\t\tcontext.dpr,\n\t\t\t\t\t\ttrueWidth\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\turl.searchParams.set('w', width.toString())\n\t\t\t}\n\n\t\t\tconst newUrl = `${IMAGE_WORKER}/${url.host}/${url.toString().slice(url.origin.length + 1)}`\n\t\t\treturn newUrl\n\t\t},\n\t}\n}\n\n/**\n * Creates a bookmark asset by fetching metadata from a URL using the demo server.\n *\n * This function uses the demo server's bookmark unfurling service to extract metadata\n * like title, description, favicon, and preview image from a given URL. If the metadata\n * fetch fails, it returns a blank bookmark asset with just the URL.\n *\n * @param host - The demo server host URL to use for bookmark unfurling\n * @param url - The URL to create a bookmark asset from\n * @returns A promise that resolves to a TLAsset of type 'bookmark' with extracted metadata\n * @example\n * ```ts\n * const asset = await createAssetFromUrlUsingDemoServer(\n * 'https://demo.tldraw.xyz',\n * 'https://example.com'\n * )\n *\n * console.log(asset.props.title) // \"Example Domain\"\n * console.log(asset.props.description) // \"This domain is for use in illustrative examples...\"\n * ```\n * @internal\n */\nasync function createAssetFromUrlUsingDemoServer(host: string, url: string): Promise<TLAsset> {\n\tconst urlHash = getHashForString(url)\n\ttry {\n\t\t// First, try to get the meta data from our endpoint\n\t\tconst fetchUrl = new URL(`${host}/bookmarks/unfurl`)\n\t\tfetchUrl.searchParams.set('url', url)\n\n\t\tconst meta = (await (await fetch(fetchUrl, { method: 'POST' })).json()) as {\n\t\t\tdescription?: string\n\t\t\timage?: string\n\t\t\tfavicon?: string\n\t\t\ttitle?: string\n\t\t} | null\n\n\t\treturn {\n\t\t\tid: AssetRecordType.createId(urlHash),\n\t\t\ttypeName: 'asset',\n\t\t\ttype: 'bookmark',\n\t\t\tprops: {\n\t\t\t\tsrc: url,\n\t\t\t\tdescription: meta?.description ?? '',\n\t\t\t\timage: meta?.image ?? '',\n\t\t\t\tfavicon: meta?.favicon ?? '',\n\t\t\t\ttitle: meta?.title ?? '',\n\t\t\t},\n\t\t\tmeta: {},\n\t\t}\n\t} catch (error) {\n\t\t// Otherwise, fallback to a blank bookmark\n\t\tconsole.error(error)\n\t\treturn {\n\t\t\tid: AssetRecordType.createId(urlHash),\n\t\t\ttypeName: 'asset',\n\t\t\ttype: 'bookmark',\n\t\t\tprops: {\n\t\t\t\tsrc: url,\n\t\t\t\tdescription: '',\n\t\t\t\timage: '',\n\t\t\t\tfavicon: '',\n\t\t\t\ttitle: '',\n\t\t\t},\n\t\t\tmeta: {},\n\t\t}\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAqC;AACrC,oBAiBO;AACP,qBAAiD;AAyCjD,SAAS,OAAO,IAAkD;AACjE,MAAI;AACH,WAAO,GAAG;AAAA,EACX,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AAEA,MAAM,cAAc,OAAO,MAAM,gCAA2B,KAAK;AACjE,MAAM,eAAe,OAAO,MAAM,QAAQ,IAAI,gBAAgB,KAAK;AAyB5D,SAAS,YACf,SAC0B;AAC1B,QAAM,EAAE,QAAQ,OAAO,aAAa,GAAG,UAAU,IAAI;AACrD,QAAM,aAAS,sBAAQ,MAAM,qBAAqB,IAAI,GAAG,CAAC,IAAI,CAAC;AAE/D,QAAM,eAAW,wCAAyB,SAAS;AACnD,QAAM,2BAAuB,sBAAQ,MAAM;AAC1C,QAAI,YAAY,YAAY,SAAS,OAAQ,QAAO;AAEpD,WAAO;AAAA,MACN,GAAG;AAAA,MACH,YACC,gBAAgB,WACb,CAAC,GAAG,iCAAmB,GAAI,SAAS,cAAc,CAAC,CAAE,IACrD;AAAA,MACJ,cACC,kBAAkB,WACf,CAAC,GAAG,mCAAqB,GAAI,SAAS,gBAAgB,CAAC,CAAE,IACzD;AAAA,IACL;AAAA,EACD,GAAG,CAAC,QAAQ,CAAC;AAEb,aAAO,wBAAQ;AAAA,IACd,KAAK,GAAG,IAAI,YAAY,mBAAmB,MAAM,CAAC;AAAA,IAClD;AAAA,IACA;AAAA,IACA,aAAS;AAAA,MACR,CAAC,WAAmB;AACnB,eAAO,
|
|
4
|
+
"sourcesContent": ["import { useCallback, useMemo } from 'react'\nimport {\n\tAssetRecordType,\n\tEditor,\n\tMediaHelpers,\n\tTLAsset,\n\tTLAssetStore,\n\tTLPresenceStateInfo,\n\tTLStore,\n\tTLStoreSchemaOptions,\n\tTLUser,\n\tTLUserStore,\n\tclamp,\n\tdefaultBindingUtils,\n\tdefaultShapeUtils,\n\tgetHashForString,\n\tuniqueId,\n\tuseShallowObjectIdentity,\n} from 'tldraw'\nimport { RemoteTLStoreWithStatus, useSync } from './useSync'\n\n/** @public */\nexport interface UseSyncDemoOptions {\n\t/**\n\t * The room ID to sync with. Make sure the room ID is unique. The namespace is shared by\n\t * everyone using the demo server. Consider prefixing it with your company or project name.\n\t */\n\troomId: string\n\n\t/**\n\t * User store for identity, presence and attribution.\n\t * If not provided, a default implementation based on localStorage will be used.\n\t */\n\tusers?: TLUserStore\n\n\t/** @internal */\n\thost?: string\n\n\t/**\n\t * {@inheritdoc UseSyncOptions.getUserPresence}\n\t * @public\n\t */\n\tgetUserPresence?(store: TLStore, user: TLUser): TLPresenceStateInfo | null\n}\n\n/**\n * Safely accesses environment variables across different bundling environments.\n *\n * Depending on the environment this package is used in, process.env may not be available. This function\n * wraps `process.env` accesses in a try/catch to prevent runtime errors in environments where process\n * is not defined.\n *\n * The reason that this is just a try/catch and not a dynamic check e.g. `process &&\n * process.env[key]` is that many bundlers implement `process.env.WHATEVER` using compile-time\n * string replacement, rather than actually creating a runtime implementation of a `process` object.\n *\n * @param cb - Callback function that accesses an environment variable\n * @returns The environment variable value if available, otherwise undefined\n * @internal\n */\nfunction getEnv(cb: () => string | undefined): string | undefined {\n\ttry {\n\t\treturn cb()\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nconst DEMO_WORKER = getEnv(() => process.env.TLDRAW_BEMO_URL) ?? 'https://demo.tldraw.xyz'\nconst IMAGE_WORKER = getEnv(() => process.env.TLDRAW_IMAGE_URL) ?? 'https://images.tldraw.xyz'\n\n/**\n * Creates a tldraw store synced with a multiplayer room hosted on tldraw's demo server `https://demo.tldraw.xyz`.\n *\n * The store can be passed directly into the `<Tldraw />` component to enable multiplayer features.\n * It will handle loading states, and enable multiplayer UX like user cursors and following.\n *\n * All data on the demo server is\n *\n * - Deleted after a day or so.\n * - Publicly accessible to anyone who knows the room ID. Use your company name as a prefix to help avoid collisions, or generate UUIDs for maximum privacy.\n *\n * @example\n * ```tsx\n * function MyApp() {\n * const store = useSyncDemo({roomId: 'my-app-test-room'})\n * return <Tldraw store={store} />\n * }\n * ```\n *\n * @param options - Options for the multiplayer demo sync store. See {@link UseSyncDemoOptions} and {@link @tldraw/editor#TLStoreSchemaOptions}.\n *\n * @public\n */\nexport function useSyncDemo(\n\toptions: UseSyncDemoOptions & TLStoreSchemaOptions\n): RemoteTLStoreWithStatus {\n\tconst { roomId, host = DEMO_WORKER, ..._syncOpts } = options\n\tconst assets = useMemo(() => createDemoAssetStore(host), [host])\n\n\tconst syncOpts = useShallowObjectIdentity(_syncOpts)\n\tconst syncOptsWithDefaults = useMemo(() => {\n\t\tif ('schema' in syncOpts && syncOpts.schema) return syncOpts\n\n\t\treturn {\n\t\t\t...syncOpts,\n\t\t\tshapeUtils:\n\t\t\t\t'shapeUtils' in syncOpts\n\t\t\t\t\t? [...defaultShapeUtils, ...(syncOpts.shapeUtils ?? [])]\n\t\t\t\t\t: defaultShapeUtils,\n\t\t\tbindingUtils:\n\t\t\t\t'bindingUtils' in syncOpts\n\t\t\t\t\t? [...defaultBindingUtils, ...(syncOpts.bindingUtils ?? [])]\n\t\t\t\t\t: defaultBindingUtils,\n\t\t}\n\t}, [syncOpts])\n\n\treturn useSync({\n\t\turi: `${host}/connect/${encodeURIComponent(roomId)}`,\n\t\troomId,\n\t\tassets,\n\t\tonMount: useCallback(\n\t\t\t(editor: Editor) => {\n\t\t\t\teditor.registerExternalAssetHandler('url', ({ url }) =>\n\t\t\t\t\tcreateAssetFromUrlUsingDemoServer(host, url)\n\t\t\t\t)\n\t\t\t},\n\t\t\t[host]\n\t\t),\n\t\t...syncOptsWithDefaults,\n\t})\n}\n\n/**\n * Determines whether file uploads should be disabled for a given host.\n *\n * Uploads are disabled for production tldraw domains to prevent abuse of the demo server\n * infrastructure. This includes tldraw.com and tldraw.xyz domains and their subdomains.\n *\n * @param host - The host URL to check for upload restrictions\n * @returns True if uploads should be disabled, false otherwise\n * @internal\n */\nfunction shouldDisallowUploads(host: string) {\n\tconst disallowedHosts = ['tldraw.com', 'tldraw.xyz']\n\treturn disallowedHosts.some(\n\t\t(disallowedHost) => host === disallowedHost || host.endsWith(`.${disallowedHost}`)\n\t)\n}\n\n/**\n * Creates an asset store implementation optimized for the tldraw demo server.\n *\n * This asset store handles file uploads to the demo server and provides intelligent\n * asset resolution with automatic image optimization based on network conditions,\n * screen density, and display size. It includes safeguards to prevent uploads to\n * production domains and optimizes images through the tldraw image processing service.\n *\n * @param host - The demo server host URL for file uploads and asset resolution\n * @returns A TLAssetStore implementation with upload and resolve capabilities\n * @example\n * ```ts\n * const assetStore = createDemoAssetStore('https://demo.tldraw.xyz')\n *\n * // Upload a file\n * const result = await assetStore.upload(asset, file)\n * console.log('Uploaded to:', result.src)\n *\n * // Resolve optimized asset URL\n * const optimizedUrl = assetStore.resolve(imageAsset, {\n * steppedScreenScale: 1.5,\n * dpr: 2,\n * networkEffectiveType: '4g'\n * })\n * ```\n * @internal\n */\nfunction createDemoAssetStore(host: string): TLAssetStore {\n\treturn {\n\t\tupload: async (_asset, file) => {\n\t\t\tif (shouldDisallowUploads(host)) {\n\t\t\t\talert('Uploading images is disabled in this demo.')\n\t\t\t\tthrow new Error('Uploading images is disabled in this demo.')\n\t\t\t}\n\t\t\tconst objectName = `${uniqueId()}-${file.name}`.replace(/\\W/g, '-')\n\t\t\tconst url = `${host}/uploads/${objectName}`\n\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: file,\n\t\t\t})\n\t\t\t// a rejected upload (invalid name, duplicate, server error) resolves the fetch; without\n\t\t\t// this the asset would point at a URL that was never stored\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`Failed to upload asset (${response.status})`)\n\t\t\t}\n\n\t\t\treturn { src: url }\n\t\t},\n\n\t\tresolve(asset, context) {\n\t\t\tconst { src } = asset.props\n\t\t\tif (!src) return null\n\n\t\t\t// We don't deal with videos at the moment.\n\t\t\tif (asset.type === 'video') return src\n\n\t\t\t// Assert it's an image to make TS happy.\n\t\t\tif (asset.type !== 'image') return null\n\n\t\t\t// Don't try to transform data: URLs, yikes.\n\t\t\tif (!src.startsWith('http:') && !src.startsWith('https:')) return src\n\n\t\t\tif (context.shouldResolveToOriginal) return src\n\n\t\t\t// Don't try to transform animated images.\n\t\t\tif (MediaHelpers.isAnimatedImageType(asset.props.mimeType) || asset.props.isAnimated)\n\t\t\t\treturn src\n\n\t\t\t// Don't try to transform vector images.\n\t\t\tif (MediaHelpers.isVectorImageType(asset.props.mimeType)) return src\n\n\t\t\tconst url = new URL(src)\n\n\t\t\t// we only transform images that are hosted on domains we control\n\t\t\tconst isTldrawImage =\n\t\t\t\turl.origin === host || /\\.tldraw\\.(?:com|xyz|dev|workers\\.dev)$/.test(url.host)\n\n\t\t\tif (!isTldrawImage) return src\n\n\t\t\t// Assets that are under a certain file size aren't worth transforming (and incurring cost).\n\t\t\t// We still send them through the image worker to get them optimized though.\n\t\t\tconst { fileSize = 0 } = asset.props\n\t\t\tconst isWorthResizing = fileSize >= 1024 * 1024 * 1.5\n\n\t\t\tif (isWorthResizing) {\n\t\t\t\t// N.B. navigator.connection is only available in certain browsers (mainly Blink-based browsers)\n\t\t\t\t// 4g is as high the 'effectiveType' goes and we can pick a lower effective image quality for slower connections.\n\t\t\t\tconst networkCompensation =\n\t\t\t\t\t!context.networkEffectiveType || context.networkEffectiveType === '4g' ? 1 : 0.5\n\n\t\t\t\tconst pixelRatio = asset.props.pixelRatio ?? 1\n\t\t\t\tconst trueWidth = asset.props.w * pixelRatio\n\t\t\t\tconst width = Math.ceil(\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\ttrueWidth *\n\t\t\t\t\t\t\tclamp(context.steppedScreenScale, 1 / 32, 1) *\n\t\t\t\t\t\t\tnetworkCompensation *\n\t\t\t\t\t\t\tcontext.dpr,\n\t\t\t\t\t\ttrueWidth\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\turl.searchParams.set('w', width.toString())\n\t\t\t}\n\n\t\t\treturn `${IMAGE_WORKER}/${url.host}/${url.toString().slice(url.origin.length + 1)}`\n\t\t},\n\t}\n}\n\n/**\n * Creates a bookmark asset by fetching metadata from a URL using the demo server.\n *\n * This function uses the demo server's bookmark unfurling service to extract metadata\n * like title, description, favicon, and preview image from a given URL. If the metadata\n * fetch fails, it returns a blank bookmark asset with just the URL.\n *\n * @param host - The demo server host URL to use for bookmark unfurling\n * @param url - The URL to create a bookmark asset from\n * @returns A promise that resolves to a TLAsset of type 'bookmark' with extracted metadata\n * @example\n * ```ts\n * const asset = await createAssetFromUrlUsingDemoServer(\n * 'https://demo.tldraw.xyz',\n * 'https://example.com'\n * )\n *\n * console.log(asset.props.title) // \"Example Domain\"\n * console.log(asset.props.description) // \"This domain is for use in illustrative examples...\"\n * ```\n * @internal\n */\nasync function createAssetFromUrlUsingDemoServer(host: string, url: string): Promise<TLAsset> {\n\tlet meta: { description?: string; image?: string; favicon?: string; title?: string } | null = null\n\ttry {\n\t\t// First, try to get the meta data from our endpoint\n\t\tconst fetchUrl = new URL(`${host}/bookmarks/unfurl`)\n\t\tfetchUrl.searchParams.set('url', url)\n\t\tmeta = await (await fetch(fetchUrl, { method: 'POST' })).json()\n\t} catch (error) {\n\t\t// Otherwise, fall back to a blank bookmark\n\t\tconsole.error(error)\n\t}\n\n\treturn {\n\t\tid: AssetRecordType.createId(getHashForString(url)),\n\t\ttypeName: 'asset',\n\t\ttype: 'bookmark',\n\t\tprops: {\n\t\t\tsrc: url,\n\t\t\tdescription: meta?.description ?? '',\n\t\t\timage: meta?.image ?? '',\n\t\t\tfavicon: meta?.favicon ?? '',\n\t\t\ttitle: meta?.title ?? '',\n\t\t},\n\t\tmeta: {},\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAqC;AACrC,oBAiBO;AACP,qBAAiD;AAyCjD,SAAS,OAAO,IAAkD;AACjE,MAAI;AACH,WAAO,GAAG;AAAA,EACX,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AAEA,MAAM,cAAc,OAAO,MAAM,gCAA2B,K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