@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.26 → 6.2.2-dev.28

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 (81) hide show
  1. package/dist/browser/assets/{entry-Bi_sLHEE.js → entry-Dk9VPWLt.js} +2 -2
  2. package/dist/browser/assets/{projection-entry-CIeJkB70.js → projection-entry-MT1aNJTP.js} +2 -2
  3. package/dist/browser/{connect-MUhMejvS.js → connect-BOSfrted.js} +6 -6
  4. package/dist/browser/{connect-MUhMejvS.js.map → connect-BOSfrted.js.map} +1 -1
  5. package/dist/browser/{dist-UIW3bhlu.js → dist-CetbB2Ax.js} +1562 -1449
  6. package/dist/browser/dist-CetbB2Ax.js.map +1 -0
  7. package/dist/browser/{dist-D8H48e8N.js → dist-D0oeNPlN.js} +1 -1
  8. package/dist/browser/{dist-D8H48e8N.js.map → dist-D0oeNPlN.js.map} +1 -1
  9. package/dist/browser/{document-drive-UzuiuvrS.js → document-drive-QCAIGn3V.js} +16 -3
  10. package/dist/browser/{document-drive-UzuiuvrS.js.map → document-drive-QCAIGn3V.js.map} +1 -1
  11. package/dist/browser/document-models/index.js +1 -1
  12. package/dist/browser/{documents-tEyvFm5w.js → documents-j_qy61X1.js} +22 -621
  13. package/dist/browser/documents-j_qy61X1.js.map +1 -0
  14. package/dist/browser/{editor-Bo7N28yK.js → editor-D6FPj2FU.js} +5 -5
  15. package/dist/browser/{editor-Bo7N28yK.js.map → editor-D6FPj2FU.js.map} +1 -1
  16. package/dist/browser/{editor-CBsDDo5E.js → editor-Dsx6DjlJ.js} +9 -9
  17. package/dist/browser/{editor-CBsDDo5E.js.map → editor-Dsx6DjlJ.js.map} +1 -1
  18. package/dist/browser/editors/document-model-editor/module.js +1 -1
  19. package/dist/browser/editors/generic-drive-explorer/index.js +10 -10
  20. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  21. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  22. package/dist/browser/{folder-view-CqTIG-gR.js → folder-view-C91sPkD7.js} +4 -4
  23. package/dist/browser/{folder-view-CqTIG-gR.js.map → folder-view-C91sPkD7.js.map} +1 -1
  24. package/dist/browser/{graphql-editor-C3Bo3g1y.js → graphql-editor-CdHcSp6b.js} +7 -6
  25. package/dist/browser/{graphql-editor-C3Bo3g1y.js.map → graphql-editor-CdHcSp6b.js.map} +1 -1
  26. package/dist/browser/{hooks-BWFXCdBN.js → hooks-BgIeO-WG.js} +2 -2
  27. package/dist/browser/{hooks-BWFXCdBN.js.map → hooks-BgIeO-WG.js.map} +1 -1
  28. package/dist/browser/index.js +2 -2
  29. package/dist/browser/{json-editor-mGzyqHBe.js → json-editor-DjoNgrAU.js} +4 -4
  30. package/dist/browser/{json-editor-mGzyqHBe.js.map → json-editor-DjoNgrAU.js.map} +1 -1
  31. package/dist/browser/{lib-B5wuTyK2.js → lib-Dx4DRbGl.js} +2 -2
  32. package/dist/browser/lib-Dx4DRbGl.js.map +1 -0
  33. package/dist/browser/{linting-DCToEa_x.js → linting-nOwKxGXw.js} +5 -4
  34. package/dist/browser/{linting-DCToEa_x.js.map → linting-nOwKxGXw.js.map} +1 -1
  35. package/dist/browser/printer-CEYr4JOg.js +604 -0
  36. package/dist/browser/printer-CEYr4JOg.js.map +1 -0
  37. package/dist/browser/{schema-context-CM52_Uom.js → schema-context-ClCYFYSx.js} +2 -2
  38. package/dist/browser/{schema-context-CM52_Uom.js.map → schema-context-ClCYFYSx.js.map} +1 -1
  39. package/dist/browser/{state-schemas-DXvb34Vy.js → state-schemas-CnCO6lVC.js} +7 -7
  40. package/dist/browser/{state-schemas-DXvb34Vy.js.map → state-schemas-CnCO6lVC.js.map} +1 -1
  41. package/dist/node/{connect-Dtv8QYvd.mjs → connect-D143FXSc.mjs} +5 -5
  42. package/dist/node/{connect-Dtv8QYvd.mjs.map → connect-D143FXSc.mjs.map} +1 -1
  43. package/dist/node/{dist-B9dsmZOQ.mjs → dist-Ch3Oiwow.mjs} +1567 -1449
  44. package/dist/node/dist-Ch3Oiwow.mjs.map +1 -0
  45. package/dist/node/{document-drive-DwU-AM0j.mjs → document-drive-DIiMiIkb.mjs} +16 -3
  46. package/dist/node/document-drive-DIiMiIkb.mjs.map +1 -0
  47. package/dist/node/document-models/index.mjs +1 -1
  48. package/dist/node/{documents-DCf53bzO.mjs → documents-Bh_lxLTV.mjs} +19 -19
  49. package/dist/node/{documents-DCf53bzO.mjs.map → documents-Bh_lxLTV.mjs.map} +1 -1
  50. package/dist/node/{editor-CqiZG2jA.mjs → editor-CSaAlHLA.mjs} +5 -5
  51. package/dist/node/{editor-CqiZG2jA.mjs.map → editor-CSaAlHLA.mjs.map} +1 -1
  52. package/dist/node/{editor-BHPkhGRc.mjs → editor-vRgf2dWH.mjs} +8 -8
  53. package/dist/node/{editor-BHPkhGRc.mjs.map → editor-vRgf2dWH.mjs.map} +1 -1
  54. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  55. package/dist/node/editors/generic-drive-explorer/index.mjs +10 -10
  56. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  57. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  58. package/dist/node/{folder-view-C5Gyifq_.mjs → folder-view-DQzUtql7.mjs} +3 -3
  59. package/dist/node/{folder-view-C5Gyifq_.mjs.map → folder-view-DQzUtql7.mjs.map} +1 -1
  60. package/dist/node/{graphql-editor-Cn9kF4fN.mjs → graphql-editor-U_ps05vi.mjs} +5 -5
  61. package/dist/node/{graphql-editor-Cn9kF4fN.mjs.map → graphql-editor-U_ps05vi.mjs.map} +1 -1
  62. package/dist/node/{hooks-D0DcS3MV.mjs → hooks-B7KF2A2g.mjs} +2 -2
  63. package/dist/node/{hooks-D0DcS3MV.mjs.map → hooks-B7KF2A2g.mjs.map} +1 -1
  64. package/dist/node/index.mjs +2 -2
  65. package/dist/node/{json-editor-D5HFrby8.mjs → json-editor-DJ9KSSQo.mjs} +4 -4
  66. package/dist/node/{json-editor-D5HFrby8.mjs.map → json-editor-DJ9KSSQo.mjs.map} +1 -1
  67. package/dist/node/{linting-BjvRPjCY.mjs → linting-D6drcQHM.mjs} +4 -4
  68. package/dist/node/{linting-BjvRPjCY.mjs.map → linting-D6drcQHM.mjs.map} +1 -1
  69. package/dist/node/{main-_cmzLLxO.mjs → main-CfVS_PlH.mjs} +2 -2
  70. package/dist/node/main-CfVS_PlH.mjs.map +1 -0
  71. package/dist/node/{schema-context-DL8jhi_d.mjs → schema-context-pefmG2VW.mjs} +2 -2
  72. package/dist/node/{schema-context-DL8jhi_d.mjs.map → schema-context-pefmG2VW.mjs.map} +1 -1
  73. package/dist/node/{state-schemas-CS_nVqVI.mjs → state-schemas-BVvdNjMt.mjs} +6 -6
  74. package/dist/node/{state-schemas-CS_nVqVI.mjs.map → state-schemas-BVvdNjMt.mjs.map} +1 -1
  75. package/package.json +6 -6
  76. package/dist/browser/dist-UIW3bhlu.js.map +0 -1
  77. package/dist/browser/documents-tEyvFm5w.js.map +0 -1
  78. package/dist/browser/lib-B5wuTyK2.js.map +0 -1
  79. package/dist/node/dist-B9dsmZOQ.mjs.map +0 -1
  80. package/dist/node/document-drive-DwU-AM0j.mjs.map +0 -1
  81. package/dist/node/main-_cmzLLxO.mjs.map +0 -1
@@ -1,9 +1,10 @@
1
1
  import { D as __commonJSMin, M as __toESM, t as capitalCase } from "./dist-DT7jI9ol.mjs";
2
- import { J as validateInitialState, M as replayDocumentVersioned, V as setName, X as validateStateSchemaName, Y as validateModules, Z as generateId, _ as baseLoadFromInput, a as handleTargetNameCollisions, b as buildSignedAction, c as moveNode, d as logger, h as assertAuthPreservedOnDuplicate, i as generateNodesCopy, l as updateNode, n as copyNode, o as isFileNode, s as isFolderNode, t as addFolder$1, v as baseLoadFromInputVersioned, w as createZip, x as createPresignedHeader, y as baseSaveToFileHandle } from "./document-drive-DwU-AM0j.mjs";
3
- import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-_cmzLLxO.mjs";
4
- import { Children, cloneElement, createContext, forwardRef, isValidElement, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
2
+ import { H as setName, N as replayDocumentVersioned, Q as generateId, X as validateModules, Y as validateInitialState, Z as validateStateSchemaName, _ as baseLoadFromInput, a as handleTargetNameCollisions, b as buildSignedAction, c as moveNode, d as logger, h as assertAuthPreservedOnDuplicate, i as generateNodesCopy, l as updateNode, n as copyNode, o as isFileNode, s as isFolderNode, t as addFolder, v as baseLoadFromInputVersioned, w as createZip, x as createPresignedHeader, y as baseSaveToFileHandle } from "./document-drive-DIiMiIkb.mjs";
3
+ import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-CfVS_PlH.mjs";
4
+ import { t as require_graphql } from "./graphql-BfAoPeWM.mjs";
5
+ import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
6
  import "react/jsx-runtime";
6
- //#region ../reactor-browser/dist/make-ph-event-functions-BHoLPif5.js
7
+ //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
7
8
  const isServer$1 = typeof window === "undefined";
8
9
  function makePHEventFunctions(key) {
9
10
  const setEventName = `ph:set${capitalCase(key)}`;
@@ -51,7 +52,7 @@ function makePHEventFunctions(key) {
51
52
  };
52
53
  }
53
54
  //#endregion
54
- //#region ../reactor-browser/dist/document-by-id-dLYFX-xz.js
55
+ //#region ../reactor-browser/dist/document-by-id-RNQCGkYh.js
55
56
  async function queueActions(document, actionOrActions) {
56
57
  if (!document) throw new Error("No document provided");
57
58
  if (!actionOrActions) throw new Error("No actions provided");
@@ -97,12 +98,12 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
97
98
  logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
99
  }
99
100
  async function signAction(action, document) {
100
- const reactor = window.ph?.reactorClient;
101
- if (!reactor) return action;
102
- const reducer = (await reactor.getDocumentModelModule(document.header.documentType)).reducer;
103
101
  const renown = window.ph?.renown;
104
102
  if (!renown?.user) return action;
105
103
  if (!action.context?.signer) return action;
104
+ const reactorClient = window.ph?.reactorClientModule?.client;
105
+ if (!reactorClient) return action;
106
+ const reducer = (await reactorClient.getDocumentModelModule(document.header.documentType)).reducer;
106
107
  const actionSigner = action.context.signer;
107
108
  return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
109
  }
@@ -180,6 +181,21 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
180
181
  if (onSuccess && result) onSuccess(result);
181
182
  return result;
182
183
  }
184
+ /**
185
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
186
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
187
+ * TypeScript string enum is nominal, so no string literal is assignable to it
188
+ * without one - and the two checks above are what make it safe.
189
+ */
190
+ const DOCUMENT_CHANGE_TYPE = {
191
+ Created: "created",
192
+ Deleted: "deleted",
193
+ Updated: "updated",
194
+ ParentAdded: "parent_added",
195
+ ParentRemoved: "parent_removed",
196
+ ChildAdded: "child_added",
197
+ ChildRemoved: "child_removed"
198
+ };
183
199
  const documentEventFunctions = makePHEventFunctions("documentCache");
184
200
  /** Returns all documents in the reactor. */
185
201
  const useDocumentCache = documentEventFunctions.useValue;
@@ -225,9 +241,27 @@ function useDocumentById(id) {
225
241
  const [, dispatch] = useDispatch(document);
226
242
  return [document, dispatch];
227
243
  }
244
+ Error;
245
+ require_graphql();
246
+ JSON;
228
247
  //#endregion
229
- //#region ../reactor-browser/dist/client-_Gh2Uf0E.js
248
+ //#region ../reactor-browser/dist/client-B1Af81HB.js
230
249
  var import_main = require_main();
250
+ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
251
+ DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
252
+ DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
253
+ DocumentChangeType["Created"] = "CREATED";
254
+ DocumentChangeType["Deleted"] = "DELETED";
255
+ DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
256
+ DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
257
+ DocumentChangeType["Updated"] = "UPDATED";
258
+ return DocumentChangeType;
259
+ }({});
260
+ let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
261
+ PropagationMode["Cascade"] = "CASCADE";
262
+ PropagationMode["Orphan"] = "ORPHAN";
263
+ return PropagationMode;
264
+ }({});
231
265
  const PhDocumentFieldsFragmentDoc = import_main.gql`
232
266
  fragment PHDocumentFields on PHDocument {
233
267
  id
@@ -738,13 +772,8 @@ function extractQueryParts(doc, fallbackBody) {
738
772
  extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
739
773
  extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
740
774
  //#endregion
741
- //#region ../renown/dist/types-C_qc_62W.js
742
- const LoginMethod = {
743
- WALLET: "wallet",
744
- GOOGLE: "google",
745
- EMAIL: "email",
746
- APPLE: "apple"
747
- };
775
+ //#region ../reactor-browser/dist/renown-BZabzj4l.js
776
+ const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
748
777
  const RenownInitialUserContext = createContext({ state: "unknown" });
749
778
  /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
750
779
  function useRenownInitialAuth() {
@@ -754,7 +783,6 @@ function useRenownInitialUser() {
754
783
  const initial = useRenownInitialAuth();
755
784
  return initial.state === "authenticated" ? initial.user : void 0;
756
785
  }
757
- const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
758
786
  const renownEventFunctions = makePHEventFunctions("renown");
759
787
  renownEventFunctions.addEventHandler;
760
788
  /** Returns the renown instance */
@@ -774,36 +802,6 @@ function useUser() {
774
802
  }, [instance]);
775
803
  return instance ? user : initialUser ?? user;
776
804
  }
777
- Object.freeze([]);
778
- function mergeProps(parentProps, childProps) {
779
- const merged = { ...parentProps };
780
- for (const key of Object.keys(childProps)) {
781
- const parentValue = parentProps[key];
782
- const childValue = childProps[key];
783
- if (key === "style") merged[key] = {
784
- ...parentValue,
785
- ...childValue
786
- };
787
- else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
788
- else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
789
- childValue(...args);
790
- parentValue(...args);
791
- };
792
- else if (childValue !== void 0) merged[key] = childValue;
793
- }
794
- return merged;
795
- }
796
- const Slot = forwardRef(({ children, ...props }, ref) => {
797
- const child = Children.only(children);
798
- if (!isValidElement(child)) return null;
799
- const childElement = child;
800
- const mergedProps = mergeProps(props, childElement.props);
801
- if (ref) mergedProps.ref = ref;
802
- return cloneElement(childElement, mergedProps);
803
- });
804
- Slot.displayName = "Slot";
805
- createContext(false);
806
- LoginMethod.WALLET, LoginMethod.GOOGLE, LoginMethod.EMAIL, LoginMethod.APPLE;
807
805
  //#endregion
808
806
  //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
809
807
  function e$8(e, t, n) {
@@ -928,6 +926,32 @@ function e(e) {
928
926
  let t = !1, n;
929
927
  return () => (t ||= (n = e(), !0), n);
930
928
  }
929
+ var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
930
+ CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
931
+ CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
932
+ CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
933
+ CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
934
+ CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
935
+ CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
936
+ CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
937
+ CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
938
+ CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
939
+ CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
940
+ CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
941
+ return CloseCode2;
942
+ })(CloseCode || {});
943
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
944
+ MessageType2["ConnectionInit"] = "connection_init";
945
+ MessageType2["ConnectionAck"] = "connection_ack";
946
+ MessageType2["Ping"] = "ping";
947
+ MessageType2["Pong"] = "pong";
948
+ MessageType2["Subscribe"] = "subscribe";
949
+ MessageType2["Next"] = "next";
950
+ MessageType2["Error"] = "error";
951
+ MessageType2["Complete"] = "complete";
952
+ return MessageType2;
953
+ })(MessageType || {});
954
+ Error;
931
955
  //#endregion
932
956
  //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
933
957
  let base64;
@@ -1715,1076 +1739,455 @@ slug.setLocale = function(locale) {
1715
1739
  defaultLocale = locales[locale] || {};
1716
1740
  };
1717
1741
  //#endregion
1718
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1719
- const normalizeDescriptors = (error) => {
1720
- CORE_ERROR_PROPS.forEach((propName) => {
1721
- normalizeDescriptor(error, propName);
1722
- });
1723
- };
1724
- const CORE_ERROR_PROPS = [
1725
- "name",
1726
- "message",
1727
- "stack",
1728
- "cause",
1729
- "errors"
1730
- ];
1731
- const normalizeDescriptor = (error, propName) => {
1732
- const descriptor = getDescriptor(error, propName);
1733
- if (descriptor === void 0) return;
1734
- if (isReadonlyGetter(descriptor)) {
1735
- setErrorProperty(error, propName, error[propName]);
1736
- return;
1742
+ //#region ../reactor-browser/dist/document-model-modules-B2_aAWc7.js
1743
+ var DocumentModelNotFoundError = class extends Error {
1744
+ documentType;
1745
+ name = "DocumentModelNotFoundError";
1746
+ constructor(documentType) {
1747
+ super(`Document model module for type ${documentType} not found`);
1748
+ this.documentType = documentType;
1749
+ }
1750
+ static isError(error) {
1751
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1737
1752
  }
1738
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1739
- };
1740
- const getDescriptor = (value, propName) => {
1741
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1742
- if (descriptor !== void 0) return descriptor;
1743
- const prototype = Object.getPrototypeOf(value);
1744
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
1745
- };
1746
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1747
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1748
- const setErrorProperty = (error, propName, value) => {
1749
- setErrorDescriptor(error, propName, { value });
1750
- };
1751
- const setErrorDescriptor = (error, propName, descriptor) => {
1752
- Object.defineProperty(error, propName, {
1753
- ...descriptor,
1754
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1755
- enumerable: false,
1756
- configurable: true
1757
- });
1758
- };
1759
- //#endregion
1760
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1761
- const normalizeAggregate = (error, recurse) => {
1762
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1763
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1764
- else if (error.errors !== void 0) deleteAggregateErrors(error);
1765
- };
1766
- const isDefined = (error) => error !== void 0;
1767
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1768
- const deleteAggregateErrors = (error) => {
1769
- delete error.errors;
1770
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1771
- };
1772
- //#endregion
1773
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1774
- const normalizeCause = (error, recurse) => {
1775
- if (!("cause" in error)) return;
1776
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1777
- if (cause === void 0) delete error.cause;
1778
- else setErrorProperty(error, "cause", cause);
1779
1753
  };
1780
- //#endregion
1781
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1782
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1783
- const isInstanceOfError = (value) => {
1784
- try {
1785
- return value instanceof Error;
1786
- } catch {
1787
- return false;
1754
+ var DocumentTypeMismatchError = class extends Error {
1755
+ constructor(documentId, expectedType, actualType) {
1756
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1788
1757
  }
1789
1758
  };
1790
- const hasErrorTag = (value) => {
1791
- try {
1792
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
1793
- } catch {
1794
- return false;
1759
+ var NoSelectedDocumentError = class extends Error {
1760
+ constructor() {
1761
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1795
1762
  }
1796
1763
  };
1797
- const ERROR_TAGS = new Set([
1798
- "[object Error]",
1799
- "[object DOMException]",
1800
- "[object DOMError]",
1801
- "[object Exception]"
1802
- ]);
1803
- //#endregion
1804
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1805
- function isPlainObject(value) {
1806
- if (typeof value !== "object" || value === null) return false;
1807
- const prototype = Object.getPrototypeOf(value);
1808
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1764
+ function getUserPermissions() {
1765
+ const user = window.ph?.renown?.user;
1766
+ const allowList = window.ph?.allowList;
1767
+ if (!allowList) return {
1768
+ isAllowedToCreateDocuments: true,
1769
+ isAllowedToEditDocuments: true
1770
+ };
1771
+ return {
1772
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
1773
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
1774
+ };
1809
1775
  }
1810
- //#endregion
1811
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1812
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1813
- const isNonConfigurableProp = (error, propName) => {
1814
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1815
- return descriptor !== void 0 && !descriptor.configurable;
1816
- };
1817
- const isThrowingProp = (error, propName) => {
1776
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
1777
+ async function downloadFile(document, fileName) {
1818
1778
  try {
1819
- error[propName];
1820
- return false;
1821
- } catch {
1822
- return true;
1779
+ const data = await createZip(document);
1780
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
1781
+ const link = window.document.createElement("a");
1782
+ link.style.display = "none";
1783
+ link.href = URL.createObjectURL(blob);
1784
+ link.download = fileName;
1785
+ window.document.body.appendChild(link);
1786
+ link.click();
1787
+ window.document.body.removeChild(link);
1788
+ } catch (e) {
1789
+ logger.error(e instanceof Error ? e.message : String(e));
1823
1790
  }
1824
- };
1825
- //#endregion
1826
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1827
- const setStack = (error) => {
1828
- setErrorProperty(error, "stack", getStack(error.message, error.name));
1829
- };
1830
- const getStack = (message = "", name = "Error") => {
1831
- const { stack } = new (getErrorClass(name))(message);
1832
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1833
- };
1834
- const getErrorClass = (name) => {
1835
- const descriptor = {
1836
- value: name,
1837
- enumerable: false,
1838
- writable: true,
1839
- configurable: true
1840
- };
1841
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1842
- Object.defineProperty(StackError.prototype, "name", descriptor);
1843
- return StackError;
1844
- };
1845
- //#endregion
1846
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1847
- const copyObject = (object) => {
1848
- const objectCopy = {};
1849
- for (const propName of getPropsToCopy(object)) try {
1850
- const value = object[propName];
1851
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1852
- Object.defineProperty(objectCopy, propName, {
1853
- value,
1854
- enumerable,
1855
- configurable,
1856
- writable
1791
+ }
1792
+ async function getDocumentExtension(document) {
1793
+ const documentType = document.header.documentType;
1794
+ let rawExtension;
1795
+ if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
1796
+ else {
1797
+ const reactorClient = window.ph?.reactorClientModule?.client;
1798
+ if (reactorClient) {
1799
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1800
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
1801
+ }
1802
+ }
1803
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
1804
+ }
1805
+ /**
1806
+ * Fetches all operations for a document using cursor-based pagination.
1807
+ * The reactor client handles multi-scope cursors transparently via
1808
+ * composite cursors, so all scopes are fetched in a single paginated stream.
1809
+ */
1810
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
1811
+ const scopes = Object.keys(document.state);
1812
+ const operations = {};
1813
+ for (const scope of scopes) operations[scope] = [];
1814
+ let cursor = "";
1815
+ do {
1816
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
1817
+ cursor,
1818
+ limit: pageSize
1857
1819
  });
1858
- } catch {}
1859
- return objectCopy;
1860
- };
1861
- const getPropsToCopy = (object) => {
1862
- const propNames = getOwnKeys(object);
1863
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1864
- return propNames;
1865
- };
1866
- const getOwnKeys = (object) => {
1820
+ for (const op of page.results) {
1821
+ const scope = op.action.scope ?? "global";
1822
+ if (operations[scope]) operations[scope].push(op);
1823
+ }
1824
+ cursor = page.nextCursor ?? "";
1825
+ } while (cursor);
1826
+ return operations;
1827
+ }
1828
+ function extractInitialState(documentScopeOps) {
1829
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
1830
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
1831
+ const input = upgradeOp.action.input;
1832
+ const initialState = input.initialState ?? input.state;
1833
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
1834
+ return initialState;
1835
+ }
1836
+ function filterDomainOperations(operations) {
1837
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
1838
+ }
1839
+ async function exportFile(document, suggestedName) {
1840
+ const reactorClient = window.ph?.reactorClient;
1841
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1842
+ const operations = await fetchDocumentOperations(reactorClient, document);
1843
+ const initialState = extractInitialState(operations["document"] ?? []);
1844
+ const documentWithOps = {
1845
+ ...document,
1846
+ operations,
1847
+ initialState
1848
+ };
1849
+ const extension = await getDocumentExtension(documentWithOps);
1850
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
1851
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
1852
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
1867
1853
  try {
1868
- return Reflect.ownKeys(object);
1869
- } catch {
1870
- return [];
1854
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
1855
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
1856
+ return fileHandle;
1857
+ } catch (e) {
1858
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
1871
1859
  }
1872
- };
1873
- const isInheritedProp = (object, propName) => {
1874
- try {
1875
- return propName in object && !Object.hasOwn(object, propName);
1876
- } catch {
1877
- return false;
1878
- }
1879
- };
1880
- //#endregion
1881
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1882
- const objectifyError = (object) => {
1883
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1884
- const messageA = getMessage(message, objectA);
1885
- const error = newError(name, messageA);
1886
- if (message === messageA) assignObjectProps(error, objectA);
1887
- Object.entries({
1888
- name,
1889
- stack,
1890
- cause,
1891
- errors
1892
- }).forEach(([propName, propValue]) => {
1893
- setNewErrorProperty(error, propName, propValue);
1860
+ }
1861
+ /**
1862
+ * Loads a document file and replays it with version-aware reducers from the registry.
1863
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
1864
+ * the document type.
1865
+ */
1866
+ async function loadFile(path) {
1867
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
1868
+ const reactorClient = window.ph?.reactorClientModule?.client;
1869
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1870
+ const documentType = baseDocument.header.documentType;
1871
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1872
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
1873
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
1874
+ const reducers = {};
1875
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
1876
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
1877
+ let upgradeManifest;
1878
+ if (registry) try {
1879
+ upgradeManifest = registry.getUpgradeManifest(documentType);
1880
+ } catch {}
1881
+ return baseLoadFromInputVersioned(path, {
1882
+ reducers,
1883
+ upgradeManifest
1894
1884
  });
1895
- if (stack === void 0) setStack(error);
1896
- return error;
1897
- };
1898
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1899
- const safeJsonStringify = (object) => {
1900
- try {
1901
- return JSON.stringify(object);
1902
- } catch {
1903
- return safeStringify(object);
1904
- }
1905
- };
1906
- const safeStringify = (object) => {
1885
+ }
1886
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
1887
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1888
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
1889
+ const reactorClient = window.ph?.reactorClientModule?.client;
1890
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1891
+ const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
1892
+ const newDocument = document ?? documentModelModule.utils.createDocument();
1893
+ newDocument.header.name = name;
1894
+ if (preferredEditor) newDocument.header.meta = {
1895
+ ...newDocument.header.meta,
1896
+ preferredEditor
1897
+ };
1898
+ let newDoc;
1907
1899
  try {
1908
- return String(object);
1909
- } catch {
1910
- return "Invalid error";
1900
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
1901
+ } catch (e) {
1902
+ logger.error("Error adding document: @error", e);
1903
+ throw new Error("There was an error adding document", { cause: e });
1911
1904
  }
1912
- };
1913
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1914
- const MESSAGE_MAX_SIZE = 1e3;
1915
- const newError = (name, message) => {
1916
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1917
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1918
- return new Error(message);
1919
- };
1920
- const NATIVE_ERRORS = {
1921
- Error,
1922
- ReferenceError,
1923
- TypeError,
1924
- SyntaxError,
1925
- RangeError,
1926
- URIError,
1927
- EvalError
1928
- };
1929
- const assignObjectProps = (error, object) => {
1930
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1931
- };
1932
- const setNewErrorProperty = (error, propName, propValue) => {
1933
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1934
- };
1935
- //#endregion
1936
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1937
- const stringifyError = (value) => {
1905
+ return {
1906
+ id: newDoc.header.id,
1907
+ name: newDoc.header.name,
1908
+ documentType,
1909
+ parentFolder: parentFolder ?? null,
1910
+ kind: "file"
1911
+ };
1912
+ }
1913
+ async function addFile(file, driveId, name, parentFolder) {
1914
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
1915
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1916
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
1917
+ const document = await loadFile(file);
1918
+ let duplicateId = false;
1919
+ const reactorClient = window.ph?.reactorClient;
1920
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1938
1921
  try {
1939
- const error = new Error(String(value));
1940
- setStack(error);
1941
- return error;
1942
- } catch (error_) {
1943
- return error_;
1922
+ await reactorClient.get(document.header.id);
1923
+ duplicateId = true;
1924
+ } catch {}
1925
+ const documentId = duplicateId ? generateId() : document.header.id;
1926
+ const header = createPresignedHeader(documentId, document.header.documentType);
1927
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
1928
+ header.meta = document.header.meta;
1929
+ header.name = name || document.header.name;
1930
+ const initialDocument = {
1931
+ ...document,
1932
+ header,
1933
+ state: document.initialState,
1934
+ operations: Object.keys(document.operations).reduce((acc, key) => {
1935
+ acc[key] = [];
1936
+ return acc;
1937
+ }, {})
1938
+ };
1939
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
1940
+ await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
1941
+ }
1942
+ async function addFolder$1(driveId, name, parentFolder) {
1943
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1944
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
1945
+ const reactorClient = window.ph?.reactorClient;
1946
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1947
+ await reactorClient.get(driveId);
1948
+ const folderId = generateId();
1949
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
1950
+ id: folderId,
1951
+ name,
1952
+ parentFolder
1953
+ })])).state.global.nodes.find((node) => node.id === folderId);
1954
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
1955
+ return node;
1956
+ }
1957
+ async function renameNode(driveId, nodeId, name) {
1958
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1959
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
1960
+ const reactorClient = window.ph?.reactorClient;
1961
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1962
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
1963
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
1964
+ id: nodeId,
1965
+ name
1966
+ })])).state.global.nodes.find((n) => n.id === nodeId);
1967
+ if (!node) throw new Error("There was an error renaming node in the drive");
1968
+ return node;
1969
+ }
1970
+ async function renameDriveNode(driveId, nodeId, name) {
1971
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1972
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
1973
+ const reactorClient = window.ph?.reactorClient;
1974
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1975
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
1976
+ await reactorClient.execute(driveId, "main", [updateNode({
1977
+ id: nodeId,
1978
+ name
1979
+ })]);
1980
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
1981
+ }
1982
+ async function moveNodeById(args) {
1983
+ const { driveId, srcId, targetId } = args;
1984
+ if (!driveId || !srcId) return;
1985
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1986
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
1987
+ const reactorClient = window.ph?.reactorClient;
1988
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1989
+ const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
1990
+ if (t(targetParentFolder, srcId)) return;
1991
+ return await reactorClient.execute(driveId, "main", [moveNode({
1992
+ srcFolder: srcId,
1993
+ targetParentFolder
1994
+ })]);
1995
+ }
1996
+ async function moveNode$1(driveId, src, target) {
1997
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1998
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
1999
+ const reactorClient = window.ph?.reactorClient;
2000
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2001
+ return await reactorClient.execute(driveId, "main", [moveNode({
2002
+ srcFolder: src.id,
2003
+ targetParentFolder: target?.id
2004
+ })]);
2005
+ }
2006
+ /**
2007
+ * Duplicates a document under a new id using version-aware replay.
2008
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
2009
+ */
2010
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
2011
+ const documentType = document.header.documentType;
2012
+ const { results: allModules } = await reactor.getDocumentModelModules();
2013
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2014
+ const reducers = {};
2015
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2016
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2017
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2018
+ let upgradeManifest;
2019
+ if (registry) try {
2020
+ upgradeManifest = registry.getUpgradeManifest(documentType);
2021
+ } catch {}
2022
+ const config = {
2023
+ reducers,
2024
+ upgradeManifest
2025
+ };
2026
+ const header = createPresignedHeader(newId, documentType);
2027
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2028
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2029
+ return duplicated;
2030
+ }
2031
+ async function copyNode$1(driveId, src, target) {
2032
+ const reactor = window.ph?.reactorClientModule?.client;
2033
+ if (!reactor) return;
2034
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2035
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2036
+ const drive = await reactor.get(driveId);
2037
+ const copyNodesInput = generateNodesCopy({
2038
+ srcId: src.id,
2039
+ targetParentFolder: target?.id,
2040
+ targetName: src.name
2041
+ }, () => generateId(), drive.state.global.nodes);
2042
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
2043
+ for (const copyNodeInput of copyNodesInput) {
2044
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2045
+ if (node) {
2046
+ const resolvedName = handleTargetNameCollisions({
2047
+ nodes: drive.state.global.nodes,
2048
+ srcName: copyNodeInput.targetName || node.name,
2049
+ srcKind: isFileNode(node) ? "file" : "folder",
2050
+ targetParentFolder: copyNodeInput.targetParentFolder || null
2051
+ });
2052
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2053
+ }
1944
2054
  }
1945
- };
1946
- //#endregion
1947
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1948
- const { toString: objectToString } = Object.prototype;
1949
- const createError = (value) => {
1950
- if (isErrorPlainObj(value)) return objectifyError(value);
1951
- if (!isErrorInstance(value)) return stringifyError(value);
1952
- if (isInvalidError(value)) return objectifyError(value);
1953
- return value;
1954
- };
1955
- const isErrorPlainObj = (value) => {
1956
- try {
1957
- return isPlainObject(value);
1958
- } catch {
1959
- return false;
1960
- }
1961
- };
1962
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1963
- const isProxy = (value) => {
1964
- try {
1965
- return objectToString.call(value) === "[object Object]";
1966
- } catch {
1967
- return true;
2055
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2056
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2057
+ return node !== void 0 && isFileNode(node);
2058
+ });
2059
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2060
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2061
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2062
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2063
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2064
+ } catch (e) {
2065
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
1968
2066
  }
2067
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2068
+ }
2069
+ const modalEventFunctions = makePHEventFunctions("modal");
2070
+ modalEventFunctions.useValue;
2071
+ /** Sets the current modal */
2072
+ const setPHModal = modalEventFunctions.setValue;
2073
+ modalEventFunctions.addEventHandler;
2074
+ /** Shows a modal */
2075
+ function showPHModal(modal) {
2076
+ setPHModal(modal);
2077
+ }
2078
+ /** Shows the create document modal */
2079
+ function showCreateDocumentModal(documentType) {
2080
+ setPHModal({
2081
+ type: "createDocument",
2082
+ documentType
2083
+ });
2084
+ }
2085
+ /** Shows the delete node modal */
2086
+ function showDeleteNodeModal(nodeOrId) {
2087
+ setPHModal({
2088
+ type: "deleteItem",
2089
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2090
+ });
2091
+ }
2092
+ /**
2093
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
2094
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
2095
+ */
2096
+ const ReactorOperationFieldsFragmentDoc = import_main.gql`
2097
+ fragment ReactorOperationFields on ReactorOperation {
2098
+ index
2099
+ timestampUtcMs
2100
+ hash
2101
+ skip
2102
+ error
2103
+ id
2104
+ action {
2105
+ id
2106
+ type
2107
+ timestampUtcMs
2108
+ input
2109
+ scope
2110
+ context {
2111
+ signer {
2112
+ user {
2113
+ address
2114
+ networkId
2115
+ chainId
2116
+ }
2117
+ app {
2118
+ name
2119
+ key
2120
+ }
2121
+ signatures
2122
+ }
2123
+ }
2124
+ }
2125
+ }
2126
+ `;
2127
+ import_main.gql`
2128
+ mutation MutateDocumentWithOperations(
2129
+ $documentIdentifier: String!
2130
+ $actions: [JSONObject!]!
2131
+ $view: ViewFilterInput
2132
+ $sinceRevision: Int
2133
+ $scopes: [String!]
2134
+ $branch: String
2135
+ ) {
2136
+ mutateDocument(
2137
+ documentIdentifier: $documentIdentifier
2138
+ actions: $actions
2139
+ view: $view
2140
+ ) {
2141
+ ...PHDocumentFields
2142
+ operations(
2143
+ filter: {
2144
+ sinceRevision: $sinceRevision
2145
+ scopes: $scopes
2146
+ branch: $branch
2147
+ }
2148
+ ) {
2149
+ items {
2150
+ ...ReactorOperationFields
2151
+ }
2152
+ }
2153
+ }
2154
+ }
2155
+ ${PhDocumentFieldsFragmentDoc}
2156
+ ${ReactorOperationFieldsFragmentDoc}
2157
+ `;
2158
+ 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;
2159
+ PropagationMode.Cascade, PropagationMode.Orphan;
2160
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2161
+ /** Sets whether external controls are enabled for a given editor. */
2162
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2163
+ /** Gets whether external controls are enabled for a given editor. */
2164
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2165
+ isExternalControlsEnabledEventFunctions.addEventHandler;
2166
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2167
+ /** Sets whether drag and drop is enabled for a given app. */
2168
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2169
+ /** Gets whether drag and drop is enabled for a given app. */
2170
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2171
+ isDragAndDropEnabledEventFunctions.addEventHandler;
2172
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2173
+ /** Sets the allowed document types for a given app. */
2174
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2175
+ /** Defines the document types a drive supports.
2176
+ *
2177
+ * Defaults to all of the document types registered in the reactor.
2178
+ */
2179
+ function useAllowedDocumentTypes() {
2180
+ return allowedDocumentTypesEventFunctions.useValue();
2181
+ }
2182
+ allowedDocumentTypesEventFunctions.addEventHandler;
2183
+ const phAppConfigSetters = {
2184
+ allowedDocumentTypes: setAllowedDocumentTypes,
2185
+ isDragAndDropEnabled: setIsDragAndDropEnabled
1969
2186
  };
1970
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1971
- //#endregion
1972
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1973
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1974
- const recurseException = (error, parents, shallow) => {
1975
- if (parents.includes(error)) return;
1976
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1977
- const errorA = createError(error);
1978
- normalizeProps(errorA, recurse);
1979
- return errorA;
1980
- };
1981
- const identity = (error) => error;
1982
- const normalizeProps = (error, recurse) => {
1983
- normalizeName(error);
1984
- normalizeMessage(error);
1985
- normalizeStack(error);
1986
- normalizeCause(error, recurse);
1987
- normalizeAggregate(error, recurse);
1988
- normalizeDescriptors(error);
1989
- };
1990
- const normalizeName = (error) => {
1991
- if (isDefinedString(error.name)) return;
1992
- const prototypeName = Object.getPrototypeOf(error).name;
1993
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1994
- };
1995
- const normalizeMessage = (error) => {
1996
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1997
- };
1998
- const normalizeStack = (error) => {
1999
- if (!isDefinedString(error.stack)) setStack(error);
2000
- };
2001
- const isDefinedString = (value) => typeof value === "string" && value !== "";
2002
- //#endregion
2003
- //#region ../reactor-browser/dist/index.js
2004
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
2005
- var LZString = (function() {
2006
- var f = String.fromCharCode;
2007
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
2008
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
2009
- var baseReverseDic = {};
2010
- function getBaseValue(alphabet, character) {
2011
- if (!baseReverseDic[alphabet]) {
2012
- baseReverseDic[alphabet] = {};
2013
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
2014
- }
2015
- return baseReverseDic[alphabet][character];
2016
- }
2017
- var LZString = {
2018
- compressToBase64: function(input) {
2019
- if (input == null) return "";
2020
- var res = LZString._compress(input, 6, function(a) {
2021
- return keyStrBase64.charAt(a);
2022
- });
2023
- switch (res.length % 4) {
2024
- default:
2025
- case 0: return res;
2026
- case 1: return res + "===";
2027
- case 2: return res + "==";
2028
- case 3: return res + "=";
2029
- }
2030
- },
2031
- decompressFromBase64: function(input) {
2032
- if (input == null) return "";
2033
- if (input == "") return null;
2034
- return LZString._decompress(input.length, 32, function(index) {
2035
- return getBaseValue(keyStrBase64, input.charAt(index));
2036
- });
2037
- },
2038
- compressToUTF16: function(input) {
2039
- if (input == null) return "";
2040
- return LZString._compress(input, 15, function(a) {
2041
- return f(a + 32);
2042
- }) + " ";
2043
- },
2044
- decompressFromUTF16: function(compressed) {
2045
- if (compressed == null) return "";
2046
- if (compressed == "") return null;
2047
- return LZString._decompress(compressed.length, 16384, function(index) {
2048
- return compressed.charCodeAt(index) - 32;
2049
- });
2050
- },
2051
- compressToUint8Array: function(uncompressed) {
2052
- var compressed = LZString.compress(uncompressed);
2053
- var buf = new Uint8Array(compressed.length * 2);
2054
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2055
- var current_value = compressed.charCodeAt(i);
2056
- buf[i * 2] = current_value >>> 8;
2057
- buf[i * 2 + 1] = current_value % 256;
2058
- }
2059
- return buf;
2060
- },
2061
- decompressFromUint8Array: function(compressed) {
2062
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2063
- else {
2064
- var buf = new Array(compressed.length / 2);
2065
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2066
- var result = [];
2067
- buf.forEach(function(c) {
2068
- result.push(f(c));
2069
- });
2070
- return LZString.decompress(result.join(""));
2071
- }
2072
- },
2073
- compressToEncodedURIComponent: function(input) {
2074
- if (input == null) return "";
2075
- return LZString._compress(input, 6, function(a) {
2076
- return keyStrUriSafe.charAt(a);
2077
- });
2078
- },
2079
- decompressFromEncodedURIComponent: function(input) {
2080
- if (input == null) return "";
2081
- if (input == "") return null;
2082
- input = input.replace(/ /g, "+");
2083
- return LZString._decompress(input.length, 32, function(index) {
2084
- return getBaseValue(keyStrUriSafe, input.charAt(index));
2085
- });
2086
- },
2087
- compress: function(uncompressed) {
2088
- return LZString._compress(uncompressed, 16, function(a) {
2089
- return f(a);
2090
- });
2091
- },
2092
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2093
- if (uncompressed == null) return "";
2094
- 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;
2095
- for (ii = 0; ii < uncompressed.length; ii += 1) {
2096
- context_c = uncompressed.charAt(ii);
2097
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2098
- context_dictionary[context_c] = context_dictSize++;
2099
- context_dictionaryToCreate[context_c] = true;
2100
- }
2101
- context_wc = context_w + context_c;
2102
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2103
- else {
2104
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2105
- if (context_w.charCodeAt(0) < 256) {
2106
- for (i = 0; i < context_numBits; i++) {
2107
- context_data_val = context_data_val << 1;
2108
- if (context_data_position == bitsPerChar - 1) {
2109
- context_data_position = 0;
2110
- context_data.push(getCharFromInt(context_data_val));
2111
- context_data_val = 0;
2112
- } else context_data_position++;
2113
- }
2114
- value = context_w.charCodeAt(0);
2115
- for (i = 0; i < 8; i++) {
2116
- context_data_val = context_data_val << 1 | value & 1;
2117
- if (context_data_position == bitsPerChar - 1) {
2118
- context_data_position = 0;
2119
- context_data.push(getCharFromInt(context_data_val));
2120
- context_data_val = 0;
2121
- } else context_data_position++;
2122
- value = value >> 1;
2123
- }
2124
- } else {
2125
- value = 1;
2126
- for (i = 0; i < context_numBits; i++) {
2127
- context_data_val = context_data_val << 1 | value;
2128
- if (context_data_position == bitsPerChar - 1) {
2129
- context_data_position = 0;
2130
- context_data.push(getCharFromInt(context_data_val));
2131
- context_data_val = 0;
2132
- } else context_data_position++;
2133
- value = 0;
2134
- }
2135
- value = context_w.charCodeAt(0);
2136
- for (i = 0; i < 16; i++) {
2137
- context_data_val = context_data_val << 1 | value & 1;
2138
- if (context_data_position == bitsPerChar - 1) {
2139
- context_data_position = 0;
2140
- context_data.push(getCharFromInt(context_data_val));
2141
- context_data_val = 0;
2142
- } else context_data_position++;
2143
- value = value >> 1;
2144
- }
2145
- }
2146
- context_enlargeIn--;
2147
- if (context_enlargeIn == 0) {
2148
- context_enlargeIn = Math.pow(2, context_numBits);
2149
- context_numBits++;
2150
- }
2151
- delete context_dictionaryToCreate[context_w];
2152
- } else {
2153
- value = context_dictionary[context_w];
2154
- for (i = 0; i < context_numBits; i++) {
2155
- context_data_val = context_data_val << 1 | value & 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
- value = value >> 1;
2162
- }
2163
- }
2164
- context_enlargeIn--;
2165
- if (context_enlargeIn == 0) {
2166
- context_enlargeIn = Math.pow(2, context_numBits);
2167
- context_numBits++;
2168
- }
2169
- context_dictionary[context_wc] = context_dictSize++;
2170
- context_w = String(context_c);
2171
- }
2172
- }
2173
- if (context_w !== "") {
2174
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2175
- if (context_w.charCodeAt(0) < 256) {
2176
- for (i = 0; i < context_numBits; i++) {
2177
- context_data_val = context_data_val << 1;
2178
- if (context_data_position == bitsPerChar - 1) {
2179
- context_data_position = 0;
2180
- context_data.push(getCharFromInt(context_data_val));
2181
- context_data_val = 0;
2182
- } else context_data_position++;
2183
- }
2184
- value = context_w.charCodeAt(0);
2185
- for (i = 0; i < 8; i++) {
2186
- context_data_val = context_data_val << 1 | value & 1;
2187
- if (context_data_position == bitsPerChar - 1) {
2188
- context_data_position = 0;
2189
- context_data.push(getCharFromInt(context_data_val));
2190
- context_data_val = 0;
2191
- } else context_data_position++;
2192
- value = value >> 1;
2193
- }
2194
- } else {
2195
- value = 1;
2196
- for (i = 0; i < context_numBits; i++) {
2197
- context_data_val = context_data_val << 1 | value;
2198
- if (context_data_position == bitsPerChar - 1) {
2199
- context_data_position = 0;
2200
- context_data.push(getCharFromInt(context_data_val));
2201
- context_data_val = 0;
2202
- } else context_data_position++;
2203
- value = 0;
2204
- }
2205
- value = context_w.charCodeAt(0);
2206
- for (i = 0; i < 16; i++) {
2207
- context_data_val = context_data_val << 1 | value & 1;
2208
- if (context_data_position == bitsPerChar - 1) {
2209
- context_data_position = 0;
2210
- context_data.push(getCharFromInt(context_data_val));
2211
- context_data_val = 0;
2212
- } else context_data_position++;
2213
- value = value >> 1;
2214
- }
2215
- }
2216
- context_enlargeIn--;
2217
- if (context_enlargeIn == 0) {
2218
- context_enlargeIn = Math.pow(2, context_numBits);
2219
- context_numBits++;
2220
- }
2221
- delete context_dictionaryToCreate[context_w];
2222
- } else {
2223
- value = context_dictionary[context_w];
2224
- for (i = 0; i < context_numBits; i++) {
2225
- context_data_val = context_data_val << 1 | value & 1;
2226
- if (context_data_position == bitsPerChar - 1) {
2227
- context_data_position = 0;
2228
- context_data.push(getCharFromInt(context_data_val));
2229
- context_data_val = 0;
2230
- } else context_data_position++;
2231
- value = value >> 1;
2232
- }
2233
- }
2234
- context_enlargeIn--;
2235
- if (context_enlargeIn == 0) {
2236
- context_enlargeIn = Math.pow(2, context_numBits);
2237
- context_numBits++;
2238
- }
2239
- }
2240
- value = 2;
2241
- for (i = 0; i < context_numBits; i++) {
2242
- context_data_val = context_data_val << 1 | value & 1;
2243
- if (context_data_position == bitsPerChar - 1) {
2244
- context_data_position = 0;
2245
- context_data.push(getCharFromInt(context_data_val));
2246
- context_data_val = 0;
2247
- } else context_data_position++;
2248
- value = value >> 1;
2249
- }
2250
- while (true) {
2251
- context_data_val = context_data_val << 1;
2252
- if (context_data_position == bitsPerChar - 1) {
2253
- context_data.push(getCharFromInt(context_data_val));
2254
- break;
2255
- } else context_data_position++;
2256
- }
2257
- return context_data.join("");
2258
- },
2259
- decompress: function(compressed) {
2260
- if (compressed == null) return "";
2261
- if (compressed == "") return null;
2262
- return LZString._decompress(compressed.length, 32768, function(index) {
2263
- return compressed.charCodeAt(index);
2264
- });
2265
- },
2266
- _decompress: function(length, resetValue, getNextValue) {
2267
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2268
- val: getNextValue(0),
2269
- position: resetValue,
2270
- index: 1
2271
- };
2272
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
2273
- bits = 0;
2274
- maxpower = Math.pow(2, 2);
2275
- power = 1;
2276
- while (power != maxpower) {
2277
- resb = data.val & data.position;
2278
- data.position >>= 1;
2279
- if (data.position == 0) {
2280
- data.position = resetValue;
2281
- data.val = getNextValue(data.index++);
2282
- }
2283
- bits |= (resb > 0 ? 1 : 0) * power;
2284
- power <<= 1;
2285
- }
2286
- switch (bits) {
2287
- case 0:
2288
- bits = 0;
2289
- maxpower = Math.pow(2, 8);
2290
- power = 1;
2291
- while (power != maxpower) {
2292
- resb = data.val & data.position;
2293
- data.position >>= 1;
2294
- if (data.position == 0) {
2295
- data.position = resetValue;
2296
- data.val = getNextValue(data.index++);
2297
- }
2298
- bits |= (resb > 0 ? 1 : 0) * power;
2299
- power <<= 1;
2300
- }
2301
- c = f(bits);
2302
- break;
2303
- case 1:
2304
- bits = 0;
2305
- maxpower = Math.pow(2, 16);
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
- c = f(bits);
2318
- break;
2319
- case 2: return "";
2320
- }
2321
- dictionary[3] = c;
2322
- w = c;
2323
- result.push(c);
2324
- while (true) {
2325
- if (data.index > length) return "";
2326
- bits = 0;
2327
- maxpower = Math.pow(2, numBits);
2328
- power = 1;
2329
- while (power != maxpower) {
2330
- resb = data.val & data.position;
2331
- data.position >>= 1;
2332
- if (data.position == 0) {
2333
- data.position = resetValue;
2334
- data.val = getNextValue(data.index++);
2335
- }
2336
- bits |= (resb > 0 ? 1 : 0) * power;
2337
- power <<= 1;
2338
- }
2339
- switch (c = bits) {
2340
- case 0:
2341
- bits = 0;
2342
- maxpower = Math.pow(2, 8);
2343
- power = 1;
2344
- while (power != maxpower) {
2345
- resb = data.val & data.position;
2346
- data.position >>= 1;
2347
- if (data.position == 0) {
2348
- data.position = resetValue;
2349
- data.val = getNextValue(data.index++);
2350
- }
2351
- bits |= (resb > 0 ? 1 : 0) * power;
2352
- power <<= 1;
2353
- }
2354
- dictionary[dictSize++] = f(bits);
2355
- c = dictSize - 1;
2356
- enlargeIn--;
2357
- break;
2358
- case 1:
2359
- bits = 0;
2360
- maxpower = Math.pow(2, 16);
2361
- power = 1;
2362
- while (power != maxpower) {
2363
- resb = data.val & data.position;
2364
- data.position >>= 1;
2365
- if (data.position == 0) {
2366
- data.position = resetValue;
2367
- data.val = getNextValue(data.index++);
2368
- }
2369
- bits |= (resb > 0 ? 1 : 0) * power;
2370
- power <<= 1;
2371
- }
2372
- dictionary[dictSize++] = f(bits);
2373
- c = dictSize - 1;
2374
- enlargeIn--;
2375
- break;
2376
- case 2: return result.join("");
2377
- }
2378
- if (enlargeIn == 0) {
2379
- enlargeIn = Math.pow(2, numBits);
2380
- numBits++;
2381
- }
2382
- if (dictionary[c]) entry = dictionary[c];
2383
- else if (c === dictSize) entry = w + w.charAt(0);
2384
- else return null;
2385
- result.push(entry);
2386
- dictionary[dictSize++] = w + entry.charAt(0);
2387
- enlargeIn--;
2388
- w = entry;
2389
- if (enlargeIn == 0) {
2390
- enlargeIn = Math.pow(2, numBits);
2391
- numBits++;
2392
- }
2393
- }
2394
- }
2395
- };
2396
- return LZString;
2397
- })();
2398
- if (typeof define === "function" && define.amd) define(function() {
2399
- return LZString;
2400
- });
2401
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2402
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2403
- return LZString;
2404
- });
2405
- })))(), 1);
2406
- var DocumentModelNotFoundError = class extends Error {
2407
- documentType;
2408
- name = "DocumentModelNotFoundError";
2409
- constructor(documentType) {
2410
- super(`Document model module for type ${documentType} not found`);
2411
- this.documentType = documentType;
2412
- }
2413
- static isError(error) {
2414
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2415
- }
2416
- };
2417
- var DocumentTypeMismatchError = class extends Error {
2418
- constructor(documentId, expectedType, actualType) {
2419
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2420
- }
2421
- };
2422
- var NoSelectedDocumentError = class extends Error {
2423
- constructor() {
2424
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2425
- }
2426
- };
2427
- function getUserPermissions() {
2428
- const user = window.ph?.renown?.user;
2429
- const allowList = window.ph?.allowList;
2430
- if (!allowList) return {
2431
- isAllowedToCreateDocuments: true,
2432
- isAllowedToEditDocuments: true
2433
- };
2434
- return {
2435
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2436
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2437
- };
2438
- }
2439
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2440
- async function downloadFile(document, fileName) {
2441
- try {
2442
- const data = await createZip(document);
2443
- const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2444
- const link = window.document.createElement("a");
2445
- link.style.display = "none";
2446
- link.href = URL.createObjectURL(blob);
2447
- link.download = fileName;
2448
- window.document.body.appendChild(link);
2449
- link.click();
2450
- window.document.body.removeChild(link);
2451
- } catch (e) {
2452
- logger.error(e instanceof Error ? e.message : String(e));
2453
- }
2454
- }
2455
- async function getDocumentExtension(document) {
2456
- const documentType = document.header.documentType;
2457
- let rawExtension;
2458
- if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2459
- else {
2460
- const reactorClient = window.ph?.reactorClient;
2461
- if (reactorClient) {
2462
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2463
- rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2464
- }
2465
- }
2466
- return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2467
- }
2468
- /**
2469
- * Fetches all operations for a document using cursor-based pagination.
2470
- * The reactor client handles multi-scope cursors transparently via
2471
- * composite cursors, so all scopes are fetched in a single paginated stream.
2472
- */
2473
- async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2474
- const scopes = Object.keys(document.state);
2475
- const operations = {};
2476
- for (const scope of scopes) operations[scope] = [];
2477
- let cursor = "";
2478
- do {
2479
- const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2480
- cursor,
2481
- limit: pageSize
2482
- });
2483
- for (const op of page.results) {
2484
- const scope = op.action.scope ?? "global";
2485
- if (operations[scope]) operations[scope].push(op);
2486
- }
2487
- cursor = page.nextCursor ?? "";
2488
- } while (cursor);
2489
- return operations;
2490
- }
2491
- function extractInitialState(documentScopeOps) {
2492
- const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2493
- if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2494
- const input = upgradeOp.action.input;
2495
- const initialState = input.initialState ?? input.state;
2496
- if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2497
- return initialState;
2498
- }
2499
- function filterDomainOperations(operations) {
2500
- return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2501
- }
2502
- async function exportFile(document, suggestedName) {
2503
- const reactorClient = window.ph?.reactorClient;
2504
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2505
- const operations = await fetchDocumentOperations(reactorClient, document);
2506
- const initialState = extractInitialState(operations["document"] ?? []);
2507
- const documentWithOps = {
2508
- ...document,
2509
- operations,
2510
- initialState
2511
- };
2512
- const extension = await getDocumentExtension(documentWithOps);
2513
- const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2514
- const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2515
- if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2516
- try {
2517
- const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2518
- await baseSaveToFileHandle(documentWithOps, fileHandle);
2519
- return fileHandle;
2520
- } catch (e) {
2521
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2522
- }
2523
- }
2524
- /**
2525
- * Loads a document file and replays it with version-aware reducers from the registry.
2526
- * Falls back to single-version legacy replay when no upgrade manifest is registered for
2527
- * the document type.
2528
- */
2529
- async function loadFile(path) {
2530
- const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2531
- const reactorClient = window.ph?.reactorClient;
2532
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2533
- const documentType = baseDocument.header.documentType;
2534
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2535
- const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2536
- if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2537
- const reducers = {};
2538
- for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2539
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2540
- let upgradeManifest;
2541
- if (registry) try {
2542
- upgradeManifest = registry.getUpgradeManifest(documentType);
2543
- } catch {}
2544
- return baseLoadFromInputVersioned(path, {
2545
- reducers,
2546
- upgradeManifest
2547
- });
2548
- }
2549
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2550
- const { isAllowedToCreateDocuments } = getUserPermissions();
2551
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2552
- const reactorClient = window.ph?.reactorClient;
2553
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2554
- const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2555
- const newDocument = document ?? documentModelModule.utils.createDocument();
2556
- newDocument.header.name = name;
2557
- if (preferredEditor) newDocument.header.meta = {
2558
- ...newDocument.header.meta,
2559
- preferredEditor
2560
- };
2561
- let newDoc;
2562
- try {
2563
- newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2564
- } catch (e) {
2565
- logger.error("Error adding document: @error", e);
2566
- throw new Error("There was an error adding document", { cause: e });
2567
- }
2568
- return {
2569
- id: newDoc.header.id,
2570
- name: newDoc.header.name,
2571
- documentType,
2572
- parentFolder: parentFolder ?? null,
2573
- kind: "file"
2574
- };
2575
- }
2576
- async function addFile(file, driveId, name, parentFolder) {
2577
- logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2578
- const { isAllowedToCreateDocuments } = getUserPermissions();
2579
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2580
- const document = await loadFile(file);
2581
- let duplicateId = false;
2582
- const reactorClient = window.ph?.reactorClient;
2583
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2584
- try {
2585
- await reactorClient.get(document.header.id);
2586
- duplicateId = true;
2587
- } catch {}
2588
- const documentId = duplicateId ? generateId() : document.header.id;
2589
- const header = createPresignedHeader(documentId, document.header.documentType);
2590
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2591
- header.meta = document.header.meta;
2592
- header.name = name || document.header.name;
2593
- const initialDocument = {
2594
- ...document,
2595
- header,
2596
- state: document.initialState,
2597
- operations: Object.keys(document.operations).reduce((acc, key) => {
2598
- acc[key] = [];
2599
- return acc;
2600
- }, {})
2601
- };
2602
- await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2603
- await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2604
- }
2605
- async function addFolder(driveId, name, parentFolder) {
2606
- const { isAllowedToCreateDocuments } = getUserPermissions();
2607
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2608
- const reactorClient = window.ph?.reactorClient;
2609
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2610
- await reactorClient.get(driveId);
2611
- const folderId = generateId();
2612
- const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2613
- id: folderId,
2614
- name,
2615
- parentFolder
2616
- })])).state.global.nodes.find((node) => node.id === folderId);
2617
- if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2618
- return node;
2619
- }
2620
- async function renameNode(driveId, nodeId, name) {
2621
- const { isAllowedToCreateDocuments } = getUserPermissions();
2622
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2623
- const reactorClient = window.ph?.reactorClient;
2624
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2625
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2626
- const node = (await reactorClient.execute(driveId, "main", [updateNode({
2627
- id: nodeId,
2628
- name
2629
- })])).state.global.nodes.find((n) => n.id === nodeId);
2630
- if (!node) throw new Error("There was an error renaming node in the drive");
2631
- return node;
2632
- }
2633
- async function renameDriveNode(driveId, nodeId, name) {
2634
- const { isAllowedToCreateDocuments } = getUserPermissions();
2635
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2636
- const reactorClient = window.ph?.reactorClient;
2637
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2638
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2639
- await reactorClient.execute(driveId, "main", [updateNode({
2640
- id: nodeId,
2641
- name
2642
- })]);
2643
- return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2644
- }
2645
- async function moveNodeById(args) {
2646
- const { driveId, srcId, targetId } = args;
2647
- if (!driveId || !srcId) return;
2648
- const { isAllowedToCreateDocuments } = getUserPermissions();
2649
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2650
- const reactorClient = window.ph?.reactorClient;
2651
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2652
- const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2653
- if (t(targetParentFolder, srcId)) return;
2654
- return await reactorClient.execute(driveId, "main", [moveNode({
2655
- srcFolder: srcId,
2656
- targetParentFolder
2657
- })]);
2658
- }
2659
- async function moveNode$1(driveId, src, target) {
2660
- const { isAllowedToCreateDocuments } = getUserPermissions();
2661
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2662
- const reactorClient = window.ph?.reactorClient;
2663
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2664
- return await reactorClient.execute(driveId, "main", [moveNode({
2665
- srcFolder: src.id,
2666
- targetParentFolder: target?.id
2667
- })]);
2668
- }
2669
- /**
2670
- * Duplicates a document under a new id using version-aware replay.
2671
- * Falls back gracefully when no upgrade manifest is registered for the document type.
2672
- */
2673
- async function _duplicateDocument(reactor, document, newId = generateId()) {
2674
- const documentType = document.header.documentType;
2675
- const { results: allModules } = await reactor.getDocumentModelModules();
2676
- const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2677
- const reducers = {};
2678
- for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2679
- if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2680
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2681
- let upgradeManifest;
2682
- if (registry) try {
2683
- upgradeManifest = registry.getUpgradeManifest(documentType);
2684
- } catch {}
2685
- const config = {
2686
- reducers,
2687
- upgradeManifest
2688
- };
2689
- const header = createPresignedHeader(newId, documentType);
2690
- const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2691
- assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2692
- return duplicated;
2693
- }
2694
- async function copyNode$1(driveId, src, target) {
2695
- const reactor = window.ph?.reactorClient;
2696
- if (!reactor) return;
2697
- const { isAllowedToCreateDocuments } = getUserPermissions();
2698
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2699
- const drive = await reactor.get(driveId);
2700
- const copyNodesInput = generateNodesCopy({
2701
- srcId: src.id,
2702
- targetParentFolder: target?.id,
2703
- targetName: src.name
2704
- }, () => generateId(), drive.state.global.nodes);
2705
- const resolvedNamesMap = /* @__PURE__ */ new Map();
2706
- for (const copyNodeInput of copyNodesInput) {
2707
- const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2708
- if (node) {
2709
- const resolvedName = handleTargetNameCollisions({
2710
- nodes: drive.state.global.nodes,
2711
- srcName: copyNodeInput.targetName || node.name,
2712
- srcKind: isFileNode(node) ? "file" : "folder",
2713
- targetParentFolder: copyNodeInput.targetParentFolder || null
2714
- });
2715
- resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2716
- }
2717
- }
2718
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2719
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2720
- return node !== void 0 && isFileNode(node);
2721
- });
2722
- for (const fileNodeToCopy of fileNodesToCopy) try {
2723
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2724
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2725
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2726
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2727
- } catch (e) {
2728
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2729
- }
2730
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2731
- }
2732
- const modalEventFunctions = makePHEventFunctions("modal");
2733
- modalEventFunctions.useValue;
2734
- /** Sets the current modal */
2735
- const setPHModal = modalEventFunctions.setValue;
2736
- modalEventFunctions.addEventHandler;
2737
- /** Shows a modal */
2738
- function showPHModal(modal) {
2739
- setPHModal(modal);
2740
- }
2741
- /** Shows the create document modal */
2742
- function showCreateDocumentModal(documentType) {
2743
- setPHModal({
2744
- type: "createDocument",
2745
- documentType
2746
- });
2747
- }
2748
- /** Shows the delete node modal */
2749
- function showDeleteNodeModal(nodeOrId) {
2750
- setPHModal({
2751
- type: "deleteItem",
2752
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2753
- });
2754
- }
2755
- /** Document types that represent a "drive": a container of nodes. */
2756
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
2757
- const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2758
- /** Sets whether external controls are enabled for a given editor. */
2759
- const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2760
- /** Gets whether external controls are enabled for a given editor. */
2761
- const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2762
- isExternalControlsEnabledEventFunctions.addEventHandler;
2763
- const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2764
- /** Sets whether drag and drop is enabled for a given app. */
2765
- const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2766
- /** Gets whether drag and drop is enabled for a given app. */
2767
- const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2768
- isDragAndDropEnabledEventFunctions.addEventHandler;
2769
- const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2770
- /** Sets the allowed document types for a given app. */
2771
- const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2772
- /** Defines the document types a drive supports.
2773
- *
2774
- * Defaults to all of the document types registered in the reactor.
2775
- */
2776
- function useAllowedDocumentTypes() {
2777
- return allowedDocumentTypesEventFunctions.useValue();
2778
- }
2779
- allowedDocumentTypesEventFunctions.addEventHandler;
2780
- const phAppConfigSetters = {
2781
- allowedDocumentTypes: setAllowedDocumentTypes,
2782
- isDragAndDropEnabled: setIsDragAndDropEnabled
2783
- };
2784
- const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2785
- const phAppConfigHooks = {
2786
- allowedDocumentTypes: useAllowedDocumentTypes,
2787
- isDragAndDropEnabled: useIsDragAndDropEnabled
2187
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2188
+ const phAppConfigHooks = {
2189
+ allowedDocumentTypes: useAllowedDocumentTypes,
2190
+ isDragAndDropEnabled: useIsDragAndDropEnabled
2788
2191
  };
2789
2192
  const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
2790
2193
  const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
@@ -2991,374 +2394,1089 @@ const nonUserConfigHooks = {
2991
2394
  ...phDocumentEditorConfigHooks,
2992
2395
  ...nonUserConfigHooks
2993
2396
  });
2994
- const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2995
- attachmentServiceEventFunctions.useValue;
2996
- attachmentServiceEventFunctions.setValue;
2997
- attachmentServiceEventFunctions.addEventHandler;
2998
- const featuresEventFunctions = makePHEventFunctions("features");
2999
- featuresEventFunctions.useValue;
3000
- featuresEventFunctions.setValue;
3001
- featuresEventFunctions.addEventHandler;
3002
- function resolveUrlPathname(path) {
3003
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2397
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2398
+ attachmentServiceEventFunctions.useValue;
2399
+ attachmentServiceEventFunctions.setValue;
2400
+ attachmentServiceEventFunctions.addEventHandler;
2401
+ const featuresEventFunctions = makePHEventFunctions("features");
2402
+ featuresEventFunctions.useValue;
2403
+ featuresEventFunctions.setValue;
2404
+ featuresEventFunctions.addEventHandler;
2405
+ function resolveUrlPathname(path) {
2406
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2407
+ }
2408
+ /** Returns the current path without the base path */
2409
+ function getPathWithoutBase(path) {
2410
+ const basePath = window.ph?.basePath ?? "/";
2411
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2412
+ }
2413
+ /** Makes a URL component for a node. */
2414
+ function makeNodeSlug(node) {
2415
+ if (!node) return "";
2416
+ const nodeName = node.name;
2417
+ if (!nodeName) return slug(node.id);
2418
+ return slug(`${nodeName}-${node.id}`);
2419
+ }
2420
+ /** Extracts the node slug from a path.
2421
+ *
2422
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
2423
+ */
2424
+ function extractNodeSlugFromPath(path) {
2425
+ const currentPath = getPathWithoutBase(path);
2426
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2427
+ }
2428
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
2429
+ function findUuid(input) {
2430
+ if (!input) return void 0;
2431
+ return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
2432
+ }
2433
+ function extractNodeIdFromSlug(nodeSlug) {
2434
+ return findUuid(nodeSlug);
2435
+ }
2436
+ /** Extracts the drive slug from a path.
2437
+ * Used for extracting drive ids from drive slugs in the URL.
2438
+ * Expects the path to be in the format `/d/<drive-slug>`.
2439
+ */
2440
+ function extractDriveSlugFromPath(path) {
2441
+ const currentPath = getPathWithoutBase(path);
2442
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2443
+ }
2444
+ /**
2445
+ * Creates a URL string with the given pathname while preserving existing query parameters.
2446
+ */
2447
+ function createUrlWithPreservedParams(pathname) {
2448
+ const search = window.location.search;
2449
+ return search ? `${pathname}${search}` : pathname;
2450
+ }
2451
+ const drivesEventFunctions = makePHEventFunctions("drives");
2452
+ /** Returns all of the drives in the reactor */
2453
+ const useDrives = drivesEventFunctions.useValue;
2454
+ /** Sets the drives in the reactor */
2455
+ const setDrives = drivesEventFunctions.setValue;
2456
+ drivesEventFunctions.addEventHandler;
2457
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
2458
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
2459
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
2460
+ selectedNodeIdEventFunctions.addEventHandler;
2461
+ /** Sets the selected node (file or folder). */
2462
+ function setSelectedNode(nodeOrNodeSlug) {
2463
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
2464
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
2465
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
2466
+ if (!driveSlugFromPath) return;
2467
+ if (!nodeSlug) {
2468
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
2469
+ if (pathname === window.location.pathname) return;
2470
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2471
+ return;
2472
+ }
2473
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
2474
+ if (pathname === window.location.pathname) return;
2475
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2476
+ }
2477
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
2478
+ /** Returns the selected drive id */
2479
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
2480
+ /** Sets the selected drive id */
2481
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
2482
+ selectedDriveIdEventFunctions.addEventHandler;
2483
+ /** Returns the selected drive, or undefined if no drive is selected */
2484
+ function useSelectedDriveSafe() {
2485
+ const selectedDriveId = useSelectedDriveId();
2486
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
2487
+ const [drive, dispatch] = useDispatch(selectedDrive);
2488
+ if (!selectedDrive) return [void 0, void 0];
2489
+ return [drive, dispatch];
2490
+ }
2491
+ function setSelectedDrive(driveOrDriveSlug) {
2492
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
2493
+ const drives = window.ph?.drives;
2494
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
2495
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
2496
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
2497
+ deferDriveSelection(driveSlug);
2498
+ return;
2499
+ }
2500
+ cancelPendingDriveSelection();
2501
+ setSelectedDriveId(driveId);
2502
+ if (!driveId) {
2503
+ const pathname = resolveUrlPathname("/");
2504
+ if (pathname === window.location.pathname) return;
2505
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2506
+ return;
2507
+ }
2508
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
2509
+ if (pathname === window.location.pathname) return;
2510
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2511
+ }
2512
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
2513
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
2514
+ function isInitialSyncInFlight() {
2515
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
2516
+ if (!remotes?.length) return false;
2517
+ return remotes.some((remote) => {
2518
+ try {
2519
+ const snapshot = remote.channel.getConnectionState();
2520
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
2521
+ } catch {
2522
+ return false;
2523
+ }
2524
+ });
2525
+ }
2526
+ let pendingHandler;
2527
+ let pendingTimeout;
2528
+ function cancelPendingDriveSelection() {
2529
+ if (pendingHandler) {
2530
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
2531
+ pendingHandler = void 0;
2532
+ }
2533
+ if (pendingTimeout) {
2534
+ clearTimeout(pendingTimeout);
2535
+ pendingTimeout = void 0;
2536
+ }
2537
+ }
2538
+ function deferDriveSelection(driveSlug) {
2539
+ cancelPendingDriveSelection();
2540
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
2541
+ const handler = () => {
2542
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
2543
+ cancelPendingDriveSelection();
2544
+ setSelectedDrive(driveSlug);
2545
+ setSelectedNode(nodeSlug);
2546
+ };
2547
+ pendingHandler = handler;
2548
+ window.addEventListener("ph:drivesUpdated", handler);
2549
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
2550
+ const scheduleTick = () => {
2551
+ pendingTimeout = setTimeout(() => {
2552
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
2553
+ scheduleTick();
2554
+ return;
2555
+ }
2556
+ cancelPendingDriveSelection();
2557
+ const pathname = resolveUrlPathname("/");
2558
+ if (pathname === window.location.pathname) return;
2559
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2560
+ }, DEFERRED_DRIVE_TICK_MS);
2561
+ };
2562
+ scheduleTick();
2563
+ }
2564
+ function useDropTarget() {
2565
+ const [isDropTarget, setIsDropTarget] = useState(false);
2566
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2567
+ const targetSetter = n$1(() => setIsDropTarget(true), {
2568
+ triggerAt: "start",
2569
+ minQuietPeriodMs: 100
2570
+ });
2571
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
2572
+ triggerAt: "start",
2573
+ minQuietPeriodMs: 100
2574
+ });
2575
+ function setTarget() {
2576
+ if (!isDragAndDropEnabled) return;
2577
+ targetUnsetter.cancel();
2578
+ targetSetter.call();
2579
+ }
2580
+ function unsetTarget() {
2581
+ if (!isDragAndDropEnabled) return;
2582
+ targetSetter.cancel();
2583
+ targetUnsetter.call();
2584
+ }
2585
+ return {
2586
+ isDropTarget,
2587
+ setTarget,
2588
+ unsetTarget
2589
+ };
2590
+ }
2591
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
2592
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
2593
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
2594
+ draggingNodeEventFunctions.addEventHandler;
2595
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
2596
+ reducer: (_, newNode) => newNode,
2597
+ triggerAt: "start",
2598
+ minQuietPeriodMs: 100
2599
+ });
2600
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
2601
+ triggerAt: "start",
2602
+ minQuietPeriodMs: 100
2603
+ });
2604
+ function setDragging(node) {
2605
+ draggingNodeUnsetter.cancel();
2606
+ draggingNodeSetter.call(node);
3004
2607
  }
3005
- /** Returns the current path without the base path */
3006
- function getPathWithoutBase(path) {
3007
- const basePath = window.ph?.basePath ?? "/";
3008
- return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2608
+ function unsetDragging() {
2609
+ draggingNodeSetter.cancel();
2610
+ draggingNodeUnsetter.call();
3009
2611
  }
3010
- /** Makes a URL component for a node. */
3011
- function makeNodeSlug(node) {
3012
- if (!node) return "";
3013
- const nodeName = node.name;
3014
- if (!nodeName) return slug(node.id);
3015
- return slug(`${nodeName}-${node.id}`);
2612
+ 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));
2613
+ function useDragNode(args) {
2614
+ const { srcId, parentId } = args;
2615
+ const driveId = useSelectedDriveId();
2616
+ const draggingNodeId = useDraggingNode()?.srcId;
2617
+ const params = {
2618
+ driveId,
2619
+ srcId,
2620
+ parentId
2621
+ };
2622
+ const draggable = isNodeDrag(params);
2623
+ const isDragging = t$4({
2624
+ srcId,
2625
+ draggingNodeId
2626
+ }, [
2627
+ () => draggable,
2628
+ ({ srcId }) => e$2(srcId),
2629
+ ({ draggingNodeId }) => e$2(draggingNodeId),
2630
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
2631
+ ]);
2632
+ const onDragStart = () => {
2633
+ if (!draggable) return;
2634
+ setDragging(params);
2635
+ };
2636
+ const onDragEnd = () => {
2637
+ if (!draggable) return;
2638
+ unsetDragging();
2639
+ };
2640
+ return {
2641
+ isDragging,
2642
+ draggable,
2643
+ onDragStart,
2644
+ onDragEnd
2645
+ };
3016
2646
  }
3017
- /** Extracts the node slug from a path.
3018
- *
3019
- * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
3020
- */
3021
- function extractNodeSlugFromPath(path) {
3022
- const currentPath = getPathWithoutBase(path);
3023
- return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2647
+ 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));
2648
+ function useDropNode(targetId) {
2649
+ const driveId = useSelectedDriveId();
2650
+ const { srcId, parentId } = useDraggingNode() ?? {};
2651
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
2652
+ const params = {
2653
+ driveId,
2654
+ parentId,
2655
+ targetId,
2656
+ srcId
2657
+ };
2658
+ function handleNodeDrop(event, cb) {
2659
+ if (!isNodeDrop(params)) return;
2660
+ event.preventDefault();
2661
+ event.stopPropagation();
2662
+ cb?.();
2663
+ }
2664
+ const onDragEnter = (event) => handleNodeDrop(event);
2665
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
2666
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
2667
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
2668
+ unsetDragging();
2669
+ unsetTarget();
2670
+ moveNodeById(params).catch(console.error);
2671
+ }));
2672
+ return {
2673
+ isDropTarget,
2674
+ onDragEnter,
2675
+ onDragOver,
2676
+ onDragLeave,
2677
+ onDrop
2678
+ };
3024
2679
  }
3025
- /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
3026
- function findUuid(input) {
3027
- if (!input) return void 0;
3028
- return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
2680
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
2681
+ graphQLReactorClientEventFunctions.useValue;
2682
+ graphQLReactorClientEventFunctions.setValue;
2683
+ graphQLReactorClientEventFunctions.addEventHandler;
2684
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
2685
+ packageDiscoveryFunctions.useValue;
2686
+ packageDiscoveryFunctions.setValue;
2687
+ packageDiscoveryFunctions.addEventHandler;
2688
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
2689
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
2690
+ /** Returns the reactor client module (in-process or worker-backed) */
2691
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
2692
+ reactorClientModuleEventFunctions.setValue;
2693
+ reactorClientModuleEventFunctions.addEventHandler;
2694
+ reactorClientEventFunctions.useValue;
2695
+ reactorClientEventFunctions.setValue;
2696
+ reactorClientEventFunctions.addEventHandler;
2697
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
2698
+ const useSyncList = () => {
2699
+ return useSync()?.list() ?? [];
2700
+ };
2701
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
2702
+ revisionHistoryEventFunctions.useValue;
2703
+ /** Sets revision history visibility */
2704
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
2705
+ revisionHistoryEventFunctions.addEventHandler;
2706
+ /** Shows the revision history */
2707
+ function showRevisionHistory() {
2708
+ setRevisionHistoryVisible(true);
3029
2709
  }
3030
- function extractNodeIdFromSlug(nodeSlug) {
3031
- return findUuid(nodeSlug);
2710
+ /** Sorts nodes by name. */
2711
+ function sortNodesByName(nodes) {
2712
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
2713
+ }
2714
+ /** Returns whether a node is a file. */
2715
+ function isFileNodeKind(node) {
2716
+ if (!node) return false;
2717
+ return node.kind.toUpperCase() === "FILE";
2718
+ }
2719
+ /** Returns whether a node is a folder. */
2720
+ function isFolderNodeKind(node) {
2721
+ if (!node) return false;
2722
+ return node.kind.toUpperCase() === "FOLDER";
2723
+ }
2724
+ /** Returns the nodes in the selected drive. */
2725
+ function useNodesInSelectedDrive() {
2726
+ const [selectedDrive] = useSelectedDriveSafe();
2727
+ return selectedDrive?.state.global.nodes;
2728
+ }
2729
+ /** Returns the folder nodes in the selected drive. */
2730
+ function useFolderNodesInSelectedDrive() {
2731
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
2732
+ }
2733
+ /** Returns the selected node. */
2734
+ function useSelectedNode() {
2735
+ const selectedNodeId = useSelectedNodeId();
2736
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3032
2737
  }
3033
- /** Extracts the drive slug from a path.
3034
- * Used for extracting drive ids from drive slugs in the URL.
3035
- * Expects the path to be in the format `/d/<drive-slug>`.
3036
- */
3037
- function extractDriveSlugFromPath(path) {
3038
- const currentPath = getPathWithoutBase(path);
3039
- return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2738
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
2739
+ selectedTimelineItemEventFunctions.useValue;
2740
+ selectedTimelineItemEventFunctions.setValue;
2741
+ selectedTimelineItemEventFunctions.addEventHandler;
2742
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
2743
+ selectedTimelineRevisionEventFunctions.useValue;
2744
+ selectedTimelineRevisionEventFunctions.setValue;
2745
+ selectedTimelineRevisionEventFunctions.addEventHandler;
2746
+ const toastEventFunctions = makePHEventFunctions("toast");
2747
+ /** Returns the toast function */
2748
+ const usePHToast = toastEventFunctions.useValue;
2749
+ toastEventFunctions.setValue;
2750
+ toastEventFunctions.addEventHandler;
2751
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
2752
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
2753
+ /** Returns all of the Vetra packages loaded by the Connect instance */
2754
+ const useVetraPackages = () => {
2755
+ const packageManager = useVetraPackageManager();
2756
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
2757
+ };
2758
+ vetraPackageManagerFunctions.addEventHandler;
2759
+ function useDocumentModelModules() {
2760
+ 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);
3040
2761
  }
3041
2762
  /**
3042
- * Creates a URL string with the given pathname while preserving existing query parameters.
2763
+ * Resolves a document model module by document type, mirroring the registry's
2764
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
2765
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
2766
+ * with `version` given only an exact match is returned. The reactor resolves
2767
+ * modules the same way when a document is created, so metadata read through
2768
+ * this hook and the version a creation actually uses cannot disagree.
3043
2769
  */
3044
- function createUrlWithPreservedParams(pathname) {
3045
- const search = window.location.search;
3046
- return search ? `${pathname}${search}` : pathname;
2770
+ function useDocumentModelModuleById(id, version) {
2771
+ const documentModelModules = useDocumentModelModules();
2772
+ if (!id || !documentModelModules) return void 0;
2773
+ let latestModule;
2774
+ let latestVersion = -1;
2775
+ for (const module of documentModelModules) {
2776
+ if (module.documentModel.global.id !== id) continue;
2777
+ const moduleVersion = module.version ?? 1;
2778
+ if (version !== void 0) {
2779
+ if (moduleVersion === version) return module;
2780
+ continue;
2781
+ }
2782
+ if (moduleVersion > latestVersion) {
2783
+ latestVersion = moduleVersion;
2784
+ latestModule = module;
2785
+ }
2786
+ }
2787
+ return latestModule;
3047
2788
  }
3048
- const drivesEventFunctions = makePHEventFunctions("drives");
3049
- /** Returns all of the drives in the reactor */
3050
- const useDrives = drivesEventFunctions.useValue;
3051
- /** Sets the drives in the reactor */
3052
- const setDrives = drivesEventFunctions.setValue;
3053
- drivesEventFunctions.addEventHandler;
3054
- const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
3055
- const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
3056
- const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
3057
- selectedNodeIdEventFunctions.addEventHandler;
3058
- /** Sets the selected node (file or folder). */
3059
- function setSelectedNode(nodeOrNodeSlug) {
3060
- const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
3061
- setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
3062
- const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
3063
- if (!driveSlugFromPath) return;
3064
- if (!nodeSlug) {
3065
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
3066
- if (pathname === window.location.pathname) return;
3067
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2789
+ //#endregion
2790
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
2791
+ const normalizeDescriptors = (error) => {
2792
+ CORE_ERROR_PROPS.forEach((propName) => {
2793
+ normalizeDescriptor(error, propName);
2794
+ });
2795
+ };
2796
+ const CORE_ERROR_PROPS = [
2797
+ "name",
2798
+ "message",
2799
+ "stack",
2800
+ "cause",
2801
+ "errors"
2802
+ ];
2803
+ const normalizeDescriptor = (error, propName) => {
2804
+ const descriptor = getDescriptor(error, propName);
2805
+ if (descriptor === void 0) return;
2806
+ if (isReadonlyGetter(descriptor)) {
2807
+ setErrorProperty(error, propName, error[propName]);
3068
2808
  return;
3069
2809
  }
3070
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
3071
- if (pathname === window.location.pathname) return;
3072
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3073
- }
3074
- const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
3075
- /** Returns the selected drive id */
3076
- const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
3077
- /** Sets the selected drive id */
3078
- const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
3079
- selectedDriveIdEventFunctions.addEventHandler;
3080
- /** Returns the selected drive, or undefined if no drive is selected */
3081
- function useSelectedDriveSafe() {
3082
- const selectedDriveId = useSelectedDriveId();
3083
- const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
3084
- const [drive, dispatch] = useDispatch(selectedDrive);
3085
- if (!selectedDrive) return [void 0, void 0];
3086
- return [drive, dispatch];
2810
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
2811
+ };
2812
+ const getDescriptor = (value, propName) => {
2813
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
2814
+ if (descriptor !== void 0) return descriptor;
2815
+ const prototype = Object.getPrototypeOf(value);
2816
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
2817
+ };
2818
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
2819
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
2820
+ const setErrorProperty = (error, propName, value) => {
2821
+ setErrorDescriptor(error, propName, { value });
2822
+ };
2823
+ const setErrorDescriptor = (error, propName, descriptor) => {
2824
+ Object.defineProperty(error, propName, {
2825
+ ...descriptor,
2826
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
2827
+ enumerable: false,
2828
+ configurable: true
2829
+ });
2830
+ };
2831
+ //#endregion
2832
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
2833
+ const normalizeAggregate = (error, recurse) => {
2834
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
2835
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
2836
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
2837
+ };
2838
+ const isDefined = (error) => error !== void 0;
2839
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
2840
+ const deleteAggregateErrors = (error) => {
2841
+ delete error.errors;
2842
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
2843
+ };
2844
+ //#endregion
2845
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
2846
+ const normalizeCause = (error, recurse) => {
2847
+ if (!("cause" in error)) return;
2848
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
2849
+ if (cause === void 0) delete error.cause;
2850
+ else setErrorProperty(error, "cause", cause);
2851
+ };
2852
+ //#endregion
2853
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
2854
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
2855
+ const isInstanceOfError = (value) => {
2856
+ try {
2857
+ return value instanceof Error;
2858
+ } catch {
2859
+ return false;
2860
+ }
2861
+ };
2862
+ const hasErrorTag = (value) => {
2863
+ try {
2864
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
2865
+ } catch {
2866
+ return false;
2867
+ }
2868
+ };
2869
+ const ERROR_TAGS = new Set([
2870
+ "[object Error]",
2871
+ "[object DOMException]",
2872
+ "[object DOMError]",
2873
+ "[object Exception]"
2874
+ ]);
2875
+ //#endregion
2876
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
2877
+ function isPlainObject(value) {
2878
+ if (typeof value !== "object" || value === null) return false;
2879
+ const prototype = Object.getPrototypeOf(value);
2880
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3087
2881
  }
3088
- function setSelectedDrive(driveOrDriveSlug) {
3089
- const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
3090
- const drives = window.ph?.drives;
3091
- const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
3092
- if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
3093
- if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
3094
- deferDriveSelection(driveSlug);
3095
- return;
2882
+ //#endregion
2883
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
2884
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
2885
+ const isNonConfigurableProp = (error, propName) => {
2886
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
2887
+ return descriptor !== void 0 && !descriptor.configurable;
2888
+ };
2889
+ const isThrowingProp = (error, propName) => {
2890
+ try {
2891
+ error[propName];
2892
+ return false;
2893
+ } catch {
2894
+ return true;
2895
+ }
2896
+ };
2897
+ //#endregion
2898
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
2899
+ const setStack = (error) => {
2900
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
2901
+ };
2902
+ const getStack = (message = "", name = "Error") => {
2903
+ const { stack } = new (getErrorClass(name))(message);
2904
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
2905
+ };
2906
+ const getErrorClass = (name) => {
2907
+ const descriptor = {
2908
+ value: name,
2909
+ enumerable: false,
2910
+ writable: true,
2911
+ configurable: true
2912
+ };
2913
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
2914
+ Object.defineProperty(StackError.prototype, "name", descriptor);
2915
+ return StackError;
2916
+ };
2917
+ //#endregion
2918
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
2919
+ const copyObject = (object) => {
2920
+ const objectCopy = {};
2921
+ for (const propName of getPropsToCopy(object)) try {
2922
+ const value = object[propName];
2923
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
2924
+ Object.defineProperty(objectCopy, propName, {
2925
+ value,
2926
+ enumerable,
2927
+ configurable,
2928
+ writable
2929
+ });
2930
+ } catch {}
2931
+ return objectCopy;
2932
+ };
2933
+ const getPropsToCopy = (object) => {
2934
+ const propNames = getOwnKeys(object);
2935
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
2936
+ return propNames;
2937
+ };
2938
+ const getOwnKeys = (object) => {
2939
+ try {
2940
+ return Reflect.ownKeys(object);
2941
+ } catch {
2942
+ return [];
2943
+ }
2944
+ };
2945
+ const isInheritedProp = (object, propName) => {
2946
+ try {
2947
+ return propName in object && !Object.hasOwn(object, propName);
2948
+ } catch {
2949
+ return false;
2950
+ }
2951
+ };
2952
+ //#endregion
2953
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
2954
+ const objectifyError = (object) => {
2955
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
2956
+ const messageA = getMessage(message, objectA);
2957
+ const error = newError(name, messageA);
2958
+ if (message === messageA) assignObjectProps(error, objectA);
2959
+ Object.entries({
2960
+ name,
2961
+ stack,
2962
+ cause,
2963
+ errors
2964
+ }).forEach(([propName, propValue]) => {
2965
+ setNewErrorProperty(error, propName, propValue);
2966
+ });
2967
+ if (stack === void 0) setStack(error);
2968
+ return error;
2969
+ };
2970
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
2971
+ const safeJsonStringify = (object) => {
2972
+ try {
2973
+ return JSON.stringify(object);
2974
+ } catch {
2975
+ return safeStringify(object);
3096
2976
  }
3097
- cancelPendingDriveSelection();
3098
- setSelectedDriveId(driveId);
3099
- if (!driveId) {
3100
- const pathname = resolveUrlPathname("/");
3101
- if (pathname === window.location.pathname) return;
3102
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3103
- return;
2977
+ };
2978
+ const safeStringify = (object) => {
2979
+ try {
2980
+ return String(object);
2981
+ } catch {
2982
+ return "Invalid error";
3104
2983
  }
3105
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
3106
- if (pathname === window.location.pathname) return;
3107
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3108
- }
3109
- const DEFERRED_DRIVE_TICK_MS = 2e3;
3110
- const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
3111
- function isInitialSyncInFlight() {
3112
- const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
3113
- if (!remotes?.length) return false;
3114
- return remotes.some((remote) => {
3115
- try {
3116
- const snapshot = remote.channel.getConnectionState();
3117
- return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
3118
- } catch {
3119
- return false;
3120
- }
3121
- });
3122
- }
3123
- let pendingHandler;
3124
- let pendingTimeout;
3125
- function cancelPendingDriveSelection() {
3126
- if (pendingHandler) {
3127
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
3128
- pendingHandler = void 0;
2984
+ };
2985
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
2986
+ const MESSAGE_MAX_SIZE = 1e3;
2987
+ const newError = (name, message) => {
2988
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
2989
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
2990
+ return new Error(message);
2991
+ };
2992
+ const NATIVE_ERRORS = {
2993
+ Error,
2994
+ ReferenceError,
2995
+ TypeError,
2996
+ SyntaxError,
2997
+ RangeError,
2998
+ URIError,
2999
+ EvalError
3000
+ };
3001
+ const assignObjectProps = (error, object) => {
3002
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3003
+ };
3004
+ const setNewErrorProperty = (error, propName, propValue) => {
3005
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3006
+ };
3007
+ //#endregion
3008
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3009
+ const stringifyError = (value) => {
3010
+ try {
3011
+ const error = new Error(String(value));
3012
+ setStack(error);
3013
+ return error;
3014
+ } catch (error_) {
3015
+ return error_;
3129
3016
  }
3130
- if (pendingTimeout) {
3131
- clearTimeout(pendingTimeout);
3132
- pendingTimeout = void 0;
3017
+ };
3018
+ //#endregion
3019
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3020
+ const { toString: objectToString } = Object.prototype;
3021
+ const createError = (value) => {
3022
+ if (isErrorPlainObj(value)) return objectifyError(value);
3023
+ if (!isErrorInstance(value)) return stringifyError(value);
3024
+ if (isInvalidError(value)) return objectifyError(value);
3025
+ return value;
3026
+ };
3027
+ const isErrorPlainObj = (value) => {
3028
+ try {
3029
+ return isPlainObject(value);
3030
+ } catch {
3031
+ return false;
3133
3032
  }
3134
- }
3135
- function deferDriveSelection(driveSlug) {
3136
- cancelPendingDriveSelection();
3137
- const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
3138
- const handler = () => {
3139
- if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
3140
- cancelPendingDriveSelection();
3141
- setSelectedDrive(driveSlug);
3142
- setSelectedNode(nodeSlug);
3143
- };
3144
- pendingHandler = handler;
3145
- window.addEventListener("ph:drivesUpdated", handler);
3146
- const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
3147
- const scheduleTick = () => {
3148
- pendingTimeout = setTimeout(() => {
3149
- if (Date.now() < deadline && isInitialSyncInFlight()) {
3150
- scheduleTick();
3151
- return;
3033
+ };
3034
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3035
+ const isProxy = (value) => {
3036
+ try {
3037
+ return objectToString.call(value) === "[object Object]";
3038
+ } catch {
3039
+ return true;
3040
+ }
3041
+ };
3042
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3043
+ //#endregion
3044
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3045
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3046
+ const recurseException = (error, parents, shallow) => {
3047
+ if (parents.includes(error)) return;
3048
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3049
+ const errorA = createError(error);
3050
+ normalizeProps(errorA, recurse);
3051
+ return errorA;
3052
+ };
3053
+ const identity = (error) => error;
3054
+ const normalizeProps = (error, recurse) => {
3055
+ normalizeName(error);
3056
+ normalizeMessage(error);
3057
+ normalizeStack(error);
3058
+ normalizeCause(error, recurse);
3059
+ normalizeAggregate(error, recurse);
3060
+ normalizeDescriptors(error);
3061
+ };
3062
+ const normalizeName = (error) => {
3063
+ if (isDefinedString(error.name)) return;
3064
+ const prototypeName = Object.getPrototypeOf(error).name;
3065
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3066
+ };
3067
+ const normalizeMessage = (error) => {
3068
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3069
+ };
3070
+ const normalizeStack = (error) => {
3071
+ if (!isDefinedString(error.stack)) setStack(error);
3072
+ };
3073
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
3074
+ //#endregion
3075
+ //#region ../reactor-browser/dist/index.js
3076
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3077
+ var LZString = (function() {
3078
+ var f = String.fromCharCode;
3079
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3080
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3081
+ var baseReverseDic = {};
3082
+ function getBaseValue(alphabet, character) {
3083
+ if (!baseReverseDic[alphabet]) {
3084
+ baseReverseDic[alphabet] = {};
3085
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3086
+ }
3087
+ return baseReverseDic[alphabet][character];
3088
+ }
3089
+ var LZString = {
3090
+ compressToBase64: function(input) {
3091
+ if (input == null) return "";
3092
+ var res = LZString._compress(input, 6, function(a) {
3093
+ return keyStrBase64.charAt(a);
3094
+ });
3095
+ switch (res.length % 4) {
3096
+ default:
3097
+ case 0: return res;
3098
+ case 1: return res + "===";
3099
+ case 2: return res + "==";
3100
+ case 3: return res + "=";
3101
+ }
3102
+ },
3103
+ decompressFromBase64: function(input) {
3104
+ if (input == null) return "";
3105
+ if (input == "") return null;
3106
+ return LZString._decompress(input.length, 32, function(index) {
3107
+ return getBaseValue(keyStrBase64, input.charAt(index));
3108
+ });
3109
+ },
3110
+ compressToUTF16: function(input) {
3111
+ if (input == null) return "";
3112
+ return LZString._compress(input, 15, function(a) {
3113
+ return f(a + 32);
3114
+ }) + " ";
3115
+ },
3116
+ decompressFromUTF16: function(compressed) {
3117
+ if (compressed == null) return "";
3118
+ if (compressed == "") return null;
3119
+ return LZString._decompress(compressed.length, 16384, function(index) {
3120
+ return compressed.charCodeAt(index) - 32;
3121
+ });
3122
+ },
3123
+ compressToUint8Array: function(uncompressed) {
3124
+ var compressed = LZString.compress(uncompressed);
3125
+ var buf = new Uint8Array(compressed.length * 2);
3126
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3127
+ var current_value = compressed.charCodeAt(i);
3128
+ buf[i * 2] = current_value >>> 8;
3129
+ buf[i * 2 + 1] = current_value % 256;
3130
+ }
3131
+ return buf;
3132
+ },
3133
+ decompressFromUint8Array: function(compressed) {
3134
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3135
+ else {
3136
+ var buf = new Array(compressed.length / 2);
3137
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3138
+ var result = [];
3139
+ buf.forEach(function(c) {
3140
+ result.push(f(c));
3141
+ });
3142
+ return LZString.decompress(result.join(""));
3143
+ }
3144
+ },
3145
+ compressToEncodedURIComponent: function(input) {
3146
+ if (input == null) return "";
3147
+ return LZString._compress(input, 6, function(a) {
3148
+ return keyStrUriSafe.charAt(a);
3149
+ });
3150
+ },
3151
+ decompressFromEncodedURIComponent: function(input) {
3152
+ if (input == null) return "";
3153
+ if (input == "") return null;
3154
+ input = input.replace(/ /g, "+");
3155
+ return LZString._decompress(input.length, 32, function(index) {
3156
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
3157
+ });
3158
+ },
3159
+ compress: function(uncompressed) {
3160
+ return LZString._compress(uncompressed, 16, function(a) {
3161
+ return f(a);
3162
+ });
3163
+ },
3164
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3165
+ if (uncompressed == null) return "";
3166
+ 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;
3167
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
3168
+ context_c = uncompressed.charAt(ii);
3169
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3170
+ context_dictionary[context_c] = context_dictSize++;
3171
+ context_dictionaryToCreate[context_c] = true;
3172
+ }
3173
+ context_wc = context_w + context_c;
3174
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3175
+ else {
3176
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3177
+ if (context_w.charCodeAt(0) < 256) {
3178
+ for (i = 0; i < context_numBits; i++) {
3179
+ context_data_val = context_data_val << 1;
3180
+ if (context_data_position == bitsPerChar - 1) {
3181
+ context_data_position = 0;
3182
+ context_data.push(getCharFromInt(context_data_val));
3183
+ context_data_val = 0;
3184
+ } else context_data_position++;
3185
+ }
3186
+ value = context_w.charCodeAt(0);
3187
+ for (i = 0; i < 8; i++) {
3188
+ context_data_val = context_data_val << 1 | value & 1;
3189
+ if (context_data_position == bitsPerChar - 1) {
3190
+ context_data_position = 0;
3191
+ context_data.push(getCharFromInt(context_data_val));
3192
+ context_data_val = 0;
3193
+ } else context_data_position++;
3194
+ value = value >> 1;
3195
+ }
3196
+ } else {
3197
+ value = 1;
3198
+ for (i = 0; i < context_numBits; i++) {
3199
+ context_data_val = context_data_val << 1 | value;
3200
+ if (context_data_position == bitsPerChar - 1) {
3201
+ context_data_position = 0;
3202
+ context_data.push(getCharFromInt(context_data_val));
3203
+ context_data_val = 0;
3204
+ } else context_data_position++;
3205
+ value = 0;
3206
+ }
3207
+ value = context_w.charCodeAt(0);
3208
+ for (i = 0; i < 16; i++) {
3209
+ context_data_val = context_data_val << 1 | value & 1;
3210
+ if (context_data_position == bitsPerChar - 1) {
3211
+ context_data_position = 0;
3212
+ context_data.push(getCharFromInt(context_data_val));
3213
+ context_data_val = 0;
3214
+ } else context_data_position++;
3215
+ value = value >> 1;
3216
+ }
3217
+ }
3218
+ context_enlargeIn--;
3219
+ if (context_enlargeIn == 0) {
3220
+ context_enlargeIn = Math.pow(2, context_numBits);
3221
+ context_numBits++;
3222
+ }
3223
+ delete context_dictionaryToCreate[context_w];
3224
+ } else {
3225
+ value = context_dictionary[context_w];
3226
+ for (i = 0; i < context_numBits; i++) {
3227
+ context_data_val = context_data_val << 1 | value & 1;
3228
+ if (context_data_position == bitsPerChar - 1) {
3229
+ context_data_position = 0;
3230
+ context_data.push(getCharFromInt(context_data_val));
3231
+ context_data_val = 0;
3232
+ } else context_data_position++;
3233
+ value = value >> 1;
3234
+ }
3235
+ }
3236
+ context_enlargeIn--;
3237
+ if (context_enlargeIn == 0) {
3238
+ context_enlargeIn = Math.pow(2, context_numBits);
3239
+ context_numBits++;
3240
+ }
3241
+ context_dictionary[context_wc] = context_dictSize++;
3242
+ context_w = String(context_c);
3243
+ }
3244
+ }
3245
+ if (context_w !== "") {
3246
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3247
+ if (context_w.charCodeAt(0) < 256) {
3248
+ for (i = 0; i < context_numBits; i++) {
3249
+ context_data_val = context_data_val << 1;
3250
+ if (context_data_position == bitsPerChar - 1) {
3251
+ context_data_position = 0;
3252
+ context_data.push(getCharFromInt(context_data_val));
3253
+ context_data_val = 0;
3254
+ } else context_data_position++;
3255
+ }
3256
+ value = context_w.charCodeAt(0);
3257
+ for (i = 0; i < 8; i++) {
3258
+ context_data_val = context_data_val << 1 | value & 1;
3259
+ if (context_data_position == bitsPerChar - 1) {
3260
+ context_data_position = 0;
3261
+ context_data.push(getCharFromInt(context_data_val));
3262
+ context_data_val = 0;
3263
+ } else context_data_position++;
3264
+ value = value >> 1;
3265
+ }
3266
+ } else {
3267
+ value = 1;
3268
+ for (i = 0; i < context_numBits; i++) {
3269
+ context_data_val = context_data_val << 1 | value;
3270
+ if (context_data_position == bitsPerChar - 1) {
3271
+ context_data_position = 0;
3272
+ context_data.push(getCharFromInt(context_data_val));
3273
+ context_data_val = 0;
3274
+ } else context_data_position++;
3275
+ value = 0;
3276
+ }
3277
+ value = context_w.charCodeAt(0);
3278
+ for (i = 0; i < 16; i++) {
3279
+ context_data_val = context_data_val << 1 | value & 1;
3280
+ if (context_data_position == bitsPerChar - 1) {
3281
+ context_data_position = 0;
3282
+ context_data.push(getCharFromInt(context_data_val));
3283
+ context_data_val = 0;
3284
+ } else context_data_position++;
3285
+ value = value >> 1;
3286
+ }
3287
+ }
3288
+ context_enlargeIn--;
3289
+ if (context_enlargeIn == 0) {
3290
+ context_enlargeIn = Math.pow(2, context_numBits);
3291
+ context_numBits++;
3292
+ }
3293
+ delete context_dictionaryToCreate[context_w];
3294
+ } else {
3295
+ value = context_dictionary[context_w];
3296
+ for (i = 0; i < context_numBits; i++) {
3297
+ context_data_val = context_data_val << 1 | value & 1;
3298
+ if (context_data_position == bitsPerChar - 1) {
3299
+ context_data_position = 0;
3300
+ context_data.push(getCharFromInt(context_data_val));
3301
+ context_data_val = 0;
3302
+ } else context_data_position++;
3303
+ value = value >> 1;
3304
+ }
3305
+ }
3306
+ context_enlargeIn--;
3307
+ if (context_enlargeIn == 0) {
3308
+ context_enlargeIn = Math.pow(2, context_numBits);
3309
+ context_numBits++;
3310
+ }
3311
+ }
3312
+ value = 2;
3313
+ for (i = 0; i < context_numBits; i++) {
3314
+ context_data_val = context_data_val << 1 | value & 1;
3315
+ if (context_data_position == bitsPerChar - 1) {
3316
+ context_data_position = 0;
3317
+ context_data.push(getCharFromInt(context_data_val));
3318
+ context_data_val = 0;
3319
+ } else context_data_position++;
3320
+ value = value >> 1;
3321
+ }
3322
+ while (true) {
3323
+ context_data_val = context_data_val << 1;
3324
+ if (context_data_position == bitsPerChar - 1) {
3325
+ context_data.push(getCharFromInt(context_data_val));
3326
+ break;
3327
+ } else context_data_position++;
3328
+ }
3329
+ return context_data.join("");
3330
+ },
3331
+ decompress: function(compressed) {
3332
+ if (compressed == null) return "";
3333
+ if (compressed == "") return null;
3334
+ return LZString._decompress(compressed.length, 32768, function(index) {
3335
+ return compressed.charCodeAt(index);
3336
+ });
3337
+ },
3338
+ _decompress: function(length, resetValue, getNextValue) {
3339
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3340
+ val: getNextValue(0),
3341
+ position: resetValue,
3342
+ index: 1
3343
+ };
3344
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
3345
+ bits = 0;
3346
+ maxpower = Math.pow(2, 2);
3347
+ power = 1;
3348
+ while (power != maxpower) {
3349
+ resb = data.val & data.position;
3350
+ data.position >>= 1;
3351
+ if (data.position == 0) {
3352
+ data.position = resetValue;
3353
+ data.val = getNextValue(data.index++);
3354
+ }
3355
+ bits |= (resb > 0 ? 1 : 0) * power;
3356
+ power <<= 1;
3357
+ }
3358
+ switch (bits) {
3359
+ case 0:
3360
+ bits = 0;
3361
+ maxpower = Math.pow(2, 8);
3362
+ power = 1;
3363
+ while (power != maxpower) {
3364
+ resb = data.val & data.position;
3365
+ data.position >>= 1;
3366
+ if (data.position == 0) {
3367
+ data.position = resetValue;
3368
+ data.val = getNextValue(data.index++);
3369
+ }
3370
+ bits |= (resb > 0 ? 1 : 0) * power;
3371
+ power <<= 1;
3372
+ }
3373
+ c = f(bits);
3374
+ break;
3375
+ case 1:
3376
+ bits = 0;
3377
+ maxpower = Math.pow(2, 16);
3378
+ power = 1;
3379
+ while (power != maxpower) {
3380
+ resb = data.val & data.position;
3381
+ data.position >>= 1;
3382
+ if (data.position == 0) {
3383
+ data.position = resetValue;
3384
+ data.val = getNextValue(data.index++);
3385
+ }
3386
+ bits |= (resb > 0 ? 1 : 0) * power;
3387
+ power <<= 1;
3388
+ }
3389
+ c = f(bits);
3390
+ break;
3391
+ case 2: return "";
3392
+ }
3393
+ dictionary[3] = c;
3394
+ w = c;
3395
+ result.push(c);
3396
+ while (true) {
3397
+ if (data.index > length) return "";
3398
+ bits = 0;
3399
+ maxpower = Math.pow(2, numBits);
3400
+ power = 1;
3401
+ while (power != maxpower) {
3402
+ resb = data.val & data.position;
3403
+ data.position >>= 1;
3404
+ if (data.position == 0) {
3405
+ data.position = resetValue;
3406
+ data.val = getNextValue(data.index++);
3407
+ }
3408
+ bits |= (resb > 0 ? 1 : 0) * power;
3409
+ power <<= 1;
3410
+ }
3411
+ switch (c = bits) {
3412
+ case 0:
3413
+ bits = 0;
3414
+ maxpower = Math.pow(2, 8);
3415
+ power = 1;
3416
+ while (power != maxpower) {
3417
+ resb = data.val & data.position;
3418
+ data.position >>= 1;
3419
+ if (data.position == 0) {
3420
+ data.position = resetValue;
3421
+ data.val = getNextValue(data.index++);
3422
+ }
3423
+ bits |= (resb > 0 ? 1 : 0) * power;
3424
+ power <<= 1;
3425
+ }
3426
+ dictionary[dictSize++] = f(bits);
3427
+ c = dictSize - 1;
3428
+ enlargeIn--;
3429
+ break;
3430
+ case 1:
3431
+ bits = 0;
3432
+ maxpower = Math.pow(2, 16);
3433
+ power = 1;
3434
+ while (power != maxpower) {
3435
+ resb = data.val & data.position;
3436
+ data.position >>= 1;
3437
+ if (data.position == 0) {
3438
+ data.position = resetValue;
3439
+ data.val = getNextValue(data.index++);
3440
+ }
3441
+ bits |= (resb > 0 ? 1 : 0) * power;
3442
+ power <<= 1;
3443
+ }
3444
+ dictionary[dictSize++] = f(bits);
3445
+ c = dictSize - 1;
3446
+ enlargeIn--;
3447
+ break;
3448
+ case 2: return result.join("");
3449
+ }
3450
+ if (enlargeIn == 0) {
3451
+ enlargeIn = Math.pow(2, numBits);
3452
+ numBits++;
3453
+ }
3454
+ if (dictionary[c]) entry = dictionary[c];
3455
+ else if (c === dictSize) entry = w + w.charAt(0);
3456
+ else return null;
3457
+ result.push(entry);
3458
+ dictionary[dictSize++] = w + entry.charAt(0);
3459
+ enlargeIn--;
3460
+ w = entry;
3461
+ if (enlargeIn == 0) {
3462
+ enlargeIn = Math.pow(2, numBits);
3463
+ numBits++;
3464
+ }
3465
+ }
3152
3466
  }
3153
- cancelPendingDriveSelection();
3154
- const pathname = resolveUrlPathname("/");
3155
- if (pathname === window.location.pathname) return;
3156
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3157
- }, DEFERRED_DRIVE_TICK_MS);
3158
- };
3159
- scheduleTick();
3160
- }
3161
- function useDropTarget() {
3162
- const [isDropTarget, setIsDropTarget] = useState(false);
3163
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3164
- const targetSetter = n$1(() => setIsDropTarget(true), {
3165
- triggerAt: "start",
3166
- minQuietPeriodMs: 100
3467
+ };
3468
+ return LZString;
3469
+ })();
3470
+ if (typeof define === "function" && define.amd) define(function() {
3471
+ return LZString;
3167
3472
  });
3168
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3169
- triggerAt: "start",
3170
- minQuietPeriodMs: 100
3473
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3474
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3475
+ return LZString;
3171
3476
  });
3172
- function setTarget() {
3173
- if (!isDragAndDropEnabled) return;
3174
- targetUnsetter.cancel();
3175
- targetSetter.call();
3176
- }
3177
- function unsetTarget() {
3178
- if (!isDragAndDropEnabled) return;
3179
- targetSetter.cancel();
3180
- targetUnsetter.call();
3181
- }
3182
- return {
3183
- isDropTarget,
3184
- setTarget,
3185
- unsetTarget
3186
- };
3187
- }
3188
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3189
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3190
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3191
- draggingNodeEventFunctions.addEventHandler;
3192
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3193
- reducer: (_, newNode) => newNode,
3194
- triggerAt: "start",
3195
- minQuietPeriodMs: 100
3196
- });
3197
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3198
- triggerAt: "start",
3199
- minQuietPeriodMs: 100
3200
- });
3201
- function setDragging(node) {
3202
- draggingNodeUnsetter.cancel();
3203
- draggingNodeSetter.call(node);
3204
- }
3205
- function unsetDragging() {
3206
- draggingNodeSetter.cancel();
3207
- draggingNodeUnsetter.call();
3208
- }
3209
- 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));
3210
- function useDragNode(args) {
3211
- const { srcId, parentId } = args;
3212
- const driveId = useSelectedDriveId();
3213
- const draggingNodeId = useDraggingNode()?.srcId;
3214
- const params = {
3215
- driveId,
3216
- srcId,
3217
- parentId
3218
- };
3219
- const draggable = isNodeDrag(params);
3220
- const isDragging = t$4({
3221
- srcId,
3222
- draggingNodeId
3223
- }, [
3224
- () => draggable,
3225
- ({ srcId }) => e$2(srcId),
3226
- ({ draggingNodeId }) => e$2(draggingNodeId),
3227
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3228
- ]);
3229
- const onDragStart = () => {
3230
- if (!draggable) return;
3231
- setDragging(params);
3232
- };
3233
- const onDragEnd = () => {
3234
- if (!draggable) return;
3235
- unsetDragging();
3236
- };
3237
- return {
3238
- isDragging,
3239
- draggable,
3240
- onDragStart,
3241
- onDragEnd
3242
- };
3243
- }
3244
- 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));
3245
- function useDropNode(targetId) {
3246
- const driveId = useSelectedDriveId();
3247
- const { srcId, parentId } = useDraggingNode() ?? {};
3248
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3249
- const params = {
3250
- driveId,
3251
- parentId,
3252
- targetId,
3253
- srcId
3254
- };
3255
- function handleNodeDrop(event, cb) {
3256
- if (!isNodeDrop(params)) return;
3257
- event.preventDefault();
3258
- event.stopPropagation();
3259
- cb?.();
3260
- }
3261
- const onDragEnter = (event) => handleNodeDrop(event);
3262
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3263
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3264
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3265
- unsetDragging();
3266
- unsetTarget();
3267
- moveNodeById(params).catch(console.error);
3268
- }));
3269
- return {
3270
- isDropTarget,
3271
- onDragEnter,
3272
- onDragOver,
3273
- onDragLeave,
3274
- onDrop
3275
- };
3276
- }
3277
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3278
- graphQLReactorClientEventFunctions.useValue;
3279
- graphQLReactorClientEventFunctions.setValue;
3280
- graphQLReactorClientEventFunctions.addEventHandler;
3281
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3282
- packageDiscoveryFunctions.useValue;
3283
- packageDiscoveryFunctions.setValue;
3284
- packageDiscoveryFunctions.addEventHandler;
3285
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3286
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3287
- /** Returns the reactor client module (in-process or worker-backed) */
3288
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3289
- reactorClientModuleEventFunctions.setValue;
3290
- reactorClientModuleEventFunctions.addEventHandler;
3291
- reactorClientEventFunctions.useValue;
3292
- reactorClientEventFunctions.setValue;
3293
- reactorClientEventFunctions.addEventHandler;
3294
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3295
- const useSyncList = () => {
3296
- return useSync()?.list() ?? [];
3297
- };
3298
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3299
- revisionHistoryEventFunctions.useValue;
3300
- /** Sets revision history visibility */
3301
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3302
- revisionHistoryEventFunctions.addEventHandler;
3303
- /** Shows the revision history */
3304
- function showRevisionHistory() {
3305
- setRevisionHistoryVisible(true);
3306
- }
3307
- /** Sorts nodes by name. */
3308
- function sortNodesByName(nodes) {
3309
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3310
- }
3311
- /** Returns whether a node is a file. */
3312
- function isFileNodeKind(node) {
3313
- if (!node) return false;
3314
- return node.kind.toUpperCase() === "FILE";
3315
- }
3316
- /** Returns whether a node is a folder. */
3317
- function isFolderNodeKind(node) {
3318
- if (!node) return false;
3319
- return node.kind.toUpperCase() === "FOLDER";
3320
- }
3321
- /** Returns the nodes in the selected drive. */
3322
- function useNodesInSelectedDrive() {
3323
- const [selectedDrive] = useSelectedDriveSafe();
3324
- return selectedDrive?.state.global.nodes;
3325
- }
3326
- /** Returns the folder nodes in the selected drive. */
3327
- function useFolderNodesInSelectedDrive() {
3328
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3329
- }
3330
- /** Returns the selected node. */
3331
- function useSelectedNode() {
3332
- const selectedNodeId = useSelectedNodeId();
3333
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3334
- }
3335
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3336
- selectedTimelineItemEventFunctions.useValue;
3337
- selectedTimelineItemEventFunctions.setValue;
3338
- selectedTimelineItemEventFunctions.addEventHandler;
3339
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3340
- selectedTimelineRevisionEventFunctions.useValue;
3341
- selectedTimelineRevisionEventFunctions.setValue;
3342
- selectedTimelineRevisionEventFunctions.addEventHandler;
3343
- const toastEventFunctions = makePHEventFunctions("toast");
3344
- /** Returns the toast function */
3345
- const usePHToast = toastEventFunctions.useValue;
3346
- toastEventFunctions.setValue;
3347
- toastEventFunctions.addEventHandler;
3348
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3349
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3350
- /** Returns all of the Vetra packages loaded by the Connect instance */
3351
- const useVetraPackages = () => {
3352
- const packageManager = useVetraPackageManager();
3353
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3354
- };
3355
- vetraPackageManagerFunctions.addEventHandler;
3356
- function useDocumentModelModules() {
3357
- 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);
3358
- }
3359
- function useDocumentModelModuleById(id) {
3360
- return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3361
- }
3477
+ })))(), 1);
3478
+ /** Document types that represent a "drive": a container of nodes. */
3479
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
3362
3480
  function useAllowedDocumentModelModules() {
3363
3481
  const documentModelModules = useDocumentModelModules();
3364
3482
  const allowedDocumentTypes = useAllowedDocumentTypes();
@@ -3543,7 +3661,7 @@ function useNodeActions() {
3543
3661
  }
3544
3662
  async function onAddFolder(name, parent) {
3545
3663
  if (!selectedDriveId) return;
3546
- return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3664
+ return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3547
3665
  }
3548
3666
  async function onRenameNode(newName, node) {
3549
3667
  if (!selectedDriveId) return;
@@ -3858,6 +3976,6 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
3858
3976
  createDebouncedRefreshReactorData();
3859
3977
  createDebouncedRefreshReactorDataClient();
3860
3978
  //#endregion
3861
- 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 };
3979
+ export { usePHToast as A, setSelectedNode as C, useDisabledEditors as D, showRevisionHistory as E, t$2 as F, t$5 as I, useDocumentById as L, useSelectedDriveSafe as M, e$1 as N, useDragNode as O, e$4 as P, setSelectedDrive as S, showDeleteNodeModal as T, useTheme as _, useEditorModules as a, isFileNodeKind as b, useNodeActions as c, useNodesInSelectedDriveOrFolder as d, useSelectedDocumentOfType as f, useSetPHDocumentEditorConfig as g, useSetPHAppConfig as h, useDownloadDocument as i, useSelectedDriveId as j, useDropNode as k, useNodeById as l, useSelectedNodePath as m, preloadEditorModule as n, useEditorModulesForDocumentType as o, useSelectedDocumentSafe as p, useAllowedDocumentModelModules as r, useGetSwitchboardLink as s, getSyncStatusSync as t, useNodeParentFolderById as u, useUserPermissions as v, showCreateDocumentModal as w, isFolderNodeKind as x, addFolder$1 as y };
3862
3980
 
3863
- //# sourceMappingURL=dist-B9dsmZOQ.mjs.map
3981
+ //# sourceMappingURL=dist-Ch3Oiwow.mjs.map