@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.9 → 6.2.2

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 (103) hide show
  1. package/dist/browser/assets/{entry-Cvoo4_c9.js → entry-5_Eh4a2Z.js} +3 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-DgFDnTMt.js} +4 -4
  3. package/dist/browser/{linting-Dn6pXRkK.js → button-CuO8Gh3v.js} +20 -6
  4. package/dist/browser/button-CuO8Gh3v.js.map +1 -0
  5. package/dist/browser/{connect-KEU-HR3o.js → connect-DqkYyEcC.js} +927 -202
  6. package/dist/browser/connect-DqkYyEcC.js.map +1 -0
  7. package/dist/browser/{dist-CXoKspdx.js → dist-B4FWbuEM.js} +10 -2
  8. package/dist/browser/{dist-CXoKspdx.js.map → dist-B4FWbuEM.js.map} +1 -1
  9. package/dist/{node/dist-BeZaEP6S.mjs → browser/dist-BAJ5nRDl.js} +21 -2
  10. package/dist/browser/{dist-D8H48e8N.js.map → dist-BAJ5nRDl.js.map} +1 -1
  11. package/dist/browser/{dist-D5ra2aRj.js → dist-C1pi89al.js} +2640 -1833
  12. package/dist/browser/dist-C1pi89al.js.map +1 -0
  13. package/dist/browser/{document-drive-IdFV1QXL.js → document-drive-ZQzPQfEL.js} +998 -127
  14. package/dist/browser/document-drive-ZQzPQfEL.js.map +1 -0
  15. package/dist/browser/document-models/index.js +1 -1
  16. package/dist/browser/{documents-D4ek7Ubv.js → documents-J_l59mSV.js} +5 -604
  17. package/dist/browser/documents-J_l59mSV.js.map +1 -0
  18. package/dist/browser/{editor-DiZF3ao3.js → editor-Bl02Hko1.js} +671 -236
  19. package/dist/browser/editor-Bl02Hko1.js.map +1 -0
  20. package/dist/browser/editor-CbtY05JH.js +25 -0
  21. package/dist/browser/editor-CbtY05JH.js.map +1 -0
  22. package/dist/browser/editors/document-model-editor/module.js +1 -1
  23. package/dist/browser/editors/generic-drive-explorer/index.js +5 -5
  24. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  25. package/dist/{node/folder-view-Cy-QxsDg.mjs → browser/folder-view-BBm_YnKn.js} +73 -46
  26. package/dist/browser/folder-view-BBm_YnKn.js.map +1 -0
  27. package/dist/browser/{graphql-editor-ZLRO_8Ce.js → graphql-editor-LSj3LCtL.js} +8 -7
  28. package/dist/browser/{graphql-editor-ZLRO_8Ce.js.map → graphql-editor-LSj3LCtL.js.map} +1 -1
  29. package/dist/browser/{hooks-CORHBNHb.js → hooks-KKcNp2X0.js} +2 -2
  30. package/dist/browser/{hooks-CORHBNHb.js.map → hooks-KKcNp2X0.js.map} +1 -1
  31. package/dist/browser/index.js +378 -9
  32. package/dist/browser/index.js.map +1 -1
  33. package/dist/browser/{json-editor-DBuZ6gN7.js → json-editor-TVSHA4PZ.js} +4 -4
  34. package/dist/browser/{json-editor-DBuZ6gN7.js.map → json-editor-TVSHA4PZ.js.map} +1 -1
  35. package/dist/browser/{lib-C-f3izXz.js → lib-ewnRj2dJ.js} +13 -4
  36. package/dist/browser/lib-ewnRj2dJ.js.map +1 -0
  37. package/dist/browser/printer-CEYr4JOg.js +604 -0
  38. package/dist/browser/printer-CEYr4JOg.js.map +1 -0
  39. package/dist/browser/{schema-context-DY-GEGnY.js → schema-context-ZyeclQwy.js} +2 -2
  40. package/dist/browser/{schema-context-DY-GEGnY.js.map → schema-context-ZyeclQwy.js.map} +1 -1
  41. package/dist/browser/{state-schemas-BjQKM498.js → state-schemas-Bsryt22c.js} +8 -18
  42. package/dist/browser/state-schemas-Bsryt22c.js.map +1 -0
  43. package/dist/node/{linting-Dx50GuLN.mjs → button-Da7CxMn7.mjs} +20 -7
  44. package/dist/node/button-Da7CxMn7.mjs.map +1 -0
  45. package/dist/node/{connect-KcYZcy_Z.mjs → connect-B2yHg8VF.mjs} +927 -202
  46. package/dist/node/connect-B2yHg8VF.mjs.map +1 -0
  47. package/dist/node/{dist-DJEK2WVi.mjs → dist-BAXIB1_k.mjs} +2647 -1833
  48. package/dist/node/dist-BAXIB1_k.mjs.map +1 -0
  49. package/dist/{browser/dist-D8H48e8N.js → node/dist-CzYOpeXN.mjs} +21 -2
  50. package/dist/node/{dist-BeZaEP6S.mjs.map → dist-CzYOpeXN.mjs.map} +1 -1
  51. package/dist/node/{dist-fA4EItr0.mjs → dist-DT7jI9ol.mjs} +10 -2
  52. package/dist/node/{dist-fA4EItr0.mjs.map → dist-DT7jI9ol.mjs.map} +1 -1
  53. package/dist/node/{document-drive-C8hbqQ3C.mjs → document-drive-D1NMjQQc.mjs} +998 -127
  54. package/dist/node/document-drive-D1NMjQQc.mjs.map +1 -0
  55. package/dist/node/document-models/index.mjs +1 -1
  56. package/dist/node/{documents-BFBPmyw1.mjs → documents-DCf53bzO.mjs} +3 -3
  57. package/dist/node/{documents-BFBPmyw1.mjs.map → documents-DCf53bzO.mjs.map} +1 -1
  58. package/dist/node/{editor-B1KhoF1f.mjs → editor--v67sph0.mjs} +672 -237
  59. package/dist/node/editor--v67sph0.mjs.map +1 -0
  60. package/dist/node/editor-BY22Tx5_.mjs +25 -0
  61. package/dist/node/editor-BY22Tx5_.mjs.map +1 -0
  62. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  63. package/dist/node/editors/generic-drive-explorer/index.mjs +5 -5
  64. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  65. package/dist/{browser/folder-view-DMFqcJhc.js → node/folder-view-D_99HJFI.mjs} +73 -46
  66. package/dist/node/folder-view-D_99HJFI.mjs.map +1 -0
  67. package/dist/node/{graphql-DskHmkMe.mjs → graphql-BfAoPeWM.mjs} +2 -2
  68. package/dist/node/{graphql-DskHmkMe.mjs.map → graphql-BfAoPeWM.mjs.map} +1 -1
  69. package/dist/node/{graphql-editor-C5VLRqEf.mjs → graphql-editor-Bzs-PolA.mjs} +7 -7
  70. package/dist/node/{graphql-editor-C5VLRqEf.mjs.map → graphql-editor-Bzs-PolA.mjs.map} +1 -1
  71. package/dist/node/{hooks-DJrjfVaS.mjs → hooks-D0DcS3MV.mjs} +2 -2
  72. package/dist/node/{hooks-DJrjfVaS.mjs.map → hooks-D0DcS3MV.mjs.map} +1 -1
  73. package/dist/node/index.mjs +378 -9
  74. package/dist/node/index.mjs.map +1 -1
  75. package/dist/node/{json-editor-iI2s9a_4.mjs → json-editor-CCsBXZ6y.mjs} +4 -4
  76. package/dist/node/{json-editor-iI2s9a_4.mjs.map → json-editor-CCsBXZ6y.mjs.map} +1 -1
  77. package/dist/node/{main-D82dkD7g.mjs → main-B1tRsYOp.mjs} +15 -6
  78. package/dist/node/main-B1tRsYOp.mjs.map +1 -0
  79. package/dist/node/{schema-context-CX5ml_9t.mjs → schema-context-DL8jhi_d.mjs} +3 -3
  80. package/dist/node/{schema-context-CX5ml_9t.mjs.map → schema-context-DL8jhi_d.mjs.map} +1 -1
  81. package/dist/node/{state-schemas-Bl7nA8bB.mjs → state-schemas-DxJBYOC0.mjs} +10 -20
  82. package/dist/{browser/state-schemas-BjQKM498.js.map → node/state-schemas-DxJBYOC0.mjs.map} +1 -1
  83. package/package.json +8 -7
  84. package/dist/browser/connect-KEU-HR3o.js.map +0 -1
  85. package/dist/browser/dist-D5ra2aRj.js.map +0 -1
  86. package/dist/browser/document-drive-IdFV1QXL.js.map +0 -1
  87. package/dist/browser/documents-D4ek7Ubv.js.map +0 -1
  88. package/dist/browser/editor-DiZF3ao3.js.map +0 -1
  89. package/dist/browser/editor-SqNULDP-.js +0 -29
  90. package/dist/browser/editor-SqNULDP-.js.map +0 -1
  91. package/dist/browser/folder-view-DMFqcJhc.js.map +0 -1
  92. package/dist/browser/lib-C-f3izXz.js.map +0 -1
  93. package/dist/browser/linting-Dn6pXRkK.js.map +0 -1
  94. package/dist/node/connect-KcYZcy_Z.mjs.map +0 -1
  95. package/dist/node/dist-DJEK2WVi.mjs.map +0 -1
  96. package/dist/node/document-drive-C8hbqQ3C.mjs.map +0 -1
  97. package/dist/node/editor-B1KhoF1f.mjs.map +0 -1
  98. package/dist/node/editor-yBGEvMGD.mjs +0 -29
  99. package/dist/node/editor-yBGEvMGD.mjs.map +0 -1
  100. package/dist/node/folder-view-Cy-QxsDg.mjs.map +0 -1
  101. package/dist/node/linting-Dx50GuLN.mjs.map +0 -1
  102. package/dist/node/main-D82dkD7g.mjs.map +0 -1
  103. package/dist/node/state-schemas-Bl7nA8bB.mjs.map +0 -1
@@ -1,9 +1,10 @@
1
- import { E as __commonJSMin, j as __toESM, t as capitalCase } from "./dist-fA4EItr0.mjs";
2
- import { B as setName, C as createZip, J as validateModules, X as generateId, Y as validateStateSchemaName, _ as baseLoadFromInputVersioned, a as handleTargetNameCollisions, b as createPresignedHeader, c as moveNode, d as logger, g as baseLoadFromInput, i as generateNodesCopy, j as replayDocumentVersioned, l as updateNode, n as copyNode, o as isFileNode, q as validateInitialState, s as isFolderNode, t as addFolder$1, v as baseSaveToFileHandle, y as buildSignedAction } from "./document-drive-C8hbqQ3C.mjs";
3
- import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-D82dkD7g.mjs";
4
- import { Children, cloneElement, forwardRef, isValidElement, use, useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
1
+ import { D as __commonJSMin, M as __toESM, r as pascalCase, t as capitalCase } from "./dist-DT7jI9ol.mjs";
2
+ import { A as createPresignedHeader, D as buildSignedAction, E as baseSaveToFileHandle, G as replayDocumentVersioned, N as createZip, T as baseLoadFromInputVersioned, _ as UnsupportedDocumentModelVersionError, a as getDescendants, c as isFileNode, ct as validateInitialState, d as moveNode, dt as zipEntries, et as setName, f as updateNode, ft as generateId, i as generateNodesCopy, l as isFolderNode, lt as validateModules, m as logger, n as copyNode, o as getNextCopyNumber, s as handleTargetNameCollisions, t as addFolder, ut as validateStateSchemaName, w as baseLoadFromInput, x as assertAuthPreservedOnDuplicate } from "./document-drive-D1NMjQQc.mjs";
3
+ import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-B1tRsYOp.mjs";
4
+ import { t as require_graphql } from "./graphql-BfAoPeWM.mjs";
5
+ import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
6
  import "react/jsx-runtime";
6
- //#region ../reactor-browser/dist/make-ph-event-functions-BHoLPif5.js
7
+ //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
7
8
  const isServer$1 = typeof window === "undefined";
8
9
  function makePHEventFunctions(key) {
9
10
  const setEventName = `ph:set${capitalCase(key)}`;
@@ -51,7 +52,7 @@ function makePHEventFunctions(key) {
51
52
  };
52
53
  }
53
54
  //#endregion
54
- //#region ../reactor-browser/dist/document-by-id-dLYFX-xz.js
55
+ //#region ../reactor-browser/dist/document-by-id-BSZqTN66.js
55
56
  async function queueActions(document, actionOrActions) {
56
57
  if (!document) throw new Error("No document provided");
57
58
  if (!actionOrActions) throw new Error("No actions provided");
@@ -97,12 +98,12 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
97
98
  logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
99
  }
99
100
  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
101
  const renown = window.ph?.renown;
104
102
  if (!renown?.user) return action;
105
103
  if (!action.context?.signer) return action;
104
+ const reactorClient = window.ph?.reactorClientModule?.client;
105
+ if (!reactorClient) return action;
106
+ const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
106
107
  const actionSigner = action.context.signer;
107
108
  return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
109
  }
@@ -180,6 +181,21 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
180
181
  if (onSuccess && result) onSuccess(result);
181
182
  return result;
182
183
  }
184
+ /**
185
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
186
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
187
+ * TypeScript string enum is nominal, so no string literal is assignable to it
188
+ * without one - and the two checks above are what make it safe.
189
+ */
190
+ const DOCUMENT_CHANGE_TYPE = {
191
+ Created: "created",
192
+ Deleted: "deleted",
193
+ Updated: "updated",
194
+ ParentAdded: "parent_added",
195
+ ParentRemoved: "parent_removed",
196
+ ChildAdded: "child_added",
197
+ ChildRemoved: "child_removed"
198
+ };
183
199
  const documentEventFunctions = makePHEventFunctions("documentCache");
184
200
  /** Returns all documents in the reactor. */
185
201
  const useDocumentCache = documentEventFunctions.useValue;
@@ -226,711 +242,29 @@ function useDocumentById(id) {
226
242
  return [document, dispatch];
227
243
  }
228
244
  //#endregion
229
- //#region ../reactor-browser/dist/client-_Gh2Uf0E.js
230
- var import_main = require_main();
231
- const PhDocumentFieldsFragmentDoc = import_main.gql`
232
- fragment PHDocumentFields on PHDocument {
233
- id
234
- slug
235
- name
236
- documentType
237
- state
238
- revisionsList {
239
- scope
240
- revision
241
- }
242
- createdAtUtcIso
243
- lastModifiedAtUtcIso
244
- }
245
- `;
246
- import_main.gql`
247
- query GetDocumentModels($namespace: String, $paging: PagingInput) {
248
- documentModels(namespace: $namespace, paging: $paging) {
249
- items {
250
- id
251
- name
252
- namespace
253
- version
254
- specification
255
- }
256
- totalCount
257
- hasNextPage
258
- hasPreviousPage
259
- cursor
260
- }
261
- }
262
- `;
263
- const GetDocumentDocument = import_main.gql`
264
- query GetDocument($identifier: String!, $view: ViewFilterInput) {
265
- document(identifier: $identifier, view: $view) {
266
- document {
267
- ...PHDocumentFields
268
- }
269
- childIds
270
- }
271
- }
272
- ${PhDocumentFieldsFragmentDoc}
273
- `;
274
- const GetDocumentWithOperationsDocument = import_main.gql`
275
- query GetDocumentWithOperations(
276
- $identifier: String!
277
- $view: ViewFilterInput
278
- $operationsFilter: DocumentOperationsFilterInput
279
- $operationsPaging: PagingInput
280
- ) {
281
- document(identifier: $identifier, view: $view) {
282
- document {
283
- ...PHDocumentFields
284
- operations(filter: $operationsFilter, paging: $operationsPaging) {
285
- items {
286
- index
287
- timestampUtcMs
288
- hash
289
- skip
290
- error
291
- id
292
- action {
293
- id
294
- type
295
- timestampUtcMs
296
- input
297
- scope
298
- context {
299
- signer {
300
- user {
301
- address
302
- networkId
303
- chainId
304
- }
305
- app {
306
- name
307
- key
308
- }
309
- signatures
310
- }
311
- }
312
- }
313
- }
314
- totalCount
315
- hasNextPage
316
- hasPreviousPage
317
- cursor
318
- }
319
- }
320
- childIds
321
- }
322
- }
323
- ${PhDocumentFieldsFragmentDoc}
324
- `;
325
- import_main.gql`
326
- query GetDocumentOutgoingRelationships(
327
- $sourceIdentifier: String!
328
- $relationshipType: String!
329
- $view: ViewFilterInput
330
- $paging: PagingInput
331
- ) {
332
- documentOutgoingRelationships(
333
- sourceIdentifier: $sourceIdentifier
334
- relationshipType: $relationshipType
335
- view: $view
336
- paging: $paging
337
- ) {
338
- items {
339
- ...PHDocumentFields
340
- }
341
- totalCount
342
- hasNextPage
343
- hasPreviousPage
344
- cursor
345
- }
346
- }
347
- ${PhDocumentFieldsFragmentDoc}
348
- `;
349
- import_main.gql`
350
- query GetDocumentIncomingRelationships(
351
- $targetIdentifier: String!
352
- $relationshipType: String!
353
- $view: ViewFilterInput
354
- $paging: PagingInput
355
- ) {
356
- documentIncomingRelationships(
357
- targetIdentifier: $targetIdentifier
358
- relationshipType: $relationshipType
359
- view: $view
360
- paging: $paging
361
- ) {
362
- items {
363
- ...PHDocumentFields
364
- }
365
- totalCount
366
- hasNextPage
367
- hasPreviousPage
368
- cursor
369
- }
370
- }
371
- ${PhDocumentFieldsFragmentDoc}
372
- `;
373
- import_main.gql`
374
- query FindDocuments(
375
- $search: SearchFilterInput
376
- $view: ViewFilterInput
377
- $paging: PagingInput
378
- ) {
379
- findDocuments(search: $search, view: $view, paging: $paging) {
380
- items {
381
- ...PHDocumentFields
382
- }
383
- totalCount
384
- hasNextPage
385
- hasPreviousPage
386
- cursor
387
- }
388
- }
389
- ${PhDocumentFieldsFragmentDoc}
390
- `;
391
- const GetDocumentOperationsDocument = import_main.gql`
392
- query GetDocumentOperations(
393
- $filter: OperationsFilterInput!
394
- $paging: PagingInput
395
- ) {
396
- documentOperations(filter: $filter, paging: $paging) {
397
- items {
398
- index
399
- timestampUtcMs
400
- hash
401
- skip
402
- error
403
- id
404
- action {
405
- id
406
- type
407
- timestampUtcMs
408
- input
409
- scope
410
- context {
411
- signer {
412
- user {
413
- address
414
- networkId
415
- chainId
416
- }
417
- app {
418
- name
419
- key
420
- }
421
- signatures
422
- }
423
- }
424
- }
425
- }
426
- totalCount
427
- hasNextPage
428
- hasPreviousPage
429
- cursor
430
- }
431
- }
432
- `;
433
- import_main.gql`
434
- query GetJobStatus($jobId: String!) {
435
- jobStatus(jobId: $jobId) {
436
- id
437
- status
438
- result
439
- error
440
- createdAt
441
- completedAt
442
- }
443
- }
444
- `;
445
- import_main.gql`
446
- mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
447
- createDocument(document: $document, parentIdentifier: $parentIdentifier) {
448
- ...PHDocumentFields
449
- }
450
- }
451
- ${PhDocumentFieldsFragmentDoc}
452
- `;
453
- import_main.gql`
454
- mutation CreateEmptyDocument(
455
- $documentType: String!
456
- $parentIdentifier: String
457
- ) {
458
- createEmptyDocument(
459
- documentType: $documentType
460
- parentIdentifier: $parentIdentifier
461
- ) {
462
- ...PHDocumentFields
463
- }
464
- }
465
- ${PhDocumentFieldsFragmentDoc}
466
- `;
467
- import_main.gql`
468
- mutation MutateDocument(
469
- $documentIdentifier: String!
470
- $actions: [JSONObject!]!
471
- $view: ViewFilterInput
472
- ) {
473
- mutateDocument(
474
- documentIdentifier: $documentIdentifier
475
- actions: $actions
476
- view: $view
477
- ) {
478
- ...PHDocumentFields
479
- }
480
- }
481
- ${PhDocumentFieldsFragmentDoc}
482
- `;
483
- import_main.gql`
484
- mutation MutateDocumentAsync(
485
- $documentIdentifier: String!
486
- $actions: [JSONObject!]!
487
- $view: ViewFilterInput
488
- ) {
489
- mutateDocumentAsync(
490
- documentIdentifier: $documentIdentifier
491
- actions: $actions
492
- view: $view
493
- )
494
- }
495
- `;
496
- import_main.gql`
497
- mutation RenameDocument(
498
- $documentIdentifier: String!
499
- $name: String!
500
- $branch: String
501
- ) {
502
- renameDocument(
503
- documentIdentifier: $documentIdentifier
504
- name: $name
505
- branch: $branch
506
- ) {
507
- ...PHDocumentFields
508
- }
509
- }
510
- ${PhDocumentFieldsFragmentDoc}
511
- `;
512
- import_main.gql`
513
- mutation SetPreferredEditor(
514
- $documentIdentifier: String!
515
- $preferredEditor: String
516
- $branch: String
517
- ) {
518
- setPreferredEditor(
519
- documentIdentifier: $documentIdentifier
520
- preferredEditor: $preferredEditor
521
- branch: $branch
522
- ) {
523
- ...PHDocumentFields
524
- }
525
- }
526
- ${PhDocumentFieldsFragmentDoc}
527
- `;
528
- import_main.gql`
529
- mutation AddRelationship(
530
- $sourceIdentifier: String!
531
- $targetIdentifier: String!
532
- $relationshipType: String!
533
- $branch: String
534
- ) {
535
- addRelationship(
536
- sourceIdentifier: $sourceIdentifier
537
- targetIdentifier: $targetIdentifier
538
- relationshipType: $relationshipType
539
- branch: $branch
540
- ) {
541
- ...PHDocumentFields
542
- }
543
- }
544
- ${PhDocumentFieldsFragmentDoc}
545
- `;
546
- import_main.gql`
547
- mutation RemoveRelationship(
548
- $sourceIdentifier: String!
549
- $targetIdentifier: String!
550
- $relationshipType: String!
551
- $branch: String
552
- ) {
553
- removeRelationship(
554
- sourceIdentifier: $sourceIdentifier
555
- targetIdentifier: $targetIdentifier
556
- relationshipType: $relationshipType
557
- branch: $branch
558
- ) {
559
- ...PHDocumentFields
560
- }
561
- }
562
- ${PhDocumentFieldsFragmentDoc}
563
- `;
564
- import_main.gql`
565
- mutation MoveRelationship(
566
- $sourceParentIdentifier: String!
567
- $targetParentIdentifier: String!
568
- $targetIdentifier: String!
569
- $relationshipType: String!
570
- $branch: String
571
- ) {
572
- moveRelationship(
573
- sourceParentIdentifier: $sourceParentIdentifier
574
- targetParentIdentifier: $targetParentIdentifier
575
- targetIdentifier: $targetIdentifier
576
- relationshipType: $relationshipType
577
- branch: $branch
578
- ) {
579
- source {
580
- ...PHDocumentFields
581
- }
582
- target {
583
- ...PHDocumentFields
584
- }
585
- }
586
- }
587
- ${PhDocumentFieldsFragmentDoc}
588
- `;
589
- import_main.gql`
590
- mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
591
- deleteDocument(identifier: $identifier, propagate: $propagate)
592
- }
593
- `;
594
- import_main.gql`
595
- mutation DeleteDocuments(
596
- $identifiers: [String!]!
597
- $propagate: PropagationMode
598
- ) {
599
- deleteDocuments(identifiers: $identifiers, propagate: $propagate)
600
- }
601
- `;
602
- import_main.gql`
603
- subscription DocumentChanges(
604
- $search: SearchFilterInput
605
- $view: ViewFilterInput
606
- ) {
607
- documentChanges(search: $search, view: $view) {
608
- type
609
- documents {
610
- ...PHDocumentFields
611
- }
612
- context {
613
- parentId
614
- childId
615
- }
616
- }
617
- }
618
- ${PhDocumentFieldsFragmentDoc}
619
- `;
620
- import_main.gql`
621
- subscription JobChanges($jobId: String!) {
622
- jobChanges(jobId: $jobId) {
623
- jobId
624
- status
625
- result
626
- error
627
- }
628
- }
629
- `;
630
- import_main.gql`
631
- query PollSyncEnvelopes(
632
- $channelId: String!
633
- $outboxAck: Int!
634
- $outboxLatest: Int!
635
- ) {
636
- pollSyncEnvelopes(
637
- channelId: $channelId
638
- outboxAck: $outboxAck
639
- outboxLatest: $outboxLatest
640
- ) {
641
- envelopes {
642
- type
643
- channelMeta {
644
- id
645
- }
646
- operations {
647
- operation {
648
- index
649
- timestampUtcMs
650
- hash
651
- skip
652
- error
653
- id
654
- action {
655
- id
656
- type
657
- timestampUtcMs
658
- input
659
- scope
660
- context {
661
- signer {
662
- user {
663
- address
664
- networkId
665
- chainId
666
- }
667
- app {
668
- name
669
- key
670
- }
671
- signatures
672
- }
673
- }
674
- }
675
- }
676
- context {
677
- documentId
678
- documentType
679
- scope
680
- branch
681
- }
682
- }
683
- cursor {
684
- remoteName
685
- cursorOrdinal
686
- lastSyncedAtUtcMs
687
- }
688
- key
689
- dependsOn
690
- }
691
- ackOrdinal
692
- deadLetters {
693
- documentId
694
- error
695
- }
696
- hasMore
697
- }
698
- }
699
- `;
700
- import_main.gql`
701
- mutation TouchChannel($input: TouchChannelInput!) {
702
- touchChannel(input: $input) {
703
- success
704
- ackOrdinal
705
- }
706
- }
707
- `;
708
- import_main.gql`
709
- mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
710
- pushSyncEnvelopes(envelopes: $envelopes)
711
- }
712
- `;
713
- /** Get the source string from a GraphQL document (string or DocumentNode). */
714
- function getDocumentSource(doc) {
715
- return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
716
- }
717
- /**
718
- * Extract the inner selection set of a named field from a GraphQL document source.
719
- * Returns the `{ ... }` block including braces.
720
- */
721
- function extractSelectionSet(doc, fieldName, fallback) {
722
- const source = getDocumentSource(doc);
723
- return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
724
- }
725
- /**
726
- * Extract the query body and any fragment definitions from a GraphQL document.
727
- * Returns { body, fragments } where body is the content inside the query `{ ... }`
728
- * and fragments are any trailing fragment definitions.
729
- */
730
- function extractQueryParts(doc, fallbackBody) {
731
- const source = getDocumentSource(doc);
732
- const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
733
- return {
734
- body: queryMatch?.[1]?.trim() ?? fallbackBody,
735
- fragments: queryMatch?.[2]?.trim() ?? ""
736
- };
737
- }
738
- extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
739
- extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
740
- //#endregion
741
- //#region ../reactor-browser/dist/renown-D-1c_Bvx.js
742
- const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
743
- const renownEventFunctions = makePHEventFunctions("renown");
744
- renownEventFunctions.addEventHandler;
745
- /** Returns the renown instance */
746
- const useRenown = renownEventFunctions.useValue;
747
- renownEventFunctions.setValue;
748
- /** Returns the current user from the renown instance, subscribing to user events */
749
- function useUser() {
750
- const renown = useRenown();
751
- const [user, setUser] = useState(renown?.user);
752
- useEffect(() => {
753
- setUser(renown?.user);
754
- if (!renown) return;
755
- return renown.on("user", setUser);
756
- }, [renown]);
757
- return user;
758
- }
759
- function mergeProps(parentProps, childProps) {
760
- const merged = { ...parentProps };
761
- for (const key of Object.keys(childProps)) {
762
- const parentValue = parentProps[key];
763
- const childValue = childProps[key];
764
- if (key === "style") merged[key] = {
765
- ...parentValue,
766
- ...childValue
767
- };
768
- else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
769
- else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
770
- childValue(...args);
771
- parentValue(...args);
772
- };
773
- else if (childValue !== void 0) merged[key] = childValue;
774
- }
775
- return merged;
776
- }
777
- const Slot = forwardRef(({ children, ...props }, ref) => {
778
- const child = Children.only(children);
779
- if (!isValidElement(child)) return null;
780
- const childElement = child;
781
- const mergedProps = mergeProps(props, childElement.props);
782
- if (ref) mergedProps.ref = ref;
783
- return cloneElement(childElement, mergedProps);
784
- });
785
- Slot.displayName = "Slot";
786
- //#endregion
787
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
788
- function e$8(e, t, n) {
789
- let r = (n) => e(n, ...t);
790
- return n === void 0 ? r : Object.assign(r, {
791
- lazy: n,
792
- lazyArgs: t
793
- });
794
- }
795
- //#endregion
796
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
797
- function t$5(t, n, r) {
798
- let i = t.length - n.length;
799
- if (i === 0) return t(...n);
800
- if (i === 1) return e$8(t, n, r);
801
- throw Error(`Wrong number of arguments`);
802
- }
803
- //#endregion
804
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
805
- function t$4(...t) {
806
- return t$5(n$4, t);
807
- }
808
- const n$4 = (e, t) => t.every((t) => t(e));
809
- //#endregion
810
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
811
- function e$7(e, t, n) {
812
- return e(n[0]) ? (e) => t(e, ...n) : t(...n);
813
- }
814
- function t$3(...t) {
815
- return e$7(r, n$3, t);
816
- }
817
- function n$3(e, ...t) {
818
- for (let n of t) {
819
- if (typeof n == `function`) return n(e);
820
- let [t, r] = n;
821
- if (t(e)) return r(e);
822
- }
823
- throw Error(`conditional: data failed for all cases`);
824
- }
825
- function r(e) {
826
- if (!Array.isArray(e)) return !1;
827
- let [t, n, ...r] = e;
828
- return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
829
- }
830
- //#endregion
831
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
832
- function e$6(e) {
833
- return () => e;
834
- }
835
- //#endregion
836
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
837
- function t$2(...t) {
838
- return t$5(n$2, t);
839
- }
840
- const n$2 = (e, t) => e.length >= t;
841
- //#endregion
842
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
843
- const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
844
- function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
845
- let c, l, u, d, f = () => {
846
- let t = u;
847
- t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
848
- }, p = () => {
849
- clearTimeout(l), l = void 0, c === void 0 && f();
850
- }, m = () => {
851
- clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
852
- };
853
- return {
854
- call: (...e) => {
855
- let t = c === void 0 && l === void 0;
856
- if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
857
- if (i !== void 0 || a !== void 0 || o === void 0) {
858
- clearTimeout(c);
859
- let e = Date.now();
860
- d ??= e;
861
- let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
862
- c = setTimeout(m, t);
863
- }
864
- r !== `end` && t && f();
865
- }
866
- },
867
- cancel: () => {
868
- clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
869
- },
870
- flush: () => {
871
- m(), p();
872
- },
873
- get isIdle() {
874
- return c === void 0 && l === void 0;
875
- }
876
- };
877
- }
878
- //#endregion
879
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
880
- function e$4(e) {
881
- return e !== void 0;
882
- }
883
- //#endregion
884
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
885
- function e$3(e) {
886
- return (t) => !e(t);
887
- }
888
- //#endregion
889
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
890
- function t(...t) {
891
- return t$5(n, t);
892
- }
893
- const n = (e, t) => e === t || Object.is(e, t);
894
- //#endregion
895
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
896
- function e$2(e) {
897
- return typeof e == `string`;
898
- }
899
- //#endregion
900
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
901
- function e$1(e) {
902
- return !!e;
903
- }
904
- //#endregion
905
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
906
- function e(e) {
907
- let t = !1, n;
908
- return () => (t ||= (n = e(), !0), n);
909
- }
910
- //#endregion
911
- //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
912
- let base64;
913
- if (typeof window !== "undefined") if (window.btoa) base64 = function(input) {
914
- return btoa(unescape(encodeURIComponent(input)));
915
- };
916
- else base64 = function(input) {
917
- const str = unescape(encodeURIComponent(input + ""));
918
- let output = "";
919
- for (let block, charCode, idx = 0, map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; str.charAt(idx | 0) || (map = "=", idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
920
- charCode = str.charCodeAt(idx += 3 / 4);
921
- /* c8 ignore next 3 */
922
- if (charCode > 255) throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
923
- block = block << 8 | charCode;
924
- }
925
- return output;
926
- };
927
- else base64 = function(input) {
928
- return Buffer.from(input).toString("base64");
929
- };
930
- function slug(string, opts) {
931
- let result = slugify(string, opts);
932
- if ((opts && opts.fallback !== void 0 ? opts.fallback : slug.defaults.fallback) === true && result === "") result = slugify(base64(string), opts);
933
- return result;
245
+ //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
246
+ let base64;
247
+ if (typeof window !== "undefined") if (window.btoa) base64 = function(input) {
248
+ return btoa(unescape(encodeURIComponent(input)));
249
+ };
250
+ else base64 = function(input) {
251
+ const str = unescape(encodeURIComponent(input + ""));
252
+ let output = "";
253
+ for (let block, charCode, idx = 0, map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; str.charAt(idx | 0) || (map = "=", idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
254
+ charCode = str.charCodeAt(idx += 3 / 4);
255
+ /* c8 ignore next 3 */
256
+ if (charCode > 255) throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
257
+ block = block << 8 | charCode;
258
+ }
259
+ return output;
260
+ };
261
+ else base64 = function(input) {
262
+ return Buffer.from(input).toString("base64");
263
+ };
264
+ function slug(string, opts) {
265
+ let result = slugify(string, opts);
266
+ if ((opts && opts.fallback !== void 0 ? opts.fallback : slug.defaults.fallback) === true && result === "") result = slugify(base64(string), opts);
267
+ return result;
934
268
  }
935
269
  const locales = {
936
270
  bg: {
@@ -1694,715 +1028,1077 @@ slug.setLocale = function(locale) {
1694
1028
  defaultLocale = locales[locale] || {};
1695
1029
  };
1696
1030
  //#endregion
1697
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1698
- const normalizeDescriptors = (error) => {
1699
- CORE_ERROR_PROPS.forEach((propName) => {
1700
- normalizeDescriptor(error, propName);
1701
- });
1702
- };
1703
- const CORE_ERROR_PROPS = [
1704
- "name",
1705
- "message",
1706
- "stack",
1707
- "cause",
1708
- "errors"
1709
- ];
1710
- const normalizeDescriptor = (error, propName) => {
1711
- const descriptor = getDescriptor(error, propName);
1712
- if (descriptor === void 0) return;
1713
- if (isReadonlyGetter(descriptor)) {
1714
- setErrorProperty(error, propName, error[propName]);
1715
- return;
1031
+ //#region ../reactor-browser/dist/document-model-modules-DfQBNGc-.js
1032
+ var UnsupportedDocumentTypeError = class extends Error {
1033
+ constructor(documentType) {
1034
+ super(`Document type ${documentType} is not supported`);
1035
+ this.name = "UnsupportedDocumentTypeError";
1036
+ }
1037
+ static isError(error) {
1038
+ return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
1716
1039
  }
1717
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1718
- };
1719
- const getDescriptor = (value, propName) => {
1720
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1721
- if (descriptor !== void 0) return descriptor;
1722
- const prototype = Object.getPrototypeOf(value);
1723
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
1724
- };
1725
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1726
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1727
- const setErrorProperty = (error, propName, value) => {
1728
- setErrorDescriptor(error, propName, { value });
1729
1040
  };
1730
- const setErrorDescriptor = (error, propName, descriptor) => {
1731
- Object.defineProperty(error, propName, {
1732
- ...descriptor,
1733
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1734
- enumerable: false,
1735
- configurable: true
1736
- });
1041
+ var DocumentModelNotFoundError = class extends Error {
1042
+ documentType;
1043
+ name = "DocumentModelNotFoundError";
1044
+ constructor(documentType) {
1045
+ super(`Document model module for type ${documentType} not found`);
1046
+ this.documentType = documentType;
1047
+ }
1048
+ static isError(error) {
1049
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1050
+ }
1737
1051
  };
1738
- //#endregion
1739
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1740
- const normalizeAggregate = (error, recurse) => {
1741
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1742
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1743
- else if (error.errors !== void 0) deleteAggregateErrors(error);
1052
+ var DocumentTypeMismatchError = class extends Error {
1053
+ constructor(documentId, expectedType, actualType) {
1054
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1055
+ }
1744
1056
  };
1745
- const isDefined = (error) => error !== void 0;
1746
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1747
- const deleteAggregateErrors = (error) => {
1748
- delete error.errors;
1749
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1057
+ var NoSelectedDocumentError = class extends Error {
1058
+ constructor() {
1059
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1060
+ }
1750
1061
  };
1751
- //#endregion
1752
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1753
- const normalizeCause = (error, recurse) => {
1754
- if (!("cause" in error)) return;
1755
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1756
- if (cause === void 0) delete error.cause;
1757
- else setErrorProperty(error, "cause", cause);
1758
- };
1759
- //#endregion
1760
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1761
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1762
- const isInstanceOfError = (value) => {
1763
- try {
1764
- return value instanceof Error;
1765
- } catch {
1766
- return false;
1767
- }
1768
- };
1769
- const hasErrorTag = (value) => {
1770
- try {
1771
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
1772
- } catch {
1773
- return false;
1774
- }
1775
- };
1776
- const ERROR_TAGS = new Set([
1777
- "[object Error]",
1778
- "[object DOMException]",
1779
- "[object DOMError]",
1780
- "[object Exception]"
1781
- ]);
1782
- //#endregion
1783
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1784
- function isPlainObject(value) {
1785
- if (typeof value !== "object" || value === null) return false;
1786
- const prototype = Object.getPrototypeOf(value);
1787
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1062
+ function resolveUrlPathname(path) {
1063
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
1788
1064
  }
1789
- //#endregion
1790
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1791
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1792
- const isNonConfigurableProp = (error, propName) => {
1793
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1794
- return descriptor !== void 0 && !descriptor.configurable;
1795
- };
1796
- const isThrowingProp = (error, propName) => {
1797
- try {
1798
- error[propName];
1799
- return false;
1800
- } catch {
1801
- return true;
1065
+ /** Returns the current path without the base path */
1066
+ function getPathWithoutBase(path) {
1067
+ const basePath = window.ph?.basePath ?? "/";
1068
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
1069
+ }
1070
+ /** Makes a URL component for a node. */
1071
+ function makeNodeSlug(node) {
1072
+ if (!node) return "";
1073
+ const nodeName = node.name;
1074
+ if (!nodeName) return slug(node.id);
1075
+ return slug(`${nodeName}-${node.id}`);
1076
+ }
1077
+ /** Extracts the node slug from a path.
1078
+ *
1079
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
1080
+ */
1081
+ function extractNodeSlugFromPath(path) {
1082
+ const currentPath = getPathWithoutBase(path);
1083
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
1084
+ }
1085
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
1086
+ function findUuid(input) {
1087
+ if (!input) return void 0;
1088
+ return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
1089
+ }
1090
+ function extractNodeIdFromSlug(nodeSlug) {
1091
+ return findUuid(nodeSlug);
1092
+ }
1093
+ /** Extracts the drive slug from a path.
1094
+ * Used for extracting drive ids from drive slugs in the URL.
1095
+ * Expects the path to be in the format `/d/<drive-slug>`.
1096
+ */
1097
+ function extractDriveSlugFromPath(path) {
1098
+ const currentPath = getPathWithoutBase(path);
1099
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
1100
+ }
1101
+ /**
1102
+ * Creates a URL string with the given pathname while preserving existing query parameters.
1103
+ */
1104
+ function createUrlWithPreservedParams(pathname) {
1105
+ const search = window.location.search;
1106
+ return search ? `${pathname}${search}` : pathname;
1107
+ }
1108
+ const drivesEventFunctions = makePHEventFunctions("drives");
1109
+ /** Returns all of the drives in the reactor */
1110
+ const useDrives = drivesEventFunctions.useValue;
1111
+ /** Sets the drives in the reactor */
1112
+ const setDrives = drivesEventFunctions.setValue;
1113
+ drivesEventFunctions.addEventHandler;
1114
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
1115
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
1116
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
1117
+ selectedNodeIdEventFunctions.addEventHandler;
1118
+ /** Sets the selected node (file or folder). */
1119
+ function setSelectedNode(nodeOrNodeSlug) {
1120
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
1121
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
1122
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
1123
+ if (!driveSlugFromPath) return;
1124
+ if (!nodeSlug) {
1125
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
1126
+ if (pathname === window.location.pathname) return;
1127
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1128
+ return;
1802
1129
  }
1803
- };
1804
- //#endregion
1805
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1806
- const setStack = (error) => {
1807
- setErrorProperty(error, "stack", getStack(error.message, error.name));
1808
- };
1809
- const getStack = (message = "", name = "Error") => {
1810
- const { stack } = new (getErrorClass(name))(message);
1811
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1812
- };
1813
- const getErrorClass = (name) => {
1814
- const descriptor = {
1815
- value: name,
1816
- enumerable: false,
1817
- writable: true,
1818
- configurable: true
1819
- };
1820
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1821
- Object.defineProperty(StackError.prototype, "name", descriptor);
1822
- return StackError;
1823
- };
1824
- //#endregion
1825
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1826
- const copyObject = (object) => {
1827
- const objectCopy = {};
1828
- for (const propName of getPropsToCopy(object)) try {
1829
- const value = object[propName];
1830
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1831
- Object.defineProperty(objectCopy, propName, {
1832
- value,
1833
- enumerable,
1834
- configurable,
1835
- writable
1836
- });
1837
- } catch {}
1838
- return objectCopy;
1839
- };
1840
- const getPropsToCopy = (object) => {
1841
- const propNames = getOwnKeys(object);
1842
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1843
- return propNames;
1844
- };
1845
- const getOwnKeys = (object) => {
1846
- try {
1847
- return Reflect.ownKeys(object);
1848
- } catch {
1849
- return [];
1130
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
1131
+ if (pathname === window.location.pathname) return;
1132
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1133
+ }
1134
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
1135
+ /** Returns the selected drive id */
1136
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
1137
+ /** Sets the selected drive id */
1138
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
1139
+ selectedDriveIdEventFunctions.addEventHandler;
1140
+ /** Returns the selected drive, or undefined if no drive is selected */
1141
+ function useSelectedDriveSafe() {
1142
+ const selectedDriveId = useSelectedDriveId();
1143
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
1144
+ const [drive, dispatch] = useDispatch(selectedDrive);
1145
+ if (!selectedDrive) return [void 0, void 0];
1146
+ return [drive, dispatch];
1147
+ }
1148
+ function setSelectedDrive(driveOrDriveSlug) {
1149
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
1150
+ const drives = window.ph?.drives;
1151
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
1152
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
1153
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
1154
+ deferDriveSelection(driveSlug);
1155
+ return;
1850
1156
  }
1851
- };
1852
- const isInheritedProp = (object, propName) => {
1853
- try {
1854
- return propName in object && !Object.hasOwn(object, propName);
1855
- } catch {
1856
- return false;
1157
+ cancelPendingDriveSelection();
1158
+ setSelectedDriveId(driveId);
1159
+ if (!driveId) {
1160
+ const pathname = resolveUrlPathname("/");
1161
+ if (pathname === window.location.pathname) return;
1162
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1163
+ return;
1857
1164
  }
1858
- };
1859
- //#endregion
1860
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1861
- const objectifyError = (object) => {
1862
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1863
- const messageA = getMessage(message, objectA);
1864
- const error = newError(name, messageA);
1865
- if (message === messageA) assignObjectProps(error, objectA);
1866
- Object.entries({
1867
- name,
1868
- stack,
1869
- cause,
1870
- errors
1871
- }).forEach(([propName, propValue]) => {
1872
- setNewErrorProperty(error, propName, propValue);
1165
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
1166
+ if (pathname === window.location.pathname) return;
1167
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1168
+ }
1169
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
1170
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
1171
+ function isInitialSyncInFlight() {
1172
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
1173
+ if (!remotes?.length) return false;
1174
+ return remotes.some((remote) => {
1175
+ try {
1176
+ const snapshot = remote.channel.getConnectionState();
1177
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
1178
+ } catch {
1179
+ return false;
1180
+ }
1873
1181
  });
1874
- if (stack === void 0) setStack(error);
1875
- return error;
1876
- };
1877
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1878
- const safeJsonStringify = (object) => {
1879
- try {
1880
- return JSON.stringify(object);
1881
- } catch {
1882
- return safeStringify(object);
1182
+ }
1183
+ let pendingHandler;
1184
+ let pendingTimeout;
1185
+ function cancelPendingDriveSelection() {
1186
+ if (pendingHandler) {
1187
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
1188
+ pendingHandler = void 0;
1883
1189
  }
1884
- };
1885
- const safeStringify = (object) => {
1886
- try {
1887
- return String(object);
1888
- } catch {
1889
- return "Invalid error";
1890
- }
1891
- };
1892
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1893
- const MESSAGE_MAX_SIZE = 1e3;
1894
- const newError = (name, message) => {
1895
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1896
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1897
- return new Error(message);
1898
- };
1899
- const NATIVE_ERRORS = {
1900
- Error,
1901
- ReferenceError,
1902
- TypeError,
1903
- SyntaxError,
1904
- RangeError,
1905
- URIError,
1906
- EvalError
1907
- };
1908
- const assignObjectProps = (error, object) => {
1909
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1910
- };
1911
- const setNewErrorProperty = (error, propName, propValue) => {
1912
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1913
- };
1914
- //#endregion
1915
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1916
- const stringifyError = (value) => {
1917
- try {
1918
- const error = new Error(String(value));
1919
- setStack(error);
1920
- return error;
1921
- } catch (error_) {
1922
- return error_;
1923
- }
1924
- };
1925
- //#endregion
1926
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1927
- const { toString: objectToString } = Object.prototype;
1928
- const createError = (value) => {
1929
- if (isErrorPlainObj(value)) return objectifyError(value);
1930
- if (!isErrorInstance(value)) return stringifyError(value);
1931
- if (isInvalidError(value)) return objectifyError(value);
1932
- return value;
1933
- };
1934
- const isErrorPlainObj = (value) => {
1935
- try {
1936
- return isPlainObject(value);
1937
- } catch {
1938
- return false;
1190
+ if (pendingTimeout) {
1191
+ clearTimeout(pendingTimeout);
1192
+ pendingTimeout = void 0;
1939
1193
  }
1194
+ }
1195
+ function deferDriveSelection(driveSlug) {
1196
+ cancelPendingDriveSelection();
1197
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
1198
+ const handler = () => {
1199
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
1200
+ cancelPendingDriveSelection();
1201
+ setSelectedDrive(driveSlug);
1202
+ setSelectedNode(nodeSlug);
1203
+ };
1204
+ pendingHandler = handler;
1205
+ window.addEventListener("ph:drivesUpdated", handler);
1206
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
1207
+ const scheduleTick = () => {
1208
+ pendingTimeout = setTimeout(() => {
1209
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
1210
+ scheduleTick();
1211
+ return;
1212
+ }
1213
+ cancelPendingDriveSelection();
1214
+ const pathname = resolveUrlPathname("/");
1215
+ if (pathname === window.location.pathname) return;
1216
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1217
+ }, DEFERRED_DRIVE_TICK_MS);
1218
+ };
1219
+ scheduleTick();
1220
+ }
1221
+ /** Sorts nodes by name. */
1222
+ function sortNodesByName(nodes) {
1223
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
1224
+ }
1225
+ /** Returns whether a node is a file. */
1226
+ function isFileNodeKind(node) {
1227
+ if (!node) return false;
1228
+ return node.kind.toUpperCase() === "FILE";
1229
+ }
1230
+ /** Returns whether a node is a folder. */
1231
+ function isFolderNodeKind(node) {
1232
+ if (!node) return false;
1233
+ return node.kind.toUpperCase() === "FOLDER";
1234
+ }
1235
+ /** Returns the nodes in the selected drive. */
1236
+ function useNodesInSelectedDrive() {
1237
+ const [selectedDrive] = useSelectedDriveSafe();
1238
+ return selectedDrive?.state.global.nodes;
1239
+ }
1240
+ /** Returns the folder nodes in the selected drive. */
1241
+ function useFolderNodesInSelectedDrive() {
1242
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
1243
+ }
1244
+ /** Returns the selected node. */
1245
+ function useSelectedNode() {
1246
+ const selectedNodeId = useSelectedNodeId();
1247
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
1248
+ }
1249
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
1250
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
1251
+ const EMPTY_VETRA_PACKAGES = [];
1252
+ const noPackageManagerUnsubscribe = () => {};
1253
+ /**
1254
+ * Returns all of the Vetra packages loaded by the Connect instance.
1255
+ *
1256
+ * The snapshot and subscription must keep stable identity while no package
1257
+ * manager is registered: `useSyncExternalStore` loops when the snapshot
1258
+ * changes on every read, which a fresh `[]` does.
1259
+ */
1260
+ const useVetraPackages = () => {
1261
+ const packageManager = useVetraPackageManager();
1262
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : noPackageManagerUnsubscribe, () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES);
1940
1263
  };
1941
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1942
- const isProxy = (value) => {
1943
- try {
1944
- return objectToString.call(value) === "[object Object]";
1945
- } catch {
1946
- return true;
1264
+ vetraPackageManagerFunctions.addEventHandler;
1265
+ function useDocumentModelModules() {
1266
+ return useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);
1267
+ }
1268
+ /**
1269
+ * Resolves a document model module by document type, mirroring the registry's
1270
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
1271
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
1272
+ * with `version` given only an exact match is returned. The reactor resolves
1273
+ * modules the same way when a document is created, so metadata read through
1274
+ * this hook and the version a creation actually uses cannot disagree.
1275
+ */
1276
+ function useDocumentModelModuleById(id, version) {
1277
+ const documentModelModules = useDocumentModelModules();
1278
+ if (!id || !documentModelModules) return void 0;
1279
+ let latestModule;
1280
+ let latestVersion = -1;
1281
+ for (const module of documentModelModules) {
1282
+ if (module.documentModel.global.id !== id) continue;
1283
+ const moduleVersion = module.version ?? 1;
1284
+ if (version !== void 0) {
1285
+ if (moduleVersion === version) return module;
1286
+ continue;
1287
+ }
1288
+ if (moduleVersion > latestVersion) {
1289
+ latestVersion = moduleVersion;
1290
+ latestModule = module;
1291
+ }
1947
1292
  }
1948
- };
1949
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1293
+ return latestModule;
1294
+ }
1295
+ Error;
1950
1296
  //#endregion
1951
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1952
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1953
- const recurseException = (error, parents, shallow) => {
1954
- if (parents.includes(error)) return;
1955
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1956
- const errorA = createError(error);
1957
- normalizeProps(errorA, recurse);
1958
- return errorA;
1959
- };
1960
- const identity = (error) => error;
1961
- const normalizeProps = (error, recurse) => {
1962
- normalizeName(error);
1963
- normalizeMessage(error);
1964
- normalizeStack(error);
1965
- normalizeCause(error, recurse);
1966
- normalizeAggregate(error, recurse);
1967
- normalizeDescriptors(error);
1968
- };
1969
- const normalizeName = (error) => {
1970
- if (isDefinedString(error.name)) return;
1971
- const prototypeName = Object.getPrototypeOf(error).name;
1972
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1973
- };
1974
- const normalizeMessage = (error) => {
1975
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1976
- };
1977
- const normalizeStack = (error) => {
1978
- if (!isDefinedString(error.stack)) setStack(error);
1979
- };
1980
- const isDefinedString = (value) => typeof value === "string" && value !== "";
1297
+ //#region ../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/lib/graphql.js
1298
+ var import_graphql = require_graphql();
1299
+ JSON;
1981
1300
  //#endregion
1982
- //#region ../reactor-browser/dist/index.js
1983
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1984
- var LZString = (function() {
1985
- var f = String.fromCharCode;
1986
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
1987
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
1988
- var baseReverseDic = {};
1989
- function getBaseValue(alphabet, character) {
1990
- if (!baseReverseDic[alphabet]) {
1991
- baseReverseDic[alphabet] = {};
1992
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
1993
- }
1994
- return baseReverseDic[alphabet][character];
1995
- }
1996
- var LZString = {
1997
- compressToBase64: function(input) {
1998
- if (input == null) return "";
1999
- var res = LZString._compress(input, 6, function(a) {
2000
- return keyStrBase64.charAt(a);
2001
- });
2002
- switch (res.length % 4) {
2003
- default:
2004
- case 0: return res;
2005
- case 1: return res + "===";
2006
- case 2: return res + "==";
2007
- case 3: return res + "=";
2008
- }
2009
- },
2010
- decompressFromBase64: function(input) {
2011
- if (input == null) return "";
2012
- if (input == "") return null;
2013
- return LZString._decompress(input.length, 32, function(index) {
2014
- return getBaseValue(keyStrBase64, input.charAt(index));
2015
- });
2016
- },
2017
- compressToUTF16: function(input) {
2018
- if (input == null) return "";
2019
- return LZString._compress(input, 15, function(a) {
2020
- return f(a + 32);
2021
- }) + " ";
2022
- },
2023
- decompressFromUTF16: function(compressed) {
2024
- if (compressed == null) return "";
2025
- if (compressed == "") return null;
2026
- return LZString._decompress(compressed.length, 16384, function(index) {
2027
- return compressed.charCodeAt(index) - 32;
2028
- });
2029
- },
2030
- compressToUint8Array: function(uncompressed) {
2031
- var compressed = LZString.compress(uncompressed);
2032
- var buf = new Uint8Array(compressed.length * 2);
2033
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2034
- var current_value = compressed.charCodeAt(i);
2035
- buf[i * 2] = current_value >>> 8;
2036
- buf[i * 2 + 1] = current_value % 256;
2037
- }
2038
- return buf;
2039
- },
2040
- decompressFromUint8Array: function(compressed) {
2041
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2042
- else {
2043
- var buf = new Array(compressed.length / 2);
2044
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2045
- var result = [];
2046
- buf.forEach(function(c) {
2047
- result.push(f(c));
2048
- });
2049
- return LZString.decompress(result.join(""));
2050
- }
2051
- },
2052
- compressToEncodedURIComponent: function(input) {
2053
- if (input == null) return "";
2054
- return LZString._compress(input, 6, function(a) {
2055
- return keyStrUriSafe.charAt(a);
2056
- });
2057
- },
2058
- decompressFromEncodedURIComponent: function(input) {
2059
- if (input == null) return "";
2060
- if (input == "") return null;
2061
- input = input.replace(/ /g, "+");
2062
- return LZString._decompress(input.length, 32, function(index) {
2063
- return getBaseValue(keyStrUriSafe, input.charAt(index));
2064
- });
2065
- },
2066
- compress: function(uncompressed) {
2067
- return LZString._compress(uncompressed, 16, function(a) {
2068
- return f(a);
2069
- });
2070
- },
2071
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2072
- if (uncompressed == null) return "";
2073
- 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;
2074
- for (ii = 0; ii < uncompressed.length; ii += 1) {
2075
- context_c = uncompressed.charAt(ii);
2076
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2077
- context_dictionary[context_c] = context_dictSize++;
2078
- context_dictionaryToCreate[context_c] = true;
2079
- }
2080
- context_wc = context_w + context_c;
2081
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2082
- else {
2083
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2084
- if (context_w.charCodeAt(0) < 256) {
2085
- for (i = 0; i < context_numBits; i++) {
2086
- context_data_val = context_data_val << 1;
2087
- if (context_data_position == bitsPerChar - 1) {
2088
- context_data_position = 0;
2089
- context_data.push(getCharFromInt(context_data_val));
2090
- context_data_val = 0;
2091
- } else context_data_position++;
2092
- }
2093
- value = context_w.charCodeAt(0);
2094
- for (i = 0; i < 8; i++) {
2095
- context_data_val = context_data_val << 1 | value & 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
- value = value >> 1;
2102
- }
2103
- } else {
2104
- value = 1;
2105
- for (i = 0; i < context_numBits; i++) {
2106
- context_data_val = context_data_val << 1 | value;
2107
- if (context_data_position == bitsPerChar - 1) {
2108
- context_data_position = 0;
2109
- context_data.push(getCharFromInt(context_data_val));
2110
- context_data_val = 0;
2111
- } else context_data_position++;
2112
- value = 0;
2113
- }
2114
- value = context_w.charCodeAt(0);
2115
- for (i = 0; i < 16; i++) {
2116
- context_data_val = context_data_val << 1 | value & 1;
2117
- if (context_data_position == bitsPerChar - 1) {
2118
- context_data_position = 0;
2119
- context_data.push(getCharFromInt(context_data_val));
2120
- context_data_val = 0;
2121
- } else context_data_position++;
2122
- value = value >> 1;
2123
- }
2124
- }
2125
- context_enlargeIn--;
2126
- if (context_enlargeIn == 0) {
2127
- context_enlargeIn = Math.pow(2, context_numBits);
2128
- context_numBits++;
2129
- }
2130
- delete context_dictionaryToCreate[context_w];
2131
- } else {
2132
- value = context_dictionary[context_w];
2133
- for (i = 0; i < context_numBits; i++) {
2134
- context_data_val = context_data_val << 1 | value & 1;
2135
- if (context_data_position == bitsPerChar - 1) {
2136
- context_data_position = 0;
2137
- context_data.push(getCharFromInt(context_data_val));
2138
- context_data_val = 0;
2139
- } else context_data_position++;
2140
- value = value >> 1;
2141
- }
2142
- }
2143
- context_enlargeIn--;
2144
- if (context_enlargeIn == 0) {
2145
- context_enlargeIn = Math.pow(2, context_numBits);
2146
- context_numBits++;
2147
- }
2148
- context_dictionary[context_wc] = context_dictSize++;
2149
- context_w = String(context_c);
2150
- }
2151
- }
2152
- if (context_w !== "") {
2153
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2154
- if (context_w.charCodeAt(0) < 256) {
2155
- for (i = 0; i < context_numBits; i++) {
2156
- context_data_val = context_data_val << 1;
2157
- if (context_data_position == bitsPerChar - 1) {
2158
- context_data_position = 0;
2159
- context_data.push(getCharFromInt(context_data_val));
2160
- context_data_val = 0;
2161
- } else context_data_position++;
2162
- }
2163
- value = context_w.charCodeAt(0);
2164
- for (i = 0; i < 8; i++) {
2165
- context_data_val = context_data_val << 1 | value & 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
- value = value >> 1;
2172
- }
2173
- } else {
2174
- value = 1;
2175
- for (i = 0; i < context_numBits; i++) {
2176
- context_data_val = context_data_val << 1 | value;
2177
- if (context_data_position == bitsPerChar - 1) {
2178
- context_data_position = 0;
2179
- context_data.push(getCharFromInt(context_data_val));
2180
- context_data_val = 0;
2181
- } else context_data_position++;
2182
- value = 0;
2183
- }
2184
- value = context_w.charCodeAt(0);
2185
- for (i = 0; i < 16; i++) {
2186
- context_data_val = context_data_val << 1 | value & 1;
2187
- if (context_data_position == bitsPerChar - 1) {
2188
- context_data_position = 0;
2189
- context_data.push(getCharFromInt(context_data_val));
2190
- context_data_val = 0;
2191
- } else context_data_position++;
2192
- value = value >> 1;
2193
- }
2194
- }
2195
- context_enlargeIn--;
2196
- if (context_enlargeIn == 0) {
2197
- context_enlargeIn = Math.pow(2, context_numBits);
2198
- context_numBits++;
2199
- }
2200
- delete context_dictionaryToCreate[context_w];
2201
- } else {
2202
- value = context_dictionary[context_w];
2203
- for (i = 0; i < context_numBits; i++) {
2204
- context_data_val = context_data_val << 1 | value & 1;
2205
- if (context_data_position == bitsPerChar - 1) {
2206
- context_data_position = 0;
2207
- context_data.push(getCharFromInt(context_data_val));
2208
- context_data_val = 0;
2209
- } else context_data_position++;
2210
- value = value >> 1;
2211
- }
2212
- }
2213
- context_enlargeIn--;
2214
- if (context_enlargeIn == 0) {
2215
- context_enlargeIn = Math.pow(2, context_numBits);
2216
- context_numBits++;
2217
- }
2218
- }
2219
- value = 2;
2220
- for (i = 0; i < context_numBits; i++) {
2221
- context_data_val = context_data_val << 1 | value & 1;
2222
- if (context_data_position == bitsPerChar - 1) {
2223
- context_data_position = 0;
2224
- context_data.push(getCharFromInt(context_data_val));
2225
- context_data_val = 0;
2226
- } else context_data_position++;
2227
- value = value >> 1;
2228
- }
2229
- while (true) {
2230
- context_data_val = context_data_val << 1;
2231
- if (context_data_position == bitsPerChar - 1) {
2232
- context_data.push(getCharFromInt(context_data_val));
2233
- break;
2234
- } else context_data_position++;
2235
- }
2236
- return context_data.join("");
2237
- },
2238
- decompress: function(compressed) {
2239
- if (compressed == null) return "";
2240
- if (compressed == "") return null;
2241
- return LZString._decompress(compressed.length, 32768, function(index) {
2242
- return compressed.charCodeAt(index);
2243
- });
2244
- },
2245
- _decompress: function(length, resetValue, getNextValue) {
2246
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2247
- val: getNextValue(0),
2248
- position: resetValue,
2249
- index: 1
2250
- };
2251
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
2252
- bits = 0;
2253
- maxpower = Math.pow(2, 2);
2254
- power = 1;
2255
- while (power != maxpower) {
2256
- resb = data.val & data.position;
2257
- data.position >>= 1;
2258
- if (data.position == 0) {
2259
- data.position = resetValue;
2260
- data.val = getNextValue(data.index++);
2261
- }
2262
- bits |= (resb > 0 ? 1 : 0) * power;
2263
- power <<= 1;
2264
- }
2265
- switch (bits) {
2266
- case 0:
2267
- bits = 0;
2268
- maxpower = Math.pow(2, 8);
2269
- power = 1;
2270
- while (power != maxpower) {
2271
- resb = data.val & data.position;
2272
- data.position >>= 1;
2273
- if (data.position == 0) {
2274
- data.position = resetValue;
2275
- data.val = getNextValue(data.index++);
2276
- }
2277
- bits |= (resb > 0 ? 1 : 0) * power;
2278
- power <<= 1;
2279
- }
2280
- c = f(bits);
2281
- break;
2282
- case 1:
2283
- bits = 0;
2284
- maxpower = Math.pow(2, 16);
2285
- power = 1;
2286
- while (power != maxpower) {
2287
- resb = data.val & data.position;
2288
- data.position >>= 1;
2289
- if (data.position == 0) {
2290
- data.position = resetValue;
2291
- data.val = getNextValue(data.index++);
2292
- }
2293
- bits |= (resb > 0 ? 1 : 0) * power;
2294
- power <<= 1;
2295
- }
2296
- c = f(bits);
2297
- break;
2298
- case 2: return "";
2299
- }
2300
- dictionary[3] = c;
2301
- w = c;
2302
- result.push(c);
2303
- while (true) {
2304
- if (data.index > length) return "";
2305
- bits = 0;
2306
- maxpower = Math.pow(2, numBits);
2307
- power = 1;
2308
- while (power != maxpower) {
2309
- resb = data.val & data.position;
2310
- data.position >>= 1;
2311
- if (data.position == 0) {
2312
- data.position = resetValue;
2313
- data.val = getNextValue(data.index++);
2314
- }
2315
- bits |= (resb > 0 ? 1 : 0) * power;
2316
- power <<= 1;
2317
- }
2318
- switch (c = bits) {
2319
- case 0:
2320
- bits = 0;
2321
- maxpower = Math.pow(2, 8);
2322
- power = 1;
2323
- while (power != maxpower) {
2324
- resb = data.val & data.position;
2325
- data.position >>= 1;
2326
- if (data.position == 0) {
2327
- data.position = resetValue;
2328
- data.val = getNextValue(data.index++);
2329
- }
2330
- bits |= (resb > 0 ? 1 : 0) * power;
2331
- power <<= 1;
2332
- }
2333
- dictionary[dictSize++] = f(bits);
2334
- c = dictSize - 1;
2335
- enlargeIn--;
2336
- break;
2337
- case 1:
2338
- bits = 0;
2339
- maxpower = Math.pow(2, 16);
2340
- power = 1;
2341
- while (power != maxpower) {
2342
- resb = data.val & data.position;
2343
- data.position >>= 1;
2344
- if (data.position == 0) {
2345
- data.position = resetValue;
2346
- data.val = getNextValue(data.index++);
2347
- }
2348
- bits |= (resb > 0 ? 1 : 0) * power;
2349
- power <<= 1;
2350
- }
2351
- dictionary[dictSize++] = f(bits);
2352
- c = dictSize - 1;
2353
- enlargeIn--;
2354
- break;
2355
- case 2: return result.join("");
2356
- }
2357
- if (enlargeIn == 0) {
2358
- enlargeIn = Math.pow(2, numBits);
2359
- numBits++;
2360
- }
2361
- if (dictionary[c]) entry = dictionary[c];
2362
- else if (c === dictSize) entry = w + w.charAt(0);
2363
- else return null;
2364
- result.push(entry);
2365
- dictionary[dictSize++] = w + entry.charAt(0);
2366
- enlargeIn--;
2367
- w = entry;
2368
- if (enlargeIn == 0) {
2369
- enlargeIn = Math.pow(2, numBits);
2370
- numBits++;
2371
- }
1301
+ //#region ../reactor-browser/dist/client-D66jVnot.js
1302
+ var import_main = require_main();
1303
+ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
1304
+ DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
1305
+ DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
1306
+ DocumentChangeType["Created"] = "CREATED";
1307
+ DocumentChangeType["Deleted"] = "DELETED";
1308
+ DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
1309
+ DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
1310
+ DocumentChangeType["Updated"] = "UPDATED";
1311
+ return DocumentChangeType;
1312
+ }({});
1313
+ let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
1314
+ PropagationMode["Cascade"] = "CASCADE";
1315
+ PropagationMode["Orphan"] = "ORPHAN";
1316
+ return PropagationMode;
1317
+ }({});
1318
+ const PhDocumentFieldsFragmentDoc = import_main.gql`
1319
+ fragment PHDocumentFields on PHDocument {
1320
+ id
1321
+ slug
1322
+ name
1323
+ documentType
1324
+ state
1325
+ revisionsList {
1326
+ scope
1327
+ revision
1328
+ }
1329
+ createdAtUtcIso
1330
+ lastModifiedAtUtcIso
1331
+ }
1332
+ `;
1333
+ import_main.gql`
1334
+ query GetDocumentModels($namespace: String, $paging: PagingInput) {
1335
+ documentModels(namespace: $namespace, paging: $paging) {
1336
+ items {
1337
+ id
1338
+ name
1339
+ namespace
1340
+ version
1341
+ specification
1342
+ }
1343
+ totalCount
1344
+ hasNextPage
1345
+ hasPreviousPage
1346
+ cursor
1347
+ }
1348
+ }
1349
+ `;
1350
+ const GetDocumentDocument = import_main.gql`
1351
+ query GetDocument($identifier: String!, $view: ViewFilterInput) {
1352
+ document(identifier: $identifier, view: $view) {
1353
+ document {
1354
+ ...PHDocumentFields
1355
+ }
1356
+ childIds
1357
+ }
1358
+ }
1359
+ ${PhDocumentFieldsFragmentDoc}
1360
+ `;
1361
+ const GetDocumentWithOperationsDocument = import_main.gql`
1362
+ query GetDocumentWithOperations(
1363
+ $identifier: String!
1364
+ $view: ViewFilterInput
1365
+ $operationsFilter: DocumentOperationsFilterInput
1366
+ $operationsPaging: PagingInput
1367
+ ) {
1368
+ document(identifier: $identifier, view: $view) {
1369
+ document {
1370
+ ...PHDocumentFields
1371
+ operations(filter: $operationsFilter, paging: $operationsPaging) {
1372
+ items {
1373
+ index
1374
+ timestampUtcMs
1375
+ hash
1376
+ skip
1377
+ error
1378
+ deniedReason
1379
+ id
1380
+ action {
1381
+ id
1382
+ type
1383
+ timestampUtcMs
1384
+ input
1385
+ scope
1386
+ context {
1387
+ signer {
1388
+ user {
1389
+ address
1390
+ networkId
1391
+ chainId
1392
+ }
1393
+ app {
1394
+ name
1395
+ key
1396
+ }
1397
+ signatures
1398
+ }
1399
+ }
1400
+ }
1401
+ }
1402
+ totalCount
1403
+ hasNextPage
1404
+ hasPreviousPage
1405
+ cursor
1406
+ }
1407
+ }
1408
+ childIds
1409
+ }
1410
+ }
1411
+ ${PhDocumentFieldsFragmentDoc}
1412
+ `;
1413
+ import_main.gql`
1414
+ query GetDocumentOutgoingRelationships(
1415
+ $sourceIdentifier: String!
1416
+ $relationshipType: String!
1417
+ $view: ViewFilterInput
1418
+ $paging: PagingInput
1419
+ ) {
1420
+ documentOutgoingRelationships(
1421
+ sourceIdentifier: $sourceIdentifier
1422
+ relationshipType: $relationshipType
1423
+ view: $view
1424
+ paging: $paging
1425
+ ) {
1426
+ items {
1427
+ ...PHDocumentFields
1428
+ }
1429
+ totalCount
1430
+ hasNextPage
1431
+ hasPreviousPage
1432
+ cursor
1433
+ }
1434
+ }
1435
+ ${PhDocumentFieldsFragmentDoc}
1436
+ `;
1437
+ import_main.gql`
1438
+ query GetDocumentIncomingRelationships(
1439
+ $targetIdentifier: String!
1440
+ $relationshipType: String!
1441
+ $view: ViewFilterInput
1442
+ $paging: PagingInput
1443
+ ) {
1444
+ documentIncomingRelationships(
1445
+ targetIdentifier: $targetIdentifier
1446
+ relationshipType: $relationshipType
1447
+ view: $view
1448
+ paging: $paging
1449
+ ) {
1450
+ items {
1451
+ ...PHDocumentFields
1452
+ }
1453
+ totalCount
1454
+ hasNextPage
1455
+ hasPreviousPage
1456
+ cursor
1457
+ }
1458
+ }
1459
+ ${PhDocumentFieldsFragmentDoc}
1460
+ `;
1461
+ import_main.gql`
1462
+ query FindDocuments(
1463
+ $search: SearchFilterInput
1464
+ $view: ViewFilterInput
1465
+ $paging: PagingInput
1466
+ ) {
1467
+ findDocuments(search: $search, view: $view, paging: $paging) {
1468
+ items {
1469
+ ...PHDocumentFields
1470
+ }
1471
+ totalCount
1472
+ hasNextPage
1473
+ hasPreviousPage
1474
+ cursor
1475
+ }
1476
+ }
1477
+ ${PhDocumentFieldsFragmentDoc}
1478
+ `;
1479
+ const GetDocumentOperationsDocument = import_main.gql`
1480
+ query GetDocumentOperations(
1481
+ $filter: OperationsFilterInput!
1482
+ $paging: PagingInput
1483
+ ) {
1484
+ documentOperations(filter: $filter, paging: $paging) {
1485
+ items {
1486
+ index
1487
+ timestampUtcMs
1488
+ hash
1489
+ skip
1490
+ error
1491
+ deniedReason
1492
+ id
1493
+ action {
1494
+ id
1495
+ type
1496
+ timestampUtcMs
1497
+ input
1498
+ scope
1499
+ context {
1500
+ signer {
1501
+ user {
1502
+ address
1503
+ networkId
1504
+ chainId
1505
+ }
1506
+ app {
1507
+ name
1508
+ key
1509
+ }
1510
+ signatures
1511
+ }
1512
+ }
1513
+ }
1514
+ }
1515
+ totalCount
1516
+ hasNextPage
1517
+ hasPreviousPage
1518
+ cursor
1519
+ }
1520
+ }
1521
+ `;
1522
+ import_main.gql`
1523
+ query GetJobStatus($jobId: String!) {
1524
+ jobStatus(jobId: $jobId) {
1525
+ id
1526
+ status
1527
+ result
1528
+ error
1529
+ createdAt
1530
+ completedAt
1531
+ }
1532
+ }
1533
+ `;
1534
+ import_main.gql`
1535
+ query EvaluateActions(
1536
+ $documentIdentifier: String!
1537
+ $branch: String
1538
+ $candidates: [ActionCandidateInput!]!
1539
+ ) {
1540
+ evaluateActions(
1541
+ documentIdentifier: $documentIdentifier
1542
+ branch: $branch
1543
+ candidates: $candidates
1544
+ ) {
1545
+ evaluations {
1546
+ decision
1547
+ reason
1548
+ }
1549
+ allAllowed
1550
+ anyAllowed
1551
+ allDenied
1552
+ anyDenied
1553
+ }
1554
+ }
1555
+ `;
1556
+ import_main.gql`
1557
+ mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
1558
+ createDocument(document: $document, parentIdentifier: $parentIdentifier) {
1559
+ ...PHDocumentFields
1560
+ }
1561
+ }
1562
+ ${PhDocumentFieldsFragmentDoc}
1563
+ `;
1564
+ import_main.gql`
1565
+ mutation CreateEmptyDocument(
1566
+ $documentType: String!
1567
+ $parentIdentifier: String
1568
+ ) {
1569
+ createEmptyDocument(
1570
+ documentType: $documentType
1571
+ parentIdentifier: $parentIdentifier
1572
+ ) {
1573
+ ...PHDocumentFields
1574
+ }
1575
+ }
1576
+ ${PhDocumentFieldsFragmentDoc}
1577
+ `;
1578
+ import_main.gql`
1579
+ mutation MutateDocument(
1580
+ $documentIdentifier: String!
1581
+ $actions: [ActionInput!]!
1582
+ $branch: String
1583
+ ) {
1584
+ mutateDocument: execute(
1585
+ documentIdentifier: $documentIdentifier
1586
+ actions: $actions
1587
+ branch: $branch
1588
+ ) {
1589
+ ...PHDocumentFields
1590
+ }
1591
+ }
1592
+ ${PhDocumentFieldsFragmentDoc}
1593
+ `;
1594
+ import_main.gql`
1595
+ mutation MutateDocumentAsync(
1596
+ $documentIdentifier: String!
1597
+ $actions: [ActionInput!]!
1598
+ $branch: String
1599
+ ) {
1600
+ mutateDocumentAsync: executeAsync(
1601
+ documentIdentifier: $documentIdentifier
1602
+ actions: $actions
1603
+ branch: $branch
1604
+ ) {
1605
+ id
1606
+ status
1607
+ result
1608
+ error
1609
+ createdAt
1610
+ completedAt
1611
+ }
1612
+ }
1613
+ `;
1614
+ import_main.gql`
1615
+ mutation RenameDocument(
1616
+ $documentIdentifier: String!
1617
+ $name: String!
1618
+ $branch: String
1619
+ ) {
1620
+ renameDocument(
1621
+ documentIdentifier: $documentIdentifier
1622
+ name: $name
1623
+ branch: $branch
1624
+ ) {
1625
+ ...PHDocumentFields
1626
+ }
1627
+ }
1628
+ ${PhDocumentFieldsFragmentDoc}
1629
+ `;
1630
+ import_main.gql`
1631
+ mutation SetPreferredEditor(
1632
+ $documentIdentifier: String!
1633
+ $preferredEditor: String
1634
+ $branch: String
1635
+ ) {
1636
+ setPreferredEditor(
1637
+ documentIdentifier: $documentIdentifier
1638
+ preferredEditor: $preferredEditor
1639
+ branch: $branch
1640
+ ) {
1641
+ ...PHDocumentFields
1642
+ }
1643
+ }
1644
+ ${PhDocumentFieldsFragmentDoc}
1645
+ `;
1646
+ import_main.gql`
1647
+ mutation AddRelationship(
1648
+ $sourceIdentifier: String!
1649
+ $targetIdentifier: String!
1650
+ $relationshipType: String!
1651
+ $branch: String
1652
+ ) {
1653
+ addRelationship(
1654
+ sourceIdentifier: $sourceIdentifier
1655
+ targetIdentifier: $targetIdentifier
1656
+ relationshipType: $relationshipType
1657
+ branch: $branch
1658
+ ) {
1659
+ ...PHDocumentFields
1660
+ }
1661
+ }
1662
+ ${PhDocumentFieldsFragmentDoc}
1663
+ `;
1664
+ import_main.gql`
1665
+ mutation RemoveRelationship(
1666
+ $sourceIdentifier: String!
1667
+ $targetIdentifier: String!
1668
+ $relationshipType: String!
1669
+ $branch: String
1670
+ ) {
1671
+ removeRelationship(
1672
+ sourceIdentifier: $sourceIdentifier
1673
+ targetIdentifier: $targetIdentifier
1674
+ relationshipType: $relationshipType
1675
+ branch: $branch
1676
+ ) {
1677
+ ...PHDocumentFields
1678
+ }
1679
+ }
1680
+ ${PhDocumentFieldsFragmentDoc}
1681
+ `;
1682
+ import_main.gql`
1683
+ mutation MoveRelationship(
1684
+ $sourceParentIdentifier: String!
1685
+ $targetParentIdentifier: String!
1686
+ $targetIdentifier: String!
1687
+ $relationshipType: String!
1688
+ $branch: String
1689
+ ) {
1690
+ moveRelationship(
1691
+ sourceParentIdentifier: $sourceParentIdentifier
1692
+ targetParentIdentifier: $targetParentIdentifier
1693
+ targetIdentifier: $targetIdentifier
1694
+ relationshipType: $relationshipType
1695
+ branch: $branch
1696
+ ) {
1697
+ source {
1698
+ ...PHDocumentFields
1699
+ }
1700
+ target {
1701
+ ...PHDocumentFields
1702
+ }
1703
+ }
1704
+ }
1705
+ ${PhDocumentFieldsFragmentDoc}
1706
+ `;
1707
+ import_main.gql`
1708
+ mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
1709
+ deleteDocument(identifier: $identifier, propagate: $propagate)
1710
+ }
1711
+ `;
1712
+ import_main.gql`
1713
+ mutation DeleteDocuments(
1714
+ $identifiers: [String!]!
1715
+ $propagate: PropagationMode
1716
+ ) {
1717
+ deleteDocuments(identifiers: $identifiers, propagate: $propagate)
1718
+ }
1719
+ `;
1720
+ import_main.gql`
1721
+ subscription DocumentChanges(
1722
+ $search: SearchFilterInput
1723
+ $view: ViewFilterInput
1724
+ ) {
1725
+ documentChanges(search: $search, view: $view) {
1726
+ type
1727
+ documents {
1728
+ ...PHDocumentFields
1729
+ }
1730
+ context {
1731
+ parentId
1732
+ childId
1733
+ }
1734
+ }
1735
+ }
1736
+ ${PhDocumentFieldsFragmentDoc}
1737
+ `;
1738
+ import_main.gql`
1739
+ subscription JobChanges($jobId: String!) {
1740
+ jobChanges(jobId: $jobId) {
1741
+ jobId
1742
+ status
1743
+ result
1744
+ error
1745
+ }
1746
+ }
1747
+ `;
1748
+ import_main.gql`
1749
+ query PollSyncEnvelopes(
1750
+ $channelId: String!
1751
+ $outboxAck: Int!
1752
+ $outboxLatest: Int!
1753
+ ) {
1754
+ pollSyncEnvelopes(
1755
+ channelId: $channelId
1756
+ outboxAck: $outboxAck
1757
+ outboxLatest: $outboxLatest
1758
+ ) {
1759
+ envelopes {
1760
+ type
1761
+ channelMeta {
1762
+ id
1763
+ }
1764
+ operations {
1765
+ operation {
1766
+ index
1767
+ timestampUtcMs
1768
+ hash
1769
+ skip
1770
+ error
1771
+ deniedReason
1772
+ id
1773
+ action {
1774
+ id
1775
+ type
1776
+ timestampUtcMs
1777
+ input
1778
+ scope
1779
+ context {
1780
+ signer {
1781
+ user {
1782
+ address
1783
+ networkId
1784
+ chainId
1785
+ }
1786
+ app {
1787
+ name
1788
+ key
1789
+ }
1790
+ signatures
1791
+ }
1792
+ }
1793
+ }
1794
+ }
1795
+ context {
1796
+ documentId
1797
+ documentType
1798
+ scope
1799
+ branch
1800
+ }
1801
+ }
1802
+ cursor {
1803
+ remoteName
1804
+ cursorOrdinal
1805
+ lastSyncedAtUtcMs
1806
+ }
1807
+ key
1808
+ dependsOn
1809
+ }
1810
+ ackOrdinal
1811
+ deadLetters {
1812
+ documentId
1813
+ error
1814
+ errorType
1815
+ }
1816
+ hasMore
1817
+ }
1818
+ }
1819
+ `;
1820
+ import_main.gql`
1821
+ mutation TouchChannel($input: TouchChannelInput!) {
1822
+ touchChannel(input: $input) {
1823
+ success
1824
+ ackOrdinal
1825
+ }
1826
+ }
1827
+ `;
1828
+ import_main.gql`
1829
+ mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
1830
+ pushSyncEnvelopes(envelopes: $envelopes)
1831
+ }
1832
+ `;
1833
+ /** Get the source string from a GraphQL document (string or DocumentNode). */
1834
+ function getDocumentSource(doc) {
1835
+ return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
1836
+ }
1837
+ /**
1838
+ * Extract the inner selection set of a named field from a GraphQL document source.
1839
+ * Returns the `{ ... }` block including braces.
1840
+ */
1841
+ function extractSelectionSet(doc, fieldName, fallback) {
1842
+ const source = getDocumentSource(doc);
1843
+ return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
1844
+ }
1845
+ /**
1846
+ * Extract the query body and any fragment definitions from a GraphQL document.
1847
+ * Returns { body, fragments } where body is the content inside the query `{ ... }`
1848
+ * and fragments are any trailing fragment definitions.
1849
+ */
1850
+ function extractQueryParts(doc, fallbackBody) {
1851
+ const source = getDocumentSource(doc);
1852
+ const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
1853
+ return {
1854
+ body: queryMatch?.[1]?.trim() ?? fallbackBody,
1855
+ fragments: queryMatch?.[2]?.trim() ?? ""
1856
+ };
1857
+ }
1858
+ extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
1859
+ extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
1860
+ //#endregion
1861
+ //#region ../reactor-browser/dist/renown-BHxwP7xU.js
1862
+ const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
1863
+ const RenownInitialUserContext = createContext({ state: "unknown" });
1864
+ /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
1865
+ function useRenownInitialAuth() {
1866
+ return useContext(RenownInitialUserContext);
1867
+ }
1868
+ function useRenownInitialUser() {
1869
+ const initial = useRenownInitialAuth();
1870
+ return initial.state === "authenticated" ? initial.user : void 0;
1871
+ }
1872
+ const renownEventFunctions = makePHEventFunctions("renown");
1873
+ renownEventFunctions.addEventHandler;
1874
+ /** Returns the renown instance */
1875
+ const useRenown = renownEventFunctions.useValue;
1876
+ renownEventFunctions.setValue;
1877
+ function jsonEqual(a, b) {
1878
+ if (a === b) return true;
1879
+ if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
1880
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
1881
+ const ra = a;
1882
+ const rb = b;
1883
+ const keys = Object.keys(ra).filter((k) => ra[k] !== void 0);
1884
+ if (keys.length !== Object.keys(rb).filter((k) => rb[k] !== void 0).length) return false;
1885
+ return keys.every((k) => jsonEqual(ra[k], rb[k]));
1886
+ }
1887
+ function sameUser(a, b) {
1888
+ return jsonEqual(a, b);
1889
+ }
1890
+ function resolveInstanceUser(instance, seed) {
1891
+ const restored = instance.user;
1892
+ if (restored) return sameUser(seed, restored) ? seed : restored;
1893
+ return instance.status === "initial" ? void 0 : seed;
1894
+ }
1895
+ /** Returns the current user from the renown instance, subscribing to user events */
1896
+ function useUser() {
1897
+ const renown = useRenown();
1898
+ const initialUser = useRenownInitialUser();
1899
+ const instance = renown ? renown : void 0;
1900
+ const [tracked, setTracked] = useState(() => ({
1901
+ instance,
1902
+ user: instance ? resolveInstanceUser(instance, initialUser) : initialUser
1903
+ }));
1904
+ const current = tracked.instance === instance ? tracked : {
1905
+ instance,
1906
+ user: instance ? resolveInstanceUser(instance, tracked.user ?? initialUser) : tracked.user
1907
+ };
1908
+ useEffect(() => {
1909
+ if (current !== tracked) setTracked(current);
1910
+ }, [current, tracked]);
1911
+ useEffect(() => {
1912
+ if (!instance) return;
1913
+ return instance.on("user", (user) => setTracked((prev) => ({
1914
+ instance,
1915
+ user: sameUser(prev.user, user) ? prev.user : user
1916
+ })));
1917
+ }, [instance]);
1918
+ return instance ? current.user : initialUser ?? current.user;
1919
+ }
1920
+ //#endregion
1921
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
1922
+ function e$8(e, t, n) {
1923
+ let r = (n) => e(n, ...t);
1924
+ return n === void 0 ? r : Object.assign(r, {
1925
+ lazy: n,
1926
+ lazyArgs: t
1927
+ });
1928
+ }
1929
+ //#endregion
1930
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
1931
+ function t$5(t, n, r) {
1932
+ let i = t.length - n.length;
1933
+ if (i === 0) return t(...n);
1934
+ if (i === 1) return e$8(t, n, r);
1935
+ throw Error(`Wrong number of arguments`);
1936
+ }
1937
+ //#endregion
1938
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
1939
+ function t$4(...t) {
1940
+ return t$5(n$4, t);
1941
+ }
1942
+ const n$4 = (e, t) => t.every((t) => t(e));
1943
+ //#endregion
1944
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
1945
+ function e$7(e, t, n) {
1946
+ return e(n[0]) ? (e) => t(e, ...n) : t(...n);
1947
+ }
1948
+ function t$3(...t) {
1949
+ return e$7(r, n$3, t);
1950
+ }
1951
+ function n$3(e, ...t) {
1952
+ for (let n of t) {
1953
+ if (typeof n == `function`) return n(e);
1954
+ let [t, r] = n;
1955
+ if (t(e)) return r(e);
1956
+ }
1957
+ throw Error(`conditional: data failed for all cases`);
1958
+ }
1959
+ function r(e) {
1960
+ if (!Array.isArray(e)) return !1;
1961
+ let [t, n, ...r] = e;
1962
+ return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
1963
+ }
1964
+ //#endregion
1965
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
1966
+ function e$6(e) {
1967
+ return () => e;
1968
+ }
1969
+ //#endregion
1970
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
1971
+ function t$2(...t) {
1972
+ return t$5(n$2, t);
1973
+ }
1974
+ const n$2 = (e, t) => e.length >= t;
1975
+ //#endregion
1976
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
1977
+ const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
1978
+ function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
1979
+ let c, l, u, d, f = () => {
1980
+ let t = u;
1981
+ t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
1982
+ }, p = () => {
1983
+ clearTimeout(l), l = void 0, c === void 0 && f();
1984
+ }, m = () => {
1985
+ clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
1986
+ };
1987
+ return {
1988
+ call: (...e) => {
1989
+ let t = c === void 0 && l === void 0;
1990
+ if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
1991
+ if (i !== void 0 || a !== void 0 || o === void 0) {
1992
+ clearTimeout(c);
1993
+ let e = Date.now();
1994
+ d ??= e;
1995
+ let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
1996
+ c = setTimeout(m, t);
2372
1997
  }
1998
+ r !== `end` && t && f();
2373
1999
  }
2374
- };
2375
- return LZString;
2376
- })();
2377
- if (typeof define === "function" && define.amd) define(function() {
2378
- return LZString;
2000
+ },
2001
+ cancel: () => {
2002
+ clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
2003
+ },
2004
+ flush: () => {
2005
+ m(), p();
2006
+ },
2007
+ get isIdle() {
2008
+ return c === void 0 && l === void 0;
2009
+ }
2010
+ };
2011
+ }
2012
+ //#endregion
2013
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
2014
+ function e$4(e) {
2015
+ return e !== void 0;
2016
+ }
2017
+ //#endregion
2018
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
2019
+ function e$3(e) {
2020
+ return (t) => !e(t);
2021
+ }
2022
+ //#endregion
2023
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
2024
+ function t(...t) {
2025
+ return t$5(n, t);
2026
+ }
2027
+ const n = (e, t) => e === t || Object.is(e, t);
2028
+ //#endregion
2029
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
2030
+ function e$2(e) {
2031
+ return typeof e == `string`;
2032
+ }
2033
+ //#endregion
2034
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
2035
+ function e$1(e) {
2036
+ return !!e;
2037
+ }
2038
+ //#endregion
2039
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
2040
+ function e(e) {
2041
+ let t = !1, n;
2042
+ return () => (t ||= (n = e(), !0), n);
2043
+ }
2044
+ var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
2045
+ CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
2046
+ CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
2047
+ CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
2048
+ CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
2049
+ CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
2050
+ CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
2051
+ CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
2052
+ CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
2053
+ CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
2054
+ CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
2055
+ CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
2056
+ return CloseCode2;
2057
+ })(CloseCode || {});
2058
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
2059
+ MessageType2["ConnectionInit"] = "connection_init";
2060
+ MessageType2["ConnectionAck"] = "connection_ack";
2061
+ MessageType2["Ping"] = "ping";
2062
+ MessageType2["Pong"] = "pong";
2063
+ MessageType2["Subscribe"] = "subscribe";
2064
+ MessageType2["Next"] = "next";
2065
+ MessageType2["Error"] = "error";
2066
+ MessageType2["Complete"] = "complete";
2067
+ return MessageType2;
2068
+ })(MessageType || {});
2069
+ Error;
2070
+ //#endregion
2071
+ //#region ../reactor-browser/dist/document-operations-CBExT76y.js
2072
+ const modalEventFunctions = makePHEventFunctions("modal");
2073
+ modalEventFunctions.useValue;
2074
+ /** Sets the current modal */
2075
+ const setPHModal = modalEventFunctions.setValue;
2076
+ modalEventFunctions.addEventHandler;
2077
+ /** Shows a modal */
2078
+ function showPHModal(modal) {
2079
+ setPHModal(modal);
2080
+ }
2081
+ /** Shows the delete node modal */
2082
+ function showDeleteNodeModal(nodeOrId) {
2083
+ setPHModal({
2084
+ type: "deleteItem",
2085
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2379
2086
  });
2380
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2381
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2382
- return LZString;
2087
+ }
2088
+ function isDocumentTypeSupported(documentType, supportedDocuments) {
2089
+ if (!supportedDocuments?.length) return true;
2090
+ return supportedDocuments.some((pattern) => {
2091
+ if (pattern.endsWith("/*")) {
2092
+ const prefix = pattern.slice(0, -2);
2093
+ return documentType.startsWith(prefix + "/");
2094
+ }
2095
+ if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
2096
+ const prefix = pattern.slice(0, -1);
2097
+ return documentType.startsWith(prefix);
2098
+ }
2099
+ return pattern === documentType;
2383
2100
  });
2384
- })))(), 1);
2385
- var DocumentModelNotFoundError = class extends Error {
2386
- documentType;
2387
- name = "DocumentModelNotFoundError";
2388
- constructor(documentType) {
2389
- super(`Document model module for type ${documentType} not found`);
2390
- this.documentType = documentType;
2391
- }
2392
- static isError(error) {
2393
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2394
- }
2395
- };
2396
- var DocumentTypeMismatchError = class extends Error {
2397
- constructor(documentId, expectedType, actualType) {
2398
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2399
- }
2400
- };
2401
- var NoSelectedDocumentError = class extends Error {
2402
- constructor() {
2403
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2404
- }
2405
- };
2101
+ }
2406
2102
  function getUserPermissions() {
2407
2103
  const user = window.ph?.renown?.user;
2408
2104
  const allowList = window.ph?.allowList;
@@ -2415,8 +2111,41 @@ function getUserPermissions() {
2415
2111
  isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2416
2112
  };
2417
2113
  }
2418
- const BASE_STATE_KEYS = new Set(["auth"]);
2419
2114
  const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2115
+ /** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
2116
+ async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
2117
+ const drive = await reactorClient.get(driveId);
2118
+ const nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);
2119
+ if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {
2120
+ isDuplicate: true,
2121
+ duplicateType: "id",
2122
+ nodeId: nodeById.id
2123
+ };
2124
+ const nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));
2125
+ if (nodeByNameAndType) return {
2126
+ isDuplicate: true,
2127
+ duplicateType: "name",
2128
+ nodeId: nodeByNameAndType.id
2129
+ };
2130
+ return { isDuplicate: false };
2131
+ }
2132
+ function getDocumentTypeIcon(document) {
2133
+ switch (document.header.documentType) {
2134
+ case "powerhouse/document-model": return "document-model";
2135
+ case "powerhouse/app": return "app";
2136
+ case "powerhouse/document-editor": return "editor";
2137
+ case "powerhouse/subgraph": return "subgraph";
2138
+ case "powerhouse/package": return "package";
2139
+ case "powerhouse/processor": {
2140
+ const processorType = document.state.global?.type;
2141
+ if (processorType === "analytics") return "analytics-processor";
2142
+ if (processorType === "relational") return "relational-processor";
2143
+ if (processorType === "codegen") return "codegen-processor";
2144
+ return;
2145
+ }
2146
+ default: return;
2147
+ }
2148
+ }
2420
2149
  async function downloadFile(document, fileName) {
2421
2150
  try {
2422
2151
  const data = await createZip(document);
@@ -2437,7 +2166,7 @@ async function getDocumentExtension(document) {
2437
2166
  let rawExtension;
2438
2167
  if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2439
2168
  else {
2440
- const reactorClient = window.ph?.reactorClient;
2169
+ const reactorClient = window.ph?.reactorClientModule?.client;
2441
2170
  if (reactorClient) {
2442
2171
  const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2443
2172
  rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
@@ -2451,7 +2180,7 @@ async function getDocumentExtension(document) {
2451
2180
  * composite cursors, so all scopes are fetched in a single paginated stream.
2452
2181
  */
2453
2182
  async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2454
- const scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));
2183
+ const scopes = Object.keys(document.state);
2455
2184
  const operations = {};
2456
2185
  for (const scope of scopes) operations[scope] = [];
2457
2186
  let cursor = "";
@@ -2479,6 +2208,67 @@ function extractInitialState(documentScopeOps) {
2479
2208
  function filterDomainOperations(operations) {
2480
2209
  return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2481
2210
  }
2211
+ function countOperations(operations) {
2212
+ let total = 0;
2213
+ for (const ops of Object.values(operations)) total += ops?.length ?? 0;
2214
+ return total;
2215
+ }
2216
+ /**
2217
+ * Split an imported document's domain operations at its mid-history upgrade
2218
+ * boundaries, so the caller can re-dispatch each upgrade between segments.
2219
+ *
2220
+ * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
2221
+ * path and must not be repeated. A later upgrade must be: it is where the
2222
+ * reducer version changes, and dropping it replays everything after it through
2223
+ * the module the document was created with.
2224
+ */
2225
+ function splitAtUpgradeBoundaries(operations) {
2226
+ const upgrades = (operations.document ?? []).filter((op) => op.action.type === "UPGRADE_DOCUMENT").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);
2227
+ const domain = filterDomainOperations(operations);
2228
+ if (upgrades.length === 0) return [{ operations: domain }];
2229
+ const segments = [];
2230
+ const consumed = /* @__PURE__ */ new Map();
2231
+ const take = (until) => {
2232
+ const slice = {};
2233
+ for (const [scope, ops] of Object.entries(domain)) {
2234
+ if (!ops) continue;
2235
+ const from = consumed.get(scope) ?? 0;
2236
+ const stop = Math.max(from, until(scope, ops));
2237
+ const chunk = ops.slice(from, stop);
2238
+ if (chunk.length > 0) slice[scope] = chunk;
2239
+ consumed.set(scope, stop);
2240
+ }
2241
+ return slice;
2242
+ };
2243
+ for (const upgrade of upgrades) {
2244
+ const input = upgrade.action.input;
2245
+ const slice = take((scope, ops) => boundary(upgrade, scope, ops));
2246
+ segments.push({
2247
+ operations: slice,
2248
+ upgradeTo: input.toVersion
2249
+ });
2250
+ }
2251
+ const tail = take((_scope, ops) => ops.length);
2252
+ if (countOperations(tail) > 0) segments.push({ operations: tail });
2253
+ return segments;
2254
+ }
2255
+ /**
2256
+ * How many of a scope's operations precede an upgrade. Must stay identical to
2257
+ * the boundary computation in `replayDocumentVersioned` — snapshots compare
2258
+ * against operation indices, not array positions, and the timestamp fallback
2259
+ * excludes the upgrade's own instant.
2260
+ */
2261
+ function boundary(upgrade, scope, ops) {
2262
+ const snapshot = upgrade.action.input.revision;
2263
+ if (snapshot !== void 0) {
2264
+ const revision = snapshot[scope] ?? 0;
2265
+ let count = 0;
2266
+ for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
2267
+ return count;
2268
+ }
2269
+ for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
2270
+ return ops.length;
2271
+ }
2482
2272
  async function exportFile(document, suggestedName) {
2483
2273
  const reactorClient = window.ph?.reactorClient;
2484
2274
  if (!reactorClient) throw new Error("ReactorClient not initialized");
@@ -2508,7 +2298,7 @@ async function exportFile(document, suggestedName) {
2508
2298
  */
2509
2299
  async function loadFile(path) {
2510
2300
  const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2511
- const reactorClient = window.ph?.reactorClient;
2301
+ const reactorClient = window.ph?.reactorClientModule?.client;
2512
2302
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2513
2303
  const documentType = baseDocument.header.documentType;
2514
2304
  const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
@@ -2526,13 +2316,20 @@ async function loadFile(path) {
2526
2316
  upgradeManifest
2527
2317
  });
2528
2318
  }
2529
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2319
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
2530
2320
  const { isAllowedToCreateDocuments } = getUserPermissions();
2531
2321
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2532
- const reactorClient = window.ph?.reactorClient;
2322
+ const reactorClient = window.ph?.reactorClientModule?.client;
2533
2323
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2534
- const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2324
+ let documentModelModule;
2325
+ if (documentModelVersion !== void 0) {
2326
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2327
+ const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
2328
+ if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
2329
+ documentModelModule = module;
2330
+ } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2535
2331
  const newDocument = document ?? documentModelModule.utils.createDocument();
2332
+ if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
2536
2333
  newDocument.header.name = name;
2537
2334
  if (preferredEditor) newDocument.header.meta = {
2538
2335
  ...newDocument.header.meta,
@@ -2553,43 +2350,210 @@ async function addDocument(driveId, name, documentType, parentFolder, document,
2553
2350
  kind: "file"
2554
2351
  };
2555
2352
  }
2556
- async function addFile(file, driveId, name, parentFolder) {
2557
- logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2353
+ /**
2354
+ * How many ids an import will try before giving up. The check before the create
2355
+ * catches an id that is already taken; this bound covers the window between the
2356
+ * two, where a create can still lose to a claim made in the meantime.
2357
+ */
2358
+ const IMPORT_ID_ATTEMPTS = 3;
2359
+ /** True when this error, or anything it wraps, is a taken document id. */
2360
+ function isDocumentAlreadyExists(error) {
2361
+ let current = error;
2362
+ while (current instanceof Error) {
2363
+ if (current.name === "DocumentAlreadyExistsError") return true;
2364
+ current = current.cause;
2365
+ }
2366
+ return false;
2367
+ }
2368
+ /**
2369
+ * Creates the imported document under an id that is free, retrying on a
2370
+ * collision.
2371
+ *
2372
+ * The check cannot stand on its own: it answers for the moment it ran, and the
2373
+ * create that follows can still land on an id claimed in between. The store
2374
+ * rejects that create as DocumentAlreadyExistsError, which is not retryable
2375
+ * under the same id and is resolved by minting another one. A create that
2376
+ * fails leaves the drive untouched, so a retry has nothing to clean up.
2377
+ */
2378
+ async function createImportedDocument(reactor, document, driveId, name, parentFolder) {
2379
+ let documentId = await reactor.isDocumentIdTaken(document.header.id) ? generateId() : document.header.id;
2380
+ for (let attempt = 1;; attempt++) {
2381
+ const header = createPresignedHeader(documentId, document.header.documentType);
2382
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2383
+ header.meta = document.header.meta;
2384
+ header.name = name || document.header.name;
2385
+ const initialDocument = {
2386
+ ...document,
2387
+ header,
2388
+ state: document.initialState,
2389
+ operations: Object.keys(document.operations).reduce((acc, key) => {
2390
+ acc[key] = [];
2391
+ return acc;
2392
+ }, {})
2393
+ };
2394
+ try {
2395
+ const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2396
+ if (!fileNode) throw new Error("There was an error adding file");
2397
+ return {
2398
+ documentId,
2399
+ fileNode
2400
+ };
2401
+ } catch (error) {
2402
+ if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;
2403
+ logger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);
2404
+ documentId = generateId();
2405
+ }
2406
+ }
2407
+ }
2408
+ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2409
+ logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2410
+ const reactor = window.ph?.reactorClientModule?.client;
2411
+ if (!reactor) {
2412
+ onProgress?.({
2413
+ stage: "failed",
2414
+ progress: 100,
2415
+ error: "ReactorClient not initialized"
2416
+ });
2417
+ throw new Error("ReactorClient not initialized");
2418
+ }
2558
2419
  const { isAllowedToCreateDocuments } = getUserPermissions();
2559
2420
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2560
- const document = await loadFile(file);
2561
- let duplicateId = false;
2562
- const reactorClient = window.ph?.reactorClient;
2563
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2564
2421
  try {
2565
- await reactorClient.get(document.header.id);
2566
- duplicateId = true;
2567
- } catch {}
2568
- const documentId = duplicateId ? generateId() : document.header.id;
2569
- const header = createPresignedHeader(documentId, document.header.documentType);
2570
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2571
- header.meta = document.header.meta;
2572
- header.name = name || document.header.name;
2573
- const initialDocument = {
2574
- ...document,
2575
- header,
2576
- state: document.initialState,
2577
- operations: Object.keys(document.operations).reduce((acc, key) => {
2578
- acc[key] = [];
2579
- return acc;
2580
- }, {})
2581
- };
2582
- await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2583
- await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2422
+ onProgress?.({
2423
+ stage: "loading",
2424
+ progress: 0
2425
+ });
2426
+ let document;
2427
+ try {
2428
+ document = await loadFile(file);
2429
+ } catch (loadError) {
2430
+ if (UnsupportedDocumentModelVersionError.isError(loadError)) {
2431
+ showPHModal({
2432
+ type: "documentVersionUnsupported",
2433
+ documentType: loadError.documentType,
2434
+ requiredVersion: loadError.requiredVersion,
2435
+ availableVersions: loadError.availableVersions
2436
+ });
2437
+ onProgress?.({
2438
+ stage: "failed",
2439
+ progress: 100,
2440
+ error: loadError.message
2441
+ });
2442
+ return;
2443
+ }
2444
+ const discoveryService = window.ph?.packageDiscoveryService;
2445
+ if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
2446
+ retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
2447
+ logger.error("Import retry after discovery failed: @error", retryError);
2448
+ onProgress?.({
2449
+ stage: "failed",
2450
+ progress: 100,
2451
+ error: retryError instanceof Error ? retryError.message : String(retryError)
2452
+ });
2453
+ });
2454
+ return;
2455
+ }
2456
+ throw loadError;
2457
+ }
2458
+ const duplicateCheck = await isDocumentInLocation(reactor, document, driveId, parentFolder);
2459
+ if (duplicateCheck.isDuplicate && !resolveConflict) {
2460
+ onProgress?.({
2461
+ stage: "conflict",
2462
+ progress: 0,
2463
+ duplicateType: duplicateCheck.duplicateType
2464
+ });
2465
+ return;
2466
+ }
2467
+ const documentType = getDocumentTypeIcon(document);
2468
+ if (documentType) onProgress?.({
2469
+ stage: "loading",
2470
+ progress: 10,
2471
+ documentType
2472
+ });
2473
+ else onProgress?.({
2474
+ stage: "loading",
2475
+ progress: 10
2476
+ });
2477
+ if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
2478
+ onProgress?.({
2479
+ stage: "unsupported-document-type",
2480
+ progress: 100,
2481
+ error: `Document type ${document.header.documentType} is not supported`
2482
+ });
2483
+ throw new UnsupportedDocumentTypeError(document.header.documentType);
2484
+ }
2485
+ await reactor.getDocumentModelModule(document.header.documentType);
2486
+ onProgress?.({
2487
+ stage: "initializing",
2488
+ progress: 10
2489
+ });
2490
+ const created = await createImportedDocument(reactor, document, driveId, name, parentFolder);
2491
+ const documentId = created.documentId;
2492
+ const fileNode = created.fileNode;
2493
+ onProgress?.({
2494
+ stage: "initializing",
2495
+ progress: 20
2496
+ });
2497
+ await reactor.get(documentId);
2498
+ console.log("Document created, starting upload of operations");
2499
+ const segments = splitAtUpgradeBoundaries(document.operations);
2500
+ const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
2501
+ let uploadedBefore = 0;
2502
+ for (const segment of segments) {
2503
+ await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
2504
+ if (uploadProgress.uploadedOperations === void 0) return;
2505
+ const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
2506
+ const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
2507
+ onProgress?.({
2508
+ stage: "uploading",
2509
+ progress: 20 + Math.round(uploadPercent * 80),
2510
+ totalOperations,
2511
+ uploadedOperations: uploaded
2512
+ });
2513
+ } });
2514
+ uploadedBefore += countOperations(segment.operations);
2515
+ if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
2516
+ }
2517
+ onProgress?.({
2518
+ stage: "complete",
2519
+ progress: 100,
2520
+ fileNode
2521
+ });
2522
+ return fileNode;
2523
+ } catch (error) {
2524
+ if (!UnsupportedDocumentTypeError.isError(error)) {
2525
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
2526
+ onProgress?.({
2527
+ stage: "failed",
2528
+ progress: 100,
2529
+ error: errorMessage
2530
+ });
2531
+ }
2532
+ throw error;
2533
+ }
2534
+ }
2535
+ async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2536
+ if (!discoveryService) return;
2537
+ try {
2538
+ await discoveryService.load(documentType);
2539
+ } catch {
2540
+ onProgress?.({
2541
+ stage: "unsupported-document-type",
2542
+ progress: 100,
2543
+ error: `Document type ${documentType} is not supported`
2544
+ });
2545
+ return;
2546
+ }
2547
+ await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
2584
2548
  }
2585
- async function addFolder(driveId, name, parentFolder) {
2549
+ async function addFolder$1(driveId, name, parentFolder) {
2586
2550
  const { isAllowedToCreateDocuments } = getUserPermissions();
2587
2551
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2588
2552
  const reactorClient = window.ph?.reactorClient;
2589
2553
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2590
2554
  await reactorClient.get(driveId);
2591
2555
  const folderId = generateId();
2592
- const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2556
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
2593
2557
  id: folderId,
2594
2558
  name,
2595
2559
  parentFolder
@@ -2667,10 +2631,12 @@ async function _duplicateDocument(reactor, document, newId = generateId()) {
2667
2631
  upgradeManifest
2668
2632
  };
2669
2633
  const header = createPresignedHeader(newId, documentType);
2670
- return replayDocumentVersioned(document.initialState, document.operations, config, header);
2634
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2635
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2636
+ return duplicated;
2671
2637
  }
2672
2638
  async function copyNode$1(driveId, src, target) {
2673
- const reactor = window.ph?.reactorClient;
2639
+ const reactor = window.ph?.reactorClientModule?.client;
2674
2640
  if (!reactor) return;
2675
2641
  const { isAllowedToCreateDocuments } = getUserPermissions();
2676
2642
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
@@ -2707,31 +2673,74 @@ async function copyNode$1(driveId, src, target) {
2707
2673
  }
2708
2674
  return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2709
2675
  }
2710
- const modalEventFunctions = makePHEventFunctions("modal");
2711
- modalEventFunctions.useValue;
2712
- /** Sets the current modal */
2713
- const setPHModal = modalEventFunctions.setValue;
2714
- modalEventFunctions.addEventHandler;
2715
- /** Shows a modal */
2716
- function showPHModal(modal) {
2717
- setPHModal(modal);
2718
- }
2719
- /** Shows the create document modal */
2720
- function showCreateDocumentModal(documentType) {
2721
- setPHModal({
2722
- type: "createDocument",
2723
- documentType
2724
- });
2725
- }
2726
- /** Shows the delete node modal */
2727
- function showDeleteNodeModal(nodeOrId) {
2728
- setPHModal({
2729
- type: "deleteItem",
2730
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2731
- });
2732
- }
2733
- /** Document types that represent a "drive": a container of nodes. */
2734
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
2676
+ /**
2677
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
2678
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
2679
+ */
2680
+ const ReactorOperationFieldsFragmentDoc = import_main.gql`
2681
+ fragment ReactorOperationFields on ReactorOperation {
2682
+ index
2683
+ timestampUtcMs
2684
+ hash
2685
+ skip
2686
+ error
2687
+ deniedReason
2688
+ id
2689
+ action {
2690
+ id
2691
+ type
2692
+ timestampUtcMs
2693
+ input
2694
+ scope
2695
+ context {
2696
+ signer {
2697
+ user {
2698
+ address
2699
+ networkId
2700
+ chainId
2701
+ }
2702
+ app {
2703
+ name
2704
+ key
2705
+ }
2706
+ signatures
2707
+ }
2708
+ }
2709
+ }
2710
+ }
2711
+ `;
2712
+ import_main.gql`
2713
+ mutation MutateDocumentWithOperations(
2714
+ $documentIdentifier: String!
2715
+ $actions: [ActionInput!]!
2716
+ $sinceRevision: Int
2717
+ $scopes: [String!]
2718
+ $branch: String
2719
+ ) {
2720
+ mutateDocument: execute(
2721
+ documentIdentifier: $documentIdentifier
2722
+ actions: $actions
2723
+ branch: $branch
2724
+ ) {
2725
+ ...PHDocumentFields
2726
+ operations(
2727
+ filter: {
2728
+ sinceRevision: $sinceRevision
2729
+ scopes: $scopes
2730
+ branch: $branch
2731
+ }
2732
+ ) {
2733
+ items {
2734
+ ...ReactorOperationFields
2735
+ }
2736
+ }
2737
+ }
2738
+ }
2739
+ ${PhDocumentFieldsFragmentDoc}
2740
+ ${ReactorOperationFieldsFragmentDoc}
2741
+ `;
2742
+ DocumentChangeType.Created, DOCUMENT_CHANGE_TYPE.Created, DocumentChangeType.Deleted, DOCUMENT_CHANGE_TYPE.Deleted, DocumentChangeType.Updated, DOCUMENT_CHANGE_TYPE.Updated, DocumentChangeType.ParentAdded, DOCUMENT_CHANGE_TYPE.ParentAdded, DocumentChangeType.ParentRemoved, DOCUMENT_CHANGE_TYPE.ParentRemoved, DocumentChangeType.ChildAdded, DOCUMENT_CHANGE_TYPE.ChildAdded, DocumentChangeType.ChildRemoved, DOCUMENT_CHANGE_TYPE.ChildRemoved;
2743
+ PropagationMode.Cascade, PropagationMode.Orphan;
2735
2744
  const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2736
2745
  /** Sets whether external controls are enabled for a given editor. */
2737
2746
  const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
@@ -2797,6 +2806,8 @@ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabl
2797
2806
  const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2798
2807
  const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2799
2808
  const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2809
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
2810
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
2800
2811
  const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2801
2812
  const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2802
2813
  const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
@@ -2894,6 +2905,8 @@ const nonUserConfigSetters = {
2894
2905
  renownUrl: setRenownUrl,
2895
2906
  renownNetworkId: setRenownNetworkId,
2896
2907
  renownChainId: setRenownChainId,
2908
+ switchboardUrl: setSwitchboardUrl,
2909
+ renownAdapters: setRenownAdapters,
2897
2910
  sentryRelease: setSentryRelease,
2898
2911
  sentryDsn: setSentryDsn,
2899
2912
  sentryEnv: setSentryEnv,
@@ -2942,6 +2955,8 @@ const nonUserConfigHooks = {
2942
2955
  renownUrl: useRenownUrl,
2943
2956
  renownNetworkId: useRenownNetworkId,
2944
2957
  renownChainId: useRenownChainId,
2958
+ switchboardUrl: useSwitchboardUrl,
2959
+ renownAdapters: useRenownAdapters,
2945
2960
  sentryRelease: useSentryRelease,
2946
2961
  sentryDsn: useSentryDsn,
2947
2962
  sentryEnv: useSentryEnv,
@@ -2971,366 +2986,995 @@ const featuresEventFunctions = makePHEventFunctions("features");
2971
2986
  featuresEventFunctions.useValue;
2972
2987
  featuresEventFunctions.setValue;
2973
2988
  featuresEventFunctions.addEventHandler;
2974
- function resolveUrlPathname(path) {
2975
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2989
+ function useDropTarget() {
2990
+ const [isDropTarget, setIsDropTarget] = useState(false);
2991
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2992
+ const targetSetter = n$1(() => setIsDropTarget(true), {
2993
+ triggerAt: "start",
2994
+ minQuietPeriodMs: 100
2995
+ });
2996
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
2997
+ triggerAt: "start",
2998
+ minQuietPeriodMs: 100
2999
+ });
3000
+ function setTarget() {
3001
+ if (!isDragAndDropEnabled) return;
3002
+ targetUnsetter.cancel();
3003
+ targetSetter.call();
3004
+ }
3005
+ function unsetTarget() {
3006
+ if (!isDragAndDropEnabled) return;
3007
+ targetSetter.cancel();
3008
+ targetUnsetter.call();
3009
+ }
3010
+ return {
3011
+ isDropTarget,
3012
+ setTarget,
3013
+ unsetTarget
3014
+ };
2976
3015
  }
2977
- /** Returns the current path without the base path */
2978
- function getPathWithoutBase(path) {
2979
- const basePath = window.ph?.basePath ?? "/";
2980
- return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
3016
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3017
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
3018
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
3019
+ draggingNodeEventFunctions.addEventHandler;
3020
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3021
+ reducer: (_, newNode) => newNode,
3022
+ triggerAt: "start",
3023
+ minQuietPeriodMs: 100
3024
+ });
3025
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3026
+ triggerAt: "start",
3027
+ minQuietPeriodMs: 100
3028
+ });
3029
+ function setDragging(node) {
3030
+ draggingNodeUnsetter.cancel();
3031
+ draggingNodeSetter.call(node);
2981
3032
  }
2982
- /** Makes a URL component for a node. */
2983
- function makeNodeSlug(node) {
2984
- if (!node) return "";
2985
- const nodeName = node.name;
2986
- if (!nodeName) return slug(node.id);
2987
- return slug(`${nodeName}-${node.id}`);
3033
+ function unsetDragging() {
3034
+ draggingNodeSetter.cancel();
3035
+ draggingNodeUnsetter.call();
2988
3036
  }
2989
- /** Extracts the node slug from a path.
2990
- *
2991
- * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
2992
- */
2993
- function extractNodeSlugFromPath(path) {
2994
- const currentPath = getPathWithoutBase(path);
2995
- return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
3037
+ 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));
3038
+ function useDragNode(args) {
3039
+ const { srcId, parentId } = args;
3040
+ const driveId = useSelectedDriveId();
3041
+ const draggingNodeId = useDraggingNode()?.srcId;
3042
+ const params = {
3043
+ driveId,
3044
+ srcId,
3045
+ parentId
3046
+ };
3047
+ const draggable = isNodeDrag(params);
3048
+ const isDragging = t$4({
3049
+ srcId,
3050
+ draggingNodeId
3051
+ }, [
3052
+ () => draggable,
3053
+ ({ srcId }) => e$2(srcId),
3054
+ ({ draggingNodeId }) => e$2(draggingNodeId),
3055
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3056
+ ]);
3057
+ const onDragStart = () => {
3058
+ if (!draggable) return;
3059
+ setDragging(params);
3060
+ };
3061
+ const onDragEnd = () => {
3062
+ if (!draggable) return;
3063
+ unsetDragging();
3064
+ };
3065
+ return {
3066
+ isDragging,
3067
+ draggable,
3068
+ onDragStart,
3069
+ onDragEnd
3070
+ };
2996
3071
  }
2997
- /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
2998
- function findUuid(input) {
2999
- if (!input) return void 0;
3000
- 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];
3072
+ 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));
3073
+ function useDropNode(targetId) {
3074
+ const driveId = useSelectedDriveId();
3075
+ const { srcId, parentId } = useDraggingNode() ?? {};
3076
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3077
+ const params = {
3078
+ driveId,
3079
+ parentId,
3080
+ targetId,
3081
+ srcId
3082
+ };
3083
+ function handleNodeDrop(event, cb) {
3084
+ if (!isNodeDrop(params)) return;
3085
+ event.preventDefault();
3086
+ event.stopPropagation();
3087
+ cb?.();
3088
+ }
3089
+ const onDragEnter = (event) => handleNodeDrop(event);
3090
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3091
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3092
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
3093
+ unsetDragging();
3094
+ unsetTarget();
3095
+ moveNodeById(params).catch(console.error);
3096
+ }));
3097
+ return {
3098
+ isDropTarget,
3099
+ onDragEnter,
3100
+ onDragOver,
3101
+ onDragLeave,
3102
+ onDrop
3103
+ };
3001
3104
  }
3002
- function extractNodeIdFromSlug(nodeSlug) {
3003
- return findUuid(nodeSlug);
3105
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3106
+ graphQLReactorClientEventFunctions.useValue;
3107
+ graphQLReactorClientEventFunctions.setValue;
3108
+ graphQLReactorClientEventFunctions.addEventHandler;
3109
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3110
+ packageDiscoveryFunctions.useValue;
3111
+ packageDiscoveryFunctions.setValue;
3112
+ packageDiscoveryFunctions.addEventHandler;
3113
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3114
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3115
+ /** Returns the reactor client module (in-process or worker-backed) */
3116
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3117
+ reactorClientModuleEventFunctions.setValue;
3118
+ reactorClientModuleEventFunctions.addEventHandler;
3119
+ reactorClientEventFunctions.useValue;
3120
+ reactorClientEventFunctions.setValue;
3121
+ reactorClientEventFunctions.addEventHandler;
3122
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3123
+ const useSyncList = () => {
3124
+ return useSync()?.list() ?? [];
3125
+ };
3126
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
3127
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3128
+ revisionHistoryEventFunctions.useValue;
3129
+ /** Sets revision history visibility */
3130
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3131
+ revisionHistoryEventFunctions.addEventHandler;
3132
+ /** Shows the revision history */
3133
+ function showRevisionHistory() {
3134
+ setRevisionHistoryVisible(true);
3004
3135
  }
3005
- /** Extracts the drive slug from a path.
3006
- * Used for extracting drive ids from drive slugs in the URL.
3007
- * Expects the path to be in the format `/d/<drive-slug>`.
3008
- */
3009
- function extractDriveSlugFromPath(path) {
3010
- const currentPath = getPathWithoutBase(path);
3011
- return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
3136
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3137
+ selectedTimelineItemEventFunctions.useValue;
3138
+ selectedTimelineItemEventFunctions.setValue;
3139
+ selectedTimelineItemEventFunctions.addEventHandler;
3140
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3141
+ selectedTimelineRevisionEventFunctions.useValue;
3142
+ selectedTimelineRevisionEventFunctions.setValue;
3143
+ selectedTimelineRevisionEventFunctions.addEventHandler;
3144
+ const toastEventFunctions = makePHEventFunctions("toast");
3145
+ /** Returns the toast function */
3146
+ const usePHToast = toastEventFunctions.useValue;
3147
+ toastEventFunctions.setValue;
3148
+ toastEventFunctions.addEventHandler;
3149
+ //#endregion
3150
+ //#region ../reactor-browser/dist/switchboard-D4-_jwk-.js
3151
+ /** Returns a document of a specific type, throws an error if the found document has a different type */
3152
+ function useDocumentOfType(documentId, documentType) {
3153
+ const [document, dispatch] = useDocumentById(documentId);
3154
+ const documentModelModule = useDocumentModelModuleById(documentType);
3155
+ if (!documentId || !documentType) return [];
3156
+ if (!document) throw new Error(`Document not found: ${documentId}`);
3157
+ if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3158
+ if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3159
+ return [document, dispatch];
3012
3160
  }
3013
- /**
3014
- * Creates a URL string with the given pathname while preserving existing query parameters.
3015
- */
3016
- function createUrlWithPreservedParams(pathname) {
3017
- const search = window.location.search;
3018
- return search ? `${pathname}${search}` : pathname;
3161
+ /** Returns the selected document id */
3162
+ function useSelectedDocumentId() {
3163
+ const selectedNode = useSelectedNode();
3164
+ return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3019
3165
  }
3020
- const drivesEventFunctions = makePHEventFunctions("drives");
3021
- /** Returns all of the drives in the reactor */
3022
- const useDrives = drivesEventFunctions.useValue;
3023
- /** Sets the drives in the reactor */
3024
- const setDrives = drivesEventFunctions.setValue;
3025
- drivesEventFunctions.addEventHandler;
3026
- const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
3027
- const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
3028
- const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
3029
- selectedNodeIdEventFunctions.addEventHandler;
3030
- /** Sets the selected node (file or folder). */
3031
- function setSelectedNode(nodeOrNodeSlug) {
3032
- const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
3033
- setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
3034
- const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
3035
- if (!driveSlugFromPath) return;
3036
- if (!nodeSlug) {
3037
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
3038
- if (pathname === window.location.pathname) return;
3039
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3040
- return;
3041
- }
3042
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
3043
- if (pathname === window.location.pathname) return;
3044
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3166
+ /** Returns the selected document. */
3167
+ function useSelectedDocumentSafe() {
3168
+ return useDocumentById(useSelectedDocumentId());
3045
3169
  }
3046
- const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
3047
- /** Returns the selected drive id */
3048
- const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
3049
- /** Sets the selected drive id */
3050
- const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
3051
- selectedDriveIdEventFunctions.addEventHandler;
3052
- /** Returns the selected drive, or undefined if no drive is selected */
3053
- function useSelectedDriveSafe() {
3054
- const selectedDriveId = useSelectedDriveId();
3055
- const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
3056
- const [drive, dispatch] = useDispatch(selectedDrive);
3057
- if (!selectedDrive) return [void 0, void 0];
3058
- return [drive, dispatch];
3170
+ function useSelectedDocumentOfType(documentType) {
3171
+ const documentId = useSelectedDocumentId();
3172
+ if (!documentType) return [];
3173
+ if (!documentId) throw new NoSelectedDocumentError();
3174
+ return useDocumentOfType(documentId, documentType);
3059
3175
  }
3060
- function setSelectedDrive(driveOrDriveSlug) {
3061
- const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
3062
- const drives = window.ph?.drives;
3063
- const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
3064
- if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
3065
- if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
3066
- deferDriveSelection(driveSlug);
3176
+ //#endregion
3177
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
3178
+ const normalizeDescriptors = (error) => {
3179
+ CORE_ERROR_PROPS.forEach((propName) => {
3180
+ normalizeDescriptor(error, propName);
3181
+ });
3182
+ };
3183
+ const CORE_ERROR_PROPS = [
3184
+ "name",
3185
+ "message",
3186
+ "stack",
3187
+ "cause",
3188
+ "errors"
3189
+ ];
3190
+ const normalizeDescriptor = (error, propName) => {
3191
+ const descriptor = getDescriptor(error, propName);
3192
+ if (descriptor === void 0) return;
3193
+ if (isReadonlyGetter(descriptor)) {
3194
+ setErrorProperty(error, propName, error[propName]);
3067
3195
  return;
3068
3196
  }
3069
- cancelPendingDriveSelection();
3070
- setSelectedDriveId(driveId);
3071
- if (!driveId) {
3072
- const pathname = resolveUrlPathname("/");
3073
- if (pathname === window.location.pathname) return;
3074
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3075
- return;
3197
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
3198
+ };
3199
+ const getDescriptor = (value, propName) => {
3200
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
3201
+ if (descriptor !== void 0) return descriptor;
3202
+ const prototype = Object.getPrototypeOf(value);
3203
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
3204
+ };
3205
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
3206
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
3207
+ const setErrorProperty = (error, propName, value) => {
3208
+ setErrorDescriptor(error, propName, { value });
3209
+ };
3210
+ const setErrorDescriptor = (error, propName, descriptor) => {
3211
+ Object.defineProperty(error, propName, {
3212
+ ...descriptor,
3213
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
3214
+ enumerable: false,
3215
+ configurable: true
3216
+ });
3217
+ };
3218
+ //#endregion
3219
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
3220
+ const normalizeAggregate = (error, recurse) => {
3221
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
3222
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
3223
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
3224
+ };
3225
+ const isDefined = (error) => error !== void 0;
3226
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
3227
+ const deleteAggregateErrors = (error) => {
3228
+ delete error.errors;
3229
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
3230
+ };
3231
+ //#endregion
3232
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
3233
+ const normalizeCause = (error, recurse) => {
3234
+ if (!("cause" in error)) return;
3235
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
3236
+ if (cause === void 0) delete error.cause;
3237
+ else setErrorProperty(error, "cause", cause);
3238
+ };
3239
+ //#endregion
3240
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
3241
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
3242
+ const isInstanceOfError = (value) => {
3243
+ try {
3244
+ return value instanceof Error;
3245
+ } catch {
3246
+ return false;
3076
3247
  }
3077
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
3078
- if (pathname === window.location.pathname) return;
3079
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3248
+ };
3249
+ const hasErrorTag = (value) => {
3250
+ try {
3251
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
3252
+ } catch {
3253
+ return false;
3254
+ }
3255
+ };
3256
+ const ERROR_TAGS = new Set([
3257
+ "[object Error]",
3258
+ "[object DOMException]",
3259
+ "[object DOMError]",
3260
+ "[object Exception]"
3261
+ ]);
3262
+ //#endregion
3263
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
3264
+ function isPlainObject(value) {
3265
+ if (typeof value !== "object" || value === null) return false;
3266
+ const prototype = Object.getPrototypeOf(value);
3267
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3080
3268
  }
3081
- const DEFERRED_DRIVE_TICK_MS = 2e3;
3082
- const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
3083
- function isInitialSyncInFlight() {
3084
- const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
3085
- if (!remotes?.length) return false;
3086
- return remotes.some((remote) => {
3087
- try {
3088
- const snapshot = remote.channel.getConnectionState();
3089
- return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
3090
- } catch {
3091
- return false;
3092
- }
3269
+ //#endregion
3270
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
3271
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
3272
+ const isNonConfigurableProp = (error, propName) => {
3273
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
3274
+ return descriptor !== void 0 && !descriptor.configurable;
3275
+ };
3276
+ const isThrowingProp = (error, propName) => {
3277
+ try {
3278
+ error[propName];
3279
+ return false;
3280
+ } catch {
3281
+ return true;
3282
+ }
3283
+ };
3284
+ //#endregion
3285
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
3286
+ const setStack = (error) => {
3287
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
3288
+ };
3289
+ const getStack = (message = "", name = "Error") => {
3290
+ const { stack } = new (getErrorClass(name))(message);
3291
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
3292
+ };
3293
+ const getErrorClass = (name) => {
3294
+ const descriptor = {
3295
+ value: name,
3296
+ enumerable: false,
3297
+ writable: true,
3298
+ configurable: true
3299
+ };
3300
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
3301
+ Object.defineProperty(StackError.prototype, "name", descriptor);
3302
+ return StackError;
3303
+ };
3304
+ //#endregion
3305
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
3306
+ const copyObject = (object) => {
3307
+ const objectCopy = {};
3308
+ for (const propName of getPropsToCopy(object)) try {
3309
+ const value = object[propName];
3310
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
3311
+ Object.defineProperty(objectCopy, propName, {
3312
+ value,
3313
+ enumerable,
3314
+ configurable,
3315
+ writable
3316
+ });
3317
+ } catch {}
3318
+ return objectCopy;
3319
+ };
3320
+ const getPropsToCopy = (object) => {
3321
+ const propNames = getOwnKeys(object);
3322
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
3323
+ return propNames;
3324
+ };
3325
+ const getOwnKeys = (object) => {
3326
+ try {
3327
+ return Reflect.ownKeys(object);
3328
+ } catch {
3329
+ return [];
3330
+ }
3331
+ };
3332
+ const isInheritedProp = (object, propName) => {
3333
+ try {
3334
+ return propName in object && !Object.hasOwn(object, propName);
3335
+ } catch {
3336
+ return false;
3337
+ }
3338
+ };
3339
+ //#endregion
3340
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
3341
+ const objectifyError = (object) => {
3342
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
3343
+ const messageA = getMessage(message, objectA);
3344
+ const error = newError(name, messageA);
3345
+ if (message === messageA) assignObjectProps(error, objectA);
3346
+ Object.entries({
3347
+ name,
3348
+ stack,
3349
+ cause,
3350
+ errors
3351
+ }).forEach(([propName, propValue]) => {
3352
+ setNewErrorProperty(error, propName, propValue);
3093
3353
  });
3094
- }
3095
- let pendingHandler;
3096
- let pendingTimeout;
3097
- function cancelPendingDriveSelection() {
3098
- if (pendingHandler) {
3099
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
3100
- pendingHandler = void 0;
3354
+ if (stack === void 0) setStack(error);
3355
+ return error;
3356
+ };
3357
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
3358
+ const safeJsonStringify = (object) => {
3359
+ try {
3360
+ return JSON.stringify(object);
3361
+ } catch {
3362
+ return safeStringify(object);
3363
+ }
3364
+ };
3365
+ const safeStringify = (object) => {
3366
+ try {
3367
+ return String(object);
3368
+ } catch {
3369
+ return "Invalid error";
3370
+ }
3371
+ };
3372
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
3373
+ const MESSAGE_MAX_SIZE = 1e3;
3374
+ const newError = (name, message) => {
3375
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
3376
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
3377
+ return new Error(message);
3378
+ };
3379
+ const NATIVE_ERRORS = {
3380
+ Error,
3381
+ ReferenceError,
3382
+ TypeError,
3383
+ SyntaxError,
3384
+ RangeError,
3385
+ URIError,
3386
+ EvalError
3387
+ };
3388
+ const assignObjectProps = (error, object) => {
3389
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3390
+ };
3391
+ const setNewErrorProperty = (error, propName, propValue) => {
3392
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3393
+ };
3394
+ //#endregion
3395
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3396
+ const stringifyError = (value) => {
3397
+ try {
3398
+ const error = new Error(String(value));
3399
+ setStack(error);
3400
+ return error;
3401
+ } catch (error_) {
3402
+ return error_;
3403
+ }
3404
+ };
3405
+ //#endregion
3406
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3407
+ const { toString: objectToString } = Object.prototype;
3408
+ const createError = (value) => {
3409
+ if (isErrorPlainObj(value)) return objectifyError(value);
3410
+ if (!isErrorInstance(value)) return stringifyError(value);
3411
+ if (isInvalidError(value)) return objectifyError(value);
3412
+ return value;
3413
+ };
3414
+ const isErrorPlainObj = (value) => {
3415
+ try {
3416
+ return isPlainObject(value);
3417
+ } catch {
3418
+ return false;
3101
3419
  }
3102
- if (pendingTimeout) {
3103
- clearTimeout(pendingTimeout);
3104
- pendingTimeout = void 0;
3420
+ };
3421
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3422
+ const isProxy = (value) => {
3423
+ try {
3424
+ return objectToString.call(value) === "[object Object]";
3425
+ } catch {
3426
+ return true;
3105
3427
  }
3106
- }
3107
- function deferDriveSelection(driveSlug) {
3108
- cancelPendingDriveSelection();
3109
- const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
3110
- const handler = () => {
3111
- if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
3112
- cancelPendingDriveSelection();
3113
- setSelectedDrive(driveSlug);
3114
- setSelectedNode(nodeSlug);
3115
- };
3116
- pendingHandler = handler;
3117
- window.addEventListener("ph:drivesUpdated", handler);
3118
- const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
3119
- const scheduleTick = () => {
3120
- pendingTimeout = setTimeout(() => {
3121
- if (Date.now() < deadline && isInitialSyncInFlight()) {
3122
- scheduleTick();
3123
- return;
3428
+ };
3429
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3430
+ //#endregion
3431
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3432
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3433
+ const recurseException = (error, parents, shallow) => {
3434
+ if (parents.includes(error)) return;
3435
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3436
+ const errorA = createError(error);
3437
+ normalizeProps(errorA, recurse);
3438
+ return errorA;
3439
+ };
3440
+ const identity = (error) => error;
3441
+ const normalizeProps = (error, recurse) => {
3442
+ normalizeName(error);
3443
+ normalizeMessage(error);
3444
+ normalizeStack(error);
3445
+ normalizeCause(error, recurse);
3446
+ normalizeAggregate(error, recurse);
3447
+ normalizeDescriptors(error);
3448
+ };
3449
+ const normalizeName = (error) => {
3450
+ if (isDefinedString(error.name)) return;
3451
+ const prototypeName = Object.getPrototypeOf(error).name;
3452
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3453
+ };
3454
+ const normalizeMessage = (error) => {
3455
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3456
+ };
3457
+ const normalizeStack = (error) => {
3458
+ if (!isDefinedString(error.stack)) setStack(error);
3459
+ };
3460
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
3461
+ //#endregion
3462
+ //#region ../reactor-browser/dist/index.js
3463
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3464
+ var LZString = (function() {
3465
+ var f = String.fromCharCode;
3466
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3467
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3468
+ var baseReverseDic = {};
3469
+ function getBaseValue(alphabet, character) {
3470
+ if (!baseReverseDic[alphabet]) {
3471
+ baseReverseDic[alphabet] = {};
3472
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3124
3473
  }
3125
- cancelPendingDriveSelection();
3126
- const pathname = resolveUrlPathname("/");
3127
- if (pathname === window.location.pathname) return;
3128
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3129
- }, DEFERRED_DRIVE_TICK_MS);
3130
- };
3131
- scheduleTick();
3132
- }
3133
- function useDropTarget() {
3134
- const [isDropTarget, setIsDropTarget] = useState(false);
3135
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3136
- const targetSetter = n$1(() => setIsDropTarget(true), {
3137
- triggerAt: "start",
3138
- minQuietPeriodMs: 100
3139
- });
3140
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3141
- triggerAt: "start",
3142
- minQuietPeriodMs: 100
3143
- });
3144
- function setTarget() {
3145
- if (!isDragAndDropEnabled) return;
3146
- targetUnsetter.cancel();
3147
- targetSetter.call();
3148
- }
3149
- function unsetTarget() {
3150
- if (!isDragAndDropEnabled) return;
3151
- targetSetter.cancel();
3152
- targetUnsetter.call();
3153
- }
3154
- return {
3155
- isDropTarget,
3156
- setTarget,
3157
- unsetTarget
3158
- };
3159
- }
3160
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3161
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3162
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3163
- draggingNodeEventFunctions.addEventHandler;
3164
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3165
- reducer: (_, newNode) => newNode,
3166
- triggerAt: "start",
3167
- minQuietPeriodMs: 100
3168
- });
3169
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3170
- triggerAt: "start",
3171
- minQuietPeriodMs: 100
3172
- });
3173
- function setDragging(node) {
3174
- draggingNodeUnsetter.cancel();
3175
- draggingNodeSetter.call(node);
3176
- }
3177
- function unsetDragging() {
3178
- draggingNodeSetter.cancel();
3179
- draggingNodeUnsetter.call();
3180
- }
3181
- 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));
3182
- function useDragNode(args) {
3183
- const { srcId, parentId } = args;
3184
- const driveId = useSelectedDriveId();
3185
- const draggingNodeId = useDraggingNode()?.srcId;
3186
- const params = {
3187
- driveId,
3188
- srcId,
3189
- parentId
3190
- };
3191
- const draggable = isNodeDrag(params);
3192
- const isDragging = t$4({
3193
- srcId,
3194
- draggingNodeId
3195
- }, [
3196
- () => draggable,
3197
- ({ srcId }) => e$2(srcId),
3198
- ({ draggingNodeId }) => e$2(draggingNodeId),
3199
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3200
- ]);
3201
- const onDragStart = () => {
3202
- if (!draggable) return;
3203
- setDragging(params);
3204
- };
3205
- const onDragEnd = () => {
3206
- if (!draggable) return;
3207
- unsetDragging();
3208
- };
3209
- return {
3210
- isDragging,
3211
- draggable,
3212
- onDragStart,
3213
- onDragEnd
3214
- };
3474
+ return baseReverseDic[alphabet][character];
3475
+ }
3476
+ var LZString = {
3477
+ compressToBase64: function(input) {
3478
+ if (input == null) return "";
3479
+ var res = LZString._compress(input, 6, function(a) {
3480
+ return keyStrBase64.charAt(a);
3481
+ });
3482
+ switch (res.length % 4) {
3483
+ default:
3484
+ case 0: return res;
3485
+ case 1: return res + "===";
3486
+ case 2: return res + "==";
3487
+ case 3: return res + "=";
3488
+ }
3489
+ },
3490
+ decompressFromBase64: function(input) {
3491
+ if (input == null) return "";
3492
+ if (input == "") return null;
3493
+ return LZString._decompress(input.length, 32, function(index) {
3494
+ return getBaseValue(keyStrBase64, input.charAt(index));
3495
+ });
3496
+ },
3497
+ compressToUTF16: function(input) {
3498
+ if (input == null) return "";
3499
+ return LZString._compress(input, 15, function(a) {
3500
+ return f(a + 32);
3501
+ }) + " ";
3502
+ },
3503
+ decompressFromUTF16: function(compressed) {
3504
+ if (compressed == null) return "";
3505
+ if (compressed == "") return null;
3506
+ return LZString._decompress(compressed.length, 16384, function(index) {
3507
+ return compressed.charCodeAt(index) - 32;
3508
+ });
3509
+ },
3510
+ compressToUint8Array: function(uncompressed) {
3511
+ var compressed = LZString.compress(uncompressed);
3512
+ var buf = new Uint8Array(compressed.length * 2);
3513
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3514
+ var current_value = compressed.charCodeAt(i);
3515
+ buf[i * 2] = current_value >>> 8;
3516
+ buf[i * 2 + 1] = current_value % 256;
3517
+ }
3518
+ return buf;
3519
+ },
3520
+ decompressFromUint8Array: function(compressed) {
3521
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3522
+ else {
3523
+ var buf = new Array(compressed.length / 2);
3524
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3525
+ var result = [];
3526
+ buf.forEach(function(c) {
3527
+ result.push(f(c));
3528
+ });
3529
+ return LZString.decompress(result.join(""));
3530
+ }
3531
+ },
3532
+ compressToEncodedURIComponent: function(input) {
3533
+ if (input == null) return "";
3534
+ return LZString._compress(input, 6, function(a) {
3535
+ return keyStrUriSafe.charAt(a);
3536
+ });
3537
+ },
3538
+ decompressFromEncodedURIComponent: function(input) {
3539
+ if (input == null) return "";
3540
+ if (input == "") return null;
3541
+ input = input.replace(/ /g, "+");
3542
+ return LZString._decompress(input.length, 32, function(index) {
3543
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
3544
+ });
3545
+ },
3546
+ compress: function(uncompressed) {
3547
+ return LZString._compress(uncompressed, 16, function(a) {
3548
+ return f(a);
3549
+ });
3550
+ },
3551
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3552
+ if (uncompressed == null) return "";
3553
+ 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;
3554
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
3555
+ context_c = uncompressed.charAt(ii);
3556
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3557
+ context_dictionary[context_c] = context_dictSize++;
3558
+ context_dictionaryToCreate[context_c] = true;
3559
+ }
3560
+ context_wc = context_w + context_c;
3561
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3562
+ else {
3563
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3564
+ if (context_w.charCodeAt(0) < 256) {
3565
+ for (i = 0; i < context_numBits; i++) {
3566
+ context_data_val = context_data_val << 1;
3567
+ if (context_data_position == bitsPerChar - 1) {
3568
+ context_data_position = 0;
3569
+ context_data.push(getCharFromInt(context_data_val));
3570
+ context_data_val = 0;
3571
+ } else context_data_position++;
3572
+ }
3573
+ value = context_w.charCodeAt(0);
3574
+ for (i = 0; i < 8; i++) {
3575
+ context_data_val = context_data_val << 1 | value & 1;
3576
+ if (context_data_position == bitsPerChar - 1) {
3577
+ context_data_position = 0;
3578
+ context_data.push(getCharFromInt(context_data_val));
3579
+ context_data_val = 0;
3580
+ } else context_data_position++;
3581
+ value = value >> 1;
3582
+ }
3583
+ } else {
3584
+ value = 1;
3585
+ for (i = 0; i < context_numBits; i++) {
3586
+ context_data_val = context_data_val << 1 | value;
3587
+ if (context_data_position == bitsPerChar - 1) {
3588
+ context_data_position = 0;
3589
+ context_data.push(getCharFromInt(context_data_val));
3590
+ context_data_val = 0;
3591
+ } else context_data_position++;
3592
+ value = 0;
3593
+ }
3594
+ value = context_w.charCodeAt(0);
3595
+ for (i = 0; i < 16; i++) {
3596
+ context_data_val = context_data_val << 1 | value & 1;
3597
+ if (context_data_position == bitsPerChar - 1) {
3598
+ context_data_position = 0;
3599
+ context_data.push(getCharFromInt(context_data_val));
3600
+ context_data_val = 0;
3601
+ } else context_data_position++;
3602
+ value = value >> 1;
3603
+ }
3604
+ }
3605
+ context_enlargeIn--;
3606
+ if (context_enlargeIn == 0) {
3607
+ context_enlargeIn = Math.pow(2, context_numBits);
3608
+ context_numBits++;
3609
+ }
3610
+ delete context_dictionaryToCreate[context_w];
3611
+ } else {
3612
+ value = context_dictionary[context_w];
3613
+ for (i = 0; i < context_numBits; i++) {
3614
+ context_data_val = context_data_val << 1 | value & 1;
3615
+ if (context_data_position == bitsPerChar - 1) {
3616
+ context_data_position = 0;
3617
+ context_data.push(getCharFromInt(context_data_val));
3618
+ context_data_val = 0;
3619
+ } else context_data_position++;
3620
+ value = value >> 1;
3621
+ }
3622
+ }
3623
+ context_enlargeIn--;
3624
+ if (context_enlargeIn == 0) {
3625
+ context_enlargeIn = Math.pow(2, context_numBits);
3626
+ context_numBits++;
3627
+ }
3628
+ context_dictionary[context_wc] = context_dictSize++;
3629
+ context_w = String(context_c);
3630
+ }
3631
+ }
3632
+ if (context_w !== "") {
3633
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3634
+ if (context_w.charCodeAt(0) < 256) {
3635
+ for (i = 0; i < context_numBits; i++) {
3636
+ context_data_val = context_data_val << 1;
3637
+ if (context_data_position == bitsPerChar - 1) {
3638
+ context_data_position = 0;
3639
+ context_data.push(getCharFromInt(context_data_val));
3640
+ context_data_val = 0;
3641
+ } else context_data_position++;
3642
+ }
3643
+ value = context_w.charCodeAt(0);
3644
+ for (i = 0; i < 8; i++) {
3645
+ context_data_val = context_data_val << 1 | value & 1;
3646
+ if (context_data_position == bitsPerChar - 1) {
3647
+ context_data_position = 0;
3648
+ context_data.push(getCharFromInt(context_data_val));
3649
+ context_data_val = 0;
3650
+ } else context_data_position++;
3651
+ value = value >> 1;
3652
+ }
3653
+ } else {
3654
+ value = 1;
3655
+ for (i = 0; i < context_numBits; i++) {
3656
+ context_data_val = context_data_val << 1 | value;
3657
+ if (context_data_position == bitsPerChar - 1) {
3658
+ context_data_position = 0;
3659
+ context_data.push(getCharFromInt(context_data_val));
3660
+ context_data_val = 0;
3661
+ } else context_data_position++;
3662
+ value = 0;
3663
+ }
3664
+ value = context_w.charCodeAt(0);
3665
+ for (i = 0; i < 16; i++) {
3666
+ context_data_val = context_data_val << 1 | value & 1;
3667
+ if (context_data_position == bitsPerChar - 1) {
3668
+ context_data_position = 0;
3669
+ context_data.push(getCharFromInt(context_data_val));
3670
+ context_data_val = 0;
3671
+ } else context_data_position++;
3672
+ value = value >> 1;
3673
+ }
3674
+ }
3675
+ context_enlargeIn--;
3676
+ if (context_enlargeIn == 0) {
3677
+ context_enlargeIn = Math.pow(2, context_numBits);
3678
+ context_numBits++;
3679
+ }
3680
+ delete context_dictionaryToCreate[context_w];
3681
+ } else {
3682
+ value = context_dictionary[context_w];
3683
+ for (i = 0; i < context_numBits; i++) {
3684
+ context_data_val = context_data_val << 1 | value & 1;
3685
+ if (context_data_position == bitsPerChar - 1) {
3686
+ context_data_position = 0;
3687
+ context_data.push(getCharFromInt(context_data_val));
3688
+ context_data_val = 0;
3689
+ } else context_data_position++;
3690
+ value = value >> 1;
3691
+ }
3692
+ }
3693
+ context_enlargeIn--;
3694
+ if (context_enlargeIn == 0) {
3695
+ context_enlargeIn = Math.pow(2, context_numBits);
3696
+ context_numBits++;
3697
+ }
3698
+ }
3699
+ value = 2;
3700
+ for (i = 0; i < context_numBits; i++) {
3701
+ context_data_val = context_data_val << 1 | value & 1;
3702
+ if (context_data_position == bitsPerChar - 1) {
3703
+ context_data_position = 0;
3704
+ context_data.push(getCharFromInt(context_data_val));
3705
+ context_data_val = 0;
3706
+ } else context_data_position++;
3707
+ value = value >> 1;
3708
+ }
3709
+ while (true) {
3710
+ context_data_val = context_data_val << 1;
3711
+ if (context_data_position == bitsPerChar - 1) {
3712
+ context_data.push(getCharFromInt(context_data_val));
3713
+ break;
3714
+ } else context_data_position++;
3715
+ }
3716
+ return context_data.join("");
3717
+ },
3718
+ decompress: function(compressed) {
3719
+ if (compressed == null) return "";
3720
+ if (compressed == "") return null;
3721
+ return LZString._decompress(compressed.length, 32768, function(index) {
3722
+ return compressed.charCodeAt(index);
3723
+ });
3724
+ },
3725
+ _decompress: function(length, resetValue, getNextValue) {
3726
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3727
+ val: getNextValue(0),
3728
+ position: resetValue,
3729
+ index: 1
3730
+ };
3731
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
3732
+ bits = 0;
3733
+ maxpower = Math.pow(2, 2);
3734
+ power = 1;
3735
+ while (power != maxpower) {
3736
+ resb = data.val & data.position;
3737
+ data.position >>= 1;
3738
+ if (data.position == 0) {
3739
+ data.position = resetValue;
3740
+ data.val = getNextValue(data.index++);
3741
+ }
3742
+ bits |= (resb > 0 ? 1 : 0) * power;
3743
+ power <<= 1;
3744
+ }
3745
+ switch (bits) {
3746
+ case 0:
3747
+ bits = 0;
3748
+ maxpower = Math.pow(2, 8);
3749
+ power = 1;
3750
+ while (power != maxpower) {
3751
+ resb = data.val & data.position;
3752
+ data.position >>= 1;
3753
+ if (data.position == 0) {
3754
+ data.position = resetValue;
3755
+ data.val = getNextValue(data.index++);
3756
+ }
3757
+ bits |= (resb > 0 ? 1 : 0) * power;
3758
+ power <<= 1;
3759
+ }
3760
+ c = f(bits);
3761
+ break;
3762
+ case 1:
3763
+ bits = 0;
3764
+ maxpower = Math.pow(2, 16);
3765
+ power = 1;
3766
+ while (power != maxpower) {
3767
+ resb = data.val & data.position;
3768
+ data.position >>= 1;
3769
+ if (data.position == 0) {
3770
+ data.position = resetValue;
3771
+ data.val = getNextValue(data.index++);
3772
+ }
3773
+ bits |= (resb > 0 ? 1 : 0) * power;
3774
+ power <<= 1;
3775
+ }
3776
+ c = f(bits);
3777
+ break;
3778
+ case 2: return "";
3779
+ }
3780
+ dictionary[3] = c;
3781
+ w = c;
3782
+ result.push(c);
3783
+ while (true) {
3784
+ if (data.index > length) return "";
3785
+ bits = 0;
3786
+ maxpower = Math.pow(2, numBits);
3787
+ power = 1;
3788
+ while (power != maxpower) {
3789
+ resb = data.val & data.position;
3790
+ data.position >>= 1;
3791
+ if (data.position == 0) {
3792
+ data.position = resetValue;
3793
+ data.val = getNextValue(data.index++);
3794
+ }
3795
+ bits |= (resb > 0 ? 1 : 0) * power;
3796
+ power <<= 1;
3797
+ }
3798
+ switch (c = bits) {
3799
+ case 0:
3800
+ bits = 0;
3801
+ maxpower = Math.pow(2, 8);
3802
+ power = 1;
3803
+ while (power != maxpower) {
3804
+ resb = data.val & data.position;
3805
+ data.position >>= 1;
3806
+ if (data.position == 0) {
3807
+ data.position = resetValue;
3808
+ data.val = getNextValue(data.index++);
3809
+ }
3810
+ bits |= (resb > 0 ? 1 : 0) * power;
3811
+ power <<= 1;
3812
+ }
3813
+ dictionary[dictSize++] = f(bits);
3814
+ c = dictSize - 1;
3815
+ enlargeIn--;
3816
+ break;
3817
+ case 1:
3818
+ bits = 0;
3819
+ maxpower = Math.pow(2, 16);
3820
+ power = 1;
3821
+ while (power != maxpower) {
3822
+ resb = data.val & data.position;
3823
+ data.position >>= 1;
3824
+ if (data.position == 0) {
3825
+ data.position = resetValue;
3826
+ data.val = getNextValue(data.index++);
3827
+ }
3828
+ bits |= (resb > 0 ? 1 : 0) * power;
3829
+ power <<= 1;
3830
+ }
3831
+ dictionary[dictSize++] = f(bits);
3832
+ c = dictSize - 1;
3833
+ enlargeIn--;
3834
+ break;
3835
+ case 2: return result.join("");
3836
+ }
3837
+ if (enlargeIn == 0) {
3838
+ enlargeIn = Math.pow(2, numBits);
3839
+ numBits++;
3840
+ }
3841
+ if (dictionary[c]) entry = dictionary[c];
3842
+ else if (c === dictSize) entry = w + w.charAt(0);
3843
+ else return null;
3844
+ result.push(entry);
3845
+ dictionary[dictSize++] = w + entry.charAt(0);
3846
+ enlargeIn--;
3847
+ w = entry;
3848
+ if (enlargeIn == 0) {
3849
+ enlargeIn = Math.pow(2, numBits);
3850
+ numBits++;
3851
+ }
3852
+ }
3853
+ }
3854
+ };
3855
+ return LZString;
3856
+ })();
3857
+ if (typeof define === "function" && define.amd) define(function() {
3858
+ return LZString;
3859
+ });
3860
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3861
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3862
+ return LZString;
3863
+ });
3864
+ })))(), 1);
3865
+ const sanitize = (segment) => segment.replace(/\//g, "-");
3866
+ /**
3867
+ * Name segments from the exported folder (exclusive) down to `node`
3868
+ * (inclusive), in top-down order. `root === undefined` means the drive root:
3869
+ * all ancestors. A node that IS the exported folder yields no segments.
3870
+ */
3871
+ function segmentsBelow(root, node, allNodes) {
3872
+ const segments = [];
3873
+ let current = node;
3874
+ while (current && current.id !== root?.id) {
3875
+ segments.push(sanitize(current.name));
3876
+ const parentId = current.parentFolder;
3877
+ current = parentId ? allNodes.find((n) => n.id === parentId) : void 0;
3878
+ }
3879
+ return segments.reverse();
3215
3880
  }
3216
- 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));
3217
- function useDropNode(targetId) {
3218
- const driveId = useSelectedDriveId();
3219
- const { srcId, parentId } = useDraggingNode() ?? {};
3220
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3221
- const params = {
3222
- driveId,
3223
- parentId,
3224
- targetId,
3225
- srcId
3226
- };
3227
- function handleNodeDrop(event, cb) {
3228
- if (!isNodeDrop(params)) return;
3229
- event.preventDefault();
3230
- event.stopPropagation();
3231
- cb?.();
3881
+ /**
3882
+ * Assemble the archive zip for a folder (or the whole drive when
3883
+ * `folderNode` is undefined). Every folder in the subtree becomes a
3884
+ * directory entry (empty folders survive); every file becomes a standard
3885
+ * single-document zip named after the node (drive naming convention:
3886
+ * `${name}.${extension}.phd`, ` (copy) N` on a same-folder collision).
3887
+ *
3888
+ * `fetchDocument` must return the document WITH its full operations and
3889
+ * initialState (see downloadFolderZip).
3890
+ */
3891
+ async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
3892
+ const allNodes = drive.state.global.nodes;
3893
+ const topName = sanitize(folderNode?.name ?? (drive.state.global.name || drive.header.name));
3894
+ const subtree = folderNode ? [folderNode, ...getDescendants(folderNode, allNodes)] : allNodes;
3895
+ const entries = { [topName + "/"]: new Uint8Array(0) };
3896
+ for (const node of subtree) {
3897
+ if (!isFolderNode(node)) continue;
3898
+ const dir = [topName, ...segmentsBelow(folderNode, node, allNodes)].join("/");
3899
+ entries[dir + "/"] = new Uint8Array(0);
3900
+ }
3901
+ const files = subtree.filter(isFileNode);
3902
+ const failed = [];
3903
+ const usedNamesByDir = /* @__PURE__ */ new Map();
3904
+ let done = 0;
3905
+ for (const node of files) try {
3906
+ const doc = await fetchDocument(node.id);
3907
+ const extension = await getDocumentExtension(doc);
3908
+ const parent = node.parentFolder ? allNodes.find((n) => n.id === node.parentFolder) : void 0;
3909
+ const dir = [topName, ...parent ? segmentsBelow(folderNode, parent, allNodes) : []].join("/");
3910
+ let usedNames = usedNamesByDir.get(dir);
3911
+ if (!usedNames) {
3912
+ usedNames = /* @__PURE__ */ new Set();
3913
+ usedNamesByDir.set(dir, usedNames);
3914
+ }
3915
+ const base = sanitize(node.name);
3916
+ let candidate = base;
3917
+ let count = getNextCopyNumber([...usedNames], base);
3918
+ while (usedNames.has(candidate)) {
3919
+ candidate = `${base} (copy) ${count}`;
3920
+ count += 1;
3921
+ }
3922
+ usedNames.add(candidate);
3923
+ const leaf = extension ? `${candidate}.${extension}.phd` : `${candidate}.phd`;
3924
+ entries[`${dir}/${leaf}`] = await createZip(doc);
3925
+ } catch {
3926
+ failed.push(node.name);
3927
+ } finally {
3928
+ done += 1;
3929
+ onProgress?.(done, files.length);
3232
3930
  }
3233
- const onDragEnter = (event) => handleNodeDrop(event);
3234
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3235
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3236
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3237
- unsetDragging();
3238
- unsetTarget();
3239
- moveNodeById(params).catch(console.error);
3240
- }));
3241
3931
  return {
3242
- isDropTarget,
3243
- onDragEnter,
3244
- onDragOver,
3245
- onDragLeave,
3246
- onDrop
3932
+ zip: await zipEntries(entries),
3933
+ archiveName: `${topName}.zip`,
3934
+ entryCount: files.length - failed.length,
3935
+ failed
3247
3936
  };
3248
3937
  }
3249
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3250
- graphQLReactorClientEventFunctions.useValue;
3251
- graphQLReactorClientEventFunctions.setValue;
3252
- graphQLReactorClientEventFunctions.addEventHandler;
3253
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3254
- packageDiscoveryFunctions.useValue;
3255
- packageDiscoveryFunctions.setValue;
3256
- packageDiscoveryFunctions.addEventHandler;
3257
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3258
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3259
- /** Returns the reactor client module (in-process or worker-backed) */
3260
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3261
- reactorClientModuleEventFunctions.setValue;
3262
- reactorClientModuleEventFunctions.addEventHandler;
3263
- reactorClientEventFunctions.useValue;
3264
- reactorClientEventFunctions.setValue;
3265
- reactorClientEventFunctions.addEventHandler;
3266
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3267
- const useSyncList = () => {
3268
- return useSync()?.list() ?? [];
3269
- };
3270
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3271
- revisionHistoryEventFunctions.useValue;
3272
- /** Sets revision history visibility */
3273
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3274
- revisionHistoryEventFunctions.addEventHandler;
3275
- /** Shows the revision history */
3276
- function showRevisionHistory() {
3277
- setRevisionHistoryVisible(true);
3278
- }
3279
- /** Sorts nodes by name. */
3280
- function sortNodesByName(nodes) {
3281
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3282
- }
3283
- /** Returns whether a node is a file. */
3284
- function isFileNodeKind(node) {
3285
- if (!node) return false;
3286
- return node.kind.toUpperCase() === "FILE";
3287
- }
3288
- /** Returns whether a node is a folder. */
3289
- function isFolderNodeKind(node) {
3290
- if (!node) return false;
3291
- return node.kind.toUpperCase() === "FOLDER";
3292
- }
3293
- /** Returns the nodes in the selected drive. */
3294
- function useNodesInSelectedDrive() {
3295
- const [selectedDrive] = useSelectedDriveSafe();
3296
- return selectedDrive?.state.global.nodes;
3297
- }
3298
- /** Returns the folder nodes in the selected drive. */
3299
- function useFolderNodesInSelectedDrive() {
3300
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3301
- }
3302
- /** Returns the selected node. */
3303
- function useSelectedNode() {
3304
- const selectedNodeId = useSelectedNodeId();
3305
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3306
- }
3307
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3308
- selectedTimelineItemEventFunctions.useValue;
3309
- selectedTimelineItemEventFunctions.setValue;
3310
- selectedTimelineItemEventFunctions.addEventHandler;
3311
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3312
- selectedTimelineRevisionEventFunctions.useValue;
3313
- selectedTimelineRevisionEventFunctions.setValue;
3314
- selectedTimelineRevisionEventFunctions.addEventHandler;
3315
- const toastEventFunctions = makePHEventFunctions("toast");
3316
- /** Returns the toast function */
3317
- const usePHToast = toastEventFunctions.useValue;
3318
- toastEventFunctions.setValue;
3319
- toastEventFunctions.addEventHandler;
3320
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3321
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3322
- /** Returns all of the Vetra packages loaded by the Connect instance */
3323
- const useVetraPackages = () => {
3324
- const packageManager = useVetraPackageManager();
3325
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3326
- };
3327
- vetraPackageManagerFunctions.addEventHandler;
3328
- function useDocumentModelModules() {
3329
- 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);
3330
- }
3331
- function useDocumentModelModuleById(id) {
3332
- return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3938
+ /**
3939
+ * Export a folder (or whole drive) to disk: fetches every document with its
3940
+ * full operation history, builds the archive, and saves it via
3941
+ * showSaveFilePicker (fallback: blob download), mirroring exportFile.
3942
+ */
3943
+ async function downloadFolderZip(drive, folderNode, onProgress) {
3944
+ const reactorClient = window.ph?.reactorClient;
3945
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
3946
+ const result = await buildFolderZip(drive, folderNode, async (id) => {
3947
+ const doc = await reactorClient.get(id);
3948
+ const operations = await fetchDocumentOperations(reactorClient, doc);
3949
+ const initialState = extractInitialState(operations["document"] ?? []);
3950
+ return {
3951
+ ...doc,
3952
+ operations,
3953
+ initialState
3954
+ };
3955
+ }, onProgress);
3956
+ if (!window.showSaveFilePicker) {
3957
+ const blob = new Blob([new Uint8Array(result.zip)], { type: "application/zip" });
3958
+ const link = window.document.createElement("a");
3959
+ link.style.display = "none";
3960
+ link.href = URL.createObjectURL(blob);
3961
+ link.download = result.archiveName;
3962
+ window.document.body.appendChild(link);
3963
+ link.click();
3964
+ window.document.body.removeChild(link);
3965
+ return result;
3966
+ }
3967
+ try {
3968
+ const writable = await (await window.showSaveFilePicker({ suggestedName: result.archiveName })).createWritable();
3969
+ await writable.write(new Uint8Array(result.zip));
3970
+ await writable.close();
3971
+ } catch (e) {
3972
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
3973
+ }
3974
+ return result;
3333
3975
  }
3976
+ /** Document types that represent a "drive": a container of nodes. */
3977
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
3334
3978
  function useAllowedDocumentModelModules() {
3335
3979
  const documentModelModules = useDocumentModelModules();
3336
3980
  const allowedDocumentTypes = useAllowedDocumentTypes();
@@ -3396,15 +4040,49 @@ function useSetPHDocumentEditorConfig(config) {
3396
4040
  setIsInitialized(true);
3397
4041
  }, [config, isInitialized]);
3398
4042
  }
3399
- /** Returns a document of a specific type, throws an error if the found document has a different type */
3400
- function useDocumentOfType(documentId, documentType) {
3401
- const [document, dispatch] = useDocumentById(documentId);
3402
- const documentModelModule = useDocumentModelModuleById(documentType);
3403
- if (!documentId || !documentType) return [];
3404
- if (!document) throw new Error(`Document not found: ${documentId}`);
3405
- if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3406
- if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3407
- return [document, dispatch];
4043
+ /**
4044
+ * Classifies a document's model version against the installed module
4045
+ * versions. Pure logic, extracted for testing.
4046
+ */
4047
+ function getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {
4048
+ if (availableVersions.length === 0) return;
4049
+ const sorted = [...availableVersions].sort((a, b) => a - b);
4050
+ const latestVersion = sorted[sorted.length - 1];
4051
+ if (documentVersion > latestVersion) return {
4052
+ kind: "unsupported",
4053
+ documentVersion,
4054
+ availableVersions: sorted
4055
+ };
4056
+ if (documentVersion === latestVersion) return {
4057
+ kind: "current",
4058
+ documentVersion
4059
+ };
4060
+ return {
4061
+ kind: "upgrade-available",
4062
+ documentVersion,
4063
+ latestVersion,
4064
+ canUpgrade: hasUpgradePath(documentVersion, latestVersion)
4065
+ };
4066
+ }
4067
+ /**
4068
+ * Compares the given document's model version against the versions available
4069
+ * from installed Vetra packages. Returns undefined while packages load or
4070
+ * when the document type has no installed modules.
4071
+ */
4072
+ function useDocumentVersionStatus(document) {
4073
+ const modules = useDocumentModelModules();
4074
+ const registry = useModelRegistry();
4075
+ if (!document || !modules) return;
4076
+ const documentType = document.header.documentType;
4077
+ return getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {
4078
+ if (!registry) return false;
4079
+ try {
4080
+ registry.computeUpgradePath(documentType, fromVersion, toVersion);
4081
+ return true;
4082
+ } catch {
4083
+ return false;
4084
+ }
4085
+ });
3408
4086
  }
3409
4087
  const validateDocument = (document) => {
3410
4088
  const errors = [];
@@ -3472,6 +4150,25 @@ function useDownloadDocument(id) {
3472
4150
  }
3473
4151
  };
3474
4152
  }
4153
+ /**
4154
+ * Downloads the selected drive's folder (or the whole drive when no folder
4155
+ * is given) as a single zip archive mirroring the folder tree.
4156
+ */
4157
+ function useDownloadFolder(folderNode) {
4158
+ const [selectedDrive] = useSelectedDriveSafe();
4159
+ const toast = usePHToast();
4160
+ return async () => {
4161
+ if (!selectedDrive) return;
4162
+ const name = folderNode?.name ?? selectedDrive.header.name;
4163
+ toast?.(`Downloading "${name}"…`);
4164
+ try {
4165
+ const { entryCount, failed } = await downloadFolderZip(selectedDrive, folderNode);
4166
+ toast?.(failed.length ? `Downloaded ${entryCount} files (${failed.length} failed)` : `Downloaded ${entryCount} files`);
4167
+ } catch (error) {
4168
+ toast?.(`Failed to download "${name}": ${error.message}`);
4169
+ }
4170
+ };
4171
+ }
3475
4172
  /** An editor is a drive "app" if it targets any supported drive document type. */
3476
4173
  function isDriveEditor(module) {
3477
4174
  const driveTypes = DRIVE_DOCUMENT_TYPES;
@@ -3511,11 +4208,11 @@ function useNodeActions() {
3511
4208
  const drives = useDrives();
3512
4209
  async function onAddFile(file, parent) {
3513
4210
  if (!selectedDriveId) return;
3514
- return addFile(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id);
4211
+ return addFileWithProgress(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id, void 0, void 0, "duplicate");
3515
4212
  }
3516
4213
  async function onAddFolder(name, parent) {
3517
4214
  if (!selectedDriveId) return;
3518
- return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
4215
+ return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3519
4216
  }
3520
4217
  async function onRenameNode(newName, node) {
3521
4218
  if (!selectedDriveId) return;
@@ -3602,20 +4299,8 @@ function useSelectedNodePath() {
3602
4299
  function useNodeParentFolderById(id) {
3603
4300
  return useFolderById(useNodeById(id)?.parentFolder);
3604
4301
  }
3605
- /** Returns the selected document id */
3606
- function useSelectedDocumentId() {
3607
- const selectedNode = useSelectedNode();
3608
- return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3609
- }
3610
- /** Returns the selected document. */
3611
- function useSelectedDocumentSafe() {
3612
- return useDocumentById(useSelectedDocumentId());
3613
- }
3614
- function useSelectedDocumentOfType(documentType) {
3615
- const documentId = useSelectedDocumentId();
3616
- if (!documentType) return [];
3617
- if (!documentId) throw new NoSelectedDocumentError();
3618
- return useDocumentOfType(documentId, documentType);
4302
+ function useParentFolderForSelectedNode() {
4303
+ return useNodeParentFolderById(useSelectedNode()?.id);
3619
4304
  }
3620
4305
  const STORED_THEME_KEY = "ph:theme";
3621
4306
  const UPDATE_STORED_THEME = "ph:updateStoredTheme";
@@ -3706,8 +4391,134 @@ function getDocumentGraphqlQuery() {
3706
4391
  if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
3707
4392
  return loc.source.body;
3708
4393
  }
3709
- function buildDocumentSubgraphQuery(identifier, authToken) {
3710
- const query = getDocumentGraphqlQuery();
4394
+ /**
4395
+ * The base URL of the switchboard that serves a drive's GraphQL channel.
4396
+ *
4397
+ * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the
4398
+ * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does
4399
+ * not end with the suffix is unexpected — fall back to its origin.
4400
+ */
4401
+ function getSwitchboardBaseFromChannelUrl(channelUrl) {
4402
+ if (channelUrl.endsWith("/graphql/r")) return channelUrl.slice(0, -10);
4403
+ return new URL(channelUrl).origin;
4404
+ }
4405
+ /**
4406
+ * The GraphQL name the switchboard exposes a document model under. Mirrors
4407
+ * `getDocumentModelSchemaName` on the server (`create-schema.ts`): the root
4408
+ * query field and the state type names are all derived from the model's
4409
+ * `global.name`.
4410
+ */
4411
+ function getDocumentModelSchemaName(model) {
4412
+ return pascalCase(model.documentModel.global.name.replaceAll("/", " "));
4413
+ }
4414
+ function buildStateTypeMap(definitions) {
4415
+ const typeMap = /* @__PURE__ */ new Map();
4416
+ for (const def of definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION) typeMap.set(def.name.value, def);
4417
+ return typeMap;
4418
+ }
4419
+ /**
4420
+ * Recursively expands the fields of a state object type into a GraphQL
4421
+ * selection. Objects expand their sub-selection (lists expand their item
4422
+ * type); enums, scalars, and built-ins are leaves.
4423
+ */
4424
+ function expandStateFields(typeDef, typeMap) {
4425
+ return (typeDef.fields ?? []).map((field) => {
4426
+ const fieldName = field.name.value;
4427
+ let typeNode = field.type;
4428
+ if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE) typeNode = typeNode.type;
4429
+ if (typeNode.kind === import_graphql.Kind.LIST_TYPE) {
4430
+ let itemType = typeNode.type;
4431
+ if (itemType.kind === import_graphql.Kind.NON_NULL_TYPE) itemType = itemType.type;
4432
+ if (itemType.kind === import_graphql.Kind.LIST_TYPE) throw new Error(`Nested lists are not supported in state selections: ${fieldName}`);
4433
+ if (itemType.kind !== import_graphql.Kind.NAMED_TYPE) return fieldName;
4434
+ const itemTypeDef = typeMap.get(itemType.name.value);
4435
+ if (!itemTypeDef) return fieldName;
4436
+ return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;
4437
+ }
4438
+ if (typeNode.kind !== import_graphql.Kind.NAMED_TYPE) return fieldName;
4439
+ const typeDef = typeMap.get(typeNode.name.value);
4440
+ if (!typeDef) return fieldName;
4441
+ return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;
4442
+ }).join(" ");
4443
+ }
4444
+ /**
4445
+ * Finds the root state object type in a state SDL. Root state types follow
4446
+ * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last
4447
+ * by convention — the same resolution order the server uses
4448
+ * (`extractRootTypeName` in `create-schema.ts`).
4449
+ */
4450
+ function findRootStateType(definitions, candidates) {
4451
+ let lastObjectType = null;
4452
+ for (const def of definitions) {
4453
+ if (def.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION) continue;
4454
+ if (candidates.includes(def.name.value)) return def;
4455
+ lastObjectType = def;
4456
+ }
4457
+ if (!lastObjectType) throw new Error("No root state type found in the document model schema");
4458
+ return lastObjectType;
4459
+ }
4460
+ /**
4461
+ * Derives the subselection for the document's `global` state scope from the
4462
+ * model's state SDL (e.g. `name total`), expanding object fields
4463
+ * recursively. Throws when the schema is missing, unparseable, or has no
4464
+ * root object type — the caller falls back to the generic document query.
4465
+ */
4466
+ function getDocumentStateSelection(model) {
4467
+ const schema = model.documentModel.global.specifications.at(-1)?.state.global.schema;
4468
+ if (!schema || !schema.trim()) throw new Error("Document model has no global state schema");
4469
+ const ast = (0, import_graphql.parse)(schema);
4470
+ const typeMap = buildStateTypeMap(ast.definitions);
4471
+ const documentName = getDocumentModelSchemaName(model);
4472
+ return expandStateFields(findRootStateType(ast.definitions, [`${documentName}State`, `${documentName}GlobalState`]), typeMap);
4473
+ }
4474
+ function getLocalStateSelection(localSchema, documentName) {
4475
+ const ast = (0, import_graphql.parse)(localSchema);
4476
+ const typeMap = buildStateTypeMap(ast.definitions);
4477
+ return expandStateFields(findRootStateType(ast.definitions, [`${documentName}LocalState`]), typeMap);
4478
+ }
4479
+ /**
4480
+ * Builds a query scoped to a document type's own subgraph root field,
4481
+ * selecting the document and its full typed state. The shape mirrors what
4482
+ * the switchboard generates per model (`generateNewApiSchema` in
4483
+ * `create-schema.ts`): `<Name> { document(identifier:) { document { ...
4484
+ * state { auth document global local } } } childIds }`.
4485
+ */
4486
+ function buildModelScopedQuery(model) {
4487
+ const globalState = model.documentModel.global;
4488
+ const documentName = getDocumentModelSchemaName(model);
4489
+ const globalSelection = getDocumentStateSelection(model);
4490
+ const localSchema = globalState.specifications.at(-1)?.state.local.schema ?? "";
4491
+ const localSelection = localSchema.includes(`type ${documentName}LocalState`) ? getLocalStateSelection(localSchema, documentName) : null;
4492
+ return [
4493
+ "query GetDocument($identifier: String!) {",
4494
+ ` ${documentName} {`,
4495
+ " document(identifier: $identifier) {",
4496
+ " document {",
4497
+ " id",
4498
+ " name",
4499
+ " documentType",
4500
+ " state {",
4501
+ " auth",
4502
+ " document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }",
4503
+ ` global { ${globalSelection} }`,
4504
+ ` ${localSelection ? `local { ${localSelection} }` : "local"}`,
4505
+ " }",
4506
+ " }",
4507
+ " childIds",
4508
+ " }",
4509
+ " }",
4510
+ "}"
4511
+ ].join("\n");
4512
+ }
4513
+ function buildDocumentSubgraphQuery(documentType, identifier, model, authToken) {
4514
+ let query;
4515
+ if (model && model.documentModel.global.id === documentType) try {
4516
+ query = buildModelScopedQuery(model);
4517
+ } catch (error) {
4518
+ console.warn("Could not derive a document-scoped query from the document model, falling back to the generic document query:", error);
4519
+ query = getDocumentGraphqlQuery();
4520
+ }
4521
+ else query = getDocumentGraphqlQuery();
3711
4522
  const variables = { identifier };
3712
4523
  const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
3713
4524
  const payload = {
@@ -3715,10 +4526,11 @@ function buildDocumentSubgraphQuery(identifier, authToken) {
3715
4526
  variables: JSON.stringify(variables, null, 2)
3716
4527
  };
3717
4528
  if (headers) payload.headers = JSON.stringify(headers);
3718
- return import_lz_string.compressToEncodedURIComponent(JSON.stringify(payload));
4529
+ return import_lz_string.default.compressToEncodedURIComponent(JSON.stringify(payload));
3719
4530
  }
3720
- function buildDocumentSubgraphUrl(driveUrl, identifier, authToken) {
3721
- return `${driveUrl}?explorerURLState=${buildDocumentSubgraphQuery(identifier, authToken)}`;
4531
+ function buildDocumentSubgraphUrl(channelUrl, documentType, identifier, model, authToken) {
4532
+ const encodedQuery = buildDocumentSubgraphQuery(documentType, identifier, model, authToken);
4533
+ return `${getSwitchboardBaseFromChannelUrl(channelUrl)}/explorer?explorerURLState=${encodedQuery}`;
3722
4534
  }
3723
4535
  /**
3724
4536
  * Hook that returns a function to generate a document's switchboard URL.
@@ -3734,6 +4546,7 @@ function buildDocumentSubgraphUrl(driveUrl, identifier, authToken) {
3734
4546
  function useGetSwitchboardLink(document) {
3735
4547
  const [drive] = useSelectedDriveSafe();
3736
4548
  const remotes = useSyncList();
4549
+ const documentModelModule = useDocumentModelModuleById(document?.header.documentType);
3737
4550
  const isRemoteDrive = useMemo(() => {
3738
4551
  if (!e$4(drive)) return false;
3739
4552
  return remotes.some((remote) => remote.meta.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)));
@@ -3758,12 +4571,13 @@ function useGetSwitchboardLink(document) {
3758
4571
  expiresIn: 600,
3759
4572
  aud: remoteUrl
3760
4573
  }) : void 0;
3761
- return buildDocumentSubgraphUrl(remoteUrl, document.header.id, token);
4574
+ return buildDocumentSubgraphUrl(remoteUrl, document.header.documentType, document.header.id, documentModelModule, token);
3762
4575
  };
3763
4576
  }, [
3764
4577
  isRemoteDrive,
3765
4578
  remoteUrl,
3766
4579
  document,
4580
+ documentModelModule,
3767
4581
  user,
3768
4582
  renown
3769
4583
  ]);
@@ -3830,6 +4644,6 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
3830
4644
  createDebouncedRefreshReactorData();
3831
4645
  createDebouncedRefreshReactorDataClient();
3832
4646
  //#endregion
3833
- export { useSetPHDocumentEditorConfig as A, usePHToast as C, useSelectedDriveSafe as D, useSelectedDriveId as E, t$2 as F, t$5 as I, useDocumentById as L, useUserPermissions as M, e$1 as N, useSelectedNodePath as O, e$4 as P, useNodesInSelectedDriveOrFolder as S, useSelectedDocumentSafe as T, useEditorModulesForDocumentType as _, preloadEditorModule as a, useNodeById as b, showCreateDocumentModal as c, useAllowedDocumentModelModules as d, useDisabledEditors as f, useEditorModules as g, useDropNode as h, isFolderNodeKind as i, useTheme as j, useSetPHAppConfig as k, showDeleteNodeModal as l, useDragNode as m, getSyncStatusSync as n, setSelectedDrive as o, useDownloadDocument as p, isFileNodeKind as r, setSelectedNode as s, addFolder as t, showRevisionHistory as u, useGetSwitchboardLink as v, useSelectedDocumentOfType as w, useNodeParentFolderById as x, useNodeActions as y };
4647
+ export { useDropNode as A, setSelectedNode as B, addDocument as C, showRevisionHistory as D, showPHModal as E, t$2 as F, useSelectedDriveSafe as H, t$5 as I, isFileNodeKind as L, useStudioMode as M, e$1 as N, useDisabledEditors as O, e$4 as P, isFolderNodeKind as R, useSelectedDocumentSafe as S, showDeleteNodeModal as T, useDocumentById as U, useSelectedDriveId as V, useSetPHAppConfig as _, useDownloadDocument as a, useUserPermissions as b, useEditorModulesForDocumentType as c, useNodeById as d, useNodeParentFolderById as f, useSelectedNodePath as g, useSelectedFolder as h, useDocumentVersionStatus as i, usePHToast as j, useDragNode as k, useGetSwitchboardLink as l, useParentFolderForSelectedNode as m, preloadEditorModule as n, useDownloadFolder as o, useNodesInSelectedDriveOrFolder as p, useAllowedDocumentModelModules as r, useEditorModules as s, getSyncStatusSync as t, useNodeActions as u, useSetPHDocumentEditorConfig as v, addFolder$1 as w, useSelectedDocumentOfType as x, useTheme as y, setSelectedDrive as z };
3834
4648
 
3835
- //# sourceMappingURL=dist-DJEK2WVi.mjs.map
4649
+ //# sourceMappingURL=dist-BAXIB1_k.mjs.map