@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.8 → 6.2.2-dev.80

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-Df8YBCmF.js} +916 -200
  6. package/dist/browser/connect-Df8YBCmF.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-BIpFdiLp.js} +2388 -1848
  12. package/dist/browser/dist-BIpFdiLp.js.map +1 -0
  13. package/dist/browser/{document-drive-IdFV1QXL.js → document-drive-DU75CBKf.js} +1186 -124
  14. package/dist/browser/document-drive-DU75CBKf.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-BuYbUTIt.js} +671 -236
  19. package/dist/browser/editor-BuYbUTIt.js.map +1 -0
  20. package/dist/browser/editor-y1bqyeB_.js +25 -0
  21. package/dist/browser/editor-y1bqyeB_.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-BzERbCoQ.js} +73 -46
  26. package/dist/browser/folder-view-BzERbCoQ.js.map +1 -0
  27. package/dist/browser/{graphql-editor-ZLRO_8Ce.js → graphql-editor-Dv1FDpax.js} +8 -7
  28. package/dist/browser/{graphql-editor-ZLRO_8Ce.js.map → graphql-editor-Dv1FDpax.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-ZRgRDikU.js} +4 -4
  34. package/dist/browser/{json-editor-DBuZ6gN7.js.map → json-editor-ZRgRDikU.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-BBkkpjRl.js} +8 -18
  42. package/dist/browser/state-schemas-BBkkpjRl.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-DM43aaJZ.mjs} +916 -200
  46. package/dist/node/connect-DM43aaJZ.mjs.map +1 -0
  47. package/dist/node/{dist-DJEK2WVi.mjs → dist-4gA6tFmW.mjs} +2391 -1846
  48. package/dist/node/dist-4gA6tFmW.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-CRYbvD0-.mjs} +1186 -124
  54. package/dist/node/document-drive-CRYbvD0-.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-B5cnYfC7.mjs} +672 -237
  59. package/dist/node/editor-B5cnYfC7.mjs.map +1 -0
  60. package/dist/node/editor-Dn0DUR0W.mjs +25 -0
  61. package/dist/node/editor-Dn0DUR0W.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-BAAfODx_.mjs} +73 -46
  66. package/dist/node/folder-view-BAAfODx_.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-CUrJvXrG.mjs} +7 -7
  70. package/dist/node/{graphql-editor-C5VLRqEf.mjs.map → graphql-editor-CUrJvXrG.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-TvKShKo-.mjs} +4 -4
  76. package/dist/node/{json-editor-iI2s9a_4.mjs.map → json-editor-TvKShKo-.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-CJK5hin3.mjs} +10 -20
  82. package/dist/{browser/state-schemas-BjQKM498.js.map → node/state-schemas-CJK5hin3.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, t as capitalCase } from "./dist-DT7jI9ol.mjs";
2
+ import { C as baseLoadFromInputVersioned, O as createPresignedHeader, Q as setName, S as baseLoadFromInput, T as buildSignedAction, U as replayDocumentVersioned, a as handleTargetNameCollisions, ct as validateStateSchemaName, f as logger, h as UnsupportedDocumentModelVersionError, i as generateNodesCopy, j as createZip, l as moveNode, lt as generateId, n as copyNode, o as isFileNode, ot as validateInitialState, s as isFolderNode, st as validateModules, t as addFolder, u as updateNode, w as baseSaveToFileHandle, y as assertAuthPreservedOnDuplicate } from "./document-drive-CRYbvD0-.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,1067 @@ 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-DMIR-uSD.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
+ /** Returns all of the Vetra packages loaded by the Connect instance */
1252
+ const useVetraPackages = () => {
1253
+ const packageManager = useVetraPackageManager();
1254
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
1940
1255
  };
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;
1256
+ vetraPackageManagerFunctions.addEventHandler;
1257
+ function useDocumentModelModules() {
1258
+ 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);
1259
+ }
1260
+ /**
1261
+ * Resolves a document model module by document type, mirroring the registry's
1262
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
1263
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
1264
+ * with `version` given only an exact match is returned. The reactor resolves
1265
+ * modules the same way when a document is created, so metadata read through
1266
+ * this hook and the version a creation actually uses cannot disagree.
1267
+ */
1268
+ function useDocumentModelModuleById(id, version) {
1269
+ const documentModelModules = useDocumentModelModules();
1270
+ if (!id || !documentModelModules) return void 0;
1271
+ let latestModule;
1272
+ let latestVersion = -1;
1273
+ for (const module of documentModelModules) {
1274
+ if (module.documentModel.global.id !== id) continue;
1275
+ const moduleVersion = module.version ?? 1;
1276
+ if (version !== void 0) {
1277
+ if (moduleVersion === version) return module;
1278
+ continue;
1279
+ }
1280
+ if (moduleVersion > latestVersion) {
1281
+ latestVersion = moduleVersion;
1282
+ latestModule = module;
1283
+ }
1947
1284
  }
1948
- };
1949
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1950
- //#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 !== "";
1285
+ return latestModule;
1286
+ }
1287
+ Error;
1288
+ require_graphql();
1289
+ JSON;
1981
1290
  //#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
- }
1291
+ //#region ../reactor-browser/dist/client-D66jVnot.js
1292
+ var import_main = require_main();
1293
+ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
1294
+ DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
1295
+ DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
1296
+ DocumentChangeType["Created"] = "CREATED";
1297
+ DocumentChangeType["Deleted"] = "DELETED";
1298
+ DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
1299
+ DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
1300
+ DocumentChangeType["Updated"] = "UPDATED";
1301
+ return DocumentChangeType;
1302
+ }({});
1303
+ let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
1304
+ PropagationMode["Cascade"] = "CASCADE";
1305
+ PropagationMode["Orphan"] = "ORPHAN";
1306
+ return PropagationMode;
1307
+ }({});
1308
+ const PhDocumentFieldsFragmentDoc = import_main.gql`
1309
+ fragment PHDocumentFields on PHDocument {
1310
+ id
1311
+ slug
1312
+ name
1313
+ documentType
1314
+ state
1315
+ revisionsList {
1316
+ scope
1317
+ revision
1318
+ }
1319
+ createdAtUtcIso
1320
+ lastModifiedAtUtcIso
1321
+ }
1322
+ `;
1323
+ import_main.gql`
1324
+ query GetDocumentModels($namespace: String, $paging: PagingInput) {
1325
+ documentModels(namespace: $namespace, paging: $paging) {
1326
+ items {
1327
+ id
1328
+ name
1329
+ namespace
1330
+ version
1331
+ specification
1332
+ }
1333
+ totalCount
1334
+ hasNextPage
1335
+ hasPreviousPage
1336
+ cursor
1337
+ }
1338
+ }
1339
+ `;
1340
+ const GetDocumentDocument = import_main.gql`
1341
+ query GetDocument($identifier: String!, $view: ViewFilterInput) {
1342
+ document(identifier: $identifier, view: $view) {
1343
+ document {
1344
+ ...PHDocumentFields
1345
+ }
1346
+ childIds
1347
+ }
1348
+ }
1349
+ ${PhDocumentFieldsFragmentDoc}
1350
+ `;
1351
+ const GetDocumentWithOperationsDocument = import_main.gql`
1352
+ query GetDocumentWithOperations(
1353
+ $identifier: String!
1354
+ $view: ViewFilterInput
1355
+ $operationsFilter: DocumentOperationsFilterInput
1356
+ $operationsPaging: PagingInput
1357
+ ) {
1358
+ document(identifier: $identifier, view: $view) {
1359
+ document {
1360
+ ...PHDocumentFields
1361
+ operations(filter: $operationsFilter, paging: $operationsPaging) {
1362
+ items {
1363
+ index
1364
+ timestampUtcMs
1365
+ hash
1366
+ skip
1367
+ error
1368
+ deniedReason
1369
+ id
1370
+ action {
1371
+ id
1372
+ type
1373
+ timestampUtcMs
1374
+ input
1375
+ scope
1376
+ context {
1377
+ signer {
1378
+ user {
1379
+ address
1380
+ networkId
1381
+ chainId
1382
+ }
1383
+ app {
1384
+ name
1385
+ key
1386
+ }
1387
+ signatures
1388
+ }
1389
+ }
1390
+ }
1391
+ }
1392
+ totalCount
1393
+ hasNextPage
1394
+ hasPreviousPage
1395
+ cursor
1396
+ }
1397
+ }
1398
+ childIds
1399
+ }
1400
+ }
1401
+ ${PhDocumentFieldsFragmentDoc}
1402
+ `;
1403
+ import_main.gql`
1404
+ query GetDocumentOutgoingRelationships(
1405
+ $sourceIdentifier: String!
1406
+ $relationshipType: String!
1407
+ $view: ViewFilterInput
1408
+ $paging: PagingInput
1409
+ ) {
1410
+ documentOutgoingRelationships(
1411
+ sourceIdentifier: $sourceIdentifier
1412
+ relationshipType: $relationshipType
1413
+ view: $view
1414
+ paging: $paging
1415
+ ) {
1416
+ items {
1417
+ ...PHDocumentFields
1418
+ }
1419
+ totalCount
1420
+ hasNextPage
1421
+ hasPreviousPage
1422
+ cursor
1423
+ }
1424
+ }
1425
+ ${PhDocumentFieldsFragmentDoc}
1426
+ `;
1427
+ import_main.gql`
1428
+ query GetDocumentIncomingRelationships(
1429
+ $targetIdentifier: String!
1430
+ $relationshipType: String!
1431
+ $view: ViewFilterInput
1432
+ $paging: PagingInput
1433
+ ) {
1434
+ documentIncomingRelationships(
1435
+ targetIdentifier: $targetIdentifier
1436
+ relationshipType: $relationshipType
1437
+ view: $view
1438
+ paging: $paging
1439
+ ) {
1440
+ items {
1441
+ ...PHDocumentFields
1442
+ }
1443
+ totalCount
1444
+ hasNextPage
1445
+ hasPreviousPage
1446
+ cursor
1447
+ }
1448
+ }
1449
+ ${PhDocumentFieldsFragmentDoc}
1450
+ `;
1451
+ import_main.gql`
1452
+ query FindDocuments(
1453
+ $search: SearchFilterInput
1454
+ $view: ViewFilterInput
1455
+ $paging: PagingInput
1456
+ ) {
1457
+ findDocuments(search: $search, view: $view, paging: $paging) {
1458
+ items {
1459
+ ...PHDocumentFields
1460
+ }
1461
+ totalCount
1462
+ hasNextPage
1463
+ hasPreviousPage
1464
+ cursor
1465
+ }
1466
+ }
1467
+ ${PhDocumentFieldsFragmentDoc}
1468
+ `;
1469
+ const GetDocumentOperationsDocument = import_main.gql`
1470
+ query GetDocumentOperations(
1471
+ $filter: OperationsFilterInput!
1472
+ $paging: PagingInput
1473
+ ) {
1474
+ documentOperations(filter: $filter, paging: $paging) {
1475
+ items {
1476
+ index
1477
+ timestampUtcMs
1478
+ hash
1479
+ skip
1480
+ error
1481
+ deniedReason
1482
+ id
1483
+ action {
1484
+ id
1485
+ type
1486
+ timestampUtcMs
1487
+ input
1488
+ scope
1489
+ context {
1490
+ signer {
1491
+ user {
1492
+ address
1493
+ networkId
1494
+ chainId
1495
+ }
1496
+ app {
1497
+ name
1498
+ key
1499
+ }
1500
+ signatures
1501
+ }
1502
+ }
1503
+ }
1504
+ }
1505
+ totalCount
1506
+ hasNextPage
1507
+ hasPreviousPage
1508
+ cursor
1509
+ }
1510
+ }
1511
+ `;
1512
+ import_main.gql`
1513
+ query GetJobStatus($jobId: String!) {
1514
+ jobStatus(jobId: $jobId) {
1515
+ id
1516
+ status
1517
+ result
1518
+ error
1519
+ createdAt
1520
+ completedAt
1521
+ }
1522
+ }
1523
+ `;
1524
+ import_main.gql`
1525
+ query EvaluateActions(
1526
+ $documentIdentifier: String!
1527
+ $branch: String
1528
+ $candidates: [ActionCandidateInput!]!
1529
+ ) {
1530
+ evaluateActions(
1531
+ documentIdentifier: $documentIdentifier
1532
+ branch: $branch
1533
+ candidates: $candidates
1534
+ ) {
1535
+ evaluations {
1536
+ decision
1537
+ reason
1538
+ }
1539
+ allAllowed
1540
+ anyAllowed
1541
+ allDenied
1542
+ anyDenied
1543
+ }
1544
+ }
1545
+ `;
1546
+ import_main.gql`
1547
+ mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
1548
+ createDocument(document: $document, parentIdentifier: $parentIdentifier) {
1549
+ ...PHDocumentFields
1550
+ }
1551
+ }
1552
+ ${PhDocumentFieldsFragmentDoc}
1553
+ `;
1554
+ import_main.gql`
1555
+ mutation CreateEmptyDocument(
1556
+ $documentType: String!
1557
+ $parentIdentifier: String
1558
+ ) {
1559
+ createEmptyDocument(
1560
+ documentType: $documentType
1561
+ parentIdentifier: $parentIdentifier
1562
+ ) {
1563
+ ...PHDocumentFields
1564
+ }
1565
+ }
1566
+ ${PhDocumentFieldsFragmentDoc}
1567
+ `;
1568
+ import_main.gql`
1569
+ mutation MutateDocument(
1570
+ $documentIdentifier: String!
1571
+ $actions: [ActionInput!]!
1572
+ $branch: String
1573
+ ) {
1574
+ mutateDocument: execute(
1575
+ documentIdentifier: $documentIdentifier
1576
+ actions: $actions
1577
+ branch: $branch
1578
+ ) {
1579
+ ...PHDocumentFields
1580
+ }
1581
+ }
1582
+ ${PhDocumentFieldsFragmentDoc}
1583
+ `;
1584
+ import_main.gql`
1585
+ mutation MutateDocumentAsync(
1586
+ $documentIdentifier: String!
1587
+ $actions: [ActionInput!]!
1588
+ $branch: String
1589
+ ) {
1590
+ mutateDocumentAsync: executeAsync(
1591
+ documentIdentifier: $documentIdentifier
1592
+ actions: $actions
1593
+ branch: $branch
1594
+ ) {
1595
+ id
1596
+ status
1597
+ result
1598
+ error
1599
+ createdAt
1600
+ completedAt
1601
+ }
1602
+ }
1603
+ `;
1604
+ import_main.gql`
1605
+ mutation RenameDocument(
1606
+ $documentIdentifier: String!
1607
+ $name: String!
1608
+ $branch: String
1609
+ ) {
1610
+ renameDocument(
1611
+ documentIdentifier: $documentIdentifier
1612
+ name: $name
1613
+ branch: $branch
1614
+ ) {
1615
+ ...PHDocumentFields
1616
+ }
1617
+ }
1618
+ ${PhDocumentFieldsFragmentDoc}
1619
+ `;
1620
+ import_main.gql`
1621
+ mutation SetPreferredEditor(
1622
+ $documentIdentifier: String!
1623
+ $preferredEditor: String
1624
+ $branch: String
1625
+ ) {
1626
+ setPreferredEditor(
1627
+ documentIdentifier: $documentIdentifier
1628
+ preferredEditor: $preferredEditor
1629
+ branch: $branch
1630
+ ) {
1631
+ ...PHDocumentFields
1632
+ }
1633
+ }
1634
+ ${PhDocumentFieldsFragmentDoc}
1635
+ `;
1636
+ import_main.gql`
1637
+ mutation AddRelationship(
1638
+ $sourceIdentifier: String!
1639
+ $targetIdentifier: String!
1640
+ $relationshipType: String!
1641
+ $branch: String
1642
+ ) {
1643
+ addRelationship(
1644
+ sourceIdentifier: $sourceIdentifier
1645
+ targetIdentifier: $targetIdentifier
1646
+ relationshipType: $relationshipType
1647
+ branch: $branch
1648
+ ) {
1649
+ ...PHDocumentFields
1650
+ }
1651
+ }
1652
+ ${PhDocumentFieldsFragmentDoc}
1653
+ `;
1654
+ import_main.gql`
1655
+ mutation RemoveRelationship(
1656
+ $sourceIdentifier: String!
1657
+ $targetIdentifier: String!
1658
+ $relationshipType: String!
1659
+ $branch: String
1660
+ ) {
1661
+ removeRelationship(
1662
+ sourceIdentifier: $sourceIdentifier
1663
+ targetIdentifier: $targetIdentifier
1664
+ relationshipType: $relationshipType
1665
+ branch: $branch
1666
+ ) {
1667
+ ...PHDocumentFields
1668
+ }
1669
+ }
1670
+ ${PhDocumentFieldsFragmentDoc}
1671
+ `;
1672
+ import_main.gql`
1673
+ mutation MoveRelationship(
1674
+ $sourceParentIdentifier: String!
1675
+ $targetParentIdentifier: String!
1676
+ $targetIdentifier: String!
1677
+ $relationshipType: String!
1678
+ $branch: String
1679
+ ) {
1680
+ moveRelationship(
1681
+ sourceParentIdentifier: $sourceParentIdentifier
1682
+ targetParentIdentifier: $targetParentIdentifier
1683
+ targetIdentifier: $targetIdentifier
1684
+ relationshipType: $relationshipType
1685
+ branch: $branch
1686
+ ) {
1687
+ source {
1688
+ ...PHDocumentFields
1689
+ }
1690
+ target {
1691
+ ...PHDocumentFields
1692
+ }
1693
+ }
1694
+ }
1695
+ ${PhDocumentFieldsFragmentDoc}
1696
+ `;
1697
+ import_main.gql`
1698
+ mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
1699
+ deleteDocument(identifier: $identifier, propagate: $propagate)
1700
+ }
1701
+ `;
1702
+ import_main.gql`
1703
+ mutation DeleteDocuments(
1704
+ $identifiers: [String!]!
1705
+ $propagate: PropagationMode
1706
+ ) {
1707
+ deleteDocuments(identifiers: $identifiers, propagate: $propagate)
1708
+ }
1709
+ `;
1710
+ import_main.gql`
1711
+ subscription DocumentChanges(
1712
+ $search: SearchFilterInput
1713
+ $view: ViewFilterInput
1714
+ ) {
1715
+ documentChanges(search: $search, view: $view) {
1716
+ type
1717
+ documents {
1718
+ ...PHDocumentFields
1719
+ }
1720
+ context {
1721
+ parentId
1722
+ childId
1723
+ }
1724
+ }
1725
+ }
1726
+ ${PhDocumentFieldsFragmentDoc}
1727
+ `;
1728
+ import_main.gql`
1729
+ subscription JobChanges($jobId: String!) {
1730
+ jobChanges(jobId: $jobId) {
1731
+ jobId
1732
+ status
1733
+ result
1734
+ error
1735
+ }
1736
+ }
1737
+ `;
1738
+ import_main.gql`
1739
+ query PollSyncEnvelopes(
1740
+ $channelId: String!
1741
+ $outboxAck: Int!
1742
+ $outboxLatest: Int!
1743
+ ) {
1744
+ pollSyncEnvelopes(
1745
+ channelId: $channelId
1746
+ outboxAck: $outboxAck
1747
+ outboxLatest: $outboxLatest
1748
+ ) {
1749
+ envelopes {
1750
+ type
1751
+ channelMeta {
1752
+ id
1753
+ }
1754
+ operations {
1755
+ operation {
1756
+ index
1757
+ timestampUtcMs
1758
+ hash
1759
+ skip
1760
+ error
1761
+ deniedReason
1762
+ id
1763
+ action {
1764
+ id
1765
+ type
1766
+ timestampUtcMs
1767
+ input
1768
+ scope
1769
+ context {
1770
+ signer {
1771
+ user {
1772
+ address
1773
+ networkId
1774
+ chainId
1775
+ }
1776
+ app {
1777
+ name
1778
+ key
1779
+ }
1780
+ signatures
1781
+ }
1782
+ }
1783
+ }
1784
+ }
1785
+ context {
1786
+ documentId
1787
+ documentType
1788
+ scope
1789
+ branch
1790
+ }
1791
+ }
1792
+ cursor {
1793
+ remoteName
1794
+ cursorOrdinal
1795
+ lastSyncedAtUtcMs
1796
+ }
1797
+ key
1798
+ dependsOn
1799
+ }
1800
+ ackOrdinal
1801
+ deadLetters {
1802
+ documentId
1803
+ error
1804
+ errorType
1805
+ }
1806
+ hasMore
1807
+ }
1808
+ }
1809
+ `;
1810
+ import_main.gql`
1811
+ mutation TouchChannel($input: TouchChannelInput!) {
1812
+ touchChannel(input: $input) {
1813
+ success
1814
+ ackOrdinal
1815
+ }
1816
+ }
1817
+ `;
1818
+ import_main.gql`
1819
+ mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
1820
+ pushSyncEnvelopes(envelopes: $envelopes)
1821
+ }
1822
+ `;
1823
+ /** Get the source string from a GraphQL document (string or DocumentNode). */
1824
+ function getDocumentSource(doc) {
1825
+ return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
1826
+ }
1827
+ /**
1828
+ * Extract the inner selection set of a named field from a GraphQL document source.
1829
+ * Returns the `{ ... }` block including braces.
1830
+ */
1831
+ function extractSelectionSet(doc, fieldName, fallback) {
1832
+ const source = getDocumentSource(doc);
1833
+ return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
1834
+ }
1835
+ /**
1836
+ * Extract the query body and any fragment definitions from a GraphQL document.
1837
+ * Returns { body, fragments } where body is the content inside the query `{ ... }`
1838
+ * and fragments are any trailing fragment definitions.
1839
+ */
1840
+ function extractQueryParts(doc, fallbackBody) {
1841
+ const source = getDocumentSource(doc);
1842
+ const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
1843
+ return {
1844
+ body: queryMatch?.[1]?.trim() ?? fallbackBody,
1845
+ fragments: queryMatch?.[2]?.trim() ?? ""
1846
+ };
1847
+ }
1848
+ extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
1849
+ extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
1850
+ //#endregion
1851
+ //#region ../reactor-browser/dist/renown-BHxwP7xU.js
1852
+ const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
1853
+ const RenownInitialUserContext = createContext({ state: "unknown" });
1854
+ /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
1855
+ function useRenownInitialAuth() {
1856
+ return useContext(RenownInitialUserContext);
1857
+ }
1858
+ function useRenownInitialUser() {
1859
+ const initial = useRenownInitialAuth();
1860
+ return initial.state === "authenticated" ? initial.user : void 0;
1861
+ }
1862
+ const renownEventFunctions = makePHEventFunctions("renown");
1863
+ renownEventFunctions.addEventHandler;
1864
+ /** Returns the renown instance */
1865
+ const useRenown = renownEventFunctions.useValue;
1866
+ renownEventFunctions.setValue;
1867
+ function jsonEqual(a, b) {
1868
+ if (a === b) return true;
1869
+ if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
1870
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
1871
+ const ra = a;
1872
+ const rb = b;
1873
+ const keys = Object.keys(ra).filter((k) => ra[k] !== void 0);
1874
+ if (keys.length !== Object.keys(rb).filter((k) => rb[k] !== void 0).length) return false;
1875
+ return keys.every((k) => jsonEqual(ra[k], rb[k]));
1876
+ }
1877
+ function sameUser(a, b) {
1878
+ return jsonEqual(a, b);
1879
+ }
1880
+ function resolveInstanceUser(instance, seed) {
1881
+ const restored = instance.user;
1882
+ if (restored) return sameUser(seed, restored) ? seed : restored;
1883
+ return instance.status === "initial" ? void 0 : seed;
1884
+ }
1885
+ /** Returns the current user from the renown instance, subscribing to user events */
1886
+ function useUser() {
1887
+ const renown = useRenown();
1888
+ const initialUser = useRenownInitialUser();
1889
+ const instance = renown ? renown : void 0;
1890
+ const [tracked, setTracked] = useState(() => ({
1891
+ instance,
1892
+ user: instance ? resolveInstanceUser(instance, initialUser) : initialUser
1893
+ }));
1894
+ const current = tracked.instance === instance ? tracked : {
1895
+ instance,
1896
+ user: instance ? resolveInstanceUser(instance, tracked.user ?? initialUser) : tracked.user
1897
+ };
1898
+ useEffect(() => {
1899
+ if (current !== tracked) setTracked(current);
1900
+ }, [current, tracked]);
1901
+ useEffect(() => {
1902
+ if (!instance) return;
1903
+ return instance.on("user", (user) => setTracked((prev) => ({
1904
+ instance,
1905
+ user: sameUser(prev.user, user) ? prev.user : user
1906
+ })));
1907
+ }, [instance]);
1908
+ return instance ? current.user : initialUser ?? current.user;
1909
+ }
1910
+ //#endregion
1911
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
1912
+ function e$8(e, t, n) {
1913
+ let r = (n) => e(n, ...t);
1914
+ return n === void 0 ? r : Object.assign(r, {
1915
+ lazy: n,
1916
+ lazyArgs: t
1917
+ });
1918
+ }
1919
+ //#endregion
1920
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
1921
+ function t$5(t, n, r) {
1922
+ let i = t.length - n.length;
1923
+ if (i === 0) return t(...n);
1924
+ if (i === 1) return e$8(t, n, r);
1925
+ throw Error(`Wrong number of arguments`);
1926
+ }
1927
+ //#endregion
1928
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
1929
+ function t$4(...t) {
1930
+ return t$5(n$4, t);
1931
+ }
1932
+ const n$4 = (e, t) => t.every((t) => t(e));
1933
+ //#endregion
1934
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
1935
+ function e$7(e, t, n) {
1936
+ return e(n[0]) ? (e) => t(e, ...n) : t(...n);
1937
+ }
1938
+ function t$3(...t) {
1939
+ return e$7(r, n$3, t);
1940
+ }
1941
+ function n$3(e, ...t) {
1942
+ for (let n of t) {
1943
+ if (typeof n == `function`) return n(e);
1944
+ let [t, r] = n;
1945
+ if (t(e)) return r(e);
1946
+ }
1947
+ throw Error(`conditional: data failed for all cases`);
1948
+ }
1949
+ function r(e) {
1950
+ if (!Array.isArray(e)) return !1;
1951
+ let [t, n, ...r] = e;
1952
+ return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
1953
+ }
1954
+ //#endregion
1955
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
1956
+ function e$6(e) {
1957
+ return () => e;
1958
+ }
1959
+ //#endregion
1960
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
1961
+ function t$2(...t) {
1962
+ return t$5(n$2, t);
1963
+ }
1964
+ const n$2 = (e, t) => e.length >= t;
1965
+ //#endregion
1966
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
1967
+ const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
1968
+ function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
1969
+ let c, l, u, d, f = () => {
1970
+ let t = u;
1971
+ t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
1972
+ }, p = () => {
1973
+ clearTimeout(l), l = void 0, c === void 0 && f();
1974
+ }, m = () => {
1975
+ clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
1976
+ };
1977
+ return {
1978
+ call: (...e) => {
1979
+ let t = c === void 0 && l === void 0;
1980
+ if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
1981
+ if (i !== void 0 || a !== void 0 || o === void 0) {
1982
+ clearTimeout(c);
1983
+ let e = Date.now();
1984
+ d ??= e;
1985
+ let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
1986
+ c = setTimeout(m, t);
2372
1987
  }
1988
+ r !== `end` && t && f();
2373
1989
  }
2374
- };
2375
- return LZString;
2376
- })();
2377
- if (typeof define === "function" && define.amd) define(function() {
2378
- return LZString;
1990
+ },
1991
+ cancel: () => {
1992
+ clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
1993
+ },
1994
+ flush: () => {
1995
+ m(), p();
1996
+ },
1997
+ get isIdle() {
1998
+ return c === void 0 && l === void 0;
1999
+ }
2000
+ };
2001
+ }
2002
+ //#endregion
2003
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
2004
+ function e$4(e) {
2005
+ return e !== void 0;
2006
+ }
2007
+ //#endregion
2008
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
2009
+ function e$3(e) {
2010
+ return (t) => !e(t);
2011
+ }
2012
+ //#endregion
2013
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
2014
+ function t(...t) {
2015
+ return t$5(n, t);
2016
+ }
2017
+ const n = (e, t) => e === t || Object.is(e, t);
2018
+ //#endregion
2019
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
2020
+ function e$2(e) {
2021
+ return typeof e == `string`;
2022
+ }
2023
+ //#endregion
2024
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
2025
+ function e$1(e) {
2026
+ return !!e;
2027
+ }
2028
+ //#endregion
2029
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
2030
+ function e(e) {
2031
+ let t = !1, n;
2032
+ return () => (t ||= (n = e(), !0), n);
2033
+ }
2034
+ var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
2035
+ CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
2036
+ CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
2037
+ CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
2038
+ CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
2039
+ CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
2040
+ CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
2041
+ CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
2042
+ CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
2043
+ CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
2044
+ CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
2045
+ CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
2046
+ return CloseCode2;
2047
+ })(CloseCode || {});
2048
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
2049
+ MessageType2["ConnectionInit"] = "connection_init";
2050
+ MessageType2["ConnectionAck"] = "connection_ack";
2051
+ MessageType2["Ping"] = "ping";
2052
+ MessageType2["Pong"] = "pong";
2053
+ MessageType2["Subscribe"] = "subscribe";
2054
+ MessageType2["Next"] = "next";
2055
+ MessageType2["Error"] = "error";
2056
+ MessageType2["Complete"] = "complete";
2057
+ return MessageType2;
2058
+ })(MessageType || {});
2059
+ Error;
2060
+ //#endregion
2061
+ //#region ../reactor-browser/dist/document-operations-BO-SlTDw.js
2062
+ const modalEventFunctions = makePHEventFunctions("modal");
2063
+ modalEventFunctions.useValue;
2064
+ /** Sets the current modal */
2065
+ const setPHModal = modalEventFunctions.setValue;
2066
+ modalEventFunctions.addEventHandler;
2067
+ /** Shows a modal */
2068
+ function showPHModal(modal) {
2069
+ setPHModal(modal);
2070
+ }
2071
+ /** Shows the delete node modal */
2072
+ function showDeleteNodeModal(nodeOrId) {
2073
+ setPHModal({
2074
+ type: "deleteItem",
2075
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2379
2076
  });
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;
2077
+ }
2078
+ function isDocumentTypeSupported(documentType, supportedDocuments) {
2079
+ if (!supportedDocuments?.length) return true;
2080
+ return supportedDocuments.some((pattern) => {
2081
+ if (pattern.endsWith("/*")) {
2082
+ const prefix = pattern.slice(0, -2);
2083
+ return documentType.startsWith(prefix + "/");
2084
+ }
2085
+ if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
2086
+ const prefix = pattern.slice(0, -1);
2087
+ return documentType.startsWith(prefix);
2088
+ }
2089
+ return pattern === documentType;
2383
2090
  });
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
- };
2091
+ }
2406
2092
  function getUserPermissions() {
2407
2093
  const user = window.ph?.renown?.user;
2408
2094
  const allowList = window.ph?.allowList;
@@ -2415,8 +2101,41 @@ function getUserPermissions() {
2415
2101
  isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2416
2102
  };
2417
2103
  }
2418
- const BASE_STATE_KEYS = new Set(["auth"]);
2419
2104
  const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2105
+ /** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
2106
+ async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
2107
+ const drive = await reactorClient.get(driveId);
2108
+ const nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);
2109
+ if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {
2110
+ isDuplicate: true,
2111
+ duplicateType: "id",
2112
+ nodeId: nodeById.id
2113
+ };
2114
+ const nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));
2115
+ if (nodeByNameAndType) return {
2116
+ isDuplicate: true,
2117
+ duplicateType: "name",
2118
+ nodeId: nodeByNameAndType.id
2119
+ };
2120
+ return { isDuplicate: false };
2121
+ }
2122
+ function getDocumentTypeIcon(document) {
2123
+ switch (document.header.documentType) {
2124
+ case "powerhouse/document-model": return "document-model";
2125
+ case "powerhouse/app": return "app";
2126
+ case "powerhouse/document-editor": return "editor";
2127
+ case "powerhouse/subgraph": return "subgraph";
2128
+ case "powerhouse/package": return "package";
2129
+ case "powerhouse/processor": {
2130
+ const processorType = document.state.global?.type;
2131
+ if (processorType === "analytics") return "analytics-processor";
2132
+ if (processorType === "relational") return "relational-processor";
2133
+ if (processorType === "codegen") return "codegen-processor";
2134
+ return;
2135
+ }
2136
+ default: return;
2137
+ }
2138
+ }
2420
2139
  async function downloadFile(document, fileName) {
2421
2140
  try {
2422
2141
  const data = await createZip(document);
@@ -2437,7 +2156,7 @@ async function getDocumentExtension(document) {
2437
2156
  let rawExtension;
2438
2157
  if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2439
2158
  else {
2440
- const reactorClient = window.ph?.reactorClient;
2159
+ const reactorClient = window.ph?.reactorClientModule?.client;
2441
2160
  if (reactorClient) {
2442
2161
  const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2443
2162
  rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
@@ -2451,7 +2170,7 @@ async function getDocumentExtension(document) {
2451
2170
  * composite cursors, so all scopes are fetched in a single paginated stream.
2452
2171
  */
2453
2172
  async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2454
- const scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));
2173
+ const scopes = Object.keys(document.state);
2455
2174
  const operations = {};
2456
2175
  for (const scope of scopes) operations[scope] = [];
2457
2176
  let cursor = "";
@@ -2479,6 +2198,67 @@ function extractInitialState(documentScopeOps) {
2479
2198
  function filterDomainOperations(operations) {
2480
2199
  return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2481
2200
  }
2201
+ function countOperations(operations) {
2202
+ let total = 0;
2203
+ for (const ops of Object.values(operations)) total += ops?.length ?? 0;
2204
+ return total;
2205
+ }
2206
+ /**
2207
+ * Split an imported document's domain operations at its mid-history upgrade
2208
+ * boundaries, so the caller can re-dispatch each upgrade between segments.
2209
+ *
2210
+ * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
2211
+ * path and must not be repeated. A later upgrade must be: it is where the
2212
+ * reducer version changes, and dropping it replays everything after it through
2213
+ * the module the document was created with.
2214
+ */
2215
+ function splitAtUpgradeBoundaries(operations) {
2216
+ 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);
2217
+ const domain = filterDomainOperations(operations);
2218
+ if (upgrades.length === 0) return [{ operations: domain }];
2219
+ const segments = [];
2220
+ const consumed = /* @__PURE__ */ new Map();
2221
+ const take = (until) => {
2222
+ const slice = {};
2223
+ for (const [scope, ops] of Object.entries(domain)) {
2224
+ if (!ops) continue;
2225
+ const from = consumed.get(scope) ?? 0;
2226
+ const stop = Math.max(from, until(scope, ops));
2227
+ const chunk = ops.slice(from, stop);
2228
+ if (chunk.length > 0) slice[scope] = chunk;
2229
+ consumed.set(scope, stop);
2230
+ }
2231
+ return slice;
2232
+ };
2233
+ for (const upgrade of upgrades) {
2234
+ const input = upgrade.action.input;
2235
+ const slice = take((scope, ops) => boundary(upgrade, scope, ops));
2236
+ segments.push({
2237
+ operations: slice,
2238
+ upgradeTo: input.toVersion
2239
+ });
2240
+ }
2241
+ const tail = take((_scope, ops) => ops.length);
2242
+ if (countOperations(tail) > 0) segments.push({ operations: tail });
2243
+ return segments;
2244
+ }
2245
+ /**
2246
+ * How many of a scope's operations precede an upgrade. Must stay identical to
2247
+ * the boundary computation in `replayDocumentVersioned` — snapshots compare
2248
+ * against operation indices, not array positions, and the timestamp fallback
2249
+ * excludes the upgrade's own instant.
2250
+ */
2251
+ function boundary(upgrade, scope, ops) {
2252
+ const snapshot = upgrade.action.input.revision;
2253
+ if (snapshot !== void 0) {
2254
+ const revision = snapshot[scope] ?? 0;
2255
+ let count = 0;
2256
+ for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
2257
+ return count;
2258
+ }
2259
+ for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
2260
+ return ops.length;
2261
+ }
2482
2262
  async function exportFile(document, suggestedName) {
2483
2263
  const reactorClient = window.ph?.reactorClient;
2484
2264
  if (!reactorClient) throw new Error("ReactorClient not initialized");
@@ -2508,7 +2288,7 @@ async function exportFile(document, suggestedName) {
2508
2288
  */
2509
2289
  async function loadFile(path) {
2510
2290
  const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2511
- const reactorClient = window.ph?.reactorClient;
2291
+ const reactorClient = window.ph?.reactorClientModule?.client;
2512
2292
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2513
2293
  const documentType = baseDocument.header.documentType;
2514
2294
  const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
@@ -2526,13 +2306,20 @@ async function loadFile(path) {
2526
2306
  upgradeManifest
2527
2307
  });
2528
2308
  }
2529
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2309
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
2530
2310
  const { isAllowedToCreateDocuments } = getUserPermissions();
2531
2311
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2532
- const reactorClient = window.ph?.reactorClient;
2312
+ const reactorClient = window.ph?.reactorClientModule?.client;
2533
2313
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2534
- const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2314
+ let documentModelModule;
2315
+ if (documentModelVersion !== void 0) {
2316
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2317
+ const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
2318
+ if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
2319
+ documentModelModule = module;
2320
+ } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2535
2321
  const newDocument = document ?? documentModelModule.utils.createDocument();
2322
+ if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
2536
2323
  newDocument.header.name = name;
2537
2324
  if (preferredEditor) newDocument.header.meta = {
2538
2325
  ...newDocument.header.meta,
@@ -2553,43 +2340,210 @@ async function addDocument(driveId, name, documentType, parentFolder, document,
2553
2340
  kind: "file"
2554
2341
  };
2555
2342
  }
2556
- async function addFile(file, driveId, name, parentFolder) {
2557
- logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2343
+ /**
2344
+ * How many ids an import will try before giving up. The check before the create
2345
+ * catches an id that is already taken; this bound covers the window between the
2346
+ * two, where a create can still lose to a claim made in the meantime.
2347
+ */
2348
+ const IMPORT_ID_ATTEMPTS = 3;
2349
+ /** True when this error, or anything it wraps, is a taken document id. */
2350
+ function isDocumentAlreadyExists(error) {
2351
+ let current = error;
2352
+ while (current instanceof Error) {
2353
+ if (current.name === "DocumentAlreadyExistsError") return true;
2354
+ current = current.cause;
2355
+ }
2356
+ return false;
2357
+ }
2358
+ /**
2359
+ * Creates the imported document under an id that is free, retrying on a
2360
+ * collision.
2361
+ *
2362
+ * The check cannot stand on its own: it answers for the moment it ran, and the
2363
+ * create that follows can still land on an id claimed in between. The store
2364
+ * rejects that create as DocumentAlreadyExistsError, which is not retryable
2365
+ * under the same id and is resolved by minting another one. A create that
2366
+ * fails leaves the drive untouched, so a retry has nothing to clean up.
2367
+ */
2368
+ async function createImportedDocument(reactor, document, driveId, name, parentFolder) {
2369
+ let documentId = await reactor.isDocumentIdTaken(document.header.id) ? generateId() : document.header.id;
2370
+ for (let attempt = 1;; attempt++) {
2371
+ const header = createPresignedHeader(documentId, document.header.documentType);
2372
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2373
+ header.meta = document.header.meta;
2374
+ header.name = name || document.header.name;
2375
+ const initialDocument = {
2376
+ ...document,
2377
+ header,
2378
+ state: document.initialState,
2379
+ operations: Object.keys(document.operations).reduce((acc, key) => {
2380
+ acc[key] = [];
2381
+ return acc;
2382
+ }, {})
2383
+ };
2384
+ try {
2385
+ const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2386
+ if (!fileNode) throw new Error("There was an error adding file");
2387
+ return {
2388
+ documentId,
2389
+ fileNode
2390
+ };
2391
+ } catch (error) {
2392
+ if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;
2393
+ logger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);
2394
+ documentId = generateId();
2395
+ }
2396
+ }
2397
+ }
2398
+ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2399
+ logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2400
+ const reactor = window.ph?.reactorClientModule?.client;
2401
+ if (!reactor) {
2402
+ onProgress?.({
2403
+ stage: "failed",
2404
+ progress: 100,
2405
+ error: "ReactorClient not initialized"
2406
+ });
2407
+ throw new Error("ReactorClient not initialized");
2408
+ }
2558
2409
  const { isAllowedToCreateDocuments } = getUserPermissions();
2559
2410
  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
2411
  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);
2412
+ onProgress?.({
2413
+ stage: "loading",
2414
+ progress: 0
2415
+ });
2416
+ let document;
2417
+ try {
2418
+ document = await loadFile(file);
2419
+ } catch (loadError) {
2420
+ if (UnsupportedDocumentModelVersionError.isError(loadError)) {
2421
+ showPHModal({
2422
+ type: "documentVersionUnsupported",
2423
+ documentType: loadError.documentType,
2424
+ requiredVersion: loadError.requiredVersion,
2425
+ availableVersions: loadError.availableVersions
2426
+ });
2427
+ onProgress?.({
2428
+ stage: "failed",
2429
+ progress: 100,
2430
+ error: loadError.message
2431
+ });
2432
+ return;
2433
+ }
2434
+ const discoveryService = window.ph?.packageDiscoveryService;
2435
+ if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
2436
+ retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
2437
+ logger.error("Import retry after discovery failed: @error", retryError);
2438
+ onProgress?.({
2439
+ stage: "failed",
2440
+ progress: 100,
2441
+ error: retryError instanceof Error ? retryError.message : String(retryError)
2442
+ });
2443
+ });
2444
+ return;
2445
+ }
2446
+ throw loadError;
2447
+ }
2448
+ const duplicateCheck = await isDocumentInLocation(reactor, document, driveId, parentFolder);
2449
+ if (duplicateCheck.isDuplicate && !resolveConflict) {
2450
+ onProgress?.({
2451
+ stage: "conflict",
2452
+ progress: 0,
2453
+ duplicateType: duplicateCheck.duplicateType
2454
+ });
2455
+ return;
2456
+ }
2457
+ const documentType = getDocumentTypeIcon(document);
2458
+ if (documentType) onProgress?.({
2459
+ stage: "loading",
2460
+ progress: 10,
2461
+ documentType
2462
+ });
2463
+ else onProgress?.({
2464
+ stage: "loading",
2465
+ progress: 10
2466
+ });
2467
+ if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
2468
+ onProgress?.({
2469
+ stage: "unsupported-document-type",
2470
+ progress: 100,
2471
+ error: `Document type ${document.header.documentType} is not supported`
2472
+ });
2473
+ throw new UnsupportedDocumentTypeError(document.header.documentType);
2474
+ }
2475
+ await reactor.getDocumentModelModule(document.header.documentType);
2476
+ onProgress?.({
2477
+ stage: "initializing",
2478
+ progress: 10
2479
+ });
2480
+ const created = await createImportedDocument(reactor, document, driveId, name, parentFolder);
2481
+ const documentId = created.documentId;
2482
+ const fileNode = created.fileNode;
2483
+ onProgress?.({
2484
+ stage: "initializing",
2485
+ progress: 20
2486
+ });
2487
+ await reactor.get(documentId);
2488
+ console.log("Document created, starting upload of operations");
2489
+ const segments = splitAtUpgradeBoundaries(document.operations);
2490
+ const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
2491
+ let uploadedBefore = 0;
2492
+ for (const segment of segments) {
2493
+ await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
2494
+ if (uploadProgress.uploadedOperations === void 0) return;
2495
+ const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
2496
+ const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
2497
+ onProgress?.({
2498
+ stage: "uploading",
2499
+ progress: 20 + Math.round(uploadPercent * 80),
2500
+ totalOperations,
2501
+ uploadedOperations: uploaded
2502
+ });
2503
+ } });
2504
+ uploadedBefore += countOperations(segment.operations);
2505
+ if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
2506
+ }
2507
+ onProgress?.({
2508
+ stage: "complete",
2509
+ progress: 100,
2510
+ fileNode
2511
+ });
2512
+ return fileNode;
2513
+ } catch (error) {
2514
+ if (!UnsupportedDocumentTypeError.isError(error)) {
2515
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
2516
+ onProgress?.({
2517
+ stage: "failed",
2518
+ progress: 100,
2519
+ error: errorMessage
2520
+ });
2521
+ }
2522
+ throw error;
2523
+ }
2524
+ }
2525
+ async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2526
+ if (!discoveryService) return;
2527
+ try {
2528
+ await discoveryService.load(documentType);
2529
+ } catch {
2530
+ onProgress?.({
2531
+ stage: "unsupported-document-type",
2532
+ progress: 100,
2533
+ error: `Document type ${documentType} is not supported`
2534
+ });
2535
+ return;
2536
+ }
2537
+ await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
2584
2538
  }
2585
- async function addFolder(driveId, name, parentFolder) {
2539
+ async function addFolder$1(driveId, name, parentFolder) {
2586
2540
  const { isAllowedToCreateDocuments } = getUserPermissions();
2587
2541
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2588
2542
  const reactorClient = window.ph?.reactorClient;
2589
2543
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2590
2544
  await reactorClient.get(driveId);
2591
2545
  const folderId = generateId();
2592
- const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2546
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
2593
2547
  id: folderId,
2594
2548
  name,
2595
2549
  parentFolder
@@ -2667,10 +2621,12 @@ async function _duplicateDocument(reactor, document, newId = generateId()) {
2667
2621
  upgradeManifest
2668
2622
  };
2669
2623
  const header = createPresignedHeader(newId, documentType);
2670
- return replayDocumentVersioned(document.initialState, document.operations, config, header);
2624
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2625
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2626
+ return duplicated;
2671
2627
  }
2672
2628
  async function copyNode$1(driveId, src, target) {
2673
- const reactor = window.ph?.reactorClient;
2629
+ const reactor = window.ph?.reactorClientModule?.client;
2674
2630
  if (!reactor) return;
2675
2631
  const { isAllowedToCreateDocuments } = getUserPermissions();
2676
2632
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
@@ -2693,45 +2649,88 @@ async function copyNode$1(driveId, src, target) {
2693
2649
  resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2694
2650
  }
2695
2651
  }
2696
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2697
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2698
- return node !== void 0 && isFileNode(node);
2699
- });
2700
- for (const fileNodeToCopy of fileNodesToCopy) try {
2701
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2702
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2703
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2704
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2705
- } catch (e) {
2706
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2707
- }
2708
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2709
- }
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
2652
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2653
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2654
+ return node !== void 0 && isFileNode(node);
2731
2655
  });
2656
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2657
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2658
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2659
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2660
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2661
+ } catch (e) {
2662
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2663
+ }
2664
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2732
2665
  }
2733
- /** Document types that represent a "drive": a container of nodes. */
2734
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
2666
+ /**
2667
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
2668
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
2669
+ */
2670
+ const ReactorOperationFieldsFragmentDoc = import_main.gql`
2671
+ fragment ReactorOperationFields on ReactorOperation {
2672
+ index
2673
+ timestampUtcMs
2674
+ hash
2675
+ skip
2676
+ error
2677
+ deniedReason
2678
+ id
2679
+ action {
2680
+ id
2681
+ type
2682
+ timestampUtcMs
2683
+ input
2684
+ scope
2685
+ context {
2686
+ signer {
2687
+ user {
2688
+ address
2689
+ networkId
2690
+ chainId
2691
+ }
2692
+ app {
2693
+ name
2694
+ key
2695
+ }
2696
+ signatures
2697
+ }
2698
+ }
2699
+ }
2700
+ }
2701
+ `;
2702
+ import_main.gql`
2703
+ mutation MutateDocumentWithOperations(
2704
+ $documentIdentifier: String!
2705
+ $actions: [ActionInput!]!
2706
+ $sinceRevision: Int
2707
+ $scopes: [String!]
2708
+ $branch: String
2709
+ ) {
2710
+ mutateDocument: execute(
2711
+ documentIdentifier: $documentIdentifier
2712
+ actions: $actions
2713
+ branch: $branch
2714
+ ) {
2715
+ ...PHDocumentFields
2716
+ operations(
2717
+ filter: {
2718
+ sinceRevision: $sinceRevision
2719
+ scopes: $scopes
2720
+ branch: $branch
2721
+ }
2722
+ ) {
2723
+ items {
2724
+ ...ReactorOperationFields
2725
+ }
2726
+ }
2727
+ }
2728
+ }
2729
+ ${PhDocumentFieldsFragmentDoc}
2730
+ ${ReactorOperationFieldsFragmentDoc}
2731
+ `;
2732
+ 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;
2733
+ PropagationMode.Cascade, PropagationMode.Orphan;
2735
2734
  const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2736
2735
  /** Sets whether external controls are enabled for a given editor. */
2737
2736
  const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
@@ -2797,6 +2796,8 @@ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabl
2797
2796
  const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2798
2797
  const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2799
2798
  const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2799
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
2800
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
2800
2801
  const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2801
2802
  const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2802
2803
  const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
@@ -2894,6 +2895,8 @@ const nonUserConfigSetters = {
2894
2895
  renownUrl: setRenownUrl,
2895
2896
  renownNetworkId: setRenownNetworkId,
2896
2897
  renownChainId: setRenownChainId,
2898
+ switchboardUrl: setSwitchboardUrl,
2899
+ renownAdapters: setRenownAdapters,
2897
2900
  sentryRelease: setSentryRelease,
2898
2901
  sentryDsn: setSentryDsn,
2899
2902
  sentryEnv: setSentryEnv,
@@ -2942,6 +2945,8 @@ const nonUserConfigHooks = {
2942
2945
  renownUrl: useRenownUrl,
2943
2946
  renownNetworkId: useRenownNetworkId,
2944
2947
  renownChainId: useRenownChainId,
2948
+ switchboardUrl: useSwitchboardUrl,
2949
+ renownAdapters: useRenownAdapters,
2945
2950
  sentryRelease: useSentryRelease,
2946
2951
  sentryDsn: useSentryDsn,
2947
2952
  sentryEnv: useSentryEnv,
@@ -2971,366 +2976,884 @@ const featuresEventFunctions = makePHEventFunctions("features");
2971
2976
  featuresEventFunctions.useValue;
2972
2977
  featuresEventFunctions.setValue;
2973
2978
  featuresEventFunctions.addEventHandler;
2974
- function resolveUrlPathname(path) {
2975
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2979
+ function useDropTarget() {
2980
+ const [isDropTarget, setIsDropTarget] = useState(false);
2981
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2982
+ const targetSetter = n$1(() => setIsDropTarget(true), {
2983
+ triggerAt: "start",
2984
+ minQuietPeriodMs: 100
2985
+ });
2986
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
2987
+ triggerAt: "start",
2988
+ minQuietPeriodMs: 100
2989
+ });
2990
+ function setTarget() {
2991
+ if (!isDragAndDropEnabled) return;
2992
+ targetUnsetter.cancel();
2993
+ targetSetter.call();
2994
+ }
2995
+ function unsetTarget() {
2996
+ if (!isDragAndDropEnabled) return;
2997
+ targetSetter.cancel();
2998
+ targetUnsetter.call();
2999
+ }
3000
+ return {
3001
+ isDropTarget,
3002
+ setTarget,
3003
+ unsetTarget
3004
+ };
2976
3005
  }
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("/") ? "/" : "");
3006
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3007
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
3008
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
3009
+ draggingNodeEventFunctions.addEventHandler;
3010
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3011
+ reducer: (_, newNode) => newNode,
3012
+ triggerAt: "start",
3013
+ minQuietPeriodMs: 100
3014
+ });
3015
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3016
+ triggerAt: "start",
3017
+ minQuietPeriodMs: 100
3018
+ });
3019
+ function setDragging(node) {
3020
+ draggingNodeUnsetter.cancel();
3021
+ draggingNodeSetter.call(node);
2981
3022
  }
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}`);
3023
+ function unsetDragging() {
3024
+ draggingNodeSetter.cancel();
3025
+ draggingNodeUnsetter.call();
2988
3026
  }
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];
3027
+ 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));
3028
+ function useDragNode(args) {
3029
+ const { srcId, parentId } = args;
3030
+ const driveId = useSelectedDriveId();
3031
+ const draggingNodeId = useDraggingNode()?.srcId;
3032
+ const params = {
3033
+ driveId,
3034
+ srcId,
3035
+ parentId
3036
+ };
3037
+ const draggable = isNodeDrag(params);
3038
+ const isDragging = t$4({
3039
+ srcId,
3040
+ draggingNodeId
3041
+ }, [
3042
+ () => draggable,
3043
+ ({ srcId }) => e$2(srcId),
3044
+ ({ draggingNodeId }) => e$2(draggingNodeId),
3045
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3046
+ ]);
3047
+ const onDragStart = () => {
3048
+ if (!draggable) return;
3049
+ setDragging(params);
3050
+ };
3051
+ const onDragEnd = () => {
3052
+ if (!draggable) return;
3053
+ unsetDragging();
3054
+ };
3055
+ return {
3056
+ isDragging,
3057
+ draggable,
3058
+ onDragStart,
3059
+ onDragEnd
3060
+ };
2996
3061
  }
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];
3062
+ 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));
3063
+ function useDropNode(targetId) {
3064
+ const driveId = useSelectedDriveId();
3065
+ const { srcId, parentId } = useDraggingNode() ?? {};
3066
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3067
+ const params = {
3068
+ driveId,
3069
+ parentId,
3070
+ targetId,
3071
+ srcId
3072
+ };
3073
+ function handleNodeDrop(event, cb) {
3074
+ if (!isNodeDrop(params)) return;
3075
+ event.preventDefault();
3076
+ event.stopPropagation();
3077
+ cb?.();
3078
+ }
3079
+ const onDragEnter = (event) => handleNodeDrop(event);
3080
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3081
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3082
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
3083
+ unsetDragging();
3084
+ unsetTarget();
3085
+ moveNodeById(params).catch(console.error);
3086
+ }));
3087
+ return {
3088
+ isDropTarget,
3089
+ onDragEnter,
3090
+ onDragOver,
3091
+ onDragLeave,
3092
+ onDrop
3093
+ };
3001
3094
  }
3002
- function extractNodeIdFromSlug(nodeSlug) {
3003
- return findUuid(nodeSlug);
3095
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3096
+ graphQLReactorClientEventFunctions.useValue;
3097
+ graphQLReactorClientEventFunctions.setValue;
3098
+ graphQLReactorClientEventFunctions.addEventHandler;
3099
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3100
+ packageDiscoveryFunctions.useValue;
3101
+ packageDiscoveryFunctions.setValue;
3102
+ packageDiscoveryFunctions.addEventHandler;
3103
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3104
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3105
+ /** Returns the reactor client module (in-process or worker-backed) */
3106
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3107
+ reactorClientModuleEventFunctions.setValue;
3108
+ reactorClientModuleEventFunctions.addEventHandler;
3109
+ reactorClientEventFunctions.useValue;
3110
+ reactorClientEventFunctions.setValue;
3111
+ reactorClientEventFunctions.addEventHandler;
3112
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3113
+ const useSyncList = () => {
3114
+ return useSync()?.list() ?? [];
3115
+ };
3116
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
3117
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3118
+ revisionHistoryEventFunctions.useValue;
3119
+ /** Sets revision history visibility */
3120
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3121
+ revisionHistoryEventFunctions.addEventHandler;
3122
+ /** Shows the revision history */
3123
+ function showRevisionHistory() {
3124
+ setRevisionHistoryVisible(true);
3004
3125
  }
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] ?? "";
3126
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3127
+ selectedTimelineItemEventFunctions.useValue;
3128
+ selectedTimelineItemEventFunctions.setValue;
3129
+ selectedTimelineItemEventFunctions.addEventHandler;
3130
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3131
+ selectedTimelineRevisionEventFunctions.useValue;
3132
+ selectedTimelineRevisionEventFunctions.setValue;
3133
+ selectedTimelineRevisionEventFunctions.addEventHandler;
3134
+ const toastEventFunctions = makePHEventFunctions("toast");
3135
+ /** Returns the toast function */
3136
+ const usePHToast = toastEventFunctions.useValue;
3137
+ toastEventFunctions.setValue;
3138
+ toastEventFunctions.addEventHandler;
3139
+ //#endregion
3140
+ //#region ../reactor-browser/dist/selected-document-xFBNPc9Q.js
3141
+ /** Returns a document of a specific type, throws an error if the found document has a different type */
3142
+ function useDocumentOfType(documentId, documentType) {
3143
+ const [document, dispatch] = useDocumentById(documentId);
3144
+ const documentModelModule = useDocumentModelModuleById(documentType);
3145
+ if (!documentId || !documentType) return [];
3146
+ if (!document) throw new Error(`Document not found: ${documentId}`);
3147
+ if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3148
+ if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3149
+ return [document, dispatch];
3012
3150
  }
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;
3151
+ /** Returns the selected document id */
3152
+ function useSelectedDocumentId() {
3153
+ const selectedNode = useSelectedNode();
3154
+ return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3155
+ }
3156
+ /** Returns the selected document. */
3157
+ function useSelectedDocumentSafe() {
3158
+ return useDocumentById(useSelectedDocumentId());
3159
+ }
3160
+ function useSelectedDocumentOfType(documentType) {
3161
+ const documentId = useSelectedDocumentId();
3162
+ if (!documentType) return [];
3163
+ if (!documentId) throw new NoSelectedDocumentError();
3164
+ return useDocumentOfType(documentId, documentType);
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));
3166
+ //#endregion
3167
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
3168
+ const normalizeDescriptors = (error) => {
3169
+ CORE_ERROR_PROPS.forEach((propName) => {
3170
+ normalizeDescriptor(error, propName);
3171
+ });
3172
+ };
3173
+ const CORE_ERROR_PROPS = [
3174
+ "name",
3175
+ "message",
3176
+ "stack",
3177
+ "cause",
3178
+ "errors"
3179
+ ];
3180
+ const normalizeDescriptor = (error, propName) => {
3181
+ const descriptor = getDescriptor(error, propName);
3182
+ if (descriptor === void 0) return;
3183
+ if (isReadonlyGetter(descriptor)) {
3184
+ setErrorProperty(error, propName, error[propName]);
3040
3185
  return;
3041
3186
  }
3042
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
3043
- if (pathname === window.location.pathname) return;
3044
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3045
- }
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];
3187
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
3188
+ };
3189
+ const getDescriptor = (value, propName) => {
3190
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
3191
+ if (descriptor !== void 0) return descriptor;
3192
+ const prototype = Object.getPrototypeOf(value);
3193
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
3194
+ };
3195
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
3196
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
3197
+ const setErrorProperty = (error, propName, value) => {
3198
+ setErrorDescriptor(error, propName, { value });
3199
+ };
3200
+ const setErrorDescriptor = (error, propName, descriptor) => {
3201
+ Object.defineProperty(error, propName, {
3202
+ ...descriptor,
3203
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
3204
+ enumerable: false,
3205
+ configurable: true
3206
+ });
3207
+ };
3208
+ //#endregion
3209
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
3210
+ const normalizeAggregate = (error, recurse) => {
3211
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
3212
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
3213
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
3214
+ };
3215
+ const isDefined = (error) => error !== void 0;
3216
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
3217
+ const deleteAggregateErrors = (error) => {
3218
+ delete error.errors;
3219
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
3220
+ };
3221
+ //#endregion
3222
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
3223
+ const normalizeCause = (error, recurse) => {
3224
+ if (!("cause" in error)) return;
3225
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
3226
+ if (cause === void 0) delete error.cause;
3227
+ else setErrorProperty(error, "cause", cause);
3228
+ };
3229
+ //#endregion
3230
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
3231
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
3232
+ const isInstanceOfError = (value) => {
3233
+ try {
3234
+ return value instanceof Error;
3235
+ } catch {
3236
+ return false;
3237
+ }
3238
+ };
3239
+ const hasErrorTag = (value) => {
3240
+ try {
3241
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
3242
+ } catch {
3243
+ return false;
3244
+ }
3245
+ };
3246
+ const ERROR_TAGS = new Set([
3247
+ "[object Error]",
3248
+ "[object DOMException]",
3249
+ "[object DOMError]",
3250
+ "[object Exception]"
3251
+ ]);
3252
+ //#endregion
3253
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
3254
+ function isPlainObject(value) {
3255
+ if (typeof value !== "object" || value === null) return false;
3256
+ const prototype = Object.getPrototypeOf(value);
3257
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3059
3258
  }
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);
3067
- return;
3259
+ //#endregion
3260
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
3261
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
3262
+ const isNonConfigurableProp = (error, propName) => {
3263
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
3264
+ return descriptor !== void 0 && !descriptor.configurable;
3265
+ };
3266
+ const isThrowingProp = (error, propName) => {
3267
+ try {
3268
+ error[propName];
3269
+ return false;
3270
+ } catch {
3271
+ return true;
3068
3272
  }
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;
3273
+ };
3274
+ //#endregion
3275
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
3276
+ const setStack = (error) => {
3277
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
3278
+ };
3279
+ const getStack = (message = "", name = "Error") => {
3280
+ const { stack } = new (getErrorClass(name))(message);
3281
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
3282
+ };
3283
+ const getErrorClass = (name) => {
3284
+ const descriptor = {
3285
+ value: name,
3286
+ enumerable: false,
3287
+ writable: true,
3288
+ configurable: true
3289
+ };
3290
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
3291
+ Object.defineProperty(StackError.prototype, "name", descriptor);
3292
+ return StackError;
3293
+ };
3294
+ //#endregion
3295
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
3296
+ const copyObject = (object) => {
3297
+ const objectCopy = {};
3298
+ for (const propName of getPropsToCopy(object)) try {
3299
+ const value = object[propName];
3300
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
3301
+ Object.defineProperty(objectCopy, propName, {
3302
+ value,
3303
+ enumerable,
3304
+ configurable,
3305
+ writable
3306
+ });
3307
+ } catch {}
3308
+ return objectCopy;
3309
+ };
3310
+ const getPropsToCopy = (object) => {
3311
+ const propNames = getOwnKeys(object);
3312
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
3313
+ return propNames;
3314
+ };
3315
+ const getOwnKeys = (object) => {
3316
+ try {
3317
+ return Reflect.ownKeys(object);
3318
+ } catch {
3319
+ return [];
3320
+ }
3321
+ };
3322
+ const isInheritedProp = (object, propName) => {
3323
+ try {
3324
+ return propName in object && !Object.hasOwn(object, propName);
3325
+ } catch {
3326
+ return false;
3327
+ }
3328
+ };
3329
+ //#endregion
3330
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
3331
+ const objectifyError = (object) => {
3332
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
3333
+ const messageA = getMessage(message, objectA);
3334
+ const error = newError(name, messageA);
3335
+ if (message === messageA) assignObjectProps(error, objectA);
3336
+ Object.entries({
3337
+ name,
3338
+ stack,
3339
+ cause,
3340
+ errors
3341
+ }).forEach(([propName, propValue]) => {
3342
+ setNewErrorProperty(error, propName, propValue);
3343
+ });
3344
+ if (stack === void 0) setStack(error);
3345
+ return error;
3346
+ };
3347
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
3348
+ const safeJsonStringify = (object) => {
3349
+ try {
3350
+ return JSON.stringify(object);
3351
+ } catch {
3352
+ return safeStringify(object);
3353
+ }
3354
+ };
3355
+ const safeStringify = (object) => {
3356
+ try {
3357
+ return String(object);
3358
+ } catch {
3359
+ return "Invalid error";
3360
+ }
3361
+ };
3362
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
3363
+ const MESSAGE_MAX_SIZE = 1e3;
3364
+ const newError = (name, message) => {
3365
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
3366
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
3367
+ return new Error(message);
3368
+ };
3369
+ const NATIVE_ERRORS = {
3370
+ Error,
3371
+ ReferenceError,
3372
+ TypeError,
3373
+ SyntaxError,
3374
+ RangeError,
3375
+ URIError,
3376
+ EvalError
3377
+ };
3378
+ const assignObjectProps = (error, object) => {
3379
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3380
+ };
3381
+ const setNewErrorProperty = (error, propName, propValue) => {
3382
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3383
+ };
3384
+ //#endregion
3385
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3386
+ const stringifyError = (value) => {
3387
+ try {
3388
+ const error = new Error(String(value));
3389
+ setStack(error);
3390
+ return error;
3391
+ } catch (error_) {
3392
+ return error_;
3076
3393
  }
3077
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
3078
- if (pathname === window.location.pathname) return;
3079
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3080
- }
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
- }
3093
- });
3094
- }
3095
- let pendingHandler;
3096
- let pendingTimeout;
3097
- function cancelPendingDriveSelection() {
3098
- if (pendingHandler) {
3099
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
3100
- pendingHandler = void 0;
3394
+ };
3395
+ //#endregion
3396
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3397
+ const { toString: objectToString } = Object.prototype;
3398
+ const createError = (value) => {
3399
+ if (isErrorPlainObj(value)) return objectifyError(value);
3400
+ if (!isErrorInstance(value)) return stringifyError(value);
3401
+ if (isInvalidError(value)) return objectifyError(value);
3402
+ return value;
3403
+ };
3404
+ const isErrorPlainObj = (value) => {
3405
+ try {
3406
+ return isPlainObject(value);
3407
+ } catch {
3408
+ return false;
3101
3409
  }
3102
- if (pendingTimeout) {
3103
- clearTimeout(pendingTimeout);
3104
- pendingTimeout = void 0;
3410
+ };
3411
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3412
+ const isProxy = (value) => {
3413
+ try {
3414
+ return objectToString.call(value) === "[object Object]";
3415
+ } catch {
3416
+ return true;
3105
3417
  }
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;
3418
+ };
3419
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3420
+ //#endregion
3421
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3422
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3423
+ const recurseException = (error, parents, shallow) => {
3424
+ if (parents.includes(error)) return;
3425
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3426
+ const errorA = createError(error);
3427
+ normalizeProps(errorA, recurse);
3428
+ return errorA;
3429
+ };
3430
+ const identity = (error) => error;
3431
+ const normalizeProps = (error, recurse) => {
3432
+ normalizeName(error);
3433
+ normalizeMessage(error);
3434
+ normalizeStack(error);
3435
+ normalizeCause(error, recurse);
3436
+ normalizeAggregate(error, recurse);
3437
+ normalizeDescriptors(error);
3438
+ };
3439
+ const normalizeName = (error) => {
3440
+ if (isDefinedString(error.name)) return;
3441
+ const prototypeName = Object.getPrototypeOf(error).name;
3442
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3443
+ };
3444
+ const normalizeMessage = (error) => {
3445
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3446
+ };
3447
+ const normalizeStack = (error) => {
3448
+ if (!isDefinedString(error.stack)) setStack(error);
3449
+ };
3450
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
3451
+ //#endregion
3452
+ //#region ../reactor-browser/dist/index.js
3453
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3454
+ var LZString = (function() {
3455
+ var f = String.fromCharCode;
3456
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3457
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3458
+ var baseReverseDic = {};
3459
+ function getBaseValue(alphabet, character) {
3460
+ if (!baseReverseDic[alphabet]) {
3461
+ baseReverseDic[alphabet] = {};
3462
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3463
+ }
3464
+ return baseReverseDic[alphabet][character];
3465
+ }
3466
+ var LZString = {
3467
+ compressToBase64: function(input) {
3468
+ if (input == null) return "";
3469
+ var res = LZString._compress(input, 6, function(a) {
3470
+ return keyStrBase64.charAt(a);
3471
+ });
3472
+ switch (res.length % 4) {
3473
+ default:
3474
+ case 0: return res;
3475
+ case 1: return res + "===";
3476
+ case 2: return res + "==";
3477
+ case 3: return res + "=";
3478
+ }
3479
+ },
3480
+ decompressFromBase64: function(input) {
3481
+ if (input == null) return "";
3482
+ if (input == "") return null;
3483
+ return LZString._decompress(input.length, 32, function(index) {
3484
+ return getBaseValue(keyStrBase64, input.charAt(index));
3485
+ });
3486
+ },
3487
+ compressToUTF16: function(input) {
3488
+ if (input == null) return "";
3489
+ return LZString._compress(input, 15, function(a) {
3490
+ return f(a + 32);
3491
+ }) + " ";
3492
+ },
3493
+ decompressFromUTF16: function(compressed) {
3494
+ if (compressed == null) return "";
3495
+ if (compressed == "") return null;
3496
+ return LZString._decompress(compressed.length, 16384, function(index) {
3497
+ return compressed.charCodeAt(index) - 32;
3498
+ });
3499
+ },
3500
+ compressToUint8Array: function(uncompressed) {
3501
+ var compressed = LZString.compress(uncompressed);
3502
+ var buf = new Uint8Array(compressed.length * 2);
3503
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3504
+ var current_value = compressed.charCodeAt(i);
3505
+ buf[i * 2] = current_value >>> 8;
3506
+ buf[i * 2 + 1] = current_value % 256;
3507
+ }
3508
+ return buf;
3509
+ },
3510
+ decompressFromUint8Array: function(compressed) {
3511
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3512
+ else {
3513
+ var buf = new Array(compressed.length / 2);
3514
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3515
+ var result = [];
3516
+ buf.forEach(function(c) {
3517
+ result.push(f(c));
3518
+ });
3519
+ return LZString.decompress(result.join(""));
3520
+ }
3521
+ },
3522
+ compressToEncodedURIComponent: function(input) {
3523
+ if (input == null) return "";
3524
+ return LZString._compress(input, 6, function(a) {
3525
+ return keyStrUriSafe.charAt(a);
3526
+ });
3527
+ },
3528
+ decompressFromEncodedURIComponent: function(input) {
3529
+ if (input == null) return "";
3530
+ if (input == "") return null;
3531
+ input = input.replace(/ /g, "+");
3532
+ return LZString._decompress(input.length, 32, function(index) {
3533
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
3534
+ });
3535
+ },
3536
+ compress: function(uncompressed) {
3537
+ return LZString._compress(uncompressed, 16, function(a) {
3538
+ return f(a);
3539
+ });
3540
+ },
3541
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3542
+ if (uncompressed == null) return "";
3543
+ 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;
3544
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
3545
+ context_c = uncompressed.charAt(ii);
3546
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3547
+ context_dictionary[context_c] = context_dictSize++;
3548
+ context_dictionaryToCreate[context_c] = true;
3549
+ }
3550
+ context_wc = context_w + context_c;
3551
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3552
+ else {
3553
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3554
+ if (context_w.charCodeAt(0) < 256) {
3555
+ for (i = 0; i < context_numBits; i++) {
3556
+ context_data_val = context_data_val << 1;
3557
+ if (context_data_position == bitsPerChar - 1) {
3558
+ context_data_position = 0;
3559
+ context_data.push(getCharFromInt(context_data_val));
3560
+ context_data_val = 0;
3561
+ } else context_data_position++;
3562
+ }
3563
+ value = context_w.charCodeAt(0);
3564
+ for (i = 0; i < 8; i++) {
3565
+ context_data_val = context_data_val << 1 | value & 1;
3566
+ if (context_data_position == bitsPerChar - 1) {
3567
+ context_data_position = 0;
3568
+ context_data.push(getCharFromInt(context_data_val));
3569
+ context_data_val = 0;
3570
+ } else context_data_position++;
3571
+ value = value >> 1;
3572
+ }
3573
+ } else {
3574
+ value = 1;
3575
+ for (i = 0; i < context_numBits; i++) {
3576
+ context_data_val = context_data_val << 1 | value;
3577
+ if (context_data_position == bitsPerChar - 1) {
3578
+ context_data_position = 0;
3579
+ context_data.push(getCharFromInt(context_data_val));
3580
+ context_data_val = 0;
3581
+ } else context_data_position++;
3582
+ value = 0;
3583
+ }
3584
+ value = context_w.charCodeAt(0);
3585
+ for (i = 0; i < 16; i++) {
3586
+ context_data_val = context_data_val << 1 | value & 1;
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 = value >> 1;
3593
+ }
3594
+ }
3595
+ context_enlargeIn--;
3596
+ if (context_enlargeIn == 0) {
3597
+ context_enlargeIn = Math.pow(2, context_numBits);
3598
+ context_numBits++;
3599
+ }
3600
+ delete context_dictionaryToCreate[context_w];
3601
+ } else {
3602
+ value = context_dictionary[context_w];
3603
+ for (i = 0; i < context_numBits; i++) {
3604
+ context_data_val = context_data_val << 1 | value & 1;
3605
+ if (context_data_position == bitsPerChar - 1) {
3606
+ context_data_position = 0;
3607
+ context_data.push(getCharFromInt(context_data_val));
3608
+ context_data_val = 0;
3609
+ } else context_data_position++;
3610
+ value = value >> 1;
3611
+ }
3612
+ }
3613
+ context_enlargeIn--;
3614
+ if (context_enlargeIn == 0) {
3615
+ context_enlargeIn = Math.pow(2, context_numBits);
3616
+ context_numBits++;
3617
+ }
3618
+ context_dictionary[context_wc] = context_dictSize++;
3619
+ context_w = String(context_c);
3620
+ }
3621
+ }
3622
+ if (context_w !== "") {
3623
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3624
+ if (context_w.charCodeAt(0) < 256) {
3625
+ for (i = 0; i < context_numBits; i++) {
3626
+ context_data_val = context_data_val << 1;
3627
+ if (context_data_position == bitsPerChar - 1) {
3628
+ context_data_position = 0;
3629
+ context_data.push(getCharFromInt(context_data_val));
3630
+ context_data_val = 0;
3631
+ } else context_data_position++;
3632
+ }
3633
+ value = context_w.charCodeAt(0);
3634
+ for (i = 0; i < 8; i++) {
3635
+ context_data_val = context_data_val << 1 | value & 1;
3636
+ if (context_data_position == bitsPerChar - 1) {
3637
+ context_data_position = 0;
3638
+ context_data.push(getCharFromInt(context_data_val));
3639
+ context_data_val = 0;
3640
+ } else context_data_position++;
3641
+ value = value >> 1;
3642
+ }
3643
+ } else {
3644
+ value = 1;
3645
+ for (i = 0; i < context_numBits; i++) {
3646
+ context_data_val = context_data_val << 1 | value;
3647
+ if (context_data_position == bitsPerChar - 1) {
3648
+ context_data_position = 0;
3649
+ context_data.push(getCharFromInt(context_data_val));
3650
+ context_data_val = 0;
3651
+ } else context_data_position++;
3652
+ value = 0;
3653
+ }
3654
+ value = context_w.charCodeAt(0);
3655
+ for (i = 0; i < 16; i++) {
3656
+ context_data_val = context_data_val << 1 | value & 1;
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 = value >> 1;
3663
+ }
3664
+ }
3665
+ context_enlargeIn--;
3666
+ if (context_enlargeIn == 0) {
3667
+ context_enlargeIn = Math.pow(2, context_numBits);
3668
+ context_numBits++;
3669
+ }
3670
+ delete context_dictionaryToCreate[context_w];
3671
+ } else {
3672
+ value = context_dictionary[context_w];
3673
+ for (i = 0; i < context_numBits; i++) {
3674
+ context_data_val = context_data_val << 1 | value & 1;
3675
+ if (context_data_position == bitsPerChar - 1) {
3676
+ context_data_position = 0;
3677
+ context_data.push(getCharFromInt(context_data_val));
3678
+ context_data_val = 0;
3679
+ } else context_data_position++;
3680
+ value = value >> 1;
3681
+ }
3682
+ }
3683
+ context_enlargeIn--;
3684
+ if (context_enlargeIn == 0) {
3685
+ context_enlargeIn = Math.pow(2, context_numBits);
3686
+ context_numBits++;
3687
+ }
3688
+ }
3689
+ value = 2;
3690
+ for (i = 0; i < context_numBits; i++) {
3691
+ context_data_val = context_data_val << 1 | value & 1;
3692
+ if (context_data_position == bitsPerChar - 1) {
3693
+ context_data_position = 0;
3694
+ context_data.push(getCharFromInt(context_data_val));
3695
+ context_data_val = 0;
3696
+ } else context_data_position++;
3697
+ value = value >> 1;
3698
+ }
3699
+ while (true) {
3700
+ context_data_val = context_data_val << 1;
3701
+ if (context_data_position == bitsPerChar - 1) {
3702
+ context_data.push(getCharFromInt(context_data_val));
3703
+ break;
3704
+ } else context_data_position++;
3705
+ }
3706
+ return context_data.join("");
3707
+ },
3708
+ decompress: function(compressed) {
3709
+ if (compressed == null) return "";
3710
+ if (compressed == "") return null;
3711
+ return LZString._decompress(compressed.length, 32768, function(index) {
3712
+ return compressed.charCodeAt(index);
3713
+ });
3714
+ },
3715
+ _decompress: function(length, resetValue, getNextValue) {
3716
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3717
+ val: getNextValue(0),
3718
+ position: resetValue,
3719
+ index: 1
3720
+ };
3721
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
3722
+ bits = 0;
3723
+ maxpower = Math.pow(2, 2);
3724
+ power = 1;
3725
+ while (power != maxpower) {
3726
+ resb = data.val & data.position;
3727
+ data.position >>= 1;
3728
+ if (data.position == 0) {
3729
+ data.position = resetValue;
3730
+ data.val = getNextValue(data.index++);
3731
+ }
3732
+ bits |= (resb > 0 ? 1 : 0) * power;
3733
+ power <<= 1;
3734
+ }
3735
+ switch (bits) {
3736
+ case 0:
3737
+ bits = 0;
3738
+ maxpower = Math.pow(2, 8);
3739
+ power = 1;
3740
+ while (power != maxpower) {
3741
+ resb = data.val & data.position;
3742
+ data.position >>= 1;
3743
+ if (data.position == 0) {
3744
+ data.position = resetValue;
3745
+ data.val = getNextValue(data.index++);
3746
+ }
3747
+ bits |= (resb > 0 ? 1 : 0) * power;
3748
+ power <<= 1;
3749
+ }
3750
+ c = f(bits);
3751
+ break;
3752
+ case 1:
3753
+ bits = 0;
3754
+ maxpower = Math.pow(2, 16);
3755
+ power = 1;
3756
+ while (power != maxpower) {
3757
+ resb = data.val & data.position;
3758
+ data.position >>= 1;
3759
+ if (data.position == 0) {
3760
+ data.position = resetValue;
3761
+ data.val = getNextValue(data.index++);
3762
+ }
3763
+ bits |= (resb > 0 ? 1 : 0) * power;
3764
+ power <<= 1;
3765
+ }
3766
+ c = f(bits);
3767
+ break;
3768
+ case 2: return "";
3769
+ }
3770
+ dictionary[3] = c;
3771
+ w = c;
3772
+ result.push(c);
3773
+ while (true) {
3774
+ if (data.index > length) return "";
3775
+ bits = 0;
3776
+ maxpower = Math.pow(2, numBits);
3777
+ power = 1;
3778
+ while (power != maxpower) {
3779
+ resb = data.val & data.position;
3780
+ data.position >>= 1;
3781
+ if (data.position == 0) {
3782
+ data.position = resetValue;
3783
+ data.val = getNextValue(data.index++);
3784
+ }
3785
+ bits |= (resb > 0 ? 1 : 0) * power;
3786
+ power <<= 1;
3787
+ }
3788
+ switch (c = bits) {
3789
+ case 0:
3790
+ bits = 0;
3791
+ maxpower = Math.pow(2, 8);
3792
+ power = 1;
3793
+ while (power != maxpower) {
3794
+ resb = data.val & data.position;
3795
+ data.position >>= 1;
3796
+ if (data.position == 0) {
3797
+ data.position = resetValue;
3798
+ data.val = getNextValue(data.index++);
3799
+ }
3800
+ bits |= (resb > 0 ? 1 : 0) * power;
3801
+ power <<= 1;
3802
+ }
3803
+ dictionary[dictSize++] = f(bits);
3804
+ c = dictSize - 1;
3805
+ enlargeIn--;
3806
+ break;
3807
+ case 1:
3808
+ bits = 0;
3809
+ maxpower = Math.pow(2, 16);
3810
+ power = 1;
3811
+ while (power != maxpower) {
3812
+ resb = data.val & data.position;
3813
+ data.position >>= 1;
3814
+ if (data.position == 0) {
3815
+ data.position = resetValue;
3816
+ data.val = getNextValue(data.index++);
3817
+ }
3818
+ bits |= (resb > 0 ? 1 : 0) * power;
3819
+ power <<= 1;
3820
+ }
3821
+ dictionary[dictSize++] = f(bits);
3822
+ c = dictSize - 1;
3823
+ enlargeIn--;
3824
+ break;
3825
+ case 2: return result.join("");
3826
+ }
3827
+ if (enlargeIn == 0) {
3828
+ enlargeIn = Math.pow(2, numBits);
3829
+ numBits++;
3830
+ }
3831
+ if (dictionary[c]) entry = dictionary[c];
3832
+ else if (c === dictSize) entry = w + w.charAt(0);
3833
+ else return null;
3834
+ result.push(entry);
3835
+ dictionary[dictSize++] = w + entry.charAt(0);
3836
+ enlargeIn--;
3837
+ w = entry;
3838
+ if (enlargeIn == 0) {
3839
+ enlargeIn = Math.pow(2, numBits);
3840
+ numBits++;
3841
+ }
3842
+ }
3124
3843
  }
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
3844
+ };
3845
+ return LZString;
3846
+ })();
3847
+ if (typeof define === "function" && define.amd) define(function() {
3848
+ return LZString;
3139
3849
  });
3140
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3141
- triggerAt: "start",
3142
- minQuietPeriodMs: 100
3850
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3851
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3852
+ return LZString;
3143
3853
  });
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
- };
3215
- }
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?.();
3232
- }
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
- return {
3242
- isDropTarget,
3243
- onDragEnter,
3244
- onDragOver,
3245
- onDragLeave,
3246
- onDrop
3247
- };
3248
- }
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);
3333
- }
3854
+ })))(), 1);
3855
+ /** Document types that represent a "drive": a container of nodes. */
3856
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
3334
3857
  function useAllowedDocumentModelModules() {
3335
3858
  const documentModelModules = useDocumentModelModules();
3336
3859
  const allowedDocumentTypes = useAllowedDocumentTypes();
@@ -3396,15 +3919,49 @@ function useSetPHDocumentEditorConfig(config) {
3396
3919
  setIsInitialized(true);
3397
3920
  }, [config, isInitialized]);
3398
3921
  }
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];
3922
+ /**
3923
+ * Classifies a document's model version against the installed module
3924
+ * versions. Pure logic, extracted for testing.
3925
+ */
3926
+ function getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {
3927
+ if (availableVersions.length === 0) return;
3928
+ const sorted = [...availableVersions].sort((a, b) => a - b);
3929
+ const latestVersion = sorted[sorted.length - 1];
3930
+ if (documentVersion > latestVersion) return {
3931
+ kind: "unsupported",
3932
+ documentVersion,
3933
+ availableVersions: sorted
3934
+ };
3935
+ if (documentVersion === latestVersion) return {
3936
+ kind: "current",
3937
+ documentVersion
3938
+ };
3939
+ return {
3940
+ kind: "upgrade-available",
3941
+ documentVersion,
3942
+ latestVersion,
3943
+ canUpgrade: hasUpgradePath(documentVersion, latestVersion)
3944
+ };
3945
+ }
3946
+ /**
3947
+ * Compares the given document's model version against the versions available
3948
+ * from installed Vetra packages. Returns undefined while packages load or
3949
+ * when the document type has no installed modules.
3950
+ */
3951
+ function useDocumentVersionStatus(document) {
3952
+ const modules = useDocumentModelModules();
3953
+ const registry = useModelRegistry();
3954
+ if (!document || !modules) return;
3955
+ const documentType = document.header.documentType;
3956
+ return getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {
3957
+ if (!registry) return false;
3958
+ try {
3959
+ registry.computeUpgradePath(documentType, fromVersion, toVersion);
3960
+ return true;
3961
+ } catch {
3962
+ return false;
3963
+ }
3964
+ });
3408
3965
  }
3409
3966
  const validateDocument = (document) => {
3410
3967
  const errors = [];
@@ -3511,11 +4068,11 @@ function useNodeActions() {
3511
4068
  const drives = useDrives();
3512
4069
  async function onAddFile(file, parent) {
3513
4070
  if (!selectedDriveId) return;
3514
- return addFile(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id);
4071
+ return addFileWithProgress(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id, void 0, void 0, "duplicate");
3515
4072
  }
3516
4073
  async function onAddFolder(name, parent) {
3517
4074
  if (!selectedDriveId) return;
3518
- return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
4075
+ return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3519
4076
  }
3520
4077
  async function onRenameNode(newName, node) {
3521
4078
  if (!selectedDriveId) return;
@@ -3602,20 +4159,8 @@ function useSelectedNodePath() {
3602
4159
  function useNodeParentFolderById(id) {
3603
4160
  return useFolderById(useNodeById(id)?.parentFolder);
3604
4161
  }
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);
4162
+ function useParentFolderForSelectedNode() {
4163
+ return useNodeParentFolderById(useSelectedNode()?.id);
3619
4164
  }
3620
4165
  const STORED_THEME_KEY = "ph:theme";
3621
4166
  const UPDATE_STORED_THEME = "ph:updateStoredTheme";
@@ -3830,6 +4375,6 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
3830
4375
  createDebouncedRefreshReactorData();
3831
4376
  createDebouncedRefreshReactorDataClient();
3832
4377
  //#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 };
4378
+ export { usePHToast as A, useSelectedDriveId as B, addFolder$1 as C, useDisabledEditors as D, showRevisionHistory as E, t$5 as F, useDocumentById as H, isFileNodeKind as I, isFolderNodeKind as L, e$1 as M, e$4 as N, useDragNode as O, t$2 as P, setSelectedDrive as R, addDocument as S, showPHModal as T, useSelectedDriveSafe as V, useSetPHDocumentEditorConfig as _, useDownloadDocument as a, useSelectedDocumentOfType as b, useGetSwitchboardLink as c, useNodeParentFolderById as d, useNodesInSelectedDriveOrFolder as f, useSetPHAppConfig as g, useSelectedNodePath as h, useDocumentVersionStatus as i, useStudioMode as j, useDropNode as k, useNodeActions as l, useSelectedFolder as m, preloadEditorModule as n, useEditorModules as o, useParentFolderForSelectedNode as p, useAllowedDocumentModelModules as r, useEditorModulesForDocumentType as s, getSyncStatusSync as t, useNodeById as u, useTheme as v, showDeleteNodeModal as w, useSelectedDocumentSafe as x, useUserPermissions as y, setSelectedNode as z };
3834
4379
 
3835
- //# sourceMappingURL=dist-DJEK2WVi.mjs.map
4380
+ //# sourceMappingURL=dist-4gA6tFmW.mjs.map