@powerhousedao/powerhouse-vetra-packages 6.1.0-dev.2 → 6.1.0-dev.21

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 (119) hide show
  1. package/dist/browser/assets/entry-Bzani6_n.js +313 -0
  2. package/dist/browser/assets/projection-entry-Bpu-8SnI.js +406 -0
  3. package/dist/browser/{dist-DOMEWT3x.js → connect-ZnLjvmRt.js} +13013 -10302
  4. package/dist/browser/connect-ZnLjvmRt.js.map +1 -0
  5. package/dist/browser/dist-C1nRM9t2.js +3768 -0
  6. package/dist/browser/dist-C1nRM9t2.js.map +1 -0
  7. package/dist/browser/{schemas-Bqem6NRm.js → dist-CXoKspdx.js} +131 -2
  8. package/dist/browser/dist-CXoKspdx.js.map +1 -0
  9. package/dist/browser/dist-D8H48e8N.js +2692 -0
  10. package/dist/browser/dist-D8H48e8N.js.map +1 -0
  11. package/dist/browser/{dist-CC1E3l2O.js → dist-DLFI75Zd.js} +37 -9
  12. package/dist/browser/dist-DLFI75Zd.js.map +1 -0
  13. package/dist/browser/{dist-DQgJ8n4d.js → document-drive-oqv68jDU.js} +432 -290
  14. package/dist/browser/document-drive-oqv68jDU.js.map +1 -0
  15. package/dist/browser/document-models/index.js +1 -1
  16. package/dist/browser/{documents-Bpu0aSLb.js → documents-D4ek7Ubv.js} +3 -3
  17. package/dist/browser/{documents-Bpu0aSLb.js.map → documents-D4ek7Ubv.js.map} +1 -1
  18. package/dist/browser/{editor-B3yz7YdR.js → editor-CoTq6fqT.js} +32 -31
  19. package/dist/browser/editor-CoTq6fqT.js.map +1 -0
  20. package/dist/browser/{editor-Dm_73jiz.js → editor-DC3bigBu.js} +5 -5
  21. package/dist/browser/{editor-Dm_73jiz.js.map → editor-DC3bigBu.js.map} +1 -1
  22. package/dist/browser/editors/document-model-editor/module.js +1 -1
  23. package/dist/browser/editors/generic-drive-explorer/index.js +6 -6
  24. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  25. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  26. package/dist/browser/{folder-view-H2ov-zId.js → folder-view-DmYBf2pP.js} +13 -12
  27. package/dist/browser/folder-view-DmYBf2pP.js.map +1 -0
  28. package/dist/browser/{graphql-editor-CnaQ3XWx.js → graphql-editor-CiGd_Li7.js} +15 -7
  29. package/dist/browser/{graphql-editor-CnaQ3XWx.js.map → graphql-editor-CiGd_Li7.js.map} +1 -1
  30. package/dist/{node/hooks-Lbsf6g-v.mjs → browser/hooks-CORHBNHb.js} +6 -4
  31. package/dist/browser/{hooks-Beny0xpe.js.map → hooks-CORHBNHb.js.map} +1 -1
  32. package/dist/browser/index.js +2 -2
  33. package/dist/{node/json-editor-CVGgDVh2.mjs → browser/json-editor-sEqd5piI.js} +12 -4
  34. package/dist/browser/json-editor-sEqd5piI.js.map +1 -0
  35. package/dist/browser/{style-DYS_RFSN.js → linting-Dn6pXRkK.js} +7 -14
  36. package/dist/browser/linting-Dn6pXRkK.js.map +1 -0
  37. package/dist/browser/{parser-B0sh99Kk.js → parser-CkF6Qt8V.js} +1 -1
  38. package/dist/browser/{parser-B0sh99Kk.js.map → parser-CkF6Qt8V.js.map} +1 -1
  39. package/dist/browser/{schema-context-C0GpuR27.js → schema-context-DY-GEGnY.js} +4 -4
  40. package/dist/browser/schema-context-DY-GEGnY.js.map +1 -0
  41. package/dist/browser/state-schemas-DJmzG_M8.js +308 -0
  42. package/dist/browser/state-schemas-DJmzG_M8.js.map +1 -0
  43. package/dist/node/{dist-1kPMPFPD.mjs → connect-BLC4PXD9.mjs} +13953 -11229
  44. package/dist/node/connect-BLC4PXD9.mjs.map +1 -0
  45. package/dist/node/dist-BeZaEP6S.mjs +2692 -0
  46. package/dist/node/dist-BeZaEP6S.mjs.map +1 -0
  47. package/dist/node/dist-Bm05eoTg.mjs +3769 -0
  48. package/dist/node/dist-Bm05eoTg.mjs.map +1 -0
  49. package/dist/node/{tslib.es6-DwVpIYUS.mjs → dist-Cn3iExnV.mjs} +489 -3
  50. package/dist/node/dist-Cn3iExnV.mjs.map +1 -0
  51. package/dist/node/{schemas-Cb8uEF9u.mjs → dist-fA4EItr0.mjs} +131 -2
  52. package/dist/node/dist-fA4EItr0.mjs.map +1 -0
  53. package/dist/node/{dist-Bz4SgEHs.mjs → document-drive-sM33juXr.mjs} +432 -290
  54. package/dist/node/document-drive-sM33juXr.mjs.map +1 -0
  55. package/dist/node/document-models/index.mjs +1 -1
  56. package/dist/node/{documents-BWJpUm9f.mjs → documents-BFBPmyw1.mjs} +3 -3
  57. package/dist/node/{documents-BWJpUm9f.mjs.map → documents-BFBPmyw1.mjs.map} +1 -1
  58. package/dist/node/{editor-W8QOlGXD.mjs → editor-BFBa9nsO.mjs} +32 -31
  59. package/dist/node/editor-BFBa9nsO.mjs.map +1 -0
  60. package/dist/node/{editor-BaXuDsby.mjs → editor-BrS98lEH.mjs} +5 -5
  61. package/dist/node/{editor-BaXuDsby.mjs.map → editor-BrS98lEH.mjs.map} +1 -1
  62. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  63. package/dist/node/editors/generic-drive-explorer/index.mjs +6 -6
  64. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  65. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  66. package/dist/node/{folder-view-B0FNXbc0.mjs → folder-view-DHph3Yuu.mjs} +13 -12
  67. package/dist/node/folder-view-DHph3Yuu.mjs.map +1 -0
  68. package/dist/node/{graphql-Du2phcBf.mjs → graphql-DskHmkMe.mjs} +2 -2
  69. package/dist/node/{graphql-Du2phcBf.mjs.map → graphql-DskHmkMe.mjs.map} +1 -1
  70. package/dist/node/{graphql-editor-D1koK5kR.mjs → graphql-editor-CPq7oIbf.mjs} +14 -6
  71. package/dist/node/{graphql-editor-D1koK5kR.mjs.map → graphql-editor-CPq7oIbf.mjs.map} +1 -1
  72. package/dist/{browser/hooks-Beny0xpe.js → node/hooks-DJrjfVaS.mjs} +6 -4
  73. package/dist/node/{hooks-Lbsf6g-v.mjs.map → hooks-DJrjfVaS.mjs.map} +1 -1
  74. package/dist/node/index.mjs +2 -2
  75. package/dist/{browser/json-editor-h3cffF6X.js → node/json-editor-L32CP7TS.mjs} +12 -4
  76. package/dist/node/json-editor-L32CP7TS.mjs.map +1 -0
  77. package/dist/node/{style-CxHkfyna.mjs → linting-Dx50GuLN.mjs} +7 -14
  78. package/dist/node/linting-Dx50GuLN.mjs.map +1 -0
  79. package/dist/node/{schema-context-mLgEY1Hh.mjs → schema-context-CX5ml_9t.mjs} +4 -4
  80. package/dist/node/schema-context-CX5ml_9t.mjs.map +1 -0
  81. package/dist/node/state-schemas-XTTjQZOe.mjs +309 -0
  82. package/dist/node/state-schemas-XTTjQZOe.mjs.map +1 -0
  83. package/package.json +10 -10
  84. package/style.css +1 -0
  85. package/dist/browser/connect-CKdlDSUw.js +0 -9460
  86. package/dist/browser/connect-CKdlDSUw.js.map +0 -1
  87. package/dist/browser/dist-BXygvBtd.js +0 -132
  88. package/dist/browser/dist-BXygvBtd.js.map +0 -1
  89. package/dist/browser/dist-CC1E3l2O.js.map +0 -1
  90. package/dist/browser/dist-DOMEWT3x.js.map +0 -1
  91. package/dist/browser/dist-DQgJ8n4d.js.map +0 -1
  92. package/dist/browser/editor-B3yz7YdR.js.map +0 -1
  93. package/dist/browser/folder-view-H2ov-zId.js.map +0 -1
  94. package/dist/browser/json-editor-h3cffF6X.js.map +0 -1
  95. package/dist/browser/schema-context-C0GpuR27.js.map +0 -1
  96. package/dist/browser/schemas-Bqem6NRm.js.map +0 -1
  97. package/dist/browser/state-schemas-C5NPeV6-.js +0 -674
  98. package/dist/browser/state-schemas-C5NPeV6-.js.map +0 -1
  99. package/dist/browser/style-DYS_RFSN.js.map +0 -1
  100. package/dist/browser/tslib.es6-DRuVAsR8.js +0 -32
  101. package/dist/browser/tslib.es6-DRuVAsR8.js.map +0 -1
  102. package/dist/node/connect-SGvLzr5K.mjs +0 -9475
  103. package/dist/node/connect-SGvLzr5K.mjs.map +0 -1
  104. package/dist/node/dist-1kPMPFPD.mjs.map +0 -1
  105. package/dist/node/dist-BQTIepWC.mjs +0 -132
  106. package/dist/node/dist-BQTIepWC.mjs.map +0 -1
  107. package/dist/node/dist-Bz4SgEHs.mjs.map +0 -1
  108. package/dist/node/dist-Cay1iRRr.mjs +0 -491
  109. package/dist/node/dist-Cay1iRRr.mjs.map +0 -1
  110. package/dist/node/editor-W8QOlGXD.mjs.map +0 -1
  111. package/dist/node/folder-view-B0FNXbc0.mjs.map +0 -1
  112. package/dist/node/json-editor-CVGgDVh2.mjs.map +0 -1
  113. package/dist/node/schema-context-mLgEY1Hh.mjs.map +0 -1
  114. package/dist/node/schemas-Cb8uEF9u.mjs.map +0 -1
  115. package/dist/node/state-schemas-DAthoEEk.mjs +0 -675
  116. package/dist/node/state-schemas-DAthoEEk.mjs.map +0 -1
  117. package/dist/node/style-CxHkfyna.mjs.map +0 -1
  118. package/dist/node/tslib.es6-DwVpIYUS.mjs.map +0 -1
  119. package/dist/style.css +0 -906
@@ -0,0 +1,3769 @@
1
+ import { E as __commonJSMin, j as __toESM, t as capitalCase } from "./dist-fA4EItr0.mjs";
2
+ import { A as replayDocument, J as validateStateSchemaName, K as validateInitialState, S as createZip, Y as generateId, _ as baseSaveToFileHandle, a as handleTargetNameCollisions, c as moveNode, d as logger, g as baseLoadFromInput, i as generateNodesCopy, l as updateNode, n as copyNode, o as isFileNode, q as validateModules, r as driveDocumentModelModule, s as isFolderNode, t as addFolder$1, u as documentModelDocumentModelModule, v as buildSignedAction, y as createPresignedHeader, z as setName } from "./document-drive-sM33juXr.mjs";
3
+ import { a as SyncStatus, n as require_main, o as ModuleNotFoundError, s as driveCollectionId, t as reactorDriveDocumentModelModule } from "./dist-Cn3iExnV.mjs";
4
+ import { Children, cloneElement, forwardRef, isValidElement, use, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
+ import "react/jsx-runtime";
6
+ //#region ../reactor-browser/dist/make-ph-event-functions-DwiD1zH9.js
7
+ const isServer$1 = typeof window === "undefined";
8
+ function makePHEventFunctions(key) {
9
+ const setEventName = `ph:set${capitalCase(key)}`;
10
+ const updateEventName = `ph:${key}Updated`;
11
+ function setValue(value) {
12
+ if (isServer$1) return;
13
+ const event = new CustomEvent(setEventName, { detail: { [key]: value } });
14
+ window.dispatchEvent(event);
15
+ }
16
+ function dispatchUpdatedEvent() {
17
+ if (isServer$1) return;
18
+ const event = new CustomEvent(updateEventName);
19
+ window.dispatchEvent(event);
20
+ }
21
+ function handleSetValueEvent(event) {
22
+ if (isServer$1) return;
23
+ const value = event.detail[key];
24
+ if (!window.ph) window.ph = {};
25
+ window.ph[key] = value;
26
+ dispatchUpdatedEvent();
27
+ }
28
+ function addEventHandler() {
29
+ if (isServer$1) return;
30
+ window.addEventListener(setEventName, handleSetValueEvent);
31
+ }
32
+ function subscribeToValue(onStoreChange) {
33
+ if (isServer$1) return () => {};
34
+ window.addEventListener(updateEventName, onStoreChange);
35
+ return () => {
36
+ window.removeEventListener(updateEventName, onStoreChange);
37
+ };
38
+ }
39
+ function getSnapshot() {
40
+ if (isServer$1) return;
41
+ return window.ph?.[key];
42
+ }
43
+ function getServerSnapshot() {}
44
+ function useValue() {
45
+ return useSyncExternalStore(subscribeToValue, getSnapshot, getServerSnapshot);
46
+ }
47
+ return {
48
+ useValue,
49
+ setValue,
50
+ addEventHandler
51
+ };
52
+ }
53
+ //#endregion
54
+ //#region ../reactor-browser/dist/document-by-id-BrIy0iHX.js
55
+ async function queueActions(document, actionOrActions) {
56
+ if (!document) throw new Error("No document provided");
57
+ if (!actionOrActions) throw new Error("No actions provided");
58
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
59
+ if (actions.length === 0) throw new Error("No actions provided");
60
+ const reactorClient = window.ph?.reactorClient;
61
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
62
+ return await reactorClient.execute(document.header.id, "main", actions);
63
+ }
64
+ async function queueOperations(documentId, operationOrOperations) {
65
+ if (!documentId) throw new Error("No documentId provided");
66
+ if (!operationOrOperations) throw new Error("No operations provided");
67
+ const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
68
+ if (operations.length === 0) throw new Error("No operations provided");
69
+ const reactorClient = window.ph?.reactorClient;
70
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
71
+ const actions = operations.map((op) => op.action);
72
+ return await reactorClient.execute(documentId, "main", actions);
73
+ }
74
+ async function uploadOperations(documentId, allOperations, pushOperations, options) {
75
+ const operationsLimit = options?.operationsLimit || 50;
76
+ const onProgress = options?.onProgress;
77
+ logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
78
+ const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
79
+ const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
80
+ let uploadedOperations = 0;
81
+ for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
82
+ logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
83
+ const chunk = operations.slice(i, i + operationsLimit);
84
+ const operation = chunk.at(-1);
85
+ if (!operation) break;
86
+ const scope = operation.action.scope;
87
+ await pushOperations(documentId, chunk);
88
+ uploadedOperations += chunk.length;
89
+ if (onProgress) onProgress({
90
+ stage: "uploading",
91
+ progress: Math.round(uploadedOperations / totalOperations * 100),
92
+ totalOperations,
93
+ uploadedOperations
94
+ });
95
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
96
+ }
97
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
+ }
99
+ async function signAction(action, document) {
100
+ const reactor = window.ph?.reactorClient;
101
+ if (!reactor) return action;
102
+ const reducer = (await reactor.getDocumentModelModule(document.header.documentType)).reducer;
103
+ const renown = window.ph?.renown;
104
+ if (!renown?.user) return action;
105
+ if (!action.context?.signer) return action;
106
+ const actionSigner = action.context.signer;
107
+ return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
+ }
109
+ function addActionContext(action) {
110
+ const renown = window.ph?.renown;
111
+ if (!renown?.user) return action;
112
+ return {
113
+ context: { signer: {
114
+ app: {
115
+ name: "Connect",
116
+ key: renown.did
117
+ },
118
+ user: {
119
+ address: renown.user.address,
120
+ networkId: renown.user.networkId,
121
+ chainId: renown.user.chainId
122
+ },
123
+ signatures: []
124
+ } },
125
+ ...action
126
+ };
127
+ }
128
+ async function makeSignedActionWithContext(action, document) {
129
+ if (!action) {
130
+ logger.error("No action found");
131
+ return;
132
+ }
133
+ if (!document) {
134
+ logger.error("No document found");
135
+ return;
136
+ }
137
+ return addActionContext(await signAction(action, document));
138
+ }
139
+ async function makeSignedActionsWithContext(actionOrActions, document) {
140
+ if (!actionOrActions) {
141
+ logger.error("No actions found");
142
+ return;
143
+ }
144
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
145
+ return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
146
+ }
147
+ async function getDocument(documentId) {
148
+ try {
149
+ return await window.ph?.reactorClient?.get(documentId);
150
+ } catch (error) {
151
+ logger.debug(`Failed to get document with id ${documentId}:`, error);
152
+ return;
153
+ }
154
+ }
155
+ function getActionErrors(result, actions) {
156
+ return actions.reduce((errors, a) => {
157
+ const scopeOperations = result.operations[a.scope];
158
+ if (!scopeOperations) return errors;
159
+ const op = scopeOperations.findLast((op) => op.action.id === a.id);
160
+ if (op?.error) errors.push(new Error(op.error));
161
+ return errors;
162
+ }, new Array());
163
+ }
164
+ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
165
+ const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
166
+ if (!document) {
167
+ logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
168
+ return;
169
+ }
170
+ const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
171
+ if (!signedActionsWithContext) {
172
+ logger.error("No signed actions with context found");
173
+ return;
174
+ }
175
+ const result = await queueActions(document, signedActionsWithContext);
176
+ if (onErrors && result) {
177
+ const errors = getActionErrors(result, signedActionsWithContext);
178
+ if (errors.length) onErrors(errors);
179
+ }
180
+ if (onSuccess && result) onSuccess(result);
181
+ return result;
182
+ }
183
+ const documentEventFunctions = makePHEventFunctions("documentCache");
184
+ /** Returns all documents in the reactor. */
185
+ const useDocumentCache = documentEventFunctions.useValue;
186
+ documentEventFunctions.setValue;
187
+ documentEventFunctions.addEventHandler;
188
+ /**
189
+ * Retrieves a document from the reactor and subscribes to changes using React Suspense.
190
+ * This hook will suspend rendering while the document is loading.
191
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
192
+ * @returns The document if found, or undefined if id is null/undefined
193
+ */
194
+ function useDocument(id) {
195
+ const documentCache = useDocumentCache();
196
+ const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
197
+ return document ? use(document) : void 0;
198
+ }
199
+ function useDispatch(document) {
200
+ /**
201
+ * Dispatches actions to the document.
202
+ * @param actionOrActions - The action or actions to dispatch.
203
+ * @param onErrors - Callback invoked with any errors that occurred during action execution.
204
+ */
205
+ function dispatch(actionOrActions, onErrors, onSuccess) {
206
+ dispatchActions(actionOrActions, document, onErrors, onSuccess).catch(logger.error);
207
+ }
208
+ return [document, dispatch];
209
+ }
210
+ /** Returns a document by id. */
211
+ function useDocumentById(id) {
212
+ const document = useDocument(id);
213
+ const [, dispatch] = useDispatch(document);
214
+ return [document, dispatch];
215
+ }
216
+ //#endregion
217
+ //#region ../reactor-browser/dist/client-D7hUM13i.js
218
+ var import_main = require_main();
219
+ const PhDocumentFieldsFragmentDoc = import_main.gql`
220
+ fragment PHDocumentFields on PHDocument {
221
+ id
222
+ slug
223
+ name
224
+ documentType
225
+ state
226
+ revisionsList {
227
+ scope
228
+ revision
229
+ }
230
+ createdAtUtcIso
231
+ lastModifiedAtUtcIso
232
+ }
233
+ `;
234
+ import_main.gql`
235
+ query GetDocumentModels($namespace: String, $paging: PagingInput) {
236
+ documentModels(namespace: $namespace, paging: $paging) {
237
+ items {
238
+ id
239
+ name
240
+ namespace
241
+ version
242
+ specification
243
+ }
244
+ totalCount
245
+ hasNextPage
246
+ hasPreviousPage
247
+ cursor
248
+ }
249
+ }
250
+ `;
251
+ const GetDocumentDocument = import_main.gql`
252
+ query GetDocument($identifier: String!, $view: ViewFilterInput) {
253
+ document(identifier: $identifier, view: $view) {
254
+ document {
255
+ ...PHDocumentFields
256
+ }
257
+ childIds
258
+ }
259
+ }
260
+ ${PhDocumentFieldsFragmentDoc}
261
+ `;
262
+ const GetDocumentWithOperationsDocument = import_main.gql`
263
+ query GetDocumentWithOperations(
264
+ $identifier: String!
265
+ $view: ViewFilterInput
266
+ $operationsFilter: DocumentOperationsFilterInput
267
+ $operationsPaging: PagingInput
268
+ ) {
269
+ document(identifier: $identifier, view: $view) {
270
+ document {
271
+ ...PHDocumentFields
272
+ operations(filter: $operationsFilter, paging: $operationsPaging) {
273
+ items {
274
+ index
275
+ timestampUtcMs
276
+ hash
277
+ skip
278
+ error
279
+ id
280
+ action {
281
+ id
282
+ type
283
+ timestampUtcMs
284
+ input
285
+ scope
286
+ attachments {
287
+ data
288
+ mimeType
289
+ hash
290
+ extension
291
+ fileName
292
+ }
293
+ context {
294
+ signer {
295
+ user {
296
+ address
297
+ networkId
298
+ chainId
299
+ }
300
+ app {
301
+ name
302
+ key
303
+ }
304
+ signatures
305
+ }
306
+ }
307
+ }
308
+ }
309
+ totalCount
310
+ hasNextPage
311
+ hasPreviousPage
312
+ cursor
313
+ }
314
+ }
315
+ childIds
316
+ }
317
+ }
318
+ ${PhDocumentFieldsFragmentDoc}
319
+ `;
320
+ import_main.gql`
321
+ query GetDocumentOutgoingRelationships(
322
+ $sourceIdentifier: String!
323
+ $relationshipType: String!
324
+ $view: ViewFilterInput
325
+ $paging: PagingInput
326
+ ) {
327
+ documentOutgoingRelationships(
328
+ sourceIdentifier: $sourceIdentifier
329
+ relationshipType: $relationshipType
330
+ view: $view
331
+ paging: $paging
332
+ ) {
333
+ items {
334
+ ...PHDocumentFields
335
+ }
336
+ totalCount
337
+ hasNextPage
338
+ hasPreviousPage
339
+ cursor
340
+ }
341
+ }
342
+ ${PhDocumentFieldsFragmentDoc}
343
+ `;
344
+ import_main.gql`
345
+ query GetDocumentIncomingRelationships(
346
+ $targetIdentifier: String!
347
+ $relationshipType: String!
348
+ $view: ViewFilterInput
349
+ $paging: PagingInput
350
+ ) {
351
+ documentIncomingRelationships(
352
+ targetIdentifier: $targetIdentifier
353
+ relationshipType: $relationshipType
354
+ view: $view
355
+ paging: $paging
356
+ ) {
357
+ items {
358
+ ...PHDocumentFields
359
+ }
360
+ totalCount
361
+ hasNextPage
362
+ hasPreviousPage
363
+ cursor
364
+ }
365
+ }
366
+ ${PhDocumentFieldsFragmentDoc}
367
+ `;
368
+ import_main.gql`
369
+ query FindDocuments(
370
+ $search: SearchFilterInput
371
+ $view: ViewFilterInput
372
+ $paging: PagingInput
373
+ ) {
374
+ findDocuments(search: $search, view: $view, paging: $paging) {
375
+ items {
376
+ ...PHDocumentFields
377
+ }
378
+ totalCount
379
+ hasNextPage
380
+ hasPreviousPage
381
+ cursor
382
+ }
383
+ }
384
+ ${PhDocumentFieldsFragmentDoc}
385
+ `;
386
+ const GetDocumentOperationsDocument = import_main.gql`
387
+ query GetDocumentOperations(
388
+ $filter: OperationsFilterInput!
389
+ $paging: PagingInput
390
+ ) {
391
+ documentOperations(filter: $filter, paging: $paging) {
392
+ items {
393
+ index
394
+ timestampUtcMs
395
+ hash
396
+ skip
397
+ error
398
+ id
399
+ action {
400
+ id
401
+ type
402
+ timestampUtcMs
403
+ input
404
+ scope
405
+ attachments {
406
+ data
407
+ mimeType
408
+ hash
409
+ extension
410
+ fileName
411
+ }
412
+ context {
413
+ signer {
414
+ user {
415
+ address
416
+ networkId
417
+ chainId
418
+ }
419
+ app {
420
+ name
421
+ key
422
+ }
423
+ signatures
424
+ }
425
+ }
426
+ }
427
+ }
428
+ totalCount
429
+ hasNextPage
430
+ hasPreviousPage
431
+ cursor
432
+ }
433
+ }
434
+ `;
435
+ import_main.gql`
436
+ query GetJobStatus($jobId: String!) {
437
+ jobStatus(jobId: $jobId) {
438
+ id
439
+ status
440
+ result
441
+ error
442
+ createdAt
443
+ completedAt
444
+ }
445
+ }
446
+ `;
447
+ import_main.gql`
448
+ mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
449
+ createDocument(document: $document, parentIdentifier: $parentIdentifier) {
450
+ ...PHDocumentFields
451
+ }
452
+ }
453
+ ${PhDocumentFieldsFragmentDoc}
454
+ `;
455
+ import_main.gql`
456
+ mutation CreateEmptyDocument(
457
+ $documentType: String!
458
+ $parentIdentifier: String
459
+ ) {
460
+ createEmptyDocument(
461
+ documentType: $documentType
462
+ parentIdentifier: $parentIdentifier
463
+ ) {
464
+ ...PHDocumentFields
465
+ }
466
+ }
467
+ ${PhDocumentFieldsFragmentDoc}
468
+ `;
469
+ import_main.gql`
470
+ mutation MutateDocument(
471
+ $documentIdentifier: String!
472
+ $actions: [JSONObject!]!
473
+ $view: ViewFilterInput
474
+ ) {
475
+ mutateDocument(
476
+ documentIdentifier: $documentIdentifier
477
+ actions: $actions
478
+ view: $view
479
+ ) {
480
+ ...PHDocumentFields
481
+ }
482
+ }
483
+ ${PhDocumentFieldsFragmentDoc}
484
+ `;
485
+ import_main.gql`
486
+ mutation MutateDocumentAsync(
487
+ $documentIdentifier: String!
488
+ $actions: [JSONObject!]!
489
+ $view: ViewFilterInput
490
+ ) {
491
+ mutateDocumentAsync(
492
+ documentIdentifier: $documentIdentifier
493
+ actions: $actions
494
+ view: $view
495
+ )
496
+ }
497
+ `;
498
+ import_main.gql`
499
+ mutation RenameDocument(
500
+ $documentIdentifier: String!
501
+ $name: String!
502
+ $branch: String
503
+ ) {
504
+ renameDocument(
505
+ documentIdentifier: $documentIdentifier
506
+ name: $name
507
+ branch: $branch
508
+ ) {
509
+ ...PHDocumentFields
510
+ }
511
+ }
512
+ ${PhDocumentFieldsFragmentDoc}
513
+ `;
514
+ import_main.gql`
515
+ mutation SetPreferredEditor(
516
+ $documentIdentifier: String!
517
+ $preferredEditor: String
518
+ $branch: String
519
+ ) {
520
+ setPreferredEditor(
521
+ documentIdentifier: $documentIdentifier
522
+ preferredEditor: $preferredEditor
523
+ branch: $branch
524
+ ) {
525
+ ...PHDocumentFields
526
+ }
527
+ }
528
+ ${PhDocumentFieldsFragmentDoc}
529
+ `;
530
+ import_main.gql`
531
+ mutation AddRelationship(
532
+ $sourceIdentifier: String!
533
+ $targetIdentifier: String!
534
+ $relationshipType: String!
535
+ $branch: String
536
+ ) {
537
+ addRelationship(
538
+ sourceIdentifier: $sourceIdentifier
539
+ targetIdentifier: $targetIdentifier
540
+ relationshipType: $relationshipType
541
+ branch: $branch
542
+ ) {
543
+ ...PHDocumentFields
544
+ }
545
+ }
546
+ ${PhDocumentFieldsFragmentDoc}
547
+ `;
548
+ import_main.gql`
549
+ mutation RemoveRelationship(
550
+ $sourceIdentifier: String!
551
+ $targetIdentifier: String!
552
+ $relationshipType: String!
553
+ $branch: String
554
+ ) {
555
+ removeRelationship(
556
+ sourceIdentifier: $sourceIdentifier
557
+ targetIdentifier: $targetIdentifier
558
+ relationshipType: $relationshipType
559
+ branch: $branch
560
+ ) {
561
+ ...PHDocumentFields
562
+ }
563
+ }
564
+ ${PhDocumentFieldsFragmentDoc}
565
+ `;
566
+ import_main.gql`
567
+ mutation MoveRelationship(
568
+ $sourceParentIdentifier: String!
569
+ $targetParentIdentifier: String!
570
+ $targetIdentifier: String!
571
+ $relationshipType: String!
572
+ $branch: String
573
+ ) {
574
+ moveRelationship(
575
+ sourceParentIdentifier: $sourceParentIdentifier
576
+ targetParentIdentifier: $targetParentIdentifier
577
+ targetIdentifier: $targetIdentifier
578
+ relationshipType: $relationshipType
579
+ branch: $branch
580
+ ) {
581
+ source {
582
+ ...PHDocumentFields
583
+ }
584
+ target {
585
+ ...PHDocumentFields
586
+ }
587
+ }
588
+ }
589
+ ${PhDocumentFieldsFragmentDoc}
590
+ `;
591
+ import_main.gql`
592
+ mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
593
+ deleteDocument(identifier: $identifier, propagate: $propagate)
594
+ }
595
+ `;
596
+ import_main.gql`
597
+ mutation DeleteDocuments(
598
+ $identifiers: [String!]!
599
+ $propagate: PropagationMode
600
+ ) {
601
+ deleteDocuments(identifiers: $identifiers, propagate: $propagate)
602
+ }
603
+ `;
604
+ import_main.gql`
605
+ subscription DocumentChanges(
606
+ $search: SearchFilterInput
607
+ $view: ViewFilterInput
608
+ ) {
609
+ documentChanges(search: $search, view: $view) {
610
+ type
611
+ documents {
612
+ ...PHDocumentFields
613
+ }
614
+ context {
615
+ parentId
616
+ childId
617
+ }
618
+ }
619
+ }
620
+ ${PhDocumentFieldsFragmentDoc}
621
+ `;
622
+ import_main.gql`
623
+ subscription JobChanges($jobId: String!) {
624
+ jobChanges(jobId: $jobId) {
625
+ jobId
626
+ status
627
+ result
628
+ error
629
+ }
630
+ }
631
+ `;
632
+ import_main.gql`
633
+ query PollSyncEnvelopes(
634
+ $channelId: String!
635
+ $outboxAck: Int!
636
+ $outboxLatest: Int!
637
+ ) {
638
+ pollSyncEnvelopes(
639
+ channelId: $channelId
640
+ outboxAck: $outboxAck
641
+ outboxLatest: $outboxLatest
642
+ ) {
643
+ envelopes {
644
+ type
645
+ channelMeta {
646
+ id
647
+ }
648
+ operations {
649
+ operation {
650
+ index
651
+ timestampUtcMs
652
+ hash
653
+ skip
654
+ error
655
+ id
656
+ action {
657
+ id
658
+ type
659
+ timestampUtcMs
660
+ input
661
+ scope
662
+ attachments {
663
+ data
664
+ mimeType
665
+ hash
666
+ extension
667
+ fileName
668
+ }
669
+ context {
670
+ signer {
671
+ user {
672
+ address
673
+ networkId
674
+ chainId
675
+ }
676
+ app {
677
+ name
678
+ key
679
+ }
680
+ signatures
681
+ }
682
+ }
683
+ }
684
+ }
685
+ context {
686
+ documentId
687
+ documentType
688
+ scope
689
+ branch
690
+ }
691
+ }
692
+ cursor {
693
+ remoteName
694
+ cursorOrdinal
695
+ lastSyncedAtUtcMs
696
+ }
697
+ key
698
+ dependsOn
699
+ }
700
+ ackOrdinal
701
+ deadLetters {
702
+ documentId
703
+ error
704
+ }
705
+ hasMore
706
+ }
707
+ }
708
+ `;
709
+ import_main.gql`
710
+ mutation TouchChannel($input: TouchChannelInput!) {
711
+ touchChannel(input: $input) {
712
+ success
713
+ ackOrdinal
714
+ }
715
+ }
716
+ `;
717
+ import_main.gql`
718
+ mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
719
+ pushSyncEnvelopes(envelopes: $envelopes)
720
+ }
721
+ `;
722
+ /** Get the source string from a GraphQL document (string or DocumentNode). */
723
+ function getDocumentSource(doc) {
724
+ return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
725
+ }
726
+ /**
727
+ * Extract the inner selection set of a named field from a GraphQL document source.
728
+ * Returns the `{ ... }` block including braces.
729
+ */
730
+ function extractSelectionSet(doc, fieldName, fallback) {
731
+ const source = getDocumentSource(doc);
732
+ return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
733
+ }
734
+ /**
735
+ * Extract the query body and any fragment definitions from a GraphQL document.
736
+ * Returns { body, fragments } where body is the content inside the query `{ ... }`
737
+ * and fragments are any trailing fragment definitions.
738
+ */
739
+ function extractQueryParts(doc, fallbackBody) {
740
+ const source = getDocumentSource(doc);
741
+ const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
742
+ return {
743
+ body: queryMatch?.[1]?.trim() ?? fallbackBody,
744
+ fragments: queryMatch?.[2]?.trim() ?? ""
745
+ };
746
+ }
747
+ extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
748
+ extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
749
+ //#endregion
750
+ //#region ../reactor-browser/dist/renown-Dzmo1gJD.js
751
+ const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
752
+ const renownEventFunctions = makePHEventFunctions("renown");
753
+ renownEventFunctions.addEventHandler;
754
+ /** Returns the renown instance */
755
+ const useRenown = renownEventFunctions.useValue;
756
+ renownEventFunctions.setValue;
757
+ /** Returns the current user from the renown instance, subscribing to user events */
758
+ function useUser() {
759
+ const renown = useRenown();
760
+ const [user, setUser] = useState(renown?.user);
761
+ useEffect(() => {
762
+ setUser(renown?.user);
763
+ if (!renown) return;
764
+ return renown.on("user", setUser);
765
+ }, [renown]);
766
+ return user;
767
+ }
768
+ function mergeProps(parentProps, childProps) {
769
+ const merged = { ...parentProps };
770
+ for (const key of Object.keys(childProps)) {
771
+ const parentValue = parentProps[key];
772
+ const childValue = childProps[key];
773
+ if (key === "style") merged[key] = {
774
+ ...parentValue,
775
+ ...childValue
776
+ };
777
+ else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
778
+ else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
779
+ childValue(...args);
780
+ parentValue(...args);
781
+ };
782
+ else if (childValue !== void 0) merged[key] = childValue;
783
+ }
784
+ return merged;
785
+ }
786
+ const Slot = forwardRef(({ children, ...props }, ref) => {
787
+ const child = Children.only(children);
788
+ if (!isValidElement(child)) return null;
789
+ const childElement = child;
790
+ const mergedProps = mergeProps(props, childElement.props);
791
+ if (ref) mergedProps.ref = ref;
792
+ return cloneElement(childElement, mergedProps);
793
+ });
794
+ Slot.displayName = "Slot";
795
+ //#endregion
796
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
797
+ function e$8(e, t, n) {
798
+ let r = (n) => e(n, ...t);
799
+ return n === void 0 ? r : Object.assign(r, {
800
+ lazy: n,
801
+ lazyArgs: t
802
+ });
803
+ }
804
+ //#endregion
805
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
806
+ function t$5(t, n, r) {
807
+ let i = t.length - n.length;
808
+ if (i === 0) return t(...n);
809
+ if (i === 1) return e$8(t, n, r);
810
+ throw Error(`Wrong number of arguments`);
811
+ }
812
+ //#endregion
813
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
814
+ function t$4(...t) {
815
+ return t$5(n$4, t);
816
+ }
817
+ const n$4 = (e, t) => t.every((t) => t(e));
818
+ //#endregion
819
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
820
+ function e$7(e, t, n) {
821
+ return e(n[0]) ? (e) => t(e, ...n) : t(...n);
822
+ }
823
+ function t$3(...t) {
824
+ return e$7(r, n$3, t);
825
+ }
826
+ function n$3(e, ...t) {
827
+ for (let n of t) {
828
+ if (typeof n == `function`) return n(e);
829
+ let [t, r] = n;
830
+ if (t(e)) return r(e);
831
+ }
832
+ throw Error(`conditional: data failed for all cases`);
833
+ }
834
+ function r(e) {
835
+ if (!Array.isArray(e)) return !1;
836
+ let [t, n, ...r] = e;
837
+ return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
838
+ }
839
+ //#endregion
840
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
841
+ function e$6(e) {
842
+ return () => e;
843
+ }
844
+ //#endregion
845
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
846
+ function t$2(...t) {
847
+ return t$5(n$2, t);
848
+ }
849
+ const n$2 = (e, t) => e.length >= t;
850
+ //#endregion
851
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
852
+ const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
853
+ function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
854
+ let c, l, u, d, f = () => {
855
+ let t = u;
856
+ t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
857
+ }, p = () => {
858
+ clearTimeout(l), l = void 0, c === void 0 && f();
859
+ }, m = () => {
860
+ clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
861
+ };
862
+ return {
863
+ call: (...e) => {
864
+ let t = c === void 0 && l === void 0;
865
+ if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
866
+ if (i !== void 0 || a !== void 0 || o === void 0) {
867
+ clearTimeout(c);
868
+ let e = Date.now();
869
+ d ??= e;
870
+ let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
871
+ c = setTimeout(m, t);
872
+ }
873
+ r !== `end` && t && f();
874
+ }
875
+ },
876
+ cancel: () => {
877
+ clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
878
+ },
879
+ flush: () => {
880
+ m(), p();
881
+ },
882
+ get isIdle() {
883
+ return c === void 0 && l === void 0;
884
+ }
885
+ };
886
+ }
887
+ //#endregion
888
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
889
+ function e$4(e) {
890
+ return e !== void 0;
891
+ }
892
+ //#endregion
893
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
894
+ function e$3(e) {
895
+ return (t) => !e(t);
896
+ }
897
+ //#endregion
898
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
899
+ function t(...t) {
900
+ return t$5(n, t);
901
+ }
902
+ const n = (e, t) => e === t || Object.is(e, t);
903
+ //#endregion
904
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
905
+ function e$2(e) {
906
+ return typeof e == `string`;
907
+ }
908
+ //#endregion
909
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
910
+ function e$1(e) {
911
+ return !!e;
912
+ }
913
+ //#endregion
914
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
915
+ function e(e) {
916
+ let t = !1, n;
917
+ return () => (t ||= (n = e(), !0), n);
918
+ }
919
+ //#endregion
920
+ //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
921
+ let base64;
922
+ if (typeof window !== "undefined") if (window.btoa) base64 = function(input) {
923
+ return btoa(unescape(encodeURIComponent(input)));
924
+ };
925
+ else base64 = function(input) {
926
+ const str = unescape(encodeURIComponent(input + ""));
927
+ let output = "";
928
+ for (let block, charCode, idx = 0, map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; str.charAt(idx | 0) || (map = "=", idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
929
+ charCode = str.charCodeAt(idx += 3 / 4);
930
+ /* c8 ignore next 3 */
931
+ if (charCode > 255) throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
932
+ block = block << 8 | charCode;
933
+ }
934
+ return output;
935
+ };
936
+ else base64 = function(input) {
937
+ return Buffer.from(input).toString("base64");
938
+ };
939
+ function slug(string, opts) {
940
+ let result = slugify(string, opts);
941
+ if ((opts && opts.fallback !== void 0 ? opts.fallback : slug.defaults.fallback) === true && result === "") result = slugify(base64(string), opts);
942
+ return result;
943
+ }
944
+ const locales = {
945
+ bg: {
946
+ Й: "Y",
947
+ й: "y",
948
+ X: "H",
949
+ x: "h",
950
+ Ц: "Ts",
951
+ ц: "ts",
952
+ Щ: "Sht",
953
+ щ: "sht",
954
+ Ъ: "A",
955
+ ъ: "a",
956
+ Ь: "Y",
957
+ ь: "y"
958
+ },
959
+ de: {
960
+ Ä: "AE",
961
+ ä: "ae",
962
+ Ö: "OE",
963
+ ö: "oe",
964
+ Ü: "UE",
965
+ ü: "ue"
966
+ },
967
+ sr: {
968
+ đ: "dj",
969
+ Đ: "DJ"
970
+ },
971
+ uk: {
972
+ И: "Y",
973
+ и: "y",
974
+ Й: "Y",
975
+ й: "y",
976
+ Ц: "Ts",
977
+ ц: "ts",
978
+ Х: "Kh",
979
+ х: "kh",
980
+ Щ: "Shch",
981
+ щ: "shch",
982
+ Г: "H",
983
+ г: "h"
984
+ }
985
+ };
986
+ let defaultLocale = {};
987
+ function slugify(string, opts) {
988
+ if (typeof string !== "string") throw new Error("slug() requires a string argument, received " + typeof string);
989
+ if (!string.isWellFormed()) throw new Error("slug() received a malformed string with lone surrogates");
990
+ if (typeof opts === "string") opts = { replacement: opts };
991
+ opts = opts ? Object.assign({}, opts) : {};
992
+ opts.mode = opts.mode || slug.defaults.mode;
993
+ const defaults = slug.defaults.modes[opts.mode];
994
+ const keys = [
995
+ "replacement",
996
+ "multicharmap",
997
+ "charmap",
998
+ "remove",
999
+ "lower",
1000
+ "trim"
1001
+ ];
1002
+ for (let key, i = 0, l = keys.length; i < l; i++) {
1003
+ key = keys[i];
1004
+ opts[key] = key in opts ? opts[key] : defaults[key];
1005
+ }
1006
+ const localeMap = locales[opts.locale] || defaultLocale;
1007
+ let lengths = [];
1008
+ for (const key in opts.multicharmap) {
1009
+ if (!Object.prototype.hasOwnProperty.call(opts.multicharmap, key)) continue;
1010
+ const len = key.length;
1011
+ if (lengths.indexOf(len) === -1) lengths.push(len);
1012
+ }
1013
+ lengths = lengths.sort(function(a, b) {
1014
+ return b - a;
1015
+ });
1016
+ const disallowedChars = opts.mode === "rfc3986" ? /[^\w\s\-.~]/ : /[^A-Za-z0-9\s]/;
1017
+ let result = "";
1018
+ for (let char, i = 0, l = string.length; i < l; i++) {
1019
+ char = string[i];
1020
+ let matchedMultichar = false;
1021
+ for (let j = 0; j < lengths.length; j++) {
1022
+ const len = lengths[j];
1023
+ const str = string.substr(i, len);
1024
+ if (opts.multicharmap[str]) {
1025
+ i += len - 1;
1026
+ char = opts.multicharmap[str];
1027
+ matchedMultichar = true;
1028
+ break;
1029
+ }
1030
+ }
1031
+ if (!matchedMultichar) if (localeMap[char]) char = localeMap[char];
1032
+ else if (opts.charmap[char]) char = opts.charmap[char].replace(opts.replacement, " ");
1033
+ else if (char.includes(opts.replacement)) char = char.replace(opts.replacement, " ");
1034
+ else char = char.replace(disallowedChars, "");
1035
+ result += char;
1036
+ }
1037
+ if (opts.remove) result = result.replace(opts.remove, "");
1038
+ if (opts.trim) result = result.trim();
1039
+ result = result.replace(/\s+/g, opts.replacement);
1040
+ if (opts.lower) result = result.toLowerCase();
1041
+ return result;
1042
+ }
1043
+ const initialMulticharmap = {
1044
+ फ़: "Fi",
1045
+ ग़: "Ghi",
1046
+ ख़: "Khi",
1047
+ क़: "Qi",
1048
+ ड़: "ugDha",
1049
+ ढ़: "ugDhha",
1050
+ य़: "Yi",
1051
+ ज़: "Za",
1052
+ בִי: "i",
1053
+ בֵ: "e",
1054
+ בֵי: "e",
1055
+ בֶ: "e",
1056
+ בַ: "a",
1057
+ בָ: "a",
1058
+ בֹ: "o",
1059
+ וֹ: "o",
1060
+ בֻ: "u",
1061
+ וּ: "u",
1062
+ בּ: "b",
1063
+ כּ: "k",
1064
+ ךּ: "k",
1065
+ פּ: "p",
1066
+ שׁ: "sh",
1067
+ שׂ: "s",
1068
+ בְ: "e",
1069
+ חֱ: "e",
1070
+ חֲ: "a",
1071
+ חֳ: "o",
1072
+ בִ: "i"
1073
+ };
1074
+ const initialCharmap = {
1075
+ À: "A",
1076
+ Á: "A",
1077
+ Â: "A",
1078
+ Ã: "A",
1079
+ Ä: "A",
1080
+ Å: "A",
1081
+ Æ: "AE",
1082
+ Ç: "C",
1083
+ È: "E",
1084
+ É: "E",
1085
+ Ê: "E",
1086
+ Ë: "E",
1087
+ Ì: "I",
1088
+ Í: "I",
1089
+ Î: "I",
1090
+ Ï: "I",
1091
+ Ð: "D",
1092
+ Ñ: "N",
1093
+ Ò: "O",
1094
+ Ó: "O",
1095
+ Ô: "O",
1096
+ Õ: "O",
1097
+ Ö: "O",
1098
+ Ő: "O",
1099
+ Ø: "O",
1100
+ Ō: "O",
1101
+ Ù: "U",
1102
+ Ú: "U",
1103
+ Û: "U",
1104
+ Ü: "U",
1105
+ Ű: "U",
1106
+ Ý: "Y",
1107
+ Þ: "TH",
1108
+ ß: "ss",
1109
+ à: "a",
1110
+ á: "a",
1111
+ â: "a",
1112
+ ã: "a",
1113
+ ä: "a",
1114
+ å: "a",
1115
+ æ: "ae",
1116
+ ç: "c",
1117
+ è: "e",
1118
+ é: "e",
1119
+ ê: "e",
1120
+ ë: "e",
1121
+ ì: "i",
1122
+ í: "i",
1123
+ î: "i",
1124
+ ï: "i",
1125
+ ð: "d",
1126
+ ñ: "n",
1127
+ ò: "o",
1128
+ ó: "o",
1129
+ ô: "o",
1130
+ õ: "o",
1131
+ ö: "o",
1132
+ ő: "o",
1133
+ ø: "o",
1134
+ ō: "o",
1135
+ Œ: "OE",
1136
+ œ: "oe",
1137
+ ù: "u",
1138
+ ú: "u",
1139
+ û: "u",
1140
+ ü: "u",
1141
+ ű: "u",
1142
+ ý: "y",
1143
+ þ: "th",
1144
+ ÿ: "y",
1145
+ ẞ: "SS",
1146
+ α: "a",
1147
+ β: "b",
1148
+ γ: "g",
1149
+ δ: "d",
1150
+ ε: "e",
1151
+ ζ: "z",
1152
+ η: "h",
1153
+ θ: "th",
1154
+ ι: "i",
1155
+ κ: "k",
1156
+ λ: "l",
1157
+ μ: "m",
1158
+ ν: "n",
1159
+ ξ: "3",
1160
+ ο: "o",
1161
+ π: "p",
1162
+ ρ: "r",
1163
+ σ: "s",
1164
+ τ: "t",
1165
+ υ: "y",
1166
+ φ: "f",
1167
+ χ: "x",
1168
+ ψ: "ps",
1169
+ ω: "w",
1170
+ ά: "a",
1171
+ έ: "e",
1172
+ ί: "i",
1173
+ ό: "o",
1174
+ ύ: "y",
1175
+ ή: "h",
1176
+ ώ: "w",
1177
+ ς: "s",
1178
+ ϊ: "i",
1179
+ ΰ: "y",
1180
+ ϋ: "y",
1181
+ ΐ: "i",
1182
+ Α: "A",
1183
+ Β: "B",
1184
+ Γ: "G",
1185
+ Δ: "D",
1186
+ Ε: "E",
1187
+ Ζ: "Z",
1188
+ Η: "H",
1189
+ Θ: "Th",
1190
+ Ι: "I",
1191
+ Κ: "K",
1192
+ Λ: "L",
1193
+ Μ: "M",
1194
+ Ν: "N",
1195
+ Ξ: "3",
1196
+ Ο: "O",
1197
+ Π: "P",
1198
+ Ρ: "R",
1199
+ Σ: "S",
1200
+ Τ: "T",
1201
+ Υ: "Y",
1202
+ Φ: "F",
1203
+ Χ: "X",
1204
+ Ψ: "PS",
1205
+ Ω: "W",
1206
+ Ά: "A",
1207
+ Έ: "E",
1208
+ Ί: "I",
1209
+ Ό: "O",
1210
+ Ύ: "Y",
1211
+ Ή: "H",
1212
+ Ώ: "W",
1213
+ Ϊ: "I",
1214
+ Ϋ: "Y",
1215
+ ş: "s",
1216
+ Ş: "S",
1217
+ ı: "i",
1218
+ İ: "I",
1219
+ ğ: "g",
1220
+ Ğ: "G",
1221
+ а: "a",
1222
+ б: "b",
1223
+ в: "v",
1224
+ г: "g",
1225
+ д: "d",
1226
+ е: "e",
1227
+ ё: "yo",
1228
+ ж: "zh",
1229
+ з: "z",
1230
+ и: "i",
1231
+ й: "j",
1232
+ к: "k",
1233
+ л: "l",
1234
+ м: "m",
1235
+ н: "n",
1236
+ о: "o",
1237
+ п: "p",
1238
+ р: "r",
1239
+ с: "s",
1240
+ т: "t",
1241
+ у: "u",
1242
+ ф: "f",
1243
+ х: "h",
1244
+ ц: "c",
1245
+ ч: "ch",
1246
+ ш: "sh",
1247
+ щ: "sh",
1248
+ ъ: "u",
1249
+ ы: "y",
1250
+ ь: "",
1251
+ э: "e",
1252
+ ю: "yu",
1253
+ я: "ya",
1254
+ А: "A",
1255
+ Б: "B",
1256
+ В: "V",
1257
+ Г: "G",
1258
+ Д: "D",
1259
+ Е: "E",
1260
+ Ё: "Yo",
1261
+ Ж: "Zh",
1262
+ З: "Z",
1263
+ И: "I",
1264
+ Й: "J",
1265
+ К: "K",
1266
+ Л: "L",
1267
+ М: "M",
1268
+ Н: "N",
1269
+ О: "O",
1270
+ П: "P",
1271
+ Р: "R",
1272
+ С: "S",
1273
+ Т: "T",
1274
+ У: "U",
1275
+ Ф: "F",
1276
+ Х: "H",
1277
+ Ц: "C",
1278
+ Ч: "Ch",
1279
+ Ш: "Sh",
1280
+ Щ: "Sh",
1281
+ Ъ: "U",
1282
+ Ы: "Y",
1283
+ Ь: "",
1284
+ Э: "E",
1285
+ Ю: "Yu",
1286
+ Я: "Ya",
1287
+ Є: "Ye",
1288
+ І: "I",
1289
+ Ї: "Yi",
1290
+ Ґ: "G",
1291
+ є: "ye",
1292
+ і: "i",
1293
+ ї: "yi",
1294
+ ґ: "g",
1295
+ č: "c",
1296
+ ď: "d",
1297
+ ě: "e",
1298
+ ň: "n",
1299
+ ř: "r",
1300
+ š: "s",
1301
+ ť: "t",
1302
+ ů: "u",
1303
+ ž: "z",
1304
+ Č: "C",
1305
+ Ď: "D",
1306
+ Ě: "E",
1307
+ Ň: "N",
1308
+ Ř: "R",
1309
+ Š: "S",
1310
+ Ť: "T",
1311
+ Ů: "U",
1312
+ Ž: "Z",
1313
+ ľ: "l",
1314
+ ĺ: "l",
1315
+ ŕ: "r",
1316
+ Ľ: "L",
1317
+ Ĺ: "L",
1318
+ Ŕ: "R",
1319
+ ą: "a",
1320
+ ć: "c",
1321
+ ę: "e",
1322
+ ł: "l",
1323
+ ń: "n",
1324
+ ś: "s",
1325
+ ź: "z",
1326
+ ż: "z",
1327
+ Ą: "A",
1328
+ Ć: "C",
1329
+ Ę: "E",
1330
+ Ł: "L",
1331
+ Ń: "N",
1332
+ Ś: "S",
1333
+ Ź: "Z",
1334
+ Ż: "Z",
1335
+ ā: "a",
1336
+ ē: "e",
1337
+ ģ: "g",
1338
+ ī: "i",
1339
+ ķ: "k",
1340
+ ļ: "l",
1341
+ ņ: "n",
1342
+ ū: "u",
1343
+ Ā: "A",
1344
+ Ē: "E",
1345
+ Ģ: "G",
1346
+ Ī: "I",
1347
+ Ķ: "K",
1348
+ Ļ: "L",
1349
+ Ņ: "N",
1350
+ Ū: "U",
1351
+ أ: "a",
1352
+ إ: "i",
1353
+ ب: "b",
1354
+ ت: "t",
1355
+ ث: "th",
1356
+ ج: "g",
1357
+ ح: "h",
1358
+ خ: "kh",
1359
+ د: "d",
1360
+ ذ: "th",
1361
+ ر: "r",
1362
+ ز: "z",
1363
+ س: "s",
1364
+ ش: "sh",
1365
+ ص: "s",
1366
+ ض: "d",
1367
+ ط: "t",
1368
+ ظ: "th",
1369
+ ع: "aa",
1370
+ غ: "gh",
1371
+ ف: "f",
1372
+ ق: "k",
1373
+ ك: "k",
1374
+ ل: "l",
1375
+ م: "m",
1376
+ ن: "n",
1377
+ ه: "h",
1378
+ و: "o",
1379
+ ي: "y",
1380
+ ء: "aa",
1381
+ ة: "a",
1382
+ آ: "a",
1383
+ ا: "a",
1384
+ پ: "p",
1385
+ ژ: "zh",
1386
+ گ: "g",
1387
+ چ: "ch",
1388
+ ک: "k",
1389
+ ی: "i",
1390
+ ė: "e",
1391
+ į: "i",
1392
+ ų: "u",
1393
+ Ė: "E",
1394
+ Į: "I",
1395
+ Ų: "U",
1396
+ ț: "t",
1397
+ Ț: "T",
1398
+ ţ: "t",
1399
+ Ţ: "T",
1400
+ ș: "s",
1401
+ Ș: "S",
1402
+ ă: "a",
1403
+ Ă: "A",
1404
+ Ạ: "A",
1405
+ Ả: "A",
1406
+ Ầ: "A",
1407
+ Ấ: "A",
1408
+ Ậ: "A",
1409
+ Ẩ: "A",
1410
+ Ẫ: "A",
1411
+ Ằ: "A",
1412
+ Ắ: "A",
1413
+ Ặ: "A",
1414
+ Ẳ: "A",
1415
+ Ẵ: "A",
1416
+ Ẹ: "E",
1417
+ Ẻ: "E",
1418
+ Ẽ: "E",
1419
+ Ề: "E",
1420
+ Ế: "E",
1421
+ Ệ: "E",
1422
+ Ể: "E",
1423
+ Ễ: "E",
1424
+ Ị: "I",
1425
+ Ỉ: "I",
1426
+ Ĩ: "I",
1427
+ Ọ: "O",
1428
+ Ỏ: "O",
1429
+ Ồ: "O",
1430
+ Ố: "O",
1431
+ Ộ: "O",
1432
+ Ổ: "O",
1433
+ Ỗ: "O",
1434
+ Ơ: "O",
1435
+ Ờ: "O",
1436
+ Ớ: "O",
1437
+ Ợ: "O",
1438
+ Ở: "O",
1439
+ Ỡ: "O",
1440
+ Ụ: "U",
1441
+ Ủ: "U",
1442
+ Ũ: "U",
1443
+ Ư: "U",
1444
+ Ừ: "U",
1445
+ Ứ: "U",
1446
+ Ự: "U",
1447
+ Ử: "U",
1448
+ Ữ: "U",
1449
+ Ỳ: "Y",
1450
+ Ỵ: "Y",
1451
+ Ỷ: "Y",
1452
+ Ỹ: "Y",
1453
+ Đ: "D",
1454
+ ạ: "a",
1455
+ ả: "a",
1456
+ ầ: "a",
1457
+ ấ: "a",
1458
+ ậ: "a",
1459
+ ẩ: "a",
1460
+ ẫ: "a",
1461
+ ằ: "a",
1462
+ ắ: "a",
1463
+ ặ: "a",
1464
+ ẳ: "a",
1465
+ ẵ: "a",
1466
+ ẹ: "e",
1467
+ ẻ: "e",
1468
+ ẽ: "e",
1469
+ ề: "e",
1470
+ ế: "e",
1471
+ ệ: "e",
1472
+ ể: "e",
1473
+ ễ: "e",
1474
+ ị: "i",
1475
+ ỉ: "i",
1476
+ ĩ: "i",
1477
+ ọ: "o",
1478
+ ỏ: "o",
1479
+ ồ: "o",
1480
+ ố: "o",
1481
+ ộ: "o",
1482
+ ổ: "o",
1483
+ ỗ: "o",
1484
+ ơ: "o",
1485
+ ờ: "o",
1486
+ ớ: "o",
1487
+ ợ: "o",
1488
+ ở: "o",
1489
+ ỡ: "o",
1490
+ ụ: "u",
1491
+ ủ: "u",
1492
+ ũ: "u",
1493
+ ư: "u",
1494
+ ừ: "u",
1495
+ ứ: "u",
1496
+ ự: "u",
1497
+ ử: "u",
1498
+ ữ: "u",
1499
+ ỳ: "y",
1500
+ ỵ: "y",
1501
+ ỷ: "y",
1502
+ ỹ: "y",
1503
+ đ: "d",
1504
+ Ә: "AE",
1505
+ ә: "ae",
1506
+ Ғ: "GH",
1507
+ ғ: "gh",
1508
+ Қ: "KH",
1509
+ қ: "kh",
1510
+ Ң: "NG",
1511
+ ң: "ng",
1512
+ Ү: "UE",
1513
+ ү: "ue",
1514
+ Ұ: "U",
1515
+ ұ: "u",
1516
+ Һ: "H",
1517
+ һ: "h",
1518
+ Ө: "OE",
1519
+ ө: "oe",
1520
+ ђ: "dj",
1521
+ ј: "j",
1522
+ љ: "lj",
1523
+ њ: "nj",
1524
+ ћ: "c",
1525
+ џ: "dz",
1526
+ Ђ: "Dj",
1527
+ Ј: "j",
1528
+ Љ: "Lj",
1529
+ Њ: "Nj",
1530
+ Ћ: "C",
1531
+ Џ: "Dz",
1532
+ nj: "nj",
1533
+ lj: "lj",
1534
+ Nj: "NJ",
1535
+ Lj: "LJ",
1536
+ अ: "a",
1537
+ आ: "aa",
1538
+ ए: "e",
1539
+ ई: "ii",
1540
+ ऍ: "ei",
1541
+ ऎ: "ae",
1542
+ ऐ: "ai",
1543
+ इ: "i",
1544
+ ओ: "o",
1545
+ ऑ: "oi",
1546
+ ऒ: "oii",
1547
+ ऊ: "uu",
1548
+ औ: "ou",
1549
+ उ: "u",
1550
+ ब: "B",
1551
+ भ: "Bha",
1552
+ च: "Ca",
1553
+ छ: "Chha",
1554
+ ड: "Da",
1555
+ ढ: "Dha",
1556
+ फ: "Fa",
1557
+ ग: "Ga",
1558
+ घ: "Gha",
1559
+ ग़: "Ghi",
1560
+ ह: "Ha",
1561
+ ज: "Ja",
1562
+ झ: "Jha",
1563
+ क: "Ka",
1564
+ ख: "Kha",
1565
+ ख़: "Khi",
1566
+ ल: "L",
1567
+ ळ: "Li",
1568
+ ऌ: "Li",
1569
+ ऴ: "Lii",
1570
+ ॡ: "Lii",
1571
+ म: "Ma",
1572
+ न: "Na",
1573
+ ङ: "Na",
1574
+ ञ: "Nia",
1575
+ ण: "Nae",
1576
+ ऩ: "Ni",
1577
+ ॐ: "oms",
1578
+ प: "Pa",
1579
+ क़: "Qi",
1580
+ र: "Ra",
1581
+ ऋ: "Ri",
1582
+ ॠ: "Ri",
1583
+ ऱ: "Ri",
1584
+ स: "Sa",
1585
+ श: "Sha",
1586
+ ष: "Shha",
1587
+ ट: "Ta",
1588
+ त: "Ta",
1589
+ ठ: "Tha",
1590
+ द: "Tha",
1591
+ थ: "Tha",
1592
+ ध: "Thha",
1593
+ ड़: "ugDha",
1594
+ ढ़: "ugDhha",
1595
+ व: "Va",
1596
+ य: "Ya",
1597
+ य़: "Yi",
1598
+ ज़: "Za",
1599
+ ə: "e",
1600
+ Ə: "E",
1601
+ ა: "a",
1602
+ ბ: "b",
1603
+ გ: "g",
1604
+ დ: "d",
1605
+ ე: "e",
1606
+ ვ: "v",
1607
+ ზ: "z",
1608
+ თ: "t",
1609
+ ი: "i",
1610
+ კ: "k",
1611
+ ლ: "l",
1612
+ მ: "m",
1613
+ ნ: "n",
1614
+ ო: "o",
1615
+ პ: "p",
1616
+ ჟ: "zh",
1617
+ რ: "r",
1618
+ ს: "s",
1619
+ ტ: "t",
1620
+ უ: "u",
1621
+ ფ: "p",
1622
+ ქ: "k",
1623
+ ღ: "gh",
1624
+ ყ: "q",
1625
+ შ: "sh",
1626
+ ჩ: "ch",
1627
+ ც: "ts",
1628
+ ძ: "dz",
1629
+ წ: "ts",
1630
+ ჭ: "ch",
1631
+ ხ: "kh",
1632
+ ჯ: "j",
1633
+ ჰ: "h",
1634
+ ב: "v",
1635
+ גּ: "g",
1636
+ ג: "g",
1637
+ ד: "d",
1638
+ דּ: "d",
1639
+ ה: "h",
1640
+ ו: "v",
1641
+ ז: "z",
1642
+ ח: "h",
1643
+ ט: "t",
1644
+ י: "y",
1645
+ כ: "kh",
1646
+ ך: "kh",
1647
+ ל: "l",
1648
+ מ: "m",
1649
+ ם: "m",
1650
+ נ: "n",
1651
+ ן: "n",
1652
+ ס: "s",
1653
+ פ: "f",
1654
+ ף: "f",
1655
+ ץ: "ts",
1656
+ צ: "ts",
1657
+ ק: "k",
1658
+ ר: "r",
1659
+ תּ: "t",
1660
+ ת: "t"
1661
+ };
1662
+ slug.charmap = Object.assign({}, initialCharmap);
1663
+ slug.multicharmap = Object.assign({}, initialMulticharmap);
1664
+ slug.defaults = {
1665
+ charmap: slug.charmap,
1666
+ mode: "pretty",
1667
+ modes: {
1668
+ rfc3986: {
1669
+ replacement: "-",
1670
+ remove: null,
1671
+ lower: true,
1672
+ charmap: slug.charmap,
1673
+ multicharmap: slug.multicharmap,
1674
+ trim: true
1675
+ },
1676
+ pretty: {
1677
+ replacement: "-",
1678
+ remove: null,
1679
+ lower: true,
1680
+ charmap: slug.charmap,
1681
+ multicharmap: slug.multicharmap,
1682
+ trim: true
1683
+ }
1684
+ },
1685
+ multicharmap: slug.multicharmap,
1686
+ fallback: true
1687
+ };
1688
+ slug.reset = function() {
1689
+ slug.defaults.modes.rfc3986.charmap = slug.defaults.modes.pretty.charmap = slug.charmap = slug.defaults.charmap = Object.assign({}, initialCharmap);
1690
+ slug.defaults.modes.rfc3986.multicharmap = slug.defaults.modes.pretty.multicharmap = slug.multicharmap = slug.defaults.multicharmap = Object.assign({}, initialMulticharmap);
1691
+ defaultLocale = "";
1692
+ };
1693
+ slug.extend = function(customMap) {
1694
+ const keys = Object.keys(customMap);
1695
+ const multi = {};
1696
+ const single = {};
1697
+ for (let i = 0; i < keys.length; i++) if (keys[i].length > 1) multi[keys[i]] = customMap[keys[i]];
1698
+ else single[keys[i]] = customMap[keys[i]];
1699
+ Object.assign(slug.charmap, single);
1700
+ Object.assign(slug.multicharmap, multi);
1701
+ };
1702
+ slug.setLocale = function(locale) {
1703
+ defaultLocale = locales[locale] || {};
1704
+ };
1705
+ //#endregion
1706
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1707
+ const normalizeDescriptors = (error) => {
1708
+ CORE_ERROR_PROPS.forEach((propName) => {
1709
+ normalizeDescriptor(error, propName);
1710
+ });
1711
+ };
1712
+ const CORE_ERROR_PROPS = [
1713
+ "name",
1714
+ "message",
1715
+ "stack",
1716
+ "cause",
1717
+ "errors"
1718
+ ];
1719
+ const normalizeDescriptor = (error, propName) => {
1720
+ const descriptor = getDescriptor(error, propName);
1721
+ if (descriptor === void 0) return;
1722
+ if (isReadonlyGetter(descriptor)) {
1723
+ setErrorProperty(error, propName, error[propName]);
1724
+ return;
1725
+ }
1726
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1727
+ };
1728
+ const getDescriptor = (value, propName) => {
1729
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1730
+ if (descriptor !== void 0) return descriptor;
1731
+ const prototype = Object.getPrototypeOf(value);
1732
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
1733
+ };
1734
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1735
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1736
+ const setErrorProperty = (error, propName, value) => {
1737
+ setErrorDescriptor(error, propName, { value });
1738
+ };
1739
+ const setErrorDescriptor = (error, propName, descriptor) => {
1740
+ Object.defineProperty(error, propName, {
1741
+ ...descriptor,
1742
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1743
+ enumerable: false,
1744
+ configurable: true
1745
+ });
1746
+ };
1747
+ //#endregion
1748
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1749
+ const normalizeAggregate = (error, recurse) => {
1750
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1751
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1752
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
1753
+ };
1754
+ const isDefined = (error) => error !== void 0;
1755
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1756
+ const deleteAggregateErrors = (error) => {
1757
+ delete error.errors;
1758
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1759
+ };
1760
+ //#endregion
1761
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1762
+ const normalizeCause = (error, recurse) => {
1763
+ if (!("cause" in error)) return;
1764
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1765
+ if (cause === void 0) delete error.cause;
1766
+ else setErrorProperty(error, "cause", cause);
1767
+ };
1768
+ //#endregion
1769
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1770
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1771
+ const isInstanceOfError = (value) => {
1772
+ try {
1773
+ return value instanceof Error;
1774
+ } catch {
1775
+ return false;
1776
+ }
1777
+ };
1778
+ const hasErrorTag = (value) => {
1779
+ try {
1780
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
1781
+ } catch {
1782
+ return false;
1783
+ }
1784
+ };
1785
+ const ERROR_TAGS = new Set([
1786
+ "[object Error]",
1787
+ "[object DOMException]",
1788
+ "[object DOMError]",
1789
+ "[object Exception]"
1790
+ ]);
1791
+ //#endregion
1792
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1793
+ function isPlainObject(value) {
1794
+ if (typeof value !== "object" || value === null) return false;
1795
+ const prototype = Object.getPrototypeOf(value);
1796
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1797
+ }
1798
+ //#endregion
1799
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1800
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1801
+ const isNonConfigurableProp = (error, propName) => {
1802
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1803
+ return descriptor !== void 0 && !descriptor.configurable;
1804
+ };
1805
+ const isThrowingProp = (error, propName) => {
1806
+ try {
1807
+ error[propName];
1808
+ return false;
1809
+ } catch {
1810
+ return true;
1811
+ }
1812
+ };
1813
+ //#endregion
1814
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1815
+ const setStack = (error) => {
1816
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
1817
+ };
1818
+ const getStack = (message = "", name = "Error") => {
1819
+ const { stack } = new (getErrorClass(name))(message);
1820
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1821
+ };
1822
+ const getErrorClass = (name) => {
1823
+ const descriptor = {
1824
+ value: name,
1825
+ enumerable: false,
1826
+ writable: true,
1827
+ configurable: true
1828
+ };
1829
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1830
+ Object.defineProperty(StackError.prototype, "name", descriptor);
1831
+ return StackError;
1832
+ };
1833
+ //#endregion
1834
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1835
+ const copyObject = (object) => {
1836
+ const objectCopy = {};
1837
+ for (const propName of getPropsToCopy(object)) try {
1838
+ const value = object[propName];
1839
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1840
+ Object.defineProperty(objectCopy, propName, {
1841
+ value,
1842
+ enumerable,
1843
+ configurable,
1844
+ writable
1845
+ });
1846
+ } catch {}
1847
+ return objectCopy;
1848
+ };
1849
+ const getPropsToCopy = (object) => {
1850
+ const propNames = getOwnKeys(object);
1851
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1852
+ return propNames;
1853
+ };
1854
+ const getOwnKeys = (object) => {
1855
+ try {
1856
+ return Reflect.ownKeys(object);
1857
+ } catch {
1858
+ return [];
1859
+ }
1860
+ };
1861
+ const isInheritedProp = (object, propName) => {
1862
+ try {
1863
+ return propName in object && !Object.hasOwn(object, propName);
1864
+ } catch {
1865
+ return false;
1866
+ }
1867
+ };
1868
+ //#endregion
1869
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1870
+ const objectifyError = (object) => {
1871
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1872
+ const messageA = getMessage(message, objectA);
1873
+ const error = newError(name, messageA);
1874
+ if (message === messageA) assignObjectProps(error, objectA);
1875
+ Object.entries({
1876
+ name,
1877
+ stack,
1878
+ cause,
1879
+ errors
1880
+ }).forEach(([propName, propValue]) => {
1881
+ setNewErrorProperty(error, propName, propValue);
1882
+ });
1883
+ if (stack === void 0) setStack(error);
1884
+ return error;
1885
+ };
1886
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1887
+ const safeJsonStringify = (object) => {
1888
+ try {
1889
+ return JSON.stringify(object);
1890
+ } catch {
1891
+ return safeStringify(object);
1892
+ }
1893
+ };
1894
+ const safeStringify = (object) => {
1895
+ try {
1896
+ return String(object);
1897
+ } catch {
1898
+ return "Invalid error";
1899
+ }
1900
+ };
1901
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1902
+ const MESSAGE_MAX_SIZE = 1e3;
1903
+ const newError = (name, message) => {
1904
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1905
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1906
+ return new Error(message);
1907
+ };
1908
+ const NATIVE_ERRORS = {
1909
+ Error,
1910
+ ReferenceError,
1911
+ TypeError,
1912
+ SyntaxError,
1913
+ RangeError,
1914
+ URIError,
1915
+ EvalError
1916
+ };
1917
+ const assignObjectProps = (error, object) => {
1918
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1919
+ };
1920
+ const setNewErrorProperty = (error, propName, propValue) => {
1921
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1922
+ };
1923
+ //#endregion
1924
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1925
+ const stringifyError = (value) => {
1926
+ try {
1927
+ const error = new Error(String(value));
1928
+ setStack(error);
1929
+ return error;
1930
+ } catch (error_) {
1931
+ return error_;
1932
+ }
1933
+ };
1934
+ //#endregion
1935
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1936
+ const { toString: objectToString } = Object.prototype;
1937
+ const createError = (value) => {
1938
+ if (isErrorPlainObj(value)) return objectifyError(value);
1939
+ if (!isErrorInstance(value)) return stringifyError(value);
1940
+ if (isInvalidError(value)) return objectifyError(value);
1941
+ return value;
1942
+ };
1943
+ const isErrorPlainObj = (value) => {
1944
+ try {
1945
+ return isPlainObject(value);
1946
+ } catch {
1947
+ return false;
1948
+ }
1949
+ };
1950
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1951
+ const isProxy = (value) => {
1952
+ try {
1953
+ return objectToString.call(value) === "[object Object]";
1954
+ } catch {
1955
+ return true;
1956
+ }
1957
+ };
1958
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1959
+ //#endregion
1960
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1961
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1962
+ const recurseException = (error, parents, shallow) => {
1963
+ if (parents.includes(error)) return;
1964
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1965
+ const errorA = createError(error);
1966
+ normalizeProps(errorA, recurse);
1967
+ return errorA;
1968
+ };
1969
+ const identity = (error) => error;
1970
+ const normalizeProps = (error, recurse) => {
1971
+ normalizeName(error);
1972
+ normalizeMessage(error);
1973
+ normalizeStack(error);
1974
+ normalizeCause(error, recurse);
1975
+ normalizeAggregate(error, recurse);
1976
+ normalizeDescriptors(error);
1977
+ };
1978
+ const normalizeName = (error) => {
1979
+ if (isDefinedString(error.name)) return;
1980
+ const prototypeName = Object.getPrototypeOf(error).name;
1981
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1982
+ };
1983
+ const normalizeMessage = (error) => {
1984
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1985
+ };
1986
+ const normalizeStack = (error) => {
1987
+ if (!isDefinedString(error.stack)) setStack(error);
1988
+ };
1989
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
1990
+ //#endregion
1991
+ //#region ../reactor-browser/dist/index.js
1992
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1993
+ var LZString = (function() {
1994
+ var f = String.fromCharCode;
1995
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
1996
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
1997
+ var baseReverseDic = {};
1998
+ function getBaseValue(alphabet, character) {
1999
+ if (!baseReverseDic[alphabet]) {
2000
+ baseReverseDic[alphabet] = {};
2001
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
2002
+ }
2003
+ return baseReverseDic[alphabet][character];
2004
+ }
2005
+ var LZString = {
2006
+ compressToBase64: function(input) {
2007
+ if (input == null) return "";
2008
+ var res = LZString._compress(input, 6, function(a) {
2009
+ return keyStrBase64.charAt(a);
2010
+ });
2011
+ switch (res.length % 4) {
2012
+ default:
2013
+ case 0: return res;
2014
+ case 1: return res + "===";
2015
+ case 2: return res + "==";
2016
+ case 3: return res + "=";
2017
+ }
2018
+ },
2019
+ decompressFromBase64: function(input) {
2020
+ if (input == null) return "";
2021
+ if (input == "") return null;
2022
+ return LZString._decompress(input.length, 32, function(index) {
2023
+ return getBaseValue(keyStrBase64, input.charAt(index));
2024
+ });
2025
+ },
2026
+ compressToUTF16: function(input) {
2027
+ if (input == null) return "";
2028
+ return LZString._compress(input, 15, function(a) {
2029
+ return f(a + 32);
2030
+ }) + " ";
2031
+ },
2032
+ decompressFromUTF16: function(compressed) {
2033
+ if (compressed == null) return "";
2034
+ if (compressed == "") return null;
2035
+ return LZString._decompress(compressed.length, 16384, function(index) {
2036
+ return compressed.charCodeAt(index) - 32;
2037
+ });
2038
+ },
2039
+ compressToUint8Array: function(uncompressed) {
2040
+ var compressed = LZString.compress(uncompressed);
2041
+ var buf = new Uint8Array(compressed.length * 2);
2042
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2043
+ var current_value = compressed.charCodeAt(i);
2044
+ buf[i * 2] = current_value >>> 8;
2045
+ buf[i * 2 + 1] = current_value % 256;
2046
+ }
2047
+ return buf;
2048
+ },
2049
+ decompressFromUint8Array: function(compressed) {
2050
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2051
+ else {
2052
+ var buf = new Array(compressed.length / 2);
2053
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2054
+ var result = [];
2055
+ buf.forEach(function(c) {
2056
+ result.push(f(c));
2057
+ });
2058
+ return LZString.decompress(result.join(""));
2059
+ }
2060
+ },
2061
+ compressToEncodedURIComponent: function(input) {
2062
+ if (input == null) return "";
2063
+ return LZString._compress(input, 6, function(a) {
2064
+ return keyStrUriSafe.charAt(a);
2065
+ });
2066
+ },
2067
+ decompressFromEncodedURIComponent: function(input) {
2068
+ if (input == null) return "";
2069
+ if (input == "") return null;
2070
+ input = input.replace(/ /g, "+");
2071
+ return LZString._decompress(input.length, 32, function(index) {
2072
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
2073
+ });
2074
+ },
2075
+ compress: function(uncompressed) {
2076
+ return LZString._compress(uncompressed, 16, function(a) {
2077
+ return f(a);
2078
+ });
2079
+ },
2080
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2081
+ if (uncompressed == null) return "";
2082
+ 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;
2083
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
2084
+ context_c = uncompressed.charAt(ii);
2085
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2086
+ context_dictionary[context_c] = context_dictSize++;
2087
+ context_dictionaryToCreate[context_c] = true;
2088
+ }
2089
+ context_wc = context_w + context_c;
2090
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2091
+ else {
2092
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2093
+ if (context_w.charCodeAt(0) < 256) {
2094
+ for (i = 0; i < context_numBits; i++) {
2095
+ context_data_val = context_data_val << 1;
2096
+ if (context_data_position == bitsPerChar - 1) {
2097
+ context_data_position = 0;
2098
+ context_data.push(getCharFromInt(context_data_val));
2099
+ context_data_val = 0;
2100
+ } else context_data_position++;
2101
+ }
2102
+ value = context_w.charCodeAt(0);
2103
+ for (i = 0; i < 8; i++) {
2104
+ context_data_val = context_data_val << 1 | value & 1;
2105
+ if (context_data_position == bitsPerChar - 1) {
2106
+ context_data_position = 0;
2107
+ context_data.push(getCharFromInt(context_data_val));
2108
+ context_data_val = 0;
2109
+ } else context_data_position++;
2110
+ value = value >> 1;
2111
+ }
2112
+ } else {
2113
+ value = 1;
2114
+ for (i = 0; i < context_numBits; i++) {
2115
+ context_data_val = context_data_val << 1 | value;
2116
+ if (context_data_position == bitsPerChar - 1) {
2117
+ context_data_position = 0;
2118
+ context_data.push(getCharFromInt(context_data_val));
2119
+ context_data_val = 0;
2120
+ } else context_data_position++;
2121
+ value = 0;
2122
+ }
2123
+ value = context_w.charCodeAt(0);
2124
+ for (i = 0; i < 16; i++) {
2125
+ context_data_val = context_data_val << 1 | value & 1;
2126
+ if (context_data_position == bitsPerChar - 1) {
2127
+ context_data_position = 0;
2128
+ context_data.push(getCharFromInt(context_data_val));
2129
+ context_data_val = 0;
2130
+ } else context_data_position++;
2131
+ value = value >> 1;
2132
+ }
2133
+ }
2134
+ context_enlargeIn--;
2135
+ if (context_enlargeIn == 0) {
2136
+ context_enlargeIn = Math.pow(2, context_numBits);
2137
+ context_numBits++;
2138
+ }
2139
+ delete context_dictionaryToCreate[context_w];
2140
+ } else {
2141
+ value = context_dictionary[context_w];
2142
+ for (i = 0; i < context_numBits; i++) {
2143
+ context_data_val = context_data_val << 1 | value & 1;
2144
+ if (context_data_position == bitsPerChar - 1) {
2145
+ context_data_position = 0;
2146
+ context_data.push(getCharFromInt(context_data_val));
2147
+ context_data_val = 0;
2148
+ } else context_data_position++;
2149
+ value = value >> 1;
2150
+ }
2151
+ }
2152
+ context_enlargeIn--;
2153
+ if (context_enlargeIn == 0) {
2154
+ context_enlargeIn = Math.pow(2, context_numBits);
2155
+ context_numBits++;
2156
+ }
2157
+ context_dictionary[context_wc] = context_dictSize++;
2158
+ context_w = String(context_c);
2159
+ }
2160
+ }
2161
+ if (context_w !== "") {
2162
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2163
+ if (context_w.charCodeAt(0) < 256) {
2164
+ for (i = 0; i < context_numBits; i++) {
2165
+ context_data_val = context_data_val << 1;
2166
+ if (context_data_position == bitsPerChar - 1) {
2167
+ context_data_position = 0;
2168
+ context_data.push(getCharFromInt(context_data_val));
2169
+ context_data_val = 0;
2170
+ } else context_data_position++;
2171
+ }
2172
+ value = context_w.charCodeAt(0);
2173
+ for (i = 0; i < 8; i++) {
2174
+ context_data_val = context_data_val << 1 | value & 1;
2175
+ if (context_data_position == bitsPerChar - 1) {
2176
+ context_data_position = 0;
2177
+ context_data.push(getCharFromInt(context_data_val));
2178
+ context_data_val = 0;
2179
+ } else context_data_position++;
2180
+ value = value >> 1;
2181
+ }
2182
+ } else {
2183
+ value = 1;
2184
+ for (i = 0; i < context_numBits; i++) {
2185
+ context_data_val = context_data_val << 1 | value;
2186
+ if (context_data_position == bitsPerChar - 1) {
2187
+ context_data_position = 0;
2188
+ context_data.push(getCharFromInt(context_data_val));
2189
+ context_data_val = 0;
2190
+ } else context_data_position++;
2191
+ value = 0;
2192
+ }
2193
+ value = context_w.charCodeAt(0);
2194
+ for (i = 0; i < 16; i++) {
2195
+ context_data_val = context_data_val << 1 | value & 1;
2196
+ if (context_data_position == bitsPerChar - 1) {
2197
+ context_data_position = 0;
2198
+ context_data.push(getCharFromInt(context_data_val));
2199
+ context_data_val = 0;
2200
+ } else context_data_position++;
2201
+ value = value >> 1;
2202
+ }
2203
+ }
2204
+ context_enlargeIn--;
2205
+ if (context_enlargeIn == 0) {
2206
+ context_enlargeIn = Math.pow(2, context_numBits);
2207
+ context_numBits++;
2208
+ }
2209
+ delete context_dictionaryToCreate[context_w];
2210
+ } else {
2211
+ value = context_dictionary[context_w];
2212
+ for (i = 0; i < context_numBits; i++) {
2213
+ context_data_val = context_data_val << 1 | value & 1;
2214
+ if (context_data_position == bitsPerChar - 1) {
2215
+ context_data_position = 0;
2216
+ context_data.push(getCharFromInt(context_data_val));
2217
+ context_data_val = 0;
2218
+ } else context_data_position++;
2219
+ value = value >> 1;
2220
+ }
2221
+ }
2222
+ context_enlargeIn--;
2223
+ if (context_enlargeIn == 0) {
2224
+ context_enlargeIn = Math.pow(2, context_numBits);
2225
+ context_numBits++;
2226
+ }
2227
+ }
2228
+ value = 2;
2229
+ for (i = 0; i < context_numBits; i++) {
2230
+ context_data_val = context_data_val << 1 | value & 1;
2231
+ if (context_data_position == bitsPerChar - 1) {
2232
+ context_data_position = 0;
2233
+ context_data.push(getCharFromInt(context_data_val));
2234
+ context_data_val = 0;
2235
+ } else context_data_position++;
2236
+ value = value >> 1;
2237
+ }
2238
+ while (true) {
2239
+ context_data_val = context_data_val << 1;
2240
+ if (context_data_position == bitsPerChar - 1) {
2241
+ context_data.push(getCharFromInt(context_data_val));
2242
+ break;
2243
+ } else context_data_position++;
2244
+ }
2245
+ return context_data.join("");
2246
+ },
2247
+ decompress: function(compressed) {
2248
+ if (compressed == null) return "";
2249
+ if (compressed == "") return null;
2250
+ return LZString._decompress(compressed.length, 32768, function(index) {
2251
+ return compressed.charCodeAt(index);
2252
+ });
2253
+ },
2254
+ _decompress: function(length, resetValue, getNextValue) {
2255
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2256
+ val: getNextValue(0),
2257
+ position: resetValue,
2258
+ index: 1
2259
+ };
2260
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
2261
+ bits = 0;
2262
+ maxpower = Math.pow(2, 2);
2263
+ power = 1;
2264
+ while (power != maxpower) {
2265
+ resb = data.val & data.position;
2266
+ data.position >>= 1;
2267
+ if (data.position == 0) {
2268
+ data.position = resetValue;
2269
+ data.val = getNextValue(data.index++);
2270
+ }
2271
+ bits |= (resb > 0 ? 1 : 0) * power;
2272
+ power <<= 1;
2273
+ }
2274
+ switch (bits) {
2275
+ case 0:
2276
+ bits = 0;
2277
+ maxpower = Math.pow(2, 8);
2278
+ power = 1;
2279
+ while (power != maxpower) {
2280
+ resb = data.val & data.position;
2281
+ data.position >>= 1;
2282
+ if (data.position == 0) {
2283
+ data.position = resetValue;
2284
+ data.val = getNextValue(data.index++);
2285
+ }
2286
+ bits |= (resb > 0 ? 1 : 0) * power;
2287
+ power <<= 1;
2288
+ }
2289
+ c = f(bits);
2290
+ break;
2291
+ case 1:
2292
+ bits = 0;
2293
+ maxpower = Math.pow(2, 16);
2294
+ power = 1;
2295
+ while (power != maxpower) {
2296
+ resb = data.val & data.position;
2297
+ data.position >>= 1;
2298
+ if (data.position == 0) {
2299
+ data.position = resetValue;
2300
+ data.val = getNextValue(data.index++);
2301
+ }
2302
+ bits |= (resb > 0 ? 1 : 0) * power;
2303
+ power <<= 1;
2304
+ }
2305
+ c = f(bits);
2306
+ break;
2307
+ case 2: return "";
2308
+ }
2309
+ dictionary[3] = c;
2310
+ w = c;
2311
+ result.push(c);
2312
+ while (true) {
2313
+ if (data.index > length) return "";
2314
+ bits = 0;
2315
+ maxpower = Math.pow(2, numBits);
2316
+ power = 1;
2317
+ while (power != maxpower) {
2318
+ resb = data.val & data.position;
2319
+ data.position >>= 1;
2320
+ if (data.position == 0) {
2321
+ data.position = resetValue;
2322
+ data.val = getNextValue(data.index++);
2323
+ }
2324
+ bits |= (resb > 0 ? 1 : 0) * power;
2325
+ power <<= 1;
2326
+ }
2327
+ switch (c = bits) {
2328
+ case 0:
2329
+ bits = 0;
2330
+ maxpower = Math.pow(2, 8);
2331
+ power = 1;
2332
+ while (power != maxpower) {
2333
+ resb = data.val & data.position;
2334
+ data.position >>= 1;
2335
+ if (data.position == 0) {
2336
+ data.position = resetValue;
2337
+ data.val = getNextValue(data.index++);
2338
+ }
2339
+ bits |= (resb > 0 ? 1 : 0) * power;
2340
+ power <<= 1;
2341
+ }
2342
+ dictionary[dictSize++] = f(bits);
2343
+ c = dictSize - 1;
2344
+ enlargeIn--;
2345
+ break;
2346
+ case 1:
2347
+ bits = 0;
2348
+ maxpower = Math.pow(2, 16);
2349
+ power = 1;
2350
+ while (power != maxpower) {
2351
+ resb = data.val & data.position;
2352
+ data.position >>= 1;
2353
+ if (data.position == 0) {
2354
+ data.position = resetValue;
2355
+ data.val = getNextValue(data.index++);
2356
+ }
2357
+ bits |= (resb > 0 ? 1 : 0) * power;
2358
+ power <<= 1;
2359
+ }
2360
+ dictionary[dictSize++] = f(bits);
2361
+ c = dictSize - 1;
2362
+ enlargeIn--;
2363
+ break;
2364
+ case 2: return result.join("");
2365
+ }
2366
+ if (enlargeIn == 0) {
2367
+ enlargeIn = Math.pow(2, numBits);
2368
+ numBits++;
2369
+ }
2370
+ if (dictionary[c]) entry = dictionary[c];
2371
+ else if (c === dictSize) entry = w + w.charAt(0);
2372
+ else return null;
2373
+ result.push(entry);
2374
+ dictionary[dictSize++] = w + entry.charAt(0);
2375
+ enlargeIn--;
2376
+ w = entry;
2377
+ if (enlargeIn == 0) {
2378
+ enlargeIn = Math.pow(2, numBits);
2379
+ numBits++;
2380
+ }
2381
+ }
2382
+ }
2383
+ };
2384
+ return LZString;
2385
+ })();
2386
+ if (typeof define === "function" && define.amd) define(function() {
2387
+ return LZString;
2388
+ });
2389
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2390
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2391
+ return LZString;
2392
+ });
2393
+ })))(), 1);
2394
+ var DocumentModelNotFoundError = class extends Error {
2395
+ documentType;
2396
+ name = "DocumentModelNotFoundError";
2397
+ constructor(documentType) {
2398
+ super(`Document model module for type ${documentType} not found`);
2399
+ this.documentType = documentType;
2400
+ }
2401
+ static isError(error) {
2402
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2403
+ }
2404
+ };
2405
+ var DocumentTypeMismatchError = class extends Error {
2406
+ constructor(documentId, expectedType, actualType) {
2407
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2408
+ }
2409
+ };
2410
+ var NoSelectedDocumentError = class extends Error {
2411
+ constructor() {
2412
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2413
+ }
2414
+ };
2415
+ function getUserPermissions() {
2416
+ const user = window.ph?.renown?.user;
2417
+ const allowList = window.ph?.allowList;
2418
+ if (!allowList) return {
2419
+ isAllowedToCreateDocuments: true,
2420
+ isAllowedToEditDocuments: true
2421
+ };
2422
+ return {
2423
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2424
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2425
+ };
2426
+ }
2427
+ const BASE_STATE_KEYS = new Set(["auth"]);
2428
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2429
+ async function downloadFile(document, fileName) {
2430
+ try {
2431
+ const data = await createZip(document);
2432
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2433
+ const link = window.document.createElement("a");
2434
+ link.style.display = "none";
2435
+ link.href = URL.createObjectURL(blob);
2436
+ link.download = fileName;
2437
+ window.document.body.appendChild(link);
2438
+ link.click();
2439
+ window.document.body.removeChild(link);
2440
+ } catch (e) {
2441
+ logger.error(e instanceof Error ? e.message : String(e));
2442
+ }
2443
+ }
2444
+ async function getDocumentExtension(document) {
2445
+ const documentType = document.header.documentType;
2446
+ let rawExtension;
2447
+ if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2448
+ else {
2449
+ const reactorClient = window.ph?.reactorClient;
2450
+ if (reactorClient) {
2451
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2452
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2453
+ }
2454
+ }
2455
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2456
+ }
2457
+ /**
2458
+ * Fetches all operations for a document using cursor-based pagination.
2459
+ * The reactor client handles multi-scope cursors transparently via
2460
+ * composite cursors, so all scopes are fetched in a single paginated stream.
2461
+ */
2462
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2463
+ const scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));
2464
+ const operations = {};
2465
+ for (const scope of scopes) operations[scope] = [];
2466
+ let cursor = "";
2467
+ do {
2468
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2469
+ cursor,
2470
+ limit: pageSize
2471
+ });
2472
+ for (const op of page.results) {
2473
+ const scope = op.action.scope ?? "global";
2474
+ if (operations[scope]) operations[scope].push(op);
2475
+ }
2476
+ cursor = page.nextCursor ?? "";
2477
+ } while (cursor);
2478
+ return operations;
2479
+ }
2480
+ function extractInitialState(documentScopeOps) {
2481
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2482
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2483
+ const input = upgradeOp.action.input;
2484
+ const initialState = input.initialState ?? input.state;
2485
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2486
+ return initialState;
2487
+ }
2488
+ function filterDomainOperations(operations) {
2489
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2490
+ }
2491
+ async function exportFile(document, suggestedName) {
2492
+ const reactorClient = window.ph?.reactorClient;
2493
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2494
+ const operations = await fetchDocumentOperations(reactorClient, document);
2495
+ const initialState = extractInitialState(operations["document"] ?? []);
2496
+ const documentWithOps = {
2497
+ ...document,
2498
+ operations,
2499
+ initialState
2500
+ };
2501
+ const extension = await getDocumentExtension(documentWithOps);
2502
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2503
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2504
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2505
+ try {
2506
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2507
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
2508
+ return fileHandle;
2509
+ } catch (e) {
2510
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2511
+ }
2512
+ }
2513
+ async function loadFile(path) {
2514
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2515
+ const reactorClient = window.ph?.reactorClient;
2516
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2517
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2518
+ const documentModelModule = documentModelModules.find((module) => module.documentModel.global.id === baseDocument.header.documentType);
2519
+ if (!documentModelModule) throw new DocumentModelNotFoundError(baseDocument.header.documentType);
2520
+ return documentModelModule.utils.loadFromInput(path);
2521
+ }
2522
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2523
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2524
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2525
+ const reactorClient = window.ph?.reactorClient;
2526
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2527
+ const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2528
+ const newDocument = document ?? documentModelModule.utils.createDocument();
2529
+ newDocument.header.name = name;
2530
+ if (preferredEditor) newDocument.header.meta = {
2531
+ ...newDocument.header.meta,
2532
+ preferredEditor
2533
+ };
2534
+ let newDoc;
2535
+ try {
2536
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2537
+ } catch (e) {
2538
+ logger.error("Error adding document: @error", e);
2539
+ throw new Error("There was an error adding document", { cause: e });
2540
+ }
2541
+ return {
2542
+ id: newDoc.header.id,
2543
+ name: newDoc.header.name,
2544
+ documentType,
2545
+ parentFolder: parentFolder ?? null,
2546
+ kind: "file"
2547
+ };
2548
+ }
2549
+ async function addFile(file, driveId, name, parentFolder) {
2550
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2551
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2552
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2553
+ const document = await loadFile(file);
2554
+ let duplicateId = false;
2555
+ const reactorClient = window.ph?.reactorClient;
2556
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2557
+ try {
2558
+ await reactorClient.get(document.header.id);
2559
+ duplicateId = true;
2560
+ } catch {}
2561
+ const documentId = duplicateId ? generateId() : document.header.id;
2562
+ const header = createPresignedHeader(documentId, document.header.documentType);
2563
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2564
+ header.meta = document.header.meta;
2565
+ header.name = name || document.header.name;
2566
+ const initialDocument = {
2567
+ ...document,
2568
+ header,
2569
+ state: document.initialState,
2570
+ operations: Object.keys(document.operations).reduce((acc, key) => {
2571
+ acc[key] = [];
2572
+ return acc;
2573
+ }, {})
2574
+ };
2575
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2576
+ await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2577
+ }
2578
+ async function addFolder(driveId, name, parentFolder) {
2579
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2580
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2581
+ const reactorClient = window.ph?.reactorClient;
2582
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2583
+ await reactorClient.get(driveId);
2584
+ const folderId = generateId();
2585
+ const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2586
+ id: folderId,
2587
+ name,
2588
+ parentFolder
2589
+ })])).state.global.nodes.find((node) => node.id === folderId);
2590
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2591
+ return node;
2592
+ }
2593
+ async function renameNode(driveId, nodeId, name) {
2594
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2595
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2596
+ const reactorClient = window.ph?.reactorClient;
2597
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2598
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2599
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
2600
+ id: nodeId,
2601
+ name
2602
+ })])).state.global.nodes.find((n) => n.id === nodeId);
2603
+ if (!node) throw new Error("There was an error renaming node in the drive");
2604
+ return node;
2605
+ }
2606
+ async function renameDriveNode(driveId, nodeId, name) {
2607
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2608
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2609
+ const reactorClient = window.ph?.reactorClient;
2610
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2611
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2612
+ await reactorClient.execute(driveId, "main", [updateNode({
2613
+ id: nodeId,
2614
+ name
2615
+ })]);
2616
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2617
+ }
2618
+ async function moveNodeById(args) {
2619
+ const { driveId, srcId, targetId } = args;
2620
+ if (!driveId || !srcId) return;
2621
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2622
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2623
+ const reactorClient = window.ph?.reactorClient;
2624
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2625
+ const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2626
+ if (t(targetParentFolder, srcId)) return;
2627
+ return await reactorClient.execute(driveId, "main", [moveNode({
2628
+ srcFolder: srcId,
2629
+ targetParentFolder
2630
+ })]);
2631
+ }
2632
+ async function moveNode$1(driveId, src, target) {
2633
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2634
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2635
+ const reactorClient = window.ph?.reactorClient;
2636
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2637
+ return await reactorClient.execute(driveId, "main", [moveNode({
2638
+ srcFolder: src.id,
2639
+ targetParentFolder: target?.id
2640
+ })]);
2641
+ }
2642
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
2643
+ const documentModule = await reactor.getDocumentModelModule(document.header.documentType);
2644
+ return replayDocument(document.initialState, document.operations, documentModule.reducer, createPresignedHeader(newId, document.header.documentType));
2645
+ }
2646
+ async function copyNode$1(driveId, src, target) {
2647
+ const reactor = window.ph?.reactorClient;
2648
+ if (!reactor) return;
2649
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2650
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2651
+ const drive = await reactor.get(driveId);
2652
+ const copyNodesInput = generateNodesCopy({
2653
+ srcId: src.id,
2654
+ targetParentFolder: target?.id,
2655
+ targetName: src.name
2656
+ }, () => generateId(), drive.state.global.nodes);
2657
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
2658
+ for (const copyNodeInput of copyNodesInput) {
2659
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2660
+ if (node) {
2661
+ const resolvedName = handleTargetNameCollisions({
2662
+ nodes: drive.state.global.nodes,
2663
+ srcName: copyNodeInput.targetName || node.name,
2664
+ srcKind: isFileNode(node) ? "file" : "folder",
2665
+ targetParentFolder: copyNodeInput.targetParentFolder || null
2666
+ });
2667
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2668
+ }
2669
+ }
2670
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2671
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2672
+ return node !== void 0 && isFileNode(node);
2673
+ });
2674
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2675
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2676
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2677
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2678
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2679
+ } catch (e) {
2680
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2681
+ }
2682
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2683
+ }
2684
+ const baseDocumentModelsMap = {
2685
+ DocumentModel: documentModelDocumentModelModule,
2686
+ DocumentDrive: driveDocumentModelModule,
2687
+ ReactorDrive: reactorDriveDocumentModelModule
2688
+ };
2689
+ Object.values(baseDocumentModelsMap);
2690
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2691
+ /** Sets whether external controls are enabled for a given editor. */
2692
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2693
+ /** Gets whether external controls are enabled for a given editor. */
2694
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2695
+ isExternalControlsEnabledEventFunctions.addEventHandler;
2696
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2697
+ /** Sets whether drag and drop is enabled for a given app. */
2698
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2699
+ /** Gets whether drag and drop is enabled for a given app. */
2700
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2701
+ isDragAndDropEnabledEventFunctions.addEventHandler;
2702
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2703
+ /** Sets the allowed document types for a given app. */
2704
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2705
+ /** Defines the document types a drive supports.
2706
+ *
2707
+ * Defaults to all of the document types registered in the reactor.
2708
+ */
2709
+ function useAllowedDocumentTypes() {
2710
+ return allowedDocumentTypesEventFunctions.useValue();
2711
+ }
2712
+ allowedDocumentTypesEventFunctions.addEventHandler;
2713
+ const phAppConfigSetters = {
2714
+ allowedDocumentTypes: setAllowedDocumentTypes,
2715
+ isDragAndDropEnabled: setIsDragAndDropEnabled
2716
+ };
2717
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2718
+ const phAppConfigHooks = {
2719
+ allowedDocumentTypes: useAllowedDocumentTypes,
2720
+ isDragAndDropEnabled: useIsDragAndDropEnabled
2721
+ };
2722
+ const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
2723
+ const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
2724
+ const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
2725
+ const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
2726
+ const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
2727
+ const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
2728
+ const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
2729
+ const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
2730
+ const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
2731
+ const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
2732
+ const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
2733
+ const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
2734
+ const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
2735
+ const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
2736
+ const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2737
+ const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
2738
+ const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
2739
+ const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
2740
+ const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
2741
+ const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
2742
+ const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
2743
+ const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
2744
+ const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2745
+ const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
2746
+ const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
2747
+ const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
2748
+ const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
2749
+ const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
2750
+ const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
2751
+ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
2752
+ const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2753
+ const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2754
+ const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2755
+ const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2756
+ const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2757
+ const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
2758
+ const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
2759
+ const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
2760
+ const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
2761
+ const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
2762
+ /** Sets the enabled editors for Connect. */
2763
+ const setEnabledEditors = enabledEditorsEventFunctions.setValue;
2764
+ /** Gets the enabled editors for Connect. */
2765
+ const useEnabledEditors = enabledEditorsEventFunctions.useValue;
2766
+ enabledEditorsEventFunctions.addEventHandler;
2767
+ const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
2768
+ /** Sets the disabled editors for Connect. */
2769
+ const setDisabledEditors = disabledEditorsEventFunctions.setValue;
2770
+ /** Gets the disabled editors for Connect. */
2771
+ const useDisabledEditors = disabledEditorsEventFunctions.useValue;
2772
+ disabledEditorsEventFunctions.addEventHandler;
2773
+ const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
2774
+ /** Sets the isRelationalProcessorsEnabled for Connect. */
2775
+ const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
2776
+ /** Gets the isRelationalProcessorsEnabled for Connect. */
2777
+ const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
2778
+ isRelationalProcessorsEnabled.addEventHandler;
2779
+ const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
2780
+ /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
2781
+ const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
2782
+ /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
2783
+ const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
2784
+ isExternalRelationalProcessorsEnabled.addEventHandler;
2785
+ const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
2786
+ /** Sets the isAnalyticsEnabled for Connect. */
2787
+ const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
2788
+ /** Gets the isAnalyticsEnabled for Connect. */
2789
+ const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
2790
+ isAnalyticsEnabledEventFunctions.addEventHandler;
2791
+ const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
2792
+ /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
2793
+ const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
2794
+ /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
2795
+ const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
2796
+ isAnalyticsExternalProcessorsEnabled.addEventHandler;
2797
+ const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
2798
+ /** Sets the analytics database name for Connect. */
2799
+ const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
2800
+ /** Gets the analytics database name for Connect. */
2801
+ const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
2802
+ analyticsDatabaseNameEventFunctions.addEventHandler;
2803
+ const logLevelEventFunctions = makePHEventFunctions("logLevel");
2804
+ /** Sets the log level for Connect. */
2805
+ const setLogLevel = logLevelEventFunctions.setValue;
2806
+ /** Gets the log level for Connect. */
2807
+ const useLogLevel = logLevelEventFunctions.useValue;
2808
+ logLevelEventFunctions.addEventHandler;
2809
+ const allowListEventFunctions = makePHEventFunctions("allowList");
2810
+ /** Sets the allow list for Connect. */
2811
+ const setAllowList = allowListEventFunctions.setValue;
2812
+ /** Gets the allow list for Connect. */
2813
+ const useAllowList = allowListEventFunctions.useValue;
2814
+ allowListEventFunctions.addEventHandler;
2815
+ const nonUserConfigSetters = {
2816
+ routerBasename: setRouterBasename,
2817
+ version: setVersion,
2818
+ requiresHardRefresh: setRequiresHardRefresh,
2819
+ warnOutdatedApp: setWarnOutdatedApp,
2820
+ studioMode: setStudioMode,
2821
+ basePath: setBasePath,
2822
+ versionCheckInterval: setVersionCheckInterval,
2823
+ cliVersion: setCliVersion,
2824
+ fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
2825
+ isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
2826
+ gaTrackingId: setGaTrackingId,
2827
+ defaultDrivesUrl: setDefaultDrivesUrl,
2828
+ drivesPreserveStrategy: setDrivesPreserveStrategy,
2829
+ isLocalDrivesEnabled: setIsLocalDrivesEnabled,
2830
+ isAddDriveEnabled: setIsAddDriveEnabled,
2831
+ isPublicDrivesEnabled: setIsPublicDrivesEnabled,
2832
+ isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
2833
+ isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
2834
+ isCloudDrivesEnabled: setIsCloudDrivesEnabled,
2835
+ isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
2836
+ isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
2837
+ isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
2838
+ isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
2839
+ isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
2840
+ isEditorReadModeEnabled: setIsEditorReadModeEnabled,
2841
+ isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
2842
+ isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
2843
+ isAnalyticsEnabled: setIsAnalyticsEnabled,
2844
+ analyticsDatabaseName: setAnalyticsDatabaseName,
2845
+ isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
2846
+ isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
2847
+ isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
2848
+ isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
2849
+ renownUrl: setRenownUrl,
2850
+ renownNetworkId: setRenownNetworkId,
2851
+ renownChainId: setRenownChainId,
2852
+ sentryRelease: setSentryRelease,
2853
+ sentryDsn: setSentryDsn,
2854
+ sentryEnv: setSentryEnv,
2855
+ isSentryTracingEnabled: setIsSentryTracingEnabled,
2856
+ isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
2857
+ isExternalPackagesEnabled: setIsExternalPackagesEnabled,
2858
+ allowList: setAllowList,
2859
+ logLevel: setLogLevel,
2860
+ disabledEditors: setDisabledEditors,
2861
+ enabledEditors: setEnabledEditors
2862
+ };
2863
+ const phGlobalConfigSetters = {
2864
+ ...phAppConfigSetters,
2865
+ ...phDocumentEditorConfigSetters,
2866
+ ...nonUserConfigSetters
2867
+ };
2868
+ const nonUserConfigHooks = {
2869
+ routerBasename: useRouterBasename,
2870
+ version: useVersion,
2871
+ requiresHardRefresh: useRequiresHardRefresh,
2872
+ warnOutdatedApp: useWarnOutdatedApp,
2873
+ studioMode: useStudioMode,
2874
+ basePath: useBasePath,
2875
+ versionCheckInterval: useVersionCheckInterval,
2876
+ cliVersion: useCliVersion,
2877
+ fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
2878
+ isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
2879
+ gaTrackingId: useGaTrackingId,
2880
+ defaultDrivesUrl: useDefaultDrivesUrl,
2881
+ drivesPreserveStrategy: useDrivesPreserveStrategy,
2882
+ isAddDriveEnabled: useIsAddDriveEnabled,
2883
+ isPublicDrivesEnabled: useIsPublicDrivesEnabled,
2884
+ isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
2885
+ isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
2886
+ isCloudDrivesEnabled: useIsCloudDrivesEnabled,
2887
+ isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
2888
+ isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
2889
+ isLocalDrivesEnabled: useIsLocalDrivesEnabled,
2890
+ isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
2891
+ isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
2892
+ isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
2893
+ isEditorReadModeEnabled: useIsEditorReadModeEnabled,
2894
+ isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
2895
+ isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
2896
+ isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
2897
+ renownUrl: useRenownUrl,
2898
+ renownNetworkId: useRenownNetworkId,
2899
+ renownChainId: useRenownChainId,
2900
+ sentryRelease: useSentryRelease,
2901
+ sentryDsn: useSentryDsn,
2902
+ sentryEnv: useSentryEnv,
2903
+ isSentryTracingEnabled: useIsSentryTracingEnabled,
2904
+ isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
2905
+ isExternalPackagesEnabled: useIsExternalPackagesEnabled,
2906
+ allowList: useAllowList,
2907
+ isAnalyticsEnabled: useIsAnalyticsEnabled,
2908
+ isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
2909
+ isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
2910
+ isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
2911
+ analyticsDatabaseName: useAnalyticsDatabaseName,
2912
+ logLevel: useLogLevel,
2913
+ disabledEditors: useDisabledEditors,
2914
+ enabledEditors: useEnabledEditors
2915
+ };
2916
+ ({
2917
+ ...phAppConfigHooks,
2918
+ ...phDocumentEditorConfigHooks,
2919
+ ...nonUserConfigHooks
2920
+ });
2921
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2922
+ attachmentServiceEventFunctions.useValue;
2923
+ attachmentServiceEventFunctions.setValue;
2924
+ attachmentServiceEventFunctions.addEventHandler;
2925
+ const featuresEventFunctions = makePHEventFunctions("features");
2926
+ featuresEventFunctions.useValue;
2927
+ featuresEventFunctions.setValue;
2928
+ featuresEventFunctions.addEventHandler;
2929
+ function resolveUrlPathname(path) {
2930
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2931
+ }
2932
+ /** Returns the current path without the base path */
2933
+ function getPathWithoutBase(path) {
2934
+ const basePath = window.ph?.basePath ?? "/";
2935
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2936
+ }
2937
+ /** Makes a URL component for a node. */
2938
+ function makeNodeSlug(node) {
2939
+ if (!node) return "";
2940
+ const nodeName = node.name;
2941
+ if (!nodeName) return slug(node.id);
2942
+ return slug(`${nodeName}-${node.id}`);
2943
+ }
2944
+ /** Extracts the node slug from a path.
2945
+ *
2946
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
2947
+ */
2948
+ function extractNodeSlugFromPath(path) {
2949
+ const currentPath = getPathWithoutBase(path);
2950
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2951
+ }
2952
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
2953
+ function findUuid(input) {
2954
+ if (!input) return void 0;
2955
+ 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];
2956
+ }
2957
+ function extractNodeIdFromSlug(nodeSlug) {
2958
+ return findUuid(nodeSlug);
2959
+ }
2960
+ /** Extracts the drive slug from a path.
2961
+ * Used for extracting drive ids from drive slugs in the URL.
2962
+ * Expects the path to be in the format `/d/<drive-slug>`.
2963
+ */
2964
+ function extractDriveSlugFromPath(path) {
2965
+ const currentPath = getPathWithoutBase(path);
2966
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2967
+ }
2968
+ /**
2969
+ * Creates a URL string with the given pathname while preserving existing query parameters.
2970
+ */
2971
+ function createUrlWithPreservedParams(pathname) {
2972
+ const search = window.location.search;
2973
+ return search ? `${pathname}${search}` : pathname;
2974
+ }
2975
+ const drivesEventFunctions = makePHEventFunctions("drives");
2976
+ /** Returns all of the drives in the reactor */
2977
+ const useDrives = drivesEventFunctions.useValue;
2978
+ /** Sets the drives in the reactor */
2979
+ const setDrives = drivesEventFunctions.setValue;
2980
+ drivesEventFunctions.addEventHandler;
2981
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
2982
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
2983
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
2984
+ selectedNodeIdEventFunctions.addEventHandler;
2985
+ /** Sets the selected node (file or folder). */
2986
+ function setSelectedNode(nodeOrNodeSlug) {
2987
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
2988
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
2989
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
2990
+ if (!driveSlugFromPath) return;
2991
+ if (!nodeSlug) {
2992
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
2993
+ if (pathname === window.location.pathname) return;
2994
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2995
+ return;
2996
+ }
2997
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
2998
+ if (pathname === window.location.pathname) return;
2999
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3000
+ }
3001
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
3002
+ /** Returns the selected drive id */
3003
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
3004
+ /** Sets the selected drive id */
3005
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
3006
+ selectedDriveIdEventFunctions.addEventHandler;
3007
+ /** Returns the selected drive, or undefined if no drive is selected */
3008
+ function useSelectedDriveSafe() {
3009
+ const selectedDriveId = useSelectedDriveId();
3010
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
3011
+ const [drive, dispatch] = useDispatch(selectedDrive);
3012
+ if (!selectedDrive) return [void 0, void 0];
3013
+ return [drive, dispatch];
3014
+ }
3015
+ function setSelectedDrive(driveOrDriveSlug) {
3016
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
3017
+ const drives = window.ph?.drives;
3018
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
3019
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
3020
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
3021
+ deferDriveSelection(driveSlug);
3022
+ return;
3023
+ }
3024
+ cancelPendingDriveSelection();
3025
+ setSelectedDriveId(driveId);
3026
+ if (!driveId) {
3027
+ const pathname = resolveUrlPathname("/");
3028
+ if (pathname === window.location.pathname) return;
3029
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3030
+ return;
3031
+ }
3032
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
3033
+ if (pathname === window.location.pathname) return;
3034
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3035
+ }
3036
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
3037
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
3038
+ function isInitialSyncInFlight() {
3039
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
3040
+ if (!remotes?.length) return false;
3041
+ return remotes.some((remote) => {
3042
+ try {
3043
+ const snapshot = remote.channel.getConnectionState();
3044
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
3045
+ } catch {
3046
+ return false;
3047
+ }
3048
+ });
3049
+ }
3050
+ let pendingHandler;
3051
+ let pendingTimeout;
3052
+ function cancelPendingDriveSelection() {
3053
+ if (pendingHandler) {
3054
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
3055
+ pendingHandler = void 0;
3056
+ }
3057
+ if (pendingTimeout) {
3058
+ clearTimeout(pendingTimeout);
3059
+ pendingTimeout = void 0;
3060
+ }
3061
+ }
3062
+ function deferDriveSelection(driveSlug) {
3063
+ cancelPendingDriveSelection();
3064
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
3065
+ const handler = () => {
3066
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
3067
+ cancelPendingDriveSelection();
3068
+ setSelectedDrive(driveSlug);
3069
+ setSelectedNode(nodeSlug);
3070
+ };
3071
+ pendingHandler = handler;
3072
+ window.addEventListener("ph:drivesUpdated", handler);
3073
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
3074
+ const scheduleTick = () => {
3075
+ pendingTimeout = setTimeout(() => {
3076
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
3077
+ scheduleTick();
3078
+ return;
3079
+ }
3080
+ cancelPendingDriveSelection();
3081
+ const pathname = resolveUrlPathname("/");
3082
+ if (pathname === window.location.pathname) return;
3083
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3084
+ }, DEFERRED_DRIVE_TICK_MS);
3085
+ };
3086
+ scheduleTick();
3087
+ }
3088
+ function useDropTarget() {
3089
+ const [isDropTarget, setIsDropTarget] = useState(false);
3090
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
3091
+ const targetSetter = n$1(() => setIsDropTarget(true), {
3092
+ triggerAt: "start",
3093
+ minQuietPeriodMs: 100
3094
+ });
3095
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
3096
+ triggerAt: "start",
3097
+ minQuietPeriodMs: 100
3098
+ });
3099
+ function setTarget() {
3100
+ if (!isDragAndDropEnabled) return;
3101
+ targetUnsetter.cancel();
3102
+ targetSetter.call();
3103
+ }
3104
+ function unsetTarget() {
3105
+ if (!isDragAndDropEnabled) return;
3106
+ targetSetter.cancel();
3107
+ targetUnsetter.call();
3108
+ }
3109
+ return {
3110
+ isDropTarget,
3111
+ setTarget,
3112
+ unsetTarget
3113
+ };
3114
+ }
3115
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3116
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
3117
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
3118
+ draggingNodeEventFunctions.addEventHandler;
3119
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3120
+ reducer: (_, newNode) => newNode,
3121
+ triggerAt: "start",
3122
+ minQuietPeriodMs: 100
3123
+ });
3124
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3125
+ triggerAt: "start",
3126
+ minQuietPeriodMs: 100
3127
+ });
3128
+ function setDragging(node) {
3129
+ draggingNodeUnsetter.cancel();
3130
+ draggingNodeSetter.call(node);
3131
+ }
3132
+ function unsetDragging() {
3133
+ draggingNodeSetter.cancel();
3134
+ draggingNodeUnsetter.call();
3135
+ }
3136
+ 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));
3137
+ function useDragNode(args) {
3138
+ const { srcId, parentId } = args;
3139
+ const driveId = useSelectedDriveId();
3140
+ const draggingNodeId = useDraggingNode()?.srcId;
3141
+ const params = {
3142
+ driveId,
3143
+ srcId,
3144
+ parentId
3145
+ };
3146
+ const draggable = isNodeDrag(params);
3147
+ const isDragging = t$4({
3148
+ srcId,
3149
+ draggingNodeId
3150
+ }, [
3151
+ () => draggable,
3152
+ ({ srcId }) => e$2(srcId),
3153
+ ({ draggingNodeId }) => e$2(draggingNodeId),
3154
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3155
+ ]);
3156
+ const onDragStart = () => {
3157
+ if (!draggable) return;
3158
+ setDragging(params);
3159
+ };
3160
+ const onDragEnd = () => {
3161
+ if (!draggable) return;
3162
+ unsetDragging();
3163
+ };
3164
+ return {
3165
+ isDragging,
3166
+ draggable,
3167
+ onDragStart,
3168
+ onDragEnd
3169
+ };
3170
+ }
3171
+ 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));
3172
+ function useDropNode(targetId) {
3173
+ const driveId = useSelectedDriveId();
3174
+ const { srcId, parentId } = useDraggingNode() ?? {};
3175
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3176
+ const params = {
3177
+ driveId,
3178
+ parentId,
3179
+ targetId,
3180
+ srcId
3181
+ };
3182
+ function handleNodeDrop(event, cb) {
3183
+ if (!isNodeDrop(params)) return;
3184
+ event.preventDefault();
3185
+ event.stopPropagation();
3186
+ cb?.();
3187
+ }
3188
+ const onDragEnter = (event) => handleNodeDrop(event);
3189
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3190
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3191
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
3192
+ unsetDragging();
3193
+ unsetTarget();
3194
+ moveNodeById(params).catch(console.error);
3195
+ }));
3196
+ return {
3197
+ isDropTarget,
3198
+ onDragEnter,
3199
+ onDragOver,
3200
+ onDragLeave,
3201
+ onDrop
3202
+ };
3203
+ }
3204
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3205
+ graphQLReactorClientEventFunctions.useValue;
3206
+ graphQLReactorClientEventFunctions.setValue;
3207
+ graphQLReactorClientEventFunctions.addEventHandler;
3208
+ const modalEventFunctions = makePHEventFunctions("modal");
3209
+ modalEventFunctions.useValue;
3210
+ /** Sets the current modal */
3211
+ const setPHModal = modalEventFunctions.setValue;
3212
+ modalEventFunctions.addEventHandler;
3213
+ /** Shows a modal */
3214
+ function showPHModal(modal) {
3215
+ setPHModal(modal);
3216
+ }
3217
+ /** Shows the create document modal */
3218
+ function showCreateDocumentModal(documentType) {
3219
+ setPHModal({
3220
+ type: "createDocument",
3221
+ documentType
3222
+ });
3223
+ }
3224
+ /** Shows the delete node modal */
3225
+ function showDeleteNodeModal(nodeOrId) {
3226
+ setPHModal({
3227
+ type: "deleteItem",
3228
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
3229
+ });
3230
+ }
3231
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3232
+ packageDiscoveryFunctions.useValue;
3233
+ packageDiscoveryFunctions.setValue;
3234
+ packageDiscoveryFunctions.addEventHandler;
3235
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3236
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3237
+ /** Returns the reactor client module */
3238
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3239
+ reactorClientModuleEventFunctions.setValue;
3240
+ reactorClientModuleEventFunctions.addEventHandler;
3241
+ reactorClientEventFunctions.useValue;
3242
+ reactorClientEventFunctions.setValue;
3243
+ reactorClientEventFunctions.addEventHandler;
3244
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3245
+ const useSyncList = () => {
3246
+ return useSync()?.list() ?? [];
3247
+ };
3248
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3249
+ revisionHistoryEventFunctions.useValue;
3250
+ /** Sets revision history visibility */
3251
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3252
+ revisionHistoryEventFunctions.addEventHandler;
3253
+ /** Shows the revision history */
3254
+ function showRevisionHistory() {
3255
+ setRevisionHistoryVisible(true);
3256
+ }
3257
+ /** Sorts nodes by name. */
3258
+ function sortNodesByName(nodes) {
3259
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3260
+ }
3261
+ /** Returns whether a node is a file. */
3262
+ function isFileNodeKind(node) {
3263
+ if (!node) return false;
3264
+ return node.kind.toUpperCase() === "FILE";
3265
+ }
3266
+ /** Returns whether a node is a folder. */
3267
+ function isFolderNodeKind(node) {
3268
+ if (!node) return false;
3269
+ return node.kind.toUpperCase() === "FOLDER";
3270
+ }
3271
+ /** Returns the nodes in the selected drive. */
3272
+ function useNodesInSelectedDrive() {
3273
+ const [selectedDrive] = useSelectedDriveSafe();
3274
+ return selectedDrive?.state.global.nodes;
3275
+ }
3276
+ /** Returns the folder nodes in the selected drive. */
3277
+ function useFolderNodesInSelectedDrive() {
3278
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3279
+ }
3280
+ /** Returns the selected node. */
3281
+ function useSelectedNode() {
3282
+ const selectedNodeId = useSelectedNodeId();
3283
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3284
+ }
3285
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3286
+ selectedTimelineItemEventFunctions.useValue;
3287
+ selectedTimelineItemEventFunctions.setValue;
3288
+ selectedTimelineItemEventFunctions.addEventHandler;
3289
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3290
+ selectedTimelineRevisionEventFunctions.useValue;
3291
+ selectedTimelineRevisionEventFunctions.setValue;
3292
+ selectedTimelineRevisionEventFunctions.addEventHandler;
3293
+ const toastEventFunctions = makePHEventFunctions("toast");
3294
+ /** Returns the toast function */
3295
+ const usePHToast = toastEventFunctions.useValue;
3296
+ toastEventFunctions.setValue;
3297
+ toastEventFunctions.addEventHandler;
3298
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3299
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3300
+ /** Returns all of the Vetra packages loaded by the Connect instance */
3301
+ const useVetraPackages = () => {
3302
+ const packageManager = useVetraPackageManager();
3303
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3304
+ };
3305
+ vetraPackageManagerFunctions.addEventHandler;
3306
+ function useDocumentModelModules() {
3307
+ 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);
3308
+ }
3309
+ function useDocumentModelModuleById(id) {
3310
+ return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3311
+ }
3312
+ /** Returns the selected folder. */
3313
+ function useSelectedFolder() {
3314
+ const selectedNode = useSelectedNode();
3315
+ if (isFolderNodeKind(selectedNode)) return selectedNode;
3316
+ }
3317
+ /** Returns the child nodes for the selected drive or folder. */
3318
+ function useNodesInSelectedDriveOrFolder() {
3319
+ const nodes = useNodesInSelectedDrive();
3320
+ const selectedFolderId = useSelectedFolder()?.id;
3321
+ if (!nodes) return [];
3322
+ if (!selectedFolderId) return sortNodesByName(nodes.filter((n) => !n.parentFolder));
3323
+ return sortNodesByName(nodes.filter((n) => n.parentFolder === selectedFolderId));
3324
+ }
3325
+ function callGlobalSetterForKey(key, value) {
3326
+ const setter = phGlobalConfigSetters[key];
3327
+ setter(value);
3328
+ }
3329
+ /** Sets the global drive config.
3330
+ *
3331
+ * Pass in a partial object of the global drive config to set.
3332
+ */
3333
+ function setPHAppConfig(config) {
3334
+ for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
3335
+ }
3336
+ /** Sets the global document config.
3337
+ *
3338
+ * Pass in a partial object of the global document config to set.
3339
+ */
3340
+ function setPHDocumentEditorConfig(config) {
3341
+ for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
3342
+ }
3343
+ /** Wrapper hook for setting the global app config.
3344
+ *
3345
+ * Automatically sets the global app config when the component mounts.
3346
+ *
3347
+ * Pass in a partial object of the global app config to set.
3348
+ */
3349
+ function useSetPHAppConfig(config) {
3350
+ const [isInitialized, setIsInitialized] = useState(false);
3351
+ useEffect(() => {
3352
+ if (isInitialized) return;
3353
+ setPHAppConfig(config);
3354
+ setIsInitialized(true);
3355
+ }, [config, isInitialized]);
3356
+ }
3357
+ /** Wrapper hook for setting the global document editor config.
3358
+ *
3359
+ * Automatically sets the global document editor config when the component mounts.
3360
+ *
3361
+ * Pass in a partial object of the global document editor config to set.
3362
+ */
3363
+ function useSetPHDocumentEditorConfig(config) {
3364
+ const [isInitialized, setIsInitialized] = useState(false);
3365
+ useEffect(() => {
3366
+ if (isInitialized) return;
3367
+ setPHDocumentEditorConfig(config);
3368
+ setIsInitialized(true);
3369
+ }, [config, isInitialized]);
3370
+ }
3371
+ /** Returns a document of a specific type, throws an error if the found document has a different type */
3372
+ function useDocumentOfType(documentId, documentType) {
3373
+ const [document, dispatch] = useDocumentById(documentId);
3374
+ const documentModelModule = useDocumentModelModuleById(documentType);
3375
+ if (!documentId || !documentType) return [];
3376
+ if (!document) throw new Error(`Document not found: ${documentId}`);
3377
+ if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3378
+ if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3379
+ return [document, dispatch];
3380
+ }
3381
+ const validateDocument = (document) => {
3382
+ const errors = [];
3383
+ if (document.header.documentType !== "powerhouse/document-model") return errors;
3384
+ const doc = document;
3385
+ const specs = doc.state.global.specifications[0];
3386
+ const initialStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
3387
+ const scope = scopeKey;
3388
+ return [...acc, ...validateInitialState(specs.state[scope].initialValue, scope !== "global").map((err) => ({
3389
+ ...err,
3390
+ message: `${err.message}. Scope: ${scope}`,
3391
+ details: {
3392
+ ...err.details,
3393
+ scope
3394
+ }
3395
+ }))];
3396
+ }, []);
3397
+ const schemaStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
3398
+ const scope = scopeKey;
3399
+ const isGlobalScope = scope === "global";
3400
+ return [...acc, ...validateStateSchemaName(specs.state[scope].schema, doc.state.global?.name || doc.header.name || "", !isGlobalScope ? scope : "", !isGlobalScope).map((err) => ({
3401
+ ...err,
3402
+ message: `${err.message}. Scope: ${scope}`,
3403
+ details: {
3404
+ ...err.details,
3405
+ scope
3406
+ }
3407
+ }))];
3408
+ }, []);
3409
+ const modulesErrors = validateModules(specs.modules);
3410
+ return [
3411
+ ...initialStateErrors,
3412
+ ...schemaStateErrors,
3413
+ ...modulesErrors
3414
+ ];
3415
+ };
3416
+ function defaultHandleError(error) {
3417
+ console.error(`Failed to export document: ${error.message}`);
3418
+ }
3419
+ function handleDocumentValidation(document) {
3420
+ if (t$2(validateDocument(document), 1)) return false;
3421
+ return true;
3422
+ }
3423
+ function downloadDocument(document, handleError = defaultHandleError) {
3424
+ if (!document) return;
3425
+ if (!handleDocumentValidation(document)) {
3426
+ showPHModal({
3427
+ type: "downloadDocumentWithErrors",
3428
+ documentId: document.header.id
3429
+ });
3430
+ return;
3431
+ }
3432
+ exportFile(document).catch((error) => handleError(normalizeException(error)));
3433
+ }
3434
+ function useDownloadDocument(id) {
3435
+ const [document] = useDocumentById(id);
3436
+ const toast = usePHToast();
3437
+ return () => downloadDocument(document, (error) => toast?.(`Failed to export document: ${error.message}`));
3438
+ }
3439
+ function useFolderById(id) {
3440
+ return useFolderNodesInSelectedDrive()?.find((n) => n.id === id);
3441
+ }
3442
+ function resolveNode(driveId, node) {
3443
+ return node?.id !== driveId ? node : void 0;
3444
+ }
3445
+ function useNodeActions() {
3446
+ const [selectedDrive] = useSelectedDriveSafe();
3447
+ const selectedFolder = useSelectedFolder();
3448
+ const selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);
3449
+ const selectedDriveId = selectedDrive?.header.id;
3450
+ const drives = useDrives();
3451
+ async function onAddFile(file, parent) {
3452
+ if (!selectedDriveId) return;
3453
+ return addFile(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id);
3454
+ }
3455
+ async function onAddFolder(name, parent) {
3456
+ if (!selectedDriveId) return;
3457
+ return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3458
+ }
3459
+ async function onRenameNode(newName, node) {
3460
+ if (!selectedDriveId) return;
3461
+ if (!resolveNode(selectedDriveId, node)) {
3462
+ console.error(`Node ${node.id} not found`);
3463
+ return;
3464
+ }
3465
+ return await renameNode(selectedDriveId, node.id, newName);
3466
+ }
3467
+ async function onCopyNode(src, target) {
3468
+ if (!selectedDriveId) return;
3469
+ const resolvedSrc = resolveNode(selectedDriveId, src);
3470
+ if (!resolvedSrc) {
3471
+ console.error(`Node ${src.id} not found`);
3472
+ return;
3473
+ }
3474
+ await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));
3475
+ }
3476
+ async function onMoveNode(src, target) {
3477
+ if (!selectedDriveId) return;
3478
+ const resolvedSrc = resolveNode(selectedDriveId, src);
3479
+ if (!resolvedSrc) {
3480
+ console.error(`Node ${src.id} not found`);
3481
+ return;
3482
+ }
3483
+ const resolvedTarget = resolveNode(selectedDriveId, target);
3484
+ if (!resolvedTarget?.id && !src.parentFolder || resolvedTarget?.id === src.parentFolder) return;
3485
+ await moveNode$1(selectedDriveId, resolvedSrc, resolvedTarget);
3486
+ }
3487
+ async function onDuplicateNode(src) {
3488
+ if (!selectedDriveId) return;
3489
+ const resolvedSrc = resolveNode(selectedDriveId, src);
3490
+ if (!resolvedSrc) {
3491
+ console.error(`Node ${src.id} not found`);
3492
+ return;
3493
+ }
3494
+ await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));
3495
+ }
3496
+ async function onAddAndSelectNewFolder(name) {
3497
+ if (!name) return;
3498
+ if (!selectedDriveId) return;
3499
+ const resolvedTarget = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);
3500
+ if (!resolvedTarget) return;
3501
+ const newFolder = await onAddFolder(name, resolvedTarget);
3502
+ if (newFolder) setSelectedNode(newFolder);
3503
+ }
3504
+ async function onRenameDriveNodes(newName, nodeId) {
3505
+ if (!drives) return;
3506
+ const drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));
3507
+ await Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));
3508
+ }
3509
+ return {
3510
+ onAddFile,
3511
+ onAddFolder,
3512
+ onRenameNode,
3513
+ onCopyNode,
3514
+ onMoveNode,
3515
+ onDuplicateNode,
3516
+ onAddAndSelectNewFolder,
3517
+ onRenameDriveNodes
3518
+ };
3519
+ }
3520
+ /** Returns a node in the selected drive by id. */
3521
+ function useNodeById(id) {
3522
+ return useNodesInSelectedDrive()?.find((n) => n.id === id);
3523
+ }
3524
+ /** Returns the path to a node in the selected drive */
3525
+ function useNodePathById(id) {
3526
+ const nodes = useNodesInSelectedDrive();
3527
+ if (!nodes) return [];
3528
+ const path = [];
3529
+ let current = nodes.find((n) => n.id === id);
3530
+ while (current) {
3531
+ path.push(current);
3532
+ if (!current.parentFolder) break;
3533
+ current = nodes.find((n) => n.id === current?.parentFolder);
3534
+ }
3535
+ return path.reverse();
3536
+ }
3537
+ /** Returns the path to the currently selected node in the selected drive. */
3538
+ function useSelectedNodePath() {
3539
+ return useNodePathById(useSelectedNode()?.id);
3540
+ }
3541
+ function useNodeParentFolderById(id) {
3542
+ return useFolderById(useNodeById(id)?.parentFolder);
3543
+ }
3544
+ /** Returns the selected document id */
3545
+ function useSelectedDocumentId() {
3546
+ const selectedNode = useSelectedNode();
3547
+ return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3548
+ }
3549
+ /** Returns the selected document. */
3550
+ function useSelectedDocumentSafe() {
3551
+ return useDocumentById(useSelectedDocumentId());
3552
+ }
3553
+ function useSelectedDocumentOfType(documentType) {
3554
+ const documentId = useSelectedDocumentId();
3555
+ if (!documentType) return [];
3556
+ if (!documentId) throw new NoSelectedDocumentError();
3557
+ return useDocumentOfType(documentId, documentType);
3558
+ }
3559
+ const STORED_THEME_KEY = "ph:theme";
3560
+ const UPDATE_STORED_THEME = "ph:updateStoredTheme";
3561
+ const STORED_THEME_UPDATED = "ph:storedThemeUpdated";
3562
+ const SYSTEM_THEME_UPDATED = "ph:systemThemeUpdated";
3563
+ const isServer = typeof window === "undefined";
3564
+ function setTheme(storedTheme) {
3565
+ if (isServer) return;
3566
+ const updateStoredThemeEvent = new CustomEvent(UPDATE_STORED_THEME, { detail: { storedTheme } });
3567
+ window.dispatchEvent(updateStoredThemeEvent);
3568
+ }
3569
+ function getStoredTheme() {
3570
+ if (isServer) return void 0;
3571
+ return localStorage.getItem(STORED_THEME_KEY) ?? void 0;
3572
+ }
3573
+ function getPrefersDarkMediaQuery() {
3574
+ if (isServer) return;
3575
+ return window.matchMedia("(prefers-color-scheme: dark)");
3576
+ }
3577
+ function getPrefersDark() {
3578
+ if (isServer) return false;
3579
+ if (getPrefersDarkMediaQuery()?.matches) return true;
3580
+ return false;
3581
+ }
3582
+ function getSystemTheme() {
3583
+ if (isServer) return "light";
3584
+ if (getPrefersDark()) return "dark";
3585
+ return "light";
3586
+ }
3587
+ function toggleDark(isDark) {
3588
+ if (isServer) return;
3589
+ document.documentElement.classList.toggle("dark", isDark);
3590
+ }
3591
+ function subscribeToStoredTheme(onStoreChange) {
3592
+ if (isServer) return () => {};
3593
+ window.addEventListener(STORED_THEME_UPDATED, onStoreChange);
3594
+ return () => {
3595
+ window.removeEventListener(STORED_THEME_UPDATED, onStoreChange);
3596
+ };
3597
+ }
3598
+ function subscribeToSystemTheme(onStoreChange) {
3599
+ if (isServer) return () => {};
3600
+ window.addEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
3601
+ return () => {
3602
+ window.removeEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
3603
+ };
3604
+ }
3605
+ function useTheme() {
3606
+ const storedTheme = useSyncExternalStore(subscribeToStoredTheme, () => getStoredTheme(), () => "system");
3607
+ const systemTheme = useSyncExternalStore(subscribeToSystemTheme, () => getSystemTheme(), () => "light");
3608
+ const isSystem = storedTheme === void 0 || storedTheme === "system";
3609
+ const theme = isSystem ? systemTheme : storedTheme;
3610
+ const isDark = theme === "dark";
3611
+ useEffect(() => {
3612
+ toggleDark(isDark);
3613
+ }, [isDark]);
3614
+ return {
3615
+ theme,
3616
+ isSystem,
3617
+ setTheme
3618
+ };
3619
+ }
3620
+ const syncStatusToUI = {
3621
+ [SyncStatus.Synced]: "SUCCESS",
3622
+ [SyncStatus.Outgoing]: "SYNCING",
3623
+ [SyncStatus.Incoming]: "SYNCING",
3624
+ [SyncStatus.OutgoingAndIncoming]: "SYNCING",
3625
+ [SyncStatus.Error]: "ERROR"
3626
+ };
3627
+ async function getDrives(reactor) {
3628
+ return (await reactor.find({ type: "powerhouse/document-drive" })).results;
3629
+ }
3630
+ function getSyncStatusSync(documentId, sharingType) {
3631
+ if (sharingType === "LOCAL") return;
3632
+ const syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
3633
+ if (!syncManager) return;
3634
+ const status = syncManager.getSyncStatus(documentId);
3635
+ if (status === void 0) return;
3636
+ return syncStatusToUI[status];
3637
+ }
3638
+ function getDocumentGraphqlQuery() {
3639
+ const loc = GetDocumentWithOperationsDocument.loc;
3640
+ if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
3641
+ return loc.source.body;
3642
+ }
3643
+ function buildDocumentSubgraphQuery(identifier, authToken) {
3644
+ const query = getDocumentGraphqlQuery();
3645
+ const variables = { identifier };
3646
+ const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
3647
+ const payload = {
3648
+ document: query.trim(),
3649
+ variables: JSON.stringify(variables, null, 2)
3650
+ };
3651
+ if (headers) payload.headers = JSON.stringify(headers);
3652
+ return import_lz_string.compressToEncodedURIComponent(JSON.stringify(payload));
3653
+ }
3654
+ function buildDocumentSubgraphUrl(driveUrl, identifier, authToken) {
3655
+ return `${driveUrl}?explorerURLState=${buildDocumentSubgraphQuery(identifier, authToken)}`;
3656
+ }
3657
+ /**
3658
+ * Hook that returns a function to generate a document's switchboard URL.
3659
+ * Only returns a function for documents in remote drives.
3660
+ * Returns null for local drives or when the document/drive cannot be determined.
3661
+ *
3662
+ * The returned function generates a fresh bearer token and builds the switchboard URL
3663
+ * with authentication when called.
3664
+ *
3665
+ * @param document - The document to create a switchboard URL generator for
3666
+ * @returns An async function that returns the switchboard URL, or null if not applicable
3667
+ */
3668
+ function useGetSwitchboardLink(document) {
3669
+ const [drive] = useSelectedDriveSafe();
3670
+ const remotes = useSyncList();
3671
+ const isRemoteDrive = useMemo(() => {
3672
+ if (!e$4(drive)) return false;
3673
+ return remotes.some((remote) => remote.collectionId === driveCollectionId("main", drive.header.id));
3674
+ }, [remotes, drive]);
3675
+ const remoteUrl = useMemo(() => {
3676
+ if (!e$4(drive)) return null;
3677
+ try {
3678
+ const channelUrl = (remotes.find((remote) => remote.collectionId === driveCollectionId("main", drive.header.id))?.channel)?.config.url;
3679
+ if (typeof channelUrl === "string") return channelUrl;
3680
+ return null;
3681
+ } catch (error) {
3682
+ console.error("Error determining remote URL:", error);
3683
+ return null;
3684
+ }
3685
+ }, [remotes, drive]);
3686
+ const renown = useRenown();
3687
+ const user = useUser();
3688
+ return useMemo(() => {
3689
+ if (!isRemoteDrive || !document?.header.id || !remoteUrl) return null;
3690
+ return async () => {
3691
+ const token = user?.address ? await renown?.getBearerToken({
3692
+ expiresIn: 600,
3693
+ aud: remoteUrl
3694
+ }) : void 0;
3695
+ return buildDocumentSubgraphUrl(remoteUrl, document.header.id, token);
3696
+ };
3697
+ }, [
3698
+ isRemoteDrive,
3699
+ remoteUrl,
3700
+ document,
3701
+ user,
3702
+ renown
3703
+ ]);
3704
+ }
3705
+ function useUserPermissions() {
3706
+ const user = useUser();
3707
+ const allowList = useAllowList();
3708
+ if (!allowList) return {
3709
+ isAllowedToCreateDocuments: true,
3710
+ isAllowedToEditDocuments: true
3711
+ };
3712
+ return {
3713
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
3714
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
3715
+ };
3716
+ }
3717
+ const DEFAULT_DEBOUNCE_DELAY_MS = 200;
3718
+ const DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;
3719
+ async function _refreshReactorData(reactor) {
3720
+ setDrives(await getDrives(reactor));
3721
+ }
3722
+ async function _refreshReactorDataClient(reactor) {
3723
+ if (!reactor) return;
3724
+ setDrives((await reactor.find({ type: "powerhouse/document-drive" })).results);
3725
+ }
3726
+ function createDebouncedRefreshReactorData(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
3727
+ let timeout = null;
3728
+ let lastRefreshTime = 0;
3729
+ return (reactor, immediate = false) => {
3730
+ const now = Date.now();
3731
+ const timeSinceLastRefresh = now - lastRefreshTime;
3732
+ if (timeout !== null) clearTimeout(timeout);
3733
+ if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
3734
+ lastRefreshTime = now;
3735
+ return _refreshReactorData(reactor);
3736
+ }
3737
+ return new Promise((resolve) => {
3738
+ timeout = setTimeout(() => {
3739
+ lastRefreshTime = Date.now();
3740
+ _refreshReactorData(reactor).then(resolve);
3741
+ }, debounceDelayMs);
3742
+ });
3743
+ };
3744
+ }
3745
+ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
3746
+ let timeout = null;
3747
+ let lastRefreshTime = 0;
3748
+ return (reactor, immediate = false) => {
3749
+ const now = Date.now();
3750
+ const timeSinceLastRefresh = now - lastRefreshTime;
3751
+ if (timeout !== null) clearTimeout(timeout);
3752
+ if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
3753
+ lastRefreshTime = now;
3754
+ return _refreshReactorDataClient(reactor);
3755
+ }
3756
+ return new Promise((resolve) => {
3757
+ timeout = setTimeout(() => {
3758
+ lastRefreshTime = Date.now();
3759
+ _refreshReactorDataClient(reactor).then(resolve);
3760
+ }, debounceDelayMs);
3761
+ });
3762
+ };
3763
+ }
3764
+ createDebouncedRefreshReactorData();
3765
+ createDebouncedRefreshReactorDataClient();
3766
+ //#endregion
3767
+ export { e$4 as A, useSelectedDriveSafe as C, useTheme as D, useSetPHDocumentEditorConfig as E, t$5 as M, useDocumentById as N, useUserPermissions as O, useSelectedDriveId as S, useSetPHAppConfig as T, useNodeParentFolderById as _, setSelectedDrive as a, useSelectedDocumentOfType as b, showDeleteNodeModal as c, useDownloadDocument as d, useDragNode as f, useNodeById as g, useNodeActions as h, isFolderNodeKind as i, t$2 as j, e$1 as k, showRevisionHistory as l, useGetSwitchboardLink as m, getSyncStatusSync as n, setSelectedNode as o, useDropNode as p, isFileNodeKind as r, showCreateDocumentModal as s, addFolder as t, useDocumentModelModules as u, useNodesInSelectedDriveOrFolder as v, useSelectedNodePath as w, useSelectedDocumentSafe as x, usePHToast as y };
3768
+
3769
+ //# sourceMappingURL=dist-Bm05eoTg.mjs.map