@powerhousedao/reactor-browser 6.2.3-staging.0 → 6.3.0-dev.1

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 (87) hide show
  1. package/dist/{attachment-service-But1Xljo.d.ts → attachment-service-B-AmTrs2.d.ts} +605 -56
  2. package/dist/attachment-service-B-AmTrs2.d.ts.map +1 -0
  3. package/dist/auth-DRbzRdeC.d.ts +32 -0
  4. package/dist/auth-DRbzRdeC.d.ts.map +1 -0
  5. package/dist/{client-BiJAJ9dW.js → client-BFnMV-EO.js} +39 -22
  6. package/dist/client-BFnMV-EO.js.map +1 -0
  7. package/dist/{client-CngU4mtn.d.ts → client-BP0hXjqq.d.ts} +3 -2
  8. package/dist/client-BP0hXjqq.d.ts.map +1 -0
  9. package/dist/client-wwavHFfs.js +135 -0
  10. package/dist/client-wwavHFfs.js.map +1 -0
  11. package/dist/{dispatch-qRXS70fh.js → dispatch-Cylwl2Dk.js} +363 -44
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/{document-by-id-B_8DA4yZ.js → document-by-id-DdvqanGR.js} +2 -2
  14. package/dist/{document-by-id-B_8DA4yZ.js.map → document-by-id-DdvqanGR.js.map} +1 -1
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/{document-operations-Bt-1-ThH.js → document-operations-DRMMwmGZ.js} +2160 -181
  18. package/dist/document-operations-DRMMwmGZ.js.map +1 -0
  19. package/dist/global-iARBhxNI.d.ts +612 -0
  20. package/dist/global-iARBhxNI.d.ts.map +1 -0
  21. package/dist/{index-BABMK8cO.d.ts → index-CNS_9THu.d.ts} +14 -4
  22. package/dist/index-CNS_9THu.d.ts.map +1 -0
  23. package/dist/index.d.ts +560 -79
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +790 -317
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  28. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  29. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  30. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  31. package/dist/{relational-ChC_AWAK.js → relational-DZuyKp2y.js} +65 -5
  32. package/dist/relational-DZuyKp2y.js.map +1 -0
  33. package/dist/{renown-C9pYZRqf.js → renown-B3MUaiq7.js} +56 -25
  34. package/dist/renown-B3MUaiq7.js.map +1 -0
  35. package/dist/renown-CBoTdGrg.js +394 -0
  36. package/dist/renown-CBoTdGrg.js.map +1 -0
  37. package/dist/{client-VV9M73s_.js → schema-B5lftDPf.js} +295 -195
  38. package/dist/schema-B5lftDPf.js.map +1 -0
  39. package/dist/{types-B7-_l_wE.d.ts → schema-C6ECceaN.d.ts} +272 -82
  40. package/dist/schema-C6ECceaN.d.ts.map +1 -0
  41. package/dist/src/ai/index.d.ts +269 -24
  42. package/dist/src/ai/index.d.ts.map +1 -1
  43. package/dist/src/ai/index.js +1028 -168
  44. package/dist/src/ai/index.js.map +1 -1
  45. package/dist/src/analytics/index.js +3 -3
  46. package/dist/src/graphql/client.d.ts +2 -2
  47. package/dist/src/graphql/client.js +1 -1
  48. package/dist/src/graphql-client/entry.d.ts +6 -4
  49. package/dist/src/graphql-client/entry.js +4 -4
  50. package/dist/src/relational/index.d.ts +8 -1
  51. package/dist/src/relational/index.d.ts.map +1 -1
  52. package/dist/src/relational/index.js +1 -1
  53. package/dist/src/renown/index.d.ts +2 -2
  54. package/dist/src/renown/index.js +3 -3
  55. package/dist/src/rpc/index.d.ts +201 -144
  56. package/dist/src/rpc/index.d.ts.map +1 -1
  57. package/dist/src/rpc/index.js +562 -634
  58. package/dist/src/rpc/index.js.map +1 -1
  59. package/dist/switchboard-directory-vH6qtkh-.js +435 -0
  60. package/dist/switchboard-directory-vH6qtkh-.js.map +1 -0
  61. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  62. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  63. package/dist/types-BWx6FPO4.d.ts +63 -0
  64. package/dist/types-BWx6FPO4.d.ts.map +1 -0
  65. package/package.json +19 -17
  66. package/dist/attachment-service-But1Xljo.d.ts.map +0 -1
  67. package/dist/client-BiJAJ9dW.js.map +0 -1
  68. package/dist/client-CngU4mtn.d.ts.map +0 -1
  69. package/dist/client-VV9M73s_.js.map +0 -1
  70. package/dist/dispatch-qRXS70fh.js.map +0 -1
  71. package/dist/document-model-modules-D6I-UUXq.js +0 -386
  72. package/dist/document-model-modules-D6I-UUXq.js.map +0 -1
  73. package/dist/document-operations-Bt-1-ThH.js.map +0 -1
  74. package/dist/global-fql2bmb0.d.ts +0 -438
  75. package/dist/global-fql2bmb0.d.ts.map +0 -1
  76. package/dist/index-BABMK8cO.d.ts.map +0 -1
  77. package/dist/inspector-proxy-DCowaeeH.d.ts +0 -264
  78. package/dist/inspector-proxy-DCowaeeH.d.ts.map +0 -1
  79. package/dist/make-ph-event-functions-FzpvQtj6.js +0 -53
  80. package/dist/make-ph-event-functions-FzpvQtj6.js.map +0 -1
  81. package/dist/relational-ChC_AWAK.js.map +0 -1
  82. package/dist/renown-C9pYZRqf.js.map +0 -1
  83. package/dist/renown-Def5iO8k.js +0 -97
  84. package/dist/renown-Def5iO8k.js.map +0 -1
  85. package/dist/switchboard-CFyD_5_e.js +0 -323
  86. package/dist/switchboard-CFyD_5_e.js.map +0 -1
  87. package/dist/types-B7-_l_wE.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,27 +1,25 @@
1
- import { a as useDocumentCache, b as IDLE_REFETCH_STATE, c as useGetDocument, d as DocumentCache, f as IDLE_OPERATIONS_ENTRY, h as readPromiseState, i as useDocument, l as useGetDocumentAsync, m as isOperationCache, n as addDocumentCacheEventHandler, o as useDocumentSafe, p as addPromiseState, r as setDocumentCache, s as useDocuments, t as useDispatch, u as useGetDocuments, x as dispatchActions, y as DocumentRefetcher } from "./dispatch-qRXS70fh.js";
2
- import { A as findUuid, B as makeAuthMiddleware, C as extractDriveIdFromPath, D as extractNodeIdFromSlug, E as extractNodeIdFromPath, F as DocumentModelNotFoundError, I as DocumentTypeMismatchError, L as NoSelectedDocumentError, M as makeDriveUrlComponent, N as makeNodeSlug, O as extractNodeSlugFromPath, P as resolveUrlPathname, R as UnsupportedDocumentTypeError, S as createUrlWithPreservedParams, T as extractDriveSlugFromPath, _ as setSelectedNode, a as useVetraPackageManager, b as setDrives, c as addSetSelectedDriveOnPopStateEventHandler, d as useSelectedDrive, f as useSelectedDriveId, g as addSetSelectedNodeOnPopStateEventHandler, h as addSelectedNodeIdEventHandler, i as setVetraPackageManager, j as getPathWithoutBase, k as findDerivedId, l as setSelectedDrive, m as addResetSelectedNodeEventHandler, n as useDocumentModelModules, o as useVetraPackages, p as useSelectedDriveSafe, r as addVetraPackageManagerEventHandler, s as addSelectedDriveIdEventHandler, t as useDocumentModelModuleById, u as setSelectedDriveId, w as extractDriveIdFromSlug, x as useDrives, y as addDrivesEventHandler, z as ambientRenownTokenProvider } from "./document-model-modules-D6I-UUXq.js";
3
- import { t as makePHEventFunctions } from "./make-ph-event-functions-FzpvQtj6.js";
4
- import { $ as addDefaultDrivesUrlEventHandler, $n as useIsAddLocalDrivesEnabled, $r as isAuthRefusalClose, $t as setEnabledEditors, A as useReactorClientModule, Ai as fetchDocumentOperations, An as setRenownUrl, Ar as useSentryRelease, At as addRenownAdaptersEventHandler, B as useDragNode, Bi as addModalEventHandler, Bn as setWarnOutdatedApp, Br as phAppConfigHooks, Bt as addSwitchboardUrlEventHandler, C as addReactorClientModuleEventHandler, Ci as addDocument, Cn as setIsRelationalProcessorsEnabled, Cr as useRenownChainId, Ct as addIsExternalRelationalProcessorsEnabledEventHandler, D as useModelRegistry, Di as deleteNode, Dn as setRenownAdapters, Dr as useRouterBasename, Dt as addIsSentryTracingEnabledEventHandler, E as useDatabase, Ei as copyNode$1, En as setLogLevel, Er as useRequiresHardRefresh, Et as addIsRelationalProcessorsEnabledEventHandler, F as usePackageDiscoveryService, Fi as renameNode, Fn as setSentryRelease, Fr as useWarnOutdatedApp, Ft as addRouterBasenameEventHandler, G as useFeatures, Gi as showPHModal, Gn as useDefaultDrivesUrl, Gr as setIsDragAndDropEnabled, Gt as phGlobalConfigSetters, H as useDropTarget, Hi as setPHModal, Hn as useAnalyticsDatabaseName, Hr as phDocumentEditorConfigHooks, Ht as addVersionEventHandler, I as addGraphQLReactorClientEventHandler, Ii as setPreferredEditorOnNode, In as setStudioMode, Ir as addAllowedDocumentTypesEventHandler, It as addSentryDsnEventHandler, J as useAttachmentService, Jn as useEnabledEditors, Jr as useIsDragAndDropEnabled, Jt as setBasePath, K as addAttachmentServiceEventHandler, Ki as usePHModal, Kn as useDisabledEditors, Kr as setIsExternalControlsEnabled, Kt as setAllowList, L as setGraphQLReactorClient, Li as upgradeDocument, Ln as setSwitchboardUrl, Lr as addIsDragAndDropEnabledEventHandler, Lt as addSentryEnvEventHandler, M as useSyncList, Mi as loadFile, Mn as setRouterBasename, Mr as useSwitchboardUrl, Mt as addRenownNetworkIdEventHandler, N as addPackageDiscoveryServiceEventHandler, Ni as moveNode$1, Nn as setSentryDsn, Nr as useVersion, Nt as addRenownUrlEventHandler, O as usePGlite, Oi as exportFile, On as setRenownChainId, Or as useSentryDsn, Ot as addLocalDrivesEnabledEventHandler, P as setPackageDiscoveryService, Pi as renameDriveNode, Pn as setSentryEnv, Pr as useVersionCheckInterval, Pt as addRequiresHardRefreshEventHandler, Q as addCliVersionEventHandler, Qn as useIsAddDriveEnabled, Qr as viewFilterInputFromViewFilter, Qt as setDrivesPreserveStrategy, R as useGraphQLReactorClient, Ri as getUserPermissions, Rn as setVersion, Rr as addIsExternalControlsEnabledEventHandler, Rt as addSentryReleaseEventHandler, S as addReactorClientEventHandler, Si as screamingSnakeToCamel, Sn as setIsPublicDrivesEnabled, Sr as useRenownAdapters, St as addIsExternalProcessorsEnabledEventHandler, T as setReactorClientModule, Ti as addFolder, Tn as setLocalDrivesEnabled, Tr as useRenownUrl, Tt as addIsPublicDrivesEnabledEventHandler, U as addFeaturesEventHandler, Ui as showCreateDocumentModal, Un as useBasePath, Ur as phDocumentEditorConfigSetters, Ut as addWarnOutdatedAppEventHandler, V as useDropNode, Vi as closePHModal, Vn as useAllowList, Vr as phAppConfigSetters, Vt as addVersionCheckIntervalEventHandler, W as setFeatures, Wi as showDeleteNodeModal, Wn as useCliVersion, Wr as setAllowedDocumentTypes, Wt as phGlobalConfigHooks, X as addAnalyticsDatabaseNameEventHandler, Xn as useGaTrackingId, Xr as GraphQLReactorClient, Xt as setDefaultDrivesUrl, Y as addAllowListEventHandler, Yn as useFileUploadOperationsChunkSize, Yr as useIsExternalControlsEnabled, Yt as setCliVersion, Z as addBasePathEventHandler, Zn as useIsAddCloudDrivesEnabled, Zr as isGraphQLReactorClient, Zt as setDisabledEditors, _ as addRevisionHistoryVisibleEventHandler, _i as ConflictError, _n as setIsEditorReadModeEnabled, _r as useIsPublicDrivesEnabled, _t as addIsDocumentModelSelectionSettingsEnabledEventHandler, a as addPHEventHandlers, ai as subgraphUrlFromGraphqlUrl, an as setIsAddPublicDrivesEnabled, ar as useIsDeleteCloudDrivesEnabled, at as addIsAddCloudDrivesEnabledEventHandler, b as showRevisionHistory, bi as extractRevisionMap, bn as setIsExternalRelationalProcessorsEnabled, br as useLocalDrivesEnabled, bt as addIsEditorReadModeEnabledEventHandler, c as addToastEventHandler, ci as resolveDocumentModelModule, cn as setIsAnalyticsExternalProcessorsEnabled, cr as useIsDiffAnalyticsEnabled, ct as addIsAddPublicDrivesEnabledEventHandler, d as addSelectedTimelineRevisionEventHandler, di as stampAction, dn as setIsDeleteLocalDrivesEnabled, dr as useIsEditorDebugModeEnabled, dt as addIsAnalyticsExternalProcessorsEnabledEventHandler, ei as makeAuthConnectionParams, en as setFileUploadOperationsChunkSize, er as useIsAddPublicDrivesEnabled, et as addDisabledEditorsEventHandler, f as setSelectedTimelineRevision, fi as MutateDocumentWithOperationsDocument, fn as setIsDeletePublicDrivesEnabled, fr as useIsEditorReadModeEnabled, ft as addIsCloudDrivesEnabledEventHandler, g as useSelectedTimelineItem, gi as revisionMapFromRevisionsList, gn as setIsEditorDebugModeEnabled, gr as useIsLocalDrivesEnabled, gt as addIsDiffAnalyticsEnabledEventHandler, h as setSelectedTimelineItem, hi as phDocumentFromMutation, hn as setIsDriveAnalyticsEnabled, hr as useIsExternalRelationalProcessorsEnabled, ht as addIsDeletePublicDrivesEnabledEventHandler, i as useSwitchboardClient, ii as describeGraphQLDocument, in as setIsAddLocalDrivesEnabled, ir as useIsCloudDrivesEnabled, it as addGaTrackingIdEventHandler, j as useSync, ji as getDocumentExtension, jn as setRequiresHardRefresh, jr as useStudioMode, jt as addRenownChainIdEventHandler, k as useReactorClient, ki as extractInitialState, kn as setRenownNetworkId, kr as useSentryEnv, kt as addLogLevelEventHandler, l as setPHToast, li as prepareSignedActions, ln as setIsCloudDrivesEnabled, lr as useIsDocumentModelSelectionSettingsEnabled, lt as addIsAnalyticsDatabaseWorkerEnabledEventHandler, m as addSelectedTimelineItemEventHandler, mi as phDocumentFromGetDocument, mn as setIsDocumentModelSelectionSettingsEnabled, mr as useIsExternalProcessorsEnabled, mt as addIsDeleteLocalDrivesEnabledEventHandler, n as GraphQLReactorProvider, ni as subscriptionsUrlFromGraphqlUrl, nn as setIsAddCloudDrivesEnabled, nr as useIsAnalyticsEnabled, nt as addEnabledEditorsEventHandler, o as callEventHandlerRegisterFunctions, oi as StaticPackageManager, on as setIsAnalyticsDatabaseWorkerEnabled, or as useIsDeleteLocalDrivesEnabled, ot as addIsAddDriveEnabledEventHandler, p as useSelectedTimelineRevision, pi as ReactorOperationFieldsFragmentDoc, pn as setIsDiffAnalyticsEnabled, pr as useIsExternalPackagesEnabled, pt as addIsDeleteCloudDrivesEnabledEventHandler, q as setAttachmentService, qn as useDrivesPreserveStrategy, qr as useAllowedDocumentTypes, qt as setAnalyticsDatabaseName, r as ensurePHEventHandlers, ri as SubgraphSdkRegistry, rn as setIsAddDriveEnabled, rr as useIsAnalyticsExternalProcessorsEnabled, rt as addFileUploadOperationsChunkSizeEventHandler, s as commonGlobalEventHandlerFunctions, si as packageFromDocumentModels, sn as setIsAnalyticsEnabled, sr as useIsDeletePublicDrivesEnabled, st as addIsAddLocalDrivesEnabledEventHandler, t as useDocumentOperations, ti as startDocumentChangesSubscription, tn as setGaTrackingId, tr as useIsAnalyticsDatabaseWorkerEnabled, tt as addDrivesPreserveStrategyEventHandler, u as usePHToast, ui as signStampedAction, un as setIsDeleteCloudDrivesEnabled, ur as useIsDriveAnalyticsEnabled, ut as addIsAnalyticsEnabledEventHandler, v as hideRevisionHistory, vi as buildPulledDocument, vn as setIsExternalPackagesEnabled, vr as useIsRelationalProcessorsEnabled, vt as addIsDriveAnalyticsEnabledEventHandler, w as setReactorClient, wi as addFileWithProgress, wn as setIsSentryTracingEnabled, wr as useRenownNetworkId, wt as addIsLocalDrivesEnabledEventHandler, x as useRevisionHistoryVisible, xi as hasRevisionConflict, xn as setIsLocalDrivesEnabled, xr as useLogLevel, xt as addIsExternalPackagesEnabledEventHandler, y as setRevisionHistoryVisible, yi as convertRemoteOperations, yn as setIsExternalProcessorsEnabled, yr as useIsSentryTracingEnabled, yt as addIsEditorDebugModeEnabledEventHandler, z as addDraggingNodeEventHandler, zi as isDocumentTypeSupported, zn as setVersionCheckInterval, zr as isExternalControlsEnabledEventFunctions, zt as addStudioModeEventHandler } from "./document-operations-Bt-1-ThH.js";
1
+ import { a as createPHStore, c as getPHStore, d as subscribePHStore, f as usePHStore, i as bindPHStoreToWindow, l as getPHStoreSubscribe, n as subscribeToPHValue, o as ensurePHStore, r as PHStoreProvider, s as getActivePHStore, t as makePHEventFunctions, u as notifyPHStore } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ import { A as DocumentModelNotFoundError, E as dispatchActions, M as NoSelectedDocumentError, N as OperationRejectedError, P as UnsupportedDocumentTypeError, T as IDLE_REFETCH_STATE, _ as isDocumentTypeCache, a as useDocument, b as DOCUMENT_CHANGE_TYPE, c as useDocuments, d as useGetDocuments, f as DocumentCache, g as addPromiseState, h as IDLE_OPERATIONS_ENTRY, i as setDocumentCache, j as DocumentTypeMismatchError, l as useGetDocument, m as IDLE_DOCUMENTS_OF_TYPE_ENTRY, n as useDispatch, o as useDocumentCache, p as GET_MANY_CHUNK_SIZE, r as addDocumentCacheEventHandler, s as useDocumentSafe, t as createDispatch, u as useGetDocumentAsync, v as isOperationCache, w as DocumentRefetcher, y as readPromiseState } from "./dispatch-Cylwl2Dk.js";
3
+ import { $ as useReactorHalves, A as usePreloadNode, B as addFullReactorClientEventHandler, C as getNodeTarget, D as setSelectedNodeId, E as setSelectedNode, F as useDrives, G as setFullReactorClient, H as addReactorClientModuleEventHandler, I as DriveProvider, J as useDatabase, K as setReactorClient, L as useDriveContext, M as useSetSelectedNode, N as addDrivesEventHandler, O as useNodeTarget, P as setDrives, Q as useReactorClientModule, R as isInitialSyncInFlight, S as addSelectedNodeIdEventHandler, T as selectNode, U as addReactorHalvesEventHandler, V as addReactorClientEventHandler, W as getFullReactorClient, X as usePGlite, Y as useModelRegistry, Z as useReactorClient, _ as useSelectedDrive, _t as ambientRenownTokenProvider, a as setVetraPackageManager, at as invalidateDriveNodes, b as useSetSelectedDrive, c as addSwitchboardsEventHandler, ct as peekDriveNode, d as addSelectedDriveIdEventHandler, dt as useDriveNodes, et as useSync, f as preloadDrive, ft as useDriveNodesCache, g as usePreloadDrive, gt as sortNodesByName, h as setSelectedDriveId, ht as listAllDriveNodes, i as onVetraPackageManager, it as getDriveNode, k as useOpenNode, l as setSwitchboards, lt as takeLocalDriveWrite, m as setSelectedDrive, mt as isFolderNodeKind, n as useDocumentModelModules, nt as addDriveNodesEventHandler, o as useVetraPackageManager, ot as loadDriveNodes, p as selectDrive, pt as isFileNodeKind, q as setReactorClientModule, r as addVetraPackageManagerEventHandler, rt as dropDriveNode, s as useVetraPackages, st as markLocalDriveWrite, t as useDocumentModelModuleById, tt as useSyncList, u as useSwitchboards, ut as useDriveNode, v as useSelectedDriveId, vt as makeAuthMiddleware, w as preloadNode, x as addResetSelectedNodeEventHandler, y as useSelectedDriveSafe, z as listSyncRemotes } from "./document-model-modules-BG-61uke.js";
4
+ import { $ as makeNodeSlug, A as openTargetWith, B as createUrlWithPreservedParams, C as getCurrentPathname, D as isGlobalSearchParam, E as hasHostNavigation, F as searchParamsToString, G as extractNodeIdFromSlug, H as extractDriveIdFromSlug, I as searchToRecord, J as findDriveBySlug, K as extractNodeSlugFromPath, L as setBrowserOpenSync, M as preloadTarget, N as recordToSearch, O as isSettingsTarget, P as resolveSearchUpdate, Q as makeDriveUrlComponent, R as setSearchParams, S as browserNavigation, T as getTargetHref, U as extractDriveSlugFromPath, V as extractDriveIdFromPath, W as extractNodeIdFromPath, X as getPathWithoutBase, Y as findUuid, Z as makeDriveSlug, _ as GLOBAL_SEARCH_PARAMS, a as useRenown, b as SETTINGS_PATH, c as RENOWN_INITIAL_UNKNOWN, d as useRenownInitialUser, et as resolveUrlPathname, f as addLoadingEventHandler, g as FEATURE_FLAG_PARAM_PREFIX, h as useLoading, i as useLoginStatus, j as openedFromIndex, k as openTarget, l as RenownInitialUserProvider, m as setLoading, n as setRenown, o as useUser, p as loading, q as findDerivedId, r as useDid, s as RENOWN_INITIAL_ANONYMOUS, t as addRenownEventHandler, u as useRenownInitialAuth, v as OPENED_FROM_STATE_KEY, w as getPHNavigation, x as applySearchUpdate, y as PH_LOCATION_CHANGE_EVENT, z as targetPathname } from "./renown-CBoTdGrg.js";
5
+ import { $ as addIsAddDriveEnabledEventHandler, $i as copyNode$1, $n as useIsDeleteLocalDrivesEnabled, $r as isGraphQLReactorClient, $t as setIsAnalyticsDatabaseWorkerEnabled, A as setGraphQLReactorClient, Aa as useSearchParams, Ai as phDocumentFromGetDocument, An as setSwitchboardUrl, Ar as addIsDragAndDropEnabledEventHandler, At as addSentryEnvEventHandler, B as setAttachmentService, Bi as underSignaturePolicy, Bn as useDrivesPreserveStrategy, Br as useAllowedDocumentTypes, Bt as setAnalyticsDatabaseName, C as addSetSelectedNodeOnPopStateEventHandler, Ca as showPHModal, Ci as switchboardFetch, Cn as setRenownUrl, Cr as useSentryRelease, Ct as addRenownAdaptersEventHandler, D as setPackageDiscoveryService, Da as isPlainClick, Di as GraphQLDriveReadClient, Dn as setSentryEnv, Dr as useVersionCheckInterval, Dt as addRequiresHardRefreshEventHandler, E as addPackageDiscoveryServiceEventHandler, Ea as withoutModalSearch, Ei as GraphQLDriveNodeSource, En as setSentryDsn, Er as useVersion, Et as addRenownUrlEventHandler, F as useDropTarget, Fi as convertRemoteOperations, Fn as useAnalyticsDatabaseName, Fr as phDocumentEditorConfigHooks, Ft as addVersionEventHandler, G as addCliVersionEventHandler, Gi as GraphQLOperationNotSupportedError, Gn as useIsAddDriveEnabled, Gr as isBackendAuthError, Gt as setDrivesPreserveStrategy, H as addAllowListEventHandler, Hi as DEFAULT_DRIVE_EDITOR_ID, Hn as useFileUploadOperationsChunkSize, Hr as useIsExternalControlsEnabled, Ht as setCliVersion, I as addFeaturesEventHandler, Ii as extractRevisionMap, In as useBasePath, Ir as phDocumentEditorConfigSetters, It as addWarnOutdatedAppEventHandler, J as addDrivesPreserveStrategyEventHandler, Ji as queriesUnknownArgument, Jn as useIsAnalyticsDatabaseWorkerEnabled, Jr as useBackendAuth, Jt as setGaTrackingId, K as addDefaultDrivesUrlEventHandler, Ki as GraphQLWrongBackendError, Kn as useIsAddLocalDrivesEnabled, Kr as recordBackendAuthError, Kt as setEnabledEditors, L as setFeatures, Li as hasRevisionConflict, Ln as useCliVersion, Lr as setAllowedDocumentTypes, Lt as phGlobalConfigHooks, M as addDraggingNodeEventHandler, Mi as revisionMapFromRevisionsList, Mn as setVersionCheckInterval, Mr as isExternalControlsEnabledEventFunctions, Mt as addStudioModeEventHandler, N as useDragNode, Ni as ConflictError, Nn as setWarnOutdatedApp, Nr as phAppConfigHooks, Nt as addSwitchboardUrlEventHandler, O as usePackageDiscoveryService, Oa as useLinkProps, Oi as toLegacyNode, On as setSentryRelease, Or as useWarnOutdatedApp, Ot as addRouterBasenameEventHandler, P as useDropNode, Pi as buildPulledDocument, Pn as useAllowList, Pr as phAppConfigSetters, Pt as addVersionCheckIntervalEventHandler, Q as addIsAddCloudDrivesEnabledEventHandler, Qi as addFolder, Qn as useIsDeleteCloudDrivesEnabled, Qr as findIsServableOverGraphQL, Qt as setIsAddPublicDrivesEnabled, R as useFeatures, Ri as screamingSnakeToCamel, Rn as useDefaultDrivesUrl, Rr as setIsDragAndDropEnabled, Rt as phGlobalConfigSetters, S as addSetSelectedDriveOnPopStateEventHandler, Sa as showDeleteNodeModal, Si as isNodeFetch, Sn as setRenownNetworkId, Sr as useSentryEnv, St as addLogLevelEventHandler, T as syncSelectionFromPath, Ta as usePHModal, Ti as withStreamedBodies, Tn as setRouterBasename, Tr as useSwitchboardUrl, Tt as addRenownNetworkIdEventHandler, U as addAnalyticsDatabaseNameEventHandler, Ui as DRIVE_DOCUMENT_TYPES, Un as useGaTrackingId, Ur as addBackendAuthEventHandler, Ut as setDefaultDrivesUrl, V as useAttachmentService, Vi as COMMON_PACKAGE_ID, Vn as useEnabledEditors, Vr as useIsDragAndDropEnabled, Vt as setBasePath, W as addBasePathEventHandler, Wi as BatchJobFailedError, Wn as useIsAddCloudDrivesEnabled, Wr as backendAuthStatusOf, Wt as setDisabledEditors, X as addFileUploadOperationsChunkSizeEventHandler, Xi as addDocument, Xn as useIsAnalyticsExternalProcessorsEnabled, Xr as ambientRenownSigner, Xt as setIsAddDriveEnabled, Y as addEnabledEditorsEventHandler, Yi as queriesUnknownField, Yn as useIsAnalyticsEnabled, Yr as GraphQLReactorClient, Yt as setIsAddCloudDrivesEnabled, Z as addGaTrackingIdEventHandler, Zi as addFileWithProgress, Zn as useIsCloudDrivesEnabled, Zr as createGraphQLDriveNodeSource, Zt as setIsAddLocalDrivesEnabled, _ as setSelectedTimelineRevision, _a as modalFromSearch, _i as ReactorOperationFieldsFragmentDoc, _n as setIsSentryTracingEnabled, _r as useRenownNetworkId, _t as addIsLocalDrivesEnabledEventHandler, a as SwitchboardUnreachableError, aa as loadFile, ai as subscriptionsUrlFromGraphqlUrl, an as setIsDeletePublicDrivesEnabled, ar as useIsEditorReadModeEnabled, at as addIsCloudDrivesEnabledEventHandler, b as setSelectedTimelineItem, ba as setPHModal, bi as globalFetch, bn as setRenownAdapters, br as useRouterBasename, bt as addIsSentryTracingEnabledEventHandler, c as ensurePHEventHandlers, ca as renameNode, ci as subgraphUrlFromGraphqlUrl, cn as setIsDriveAnalyticsEnabled, cr as useIsExternalRelationalProcessorsEnabled, ct as addIsDeletePublicDrivesEnabledEventHandler, d as callEventHandlerRegisterFunctions, da as getUserPermissions, di as resolveDocumentModelModule, dn as setIsExternalPackagesEnabled, dr as useIsRelationalProcessorsEnabled, dt as addIsDriveAnalyticsEnabledEventHandler, ea as deleteNode, ei as viewFilterInputFromViewFilter, en as setIsAnalyticsEnabled, er as useIsDeletePublicDrivesEnabled, et as addIsAddLocalDrivesEnabledEventHandler, f as commonGlobalEventHandlerFunctions, fa as isDocumentTypeSupported, fi as prepareSignedActions, fn as setIsExternalProcessorsEnabled, fr as useIsSentryTracingEnabled, ft as addIsEditorDebugModeEnabledEventHandler, g as addSelectedTimelineRevisionEventHandler, ga as isRoutedModal, gi as MutateDocumentWithOperationsDocument, gn as setIsRelationalProcessorsEnabled, gr as useRenownChainId, gt as addIsExternalRelationalProcessorsEnabledEventHandler, h as usePHToast, ha as closePHModal, hi as GetDocumentAtConsistencyDocument, hn as setIsPublicDrivesEnabled, hr as useRenownAdapters, ht as addIsExternalProcessorsEnabledEventHandler, i as DEFAULT_REQUEST_TIMEOUT_MS, ia as getDocumentExtension, ii as startDocumentChangesSubscription, in as setIsDeleteLocalDrivesEnabled, ir as useIsEditorDebugModeEnabled, it as addIsAnalyticsExternalProcessorsEnabledEventHandler, j as useGraphQLReactorClient, ja as useSetSearchParams, ji as phDocumentFromMutation, jn as setVersion, jr as addIsExternalControlsEnabledEventHandler, jt as addSentryReleaseEventHandler, k as addGraphQLReactorClientEventHandler, ka as usePHNavigation, ki as isoStringFromDateTime, kn as setStudioMode, kr as addAllowedDocumentTypesEventHandler, kt as addSentryDsnEventHandler, l as useSwitchboardClient, la as setPreferredEditorOnNode, li as StaticPackageManager, ln as setIsEditorDebugModeEnabled, lr as useIsLocalDrivesEnabled, lt as addIsDiffAnalyticsEnabledEventHandler, m as setPHToast, ma as addModalEventHandler, mi as stampAction, mn as setIsLocalDrivesEnabled, mr as useLogLevel, mt as addIsExternalPackagesEnabledEventHandler, n as DEFAULT_BATCH_REQUEST_TIMEOUT_MS, na as extractInitialState, ni as isAuthRefusalClose, nn as setIsCloudDrivesEnabled, nr as useIsDocumentModelSelectionSettingsEnabled, nt as addIsAnalyticsDatabaseWorkerEnabledEventHandler, o as createSwitchboardBackend, oa as moveNode$1, oi as SubgraphSdkRegistry, on as setIsDiffAnalyticsEnabled, or as useIsExternalPackagesEnabled, ot as addIsDeleteCloudDrivesEnabledEventHandler, p as addToastEventHandler, pa as MODAL_SEARCH_PARAM, pi as signStampedAction, pn as setIsExternalRelationalProcessorsEnabled, pr as useLocalDrivesEnabled, pt as addIsEditorReadModeEnabledEventHandler, q as addDisabledEditorsEventHandler, qi as JobFailedError, qn as useIsAddPublicDrivesEnabled, qr as setBackendAuth, qt as setFileUploadOperationsChunkSize, r as DEFAULT_BREAKER, ra as fetchDocumentOperations, ri as makeAuthConnectionParams, rn as setIsDeleteCloudDrivesEnabled, rr as useIsDriveAnalyticsEnabled, rt as addIsAnalyticsEnabledEventHandler, s as GraphQLReactorProvider, sa as renameDriveNode, si as describeGraphQLDocument, sn as setIsDocumentModelSelectionSettingsEnabled, sr as useIsExternalProcessorsEnabled, st as addIsDeleteLocalDrivesEnabledEventHandler, t as useDocumentOperations, ta as exportFile, ti as createJobChangesSocket, tn as setIsAnalyticsExternalProcessorsEnabled, tr as useIsDiffAnalyticsEnabled, tt as addIsAddPublicDrivesEnabledEventHandler, u as addPHEventHandlers, ua as upgradeDocument, ui as packageFromDocumentModels, un as setIsEditorReadModeEnabled, ur as useIsPublicDrivesEnabled, ut as addIsDocumentModelSelectionSettingsEnabledEventHandler, v as useSelectedTimelineRevision, va as modalHref, vi as readCreateProtocolVersions, vn as setLocalDrivesEnabled, vr as useRenownUrl, vt as addIsPublicDrivesEnabledEventHandler, w as addSyncSelectionOnPopStateEventHandler, wa as useModalLinkProps, wi as withRequestDeadline, wn as setRequiresHardRefresh, wr as useStudioMode, wt as addRenownChainIdEventHandler, x as useSelectedTimelineItem, xa as showCreateDocumentModal, xi as isDeadlineError, xn as setRenownChainId, xr as useSentryDsn, xt as addLocalDrivesEnabledEventHandler, y as addSelectedTimelineItemEventHandler, ya as modalSearch, yi as readCreateSignaturePolicy, yn as setLogLevel, yr as useRequiresHardRefresh, yt as addIsRelationalProcessorsEnabledEventHandler, z as addAttachmentServiceEventHandler, zi as uncreatedDocument, zn as useDisabledEditors, zr as setIsExternalControlsEnabled, zt as setAllowList } from "./document-operations-DRMMwmGZ.js";
5
6
  import { a as setGlobal, i as getGlobal, n as getAnalyticsStore, r as clearGlobal, t as createAnalyticsStore } from "./store-DInXcjal.js";
6
7
  import { baseDocumentModels, baseDocumentModelsMap } from "./src/document-model.js";
7
- import { a as PropagationMode, r as GetDocumentWithOperationsDocument, t as createClient } from "./client-VV9M73s_.js";
8
- import { a as useRenown, c as RENOWN_INITIAL_UNKNOWN, d as useRenownInitialUser, f as addLoadingEventHandler, h as useLoading, i as useLoginStatus, l as RenownInitialUserProvider, m as setLoading, n as setRenown, o as useUser, p as loading, r as useDid, s as RENOWN_INITIAL_ANONYMOUS, t as addRenownEventHandler, u as useRenownInitialAuth } from "./renown-Def5iO8k.js";
9
- import { _ as useFolderNodesInSelectedDrive, b as isFolderNodeKind, c as useSelectedDocument, d as useSelectedDocumentSafe, f as useDocumentOfType, g as useFileNodesInSelectedDrive, h as useDocumentsInSelectedDrive, l as useSelectedDocumentId, m as useDocumentTypesInSelectedDrive, p as useSelectedNode, t as GQL_CHANNEL_SUFFIX, u as useSelectedDocumentOfType, v as useNodesInSelectedDrive, x as sortNodesByName, y as isFileNodeKind } from "./switchboard-CFyD_5_e.js";
10
- import { n as useDocumentsByIds, t as useDocumentById } from "./document-by-id-B_8DA4yZ.js";
11
- import { A as RENOWN_CHAIN_ID, C as logout, D as CREDENTIAL_TYPES, E as CREDENTIAL_SUBJECT_TYPE, M as RENOWN_RETURN_URL_STRIPPED_PARAMS, N as RENOWN_URL, O as DOMAIN_TYPE, P as VERIFIABLE_CREDENTIAL_EIP712_TYPE, S as login, T as CREDENTIAL_SCHEMA_EIP712_TYPE, _ as RenownLogo, a as Renown, b as useRenownAuth, c as useRenownSessionSynced, d as RenownAuthButton, f as RenownUserButton, g as DisconnectIcon, h as CopyIcon, i as RenownWalletProvider, j as RENOWN_NETWORK_ID, k as ISSUER_TYPE, l as initConnectCrypto, m as ChevronDownIcon, n as useRenownLoginMethods, o as useRenownInit, p as RenownLoginButton, r as RenownProvider, s as useRenownSessionCookie, t as useRenownWalletAdapter, u as initRenownCrypto, v as SpinnerIcon, w as openRenown, x as useRenownAuthAsync, y as UserIcon } from "./renown-C9pYZRqf.js";
12
- import { i as setPGliteDB, n as useRelationalQuery, r as useRelationalDb, t as createProcessorQuery } from "./relational-ChC_AWAK.js";
13
- import { a as getPackagesByDocumentType, i as getPackages, n as getPackageInfo, o as getPackagesForDocumentType, r as getPackagePage, s as trimTrailingSlash, t as RegistryClient } from "./client-BiJAJ9dW.js";
14
- import { AuthEnforcementDisabledError, ChannelScheme, DocumentChangeType, DocumentChangeType as DocumentChangeType$1, DocumentIntegrityService, DriveCollectionId, DriveCollectionId as DriveCollectionId$1, DriveRequestError, GqlRequestChannel, InMemoryQueue, IntervalPollTimer, PollBehavior, PropagationMode as PropagationMode$1, REACTOR_SCHEMA, REACTOR_SCHEMA as REACTOR_SCHEMA$1, ReactorBuilder, ReactorClientBuilder, RelationalDbProcessor, SyncOperationStatus, SyncStatus, driveIdFromUrl, isDriveAuthError, isDriveAuthError as isDriveAuthError$1, parseDriveUrl } from "@powerhousedao/reactor";
15
- import { DriveDocumentSchema, driveCreateDocument, getDescendants, getNextCopyNumber, isFileNode, isFolderNode, setAvailableOffline, setDriveIcon, setDriveName, setSharingType } from "@powerhousedao/shared/document-drive";
16
- import { DEFAULT_SIGNATURE_POLICY, actionSignerIdentity, actionSigningTarget, createZip, isDocumentZip, parseBulkArchive, requestedSignaturePolicy, toTransportAction, validateInitialState, validateModules, validateStateSchemaName, withSignaturePolicy, zipEntries } from "@powerhousedao/shared/document-model";
8
+ import { s as PropagationMode } from "./schema-B5lftDPf.js";
9
+ import { t as createClient } from "./client-wwavHFfs.js";
10
+ import { _ as EditorDocumentProvider, a as buildDocumentSubgraphUrl, b as useSelectedNode, c as getDriveIdBySlug, d as getSwitchboardGatewayUrlFromDriveUrl, g as useSelectedDocumentSafe, h as useSelectedDocumentOfType, i as buildDocumentSubgraphQuery, l as getSlugFromDriveUrl, m as useSelectedDocumentId, n as createSwitchboardDirectory, o as getDocumentGraphqlQuery, p as useSelectedDocument, r as resolveSwitchboard, s as getDocumentStateSelection, t as SwitchboardLookupError, u as getSwitchboardBaseFromChannelUrl, v as useEditorDocumentContext, x as useNodeById, y as useDocumentOfType } from "./switchboard-directory-vH6qtkh-.js";
11
+ import { A as CREDENTIAL_TYPES, C as useRenownAuthAsync, D as openRenown, E as logout, F as RENOWN_RETURN_URL_STRIPPED_PARAMS, I as RENOWN_URL, L as VERIFIABLE_CREDENTIAL_EIP712_TYPE, M as ISSUER_TYPE, N as RENOWN_CHAIN_ID, O as CREDENTIAL_SCHEMA_EIP712_TYPE, P as RENOWN_NETWORK_ID, S as useRenownAuth, T as login, _ as CopyIcon, a as RenownProvider, b as SpinnerIcon, c as useRenownInit, d as initConnectCrypto, f as initRenownCrypto, g as ChevronDownIcon, h as RenownLoginButton, i as useRenownLoginMethods, j as DOMAIN_TYPE, k as CREDENTIAL_SUBJECT_TYPE, l as useRenownSessionCookie, m as RenownUserButton, n as decodeDelegation, o as RenownWalletProvider, p as RenownAuthButton, r as useRenownWalletAdapter, s as Renown, t as createDelegation, u as useRenownSessionSynced, v as DisconnectIcon, w as desktopShell, x as UserIcon, y as RenownLogo } from "./renown-B3MUaiq7.js";
12
+ import { n as useDocumentsByIds, t as useDocumentById } from "./document-by-id-DdvqanGR.js";
13
+ import { i as setPGliteDB, n as useRelationalQuery, r as useRelationalDb, t as createProcessorQuery } from "./relational-DZuyKp2y.js";
14
+ import { a as getPackagesByDocumentType, c as trimTrailingSlash, i as getPackages, l as SYNC_REMOTES_CHANGED_EVENT, n as getPackageInfo, o as getPackagesForDocumentType, r as getPackagePage, s as searchPackages, t as RegistryClient } from "./client-BFnMV-EO.js";
15
+ import { use, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
16
+ import { DEFAULT_SIGNATURE_POLICY, actionSignerIdentity, actionSigningTarget, createZip, headNewDocument, isDocumentZip, parseBulkArchive, redo, requestedSignaturePolicy, stateReducerOf, toTransportAction, undo, undoCapabilitiesOf, undoNeedsTargets, undoRedoActions, undoRedoTargetsOf, validateInitialState, validateModules, validateStateSchemaName, zipEntries } from "@powerhousedao/shared/document-model";
17
+ import { AuthEnforcementDisabledError, ChannelScheme, DocumentChangeType, DocumentChangeType as DocumentChangeType$1, DocumentIntegrityService, DriveCollectionId, DriveCollectionId as DriveCollectionId$1, DriveRequestError, GqlRequestChannel, InMemoryQueue, IntervalPollTimer, PollBehavior, PropagationMode as PropagationMode$1, REACTOR_SCHEMA, REACTOR_SCHEMA as REACTOR_SCHEMA$1, ReactorBuilder, ReactorClientBuilder, RelationalDbProcessor, SyncEventTypes, SyncOperationStatus, SyncStatus, driveIdFromUrl, isDriveAuthError, isDriveAuthError as isDriveAuthError$1, parseDriveUrl } from "@powerhousedao/reactor";
18
+ import { DriveDocumentSchema, driveDocumentType, getDescendants, getNextCopyNumber, isFileNode, isFolderNode, setAvailableOffline, setDriveIcon, setDriveName, setSharingType } from "@powerhousedao/shared/document-drive";
17
19
  import { allPass, filter, find, forEach, funnel, hasAtLeast, isArray, isDefined, isIncludedIn, isStrictEqual, isTruthy, last, map, mapToObj, once, pipe, prop, split, unique } from "remeda";
18
- import { pascalCase } from "change-case";
19
- import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
20
20
  import { ClientError } from "graphql-request";
21
- import { Kind, parse } from "graphql";
22
21
  import { z } from "zod";
23
22
  import normalizeException from "normalize-exception";
24
- import lzString from "lz-string";
25
23
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
26
24
  //#region src/actions/drive-info.ts
27
25
  /**
@@ -43,8 +41,8 @@ import { createAttachmentClient } from "@powerhousedao/reactor-attachments/clien
43
41
  * `isDriveAuthError` can tell a refusal from an unreachable host and the
44
42
  * caller can prompt for a login instead of reporting a network fault.
45
43
  */
46
- async function fetchDriveInfo(url) {
47
- const token = await ambientRenownTokenProvider();
44
+ async function fetchDriveInfo(url, tokenProvider = ambientRenownTokenProvider) {
45
+ const token = await tokenProvider();
48
46
  const response = await fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
49
47
  if (!response.ok) throw new DriveRequestError(`Failed to resolve drive info from ${url}: HTTP ${response.status}`, response.status);
50
48
  return await response.json();
@@ -67,9 +65,8 @@ async function expandBulkArchive(file, driveId, targetParent) {
67
65
  }];
68
66
  const entries = await parseBulkArchive(data);
69
67
  if (!(await Promise.all(entries.map((entry) => isDocumentZip(entry.data)))).some(Boolean)) throw new Error("Archive contains no Powerhouse documents");
70
- const reactorClient = window.ph?.reactorClient;
71
- if (!reactorClient) throw new Error("ReactorClient not initialized");
72
- const knownNodes = [...(await reactorClient.get(driveId)).state.global.nodes];
68
+ if (!getPHStore()?.reactorClient) throw new Error("ReactorClient not initialized");
69
+ const knownNodes = [...await loadDriveNodes(driveId, { refresh: true })];
73
70
  const dirToNode = /* @__PURE__ */ new Map();
74
71
  const ensureDir = async (dirPath, parent) => {
75
72
  const cached = dirToNode.get(dirPath);
@@ -126,7 +123,7 @@ function segmentsBelow(root, node, allNodes) {
126
123
  * initialState (see downloadFolderZip).
127
124
  */
128
125
  async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
129
- const allNodes = drive.state.global.nodes;
126
+ const allNodes = await loadDriveNodes(drive.header.id, { refresh: true });
130
127
  const topName = sanitize(folderNode?.name ?? (drive.state.global.name || drive.header.name));
131
128
  const subtree = folderNode ? [folderNode, ...getDescendants(folderNode, allNodes)] : allNodes;
132
129
  const entries = { [topName + "/"]: /* @__PURE__ */ new Uint8Array(0) };
@@ -178,11 +175,11 @@ async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
178
175
  * showSaveFilePicker (fallback: blob download), mirroring exportFile.
179
176
  */
180
177
  async function downloadFolderZip(drive, folderNode, onProgress) {
181
- const reactorClient = window.ph?.reactorClient;
178
+ const reactorClient = getPHStore()?.reactorClient;
182
179
  if (!reactorClient) throw new Error("ReactorClient not initialized");
183
180
  const result = await buildFolderZip(drive, folderNode, async (id) => {
184
181
  const doc = await reactorClient.get(id);
185
- const operations = await fetchDocumentOperations(reactorClient, doc);
182
+ const operations = await fetchDocumentOperations(reactorClient.read, doc);
186
183
  const initialState = extractInitialState(operations["document"] ?? []);
187
184
  return {
188
185
  ...doc,
@@ -256,39 +253,39 @@ async function waitForDocumentReady(reactorClient, documentId, options) {
256
253
  }, timeoutMs);
257
254
  });
258
255
  }
259
- /** The full client's creation default, else the library's. */
260
- async function createSignaturePolicy() {
261
- const client = window.ph?.reactorClientModule?.client;
262
- return client ? client.getCreateSignaturePolicy() : DEFAULT_SIGNATURE_POLICY;
263
- }
264
- /** What the full client selects for a drive, which has no parent. */
265
- async function createProtocolVersions() {
266
- const client = window.ph?.reactorClientModule?.client;
267
- return client ? client.getCreateProtocolVersions() : {};
268
- }
269
256
  async function addDrive(input, preferredEditor) {
270
257
  const { isAllowedToCreateDocuments } = getUserPermissions();
271
258
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create drives");
272
- const reactorClient = window.ph?.reactorClient;
259
+ const reactorClient = getPHStore()?.reactorClient;
273
260
  if (!reactorClient) throw new Error("ReactorClient not initialized");
274
- const driveDoc = withSignaturePolicy(driveCreateDocument({ global: {
275
- name: input.global.name || "",
276
- icon: input.global.icon ?? null,
277
- nodes: []
278
- } }), requestedSignaturePolicy(input, input.id ? "legacy" : await createSignaturePolicy()), {
261
+ const options = {
262
+ initialState: { global: {
263
+ name: input.global.name || "",
264
+ icon: input.global.icon ?? null,
265
+ nodes: []
266
+ } },
267
+ signaturePolicy: input.id ? requestedSignaturePolicy(input, "legacy") : input.signaturePolicy,
279
268
  id: input.id || void 0,
280
- protocolVersions: {
281
- ...await createProtocolVersions(),
282
- ...input.protocolVersions
283
- }
284
- });
269
+ protocolVersions: input.protocolVersions
270
+ };
271
+ let driveDoc;
272
+ try {
273
+ driveDoc = await reactorClient.newDocument(driveDocumentType, options);
274
+ } catch (error) {
275
+ if (getFullReactorClient() || !GraphQLOperationNotSupportedError.isError(error)) throw error;
276
+ driveDoc = await reactorClient.newDocument(driveDocumentType, {
277
+ ...options,
278
+ signaturePolicy: DEFAULT_SIGNATURE_POLICY
279
+ });
280
+ }
285
281
  if (preferredEditor) driveDoc.header.meta = { preferredEditor };
286
- return await reactorClient.create(driveDoc);
282
+ if (input.global.name) driveDoc.header.name = input.global.name;
283
+ return await (await reactorClient.write.create(driveDoc)).document();
287
284
  }
288
285
  async function addRemoteDrive(url, driveId, options) {
289
- const reactorClient = window.ph?.reactorClientModule?.client;
286
+ const reactorClient = getFullReactorClient();
290
287
  if (!reactorClient) throw new Error("ReactorClient not initialized");
291
- const sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
288
+ const sync = getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
292
289
  if (!sync) throw new Error("Sync not initialized");
293
290
  let driveInfo;
294
291
  try {
@@ -315,7 +312,7 @@ async function addRemoteDrive(url, driveId, options) {
315
312
  if (isDriveAuthError$1(error)) showPHModal({ type: "driveAuthRequired" });
316
313
  throw error;
317
314
  }
318
- if (options?.awaitInitialSync) await waitForDocumentReady(reactorClient, resolvedDriveId, {
315
+ if (options?.awaitInitialSync) await waitForDocumentReady(reactorClient.read, resolvedDriveId, {
319
316
  timeoutMs: options.initialSyncTimeoutMs,
320
317
  signal: options.signal
321
318
  });
@@ -324,55 +321,49 @@ async function addRemoteDrive(url, driveId, options) {
324
321
  async function deleteDrive(driveId) {
325
322
  const { isAllowedToCreateDocuments } = getUserPermissions();
326
323
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete drives");
327
- const reactorClient = window.ph?.reactorClient;
324
+ const reactorClient = getPHStore()?.reactorClient;
328
325
  if (!reactorClient) throw new Error("ReactorClient not initialized");
329
- const sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
326
+ const sync = getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
330
327
  if (sync) {
331
328
  const collectionId = DriveCollectionId$1.forDrive(driveId);
332
329
  const remotes = sync.list().filter((remote) => remote.meta.collectionId.equals(collectionId));
333
330
  for (const remote of remotes) await sync.remove(remote.meta.name);
334
331
  }
335
- await reactorClient.deleteDocument(driveId, PropagationMode$1.Cascade);
332
+ await (await reactorClient.write.deleteDocument(driveId, PropagationMode$1.Cascade)).readable;
336
333
  }
337
334
  async function renameDrive(driveId, name) {
338
335
  const { isAllowedToCreateDocuments } = getUserPermissions();
339
336
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename drives");
340
- const reactorClient = window.ph?.reactorClientModule?.client;
337
+ const reactorClient = getFullReactorClient();
341
338
  if (!reactorClient) throw new Error("ReactorClient not initialized");
342
- return await reactorClient.rename(driveId, name);
339
+ return await (await reactorClient.write.rename(driveId, name)).document();
343
340
  }
344
341
  async function setDriveAvailableOffline(driveId, availableOffline) {
345
342
  const { isAllowedToCreateDocuments } = getUserPermissions();
346
343
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to change drive availability");
347
- const reactorClient = window.ph?.reactorClient;
344
+ const reactorClient = getPHStore()?.reactorClient;
348
345
  if (!reactorClient) throw new Error("ReactorClient not initialized");
349
- return await reactorClient.execute(driveId, "main", [setAvailableOffline({ availableOffline })]);
346
+ return await (await reactorClient.write.execute(driveId, "main", [setAvailableOffline({ availableOffline })])).document();
350
347
  }
351
348
  async function setDriveSharingType(driveId, sharingType) {
352
349
  const { isAllowedToCreateDocuments } = getUserPermissions();
353
350
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to change drive sharing type");
354
- const reactorClient = window.ph?.reactorClient;
351
+ const reactorClient = getPHStore()?.reactorClient;
355
352
  if (!reactorClient) throw new Error("ReactorClient not initialized");
356
- return await reactorClient.execute(driveId, "main", [setSharingType({ type: sharingType })]);
353
+ return await (await reactorClient.write.execute(driveId, "main", [setSharingType({ type: sharingType })])).document();
357
354
  }
358
355
  async function setDriveMetadata(driveId, metadata) {
359
356
  const { isAllowedToCreateDocuments } = getUserPermissions();
360
357
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to update drive metadata");
361
- const reactorClient = window.ph?.reactorClient;
358
+ const reactorClient = getPHStore()?.reactorClient;
362
359
  if (!reactorClient) throw new Error("ReactorClient not initialized");
363
360
  const actions = [];
364
361
  if (metadata.name) actions.push(setDriveName({ name: metadata.name }));
365
362
  if (metadata.icon !== void 0) actions.push(setDriveIcon({ icon: metadata.icon }));
366
363
  if (actions.length === 0) return;
367
- return await reactorClient.execute(driveId, "main", actions);
364
+ return await (await reactorClient.write.execute(driveId, "main", actions)).document();
368
365
  }
369
366
  //#endregion
370
- //#region src/constants.ts
371
- const DEFAULT_DRIVE_EDITOR_ID = "powerhouse/generic-drive-explorer";
372
- const COMMON_PACKAGE_ID = "powerhouse/common";
373
- /** Document types that represent a "drive": a container of nodes. */
374
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
375
- //#endregion
376
367
  //#region src/graphql/adapters.ts
377
368
  function phDocumentFromQuery(document, documentSchema) {
378
369
  const phDocument = {
@@ -408,11 +399,15 @@ function phDocumentOperationsFromGetDocumentWithOperationsQuery(queryDocument) {
408
399
  return { global: [...queryDocument.operations.items] };
409
400
  }
410
401
  function identifierFromMutateDocumentOperationVariables(variables) {
411
- return z.object({ documentIdentifier: z.string() }).parse(variables).documentIdentifier;
402
+ return z.object({ documentIdOrSlug: z.string() }).parse(variables).documentIdOrSlug;
412
403
  }
413
404
  //#endregion
414
405
  //#region src/graphql/constants.ts
415
406
  const DEFAULT_DRIVE_ID = "powerhouse";
407
+ /**
408
+ * @deprecated A guess, not a switchboard the app reaches. Pick one from the
409
+ * host's switchboard directory with `resolveSwitchboard`.
410
+ */
416
411
  const DEFAULT_SWITCHBOARD_URL = "http://localhost:4001/graphql";
417
412
  const graphqlEventsToSyncDrive = [
418
413
  "CreateEmptyDocument",
@@ -432,10 +427,10 @@ const graphqlDocumentsEvents = ["DeleteDocuments"];
432
427
  //#endregion
433
428
  //#region src/graphql/fetchers.ts
434
429
  async function reactorGraphqlFetchDocument(identifier, documentSchema) {
435
- const client = window.ph?.reactorGraphQLClient;
430
+ const client = getPHStore()?.reactorGraphQLClient;
436
431
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
437
432
  try {
438
- const document = (await client.GetDocument({ identifier })).document?.document;
433
+ const document = (await client.GetDocument({ idOrSlug: identifier })).document?.document;
439
434
  if (!document) return void 0;
440
435
  return phDocumentFromQuery(document, documentSchema);
441
436
  } catch {
@@ -443,7 +438,7 @@ async function reactorGraphqlFetchDocument(identifier, documentSchema) {
443
438
  }
444
439
  }
445
440
  async function reactorGraphqlBatchFetchDocuments(identifiers) {
446
- if (!window.ph?.reactorGraphQLClient) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
441
+ if (!getPHStore()?.reactorGraphQLClient) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
447
442
  const promises = map(identifiers, (identifier) => reactorGraphqlFetchDocument(identifier));
448
443
  return await Promise.all(promises);
449
444
  }
@@ -528,15 +523,18 @@ var DocumentFetcher = class {
528
523
  };
529
524
  //#endregion
530
525
  //#region src/graphql/graphql-client-document-cache.ts
526
+ function isMissingDocumentMessage(message) {
527
+ return message.includes("Document not found") || /Document \S+ was purged/.test(message);
528
+ }
531
529
  async function fetchDocumentForRefetch(identifier) {
532
- const client = window.ph?.reactorGraphQLClient;
530
+ const client = getPHStore()?.reactorGraphQLClient;
533
531
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
534
532
  const notFound = (cause) => new Error(`Document not found: ${identifier}`, { cause });
535
533
  let result;
536
534
  try {
537
- result = await client.GetDocument({ identifier });
535
+ result = await client.GetDocument({ idOrSlug: identifier });
538
536
  } catch (error) {
539
- if ((error instanceof ClientError ? (error.response.errors ?? []).map((e) => e.message) : []).some((message) => message.includes("Document not found"))) throw notFound(error);
537
+ if ((error instanceof ClientError ? (error.response.errors ?? []).map((e) => e.message) : []).some(isMissingDocumentMessage)) throw notFound(error);
540
538
  throw error;
541
539
  }
542
540
  const document = result.document?.document;
@@ -645,28 +643,28 @@ var GraphQLClientDocumentCache = class {
645
643
  //#endregion
646
644
  //#region src/graphql/mutators.ts
647
645
  async function reactorGraphqlCreateDocument(document, parentIdentifier = DEFAULT_DRIVE_ID) {
648
- const client = window.ph?.reactorGraphQLClient;
646
+ const client = getPHStore()?.reactorGraphQLClient;
649
647
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
650
648
  return await client.CreateDocument({
651
649
  document,
652
- parentIdentifier
650
+ parentIdOrSlug: parentIdentifier
653
651
  });
654
652
  }
655
653
  async function reactorGraphqlDeleteDocument(identifier) {
656
- const client = window.ph?.reactorGraphQLClient;
654
+ const client = getPHStore()?.reactorGraphQLClient;
657
655
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
658
- return await client.DeleteDocument({ identifier });
656
+ return await client.DeleteDocument({ idOrSlug: identifier });
659
657
  }
660
658
  async function reactorGraphqlDeleteDocuments(identifiers) {
661
- const client = window.ph?.reactorGraphQLClient;
659
+ const client = getPHStore()?.reactorGraphQLClient;
662
660
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
663
- return await client.DeleteDocuments({ identifiers });
661
+ return await client.DeleteDocuments({ idsOrSlugs: identifiers });
664
662
  }
665
663
  async function reactorGraphqlMutateDocument(documentIdentifier, ...actions) {
666
- const client = window.ph?.reactorGraphQLClient;
664
+ const client = getPHStore()?.reactorGraphQLClient;
667
665
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
668
666
  return await client.MutateDocument({
669
- documentIdentifier,
667
+ documentIdOrSlug: documentIdentifier,
670
668
  actions
671
669
  });
672
670
  }
@@ -679,10 +677,38 @@ function useAllowedDocumentModelModules() {
679
677
  return documentModelModules?.filter((module) => allowedDocumentTypes.includes(module.documentModel.global.id));
680
678
  }
681
679
  //#endregion
680
+ //#region src/hooks/items-in-selected-drive.ts
681
+ /** Returns the nodes in the selected drive. */
682
+ function useNodesInSelectedDrive() {
683
+ return useDriveNodes(useSelectedDriveId());
684
+ }
685
+ /** Returns the file nodes in the selected drive. */
686
+ function useFileNodesInSelectedDrive() {
687
+ return useNodesInSelectedDrive()?.filter((n) => isFileNodeKind(n));
688
+ }
689
+ /** Returns the folder nodes in the selected drive. */
690
+ function useFolderNodesInSelectedDrive() {
691
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
692
+ }
693
+ /** Returns the documents in the selected drive. */
694
+ function useDocumentsInSelectedDrive() {
695
+ const fileNodeIds = useFileNodesInSelectedDrive()?.map((node) => node.id);
696
+ return useDocumentsByIds(fileNodeIds);
697
+ }
698
+ /** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */
699
+ function useDocumentTypesInSelectedDrive() {
700
+ return (useDocumentsInSelectedDrive()?.filter(isDocumentModelDocument))?.map((doc) => doc.state.global.id);
701
+ }
702
+ function isDocumentModelDocument(document) {
703
+ return document.header.documentType === "powerhouse/document-model";
704
+ }
705
+ //#endregion
682
706
  //#region src/hooks/selected-folder.ts
683
- /** Returns the selected folder. */
707
+ /** Returns the selected folder: the drive app's open folder, else the app's. */
684
708
  function useSelectedFolder() {
709
+ const context = useDriveContext();
685
710
  const selectedNode = useSelectedNode();
711
+ if (context?.folder) return context.folder;
686
712
  if (isFolderNodeKind(selectedNode)) return selectedNode;
687
713
  }
688
714
  //#endregion
@@ -855,6 +881,91 @@ function buildSnapshot(syncManager) {
855
881
  return map;
856
882
  }
857
883
  //#endregion
884
+ //#region src/hooks/document-link.ts
885
+ /** Where a document opens: the loaded drive that lists it, or undefined while none does. */
886
+ function useDocumentTarget(documentId) {
887
+ const store = usePHStore() ?? getPHStore();
888
+ const drives = useDrives();
889
+ const cache = useDriveNodesCache();
890
+ const driveIds = drives?.map((d) => d.header.id).join("\n") ?? "";
891
+ let target;
892
+ if (documentId && drives) for (const drive of drives) {
893
+ const node = cache?.get(drive.header.id)?.byId.get(documentId);
894
+ if (!isFileNodeKind(node)) continue;
895
+ target = {
896
+ driveSlug: makeDriveSlug(drive),
897
+ nodeSlug: makeNodeSlug(node)
898
+ };
899
+ break;
900
+ }
901
+ const found = target !== void 0;
902
+ useEffect(() => {
903
+ if (!documentId || !driveIds || found) return;
904
+ for (const driveId of driveIds.split("\n")) getDriveNode(driveId, documentId, { store }).catch(() => void 0);
905
+ }, [
906
+ documentId,
907
+ driveIds,
908
+ found,
909
+ store
910
+ ]);
911
+ return target;
912
+ }
913
+ /** `useLinkProps` for a document by id, e.g. a `useDocumentsOfType` row;
914
+ * undefined while no loaded drive lists it. */
915
+ function useDocumentLinkProps(documentId) {
916
+ const target = useDocumentTarget(documentId);
917
+ const props = useLinkProps(target);
918
+ return target ? props : void 0;
919
+ }
920
+ //#endregion
921
+ //#region src/hooks/documents-of-type.ts
922
+ const DEFAULT_LIMIT = 25;
923
+ const NO_DOCUMENTS = {
924
+ documents: [],
925
+ invalid: [],
926
+ hasNextPage: false,
927
+ isLoadingNextPage: false,
928
+ loadNextPage: () => void 0,
929
+ error: void 0
930
+ };
931
+ const typeOf = (module) => module.documentModel.global.id;
932
+ function typeCacheOf(cache) {
933
+ if (!cache) return void 0;
934
+ if (!isDocumentTypeCache(cache)) throw new Error("This document cache can't list documents by type.");
935
+ return cache;
936
+ }
937
+ /** The documents of `module`'s type across every drive, a page at a time and
938
+ * checked against its schema; suspends until the first page has loaded. */
939
+ function useDocumentsOfType(module, { limit = DEFAULT_LIMIT } = {}) {
940
+ const cache = typeCacheOf(useDocumentCache());
941
+ const type = typeOf(module);
942
+ const read = () => cache?.getDocumentsOfTypeState(type, limit) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY;
943
+ const entry = useSyncExternalStore((onChange) => cache ? cache.subscribeDocumentsOfType(type, limit, onChange) : () => {}, read, read);
944
+ if (cache) use(cache.loadDocumentsOfType(type, limit));
945
+ if (entry.status === "error" && entry.ids.length === 0) throw entry.error;
946
+ const loaded = useDocuments(entry.ids);
947
+ const [documents, invalid] = useMemo(() => {
948
+ const valid = [];
949
+ const other = [];
950
+ for (const document of loaded) if (module.utils.isDocumentOfType(document)) valid.push(document);
951
+ else other.push(document);
952
+ return [valid, other];
953
+ }, [loaded, module]);
954
+ if (!cache) return NO_DOCUMENTS;
955
+ return {
956
+ documents,
957
+ invalid,
958
+ hasNextPage: entry.hasNextPage,
959
+ isLoadingNextPage: entry.status === "pending",
960
+ loadNextPage: () => cache.loadMoreDocumentsOfType(type, limit),
961
+ error: entry.status === "error" ? entry.error : void 0
962
+ };
963
+ }
964
+ /** Loads the first page `useDocumentsOfType` reads, e.g. in a route loader, so it doesn't suspend. */
965
+ async function loadDocumentsOfType(module, { limit = DEFAULT_LIMIT } = {}) {
966
+ await typeCacheOf(getPHStore()?.documentCache)?.loadDocumentsOfType(typeOf(module), limit);
967
+ }
968
+ //#endregion
858
969
  //#region src/hooks/supported-document-types.ts
859
970
  /** Returns the supported document types for the reactor (derived from the document model modules) */
860
971
  function useSupportedDocumentTypesInReactor() {
@@ -864,13 +975,13 @@ function useSupportedDocumentTypesInReactor() {
864
975
  //#region src/hooks/document-types.ts
865
976
  /** Returns the document types a app supports.
866
977
  *
867
- * If present, uses the `allowedDocumentTypes` config value.
868
- * Otherwise, uses the supported document types from the reactor.
978
+ * Uses the `allowedDocumentTypes` config value when it lists any types.
979
+ * Unset or empty, it means every type, so the reactor's supported types are used.
869
980
  */
870
981
  function useDocumentTypes() {
871
982
  const allowedDocumentTypes = useAllowedDocumentTypes();
872
983
  const supportedDocumentTypes = useSupportedDocumentTypesInReactor();
873
- return allowedDocumentTypes ?? supportedDocumentTypes;
984
+ return allowedDocumentTypes?.length ? allowedDocumentTypes : supportedDocumentTypes;
874
985
  }
875
986
  //#endregion
876
987
  //#region src/hooks/document-version-status.ts
@@ -1052,6 +1163,14 @@ function useEditorModulesForDocumentType(documentType) {
1052
1163
  if (!documentType) return void 0;
1053
1164
  return editorModules?.filter((module) => module.documentTypes.includes(documentType));
1054
1165
  }
1166
+ /** The editor for `document`: its preferred editor if that edits its type,
1167
+ * else the first editor for its type. */
1168
+ function useEditorModuleFor(document) {
1169
+ const documentType = document?.header.documentType;
1170
+ const preferred = useEditorModuleById(document?.header.meta?.preferredEditor);
1171
+ const fallback = useFallbackEditorModule(documentType);
1172
+ return !!documentType && !!preferred && (preferred.documentTypes.includes(documentType) || preferred.documentTypes.includes("*")) ? preferred : fallback;
1173
+ }
1055
1174
  //#endregion
1056
1175
  //#region src/utils/preload-editor.ts
1057
1176
  function preloadEditorModule(module) {
@@ -1181,7 +1300,8 @@ function useDropFile(handleAddFile) {
1181
1300
  //#endregion
1182
1301
  //#region src/hooks/folder-by-id.ts
1183
1302
  function useFolderById(id) {
1184
- return useFolderNodesInSelectedDrive()?.find((n) => n.id === id);
1303
+ const node = useNodeById(id);
1304
+ return isFolderNodeKind(node) ? node : void 0;
1185
1305
  }
1186
1306
  //#endregion
1187
1307
  //#region src/graphql/events.ts
@@ -1213,25 +1333,24 @@ function useInitReactorGraphqlClient(switchboardUrl = DEFAULT_SWITCHBOARD_URL, d
1213
1333
  return hasInit;
1214
1334
  }
1215
1335
  async function reactorGraphqlFetchDrive(identifier) {
1216
- const client = window.ph?.reactorGraphQLClient;
1336
+ const client = getPHStore()?.reactorGraphQLClient;
1217
1337
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
1218
- const result = await client.GetDocument({ identifier });
1338
+ const result = await client.GetDocument({ idOrSlug: identifier });
1219
1339
  if (!result.document?.document) throw new Error("Could not fetch drive with id: " + identifier);
1220
1340
  return phDocumentFromQuery(result.document.document, DriveDocumentSchema);
1221
1341
  }
1222
1342
  async function reactorGraphqlSyncDrive(driveId) {
1223
- if (!window.ph?.reactorGraphQLClient) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
1343
+ if (!getPHStore()?.reactorGraphQLClient) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
1224
1344
  const drive = await reactorGraphqlFetchDrive(driveId);
1225
1345
  setDrives([drive]);
1226
- setSelectedDrive(drive);
1346
+ selectDrive(drive);
1227
1347
  }
1228
1348
  async function initGraphQLReactorClientWithDocumentCache(switchboardUrl, driveId) {
1229
- if (!window.ph) window.ph = {};
1230
1349
  callEventHandlerRegisterFunctions(commonGlobalEventHandlerFunctions);
1231
1350
  const client = createClient(switchboardUrl, documentCacheClientMiddleware);
1232
1351
  setGraphQLReactorClient(client);
1233
1352
  await reactorGraphqlSyncDrive(driveId);
1234
- setSelectedNode(void 0);
1353
+ selectNode(void 0);
1235
1354
  setDocumentCache(new GraphQLClientDocumentCache());
1236
1355
  forEach(graphqlEventsToSyncDrive, (name) => {
1237
1356
  window.addEventListener(name, () => {
@@ -1272,6 +1391,7 @@ function resolveNode(driveId, node) {
1272
1391
  return node?.id !== driveId ? node : void 0;
1273
1392
  }
1274
1393
  function useNodeActions() {
1394
+ const setSelectedNode = useSetSelectedNode();
1275
1395
  const [selectedDrive] = useSelectedDriveSafe();
1276
1396
  const selectedFolder = useSelectedFolder();
1277
1397
  const selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);
@@ -1335,8 +1455,10 @@ function useNodeActions() {
1335
1455
  }
1336
1456
  async function onRenameDriveNodes(newName, nodeId) {
1337
1457
  if (!drives) return;
1338
- const drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));
1339
- await Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));
1458
+ const holders = await Promise.all(drives.map(async (drive) => {
1459
+ return await getDriveNode(drive.header.id, nodeId).catch(() => void 0) ? drive.header.id : void 0;
1460
+ }));
1461
+ await Promise.all(holders.filter((driveId) => driveId !== void 0).map((driveId) => renameDriveNode(driveId, nodeId, newName)));
1340
1462
  }
1341
1463
  return {
1342
1464
  onAddFile,
@@ -1350,12 +1472,6 @@ function useNodeActions() {
1350
1472
  };
1351
1473
  }
1352
1474
  //#endregion
1353
- //#region src/hooks/node-by-id.ts
1354
- /** Returns a node in the selected drive by id. */
1355
- function useNodeById(id) {
1356
- return useNodesInSelectedDrive()?.find((n) => n.id === id);
1357
- }
1358
- //#endregion
1359
1475
  //#region src/hooks/node-path.ts
1360
1476
  /** Returns the path to a node in the selected drive */
1361
1477
  function useNodePathById(id) {
@@ -1383,6 +1499,56 @@ function useParentFolderForSelectedNode() {
1383
1499
  return useNodeParentFolderById(useSelectedNode()?.id);
1384
1500
  }
1385
1501
  //#endregion
1502
+ //#region src/hooks/revision-history.ts
1503
+ /** The query param that opens the document's revision history: `?history`. */
1504
+ const REVISION_HISTORY_PARAM = "history";
1505
+ /** The history page shown, from 1 (the newest operations): `?history&historyPage=2`.
1506
+ * Its own name: a drive app or editor may page by `page`. */
1507
+ const REVISION_HISTORY_PAGE_PARAM = "historyPage";
1508
+ /** The page a `page` param names: a positive integer, else the first. */
1509
+ function parseRevisionHistoryPage(value) {
1510
+ const page = Number(value);
1511
+ return Number.isSafeInteger(page) && page > 0 ? page : 1;
1512
+ }
1513
+ /** Whether the URL opens the revision history. */
1514
+ function useRevisionHistoryVisible() {
1515
+ return useSearchParams()[REVISION_HISTORY_PARAM] !== void 0;
1516
+ }
1517
+ /** The revision history page the URL names, from 1. */
1518
+ function useRevisionHistoryPage() {
1519
+ return parseRevisionHistoryPage(useSearchParams()[REVISION_HISTORY_PAGE_PARAM]);
1520
+ }
1521
+ /** Shows the revision history: a new history entry, so Back closes it. */
1522
+ function showRevisionHistory() {
1523
+ setSearchParams((prev) => ({
1524
+ ...prev,
1525
+ [REVISION_HISTORY_PARAM]: ""
1526
+ }));
1527
+ }
1528
+ /** Hides the revision history. */
1529
+ function hideRevisionHistory() {
1530
+ setSearchParams((prev) => ({
1531
+ ...prev,
1532
+ [REVISION_HISTORY_PARAM]: void 0,
1533
+ [REVISION_HISTORY_PAGE_PARAM]: void 0
1534
+ }));
1535
+ }
1536
+ /** Opens history page `page`, from 1; Back returns to the page before. */
1537
+ function setRevisionHistoryPage(page) {
1538
+ setSearchParams((prev) => ({
1539
+ ...prev,
1540
+ [REVISION_HISTORY_PARAM]: "",
1541
+ [REVISION_HISTORY_PAGE_PARAM]: page > 1 ? String(page) : void 0
1542
+ }));
1543
+ }
1544
+ /** Shows or hides the revision history. */
1545
+ function setRevisionHistoryVisible(visible) {
1546
+ if (visible) showRevisionHistory();
1547
+ else hideRevisionHistory();
1548
+ }
1549
+ /** @deprecated The revision history is a URL param now; there is no store value to watch. */
1550
+ function addRevisionHistoryVisibleEventHandler() {}
1551
+ //#endregion
1386
1552
  //#region src/hooks/subgraph-modules.ts
1387
1553
  function useSubgraphModules() {
1388
1554
  return useVetraPackages().flatMap((pkg) => pkg.subgraphs || []);
@@ -1746,17 +1912,38 @@ const syncStatusToUI = {
1746
1912
  async function getDrives(reactor) {
1747
1913
  return (await Promise.all(DRIVE_DOCUMENT_TYPES.map((type) => reactor.find({ type })))).flatMap((r) => r.results);
1748
1914
  }
1915
+ /**
1916
+ * The id of every drive, from a listing that carries headers only: a drive's
1917
+ * node tree can be megabytes (a mail drive with tens of thousands of files),
1918
+ * so membership is learned without it and a new drive is then loaded on its
1919
+ * own.
1920
+ */
1921
+ async function listDriveIds(reactor) {
1922
+ return (await Promise.all(DRIVE_DOCUMENT_TYPES.map((type) => reactor.find({ type }, { scopes: ["header"] })))).flatMap((r) => r.results.map((d) => d.header.id));
1923
+ }
1924
+ /** One drive in full, or undefined once it is gone. */
1925
+ async function getDrive(reactor, driveId) {
1926
+ try {
1927
+ return await reactor.get(driveId);
1928
+ } catch {
1929
+ return;
1930
+ }
1931
+ }
1749
1932
  function getSyncStatus(documentId, sharingType) {
1750
1933
  return Promise.resolve(getSyncStatusSync(documentId, sharingType));
1751
1934
  }
1752
1935
  function getSyncStatusSync(documentId, sharingType) {
1753
- if (sharingType === "LOCAL") return;
1754
- const syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
1936
+ if (sharingType === "LOCAL" || typeof window === "undefined") return;
1937
+ const syncManager = getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
1755
1938
  if (!syncManager) return;
1756
1939
  const status = syncManager.getSyncStatus(documentId);
1757
1940
  if (status === void 0) return;
1758
1941
  return syncStatusToUI[status];
1759
1942
  }
1943
+ /** A drive's display name: the header's (renames set it), else its creation name. */
1944
+ function getDriveName(drive) {
1945
+ return drive.header.name || drive.state.global.name;
1946
+ }
1760
1947
  //#endregion
1761
1948
  //#region src/utils/get-revision-from-date.ts
1762
1949
  const getRevisionFromDate = (startDate, endDate, operations = []) => {
@@ -1768,184 +1955,6 @@ const getRevisionFromDate = (startDate, endDate, operations = []) => {
1768
1955
  return operation ? operation.index : 0;
1769
1956
  };
1770
1957
  //#endregion
1771
- //#region src/utils/switchboard.ts
1772
- async function getDriveIdBySlug(driveUrl, slug) {
1773
- if (!driveUrl) return;
1774
- const urlParts = driveUrl.split("/");
1775
- urlParts.pop();
1776
- urlParts.pop();
1777
- urlParts.push("drives");
1778
- const drivesUrl = urlParts.join("/");
1779
- return (await (await fetch(drivesUrl, {
1780
- method: "POST",
1781
- headers: { "Content-Type": "application/json" },
1782
- body: JSON.stringify({
1783
- query: `
1784
- query getDriveIdBySlug($slug: String!) {
1785
- driveIdBySlug(slug: $slug)
1786
- }
1787
- `,
1788
- variables: { slug }
1789
- })
1790
- })).json()).data.driveIdBySlug;
1791
- }
1792
- function getSlugFromDriveUrl(driveUrl) {
1793
- return driveUrl.split("/").pop();
1794
- }
1795
- function getSwitchboardGatewayUrlFromDriveUrl(driveUrl) {
1796
- const urlParts = driveUrl.split("/");
1797
- urlParts.pop();
1798
- urlParts.pop();
1799
- urlParts.push("graphql");
1800
- return urlParts.join("/");
1801
- }
1802
- function getDocumentGraphqlQuery() {
1803
- const loc = GetDocumentWithOperationsDocument.loc;
1804
- if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
1805
- return loc.source.body;
1806
- }
1807
- /**
1808
- * The base URL of the switchboard that serves a drive's GraphQL channel.
1809
- *
1810
- * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the
1811
- * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does
1812
- * not end with the suffix is unexpected — fall back to its origin.
1813
- */
1814
- function getSwitchboardBaseFromChannelUrl(channelUrl) {
1815
- if (channelUrl.endsWith("/graphql/r")) return channelUrl.slice(0, -GQL_CHANNEL_SUFFIX.length);
1816
- return new URL(channelUrl).origin;
1817
- }
1818
- /**
1819
- * The GraphQL name the switchboard exposes a document model under. Mirrors
1820
- * `getDocumentModelSchemaName` on the server (`create-schema.ts`): the root
1821
- * query field and the state type names are all derived from the model's
1822
- * `global.name`.
1823
- */
1824
- function getDocumentModelSchemaName(model) {
1825
- return pascalCase(model.documentModel.global.name.replaceAll("/", " "));
1826
- }
1827
- function buildStateTypeMap(definitions) {
1828
- const typeMap = /* @__PURE__ */ new Map();
1829
- for (const def of definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) typeMap.set(def.name.value, def);
1830
- return typeMap;
1831
- }
1832
- /**
1833
- * Recursively expands the fields of a state object type into a GraphQL
1834
- * selection. Objects expand their sub-selection (lists expand their item
1835
- * type); enums, scalars, and built-ins are leaves.
1836
- */
1837
- function expandStateFields(typeDef, typeMap) {
1838
- return (typeDef.fields ?? []).map((field) => {
1839
- const fieldName = field.name.value;
1840
- let typeNode = field.type;
1841
- if (typeNode.kind === Kind.NON_NULL_TYPE) typeNode = typeNode.type;
1842
- if (typeNode.kind === Kind.LIST_TYPE) {
1843
- let itemType = typeNode.type;
1844
- if (itemType.kind === Kind.NON_NULL_TYPE) itemType = itemType.type;
1845
- if (itemType.kind === Kind.LIST_TYPE) throw new Error(`Nested lists are not supported in state selections: ${fieldName}`);
1846
- if (itemType.kind !== Kind.NAMED_TYPE) return fieldName;
1847
- const itemTypeDef = typeMap.get(itemType.name.value);
1848
- if (!itemTypeDef) return fieldName;
1849
- return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;
1850
- }
1851
- if (typeNode.kind !== Kind.NAMED_TYPE) return fieldName;
1852
- const typeDef = typeMap.get(typeNode.name.value);
1853
- if (!typeDef) return fieldName;
1854
- return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;
1855
- }).join(" ");
1856
- }
1857
- /**
1858
- * Finds the root state object type in a state SDL. Root state types follow
1859
- * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last
1860
- * by convention — the same resolution order the server uses
1861
- * (`extractRootTypeName` in `create-schema.ts`).
1862
- */
1863
- function findRootStateType(definitions, candidates) {
1864
- let lastObjectType = null;
1865
- for (const def of definitions) {
1866
- if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
1867
- if (candidates.includes(def.name.value)) return def;
1868
- lastObjectType = def;
1869
- }
1870
- if (!lastObjectType) throw new Error("No root state type found in the document model schema");
1871
- return lastObjectType;
1872
- }
1873
- /**
1874
- * Derives the subselection for the document's `global` state scope from the
1875
- * model's state SDL (e.g. `name total`), expanding object fields
1876
- * recursively. Throws when the schema is missing, unparseable, or has no
1877
- * root object type — the caller falls back to the generic document query.
1878
- */
1879
- function getDocumentStateSelection(model) {
1880
- const schema = model.documentModel.global.specifications.at(-1)?.state.global.schema;
1881
- if (!schema || !schema.trim()) throw new Error("Document model has no global state schema");
1882
- const ast = parse(schema);
1883
- const typeMap = buildStateTypeMap(ast.definitions);
1884
- const documentName = getDocumentModelSchemaName(model);
1885
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}State`, `${documentName}GlobalState`]), typeMap);
1886
- }
1887
- function getLocalStateSelection(localSchema, documentName) {
1888
- const ast = parse(localSchema);
1889
- const typeMap = buildStateTypeMap(ast.definitions);
1890
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}LocalState`]), typeMap);
1891
- }
1892
- /**
1893
- * Builds a query scoped to a document type's own subgraph root field,
1894
- * selecting the document and its full typed state. The shape mirrors what
1895
- * the switchboard generates per model (`generateNewApiSchema` in
1896
- * `create-schema.ts`): `<Name> { document(identifier:) { document { ...
1897
- * state { auth document global local } } } childIds }`.
1898
- */
1899
- function buildModelScopedQuery(model) {
1900
- const globalState = model.documentModel.global;
1901
- const documentName = getDocumentModelSchemaName(model);
1902
- const globalSelection = getDocumentStateSelection(model);
1903
- const localSchema = globalState.specifications.at(-1)?.state.local.schema ?? "";
1904
- const localSelection = localSchema.includes(`type ${documentName}LocalState`) ? getLocalStateSelection(localSchema, documentName) : null;
1905
- return [
1906
- "query GetDocument($identifier: String!) {",
1907
- ` ${documentName} {`,
1908
- " document(identifier: $identifier) {",
1909
- " document {",
1910
- " id",
1911
- " name",
1912
- " documentType",
1913
- " state {",
1914
- " auth",
1915
- " document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }",
1916
- ` global { ${globalSelection} }`,
1917
- ` ${localSelection ? `local { ${localSelection} }` : "local"}`,
1918
- " }",
1919
- " }",
1920
- " childIds",
1921
- " }",
1922
- " }",
1923
- "}"
1924
- ].join("\n");
1925
- }
1926
- function buildDocumentSubgraphQuery(documentType, identifier, model, authToken) {
1927
- let query;
1928
- if (model && model.documentModel.global.id === documentType) try {
1929
- query = buildModelScopedQuery(model);
1930
- } catch (error) {
1931
- console.warn("Could not derive a document-scoped query from the document model, falling back to the generic document query:", error);
1932
- query = getDocumentGraphqlQuery();
1933
- }
1934
- else query = getDocumentGraphqlQuery();
1935
- const variables = { identifier };
1936
- const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
1937
- const payload = {
1938
- document: query.trim(),
1939
- variables: JSON.stringify(variables, null, 2)
1940
- };
1941
- if (headers) payload.headers = JSON.stringify(headers);
1942
- return lzString.compressToEncodedURIComponent(JSON.stringify(payload));
1943
- }
1944
- function buildDocumentSubgraphUrl(channelUrl, documentType, identifier, model, authToken) {
1945
- const encodedQuery = buildDocumentSubgraphQuery(documentType, identifier, model, authToken);
1946
- return `${getSwitchboardBaseFromChannelUrl(channelUrl)}/explorer?explorerURLState=${encodedQuery}`;
1947
- }
1948
- //#endregion
1949
1958
  //#region src/utils/upgrade-preview.ts
1950
1959
  const NON_DOMAIN_SCOPES = /* @__PURE__ */ new Set(["auth", "document"]);
1951
1960
  function isPlainObject(value) {
@@ -2139,6 +2148,19 @@ function useUserPermissions() {
2139
2148
  };
2140
2149
  }
2141
2150
  //#endregion
2151
+ //#region src/hooks/close-node.ts
2152
+ /** Leaves a node's view: back to the entry it was opened from, past entries
2153
+ * pushed inside it; else, e.g. after a deep link, to its parent in place. */
2154
+ function useCloseNode(nodeId) {
2155
+ const navigation = usePHNavigation();
2156
+ const setSelectedNode = useSetSelectedNode();
2157
+ const parentFolder = useNodeParentFolderById(nodeId);
2158
+ return () => {
2159
+ if (navigation.closeOpened?.()) return;
2160
+ setSelectedNode(parentFolder, { replace: true });
2161
+ };
2162
+ }
2163
+ //#endregion
2142
2164
  //#region src/hooks/attachment-progress.ts
2143
2165
  const IDLE_PROGRESS = {
2144
2166
  percent: 0,
@@ -2234,6 +2256,11 @@ function useAttachments() {
2234
2256
  const service = useAttachmentService();
2235
2257
  return service ? clientFor(service) : void 0;
2236
2258
  }
2259
+ /** The client {@link useAttachments} returns, for code outside React. */
2260
+ function getAttachmentClient() {
2261
+ const service = getPHStore()?.attachmentService;
2262
+ return service ? clientFor(service) : void 0;
2263
+ }
2237
2264
  const DEFAULT_PREVIEW_RETRIES = 3;
2238
2265
  const DEFAULT_PREVIEW_RETRY_DELAY_MS = 3e3;
2239
2266
  const IDLE_PREVIEW = {
@@ -2381,7 +2408,7 @@ function useAttachmentUpload() {
2381
2408
  };
2382
2409
  }, []);
2383
2410
  return {
2384
- preprocess: useCallback(async (file) => {
2411
+ preprocess: useCallback(async (file, options) => {
2385
2412
  if (!client) throw new Error("AttachmentClient not available");
2386
2413
  const runId = ++runIdRef.current;
2387
2414
  setState({
@@ -2389,7 +2416,7 @@ function useAttachmentUpload() {
2389
2416
  stage: "hashing"
2390
2417
  });
2391
2418
  try {
2392
- return await client.preprocess(file);
2419
+ return await client.preprocess(file, options);
2393
2420
  } catch (err) {
2394
2421
  const error = err instanceof Error ? err : new Error(String(err));
2395
2422
  if (mountedRef.current && runId === runIdRef.current) setState((prev) => ({
@@ -2536,6 +2563,331 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
2536
2563
  }
2537
2564
  const refreshReactorData = createDebouncedRefreshReactorData();
2538
2565
  const refreshReactorDataClient = createDebouncedRefreshReactorDataClient();
2566
+ /** How often one drive is re-read while it keeps changing (a drive being filled). */
2567
+ const DEFAULT_DRIVE_REFRESH_MIN_INTERVAL_MS = 1e4;
2568
+ function currentDrives() {
2569
+ return getPHStore()?.drives;
2570
+ }
2571
+ /**
2572
+ * Re-reads one drive and replaces it in the drives store. Only that drive
2573
+ * crosses the wire: the list used to be re-fetched whole on any drive change,
2574
+ * every drive's node tree included, which on a large mail drive was ten
2575
+ * megabytes per change. Without a store (before init) the whole list loads.
2576
+ */
2577
+ async function refreshDrive(reactor, driveId) {
2578
+ const drives = currentDrives();
2579
+ if (!drives) return _refreshReactorDataClient(reactor);
2580
+ const fresh = await getDrive(reactor, driveId);
2581
+ if (!fresh) {
2582
+ setDrives(drives.filter((d) => d.header.id !== driveId));
2583
+ return;
2584
+ }
2585
+ const at = drives.findIndex((d) => d.header.id === driveId);
2586
+ setDrives(at < 0 ? [...drives, fresh] : drives.map((d, i) => i === at ? fresh : d));
2587
+ }
2588
+ /**
2589
+ * Brings the drives store in line with which drives exist: ids come from a
2590
+ * headers-only listing, a drive not held yet is loaded on its own, and a drive
2591
+ * no longer listed is dropped. Drives already held are kept as they are.
2592
+ */
2593
+ async function refreshDriveMembership(reactor) {
2594
+ const drives = currentDrives();
2595
+ if (!drives) return _refreshReactorDataClient(reactor);
2596
+ const ids = await listDriveIds(reactor);
2597
+ const known = new Map(drives.map((d) => [d.header.id, d]));
2598
+ const added = await Promise.all(ids.filter((id) => !known.has(id)).map((id) => getDrive(reactor, id)));
2599
+ const loaded = new Map(added.filter((d) => d !== void 0).map((d) => [d.header.id, d]));
2600
+ setDrives(ids.map((id) => known.get(id) ?? loaded.get(id)).filter((d) => d !== void 0));
2601
+ }
2602
+ /**
2603
+ * Routes a drive-type document change to the smallest refresh: an update
2604
+ * re-reads that one drive and invalidates its node cache, at most once per
2605
+ * `minIntervalMs` while it keeps changing (at once after a write from this
2606
+ * tab, see `markLocalDriveWrite`); a creation or deletion refreshes the
2607
+ * membership and loads only what is new.
2608
+ */
2609
+ function createDriveChangeHandler(reactor, options = {}) {
2610
+ const minIntervalMs = options.minIntervalMs ?? DEFAULT_DRIVE_REFRESH_MIN_INTERVAL_MS;
2611
+ const onError = options.onError ?? (() => void 0);
2612
+ const lastAt = /* @__PURE__ */ new Map();
2613
+ const pending = /* @__PURE__ */ new Map();
2614
+ const run = (driveId) => {
2615
+ lastAt.set(driveId, Date.now());
2616
+ const timer = pending.get(driveId);
2617
+ if (timer !== void 0) clearTimeout(timer);
2618
+ pending.delete(driveId);
2619
+ refreshDrive(reactor, driveId).then(() => invalidateDriveNodes(driveId)).catch(onError);
2620
+ };
2621
+ const schedule = (driveId) => {
2622
+ if (takeLocalDriveWrite(driveId)) {
2623
+ run(driveId);
2624
+ return;
2625
+ }
2626
+ if (pending.has(driveId)) return;
2627
+ const wait = (lastAt.get(driveId) ?? 0) + minIntervalMs - Date.now();
2628
+ if (wait <= 0) {
2629
+ run(driveId);
2630
+ return;
2631
+ }
2632
+ pending.set(driveId, setTimeout(() => run(driveId), wait));
2633
+ };
2634
+ return (event) => {
2635
+ if (event.type === DOCUMENT_CHANGE_TYPE.Updated) {
2636
+ for (const document of event.documents) schedule(document.header.id);
2637
+ return;
2638
+ }
2639
+ refreshDriveMembership(reactor).catch(onError);
2640
+ };
2641
+ }
2642
+ //#endregion
2643
+ //#region src/routing/drive-arrivals.ts
2644
+ let pendingAdds = 0;
2645
+ const addListeners = /* @__PURE__ */ new Set();
2646
+ function notifyAdds() {
2647
+ for (const listener of [...addListeners]) listener();
2648
+ }
2649
+ /** Counts a background drive addition as pending until it settles. */
2650
+ function trackDriveArrival(promise) {
2651
+ pendingAdds++;
2652
+ notifyAdds();
2653
+ return promise.finally(() => {
2654
+ pendingAdds--;
2655
+ notifyAdds();
2656
+ });
2657
+ }
2658
+ /** Resolves once `store.drives` lists `driveId`, or after `maxWaitMs`: a
2659
+ * finished first pull does not mean the drive is listed yet. */
2660
+ function untilDriveListed(store, driveId, maxWaitMs = 15e3) {
2661
+ const listed = () => !!store.drives?.some((d) => d.header.id === driveId);
2662
+ if (listed()) return Promise.resolve();
2663
+ return new Promise((resolve) => {
2664
+ const finish = () => {
2665
+ clearTimeout(timer);
2666
+ unsubscribe();
2667
+ resolve();
2668
+ };
2669
+ const timer = setTimeout(finish, maxWaitMs);
2670
+ const unsubscribe = subscribePHStore(store, () => {
2671
+ if (listed()) finish();
2672
+ }, "drives");
2673
+ });
2674
+ }
2675
+ const REMOTE_EVENTS = [SyncEventTypes.CONNECTION_STATE_CHANGED, SYNC_REMOTES_CHANGED_EVENT];
2676
+ /** Drives still on their way into `store`: being added or first syncing. */
2677
+ function createDriveArrivals(store) {
2678
+ return {
2679
+ isPending: () => store.drives === void 0 || pendingAdds > 0 || isInitialSyncInFlight(store),
2680
+ isDrivePending: (driveId) => isInitialSyncInFlight(store, driveId),
2681
+ subscribe(listener) {
2682
+ const watched = /* @__PURE__ */ new Map();
2683
+ const listenToRemotes = () => {
2684
+ const channels = /* @__PURE__ */ new Set();
2685
+ for (const { channel } of listSyncRemotes(store)) {
2686
+ channels.add(channel);
2687
+ if (watched.has(channel)) continue;
2688
+ try {
2689
+ watched.set(channel, channel.onConnectionStateChange(listener));
2690
+ } catch {
2691
+ watched.set(channel, () => {});
2692
+ }
2693
+ }
2694
+ for (const [channel, unsubscribe] of watched) {
2695
+ if (channels.has(channel)) continue;
2696
+ unsubscribe();
2697
+ watched.delete(channel);
2698
+ }
2699
+ };
2700
+ const onChange = () => {
2701
+ listenToRemotes();
2702
+ listener();
2703
+ };
2704
+ let unsubscribeBus = [];
2705
+ const listenToBus = () => {
2706
+ for (const unsubscribe of unsubscribeBus) unsubscribe();
2707
+ const bus = store.reactorClientModule?.reactorModule?.eventBus;
2708
+ unsubscribeBus = bus ? REMOTE_EVENTS.map((type) => bus.subscribe(type, onChange)) : [];
2709
+ };
2710
+ const onModuleChange = () => {
2711
+ listenToBus();
2712
+ onChange();
2713
+ };
2714
+ listenToRemotes();
2715
+ listenToBus();
2716
+ addListeners.add(onChange);
2717
+ const unsubscribes = [subscribePHStore(store, onChange, "drives"), subscribePHStore(store, onModuleChange, "reactorClientModule")];
2718
+ return () => {
2719
+ addListeners.delete(onChange);
2720
+ for (const unsubscribe of unsubscribes) unsubscribe();
2721
+ for (const unsubscribe of unsubscribeBus) unsubscribe();
2722
+ for (const unsubscribe of watched.values()) unsubscribe();
2723
+ watched.clear();
2724
+ };
2725
+ }
2726
+ };
2727
+ }
2728
+ //#endregion
2729
+ //#region src/routing/resolve-drive-route.ts
2730
+ /** How long a navigation waits for its document and editor before it shows;
2731
+ * past it the view commits and renders them as they load. */
2732
+ const PREFETCH_WAIT_MS = 3e3;
2733
+ const DRIVE_ARRIVAL_MAX_WAIT_MS = 15e3;
2734
+ /** A listed drive by slug, id, or a `<name>-<id>` slug's trailing id. */
2735
+ function findDriveBySlugOrId(store, ref) {
2736
+ return findDriveBySlug(store.drives, ref);
2737
+ }
2738
+ async function findNode(store, driveId, nodeId) {
2739
+ const cached = peekDriveNode(driveId, nodeId, store);
2740
+ if (cached) return cached;
2741
+ try {
2742
+ return await getDriveNode(driveId, nodeId, {
2743
+ store,
2744
+ refresh: true
2745
+ });
2746
+ } catch {
2747
+ return;
2748
+ }
2749
+ }
2750
+ async function findNodeBySlug(store, driveId, slug) {
2751
+ try {
2752
+ return (await loadDriveNodes(driveId, { store })).find((n) => n.id === slug || makeNodeSlug(n) === slug);
2753
+ } catch {
2754
+ return;
2755
+ }
2756
+ }
2757
+ /** `waitForArrival` for an async read, re-run on each arrival. */
2758
+ function waitForNodeArrival(read, arrivals, signal, maxWaitMs = DRIVE_ARRIVAL_MAX_WAIT_MS) {
2759
+ if (!arrivals?.isPending() || signal.aborted) return Promise.resolve(void 0);
2760
+ return new Promise((resolve) => {
2761
+ let settled = false;
2762
+ let unsubscribe = () => {};
2763
+ const finish = (result) => {
2764
+ if (settled) return;
2765
+ settled = true;
2766
+ clearTimeout(timer);
2767
+ unsubscribe();
2768
+ signal.removeEventListener("abort", onAbort);
2769
+ resolve(result);
2770
+ };
2771
+ const onAbort = () => finish(void 0);
2772
+ const timer = setTimeout(onAbort, maxWaitMs);
2773
+ signal.addEventListener("abort", onAbort, { once: true });
2774
+ unsubscribe = arrivals.subscribe(() => {
2775
+ read().then((next) => {
2776
+ if (next !== void 0 || !arrivals.isPending()) finish(next);
2777
+ });
2778
+ });
2779
+ });
2780
+ }
2781
+ /** Resolves with `read()` once it is defined, nothing is still arriving, the
2782
+ * signal aborts or the cap passes. */
2783
+ function waitForArrival(read, arrivals, signal, maxWaitMs = DRIVE_ARRIVAL_MAX_WAIT_MS) {
2784
+ const value = read();
2785
+ if (value !== void 0 || !arrivals?.isPending() || signal.aborted) return Promise.resolve(value);
2786
+ return new Promise((resolve) => {
2787
+ let unsubscribe = () => {};
2788
+ const finish = (result) => {
2789
+ clearTimeout(timer);
2790
+ unsubscribe();
2791
+ signal.removeEventListener("abort", onAbort);
2792
+ resolve(result);
2793
+ };
2794
+ const onAbort = () => finish(void 0);
2795
+ const timer = setTimeout(onAbort, maxWaitMs);
2796
+ signal.addEventListener("abort", onAbort, { once: true });
2797
+ unsubscribe = arrivals.subscribe(() => {
2798
+ const next = read();
2799
+ if (next !== void 0 || !arrivals.isPending()) finish(next);
2800
+ });
2801
+ });
2802
+ }
2803
+ /** Asks the reactor directly: a just-created drive may not be listed yet. */
2804
+ async function fetchDrive(store, ref, signal) {
2805
+ try {
2806
+ const document = await store.reactorClient?.get(ref, void 0, signal);
2807
+ return DRIVE_DOCUMENT_TYPES.includes(document?.header.documentType ?? "") ? document : void 0;
2808
+ } catch {
2809
+ return;
2810
+ }
2811
+ }
2812
+ function editorModules(store) {
2813
+ return store.vetraPackageManager?.packages.flatMap((pkg) => pkg.editors) ?? [];
2814
+ }
2815
+ async function preloadModule(module) {
2816
+ try {
2817
+ await (module ? preloadEditorModule(module) : void 0);
2818
+ } catch {}
2819
+ }
2820
+ function documentEditor(store, document) {
2821
+ const { documentType, meta } = document.header;
2822
+ const modules = editorModules(store);
2823
+ return modules.find((module) => module.config.id === meta?.preferredEditor) ?? modules.find((module) => module.documentTypes.includes(documentType));
2824
+ }
2825
+ function driveApp(store, drive) {
2826
+ const id = drive.header.meta?.preferredEditor ?? "powerhouse/generic-drive-explorer";
2827
+ return editorModules(store).find((module) => module.config.id === id);
2828
+ }
2829
+ /** Loads a drive's app module so its view renders without suspending;
2830
+ * undefined when it is already loaded, so a warm open waits on nothing. */
2831
+ function preloadDriveApp(store, drive) {
2832
+ const module = driveApp(store, drive);
2833
+ return module && preloadEditorModule(module)?.then(noop, noop);
2834
+ }
2835
+ const noop = () => void 0;
2836
+ /** Warms a file node's document and its editor module. */
2837
+ async function prefetchDocument(store, node) {
2838
+ if (!isFileNode(node)) return;
2839
+ try {
2840
+ const document = await store.documentCache?.get(node.id);
2841
+ if (document) await preloadModule(documentEditor(store, document));
2842
+ } catch {}
2843
+ }
2844
+ /** Resolves once `work` settles, `ms` pass or `signal` aborts. */
2845
+ function settleWithin(work, ms, signal) {
2846
+ if (signal.aborted) return Promise.resolve();
2847
+ return new Promise((resolve) => {
2848
+ const done = () => {
2849
+ clearTimeout(timer);
2850
+ signal.removeEventListener("abort", done);
2851
+ resolve();
2852
+ };
2853
+ const timer = setTimeout(done, ms);
2854
+ signal.addEventListener("abort", done, { once: true });
2855
+ work.then(done, done);
2856
+ });
2857
+ }
2858
+ /** Resolves a drive route's slugs, waiting for drives that are still syncing,
2859
+ * and warms what the resolved view needs. */
2860
+ async function resolveDriveRoute(options) {
2861
+ const { store, driveSlug, nodeSlug, signal } = options;
2862
+ const arrivals = options.preload ? void 0 : options.arrivals;
2863
+ const drive = await waitForArrival(() => findDriveBySlugOrId(store, driveSlug), arrivals, signal) ?? await fetchDrive(store, extractDriveIdFromSlug(driveSlug) ?? driveSlug, signal);
2864
+ if (!drive) return { kind: "drive-not-found" };
2865
+ const driveId = drive.header.id;
2866
+ const appPreload = preloadDriveApp(store, drive);
2867
+ if (!nodeSlug) {
2868
+ if (appPreload) await settleWithin(appPreload, PREFETCH_WAIT_MS, signal);
2869
+ return {
2870
+ kind: "drive",
2871
+ driveId
2872
+ };
2873
+ }
2874
+ const nodeId = extractNodeIdFromSlug(nodeSlug) ?? (await findNodeBySlug(store, driveId, nodeSlug))?.id;
2875
+ const driveArrivals = arrivals && {
2876
+ ...arrivals,
2877
+ isPending: () => arrivals.isDrivePending(driveId)
2878
+ };
2879
+ const node = nodeId ? await findNode(store, driveId, nodeId) ?? await waitForNodeArrival(() => findNode(store, driveId, nodeId), driveArrivals, signal) : void 0;
2880
+ if (!node) return {
2881
+ kind: "node-not-found",
2882
+ driveId
2883
+ };
2884
+ await settleWithin(Promise.all([appPreload, prefetchDocument(store, node)]), PREFETCH_WAIT_MS, signal);
2885
+ return {
2886
+ kind: "drive",
2887
+ driveId,
2888
+ nodeId: node.id
2889
+ };
2890
+ }
2539
2891
  //#endregion
2540
2892
  //#region src/remote-controller/action-tracker.ts
2541
2893
  /**
@@ -2587,7 +2939,7 @@ var RemoteClient = class {
2587
2939
  /** Fetch a document by identifier. Returns null if not found. */
2588
2940
  async getDocument(identifier, branch) {
2589
2941
  return (await this.client.GetDocument({
2590
- identifier,
2942
+ idOrSlug: identifier,
2591
2943
  view: branch ? { branch } : void 0
2592
2944
  })).document ?? null;
2593
2945
  }
@@ -2602,7 +2954,7 @@ var RemoteClient = class {
2602
2954
  async getDocumentWithOperations(identifier, branch, sinceRevision, scopes) {
2603
2955
  if (this.client.BatchGetDocumentWithOperations && scopes && scopes.length > 0) return this.batchGetDocumentWithOperations(identifier, branch, sinceRevision, scopes);
2604
2956
  const result = await this.client.GetDocumentWithOperations({
2605
- identifier,
2957
+ idOrSlug: identifier,
2606
2958
  view: branch ? { branch } : void 0,
2607
2959
  operationsPaging: {
2608
2960
  limit: this.pageSize,
@@ -2635,7 +2987,7 @@ var RemoteClient = class {
2635
2987
  async batchGetDocumentWithOperations(identifier, branch, sinceRevision, scopes) {
2636
2988
  const view = branch ? { branch } : void 0;
2637
2989
  const filters = scopes.map((scope) => ({
2638
- documentId: identifier,
2990
+ documentIdOrSlug: identifier,
2639
2991
  branch: branch ?? null,
2640
2992
  sinceRevision: sinceRevision?.[scope] ?? 0,
2641
2993
  scopes: [scope]
@@ -2690,7 +3042,7 @@ var RemoteClient = class {
2690
3042
  let pending = scopes.map((scope) => ({
2691
3043
  scope,
2692
3044
  filter: {
2693
- documentId,
3045
+ documentIdOrSlug: documentId,
2694
3046
  branch: branch ?? null,
2695
3047
  sinceRevision: sinceRevision?.[scope] ?? 0,
2696
3048
  scopes: [scope]
@@ -2737,7 +3089,7 @@ var RemoteClient = class {
2737
3089
  while (hasNextPage) {
2738
3090
  const page = (await this.client.GetDocumentOperations({
2739
3091
  filter: {
2740
- documentId,
3092
+ documentIdOrSlug: documentId,
2741
3093
  branch: branch ?? null,
2742
3094
  sinceRevision: sinceRevision ?? 0,
2743
3095
  scopes: scope ? [scope] : null
@@ -2765,7 +3117,7 @@ var RemoteClient = class {
2765
3117
  */
2766
3118
  async pushActions(documentIdentifier, actions, branch) {
2767
3119
  return (await this.client.MutateDocument({
2768
- documentIdentifier,
3120
+ documentIdOrSlug: documentIdentifier,
2769
3121
  actions,
2770
3122
  branch
2771
3123
  })).mutateDocument;
@@ -2774,20 +3126,20 @@ var RemoteClient = class {
2774
3126
  async createDocument(document, parentIdentifier) {
2775
3127
  return (await this.client.CreateDocument({
2776
3128
  document,
2777
- parentIdentifier: parentIdentifier ?? null
3129
+ parentIdOrSlug: parentIdentifier ?? null
2778
3130
  })).createDocument;
2779
3131
  }
2780
3132
  /** Create an empty document of a given type on the remote. */
2781
3133
  async createEmptyDocument(documentType, parentIdentifier) {
2782
3134
  return (await this.client.CreateEmptyDocument({
2783
3135
  documentType,
2784
- parentIdentifier: parentIdentifier ?? null
3136
+ parentIdOrSlug: parentIdentifier ?? null
2785
3137
  })).createEmptyDocument;
2786
3138
  }
2787
3139
  /** Delete a document on the remote. Returns true if successful. */
2788
3140
  async deleteDocument(identifier, propagate) {
2789
3141
  return (await this.client.DeleteDocument({
2790
- identifier,
3142
+ idOrSlug: identifier,
2791
3143
  propagate
2792
3144
  })).deleteDocument;
2793
3145
  }
@@ -2807,6 +3159,10 @@ var RemoteDocumentController = class RemoteDocumentController {
2807
3159
  /** The remote's id for the document; `documentId` may be a slug. */
2808
3160
  canonicalDocumentId;
2809
3161
  remoteRevision = {};
3162
+ /** What the first push creates the remote from, until it has. */
3163
+ uncreated;
3164
+ /** A wrapped new document takes the host's signature policy at its first push. */
3165
+ takesHostPolicy = false;
2810
3166
  hasPulled = false;
2811
3167
  pushScheduled = false;
2812
3168
  pushQueue = Promise.resolve();
@@ -2815,6 +3171,7 @@ var RemoteDocumentController = class RemoteDocumentController {
2815
3171
  this.inner = inner;
2816
3172
  this.options = options;
2817
3173
  this.documentId = options.documentId ?? "";
3174
+ if (this.documentId === "") this.uncreated = uncreatedDocument(inner.document);
2818
3175
  this.remoteClient = new RemoteClient(options.client, options.operationsPageSize);
2819
3176
  this.setupActionInterceptors();
2820
3177
  }
@@ -2898,37 +3255,112 @@ var RemoteDocumentController = class RemoteDocumentController {
2898
3255
  this.canonicalDocumentId = remoteDoc.id;
2899
3256
  const initialDoc = this.inner.module.utils.createDocument();
2900
3257
  const pulledDocument = buildPulledDocument(remoteDoc, operations, initialDoc, this.options.branch ?? "main");
2901
- const ControllerClass = this.inner.constructor;
2902
- this.inner = new ControllerClass(pulledDocument);
2903
- this.setupActionInterceptors();
3258
+ this.replaceInner(pulledDocument);
2904
3259
  this.tracker.clear();
2905
3260
  this.remoteRevision = extractRevisionMap(remoteDoc.revisionsList);
2906
3261
  this.notifyListeners("pull");
2907
3262
  return remoteDoc;
2908
3263
  }
2909
3264
  /**
3265
+ * Undoes the last `count` operations of `scope`. Below base-reducer 3 (or
3266
+ * with no version) it applies the model's UNDO, as the action method did; on
3267
+ * 3, or an unknown number run as 3, it applies a RETRACT per step, each
3268
+ * resolved from this controller's own log, pending actions included.
3269
+ */
3270
+ undo(count = 1, scope = "global") {
3271
+ return this.undoOrRedo("UNDO", count, scope);
3272
+ }
3273
+ /** Redoes the last `count` undos of `scope`; see {@link undo}. */
3274
+ redo(count = 1, scope = "global") {
3275
+ return this.undoOrRedo("REDO", count, scope);
3276
+ }
3277
+ undoOrRedo(type, count, scope) {
3278
+ const caps = undoCapabilitiesOf(this.inner.header);
3279
+ if (caps === void 0 || !undoNeedsTargets(caps)) return this.applyAction(type === "UNDO" ? undo(count, scope) : redo(count, scope));
3280
+ if (!Number.isInteger(count) || count < 1) throw new RangeError(`${type} count must be a positive integer on base-reducer 3, got ${count}`);
3281
+ const stateReducer = this.stateReducer();
3282
+ const actions = [];
3283
+ let scratch = this.inner.document;
3284
+ for (let step = 0; step < count; step++) {
3285
+ const targets = undoRedoTargetsOf(scratch, caps, scope, stateReducer);
3286
+ for (const action of undoRedoActions(caps, type, scope, targets)) {
3287
+ scratch = this.inner.module.reducer(scratch, action);
3288
+ actions.push(action);
3289
+ }
3290
+ }
3291
+ for (const action of actions) this.applyAction(action);
3292
+ return this;
3293
+ }
3294
+ stateReducer() {
3295
+ const reducer = stateReducerOf(this.inner.module.reducer);
3296
+ if (reducer === void 0) throw new Error(`Document model ${this.inner.header.documentType} has no state reducer to resolve undo targets with`);
3297
+ return reducer;
3298
+ }
3299
+ /**
2910
3300
  * Pull an existing document from remote and create a controller for it.
2911
3301
  */
2912
3302
  static async pull(ControllerClass, options) {
2913
3303
  const temp = new ControllerClass();
2914
3304
  const remote = new RemoteDocumentController(temp, options);
2915
3305
  if (options.documentId) await remote.pull();
3306
+ else await remote.headNewDocument();
2916
3307
  return remote;
2917
3308
  }
2918
3309
  /**
2919
3310
  * Wrap an existing controller instance with remote capabilities.
2920
3311
  * Pending local actions on the inner controller are NOT tracked
2921
3312
  * (only new actions through the remote controller are tracked).
3313
+ * Without a `documentId`, the first push creates the remote from the
3314
+ * wrapped document's header, under the host's create signature policy.
2922
3315
  */
2923
3316
  static from(controller, options) {
2924
- return new RemoteDocumentController(controller, options);
3317
+ const remote = new RemoteDocumentController(controller, options);
3318
+ remote.takesHostPolicy = remote.documentId === "";
3319
+ return remote;
2925
3320
  }
2926
- /** Create the document on the remote if it doesn't exist yet. */
3321
+ /** Heads the new document with the host's versions for its type, as `newDocument` does; a host without `createDefaults` creates it with `createEmptyDocument`. */
3322
+ async headNewDocument() {
3323
+ const module = this.inner.module;
3324
+ let policy;
3325
+ let versions;
3326
+ try {
3327
+ [policy, versions] = await Promise.all([readCreateSignaturePolicy(this.options.client), readCreateProtocolVersions(this.options.client, {
3328
+ documentType: this.inner.header.documentType,
3329
+ parentIdentifier: this.options.parentIdentifier
3330
+ }, [module])]);
3331
+ } catch (error) {
3332
+ if (!GraphQLOperationNotSupportedError.isError(error)) throw error;
3333
+ this.uncreated = void 0;
3334
+ return;
3335
+ }
3336
+ const document = headNewDocument(module, void 0, policy, versions);
3337
+ this.uncreated = structuredClone(document);
3338
+ this.replaceInner(document);
3339
+ }
3340
+ /** Creates the remote from the local header, so both run the versions its creator chose. */
2927
3341
  async ensureRemoteDocument() {
2928
3342
  if (this.documentId !== "") return;
2929
- const remoteDoc = await this.remoteClient.createEmptyDocument(this.inner.header.documentType, this.options.parentIdentifier);
3343
+ if (this.takesHostPolicy) {
3344
+ await this.takeHostSignaturePolicy();
3345
+ this.takesHostPolicy = false;
3346
+ }
3347
+ const remoteDoc = this.uncreated === void 0 ? await this.remoteClient.createEmptyDocument(this.inner.header.documentType, this.options.parentIdentifier) : await this.remoteClient.createDocument(this.uncreated, this.options.parentIdentifier);
2930
3348
  this.documentId = remoteDoc.id;
2931
3349
  this.canonicalDocumentId = remoteDoc.id;
3350
+ this.uncreated = void 0;
3351
+ }
3352
+ /** Puts the uncreated document under the host's policy; a host without `createDefaults` creates it with `createEmptyDocument`. */
3353
+ async takeHostSignaturePolicy() {
3354
+ if (this.uncreated === void 0) return;
3355
+ let policy;
3356
+ try {
3357
+ policy = await readCreateSignaturePolicy(this.options.client);
3358
+ } catch (error) {
3359
+ if (!GraphQLOperationNotSupportedError.isError(error)) throw error;
3360
+ this.uncreated = void 0;
3361
+ return;
3362
+ }
3363
+ this.uncreated = underSignaturePolicy(this.uncreated, policy);
2932
3364
  }
2933
3365
  /** Set up interceptors for all action methods on the inner controller. */
2934
3366
  setupActionInterceptors() {
@@ -2936,25 +3368,45 @@ var RemoteDocumentController = class RemoteDocumentController {
2936
3368
  for (const actionType in module.actions) {
2937
3369
  if (actionType in RemoteDocumentController.prototype) continue;
2938
3370
  Object.defineProperty(this, actionType, {
2939
- value: (input) => {
2940
- const opCountsBefore = {};
2941
- for (const scope in this.inner.operations) opCountsBefore[scope] = this.inner.operations[scope].length;
2942
- this.inner[actionType](input);
2943
- const newOp = this.findNewOperation(opCountsBefore);
2944
- const prevOp = newOp ? this.getLastOperationInScope(newOp.action.scope, newOp) : void 0;
2945
- const prevOpHash = prevOp?.hash ?? "";
2946
- const prevOpIndex = prevOp?.index ?? -1;
2947
- if (!newOp) return this;
2948
- this.tracker.track(newOp.action, prevOpHash, prevOpIndex);
2949
- this.notifyListeners("action");
2950
- if (this.options.mode === "streaming") this.schedulePush();
2951
- return this;
2952
- },
3371
+ value: (input) => this.dispatchModelAction(actionType, input),
2953
3372
  enumerable: true,
2954
3373
  configurable: true
2955
3374
  });
2956
3375
  }
2957
3376
  }
3377
+ /** Applies the model's `actionType` action method locally and tracks it. */
3378
+ dispatchModelAction(actionType, input) {
3379
+ return this.applyAndTrack(() => {
3380
+ this.inner[actionType](input);
3381
+ });
3382
+ }
3383
+ /** Applies `action` locally through the model's reducer and tracks it. */
3384
+ applyAction(action) {
3385
+ return this.applyAndTrack(() => {
3386
+ this.replaceInner(this.inner.module.reducer(this.inner.document, action));
3387
+ });
3388
+ }
3389
+ /** Runs `apply`, then tracks the operation it added for push. */
3390
+ applyAndTrack(apply) {
3391
+ const opCountsBefore = {};
3392
+ for (const scope in this.inner.operations) opCountsBefore[scope] = this.inner.operations[scope].length;
3393
+ apply();
3394
+ const newOp = this.findNewOperation(opCountsBefore);
3395
+ const prevOp = newOp ? this.getLastOperationInScope(newOp.action.scope, newOp) : void 0;
3396
+ const prevOpHash = prevOp?.hash ?? "";
3397
+ const prevOpIndex = prevOp?.index ?? -1;
3398
+ if (!newOp) return this;
3399
+ this.tracker.track(newOp.action, prevOpHash, prevOpIndex);
3400
+ this.notifyListeners("action");
3401
+ if (this.options.mode === "streaming") this.schedulePush();
3402
+ return this;
3403
+ }
3404
+ /** Recreates the inner controller over `document` and re-intercepts it. */
3405
+ replaceInner(document) {
3406
+ const ControllerClass = this.inner.constructor;
3407
+ this.inner = new ControllerClass(document);
3408
+ this.setupActionInterceptors();
3409
+ }
2958
3410
  /**
2959
3411
  * Find the new operation added after applying an action,
2960
3412
  * by comparing current operation counts against a previous snapshot.
@@ -3008,13 +3460,34 @@ var RemoteDocumentController = class RemoteDocumentController {
3008
3460
  */
3009
3461
  async pullAndReplay(actions) {
3010
3462
  await this.pull();
3463
+ const replayedIds = /* @__PURE__ */ new Map();
3011
3464
  for (const action of actions) {
3012
- const methodName = screamingSnakeToCamel(action.type);
3013
- const method = this[methodName];
3014
- if (typeof method === "function") method.call(this, action.input);
3465
+ const scopeOps = () => this.inner.operations[action.scope] ?? [];
3466
+ const before = scopeOps().length;
3467
+ this.replayAction(action, replayedIds);
3468
+ const after = scopeOps();
3469
+ if (after.length > before) replayedIds.set(action.id, after[after.length - 1].action.id);
3015
3470
  }
3016
3471
  return this.tracker.flush();
3017
3472
  }
3473
+ replayAction(action, replayedIds) {
3474
+ if (action.type === "RETRACT") {
3475
+ const { target } = action.input;
3476
+ const replayed = replayedIds.get(target);
3477
+ this.applyAction(replayed === void 0 ? action : {
3478
+ ...action,
3479
+ input: { target: replayed }
3480
+ });
3481
+ return;
3482
+ }
3483
+ const methodName = screamingSnakeToCamel(action.type);
3484
+ if (methodName === "undo" || methodName === "redo") {
3485
+ this.dispatchModelAction(methodName, action.input);
3486
+ return;
3487
+ }
3488
+ const method = this[methodName];
3489
+ if (typeof method === "function") method.call(this, action.input);
3490
+ }
3018
3491
  /** Prepare actions for push, optionally signing them. */
3019
3492
  async prepareActionsForPush(tracked) {
3020
3493
  const actions = [];
@@ -3208,6 +3681,6 @@ var BrowserLocalStorage = class extends BaseStorage {
3208
3681
  }
3209
3682
  };
3210
3683
  //#endregion
3211
- export { ActionTracker, BaseStorage, BrowserLocalStorage, COMMON_PACKAGE_ID, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChannelScheme, ChevronDownIcon, ConflictError, CopyIcon, DEFAULT_DRIVE_EDITOR_ID, DEFAULT_DRIVE_ID, DEFAULT_SWITCHBOARD_URL, DOMAIN_TYPE, DRIVE_DOCUMENT_TYPES, DisconnectIcon, DocumentCache, DocumentChangeType, DocumentIntegrityService, DocumentModelNotFoundError, DocumentTypeMismatchError, DriveCollectionId, EDITOR_FILE_DROP_OPT_OUT_ATTR, GqlRequestChannel, GraphQLClientDocumentCache, GraphQLReactorClient, GraphQLReactorProvider, IDLE_OPERATIONS_ENTRY, IDLE_REFETCH_STATE, ISSUER_TYPE, InMemoryQueue, IntervalPollTimer, MutateDocumentWithOperationsDocument, NoSelectedDocumentError, PollBehavior, PropagationMode, REACTOR_SCHEMA, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, RENOWN_RETURN_URL_STRIPPED_PARAMS, RENOWN_URL, ReactorBuilder, ReactorClientBuilder, ReactorOperationFieldsFragmentDoc, RegistryClient, RelationalDbProcessor, RemoteClient, RemoteDocumentController, Renown, RenownAuthButton, RenownInitialUserProvider, RenownLoginButton, RenownLogo, RenownProvider, RenownUserButton, RenownWalletProvider, SpinnerIcon, StaticPackageManager, SubgraphSdkRegistry, SyncOperationStatus, UnsupportedDocumentTypeError, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, addAllowListEventHandler, addAllowedDocumentTypesEventHandler, addAnalyticsDatabaseNameEventHandler, addAttachmentServiceEventHandler, addBasePathEventHandler, addCliVersionEventHandler, addDefaultDrivesUrlEventHandler, addDisabledEditorsEventHandler, addDocument, addDocumentCacheEventHandler, addDraggingNodeEventHandler, addDrive, addDrivesEventHandler, addDrivesPreserveStrategyEventHandler, addEnabledEditorsEventHandler, addFeaturesEventHandler, addFileUploadOperationsChunkSizeEventHandler, addFileWithProgress, addFolder, addGaTrackingIdEventHandler, addGraphQLReactorClientEventHandler, addIsAddCloudDrivesEnabledEventHandler, addIsAddDriveEnabledEventHandler, addIsAddLocalDrivesEnabledEventHandler, addIsAddPublicDrivesEnabledEventHandler, addIsAnalyticsDatabaseWorkerEnabledEventHandler, addIsAnalyticsEnabledEventHandler, addIsAnalyticsExternalProcessorsEnabledEventHandler, addIsCloudDrivesEnabledEventHandler, addIsDeleteCloudDrivesEnabledEventHandler, addIsDeleteLocalDrivesEnabledEventHandler, addIsDeletePublicDrivesEnabledEventHandler, addIsDiffAnalyticsEnabledEventHandler, addIsDocumentModelSelectionSettingsEnabledEventHandler, addIsDragAndDropEnabledEventHandler, addIsDriveAnalyticsEnabledEventHandler, addIsEditorDebugModeEnabledEventHandler, addIsEditorReadModeEnabledEventHandler, addIsExternalControlsEnabledEventHandler, addIsExternalPackagesEnabledEventHandler, addIsExternalProcessorsEnabledEventHandler, addIsExternalRelationalProcessorsEnabledEventHandler, addIsLocalDrivesEnabledEventHandler, addIsPublicDrivesEnabledEventHandler, addIsRelationalProcessorsEnabledEventHandler, addIsSentryTracingEnabledEventHandler, addLoadingEventHandler, addLocalDrivesEnabledEventHandler, addLogLevelEventHandler, addModalEventHandler, addPHEventHandlers, addPackageDiscoveryServiceEventHandler, addPromiseState, addReactorClientEventHandler, addReactorClientModuleEventHandler, addRemoteDrive, addRenownAdaptersEventHandler, addRenownChainIdEventHandler, addRenownEventHandler, addRenownNetworkIdEventHandler, addRenownUrlEventHandler, addRequiresHardRefreshEventHandler, addResetSelectedNodeEventHandler, addRevisionHistoryVisibleEventHandler, addRouterBasenameEventHandler, addSelectedDriveIdEventHandler, addSelectedNodeIdEventHandler, addSelectedTimelineItemEventHandler, addSelectedTimelineRevisionEventHandler, addSentryDsnEventHandler, addSentryEnvEventHandler, addSentryReleaseEventHandler, addSetSelectedDriveOnPopStateEventHandler, addSetSelectedNodeOnPopStateEventHandler, addStudioModeEventHandler, addSwitchboardUrlEventHandler, addToastEventHandler, addVersionCheckIntervalEventHandler, addVersionEventHandler, addVetraPackageManagerEventHandler, addWarnOutdatedAppEventHandler, ambientRenownTokenProvider, baseDocumentModels, baseDocumentModelsMap, buildDocumentSubgraphQuery, buildDocumentSubgraphUrl, buildFolderZip, callEventHandlerRegisterFunctions, callGlobalSetterForKey, clearGlobal, closePHModal, commonGlobalEventHandlerFunctions, convertRemoteOperations, createAnalyticsStore, createClient, createProcessorQuery, createUrlWithPreservedParams, deleteDrive, deleteNode, deriveSystemUrl, describeGraphQLDocument, diffStateShapes, dispatchActions, downloadDocument, downloadFolderZip, driveIdFromUrl, dropAllReactorStorage, ensurePHEventHandlers, expandBulkArchive, exportFile, extractDriveIdFromPath, extractDriveIdFromSlug, extractDriveSlugFromPath, extractNodeIdFromPath, extractNodeIdFromSlug, extractNodeSlugFromPath, fetchDriveInfo, findDerivedId, findUuid, getAnalyticsStore, getDocumentExtension, getDocumentGraphqlQuery, getDocumentStateSelection, getDocumentUpgradePreview, getDocumentVersionStatus, getDriveIdBySlug, getDrives, getGlobal, getPackageInfo, getPackagePage, getPackages, getPackagesByDocumentType, getPackagesForDocumentType, getPathWithoutBase, getRevisionFromDate, getSlugFromDriveUrl, getSwitchboardBaseFromChannelUrl, getSwitchboardGatewayUrlFromDriveUrl, getSyncStatus, getSyncStatusSync, getUserPermissions, graphqlDocumentEvents, graphqlDocumentsEvents, graphqlEventsToSyncDrive, hasPreloadBandwidth, hideRevisionHistory, identifierFromMutateDocumentOperationVariables, initConnectCrypto, initRenownCrypto, initTheme, isAuthRefusalClose, isDocumentTypeSupported, isDriveAuthError, isExternalControlsEnabledEventFunctions, isFileNodeKind, isFolderNodeKind, isGraphQLReactorClient, isOperationCache, loadFile, loading, login, logout, makeAuthConnectionParams, makeAuthMiddleware, makeDriveUrlComponent, makeNodeSlug, makePHEventFunctions, openRenown, packageFromDocumentModels, parseDriveUrl, phAppConfigHooks, phAppConfigSetters, phDocumentEditorConfigHooks, phDocumentEditorConfigSetters, phDocumentFromGetDocument, phDocumentFromMutation, phDocumentFromQuery, phDocumentsFromQuery, phGlobalConfigHooks, phGlobalConfigSetters, preloadEditorModule, prepareSignedActions, reactorGraphqlBatchFetchDocuments, reactorGraphqlCreateDocument, reactorGraphqlDeleteDocument, reactorGraphqlDeleteDocuments, reactorGraphqlFetchDocument, reactorGraphqlMutateDocument, readPromiseState, refreshReactorData, refreshReactorDataClient, renameDrive, renameDriveNode, resolveDocumentModelModule, resolveUrlPathname, revisionMapFromRevisionsList, setAllowList, setAllowedDocumentTypes, setAnalyticsDatabaseName, setAttachmentService, setBasePath, setCliVersion, setDefaultDrivesUrl, setDefaultPHGlobalConfig, setDisabledEditors, setDocumentCache, setDriveAvailableOffline, setDriveMetadata, setDriveSharingType, setDrives, setDrivesPreserveStrategy, setEnabledEditors, setFeatures, setFileUploadOperationsChunkSize, setGaTrackingId, setGlobal, setGraphQLReactorClient, setIsAddCloudDrivesEnabled, setIsAddDriveEnabled, setIsAddLocalDrivesEnabled, setIsAddPublicDrivesEnabled, setIsAnalyticsDatabaseWorkerEnabled, setIsAnalyticsEnabled, setIsAnalyticsExternalProcessorsEnabled, setIsCloudDrivesEnabled, setIsDeleteCloudDrivesEnabled, setIsDeleteLocalDrivesEnabled, setIsDeletePublicDrivesEnabled, setIsDiffAnalyticsEnabled, setIsDocumentModelSelectionSettingsEnabled, setIsDragAndDropEnabled, setIsDriveAnalyticsEnabled, setIsEditorDebugModeEnabled, setIsEditorReadModeEnabled, setIsExternalControlsEnabled, setIsExternalPackagesEnabled, setIsExternalProcessorsEnabled, setIsExternalRelationalProcessorsEnabled, setIsLocalDrivesEnabled, setIsPublicDrivesEnabled, setIsRelationalProcessorsEnabled, setIsSentryTracingEnabled, setLoading, setLocalDrivesEnabled, setLogLevel, setPGliteDB, setPHAppConfig, setPHAppConfigByKey, setPHDocumentEditorConfig, setPHDocumentEditorConfigByKey, setPHGlobalConfig, setPHGlobalConfigByKey, setPHModal, setPHToast, setPackageDiscoveryService, setPreferredEditorOnNode, setReactorClient, setReactorClientModule, setRenown, setRenownAdapters, setRenownChainId, setRenownNetworkId, setRenownUrl, setRequiresHardRefresh, setRevisionHistoryVisible, setRouterBasename, setSelectedDrive, setSelectedDriveId, setSelectedNode, setSelectedTimelineItem, setSelectedTimelineRevision, setSentryDsn, setSentryEnv, setSentryRelease, setStudioMode, setSwitchboardUrl, setVersion, setVersionCheckInterval, setVetraPackageManager, setWarnOutdatedApp, showCreateDocumentModal, showDeleteNodeModal, showPHModal, showRevisionHistory, signStampedAction, sortNodesByName, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscriptionsUrlFromGraphqlUrl, trimTrailingSlash, truncateAllTables, upgradeDocument, useAllowList, useAllowedDocumentModelModules, useAllowedDocumentTypes, useAnalyticsDatabaseName, useAppModuleById, useAppModules, useAttachmentPreview, useAttachmentService, useAttachmentUpload, useAttachments, useBasePath, useCanExecute, useCliVersion, useConnectionState, useConnectionStates, useDatabase, useDefaultAppModule, useDefaultDrivesUrl, useDid, useDisabledEditors, useDispatch, useDocument, useDocumentById, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOfType, useDocumentOperations, useDocumentSafe, useDocumentTypes, useDocumentTypesInSelectedDrive, useDocumentVersionStatus, useDocuments, useDocumentsByIds, useDocumentsInSelectedDrive, useDocumentsInSelectedFolder, useDownloadDocument, useDownloadFolder, useDragNode, useDriveById, useDriveSystemInfo, useDrives, useDrivesPreserveStrategy, useDropFile, useDropNode, useEditorFileDrop, useEditorModuleById, useEditorModules, useEditorModulesForDocumentType, useEditorPreloader, useEnabledEditors, useFallbackEditorModule, useFeatures, useFileNodesInSelectedDrive, useFileNodesInSelectedFolder, useFileUploadOperationsChunkSize, useFolderById, useFolderNodesInSelectedDrive, useFolderNodesInSelectedFolder, useGaTrackingId, useGetDocument, useGetDocumentAsync, useGetDocuments, useGetSwitchboardLink, useGraphQLReactorClient, useInitReactorGraphqlClient, useIsAddCloudDrivesEnabled, useIsAddDriveEnabled, useIsAddLocalDrivesEnabled, useIsAddPublicDrivesEnabled, useIsAnalyticsDatabaseWorkerEnabled, useIsAnalyticsEnabled, useIsAnalyticsExternalProcessorsEnabled, useIsCloudDrivesEnabled, useIsDeleteCloudDrivesEnabled, useIsDeleteLocalDrivesEnabled, useIsDeletePublicDrivesEnabled, useIsDiffAnalyticsEnabled, useIsDocumentModelSelectionSettingsEnabled, useIsDragAndDropEnabled, useIsDriveAnalyticsEnabled, useIsEditorDebugModeEnabled, useIsEditorReadModeEnabled, useIsExternalControlsEnabled, useIsExternalPackagesEnabled, useIsExternalProcessorsEnabled, useIsExternalRelationalProcessorsEnabled, useIsLocalDrivesEnabled, useIsPublicDrivesEnabled, useIsRelationalProcessorsEnabled, useIsSentryTracingEnabled, useLoading, useLocalDrivesEnabled, useLogLevel, useLoginStatus, useModelRegistry, useNodeActions, useNodeById, useNodeParentFolderById, useNodePathById, useNodesInSelectedDrive, useNodesInSelectedDriveOrFolder, useNodesInSelectedFolder, useOnDropFile, usePGlite, usePHAppConfigByKey, usePHDocumentEditorConfigByKey, usePHGlobalConfigByKey, usePHModal, usePHToast, usePackageDiscoveryService, useParentFolderForSelectedNode, useReactorClient, useReactorClientModule, useRelationalDb, useRelationalQuery, useRenown, useRenownAdapters, useRenownAuth, useRenownAuthAsync, useRenownChainId, useRenownInit, useRenownInitialAuth, useRenownInitialUser, useRenownLoginMethods, useRenownNetworkId, useRenownSessionCookie, useRenownSessionSynced, useRenownUrl, useRenownWalletAdapter, useRequiresHardRefresh, useResetPHGlobalConfig, useRevisionHistoryVisible, useRouterBasename, useSelectedDocument, useSelectedDocumentId, useSelectedDocumentOfType, useSelectedDocumentSafe, useSelectedDrive, useSelectedDriveId, useSelectedDriveSafe, useSelectedFolder, useSelectedNode, useSelectedNodePath, useSelectedTimelineItem, useSelectedTimelineRevision, useSentryDsn, useSentryEnv, useSentryRelease, useSetDefaultPHGlobalConfig, useSetPHAppConfig, useSetPHDocumentEditorConfig, useSetPHGlobalConfig, useStudioMode, useSubgraphModules, useSupportedDocumentTypesInReactor, useSwitchboardClient, useSwitchboardUrl, useSync, useSyncList, useTheme, useUser, useUserPermissions, useVersion, useVersionCheckInterval, useVetraPackageManager, useVetraPackages, useWarnOutdatedApp, validateDocument, viewFilterInputFromViewFilter, waitForDocumentReady };
3684
+ export { ActionTracker, BaseStorage, BatchJobFailedError, BrowserLocalStorage, COMMON_PACKAGE_ID, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChannelScheme, ChevronDownIcon, ConflictError, CopyIcon, DEFAULT_BATCH_REQUEST_TIMEOUT_MS, DEFAULT_BREAKER, DEFAULT_DRIVE_EDITOR_ID, DEFAULT_DRIVE_ID, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_SWITCHBOARD_URL, DOMAIN_TYPE, DRIVE_ARRIVAL_MAX_WAIT_MS, DRIVE_DOCUMENT_TYPES, DisconnectIcon, DocumentCache, DocumentChangeType, DocumentIntegrityService, DocumentModelNotFoundError, DocumentTypeMismatchError, DriveCollectionId, DriveProvider, EDITOR_FILE_DROP_OPT_OUT_ATTR, EditorDocumentProvider, FEATURE_FLAG_PARAM_PREFIX, GET_MANY_CHUNK_SIZE, GLOBAL_SEARCH_PARAMS, GetDocumentAtConsistencyDocument, GqlRequestChannel, GraphQLClientDocumentCache, GraphQLDriveNodeSource, GraphQLDriveReadClient, GraphQLOperationNotSupportedError, GraphQLReactorClient, GraphQLReactorProvider, GraphQLWrongBackendError, IDLE_DOCUMENTS_OF_TYPE_ENTRY, IDLE_OPERATIONS_ENTRY, IDLE_REFETCH_STATE, ISSUER_TYPE, InMemoryQueue, IntervalPollTimer, JobFailedError, MODAL_SEARCH_PARAM, MutateDocumentWithOperationsDocument, NoSelectedDocumentError, OPENED_FROM_STATE_KEY, OperationRejectedError, PHStoreProvider, PH_LOCATION_CHANGE_EVENT, PREFETCH_WAIT_MS, PollBehavior, PropagationMode, REACTOR_SCHEMA, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, RENOWN_RETURN_URL_STRIPPED_PARAMS, RENOWN_URL, REVISION_HISTORY_PAGE_PARAM, REVISION_HISTORY_PARAM, ReactorBuilder, ReactorClientBuilder, ReactorOperationFieldsFragmentDoc, RegistryClient, RelationalDbProcessor, RemoteClient, RemoteDocumentController, Renown, RenownAuthButton, RenownInitialUserProvider, RenownLoginButton, RenownLogo, RenownProvider, RenownUserButton, RenownWalletProvider, SETTINGS_PATH, SpinnerIcon, StaticPackageManager, SubgraphSdkRegistry, SwitchboardLookupError, SwitchboardUnreachableError, SyncOperationStatus, UnsupportedDocumentTypeError, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, addAllowListEventHandler, addAllowedDocumentTypesEventHandler, addAnalyticsDatabaseNameEventHandler, addAttachmentServiceEventHandler, addBackendAuthEventHandler, addBasePathEventHandler, addCliVersionEventHandler, addDefaultDrivesUrlEventHandler, addDisabledEditorsEventHandler, addDocument, addDocumentCacheEventHandler, addDraggingNodeEventHandler, addDrive, addDriveNodesEventHandler, addDrivesEventHandler, addDrivesPreserveStrategyEventHandler, addEnabledEditorsEventHandler, addFeaturesEventHandler, addFileUploadOperationsChunkSizeEventHandler, addFileWithProgress, addFolder, addFullReactorClientEventHandler, addGaTrackingIdEventHandler, addGraphQLReactorClientEventHandler, addIsAddCloudDrivesEnabledEventHandler, addIsAddDriveEnabledEventHandler, addIsAddLocalDrivesEnabledEventHandler, addIsAddPublicDrivesEnabledEventHandler, addIsAnalyticsDatabaseWorkerEnabledEventHandler, addIsAnalyticsEnabledEventHandler, addIsAnalyticsExternalProcessorsEnabledEventHandler, addIsCloudDrivesEnabledEventHandler, addIsDeleteCloudDrivesEnabledEventHandler, addIsDeleteLocalDrivesEnabledEventHandler, addIsDeletePublicDrivesEnabledEventHandler, addIsDiffAnalyticsEnabledEventHandler, addIsDocumentModelSelectionSettingsEnabledEventHandler, addIsDragAndDropEnabledEventHandler, addIsDriveAnalyticsEnabledEventHandler, addIsEditorDebugModeEnabledEventHandler, addIsEditorReadModeEnabledEventHandler, addIsExternalControlsEnabledEventHandler, addIsExternalPackagesEnabledEventHandler, addIsExternalProcessorsEnabledEventHandler, addIsExternalRelationalProcessorsEnabledEventHandler, addIsLocalDrivesEnabledEventHandler, addIsPublicDrivesEnabledEventHandler, addIsRelationalProcessorsEnabledEventHandler, addIsSentryTracingEnabledEventHandler, addLoadingEventHandler, addLocalDrivesEnabledEventHandler, addLogLevelEventHandler, addModalEventHandler, addPHEventHandlers, addPackageDiscoveryServiceEventHandler, addPromiseState, addReactorClientEventHandler, addReactorClientModuleEventHandler, addReactorHalvesEventHandler, addRemoteDrive, addRenownAdaptersEventHandler, addRenownChainIdEventHandler, addRenownEventHandler, addRenownNetworkIdEventHandler, addRenownUrlEventHandler, addRequiresHardRefreshEventHandler, addResetSelectedNodeEventHandler, addRevisionHistoryVisibleEventHandler, addRouterBasenameEventHandler, addSelectedDriveIdEventHandler, addSelectedNodeIdEventHandler, addSelectedTimelineItemEventHandler, addSelectedTimelineRevisionEventHandler, addSentryDsnEventHandler, addSentryEnvEventHandler, addSentryReleaseEventHandler, addSetSelectedDriveOnPopStateEventHandler, addSetSelectedNodeOnPopStateEventHandler, addStudioModeEventHandler, addSwitchboardUrlEventHandler, addSwitchboardsEventHandler, addSyncSelectionOnPopStateEventHandler, addToastEventHandler, addVersionCheckIntervalEventHandler, addVersionEventHandler, addVetraPackageManagerEventHandler, addWarnOutdatedAppEventHandler, ambientRenownSigner, ambientRenownTokenProvider, applySearchUpdate, backendAuthStatusOf, baseDocumentModels, baseDocumentModelsMap, bindPHStoreToWindow, browserNavigation, buildDocumentSubgraphQuery, buildDocumentSubgraphUrl, buildFolderZip, callEventHandlerRegisterFunctions, callGlobalSetterForKey, clearGlobal, closePHModal, commonGlobalEventHandlerFunctions, convertRemoteOperations, createAnalyticsStore, createClient, createDelegation, createDispatch, createDriveArrivals, createDriveChangeHandler, createGraphQLDriveNodeSource, createJobChangesSocket, createPHStore, createProcessorQuery, createSwitchboardBackend, createSwitchboardDirectory, createUrlWithPreservedParams, decodeDelegation, deleteDrive, deleteNode, deriveSystemUrl, describeGraphQLDocument, desktopShell, diffStateShapes, dispatchActions, downloadDocument, downloadFolderZip, driveIdFromUrl, dropAllReactorStorage, dropDriveNode, ensurePHEventHandlers, ensurePHStore, expandBulkArchive, exportFile, extractDriveIdFromPath, extractDriveIdFromSlug, extractDriveSlugFromPath, extractNodeIdFromPath, extractNodeIdFromSlug, extractNodeSlugFromPath, fetchDrive, fetchDriveInfo, findDerivedId, findDriveBySlug, findDriveBySlugOrId, findIsServableOverGraphQL, findUuid, getActivePHStore, getAnalyticsStore, getAttachmentClient, getCurrentPathname, getDocumentExtension, getDocumentGraphqlQuery, getDocumentStateSelection, getDocumentUpgradePreview, getDocumentVersionStatus, getDrive, getDriveIdBySlug, getDriveName, getDriveNode, getDrives, getFullReactorClient, getGlobal, getNodeTarget, getPHNavigation, getPHStore, getPHStoreSubscribe, getPackageInfo, getPackagePage, getPackages, getPackagesByDocumentType, getPackagesForDocumentType, getPathWithoutBase, getRevisionFromDate, getSlugFromDriveUrl, getSwitchboardBaseFromChannelUrl, getSwitchboardGatewayUrlFromDriveUrl, getSyncStatus, getSyncStatusSync, getTargetHref, getUserPermissions, globalFetch, graphqlDocumentEvents, graphqlDocumentsEvents, graphqlEventsToSyncDrive, hasHostNavigation, hasPreloadBandwidth, hideRevisionHistory, identifierFromMutateDocumentOperationVariables, initConnectCrypto, initRenownCrypto, initTheme, invalidateDriveNodes, isAuthRefusalClose, isBackendAuthError, isDeadlineError, isDocumentTypeCache, isDocumentTypeSupported, isDriveAuthError, isExternalControlsEnabledEventFunctions, isFileNodeKind, isFolderNodeKind, isGlobalSearchParam, isGraphQLReactorClient, isNodeFetch, isOperationCache, isPlainClick, isRoutedModal, isSettingsTarget, isoStringFromDateTime, listAllDriveNodes, listDriveIds, loadDocumentsOfType, loadDriveNodes, loadFile, loading, login, logout, makeAuthConnectionParams, makeAuthMiddleware, makeDriveSlug, makeDriveUrlComponent, makeNodeSlug, makePHEventFunctions, markLocalDriveWrite, modalFromSearch, modalHref, modalSearch, notifyPHStore, onVetraPackageManager, openRenown, openTarget, openTargetWith, openedFromIndex, packageFromDocumentModels, parseDriveUrl, parseRevisionHistoryPage, peekDriveNode, phAppConfigHooks, phAppConfigSetters, phDocumentEditorConfigHooks, phDocumentEditorConfigSetters, phDocumentFromGetDocument, phDocumentFromMutation, phDocumentFromQuery, phDocumentsFromQuery, phGlobalConfigHooks, phGlobalConfigSetters, prefetchDocument, preloadDrive, preloadDriveApp, preloadEditorModule, preloadNode, preloadTarget, prepareSignedActions, queriesUnknownArgument, queriesUnknownField, reactorGraphqlBatchFetchDocuments, reactorGraphqlCreateDocument, reactorGraphqlDeleteDocument, reactorGraphqlDeleteDocuments, reactorGraphqlFetchDocument, reactorGraphqlMutateDocument, readPromiseState, recordBackendAuthError, recordToSearch, refreshDrive, refreshDriveMembership, refreshReactorData, refreshReactorDataClient, renameDrive, renameDriveNode, resolveDocumentModelModule, resolveDriveRoute, resolveSearchUpdate, resolveSwitchboard, resolveUrlPathname, revisionMapFromRevisionsList, searchPackages, searchParamsToString, searchToRecord, setAllowList, setAllowedDocumentTypes, setAnalyticsDatabaseName, setAttachmentService, setBackendAuth, setBasePath, setBrowserOpenSync, setCliVersion, setDefaultDrivesUrl, setDefaultPHGlobalConfig, setDisabledEditors, setDocumentCache, setDriveAvailableOffline, setDriveMetadata, setDriveSharingType, setDrives, setDrivesPreserveStrategy, setEnabledEditors, setFeatures, setFileUploadOperationsChunkSize, setFullReactorClient, setGaTrackingId, setGlobal, setGraphQLReactorClient, setIsAddCloudDrivesEnabled, setIsAddDriveEnabled, setIsAddLocalDrivesEnabled, setIsAddPublicDrivesEnabled, setIsAnalyticsDatabaseWorkerEnabled, setIsAnalyticsEnabled, setIsAnalyticsExternalProcessorsEnabled, setIsCloudDrivesEnabled, setIsDeleteCloudDrivesEnabled, setIsDeleteLocalDrivesEnabled, setIsDeletePublicDrivesEnabled, setIsDiffAnalyticsEnabled, setIsDocumentModelSelectionSettingsEnabled, setIsDragAndDropEnabled, setIsDriveAnalyticsEnabled, setIsEditorDebugModeEnabled, setIsEditorReadModeEnabled, setIsExternalControlsEnabled, setIsExternalPackagesEnabled, setIsExternalProcessorsEnabled, setIsExternalRelationalProcessorsEnabled, setIsLocalDrivesEnabled, setIsPublicDrivesEnabled, setIsRelationalProcessorsEnabled, setIsSentryTracingEnabled, setLoading, setLocalDrivesEnabled, setLogLevel, setPGliteDB, setPHAppConfig, setPHAppConfigByKey, setPHDocumentEditorConfig, setPHDocumentEditorConfigByKey, setPHGlobalConfig, setPHGlobalConfigByKey, setPHModal, setPHToast, setPackageDiscoveryService, setPreferredEditorOnNode, setReactorClient, setReactorClientModule, setRenown, setRenownAdapters, setRenownChainId, setRenownNetworkId, setRenownUrl, setRequiresHardRefresh, setRevisionHistoryPage, setRevisionHistoryVisible, setRouterBasename, setSearchParams, setSelectedDrive, setSelectedDriveId, setSelectedNode, setSelectedNodeId, setSelectedTimelineItem, setSelectedTimelineRevision, setSentryDsn, setSentryEnv, setSentryRelease, setStudioMode, setSwitchboardUrl, setSwitchboards, setVersion, setVersionCheckInterval, setVetraPackageManager, setWarnOutdatedApp, showCreateDocumentModal, showDeleteNodeModal, showPHModal, showRevisionHistory, signStampedAction, sortNodesByName, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscribePHStore, subscribeToPHValue, subscriptionsUrlFromGraphqlUrl, switchboardFetch, syncSelectionFromPath, takeLocalDriveWrite, targetPathname, toLegacyNode, trackDriveArrival, trimTrailingSlash, truncateAllTables, untilDriveListed, upgradeDocument, useAllowList, useAllowedDocumentModelModules, useAllowedDocumentTypes, useAnalyticsDatabaseName, useAppModuleById, useAppModules, useAttachmentPreview, useAttachmentService, useAttachmentUpload, useAttachments, useBackendAuth, useBasePath, useCanExecute, useCliVersion, useCloseNode, useConnectionState, useConnectionStates, useDatabase, useDefaultAppModule, useDefaultDrivesUrl, useDid, useDisabledEditors, useDispatch, useDocument, useDocumentById, useDocumentCache, useDocumentLinkProps, useDocumentModelModuleById, useDocumentModelModules, useDocumentOfType, useDocumentOperations, useDocumentSafe, useDocumentTarget, useDocumentTypes, useDocumentTypesInSelectedDrive, useDocumentVersionStatus, useDocuments, useDocumentsByIds, useDocumentsInSelectedDrive, useDocumentsInSelectedFolder, useDocumentsOfType, useDownloadDocument, useDownloadFolder, useDragNode, useDriveById, useDriveContext, useDriveNode, useDriveNodes, useDriveNodesCache, useDriveSystemInfo, useDrives, useDrivesPreserveStrategy, useDropFile, useDropNode, useEditorDocumentContext, useEditorFileDrop, useEditorModuleById, useEditorModuleFor, useEditorModules, useEditorModulesForDocumentType, useEditorPreloader, useEnabledEditors, useFallbackEditorModule, useFeatures, useFileNodesInSelectedDrive, useFileNodesInSelectedFolder, useFileUploadOperationsChunkSize, useFolderById, useFolderNodesInSelectedDrive, useFolderNodesInSelectedFolder, useGaTrackingId, useGetDocument, useGetDocumentAsync, useGetDocuments, useGetSwitchboardLink, useGraphQLReactorClient, useInitReactorGraphqlClient, useIsAddCloudDrivesEnabled, useIsAddDriveEnabled, useIsAddLocalDrivesEnabled, useIsAddPublicDrivesEnabled, useIsAnalyticsDatabaseWorkerEnabled, useIsAnalyticsEnabled, useIsAnalyticsExternalProcessorsEnabled, useIsCloudDrivesEnabled, useIsDeleteCloudDrivesEnabled, useIsDeleteLocalDrivesEnabled, useIsDeletePublicDrivesEnabled, useIsDiffAnalyticsEnabled, useIsDocumentModelSelectionSettingsEnabled, useIsDragAndDropEnabled, useIsDriveAnalyticsEnabled, useIsEditorDebugModeEnabled, useIsEditorReadModeEnabled, useIsExternalControlsEnabled, useIsExternalPackagesEnabled, useIsExternalProcessorsEnabled, useIsExternalRelationalProcessorsEnabled, useIsLocalDrivesEnabled, useIsPublicDrivesEnabled, useIsRelationalProcessorsEnabled, useIsSentryTracingEnabled, useLinkProps, useLoading, useLocalDrivesEnabled, useLogLevel, useLoginStatus, useModalLinkProps, useModelRegistry, useNodeActions, useNodeById, useNodeParentFolderById, useNodePathById, useNodeTarget, useNodesInSelectedDrive, useNodesInSelectedDriveOrFolder, useNodesInSelectedFolder, useOnDropFile, useOpenNode, usePGlite, usePHAppConfigByKey, usePHDocumentEditorConfigByKey, usePHGlobalConfigByKey, usePHModal, usePHNavigation, usePHStore, usePHToast, usePackageDiscoveryService, useParentFolderForSelectedNode, usePreloadDrive, usePreloadNode, useReactorClient, useReactorClientModule, useReactorHalves, useRelationalDb, useRelationalQuery, useRenown, useRenownAdapters, useRenownAuth, useRenownAuthAsync, useRenownChainId, useRenownInit, useRenownInitialAuth, useRenownInitialUser, useRenownLoginMethods, useRenownNetworkId, useRenownSessionCookie, useRenownSessionSynced, useRenownUrl, useRenownWalletAdapter, useRequiresHardRefresh, useResetPHGlobalConfig, useRevisionHistoryPage, useRevisionHistoryVisible, useRouterBasename, useSearchParams, useSelectedDocument, useSelectedDocumentId, useSelectedDocumentOfType, useSelectedDocumentSafe, useSelectedDrive, useSelectedDriveId, useSelectedDriveSafe, useSelectedFolder, useSelectedNode, useSelectedNodePath, useSelectedTimelineItem, useSelectedTimelineRevision, useSentryDsn, useSentryEnv, useSentryRelease, useSetDefaultPHGlobalConfig, useSetPHAppConfig, useSetPHDocumentEditorConfig, useSetPHGlobalConfig, useSetSearchParams, useSetSelectedDrive, useSetSelectedNode, useStudioMode, useSubgraphModules, useSupportedDocumentTypesInReactor, useSwitchboardClient, useSwitchboardUrl, useSwitchboards, useSync, useSyncList, useTheme, useUser, useUserPermissions, useVersion, useVersionCheckInterval, useVetraPackageManager, useVetraPackages, useWarnOutdatedApp, validateDocument, viewFilterInputFromViewFilter, waitForArrival, waitForDocumentReady, withRequestDeadline, withStreamedBodies, withoutModalSearch };
3212
3685
 
3213
3686
  //# sourceMappingURL=index.js.map