@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.10 → 6.2.3-dev.12

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 (114) hide show
  1. package/dist/browser/assets/{entry-DvpdFGdw.js → entry-4ObkElbc.js} +2 -2
  2. package/dist/browser/assets/{projection-entry-QU4xTPM_.js → projection-entry-DRGRQCSu.js} +8 -8
  3. package/dist/browser/{button-CuO8Gh3v.js → button-sZQCXeCo.js} +131 -24
  4. package/dist/browser/button-sZQCXeCo.js.map +1 -0
  5. package/dist/browser/chunk-BVTlhY3a.js +24 -0
  6. package/dist/browser/{dist-BAJ5nRDl.js → dist-D3_ER0Dn.js} +2 -399
  7. package/dist/browser/dist-D3_ER0Dn.js.map +1 -0
  8. package/dist/browser/document-models/index.js +2 -1
  9. package/dist/browser/{documents-J_l59mSV.js → documents-C-lAnv6o.js} +604 -735
  10. package/dist/browser/documents-C-lAnv6o.js.map +1 -0
  11. package/dist/browser/editor-CQ4wUFK5.js +3679 -0
  12. package/dist/browser/editor-CQ4wUFK5.js.map +1 -0
  13. package/dist/browser/{editor-D_gIraSB.js → editor-DNV-46lY.js} +5 -5
  14. package/dist/browser/{editor-D_gIraSB.js.map → editor-DNV-46lY.js.map} +1 -1
  15. package/dist/browser/editors/document-model-editor/module.js +1 -1
  16. package/dist/browser/editors/generic-drive-explorer/index.js +13 -8
  17. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  18. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  19. package/dist/browser/folder-view-CzItU0hn.js +957 -0
  20. package/dist/browser/folder-view-CzItU0hn.js.map +1 -0
  21. package/dist/browser/{graphql-editor-C9wxFf0b.js → graphql-editor-DoXZvdNr.js} +7 -9
  22. package/dist/browser/{graphql-editor-C9wxFf0b.js.map → graphql-editor-DoXZvdNr.js.map} +1 -1
  23. package/dist/{node/hooks-D0DcS3MV.mjs → browser/hooks-Bh1JCohS.js} +2 -2
  24. package/dist/browser/{hooks-KKcNp2X0.js.map → hooks-Bh1JCohS.js.map} +1 -1
  25. package/dist/browser/index.js +120 -20
  26. package/dist/browser/index.js.map +1 -1
  27. package/dist/browser/{json-editor-BIGVi54h.js → json-editor-DBhkG5TF.js} +3 -4
  28. package/dist/browser/{json-editor-BIGVi54h.js.map → json-editor-DBhkG5TF.js.map} +1 -1
  29. package/dist/browser/{parser-CkF6Qt8V.js → parser-BBzK7bLd.js} +1 -1
  30. package/dist/browser/{parser-CkF6Qt8V.js.map → parser-BBzK7bLd.js.map} +1 -1
  31. package/dist/browser/{schema-context-ZyeclQwy.js → schema-context-p2bhyog_.js} +3 -3
  32. package/dist/browser/{schema-context-ZyeclQwy.js.map → schema-context-p2bhyog_.js.map} +1 -1
  33. package/dist/browser/src-CVV6HzQZ-D-OQvEkh.js +5151 -0
  34. package/dist/browser/src-CVV6HzQZ-D-OQvEkh.js.map +1 -0
  35. package/dist/browser/state-schemas-B47wHvDV.js +694 -0
  36. package/dist/browser/state-schemas-B47wHvDV.js.map +1 -0
  37. package/dist/browser/tslib.es6-CeIASJ2O.js +32 -0
  38. package/dist/browser/tslib.es6-CeIASJ2O.js.map +1 -0
  39. package/dist/node/{button-Da7CxMn7.mjs → button-5bnYEAVq.mjs} +130 -23
  40. package/dist/node/button-5bnYEAVq.mjs.map +1 -0
  41. package/dist/node/chunk-17FXJ3dL.mjs +31 -0
  42. package/dist/node/{dist-CzYOpeXN.mjs → dist-Bf_PIbO7.mjs} +2 -399
  43. package/dist/node/dist-Bf_PIbO7.mjs.map +1 -0
  44. package/dist/node/document-models/index.mjs +2 -1
  45. package/dist/node/documents-XAQfHX5Q.mjs +17 -0
  46. package/dist/node/documents-XAQfHX5Q.mjs.map +1 -0
  47. package/dist/node/editor-BiiLqEe9.mjs +3679 -0
  48. package/dist/node/editor-BiiLqEe9.mjs.map +1 -0
  49. package/dist/node/{editor-CJSAZpIG.mjs → editor-Cp2TC5MJ.mjs} +5 -5
  50. package/dist/node/{editor-CJSAZpIG.mjs.map → editor-Cp2TC5MJ.mjs.map} +1 -1
  51. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  52. package/dist/node/editors/generic-drive-explorer/index.mjs +4 -5
  53. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  54. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  55. package/dist/node/folder-view-m_rH84Nz.mjs +962 -0
  56. package/dist/node/folder-view-m_rH84Nz.mjs.map +1 -0
  57. package/dist/node/{graphql-BfAoPeWM.mjs → graphql-BvV3tC1U.mjs} +2 -2
  58. package/dist/node/{graphql-BfAoPeWM.mjs.map → graphql-BvV3tC1U.mjs.map} +1 -1
  59. package/dist/node/{graphql-editor-CnK5kIk9.mjs → graphql-editor-BhF6KN6y.mjs} +6 -7
  60. package/dist/node/{graphql-editor-CnK5kIk9.mjs.map → graphql-editor-BhF6KN6y.mjs.map} +1 -1
  61. package/dist/{browser/hooks-KKcNp2X0.js → node/hooks-Di3FASx-.mjs} +2 -2
  62. package/dist/node/{hooks-D0DcS3MV.mjs.map → hooks-Di3FASx-.mjs.map} +1 -1
  63. package/dist/node/index.mjs +142 -21
  64. package/dist/node/index.mjs.map +1 -1
  65. package/dist/node/{json-editor-j8_JGfcP.mjs → json-editor-Cqc0zuz0.mjs} +3 -4
  66. package/dist/node/{json-editor-j8_JGfcP.mjs.map → json-editor-Cqc0zuz0.mjs.map} +1 -1
  67. package/dist/node/{schema-context-DL8jhi_d.mjs → schema-context-mHmP3Cl6.mjs} +3 -3
  68. package/dist/node/{schema-context-DL8jhi_d.mjs.map → schema-context-mHmP3Cl6.mjs.map} +1 -1
  69. package/dist/node/{connect-D3-HufsW.mjs → src-CVV6HzQZ-CvqjXbXk.mjs} +1829 -11022
  70. package/dist/node/src-CVV6HzQZ-CvqjXbXk.mjs.map +1 -0
  71. package/dist/node/state-schemas-DXG02fMh.mjs +695 -0
  72. package/dist/node/state-schemas-DXG02fMh.mjs.map +1 -0
  73. package/dist/node/{main-7sul-YJl.mjs → tslib.es6-DdiHgz9e.mjs} +3 -203
  74. package/dist/node/tslib.es6-DdiHgz9e.mjs.map +1 -0
  75. package/package.json +7 -7
  76. package/dist/browser/button-CuO8Gh3v.js.map +0 -1
  77. package/dist/browser/connect-kwnl2v6o.js +0 -14328
  78. package/dist/browser/connect-kwnl2v6o.js.map +0 -1
  79. package/dist/browser/dist-B4FWbuEM.js +0 -4148
  80. package/dist/browser/dist-B4FWbuEM.js.map +0 -1
  81. package/dist/browser/dist-BAJ5nRDl.js.map +0 -1
  82. package/dist/browser/dist-D0tSbK8B.js +0 -4721
  83. package/dist/browser/dist-D0tSbK8B.js.map +0 -1
  84. package/dist/browser/document-drive-fcQ4o8i3.js +0 -8320
  85. package/dist/browser/document-drive-fcQ4o8i3.js.map +0 -1
  86. package/dist/browser/documents-J_l59mSV.js.map +0 -1
  87. package/dist/browser/editor-CbJkIqg_.js +0 -1809
  88. package/dist/browser/editor-CbJkIqg_.js.map +0 -1
  89. package/dist/browser/folder-view-CGcqEbak.js +0 -232
  90. package/dist/browser/folder-view-CGcqEbak.js.map +0 -1
  91. package/dist/browser/lib-BWPfFpyy.js +0 -209
  92. package/dist/browser/lib-BWPfFpyy.js.map +0 -1
  93. package/dist/browser/printer-CEYr4JOg.js +0 -604
  94. package/dist/browser/printer-CEYr4JOg.js.map +0 -1
  95. package/dist/browser/state-schemas-C9Nb7S5z.js +0 -298
  96. package/dist/browser/state-schemas-C9Nb7S5z.js.map +0 -1
  97. package/dist/node/button-Da7CxMn7.mjs.map +0 -1
  98. package/dist/node/connect-D3-HufsW.mjs.map +0 -1
  99. package/dist/node/dist-CzYOpeXN.mjs.map +0 -1
  100. package/dist/node/dist-D5Xp9PwJ.mjs +0 -4729
  101. package/dist/node/dist-D5Xp9PwJ.mjs.map +0 -1
  102. package/dist/node/dist-DT7jI9ol.mjs +0 -4148
  103. package/dist/node/dist-DT7jI9ol.mjs.map +0 -1
  104. package/dist/node/document-drive-DuGBBYw5.mjs +0 -8337
  105. package/dist/node/document-drive-DuGBBYw5.mjs.map +0 -1
  106. package/dist/node/documents-DCf53bzO.mjs +0 -747
  107. package/dist/node/documents-DCf53bzO.mjs.map +0 -1
  108. package/dist/node/editor-D8SL0ydm.mjs +0 -1809
  109. package/dist/node/editor-D8SL0ydm.mjs.map +0 -1
  110. package/dist/node/folder-view-ChtWc33j.mjs +0 -232
  111. package/dist/node/folder-view-ChtWc33j.mjs.map +0 -1
  112. package/dist/node/main-7sul-YJl.mjs.map +0 -1
  113. package/dist/node/state-schemas-DURvYjxG.mjs +0 -299
  114. package/dist/node/state-schemas-DURvYjxG.mjs.map +0 -1
@@ -1,4729 +0,0 @@
1
- import { D as __commonJSMin, M as __toESM, r as pascalCase, t as capitalCase } from "./dist-DT7jI9ol.mjs";
2
- import { A as createPresignedHeader, D as buildSignedAction, E as baseSaveToFileHandle, G as replayDocumentVersioned, N as createZip, T as baseLoadFromInputVersioned, _ as UnsupportedDocumentModelVersionError, a as getDescendants, c as isFileNode, ct as validateInitialState, d as moveNode, dt as zipEntries, et as setName, f as updateNode, ft as generateId, i as generateNodesCopy, l as isFolderNode, lt as validateModules, m as logger, n as copyNode, o as getNextCopyNumber, s as handleTargetNameCollisions, t as addFolder, ut as validateStateSchemaName, w as baseLoadFromInput, x as assertAuthPreservedOnDuplicate } from "./document-drive-DuGBBYw5.mjs";
3
- import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-7sul-YJl.mjs";
4
- import { t as require_graphql } from "./graphql-BfAoPeWM.mjs";
5
- import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
6
- import "react/jsx-runtime";
7
- //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
8
- const isServer$1 = typeof window === "undefined";
9
- function makePHEventFunctions(key) {
10
- const setEventName = `ph:set${capitalCase(key)}`;
11
- const updateEventName = `ph:${key}Updated`;
12
- function setValue(value) {
13
- if (isServer$1) return;
14
- const event = new CustomEvent(setEventName, { detail: { [key]: value } });
15
- window.dispatchEvent(event);
16
- }
17
- function dispatchUpdatedEvent() {
18
- if (isServer$1) return;
19
- const event = new CustomEvent(updateEventName);
20
- window.dispatchEvent(event);
21
- }
22
- function handleSetValueEvent(event) {
23
- if (isServer$1) return;
24
- const value = event.detail[key];
25
- if (!window.ph) window.ph = {};
26
- window.ph[key] = value;
27
- dispatchUpdatedEvent();
28
- }
29
- function addEventHandler() {
30
- if (isServer$1) return;
31
- window.addEventListener(setEventName, handleSetValueEvent);
32
- }
33
- function subscribeToValue(onStoreChange) {
34
- if (isServer$1) return () => {};
35
- window.addEventListener(updateEventName, onStoreChange);
36
- return () => {
37
- window.removeEventListener(updateEventName, onStoreChange);
38
- };
39
- }
40
- function getSnapshot() {
41
- if (isServer$1) return;
42
- return window.ph?.[key];
43
- }
44
- function getServerSnapshot() {}
45
- function useValue() {
46
- return useSyncExternalStore(subscribeToValue, getSnapshot, getServerSnapshot);
47
- }
48
- return {
49
- useValue,
50
- setValue,
51
- addEventHandler
52
- };
53
- }
54
- //#endregion
55
- //#region ../reactor-browser/dist/document-by-id-B4FIzG1w.js
56
- async function queueActions(document, actionOrActions) {
57
- if (!document) throw new Error("No document provided");
58
- if (!actionOrActions) throw new Error("No actions provided");
59
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
60
- if (actions.length === 0) throw new Error("No actions provided");
61
- const reactorClient = window.ph?.reactorClient;
62
- if (!reactorClient) throw new Error("ReactorClient not initialized");
63
- return await reactorClient.execute(document.header.id, "main", actions);
64
- }
65
- async function queueOperations(documentId, operationOrOperations) {
66
- if (!documentId) throw new Error("No documentId provided");
67
- if (!operationOrOperations) throw new Error("No operations provided");
68
- const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
69
- if (operations.length === 0) throw new Error("No operations provided");
70
- const reactorClient = window.ph?.reactorClient;
71
- if (!reactorClient) throw new Error("ReactorClient not initialized");
72
- const actions = operations.map((op) => op.action);
73
- return await reactorClient.execute(documentId, "main", actions);
74
- }
75
- async function uploadOperations(documentId, allOperations, pushOperations, options) {
76
- const operationsLimit = options?.operationsLimit || 50;
77
- const onProgress = options?.onProgress;
78
- logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
79
- const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
80
- const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
81
- let uploadedOperations = 0;
82
- for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
83
- logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
84
- const chunk = operations.slice(i, i + operationsLimit);
85
- const operation = chunk.at(-1);
86
- if (!operation) break;
87
- const scope = operation.action.scope;
88
- await pushOperations(documentId, chunk);
89
- uploadedOperations += chunk.length;
90
- if (onProgress) onProgress({
91
- stage: "uploading",
92
- progress: Math.round(uploadedOperations / totalOperations * 100),
93
- totalOperations,
94
- uploadedOperations
95
- });
96
- logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
97
- }
98
- logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
99
- }
100
- async function signAction(action, document) {
101
- const renown = window.ph?.renown;
102
- if (!renown?.user) return action;
103
- if (!action.context?.signer) return action;
104
- const reactorClient = window.ph?.reactorClientModule?.client;
105
- if (!reactorClient) return action;
106
- const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
107
- const actionSigner = action.context.signer;
108
- return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
109
- }
110
- function addActionContext(action) {
111
- const renown = window.ph?.renown;
112
- if (!renown?.user) return action;
113
- return {
114
- context: { signer: {
115
- app: {
116
- name: "Connect",
117
- key: renown.did
118
- },
119
- user: {
120
- address: renown.user.address,
121
- networkId: renown.user.networkId,
122
- chainId: renown.user.chainId
123
- },
124
- signatures: []
125
- } },
126
- ...action
127
- };
128
- }
129
- async function makeSignedActionWithContext(action, document) {
130
- if (!action) {
131
- logger.error("No action found");
132
- return;
133
- }
134
- if (!document) {
135
- logger.error("No document found");
136
- return;
137
- }
138
- return addActionContext(await signAction(action, document));
139
- }
140
- async function makeSignedActionsWithContext(actionOrActions, document) {
141
- if (!actionOrActions) {
142
- logger.error("No actions found");
143
- return;
144
- }
145
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
146
- return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
147
- }
148
- async function getDocument(documentId) {
149
- try {
150
- return await window.ph?.reactorClient?.get(documentId);
151
- } catch (error) {
152
- logger.debug(`Failed to get document with id ${documentId}:`, error);
153
- return;
154
- }
155
- }
156
- function getActionErrors(result, actions) {
157
- return actions.reduce((errors, a) => {
158
- const scopeOperations = result.operations[a.scope];
159
- if (!scopeOperations) return errors;
160
- const op = scopeOperations.findLast((op) => op.action.id === a.id);
161
- if (op?.error) errors.push(new Error(op.error));
162
- return errors;
163
- }, new Array());
164
- }
165
- async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
166
- const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
167
- if (!document) {
168
- logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
169
- return;
170
- }
171
- const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
172
- if (!signedActionsWithContext) {
173
- logger.error("No signed actions with context found");
174
- return;
175
- }
176
- const result = await queueActions(document, signedActionsWithContext);
177
- if (onErrors && result) {
178
- const errors = getActionErrors(result, signedActionsWithContext);
179
- if (errors.length) onErrors(errors);
180
- }
181
- if (onSuccess && result) onSuccess(result);
182
- return result;
183
- }
184
- /**
185
- * The reactor's `DocumentChangeType` members, typed as the enum so they can be
186
- * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
187
- * TypeScript string enum is nominal, so no string literal is assignable to it
188
- * without one - and the two checks above are what make it safe.
189
- */
190
- const DOCUMENT_CHANGE_TYPE = {
191
- Created: "created",
192
- Deleted: "deleted",
193
- Updated: "updated",
194
- ParentAdded: "parent_added",
195
- ParentRemoved: "parent_removed",
196
- ChildAdded: "child_added",
197
- ChildRemoved: "child_removed"
198
- };
199
- const documentEventFunctions = makePHEventFunctions("documentCache");
200
- /** Returns all documents in the reactor. */
201
- const useDocumentCache = documentEventFunctions.useValue;
202
- documentEventFunctions.setValue;
203
- documentEventFunctions.addEventHandler;
204
- /**
205
- * Retrieves a document from the reactor and subscribes to changes using React Suspense.
206
- * This hook will suspend rendering while the document is loading.
207
- * @param id - The document ID to retrieve, or null/undefined to skip retrieval
208
- * @returns The document if found, or undefined if id is null/undefined
209
- */
210
- function useDocument(id) {
211
- const documentCache = useDocumentCache();
212
- const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
213
- return document ? use(document) : void 0;
214
- }
215
- /**
216
- * Returns a function to retrieve a document from the cache.
217
- * The returned function fetches and returns a document by ID.
218
- * @returns A function that takes a document ID and returns a Promise of the document
219
- */
220
- function useGetDocument() {
221
- const documentCache = useDocumentCache();
222
- return useCallback((id) => {
223
- if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
224
- return documentCache.get(id);
225
- }, [documentCache]);
226
- }
227
- function useDispatch(document) {
228
- /**
229
- * Dispatches actions to the document.
230
- * @param actionOrActions - The action or actions to dispatch.
231
- * @param onErrors - Callback invoked with any errors that occurred during action execution.
232
- */
233
- function dispatch(actionOrActions, onErrors, onSuccess) {
234
- dispatchActions(actionOrActions, document, onErrors, onSuccess).catch((error) => {
235
- logger.error("Failed to dispatch actions: @error", error);
236
- });
237
- }
238
- return [document, dispatch];
239
- }
240
- /** Returns a document by id. */
241
- function useDocumentById(id) {
242
- const document = useDocument(id);
243
- const [, dispatch] = useDispatch(document);
244
- return [document, dispatch];
245
- }
246
- //#endregion
247
- //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
248
- let base64;
249
- if (typeof window !== "undefined") if (window.btoa) base64 = function(input) {
250
- return btoa(unescape(encodeURIComponent(input)));
251
- };
252
- else base64 = function(input) {
253
- const str = unescape(encodeURIComponent(input + ""));
254
- let output = "";
255
- for (let block, charCode, idx = 0, map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; str.charAt(idx | 0) || (map = "=", idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
256
- charCode = str.charCodeAt(idx += 3 / 4);
257
- /* c8 ignore next 3 */
258
- if (charCode > 255) throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
259
- block = block << 8 | charCode;
260
- }
261
- return output;
262
- };
263
- else base64 = function(input) {
264
- return Buffer.from(input).toString("base64");
265
- };
266
- function slug(string, opts) {
267
- let result = slugify(string, opts);
268
- if ((opts && opts.fallback !== void 0 ? opts.fallback : slug.defaults.fallback) === true && result === "") result = slugify(base64(string), opts);
269
- return result;
270
- }
271
- const locales = {
272
- bg: {
273
- Й: "Y",
274
- й: "y",
275
- X: "H",
276
- x: "h",
277
- Ц: "Ts",
278
- ц: "ts",
279
- Щ: "Sht",
280
- щ: "sht",
281
- Ъ: "A",
282
- ъ: "a",
283
- Ь: "Y",
284
- ь: "y"
285
- },
286
- de: {
287
- Ä: "AE",
288
- ä: "ae",
289
- Ö: "OE",
290
- ö: "oe",
291
- Ü: "UE",
292
- ü: "ue"
293
- },
294
- sr: {
295
- đ: "dj",
296
- Đ: "DJ"
297
- },
298
- uk: {
299
- И: "Y",
300
- и: "y",
301
- Й: "Y",
302
- й: "y",
303
- Ц: "Ts",
304
- ц: "ts",
305
- Х: "Kh",
306
- х: "kh",
307
- Щ: "Shch",
308
- щ: "shch",
309
- Г: "H",
310
- г: "h"
311
- }
312
- };
313
- let defaultLocale = {};
314
- function slugify(string, opts) {
315
- if (typeof string !== "string") throw new Error("slug() requires a string argument, received " + typeof string);
316
- if (!string.isWellFormed()) throw new Error("slug() received a malformed string with lone surrogates");
317
- if (typeof opts === "string") opts = { replacement: opts };
318
- opts = opts ? Object.assign({}, opts) : {};
319
- opts.mode = opts.mode || slug.defaults.mode;
320
- const defaults = slug.defaults.modes[opts.mode];
321
- const keys = [
322
- "replacement",
323
- "multicharmap",
324
- "charmap",
325
- "remove",
326
- "lower",
327
- "trim"
328
- ];
329
- for (let key, i = 0, l = keys.length; i < l; i++) {
330
- key = keys[i];
331
- opts[key] = key in opts ? opts[key] : defaults[key];
332
- }
333
- const localeMap = locales[opts.locale] || defaultLocale;
334
- let lengths = [];
335
- for (const key in opts.multicharmap) {
336
- if (!Object.prototype.hasOwnProperty.call(opts.multicharmap, key)) continue;
337
- const len = key.length;
338
- if (lengths.indexOf(len) === -1) lengths.push(len);
339
- }
340
- lengths = lengths.sort(function(a, b) {
341
- return b - a;
342
- });
343
- const disallowedChars = opts.mode === "rfc3986" ? /[^\w\s\-.~]/ : /[^A-Za-z0-9\s]/;
344
- let result = "";
345
- for (let char, i = 0, l = string.length; i < l; i++) {
346
- char = string[i];
347
- let matchedMultichar = false;
348
- for (let j = 0; j < lengths.length; j++) {
349
- const len = lengths[j];
350
- const str = string.substr(i, len);
351
- if (opts.multicharmap[str]) {
352
- i += len - 1;
353
- char = opts.multicharmap[str];
354
- matchedMultichar = true;
355
- break;
356
- }
357
- }
358
- if (!matchedMultichar) if (localeMap[char]) char = localeMap[char];
359
- else if (opts.charmap[char]) char = opts.charmap[char].replace(opts.replacement, " ");
360
- else if (char.includes(opts.replacement)) char = char.replace(opts.replacement, " ");
361
- else char = char.replace(disallowedChars, "");
362
- result += char;
363
- }
364
- if (opts.remove) result = result.replace(opts.remove, "");
365
- if (opts.trim) result = result.trim();
366
- result = result.replace(/\s+/g, opts.replacement);
367
- if (opts.lower) result = result.toLowerCase();
368
- return result;
369
- }
370
- const initialMulticharmap = {
371
- फ़: "Fi",
372
- ग़: "Ghi",
373
- ख़: "Khi",
374
- क़: "Qi",
375
- ड़: "ugDha",
376
- ढ़: "ugDhha",
377
- य़: "Yi",
378
- ज़: "Za",
379
- בִי: "i",
380
- בֵ: "e",
381
- בֵי: "e",
382
- בֶ: "e",
383
- בַ: "a",
384
- בָ: "a",
385
- בֹ: "o",
386
- וֹ: "o",
387
- בֻ: "u",
388
- וּ: "u",
389
- בּ: "b",
390
- כּ: "k",
391
- ךּ: "k",
392
- פּ: "p",
393
- שׁ: "sh",
394
- שׂ: "s",
395
- בְ: "e",
396
- חֱ: "e",
397
- חֲ: "a",
398
- חֳ: "o",
399
- בִ: "i"
400
- };
401
- const initialCharmap = {
402
- À: "A",
403
- Á: "A",
404
- Â: "A",
405
- Ã: "A",
406
- Ä: "A",
407
- Å: "A",
408
- Æ: "AE",
409
- Ç: "C",
410
- È: "E",
411
- É: "E",
412
- Ê: "E",
413
- Ë: "E",
414
- Ì: "I",
415
- Í: "I",
416
- Î: "I",
417
- Ï: "I",
418
- Ð: "D",
419
- Ñ: "N",
420
- Ò: "O",
421
- Ó: "O",
422
- Ô: "O",
423
- Õ: "O",
424
- Ö: "O",
425
- Ő: "O",
426
- Ø: "O",
427
- Ō: "O",
428
- Ù: "U",
429
- Ú: "U",
430
- Û: "U",
431
- Ü: "U",
432
- Ű: "U",
433
- Ý: "Y",
434
- Þ: "TH",
435
- ß: "ss",
436
- à: "a",
437
- á: "a",
438
- â: "a",
439
- ã: "a",
440
- ä: "a",
441
- å: "a",
442
- æ: "ae",
443
- ç: "c",
444
- è: "e",
445
- é: "e",
446
- ê: "e",
447
- ë: "e",
448
- ì: "i",
449
- í: "i",
450
- î: "i",
451
- ï: "i",
452
- ð: "d",
453
- ñ: "n",
454
- ò: "o",
455
- ó: "o",
456
- ô: "o",
457
- õ: "o",
458
- ö: "o",
459
- ő: "o",
460
- ø: "o",
461
- ō: "o",
462
- Œ: "OE",
463
- œ: "oe",
464
- ù: "u",
465
- ú: "u",
466
- û: "u",
467
- ü: "u",
468
- ű: "u",
469
- ý: "y",
470
- þ: "th",
471
- ÿ: "y",
472
- ẞ: "SS",
473
- α: "a",
474
- β: "b",
475
- γ: "g",
476
- δ: "d",
477
- ε: "e",
478
- ζ: "z",
479
- η: "h",
480
- θ: "th",
481
- ι: "i",
482
- κ: "k",
483
- λ: "l",
484
- μ: "m",
485
- ν: "n",
486
- ξ: "3",
487
- ο: "o",
488
- π: "p",
489
- ρ: "r",
490
- σ: "s",
491
- τ: "t",
492
- υ: "y",
493
- φ: "f",
494
- χ: "x",
495
- ψ: "ps",
496
- ω: "w",
497
- ά: "a",
498
- έ: "e",
499
- ί: "i",
500
- ό: "o",
501
- ύ: "y",
502
- ή: "h",
503
- ώ: "w",
504
- ς: "s",
505
- ϊ: "i",
506
- ΰ: "y",
507
- ϋ: "y",
508
- ΐ: "i",
509
- Α: "A",
510
- Β: "B",
511
- Γ: "G",
512
- Δ: "D",
513
- Ε: "E",
514
- Ζ: "Z",
515
- Η: "H",
516
- Θ: "Th",
517
- Ι: "I",
518
- Κ: "K",
519
- Λ: "L",
520
- Μ: "M",
521
- Ν: "N",
522
- Ξ: "3",
523
- Ο: "O",
524
- Π: "P",
525
- Ρ: "R",
526
- Σ: "S",
527
- Τ: "T",
528
- Υ: "Y",
529
- Φ: "F",
530
- Χ: "X",
531
- Ψ: "PS",
532
- Ω: "W",
533
- Ά: "A",
534
- Έ: "E",
535
- Ί: "I",
536
- Ό: "O",
537
- Ύ: "Y",
538
- Ή: "H",
539
- Ώ: "W",
540
- Ϊ: "I",
541
- Ϋ: "Y",
542
- ş: "s",
543
- Ş: "S",
544
- ı: "i",
545
- İ: "I",
546
- ğ: "g",
547
- Ğ: "G",
548
- а: "a",
549
- б: "b",
550
- в: "v",
551
- г: "g",
552
- д: "d",
553
- е: "e",
554
- ё: "yo",
555
- ж: "zh",
556
- з: "z",
557
- и: "i",
558
- й: "j",
559
- к: "k",
560
- л: "l",
561
- м: "m",
562
- н: "n",
563
- о: "o",
564
- п: "p",
565
- р: "r",
566
- с: "s",
567
- т: "t",
568
- у: "u",
569
- ф: "f",
570
- х: "h",
571
- ц: "c",
572
- ч: "ch",
573
- ш: "sh",
574
- щ: "sh",
575
- ъ: "u",
576
- ы: "y",
577
- ь: "",
578
- э: "e",
579
- ю: "yu",
580
- я: "ya",
581
- А: "A",
582
- Б: "B",
583
- В: "V",
584
- Г: "G",
585
- Д: "D",
586
- Е: "E",
587
- Ё: "Yo",
588
- Ж: "Zh",
589
- З: "Z",
590
- И: "I",
591
- Й: "J",
592
- К: "K",
593
- Л: "L",
594
- М: "M",
595
- Н: "N",
596
- О: "O",
597
- П: "P",
598
- Р: "R",
599
- С: "S",
600
- Т: "T",
601
- У: "U",
602
- Ф: "F",
603
- Х: "H",
604
- Ц: "C",
605
- Ч: "Ch",
606
- Ш: "Sh",
607
- Щ: "Sh",
608
- Ъ: "U",
609
- Ы: "Y",
610
- Ь: "",
611
- Э: "E",
612
- Ю: "Yu",
613
- Я: "Ya",
614
- Є: "Ye",
615
- І: "I",
616
- Ї: "Yi",
617
- Ґ: "G",
618
- є: "ye",
619
- і: "i",
620
- ї: "yi",
621
- ґ: "g",
622
- č: "c",
623
- ď: "d",
624
- ě: "e",
625
- ň: "n",
626
- ř: "r",
627
- š: "s",
628
- ť: "t",
629
- ů: "u",
630
- ž: "z",
631
- Č: "C",
632
- Ď: "D",
633
- Ě: "E",
634
- Ň: "N",
635
- Ř: "R",
636
- Š: "S",
637
- Ť: "T",
638
- Ů: "U",
639
- Ž: "Z",
640
- ľ: "l",
641
- ĺ: "l",
642
- ŕ: "r",
643
- Ľ: "L",
644
- Ĺ: "L",
645
- Ŕ: "R",
646
- ą: "a",
647
- ć: "c",
648
- ę: "e",
649
- ł: "l",
650
- ń: "n",
651
- ś: "s",
652
- ź: "z",
653
- ż: "z",
654
- Ą: "A",
655
- Ć: "C",
656
- Ę: "E",
657
- Ł: "L",
658
- Ń: "N",
659
- Ś: "S",
660
- Ź: "Z",
661
- Ż: "Z",
662
- ā: "a",
663
- ē: "e",
664
- ģ: "g",
665
- ī: "i",
666
- ķ: "k",
667
- ļ: "l",
668
- ņ: "n",
669
- ū: "u",
670
- Ā: "A",
671
- Ē: "E",
672
- Ģ: "G",
673
- Ī: "I",
674
- Ķ: "K",
675
- Ļ: "L",
676
- Ņ: "N",
677
- Ū: "U",
678
- أ: "a",
679
- إ: "i",
680
- ب: "b",
681
- ت: "t",
682
- ث: "th",
683
- ج: "g",
684
- ح: "h",
685
- خ: "kh",
686
- د: "d",
687
- ذ: "th",
688
- ر: "r",
689
- ز: "z",
690
- س: "s",
691
- ش: "sh",
692
- ص: "s",
693
- ض: "d",
694
- ط: "t",
695
- ظ: "th",
696
- ع: "aa",
697
- غ: "gh",
698
- ف: "f",
699
- ق: "k",
700
- ك: "k",
701
- ل: "l",
702
- م: "m",
703
- ن: "n",
704
- ه: "h",
705
- و: "o",
706
- ي: "y",
707
- ء: "aa",
708
- ة: "a",
709
- آ: "a",
710
- ا: "a",
711
- پ: "p",
712
- ژ: "zh",
713
- گ: "g",
714
- چ: "ch",
715
- ک: "k",
716
- ی: "i",
717
- ė: "e",
718
- į: "i",
719
- ų: "u",
720
- Ė: "E",
721
- Į: "I",
722
- Ų: "U",
723
- ț: "t",
724
- Ț: "T",
725
- ţ: "t",
726
- Ţ: "T",
727
- ș: "s",
728
- Ș: "S",
729
- ă: "a",
730
- Ă: "A",
731
- Ạ: "A",
732
- Ả: "A",
733
- Ầ: "A",
734
- Ấ: "A",
735
- Ậ: "A",
736
- Ẩ: "A",
737
- Ẫ: "A",
738
- Ằ: "A",
739
- Ắ: "A",
740
- Ặ: "A",
741
- Ẳ: "A",
742
- Ẵ: "A",
743
- Ẹ: "E",
744
- Ẻ: "E",
745
- Ẽ: "E",
746
- Ề: "E",
747
- Ế: "E",
748
- Ệ: "E",
749
- Ể: "E",
750
- Ễ: "E",
751
- Ị: "I",
752
- Ỉ: "I",
753
- Ĩ: "I",
754
- Ọ: "O",
755
- Ỏ: "O",
756
- Ồ: "O",
757
- Ố: "O",
758
- Ộ: "O",
759
- Ổ: "O",
760
- Ỗ: "O",
761
- Ơ: "O",
762
- Ờ: "O",
763
- Ớ: "O",
764
- Ợ: "O",
765
- Ở: "O",
766
- Ỡ: "O",
767
- Ụ: "U",
768
- Ủ: "U",
769
- Ũ: "U",
770
- Ư: "U",
771
- Ừ: "U",
772
- Ứ: "U",
773
- Ự: "U",
774
- Ử: "U",
775
- Ữ: "U",
776
- Ỳ: "Y",
777
- Ỵ: "Y",
778
- Ỷ: "Y",
779
- Ỹ: "Y",
780
- Đ: "D",
781
- ạ: "a",
782
- ả: "a",
783
- ầ: "a",
784
- ấ: "a",
785
- ậ: "a",
786
- ẩ: "a",
787
- ẫ: "a",
788
- ằ: "a",
789
- ắ: "a",
790
- ặ: "a",
791
- ẳ: "a",
792
- ẵ: "a",
793
- ẹ: "e",
794
- ẻ: "e",
795
- ẽ: "e",
796
- ề: "e",
797
- ế: "e",
798
- ệ: "e",
799
- ể: "e",
800
- ễ: "e",
801
- ị: "i",
802
- ỉ: "i",
803
- ĩ: "i",
804
- ọ: "o",
805
- ỏ: "o",
806
- ồ: "o",
807
- ố: "o",
808
- ộ: "o",
809
- ổ: "o",
810
- ỗ: "o",
811
- ơ: "o",
812
- ờ: "o",
813
- ớ: "o",
814
- ợ: "o",
815
- ở: "o",
816
- ỡ: "o",
817
- ụ: "u",
818
- ủ: "u",
819
- ũ: "u",
820
- ư: "u",
821
- ừ: "u",
822
- ứ: "u",
823
- ự: "u",
824
- ử: "u",
825
- ữ: "u",
826
- ỳ: "y",
827
- ỵ: "y",
828
- ỷ: "y",
829
- ỹ: "y",
830
- đ: "d",
831
- Ә: "AE",
832
- ә: "ae",
833
- Ғ: "GH",
834
- ғ: "gh",
835
- Қ: "KH",
836
- қ: "kh",
837
- Ң: "NG",
838
- ң: "ng",
839
- Ү: "UE",
840
- ү: "ue",
841
- Ұ: "U",
842
- ұ: "u",
843
- Һ: "H",
844
- һ: "h",
845
- Ө: "OE",
846
- ө: "oe",
847
- ђ: "dj",
848
- ј: "j",
849
- љ: "lj",
850
- њ: "nj",
851
- ћ: "c",
852
- џ: "dz",
853
- Ђ: "Dj",
854
- Ј: "j",
855
- Љ: "Lj",
856
- Њ: "Nj",
857
- Ћ: "C",
858
- Џ: "Dz",
859
- nj: "nj",
860
- lj: "lj",
861
- Nj: "NJ",
862
- Lj: "LJ",
863
- अ: "a",
864
- आ: "aa",
865
- ए: "e",
866
- ई: "ii",
867
- ऍ: "ei",
868
- ऎ: "ae",
869
- ऐ: "ai",
870
- इ: "i",
871
- ओ: "o",
872
- ऑ: "oi",
873
- ऒ: "oii",
874
- ऊ: "uu",
875
- औ: "ou",
876
- उ: "u",
877
- ब: "B",
878
- भ: "Bha",
879
- च: "Ca",
880
- छ: "Chha",
881
- ड: "Da",
882
- ढ: "Dha",
883
- फ: "Fa",
884
- ग: "Ga",
885
- घ: "Gha",
886
- ग़: "Ghi",
887
- ह: "Ha",
888
- ज: "Ja",
889
- झ: "Jha",
890
- क: "Ka",
891
- ख: "Kha",
892
- ख़: "Khi",
893
- ल: "L",
894
- ळ: "Li",
895
- ऌ: "Li",
896
- ऴ: "Lii",
897
- ॡ: "Lii",
898
- म: "Ma",
899
- न: "Na",
900
- ङ: "Na",
901
- ञ: "Nia",
902
- ण: "Nae",
903
- ऩ: "Ni",
904
- ॐ: "oms",
905
- प: "Pa",
906
- क़: "Qi",
907
- र: "Ra",
908
- ऋ: "Ri",
909
- ॠ: "Ri",
910
- ऱ: "Ri",
911
- स: "Sa",
912
- श: "Sha",
913
- ष: "Shha",
914
- ट: "Ta",
915
- त: "Ta",
916
- ठ: "Tha",
917
- द: "Tha",
918
- थ: "Tha",
919
- ध: "Thha",
920
- ड़: "ugDha",
921
- ढ़: "ugDhha",
922
- व: "Va",
923
- य: "Ya",
924
- य़: "Yi",
925
- ज़: "Za",
926
- ə: "e",
927
- Ə: "E",
928
- ა: "a",
929
- ბ: "b",
930
- გ: "g",
931
- დ: "d",
932
- ე: "e",
933
- ვ: "v",
934
- ზ: "z",
935
- თ: "t",
936
- ი: "i",
937
- კ: "k",
938
- ლ: "l",
939
- მ: "m",
940
- ნ: "n",
941
- ო: "o",
942
- პ: "p",
943
- ჟ: "zh",
944
- რ: "r",
945
- ს: "s",
946
- ტ: "t",
947
- უ: "u",
948
- ფ: "p",
949
- ქ: "k",
950
- ღ: "gh",
951
- ყ: "q",
952
- შ: "sh",
953
- ჩ: "ch",
954
- ც: "ts",
955
- ძ: "dz",
956
- წ: "ts",
957
- ჭ: "ch",
958
- ხ: "kh",
959
- ჯ: "j",
960
- ჰ: "h",
961
- ב: "v",
962
- גּ: "g",
963
- ג: "g",
964
- ד: "d",
965
- דּ: "d",
966
- ה: "h",
967
- ו: "v",
968
- ז: "z",
969
- ח: "h",
970
- ט: "t",
971
- י: "y",
972
- כ: "kh",
973
- ך: "kh",
974
- ל: "l",
975
- מ: "m",
976
- ם: "m",
977
- נ: "n",
978
- ן: "n",
979
- ס: "s",
980
- פ: "f",
981
- ף: "f",
982
- ץ: "ts",
983
- צ: "ts",
984
- ק: "k",
985
- ר: "r",
986
- תּ: "t",
987
- ת: "t"
988
- };
989
- slug.charmap = Object.assign({}, initialCharmap);
990
- slug.multicharmap = Object.assign({}, initialMulticharmap);
991
- slug.defaults = {
992
- charmap: slug.charmap,
993
- mode: "pretty",
994
- modes: {
995
- rfc3986: {
996
- replacement: "-",
997
- remove: null,
998
- lower: true,
999
- charmap: slug.charmap,
1000
- multicharmap: slug.multicharmap,
1001
- trim: true
1002
- },
1003
- pretty: {
1004
- replacement: "-",
1005
- remove: null,
1006
- lower: true,
1007
- charmap: slug.charmap,
1008
- multicharmap: slug.multicharmap,
1009
- trim: true
1010
- }
1011
- },
1012
- multicharmap: slug.multicharmap,
1013
- fallback: true
1014
- };
1015
- slug.reset = function() {
1016
- slug.defaults.modes.rfc3986.charmap = slug.defaults.modes.pretty.charmap = slug.charmap = slug.defaults.charmap = Object.assign({}, initialCharmap);
1017
- slug.defaults.modes.rfc3986.multicharmap = slug.defaults.modes.pretty.multicharmap = slug.multicharmap = slug.defaults.multicharmap = Object.assign({}, initialMulticharmap);
1018
- defaultLocale = "";
1019
- };
1020
- slug.extend = function(customMap) {
1021
- const keys = Object.keys(customMap);
1022
- const multi = {};
1023
- const single = {};
1024
- for (let i = 0; i < keys.length; i++) if (keys[i].length > 1) multi[keys[i]] = customMap[keys[i]];
1025
- else single[keys[i]] = customMap[keys[i]];
1026
- Object.assign(slug.charmap, single);
1027
- Object.assign(slug.multicharmap, multi);
1028
- };
1029
- slug.setLocale = function(locale) {
1030
- defaultLocale = locales[locale] || {};
1031
- };
1032
- var UnsupportedDocumentTypeError = class extends Error {
1033
- constructor(documentType) {
1034
- super(`Document type ${documentType} is not supported`);
1035
- this.name = "UnsupportedDocumentTypeError";
1036
- }
1037
- static isError(error) {
1038
- return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
1039
- }
1040
- };
1041
- var DocumentModelNotFoundError = class extends Error {
1042
- documentType;
1043
- name = "DocumentModelNotFoundError";
1044
- constructor(documentType) {
1045
- super(`Document model module for type ${documentType} not found`);
1046
- this.documentType = documentType;
1047
- }
1048
- static isError(error) {
1049
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1050
- }
1051
- };
1052
- var DocumentTypeMismatchError = class extends Error {
1053
- constructor(documentId, expectedType, actualType) {
1054
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1055
- }
1056
- };
1057
- var NoSelectedDocumentError = class extends Error {
1058
- constructor() {
1059
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1060
- }
1061
- };
1062
- function resolveUrlPathname(path) {
1063
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
1064
- }
1065
- /** Returns the current path without the base path */
1066
- function getPathWithoutBase(path) {
1067
- const basePath = window.ph?.basePath ?? "/";
1068
- return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
1069
- }
1070
- /** Makes a URL component for a node. */
1071
- function makeNodeSlug(node) {
1072
- if (!node) return "";
1073
- const nodeName = node.name;
1074
- if (!nodeName) return slug(node.id);
1075
- return slug(`${nodeName}-${node.id}`);
1076
- }
1077
- /** Extracts the node slug from a path.
1078
- *
1079
- * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
1080
- */
1081
- function extractNodeSlugFromPath(path) {
1082
- const currentPath = getPathWithoutBase(path);
1083
- return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
1084
- }
1085
- /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
1086
- function findUuid(input) {
1087
- if (!input) return void 0;
1088
- 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];
1089
- }
1090
- function extractNodeIdFromSlug(nodeSlug) {
1091
- return findUuid(nodeSlug);
1092
- }
1093
- /** Extracts the drive slug from a path.
1094
- * Used for extracting drive ids from drive slugs in the URL.
1095
- * Expects the path to be in the format `/d/<drive-slug>`.
1096
- */
1097
- function extractDriveSlugFromPath(path) {
1098
- const currentPath = getPathWithoutBase(path);
1099
- return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
1100
- }
1101
- /**
1102
- * Creates a URL string with the given pathname while preserving existing query parameters.
1103
- */
1104
- function createUrlWithPreservedParams(pathname) {
1105
- const search = window.location.search;
1106
- return search ? `${pathname}${search}` : pathname;
1107
- }
1108
- const drivesEventFunctions = makePHEventFunctions("drives");
1109
- /** Returns all of the drives in the reactor */
1110
- const useDrives = drivesEventFunctions.useValue;
1111
- /** Sets the drives in the reactor */
1112
- const setDrives = drivesEventFunctions.setValue;
1113
- drivesEventFunctions.addEventHandler;
1114
- const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
1115
- const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
1116
- const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
1117
- selectedNodeIdEventFunctions.addEventHandler;
1118
- /** Sets the selected node (file or folder). */
1119
- function setSelectedNode(nodeOrNodeSlug) {
1120
- const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
1121
- setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
1122
- const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
1123
- if (!driveSlugFromPath) return;
1124
- if (!nodeSlug) {
1125
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
1126
- if (pathname === window.location.pathname) return;
1127
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1128
- return;
1129
- }
1130
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
1131
- if (pathname === window.location.pathname) return;
1132
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1133
- }
1134
- const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
1135
- /** Returns the selected drive id */
1136
- const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
1137
- /** Sets the selected drive id */
1138
- const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
1139
- selectedDriveIdEventFunctions.addEventHandler;
1140
- /** Returns the selected drive, or undefined if no drive is selected */
1141
- function useSelectedDriveSafe() {
1142
- const selectedDriveId = useSelectedDriveId();
1143
- const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
1144
- const [drive, dispatch] = useDispatch(selectedDrive);
1145
- if (!selectedDrive) return [void 0, void 0];
1146
- return [drive, dispatch];
1147
- }
1148
- function setSelectedDrive(driveOrDriveSlug) {
1149
- const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
1150
- const drives = window.ph?.drives;
1151
- const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
1152
- if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
1153
- if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
1154
- deferDriveSelection(driveSlug);
1155
- return;
1156
- }
1157
- cancelPendingDriveSelection();
1158
- setSelectedDriveId(driveId);
1159
- if (!driveId) {
1160
- const pathname = resolveUrlPathname("/");
1161
- if (pathname === window.location.pathname) return;
1162
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1163
- return;
1164
- }
1165
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
1166
- if (pathname === window.location.pathname) return;
1167
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1168
- }
1169
- const DEFERRED_DRIVE_TICK_MS = 2e3;
1170
- const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
1171
- function isInitialSyncInFlight() {
1172
- const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
1173
- if (!remotes?.length) return false;
1174
- return remotes.some((remote) => {
1175
- try {
1176
- const snapshot = remote.channel.getConnectionState();
1177
- return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
1178
- } catch {
1179
- return false;
1180
- }
1181
- });
1182
- }
1183
- let pendingHandler;
1184
- let pendingTimeout;
1185
- function cancelPendingDriveSelection() {
1186
- if (pendingHandler) {
1187
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
1188
- pendingHandler = void 0;
1189
- }
1190
- if (pendingTimeout) {
1191
- clearTimeout(pendingTimeout);
1192
- pendingTimeout = void 0;
1193
- }
1194
- }
1195
- function deferDriveSelection(driveSlug) {
1196
- cancelPendingDriveSelection();
1197
- const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
1198
- const handler = () => {
1199
- if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
1200
- cancelPendingDriveSelection();
1201
- setSelectedDrive(driveSlug);
1202
- setSelectedNode(nodeSlug);
1203
- };
1204
- pendingHandler = handler;
1205
- window.addEventListener("ph:drivesUpdated", handler);
1206
- const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
1207
- const scheduleTick = () => {
1208
- pendingTimeout = setTimeout(() => {
1209
- if (Date.now() < deadline && isInitialSyncInFlight()) {
1210
- scheduleTick();
1211
- return;
1212
- }
1213
- cancelPendingDriveSelection();
1214
- const pathname = resolveUrlPathname("/");
1215
- if (pathname === window.location.pathname) return;
1216
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1217
- }, DEFERRED_DRIVE_TICK_MS);
1218
- };
1219
- scheduleTick();
1220
- }
1221
- /** Sorts nodes by name. */
1222
- function sortNodesByName(nodes) {
1223
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
1224
- }
1225
- /** Returns whether a node is a file. */
1226
- function isFileNodeKind(node) {
1227
- if (!node) return false;
1228
- return node.kind.toUpperCase() === "FILE";
1229
- }
1230
- /** Returns whether a node is a folder. */
1231
- function isFolderNodeKind(node) {
1232
- if (!node) return false;
1233
- return node.kind.toUpperCase() === "FOLDER";
1234
- }
1235
- /** Returns the nodes in the selected drive. */
1236
- function useNodesInSelectedDrive() {
1237
- const [selectedDrive] = useSelectedDriveSafe();
1238
- return selectedDrive?.state.global.nodes;
1239
- }
1240
- /** Returns the folder nodes in the selected drive. */
1241
- function useFolderNodesInSelectedDrive() {
1242
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
1243
- }
1244
- /** Returns the selected node. */
1245
- function useSelectedNode() {
1246
- const selectedNodeId = useSelectedNodeId();
1247
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
1248
- }
1249
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
1250
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
1251
- const EMPTY_VETRA_PACKAGES = [];
1252
- const noPackageManagerUnsubscribe = () => {};
1253
- /**
1254
- * Returns all of the Vetra packages loaded by the Connect instance.
1255
- *
1256
- * The snapshot and subscription must keep stable identity while no package
1257
- * manager is registered: `useSyncExternalStore` loops when the snapshot
1258
- * changes on every read, which a fresh `[]` does.
1259
- */
1260
- const useVetraPackages = () => {
1261
- const packageManager = useVetraPackageManager();
1262
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : noPackageManagerUnsubscribe, () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES);
1263
- };
1264
- vetraPackageManagerFunctions.addEventHandler;
1265
- function useDocumentModelModules() {
1266
- 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);
1267
- }
1268
- /**
1269
- * Resolves a document model module by document type, mirroring the registry's
1270
- * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
1271
- * LATEST version of the type wins (`version ?? 1` as each module's default),
1272
- * with `version` given only an exact match is returned. The reactor resolves
1273
- * modules the same way when a document is created, so metadata read through
1274
- * this hook and the version a creation actually uses cannot disagree.
1275
- */
1276
- function useDocumentModelModuleById(id, version) {
1277
- const documentModelModules = useDocumentModelModules();
1278
- if (!id || !documentModelModules) return void 0;
1279
- let latestModule;
1280
- let latestVersion = -1;
1281
- for (const module of documentModelModules) {
1282
- if (module.documentModel.global.id !== id) continue;
1283
- const moduleVersion = module.version ?? 1;
1284
- if (version !== void 0) {
1285
- if (moduleVersion === version) return module;
1286
- continue;
1287
- }
1288
- if (moduleVersion > latestVersion) {
1289
- latestVersion = moduleVersion;
1290
- latestModule = module;
1291
- }
1292
- }
1293
- return latestModule;
1294
- }
1295
- Error;
1296
- //#endregion
1297
- //#region ../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/lib/graphql.js
1298
- var import_graphql = require_graphql();
1299
- JSON;
1300
- //#endregion
1301
- //#region ../reactor-browser/dist/client-D4bkR4pH.js
1302
- var import_main = require_main();
1303
- let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
1304
- DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
1305
- DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
1306
- DocumentChangeType["Created"] = "CREATED";
1307
- DocumentChangeType["Deleted"] = "DELETED";
1308
- DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
1309
- DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
1310
- DocumentChangeType["Updated"] = "UPDATED";
1311
- return DocumentChangeType;
1312
- }({});
1313
- let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
1314
- PropagationMode["Cascade"] = "CASCADE";
1315
- PropagationMode["Orphan"] = "ORPHAN";
1316
- return PropagationMode;
1317
- }({});
1318
- const PhDocumentFieldsFragmentDoc = import_main.gql`
1319
- fragment PHDocumentFields on PHDocument {
1320
- id
1321
- slug
1322
- name
1323
- documentType
1324
- state
1325
- revisionsList {
1326
- scope
1327
- revision
1328
- }
1329
- createdAtUtcIso
1330
- lastModifiedAtUtcIso
1331
- }
1332
- `;
1333
- const DocumentRelationshipFieldsFragmentDoc = import_main.gql`
1334
- fragment DocumentRelationshipFields on DocumentRelationship {
1335
- sourceId
1336
- targetId
1337
- relationshipType
1338
- metadata
1339
- createdAt
1340
- updatedAt
1341
- }
1342
- `;
1343
- import_main.gql`
1344
- query GetDocumentModels($namespace: String, $paging: PagingInput) {
1345
- documentModels(namespace: $namespace, paging: $paging) {
1346
- items {
1347
- id
1348
- name
1349
- namespace
1350
- version
1351
- specification
1352
- }
1353
- totalCount
1354
- hasNextPage
1355
- hasPreviousPage
1356
- cursor
1357
- }
1358
- }
1359
- `;
1360
- const GetDocumentDocument = import_main.gql`
1361
- query GetDocument($identifier: String!, $view: ViewFilterInput) {
1362
- document(identifier: $identifier, view: $view) {
1363
- document {
1364
- ...PHDocumentFields
1365
- }
1366
- childIds
1367
- }
1368
- }
1369
- ${PhDocumentFieldsFragmentDoc}
1370
- `;
1371
- const GetDocumentWithOperationsDocument = import_main.gql`
1372
- query GetDocumentWithOperations(
1373
- $identifier: String!
1374
- $view: ViewFilterInput
1375
- $operationsFilter: DocumentOperationsFilterInput
1376
- $operationsPaging: PagingInput
1377
- ) {
1378
- document(identifier: $identifier, view: $view) {
1379
- document {
1380
- ...PHDocumentFields
1381
- operations(filter: $operationsFilter, paging: $operationsPaging) {
1382
- items {
1383
- index
1384
- timestampUtcMs
1385
- hash
1386
- skip
1387
- error
1388
- deniedReason
1389
- id
1390
- action {
1391
- id
1392
- type
1393
- timestampUtcMs
1394
- input
1395
- scope
1396
- context {
1397
- signer {
1398
- user {
1399
- address
1400
- networkId
1401
- chainId
1402
- }
1403
- app {
1404
- name
1405
- key
1406
- }
1407
- signatures
1408
- }
1409
- }
1410
- }
1411
- }
1412
- totalCount
1413
- hasNextPage
1414
- hasPreviousPage
1415
- cursor
1416
- }
1417
- }
1418
- childIds
1419
- }
1420
- }
1421
- ${PhDocumentFieldsFragmentDoc}
1422
- `;
1423
- import_main.gql`
1424
- query GetDocumentOutgoingRelationships(
1425
- $sourceIdentifier: String!
1426
- $relationshipType: String!
1427
- $view: ViewFilterInput
1428
- $paging: PagingInput
1429
- ) {
1430
- documentOutgoingRelationships(
1431
- sourceIdentifier: $sourceIdentifier
1432
- relationshipType: $relationshipType
1433
- view: $view
1434
- paging: $paging
1435
- ) {
1436
- items {
1437
- ...PHDocumentFields
1438
- }
1439
- totalCount
1440
- hasNextPage
1441
- hasPreviousPage
1442
- cursor
1443
- }
1444
- }
1445
- ${PhDocumentFieldsFragmentDoc}
1446
- `;
1447
- import_main.gql`
1448
- query GetDocumentIncomingRelationships(
1449
- $targetIdentifier: String!
1450
- $relationshipType: String!
1451
- $view: ViewFilterInput
1452
- $paging: PagingInput
1453
- ) {
1454
- documentIncomingRelationships(
1455
- targetIdentifier: $targetIdentifier
1456
- relationshipType: $relationshipType
1457
- view: $view
1458
- paging: $paging
1459
- ) {
1460
- items {
1461
- ...PHDocumentFields
1462
- }
1463
- totalCount
1464
- hasNextPage
1465
- hasPreviousPage
1466
- cursor
1467
- }
1468
- }
1469
- ${PhDocumentFieldsFragmentDoc}
1470
- `;
1471
- import_main.gql`
1472
- query GetDocumentOutgoingRelationshipEdges(
1473
- $sourceIdentifier: String!
1474
- $relationshipType: String
1475
- $view: ViewFilterInput
1476
- $paging: PagingInput
1477
- ) {
1478
- documentOutgoingRelationshipEdges(
1479
- sourceIdentifier: $sourceIdentifier
1480
- relationshipType: $relationshipType
1481
- view: $view
1482
- paging: $paging
1483
- ) {
1484
- items {
1485
- ...DocumentRelationshipFields
1486
- }
1487
- totalCount
1488
- hasNextPage
1489
- hasPreviousPage
1490
- cursor
1491
- }
1492
- }
1493
- ${DocumentRelationshipFieldsFragmentDoc}
1494
- `;
1495
- import_main.gql`
1496
- query GetDocumentIncomingRelationshipEdges(
1497
- $targetIdentifier: String!
1498
- $relationshipType: String
1499
- $view: ViewFilterInput
1500
- $paging: PagingInput
1501
- ) {
1502
- documentIncomingRelationshipEdges(
1503
- targetIdentifier: $targetIdentifier
1504
- relationshipType: $relationshipType
1505
- view: $view
1506
- paging: $paging
1507
- ) {
1508
- items {
1509
- ...DocumentRelationshipFields
1510
- }
1511
- totalCount
1512
- hasNextPage
1513
- hasPreviousPage
1514
- cursor
1515
- }
1516
- }
1517
- ${DocumentRelationshipFieldsFragmentDoc}
1518
- `;
1519
- import_main.gql`
1520
- query FindDocuments(
1521
- $search: SearchFilterInput
1522
- $view: ViewFilterInput
1523
- $paging: PagingInput
1524
- ) {
1525
- findDocuments(search: $search, view: $view, paging: $paging) {
1526
- items {
1527
- ...PHDocumentFields
1528
- }
1529
- totalCount
1530
- hasNextPage
1531
- hasPreviousPage
1532
- cursor
1533
- }
1534
- }
1535
- ${PhDocumentFieldsFragmentDoc}
1536
- `;
1537
- const GetDocumentOperationsDocument = import_main.gql`
1538
- query GetDocumentOperations(
1539
- $filter: OperationsFilterInput!
1540
- $paging: PagingInput
1541
- ) {
1542
- documentOperations(filter: $filter, paging: $paging) {
1543
- items {
1544
- index
1545
- timestampUtcMs
1546
- hash
1547
- skip
1548
- error
1549
- deniedReason
1550
- id
1551
- action {
1552
- id
1553
- type
1554
- timestampUtcMs
1555
- input
1556
- scope
1557
- context {
1558
- signer {
1559
- user {
1560
- address
1561
- networkId
1562
- chainId
1563
- }
1564
- app {
1565
- name
1566
- key
1567
- }
1568
- signatures
1569
- }
1570
- }
1571
- }
1572
- }
1573
- totalCount
1574
- hasNextPage
1575
- hasPreviousPage
1576
- cursor
1577
- }
1578
- }
1579
- `;
1580
- import_main.gql`
1581
- query GetJobStatus($jobId: String!) {
1582
- jobStatus(jobId: $jobId) {
1583
- id
1584
- status
1585
- result
1586
- error
1587
- createdAt
1588
- completedAt
1589
- }
1590
- }
1591
- `;
1592
- import_main.gql`
1593
- query EvaluateActions(
1594
- $documentIdentifier: String!
1595
- $branch: String
1596
- $candidates: [ActionCandidateInput!]!
1597
- ) {
1598
- evaluateActions(
1599
- documentIdentifier: $documentIdentifier
1600
- branch: $branch
1601
- candidates: $candidates
1602
- ) {
1603
- evaluations {
1604
- decision
1605
- reason
1606
- }
1607
- allAllowed
1608
- anyAllowed
1609
- allDenied
1610
- anyDenied
1611
- }
1612
- }
1613
- `;
1614
- import_main.gql`
1615
- mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
1616
- createDocument(document: $document, parentIdentifier: $parentIdentifier) {
1617
- ...PHDocumentFields
1618
- }
1619
- }
1620
- ${PhDocumentFieldsFragmentDoc}
1621
- `;
1622
- import_main.gql`
1623
- mutation CreateEmptyDocument(
1624
- $documentType: String!
1625
- $parentIdentifier: String
1626
- ) {
1627
- createEmptyDocument(
1628
- documentType: $documentType
1629
- parentIdentifier: $parentIdentifier
1630
- ) {
1631
- ...PHDocumentFields
1632
- }
1633
- }
1634
- ${PhDocumentFieldsFragmentDoc}
1635
- `;
1636
- import_main.gql`
1637
- mutation MutateDocument(
1638
- $documentIdentifier: String!
1639
- $actions: [ActionInput!]!
1640
- $branch: String
1641
- ) {
1642
- mutateDocument: execute(
1643
- documentIdentifier: $documentIdentifier
1644
- actions: $actions
1645
- branch: $branch
1646
- ) {
1647
- ...PHDocumentFields
1648
- }
1649
- }
1650
- ${PhDocumentFieldsFragmentDoc}
1651
- `;
1652
- import_main.gql`
1653
- mutation MutateDocumentAsync(
1654
- $documentIdentifier: String!
1655
- $actions: [ActionInput!]!
1656
- $branch: String
1657
- ) {
1658
- mutateDocumentAsync: executeAsync(
1659
- documentIdentifier: $documentIdentifier
1660
- actions: $actions
1661
- branch: $branch
1662
- ) {
1663
- id
1664
- status
1665
- result
1666
- error
1667
- createdAt
1668
- completedAt
1669
- }
1670
- }
1671
- `;
1672
- import_main.gql`
1673
- mutation RenameDocument(
1674
- $documentIdentifier: String!
1675
- $name: String!
1676
- $branch: String
1677
- ) {
1678
- renameDocument(
1679
- documentIdentifier: $documentIdentifier
1680
- name: $name
1681
- branch: $branch
1682
- ) {
1683
- ...PHDocumentFields
1684
- }
1685
- }
1686
- ${PhDocumentFieldsFragmentDoc}
1687
- `;
1688
- import_main.gql`
1689
- mutation SetPreferredEditor(
1690
- $documentIdentifier: String!
1691
- $preferredEditor: String
1692
- $branch: String
1693
- ) {
1694
- setPreferredEditor(
1695
- documentIdentifier: $documentIdentifier
1696
- preferredEditor: $preferredEditor
1697
- branch: $branch
1698
- ) {
1699
- ...PHDocumentFields
1700
- }
1701
- }
1702
- ${PhDocumentFieldsFragmentDoc}
1703
- `;
1704
- import_main.gql`
1705
- mutation AddRelationship(
1706
- $sourceIdentifier: String!
1707
- $targetIdentifier: String!
1708
- $relationshipType: String!
1709
- $metadata: JSONObject
1710
- $branch: String
1711
- ) {
1712
- addRelationship(
1713
- sourceIdentifier: $sourceIdentifier
1714
- targetIdentifier: $targetIdentifier
1715
- relationshipType: $relationshipType
1716
- metadata: $metadata
1717
- branch: $branch
1718
- ) {
1719
- ...PHDocumentFields
1720
- }
1721
- }
1722
- ${PhDocumentFieldsFragmentDoc}
1723
- `;
1724
- import_main.gql`
1725
- mutation UpdateRelationship(
1726
- $sourceIdentifier: String!
1727
- $targetIdentifier: String!
1728
- $relationshipType: String!
1729
- $metadata: JSONObject
1730
- $branch: String
1731
- ) {
1732
- updateRelationship(
1733
- sourceIdentifier: $sourceIdentifier
1734
- targetIdentifier: $targetIdentifier
1735
- relationshipType: $relationshipType
1736
- metadata: $metadata
1737
- branch: $branch
1738
- ) {
1739
- ...PHDocumentFields
1740
- }
1741
- }
1742
- ${PhDocumentFieldsFragmentDoc}
1743
- `;
1744
- import_main.gql`
1745
- mutation RemoveRelationship(
1746
- $sourceIdentifier: String!
1747
- $targetIdentifier: String!
1748
- $relationshipType: String!
1749
- $branch: String
1750
- ) {
1751
- removeRelationship(
1752
- sourceIdentifier: $sourceIdentifier
1753
- targetIdentifier: $targetIdentifier
1754
- relationshipType: $relationshipType
1755
- branch: $branch
1756
- ) {
1757
- ...PHDocumentFields
1758
- }
1759
- }
1760
- ${PhDocumentFieldsFragmentDoc}
1761
- `;
1762
- import_main.gql`
1763
- mutation MoveRelationship(
1764
- $sourceParentIdentifier: String!
1765
- $targetParentIdentifier: String!
1766
- $targetIdentifier: String!
1767
- $relationshipType: String!
1768
- $branch: String
1769
- ) {
1770
- moveRelationship(
1771
- sourceParentIdentifier: $sourceParentIdentifier
1772
- targetParentIdentifier: $targetParentIdentifier
1773
- targetIdentifier: $targetIdentifier
1774
- relationshipType: $relationshipType
1775
- branch: $branch
1776
- ) {
1777
- source {
1778
- ...PHDocumentFields
1779
- }
1780
- target {
1781
- ...PHDocumentFields
1782
- }
1783
- }
1784
- }
1785
- ${PhDocumentFieldsFragmentDoc}
1786
- `;
1787
- import_main.gql`
1788
- mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
1789
- deleteDocument(identifier: $identifier, propagate: $propagate)
1790
- }
1791
- `;
1792
- import_main.gql`
1793
- mutation DeleteDocuments(
1794
- $identifiers: [String!]!
1795
- $propagate: PropagationMode
1796
- ) {
1797
- deleteDocuments(identifiers: $identifiers, propagate: $propagate)
1798
- }
1799
- `;
1800
- import_main.gql`
1801
- subscription DocumentChanges(
1802
- $search: SearchFilterInput
1803
- $view: ViewFilterInput
1804
- ) {
1805
- documentChanges(search: $search, view: $view) {
1806
- type
1807
- documents {
1808
- ...PHDocumentFields
1809
- }
1810
- context {
1811
- parentId
1812
- childId
1813
- }
1814
- }
1815
- }
1816
- ${PhDocumentFieldsFragmentDoc}
1817
- `;
1818
- import_main.gql`
1819
- subscription JobChanges($jobId: String!) {
1820
- jobChanges(jobId: $jobId) {
1821
- jobId
1822
- status
1823
- result
1824
- error
1825
- }
1826
- }
1827
- `;
1828
- import_main.gql`
1829
- query PollSyncEnvelopes(
1830
- $channelId: String!
1831
- $outboxAck: Int!
1832
- $outboxLatest: Int!
1833
- ) {
1834
- pollSyncEnvelopes(
1835
- channelId: $channelId
1836
- outboxAck: $outboxAck
1837
- outboxLatest: $outboxLatest
1838
- ) {
1839
- envelopes {
1840
- type
1841
- channelMeta {
1842
- id
1843
- }
1844
- operations {
1845
- operation {
1846
- index
1847
- timestampUtcMs
1848
- hash
1849
- skip
1850
- error
1851
- deniedReason
1852
- id
1853
- action {
1854
- id
1855
- type
1856
- timestampUtcMs
1857
- input
1858
- scope
1859
- context {
1860
- signer {
1861
- user {
1862
- address
1863
- networkId
1864
- chainId
1865
- }
1866
- app {
1867
- name
1868
- key
1869
- }
1870
- signatures
1871
- }
1872
- }
1873
- }
1874
- }
1875
- context {
1876
- documentId
1877
- documentType
1878
- scope
1879
- branch
1880
- }
1881
- }
1882
- cursor {
1883
- remoteName
1884
- cursorOrdinal
1885
- lastSyncedAtUtcMs
1886
- }
1887
- key
1888
- dependsOn
1889
- }
1890
- ackOrdinal
1891
- deadLetters {
1892
- documentId
1893
- error
1894
- errorType
1895
- }
1896
- hasMore
1897
- }
1898
- }
1899
- `;
1900
- import_main.gql`
1901
- mutation TouchChannel($input: TouchChannelInput!) {
1902
- touchChannel(input: $input) {
1903
- success
1904
- ackOrdinal
1905
- }
1906
- }
1907
- `;
1908
- import_main.gql`
1909
- mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
1910
- pushSyncEnvelopes(envelopes: $envelopes)
1911
- }
1912
- `;
1913
- /** Get the source string from a GraphQL document (string or DocumentNode). */
1914
- function getDocumentSource(doc) {
1915
- return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
1916
- }
1917
- /**
1918
- * Extract the inner selection set of a named field from a GraphQL document source.
1919
- * Returns the `{ ... }` block including braces.
1920
- */
1921
- function extractSelectionSet(doc, fieldName, fallback) {
1922
- const source = getDocumentSource(doc);
1923
- return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
1924
- }
1925
- /**
1926
- * Extract the query body and any fragment definitions from a GraphQL document.
1927
- * Returns { body, fragments } where body is the content inside the query `{ ... }`
1928
- * and fragments are any trailing fragment definitions.
1929
- */
1930
- function extractQueryParts(doc, fallbackBody) {
1931
- const source = getDocumentSource(doc);
1932
- const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
1933
- return {
1934
- body: queryMatch?.[1]?.trim() ?? fallbackBody,
1935
- fragments: queryMatch?.[2]?.trim() ?? ""
1936
- };
1937
- }
1938
- extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
1939
- extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
1940
- //#endregion
1941
- //#region ../reactor-browser/dist/renown-BHxwP7xU.js
1942
- const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
1943
- const RenownInitialUserContext = createContext({ state: "unknown" });
1944
- /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
1945
- function useRenownInitialAuth() {
1946
- return useContext(RenownInitialUserContext);
1947
- }
1948
- function useRenownInitialUser() {
1949
- const initial = useRenownInitialAuth();
1950
- return initial.state === "authenticated" ? initial.user : void 0;
1951
- }
1952
- const renownEventFunctions = makePHEventFunctions("renown");
1953
- renownEventFunctions.addEventHandler;
1954
- /** Returns the renown instance */
1955
- const useRenown = renownEventFunctions.useValue;
1956
- renownEventFunctions.setValue;
1957
- function jsonEqual(a, b) {
1958
- if (a === b) return true;
1959
- if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
1960
- if (Array.isArray(a) !== Array.isArray(b)) return false;
1961
- const ra = a;
1962
- const rb = b;
1963
- const keys = Object.keys(ra).filter((k) => ra[k] !== void 0);
1964
- if (keys.length !== Object.keys(rb).filter((k) => rb[k] !== void 0).length) return false;
1965
- return keys.every((k) => jsonEqual(ra[k], rb[k]));
1966
- }
1967
- function sameUser(a, b) {
1968
- return jsonEqual(a, b);
1969
- }
1970
- function resolveInstanceUser(instance, seed) {
1971
- const restored = instance.user;
1972
- if (restored) return sameUser(seed, restored) ? seed : restored;
1973
- return instance.status === "initial" ? void 0 : seed;
1974
- }
1975
- /** Returns the current user from the renown instance, subscribing to user events */
1976
- function useUser() {
1977
- const renown = useRenown();
1978
- const initialUser = useRenownInitialUser();
1979
- const instance = renown ? renown : void 0;
1980
- const [tracked, setTracked] = useState(() => ({
1981
- instance,
1982
- user: instance ? resolveInstanceUser(instance, initialUser) : initialUser
1983
- }));
1984
- const current = tracked.instance === instance ? tracked : {
1985
- instance,
1986
- user: instance ? resolveInstanceUser(instance, tracked.user ?? initialUser) : tracked.user
1987
- };
1988
- useEffect(() => {
1989
- if (current !== tracked) setTracked(current);
1990
- }, [current, tracked]);
1991
- useEffect(() => {
1992
- if (!instance) return;
1993
- return instance.on("user", (user) => setTracked((prev) => ({
1994
- instance,
1995
- user: sameUser(prev.user, user) ? prev.user : user
1996
- })));
1997
- }, [instance]);
1998
- return instance ? current.user : initialUser ?? current.user;
1999
- }
2000
- //#endregion
2001
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
2002
- function e$8(e, t, n) {
2003
- let r = (n) => e(n, ...t);
2004
- return n === void 0 ? r : Object.assign(r, {
2005
- lazy: n,
2006
- lazyArgs: t
2007
- });
2008
- }
2009
- //#endregion
2010
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
2011
- function t$5(t, n, r) {
2012
- let i = t.length - n.length;
2013
- if (i === 0) return t(...n);
2014
- if (i === 1) return e$8(t, n, r);
2015
- throw Error(`Wrong number of arguments`);
2016
- }
2017
- //#endregion
2018
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
2019
- function t$4(...t) {
2020
- return t$5(n$4, t);
2021
- }
2022
- const n$4 = (e, t) => t.every((t) => t(e));
2023
- //#endregion
2024
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
2025
- function e$7(e, t, n) {
2026
- return e(n[0]) ? (e) => t(e, ...n) : t(...n);
2027
- }
2028
- function t$3(...t) {
2029
- return e$7(r, n$3, t);
2030
- }
2031
- function n$3(e, ...t) {
2032
- for (let n of t) {
2033
- if (typeof n == `function`) return n(e);
2034
- let [t, r] = n;
2035
- if (t(e)) return r(e);
2036
- }
2037
- throw Error(`conditional: data failed for all cases`);
2038
- }
2039
- function r(e) {
2040
- if (!Array.isArray(e)) return !1;
2041
- let [t, n, ...r] = e;
2042
- return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
2043
- }
2044
- //#endregion
2045
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
2046
- function e$6(e) {
2047
- return () => e;
2048
- }
2049
- //#endregion
2050
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
2051
- function t$2(...t) {
2052
- return t$5(n$2, t);
2053
- }
2054
- const n$2 = (e, t) => e.length >= t;
2055
- //#endregion
2056
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
2057
- const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
2058
- function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
2059
- let c, l, u, d, f = () => {
2060
- let t = u;
2061
- t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
2062
- }, p = () => {
2063
- clearTimeout(l), l = void 0, c === void 0 && f();
2064
- }, m = () => {
2065
- clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
2066
- };
2067
- return {
2068
- call: (...e) => {
2069
- let t = c === void 0 && l === void 0;
2070
- if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
2071
- if (i !== void 0 || a !== void 0 || o === void 0) {
2072
- clearTimeout(c);
2073
- let e = Date.now();
2074
- d ??= e;
2075
- let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
2076
- c = setTimeout(m, t);
2077
- }
2078
- r !== `end` && t && f();
2079
- }
2080
- },
2081
- cancel: () => {
2082
- clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
2083
- },
2084
- flush: () => {
2085
- m(), p();
2086
- },
2087
- get isIdle() {
2088
- return c === void 0 && l === void 0;
2089
- }
2090
- };
2091
- }
2092
- //#endregion
2093
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
2094
- function e$4(e) {
2095
- return e !== void 0;
2096
- }
2097
- //#endregion
2098
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
2099
- function e$3(e) {
2100
- return (t) => !e(t);
2101
- }
2102
- //#endregion
2103
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
2104
- function t(...t) {
2105
- return t$5(n, t);
2106
- }
2107
- const n = (e, t) => e === t || Object.is(e, t);
2108
- //#endregion
2109
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
2110
- function e$2(e) {
2111
- return typeof e == `string`;
2112
- }
2113
- //#endregion
2114
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
2115
- function e$1(e) {
2116
- return !!e;
2117
- }
2118
- //#endregion
2119
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
2120
- function e(e) {
2121
- let t = !1, n;
2122
- return () => (t ||= (n = e(), !0), n);
2123
- }
2124
- var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
2125
- CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
2126
- CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
2127
- CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
2128
- CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
2129
- CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
2130
- CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
2131
- CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
2132
- CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
2133
- CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
2134
- CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
2135
- CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
2136
- return CloseCode2;
2137
- })(CloseCode || {});
2138
- var MessageType = /* @__PURE__ */ ((MessageType2) => {
2139
- MessageType2["ConnectionInit"] = "connection_init";
2140
- MessageType2["ConnectionAck"] = "connection_ack";
2141
- MessageType2["Ping"] = "ping";
2142
- MessageType2["Pong"] = "pong";
2143
- MessageType2["Subscribe"] = "subscribe";
2144
- MessageType2["Next"] = "next";
2145
- MessageType2["Error"] = "error";
2146
- MessageType2["Complete"] = "complete";
2147
- return MessageType2;
2148
- })(MessageType || {});
2149
- Error;
2150
- //#endregion
2151
- //#region ../reactor-browser/dist/document-operations-Cm4EtaZs.js
2152
- const modalEventFunctions = makePHEventFunctions("modal");
2153
- modalEventFunctions.useValue;
2154
- /** Sets the current modal */
2155
- const setPHModal = modalEventFunctions.setValue;
2156
- modalEventFunctions.addEventHandler;
2157
- /** Shows a modal */
2158
- function showPHModal(modal) {
2159
- setPHModal(modal);
2160
- }
2161
- /** Shows the delete node modal */
2162
- function showDeleteNodeModal(nodeOrId) {
2163
- setPHModal({
2164
- type: "deleteItem",
2165
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2166
- });
2167
- }
2168
- function isDocumentTypeSupported(documentType, supportedDocuments) {
2169
- if (!supportedDocuments?.length) return true;
2170
- return supportedDocuments.some((pattern) => {
2171
- if (pattern.endsWith("/*")) {
2172
- const prefix = pattern.slice(0, -2);
2173
- return documentType.startsWith(prefix + "/");
2174
- }
2175
- if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
2176
- const prefix = pattern.slice(0, -1);
2177
- return documentType.startsWith(prefix);
2178
- }
2179
- return pattern === documentType;
2180
- });
2181
- }
2182
- function getUserPermissions() {
2183
- const user = window.ph?.renown?.user;
2184
- const allowList = window.ph?.allowList;
2185
- if (!allowList) return {
2186
- isAllowedToCreateDocuments: true,
2187
- isAllowedToEditDocuments: true
2188
- };
2189
- return {
2190
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2191
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2192
- };
2193
- }
2194
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2195
- /** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
2196
- async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
2197
- const drive = await reactorClient.get(driveId);
2198
- const nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);
2199
- if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {
2200
- isDuplicate: true,
2201
- duplicateType: "id",
2202
- nodeId: nodeById.id
2203
- };
2204
- const nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));
2205
- if (nodeByNameAndType) return {
2206
- isDuplicate: true,
2207
- duplicateType: "name",
2208
- nodeId: nodeByNameAndType.id
2209
- };
2210
- return { isDuplicate: false };
2211
- }
2212
- function getDocumentTypeIcon(document) {
2213
- switch (document.header.documentType) {
2214
- case "powerhouse/document-model": return "document-model";
2215
- case "powerhouse/app": return "app";
2216
- case "powerhouse/document-editor": return "editor";
2217
- case "powerhouse/subgraph": return "subgraph";
2218
- case "powerhouse/package": return "package";
2219
- case "powerhouse/processor": {
2220
- const processorType = document.state.global?.type;
2221
- if (processorType === "analytics") return "analytics-processor";
2222
- if (processorType === "relational") return "relational-processor";
2223
- if (processorType === "codegen") return "codegen-processor";
2224
- return;
2225
- }
2226
- default: return;
2227
- }
2228
- }
2229
- async function downloadFile(document, fileName) {
2230
- try {
2231
- const data = await createZip(document);
2232
- const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2233
- const link = window.document.createElement("a");
2234
- link.style.display = "none";
2235
- link.href = URL.createObjectURL(blob);
2236
- link.download = fileName;
2237
- window.document.body.appendChild(link);
2238
- link.click();
2239
- window.document.body.removeChild(link);
2240
- } catch (e) {
2241
- logger.error(e instanceof Error ? e.message : String(e));
2242
- }
2243
- }
2244
- async function getDocumentExtension(document) {
2245
- const documentType = document.header.documentType;
2246
- let rawExtension;
2247
- if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2248
- else {
2249
- const reactorClient = window.ph?.reactorClientModule?.client;
2250
- if (reactorClient) {
2251
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2252
- rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2253
- }
2254
- }
2255
- return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2256
- }
2257
- /**
2258
- * Fetches all operations for a document using cursor-based pagination.
2259
- * The reactor client handles multi-scope cursors transparently via
2260
- * composite cursors, so all scopes are fetched in a single paginated stream.
2261
- */
2262
- async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2263
- const scopes = Object.keys(document.state);
2264
- const operations = {};
2265
- for (const scope of scopes) operations[scope] = [];
2266
- let cursor = "";
2267
- do {
2268
- const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2269
- cursor,
2270
- limit: pageSize
2271
- });
2272
- for (const op of page.results) {
2273
- const scope = op.action.scope ?? "global";
2274
- if (operations[scope]) operations[scope].push(op);
2275
- }
2276
- cursor = page.nextCursor ?? "";
2277
- } while (cursor);
2278
- return operations;
2279
- }
2280
- function extractInitialState(documentScopeOps) {
2281
- const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2282
- if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2283
- const input = upgradeOp.action.input;
2284
- const initialState = input.initialState ?? input.state;
2285
- if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2286
- return initialState;
2287
- }
2288
- function filterDomainOperations(operations) {
2289
- return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2290
- }
2291
- function countOperations(operations) {
2292
- let total = 0;
2293
- for (const ops of Object.values(operations)) total += ops?.length ?? 0;
2294
- return total;
2295
- }
2296
- /**
2297
- * Split an imported document's domain operations at its mid-history upgrade
2298
- * boundaries, so the caller can re-dispatch each upgrade between segments.
2299
- *
2300
- * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
2301
- * path and must not be repeated. A later upgrade must be: it is where the
2302
- * reducer version changes, and dropping it replays everything after it through
2303
- * the module the document was created with.
2304
- */
2305
- function splitAtUpgradeBoundaries(operations) {
2306
- 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);
2307
- const domain = filterDomainOperations(operations);
2308
- if (upgrades.length === 0) return [{ operations: domain }];
2309
- const segments = [];
2310
- const consumed = /* @__PURE__ */ new Map();
2311
- const take = (until) => {
2312
- const slice = {};
2313
- for (const [scope, ops] of Object.entries(domain)) {
2314
- if (!ops) continue;
2315
- const from = consumed.get(scope) ?? 0;
2316
- const stop = Math.max(from, until(scope, ops));
2317
- const chunk = ops.slice(from, stop);
2318
- if (chunk.length > 0) slice[scope] = chunk;
2319
- consumed.set(scope, stop);
2320
- }
2321
- return slice;
2322
- };
2323
- for (const upgrade of upgrades) {
2324
- const input = upgrade.action.input;
2325
- const slice = take((scope, ops) => boundary(upgrade, scope, ops));
2326
- segments.push({
2327
- operations: slice,
2328
- upgradeTo: input.toVersion
2329
- });
2330
- }
2331
- const tail = take((_scope, ops) => ops.length);
2332
- if (countOperations(tail) > 0) segments.push({ operations: tail });
2333
- return segments;
2334
- }
2335
- /**
2336
- * How many of a scope's operations precede an upgrade. Must stay identical to
2337
- * the boundary computation in `replayDocumentVersioned` — snapshots compare
2338
- * against operation indices, not array positions, and the timestamp fallback
2339
- * excludes the upgrade's own instant.
2340
- */
2341
- function boundary(upgrade, scope, ops) {
2342
- const snapshot = upgrade.action.input.revision;
2343
- if (snapshot !== void 0) {
2344
- const revision = snapshot[scope] ?? 0;
2345
- let count = 0;
2346
- for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
2347
- return count;
2348
- }
2349
- for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
2350
- return ops.length;
2351
- }
2352
- async function exportFile(document, suggestedName) {
2353
- const reactorClient = window.ph?.reactorClient;
2354
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2355
- const operations = await fetchDocumentOperations(reactorClient, document);
2356
- const initialState = extractInitialState(operations["document"] ?? []);
2357
- const documentWithOps = {
2358
- ...document,
2359
- operations,
2360
- initialState
2361
- };
2362
- const extension = await getDocumentExtension(documentWithOps);
2363
- const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2364
- const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2365
- if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2366
- try {
2367
- const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2368
- await baseSaveToFileHandle(documentWithOps, fileHandle);
2369
- return fileHandle;
2370
- } catch (e) {
2371
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2372
- }
2373
- }
2374
- /**
2375
- * Loads a document file and replays it with version-aware reducers from the registry.
2376
- * Falls back to single-version legacy replay when no upgrade manifest is registered for
2377
- * the document type.
2378
- */
2379
- async function loadFile(path) {
2380
- const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2381
- const reactorClient = window.ph?.reactorClientModule?.client;
2382
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2383
- const documentType = baseDocument.header.documentType;
2384
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2385
- const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2386
- if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2387
- const reducers = {};
2388
- for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2389
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2390
- let upgradeManifest;
2391
- if (registry) try {
2392
- upgradeManifest = registry.getUpgradeManifest(documentType);
2393
- } catch {}
2394
- return baseLoadFromInputVersioned(path, {
2395
- reducers,
2396
- upgradeManifest
2397
- });
2398
- }
2399
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
2400
- const { isAllowedToCreateDocuments } = getUserPermissions();
2401
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2402
- const reactorClient = window.ph?.reactorClientModule?.client;
2403
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2404
- let documentModelModule;
2405
- if (documentModelVersion !== void 0) {
2406
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2407
- const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
2408
- if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
2409
- documentModelModule = module;
2410
- } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2411
- const newDocument = document ?? documentModelModule.utils.createDocument();
2412
- if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
2413
- newDocument.header.name = name;
2414
- if (preferredEditor) newDocument.header.meta = {
2415
- ...newDocument.header.meta,
2416
- preferredEditor
2417
- };
2418
- let newDoc;
2419
- try {
2420
- newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2421
- } catch (e) {
2422
- logger.error("Error adding document: @error", e);
2423
- throw new Error("There was an error adding document", { cause: e });
2424
- }
2425
- return {
2426
- id: newDoc.header.id,
2427
- name: newDoc.header.name,
2428
- documentType,
2429
- parentFolder: parentFolder ?? null,
2430
- kind: "file"
2431
- };
2432
- }
2433
- /**
2434
- * How many ids an import will try before giving up. The check before the create
2435
- * catches an id that is already taken; this bound covers the window between the
2436
- * two, where a create can still lose to a claim made in the meantime.
2437
- */
2438
- const IMPORT_ID_ATTEMPTS = 3;
2439
- /** True when this error, or anything it wraps, is a taken document id. */
2440
- function isDocumentAlreadyExists(error) {
2441
- let current = error;
2442
- while (current instanceof Error) {
2443
- if (current.name === "DocumentAlreadyExistsError") return true;
2444
- current = current.cause;
2445
- }
2446
- return false;
2447
- }
2448
- /**
2449
- * Creates the imported document under an id that is free, retrying on a
2450
- * collision.
2451
- *
2452
- * The check cannot stand on its own: it answers for the moment it ran, and the
2453
- * create that follows can still land on an id claimed in between. The store
2454
- * rejects that create as DocumentAlreadyExistsError, which is not retryable
2455
- * under the same id and is resolved by minting another one. A create that
2456
- * fails leaves the drive untouched, so a retry has nothing to clean up.
2457
- */
2458
- async function createImportedDocument(reactor, document, driveId, name, parentFolder) {
2459
- let documentId = await reactor.isDocumentIdTaken(document.header.id) ? generateId() : document.header.id;
2460
- for (let attempt = 1;; attempt++) {
2461
- const header = createPresignedHeader(documentId, document.header.documentType);
2462
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2463
- header.meta = document.header.meta;
2464
- header.name = name || document.header.name;
2465
- const initialDocument = {
2466
- ...document,
2467
- header,
2468
- state: document.initialState,
2469
- operations: Object.keys(document.operations).reduce((acc, key) => {
2470
- acc[key] = [];
2471
- return acc;
2472
- }, {})
2473
- };
2474
- try {
2475
- const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2476
- if (!fileNode) throw new Error("There was an error adding file");
2477
- return {
2478
- documentId,
2479
- fileNode
2480
- };
2481
- } catch (error) {
2482
- if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;
2483
- logger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);
2484
- documentId = generateId();
2485
- }
2486
- }
2487
- }
2488
- async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2489
- logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2490
- const reactor = window.ph?.reactorClientModule?.client;
2491
- if (!reactor) {
2492
- onProgress?.({
2493
- stage: "failed",
2494
- progress: 100,
2495
- error: "ReactorClient not initialized"
2496
- });
2497
- throw new Error("ReactorClient not initialized");
2498
- }
2499
- const { isAllowedToCreateDocuments } = getUserPermissions();
2500
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2501
- try {
2502
- onProgress?.({
2503
- stage: "loading",
2504
- progress: 0
2505
- });
2506
- let document;
2507
- try {
2508
- document = await loadFile(file);
2509
- } catch (loadError) {
2510
- if (UnsupportedDocumentModelVersionError.isError(loadError)) {
2511
- showPHModal({
2512
- type: "documentVersionUnsupported",
2513
- documentType: loadError.documentType,
2514
- requiredVersion: loadError.requiredVersion,
2515
- availableVersions: loadError.availableVersions
2516
- });
2517
- onProgress?.({
2518
- stage: "failed",
2519
- progress: 100,
2520
- error: loadError.message
2521
- });
2522
- return;
2523
- }
2524
- const discoveryService = window.ph?.packageDiscoveryService;
2525
- if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
2526
- retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
2527
- logger.error("Import retry after discovery failed: @error", retryError);
2528
- onProgress?.({
2529
- stage: "failed",
2530
- progress: 100,
2531
- error: retryError instanceof Error ? retryError.message : String(retryError)
2532
- });
2533
- });
2534
- return;
2535
- }
2536
- throw loadError;
2537
- }
2538
- const duplicateCheck = await isDocumentInLocation(reactor, document, driveId, parentFolder);
2539
- if (duplicateCheck.isDuplicate && !resolveConflict) {
2540
- onProgress?.({
2541
- stage: "conflict",
2542
- progress: 0,
2543
- duplicateType: duplicateCheck.duplicateType
2544
- });
2545
- return;
2546
- }
2547
- const documentType = getDocumentTypeIcon(document);
2548
- if (documentType) onProgress?.({
2549
- stage: "loading",
2550
- progress: 10,
2551
- documentType
2552
- });
2553
- else onProgress?.({
2554
- stage: "loading",
2555
- progress: 10
2556
- });
2557
- if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
2558
- onProgress?.({
2559
- stage: "unsupported-document-type",
2560
- progress: 100,
2561
- error: `Document type ${document.header.documentType} is not supported`
2562
- });
2563
- throw new UnsupportedDocumentTypeError(document.header.documentType);
2564
- }
2565
- await reactor.getDocumentModelModule(document.header.documentType);
2566
- onProgress?.({
2567
- stage: "initializing",
2568
- progress: 10
2569
- });
2570
- const created = await createImportedDocument(reactor, document, driveId, name, parentFolder);
2571
- const documentId = created.documentId;
2572
- const fileNode = created.fileNode;
2573
- onProgress?.({
2574
- stage: "initializing",
2575
- progress: 20
2576
- });
2577
- await reactor.get(documentId);
2578
- console.log("Document created, starting upload of operations");
2579
- const segments = splitAtUpgradeBoundaries(document.operations);
2580
- const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
2581
- let uploadedBefore = 0;
2582
- for (const segment of segments) {
2583
- await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
2584
- if (uploadProgress.uploadedOperations === void 0) return;
2585
- const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
2586
- const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
2587
- onProgress?.({
2588
- stage: "uploading",
2589
- progress: 20 + Math.round(uploadPercent * 80),
2590
- totalOperations,
2591
- uploadedOperations: uploaded
2592
- });
2593
- } });
2594
- uploadedBefore += countOperations(segment.operations);
2595
- if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
2596
- }
2597
- onProgress?.({
2598
- stage: "complete",
2599
- progress: 100,
2600
- fileNode
2601
- });
2602
- return fileNode;
2603
- } catch (error) {
2604
- if (!UnsupportedDocumentTypeError.isError(error)) {
2605
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
2606
- onProgress?.({
2607
- stage: "failed",
2608
- progress: 100,
2609
- error: errorMessage
2610
- });
2611
- }
2612
- throw error;
2613
- }
2614
- }
2615
- async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2616
- if (!discoveryService) return;
2617
- try {
2618
- await discoveryService.load(documentType);
2619
- } catch {
2620
- onProgress?.({
2621
- stage: "unsupported-document-type",
2622
- progress: 100,
2623
- error: `Document type ${documentType} is not supported`
2624
- });
2625
- return;
2626
- }
2627
- await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
2628
- }
2629
- async function addFolder$1(driveId, name, parentFolder) {
2630
- const { isAllowedToCreateDocuments } = getUserPermissions();
2631
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2632
- const reactorClient = window.ph?.reactorClient;
2633
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2634
- await reactorClient.get(driveId);
2635
- const folderId = generateId();
2636
- const node = (await reactorClient.execute(driveId, "main", [addFolder({
2637
- id: folderId,
2638
- name,
2639
- parentFolder
2640
- })])).state.global.nodes.find((node) => node.id === folderId);
2641
- if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2642
- return node;
2643
- }
2644
- async function renameNode(driveId, nodeId, name) {
2645
- const { isAllowedToCreateDocuments } = getUserPermissions();
2646
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2647
- const reactorClient = window.ph?.reactorClient;
2648
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2649
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2650
- const node = (await reactorClient.execute(driveId, "main", [updateNode({
2651
- id: nodeId,
2652
- name
2653
- })])).state.global.nodes.find((n) => n.id === nodeId);
2654
- if (!node) throw new Error("There was an error renaming node in the drive");
2655
- return node;
2656
- }
2657
- async function renameDriveNode(driveId, nodeId, name) {
2658
- const { isAllowedToCreateDocuments } = getUserPermissions();
2659
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2660
- const reactorClient = window.ph?.reactorClient;
2661
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2662
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2663
- await reactorClient.execute(driveId, "main", [updateNode({
2664
- id: nodeId,
2665
- name
2666
- })]);
2667
- return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2668
- }
2669
- async function moveNodeById(args) {
2670
- const { driveId, srcId, targetId } = args;
2671
- if (!driveId || !srcId) return;
2672
- const { isAllowedToCreateDocuments } = getUserPermissions();
2673
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2674
- const reactorClient = window.ph?.reactorClient;
2675
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2676
- const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2677
- if (t(targetParentFolder, srcId)) return;
2678
- return await reactorClient.execute(driveId, "main", [moveNode({
2679
- srcFolder: srcId,
2680
- targetParentFolder
2681
- })]);
2682
- }
2683
- async function moveNode$1(driveId, src, target) {
2684
- const { isAllowedToCreateDocuments } = getUserPermissions();
2685
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2686
- const reactorClient = window.ph?.reactorClient;
2687
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2688
- return await reactorClient.execute(driveId, "main", [moveNode({
2689
- srcFolder: src.id,
2690
- targetParentFolder: target?.id
2691
- })]);
2692
- }
2693
- /**
2694
- * Duplicates a document under a new id using version-aware replay.
2695
- * Falls back gracefully when no upgrade manifest is registered for the document type.
2696
- */
2697
- async function _duplicateDocument(reactor, document, newId = generateId()) {
2698
- const documentType = document.header.documentType;
2699
- const { results: allModules } = await reactor.getDocumentModelModules();
2700
- const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2701
- const reducers = {};
2702
- for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2703
- if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2704
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2705
- let upgradeManifest;
2706
- if (registry) try {
2707
- upgradeManifest = registry.getUpgradeManifest(documentType);
2708
- } catch {}
2709
- const config = {
2710
- reducers,
2711
- upgradeManifest
2712
- };
2713
- const header = createPresignedHeader(newId, documentType);
2714
- const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2715
- assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2716
- return duplicated;
2717
- }
2718
- async function copyNode$1(driveId, src, target) {
2719
- const reactor = window.ph?.reactorClientModule?.client;
2720
- if (!reactor) return;
2721
- const { isAllowedToCreateDocuments } = getUserPermissions();
2722
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2723
- const drive = await reactor.get(driveId);
2724
- const copyNodesInput = generateNodesCopy({
2725
- srcId: src.id,
2726
- targetParentFolder: target?.id,
2727
- targetName: src.name
2728
- }, () => generateId(), drive.state.global.nodes);
2729
- const resolvedNamesMap = /* @__PURE__ */ new Map();
2730
- for (const copyNodeInput of copyNodesInput) {
2731
- const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2732
- if (node) {
2733
- const resolvedName = handleTargetNameCollisions({
2734
- nodes: drive.state.global.nodes,
2735
- srcName: copyNodeInput.targetName || node.name,
2736
- srcKind: isFileNode(node) ? "file" : "folder",
2737
- targetParentFolder: copyNodeInput.targetParentFolder || null
2738
- });
2739
- resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2740
- }
2741
- }
2742
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2743
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2744
- return node !== void 0 && isFileNode(node);
2745
- });
2746
- for (const fileNodeToCopy of fileNodesToCopy) try {
2747
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2748
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2749
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2750
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2751
- } catch (e) {
2752
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2753
- }
2754
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2755
- }
2756
- /**
2757
- * The operation selection of `GetDocumentOperations`, lifted into a fragment so
2758
- * the write path can reuse `remoteOperationToLocal` on the items it selects.
2759
- */
2760
- const ReactorOperationFieldsFragmentDoc = import_main.gql`
2761
- fragment ReactorOperationFields on ReactorOperation {
2762
- index
2763
- timestampUtcMs
2764
- hash
2765
- skip
2766
- error
2767
- deniedReason
2768
- id
2769
- action {
2770
- id
2771
- type
2772
- timestampUtcMs
2773
- input
2774
- scope
2775
- context {
2776
- signer {
2777
- user {
2778
- address
2779
- networkId
2780
- chainId
2781
- }
2782
- app {
2783
- name
2784
- key
2785
- }
2786
- signatures
2787
- }
2788
- }
2789
- }
2790
- }
2791
- `;
2792
- import_main.gql`
2793
- mutation MutateDocumentWithOperations(
2794
- $documentIdentifier: String!
2795
- $actions: [ActionInput!]!
2796
- $sinceRevision: Int
2797
- $scopes: [String!]
2798
- $branch: String
2799
- ) {
2800
- mutateDocument: execute(
2801
- documentIdentifier: $documentIdentifier
2802
- actions: $actions
2803
- branch: $branch
2804
- ) {
2805
- ...PHDocumentFields
2806
- operations(
2807
- filter: {
2808
- sinceRevision: $sinceRevision
2809
- scopes: $scopes
2810
- branch: $branch
2811
- }
2812
- ) {
2813
- items {
2814
- ...ReactorOperationFields
2815
- }
2816
- }
2817
- }
2818
- }
2819
- ${PhDocumentFieldsFragmentDoc}
2820
- ${ReactorOperationFieldsFragmentDoc}
2821
- `;
2822
- DocumentChangeType.Created, DOCUMENT_CHANGE_TYPE.Created, DocumentChangeType.Deleted, DOCUMENT_CHANGE_TYPE.Deleted, DocumentChangeType.Updated, DOCUMENT_CHANGE_TYPE.Updated, DocumentChangeType.ParentAdded, DOCUMENT_CHANGE_TYPE.ParentAdded, DocumentChangeType.ParentRemoved, DOCUMENT_CHANGE_TYPE.ParentRemoved, DocumentChangeType.ChildAdded, DOCUMENT_CHANGE_TYPE.ChildAdded, DocumentChangeType.ChildRemoved, DOCUMENT_CHANGE_TYPE.ChildRemoved;
2823
- PropagationMode.Cascade, PropagationMode.Orphan;
2824
- const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2825
- /** Sets whether external controls are enabled for a given editor. */
2826
- const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2827
- /** Gets whether external controls are enabled for a given editor. */
2828
- const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2829
- isExternalControlsEnabledEventFunctions.addEventHandler;
2830
- const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2831
- /** Sets whether drag and drop is enabled for a given app. */
2832
- const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2833
- /** Gets whether drag and drop is enabled for a given app. */
2834
- const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2835
- isDragAndDropEnabledEventFunctions.addEventHandler;
2836
- const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2837
- /** Sets the allowed document types for a given app. */
2838
- const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2839
- /** Defines the document types a drive supports.
2840
- *
2841
- * Defaults to all of the document types registered in the reactor.
2842
- */
2843
- function useAllowedDocumentTypes() {
2844
- return allowedDocumentTypesEventFunctions.useValue();
2845
- }
2846
- allowedDocumentTypesEventFunctions.addEventHandler;
2847
- const phAppConfigSetters = {
2848
- allowedDocumentTypes: setAllowedDocumentTypes,
2849
- isDragAndDropEnabled: setIsDragAndDropEnabled
2850
- };
2851
- const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2852
- const phAppConfigHooks = {
2853
- allowedDocumentTypes: useAllowedDocumentTypes,
2854
- isDragAndDropEnabled: useIsDragAndDropEnabled
2855
- };
2856
- const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
2857
- const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
2858
- const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
2859
- const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
2860
- const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
2861
- const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
2862
- const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
2863
- const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
2864
- const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
2865
- const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
2866
- const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
2867
- const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
2868
- const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
2869
- const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
2870
- const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2871
- const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
2872
- const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
2873
- const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
2874
- const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
2875
- const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
2876
- const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
2877
- const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
2878
- const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2879
- const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
2880
- const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
2881
- const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
2882
- const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
2883
- const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
2884
- const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
2885
- const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
2886
- const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2887
- const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2888
- const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2889
- const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
2890
- const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
2891
- const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2892
- const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2893
- const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
2894
- const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
2895
- const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
2896
- const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
2897
- const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
2898
- /** Sets the enabled editors for Connect. */
2899
- const setEnabledEditors = enabledEditorsEventFunctions.setValue;
2900
- /** Gets the enabled editors for Connect. */
2901
- const useEnabledEditors = enabledEditorsEventFunctions.useValue;
2902
- enabledEditorsEventFunctions.addEventHandler;
2903
- const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
2904
- /** Sets the disabled editors for Connect. */
2905
- const setDisabledEditors = disabledEditorsEventFunctions.setValue;
2906
- /** Gets the disabled editors for Connect. */
2907
- const useDisabledEditors = disabledEditorsEventFunctions.useValue;
2908
- disabledEditorsEventFunctions.addEventHandler;
2909
- const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
2910
- /** Sets the isRelationalProcessorsEnabled for Connect. */
2911
- const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
2912
- /** Gets the isRelationalProcessorsEnabled for Connect. */
2913
- const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
2914
- isRelationalProcessorsEnabled.addEventHandler;
2915
- const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
2916
- /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
2917
- const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
2918
- /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
2919
- const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
2920
- isExternalRelationalProcessorsEnabled.addEventHandler;
2921
- const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
2922
- /** Sets the isAnalyticsEnabled for Connect. */
2923
- const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
2924
- /** Gets the isAnalyticsEnabled for Connect. */
2925
- const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
2926
- isAnalyticsEnabledEventFunctions.addEventHandler;
2927
- const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
2928
- /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
2929
- const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
2930
- /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
2931
- const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
2932
- isAnalyticsExternalProcessorsEnabled.addEventHandler;
2933
- const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
2934
- /** Sets the analytics database name for Connect. */
2935
- const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
2936
- /** Gets the analytics database name for Connect. */
2937
- const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
2938
- analyticsDatabaseNameEventFunctions.addEventHandler;
2939
- const logLevelEventFunctions = makePHEventFunctions("logLevel");
2940
- /** Sets the log level for Connect. */
2941
- const setLogLevel = logLevelEventFunctions.setValue;
2942
- /** Gets the log level for Connect. */
2943
- const useLogLevel = logLevelEventFunctions.useValue;
2944
- logLevelEventFunctions.addEventHandler;
2945
- const allowListEventFunctions = makePHEventFunctions("allowList");
2946
- /** Sets the allow list for Connect. */
2947
- const setAllowList = allowListEventFunctions.setValue;
2948
- /** Gets the allow list for Connect. */
2949
- const useAllowList = allowListEventFunctions.useValue;
2950
- allowListEventFunctions.addEventHandler;
2951
- const nonUserConfigSetters = {
2952
- routerBasename: setRouterBasename,
2953
- version: setVersion,
2954
- requiresHardRefresh: setRequiresHardRefresh,
2955
- warnOutdatedApp: setWarnOutdatedApp,
2956
- studioMode: setStudioMode,
2957
- basePath: setBasePath,
2958
- versionCheckInterval: setVersionCheckInterval,
2959
- cliVersion: setCliVersion,
2960
- fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
2961
- isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
2962
- gaTrackingId: setGaTrackingId,
2963
- defaultDrivesUrl: setDefaultDrivesUrl,
2964
- drivesPreserveStrategy: setDrivesPreserveStrategy,
2965
- isLocalDrivesEnabled: setIsLocalDrivesEnabled,
2966
- isAddDriveEnabled: setIsAddDriveEnabled,
2967
- isPublicDrivesEnabled: setIsPublicDrivesEnabled,
2968
- isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
2969
- isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
2970
- isCloudDrivesEnabled: setIsCloudDrivesEnabled,
2971
- isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
2972
- isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
2973
- isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
2974
- isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
2975
- isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
2976
- isEditorReadModeEnabled: setIsEditorReadModeEnabled,
2977
- isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
2978
- isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
2979
- isAnalyticsEnabled: setIsAnalyticsEnabled,
2980
- analyticsDatabaseName: setAnalyticsDatabaseName,
2981
- isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
2982
- isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
2983
- isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
2984
- isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
2985
- renownUrl: setRenownUrl,
2986
- renownNetworkId: setRenownNetworkId,
2987
- renownChainId: setRenownChainId,
2988
- switchboardUrl: setSwitchboardUrl,
2989
- renownAdapters: setRenownAdapters,
2990
- sentryRelease: setSentryRelease,
2991
- sentryDsn: setSentryDsn,
2992
- sentryEnv: setSentryEnv,
2993
- isSentryTracingEnabled: setIsSentryTracingEnabled,
2994
- isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
2995
- isExternalPackagesEnabled: setIsExternalPackagesEnabled,
2996
- allowList: setAllowList,
2997
- logLevel: setLogLevel,
2998
- disabledEditors: setDisabledEditors,
2999
- enabledEditors: setEnabledEditors
3000
- };
3001
- const phGlobalConfigSetters = {
3002
- ...phAppConfigSetters,
3003
- ...phDocumentEditorConfigSetters,
3004
- ...nonUserConfigSetters
3005
- };
3006
- const nonUserConfigHooks = {
3007
- routerBasename: useRouterBasename,
3008
- version: useVersion,
3009
- requiresHardRefresh: useRequiresHardRefresh,
3010
- warnOutdatedApp: useWarnOutdatedApp,
3011
- studioMode: useStudioMode,
3012
- basePath: useBasePath,
3013
- versionCheckInterval: useVersionCheckInterval,
3014
- cliVersion: useCliVersion,
3015
- fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
3016
- isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
3017
- gaTrackingId: useGaTrackingId,
3018
- defaultDrivesUrl: useDefaultDrivesUrl,
3019
- drivesPreserveStrategy: useDrivesPreserveStrategy,
3020
- isAddDriveEnabled: useIsAddDriveEnabled,
3021
- isPublicDrivesEnabled: useIsPublicDrivesEnabled,
3022
- isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
3023
- isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
3024
- isCloudDrivesEnabled: useIsCloudDrivesEnabled,
3025
- isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
3026
- isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
3027
- isLocalDrivesEnabled: useIsLocalDrivesEnabled,
3028
- isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
3029
- isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
3030
- isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
3031
- isEditorReadModeEnabled: useIsEditorReadModeEnabled,
3032
- isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
3033
- isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
3034
- isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
3035
- renownUrl: useRenownUrl,
3036
- renownNetworkId: useRenownNetworkId,
3037
- renownChainId: useRenownChainId,
3038
- switchboardUrl: useSwitchboardUrl,
3039
- renownAdapters: useRenownAdapters,
3040
- sentryRelease: useSentryRelease,
3041
- sentryDsn: useSentryDsn,
3042
- sentryEnv: useSentryEnv,
3043
- isSentryTracingEnabled: useIsSentryTracingEnabled,
3044
- isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
3045
- isExternalPackagesEnabled: useIsExternalPackagesEnabled,
3046
- allowList: useAllowList,
3047
- isAnalyticsEnabled: useIsAnalyticsEnabled,
3048
- isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
3049
- isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
3050
- isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
3051
- analyticsDatabaseName: useAnalyticsDatabaseName,
3052
- logLevel: useLogLevel,
3053
- disabledEditors: useDisabledEditors,
3054
- enabledEditors: useEnabledEditors
3055
- };
3056
- ({
3057
- ...phAppConfigHooks,
3058
- ...phDocumentEditorConfigHooks,
3059
- ...nonUserConfigHooks
3060
- });
3061
- const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
3062
- attachmentServiceEventFunctions.useValue;
3063
- attachmentServiceEventFunctions.setValue;
3064
- attachmentServiceEventFunctions.addEventHandler;
3065
- const featuresEventFunctions = makePHEventFunctions("features");
3066
- featuresEventFunctions.useValue;
3067
- featuresEventFunctions.setValue;
3068
- featuresEventFunctions.addEventHandler;
3069
- function useDropTarget() {
3070
- const [isDropTarget, setIsDropTarget] = useState(false);
3071
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3072
- const targetSetter = n$1(() => setIsDropTarget(true), {
3073
- triggerAt: "start",
3074
- minQuietPeriodMs: 100
3075
- });
3076
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3077
- triggerAt: "start",
3078
- minQuietPeriodMs: 100
3079
- });
3080
- function setTarget() {
3081
- if (!isDragAndDropEnabled) return;
3082
- targetUnsetter.cancel();
3083
- targetSetter.call();
3084
- }
3085
- function unsetTarget() {
3086
- if (!isDragAndDropEnabled) return;
3087
- targetSetter.cancel();
3088
- targetUnsetter.call();
3089
- }
3090
- return {
3091
- isDropTarget,
3092
- setTarget,
3093
- unsetTarget
3094
- };
3095
- }
3096
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3097
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3098
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3099
- draggingNodeEventFunctions.addEventHandler;
3100
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3101
- reducer: (_, newNode) => newNode,
3102
- triggerAt: "start",
3103
- minQuietPeriodMs: 100
3104
- });
3105
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3106
- triggerAt: "start",
3107
- minQuietPeriodMs: 100
3108
- });
3109
- function setDragging(node) {
3110
- draggingNodeUnsetter.cancel();
3111
- draggingNodeSetter.call(node);
3112
- }
3113
- function unsetDragging() {
3114
- draggingNodeSetter.cancel();
3115
- draggingNodeUnsetter.call();
3116
- }
3117
- const isNodeDrag = (params) => t$3(params, [({ srcId }) => e$3(e$1)(srcId), e$6(false)], [({ driveId }) => e$3(e$1)(driveId), e$6(false)], [({ driveId, srcId }) => t(driveId, srcId), e$6(false)], e$6(true));
3118
- function useDragNode(args) {
3119
- const { srcId, parentId } = args;
3120
- const driveId = useSelectedDriveId();
3121
- const draggingNodeId = useDraggingNode()?.srcId;
3122
- const params = {
3123
- driveId,
3124
- srcId,
3125
- parentId
3126
- };
3127
- const draggable = isNodeDrag(params);
3128
- const isDragging = t$4({
3129
- srcId,
3130
- draggingNodeId
3131
- }, [
3132
- () => draggable,
3133
- ({ srcId }) => e$2(srcId),
3134
- ({ draggingNodeId }) => e$2(draggingNodeId),
3135
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3136
- ]);
3137
- const onDragStart = () => {
3138
- if (!draggable) return;
3139
- setDragging(params);
3140
- };
3141
- const onDragEnd = () => {
3142
- if (!draggable) return;
3143
- unsetDragging();
3144
- };
3145
- return {
3146
- isDragging,
3147
- draggable,
3148
- onDragStart,
3149
- onDragEnd
3150
- };
3151
- }
3152
- const isNodeDrop = (params) => t$3(params, [({ srcId }) => e$3(e$1)(srcId), e$6(false)], [({ driveId }) => e$3(e$4)(driveId), e$6(false)], [({ srcId, targetId }) => t(srcId, targetId), e$6(false)], [({ driveId, parentId, targetId }) => e$3(e$1)(parentId) && t(targetId, driveId), e$6(false)], [({ targetId, parentId }) => t(targetId, parentId), e$6(false)], e$6(true));
3153
- function useDropNode(targetId) {
3154
- const driveId = useSelectedDriveId();
3155
- const { srcId, parentId } = useDraggingNode() ?? {};
3156
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3157
- const params = {
3158
- driveId,
3159
- parentId,
3160
- targetId,
3161
- srcId
3162
- };
3163
- function handleNodeDrop(event, cb) {
3164
- if (!isNodeDrop(params)) return;
3165
- event.preventDefault();
3166
- event.stopPropagation();
3167
- cb?.();
3168
- }
3169
- const onDragEnter = (event) => handleNodeDrop(event);
3170
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3171
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3172
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3173
- unsetDragging();
3174
- unsetTarget();
3175
- moveNodeById(params).catch(console.error);
3176
- }));
3177
- return {
3178
- isDropTarget,
3179
- onDragEnter,
3180
- onDragOver,
3181
- onDragLeave,
3182
- onDrop
3183
- };
3184
- }
3185
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3186
- graphQLReactorClientEventFunctions.useValue;
3187
- graphQLReactorClientEventFunctions.setValue;
3188
- graphQLReactorClientEventFunctions.addEventHandler;
3189
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3190
- packageDiscoveryFunctions.useValue;
3191
- packageDiscoveryFunctions.setValue;
3192
- packageDiscoveryFunctions.addEventHandler;
3193
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3194
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3195
- /** Returns the reactor client module (in-process or worker-backed) */
3196
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3197
- reactorClientModuleEventFunctions.setValue;
3198
- reactorClientModuleEventFunctions.addEventHandler;
3199
- reactorClientEventFunctions.useValue;
3200
- reactorClientEventFunctions.setValue;
3201
- reactorClientEventFunctions.addEventHandler;
3202
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3203
- const useSyncList = () => {
3204
- return useSync()?.list() ?? [];
3205
- };
3206
- const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
3207
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3208
- revisionHistoryEventFunctions.useValue;
3209
- /** Sets revision history visibility */
3210
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3211
- revisionHistoryEventFunctions.addEventHandler;
3212
- /** Shows the revision history */
3213
- function showRevisionHistory() {
3214
- setRevisionHistoryVisible(true);
3215
- }
3216
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3217
- selectedTimelineItemEventFunctions.useValue;
3218
- selectedTimelineItemEventFunctions.setValue;
3219
- selectedTimelineItemEventFunctions.addEventHandler;
3220
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3221
- selectedTimelineRevisionEventFunctions.useValue;
3222
- selectedTimelineRevisionEventFunctions.setValue;
3223
- selectedTimelineRevisionEventFunctions.addEventHandler;
3224
- const toastEventFunctions = makePHEventFunctions("toast");
3225
- /** Returns the toast function */
3226
- const usePHToast = toastEventFunctions.useValue;
3227
- toastEventFunctions.setValue;
3228
- toastEventFunctions.addEventHandler;
3229
- //#endregion
3230
- //#region ../reactor-browser/dist/switchboard-CaXQ4-5Q.js
3231
- /** Returns a document of a specific type, throws an error if the found document has a different type */
3232
- function useDocumentOfType(documentId, documentType) {
3233
- const [document, dispatch] = useDocumentById(documentId);
3234
- const documentModelModule = useDocumentModelModuleById(documentType);
3235
- if (!documentId || !documentType) return [];
3236
- if (!document) throw new Error(`Document not found: ${documentId}`);
3237
- if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3238
- if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3239
- return [document, dispatch];
3240
- }
3241
- /** Returns the selected document id */
3242
- function useSelectedDocumentId() {
3243
- const selectedNode = useSelectedNode();
3244
- return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3245
- }
3246
- /** Returns the selected document. */
3247
- function useSelectedDocumentSafe() {
3248
- return useDocumentById(useSelectedDocumentId());
3249
- }
3250
- function useSelectedDocumentOfType(documentType) {
3251
- const documentId = useSelectedDocumentId();
3252
- if (!documentType) return [];
3253
- if (!documentId) throw new NoSelectedDocumentError();
3254
- return useDocumentOfType(documentId, documentType);
3255
- }
3256
- //#endregion
3257
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
3258
- const normalizeDescriptors = (error) => {
3259
- CORE_ERROR_PROPS.forEach((propName) => {
3260
- normalizeDescriptor(error, propName);
3261
- });
3262
- };
3263
- const CORE_ERROR_PROPS = [
3264
- "name",
3265
- "message",
3266
- "stack",
3267
- "cause",
3268
- "errors"
3269
- ];
3270
- const normalizeDescriptor = (error, propName) => {
3271
- const descriptor = getDescriptor(error, propName);
3272
- if (descriptor === void 0) return;
3273
- if (isReadonlyGetter(descriptor)) {
3274
- setErrorProperty(error, propName, error[propName]);
3275
- return;
3276
- }
3277
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
3278
- };
3279
- const getDescriptor = (value, propName) => {
3280
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
3281
- if (descriptor !== void 0) return descriptor;
3282
- const prototype = Object.getPrototypeOf(value);
3283
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
3284
- };
3285
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
3286
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
3287
- const setErrorProperty = (error, propName, value) => {
3288
- setErrorDescriptor(error, propName, { value });
3289
- };
3290
- const setErrorDescriptor = (error, propName, descriptor) => {
3291
- Object.defineProperty(error, propName, {
3292
- ...descriptor,
3293
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
3294
- enumerable: false,
3295
- configurable: true
3296
- });
3297
- };
3298
- //#endregion
3299
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
3300
- const normalizeAggregate = (error, recurse) => {
3301
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
3302
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
3303
- else if (error.errors !== void 0) deleteAggregateErrors(error);
3304
- };
3305
- const isDefined = (error) => error !== void 0;
3306
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
3307
- const deleteAggregateErrors = (error) => {
3308
- delete error.errors;
3309
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
3310
- };
3311
- //#endregion
3312
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
3313
- const normalizeCause = (error, recurse) => {
3314
- if (!("cause" in error)) return;
3315
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
3316
- if (cause === void 0) delete error.cause;
3317
- else setErrorProperty(error, "cause", cause);
3318
- };
3319
- //#endregion
3320
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
3321
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
3322
- const isInstanceOfError = (value) => {
3323
- try {
3324
- return value instanceof Error;
3325
- } catch {
3326
- return false;
3327
- }
3328
- };
3329
- const hasErrorTag = (value) => {
3330
- try {
3331
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
3332
- } catch {
3333
- return false;
3334
- }
3335
- };
3336
- const ERROR_TAGS = new Set([
3337
- "[object Error]",
3338
- "[object DOMException]",
3339
- "[object DOMError]",
3340
- "[object Exception]"
3341
- ]);
3342
- //#endregion
3343
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
3344
- function isPlainObject(value) {
3345
- if (typeof value !== "object" || value === null) return false;
3346
- const prototype = Object.getPrototypeOf(value);
3347
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3348
- }
3349
- //#endregion
3350
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
3351
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
3352
- const isNonConfigurableProp = (error, propName) => {
3353
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
3354
- return descriptor !== void 0 && !descriptor.configurable;
3355
- };
3356
- const isThrowingProp = (error, propName) => {
3357
- try {
3358
- error[propName];
3359
- return false;
3360
- } catch {
3361
- return true;
3362
- }
3363
- };
3364
- //#endregion
3365
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
3366
- const setStack = (error) => {
3367
- setErrorProperty(error, "stack", getStack(error.message, error.name));
3368
- };
3369
- const getStack = (message = "", name = "Error") => {
3370
- const { stack } = new (getErrorClass(name))(message);
3371
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
3372
- };
3373
- const getErrorClass = (name) => {
3374
- const descriptor = {
3375
- value: name,
3376
- enumerable: false,
3377
- writable: true,
3378
- configurable: true
3379
- };
3380
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
3381
- Object.defineProperty(StackError.prototype, "name", descriptor);
3382
- return StackError;
3383
- };
3384
- //#endregion
3385
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
3386
- const copyObject = (object) => {
3387
- const objectCopy = {};
3388
- for (const propName of getPropsToCopy(object)) try {
3389
- const value = object[propName];
3390
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
3391
- Object.defineProperty(objectCopy, propName, {
3392
- value,
3393
- enumerable,
3394
- configurable,
3395
- writable
3396
- });
3397
- } catch {}
3398
- return objectCopy;
3399
- };
3400
- const getPropsToCopy = (object) => {
3401
- const propNames = getOwnKeys(object);
3402
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
3403
- return propNames;
3404
- };
3405
- const getOwnKeys = (object) => {
3406
- try {
3407
- return Reflect.ownKeys(object);
3408
- } catch {
3409
- return [];
3410
- }
3411
- };
3412
- const isInheritedProp = (object, propName) => {
3413
- try {
3414
- return propName in object && !Object.hasOwn(object, propName);
3415
- } catch {
3416
- return false;
3417
- }
3418
- };
3419
- //#endregion
3420
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
3421
- const objectifyError = (object) => {
3422
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
3423
- const messageA = getMessage(message, objectA);
3424
- const error = newError(name, messageA);
3425
- if (message === messageA) assignObjectProps(error, objectA);
3426
- Object.entries({
3427
- name,
3428
- stack,
3429
- cause,
3430
- errors
3431
- }).forEach(([propName, propValue]) => {
3432
- setNewErrorProperty(error, propName, propValue);
3433
- });
3434
- if (stack === void 0) setStack(error);
3435
- return error;
3436
- };
3437
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
3438
- const safeJsonStringify = (object) => {
3439
- try {
3440
- return JSON.stringify(object);
3441
- } catch {
3442
- return safeStringify(object);
3443
- }
3444
- };
3445
- const safeStringify = (object) => {
3446
- try {
3447
- return String(object);
3448
- } catch {
3449
- return "Invalid error";
3450
- }
3451
- };
3452
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
3453
- const MESSAGE_MAX_SIZE = 1e3;
3454
- const newError = (name, message) => {
3455
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
3456
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
3457
- return new Error(message);
3458
- };
3459
- const NATIVE_ERRORS = {
3460
- Error,
3461
- ReferenceError,
3462
- TypeError,
3463
- SyntaxError,
3464
- RangeError,
3465
- URIError,
3466
- EvalError
3467
- };
3468
- const assignObjectProps = (error, object) => {
3469
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3470
- };
3471
- const setNewErrorProperty = (error, propName, propValue) => {
3472
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3473
- };
3474
- //#endregion
3475
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3476
- const stringifyError = (value) => {
3477
- try {
3478
- const error = new Error(String(value));
3479
- setStack(error);
3480
- return error;
3481
- } catch (error_) {
3482
- return error_;
3483
- }
3484
- };
3485
- //#endregion
3486
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3487
- const { toString: objectToString } = Object.prototype;
3488
- const createError = (value) => {
3489
- if (isErrorPlainObj(value)) return objectifyError(value);
3490
- if (!isErrorInstance(value)) return stringifyError(value);
3491
- if (isInvalidError(value)) return objectifyError(value);
3492
- return value;
3493
- };
3494
- const isErrorPlainObj = (value) => {
3495
- try {
3496
- return isPlainObject(value);
3497
- } catch {
3498
- return false;
3499
- }
3500
- };
3501
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3502
- const isProxy = (value) => {
3503
- try {
3504
- return objectToString.call(value) === "[object Object]";
3505
- } catch {
3506
- return true;
3507
- }
3508
- };
3509
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3510
- //#endregion
3511
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3512
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3513
- const recurseException = (error, parents, shallow) => {
3514
- if (parents.includes(error)) return;
3515
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3516
- const errorA = createError(error);
3517
- normalizeProps(errorA, recurse);
3518
- return errorA;
3519
- };
3520
- const identity = (error) => error;
3521
- const normalizeProps = (error, recurse) => {
3522
- normalizeName(error);
3523
- normalizeMessage(error);
3524
- normalizeStack(error);
3525
- normalizeCause(error, recurse);
3526
- normalizeAggregate(error, recurse);
3527
- normalizeDescriptors(error);
3528
- };
3529
- const normalizeName = (error) => {
3530
- if (isDefinedString(error.name)) return;
3531
- const prototypeName = Object.getPrototypeOf(error).name;
3532
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3533
- };
3534
- const normalizeMessage = (error) => {
3535
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3536
- };
3537
- const normalizeStack = (error) => {
3538
- if (!isDefinedString(error.stack)) setStack(error);
3539
- };
3540
- const isDefinedString = (value) => typeof value === "string" && value !== "";
3541
- //#endregion
3542
- //#region ../reactor-browser/dist/index.js
3543
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3544
- var LZString = (function() {
3545
- var f = String.fromCharCode;
3546
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3547
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3548
- var baseReverseDic = {};
3549
- function getBaseValue(alphabet, character) {
3550
- if (!baseReverseDic[alphabet]) {
3551
- baseReverseDic[alphabet] = {};
3552
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3553
- }
3554
- return baseReverseDic[alphabet][character];
3555
- }
3556
- var LZString = {
3557
- compressToBase64: function(input) {
3558
- if (input == null) return "";
3559
- var res = LZString._compress(input, 6, function(a) {
3560
- return keyStrBase64.charAt(a);
3561
- });
3562
- switch (res.length % 4) {
3563
- default:
3564
- case 0: return res;
3565
- case 1: return res + "===";
3566
- case 2: return res + "==";
3567
- case 3: return res + "=";
3568
- }
3569
- },
3570
- decompressFromBase64: function(input) {
3571
- if (input == null) return "";
3572
- if (input == "") return null;
3573
- return LZString._decompress(input.length, 32, function(index) {
3574
- return getBaseValue(keyStrBase64, input.charAt(index));
3575
- });
3576
- },
3577
- compressToUTF16: function(input) {
3578
- if (input == null) return "";
3579
- return LZString._compress(input, 15, function(a) {
3580
- return f(a + 32);
3581
- }) + " ";
3582
- },
3583
- decompressFromUTF16: function(compressed) {
3584
- if (compressed == null) return "";
3585
- if (compressed == "") return null;
3586
- return LZString._decompress(compressed.length, 16384, function(index) {
3587
- return compressed.charCodeAt(index) - 32;
3588
- });
3589
- },
3590
- compressToUint8Array: function(uncompressed) {
3591
- var compressed = LZString.compress(uncompressed);
3592
- var buf = new Uint8Array(compressed.length * 2);
3593
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3594
- var current_value = compressed.charCodeAt(i);
3595
- buf[i * 2] = current_value >>> 8;
3596
- buf[i * 2 + 1] = current_value % 256;
3597
- }
3598
- return buf;
3599
- },
3600
- decompressFromUint8Array: function(compressed) {
3601
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3602
- else {
3603
- var buf = new Array(compressed.length / 2);
3604
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3605
- var result = [];
3606
- buf.forEach(function(c) {
3607
- result.push(f(c));
3608
- });
3609
- return LZString.decompress(result.join(""));
3610
- }
3611
- },
3612
- compressToEncodedURIComponent: function(input) {
3613
- if (input == null) return "";
3614
- return LZString._compress(input, 6, function(a) {
3615
- return keyStrUriSafe.charAt(a);
3616
- });
3617
- },
3618
- decompressFromEncodedURIComponent: function(input) {
3619
- if (input == null) return "";
3620
- if (input == "") return null;
3621
- input = input.replace(/ /g, "+");
3622
- return LZString._decompress(input.length, 32, function(index) {
3623
- return getBaseValue(keyStrUriSafe, input.charAt(index));
3624
- });
3625
- },
3626
- compress: function(uncompressed) {
3627
- return LZString._compress(uncompressed, 16, function(a) {
3628
- return f(a);
3629
- });
3630
- },
3631
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3632
- if (uncompressed == null) return "";
3633
- var i, value, context_dictionary = {}, context_dictionaryToCreate = {}, context_c = "", context_wc = "", context_w = "", context_enlargeIn = 2, context_dictSize = 3, context_numBits = 2, context_data = [], context_data_val = 0, context_data_position = 0, ii;
3634
- for (ii = 0; ii < uncompressed.length; ii += 1) {
3635
- context_c = uncompressed.charAt(ii);
3636
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3637
- context_dictionary[context_c] = context_dictSize++;
3638
- context_dictionaryToCreate[context_c] = true;
3639
- }
3640
- context_wc = context_w + context_c;
3641
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3642
- else {
3643
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3644
- if (context_w.charCodeAt(0) < 256) {
3645
- for (i = 0; i < context_numBits; i++) {
3646
- context_data_val = context_data_val << 1;
3647
- if (context_data_position == bitsPerChar - 1) {
3648
- context_data_position = 0;
3649
- context_data.push(getCharFromInt(context_data_val));
3650
- context_data_val = 0;
3651
- } else context_data_position++;
3652
- }
3653
- value = context_w.charCodeAt(0);
3654
- for (i = 0; i < 8; i++) {
3655
- context_data_val = context_data_val << 1 | value & 1;
3656
- if (context_data_position == bitsPerChar - 1) {
3657
- context_data_position = 0;
3658
- context_data.push(getCharFromInt(context_data_val));
3659
- context_data_val = 0;
3660
- } else context_data_position++;
3661
- value = value >> 1;
3662
- }
3663
- } else {
3664
- value = 1;
3665
- for (i = 0; i < context_numBits; i++) {
3666
- context_data_val = context_data_val << 1 | value;
3667
- if (context_data_position == bitsPerChar - 1) {
3668
- context_data_position = 0;
3669
- context_data.push(getCharFromInt(context_data_val));
3670
- context_data_val = 0;
3671
- } else context_data_position++;
3672
- value = 0;
3673
- }
3674
- value = context_w.charCodeAt(0);
3675
- for (i = 0; i < 16; i++) {
3676
- context_data_val = context_data_val << 1 | value & 1;
3677
- if (context_data_position == bitsPerChar - 1) {
3678
- context_data_position = 0;
3679
- context_data.push(getCharFromInt(context_data_val));
3680
- context_data_val = 0;
3681
- } else context_data_position++;
3682
- value = value >> 1;
3683
- }
3684
- }
3685
- context_enlargeIn--;
3686
- if (context_enlargeIn == 0) {
3687
- context_enlargeIn = Math.pow(2, context_numBits);
3688
- context_numBits++;
3689
- }
3690
- delete context_dictionaryToCreate[context_w];
3691
- } else {
3692
- value = context_dictionary[context_w];
3693
- for (i = 0; i < context_numBits; i++) {
3694
- context_data_val = context_data_val << 1 | value & 1;
3695
- if (context_data_position == bitsPerChar - 1) {
3696
- context_data_position = 0;
3697
- context_data.push(getCharFromInt(context_data_val));
3698
- context_data_val = 0;
3699
- } else context_data_position++;
3700
- value = value >> 1;
3701
- }
3702
- }
3703
- context_enlargeIn--;
3704
- if (context_enlargeIn == 0) {
3705
- context_enlargeIn = Math.pow(2, context_numBits);
3706
- context_numBits++;
3707
- }
3708
- context_dictionary[context_wc] = context_dictSize++;
3709
- context_w = String(context_c);
3710
- }
3711
- }
3712
- if (context_w !== "") {
3713
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3714
- if (context_w.charCodeAt(0) < 256) {
3715
- for (i = 0; i < context_numBits; i++) {
3716
- context_data_val = context_data_val << 1;
3717
- if (context_data_position == bitsPerChar - 1) {
3718
- context_data_position = 0;
3719
- context_data.push(getCharFromInt(context_data_val));
3720
- context_data_val = 0;
3721
- } else context_data_position++;
3722
- }
3723
- value = context_w.charCodeAt(0);
3724
- for (i = 0; i < 8; i++) {
3725
- context_data_val = context_data_val << 1 | value & 1;
3726
- if (context_data_position == bitsPerChar - 1) {
3727
- context_data_position = 0;
3728
- context_data.push(getCharFromInt(context_data_val));
3729
- context_data_val = 0;
3730
- } else context_data_position++;
3731
- value = value >> 1;
3732
- }
3733
- } else {
3734
- value = 1;
3735
- for (i = 0; i < context_numBits; i++) {
3736
- context_data_val = context_data_val << 1 | value;
3737
- if (context_data_position == bitsPerChar - 1) {
3738
- context_data_position = 0;
3739
- context_data.push(getCharFromInt(context_data_val));
3740
- context_data_val = 0;
3741
- } else context_data_position++;
3742
- value = 0;
3743
- }
3744
- value = context_w.charCodeAt(0);
3745
- for (i = 0; i < 16; i++) {
3746
- context_data_val = context_data_val << 1 | value & 1;
3747
- if (context_data_position == bitsPerChar - 1) {
3748
- context_data_position = 0;
3749
- context_data.push(getCharFromInt(context_data_val));
3750
- context_data_val = 0;
3751
- } else context_data_position++;
3752
- value = value >> 1;
3753
- }
3754
- }
3755
- context_enlargeIn--;
3756
- if (context_enlargeIn == 0) {
3757
- context_enlargeIn = Math.pow(2, context_numBits);
3758
- context_numBits++;
3759
- }
3760
- delete context_dictionaryToCreate[context_w];
3761
- } else {
3762
- value = context_dictionary[context_w];
3763
- for (i = 0; i < context_numBits; i++) {
3764
- context_data_val = context_data_val << 1 | value & 1;
3765
- if (context_data_position == bitsPerChar - 1) {
3766
- context_data_position = 0;
3767
- context_data.push(getCharFromInt(context_data_val));
3768
- context_data_val = 0;
3769
- } else context_data_position++;
3770
- value = value >> 1;
3771
- }
3772
- }
3773
- context_enlargeIn--;
3774
- if (context_enlargeIn == 0) {
3775
- context_enlargeIn = Math.pow(2, context_numBits);
3776
- context_numBits++;
3777
- }
3778
- }
3779
- value = 2;
3780
- for (i = 0; i < context_numBits; i++) {
3781
- context_data_val = context_data_val << 1 | value & 1;
3782
- if (context_data_position == bitsPerChar - 1) {
3783
- context_data_position = 0;
3784
- context_data.push(getCharFromInt(context_data_val));
3785
- context_data_val = 0;
3786
- } else context_data_position++;
3787
- value = value >> 1;
3788
- }
3789
- while (true) {
3790
- context_data_val = context_data_val << 1;
3791
- if (context_data_position == bitsPerChar - 1) {
3792
- context_data.push(getCharFromInt(context_data_val));
3793
- break;
3794
- } else context_data_position++;
3795
- }
3796
- return context_data.join("");
3797
- },
3798
- decompress: function(compressed) {
3799
- if (compressed == null) return "";
3800
- if (compressed == "") return null;
3801
- return LZString._decompress(compressed.length, 32768, function(index) {
3802
- return compressed.charCodeAt(index);
3803
- });
3804
- },
3805
- _decompress: function(length, resetValue, getNextValue) {
3806
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3807
- val: getNextValue(0),
3808
- position: resetValue,
3809
- index: 1
3810
- };
3811
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
3812
- bits = 0;
3813
- maxpower = Math.pow(2, 2);
3814
- power = 1;
3815
- while (power != maxpower) {
3816
- resb = data.val & data.position;
3817
- data.position >>= 1;
3818
- if (data.position == 0) {
3819
- data.position = resetValue;
3820
- data.val = getNextValue(data.index++);
3821
- }
3822
- bits |= (resb > 0 ? 1 : 0) * power;
3823
- power <<= 1;
3824
- }
3825
- switch (bits) {
3826
- case 0:
3827
- bits = 0;
3828
- maxpower = Math.pow(2, 8);
3829
- power = 1;
3830
- while (power != maxpower) {
3831
- resb = data.val & data.position;
3832
- data.position >>= 1;
3833
- if (data.position == 0) {
3834
- data.position = resetValue;
3835
- data.val = getNextValue(data.index++);
3836
- }
3837
- bits |= (resb > 0 ? 1 : 0) * power;
3838
- power <<= 1;
3839
- }
3840
- c = f(bits);
3841
- break;
3842
- case 1:
3843
- bits = 0;
3844
- maxpower = Math.pow(2, 16);
3845
- power = 1;
3846
- while (power != maxpower) {
3847
- resb = data.val & data.position;
3848
- data.position >>= 1;
3849
- if (data.position == 0) {
3850
- data.position = resetValue;
3851
- data.val = getNextValue(data.index++);
3852
- }
3853
- bits |= (resb > 0 ? 1 : 0) * power;
3854
- power <<= 1;
3855
- }
3856
- c = f(bits);
3857
- break;
3858
- case 2: return "";
3859
- }
3860
- dictionary[3] = c;
3861
- w = c;
3862
- result.push(c);
3863
- while (true) {
3864
- if (data.index > length) return "";
3865
- bits = 0;
3866
- maxpower = Math.pow(2, numBits);
3867
- power = 1;
3868
- while (power != maxpower) {
3869
- resb = data.val & data.position;
3870
- data.position >>= 1;
3871
- if (data.position == 0) {
3872
- data.position = resetValue;
3873
- data.val = getNextValue(data.index++);
3874
- }
3875
- bits |= (resb > 0 ? 1 : 0) * power;
3876
- power <<= 1;
3877
- }
3878
- switch (c = bits) {
3879
- case 0:
3880
- bits = 0;
3881
- maxpower = Math.pow(2, 8);
3882
- power = 1;
3883
- while (power != maxpower) {
3884
- resb = data.val & data.position;
3885
- data.position >>= 1;
3886
- if (data.position == 0) {
3887
- data.position = resetValue;
3888
- data.val = getNextValue(data.index++);
3889
- }
3890
- bits |= (resb > 0 ? 1 : 0) * power;
3891
- power <<= 1;
3892
- }
3893
- dictionary[dictSize++] = f(bits);
3894
- c = dictSize - 1;
3895
- enlargeIn--;
3896
- break;
3897
- case 1:
3898
- bits = 0;
3899
- maxpower = Math.pow(2, 16);
3900
- power = 1;
3901
- while (power != maxpower) {
3902
- resb = data.val & data.position;
3903
- data.position >>= 1;
3904
- if (data.position == 0) {
3905
- data.position = resetValue;
3906
- data.val = getNextValue(data.index++);
3907
- }
3908
- bits |= (resb > 0 ? 1 : 0) * power;
3909
- power <<= 1;
3910
- }
3911
- dictionary[dictSize++] = f(bits);
3912
- c = dictSize - 1;
3913
- enlargeIn--;
3914
- break;
3915
- case 2: return result.join("");
3916
- }
3917
- if (enlargeIn == 0) {
3918
- enlargeIn = Math.pow(2, numBits);
3919
- numBits++;
3920
- }
3921
- if (dictionary[c]) entry = dictionary[c];
3922
- else if (c === dictSize) entry = w + w.charAt(0);
3923
- else return null;
3924
- result.push(entry);
3925
- dictionary[dictSize++] = w + entry.charAt(0);
3926
- enlargeIn--;
3927
- w = entry;
3928
- if (enlargeIn == 0) {
3929
- enlargeIn = Math.pow(2, numBits);
3930
- numBits++;
3931
- }
3932
- }
3933
- }
3934
- };
3935
- return LZString;
3936
- })();
3937
- if (typeof define === "function" && define.amd) define(function() {
3938
- return LZString;
3939
- });
3940
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3941
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3942
- return LZString;
3943
- });
3944
- })))(), 1);
3945
- const sanitize = (segment) => segment.replace(/\//g, "-");
3946
- /**
3947
- * Name segments from the exported folder (exclusive) down to `node`
3948
- * (inclusive), in top-down order. `root === undefined` means the drive root:
3949
- * all ancestors. A node that IS the exported folder yields no segments.
3950
- */
3951
- function segmentsBelow(root, node, allNodes) {
3952
- const segments = [];
3953
- let current = node;
3954
- while (current && current.id !== root?.id) {
3955
- segments.push(sanitize(current.name));
3956
- const parentId = current.parentFolder;
3957
- current = parentId ? allNodes.find((n) => n.id === parentId) : void 0;
3958
- }
3959
- return segments.reverse();
3960
- }
3961
- /**
3962
- * Assemble the archive zip for a folder (or the whole drive when
3963
- * `folderNode` is undefined). Every folder in the subtree becomes a
3964
- * directory entry (empty folders survive); every file becomes a standard
3965
- * single-document zip named after the node (drive naming convention:
3966
- * `${name}.${extension}.phd`, ` (copy) N` on a same-folder collision).
3967
- *
3968
- * `fetchDocument` must return the document WITH its full operations and
3969
- * initialState (see downloadFolderZip).
3970
- */
3971
- async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
3972
- const allNodes = drive.state.global.nodes;
3973
- const topName = sanitize(folderNode?.name ?? (drive.state.global.name || drive.header.name));
3974
- const subtree = folderNode ? [folderNode, ...getDescendants(folderNode, allNodes)] : allNodes;
3975
- const entries = { [topName + "/"]: new Uint8Array(0) };
3976
- for (const node of subtree) {
3977
- if (!isFolderNode(node)) continue;
3978
- const dir = [topName, ...segmentsBelow(folderNode, node, allNodes)].join("/");
3979
- entries[dir + "/"] = new Uint8Array(0);
3980
- }
3981
- const files = subtree.filter(isFileNode);
3982
- const failed = [];
3983
- const usedNamesByDir = /* @__PURE__ */ new Map();
3984
- let done = 0;
3985
- for (const node of files) try {
3986
- const doc = await fetchDocument(node.id);
3987
- const extension = await getDocumentExtension(doc);
3988
- const parent = node.parentFolder ? allNodes.find((n) => n.id === node.parentFolder) : void 0;
3989
- const dir = [topName, ...parent ? segmentsBelow(folderNode, parent, allNodes) : []].join("/");
3990
- let usedNames = usedNamesByDir.get(dir);
3991
- if (!usedNames) {
3992
- usedNames = /* @__PURE__ */ new Set();
3993
- usedNamesByDir.set(dir, usedNames);
3994
- }
3995
- const base = sanitize(node.name);
3996
- let candidate = base;
3997
- let count = getNextCopyNumber([...usedNames], base);
3998
- while (usedNames.has(candidate)) {
3999
- candidate = `${base} (copy) ${count}`;
4000
- count += 1;
4001
- }
4002
- usedNames.add(candidate);
4003
- const leaf = extension ? `${candidate}.${extension}.phd` : `${candidate}.phd`;
4004
- entries[`${dir}/${leaf}`] = await createZip(doc);
4005
- } catch {
4006
- failed.push(node.name);
4007
- } finally {
4008
- done += 1;
4009
- onProgress?.(done, files.length);
4010
- }
4011
- return {
4012
- zip: await zipEntries(entries),
4013
- archiveName: `${topName}.zip`,
4014
- entryCount: files.length - failed.length,
4015
- failed
4016
- };
4017
- }
4018
- /**
4019
- * Export a folder (or whole drive) to disk: fetches every document with its
4020
- * full operation history, builds the archive, and saves it via
4021
- * showSaveFilePicker (fallback: blob download), mirroring exportFile.
4022
- */
4023
- async function downloadFolderZip(drive, folderNode, onProgress) {
4024
- const reactorClient = window.ph?.reactorClient;
4025
- if (!reactorClient) throw new Error("ReactorClient not initialized");
4026
- const result = await buildFolderZip(drive, folderNode, async (id) => {
4027
- const doc = await reactorClient.get(id);
4028
- const operations = await fetchDocumentOperations(reactorClient, doc);
4029
- const initialState = extractInitialState(operations["document"] ?? []);
4030
- return {
4031
- ...doc,
4032
- operations,
4033
- initialState
4034
- };
4035
- }, onProgress);
4036
- if (!window.showSaveFilePicker) {
4037
- const blob = new Blob([new Uint8Array(result.zip)], { type: "application/zip" });
4038
- const link = window.document.createElement("a");
4039
- link.style.display = "none";
4040
- link.href = URL.createObjectURL(blob);
4041
- link.download = result.archiveName;
4042
- window.document.body.appendChild(link);
4043
- link.click();
4044
- window.document.body.removeChild(link);
4045
- return result;
4046
- }
4047
- try {
4048
- const writable = await (await window.showSaveFilePicker({ suggestedName: result.archiveName })).createWritable();
4049
- await writable.write(new Uint8Array(result.zip));
4050
- await writable.close();
4051
- } catch (e) {
4052
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
4053
- }
4054
- return result;
4055
- }
4056
- /** Document types that represent a "drive": a container of nodes. */
4057
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
4058
- function useAllowedDocumentModelModules() {
4059
- const documentModelModules = useDocumentModelModules();
4060
- const allowedDocumentTypes = useAllowedDocumentTypes();
4061
- if (!allowedDocumentTypes?.length) return documentModelModules;
4062
- return documentModelModules?.filter((module) => allowedDocumentTypes.includes(module.documentModel.global.id));
4063
- }
4064
- /** Returns the selected folder. */
4065
- function useSelectedFolder() {
4066
- const selectedNode = useSelectedNode();
4067
- if (isFolderNodeKind(selectedNode)) return selectedNode;
4068
- }
4069
- /** Returns the child nodes for the selected drive or folder. */
4070
- function useNodesInSelectedDriveOrFolder() {
4071
- const nodes = useNodesInSelectedDrive();
4072
- const selectedFolderId = useSelectedFolder()?.id;
4073
- if (!nodes) return [];
4074
- if (!selectedFolderId) return sortNodesByName(nodes.filter((n) => !n.parentFolder));
4075
- return sortNodesByName(nodes.filter((n) => n.parentFolder === selectedFolderId));
4076
- }
4077
- function callGlobalSetterForKey(key, value) {
4078
- const setter = phGlobalConfigSetters[key];
4079
- setter(value);
4080
- }
4081
- /** Sets the global drive config.
4082
- *
4083
- * Pass in a partial object of the global drive config to set.
4084
- */
4085
- function setPHAppConfig(config) {
4086
- for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
4087
- }
4088
- /** Sets the global document config.
4089
- *
4090
- * Pass in a partial object of the global document config to set.
4091
- */
4092
- function setPHDocumentEditorConfig(config) {
4093
- for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
4094
- }
4095
- /** Wrapper hook for setting the global app config.
4096
- *
4097
- * Automatically sets the global app config when the component mounts.
4098
- *
4099
- * Pass in a partial object of the global app config to set.
4100
- */
4101
- function useSetPHAppConfig(config) {
4102
- const [isInitialized, setIsInitialized] = useState(false);
4103
- useEffect(() => {
4104
- if (isInitialized) return;
4105
- setPHAppConfig(config);
4106
- setIsInitialized(true);
4107
- }, [config, isInitialized]);
4108
- }
4109
- /** Wrapper hook for setting the global document editor config.
4110
- *
4111
- * Automatically sets the global document editor config when the component mounts.
4112
- *
4113
- * Pass in a partial object of the global document editor config to set.
4114
- */
4115
- function useSetPHDocumentEditorConfig(config) {
4116
- const [isInitialized, setIsInitialized] = useState(false);
4117
- useEffect(() => {
4118
- if (isInitialized) return;
4119
- setPHDocumentEditorConfig(config);
4120
- setIsInitialized(true);
4121
- }, [config, isInitialized]);
4122
- }
4123
- /**
4124
- * Classifies a document's model version against the installed module
4125
- * versions. Pure logic, extracted for testing.
4126
- */
4127
- function getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {
4128
- if (availableVersions.length === 0) return;
4129
- const sorted = [...availableVersions].sort((a, b) => a - b);
4130
- const latestVersion = sorted[sorted.length - 1];
4131
- if (documentVersion > latestVersion) return {
4132
- kind: "unsupported",
4133
- documentVersion,
4134
- availableVersions: sorted
4135
- };
4136
- if (documentVersion === latestVersion) return {
4137
- kind: "current",
4138
- documentVersion
4139
- };
4140
- return {
4141
- kind: "upgrade-available",
4142
- documentVersion,
4143
- latestVersion,
4144
- canUpgrade: hasUpgradePath(documentVersion, latestVersion)
4145
- };
4146
- }
4147
- /**
4148
- * Compares the given document's model version against the versions available
4149
- * from installed Vetra packages. Returns undefined while packages load or
4150
- * when the document type has no installed modules.
4151
- */
4152
- function useDocumentVersionStatus(document) {
4153
- const modules = useDocumentModelModules();
4154
- const registry = useModelRegistry();
4155
- if (!document || !modules) return;
4156
- const documentType = document.header.documentType;
4157
- return getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {
4158
- if (!registry) return false;
4159
- try {
4160
- registry.computeUpgradePath(documentType, fromVersion, toVersion);
4161
- return true;
4162
- } catch {
4163
- return false;
4164
- }
4165
- });
4166
- }
4167
- const validateDocument = (document) => {
4168
- const errors = [];
4169
- if (document.header.documentType !== "powerhouse/document-model") return errors;
4170
- const doc = document;
4171
- const specs = doc.state.global.specifications[0];
4172
- const initialStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
4173
- const scope = scopeKey;
4174
- return [...acc, ...validateInitialState(specs.state[scope].initialValue, scope !== "global").map((err) => ({
4175
- ...err,
4176
- message: `${err.message}. Scope: ${scope}`,
4177
- details: {
4178
- ...err.details,
4179
- scope
4180
- }
4181
- }))];
4182
- }, []);
4183
- const schemaStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
4184
- const scope = scopeKey;
4185
- const isGlobalScope = scope === "global";
4186
- return [...acc, ...validateStateSchemaName(specs.state[scope].schema, doc.state.global?.name || doc.header.name || "", !isGlobalScope ? scope : "", !isGlobalScope).map((err) => ({
4187
- ...err,
4188
- message: `${err.message}. Scope: ${scope}`,
4189
- details: {
4190
- ...err.details,
4191
- scope
4192
- }
4193
- }))];
4194
- }, []);
4195
- const modulesErrors = validateModules(specs.modules);
4196
- return [
4197
- ...initialStateErrors,
4198
- ...schemaStateErrors,
4199
- ...modulesErrors
4200
- ];
4201
- };
4202
- function defaultHandleError(error) {
4203
- console.error(`Failed to export document: ${error.message}`);
4204
- }
4205
- function handleDocumentValidation(document) {
4206
- if (t$2(validateDocument(document), 1)) return false;
4207
- return true;
4208
- }
4209
- function downloadDocument(document, handleError = defaultHandleError) {
4210
- if (!document) return;
4211
- if (!handleDocumentValidation(document)) {
4212
- showPHModal({
4213
- type: "downloadDocumentWithErrors",
4214
- documentId: document.header.id
4215
- });
4216
- return;
4217
- }
4218
- exportFile(document).catch((error) => handleError(normalizeException(error)));
4219
- }
4220
- function useDownloadDocument(id) {
4221
- const getDocument = useGetDocument();
4222
- const toast = usePHToast();
4223
- return async () => {
4224
- if (!id) return;
4225
- const handleError = (error) => toast?.(`Failed to export document: ${error.message}`);
4226
- try {
4227
- downloadDocument(await getDocument(id), handleError);
4228
- } catch (error) {
4229
- handleError(error);
4230
- }
4231
- };
4232
- }
4233
- /**
4234
- * Downloads the selected drive's folder (or the whole drive when no folder
4235
- * is given) as a single zip archive mirroring the folder tree.
4236
- */
4237
- function useDownloadFolder(folderNode) {
4238
- const [selectedDrive] = useSelectedDriveSafe();
4239
- const toast = usePHToast();
4240
- return async () => {
4241
- if (!selectedDrive) return;
4242
- const name = folderNode?.name ?? selectedDrive.header.name;
4243
- toast?.(`Downloading "${name}"…`);
4244
- try {
4245
- const { entryCount, failed } = await downloadFolderZip(selectedDrive, folderNode);
4246
- toast?.(failed.length ? `Downloaded ${entryCount} files (${failed.length} failed)` : `Downloaded ${entryCount} files`);
4247
- } catch (error) {
4248
- toast?.(`Failed to download "${name}": ${error.message}`);
4249
- }
4250
- };
4251
- }
4252
- /** An editor is a drive "app" if it targets any supported drive document type. */
4253
- function isDriveEditor(module) {
4254
- const driveTypes = DRIVE_DOCUMENT_TYPES;
4255
- return module.documentTypes.some((t) => driveTypes.includes(t));
4256
- }
4257
- function useEditorModules() {
4258
- return useVetraPackages().flatMap((pkg) => pkg.editors).filter((module) => !isDriveEditor(module));
4259
- }
4260
- function useEditorModulesForDocumentType(documentType) {
4261
- const editorModules = useEditorModules();
4262
- if (!documentType) return void 0;
4263
- return editorModules?.filter((module) => module.documentTypes.includes(documentType));
4264
- }
4265
- function preloadEditorModule(module) {
4266
- const Component = module.Component;
4267
- if (typeof Component.preload === "function") return Component.preload();
4268
- const payload = Component._payload;
4269
- const init = Component._init;
4270
- if (!payload || typeof init !== "function") return void 0;
4271
- try {
4272
- init(payload);
4273
- } catch (thrown) {
4274
- if (thrown && typeof thrown.then === "function") return thrown;
4275
- }
4276
- }
4277
- function useFolderById(id) {
4278
- return useFolderNodesInSelectedDrive()?.find((n) => n.id === id);
4279
- }
4280
- function resolveNode(driveId, node) {
4281
- return node?.id !== driveId ? node : void 0;
4282
- }
4283
- function useNodeActions() {
4284
- const [selectedDrive] = useSelectedDriveSafe();
4285
- const selectedFolder = useSelectedFolder();
4286
- const selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);
4287
- const selectedDriveId = selectedDrive?.header.id;
4288
- const drives = useDrives();
4289
- async function onAddFile(file, parent) {
4290
- if (!selectedDriveId) return;
4291
- return addFileWithProgress(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id, void 0, void 0, "duplicate");
4292
- }
4293
- async function onAddFolder(name, parent) {
4294
- if (!selectedDriveId) return;
4295
- return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
4296
- }
4297
- async function onRenameNode(newName, node) {
4298
- if (!selectedDriveId) return;
4299
- if (!resolveNode(selectedDriveId, node)) {
4300
- console.error(`Node ${node.id} not found`);
4301
- return;
4302
- }
4303
- return await renameNode(selectedDriveId, node.id, newName);
4304
- }
4305
- async function onCopyNode(src, target) {
4306
- if (!selectedDriveId) return;
4307
- const resolvedSrc = resolveNode(selectedDriveId, src);
4308
- if (!resolvedSrc) {
4309
- console.error(`Node ${src.id} not found`);
4310
- return;
4311
- }
4312
- await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));
4313
- }
4314
- async function onMoveNode(src, target) {
4315
- if (!selectedDriveId) return;
4316
- const resolvedSrc = resolveNode(selectedDriveId, src);
4317
- if (!resolvedSrc) {
4318
- console.error(`Node ${src.id} not found`);
4319
- return;
4320
- }
4321
- const resolvedTarget = resolveNode(selectedDriveId, target);
4322
- if (!resolvedTarget?.id && !src.parentFolder || resolvedTarget?.id === src.parentFolder) return;
4323
- await moveNode$1(selectedDriveId, resolvedSrc, resolvedTarget);
4324
- }
4325
- async function onDuplicateNode(src) {
4326
- if (!selectedDriveId) return;
4327
- const resolvedSrc = resolveNode(selectedDriveId, src);
4328
- if (!resolvedSrc) {
4329
- console.error(`Node ${src.id} not found`);
4330
- return;
4331
- }
4332
- await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));
4333
- }
4334
- async function onAddAndSelectNewFolder(name) {
4335
- if (!name) return;
4336
- if (!selectedDriveId) return;
4337
- const resolvedTarget = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);
4338
- if (!resolvedTarget) return;
4339
- const newFolder = await onAddFolder(name, resolvedTarget);
4340
- if (newFolder) setSelectedNode(newFolder);
4341
- }
4342
- async function onRenameDriveNodes(newName, nodeId) {
4343
- if (!drives) return;
4344
- const drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));
4345
- await Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));
4346
- }
4347
- return {
4348
- onAddFile,
4349
- onAddFolder,
4350
- onRenameNode,
4351
- onCopyNode,
4352
- onMoveNode,
4353
- onDuplicateNode,
4354
- onAddAndSelectNewFolder,
4355
- onRenameDriveNodes
4356
- };
4357
- }
4358
- /** Returns a node in the selected drive by id. */
4359
- function useNodeById(id) {
4360
- return useNodesInSelectedDrive()?.find((n) => n.id === id);
4361
- }
4362
- /** Returns the path to a node in the selected drive */
4363
- function useNodePathById(id) {
4364
- const nodes = useNodesInSelectedDrive();
4365
- if (!nodes) return [];
4366
- const path = [];
4367
- let current = nodes.find((n) => n.id === id);
4368
- while (current) {
4369
- path.push(current);
4370
- if (!current.parentFolder) break;
4371
- current = nodes.find((n) => n.id === current?.parentFolder);
4372
- }
4373
- return path.reverse();
4374
- }
4375
- /** Returns the path to the currently selected node in the selected drive. */
4376
- function useSelectedNodePath() {
4377
- return useNodePathById(useSelectedNode()?.id);
4378
- }
4379
- function useNodeParentFolderById(id) {
4380
- return useFolderById(useNodeById(id)?.parentFolder);
4381
- }
4382
- function useParentFolderForSelectedNode() {
4383
- return useNodeParentFolderById(useSelectedNode()?.id);
4384
- }
4385
- const STORED_THEME_KEY = "ph:theme";
4386
- const UPDATE_STORED_THEME = "ph:updateStoredTheme";
4387
- const STORED_THEME_UPDATED = "ph:storedThemeUpdated";
4388
- const SYSTEM_THEME_UPDATED = "ph:systemThemeUpdated";
4389
- const isServer = typeof window === "undefined";
4390
- function setTheme(storedTheme) {
4391
- if (isServer) return;
4392
- const updateStoredThemeEvent = new CustomEvent(UPDATE_STORED_THEME, { detail: { storedTheme } });
4393
- window.dispatchEvent(updateStoredThemeEvent);
4394
- }
4395
- function getStoredTheme() {
4396
- if (isServer) return void 0;
4397
- return localStorage.getItem(STORED_THEME_KEY) ?? void 0;
4398
- }
4399
- function getPrefersDarkMediaQuery() {
4400
- if (isServer) return;
4401
- return window.matchMedia("(prefers-color-scheme: dark)");
4402
- }
4403
- function getPrefersDark() {
4404
- if (isServer) return false;
4405
- if (getPrefersDarkMediaQuery()?.matches) return true;
4406
- return false;
4407
- }
4408
- function getSystemTheme() {
4409
- if (isServer) return "light";
4410
- if (getPrefersDark()) return "dark";
4411
- return "light";
4412
- }
4413
- function toggleDark(isDark) {
4414
- if (isServer) return;
4415
- document.documentElement.classList.toggle("dark", isDark);
4416
- }
4417
- function subscribeToStoredTheme(onStoreChange) {
4418
- if (isServer) return () => {};
4419
- const handleStorage = (event) => {
4420
- if (event.key === STORED_THEME_KEY || event.key === null) onStoreChange();
4421
- };
4422
- window.addEventListener(STORED_THEME_UPDATED, onStoreChange);
4423
- window.addEventListener("storage", handleStorage);
4424
- return () => {
4425
- window.removeEventListener(STORED_THEME_UPDATED, onStoreChange);
4426
- window.removeEventListener("storage", handleStorage);
4427
- };
4428
- }
4429
- function subscribeToSystemTheme(onStoreChange) {
4430
- if (isServer) return () => {};
4431
- window.addEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
4432
- return () => {
4433
- window.removeEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
4434
- };
4435
- }
4436
- function useTheme() {
4437
- const storedTheme = useSyncExternalStore(subscribeToStoredTheme, () => getStoredTheme(), () => "system");
4438
- const systemTheme = useSyncExternalStore(subscribeToSystemTheme, () => getSystemTheme(), () => "light");
4439
- const isSystem = storedTheme === void 0 || storedTheme === "system";
4440
- const theme = isSystem ? systemTheme : storedTheme;
4441
- const isDark = theme === "dark";
4442
- useEffect(() => {
4443
- toggleDark(isDark);
4444
- }, [isDark]);
4445
- return {
4446
- theme,
4447
- isSystem,
4448
- setTheme
4449
- };
4450
- }
4451
- const syncStatusToUI = {
4452
- [SyncStatus.Synced]: "SUCCESS",
4453
- [SyncStatus.Outgoing]: "SYNCING",
4454
- [SyncStatus.Incoming]: "SYNCING",
4455
- [SyncStatus.OutgoingAndIncoming]: "SYNCING",
4456
- [SyncStatus.Error]: "ERROR"
4457
- };
4458
- async function getDrives(reactor) {
4459
- return (await Promise.all(DRIVE_DOCUMENT_TYPES.map((type) => reactor.find({ type })))).flatMap((r) => r.results);
4460
- }
4461
- function getSyncStatusSync(documentId, sharingType) {
4462
- if (sharingType === "LOCAL") return;
4463
- const syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
4464
- if (!syncManager) return;
4465
- const status = syncManager.getSyncStatus(documentId);
4466
- if (status === void 0) return;
4467
- return syncStatusToUI[status];
4468
- }
4469
- function getDocumentGraphqlQuery() {
4470
- const loc = GetDocumentWithOperationsDocument.loc;
4471
- if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
4472
- return loc.source.body;
4473
- }
4474
- /**
4475
- * The base URL of the switchboard that serves a drive's GraphQL channel.
4476
- *
4477
- * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the
4478
- * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does
4479
- * not end with the suffix is unexpected — fall back to its origin.
4480
- */
4481
- function getSwitchboardBaseFromChannelUrl(channelUrl) {
4482
- if (channelUrl.endsWith("/graphql/r")) return channelUrl.slice(0, -10);
4483
- return new URL(channelUrl).origin;
4484
- }
4485
- /**
4486
- * The GraphQL name the switchboard exposes a document model under. Mirrors
4487
- * `getDocumentModelSchemaName` on the server (`create-schema.ts`): the root
4488
- * query field and the state type names are all derived from the model's
4489
- * `global.name`.
4490
- */
4491
- function getDocumentModelSchemaName(model) {
4492
- return pascalCase(model.documentModel.global.name.replaceAll("/", " "));
4493
- }
4494
- function buildStateTypeMap(definitions) {
4495
- const typeMap = /* @__PURE__ */ new Map();
4496
- for (const def of definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION) typeMap.set(def.name.value, def);
4497
- return typeMap;
4498
- }
4499
- /**
4500
- * Recursively expands the fields of a state object type into a GraphQL
4501
- * selection. Objects expand their sub-selection (lists expand their item
4502
- * type); enums, scalars, and built-ins are leaves.
4503
- */
4504
- function expandStateFields(typeDef, typeMap) {
4505
- return (typeDef.fields ?? []).map((field) => {
4506
- const fieldName = field.name.value;
4507
- let typeNode = field.type;
4508
- if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE) typeNode = typeNode.type;
4509
- if (typeNode.kind === import_graphql.Kind.LIST_TYPE) {
4510
- let itemType = typeNode.type;
4511
- if (itemType.kind === import_graphql.Kind.NON_NULL_TYPE) itemType = itemType.type;
4512
- if (itemType.kind === import_graphql.Kind.LIST_TYPE) throw new Error(`Nested lists are not supported in state selections: ${fieldName}`);
4513
- if (itemType.kind !== import_graphql.Kind.NAMED_TYPE) return fieldName;
4514
- const itemTypeDef = typeMap.get(itemType.name.value);
4515
- if (!itemTypeDef) return fieldName;
4516
- return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;
4517
- }
4518
- if (typeNode.kind !== import_graphql.Kind.NAMED_TYPE) return fieldName;
4519
- const typeDef = typeMap.get(typeNode.name.value);
4520
- if (!typeDef) return fieldName;
4521
- return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;
4522
- }).join(" ");
4523
- }
4524
- /**
4525
- * Finds the root state object type in a state SDL. Root state types follow
4526
- * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last
4527
- * by convention — the same resolution order the server uses
4528
- * (`extractRootTypeName` in `create-schema.ts`).
4529
- */
4530
- function findRootStateType(definitions, candidates) {
4531
- let lastObjectType = null;
4532
- for (const def of definitions) {
4533
- if (def.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION) continue;
4534
- if (candidates.includes(def.name.value)) return def;
4535
- lastObjectType = def;
4536
- }
4537
- if (!lastObjectType) throw new Error("No root state type found in the document model schema");
4538
- return lastObjectType;
4539
- }
4540
- /**
4541
- * Derives the subselection for the document's `global` state scope from the
4542
- * model's state SDL (e.g. `name total`), expanding object fields
4543
- * recursively. Throws when the schema is missing, unparseable, or has no
4544
- * root object type — the caller falls back to the generic document query.
4545
- */
4546
- function getDocumentStateSelection(model) {
4547
- const schema = model.documentModel.global.specifications.at(-1)?.state.global.schema;
4548
- if (!schema || !schema.trim()) throw new Error("Document model has no global state schema");
4549
- const ast = (0, import_graphql.parse)(schema);
4550
- const typeMap = buildStateTypeMap(ast.definitions);
4551
- const documentName = getDocumentModelSchemaName(model);
4552
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}State`, `${documentName}GlobalState`]), typeMap);
4553
- }
4554
- function getLocalStateSelection(localSchema, documentName) {
4555
- const ast = (0, import_graphql.parse)(localSchema);
4556
- const typeMap = buildStateTypeMap(ast.definitions);
4557
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}LocalState`]), typeMap);
4558
- }
4559
- /**
4560
- * Builds a query scoped to a document type's own subgraph root field,
4561
- * selecting the document and its full typed state. The shape mirrors what
4562
- * the switchboard generates per model (`generateNewApiSchema` in
4563
- * `create-schema.ts`): `<Name> { document(identifier:) { document { ...
4564
- * state { auth document global local } } } childIds }`.
4565
- */
4566
- function buildModelScopedQuery(model) {
4567
- const globalState = model.documentModel.global;
4568
- const documentName = getDocumentModelSchemaName(model);
4569
- const globalSelection = getDocumentStateSelection(model);
4570
- const localSchema = globalState.specifications.at(-1)?.state.local.schema ?? "";
4571
- const localSelection = localSchema.includes(`type ${documentName}LocalState`) ? getLocalStateSelection(localSchema, documentName) : null;
4572
- return [
4573
- "query GetDocument($identifier: String!) {",
4574
- ` ${documentName} {`,
4575
- " document(identifier: $identifier) {",
4576
- " document {",
4577
- " id",
4578
- " name",
4579
- " documentType",
4580
- " state {",
4581
- " auth",
4582
- " document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }",
4583
- ` global { ${globalSelection} }`,
4584
- ` ${localSelection ? `local { ${localSelection} }` : "local"}`,
4585
- " }",
4586
- " }",
4587
- " childIds",
4588
- " }",
4589
- " }",
4590
- "}"
4591
- ].join("\n");
4592
- }
4593
- function buildDocumentSubgraphQuery(documentType, identifier, model, authToken) {
4594
- let query;
4595
- if (model && model.documentModel.global.id === documentType) try {
4596
- query = buildModelScopedQuery(model);
4597
- } catch (error) {
4598
- console.warn("Could not derive a document-scoped query from the document model, falling back to the generic document query:", error);
4599
- query = getDocumentGraphqlQuery();
4600
- }
4601
- else query = getDocumentGraphqlQuery();
4602
- const variables = { identifier };
4603
- const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
4604
- const payload = {
4605
- document: query.trim(),
4606
- variables: JSON.stringify(variables, null, 2)
4607
- };
4608
- if (headers) payload.headers = JSON.stringify(headers);
4609
- return import_lz_string.default.compressToEncodedURIComponent(JSON.stringify(payload));
4610
- }
4611
- function buildDocumentSubgraphUrl(channelUrl, documentType, identifier, model, authToken) {
4612
- const encodedQuery = buildDocumentSubgraphQuery(documentType, identifier, model, authToken);
4613
- return `${getSwitchboardBaseFromChannelUrl(channelUrl)}/explorer?explorerURLState=${encodedQuery}`;
4614
- }
4615
- /**
4616
- * Hook that returns a function to generate a document's switchboard URL.
4617
- * Only returns a function for documents in remote drives.
4618
- * Returns null for local drives or when the document/drive cannot be determined.
4619
- *
4620
- * The returned function generates a fresh bearer token and builds the switchboard URL
4621
- * with authentication when called.
4622
- *
4623
- * @param document - The document to create a switchboard URL generator for
4624
- * @returns An async function that returns the switchboard URL, or null if not applicable
4625
- */
4626
- function useGetSwitchboardLink(document) {
4627
- const [drive] = useSelectedDriveSafe();
4628
- const remotes = useSyncList();
4629
- const documentModelModule = useDocumentModelModuleById(document?.header.documentType);
4630
- const isRemoteDrive = useMemo(() => {
4631
- if (!e$4(drive)) return false;
4632
- return remotes.some((remote) => remote.meta.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)));
4633
- }, [remotes, drive]);
4634
- const remoteUrl = useMemo(() => {
4635
- if (!e$4(drive)) return null;
4636
- try {
4637
- const channelUrl = (remotes.find((remote) => remote.meta.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)))?.channel)?.config.url;
4638
- if (typeof channelUrl === "string") return channelUrl;
4639
- return null;
4640
- } catch (error) {
4641
- console.error("Error determining remote URL:", error);
4642
- return null;
4643
- }
4644
- }, [remotes, drive]);
4645
- const renown = useRenown();
4646
- const user = useUser();
4647
- return useMemo(() => {
4648
- if (!isRemoteDrive || !document?.header.id || !remoteUrl) return null;
4649
- return async () => {
4650
- const token = user?.address ? await renown?.getBearerToken({
4651
- expiresIn: 600,
4652
- aud: remoteUrl
4653
- }) : void 0;
4654
- return buildDocumentSubgraphUrl(remoteUrl, document.header.documentType, document.header.id, documentModelModule, token);
4655
- };
4656
- }, [
4657
- isRemoteDrive,
4658
- remoteUrl,
4659
- document,
4660
- documentModelModule,
4661
- user,
4662
- renown
4663
- ]);
4664
- }
4665
- function useUserPermissions() {
4666
- const user = useUser();
4667
- const allowList = useAllowList();
4668
- if (!allowList) return {
4669
- isAllowedToCreateDocuments: true,
4670
- isAllowedToEditDocuments: true
4671
- };
4672
- return {
4673
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
4674
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
4675
- };
4676
- }
4677
- const DEFAULT_DEBOUNCE_DELAY_MS = 200;
4678
- const DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;
4679
- async function _refreshReactorData(reactor) {
4680
- setDrives(await getDrives(reactor));
4681
- }
4682
- async function _refreshReactorDataClient(reactor) {
4683
- if (!reactor) return;
4684
- setDrives(await getDrives(reactor));
4685
- }
4686
- function createDebouncedRefreshReactorData(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
4687
- let timeout = null;
4688
- let lastRefreshTime = 0;
4689
- return (reactor, immediate = false) => {
4690
- const now = Date.now();
4691
- const timeSinceLastRefresh = now - lastRefreshTime;
4692
- if (timeout !== null) clearTimeout(timeout);
4693
- if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
4694
- lastRefreshTime = now;
4695
- return _refreshReactorData(reactor);
4696
- }
4697
- return new Promise((resolve) => {
4698
- timeout = setTimeout(() => {
4699
- lastRefreshTime = Date.now();
4700
- _refreshReactorData(reactor).then(resolve);
4701
- }, debounceDelayMs);
4702
- });
4703
- };
4704
- }
4705
- function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
4706
- let timeout = null;
4707
- let lastRefreshTime = 0;
4708
- return (reactor, immediate = false) => {
4709
- const now = Date.now();
4710
- const timeSinceLastRefresh = now - lastRefreshTime;
4711
- if (timeout !== null) clearTimeout(timeout);
4712
- if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
4713
- lastRefreshTime = now;
4714
- return _refreshReactorDataClient(reactor);
4715
- }
4716
- return new Promise((resolve) => {
4717
- timeout = setTimeout(() => {
4718
- lastRefreshTime = Date.now();
4719
- _refreshReactorDataClient(reactor).then(resolve);
4720
- }, debounceDelayMs);
4721
- });
4722
- };
4723
- }
4724
- createDebouncedRefreshReactorData();
4725
- createDebouncedRefreshReactorDataClient();
4726
- //#endregion
4727
- export { useDropNode as A, setSelectedNode as B, addDocument as C, showRevisionHistory as D, showPHModal as E, t$2 as F, useSelectedDriveSafe as H, t$5 as I, isFileNodeKind as L, useStudioMode as M, e$1 as N, useDisabledEditors as O, e$4 as P, isFolderNodeKind as R, useSelectedDocumentSafe as S, showDeleteNodeModal as T, useDocumentById as U, useSelectedDriveId as V, useSetPHAppConfig as _, useDownloadDocument as a, useUserPermissions as b, useEditorModulesForDocumentType as c, useNodeById as d, useNodeParentFolderById as f, useSelectedNodePath as g, useSelectedFolder as h, useDocumentVersionStatus as i, usePHToast as j, useDragNode as k, useGetSwitchboardLink as l, useParentFolderForSelectedNode as m, preloadEditorModule as n, useDownloadFolder as o, useNodesInSelectedDriveOrFolder as p, useAllowedDocumentModelModules as r, useEditorModules as s, getSyncStatusSync as t, useNodeActions as u, useSetPHDocumentEditorConfig as v, addFolder$1 as w, useSelectedDocumentOfType as x, useTheme as y, setSelectedDrive as z };
4728
-
4729
- //# sourceMappingURL=dist-D5Xp9PwJ.mjs.map