@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.6 → 6.2.2-dev.60

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-D-JZwwGk.js} +3 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-64-WZZjU.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-D1KIMa_5.js} +916 -200
  6. package/dist/browser/connect-D1KIMa_5.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-dmLcxsWV.js} +1588 -1293
  12. package/dist/browser/dist-dmLcxsWV.js.map +1 -0
  13. package/dist/browser/{document-drive-IdFV1QXL.js → document-drive-cxHraTVQ.js} +1157 -122
  14. package/dist/browser/document-drive-cxHraTVQ.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-BAUTcFP2.js} +671 -236
  19. package/dist/browser/editor-BAUTcFP2.js.map +1 -0
  20. package/dist/browser/editor-PmQcB82h.js +25 -0
  21. package/dist/browser/editor-PmQcB82h.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-CWnDdLMC.js} +73 -46
  26. package/dist/browser/folder-view-CWnDdLMC.js.map +1 -0
  27. package/dist/browser/{graphql-editor-ZLRO_8Ce.js → graphql-editor-Cq_L5IUQ.js} +8 -7
  28. package/dist/browser/{graphql-editor-ZLRO_8Ce.js.map → graphql-editor-Cq_L5IUQ.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-D8lysNHE.js} +4 -4
  34. package/dist/browser/{json-editor-DBuZ6gN7.js.map → json-editor-D8lysNHE.js.map} +1 -1
  35. package/dist/browser/{lib-C-f3izXz.js → lib-DKvC6Hnv.js} +13 -4
  36. package/dist/browser/lib-DKvC6Hnv.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-NyThZN-C.js} +8 -18
  42. package/dist/browser/state-schemas-NyThZN-C.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-BixjoUPL.mjs} +916 -200
  46. package/dist/node/connect-BixjoUPL.mjs.map +1 -0
  47. package/dist/node/{dist-DJEK2WVi.mjs → dist-BtnA_6jV.mjs} +1592 -1292
  48. package/dist/node/dist-BtnA_6jV.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-ChLoGFvU.mjs} +1157 -122
  54. package/dist/node/document-drive-ChLoGFvU.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-C8Drq-be.mjs +25 -0
  59. package/dist/node/editor-C8Drq-be.mjs.map +1 -0
  60. package/dist/node/{editor-B1KhoF1f.mjs → editor-cfoi-9LF.mjs} +672 -237
  61. package/dist/node/editor-cfoi-9LF.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--I9GOsir.mjs} +73 -46
  66. package/dist/node/folder-view--I9GOsir.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-BKGQ8ojN.mjs} +7 -7
  70. package/dist/node/{graphql-editor-C5VLRqEf.mjs.map → graphql-editor-BKGQ8ojN.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-32paCJkU.mjs} +4 -4
  76. package/dist/node/{json-editor-iI2s9a_4.mjs.map → json-editor-32paCJkU.mjs.map} +1 -1
  77. package/dist/node/{main-D82dkD7g.mjs → main-DRfab-vL.mjs} +15 -6
  78. package/dist/node/main-DRfab-vL.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-ClrkM0Fn.mjs} +10 -20
  82. package/dist/{browser/state-schemas-BjQKM498.js.map → node/state-schemas-ClrkM0Fn.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,11 @@
1
- import { E as __commonJSMin, k as __toESM, t as capitalCase } from "./dist-CXoKspdx.js";
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-IdFV1QXL.js";
3
- import { a as SyncStatus, o as DriveCollectionId, s as ModuleNotFoundError, t as gql } from "./lib-C-f3izXz.js";
4
- import { Children, cloneElement, forwardRef, isValidElement, use, useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
1
+ import { A as __toESM, D as __commonJSMin, t as capitalCase } from "./dist-B4FWbuEM.js";
2
+ import { A as createZip, C as baseSaveToFileHandle, D as createPresignedHeader, H as replayDocumentVersioned, S as baseLoadFromInputVersioned, Z as setName, a as handleTargetNameCollisions, at as validateInitialState, ct as generateId, f as logger, i as generateNodesCopy, l as moveNode, n as copyNode, o as isFileNode, ot as validateModules, s as isFolderNode, st as validateStateSchemaName, t as addFolder, u as updateNode, v as assertAuthPreservedOnDuplicate, w as buildSignedAction, x as baseLoadFromInput } from "./document-drive-cxHraTVQ.js";
3
+ import { a as SyncStatus, o as DriveCollectionId, s as ModuleNotFoundError, t as gql } from "./lib-DKvC6Hnv.js";
4
+ import "./parser-CkF6Qt8V.js";
5
+ import "./printer-CEYr4JOg.js";
6
+ import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
7
  import "react/jsx-runtime";
6
- //#region ../reactor-browser/dist/make-ph-event-functions-BHoLPif5.js
8
+ //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
7
9
  const isServer$1 = typeof window === "undefined";
8
10
  function makePHEventFunctions(key) {
9
11
  const setEventName = `ph:set${capitalCase(key)}`;
@@ -51,7 +53,7 @@ function makePHEventFunctions(key) {
51
53
  };
52
54
  }
53
55
  //#endregion
54
- //#region ../reactor-browser/dist/document-by-id-dLYFX-xz.js
56
+ //#region ../reactor-browser/dist/document-by-id-BSZqTN66.js
55
57
  async function queueActions(document, actionOrActions) {
56
58
  if (!document) throw new Error("No document provided");
57
59
  if (!actionOrActions) throw new Error("No actions provided");
@@ -97,12 +99,12 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
97
99
  logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
100
  }
99
101
  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
102
  const renown = window.ph?.renown;
104
103
  if (!renown?.user) return action;
105
104
  if (!action.context?.signer) return action;
105
+ const reactorClient = window.ph?.reactorClientModule?.client;
106
+ if (!reactorClient) return action;
107
+ const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
106
108
  const actionSigner = action.context.signer;
107
109
  return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
110
  }
@@ -180,6 +182,21 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
180
182
  if (onSuccess && result) onSuccess(result);
181
183
  return result;
182
184
  }
185
+ /**
186
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
187
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
188
+ * TypeScript string enum is nominal, so no string literal is assignable to it
189
+ * without one - and the two checks above are what make it safe.
190
+ */
191
+ const DOCUMENT_CHANGE_TYPE = {
192
+ Created: "created",
193
+ Deleted: "deleted",
194
+ Updated: "updated",
195
+ ParentAdded: "parent_added",
196
+ ParentRemoved: "parent_removed",
197
+ ChildAdded: "child_added",
198
+ ChildRemoved: "child_removed"
199
+ };
183
200
  const documentEventFunctions = makePHEventFunctions("documentCache");
184
201
  /** Returns all documents in the reactor. */
185
202
  const useDocumentCache = documentEventFunctions.useValue;
@@ -225,8 +242,25 @@ function useDocumentById(id) {
225
242
  const [, dispatch] = useDispatch(document);
226
243
  return [document, dispatch];
227
244
  }
245
+ Error;
246
+ JSON;
228
247
  //#endregion
229
- //#region ../reactor-browser/dist/client-_Gh2Uf0E.js
248
+ //#region ../reactor-browser/dist/client-DB8gP4hz.js
249
+ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
250
+ DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
251
+ DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
252
+ DocumentChangeType["Created"] = "CREATED";
253
+ DocumentChangeType["Deleted"] = "DELETED";
254
+ DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
255
+ DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
256
+ DocumentChangeType["Updated"] = "UPDATED";
257
+ return DocumentChangeType;
258
+ }({});
259
+ let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
260
+ PropagationMode["Cascade"] = "CASCADE";
261
+ PropagationMode["Orphan"] = "ORPHAN";
262
+ return PropagationMode;
263
+ }({});
230
264
  const PhDocumentFieldsFragmentDoc = gql`
231
265
  fragment PHDocumentFields on PHDocument {
232
266
  id
@@ -287,6 +321,7 @@ const GetDocumentWithOperationsDocument = gql`
287
321
  hash
288
322
  skip
289
323
  error
324
+ deniedReason
290
325
  id
291
326
  action {
292
327
  id
@@ -399,6 +434,7 @@ const GetDocumentOperationsDocument = gql`
399
434
  hash
400
435
  skip
401
436
  error
437
+ deniedReason
402
438
  id
403
439
  action {
404
440
  id
@@ -441,6 +477,28 @@ gql`
441
477
  }
442
478
  }
443
479
  `;
480
+ gql`
481
+ query EvaluateActions(
482
+ $documentIdentifier: String!
483
+ $branch: String
484
+ $candidates: [ActionCandidateInput!]!
485
+ ) {
486
+ evaluateActions(
487
+ documentIdentifier: $documentIdentifier
488
+ branch: $branch
489
+ candidates: $candidates
490
+ ) {
491
+ evaluations {
492
+ decision
493
+ reason
494
+ }
495
+ allAllowed
496
+ anyAllowed
497
+ allDenied
498
+ anyDenied
499
+ }
500
+ }
501
+ `;
444
502
  gql`
445
503
  mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
446
504
  createDocument(document: $document, parentIdentifier: $parentIdentifier) {
@@ -466,13 +524,13 @@ gql`
466
524
  gql`
467
525
  mutation MutateDocument(
468
526
  $documentIdentifier: String!
469
- $actions: [JSONObject!]!
470
- $view: ViewFilterInput
527
+ $actions: [ActionInput!]!
528
+ $branch: String
471
529
  ) {
472
- mutateDocument(
530
+ mutateDocument: execute(
473
531
  documentIdentifier: $documentIdentifier
474
532
  actions: $actions
475
- view: $view
533
+ branch: $branch
476
534
  ) {
477
535
  ...PHDocumentFields
478
536
  }
@@ -482,14 +540,21 @@ gql`
482
540
  gql`
483
541
  mutation MutateDocumentAsync(
484
542
  $documentIdentifier: String!
485
- $actions: [JSONObject!]!
486
- $view: ViewFilterInput
543
+ $actions: [ActionInput!]!
544
+ $branch: String
487
545
  ) {
488
- mutateDocumentAsync(
546
+ mutateDocumentAsync: executeAsync(
489
547
  documentIdentifier: $documentIdentifier
490
548
  actions: $actions
491
- view: $view
492
- )
549
+ branch: $branch
550
+ ) {
551
+ id
552
+ status
553
+ result
554
+ error
555
+ createdAt
556
+ completedAt
557
+ }
493
558
  }
494
559
  `;
495
560
  gql`
@@ -649,6 +714,7 @@ gql`
649
714
  hash
650
715
  skip
651
716
  error
717
+ deniedReason
652
718
  id
653
719
  action {
654
720
  id
@@ -691,6 +757,7 @@ gql`
691
757
  deadLetters {
692
758
  documentId
693
759
  error
760
+ errorType
694
761
  }
695
762
  hasMore
696
763
  }
@@ -737,8 +804,17 @@ function extractQueryParts(doc, fallbackBody) {
737
804
  extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
738
805
  extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
739
806
  //#endregion
740
- //#region ../reactor-browser/dist/renown-D-1c_Bvx.js
807
+ //#region ../reactor-browser/dist/renown-BZabzj4l.js
741
808
  const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
809
+ const RenownInitialUserContext = createContext({ state: "unknown" });
810
+ /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
811
+ function useRenownInitialAuth() {
812
+ return useContext(RenownInitialUserContext);
813
+ }
814
+ function useRenownInitialUser() {
815
+ const initial = useRenownInitialAuth();
816
+ return initial.state === "authenticated" ? initial.user : void 0;
817
+ }
742
818
  const renownEventFunctions = makePHEventFunctions("renown");
743
819
  renownEventFunctions.addEventHandler;
744
820
  /** Returns the renown instance */
@@ -747,41 +823,17 @@ renownEventFunctions.setValue;
747
823
  /** Returns the current user from the renown instance, subscribing to user events */
748
824
  function useUser() {
749
825
  const renown = useRenown();
750
- const [user, setUser] = useState(renown?.user);
826
+ const initialUser = useRenownInitialUser();
827
+ const instance = renown ? renown : void 0;
828
+ const [user, setUser] = useState(instance ? instance.user : initialUser);
751
829
  useEffect(() => {
752
- setUser(renown?.user);
753
- if (!renown) return;
754
- return renown.on("user", setUser);
755
- }, [renown]);
756
- return user;
757
- }
758
- function mergeProps(parentProps, childProps) {
759
- const merged = { ...parentProps };
760
- for (const key of Object.keys(childProps)) {
761
- const parentValue = parentProps[key];
762
- const childValue = childProps[key];
763
- if (key === "style") merged[key] = {
764
- ...parentValue,
765
- ...childValue
766
- };
767
- else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
768
- else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
769
- childValue(...args);
770
- parentValue(...args);
771
- };
772
- else if (childValue !== void 0) merged[key] = childValue;
773
- }
774
- return merged;
830
+ if (instance) {
831
+ setUser(instance.user);
832
+ return instance.on("user", setUser);
833
+ }
834
+ }, [instance]);
835
+ return instance ? user : initialUser ?? user;
775
836
  }
776
- const Slot = forwardRef(({ children, ...props }, ref) => {
777
- const child = Children.only(children);
778
- if (!isValidElement(child)) return null;
779
- const childElement = child;
780
- const mergedProps = mergeProps(props, childElement.props);
781
- if (ref) mergedProps.ref = ref;
782
- return cloneElement(childElement, mergedProps);
783
- });
784
- Slot.displayName = "Slot";
785
837
  //#endregion
786
838
  //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
787
839
  function e$8(e, t, n) {
@@ -906,6 +958,32 @@ function e(e) {
906
958
  let t = !1, n;
907
959
  return () => (t ||= (n = e(), !0), n);
908
960
  }
961
+ var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
962
+ CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
963
+ CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
964
+ CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
965
+ CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
966
+ CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
967
+ CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
968
+ CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
969
+ CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
970
+ CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
971
+ CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
972
+ CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
973
+ return CloseCode2;
974
+ })(CloseCode || {});
975
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
976
+ MessageType2["ConnectionInit"] = "connection_init";
977
+ MessageType2["ConnectionAck"] = "connection_ack";
978
+ MessageType2["Ping"] = "ping";
979
+ MessageType2["Pong"] = "pong";
980
+ MessageType2["Subscribe"] = "subscribe";
981
+ MessageType2["Next"] = "next";
982
+ MessageType2["Error"] = "error";
983
+ MessageType2["Complete"] = "complete";
984
+ return MessageType2;
985
+ })(MessageType || {});
986
+ Error;
909
987
  //#endregion
910
988
  //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
911
989
  let base64;
@@ -1693,1065 +1771,513 @@ slug.setLocale = function(locale) {
1693
1771
  defaultLocale = locales[locale] || {};
1694
1772
  };
1695
1773
  //#endregion
1696
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1697
- const normalizeDescriptors = (error) => {
1698
- CORE_ERROR_PROPS.forEach((propName) => {
1699
- normalizeDescriptor(error, propName);
1700
- });
1701
- };
1702
- const CORE_ERROR_PROPS = [
1703
- "name",
1704
- "message",
1705
- "stack",
1706
- "cause",
1707
- "errors"
1708
- ];
1709
- const normalizeDescriptor = (error, propName) => {
1710
- const descriptor = getDescriptor(error, propName);
1711
- if (descriptor === void 0) return;
1712
- if (isReadonlyGetter(descriptor)) {
1713
- setErrorProperty(error, propName, error[propName]);
1714
- return;
1774
+ //#region ../reactor-browser/dist/document-operations-C6nce9dH.js
1775
+ var DocumentModelNotFoundError = class extends Error {
1776
+ documentType;
1777
+ name = "DocumentModelNotFoundError";
1778
+ constructor(documentType) {
1779
+ super(`Document model module for type ${documentType} not found`);
1780
+ this.documentType = documentType;
1715
1781
  }
1716
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1717
- };
1718
- const getDescriptor = (value, propName) => {
1719
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1720
- if (descriptor !== void 0) return descriptor;
1721
- const prototype = Object.getPrototypeOf(value);
1722
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
1723
- };
1724
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1725
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1726
- const setErrorProperty = (error, propName, value) => {
1727
- setErrorDescriptor(error, propName, { value });
1728
- };
1729
- const setErrorDescriptor = (error, propName, descriptor) => {
1730
- Object.defineProperty(error, propName, {
1731
- ...descriptor,
1732
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1733
- enumerable: false,
1734
- configurable: true
1735
- });
1736
- };
1737
- //#endregion
1738
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1739
- const normalizeAggregate = (error, recurse) => {
1740
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1741
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1742
- else if (error.errors !== void 0) deleteAggregateErrors(error);
1743
- };
1744
- const isDefined = (error) => error !== void 0;
1745
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1746
- const deleteAggregateErrors = (error) => {
1747
- delete error.errors;
1748
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1749
- };
1750
- //#endregion
1751
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1752
- const normalizeCause = (error, recurse) => {
1753
- if (!("cause" in error)) return;
1754
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1755
- if (cause === void 0) delete error.cause;
1756
- else setErrorProperty(error, "cause", cause);
1757
- };
1758
- //#endregion
1759
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1760
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1761
- const isInstanceOfError = (value) => {
1762
- try {
1763
- return value instanceof Error;
1764
- } catch {
1765
- return false;
1782
+ static isError(error) {
1783
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1766
1784
  }
1767
1785
  };
1768
- const hasErrorTag = (value) => {
1769
- try {
1770
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
1771
- } catch {
1772
- return false;
1786
+ var DocumentTypeMismatchError = class extends Error {
1787
+ constructor(documentId, expectedType, actualType) {
1788
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1773
1789
  }
1774
1790
  };
1775
- const ERROR_TAGS = new Set([
1776
- "[object Error]",
1777
- "[object DOMException]",
1778
- "[object DOMError]",
1779
- "[object Exception]"
1780
- ]);
1781
- //#endregion
1782
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1783
- function isPlainObject(value) {
1784
- if (typeof value !== "object" || value === null) return false;
1785
- const prototype = Object.getPrototypeOf(value);
1786
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1787
- }
1788
- //#endregion
1789
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1790
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1791
- const isNonConfigurableProp = (error, propName) => {
1792
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1793
- return descriptor !== void 0 && !descriptor.configurable;
1794
- };
1795
- const isThrowingProp = (error, propName) => {
1796
- try {
1797
- error[propName];
1798
- return false;
1799
- } catch {
1800
- return true;
1791
+ var NoSelectedDocumentError = class extends Error {
1792
+ constructor() {
1793
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1801
1794
  }
1802
1795
  };
1803
- //#endregion
1804
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1805
- const setStack = (error) => {
1806
- setErrorProperty(error, "stack", getStack(error.message, error.name));
1807
- };
1808
- const getStack = (message = "", name = "Error") => {
1809
- const { stack } = new (getErrorClass(name))(message);
1810
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1811
- };
1812
- const getErrorClass = (name) => {
1813
- const descriptor = {
1814
- value: name,
1815
- enumerable: false,
1816
- writable: true,
1817
- configurable: true
1796
+ const modalEventFunctions = makePHEventFunctions("modal");
1797
+ modalEventFunctions.useValue;
1798
+ /** Sets the current modal */
1799
+ const setPHModal = modalEventFunctions.setValue;
1800
+ modalEventFunctions.addEventHandler;
1801
+ /** Shows a modal */
1802
+ function showPHModal(modal) {
1803
+ setPHModal(modal);
1804
+ }
1805
+ /** Shows the delete node modal */
1806
+ function showDeleteNodeModal(nodeOrId) {
1807
+ setPHModal({
1808
+ type: "deleteItem",
1809
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
1810
+ });
1811
+ }
1812
+ function getUserPermissions() {
1813
+ const user = window.ph?.renown?.user;
1814
+ const allowList = window.ph?.allowList;
1815
+ if (!allowList) return {
1816
+ isAllowedToCreateDocuments: true,
1817
+ isAllowedToEditDocuments: true
1818
1818
  };
1819
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1820
- Object.defineProperty(StackError.prototype, "name", descriptor);
1821
- return StackError;
1822
- };
1823
- //#endregion
1824
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1825
- const copyObject = (object) => {
1826
- const objectCopy = {};
1827
- for (const propName of getPropsToCopy(object)) try {
1828
- const value = object[propName];
1829
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1830
- Object.defineProperty(objectCopy, propName, {
1831
- value,
1832
- enumerable,
1833
- configurable,
1834
- writable
1835
- });
1836
- } catch {}
1837
- return objectCopy;
1838
- };
1839
- const getPropsToCopy = (object) => {
1840
- const propNames = getOwnKeys(object);
1841
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1842
- return propNames;
1843
- };
1844
- const getOwnKeys = (object) => {
1819
+ return {
1820
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
1821
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
1822
+ };
1823
+ }
1824
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
1825
+ async function downloadFile(document, fileName) {
1845
1826
  try {
1846
- return Reflect.ownKeys(object);
1847
- } catch {
1848
- return [];
1827
+ const data = await createZip(document);
1828
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
1829
+ const link = window.document.createElement("a");
1830
+ link.style.display = "none";
1831
+ link.href = URL.createObjectURL(blob);
1832
+ link.download = fileName;
1833
+ window.document.body.appendChild(link);
1834
+ link.click();
1835
+ window.document.body.removeChild(link);
1836
+ } catch (e) {
1837
+ logger.error(e instanceof Error ? e.message : String(e));
1849
1838
  }
1850
- };
1851
- const isInheritedProp = (object, propName) => {
1852
- try {
1853
- return propName in object && !Object.hasOwn(object, propName);
1854
- } catch {
1855
- return false;
1839
+ }
1840
+ async function getDocumentExtension(document) {
1841
+ const documentType = document.header.documentType;
1842
+ let rawExtension;
1843
+ if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
1844
+ else {
1845
+ const reactorClient = window.ph?.reactorClientModule?.client;
1846
+ if (reactorClient) {
1847
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1848
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
1849
+ }
1856
1850
  }
1857
- };
1858
- //#endregion
1859
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1860
- const objectifyError = (object) => {
1861
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1862
- const messageA = getMessage(message, objectA);
1863
- const error = newError(name, messageA);
1864
- if (message === messageA) assignObjectProps(error, objectA);
1865
- Object.entries({
1866
- name,
1867
- stack,
1868
- cause,
1869
- errors
1870
- }).forEach(([propName, propValue]) => {
1871
- setNewErrorProperty(error, propName, propValue);
1872
- });
1873
- if (stack === void 0) setStack(error);
1874
- return error;
1875
- };
1876
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1877
- const safeJsonStringify = (object) => {
1878
- try {
1879
- return JSON.stringify(object);
1880
- } catch {
1881
- return safeStringify(object);
1851
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
1852
+ }
1853
+ /**
1854
+ * Fetches all operations for a document using cursor-based pagination.
1855
+ * The reactor client handles multi-scope cursors transparently via
1856
+ * composite cursors, so all scopes are fetched in a single paginated stream.
1857
+ */
1858
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
1859
+ const scopes = Object.keys(document.state);
1860
+ const operations = {};
1861
+ for (const scope of scopes) operations[scope] = [];
1862
+ let cursor = "";
1863
+ do {
1864
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
1865
+ cursor,
1866
+ limit: pageSize
1867
+ });
1868
+ for (const op of page.results) {
1869
+ const scope = op.action.scope ?? "global";
1870
+ if (operations[scope]) operations[scope].push(op);
1871
+ }
1872
+ cursor = page.nextCursor ?? "";
1873
+ } while (cursor);
1874
+ return operations;
1875
+ }
1876
+ function extractInitialState(documentScopeOps) {
1877
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
1878
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
1879
+ const input = upgradeOp.action.input;
1880
+ const initialState = input.initialState ?? input.state;
1881
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
1882
+ return initialState;
1883
+ }
1884
+ function filterDomainOperations(operations) {
1885
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
1886
+ }
1887
+ function countOperations(operations) {
1888
+ let total = 0;
1889
+ for (const ops of Object.values(operations)) total += ops?.length ?? 0;
1890
+ return total;
1891
+ }
1892
+ /**
1893
+ * Split an imported document's domain operations at its mid-history upgrade
1894
+ * boundaries, so the caller can re-dispatch each upgrade between segments.
1895
+ *
1896
+ * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
1897
+ * path and must not be repeated. A later upgrade must be: it is where the
1898
+ * reducer version changes, and dropping it replays everything after it through
1899
+ * the module the document was created with.
1900
+ */
1901
+ function splitAtUpgradeBoundaries(operations) {
1902
+ 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);
1903
+ const domain = filterDomainOperations(operations);
1904
+ if (upgrades.length === 0) return [{ operations: domain }];
1905
+ const segments = [];
1906
+ const consumed = /* @__PURE__ */ new Map();
1907
+ const take = (until) => {
1908
+ const slice = {};
1909
+ for (const [scope, ops] of Object.entries(domain)) {
1910
+ if (!ops) continue;
1911
+ const from = consumed.get(scope) ?? 0;
1912
+ const stop = Math.max(from, until(scope, ops));
1913
+ const chunk = ops.slice(from, stop);
1914
+ if (chunk.length > 0) slice[scope] = chunk;
1915
+ consumed.set(scope, stop);
1916
+ }
1917
+ return slice;
1918
+ };
1919
+ for (const upgrade of upgrades) {
1920
+ const input = upgrade.action.input;
1921
+ const slice = take((scope, ops) => boundary(upgrade, scope, ops));
1922
+ segments.push({
1923
+ operations: slice,
1924
+ upgradeTo: input.toVersion
1925
+ });
1882
1926
  }
1883
- };
1884
- const safeStringify = (object) => {
1885
- try {
1886
- return String(object);
1887
- } catch {
1888
- return "Invalid error";
1927
+ const tail = take((_scope, ops) => ops.length);
1928
+ if (countOperations(tail) > 0) segments.push({ operations: tail });
1929
+ return segments;
1930
+ }
1931
+ /**
1932
+ * How many of a scope's operations precede an upgrade. Must stay identical to
1933
+ * the boundary computation in `replayDocumentVersioned` — snapshots compare
1934
+ * against operation indices, not array positions, and the timestamp fallback
1935
+ * excludes the upgrade's own instant.
1936
+ */
1937
+ function boundary(upgrade, scope, ops) {
1938
+ const snapshot = upgrade.action.input.revision;
1939
+ if (snapshot !== void 0) {
1940
+ const revision = snapshot[scope] ?? 0;
1941
+ let count = 0;
1942
+ for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
1943
+ return count;
1889
1944
  }
1890
- };
1891
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1892
- const MESSAGE_MAX_SIZE = 1e3;
1893
- const newError = (name, message) => {
1894
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1895
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1896
- return new Error(message);
1897
- };
1898
- const NATIVE_ERRORS = {
1899
- Error,
1900
- ReferenceError,
1901
- TypeError,
1902
- SyntaxError,
1903
- RangeError,
1904
- URIError,
1905
- EvalError
1906
- };
1907
- const assignObjectProps = (error, object) => {
1908
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1909
- };
1910
- const setNewErrorProperty = (error, propName, propValue) => {
1911
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1912
- };
1913
- //#endregion
1914
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1915
- const stringifyError = (value) => {
1945
+ for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
1946
+ return ops.length;
1947
+ }
1948
+ async function exportFile(document, suggestedName) {
1949
+ const reactorClient = window.ph?.reactorClient;
1950
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1951
+ const operations = await fetchDocumentOperations(reactorClient, document);
1952
+ const initialState = extractInitialState(operations["document"] ?? []);
1953
+ const documentWithOps = {
1954
+ ...document,
1955
+ operations,
1956
+ initialState
1957
+ };
1958
+ const extension = await getDocumentExtension(documentWithOps);
1959
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
1960
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
1961
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
1916
1962
  try {
1917
- const error = new Error(String(value));
1918
- setStack(error);
1919
- return error;
1920
- } catch (error_) {
1921
- return error_;
1963
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
1964
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
1965
+ return fileHandle;
1966
+ } catch (e) {
1967
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
1922
1968
  }
1923
- };
1924
- //#endregion
1925
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1926
- const { toString: objectToString } = Object.prototype;
1927
- const createError = (value) => {
1928
- if (isErrorPlainObj(value)) return objectifyError(value);
1929
- if (!isErrorInstance(value)) return stringifyError(value);
1930
- if (isInvalidError(value)) return objectifyError(value);
1931
- return value;
1932
- };
1933
- const isErrorPlainObj = (value) => {
1969
+ }
1970
+ /**
1971
+ * Loads a document file and replays it with version-aware reducers from the registry.
1972
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
1973
+ * the document type.
1974
+ */
1975
+ async function loadFile(path) {
1976
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
1977
+ const reactorClient = window.ph?.reactorClientModule?.client;
1978
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1979
+ const documentType = baseDocument.header.documentType;
1980
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1981
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
1982
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
1983
+ const reducers = {};
1984
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
1985
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
1986
+ let upgradeManifest;
1987
+ if (registry) try {
1988
+ upgradeManifest = registry.getUpgradeManifest(documentType);
1989
+ } catch {}
1990
+ return baseLoadFromInputVersioned(path, {
1991
+ reducers,
1992
+ upgradeManifest
1993
+ });
1994
+ }
1995
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
1996
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1997
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
1998
+ const reactorClient = window.ph?.reactorClientModule?.client;
1999
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2000
+ let documentModelModule;
2001
+ if (documentModelVersion !== void 0) {
2002
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2003
+ const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
2004
+ if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
2005
+ documentModelModule = module;
2006
+ } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2007
+ const newDocument = document ?? documentModelModule.utils.createDocument();
2008
+ if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
2009
+ newDocument.header.name = name;
2010
+ if (preferredEditor) newDocument.header.meta = {
2011
+ ...newDocument.header.meta,
2012
+ preferredEditor
2013
+ };
2014
+ let newDoc;
1934
2015
  try {
1935
- return isPlainObject(value);
1936
- } catch {
1937
- return false;
2016
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2017
+ } catch (e) {
2018
+ logger.error("Error adding document: @error", e);
2019
+ throw new Error("There was an error adding document", { cause: e });
1938
2020
  }
1939
- };
1940
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1941
- const isProxy = (value) => {
2021
+ return {
2022
+ id: newDoc.header.id,
2023
+ name: newDoc.header.name,
2024
+ documentType,
2025
+ parentFolder: parentFolder ?? null,
2026
+ kind: "file"
2027
+ };
2028
+ }
2029
+ async function addFile(file, driveId, name, parentFolder) {
2030
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2031
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2032
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2033
+ const document = await loadFile(file);
2034
+ let duplicateId = false;
2035
+ const reactorClient = window.ph?.reactorClient;
2036
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1942
2037
  try {
1943
- return objectToString.call(value) === "[object Object]";
1944
- } catch {
1945
- return true;
2038
+ await reactorClient.get(document.header.id);
2039
+ duplicateId = true;
2040
+ } catch {}
2041
+ const documentId = duplicateId ? generateId() : document.header.id;
2042
+ const header = createPresignedHeader(documentId, document.header.documentType);
2043
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2044
+ header.meta = document.header.meta;
2045
+ header.name = name || document.header.name;
2046
+ const initialDocument = {
2047
+ ...document,
2048
+ header,
2049
+ state: document.initialState,
2050
+ operations: Object.keys(document.operations).reduce((acc, key) => {
2051
+ acc[key] = [];
2052
+ return acc;
2053
+ }, {})
2054
+ };
2055
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2056
+ for (const segment of splitAtUpgradeBoundaries(document.operations)) {
2057
+ await uploadOperations(documentId, segment.operations, queueOperations);
2058
+ if (segment.upgradeTo !== void 0) await upgradeDocument(documentId, segment.upgradeTo);
1946
2059
  }
1947
- };
1948
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1949
- //#endregion
1950
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1951
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1952
- const recurseException = (error, parents, shallow) => {
1953
- if (parents.includes(error)) return;
1954
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1955
- const errorA = createError(error);
1956
- normalizeProps(errorA, recurse);
1957
- return errorA;
1958
- };
1959
- const identity = (error) => error;
1960
- const normalizeProps = (error, recurse) => {
1961
- normalizeName(error);
1962
- normalizeMessage(error);
1963
- normalizeStack(error);
1964
- normalizeCause(error, recurse);
1965
- normalizeAggregate(error, recurse);
1966
- normalizeDescriptors(error);
1967
- };
1968
- const normalizeName = (error) => {
1969
- if (isDefinedString(error.name)) return;
1970
- const prototypeName = Object.getPrototypeOf(error).name;
1971
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1972
- };
1973
- const normalizeMessage = (error) => {
1974
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1975
- };
1976
- const normalizeStack = (error) => {
1977
- if (!isDefinedString(error.stack)) setStack(error);
1978
- };
1979
- const isDefinedString = (value) => typeof value === "string" && value !== "";
1980
- //#endregion
1981
- //#region ../reactor-browser/dist/index.js
1982
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1983
- var LZString = (function() {
1984
- var f = String.fromCharCode;
1985
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
1986
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
1987
- var baseReverseDic = {};
1988
- function getBaseValue(alphabet, character) {
1989
- if (!baseReverseDic[alphabet]) {
1990
- baseReverseDic[alphabet] = {};
1991
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
1992
- }
1993
- return baseReverseDic[alphabet][character];
2060
+ }
2061
+ async function addFolder$1(driveId, name, parentFolder) {
2062
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2063
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2064
+ const reactorClient = window.ph?.reactorClient;
2065
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2066
+ await reactorClient.get(driveId);
2067
+ const folderId = generateId();
2068
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
2069
+ id: folderId,
2070
+ name,
2071
+ parentFolder
2072
+ })])).state.global.nodes.find((node) => node.id === folderId);
2073
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2074
+ return node;
2075
+ }
2076
+ async function renameNode(driveId, nodeId, name) {
2077
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2078
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2079
+ const reactorClient = window.ph?.reactorClient;
2080
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2081
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2082
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
2083
+ id: nodeId,
2084
+ name
2085
+ })])).state.global.nodes.find((n) => n.id === nodeId);
2086
+ if (!node) throw new Error("There was an error renaming node in the drive");
2087
+ return node;
2088
+ }
2089
+ async function renameDriveNode(driveId, nodeId, name) {
2090
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2091
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2092
+ const reactorClient = window.ph?.reactorClient;
2093
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2094
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2095
+ await reactorClient.execute(driveId, "main", [updateNode({
2096
+ id: nodeId,
2097
+ name
2098
+ })]);
2099
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2100
+ }
2101
+ async function moveNodeById(args) {
2102
+ const { driveId, srcId, targetId } = args;
2103
+ if (!driveId || !srcId) return;
2104
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2105
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2106
+ const reactorClient = window.ph?.reactorClient;
2107
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2108
+ const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2109
+ if (t(targetParentFolder, srcId)) return;
2110
+ return await reactorClient.execute(driveId, "main", [moveNode({
2111
+ srcFolder: srcId,
2112
+ targetParentFolder
2113
+ })]);
2114
+ }
2115
+ async function moveNode$1(driveId, src, target) {
2116
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2117
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2118
+ const reactorClient = window.ph?.reactorClient;
2119
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2120
+ return await reactorClient.execute(driveId, "main", [moveNode({
2121
+ srcFolder: src.id,
2122
+ targetParentFolder: target?.id
2123
+ })]);
2124
+ }
2125
+ /**
2126
+ * Duplicates a document under a new id using version-aware replay.
2127
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
2128
+ */
2129
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
2130
+ const documentType = document.header.documentType;
2131
+ const { results: allModules } = await reactor.getDocumentModelModules();
2132
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2133
+ const reducers = {};
2134
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2135
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2136
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2137
+ let upgradeManifest;
2138
+ if (registry) try {
2139
+ upgradeManifest = registry.getUpgradeManifest(documentType);
2140
+ } catch {}
2141
+ const config = {
2142
+ reducers,
2143
+ upgradeManifest
2144
+ };
2145
+ const header = createPresignedHeader(newId, documentType);
2146
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2147
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2148
+ return duplicated;
2149
+ }
2150
+ async function copyNode$1(driveId, src, target) {
2151
+ const reactor = window.ph?.reactorClientModule?.client;
2152
+ if (!reactor) return;
2153
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2154
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2155
+ const drive = await reactor.get(driveId);
2156
+ const copyNodesInput = generateNodesCopy({
2157
+ srcId: src.id,
2158
+ targetParentFolder: target?.id,
2159
+ targetName: src.name
2160
+ }, () => generateId(), drive.state.global.nodes);
2161
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
2162
+ for (const copyNodeInput of copyNodesInput) {
2163
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2164
+ if (node) {
2165
+ const resolvedName = handleTargetNameCollisions({
2166
+ nodes: drive.state.global.nodes,
2167
+ srcName: copyNodeInput.targetName || node.name,
2168
+ srcKind: isFileNode(node) ? "file" : "folder",
2169
+ targetParentFolder: copyNodeInput.targetParentFolder || null
2170
+ });
2171
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
1994
2172
  }
1995
- var LZString = {
1996
- compressToBase64: function(input) {
1997
- if (input == null) return "";
1998
- var res = LZString._compress(input, 6, function(a) {
1999
- return keyStrBase64.charAt(a);
2000
- });
2001
- switch (res.length % 4) {
2002
- default:
2003
- case 0: return res;
2004
- case 1: return res + "===";
2005
- case 2: return res + "==";
2006
- case 3: return res + "=";
2007
- }
2008
- },
2009
- decompressFromBase64: function(input) {
2010
- if (input == null) return "";
2011
- if (input == "") return null;
2012
- return LZString._decompress(input.length, 32, function(index) {
2013
- return getBaseValue(keyStrBase64, input.charAt(index));
2014
- });
2015
- },
2016
- compressToUTF16: function(input) {
2017
- if (input == null) return "";
2018
- return LZString._compress(input, 15, function(a) {
2019
- return f(a + 32);
2020
- }) + " ";
2021
- },
2022
- decompressFromUTF16: function(compressed) {
2023
- if (compressed == null) return "";
2024
- if (compressed == "") return null;
2025
- return LZString._decompress(compressed.length, 16384, function(index) {
2026
- return compressed.charCodeAt(index) - 32;
2027
- });
2028
- },
2029
- compressToUint8Array: function(uncompressed) {
2030
- var compressed = LZString.compress(uncompressed);
2031
- var buf = new Uint8Array(compressed.length * 2);
2032
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2033
- var current_value = compressed.charCodeAt(i);
2034
- buf[i * 2] = current_value >>> 8;
2035
- buf[i * 2 + 1] = current_value % 256;
2036
- }
2037
- return buf;
2038
- },
2039
- decompressFromUint8Array: function(compressed) {
2040
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2041
- else {
2042
- var buf = new Array(compressed.length / 2);
2043
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2044
- var result = [];
2045
- buf.forEach(function(c) {
2046
- result.push(f(c));
2047
- });
2048
- return LZString.decompress(result.join(""));
2049
- }
2050
- },
2051
- compressToEncodedURIComponent: function(input) {
2052
- if (input == null) return "";
2053
- return LZString._compress(input, 6, function(a) {
2054
- return keyStrUriSafe.charAt(a);
2055
- });
2056
- },
2057
- decompressFromEncodedURIComponent: function(input) {
2058
- if (input == null) return "";
2059
- if (input == "") return null;
2060
- input = input.replace(/ /g, "+");
2061
- return LZString._decompress(input.length, 32, function(index) {
2062
- return getBaseValue(keyStrUriSafe, input.charAt(index));
2063
- });
2064
- },
2065
- compress: function(uncompressed) {
2066
- return LZString._compress(uncompressed, 16, function(a) {
2067
- return f(a);
2068
- });
2069
- },
2070
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2071
- if (uncompressed == null) return "";
2072
- 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;
2073
- for (ii = 0; ii < uncompressed.length; ii += 1) {
2074
- context_c = uncompressed.charAt(ii);
2075
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2076
- context_dictionary[context_c] = context_dictSize++;
2077
- context_dictionaryToCreate[context_c] = true;
2078
- }
2079
- context_wc = context_w + context_c;
2080
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2081
- else {
2082
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2083
- if (context_w.charCodeAt(0) < 256) {
2084
- for (i = 0; i < context_numBits; i++) {
2085
- context_data_val = context_data_val << 1;
2086
- if (context_data_position == bitsPerChar - 1) {
2087
- context_data_position = 0;
2088
- context_data.push(getCharFromInt(context_data_val));
2089
- context_data_val = 0;
2090
- } else context_data_position++;
2091
- }
2092
- value = context_w.charCodeAt(0);
2093
- for (i = 0; i < 8; i++) {
2094
- context_data_val = context_data_val << 1 | value & 1;
2095
- if (context_data_position == bitsPerChar - 1) {
2096
- context_data_position = 0;
2097
- context_data.push(getCharFromInt(context_data_val));
2098
- context_data_val = 0;
2099
- } else context_data_position++;
2100
- value = value >> 1;
2101
- }
2102
- } else {
2103
- value = 1;
2104
- for (i = 0; i < context_numBits; i++) {
2105
- context_data_val = context_data_val << 1 | value;
2106
- if (context_data_position == bitsPerChar - 1) {
2107
- context_data_position = 0;
2108
- context_data.push(getCharFromInt(context_data_val));
2109
- context_data_val = 0;
2110
- } else context_data_position++;
2111
- value = 0;
2112
- }
2113
- value = context_w.charCodeAt(0);
2114
- for (i = 0; i < 16; i++) {
2115
- context_data_val = context_data_val << 1 | value & 1;
2116
- if (context_data_position == bitsPerChar - 1) {
2117
- context_data_position = 0;
2118
- context_data.push(getCharFromInt(context_data_val));
2119
- context_data_val = 0;
2120
- } else context_data_position++;
2121
- value = value >> 1;
2122
- }
2123
- }
2124
- context_enlargeIn--;
2125
- if (context_enlargeIn == 0) {
2126
- context_enlargeIn = Math.pow(2, context_numBits);
2127
- context_numBits++;
2128
- }
2129
- delete context_dictionaryToCreate[context_w];
2130
- } else {
2131
- value = context_dictionary[context_w];
2132
- for (i = 0; i < context_numBits; i++) {
2133
- context_data_val = context_data_val << 1 | value & 1;
2134
- if (context_data_position == bitsPerChar - 1) {
2135
- context_data_position = 0;
2136
- context_data.push(getCharFromInt(context_data_val));
2137
- context_data_val = 0;
2138
- } else context_data_position++;
2139
- value = value >> 1;
2140
- }
2141
- }
2142
- context_enlargeIn--;
2143
- if (context_enlargeIn == 0) {
2144
- context_enlargeIn = Math.pow(2, context_numBits);
2145
- context_numBits++;
2146
- }
2147
- context_dictionary[context_wc] = context_dictSize++;
2148
- context_w = String(context_c);
2149
- }
2150
- }
2151
- if (context_w !== "") {
2152
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2153
- if (context_w.charCodeAt(0) < 256) {
2154
- for (i = 0; i < context_numBits; i++) {
2155
- context_data_val = context_data_val << 1;
2156
- if (context_data_position == bitsPerChar - 1) {
2157
- context_data_position = 0;
2158
- context_data.push(getCharFromInt(context_data_val));
2159
- context_data_val = 0;
2160
- } else context_data_position++;
2161
- }
2162
- value = context_w.charCodeAt(0);
2163
- for (i = 0; i < 8; i++) {
2164
- context_data_val = context_data_val << 1 | value & 1;
2165
- if (context_data_position == bitsPerChar - 1) {
2166
- context_data_position = 0;
2167
- context_data.push(getCharFromInt(context_data_val));
2168
- context_data_val = 0;
2169
- } else context_data_position++;
2170
- value = value >> 1;
2171
- }
2172
- } else {
2173
- value = 1;
2174
- for (i = 0; i < context_numBits; i++) {
2175
- context_data_val = context_data_val << 1 | value;
2176
- if (context_data_position == bitsPerChar - 1) {
2177
- context_data_position = 0;
2178
- context_data.push(getCharFromInt(context_data_val));
2179
- context_data_val = 0;
2180
- } else context_data_position++;
2181
- value = 0;
2182
- }
2183
- value = context_w.charCodeAt(0);
2184
- for (i = 0; i < 16; i++) {
2185
- context_data_val = context_data_val << 1 | value & 1;
2186
- if (context_data_position == bitsPerChar - 1) {
2187
- context_data_position = 0;
2188
- context_data.push(getCharFromInt(context_data_val));
2189
- context_data_val = 0;
2190
- } else context_data_position++;
2191
- value = value >> 1;
2192
- }
2193
- }
2194
- context_enlargeIn--;
2195
- if (context_enlargeIn == 0) {
2196
- context_enlargeIn = Math.pow(2, context_numBits);
2197
- context_numBits++;
2198
- }
2199
- delete context_dictionaryToCreate[context_w];
2200
- } else {
2201
- value = context_dictionary[context_w];
2202
- for (i = 0; i < context_numBits; i++) {
2203
- context_data_val = context_data_val << 1 | value & 1;
2204
- if (context_data_position == bitsPerChar - 1) {
2205
- context_data_position = 0;
2206
- context_data.push(getCharFromInt(context_data_val));
2207
- context_data_val = 0;
2208
- } else context_data_position++;
2209
- value = value >> 1;
2210
- }
2211
- }
2212
- context_enlargeIn--;
2213
- if (context_enlargeIn == 0) {
2214
- context_enlargeIn = Math.pow(2, context_numBits);
2215
- context_numBits++;
2216
- }
2217
- }
2218
- value = 2;
2219
- for (i = 0; i < context_numBits; i++) {
2220
- context_data_val = context_data_val << 1 | value & 1;
2221
- if (context_data_position == bitsPerChar - 1) {
2222
- context_data_position = 0;
2223
- context_data.push(getCharFromInt(context_data_val));
2224
- context_data_val = 0;
2225
- } else context_data_position++;
2226
- value = value >> 1;
2227
- }
2228
- while (true) {
2229
- context_data_val = context_data_val << 1;
2230
- if (context_data_position == bitsPerChar - 1) {
2231
- context_data.push(getCharFromInt(context_data_val));
2232
- break;
2233
- } else context_data_position++;
2234
- }
2235
- return context_data.join("");
2236
- },
2237
- decompress: function(compressed) {
2238
- if (compressed == null) return "";
2239
- if (compressed == "") return null;
2240
- return LZString._decompress(compressed.length, 32768, function(index) {
2241
- return compressed.charCodeAt(index);
2242
- });
2243
- },
2244
- _decompress: function(length, resetValue, getNextValue) {
2245
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2246
- val: getNextValue(0),
2247
- position: resetValue,
2248
- index: 1
2249
- };
2250
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
2251
- bits = 0;
2252
- maxpower = Math.pow(2, 2);
2253
- power = 1;
2254
- while (power != maxpower) {
2255
- resb = data.val & data.position;
2256
- data.position >>= 1;
2257
- if (data.position == 0) {
2258
- data.position = resetValue;
2259
- data.val = getNextValue(data.index++);
2260
- }
2261
- bits |= (resb > 0 ? 1 : 0) * power;
2262
- power <<= 1;
2263
- }
2264
- switch (bits) {
2265
- case 0:
2266
- bits = 0;
2267
- maxpower = Math.pow(2, 8);
2268
- power = 1;
2269
- while (power != maxpower) {
2270
- resb = data.val & data.position;
2271
- data.position >>= 1;
2272
- if (data.position == 0) {
2273
- data.position = resetValue;
2274
- data.val = getNextValue(data.index++);
2275
- }
2276
- bits |= (resb > 0 ? 1 : 0) * power;
2277
- power <<= 1;
2278
- }
2279
- c = f(bits);
2280
- break;
2281
- case 1:
2282
- bits = 0;
2283
- maxpower = Math.pow(2, 16);
2284
- power = 1;
2285
- while (power != maxpower) {
2286
- resb = data.val & data.position;
2287
- data.position >>= 1;
2288
- if (data.position == 0) {
2289
- data.position = resetValue;
2290
- data.val = getNextValue(data.index++);
2291
- }
2292
- bits |= (resb > 0 ? 1 : 0) * power;
2293
- power <<= 1;
2294
- }
2295
- c = f(bits);
2296
- break;
2297
- case 2: return "";
2298
- }
2299
- dictionary[3] = c;
2300
- w = c;
2301
- result.push(c);
2302
- while (true) {
2303
- if (data.index > length) return "";
2304
- bits = 0;
2305
- maxpower = Math.pow(2, numBits);
2306
- power = 1;
2307
- while (power != maxpower) {
2308
- resb = data.val & data.position;
2309
- data.position >>= 1;
2310
- if (data.position == 0) {
2311
- data.position = resetValue;
2312
- data.val = getNextValue(data.index++);
2313
- }
2314
- bits |= (resb > 0 ? 1 : 0) * power;
2315
- power <<= 1;
2316
- }
2317
- switch (c = bits) {
2318
- case 0:
2319
- bits = 0;
2320
- maxpower = Math.pow(2, 8);
2321
- power = 1;
2322
- while (power != maxpower) {
2323
- resb = data.val & data.position;
2324
- data.position >>= 1;
2325
- if (data.position == 0) {
2326
- data.position = resetValue;
2327
- data.val = getNextValue(data.index++);
2328
- }
2329
- bits |= (resb > 0 ? 1 : 0) * power;
2330
- power <<= 1;
2331
- }
2332
- dictionary[dictSize++] = f(bits);
2333
- c = dictSize - 1;
2334
- enlargeIn--;
2335
- break;
2336
- case 1:
2337
- bits = 0;
2338
- maxpower = Math.pow(2, 16);
2339
- power = 1;
2340
- while (power != maxpower) {
2341
- resb = data.val & data.position;
2342
- data.position >>= 1;
2343
- if (data.position == 0) {
2344
- data.position = resetValue;
2345
- data.val = getNextValue(data.index++);
2346
- }
2347
- bits |= (resb > 0 ? 1 : 0) * power;
2348
- power <<= 1;
2349
- }
2350
- dictionary[dictSize++] = f(bits);
2351
- c = dictSize - 1;
2352
- enlargeIn--;
2353
- break;
2354
- case 2: return result.join("");
2355
- }
2356
- if (enlargeIn == 0) {
2357
- enlargeIn = Math.pow(2, numBits);
2358
- numBits++;
2359
- }
2360
- if (dictionary[c]) entry = dictionary[c];
2361
- else if (c === dictSize) entry = w + w.charAt(0);
2362
- else return null;
2363
- result.push(entry);
2364
- dictionary[dictSize++] = w + entry.charAt(0);
2365
- enlargeIn--;
2366
- w = entry;
2367
- if (enlargeIn == 0) {
2368
- enlargeIn = Math.pow(2, numBits);
2369
- numBits++;
2370
- }
2371
- }
2372
- }
2373
- };
2374
- return LZString;
2375
- })();
2376
- if (typeof define === "function" && define.amd) define(function() {
2377
- return LZString;
2378
- });
2379
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2380
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2381
- return LZString;
2382
- });
2383
- })))(), 1);
2384
- var DocumentModelNotFoundError = class extends Error {
2385
- documentType;
2386
- name = "DocumentModelNotFoundError";
2387
- constructor(documentType) {
2388
- super(`Document model module for type ${documentType} not found`);
2389
- this.documentType = documentType;
2390
- }
2391
- static isError(error) {
2392
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2393
2173
  }
2394
- };
2395
- var DocumentTypeMismatchError = class extends Error {
2396
- constructor(documentId, expectedType, actualType) {
2397
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2398
- }
2399
- };
2400
- var NoSelectedDocumentError = class extends Error {
2401
- constructor() {
2402
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2403
- }
2404
- };
2405
- function getUserPermissions() {
2406
- const user = window.ph?.renown?.user;
2407
- const allowList = window.ph?.allowList;
2408
- if (!allowList) return {
2409
- isAllowedToCreateDocuments: true,
2410
- isAllowedToEditDocuments: true
2411
- };
2412
- return {
2413
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2414
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2415
- };
2416
- }
2417
- const BASE_STATE_KEYS = new Set(["auth"]);
2418
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2419
- async function downloadFile(document, fileName) {
2420
- try {
2421
- const data = await createZip(document);
2422
- const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2423
- const link = window.document.createElement("a");
2424
- link.style.display = "none";
2425
- link.href = URL.createObjectURL(blob);
2426
- link.download = fileName;
2427
- window.document.body.appendChild(link);
2428
- link.click();
2429
- window.document.body.removeChild(link);
2174
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2175
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2176
+ return node !== void 0 && isFileNode(node);
2177
+ });
2178
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2179
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2180
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2181
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2182
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2430
2183
  } catch (e) {
2431
- logger.error(e instanceof Error ? e.message : String(e));
2432
- }
2433
- }
2434
- async function getDocumentExtension(document) {
2435
- const documentType = document.header.documentType;
2436
- let rawExtension;
2437
- if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2438
- else {
2439
- const reactorClient = window.ph?.reactorClient;
2440
- if (reactorClient) {
2441
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2442
- rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2443
- }
2184
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2444
2185
  }
2445
- return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2186
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2446
2187
  }
2447
2188
  /**
2448
- * Fetches all operations for a document using cursor-based pagination.
2449
- * The reactor client handles multi-scope cursors transparently via
2450
- * composite cursors, so all scopes are fetched in a single paginated stream.
2189
+ * Upgrades a document to a newer document model version. Defaults to the
2190
+ * latest registered version for the document's type.
2451
2191
  */
2452
- async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2453
- const scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));
2454
- const operations = {};
2455
- for (const scope of scopes) operations[scope] = [];
2456
- let cursor = "";
2457
- do {
2458
- const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2459
- cursor,
2460
- limit: pageSize
2461
- });
2462
- for (const op of page.results) {
2463
- const scope = op.action.scope ?? "global";
2464
- if (operations[scope]) operations[scope].push(op);
2465
- }
2466
- cursor = page.nextCursor ?? "";
2467
- } while (cursor);
2468
- return operations;
2469
- }
2470
- function extractInitialState(documentScopeOps) {
2471
- const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2472
- if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2473
- const input = upgradeOp.action.input;
2474
- const initialState = input.initialState ?? input.state;
2475
- if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2476
- return initialState;
2477
- }
2478
- function filterDomainOperations(operations) {
2479
- return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2480
- }
2481
- async function exportFile(document, suggestedName) {
2482
- const reactorClient = window.ph?.reactorClient;
2192
+ async function upgradeDocument(documentId, toVersion) {
2193
+ const reactorClient = window.ph?.reactorClientModule?.client;
2483
2194
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2484
- const operations = await fetchDocumentOperations(reactorClient, document);
2485
- const initialState = extractInitialState(operations["document"] ?? []);
2486
- const documentWithOps = {
2487
- ...document,
2488
- operations,
2489
- initialState
2490
- };
2491
- const extension = await getDocumentExtension(documentWithOps);
2492
- const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2493
- const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2494
- if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2495
- try {
2496
- const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2497
- await baseSaveToFileHandle(documentWithOps, fileHandle);
2498
- return fileHandle;
2499
- } catch (e) {
2500
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2501
- }
2195
+ return reactorClient.upgradeDocument(documentId, toVersion);
2502
2196
  }
2503
- /**
2504
- * Loads a document file and replays it with version-aware reducers from the registry.
2505
- * Falls back to single-version legacy replay when no upgrade manifest is registered for
2506
- * the document type.
2197
+ gql`
2198
+ mutation MutateDocumentWithOperations(
2199
+ $documentIdentifier: String!
2200
+ $actions: [ActionInput!]!
2201
+ $sinceRevision: Int
2202
+ $scopes: [String!]
2203
+ $branch: String
2204
+ ) {
2205
+ mutateDocument: execute(
2206
+ documentIdentifier: $documentIdentifier
2207
+ actions: $actions
2208
+ branch: $branch
2209
+ ) {
2210
+ ...PHDocumentFields
2211
+ operations(
2212
+ filter: {
2213
+ sinceRevision: $sinceRevision
2214
+ scopes: $scopes
2215
+ branch: $branch
2216
+ }
2217
+ ) {
2218
+ items {
2219
+ ...ReactorOperationFields
2220
+ }
2221
+ }
2222
+ }
2223
+ }
2224
+ ${PhDocumentFieldsFragmentDoc}
2225
+ ${gql`
2226
+ fragment ReactorOperationFields on ReactorOperation {
2227
+ index
2228
+ timestampUtcMs
2229
+ hash
2230
+ skip
2231
+ error
2232
+ deniedReason
2233
+ id
2234
+ action {
2235
+ id
2236
+ type
2237
+ timestampUtcMs
2238
+ input
2239
+ scope
2240
+ context {
2241
+ signer {
2242
+ user {
2243
+ address
2244
+ networkId
2245
+ chainId
2246
+ }
2247
+ app {
2248
+ name
2249
+ key
2250
+ }
2251
+ signatures
2252
+ }
2253
+ }
2254
+ }
2255
+ }
2256
+ `}
2257
+ `;
2258
+ 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;
2259
+ PropagationMode.Cascade, PropagationMode.Orphan;
2260
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2261
+ /** Sets whether external controls are enabled for a given editor. */
2262
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2263
+ /** Gets whether external controls are enabled for a given editor. */
2264
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2265
+ isExternalControlsEnabledEventFunctions.addEventHandler;
2266
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2267
+ /** Sets whether drag and drop is enabled for a given app. */
2268
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2269
+ /** Gets whether drag and drop is enabled for a given app. */
2270
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2271
+ isDragAndDropEnabledEventFunctions.addEventHandler;
2272
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2273
+ /** Sets the allowed document types for a given app. */
2274
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2275
+ /** Defines the document types a drive supports.
2276
+ *
2277
+ * Defaults to all of the document types registered in the reactor.
2507
2278
  */
2508
- async function loadFile(path) {
2509
- const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2510
- const reactorClient = window.ph?.reactorClient;
2511
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2512
- const documentType = baseDocument.header.documentType;
2513
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2514
- const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2515
- if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2516
- const reducers = {};
2517
- for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2518
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2519
- let upgradeManifest;
2520
- if (registry) try {
2521
- upgradeManifest = registry.getUpgradeManifest(documentType);
2522
- } catch {}
2523
- return baseLoadFromInputVersioned(path, {
2524
- reducers,
2525
- upgradeManifest
2526
- });
2527
- }
2528
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2529
- const { isAllowedToCreateDocuments } = getUserPermissions();
2530
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2531
- const reactorClient = window.ph?.reactorClient;
2532
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2533
- const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2534
- const newDocument = document ?? documentModelModule.utils.createDocument();
2535
- newDocument.header.name = name;
2536
- if (preferredEditor) newDocument.header.meta = {
2537
- ...newDocument.header.meta,
2538
- preferredEditor
2539
- };
2540
- let newDoc;
2541
- try {
2542
- newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2543
- } catch (e) {
2544
- logger.error("Error adding document: @error", e);
2545
- throw new Error("There was an error adding document", { cause: e });
2546
- }
2547
- return {
2548
- id: newDoc.header.id,
2549
- name: newDoc.header.name,
2550
- documentType,
2551
- parentFolder: parentFolder ?? null,
2552
- kind: "file"
2553
- };
2554
- }
2555
- async function addFile(file, driveId, name, parentFolder) {
2556
- logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2557
- const { isAllowedToCreateDocuments } = getUserPermissions();
2558
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2559
- const document = await loadFile(file);
2560
- let duplicateId = false;
2561
- const reactorClient = window.ph?.reactorClient;
2562
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2563
- try {
2564
- await reactorClient.get(document.header.id);
2565
- duplicateId = true;
2566
- } catch {}
2567
- const documentId = duplicateId ? generateId() : document.header.id;
2568
- const header = createPresignedHeader(documentId, document.header.documentType);
2569
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2570
- header.meta = document.header.meta;
2571
- header.name = name || document.header.name;
2572
- const initialDocument = {
2573
- ...document,
2574
- header,
2575
- state: document.initialState,
2576
- operations: Object.keys(document.operations).reduce((acc, key) => {
2577
- acc[key] = [];
2578
- return acc;
2579
- }, {})
2580
- };
2581
- await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2582
- await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2583
- }
2584
- async function addFolder(driveId, name, parentFolder) {
2585
- const { isAllowedToCreateDocuments } = getUserPermissions();
2586
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2587
- const reactorClient = window.ph?.reactorClient;
2588
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2589
- await reactorClient.get(driveId);
2590
- const folderId = generateId();
2591
- const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2592
- id: folderId,
2593
- name,
2594
- parentFolder
2595
- })])).state.global.nodes.find((node) => node.id === folderId);
2596
- if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2597
- return node;
2598
- }
2599
- async function renameNode(driveId, nodeId, name) {
2600
- const { isAllowedToCreateDocuments } = getUserPermissions();
2601
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2602
- const reactorClient = window.ph?.reactorClient;
2603
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2604
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2605
- const node = (await reactorClient.execute(driveId, "main", [updateNode({
2606
- id: nodeId,
2607
- name
2608
- })])).state.global.nodes.find((n) => n.id === nodeId);
2609
- if (!node) throw new Error("There was an error renaming node in the drive");
2610
- return node;
2611
- }
2612
- async function renameDriveNode(driveId, nodeId, name) {
2613
- const { isAllowedToCreateDocuments } = getUserPermissions();
2614
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2615
- const reactorClient = window.ph?.reactorClient;
2616
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2617
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2618
- await reactorClient.execute(driveId, "main", [updateNode({
2619
- id: nodeId,
2620
- name
2621
- })]);
2622
- return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2623
- }
2624
- async function moveNodeById(args) {
2625
- const { driveId, srcId, targetId } = args;
2626
- if (!driveId || !srcId) return;
2627
- const { isAllowedToCreateDocuments } = getUserPermissions();
2628
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2629
- const reactorClient = window.ph?.reactorClient;
2630
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2631
- const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2632
- if (t(targetParentFolder, srcId)) return;
2633
- return await reactorClient.execute(driveId, "main", [moveNode({
2634
- srcFolder: srcId,
2635
- targetParentFolder
2636
- })]);
2637
- }
2638
- async function moveNode$1(driveId, src, target) {
2639
- const { isAllowedToCreateDocuments } = getUserPermissions();
2640
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2641
- const reactorClient = window.ph?.reactorClient;
2642
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2643
- return await reactorClient.execute(driveId, "main", [moveNode({
2644
- srcFolder: src.id,
2645
- targetParentFolder: target?.id
2646
- })]);
2647
- }
2648
- /**
2649
- * Duplicates a document under a new id using version-aware replay.
2650
- * Falls back gracefully when no upgrade manifest is registered for the document type.
2651
- */
2652
- async function _duplicateDocument(reactor, document, newId = generateId()) {
2653
- const documentType = document.header.documentType;
2654
- const { results: allModules } = await reactor.getDocumentModelModules();
2655
- const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2656
- const reducers = {};
2657
- for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2658
- if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2659
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2660
- let upgradeManifest;
2661
- if (registry) try {
2662
- upgradeManifest = registry.getUpgradeManifest(documentType);
2663
- } catch {}
2664
- const config = {
2665
- reducers,
2666
- upgradeManifest
2667
- };
2668
- const header = createPresignedHeader(newId, documentType);
2669
- return replayDocumentVersioned(document.initialState, document.operations, config, header);
2670
- }
2671
- async function copyNode$1(driveId, src, target) {
2672
- const reactor = window.ph?.reactorClient;
2673
- if (!reactor) return;
2674
- const { isAllowedToCreateDocuments } = getUserPermissions();
2675
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2676
- const drive = await reactor.get(driveId);
2677
- const copyNodesInput = generateNodesCopy({
2678
- srcId: src.id,
2679
- targetParentFolder: target?.id,
2680
- targetName: src.name
2681
- }, () => generateId(), drive.state.global.nodes);
2682
- const resolvedNamesMap = /* @__PURE__ */ new Map();
2683
- for (const copyNodeInput of copyNodesInput) {
2684
- const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2685
- if (node) {
2686
- const resolvedName = handleTargetNameCollisions({
2687
- nodes: drive.state.global.nodes,
2688
- srcName: copyNodeInput.targetName || node.name,
2689
- srcKind: isFileNode(node) ? "file" : "folder",
2690
- targetParentFolder: copyNodeInput.targetParentFolder || null
2691
- });
2692
- resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2693
- }
2694
- }
2695
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2696
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2697
- return node !== void 0 && isFileNode(node);
2698
- });
2699
- for (const fileNodeToCopy of fileNodesToCopy) try {
2700
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2701
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2702
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2703
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2704
- } catch (e) {
2705
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2706
- }
2707
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2708
- }
2709
- const modalEventFunctions = makePHEventFunctions("modal");
2710
- modalEventFunctions.useValue;
2711
- /** Sets the current modal */
2712
- const setPHModal = modalEventFunctions.setValue;
2713
- modalEventFunctions.addEventHandler;
2714
- /** Shows a modal */
2715
- function showPHModal(modal) {
2716
- setPHModal(modal);
2717
- }
2718
- /** Shows the create document modal */
2719
- function showCreateDocumentModal(documentType) {
2720
- setPHModal({
2721
- type: "createDocument",
2722
- documentType
2723
- });
2724
- }
2725
- /** Shows the delete node modal */
2726
- function showDeleteNodeModal(nodeOrId) {
2727
- setPHModal({
2728
- type: "deleteItem",
2729
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2730
- });
2731
- }
2732
- /** Document types that represent a "drive": a container of nodes. */
2733
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
2734
- const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2735
- /** Sets whether external controls are enabled for a given editor. */
2736
- const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2737
- /** Gets whether external controls are enabled for a given editor. */
2738
- const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2739
- isExternalControlsEnabledEventFunctions.addEventHandler;
2740
- const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2741
- /** Sets whether drag and drop is enabled for a given app. */
2742
- const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2743
- /** Gets whether drag and drop is enabled for a given app. */
2744
- const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2745
- isDragAndDropEnabledEventFunctions.addEventHandler;
2746
- const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2747
- /** Sets the allowed document types for a given app. */
2748
- const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2749
- /** Defines the document types a drive supports.
2750
- *
2751
- * Defaults to all of the document types registered in the reactor.
2752
- */
2753
- function useAllowedDocumentTypes() {
2754
- return allowedDocumentTypesEventFunctions.useValue();
2279
+ function useAllowedDocumentTypes() {
2280
+ return allowedDocumentTypesEventFunctions.useValue();
2755
2281
  }
2756
2282
  allowedDocumentTypesEventFunctions.addEventHandler;
2757
2283
  const phAppConfigSetters = {
@@ -2796,6 +2322,8 @@ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabl
2796
2322
  const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2797
2323
  const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2798
2324
  const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2325
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
2326
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
2799
2327
  const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2800
2328
  const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2801
2329
  const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
@@ -2893,6 +2421,8 @@ const nonUserConfigSetters = {
2893
2421
  renownUrl: setRenownUrl,
2894
2422
  renownNetworkId: setRenownNetworkId,
2895
2423
  renownChainId: setRenownChainId,
2424
+ switchboardUrl: setSwitchboardUrl,
2425
+ renownAdapters: setRenownAdapters,
2896
2426
  sentryRelease: setSentryRelease,
2897
2427
  sentryDsn: setSentryDsn,
2898
2428
  sentryEnv: setSentryEnv,
@@ -2941,6 +2471,8 @@ const nonUserConfigHooks = {
2941
2471
  renownUrl: useRenownUrl,
2942
2472
  renownNetworkId: useRenownNetworkId,
2943
2473
  renownChainId: useRenownChainId,
2474
+ switchboardUrl: useSwitchboardUrl,
2475
+ renownAdapters: useRenownAdapters,
2944
2476
  sentryRelease: useSentryRelease,
2945
2477
  sentryDsn: useSentryDsn,
2946
2478
  sentryEnv: useSentryEnv,
@@ -3121,215 +2653,931 @@ function deferDriveSelection(driveSlug) {
3121
2653
  scheduleTick();
3122
2654
  return;
3123
2655
  }
3124
- cancelPendingDriveSelection();
3125
- const pathname = resolveUrlPathname("/");
3126
- if (pathname === window.location.pathname) return;
3127
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3128
- }, DEFERRED_DRIVE_TICK_MS);
3129
- };
3130
- scheduleTick();
3131
- }
3132
- function useDropTarget() {
3133
- const [isDropTarget, setIsDropTarget] = useState(false);
3134
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3135
- const targetSetter = n$1(() => setIsDropTarget(true), {
3136
- triggerAt: "start",
3137
- minQuietPeriodMs: 100
2656
+ cancelPendingDriveSelection();
2657
+ const pathname = resolveUrlPathname("/");
2658
+ if (pathname === window.location.pathname) return;
2659
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2660
+ }, DEFERRED_DRIVE_TICK_MS);
2661
+ };
2662
+ scheduleTick();
2663
+ }
2664
+ function useDropTarget() {
2665
+ const [isDropTarget, setIsDropTarget] = useState(false);
2666
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2667
+ const targetSetter = n$1(() => setIsDropTarget(true), {
2668
+ triggerAt: "start",
2669
+ minQuietPeriodMs: 100
2670
+ });
2671
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
2672
+ triggerAt: "start",
2673
+ minQuietPeriodMs: 100
2674
+ });
2675
+ function setTarget() {
2676
+ if (!isDragAndDropEnabled) return;
2677
+ targetUnsetter.cancel();
2678
+ targetSetter.call();
2679
+ }
2680
+ function unsetTarget() {
2681
+ if (!isDragAndDropEnabled) return;
2682
+ targetSetter.cancel();
2683
+ targetUnsetter.call();
2684
+ }
2685
+ return {
2686
+ isDropTarget,
2687
+ setTarget,
2688
+ unsetTarget
2689
+ };
2690
+ }
2691
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
2692
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
2693
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
2694
+ draggingNodeEventFunctions.addEventHandler;
2695
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
2696
+ reducer: (_, newNode) => newNode,
2697
+ triggerAt: "start",
2698
+ minQuietPeriodMs: 100
2699
+ });
2700
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
2701
+ triggerAt: "start",
2702
+ minQuietPeriodMs: 100
2703
+ });
2704
+ function setDragging(node) {
2705
+ draggingNodeUnsetter.cancel();
2706
+ draggingNodeSetter.call(node);
2707
+ }
2708
+ function unsetDragging() {
2709
+ draggingNodeSetter.cancel();
2710
+ draggingNodeUnsetter.call();
2711
+ }
2712
+ 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));
2713
+ function useDragNode(args) {
2714
+ const { srcId, parentId } = args;
2715
+ const driveId = useSelectedDriveId();
2716
+ const draggingNodeId = useDraggingNode()?.srcId;
2717
+ const params = {
2718
+ driveId,
2719
+ srcId,
2720
+ parentId
2721
+ };
2722
+ const draggable = isNodeDrag(params);
2723
+ const isDragging = t$4({
2724
+ srcId,
2725
+ draggingNodeId
2726
+ }, [
2727
+ () => draggable,
2728
+ ({ srcId }) => e$2(srcId),
2729
+ ({ draggingNodeId }) => e$2(draggingNodeId),
2730
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
2731
+ ]);
2732
+ const onDragStart = () => {
2733
+ if (!draggable) return;
2734
+ setDragging(params);
2735
+ };
2736
+ const onDragEnd = () => {
2737
+ if (!draggable) return;
2738
+ unsetDragging();
2739
+ };
2740
+ return {
2741
+ isDragging,
2742
+ draggable,
2743
+ onDragStart,
2744
+ onDragEnd
2745
+ };
2746
+ }
2747
+ 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));
2748
+ function useDropNode(targetId) {
2749
+ const driveId = useSelectedDriveId();
2750
+ const { srcId, parentId } = useDraggingNode() ?? {};
2751
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
2752
+ const params = {
2753
+ driveId,
2754
+ parentId,
2755
+ targetId,
2756
+ srcId
2757
+ };
2758
+ function handleNodeDrop(event, cb) {
2759
+ if (!isNodeDrop(params)) return;
2760
+ event.preventDefault();
2761
+ event.stopPropagation();
2762
+ cb?.();
2763
+ }
2764
+ const onDragEnter = (event) => handleNodeDrop(event);
2765
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
2766
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
2767
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
2768
+ unsetDragging();
2769
+ unsetTarget();
2770
+ moveNodeById(params).catch(console.error);
2771
+ }));
2772
+ return {
2773
+ isDropTarget,
2774
+ onDragEnter,
2775
+ onDragOver,
2776
+ onDragLeave,
2777
+ onDrop
2778
+ };
2779
+ }
2780
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
2781
+ graphQLReactorClientEventFunctions.useValue;
2782
+ graphQLReactorClientEventFunctions.setValue;
2783
+ graphQLReactorClientEventFunctions.addEventHandler;
2784
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
2785
+ packageDiscoveryFunctions.useValue;
2786
+ packageDiscoveryFunctions.setValue;
2787
+ packageDiscoveryFunctions.addEventHandler;
2788
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
2789
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
2790
+ /** Returns the reactor client module (in-process or worker-backed) */
2791
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
2792
+ reactorClientModuleEventFunctions.setValue;
2793
+ reactorClientModuleEventFunctions.addEventHandler;
2794
+ reactorClientEventFunctions.useValue;
2795
+ reactorClientEventFunctions.setValue;
2796
+ reactorClientEventFunctions.addEventHandler;
2797
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
2798
+ const useSyncList = () => {
2799
+ return useSync()?.list() ?? [];
2800
+ };
2801
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
2802
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
2803
+ revisionHistoryEventFunctions.useValue;
2804
+ /** Sets revision history visibility */
2805
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
2806
+ revisionHistoryEventFunctions.addEventHandler;
2807
+ /** Shows the revision history */
2808
+ function showRevisionHistory() {
2809
+ setRevisionHistoryVisible(true);
2810
+ }
2811
+ /** Sorts nodes by name. */
2812
+ function sortNodesByName(nodes) {
2813
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
2814
+ }
2815
+ /** Returns whether a node is a file. */
2816
+ function isFileNodeKind(node) {
2817
+ if (!node) return false;
2818
+ return node.kind.toUpperCase() === "FILE";
2819
+ }
2820
+ /** Returns whether a node is a folder. */
2821
+ function isFolderNodeKind(node) {
2822
+ if (!node) return false;
2823
+ return node.kind.toUpperCase() === "FOLDER";
2824
+ }
2825
+ /** Returns the nodes in the selected drive. */
2826
+ function useNodesInSelectedDrive() {
2827
+ const [selectedDrive] = useSelectedDriveSafe();
2828
+ return selectedDrive?.state.global.nodes;
2829
+ }
2830
+ /** Returns the folder nodes in the selected drive. */
2831
+ function useFolderNodesInSelectedDrive() {
2832
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
2833
+ }
2834
+ /** Returns the selected node. */
2835
+ function useSelectedNode() {
2836
+ const selectedNodeId = useSelectedNodeId();
2837
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
2838
+ }
2839
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
2840
+ selectedTimelineItemEventFunctions.useValue;
2841
+ selectedTimelineItemEventFunctions.setValue;
2842
+ selectedTimelineItemEventFunctions.addEventHandler;
2843
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
2844
+ selectedTimelineRevisionEventFunctions.useValue;
2845
+ selectedTimelineRevisionEventFunctions.setValue;
2846
+ selectedTimelineRevisionEventFunctions.addEventHandler;
2847
+ const toastEventFunctions = makePHEventFunctions("toast");
2848
+ /** Returns the toast function */
2849
+ const usePHToast = toastEventFunctions.useValue;
2850
+ toastEventFunctions.setValue;
2851
+ toastEventFunctions.addEventHandler;
2852
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
2853
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
2854
+ /** Returns all of the Vetra packages loaded by the Connect instance */
2855
+ const useVetraPackages = () => {
2856
+ const packageManager = useVetraPackageManager();
2857
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
2858
+ };
2859
+ vetraPackageManagerFunctions.addEventHandler;
2860
+ function useDocumentModelModules() {
2861
+ 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);
2862
+ }
2863
+ /**
2864
+ * Resolves a document model module by document type, mirroring the registry's
2865
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
2866
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
2867
+ * with `version` given only an exact match is returned. The reactor resolves
2868
+ * modules the same way when a document is created, so metadata read through
2869
+ * this hook and the version a creation actually uses cannot disagree.
2870
+ */
2871
+ function useDocumentModelModuleById(id, version) {
2872
+ const documentModelModules = useDocumentModelModules();
2873
+ if (!id || !documentModelModules) return void 0;
2874
+ let latestModule;
2875
+ let latestVersion = -1;
2876
+ for (const module of documentModelModules) {
2877
+ if (module.documentModel.global.id !== id) continue;
2878
+ const moduleVersion = module.version ?? 1;
2879
+ if (version !== void 0) {
2880
+ if (moduleVersion === version) return module;
2881
+ continue;
2882
+ }
2883
+ if (moduleVersion > latestVersion) {
2884
+ latestVersion = moduleVersion;
2885
+ latestModule = module;
2886
+ }
2887
+ }
2888
+ return latestModule;
2889
+ }
2890
+ //#endregion
2891
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
2892
+ const normalizeDescriptors = (error) => {
2893
+ CORE_ERROR_PROPS.forEach((propName) => {
2894
+ normalizeDescriptor(error, propName);
2895
+ });
2896
+ };
2897
+ const CORE_ERROR_PROPS = [
2898
+ "name",
2899
+ "message",
2900
+ "stack",
2901
+ "cause",
2902
+ "errors"
2903
+ ];
2904
+ const normalizeDescriptor = (error, propName) => {
2905
+ const descriptor = getDescriptor(error, propName);
2906
+ if (descriptor === void 0) return;
2907
+ if (isReadonlyGetter(descriptor)) {
2908
+ setErrorProperty(error, propName, error[propName]);
2909
+ return;
2910
+ }
2911
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
2912
+ };
2913
+ const getDescriptor = (value, propName) => {
2914
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
2915
+ if (descriptor !== void 0) return descriptor;
2916
+ const prototype = Object.getPrototypeOf(value);
2917
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
2918
+ };
2919
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
2920
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
2921
+ const setErrorProperty = (error, propName, value) => {
2922
+ setErrorDescriptor(error, propName, { value });
2923
+ };
2924
+ const setErrorDescriptor = (error, propName, descriptor) => {
2925
+ Object.defineProperty(error, propName, {
2926
+ ...descriptor,
2927
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
2928
+ enumerable: false,
2929
+ configurable: true
2930
+ });
2931
+ };
2932
+ //#endregion
2933
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
2934
+ const normalizeAggregate = (error, recurse) => {
2935
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
2936
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
2937
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
2938
+ };
2939
+ const isDefined = (error) => error !== void 0;
2940
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
2941
+ const deleteAggregateErrors = (error) => {
2942
+ delete error.errors;
2943
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
2944
+ };
2945
+ //#endregion
2946
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
2947
+ const normalizeCause = (error, recurse) => {
2948
+ if (!("cause" in error)) return;
2949
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
2950
+ if (cause === void 0) delete error.cause;
2951
+ else setErrorProperty(error, "cause", cause);
2952
+ };
2953
+ //#endregion
2954
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
2955
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
2956
+ const isInstanceOfError = (value) => {
2957
+ try {
2958
+ return value instanceof Error;
2959
+ } catch {
2960
+ return false;
2961
+ }
2962
+ };
2963
+ const hasErrorTag = (value) => {
2964
+ try {
2965
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
2966
+ } catch {
2967
+ return false;
2968
+ }
2969
+ };
2970
+ const ERROR_TAGS = new Set([
2971
+ "[object Error]",
2972
+ "[object DOMException]",
2973
+ "[object DOMError]",
2974
+ "[object Exception]"
2975
+ ]);
2976
+ //#endregion
2977
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
2978
+ function isPlainObject(value) {
2979
+ if (typeof value !== "object" || value === null) return false;
2980
+ const prototype = Object.getPrototypeOf(value);
2981
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
2982
+ }
2983
+ //#endregion
2984
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
2985
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
2986
+ const isNonConfigurableProp = (error, propName) => {
2987
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
2988
+ return descriptor !== void 0 && !descriptor.configurable;
2989
+ };
2990
+ const isThrowingProp = (error, propName) => {
2991
+ try {
2992
+ error[propName];
2993
+ return false;
2994
+ } catch {
2995
+ return true;
2996
+ }
2997
+ };
2998
+ //#endregion
2999
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
3000
+ const setStack = (error) => {
3001
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
3002
+ };
3003
+ const getStack = (message = "", name = "Error") => {
3004
+ const { stack } = new (getErrorClass(name))(message);
3005
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
3006
+ };
3007
+ const getErrorClass = (name) => {
3008
+ const descriptor = {
3009
+ value: name,
3010
+ enumerable: false,
3011
+ writable: true,
3012
+ configurable: true
3013
+ };
3014
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
3015
+ Object.defineProperty(StackError.prototype, "name", descriptor);
3016
+ return StackError;
3017
+ };
3018
+ //#endregion
3019
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
3020
+ const copyObject = (object) => {
3021
+ const objectCopy = {};
3022
+ for (const propName of getPropsToCopy(object)) try {
3023
+ const value = object[propName];
3024
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
3025
+ Object.defineProperty(objectCopy, propName, {
3026
+ value,
3027
+ enumerable,
3028
+ configurable,
3029
+ writable
3030
+ });
3031
+ } catch {}
3032
+ return objectCopy;
3033
+ };
3034
+ const getPropsToCopy = (object) => {
3035
+ const propNames = getOwnKeys(object);
3036
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
3037
+ return propNames;
3038
+ };
3039
+ const getOwnKeys = (object) => {
3040
+ try {
3041
+ return Reflect.ownKeys(object);
3042
+ } catch {
3043
+ return [];
3044
+ }
3045
+ };
3046
+ const isInheritedProp = (object, propName) => {
3047
+ try {
3048
+ return propName in object && !Object.hasOwn(object, propName);
3049
+ } catch {
3050
+ return false;
3051
+ }
3052
+ };
3053
+ //#endregion
3054
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
3055
+ const objectifyError = (object) => {
3056
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
3057
+ const messageA = getMessage(message, objectA);
3058
+ const error = newError(name, messageA);
3059
+ if (message === messageA) assignObjectProps(error, objectA);
3060
+ Object.entries({
3061
+ name,
3062
+ stack,
3063
+ cause,
3064
+ errors
3065
+ }).forEach(([propName, propValue]) => {
3066
+ setNewErrorProperty(error, propName, propValue);
3067
+ });
3068
+ if (stack === void 0) setStack(error);
3069
+ return error;
3070
+ };
3071
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
3072
+ const safeJsonStringify = (object) => {
3073
+ try {
3074
+ return JSON.stringify(object);
3075
+ } catch {
3076
+ return safeStringify(object);
3077
+ }
3078
+ };
3079
+ const safeStringify = (object) => {
3080
+ try {
3081
+ return String(object);
3082
+ } catch {
3083
+ return "Invalid error";
3084
+ }
3085
+ };
3086
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
3087
+ const MESSAGE_MAX_SIZE = 1e3;
3088
+ const newError = (name, message) => {
3089
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
3090
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
3091
+ return new Error(message);
3092
+ };
3093
+ const NATIVE_ERRORS = {
3094
+ Error,
3095
+ ReferenceError,
3096
+ TypeError,
3097
+ SyntaxError,
3098
+ RangeError,
3099
+ URIError,
3100
+ EvalError
3101
+ };
3102
+ const assignObjectProps = (error, object) => {
3103
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3104
+ };
3105
+ const setNewErrorProperty = (error, propName, propValue) => {
3106
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3107
+ };
3108
+ //#endregion
3109
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3110
+ const stringifyError = (value) => {
3111
+ try {
3112
+ const error = new Error(String(value));
3113
+ setStack(error);
3114
+ return error;
3115
+ } catch (error_) {
3116
+ return error_;
3117
+ }
3118
+ };
3119
+ //#endregion
3120
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3121
+ const { toString: objectToString } = Object.prototype;
3122
+ const createError = (value) => {
3123
+ if (isErrorPlainObj(value)) return objectifyError(value);
3124
+ if (!isErrorInstance(value)) return stringifyError(value);
3125
+ if (isInvalidError(value)) return objectifyError(value);
3126
+ return value;
3127
+ };
3128
+ const isErrorPlainObj = (value) => {
3129
+ try {
3130
+ return isPlainObject(value);
3131
+ } catch {
3132
+ return false;
3133
+ }
3134
+ };
3135
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3136
+ const isProxy = (value) => {
3137
+ try {
3138
+ return objectToString.call(value) === "[object Object]";
3139
+ } catch {
3140
+ return true;
3141
+ }
3142
+ };
3143
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3144
+ //#endregion
3145
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3146
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3147
+ const recurseException = (error, parents, shallow) => {
3148
+ if (parents.includes(error)) return;
3149
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3150
+ const errorA = createError(error);
3151
+ normalizeProps(errorA, recurse);
3152
+ return errorA;
3153
+ };
3154
+ const identity = (error) => error;
3155
+ const normalizeProps = (error, recurse) => {
3156
+ normalizeName(error);
3157
+ normalizeMessage(error);
3158
+ normalizeStack(error);
3159
+ normalizeCause(error, recurse);
3160
+ normalizeAggregate(error, recurse);
3161
+ normalizeDescriptors(error);
3162
+ };
3163
+ const normalizeName = (error) => {
3164
+ if (isDefinedString(error.name)) return;
3165
+ const prototypeName = Object.getPrototypeOf(error).name;
3166
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3167
+ };
3168
+ const normalizeMessage = (error) => {
3169
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3170
+ };
3171
+ const normalizeStack = (error) => {
3172
+ if (!isDefinedString(error.stack)) setStack(error);
3173
+ };
3174
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
3175
+ //#endregion
3176
+ //#region ../reactor-browser/dist/index.js
3177
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3178
+ var LZString = (function() {
3179
+ var f = String.fromCharCode;
3180
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3181
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3182
+ var baseReverseDic = {};
3183
+ function getBaseValue(alphabet, character) {
3184
+ if (!baseReverseDic[alphabet]) {
3185
+ baseReverseDic[alphabet] = {};
3186
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3187
+ }
3188
+ return baseReverseDic[alphabet][character];
3189
+ }
3190
+ var LZString = {
3191
+ compressToBase64: function(input) {
3192
+ if (input == null) return "";
3193
+ var res = LZString._compress(input, 6, function(a) {
3194
+ return keyStrBase64.charAt(a);
3195
+ });
3196
+ switch (res.length % 4) {
3197
+ default:
3198
+ case 0: return res;
3199
+ case 1: return res + "===";
3200
+ case 2: return res + "==";
3201
+ case 3: return res + "=";
3202
+ }
3203
+ },
3204
+ decompressFromBase64: function(input) {
3205
+ if (input == null) return "";
3206
+ if (input == "") return null;
3207
+ return LZString._decompress(input.length, 32, function(index) {
3208
+ return getBaseValue(keyStrBase64, input.charAt(index));
3209
+ });
3210
+ },
3211
+ compressToUTF16: function(input) {
3212
+ if (input == null) return "";
3213
+ return LZString._compress(input, 15, function(a) {
3214
+ return f(a + 32);
3215
+ }) + " ";
3216
+ },
3217
+ decompressFromUTF16: function(compressed) {
3218
+ if (compressed == null) return "";
3219
+ if (compressed == "") return null;
3220
+ return LZString._decompress(compressed.length, 16384, function(index) {
3221
+ return compressed.charCodeAt(index) - 32;
3222
+ });
3223
+ },
3224
+ compressToUint8Array: function(uncompressed) {
3225
+ var compressed = LZString.compress(uncompressed);
3226
+ var buf = new Uint8Array(compressed.length * 2);
3227
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3228
+ var current_value = compressed.charCodeAt(i);
3229
+ buf[i * 2] = current_value >>> 8;
3230
+ buf[i * 2 + 1] = current_value % 256;
3231
+ }
3232
+ return buf;
3233
+ },
3234
+ decompressFromUint8Array: function(compressed) {
3235
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3236
+ else {
3237
+ var buf = new Array(compressed.length / 2);
3238
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3239
+ var result = [];
3240
+ buf.forEach(function(c) {
3241
+ result.push(f(c));
3242
+ });
3243
+ return LZString.decompress(result.join(""));
3244
+ }
3245
+ },
3246
+ compressToEncodedURIComponent: function(input) {
3247
+ if (input == null) return "";
3248
+ return LZString._compress(input, 6, function(a) {
3249
+ return keyStrUriSafe.charAt(a);
3250
+ });
3251
+ },
3252
+ decompressFromEncodedURIComponent: function(input) {
3253
+ if (input == null) return "";
3254
+ if (input == "") return null;
3255
+ input = input.replace(/ /g, "+");
3256
+ return LZString._decompress(input.length, 32, function(index) {
3257
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
3258
+ });
3259
+ },
3260
+ compress: function(uncompressed) {
3261
+ return LZString._compress(uncompressed, 16, function(a) {
3262
+ return f(a);
3263
+ });
3264
+ },
3265
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3266
+ if (uncompressed == null) return "";
3267
+ 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;
3268
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
3269
+ context_c = uncompressed.charAt(ii);
3270
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3271
+ context_dictionary[context_c] = context_dictSize++;
3272
+ context_dictionaryToCreate[context_c] = true;
3273
+ }
3274
+ context_wc = context_w + context_c;
3275
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3276
+ else {
3277
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3278
+ if (context_w.charCodeAt(0) < 256) {
3279
+ for (i = 0; i < context_numBits; i++) {
3280
+ context_data_val = context_data_val << 1;
3281
+ if (context_data_position == bitsPerChar - 1) {
3282
+ context_data_position = 0;
3283
+ context_data.push(getCharFromInt(context_data_val));
3284
+ context_data_val = 0;
3285
+ } else context_data_position++;
3286
+ }
3287
+ value = context_w.charCodeAt(0);
3288
+ for (i = 0; i < 8; i++) {
3289
+ context_data_val = context_data_val << 1 | value & 1;
3290
+ if (context_data_position == bitsPerChar - 1) {
3291
+ context_data_position = 0;
3292
+ context_data.push(getCharFromInt(context_data_val));
3293
+ context_data_val = 0;
3294
+ } else context_data_position++;
3295
+ value = value >> 1;
3296
+ }
3297
+ } else {
3298
+ value = 1;
3299
+ for (i = 0; i < context_numBits; i++) {
3300
+ context_data_val = context_data_val << 1 | value;
3301
+ if (context_data_position == bitsPerChar - 1) {
3302
+ context_data_position = 0;
3303
+ context_data.push(getCharFromInt(context_data_val));
3304
+ context_data_val = 0;
3305
+ } else context_data_position++;
3306
+ value = 0;
3307
+ }
3308
+ value = context_w.charCodeAt(0);
3309
+ for (i = 0; i < 16; i++) {
3310
+ context_data_val = context_data_val << 1 | value & 1;
3311
+ if (context_data_position == bitsPerChar - 1) {
3312
+ context_data_position = 0;
3313
+ context_data.push(getCharFromInt(context_data_val));
3314
+ context_data_val = 0;
3315
+ } else context_data_position++;
3316
+ value = value >> 1;
3317
+ }
3318
+ }
3319
+ context_enlargeIn--;
3320
+ if (context_enlargeIn == 0) {
3321
+ context_enlargeIn = Math.pow(2, context_numBits);
3322
+ context_numBits++;
3323
+ }
3324
+ delete context_dictionaryToCreate[context_w];
3325
+ } else {
3326
+ value = context_dictionary[context_w];
3327
+ for (i = 0; i < context_numBits; i++) {
3328
+ context_data_val = context_data_val << 1 | value & 1;
3329
+ if (context_data_position == bitsPerChar - 1) {
3330
+ context_data_position = 0;
3331
+ context_data.push(getCharFromInt(context_data_val));
3332
+ context_data_val = 0;
3333
+ } else context_data_position++;
3334
+ value = value >> 1;
3335
+ }
3336
+ }
3337
+ context_enlargeIn--;
3338
+ if (context_enlargeIn == 0) {
3339
+ context_enlargeIn = Math.pow(2, context_numBits);
3340
+ context_numBits++;
3341
+ }
3342
+ context_dictionary[context_wc] = context_dictSize++;
3343
+ context_w = String(context_c);
3344
+ }
3345
+ }
3346
+ if (context_w !== "") {
3347
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3348
+ if (context_w.charCodeAt(0) < 256) {
3349
+ for (i = 0; i < context_numBits; i++) {
3350
+ context_data_val = context_data_val << 1;
3351
+ if (context_data_position == bitsPerChar - 1) {
3352
+ context_data_position = 0;
3353
+ context_data.push(getCharFromInt(context_data_val));
3354
+ context_data_val = 0;
3355
+ } else context_data_position++;
3356
+ }
3357
+ value = context_w.charCodeAt(0);
3358
+ for (i = 0; i < 8; i++) {
3359
+ context_data_val = context_data_val << 1 | value & 1;
3360
+ if (context_data_position == bitsPerChar - 1) {
3361
+ context_data_position = 0;
3362
+ context_data.push(getCharFromInt(context_data_val));
3363
+ context_data_val = 0;
3364
+ } else context_data_position++;
3365
+ value = value >> 1;
3366
+ }
3367
+ } else {
3368
+ value = 1;
3369
+ for (i = 0; i < context_numBits; i++) {
3370
+ context_data_val = context_data_val << 1 | value;
3371
+ if (context_data_position == bitsPerChar - 1) {
3372
+ context_data_position = 0;
3373
+ context_data.push(getCharFromInt(context_data_val));
3374
+ context_data_val = 0;
3375
+ } else context_data_position++;
3376
+ value = 0;
3377
+ }
3378
+ value = context_w.charCodeAt(0);
3379
+ for (i = 0; i < 16; i++) {
3380
+ context_data_val = context_data_val << 1 | value & 1;
3381
+ if (context_data_position == bitsPerChar - 1) {
3382
+ context_data_position = 0;
3383
+ context_data.push(getCharFromInt(context_data_val));
3384
+ context_data_val = 0;
3385
+ } else context_data_position++;
3386
+ value = value >> 1;
3387
+ }
3388
+ }
3389
+ context_enlargeIn--;
3390
+ if (context_enlargeIn == 0) {
3391
+ context_enlargeIn = Math.pow(2, context_numBits);
3392
+ context_numBits++;
3393
+ }
3394
+ delete context_dictionaryToCreate[context_w];
3395
+ } else {
3396
+ value = context_dictionary[context_w];
3397
+ for (i = 0; i < context_numBits; i++) {
3398
+ context_data_val = context_data_val << 1 | value & 1;
3399
+ if (context_data_position == bitsPerChar - 1) {
3400
+ context_data_position = 0;
3401
+ context_data.push(getCharFromInt(context_data_val));
3402
+ context_data_val = 0;
3403
+ } else context_data_position++;
3404
+ value = value >> 1;
3405
+ }
3406
+ }
3407
+ context_enlargeIn--;
3408
+ if (context_enlargeIn == 0) {
3409
+ context_enlargeIn = Math.pow(2, context_numBits);
3410
+ context_numBits++;
3411
+ }
3412
+ }
3413
+ value = 2;
3414
+ for (i = 0; i < context_numBits; i++) {
3415
+ context_data_val = context_data_val << 1 | value & 1;
3416
+ if (context_data_position == bitsPerChar - 1) {
3417
+ context_data_position = 0;
3418
+ context_data.push(getCharFromInt(context_data_val));
3419
+ context_data_val = 0;
3420
+ } else context_data_position++;
3421
+ value = value >> 1;
3422
+ }
3423
+ while (true) {
3424
+ context_data_val = context_data_val << 1;
3425
+ if (context_data_position == bitsPerChar - 1) {
3426
+ context_data.push(getCharFromInt(context_data_val));
3427
+ break;
3428
+ } else context_data_position++;
3429
+ }
3430
+ return context_data.join("");
3431
+ },
3432
+ decompress: function(compressed) {
3433
+ if (compressed == null) return "";
3434
+ if (compressed == "") return null;
3435
+ return LZString._decompress(compressed.length, 32768, function(index) {
3436
+ return compressed.charCodeAt(index);
3437
+ });
3438
+ },
3439
+ _decompress: function(length, resetValue, getNextValue) {
3440
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3441
+ val: getNextValue(0),
3442
+ position: resetValue,
3443
+ index: 1
3444
+ };
3445
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
3446
+ bits = 0;
3447
+ maxpower = Math.pow(2, 2);
3448
+ power = 1;
3449
+ while (power != maxpower) {
3450
+ resb = data.val & data.position;
3451
+ data.position >>= 1;
3452
+ if (data.position == 0) {
3453
+ data.position = resetValue;
3454
+ data.val = getNextValue(data.index++);
3455
+ }
3456
+ bits |= (resb > 0 ? 1 : 0) * power;
3457
+ power <<= 1;
3458
+ }
3459
+ switch (bits) {
3460
+ case 0:
3461
+ bits = 0;
3462
+ maxpower = Math.pow(2, 8);
3463
+ power = 1;
3464
+ while (power != maxpower) {
3465
+ resb = data.val & data.position;
3466
+ data.position >>= 1;
3467
+ if (data.position == 0) {
3468
+ data.position = resetValue;
3469
+ data.val = getNextValue(data.index++);
3470
+ }
3471
+ bits |= (resb > 0 ? 1 : 0) * power;
3472
+ power <<= 1;
3473
+ }
3474
+ c = f(bits);
3475
+ break;
3476
+ case 1:
3477
+ bits = 0;
3478
+ maxpower = Math.pow(2, 16);
3479
+ power = 1;
3480
+ while (power != maxpower) {
3481
+ resb = data.val & data.position;
3482
+ data.position >>= 1;
3483
+ if (data.position == 0) {
3484
+ data.position = resetValue;
3485
+ data.val = getNextValue(data.index++);
3486
+ }
3487
+ bits |= (resb > 0 ? 1 : 0) * power;
3488
+ power <<= 1;
3489
+ }
3490
+ c = f(bits);
3491
+ break;
3492
+ case 2: return "";
3493
+ }
3494
+ dictionary[3] = c;
3495
+ w = c;
3496
+ result.push(c);
3497
+ while (true) {
3498
+ if (data.index > length) return "";
3499
+ bits = 0;
3500
+ maxpower = Math.pow(2, numBits);
3501
+ power = 1;
3502
+ while (power != maxpower) {
3503
+ resb = data.val & data.position;
3504
+ data.position >>= 1;
3505
+ if (data.position == 0) {
3506
+ data.position = resetValue;
3507
+ data.val = getNextValue(data.index++);
3508
+ }
3509
+ bits |= (resb > 0 ? 1 : 0) * power;
3510
+ power <<= 1;
3511
+ }
3512
+ switch (c = bits) {
3513
+ case 0:
3514
+ bits = 0;
3515
+ maxpower = Math.pow(2, 8);
3516
+ power = 1;
3517
+ while (power != maxpower) {
3518
+ resb = data.val & data.position;
3519
+ data.position >>= 1;
3520
+ if (data.position == 0) {
3521
+ data.position = resetValue;
3522
+ data.val = getNextValue(data.index++);
3523
+ }
3524
+ bits |= (resb > 0 ? 1 : 0) * power;
3525
+ power <<= 1;
3526
+ }
3527
+ dictionary[dictSize++] = f(bits);
3528
+ c = dictSize - 1;
3529
+ enlargeIn--;
3530
+ break;
3531
+ case 1:
3532
+ bits = 0;
3533
+ maxpower = Math.pow(2, 16);
3534
+ power = 1;
3535
+ while (power != maxpower) {
3536
+ resb = data.val & data.position;
3537
+ data.position >>= 1;
3538
+ if (data.position == 0) {
3539
+ data.position = resetValue;
3540
+ data.val = getNextValue(data.index++);
3541
+ }
3542
+ bits |= (resb > 0 ? 1 : 0) * power;
3543
+ power <<= 1;
3544
+ }
3545
+ dictionary[dictSize++] = f(bits);
3546
+ c = dictSize - 1;
3547
+ enlargeIn--;
3548
+ break;
3549
+ case 2: return result.join("");
3550
+ }
3551
+ if (enlargeIn == 0) {
3552
+ enlargeIn = Math.pow(2, numBits);
3553
+ numBits++;
3554
+ }
3555
+ if (dictionary[c]) entry = dictionary[c];
3556
+ else if (c === dictSize) entry = w + w.charAt(0);
3557
+ else return null;
3558
+ result.push(entry);
3559
+ dictionary[dictSize++] = w + entry.charAt(0);
3560
+ enlargeIn--;
3561
+ w = entry;
3562
+ if (enlargeIn == 0) {
3563
+ enlargeIn = Math.pow(2, numBits);
3564
+ numBits++;
3565
+ }
3566
+ }
3567
+ }
3568
+ };
3569
+ return LZString;
3570
+ })();
3571
+ if (typeof define === "function" && define.amd) define(function() {
3572
+ return LZString;
3138
3573
  });
3139
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3140
- triggerAt: "start",
3141
- minQuietPeriodMs: 100
3574
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3575
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3576
+ return LZString;
3142
3577
  });
3143
- function setTarget() {
3144
- if (!isDragAndDropEnabled) return;
3145
- targetUnsetter.cancel();
3146
- targetSetter.call();
3147
- }
3148
- function unsetTarget() {
3149
- if (!isDragAndDropEnabled) return;
3150
- targetSetter.cancel();
3151
- targetUnsetter.call();
3152
- }
3153
- return {
3154
- isDropTarget,
3155
- setTarget,
3156
- unsetTarget
3157
- };
3158
- }
3159
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3160
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3161
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3162
- draggingNodeEventFunctions.addEventHandler;
3163
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3164
- reducer: (_, newNode) => newNode,
3165
- triggerAt: "start",
3166
- minQuietPeriodMs: 100
3167
- });
3168
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3169
- triggerAt: "start",
3170
- minQuietPeriodMs: 100
3171
- });
3172
- function setDragging(node) {
3173
- draggingNodeUnsetter.cancel();
3174
- draggingNodeSetter.call(node);
3175
- }
3176
- function unsetDragging() {
3177
- draggingNodeSetter.cancel();
3178
- draggingNodeUnsetter.call();
3179
- }
3180
- 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));
3181
- function useDragNode(args) {
3182
- const { srcId, parentId } = args;
3183
- const driveId = useSelectedDriveId();
3184
- const draggingNodeId = useDraggingNode()?.srcId;
3185
- const params = {
3186
- driveId,
3187
- srcId,
3188
- parentId
3189
- };
3190
- const draggable = isNodeDrag(params);
3191
- const isDragging = t$4({
3192
- srcId,
3193
- draggingNodeId
3194
- }, [
3195
- () => draggable,
3196
- ({ srcId }) => e$2(srcId),
3197
- ({ draggingNodeId }) => e$2(draggingNodeId),
3198
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3199
- ]);
3200
- const onDragStart = () => {
3201
- if (!draggable) return;
3202
- setDragging(params);
3203
- };
3204
- const onDragEnd = () => {
3205
- if (!draggable) return;
3206
- unsetDragging();
3207
- };
3208
- return {
3209
- isDragging,
3210
- draggable,
3211
- onDragStart,
3212
- onDragEnd
3213
- };
3214
- }
3215
- 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));
3216
- function useDropNode(targetId) {
3217
- const driveId = useSelectedDriveId();
3218
- const { srcId, parentId } = useDraggingNode() ?? {};
3219
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3220
- const params = {
3221
- driveId,
3222
- parentId,
3223
- targetId,
3224
- srcId
3225
- };
3226
- function handleNodeDrop(event, cb) {
3227
- if (!isNodeDrop(params)) return;
3228
- event.preventDefault();
3229
- event.stopPropagation();
3230
- cb?.();
3231
- }
3232
- const onDragEnter = (event) => handleNodeDrop(event);
3233
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3234
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3235
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3236
- unsetDragging();
3237
- unsetTarget();
3238
- moveNodeById(params).catch(console.error);
3239
- }));
3240
- return {
3241
- isDropTarget,
3242
- onDragEnter,
3243
- onDragOver,
3244
- onDragLeave,
3245
- onDrop
3246
- };
3247
- }
3248
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3249
- graphQLReactorClientEventFunctions.useValue;
3250
- graphQLReactorClientEventFunctions.setValue;
3251
- graphQLReactorClientEventFunctions.addEventHandler;
3252
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3253
- packageDiscoveryFunctions.useValue;
3254
- packageDiscoveryFunctions.setValue;
3255
- packageDiscoveryFunctions.addEventHandler;
3256
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3257
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3258
- /** Returns the reactor client module (in-process or worker-backed) */
3259
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3260
- reactorClientModuleEventFunctions.setValue;
3261
- reactorClientModuleEventFunctions.addEventHandler;
3262
- reactorClientEventFunctions.useValue;
3263
- reactorClientEventFunctions.setValue;
3264
- reactorClientEventFunctions.addEventHandler;
3265
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3266
- const useSyncList = () => {
3267
- return useSync()?.list() ?? [];
3268
- };
3269
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3270
- revisionHistoryEventFunctions.useValue;
3271
- /** Sets revision history visibility */
3272
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3273
- revisionHistoryEventFunctions.addEventHandler;
3274
- /** Shows the revision history */
3275
- function showRevisionHistory() {
3276
- setRevisionHistoryVisible(true);
3277
- }
3278
- /** Sorts nodes by name. */
3279
- function sortNodesByName(nodes) {
3280
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3281
- }
3282
- /** Returns whether a node is a file. */
3283
- function isFileNodeKind(node) {
3284
- if (!node) return false;
3285
- return node.kind.toUpperCase() === "FILE";
3286
- }
3287
- /** Returns whether a node is a folder. */
3288
- function isFolderNodeKind(node) {
3289
- if (!node) return false;
3290
- return node.kind.toUpperCase() === "FOLDER";
3291
- }
3292
- /** Returns the nodes in the selected drive. */
3293
- function useNodesInSelectedDrive() {
3294
- const [selectedDrive] = useSelectedDriveSafe();
3295
- return selectedDrive?.state.global.nodes;
3296
- }
3297
- /** Returns the folder nodes in the selected drive. */
3298
- function useFolderNodesInSelectedDrive() {
3299
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3300
- }
3301
- /** Returns the selected node. */
3302
- function useSelectedNode() {
3303
- const selectedNodeId = useSelectedNodeId();
3304
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3305
- }
3306
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3307
- selectedTimelineItemEventFunctions.useValue;
3308
- selectedTimelineItemEventFunctions.setValue;
3309
- selectedTimelineItemEventFunctions.addEventHandler;
3310
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3311
- selectedTimelineRevisionEventFunctions.useValue;
3312
- selectedTimelineRevisionEventFunctions.setValue;
3313
- selectedTimelineRevisionEventFunctions.addEventHandler;
3314
- const toastEventFunctions = makePHEventFunctions("toast");
3315
- /** Returns the toast function */
3316
- const usePHToast = toastEventFunctions.useValue;
3317
- toastEventFunctions.setValue;
3318
- toastEventFunctions.addEventHandler;
3319
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3320
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3321
- /** Returns all of the Vetra packages loaded by the Connect instance */
3322
- const useVetraPackages = () => {
3323
- const packageManager = useVetraPackageManager();
3324
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3325
- };
3326
- vetraPackageManagerFunctions.addEventHandler;
3327
- function useDocumentModelModules() {
3328
- 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);
3329
- }
3330
- function useDocumentModelModuleById(id) {
3331
- return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3332
- }
3578
+ })))(), 1);
3579
+ /** Document types that represent a "drive": a container of nodes. */
3580
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
3333
3581
  function useAllowedDocumentModelModules() {
3334
3582
  const documentModelModules = useDocumentModelModules();
3335
3583
  const allowedDocumentTypes = useAllowedDocumentTypes();
@@ -3405,6 +3653,50 @@ function useDocumentOfType(documentId, documentType) {
3405
3653
  if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3406
3654
  return [document, dispatch];
3407
3655
  }
3656
+ /**
3657
+ * Classifies a document's model version against the installed module
3658
+ * versions. Pure logic, extracted for testing.
3659
+ */
3660
+ function getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {
3661
+ if (availableVersions.length === 0) return;
3662
+ const sorted = [...availableVersions].sort((a, b) => a - b);
3663
+ const latestVersion = sorted[sorted.length - 1];
3664
+ if (documentVersion > latestVersion) return {
3665
+ kind: "unsupported",
3666
+ documentVersion,
3667
+ availableVersions: sorted
3668
+ };
3669
+ if (documentVersion === latestVersion) return {
3670
+ kind: "current",
3671
+ documentVersion
3672
+ };
3673
+ return {
3674
+ kind: "upgrade-available",
3675
+ documentVersion,
3676
+ latestVersion,
3677
+ canUpgrade: hasUpgradePath(documentVersion, latestVersion)
3678
+ };
3679
+ }
3680
+ /**
3681
+ * Compares the given document's model version against the versions available
3682
+ * from installed Vetra packages. Returns undefined while packages load or
3683
+ * when the document type has no installed modules.
3684
+ */
3685
+ function useDocumentVersionStatus(document) {
3686
+ const modules = useDocumentModelModules();
3687
+ const registry = useModelRegistry();
3688
+ if (!document || !modules) return;
3689
+ const documentType = document.header.documentType;
3690
+ return getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {
3691
+ if (!registry) return false;
3692
+ try {
3693
+ registry.computeUpgradePath(documentType, fromVersion, toVersion);
3694
+ return true;
3695
+ } catch {
3696
+ return false;
3697
+ }
3698
+ });
3699
+ }
3408
3700
  const validateDocument = (document) => {
3409
3701
  const errors = [];
3410
3702
  if (document.header.documentType !== "powerhouse/document-model") return errors;
@@ -3514,7 +3806,7 @@ function useNodeActions() {
3514
3806
  }
3515
3807
  async function onAddFolder(name, parent) {
3516
3808
  if (!selectedDriveId) return;
3517
- return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3809
+ return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3518
3810
  }
3519
3811
  async function onRenameNode(newName, node) {
3520
3812
  if (!selectedDriveId) return;
@@ -3601,6 +3893,9 @@ function useSelectedNodePath() {
3601
3893
  function useNodeParentFolderById(id) {
3602
3894
  return useFolderById(useNodeById(id)?.parentFolder);
3603
3895
  }
3896
+ function useParentFolderForSelectedNode() {
3897
+ return useNodeParentFolderById(useSelectedNode()?.id);
3898
+ }
3604
3899
  /** Returns the selected document id */
3605
3900
  function useSelectedDocumentId() {
3606
3901
  const selectedNode = useSelectedNode();
@@ -3829,6 +4124,6 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
3829
4124
  createDebouncedRefreshReactorData();
3830
4125
  createDebouncedRefreshReactorDataClient();
3831
4126
  //#endregion
3832
- 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 };
4127
+ export { showRevisionHistory as A, t$2 as B, addFolder$1 as C, setSelectedNode as D, setSelectedDrive as E, useSelectedDriveId as F, useDocumentById as H, useSelectedDriveSafe as I, useStudioMode as L, useDragNode as M, useDropNode as N, showDeleteNodeModal as O, usePHToast as P, e$1 as R, addDocument as S, isFolderNodeKind as T, t$5 as V, useSelectedNodePath as _, useDownloadDocument as a, useTheme as b, useGetSwitchboardLink as c, useNodeParentFolderById as d, useNodesInSelectedDriveOrFolder as f, useSelectedFolder as g, useSelectedDocumentSafe as h, useDocumentVersionStatus as i, useDisabledEditors as j, showPHModal as k, useNodeActions as l, useSelectedDocumentOfType as m, preloadEditorModule as n, useEditorModules as o, useParentFolderForSelectedNode as p, useAllowedDocumentModelModules as r, useEditorModulesForDocumentType as s, getSyncStatusSync as t, useNodeById as u, useSetPHAppConfig as v, isFileNodeKind as w, useUserPermissions as x, useSetPHDocumentEditorConfig as y, e$4 as z };
3833
4128
 
3834
- //# sourceMappingURL=dist-D5ra2aRj.js.map
4129
+ //# sourceMappingURL=dist-dmLcxsWV.js.map