@powerhousedao/reactor-browser 6.2.2-dev.6 → 6.2.2-dev.61

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.
Files changed (66) hide show
  1. package/README.md +283 -0
  2. package/dist/attachment-service-DTFJRf5j.d.ts +1057 -0
  3. package/dist/attachment-service-DTFJRf5j.d.ts.map +1 -0
  4. package/dist/{client-_Gh2Uf0E.js → client-DB8gP4hz.js} +79 -13
  5. package/dist/client-DB8gP4hz.js.map +1 -0
  6. package/dist/client-DjkEpwu_.d.ts +14 -0
  7. package/dist/client-DjkEpwu_.d.ts.map +1 -0
  8. package/dist/{client-u13cr-Vg.js → client-Zz_l9QzI.js} +30 -3
  9. package/dist/client-Zz_l9QzI.js.map +1 -0
  10. package/dist/{document-by-id-dLYFX-xz.js → document-by-id-BSZqTN66.js} +81 -51
  11. package/dist/document-by-id-BSZqTN66.js.map +1 -0
  12. package/dist/document-operations-C6nce9dH.js +2928 -0
  13. package/dist/document-operations-C6nce9dH.js.map +1 -0
  14. package/dist/global-pg5gy2eZ.d.ts +400 -0
  15. package/dist/global-pg5gy2eZ.d.ts.map +1 -0
  16. package/dist/index-CxxxP14A.d.ts +144 -0
  17. package/dist/index-CxxxP14A.d.ts.map +1 -0
  18. package/dist/index-DjloxNSR.d.ts +345 -0
  19. package/dist/index-DjloxNSR.d.ts.map +1 -0
  20. package/dist/index.d.ts +305 -709
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +608 -1660
  23. package/dist/index.js.map +1 -1
  24. package/dist/{inspector-proxy-CvQDDxmT.d.ts → inspector-proxy-CaCFdEG4.d.ts} +4 -2
  25. package/dist/inspector-proxy-CaCFdEG4.d.ts.map +1 -0
  26. package/dist/{make-ph-event-functions-BHoLPif5.js → make-ph-event-functions-DBq3iWYn.js} +1 -1
  27. package/dist/{make-ph-event-functions-BHoLPif5.js.map → make-ph-event-functions-DBq3iWYn.js.map} +1 -1
  28. package/dist/{index-DS4W07Y8.d.ts → pglite-CntadC_p-BtEalg1H.d.ts} +2 -142
  29. package/dist/pglite-CntadC_p-BtEalg1H.d.ts.map +1 -0
  30. package/dist/{relational-Dj06-YkI.js → relational-C_0GdGVN.js} +2 -2
  31. package/dist/{relational-Dj06-YkI.js.map → relational-C_0GdGVN.js.map} +1 -1
  32. package/dist/{renown-D-1c_Bvx.js → renown-2nWrFlDw.js} +471 -57
  33. package/dist/renown-2nWrFlDw.js.map +1 -0
  34. package/dist/renown-BZabzj4l.js +68 -0
  35. package/dist/renown-BZabzj4l.js.map +1 -0
  36. package/dist/src/analytics/index.d.ts +1 -1
  37. package/dist/src/analytics/index.js +2 -1
  38. package/dist/src/analytics/index.js.map +1 -1
  39. package/dist/src/graphql/client.d.ts +3 -2
  40. package/dist/src/graphql/client.js +1 -1
  41. package/dist/src/graphql-client/entry.d.ts +4 -0
  42. package/dist/src/graphql-client/entry.js +3 -0
  43. package/dist/src/relational/index.d.ts +1 -1
  44. package/dist/src/relational/index.js +1 -1
  45. package/dist/src/renown/index.d.ts +2 -2
  46. package/dist/src/renown/index.js +3 -2
  47. package/dist/src/rpc/index.d.ts +6 -3
  48. package/dist/src/rpc/index.d.ts.map +1 -1
  49. package/dist/src/rpc/index.js +41 -10
  50. package/dist/src/rpc/index.js.map +1 -1
  51. package/dist/store-DAJq6vSs.js +37 -0
  52. package/dist/store-DAJq6vSs.js.map +1 -0
  53. package/dist/{client-09xv0Dq6.d.ts → types-4rfAFZQd.d.ts} +87 -19
  54. package/dist/types-4rfAFZQd.d.ts.map +1 -0
  55. package/dist/{types-CPV0Cnsy.d.ts → types-wGaiXwjh.d.ts} +1 -1
  56. package/dist/{types-CPV0Cnsy.d.ts.map → types-wGaiXwjh.d.ts.map} +1 -1
  57. package/package.json +16 -10
  58. package/dist/client-09xv0Dq6.d.ts.map +0 -1
  59. package/dist/client-_Gh2Uf0E.js.map +0 -1
  60. package/dist/client-u13cr-Vg.js.map +0 -1
  61. package/dist/document-by-id-dLYFX-xz.js.map +0 -1
  62. package/dist/index-D3bV5rcl.d.ts +0 -216
  63. package/dist/index-D3bV5rcl.d.ts.map +0 -1
  64. package/dist/index-DS4W07Y8.d.ts.map +0 -1
  65. package/dist/inspector-proxy-CvQDDxmT.d.ts.map +0 -1
  66. package/dist/renown-D-1c_Bvx.js.map +0 -1
@@ -0,0 +1,2928 @@
1
+ import { S as uploadOperations, _ as isDuplicateManifestError, a as setDocumentCache, b as queueActions, g as DOCUMENT_CHANGE_TYPE, i as addDocumentCacheEventHandler, n as useDocumentsByIds, p as DocumentCache, r as useDispatch, v as isDuplicateModuleError, x as queueOperations } from "./document-by-id-BSZqTN66.js";
2
+ import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
3
+ import { a as PhDocumentFieldsFragmentDoc, n as DocumentChangeType, o as PropagationMode, r as DocumentChangesDocument, t as createClient$1 } from "./client-DB8gP4hz.js";
4
+ import { f as addLoadingEventHandler, t as addRenownEventHandler } from "./renown-BZabzj4l.js";
5
+ import { logger } from "document-model";
6
+ import { UnsupportedDocumentModelVersionError, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, createPresignedHeader, createZip, deserializeSignature, documentModelDocumentType, generateId, hashDocumentStateForScope, normalizeDocumentModelVersion, replayDocumentVersioned, setName, toTransportAction } from "@powerhousedao/shared/document-model";
7
+ import { addFolder, copyNode, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
8
+ import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
9
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
10
+ import { GraphQLClient } from "graphql-request";
11
+ import { gql } from "graphql-tag";
12
+ import { Kind, print } from "graphql";
13
+ import { createClient } from "graphql-ws/client";
14
+ import slug from "slug";
15
+ import { Fragment, jsx } from "react/jsx-runtime";
16
+ //#region src/errors.ts
17
+ var UnsupportedDocumentTypeError = class extends Error {
18
+ constructor(documentType) {
19
+ super(`Document type ${documentType} is not supported`);
20
+ this.name = "UnsupportedDocumentTypeError";
21
+ }
22
+ static isError(error) {
23
+ return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
24
+ }
25
+ };
26
+ var DocumentNotFoundError = class extends Error {
27
+ constructor(documentId) {
28
+ super(`Document with id ${documentId} not found`);
29
+ }
30
+ };
31
+ var DocumentModelNotFoundError = class extends Error {
32
+ documentType;
33
+ name = "DocumentModelNotFoundError";
34
+ constructor(documentType) {
35
+ super(`Document model module for type ${documentType} not found`);
36
+ this.documentType = documentType;
37
+ }
38
+ static isError(error) {
39
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
40
+ }
41
+ };
42
+ var DocumentTypeMismatchError = class extends Error {
43
+ constructor(documentId, expectedType, actualType) {
44
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
45
+ }
46
+ };
47
+ var NoSelectedDocumentError = class extends Error {
48
+ constructor() {
49
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
50
+ }
51
+ };
52
+ //#endregion
53
+ //#region src/hooks/modals.ts
54
+ const modalEventFunctions = makePHEventFunctions("modal");
55
+ /** Returns the current modal */
56
+ const usePHModal = modalEventFunctions.useValue;
57
+ /** Sets the current modal */
58
+ const setPHModal = modalEventFunctions.setValue;
59
+ /** Adds an event handler for the modal */
60
+ const addModalEventHandler = modalEventFunctions.addEventHandler;
61
+ /** Shows a modal */
62
+ function showPHModal(modal) {
63
+ setPHModal(modal);
64
+ }
65
+ /** Closes the current modal */
66
+ function closePHModal() {
67
+ setPHModal(void 0);
68
+ }
69
+ /** Shows the create document modal */
70
+ function showCreateDocumentModal(documentType, documentModelVersion) {
71
+ setPHModal({
72
+ type: "createDocument",
73
+ documentType,
74
+ ...documentModelVersion !== void 0 && { documentModelVersion }
75
+ });
76
+ }
77
+ /** Shows the delete node modal */
78
+ function showDeleteNodeModal(nodeOrId) {
79
+ setPHModal({
80
+ type: "deleteItem",
81
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
82
+ });
83
+ }
84
+ //#endregion
85
+ //#region src/utils/documents.ts
86
+ function isDocumentTypeSupported(documentType, supportedDocuments) {
87
+ if (!supportedDocuments?.length) return true;
88
+ return supportedDocuments.some((pattern) => {
89
+ if (pattern.endsWith("/*")) {
90
+ const prefix = pattern.slice(0, -2);
91
+ return documentType.startsWith(prefix + "/");
92
+ }
93
+ if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
94
+ const prefix = pattern.slice(0, -1);
95
+ return documentType.startsWith(prefix);
96
+ }
97
+ return pattern === documentType;
98
+ });
99
+ }
100
+ //#endregion
101
+ //#region src/utils/user.ts
102
+ function getUserPermissions() {
103
+ const user = window.ph?.renown?.user;
104
+ const allowList = window.ph?.allowList;
105
+ if (!allowList) return {
106
+ isAllowedToCreateDocuments: true,
107
+ isAllowedToEditDocuments: true
108
+ };
109
+ return {
110
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
111
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
112
+ };
113
+ }
114
+ //#endregion
115
+ //#region src/actions/document.ts
116
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
117
+ async function isDocumentInLocation(document, driveId, parentFolder) {
118
+ const reactorClient = window.ph?.reactorClient;
119
+ if (!reactorClient) return { isDuplicate: false };
120
+ let drive;
121
+ try {
122
+ drive = await reactorClient.get(driveId);
123
+ } catch {
124
+ return { isDuplicate: false };
125
+ }
126
+ const nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);
127
+ if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {
128
+ isDuplicate: true,
129
+ duplicateType: "id",
130
+ nodeId: nodeById.id
131
+ };
132
+ const nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));
133
+ if (nodeByNameAndType) return {
134
+ isDuplicate: true,
135
+ duplicateType: "name",
136
+ nodeId: nodeByNameAndType.id
137
+ };
138
+ return { isDuplicate: false };
139
+ }
140
+ function getDocumentTypeIcon(document) {
141
+ switch (document.header.documentType) {
142
+ case "powerhouse/document-model": return "document-model";
143
+ case "powerhouse/app": return "app";
144
+ case "powerhouse/document-editor": return "editor";
145
+ case "powerhouse/subgraph": return "subgraph";
146
+ case "powerhouse/package": return "package";
147
+ case "powerhouse/processor": {
148
+ const processorType = document.state.global?.type;
149
+ if (processorType === "analytics") return "analytics-processor";
150
+ if (processorType === "relational") return "relational-processor";
151
+ if (processorType === "codegen") return "codegen-processor";
152
+ return;
153
+ }
154
+ default: return;
155
+ }
156
+ }
157
+ async function downloadFile(document, fileName) {
158
+ try {
159
+ const data = await createZip(document);
160
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
161
+ const link = window.document.createElement("a");
162
+ link.style.display = "none";
163
+ link.href = URL.createObjectURL(blob);
164
+ link.download = fileName;
165
+ window.document.body.appendChild(link);
166
+ link.click();
167
+ window.document.body.removeChild(link);
168
+ } catch (e) {
169
+ logger.error(e instanceof Error ? e.message : String(e));
170
+ }
171
+ }
172
+ async function getDocumentExtension(document) {
173
+ const documentType = document.header.documentType;
174
+ let rawExtension;
175
+ if (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;
176
+ else {
177
+ const reactorClient = window.ph?.reactorClientModule?.client;
178
+ if (reactorClient) {
179
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
180
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
181
+ }
182
+ }
183
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
184
+ }
185
+ /**
186
+ * Fetches all operations for a document using cursor-based pagination.
187
+ * The reactor client handles multi-scope cursors transparently via
188
+ * composite cursors, so all scopes are fetched in a single paginated stream.
189
+ */
190
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
191
+ const scopes = Object.keys(document.state);
192
+ const operations = {};
193
+ for (const scope of scopes) operations[scope] = [];
194
+ let cursor = "";
195
+ do {
196
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
197
+ cursor,
198
+ limit: pageSize
199
+ });
200
+ for (const op of page.results) {
201
+ const scope = op.action.scope ?? "global";
202
+ if (operations[scope]) operations[scope].push(op);
203
+ }
204
+ cursor = page.nextCursor ?? "";
205
+ } while (cursor);
206
+ return operations;
207
+ }
208
+ function extractInitialState(documentScopeOps) {
209
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
210
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
211
+ const input = upgradeOp.action.input;
212
+ const initialState = input.initialState ?? input.state;
213
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
214
+ return initialState;
215
+ }
216
+ function filterDomainOperations(operations) {
217
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
218
+ }
219
+ function countOperations(operations) {
220
+ let total = 0;
221
+ for (const ops of Object.values(operations)) total += ops?.length ?? 0;
222
+ return total;
223
+ }
224
+ /**
225
+ * Split an imported document's domain operations at its mid-history upgrade
226
+ * boundaries, so the caller can re-dispatch each upgrade between segments.
227
+ *
228
+ * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
229
+ * path and must not be repeated. A later upgrade must be: it is where the
230
+ * reducer version changes, and dropping it replays everything after it through
231
+ * the module the document was created with.
232
+ */
233
+ function splitAtUpgradeBoundaries(operations) {
234
+ const upgrades = (operations.document ?? []).filter((op) => op.action.type === "UPGRADE_DOCUMENT").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);
235
+ const domain = filterDomainOperations(operations);
236
+ if (upgrades.length === 0) return [{ operations: domain }];
237
+ const segments = [];
238
+ const consumed = /* @__PURE__ */ new Map();
239
+ const take = (until) => {
240
+ const slice = {};
241
+ for (const [scope, ops] of Object.entries(domain)) {
242
+ if (!ops) continue;
243
+ const from = consumed.get(scope) ?? 0;
244
+ const stop = Math.max(from, until(scope, ops));
245
+ const chunk = ops.slice(from, stop);
246
+ if (chunk.length > 0) slice[scope] = chunk;
247
+ consumed.set(scope, stop);
248
+ }
249
+ return slice;
250
+ };
251
+ for (const upgrade of upgrades) {
252
+ const input = upgrade.action.input;
253
+ const slice = take((scope, ops) => boundary(upgrade, scope, ops));
254
+ segments.push({
255
+ operations: slice,
256
+ upgradeTo: input.toVersion
257
+ });
258
+ }
259
+ const tail = take((_scope, ops) => ops.length);
260
+ if (countOperations(tail) > 0) segments.push({ operations: tail });
261
+ return segments;
262
+ }
263
+ /**
264
+ * How many of a scope's operations precede an upgrade. Must stay identical to
265
+ * the boundary computation in `replayDocumentVersioned` — snapshots compare
266
+ * against operation indices, not array positions, and the timestamp fallback
267
+ * excludes the upgrade's own instant.
268
+ */
269
+ function boundary(upgrade, scope, ops) {
270
+ const snapshot = upgrade.action.input.revision;
271
+ if (snapshot !== void 0) {
272
+ const revision = snapshot[scope] ?? 0;
273
+ let count = 0;
274
+ for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
275
+ return count;
276
+ }
277
+ for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
278
+ return ops.length;
279
+ }
280
+ async function exportFile(document, suggestedName) {
281
+ const reactorClient = window.ph?.reactorClient;
282
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
283
+ const operations = await fetchDocumentOperations(reactorClient, document);
284
+ const initialState = extractInitialState(operations["document"] ?? []);
285
+ const documentWithOps = {
286
+ ...document,
287
+ operations,
288
+ initialState
289
+ };
290
+ const extension = await getDocumentExtension(documentWithOps);
291
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
292
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
293
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
294
+ try {
295
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
296
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
297
+ return fileHandle;
298
+ } catch (e) {
299
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
300
+ }
301
+ }
302
+ /**
303
+ * Loads a document file and replays it with version-aware reducers from the registry.
304
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
305
+ * the document type.
306
+ */
307
+ async function loadFile(path) {
308
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
309
+ const reactorClient = window.ph?.reactorClientModule?.client;
310
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
311
+ const documentType = baseDocument.header.documentType;
312
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
313
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
314
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
315
+ const reducers = {};
316
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
317
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
318
+ let upgradeManifest;
319
+ if (registry) try {
320
+ upgradeManifest = registry.getUpgradeManifest(documentType);
321
+ } catch {}
322
+ return baseLoadFromInputVersioned(path, {
323
+ reducers,
324
+ upgradeManifest
325
+ });
326
+ }
327
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
328
+ const { isAllowedToCreateDocuments } = getUserPermissions();
329
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
330
+ const reactorClient = window.ph?.reactorClientModule?.client;
331
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
332
+ let documentModelModule;
333
+ if (documentModelVersion !== void 0) {
334
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
335
+ const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
336
+ if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
337
+ documentModelModule = module;
338
+ } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
339
+ const newDocument = document ?? documentModelModule.utils.createDocument();
340
+ if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
341
+ newDocument.header.name = name;
342
+ if (preferredEditor) newDocument.header.meta = {
343
+ ...newDocument.header.meta,
344
+ preferredEditor
345
+ };
346
+ let newDoc;
347
+ try {
348
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
349
+ } catch (e) {
350
+ logger.error("Error adding document: @error", e);
351
+ throw new Error("There was an error adding document", { cause: e });
352
+ }
353
+ return {
354
+ id: newDoc.header.id,
355
+ name: newDoc.header.name,
356
+ documentType,
357
+ parentFolder: parentFolder ?? null,
358
+ kind: "file"
359
+ };
360
+ }
361
+ async function addFile(file, driveId, name, parentFolder) {
362
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
363
+ const { isAllowedToCreateDocuments } = getUserPermissions();
364
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
365
+ const document = await loadFile(file);
366
+ let duplicateId = false;
367
+ const reactorClient = window.ph?.reactorClient;
368
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
369
+ try {
370
+ await reactorClient.get(document.header.id);
371
+ duplicateId = true;
372
+ } catch {}
373
+ const documentId = duplicateId ? generateId() : document.header.id;
374
+ const header = createPresignedHeader(documentId, document.header.documentType);
375
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
376
+ header.meta = document.header.meta;
377
+ header.name = name || document.header.name;
378
+ const initialDocument = {
379
+ ...document,
380
+ header,
381
+ state: document.initialState,
382
+ operations: Object.keys(document.operations).reduce((acc, key) => {
383
+ acc[key] = [];
384
+ return acc;
385
+ }, {})
386
+ };
387
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
388
+ for (const segment of splitAtUpgradeBoundaries(document.operations)) {
389
+ await uploadOperations(documentId, segment.operations, queueOperations);
390
+ if (segment.upgradeTo !== void 0) await upgradeDocument(documentId, segment.upgradeTo);
391
+ }
392
+ }
393
+ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
394
+ logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
395
+ const reactor = window.ph?.reactorClientModule?.client;
396
+ if (!reactor) return;
397
+ const { isAllowedToCreateDocuments } = getUserPermissions();
398
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
399
+ try {
400
+ onProgress?.({
401
+ stage: "loading",
402
+ progress: 0
403
+ });
404
+ let document;
405
+ try {
406
+ document = await loadFile(file);
407
+ } catch (loadError) {
408
+ if (UnsupportedDocumentModelVersionError.isError(loadError)) {
409
+ showPHModal({
410
+ type: "documentVersionUnsupported",
411
+ documentType: loadError.documentType,
412
+ requiredVersion: loadError.requiredVersion,
413
+ availableVersions: loadError.availableVersions
414
+ });
415
+ onProgress?.({
416
+ stage: "failed",
417
+ progress: 100,
418
+ error: loadError.message
419
+ });
420
+ return;
421
+ }
422
+ const discoveryService = window.ph?.packageDiscoveryService;
423
+ if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
424
+ retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
425
+ return;
426
+ }
427
+ throw loadError;
428
+ }
429
+ const duplicateCheck = await isDocumentInLocation(document, driveId, parentFolder);
430
+ if (duplicateCheck.isDuplicate && !resolveConflict) {
431
+ onProgress?.({
432
+ stage: "conflict",
433
+ progress: 0,
434
+ duplicateType: duplicateCheck.duplicateType
435
+ });
436
+ return;
437
+ }
438
+ const documentType = getDocumentTypeIcon(document);
439
+ if (documentType) onProgress?.({
440
+ stage: "loading",
441
+ progress: 10,
442
+ documentType
443
+ });
444
+ else onProgress?.({
445
+ stage: "loading",
446
+ progress: 10
447
+ });
448
+ if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
449
+ onProgress?.({
450
+ stage: "unsupported-document-type",
451
+ progress: 100,
452
+ error: `Document type ${document.header.documentType} is not supported`
453
+ });
454
+ throw new UnsupportedDocumentTypeError(document.header.documentType);
455
+ }
456
+ await reactor.getDocumentModelModule(document.header.documentType);
457
+ onProgress?.({
458
+ stage: "initializing",
459
+ progress: 10
460
+ });
461
+ let duplicateId = false;
462
+ try {
463
+ await reactor.get(document.header.id);
464
+ duplicateId = true;
465
+ } catch {}
466
+ const documentId = duplicateId ? generateId() : document.header.id;
467
+ const header = createPresignedHeader(documentId, document.header.documentType);
468
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
469
+ header.meta = document.header.meta;
470
+ header.name = name || document.header.name;
471
+ const initialDocument = {
472
+ ...document,
473
+ header,
474
+ state: document.initialState,
475
+ operations: Object.keys(document.operations).reduce((acc, key) => {
476
+ acc[key] = [];
477
+ return acc;
478
+ }, {})
479
+ };
480
+ const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
481
+ if (!fileNode) throw new Error("There was an error adding file");
482
+ onProgress?.({
483
+ stage: "initializing",
484
+ progress: 20
485
+ });
486
+ await reactor.get(documentId);
487
+ console.log("Document created, starting upload of operations");
488
+ const segments = splitAtUpgradeBoundaries(document.operations);
489
+ const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
490
+ let uploadedBefore = 0;
491
+ for (const segment of segments) {
492
+ await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
493
+ if (uploadProgress.uploadedOperations === void 0) return;
494
+ const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
495
+ const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
496
+ onProgress?.({
497
+ stage: "uploading",
498
+ progress: 20 + Math.round(uploadPercent * 80),
499
+ totalOperations,
500
+ uploadedOperations: uploaded
501
+ });
502
+ } });
503
+ uploadedBefore += countOperations(segment.operations);
504
+ if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
505
+ }
506
+ onProgress?.({
507
+ stage: "complete",
508
+ progress: 100,
509
+ fileNode
510
+ });
511
+ return fileNode;
512
+ } catch (error) {
513
+ if (!UnsupportedDocumentTypeError.isError(error)) {
514
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
515
+ onProgress?.({
516
+ stage: "failed",
517
+ progress: 100,
518
+ error: errorMessage
519
+ });
520
+ }
521
+ throw error;
522
+ }
523
+ }
524
+ async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
525
+ if (!discoveryService) return;
526
+ try {
527
+ await discoveryService.load(documentType);
528
+ } catch {
529
+ onProgress?.({
530
+ stage: "unsupported-document-type",
531
+ progress: 100,
532
+ error: `Document type ${documentType} is not supported`
533
+ });
534
+ return;
535
+ }
536
+ await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
537
+ }
538
+ async function addFolder$1(driveId, name, parentFolder) {
539
+ const { isAllowedToCreateDocuments } = getUserPermissions();
540
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
541
+ const reactorClient = window.ph?.reactorClient;
542
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
543
+ await reactorClient.get(driveId);
544
+ const folderId = generateId();
545
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
546
+ id: folderId,
547
+ name,
548
+ parentFolder
549
+ })])).state.global.nodes.find((node) => node.id === folderId);
550
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
551
+ return node;
552
+ }
553
+ async function deleteNode(driveId, nodeId) {
554
+ const { isAllowedToCreateDocuments } = getUserPermissions();
555
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete documents");
556
+ const reactorClient = window.ph?.reactorClientModule?.client;
557
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
558
+ await reactorClient.drives.removeNode(driveId, nodeId);
559
+ }
560
+ async function renameNode(driveId, nodeId, name) {
561
+ const { isAllowedToCreateDocuments } = getUserPermissions();
562
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
563
+ const reactorClient = window.ph?.reactorClient;
564
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
565
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
566
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
567
+ id: nodeId,
568
+ name
569
+ })])).state.global.nodes.find((n) => n.id === nodeId);
570
+ if (!node) throw new Error("There was an error renaming node in the drive");
571
+ return node;
572
+ }
573
+ async function renameDriveNode(driveId, nodeId, name) {
574
+ const { isAllowedToCreateDocuments } = getUserPermissions();
575
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
576
+ const reactorClient = window.ph?.reactorClient;
577
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
578
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
579
+ await reactorClient.execute(driveId, "main", [updateNode({
580
+ id: nodeId,
581
+ name
582
+ })]);
583
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
584
+ }
585
+ async function moveNodeById(args) {
586
+ const { driveId, srcId, targetId } = args;
587
+ if (!driveId || !srcId) return;
588
+ const { isAllowedToCreateDocuments } = getUserPermissions();
589
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
590
+ const reactorClient = window.ph?.reactorClient;
591
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
592
+ const targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));
593
+ if (isStrictEqual(targetParentFolder, srcId)) return;
594
+ return await reactorClient.execute(driveId, "main", [moveNode({
595
+ srcFolder: srcId,
596
+ targetParentFolder
597
+ })]);
598
+ }
599
+ async function moveNode$1(driveId, src, target) {
600
+ const { isAllowedToCreateDocuments } = getUserPermissions();
601
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
602
+ const reactorClient = window.ph?.reactorClient;
603
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
604
+ return await reactorClient.execute(driveId, "main", [moveNode({
605
+ srcFolder: src.id,
606
+ targetParentFolder: target?.id
607
+ })]);
608
+ }
609
+ /**
610
+ * Duplicates a document under a new id using version-aware replay.
611
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
612
+ */
613
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
614
+ const documentType = document.header.documentType;
615
+ const { results: allModules } = await reactor.getDocumentModelModules();
616
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
617
+ const reducers = {};
618
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
619
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
620
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
621
+ let upgradeManifest;
622
+ if (registry) try {
623
+ upgradeManifest = registry.getUpgradeManifest(documentType);
624
+ } catch {}
625
+ const config = {
626
+ reducers,
627
+ upgradeManifest
628
+ };
629
+ const header = createPresignedHeader(newId, documentType);
630
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
631
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
632
+ return duplicated;
633
+ }
634
+ async function copyNode$1(driveId, src, target) {
635
+ const reactor = window.ph?.reactorClientModule?.client;
636
+ if (!reactor) return;
637
+ const { isAllowedToCreateDocuments } = getUserPermissions();
638
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
639
+ const drive = await reactor.get(driveId);
640
+ const copyNodesInput = generateNodesCopy({
641
+ srcId: src.id,
642
+ targetParentFolder: target?.id,
643
+ targetName: src.name
644
+ }, () => generateId(), drive.state.global.nodes);
645
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
646
+ for (const copyNodeInput of copyNodesInput) {
647
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
648
+ if (node) {
649
+ const resolvedName = handleTargetNameCollisions({
650
+ nodes: drive.state.global.nodes,
651
+ srcName: copyNodeInput.targetName || node.name,
652
+ srcKind: isFileNode(node) ? "file" : "folder",
653
+ targetParentFolder: copyNodeInput.targetParentFolder || null
654
+ });
655
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
656
+ }
657
+ }
658
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
659
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
660
+ return node !== void 0 && isFileNode(node);
661
+ });
662
+ for (const fileNodeToCopy of fileNodesToCopy) try {
663
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
664
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
665
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
666
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
667
+ } catch (e) {
668
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
669
+ }
670
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
671
+ }
672
+ /**
673
+ * Upgrades a document to a newer document model version. Defaults to the
674
+ * latest registered version for the document's type.
675
+ */
676
+ async function upgradeDocument(documentId, toVersion) {
677
+ const reactorClient = window.ph?.reactorClientModule?.client;
678
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
679
+ return reactorClient.upgradeDocument(documentId, toVersion);
680
+ }
681
+ //#endregion
682
+ //#region src/remote-controller/utils.ts
683
+ /** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. "SET_MODEL_NAME" → "setModelName"). */
684
+ function screamingSnakeToCamel(s) {
685
+ return s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());
686
+ }
687
+ /** Error thrown when a push conflict is detected with the "reject" strategy. */
688
+ var ConflictError = class extends Error {
689
+ constructor(conflict) {
690
+ super("Push conflict: remote has new operations since last pull");
691
+ this.conflict = conflict;
692
+ this.name = "ConflictError";
693
+ }
694
+ };
695
+ /** Convert a remote operation to the local Operation type. */
696
+ function remoteOperationToLocal(remote) {
697
+ return {
698
+ id: remote.id ?? "",
699
+ index: remote.index,
700
+ skip: remote.skip,
701
+ timestampUtcMs: remote.timestampUtcMs,
702
+ hash: remote.hash,
703
+ error: remote.error ?? void 0,
704
+ deniedReason: remote.deniedReason ?? void 0,
705
+ action: {
706
+ id: remote.action.id,
707
+ type: remote.action.type,
708
+ timestampUtcMs: remote.action.timestampUtcMs,
709
+ input: remote.action.input,
710
+ scope: remote.action.scope,
711
+ context: remote.action.context?.signer ? { signer: {
712
+ user: remote.action.context.signer.user ?? {
713
+ address: "",
714
+ networkId: "",
715
+ chainId: 0
716
+ },
717
+ app: remote.action.context.signer.app ?? {
718
+ name: "",
719
+ key: ""
720
+ },
721
+ signatures: remote.action.context.signer.signatures.map((s) => deserializeSignature(s))
722
+ } } : void 0
723
+ }
724
+ };
725
+ }
726
+ /** Convert remote operations to local DocumentOperations format. */
727
+ function convertRemoteOperations(operationsByScope) {
728
+ const operations = {};
729
+ for (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));
730
+ return operations;
731
+ }
732
+ /** Reconstruct a PHDocument from remote document data and operations. */
733
+ function buildPulledDocument(remoteDoc, operations, initialDoc, branch) {
734
+ return {
735
+ header: {
736
+ ...initialDoc.header,
737
+ id: remoteDoc.id,
738
+ name: remoteDoc.name,
739
+ slug: remoteDoc.slug ?? "",
740
+ documentType: remoteDoc.documentType,
741
+ createdAtUtcIso: typeof remoteDoc.createdAtUtcIso === "string" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),
742
+ lastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === "string" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),
743
+ revision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),
744
+ branch
745
+ },
746
+ state: remoteDoc.state,
747
+ initialState: initialDoc.initialState,
748
+ operations,
749
+ clipboard: []
750
+ };
751
+ }
752
+ /** Extract revision map from a remote document's revisionsList. */
753
+ function extractRevisionMap(revisionsList) {
754
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
755
+ }
756
+ /**
757
+ * Check if any scope in currentRevision is ahead of knownRevision.
758
+ * When `scopes` is provided, only those scopes are checked.
759
+ */
760
+ function hasRevisionConflict(currentRevision, knownRevision, scopes) {
761
+ for (const scope in currentRevision) {
762
+ if (scopes && !scopes.has(scope)) continue;
763
+ if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) return true;
764
+ }
765
+ return false;
766
+ }
767
+ //#endregion
768
+ //#region src/graphql-client/adapter.ts
769
+ /**
770
+ * Converts a `GetDocument` result into a `PHDocument`.
771
+ *
772
+ * Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope
773
+ * revision map, which the write path needs to compute the `prevOpIndex` of a
774
+ * signed action. `sig` is filled with the empty shape used by
775
+ * `createPresignedHeader`: the creation signature is not fetchable over
776
+ * GraphQL and is not part of the operation signing payload.
777
+ *
778
+ * The read path never fetches operation history, so `operations` is a map of
779
+ * the document's known scopes to empty arrays.
780
+ *
781
+ * `branch` is the branch the document was read from. The GraphQL type does not
782
+ * carry it, so it has to be passed back in by the caller; it defaults to the
783
+ * server's own default branch.
784
+ */
785
+ function phDocumentFromGetDocument(document, branch) {
786
+ const state = document.state;
787
+ return {
788
+ header: phDocumentHeaderFromGetDocument(document, branch),
789
+ state,
790
+ initialState: state,
791
+ operations: emptyOperationsForScopes(document.revisionsList),
792
+ clipboard: []
793
+ };
794
+ }
795
+ /**
796
+ * Converts a mutation result into a `PHDocument`, carrying the operations the
797
+ * mutation produced.
798
+ *
799
+ * `dispatchActions` reads per-action failures out of `operations[scope]`, so
800
+ * unlike the read path this one must not return empty operation lists.
801
+ */
802
+ function phDocumentFromMutation(document, operations, branch) {
803
+ const phDocument = phDocumentFromGetDocument(document, branch);
804
+ const operationsByScope = { ...phDocument.operations };
805
+ for (const remote of operations) {
806
+ const operation = remoteOperationToLocal(remote);
807
+ const scope = operation.action.scope;
808
+ const scopeOperations = operationsByScope[scope] ?? [];
809
+ scopeOperations.push(operation);
810
+ operationsByScope[scope] = scopeOperations;
811
+ }
812
+ phDocument.operations = operationsByScope;
813
+ return phDocument;
814
+ }
815
+ /** Turns a `revisionsList` selection into the header's per-scope revision map. */
816
+ function revisionMapFromRevisionsList(revisionsList) {
817
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
818
+ }
819
+ /** The branch the server reads and writes when none is asked for. */
820
+ const defaultBranch = "main";
821
+ function phDocumentHeaderFromGetDocument(document, branch) {
822
+ return {
823
+ id: document.id,
824
+ sig: {
825
+ publicKey: {},
826
+ nonce: ""
827
+ },
828
+ documentType: document.documentType,
829
+ createdAtUtcIso: isoStringFromDateTime(document.createdAtUtcIso),
830
+ slug: document.slug ?? "",
831
+ name: document.name,
832
+ branch: branch ?? defaultBranch,
833
+ revision: revisionMapFromRevisionsList(document.revisionsList),
834
+ lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso)
835
+ };
836
+ }
837
+ function emptyOperationsForScopes(revisionsList) {
838
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, []]));
839
+ }
840
+ /** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
841
+ function isoStringFromDateTime(value) {
842
+ return value instanceof Date ? value.toISOString() : value;
843
+ }
844
+ //#endregion
845
+ //#region src/graphql-client/auth.ts
846
+ /** Lifetime requested for an ambient Renown token, in seconds. */
847
+ const ambientTokenExpiresInSeconds = 600;
848
+ /**
849
+ * The default token provider: the token of the currently logged-in Renown user.
850
+ *
851
+ * It is deliberately resolved from `window.ph` on every call rather than
852
+ * captured at construction time, so a client built before login starts sending
853
+ * the token as soon as there is one.
854
+ *
855
+ * The token is requested WITHOUT an `aud` claim - the Switchboard verifier
856
+ * rejects tokens that carry an audience.
857
+ */
858
+ async function ambientRenownTokenProvider() {
859
+ if (typeof window === "undefined") return;
860
+ const renown = window.ph?.renown;
861
+ if (!renown?.user) return;
862
+ return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });
863
+ }
864
+ /**
865
+ * Builds the SDK middleware that authenticates every request.
866
+ *
867
+ * The token is resolved per request and never cached, so a login, a logout or
868
+ * an expiry between two calls is picked up by the next one. When no token is
869
+ * available the request goes out unauthenticated.
870
+ */
871
+ function makeAuthMiddleware(tokenProvider) {
872
+ return async (action) => {
873
+ const token = await tokenProvider();
874
+ if (!token) return action();
875
+ return action({ authorization: `Bearer ${token}` });
876
+ };
877
+ }
878
+ //#endregion
879
+ //#region src/graphql-client/operations.ts
880
+ /**
881
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
882
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
883
+ */
884
+ const ReactorOperationFieldsFragmentDoc = gql`
885
+ fragment ReactorOperationFields on ReactorOperation {
886
+ index
887
+ timestampUtcMs
888
+ hash
889
+ skip
890
+ error
891
+ deniedReason
892
+ id
893
+ action {
894
+ id
895
+ type
896
+ timestampUtcMs
897
+ input
898
+ scope
899
+ context {
900
+ signer {
901
+ user {
902
+ address
903
+ networkId
904
+ chainId
905
+ }
906
+ app {
907
+ name
908
+ key
909
+ }
910
+ signatures
911
+ }
912
+ }
913
+ }
914
+ }
915
+ `;
916
+ /**
917
+ * `mutateDocument` plus the operations the mutation produced.
918
+ *
919
+ * The generated `MutateDocument` only selects the document fields, but
920
+ * `dispatchActions` reads per-action failures out of `result.operations[scope]`
921
+ * (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.
922
+ *
923
+ * The operations filter keeps the extra selection to the operations this call
924
+ * could have appended rather than the whole history. All three of its fields
925
+ * matter:
926
+ * - `sinceRevision` is the lowest head revision across the targeted scopes, so
927
+ * it is only a safe window when the selection is scope-limited as well;
928
+ * - `scopes` limits the response to the scopes the pushed actions target,
929
+ * without it the server walks every scope of the document
930
+ * (`packages/reactor/src/core/reactor.ts` `getOperations`);
931
+ * - `branch` selects the branch the operations are read from, and is the same
932
+ * variable the mutation writes to. It used to be two - the write went through
933
+ * a `view`, the filter took its own `branch` - and they had to be kept equal
934
+ * by hand or the operations came from `main` while the actions were applied
935
+ * elsewhere. One variable cannot disagree with itself.
936
+ */
937
+ const MutateDocumentWithOperationsDocument = gql`
938
+ mutation MutateDocumentWithOperations(
939
+ $documentIdentifier: String!
940
+ $actions: [ActionInput!]!
941
+ $sinceRevision: Int
942
+ $scopes: [String!]
943
+ $branch: String
944
+ ) {
945
+ mutateDocument: execute(
946
+ documentIdentifier: $documentIdentifier
947
+ actions: $actions
948
+ branch: $branch
949
+ ) {
950
+ ...PHDocumentFields
951
+ operations(
952
+ filter: {
953
+ sinceRevision: $sinceRevision
954
+ scopes: $scopes
955
+ branch: $branch
956
+ }
957
+ ) {
958
+ items {
959
+ ...ReactorOperationFields
960
+ }
961
+ }
962
+ }
963
+ }
964
+ ${PhDocumentFieldsFragmentDoc}
965
+ ${ReactorOperationFieldsFragmentDoc}
966
+ `;
967
+ //#endregion
968
+ //#region src/graphql-client/signing.ts
969
+ /**
970
+ * Stamps an action with the head of the scope it targets.
971
+ *
972
+ * `prevOpHash` is the hash of the scope state the action is meant to apply to;
973
+ * for a document at head that is the hash of the last operation in the scope,
974
+ * which the read path cannot fetch, so it is recomputed from the state.
975
+ * `prevOpIndex` is the index of that last operation: revisions count
976
+ * operations and indices are zero based, so an empty scope stamps `-1`, which
977
+ * matches what the remote controller records.
978
+ *
979
+ * `revision` overrides the scope revision the index is derived from. Only a
980
+ * batch needs it - {@link prepareSignedActions} stamps action N at the revision
981
+ * the N actions before it will have produced, which the document itself does
982
+ * not know yet. `prevOpHash` always comes from the supplied document's state.
983
+ */
984
+ function stampAction(action, document, revision = document.header.revision[action.scope] ?? 0) {
985
+ return {
986
+ ...action,
987
+ context: {
988
+ ...action.context,
989
+ prevOpHash: hashDocumentStateForScope(document, action.scope),
990
+ prevOpIndex: revision - 1
991
+ }
992
+ };
993
+ }
994
+ /**
995
+ * Signs a stamped action, preserving any signatures it already carries.
996
+ *
997
+ * The signer reads `context.prevOpHash` off the action, so this must run after
998
+ * {@link stampAction}.
999
+ */
1000
+ async function signStampedAction(action, signer, signal) {
1001
+ const actionSigner = action.context?.signer;
1002
+ const user = actionSigner?.user ?? signer.user;
1003
+ const app = actionSigner?.app ?? signer.app;
1004
+ if (!user || !app) throw new Error("cannot sign an action: the signer has no user or app identity");
1005
+ const signature = await signer.signAction(action, signal);
1006
+ return {
1007
+ ...action,
1008
+ context: {
1009
+ ...action.context,
1010
+ signer: {
1011
+ user,
1012
+ app,
1013
+ signatures: [...actionSigner?.signatures ?? [], signature]
1014
+ }
1015
+ }
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Actions a snapshot batch cannot predict the next state for.
1020
+ *
1021
+ * `UNDO`, `REDO` and `PRUNE` rewrite history the light read path never fetched
1022
+ * (and the reducer appends no operation for them); `NOOP` is only ever produced
1023
+ * by an undo chain; the document-scope actions run through the reactor's
1024
+ * document-action handler rather than a document-model reducer
1025
+ * (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and
1026
+ * `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.
1027
+ */
1028
+ const unsupportedBatchActions = new Set([
1029
+ "UNDO",
1030
+ "REDO",
1031
+ "PRUNE",
1032
+ "NOOP",
1033
+ "CREATE_DOCUMENT",
1034
+ "DELETE_DOCUMENT",
1035
+ "UPGRADE_DOCUMENT",
1036
+ "ADD_RELATIONSHIP",
1037
+ "REMOVE_RELATIONSHIP",
1038
+ "UPDATE_RELATIONSHIP"
1039
+ ]);
1040
+ /**
1041
+ * The base-reducer protocol version to predict with when the snapshot's header
1042
+ * carries none.
1043
+ *
1044
+ * `baseReducer` reads `baseReducerVersion(document.header)` for every action and
1045
+ * throws when the header has no `protocolVersions` - and a header built by
1046
+ * {@link phDocumentFromGetDocument} never has one, because the GraphQL
1047
+ * `PHDocument` type does not expose it. The version only selects between the v1
1048
+ * and v2 UNDO/NOOP branches, and every action reaching the prediction loop is an
1049
+ * ordinary append-only one, so it cannot change the predicted state here; it is
1050
+ * passed purely so the lookup does not throw.
1051
+ */
1052
+ const predictionProtocolVersion = 2;
1053
+ /**
1054
+ * Stamps and signs a batch of actions against one document snapshot, so every
1055
+ * action carries the head its predecessor will leave behind.
1056
+ *
1057
+ * The server executes the array in order, each action against the state the one
1058
+ * before it produced. The snapshot the light client reads has correct state and
1059
+ * per-scope revisions but NO operation history (see `adapter.ts`), so the chain
1060
+ * is predicted here: reduce action N over the working document to get the state
1061
+ * action N+1 hashes, and carry a virtual revision alongside it. The revision has
1062
+ * to be tracked separately because the reducer derives operation indices from
1063
+ * the last stored operation, and with an empty history that counts from zero
1064
+ * rather than from the document's real revision.
1065
+ *
1066
+ * A single action needs no prediction and therefore no `module`, which keeps
1067
+ * today's callers working unchanged. Two or more require the document's exact
1068
+ * reducer, one shared scope (the reactor rejects mixed-scope jobs) and only
1069
+ * append-only actions. Anything else rejects: a batch that cannot be predicted
1070
+ * must fail before the mutation, never be downgraded to unsigned.
1071
+ */
1072
+ async function prepareSignedActions(actions, snapshot, signer, module, signal) {
1073
+ if (actions.length === 0) return [];
1074
+ if (actions.length === 1) return [await signStampedAction(stampAction(actions[0], snapshot), signer, signal)];
1075
+ const scope = sharedScope(actions);
1076
+ assertSupportedBatch(actions);
1077
+ if (!module) throw new Error(`cannot sign ${actions.length} actions: no document model module for ${snapshot.header.documentType} was supplied, so the batch state cannot be predicted`);
1078
+ let working = {
1079
+ ...snapshot,
1080
+ operations: {
1081
+ ...snapshot.operations,
1082
+ [scope]: [...snapshot.operations[scope] ?? []]
1083
+ }
1084
+ };
1085
+ let revision = snapshot.header.revision[scope] ?? 0;
1086
+ const signed = [];
1087
+ for (const [index, action] of actions.entries()) {
1088
+ throwIfAborted(signal, index);
1089
+ const signedAction = await signStampedAction(stampAction(action, working, revision), signer, signal);
1090
+ signed.push(signedAction);
1091
+ const before = scopeOperationCount(working, scope);
1092
+ let next;
1093
+ try {
1094
+ next = module.reducer(working, signedAction, void 0, { protocolVersion: working.header.protocolVersions?.["base-reducer"] ?? predictionProtocolVersion });
1095
+ } catch (error) {
1096
+ throw new Error(`cannot sign action ${index} (${action.type}): the ${snapshot.header.documentType} reducer rejected it, so the rest of the batch cannot be predicted`, { cause: error });
1097
+ }
1098
+ const after = scopeOperationCount(next, scope);
1099
+ if (after !== before + 1) throw new Error(`cannot sign action ${index} (${action.type}): the reducer appended ${after - before} operations to ${scope}, expected exactly 1`);
1100
+ working = next;
1101
+ revision += 1;
1102
+ }
1103
+ return signed;
1104
+ }
1105
+ /**
1106
+ * How many operations a scope holds.
1107
+ *
1108
+ * The index signature types the array as always present, but a module's reducer
1109
+ * is arbitrary code: one that hands back a document without the scope should
1110
+ * produce the actionable error above, not a `TypeError` on `.length`.
1111
+ */
1112
+ function scopeOperationCount(document, scope) {
1113
+ return document.operations[scope]?.length ?? 0;
1114
+ }
1115
+ /** The one scope a reactor job may span (`getSharedActionScope`). */
1116
+ function sharedScope(actions) {
1117
+ const scope = actions[0].scope;
1118
+ const mixed = actions.find((action) => action.scope !== scope);
1119
+ if (mixed) throw new Error(`cannot sign a batch spanning scopes "${scope}" and "${mixed.scope}": every action in one request must share a scope`);
1120
+ return scope;
1121
+ }
1122
+ function assertSupportedBatch(actions) {
1123
+ const unsupported = actions.find((action) => unsupportedBatchActions.has(action.type));
1124
+ if (unsupported) throw new Error(`cannot sign a batch containing ${unsupported.type}: it needs operation history or an alternate executor path, so send it as a single action`);
1125
+ }
1126
+ function throwIfAborted(signal, index) {
1127
+ if (signal?.aborted) throw new Error(`signing aborted before action ${index}`, { cause: signal.reason });
1128
+ }
1129
+ //#endregion
1130
+ //#region src/graphql-client/static-package-manager.ts
1131
+ /**
1132
+ * A fixed set of packages presented through the `IPackageManager` interface,
1133
+ * so the package-derived hooks - `useDocumentModelModules`,
1134
+ * `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work
1135
+ * below `GraphQLReactorProvider` exactly as they do below Connect.
1136
+ *
1137
+ * Connect's package manager installs, updates and removes packages at runtime.
1138
+ * A light app instead declares its packages once, as code it imports itself
1139
+ * (every generated package root exports `manifest`, `documentModels`, `editors`
1140
+ * and `upgradeManifests` by name), so every mutating member throws and
1141
+ * `subscribe` never emits. For hand-picked modules without package artifacts,
1142
+ * {@link packageFromDocumentModels} wraps them in one synthetic package.
1143
+ */
1144
+ var StaticPackageManager = class {
1145
+ registryUrl = null;
1146
+ packages;
1147
+ constructor(packages) {
1148
+ this.packages = [...packages];
1149
+ }
1150
+ /**
1151
+ * Resolves a module by document type across all packages. Mirrors the
1152
+ * registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST
1153
+ * version wins, with `version ?? 1` as each module's default.
1154
+ */
1155
+ load(documentType) {
1156
+ const modules = this.packages.flatMap((pkg) => pkg.documentModels);
1157
+ try {
1158
+ return Promise.resolve(resolveDocumentModelModule(modules, documentType));
1159
+ } catch (error) {
1160
+ return Promise.reject(error);
1161
+ }
1162
+ }
1163
+ subscribe(_handler) {
1164
+ return () => {};
1165
+ }
1166
+ getPackageSource(_packageName) {
1167
+ return null;
1168
+ }
1169
+ getPackageVersion(_packageName) {}
1170
+ getRegistryPackages() {
1171
+ return [];
1172
+ }
1173
+ addPackage(_packageName) {
1174
+ throw staticPackageManagerError("addPackage");
1175
+ }
1176
+ addPackages(_packageNames) {
1177
+ throw staticPackageManagerError("addPackages");
1178
+ }
1179
+ removePackage(_name) {
1180
+ throw staticPackageManagerError("removePackage");
1181
+ }
1182
+ updateLocalPackage(_pkg, _version) {
1183
+ throw staticPackageManagerError("updateLocalPackage");
1184
+ }
1185
+ addLocalPackage(_name, _loadedPackage, _version) {
1186
+ throw staticPackageManagerError("addLocalPackage");
1187
+ }
1188
+ };
1189
+ /**
1190
+ * Resolves one document-model module out of a flat module list, with the same
1191
+ * rule the reactor registry uses (`IDocumentModelRegistry.getModule`, at
1192
+ * packages/reactor/src/registry/implementation.ts): with a `version`, only an
1193
+ * EXACT `version ?? 1` match resolves; without one, the LATEST version wins.
1194
+ *
1195
+ * Signing an existing document needs the exact rule. A document carries the
1196
+ * model version it was written with in `state.document.version`, and its
1197
+ * reducer is the only one whose operations that document's history can accept -
1198
+ * so "latest" is correct only when no version is asked for.
1199
+ *
1200
+ * Pure and dependency-free on purpose: this is reachable from the browser
1201
+ * entry, so it must not pull the reactor registry in as a value.
1202
+ */
1203
+ function resolveDocumentModelModule(modules, documentType, version) {
1204
+ let latestModule;
1205
+ let latestVersion = -1;
1206
+ for (const module of modules) {
1207
+ if (module.documentModel.global.id !== documentType) continue;
1208
+ const moduleVersion = module.version ?? 1;
1209
+ if (version !== void 0 && moduleVersion === version) return module;
1210
+ if (moduleVersion > latestVersion) {
1211
+ latestVersion = moduleVersion;
1212
+ latestModule = module;
1213
+ }
1214
+ }
1215
+ if (version === void 0 && latestModule) return latestModule;
1216
+ throw new Error(version === void 0 ? `Unknown document type: ${documentType}` : `Unknown document model version: ${documentType} v${version}` + (latestModule ? ` (available: ${availableVersions(modules, documentType).join(", ")})` : " (no module for this document type)"));
1217
+ }
1218
+ function availableVersions(modules, documentType) {
1219
+ return modules.filter((module) => module.documentModel.global.id === documentType).map((module) => module.version ?? 1).sort((a, b) => a - b);
1220
+ }
1221
+ function staticPackageManagerError(member) {
1222
+ return /* @__PURE__ */ new Error(`${member} is not supported: StaticPackageManager holds a fixed set of packages`);
1223
+ }
1224
+ /**
1225
+ * Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that
1226
+ * assemble their model list from mixed sources instead of passing whole
1227
+ * packages. The manifest is fabricated - loose modules carry none - so prefer
1228
+ * the `packages` prop with the real package exports when you have them: a real
1229
+ * package also carries `editors`, which makes the editor hooks work.
1230
+ */
1231
+ function packageFromDocumentModels(documentModels) {
1232
+ return {
1233
+ manifest: {
1234
+ name: "graphql-reactor-provider",
1235
+ description: "Document models passed to GraphQLReactorProvider"
1236
+ },
1237
+ documentModels,
1238
+ editors: []
1239
+ };
1240
+ }
1241
+ //#endregion
1242
+ //#region src/graphql-client/subgraph.ts
1243
+ /** What {@link describeGraphQLDocument} could not read off a document. */
1244
+ const unnamedOperation = "AnonymousOperation";
1245
+ const defaultOperationType = "query";
1246
+ /**
1247
+ * Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.
1248
+ *
1249
+ * Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so
1250
+ * `http://localhost:4001/graphql` plus `statements` is
1251
+ * `http://localhost:4001/graphql/statements`.
1252
+ */
1253
+ function subgraphUrlFromGraphqlUrl(url, name) {
1254
+ const trimmed = name.trim();
1255
+ if (trimmed === "") throw new Error("a subgraph name is required");
1256
+ return `${url.replace(/\/+$/, "")}/${trimmed}`;
1257
+ }
1258
+ /**
1259
+ * Reads the operation name and type off a document, for the middleware.
1260
+ *
1261
+ * Nothing depends on getting this right - it is reported to the middleware, not
1262
+ * sent to the server - so an unreadable document falls back to an anonymous
1263
+ * query rather than throwing.
1264
+ */
1265
+ function describeGraphQLDocument(document) {
1266
+ if (typeof document !== "string") {
1267
+ const operation = document.definitions.find((definition) => definition.kind === Kind.OPERATION_DEFINITION);
1268
+ if (!operation || operation.kind !== Kind.OPERATION_DEFINITION) return {
1269
+ operationName: unnamedOperation,
1270
+ operationType: defaultOperationType
1271
+ };
1272
+ return {
1273
+ operationName: operation.name?.value ?? unnamedOperation,
1274
+ operationType: operation.operation
1275
+ };
1276
+ }
1277
+ const match = /\b(query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document);
1278
+ if (!match) return {
1279
+ operationName: unnamedOperation,
1280
+ operationType: /\bmutation\b/.test(document) ? "mutation" : defaultOperationType
1281
+ };
1282
+ return {
1283
+ operationName: match[2],
1284
+ operationType: match[1]
1285
+ };
1286
+ }
1287
+ /**
1288
+ * Binds typed subgraph SDKs to one Switchboard's transport and auth.
1289
+ *
1290
+ * Every capability a Switchboard exposes lives behind the same base URL, so an
1291
+ * app should not have to build a second client - with a second copy of the auth
1292
+ * configuration - to reach a project's own subgraph. The registry derives the
1293
+ * endpoint, reuses one transport per subgraph and hands the code generator's
1294
+ * `getSdk` the very middleware the reactor operations already go through.
1295
+ *
1296
+ * Transport and typing only: subgraph results are not cached and produce no
1297
+ * change events.
1298
+ */
1299
+ var SubgraphSdkRegistry = class {
1300
+ url;
1301
+ middleware;
1302
+ bindings = /* @__PURE__ */ new Map();
1303
+ constructor(url, middleware) {
1304
+ this.url = url;
1305
+ this.middleware = middleware;
1306
+ }
1307
+ /**
1308
+ * Returns the subgraph's SDK, building it on first use.
1309
+ *
1310
+ * The transport is kept per subgraph name, so repeated calls do not rebuild
1311
+ * it. The SDK itself is only reused when the same factory is passed again -
1312
+ * two different generated SDKs over one subgraph each get their own, rather
1313
+ * than the second call being handed the first one's methods.
1314
+ */
1315
+ get(name, getSdk) {
1316
+ const binding = this.binding(name);
1317
+ if (binding.factory === getSdk) return binding.sdk;
1318
+ const sdk = getSdk(binding.transport, this.middleware);
1319
+ binding.factory = getSdk;
1320
+ binding.sdk = sdk;
1321
+ return sdk;
1322
+ }
1323
+ /** Returns the subgraph's endpoint, for diagnostics and tests. */
1324
+ urlFor(name) {
1325
+ return subgraphUrlFromGraphqlUrl(this.url, name);
1326
+ }
1327
+ binding(name) {
1328
+ const existing = this.bindings.get(name);
1329
+ if (existing) return existing;
1330
+ const binding = { transport: new GraphQLClient(this.urlFor(name)) };
1331
+ this.bindings.set(name, binding);
1332
+ return binding;
1333
+ }
1334
+ };
1335
+ //#endregion
1336
+ //#region src/graphql-client/subscriptions.ts
1337
+ /**
1338
+ * Opens one `documentChanges` subscription and feeds every event to `onEvent`.
1339
+ *
1340
+ * The subscription is a firehose: no `search` argument, so the server sends
1341
+ * every change the connection is allowed to see and the caller filters. This is
1342
+ * the only module that knows about `graphql-ws`.
1343
+ *
1344
+ * Returns the stop function, which cancels the subscription and closes the
1345
+ * socket. It is safe to call more than once.
1346
+ */
1347
+ function startDocumentChangesSubscription(options) {
1348
+ const client = createClient({
1349
+ url: options.wsUrl,
1350
+ connectionParams: options.connectionParams
1351
+ });
1352
+ const unsubscribe = client.subscribe({
1353
+ operationName: "DocumentChanges",
1354
+ query: print(DocumentChangesDocument)
1355
+ }, {
1356
+ next: (result) => {
1357
+ const event = result.data?.documentChanges;
1358
+ if (event) options.onEvent(event);
1359
+ },
1360
+ error: (error) => options.onError(error),
1361
+ complete: () => void 0
1362
+ });
1363
+ let stopped = false;
1364
+ return () => {
1365
+ if (stopped) return;
1366
+ stopped = true;
1367
+ unsubscribe();
1368
+ client.dispose();
1369
+ };
1370
+ }
1371
+ /**
1372
+ * Derives the websocket endpoint from the GraphQL http endpoint.
1373
+ *
1374
+ * `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is
1375
+ * where the Switchboard mounts its websocket server (`packages/reactor-api`
1376
+ * `startServer`). A URL that already speaks `ws`/`wss` only gets the path.
1377
+ */
1378
+ function subscriptionsUrlFromGraphqlUrl(url) {
1379
+ const trimmed = url.replace(/\/+$/, "");
1380
+ return `${trimmed.startsWith("https://") ? `wss://${trimmed.slice(8)}` : trimmed.startsWith("http://") ? `ws://${trimmed.slice(7)}` : trimmed}/subscriptions`;
1381
+ }
1382
+ /**
1383
+ * Turns a bearer token provider into `connectionParams`.
1384
+ *
1385
+ * The header key is the lowercase `authorization` the Switchboard's websocket
1386
+ * context factory reads. Without a token the payload is empty: an open
1387
+ * Switchboard serves anonymous subscribers.
1388
+ */
1389
+ function makeAuthConnectionParams(tokenProvider) {
1390
+ return async () => {
1391
+ const token = await tokenProvider();
1392
+ if (!token) return {};
1393
+ return { authorization: `Bearer ${token}` };
1394
+ };
1395
+ }
1396
+ //#endregion
1397
+ //#region src/graphql-client/graphql-reactor-client.ts
1398
+ /** Paging defaults, matching the reactor's own client. */
1399
+ const defaultPaging = {
1400
+ cursor: "0",
1401
+ limit: 100
1402
+ };
1403
+ /**
1404
+ * The marker {@link isGraphQLReactorClient} looks for.
1405
+ *
1406
+ * A page can end up with two copies of this module - an app that bundles a
1407
+ * package carrying its own copy, or a dev server that hot-replaced it - and
1408
+ * then `instanceof` compares an instance against the other copy's class object
1409
+ * and answers `false`. A branded property survives both.
1410
+ */
1411
+ const graphQLReactorClientBrand = "__powerhouseGraphQLReactorClient";
1412
+ /**
1413
+ * A light implementation of {@link IReactorBrowserClient} that talks plain
1414
+ * GraphQL to a Switchboard, with no reactor in the bundle.
1415
+ *
1416
+ * It fills the same `window.ph` slots the full in-browser reactor client fills,
1417
+ * so the reactor-browser hooks cannot tell the two apart.
1418
+ */
1419
+ var GraphQLReactorClient = class {
1420
+ /** See {@link isGraphQLReactorClient}. */
1421
+ [graphQLReactorClientBrand] = true;
1422
+ sdk;
1423
+ subgraphs;
1424
+ listeners = [];
1425
+ tokenProvider;
1426
+ subscriptionsUrl;
1427
+ documentModels;
1428
+ signer;
1429
+ stopRealtime;
1430
+ realtimeStarted = false;
1431
+ realtimeGeneration = 0;
1432
+ realtimeErrorLogged = false;
1433
+ constructor(options) {
1434
+ this.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;
1435
+ this.documentModels = [...options.documentModels ?? []];
1436
+ this.signer = options.signer;
1437
+ this.subscriptionsUrl = options.realtime === false ? void 0 : options.subscriptionsUrl ?? subscriptionsUrlFromGraphqlUrl(options.url);
1438
+ const middleware = makeAuthMiddleware(this.tokenProvider);
1439
+ this.sdk = options.graphqlClient ?? createClient$1(options.url, middleware);
1440
+ this.subgraphs = new SubgraphSdkRegistry(options.url, middleware);
1441
+ }
1442
+ async get(identifier, view, signal) {
1443
+ const viewInput = viewFilterInputFromViewFilter(view);
1444
+ const document = (await this.sdk.GetDocument({
1445
+ identifier,
1446
+ view: viewInput
1447
+ }, void 0, signal)).document;
1448
+ if (!document) throw new Error(`Document not found: ${identifier}`);
1449
+ return phDocumentFromGetDocument(document.document, view?.branch);
1450
+ }
1451
+ async getOperations(documentIdentifier, view, filter, paging, signal) {
1452
+ const viewInput = viewFilterInputFromViewFilter(view);
1453
+ const operationsFilter = {
1454
+ documentId: documentIdentifier,
1455
+ branch: viewInput?.branch,
1456
+ scopes: viewInput?.scopes,
1457
+ actionTypes: filter?.actionTypes,
1458
+ timestampFrom: filter?.timestampFrom,
1459
+ timestampTo: filter?.timestampTo,
1460
+ sinceRevision: filter?.sinceRevision
1461
+ };
1462
+ const page = (await this.sdk.GetDocumentOperations({
1463
+ filter: operationsFilter,
1464
+ paging: pagingInputFromPaging(paging)
1465
+ }, void 0, signal)).documentOperations;
1466
+ const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
1467
+ const effectivePaging = paging ?? defaultPaging;
1468
+ return {
1469
+ results: page.items.map((item) => remoteOperationToLocal(item)),
1470
+ options: effectivePaging,
1471
+ nextCursor,
1472
+ totalCount: page.totalCount,
1473
+ next: nextCursor ? () => this.getOperations(documentIdentifier, view, filter, {
1474
+ cursor: nextCursor,
1475
+ limit: effectivePaging.limit
1476
+ }, signal) : void 0
1477
+ };
1478
+ }
1479
+ async create(document, parentIdentifier, signal) {
1480
+ const created = phDocumentFromGetDocument((await this.sdk.CreateDocument({
1481
+ document,
1482
+ parentIdentifier
1483
+ }, void 0, signal)).createDocument);
1484
+ this.emitChange({
1485
+ type: DOCUMENT_CHANGE_TYPE.Created,
1486
+ documents: [created]
1487
+ });
1488
+ return created;
1489
+ }
1490
+ /**
1491
+ * Pushes actions to the Switchboard and returns the updated document.
1492
+ *
1493
+ * The document is fetched first: the response is the baseline for the
1494
+ * `sinceRevision` filter that narrows the returned operations to the ones
1495
+ * this call appended, and it carries the state hash a signed action is
1496
+ * stamped with.
1497
+ *
1498
+ * The emitted `Updated` event carries the document's id, never the
1499
+ * identifier this was called with: subscribers - including `DocumentCache` -
1500
+ * work in id space.
1501
+ */
1502
+ async execute(documentIdentifier, branch, actions, signal) {
1503
+ const document = await this.get(documentIdentifier, { branch }, signal);
1504
+ const variables = {
1505
+ documentIdentifier,
1506
+ actions: (await prepareActionsForPush(actions, document, this.documentModels, this.signer, signal)).map(toTransportAction),
1507
+ sinceRevision: sinceRevisionForActions(document, actions),
1508
+ scopes: scopesForActions(actions),
1509
+ branch
1510
+ };
1511
+ const mutated = (await this.sdk.RunDocument({
1512
+ operationName: "MutateDocumentWithOperations",
1513
+ operationType: "mutation",
1514
+ document: MutateDocumentWithOperationsDocument,
1515
+ variables,
1516
+ signal
1517
+ })).mutateDocument;
1518
+ const updated = phDocumentFromMutation(mutated, mutated.operations?.items ?? [], branch);
1519
+ this.emitChange({
1520
+ type: DOCUMENT_CHANGE_TYPE.Updated,
1521
+ documents: [updated]
1522
+ });
1523
+ return updated;
1524
+ }
1525
+ /**
1526
+ * Deletes a document and announces it as a `Deleted` event.
1527
+ *
1528
+ * Pass a document id. The server resolves a slug just as happily, but
1529
+ * `deleteDocument` returns a boolean - there is no document left to read an
1530
+ * id off - so the identifier is announced verbatim on `context.childId`. A
1531
+ * subscriber keyed by id, `DocumentCache` included, therefore only reacts to
1532
+ * a delete by id.
1533
+ */
1534
+ async deleteDocument(identifier, propagate, signal) {
1535
+ await this.sdk.DeleteDocument({
1536
+ identifier,
1537
+ propagate: propagationModeInput(propagate)
1538
+ }, void 0, signal);
1539
+ this.emitChange({
1540
+ type: DOCUMENT_CHANGE_TYPE.Deleted,
1541
+ documents: [],
1542
+ context: { childId: identifier }
1543
+ });
1544
+ }
1545
+ /**
1546
+ * Registers a change subscriber and returns its unsubscribe function.
1547
+ *
1548
+ * Two things produce the events delivered here. Every successful `create`,
1549
+ * `execute` and `deleteDocument` emits one, which is what makes a
1550
+ * `DocumentCache` built on this client invalidate after a dispatch. And,
1551
+ * unless realtime is switched off, the first call to this method opens a
1552
+ * websocket to the Switchboard and every change it reports - from another
1553
+ * user, another tab or a server-side processor - is emitted too. A write of
1554
+ * this client's own is therefore announced twice, once locally and once by
1555
+ * the server; the cache refetches twice, which is harmless.
1556
+ *
1557
+ * A websocket that cannot be opened or is refused is logged once and then
1558
+ * ignored: realtime is an enhancement, never a dependency. The failed socket
1559
+ * is closed, so the next subscriber to arrive tries again.
1560
+ *
1561
+ * `view` is accepted for interface compatibility and ignored: the emitted
1562
+ * documents are whatever the write returned, so there is nothing to re-scope.
1563
+ *
1564
+ * Events live in id space: `search.ids` is matched against the resolved
1565
+ * document id, never against the identifier the write was issued with. The
1566
+ * one exception is `deleteDocument`, which has no document to resolve an id
1567
+ * from - see its own note. A `DocumentCache` on this client must therefore
1568
+ * be read by id: a slug-keyed entry is never invalidated.
1569
+ */
1570
+ subscribe(search, callback, view) {
1571
+ const listener = {
1572
+ search,
1573
+ callback
1574
+ };
1575
+ this.listeners.push(listener);
1576
+ this.startRealtime();
1577
+ return () => {
1578
+ const index = this.listeners.indexOf(listener);
1579
+ if (index !== -1) this.listeners.splice(index, 1);
1580
+ };
1581
+ }
1582
+ /**
1583
+ * Closes the realtime socket, if one was opened.
1584
+ *
1585
+ * Registered subscribers are left in place: they still receive the events
1586
+ * this client produces itself.
1587
+ *
1588
+ * Disposing is NOT final - a later `subscribe` opens a new socket. React
1589
+ * remounts a tree by running an effect's cleanup and then the effect again,
1590
+ * on the same client, and `StrictMode` does exactly that on every mount; a
1591
+ * terminal flag here would leave those pages without realtime for good, with
1592
+ * nothing logged.
1593
+ */
1594
+ dispose() {
1595
+ this.teardownRealtime();
1596
+ }
1597
+ /**
1598
+ * Binds a project's generated SDK to this client's transport and auth.
1599
+ *
1600
+ * Subgraphs are served next to the reactor's own supergraph, so the endpoint
1601
+ * is derived from the client's `url` by appending the name, and the SDK is
1602
+ * handed the same auth middleware every reactor call goes through. An app
1603
+ * therefore configures one URL and one token provider, and reaches every
1604
+ * capability of its Switchboard through this one client.
1605
+ *
1606
+ * `getSdk` is the function a GraphQL code generator emits for the subgraph's
1607
+ * schema - see the README in this folder for the codegen recipe.
1608
+ *
1609
+ * Transport and typing only. Subgraph results are not cached, produce no
1610
+ * change events and never reach `useDocument`.
1611
+ */
1612
+ subgraph(name, getSdk) {
1613
+ return this.subgraphs.get(name, getSdk);
1614
+ }
1615
+ /**
1616
+ * Runs a one-off GraphQL document against the Switchboard's own endpoint,
1617
+ * through the same transport and auth as everything else.
1618
+ *
1619
+ * The escape hatch for an operation not worth generating an SDK for. Pass a
1620
+ * document a code generator typed and the result type follows; pass a plain
1621
+ * `gql` document or a string and name the result type at the call site.
1622
+ */
1623
+ async request(document, variables, options) {
1624
+ const described = describeGraphQLDocument(document);
1625
+ return this.sdk.RunDocument({
1626
+ operationName: options?.operationName ?? described.operationName,
1627
+ operationType: options?.operationType ?? described.operationType,
1628
+ document,
1629
+ variables,
1630
+ signal: options?.signal
1631
+ });
1632
+ }
1633
+ /**
1634
+ * Opens the realtime socket on the first subscriber.
1635
+ *
1636
+ * The subscription is a firehose - no `search` argument - and this client
1637
+ * applies each subscriber's own filter on the way out, exactly as it does for
1638
+ * its own emissions.
1639
+ */
1640
+ startRealtime() {
1641
+ if (!this.subscriptionsUrl || this.realtimeStarted) return;
1642
+ this.realtimeStarted = true;
1643
+ const generation = this.realtimeGeneration;
1644
+ const stop = startDocumentChangesSubscription({
1645
+ wsUrl: this.subscriptionsUrl,
1646
+ connectionParams: makeAuthConnectionParams(this.tokenProvider),
1647
+ onEvent: (event) => this.emitServerEvent(event),
1648
+ onError: (error) => this.handleRealtimeFailure(generation, error)
1649
+ });
1650
+ if (this.realtimeGeneration !== generation) {
1651
+ stop();
1652
+ return;
1653
+ }
1654
+ this.stopRealtime = stop;
1655
+ }
1656
+ /**
1657
+ * Gives up on a failed socket so that a later subscriber can try again.
1658
+ *
1659
+ * `graphql-ws` retries on its own and only reports here once it has given up,
1660
+ * or once the server refused the subscription outright - which is what an
1661
+ * auth-enabled Switchboard does to an anonymous subscriber. Keeping the dead
1662
+ * stop function would make every later `subscribe` a no-op, so realtime would
1663
+ * stay off for the life of the page even after the user signs in.
1664
+ *
1665
+ * The generation stamp discards a report from a socket that has already been
1666
+ * replaced or disposed.
1667
+ */
1668
+ handleRealtimeFailure(generation, error) {
1669
+ if (generation !== this.realtimeGeneration) return;
1670
+ this.teardownRealtime();
1671
+ this.logRealtimeError(error);
1672
+ }
1673
+ /** Closes the socket and lets a later subscriber open a new one. */
1674
+ teardownRealtime() {
1675
+ this.realtimeGeneration += 1;
1676
+ this.realtimeStarted = false;
1677
+ this.stopRealtime?.();
1678
+ this.stopRealtime = void 0;
1679
+ }
1680
+ /** Maps a server event onto the client-side event and emits it. */
1681
+ emitServerEvent(event) {
1682
+ this.emitChange({
1683
+ type: documentChangeTypes[event.type],
1684
+ documents: event.documents.map((document) => phDocumentFromGetDocument(document)),
1685
+ context: event.context ? {
1686
+ parentId: event.context.parentId ?? void 0,
1687
+ childId: event.context.childId ?? void 0
1688
+ } : void 0
1689
+ });
1690
+ }
1691
+ /**
1692
+ * Reports a broken realtime socket once per client, however many sockets it
1693
+ * goes through.
1694
+ *
1695
+ * `graphql-ws` retries on its own, and a Switchboard without a websocket
1696
+ * endpoint would otherwise fill the console for as long as the page is open.
1697
+ */
1698
+ logRealtimeError(error) {
1699
+ if (this.realtimeErrorLogged) return;
1700
+ this.realtimeErrorLogged = true;
1701
+ logger.warn("GraphQLReactorClient: realtime document changes are unavailable, falling back to local change events", error);
1702
+ }
1703
+ /**
1704
+ * Delivers an event to every matching subscriber.
1705
+ *
1706
+ * A subscriber that throws is logged and skipped so one bad listener cannot
1707
+ * stop the others from being notified.
1708
+ */
1709
+ emitChange(event) {
1710
+ for (const listener of [...this.listeners]) {
1711
+ if (!eventMatchesSearch(event, listener.search)) continue;
1712
+ try {
1713
+ listener.callback(event);
1714
+ } catch (error) {
1715
+ logger.error("GraphQLReactorClient: a document change subscriber threw", error);
1716
+ }
1717
+ }
1718
+ }
1719
+ };
1720
+ /**
1721
+ * Whether a value is a {@link GraphQLReactorClient}, including one built by
1722
+ * another copy of this module.
1723
+ *
1724
+ * Use this rather than `instanceof`: the brand it tests for is shared by every
1725
+ * copy of the class, so a client built by a hot-replaced module or by a package
1726
+ * that bundled its own copy is still recognised.
1727
+ */
1728
+ function isGraphQLReactorClient(client) {
1729
+ return client?.[graphQLReactorClientBrand] === true;
1730
+ }
1731
+ /** The schema's change types, mapped onto the reactor's. */
1732
+ const documentChangeTypes = {
1733
+ [DocumentChangeType.Created]: DOCUMENT_CHANGE_TYPE.Created,
1734
+ [DocumentChangeType.Deleted]: DOCUMENT_CHANGE_TYPE.Deleted,
1735
+ [DocumentChangeType.Updated]: DOCUMENT_CHANGE_TYPE.Updated,
1736
+ [DocumentChangeType.ParentAdded]: DOCUMENT_CHANGE_TYPE.ParentAdded,
1737
+ [DocumentChangeType.ParentRemoved]: DOCUMENT_CHANGE_TYPE.ParentRemoved,
1738
+ [DocumentChangeType.ChildAdded]: DOCUMENT_CHANGE_TYPE.ChildAdded,
1739
+ [DocumentChangeType.ChildRemoved]: DOCUMENT_CHANGE_TYPE.ChildRemoved
1740
+ };
1741
+ /**
1742
+ * Decides whether an event reaches a subscriber.
1743
+ *
1744
+ * Every populated field of the search filter is an AND condition, matching the
1745
+ * reactor's own subscription manager - which also treats an empty array as a
1746
+ * filter that nothing satisfies. `parentId` is a drive concept and is ignored.
1747
+ *
1748
+ * A `Deleted` event carries no documents, so it is matched on its
1749
+ * `context.childId` for identifier filters and delivered unconditionally to
1750
+ * type and slug filters: there is no document left to check them against.
1751
+ */
1752
+ function eventMatchesSearch(event, search) {
1753
+ const deleted = event.type === DOCUMENT_CHANGE_TYPE.Deleted;
1754
+ const { ids, slugs, type } = search;
1755
+ if (ids) {
1756
+ if (!(deleted ? [event.context?.childId] : event.documents.map((document) => document.header.id)).some((id) => id !== void 0 && ids.includes(id))) return false;
1757
+ }
1758
+ if (slugs && !deleted) {
1759
+ if (!event.documents.map((document) => document.header.slug).some((slug) => slugs.includes(slug))) return false;
1760
+ }
1761
+ if (type && !deleted) {
1762
+ if (!event.documents.map((document) => document.header.documentType).includes(type)) return false;
1763
+ }
1764
+ return true;
1765
+ }
1766
+ /**
1767
+ * Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.
1768
+ *
1769
+ * Point-in-time reads are rejected: the Switchboard read API has no revision
1770
+ * argument, so silently returning the head state would be wrong.
1771
+ */
1772
+ function viewFilterInputFromViewFilter(view) {
1773
+ if (!view) return;
1774
+ if (view.revision !== void 0) throw new Error("point-in-time views are not supported by GraphQLReactorClient");
1775
+ if (view.branch === void 0 && view.scopes === void 0) return;
1776
+ return {
1777
+ branch: view.branch,
1778
+ scopes: view.scopes
1779
+ };
1780
+ }
1781
+ function pagingInputFromPaging(paging) {
1782
+ if (!paging) return;
1783
+ return {
1784
+ cursor: paging.cursor,
1785
+ limit: paging.limit
1786
+ };
1787
+ }
1788
+ /**
1789
+ * The reactor and the GraphQL schema disagree on the enum: the reactor's
1790
+ * `None` is the schema's `ORPHAN`. This is the inverse of the server's
1791
+ * `toReactorPropagationMode`.
1792
+ */
1793
+ const propagationModeInputs = {
1794
+ cascade: PropagationMode.Cascade,
1795
+ none: PropagationMode.Orphan
1796
+ };
1797
+ function propagationModeInput(propagate) {
1798
+ return propagate === void 0 ? void 0 : propagationModeInputs[propagate];
1799
+ }
1800
+ /**
1801
+ * Stamps and signs the actions about to be pushed.
1802
+ *
1803
+ * With no signer the actions go out exactly as given, batch or not - this
1804
+ * client does not require signatures. With one, every action is signed:
1805
+ * {@link prepareSignedActions} predicts the chain a batch will produce by
1806
+ * running the document's own reducer between signatures, which is why a batch
1807
+ * needs the module matching the document's type and exact version.
1808
+ *
1809
+ * A batch that cannot be predicted - no matching module, mixed scopes, an
1810
+ * action needing history - throws here, before the mutation. Sending it
1811
+ * unsigned instead would silently drop the signatures the caller asked for.
1812
+ */
1813
+ async function prepareActionsForPush(actions, document, documentModels, explicitSigner, signal) {
1814
+ const signer = explicitSigner ?? resolveAmbientSigner();
1815
+ if (!signer || actions.length === 0) return actions;
1816
+ return prepareSignedActions(actions, document, signer, actions.length > 1 ? resolveDocumentModelModule(documentModels, document.header.documentType, documentModelVersion(document)) : void 0, signal);
1817
+ }
1818
+ /**
1819
+ * The document-model version the document's actions must be reduced with.
1820
+ *
1821
+ * `state` arrives as JSON over GraphQL, so its `document` scope is only as
1822
+ * reliable as the server that sent it - one written before that scope existed
1823
+ * carries no version at all. `normalizeDocumentModelVersion` maps that, and 0,
1824
+ * to 1: the same rule `SimpleJobExecutor` applies before asking the registry
1825
+ * for a module, so client and server cannot resolve different reducers.
1826
+ */
1827
+ function documentModelVersion(document) {
1828
+ const documentScope = document.state.document;
1829
+ return normalizeDocumentModelVersion(documentScope?.version);
1830
+ }
1831
+ /** Resolves the signer of the logged-in user, if there is one. */
1832
+ function resolveAmbientSigner() {
1833
+ if (typeof window === "undefined") return;
1834
+ const renown = window.ph?.renown;
1835
+ return renown?.user ? renown.signer : void 0;
1836
+ }
1837
+ /**
1838
+ * The revision the pushed operations start from: the lowest head revision
1839
+ * across the scopes the actions target.
1840
+ *
1841
+ * The baseline is only meaningful together with {@link scopesForActions}: a
1842
+ * batch that touches a scope at revision 1 and one at revision 5000 would
1843
+ * otherwise re-download the whole history of every scope of the document.
1844
+ */
1845
+ function sinceRevisionForActions(document, actions) {
1846
+ const revisions = actions.map((action) => document.header.revision[action.scope] ?? 0);
1847
+ return revisions.length > 0 ? Math.min(...revisions) : 0;
1848
+ }
1849
+ /** The distinct scopes the pushed actions target, in first-seen order. */
1850
+ function scopesForActions(actions) {
1851
+ if (actions.length === 0) return;
1852
+ return [...new Set(actions.map((action) => action.scope))];
1853
+ }
1854
+ //#endregion
1855
+ //#region src/hooks/config/editor.ts
1856
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
1857
+ /** Sets whether external controls are enabled for a given editor. */
1858
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
1859
+ /** Gets whether external controls are enabled for a given editor. */
1860
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
1861
+ /** Adds an event handler for when the external controls enabled state changes. */
1862
+ const addIsExternalControlsEnabledEventHandler = isExternalControlsEnabledEventFunctions.addEventHandler;
1863
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
1864
+ /** Sets whether drag and drop is enabled for a given app. */
1865
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
1866
+ /** Gets whether drag and drop is enabled for a given app. */
1867
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
1868
+ /** Adds an event handler for when the drag and drop enabled state changes. */
1869
+ const addIsDragAndDropEnabledEventHandler = isDragAndDropEnabledEventFunctions.addEventHandler;
1870
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
1871
+ /** Sets the allowed document types for a given app. */
1872
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
1873
+ /** Defines the document types a drive supports.
1874
+ *
1875
+ * Defaults to all of the document types registered in the reactor.
1876
+ */
1877
+ function useAllowedDocumentTypes() {
1878
+ return allowedDocumentTypesEventFunctions.useValue();
1879
+ }
1880
+ /** Adds an event handler for when the allowed document types for a given app changes. */
1881
+ const addAllowedDocumentTypesEventHandler = allowedDocumentTypesEventFunctions.addEventHandler;
1882
+ const phAppConfigSetters = {
1883
+ allowedDocumentTypes: setAllowedDocumentTypes,
1884
+ isDragAndDropEnabled: setIsDragAndDropEnabled
1885
+ };
1886
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
1887
+ const phAppConfigHooks = {
1888
+ allowedDocumentTypes: useAllowedDocumentTypes,
1889
+ isDragAndDropEnabled: useIsDragAndDropEnabled
1890
+ };
1891
+ const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
1892
+ //#endregion
1893
+ //#region src/hooks/config/connect.ts
1894
+ const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
1895
+ const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
1896
+ const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
1897
+ const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
1898
+ const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
1899
+ const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
1900
+ const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
1901
+ const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
1902
+ const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
1903
+ const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
1904
+ const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
1905
+ const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
1906
+ const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
1907
+ const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
1908
+ const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
1909
+ const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
1910
+ const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
1911
+ const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
1912
+ const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
1913
+ const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
1914
+ const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
1915
+ const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
1916
+ const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
1917
+ const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
1918
+ const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
1919
+ const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
1920
+ const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
1921
+ const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
1922
+ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
1923
+ const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
1924
+ const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
1925
+ const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
1926
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
1927
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
1928
+ const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
1929
+ const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
1930
+ const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
1931
+ const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
1932
+ const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
1933
+ const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
1934
+ const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
1935
+ /** Sets the enabled editors for Connect. */
1936
+ const setEnabledEditors = enabledEditorsEventFunctions.setValue;
1937
+ /** Gets the enabled editors for Connect. */
1938
+ const useEnabledEditors = enabledEditorsEventFunctions.useValue;
1939
+ /** Adds an event handler for when the enabled editors for Connect changes. */
1940
+ const addEnabledEditorsEventHandler = enabledEditorsEventFunctions.addEventHandler;
1941
+ const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
1942
+ /** Sets the disabled editors for Connect. */
1943
+ const setDisabledEditors = disabledEditorsEventFunctions.setValue;
1944
+ /** Gets the disabled editors for Connect. */
1945
+ const useDisabledEditors = disabledEditorsEventFunctions.useValue;
1946
+ /** Adds an event handler for when the disabled editors for Connect changes. */
1947
+ const addDisabledEditorsEventHandler = disabledEditorsEventFunctions.addEventHandler;
1948
+ const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
1949
+ /** Sets the isRelationalProcessorsEnabled for Connect. */
1950
+ const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
1951
+ /** Gets the isRelationalProcessorsEnabled for Connect. */
1952
+ const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
1953
+ /** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */
1954
+ const addIsRelationalProcessorsEnabledEventHandler = isRelationalProcessorsEnabled.addEventHandler;
1955
+ const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
1956
+ /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
1957
+ const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
1958
+ /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
1959
+ const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
1960
+ /** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */
1961
+ const addIsExternalRelationalProcessorsEnabledEventHandler = isExternalRelationalProcessorsEnabled.addEventHandler;
1962
+ const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
1963
+ /** Sets the isAnalyticsEnabled for Connect. */
1964
+ const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
1965
+ /** Gets the isAnalyticsEnabled for Connect. */
1966
+ const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
1967
+ /** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */
1968
+ const addIsAnalyticsEnabledEventHandler = isAnalyticsEnabledEventFunctions.addEventHandler;
1969
+ const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
1970
+ /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
1971
+ const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
1972
+ /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
1973
+ const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
1974
+ /** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */
1975
+ const addIsAnalyticsExternalProcessorsEnabledEventHandler = isAnalyticsExternalProcessorsEnabled.addEventHandler;
1976
+ const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
1977
+ /** Sets the analytics database name for Connect. */
1978
+ const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
1979
+ /** Gets the analytics database name for Connect. */
1980
+ const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
1981
+ /** Adds an event handler for when the analytics database name for Connect changes. */
1982
+ const addAnalyticsDatabaseNameEventHandler = analyticsDatabaseNameEventFunctions.addEventHandler;
1983
+ const logLevelEventFunctions = makePHEventFunctions("logLevel");
1984
+ /** Sets the log level for Connect. */
1985
+ const setLogLevel = logLevelEventFunctions.setValue;
1986
+ /** Gets the log level for Connect. */
1987
+ const useLogLevel = logLevelEventFunctions.useValue;
1988
+ /** Adds an event handler for when the log level for Connect changes. */
1989
+ const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;
1990
+ const allowListEventFunctions = makePHEventFunctions("allowList");
1991
+ /** Sets the allow list for Connect. */
1992
+ const setAllowList = allowListEventFunctions.setValue;
1993
+ /** Gets the allow list for Connect. */
1994
+ const useAllowList = allowListEventFunctions.useValue;
1995
+ /** Adds an event handler for when the allow list for Connect changes. */
1996
+ const addAllowListEventHandler = allowListEventFunctions.addEventHandler;
1997
+ const nonUserConfigSetters = {
1998
+ routerBasename: setRouterBasename,
1999
+ version: setVersion,
2000
+ requiresHardRefresh: setRequiresHardRefresh,
2001
+ warnOutdatedApp: setWarnOutdatedApp,
2002
+ studioMode: setStudioMode,
2003
+ basePath: setBasePath,
2004
+ versionCheckInterval: setVersionCheckInterval,
2005
+ cliVersion: setCliVersion,
2006
+ fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
2007
+ isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
2008
+ gaTrackingId: setGaTrackingId,
2009
+ defaultDrivesUrl: setDefaultDrivesUrl,
2010
+ drivesPreserveStrategy: setDrivesPreserveStrategy,
2011
+ isLocalDrivesEnabled: setIsLocalDrivesEnabled,
2012
+ isAddDriveEnabled: setIsAddDriveEnabled,
2013
+ isPublicDrivesEnabled: setIsPublicDrivesEnabled,
2014
+ isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
2015
+ isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
2016
+ isCloudDrivesEnabled: setIsCloudDrivesEnabled,
2017
+ isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
2018
+ isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
2019
+ isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
2020
+ isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
2021
+ isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
2022
+ isEditorReadModeEnabled: setIsEditorReadModeEnabled,
2023
+ isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
2024
+ isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
2025
+ isAnalyticsEnabled: setIsAnalyticsEnabled,
2026
+ analyticsDatabaseName: setAnalyticsDatabaseName,
2027
+ isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
2028
+ isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
2029
+ isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
2030
+ isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
2031
+ renownUrl: setRenownUrl,
2032
+ renownNetworkId: setRenownNetworkId,
2033
+ renownChainId: setRenownChainId,
2034
+ switchboardUrl: setSwitchboardUrl,
2035
+ renownAdapters: setRenownAdapters,
2036
+ sentryRelease: setSentryRelease,
2037
+ sentryDsn: setSentryDsn,
2038
+ sentryEnv: setSentryEnv,
2039
+ isSentryTracingEnabled: setIsSentryTracingEnabled,
2040
+ isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
2041
+ isExternalPackagesEnabled: setIsExternalPackagesEnabled,
2042
+ allowList: setAllowList,
2043
+ logLevel: setLogLevel,
2044
+ disabledEditors: setDisabledEditors,
2045
+ enabledEditors: setEnabledEditors
2046
+ };
2047
+ const phGlobalConfigSetters = {
2048
+ ...phAppConfigSetters,
2049
+ ...phDocumentEditorConfigSetters,
2050
+ ...nonUserConfigSetters
2051
+ };
2052
+ const nonUserConfigHooks = {
2053
+ routerBasename: useRouterBasename,
2054
+ version: useVersion,
2055
+ requiresHardRefresh: useRequiresHardRefresh,
2056
+ warnOutdatedApp: useWarnOutdatedApp,
2057
+ studioMode: useStudioMode,
2058
+ basePath: useBasePath,
2059
+ versionCheckInterval: useVersionCheckInterval,
2060
+ cliVersion: useCliVersion,
2061
+ fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
2062
+ isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
2063
+ gaTrackingId: useGaTrackingId,
2064
+ defaultDrivesUrl: useDefaultDrivesUrl,
2065
+ drivesPreserveStrategy: useDrivesPreserveStrategy,
2066
+ isAddDriveEnabled: useIsAddDriveEnabled,
2067
+ isPublicDrivesEnabled: useIsPublicDrivesEnabled,
2068
+ isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
2069
+ isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
2070
+ isCloudDrivesEnabled: useIsCloudDrivesEnabled,
2071
+ isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
2072
+ isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
2073
+ isLocalDrivesEnabled: useIsLocalDrivesEnabled,
2074
+ isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
2075
+ isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
2076
+ isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
2077
+ isEditorReadModeEnabled: useIsEditorReadModeEnabled,
2078
+ isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
2079
+ isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
2080
+ isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
2081
+ renownUrl: useRenownUrl,
2082
+ renownNetworkId: useRenownNetworkId,
2083
+ renownChainId: useRenownChainId,
2084
+ switchboardUrl: useSwitchboardUrl,
2085
+ renownAdapters: useRenownAdapters,
2086
+ sentryRelease: useSentryRelease,
2087
+ sentryDsn: useSentryDsn,
2088
+ sentryEnv: useSentryEnv,
2089
+ isSentryTracingEnabled: useIsSentryTracingEnabled,
2090
+ isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
2091
+ isExternalPackagesEnabled: useIsExternalPackagesEnabled,
2092
+ allowList: useAllowList,
2093
+ isAnalyticsEnabled: useIsAnalyticsEnabled,
2094
+ isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
2095
+ isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
2096
+ isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
2097
+ analyticsDatabaseName: useAnalyticsDatabaseName,
2098
+ logLevel: useLogLevel,
2099
+ disabledEditors: useDisabledEditors,
2100
+ enabledEditors: useEnabledEditors
2101
+ };
2102
+ const phGlobalConfigHooks = {
2103
+ ...phAppConfigHooks,
2104
+ ...phDocumentEditorConfigHooks,
2105
+ ...nonUserConfigHooks
2106
+ };
2107
+ //#endregion
2108
+ //#region src/hooks/attachment-service.ts
2109
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2110
+ /** Returns the attachment service from window.ph */
2111
+ const useAttachmentService = attachmentServiceEventFunctions.useValue;
2112
+ /** Sets the attachment service on window.ph */
2113
+ const setAttachmentService = attachmentServiceEventFunctions.setValue;
2114
+ /** Registers the attachmentService window event handler */
2115
+ const addAttachmentServiceEventHandler = attachmentServiceEventFunctions.addEventHandler;
2116
+ //#endregion
2117
+ //#region src/hooks/features.ts
2118
+ const featuresEventFunctions = makePHEventFunctions("features");
2119
+ const useFeatures = featuresEventFunctions.useValue;
2120
+ const setFeatures = featuresEventFunctions.setValue;
2121
+ const addFeaturesEventHandler = featuresEventFunctions.addEventHandler;
2122
+ //#endregion
2123
+ //#region src/utils/url.ts
2124
+ function resolveUrlPathname(path) {
2125
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2126
+ }
2127
+ /** Returns the current path without the base path */
2128
+ function getPathWithoutBase(path) {
2129
+ const basePath = window.ph?.basePath ?? "/";
2130
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2131
+ }
2132
+ /** Makes a URL component for a drive. */
2133
+ function makeDriveUrlComponent(drive) {
2134
+ if (!drive) return "";
2135
+ return `/d/${slug(drive.header.slug)}`;
2136
+ }
2137
+ /** Makes a URL component for a node. */
2138
+ function makeNodeSlug(node) {
2139
+ if (!node) return "";
2140
+ const nodeName = node.name;
2141
+ if (!nodeName) return slug(node.id);
2142
+ return slug(`${nodeName}-${node.id}`);
2143
+ }
2144
+ /** Extracts the node slug from a path.
2145
+ *
2146
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
2147
+ */
2148
+ function extractNodeSlugFromPath(path) {
2149
+ const currentPath = getPathWithoutBase(path);
2150
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2151
+ }
2152
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
2153
+ function findUuid(input) {
2154
+ if (!input) return void 0;
2155
+ return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
2156
+ }
2157
+ function extractNodeIdFromSlug(nodeSlug) {
2158
+ return findUuid(nodeSlug);
2159
+ }
2160
+ function extractNodeIdFromPath(path) {
2161
+ return extractNodeIdFromSlug(extractNodeSlugFromPath(path));
2162
+ }
2163
+ /** Extracts the drive slug from a path.
2164
+ * Used for extracting drive ids from drive slugs in the URL.
2165
+ * Expects the path to be in the format `/d/<drive-slug>`.
2166
+ */
2167
+ function extractDriveSlugFromPath(path) {
2168
+ const currentPath = getPathWithoutBase(path);
2169
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2170
+ }
2171
+ function extractDriveIdFromSlug(driveSlug) {
2172
+ return findUuid(driveSlug);
2173
+ }
2174
+ function extractDriveIdFromPath(path) {
2175
+ return extractDriveIdFromSlug(extractDriveSlugFromPath(path));
2176
+ }
2177
+ /**
2178
+ * Creates a URL string with the given pathname while preserving existing query parameters.
2179
+ */
2180
+ function createUrlWithPreservedParams(pathname) {
2181
+ const search = window.location.search;
2182
+ return search ? `${pathname}${search}` : pathname;
2183
+ }
2184
+ //#endregion
2185
+ //#region src/hooks/drives.ts
2186
+ const drivesEventFunctions = makePHEventFunctions("drives");
2187
+ /** Returns all of the drives in the reactor */
2188
+ const useDrives = drivesEventFunctions.useValue;
2189
+ /** Sets the drives in the reactor */
2190
+ const setDrives = drivesEventFunctions.setValue;
2191
+ /** Adds an event handler for the drives */
2192
+ const addDrivesEventHandler = drivesEventFunctions.addEventHandler;
2193
+ //#endregion
2194
+ //#region src/hooks/set-selected-node.ts
2195
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
2196
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
2197
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
2198
+ const addSelectedNodeIdEventHandler = selectedNodeIdEventFunctions.addEventHandler;
2199
+ /** Sets the selected node (file or folder). */
2200
+ function setSelectedNode(nodeOrNodeSlug) {
2201
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
2202
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
2203
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
2204
+ if (!driveSlugFromPath) return;
2205
+ if (!nodeSlug) {
2206
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
2207
+ if (pathname === window.location.pathname) return;
2208
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2209
+ return;
2210
+ }
2211
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
2212
+ if (pathname === window.location.pathname) return;
2213
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2214
+ }
2215
+ function addResetSelectedNodeEventHandler() {
2216
+ window.addEventListener("ph:selectedDriveIdUpdated", () => {
2217
+ setSelectedNodeId(void 0);
2218
+ });
2219
+ }
2220
+ function addSetSelectedNodeOnPopStateEventHandler() {
2221
+ window.addEventListener("popstate", () => {
2222
+ const pathname = window.location.pathname;
2223
+ const nodeSlug = extractNodeSlugFromPath(pathname);
2224
+ if (extractNodeIdFromSlug(nodeSlug) !== window.ph?.selectedNodeId) setSelectedNode(nodeSlug);
2225
+ });
2226
+ }
2227
+ //#endregion
2228
+ //#region src/hooks/selected-drive.ts
2229
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
2230
+ /** Returns the selected drive id */
2231
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
2232
+ /** Sets the selected drive id */
2233
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
2234
+ /** Adds an event handler for the selected drive id */
2235
+ const addSelectedDriveIdEventHandler = selectedDriveIdEventFunctions.addEventHandler;
2236
+ /** Returns the selected drive */
2237
+ function useSelectedDrive() {
2238
+ const drive = useSelectedDriveSafe();
2239
+ if (!drive[0]) throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");
2240
+ return drive;
2241
+ }
2242
+ /** Returns the selected drive, or undefined if no drive is selected */
2243
+ function useSelectedDriveSafe() {
2244
+ const selectedDriveId = useSelectedDriveId();
2245
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
2246
+ const [drive, dispatch] = useDispatch(selectedDrive);
2247
+ if (!selectedDrive) return [void 0, void 0];
2248
+ return [drive, dispatch];
2249
+ }
2250
+ function setSelectedDrive(driveOrDriveSlug) {
2251
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
2252
+ const drives = window.ph?.drives;
2253
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
2254
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
2255
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
2256
+ deferDriveSelection(driveSlug);
2257
+ return;
2258
+ }
2259
+ cancelPendingDriveSelection();
2260
+ setSelectedDriveId(driveId);
2261
+ if (!driveId) {
2262
+ const pathname = resolveUrlPathname("/");
2263
+ if (pathname === window.location.pathname) return;
2264
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2265
+ return;
2266
+ }
2267
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
2268
+ if (pathname === window.location.pathname) return;
2269
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2270
+ }
2271
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
2272
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
2273
+ function isInitialSyncInFlight() {
2274
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
2275
+ if (!remotes?.length) return false;
2276
+ return remotes.some((remote) => {
2277
+ try {
2278
+ const snapshot = remote.channel.getConnectionState();
2279
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
2280
+ } catch {
2281
+ return false;
2282
+ }
2283
+ });
2284
+ }
2285
+ let pendingHandler;
2286
+ let pendingTimeout;
2287
+ function cancelPendingDriveSelection() {
2288
+ if (pendingHandler) {
2289
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
2290
+ pendingHandler = void 0;
2291
+ }
2292
+ if (pendingTimeout) {
2293
+ clearTimeout(pendingTimeout);
2294
+ pendingTimeout = void 0;
2295
+ }
2296
+ }
2297
+ function deferDriveSelection(driveSlug) {
2298
+ cancelPendingDriveSelection();
2299
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
2300
+ const handler = () => {
2301
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
2302
+ cancelPendingDriveSelection();
2303
+ setSelectedDrive(driveSlug);
2304
+ setSelectedNode(nodeSlug);
2305
+ };
2306
+ pendingHandler = handler;
2307
+ window.addEventListener("ph:drivesUpdated", handler);
2308
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
2309
+ const scheduleTick = () => {
2310
+ pendingTimeout = setTimeout(() => {
2311
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
2312
+ scheduleTick();
2313
+ return;
2314
+ }
2315
+ cancelPendingDriveSelection();
2316
+ const pathname = resolveUrlPathname("/");
2317
+ if (pathname === window.location.pathname) return;
2318
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2319
+ }, DEFERRED_DRIVE_TICK_MS);
2320
+ };
2321
+ scheduleTick();
2322
+ }
2323
+ function addSetSelectedDriveOnPopStateEventHandler() {
2324
+ window.addEventListener("popstate", () => {
2325
+ const pathname = window.location.pathname;
2326
+ const driveId = extractDriveIdFromPath(pathname);
2327
+ if (driveId !== window.ph?.selectedDriveId) setSelectedDrive(driveId);
2328
+ });
2329
+ }
2330
+ //#endregion
2331
+ //#region src/hooks/use-drop-target.ts
2332
+ function useDropTarget() {
2333
+ const [isDropTarget, setIsDropTarget] = useState(false);
2334
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2335
+ const targetSetter = funnel(() => setIsDropTarget(true), {
2336
+ triggerAt: "start",
2337
+ minQuietPeriodMs: 100
2338
+ });
2339
+ const targetUnsetter = funnel(() => setIsDropTarget(false), {
2340
+ triggerAt: "start",
2341
+ minQuietPeriodMs: 100
2342
+ });
2343
+ function setTarget() {
2344
+ if (!isDragAndDropEnabled) return;
2345
+ targetUnsetter.cancel();
2346
+ targetSetter.call();
2347
+ }
2348
+ function unsetTarget() {
2349
+ if (!isDragAndDropEnabled) return;
2350
+ targetSetter.cancel();
2351
+ targetUnsetter.call();
2352
+ }
2353
+ return {
2354
+ isDropTarget,
2355
+ setTarget,
2356
+ unsetTarget
2357
+ };
2358
+ }
2359
+ //#endregion
2360
+ //#region src/hooks/node-drag-and-drop.ts
2361
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
2362
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
2363
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
2364
+ const addDraggingNodeEventHandler = draggingNodeEventFunctions.addEventHandler;
2365
+ const draggingNodeSetter = funnel((node) => setDraggingNode(node), {
2366
+ reducer: (_, newNode) => newNode,
2367
+ triggerAt: "start",
2368
+ minQuietPeriodMs: 100
2369
+ });
2370
+ const draggingNodeUnsetter = funnel(() => setDraggingNode(void 0), {
2371
+ triggerAt: "start",
2372
+ minQuietPeriodMs: 100
2373
+ });
2374
+ function setDragging(node) {
2375
+ draggingNodeUnsetter.cancel();
2376
+ draggingNodeSetter.call(node);
2377
+ }
2378
+ function unsetDragging() {
2379
+ draggingNodeSetter.cancel();
2380
+ draggingNodeUnsetter.call();
2381
+ }
2382
+ const isNodeDrag = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isTruthy)(driveId), constant(false)], [({ driveId, srcId }) => isStrictEqual(driveId, srcId), constant(false)], constant(true));
2383
+ function useDragNode(args) {
2384
+ const { srcId, parentId } = args;
2385
+ const driveId = useSelectedDriveId();
2386
+ const draggingNodeId = useDraggingNode()?.srcId;
2387
+ const params = {
2388
+ driveId,
2389
+ srcId,
2390
+ parentId
2391
+ };
2392
+ const draggable = isNodeDrag(params);
2393
+ const isDragging = allPass({
2394
+ srcId,
2395
+ draggingNodeId
2396
+ }, [
2397
+ () => draggable,
2398
+ ({ srcId }) => isString(srcId),
2399
+ ({ draggingNodeId }) => isString(draggingNodeId),
2400
+ ({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId)
2401
+ ]);
2402
+ const onDragStart = () => {
2403
+ if (!draggable) return;
2404
+ setDragging(params);
2405
+ };
2406
+ const onDragEnd = () => {
2407
+ if (!draggable) return;
2408
+ unsetDragging();
2409
+ };
2410
+ return {
2411
+ isDragging,
2412
+ draggable,
2413
+ onDragStart,
2414
+ onDragEnd
2415
+ };
2416
+ }
2417
+ const isNodeDrop = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isDefined)(driveId), constant(false)], [({ srcId, targetId }) => isStrictEqual(srcId, targetId), constant(false)], [({ driveId, parentId, targetId }) => isNot(isTruthy)(parentId) && isStrictEqual(targetId, driveId), constant(false)], [({ targetId, parentId }) => isStrictEqual(targetId, parentId), constant(false)], constant(true));
2418
+ function useDropNode(targetId) {
2419
+ const driveId = useSelectedDriveId();
2420
+ const { srcId, parentId } = useDraggingNode() ?? {};
2421
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
2422
+ const params = {
2423
+ driveId,
2424
+ parentId,
2425
+ targetId,
2426
+ srcId
2427
+ };
2428
+ function handleNodeDrop(event, cb) {
2429
+ if (!isNodeDrop(params)) return;
2430
+ event.preventDefault();
2431
+ event.stopPropagation();
2432
+ cb?.();
2433
+ }
2434
+ const onDragEnter = (event) => handleNodeDrop(event);
2435
+ const onDragOver = (event) => handleNodeDrop(event, once(setTarget));
2436
+ const onDragLeave = (event) => handleNodeDrop(event, once(unsetTarget));
2437
+ const onDrop = (event) => handleNodeDrop(event, once(() => {
2438
+ unsetDragging();
2439
+ unsetTarget();
2440
+ moveNodeById(params).catch(console.error);
2441
+ }));
2442
+ return {
2443
+ isDropTarget,
2444
+ onDragEnter,
2445
+ onDragOver,
2446
+ onDragLeave,
2447
+ onDrop
2448
+ };
2449
+ }
2450
+ //#endregion
2451
+ //#region src/hooks/graphql-reactor-client.ts
2452
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
2453
+ const useGraphQLReactorClient = graphQLReactorClientEventFunctions.useValue;
2454
+ const setGraphQLReactorClient = graphQLReactorClientEventFunctions.setValue;
2455
+ const addGraphQLReactorClientEventHandler = graphQLReactorClientEventFunctions.addEventHandler;
2456
+ //#endregion
2457
+ //#region src/hooks/package-discovery.ts
2458
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
2459
+ const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;
2460
+ const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;
2461
+ const addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;
2462
+ //#endregion
2463
+ //#region src/hooks/reactor.ts
2464
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
2465
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
2466
+ /** Returns the reactor client module (in-process or worker-backed) */
2467
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
2468
+ /** Sets the reactor client module */
2469
+ const setReactorClientModule = reactorClientModuleEventFunctions.setValue;
2470
+ /** Adds an event handler for the reactor client module */
2471
+ const addReactorClientModuleEventHandler = reactorClientModuleEventFunctions.addEventHandler;
2472
+ /** Returns the reactor client */
2473
+ const useReactorClient = reactorClientEventFunctions.useValue;
2474
+ /** Sets the reactor client */
2475
+ const setReactorClient = reactorClientEventFunctions.setValue;
2476
+ /** Adds an event handler for the reactor client */
2477
+ const addReactorClientEventHandler = reactorClientEventFunctions.addEventHandler;
2478
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
2479
+ const useSyncList = () => {
2480
+ return useSync()?.list() ?? [];
2481
+ };
2482
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
2483
+ const useDatabase = () => {
2484
+ const module = useReactorClientModule();
2485
+ return module?.kind === "browser" ? module.reactorModule?.database : void 0;
2486
+ };
2487
+ const usePGlite = () => {
2488
+ const module = useReactorClientModule();
2489
+ return module?.kind === "browser" ? module.reactorModule?.pg : void 0;
2490
+ };
2491
+ //#endregion
2492
+ //#region src/hooks/revision-history.ts
2493
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
2494
+ /** Returns whether revision history is visible */
2495
+ const useRevisionHistoryVisible = revisionHistoryEventFunctions.useValue;
2496
+ /** Sets revision history visibility */
2497
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
2498
+ /** Adds event handler for revision history visibility */
2499
+ const addRevisionHistoryVisibleEventHandler = revisionHistoryEventFunctions.addEventHandler;
2500
+ /** Shows the revision history */
2501
+ function showRevisionHistory() {
2502
+ setRevisionHistoryVisible(true);
2503
+ }
2504
+ /** Hides the revision history */
2505
+ function hideRevisionHistory() {
2506
+ setRevisionHistoryVisible(false);
2507
+ }
2508
+ //#endregion
2509
+ //#region src/utils/nodes.ts
2510
+ /** Sorts nodes by name. */
2511
+ function sortNodesByName(nodes) {
2512
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
2513
+ }
2514
+ /** Returns whether a node is a file. */
2515
+ function isFileNodeKind(node) {
2516
+ if (!node) return false;
2517
+ return node.kind.toUpperCase() === "FILE";
2518
+ }
2519
+ /** Returns whether a node is a folder. */
2520
+ function isFolderNodeKind(node) {
2521
+ if (!node) return false;
2522
+ return node.kind.toUpperCase() === "FOLDER";
2523
+ }
2524
+ //#endregion
2525
+ //#region src/hooks/items-in-selected-drive.ts
2526
+ /** Returns the nodes in the selected drive. */
2527
+ function useNodesInSelectedDrive() {
2528
+ const [selectedDrive] = useSelectedDriveSafe();
2529
+ return selectedDrive?.state.global.nodes;
2530
+ }
2531
+ /** Returns the file nodes in the selected drive. */
2532
+ function useFileNodesInSelectedDrive() {
2533
+ return useNodesInSelectedDrive()?.filter((n) => isFileNodeKind(n));
2534
+ }
2535
+ /** Returns the folder nodes in the selected drive. */
2536
+ function useFolderNodesInSelectedDrive() {
2537
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
2538
+ }
2539
+ /** Returns the documents in the selected drive. */
2540
+ function useDocumentsInSelectedDrive() {
2541
+ const fileNodeIds = useFileNodesInSelectedDrive()?.map((node) => node.id);
2542
+ return useDocumentsByIds(fileNodeIds);
2543
+ }
2544
+ /** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */
2545
+ function useDocumentTypesInSelectedDrive() {
2546
+ return (useDocumentsInSelectedDrive()?.filter(isDocumentModelDocument))?.map((doc) => doc.state.global.id);
2547
+ }
2548
+ function isDocumentModelDocument(document) {
2549
+ return document.header.documentType === "powerhouse/document-model";
2550
+ }
2551
+ //#endregion
2552
+ //#region src/hooks/selected-node.ts
2553
+ /** Returns the selected node. */
2554
+ function useSelectedNode() {
2555
+ const selectedNodeId = useSelectedNodeId();
2556
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
2557
+ }
2558
+ //#endregion
2559
+ //#region src/hooks/selected-timeline-item.ts
2560
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
2561
+ /** Returns the selected timeline item */
2562
+ const useSelectedTimelineItem = selectedTimelineItemEventFunctions.useValue;
2563
+ /** Sets the selected timeline item */
2564
+ const setSelectedTimelineItem = selectedTimelineItemEventFunctions.setValue;
2565
+ /** Adds event handler for selected timeline item */
2566
+ const addSelectedTimelineItemEventHandler = selectedTimelineItemEventFunctions.addEventHandler;
2567
+ //#endregion
2568
+ //#region src/hooks/timeline-revision.ts
2569
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
2570
+ /** Returns the selected timeline revision. */
2571
+ const useSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.useValue;
2572
+ /** Sets the selected timeline revision. */
2573
+ const setSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.setValue;
2574
+ /** Adds an event handler for the selected timeline revision. */
2575
+ const addSelectedTimelineRevisionEventHandler = selectedTimelineRevisionEventFunctions.addEventHandler;
2576
+ //#endregion
2577
+ //#region src/hooks/toast.ts
2578
+ const toastEventFunctions = makePHEventFunctions("toast");
2579
+ /** Returns the toast function */
2580
+ const usePHToast = toastEventFunctions.useValue;
2581
+ /** Sets the toast function */
2582
+ const setPHToast = toastEventFunctions.setValue;
2583
+ /** Adds an event handler for the toast */
2584
+ const addToastEventHandler = toastEventFunctions.addEventHandler;
2585
+ //#endregion
2586
+ //#region src/hooks/vetra-packages.ts
2587
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
2588
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
2589
+ /** Returns all of the Vetra packages loaded by the Connect instance */
2590
+ const useVetraPackages = () => {
2591
+ const packageManager = useVetraPackageManager();
2592
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
2593
+ };
2594
+ /** Adds the Vetra package manager event handler */
2595
+ const addVetraPackageManagerEventHandler = vetraPackageManagerFunctions.addEventHandler;
2596
+ /** Sets the Vetra package manager and registers its packages */
2597
+ function setVetraPackageManager(packageManager) {
2598
+ vetraPackageManagerFunctions.setValue(packageManager);
2599
+ updateReactorClientDocumentModels(packageManager.packages);
2600
+ updateReactorClientUpgradeManifests(packageManager.packages);
2601
+ packageManager.subscribe(({ packages }) => {
2602
+ updateReactorClientDocumentModels(packages);
2603
+ updateReactorClientUpgradeManifests(packages);
2604
+ });
2605
+ }
2606
+ function updateReactorClientDocumentModels(packages) {
2607
+ const documentModelModules = packages.flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && (m.version ?? 1) === (module.version ?? 1)) === index);
2608
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2609
+ if (!registry || documentModelModules.length === 0) return;
2610
+ const results = registry.registerModules(...documentModelModules);
2611
+ const duplicateTypes = /* @__PURE__ */ new Set();
2612
+ for (const result of results) if (result.status === "error") if (isDuplicateModuleError(result.error)) duplicateTypes.add(result.item.documentModel.global.id);
2613
+ else console.error("Failed to register document model module:", result.error);
2614
+ if (duplicateTypes.size > 0) {
2615
+ registry.unregisterModules(...duplicateTypes);
2616
+ registry.registerModules(...documentModelModules.filter((module) => duplicateTypes.has(module.documentModel.global.id)));
2617
+ }
2618
+ }
2619
+ function updateReactorClientUpgradeManifests(packages) {
2620
+ const upgradeManifests = packages.flatMap((pkg) => pkg.upgradeManifests).filter((u) => u !== void 0);
2621
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2622
+ if (!registry || upgradeManifests.length === 0) return;
2623
+ const results = registry.registerUpgradeManifests(...upgradeManifests);
2624
+ const duplicates = [];
2625
+ for (const result of results) if (result.status === "error") if (isDuplicateManifestError(result.error)) duplicates.push(result);
2626
+ else console.error("Failed to register upgrade manifest:", result.error);
2627
+ if (duplicates.length > 0) {
2628
+ const duplicateTypes = duplicates.map((r) => r.item.documentType).filter((t) => !!t);
2629
+ registry.unregisterUpgradeManifests(...duplicateTypes);
2630
+ registry.registerUpgradeManifests(...duplicates.map((r) => r.item));
2631
+ }
2632
+ }
2633
+ //#endregion
2634
+ //#region src/hooks/add-ph-event-handlers.ts
2635
+ const commonGlobalEventHandlerFunctions = {
2636
+ loading: addLoadingEventHandler,
2637
+ drives: addDrivesEventHandler,
2638
+ selectedDriveId: () => {
2639
+ addSelectedDriveIdEventHandler();
2640
+ addSetSelectedDriveOnPopStateEventHandler();
2641
+ addResetSelectedNodeEventHandler();
2642
+ },
2643
+ selectedNodeId: () => {
2644
+ addSelectedNodeIdEventHandler();
2645
+ addSetSelectedNodeOnPopStateEventHandler();
2646
+ },
2647
+ documentCache: addDocumentCacheEventHandler,
2648
+ reactorGraphQLClient: addGraphQLReactorClientEventHandler,
2649
+ draggingNode: addDraggingNodeEventHandler
2650
+ };
2651
+ const phGlobalEventHandlerRegisterFunctions = {
2652
+ ...commonGlobalEventHandlerFunctions,
2653
+ reactorClientModule: addReactorClientModuleEventHandler,
2654
+ reactorClient: addReactorClientEventHandler,
2655
+ attachmentService: addAttachmentServiceEventHandler,
2656
+ features: addFeaturesEventHandler,
2657
+ modal: addModalEventHandler,
2658
+ renown: addRenownEventHandler,
2659
+ vetraPackageManager: addVetraPackageManagerEventHandler,
2660
+ packageDiscoveryService: addPackageDiscoveryServiceEventHandler,
2661
+ selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,
2662
+ revisionHistoryVisible: addRevisionHistoryVisibleEventHandler,
2663
+ selectedTimelineItem: addSelectedTimelineItemEventHandler,
2664
+ routerBasename: addRouterBasenameEventHandler,
2665
+ version: addVersionEventHandler,
2666
+ logLevel: addLogLevelEventHandler,
2667
+ requiresHardRefresh: addRequiresHardRefreshEventHandler,
2668
+ warnOutdatedApp: addWarnOutdatedAppEventHandler,
2669
+ studioMode: addStudioModeEventHandler,
2670
+ basePath: addBasePathEventHandler,
2671
+ versionCheckInterval: addVersionCheckIntervalEventHandler,
2672
+ cliVersion: addCliVersionEventHandler,
2673
+ fileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,
2674
+ isDocumentModelSelectionSettingsEnabled: addIsDocumentModelSelectionSettingsEnabledEventHandler,
2675
+ gaTrackingId: addGaTrackingIdEventHandler,
2676
+ allowList: addAllowListEventHandler,
2677
+ defaultDrivesUrl: addDefaultDrivesUrlEventHandler,
2678
+ drivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,
2679
+ allowedDocumentTypes: addAllowedDocumentTypesEventHandler,
2680
+ enabledEditors: addEnabledEditorsEventHandler,
2681
+ disabledEditors: addDisabledEditorsEventHandler,
2682
+ isAddDriveEnabled: addIsAddDriveEnabledEventHandler,
2683
+ isLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,
2684
+ isPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,
2685
+ isAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,
2686
+ isDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,
2687
+ isCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,
2688
+ isAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,
2689
+ isDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,
2690
+ isAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,
2691
+ isDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,
2692
+ isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,
2693
+ isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,
2694
+ isEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,
2695
+ isEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,
2696
+ isRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,
2697
+ isExternalRelationalProcessorsEnabled: addIsExternalRelationalProcessorsEnabledEventHandler,
2698
+ isAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,
2699
+ isAnalyticsExternalProcessorsEnabled: addIsAnalyticsExternalProcessorsEnabledEventHandler,
2700
+ analyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,
2701
+ isAnalyticsDatabaseWorkerEnabled: addIsAnalyticsDatabaseWorkerEnabledEventHandler,
2702
+ isDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,
2703
+ isDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,
2704
+ renownUrl: addRenownUrlEventHandler,
2705
+ renownNetworkId: addRenownNetworkIdEventHandler,
2706
+ renownChainId: addRenownChainIdEventHandler,
2707
+ switchboardUrl: addSwitchboardUrlEventHandler,
2708
+ renownAdapters: addRenownAdaptersEventHandler,
2709
+ sentryRelease: addSentryReleaseEventHandler,
2710
+ sentryDsn: addSentryDsnEventHandler,
2711
+ sentryEnv: addSentryEnvEventHandler,
2712
+ isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,
2713
+ isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,
2714
+ isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,
2715
+ toast: addToastEventHandler
2716
+ };
2717
+ function addPHEventHandlers() {
2718
+ callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);
2719
+ }
2720
+ function callEventHandlerRegisterFunctions(registerFunctions) {
2721
+ forEachObj(registerFunctions, (fn) => fn());
2722
+ }
2723
+ //#endregion
2724
+ //#region src/graphql-client/graphql-reactor-provider.tsx
2725
+ /**
2726
+ * Registers the `window.ph` event handlers once per page.
2727
+ *
2728
+ * The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`
2729
+ * until `addPHEventHandlers` has registered the listeners that do. Registration
2730
+ * is guarded by a marker on `window` rather than a module-level flag so that a
2731
+ * hot module replacement, or two copies of this module, still register once.
2732
+ */
2733
+ function ensurePHEventHandlers() {
2734
+ if (typeof window === "undefined" || window.__phEventHandlersRegistered) return;
2735
+ addPHEventHandlers();
2736
+ window.__phEventHandlersRegistered = true;
2737
+ }
2738
+ /**
2739
+ * Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the
2740
+ * reactor-browser hooks read, so `useDocument`, `useDispatch` and
2741
+ * `useReactorClient` work below it against a Switchboard, with no reactor in
2742
+ * the bundle.
2743
+ *
2744
+ * It fills the document slots, plus `window.ph.vetraPackageManager` when
2745
+ * `documentModels` is given (a fixed {@link StaticPackageManager}, which makes
2746
+ * the document-model hooks work). The same modules go to the client itself, so
2747
+ * a dispatch of two or more actions is signed rather than refused.
2748
+ * `window.ph.reactorClientModule` always stays empty, so full-reactor surfaces
2749
+ * (drives, jobs, editor auto-discovery) find nothing - an app below this
2750
+ * provider renders components it imports itself.
2751
+ *
2752
+ * The client is built on the client only: on the server the slots stay empty
2753
+ * and the hooks report their normal loading states. The props are read once,
2754
+ * when the client is built - changing `url` afterwards does not rebuild it.
2755
+ *
2756
+ * The effect's cleanup disposes the cache and the client's socket, and the
2757
+ * effect rebuilds both if it runs again on the same client - which is what a
2758
+ * `StrictMode` mount does.
2759
+ */
2760
+ function GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, documentModels, children }) {
2761
+ const [client] = useState(() => typeof window === "undefined" ? void 0 : new GraphQLReactorClient({
2762
+ url,
2763
+ tokenProvider,
2764
+ subscriptionsUrl,
2765
+ realtime,
2766
+ documentModels
2767
+ }));
2768
+ useEffect(() => {
2769
+ if (!client) return;
2770
+ ensurePHEventHandlers();
2771
+ setReactorClient(client);
2772
+ const documentCache = new DocumentCache(client);
2773
+ setDocumentCache(documentCache);
2774
+ return () => {
2775
+ documentCache.dispose();
2776
+ client.dispose();
2777
+ };
2778
+ }, [client]);
2779
+ useEffect(() => {
2780
+ if (!attachmentService) return;
2781
+ ensurePHEventHandlers();
2782
+ setAttachmentService(attachmentService);
2783
+ }, [attachmentService]);
2784
+ useEffect(() => {
2785
+ if (!documentModels || documentModels.length === 0) return;
2786
+ ensurePHEventHandlers();
2787
+ setVetraPackageManager(new StaticPackageManager([packageFromDocumentModels(documentModels)]));
2788
+ }, [documentModels]);
2789
+ return /* @__PURE__ */ jsx(Fragment, { children });
2790
+ }
2791
+ /**
2792
+ * Returns the {@link GraphQLReactorClient} mounted by
2793
+ * {@link GraphQLReactorProvider}, or `undefined` when the slot holds something
2794
+ * else - the full in-browser reactor client, or nothing yet.
2795
+ *
2796
+ * `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both
2797
+ * implementations share. This is how a component reaches the light client's own
2798
+ * surface, i.e. `subgraph` and `request`.
2799
+ *
2800
+ * The narrowing is by brand, not by `instanceof`: a page can carry two copies
2801
+ * of this module - a bundled package with its own copy, or a hot-replaced one -
2802
+ * and `instanceof` would then answer `false` for a perfectly good client and
2803
+ * leave the component silently without one.
2804
+ */
2805
+ function useSwitchboardClient() {
2806
+ const client = useReactorClient();
2807
+ return isGraphQLReactorClient(client) ? client : void 0;
2808
+ }
2809
+ //#endregion
2810
+ //#region src/hooks/document-model-modules.ts
2811
+ function useDocumentModelModules() {
2812
+ return useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);
2813
+ }
2814
+ /**
2815
+ * Resolves a document model module by document type, mirroring the registry's
2816
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
2817
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
2818
+ * with `version` given only an exact match is returned. The reactor resolves
2819
+ * modules the same way when a document is created, so metadata read through
2820
+ * this hook and the version a creation actually uses cannot disagree.
2821
+ */
2822
+ function useDocumentModelModuleById(id, version) {
2823
+ const documentModelModules = useDocumentModelModules();
2824
+ if (!id || !documentModelModules) return void 0;
2825
+ let latestModule;
2826
+ let latestVersion = -1;
2827
+ for (const module of documentModelModules) {
2828
+ if (module.documentModel.global.id !== id) continue;
2829
+ const moduleVersion = module.version ?? 1;
2830
+ if (version !== void 0) {
2831
+ if (moduleVersion === version) return module;
2832
+ continue;
2833
+ }
2834
+ if (moduleVersion > latestVersion) {
2835
+ latestVersion = moduleVersion;
2836
+ latestModule = module;
2837
+ }
2838
+ }
2839
+ return latestModule;
2840
+ }
2841
+ //#endregion
2842
+ //#region src/hooks/document-operations.ts
2843
+ /**
2844
+ * Hook to fetch document operations via the reactor client.
2845
+ * Operations are no longer auto-populated on documents and must be fetched explicitly.
2846
+ *
2847
+ * @param documentId - The document ID to fetch operations for
2848
+ * @returns Object containing globalOperations, localOperations, isLoading, and error
2849
+ */
2850
+ function useDocumentOperations(documentId) {
2851
+ const reactorClient = useReactorClient();
2852
+ const hasFetchedRef = useRef(false);
2853
+ const [state, setState] = useState(() => ({
2854
+ globalOperations: [],
2855
+ localOperations: [],
2856
+ isLoading: !!documentId,
2857
+ error: void 0
2858
+ }));
2859
+ const fetchOperations = useCallback(async (retryCount = 0) => {
2860
+ const MAX_RETRIES = 5;
2861
+ const RETRY_DELAY_MS = 500;
2862
+ if (!documentId || !reactorClient) {
2863
+ setState({
2864
+ globalOperations: [],
2865
+ localOperations: [],
2866
+ isLoading: false,
2867
+ error: void 0
2868
+ });
2869
+ return;
2870
+ }
2871
+ setState((prev) => ({
2872
+ ...prev,
2873
+ isLoading: true,
2874
+ error: void 0
2875
+ }));
2876
+ let globalOps = [];
2877
+ let localOps = [];
2878
+ let fetchError;
2879
+ try {
2880
+ globalOps = (await reactorClient.getOperations(documentId, { scopes: ["global"] })).results;
2881
+ } catch (err) {
2882
+ fetchError = err instanceof Error ? err : new Error(String(err));
2883
+ }
2884
+ if (!fetchError) try {
2885
+ localOps = (await reactorClient.getOperations(documentId, { scopes: ["local"] })).results;
2886
+ } catch (err) {
2887
+ fetchError = err instanceof Error ? err : new Error(String(err));
2888
+ }
2889
+ if (!fetchError && globalOps.length === 0 && localOps.length === 0 && retryCount < MAX_RETRIES) {
2890
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
2891
+ return fetchOperations(retryCount + 1);
2892
+ }
2893
+ setState({
2894
+ globalOperations: globalOps,
2895
+ localOperations: localOps,
2896
+ isLoading: false,
2897
+ error: fetchError
2898
+ });
2899
+ hasFetchedRef.current = true;
2900
+ }, [documentId, reactorClient]);
2901
+ useEffect(() => {
2902
+ if (documentId && reactorClient) fetchOperations();
2903
+ else if (!documentId) {
2904
+ setState({
2905
+ globalOperations: [],
2906
+ localOperations: [],
2907
+ isLoading: false,
2908
+ error: void 0
2909
+ });
2910
+ hasFetchedRef.current = false;
2911
+ }
2912
+ }, [
2913
+ documentId,
2914
+ reactorClient,
2915
+ fetchOperations
2916
+ ]);
2917
+ const refetch = useCallback(() => {
2918
+ fetchOperations(0);
2919
+ }, [fetchOperations]);
2920
+ return {
2921
+ ...state,
2922
+ refetch
2923
+ };
2924
+ }
2925
+ //#endregion
2926
+ export { useGraphQLReactorClient as $, ReactorOperationFieldsFragmentDoc as $i, setIsDeletePublicDrivesEnabled as $n, useIsEditorReadModeEnabled as $r, addIsCloudDrivesEnabledEventHandler as $t, isFolderNodeKind as A, showPHModal as Aa, phDocumentEditorConfigSetters as Ai, addWarnOutdatedAppEventHandler as An, useBasePath as Ar, addFeaturesEventHandler as At, setReactorClientModule as B, makeAuthConnectionParams as Bi, setEnabledEditors as Bn, useIsAddLocalDrivesEnabled as Br, addDefaultDrivesUrlEventHandler as Bt, useSelectedNode as C, getUserPermissions as Ca, addAllowedDocumentTypesEventHandler as Ci, addSentryDsnEventHandler as Cn, setStudioMode as Cr, extractNodeIdFromSlug as Ct, useFolderNodesInSelectedDrive as D, setPHModal as Da, phAppConfigHooks as Di, addSwitchboardUrlEventHandler as Dn, setWarnOutdatedApp as Dr, makeDriveUrlComponent as Dt, useFileNodesInSelectedDrive as E, closePHModal as Ea, isExternalControlsEnabledEventFunctions as Ei, addStudioModeEventHandler as En, setVersionCheckInterval as Er, getPathWithoutBase as Et, showRevisionHistory as F, NoSelectedDocumentError as Fa, useIsDragAndDropEnabled as Fi, setBasePath as Fn, useEnabledEditors as Fr, useAttachmentService as Ft, useReactorClientModule as G, subgraphUrlFromGraphqlUrl as Gi, setIsAddLocalDrivesEnabled as Gn, useIsCloudDrivesEnabled as Gr, addGaTrackingIdEventHandler as Gt, useModelRegistry as H, subscriptionsUrlFromGraphqlUrl as Hi, setGaTrackingId as Hn, useIsAnalyticsDatabaseWorkerEnabled as Hr, addDrivesPreserveStrategyEventHandler as Ht, useRevisionHistoryVisible as I, UnsupportedDocumentTypeError as Ia, useIsExternalControlsEnabled as Ii, setCliVersion as In, useFileUploadOperationsChunkSize as Ir, addAllowListEventHandler as It, addPackageDiscoveryServiceEventHandler as J, resolveDocumentModelModule as Ji, setIsAnalyticsEnabled as Jn, useIsDeletePublicDrivesEnabled as Jr, addIsAddLocalDrivesEnabledEventHandler as Jt, useSync as K, StaticPackageManager as Ki, setIsAddPublicDrivesEnabled as Kn, useIsDeleteCloudDrivesEnabled as Kr, addIsAddCloudDrivesEnabledEventHandler as Kt, addReactorClientEventHandler as L, GraphQLReactorClient as Li, setDefaultDrivesUrl as Ln, useGaTrackingId as Lr, addAnalyticsDatabaseNameEventHandler as Lt, addRevisionHistoryVisibleEventHandler as M, DocumentModelNotFoundError as Ma, setIsDragAndDropEnabled as Mi, phGlobalConfigSetters as Mn, useDefaultDrivesUrl as Mr, useFeatures as Mt, hideRevisionHistory as N, DocumentNotFoundError as Na, setIsExternalControlsEnabled as Ni, setAllowList as Nn, useDisabledEditors as Nr, addAttachmentServiceEventHandler as Nt, useNodesInSelectedDrive as O, showCreateDocumentModal as Oa, phAppConfigSetters as Oi, addVersionCheckIntervalEventHandler as On, useAllowList as Or, makeNodeSlug as Ot, setRevisionHistoryVisible as P, DocumentTypeMismatchError as Pa, useAllowedDocumentTypes as Pi, setAnalyticsDatabaseName as Pn, useDrivesPreserveStrategy as Pr, setAttachmentService as Pt, setGraphQLReactorClient as Q, MutateDocumentWithOperationsDocument as Qi, setIsDeleteLocalDrivesEnabled as Qn, useIsEditorDebugModeEnabled as Qr, addIsAnalyticsExternalProcessorsEnabledEventHandler as Qt, addReactorClientModuleEventHandler as R, isGraphQLReactorClient as Ri, setDisabledEditors as Rn, useIsAddCloudDrivesEnabled as Rr, addBasePathEventHandler as Rt, useSelectedTimelineItem as S, upgradeDocument as Sa, useWarnOutdatedApp as Si, addRouterBasenameEventHandler as Sn, setSentryRelease as Sr, extractNodeIdFromPath as St, useDocumentsInSelectedDrive as T, addModalEventHandler as Ta, addIsExternalControlsEnabledEventHandler as Ti, addSentryReleaseEventHandler as Tn, setVersion as Tr, findUuid as Tt, usePGlite as U, SubgraphSdkRegistry as Ui, setIsAddCloudDrivesEnabled as Un, useIsAnalyticsEnabled as Ur, addEnabledEditorsEventHandler as Ut, useDatabase as V, startDocumentChangesSubscription as Vi, setFileUploadOperationsChunkSize as Vn, useIsAddPublicDrivesEnabled as Vr, addDisabledEditorsEventHandler as Vt, useReactorClient as W, describeGraphQLDocument as Wi, setIsAddDriveEnabled as Wn, useIsAnalyticsExternalProcessorsEnabled as Wr, addFileUploadOperationsChunkSizeEventHandler as Wt, usePackageDiscoveryService as X, signStampedAction as Xi, setIsCloudDrivesEnabled as Xn, useIsDocumentModelSelectionSettingsEnabled as Xr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as Xt, setPackageDiscoveryService as Y, prepareSignedActions as Yi, setIsAnalyticsExternalProcessorsEnabled as Yn, useIsDiffAnalyticsEnabled as Yr, addIsAddPublicDrivesEnabledEventHandler as Yt, addGraphQLReactorClientEventHandler as Z, stampAction as Zi, setIsDeleteCloudDrivesEnabled as Zn, useIsDriveAnalyticsEnabled as Zr, addIsAnalyticsEnabledEventHandler as Zt, addSelectedTimelineRevisionEventHandler as _, exportFile as _a, useSentryRelease as _i, addRenownAdaptersEventHandler as _n, setRenownUrl as _r, useDrives as _t, ensurePHEventHandlers as a, ConflictError as aa, useIsRelationalProcessorsEnabled as ai, addIsDriveAnalyticsEnabledEventHandler as an, setIsExternalPackagesEnabled as ar, addSetSelectedDriveOnPopStateEventHandler as at, addSelectedTimelineItemEventHandler as b, renameDriveNode as ba, useVersion as bi, addRenownUrlEventHandler as bn, setSentryDsn as br, extractDriveIdFromSlug as bt, callEventHandlerRegisterFunctions as c, extractRevisionMap as ca, useLogLevel as ci, addIsExternalPackagesEnabledEventHandler as cn, setIsLocalDrivesEnabled as cr, useSelectedDrive as ct, setVetraPackageManager as d, addDocument as da, useRenownNetworkId as di, addIsLocalDrivesEnabledEventHandler as dn, setIsSentryTracingEnabled as dr, addResetSelectedNodeEventHandler as dt, ambientRenownTokenProvider as ea, useIsExternalPackagesEnabled as ei, addIsDeleteCloudDrivesEnabledEventHandler as en, setIsDiffAnalyticsEnabled as er, addDraggingNodeEventHandler as et, useVetraPackageManager as f, addFile as fa, useRenownUrl as fi, addIsPublicDrivesEnabledEventHandler as fn, setLocalDrivesEnabled as fr, addSelectedNodeIdEventHandler as ft, usePHToast as g, deleteNode as ga, useSentryEnv as gi, addLogLevelEventHandler as gn, setRenownNetworkId as gr, setDrives as gt, setPHToast as h, copyNode$1 as ha, useSentryDsn as hi, addLocalDrivesEnabledEventHandler as hn, setRenownChainId as hr, addDrivesEventHandler as ht, GraphQLReactorProvider as i, revisionMapFromRevisionsList as ia, useIsPublicDrivesEnabled as ii, addIsDocumentModelSelectionSettingsEnabledEventHandler as in, setIsEditorReadModeEnabled as ir, addSelectedDriveIdEventHandler as it, sortNodesByName as j, usePHModal as ja, setAllowedDocumentTypes as ji, phGlobalConfigHooks as jn, useCliVersion as jr, setFeatures as jt, isFileNodeKind as k, showDeleteNodeModal as ka, phDocumentEditorConfigHooks as ki, addVersionEventHandler as kn, useAnalyticsDatabaseName as kr, resolveUrlPathname as kt, commonGlobalEventHandlerFunctions as l, hasRevisionConflict as la, useRenownAdapters as li, addIsExternalProcessorsEnabledEventHandler as ln, setIsPublicDrivesEnabled as lr, useSelectedDriveId as lt, addToastEventHandler as m, addFolder$1 as ma, useRouterBasename as mi, addIsSentryTracingEnabledEventHandler as mn, setRenownAdapters as mr, setSelectedNode as mt, useDocumentModelModuleById as n, phDocumentFromGetDocument as na, useIsExternalRelationalProcessorsEnabled as ni, addIsDeletePublicDrivesEnabledEventHandler as nn, setIsDriveAnalyticsEnabled as nr, useDropNode as nt, useSwitchboardClient as o, buildPulledDocument as oa, useIsSentryTracingEnabled as oi, addIsEditorDebugModeEnabledEventHandler as on, setIsExternalProcessorsEnabled as or, setSelectedDrive as ot, useVetraPackages as p, addFileWithProgress as pa, useRequiresHardRefresh as pi, addIsRelationalProcessorsEnabledEventHandler as pn, setLogLevel as pr, addSetSelectedNodeOnPopStateEventHandler as pt, useSyncList as q, packageFromDocumentModels as qi, setIsAnalyticsDatabaseWorkerEnabled as qn, useIsDeleteLocalDrivesEnabled as qr, addIsAddDriveEnabledEventHandler as qt, useDocumentModelModules as r, phDocumentFromMutation as ra, useIsLocalDrivesEnabled as ri, addIsDiffAnalyticsEnabledEventHandler as rn, setIsEditorDebugModeEnabled as rr, useDropTarget as rt, addPHEventHandlers as s, convertRemoteOperations as sa, useLocalDrivesEnabled as si, addIsEditorReadModeEnabledEventHandler as sn, setIsExternalRelationalProcessorsEnabled as sr, setSelectedDriveId as st, useDocumentOperations as t, makeAuthMiddleware as ta, useIsExternalProcessorsEnabled as ti, addIsDeleteLocalDrivesEnabledEventHandler as tn, setIsDocumentModelSelectionSettingsEnabled as tr, useDragNode as tt, addVetraPackageManagerEventHandler as u, screamingSnakeToCamel as ua, useRenownChainId as ui, addIsExternalRelationalProcessorsEnabledEventHandler as un, setIsRelationalProcessorsEnabled as ur, useSelectedDriveSafe as ut, setSelectedTimelineRevision as v, loadFile as va, useStudioMode as vi, addRenownChainIdEventHandler as vn, setRequiresHardRefresh as vr, createUrlWithPreservedParams as vt, useDocumentTypesInSelectedDrive as w, isDocumentTypeSupported as wa, addIsDragAndDropEnabledEventHandler as wi, addSentryEnvEventHandler as wn, setSwitchboardUrl as wr, extractNodeSlugFromPath as wt, setSelectedTimelineItem as x, renameNode as xa, useVersionCheckInterval as xi, addRequiresHardRefreshEventHandler as xn, setSentryEnv as xr, extractDriveSlugFromPath as xt, useSelectedTimelineRevision as y, moveNode$1 as ya, useSwitchboardUrl as yi, addRenownNetworkIdEventHandler as yn, setRouterBasename as yr, extractDriveIdFromPath as yt, setReactorClient as z, viewFilterInputFromViewFilter as zi, setDrivesPreserveStrategy as zn, useIsAddDriveEnabled as zr, addCliVersionEventHandler as zt };
2927
+
2928
+ //# sourceMappingURL=document-operations-C6nce9dH.js.map