@powerhousedao/reactor-browser 6.2.3-dev.1 → 6.2.3-dev.100

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 (107) hide show
  1. package/dist/attachment-service-DXfpfp98.d.ts +1757 -0
  2. package/dist/attachment-service-DXfpfp98.d.ts.map +1 -0
  3. package/dist/auth-DzIYxeEJ.d.ts +32 -0
  4. package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
  5. package/dist/client-1n_ZUXeu.js +135 -0
  6. package/dist/client-1n_ZUXeu.js.map +1 -0
  7. package/dist/{client-BIHN_UyR.d.ts → client-BFk0MY6A.d.ts} +4 -3
  8. package/dist/client-BFk0MY6A.d.ts.map +1 -0
  9. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  10. package/dist/client-BFnMV-EO.js.map +1 -0
  11. package/dist/dispatch-Cylwl2Dk.js +1173 -0
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/document-by-id-DdvqanGR.js +16 -0
  14. package/dist/document-by-id-DdvqanGR.js.map +1 -0
  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-D5QXcJbV.js +4609 -0
  18. package/dist/document-operations-D5QXcJbV.js.map +1 -0
  19. package/dist/global-DAAmZGCO.d.ts +612 -0
  20. package/dist/global-DAAmZGCO.d.ts.map +1 -0
  21. package/dist/{index-CkJNhsQo.d.ts → index-Bj1poVfa.d.ts} +32 -100
  22. package/dist/index-Bj1poVfa.d.ts.map +1 -0
  23. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  24. package/dist/index-rtDmzViP.d.ts.map +1 -0
  25. package/dist/index.d.ts +938 -405
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +883 -307
  28. package/dist/index.js.map +1 -1
  29. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  30. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  31. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  32. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  33. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  34. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  35. package/dist/{relational-D4sxGPz7.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-BIEv6bSI.js → renown-B3MUaiq7.js} +78 -33
  38. package/dist/renown-B3MUaiq7.js.map +1 -0
  39. package/dist/renown-CBoTdGrg.js +394 -0
  40. package/dist/renown-CBoTdGrg.js.map +1 -0
  41. package/dist/{types-Dcv1ZLoW.d.ts → schema-Bn6L3QR1.d.ts} +324 -64
  42. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  43. package/dist/{client-D66jVnot.js → schema-D0G1oAo9.js} +358 -150
  44. package/dist/schema-D0G1oAo9.js.map +1 -0
  45. package/dist/src/ai/index.d.ts +313 -79
  46. package/dist/src/ai/index.d.ts.map +1 -1
  47. package/dist/src/ai/index.js +1030 -173
  48. package/dist/src/ai/index.js.map +1 -1
  49. package/dist/src/analytics/index.d.ts +36 -44
  50. package/dist/src/analytics/index.d.ts.map +1 -1
  51. package/dist/src/analytics/index.js +4 -4
  52. package/dist/src/analytics/index.js.map +1 -1
  53. package/dist/src/document-model.d.ts +3 -4
  54. package/dist/src/document-model.d.ts.map +1 -1
  55. package/dist/src/document-model.js.map +1 -1
  56. package/dist/src/graphql/client.d.ts +4 -3
  57. package/dist/src/graphql/client.js +1 -1
  58. package/dist/src/graphql-client/entry.d.ts +7 -4
  59. package/dist/src/graphql-client/entry.js +4 -4
  60. package/dist/src/relational/index.d.ts +15 -9
  61. package/dist/src/relational/index.d.ts.map +1 -1
  62. package/dist/src/relational/index.js +1 -1
  63. package/dist/src/renown/index.d.ts +3 -2
  64. package/dist/src/renown/index.js +3 -3
  65. package/dist/src/rpc/index.d.ts +217 -140
  66. package/dist/src/rpc/index.d.ts.map +1 -1
  67. package/dist/src/rpc/index.js +602 -623
  68. package/dist/src/rpc/index.js.map +1 -1
  69. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  70. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  71. package/dist/switchboard-directory-CWf5SRo7.js +435 -0
  72. package/dist/switchboard-directory-CWf5SRo7.js.map +1 -0
  73. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  74. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  75. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  76. package/dist/types-520nWrB3.d.ts.map +1 -0
  77. package/dist/types-CyPDurGV.d.ts +63 -0
  78. package/dist/types-CyPDurGV.d.ts.map +1 -0
  79. package/package.json +24 -23
  80. package/dist/attachment-service-CdwHrbDH.d.ts +0 -1063
  81. package/dist/attachment-service-CdwHrbDH.d.ts.map +0 -1
  82. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  83. package/dist/client-D66jVnot.js.map +0 -1
  84. package/dist/client-DjK30EQ-.js.map +0 -1
  85. package/dist/document-by-id-BSZqTN66.js +0 -517
  86. package/dist/document-by-id-BSZqTN66.js.map +0 -1
  87. package/dist/document-model-modules-DfQBNGc-.js +0 -419
  88. package/dist/document-model-modules-DfQBNGc-.js.map +0 -1
  89. package/dist/document-operations-Bgo6A6W2.js +0 -2545
  90. package/dist/document-operations-Bgo6A6W2.js.map +0 -1
  91. package/dist/global-BggszP4X.d.ts +0 -401
  92. package/dist/global-BggszP4X.d.ts.map +0 -1
  93. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  94. package/dist/index-CkJNhsQo.d.ts.map +0 -1
  95. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  96. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  97. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  98. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  99. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  100. package/dist/relational-D4sxGPz7.js.map +0 -1
  101. package/dist/renown-BHxwP7xU.js +0 -97
  102. package/dist/renown-BHxwP7xU.js.map +0 -1
  103. package/dist/renown-BIEv6bSI.js.map +0 -1
  104. package/dist/switchboard-D4-_jwk-.js +0 -271
  105. package/dist/switchboard-D4-_jwk-.js.map +0 -1
  106. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  107. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,26 +1,53 @@
1
- import { a as setDocumentCache, c as useDocumentSafe, d as useGetDocumentAsync, f as useGetDocuments, h as readPromiseState, i as addDocumentCacheEventHandler, l as useDocuments, m as addPromiseState, n as useDocumentsByIds, o as useDocument, p as DocumentCache, r as useDispatch, s as useDocumentCache, t as useDocumentById, u as useGetDocument, y as dispatchActions } from "./document-by-id-BSZqTN66.js";
2
- import { A as createUrlWithPreservedParams, B as makeNodeSlug, C as addResetSelectedNodeEventHandler, D as addDrivesEventHandler, E as setSelectedNode, F as extractNodeIdFromSlug, G as DocumentTypeMismatchError, H as ambientRenownTokenProvider, I as extractNodeSlugFromPath, K as NoSelectedDocumentError, L as findUuid, M as extractDriveIdFromSlug, N as extractDriveSlugFromPath, O as setDrives, P as extractNodeIdFromPath, R as getPathWithoutBase, S as useSelectedDriveSafe, T as addSetSelectedNodeOnPopStateEventHandler, U as makeAuthMiddleware, V as resolveUrlPathname, W as DocumentModelNotFoundError, _ as addSetSelectedDriveOnPopStateEventHandler, a as useVetraPackageManager, b as useSelectedDrive, c as useDocumentTypesInSelectedDrive, d as useFolderNodesInSelectedDrive, f as useNodesInSelectedDrive, g as addSelectedDriveIdEventHandler, h as sortNodesByName, i as setVetraPackageManager, j as extractDriveIdFromPath, k as useDrives, l as useDocumentsInSelectedDrive, m as isFolderNodeKind, n as useDocumentModelModules, o as useVetraPackages, p as isFileNodeKind, q as UnsupportedDocumentTypeError, r as addVetraPackageManagerEventHandler, s as useSelectedNode, t as useDocumentModelModuleById, u as useFileNodesInSelectedDrive, v as setSelectedDrive, w as addSelectedNodeIdEventHandler, x as useSelectedDriveId, y as setSelectedDriveId, z as makeDriveUrlComponent } from "./document-model-modules-DfQBNGc-.js";
3
- import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
4
- import { $ as addDefaultDrivesUrlEventHandler, $n as useIsAddLocalDrivesEnabled, $r as makeAuthConnectionParams, $t as setEnabledEditors, A as useReactorClientModule, Ai as getDocumentExtension, An as setRenownUrl, Ar as useSentryRelease, At as addRenownAdaptersEventHandler, B as useDragNode, Bi as closePHModal, Bn as setWarnOutdatedApp, Br as phAppConfigHooks, Bt as addSwitchboardUrlEventHandler, C as addReactorClientModuleEventHandler, Ci as addFileWithProgress, Cn as setIsRelationalProcessorsEnabled, Cr as useRenownChainId, Ct as addIsExternalRelationalProcessorsEnabledEventHandler, D as useModelRegistry, Di as exportFile, Dn as setRenownAdapters, Dr as useRouterBasename, Dt as addIsSentryTracingEnabledEventHandler, E as useDatabase, Ei as deleteNode, En as setLogLevel, Er as useRequiresHardRefresh, Et as addIsRelationalProcessorsEnabledEventHandler, F as usePackageDiscoveryService, Fi as setPreferredEditorOnNode, Fn as setSentryRelease, Fr as useWarnOutdatedApp, Ft as addRouterBasenameEventHandler, G as useFeatures, Gi as usePHModal, Gn as useDefaultDrivesUrl, Gr as setIsDragAndDropEnabled, Gt as phGlobalConfigSetters, H as useDropTarget, Hi as showCreateDocumentModal, Hn as useAnalyticsDatabaseName, Hr as phDocumentEditorConfigHooks, Ht as addVersionEventHandler, I as addGraphQLReactorClientEventHandler, Ii as upgradeDocument, In as setStudioMode, Ir as addAllowedDocumentTypesEventHandler, It as addSentryDsnEventHandler, J as useAttachmentService, Jn as useEnabledEditors, Jr as useIsDragAndDropEnabled, Jt as setBasePath, K as addAttachmentServiceEventHandler, Kn as useDisabledEditors, Kr as setIsExternalControlsEnabled, Kt as setAllowList, L as setGraphQLReactorClient, Li as getUserPermissions, Ln as setSwitchboardUrl, Lr as addIsDragAndDropEnabledEventHandler, Lt as addSentryEnvEventHandler, M as useSyncList, Mi as moveNode$1, Mn as setRouterBasename, Mr as useSwitchboardUrl, Mt as addRenownNetworkIdEventHandler, N as addPackageDiscoveryServiceEventHandler, Ni as renameDriveNode, Nn as setSentryDsn, Nr as useVersion, Nt as addRenownUrlEventHandler, O as usePGlite, Oi as extractInitialState, On as setRenownChainId, Or as useSentryDsn, Ot as addLocalDrivesEnabledEventHandler, P as setPackageDiscoveryService, Pi as renameNode, 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 isDocumentTypeSupported, Rn as setVersion, Rr as addIsExternalControlsEnabledEventHandler, Rt as addSentryReleaseEventHandler, S as addReactorClientEventHandler, Si as addDocument, Sn as setIsPublicDrivesEnabled, Sr as useRenownAdapters, St as addIsExternalProcessorsEnabledEventHandler, T as setReactorClientModule, Ti as copyNode$1, Tn as setLocalDrivesEnabled, Tr as useRenownUrl, Tt as addIsPublicDrivesEnabledEventHandler, U as addFeaturesEventHandler, Ui as showDeleteNodeModal, Un as useBasePath, Ur as phDocumentEditorConfigSetters, Ut as addWarnOutdatedAppEventHandler, V as useDropNode, Vi as setPHModal, Vn as useAllowList, Vr as phAppConfigSetters, Vt as addVersionCheckIntervalEventHandler, W as setFeatures, Wi as showPHModal, 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 buildPulledDocument, _n as setIsEditorReadModeEnabled, _r as useIsPublicDrivesEnabled, _t as addIsDocumentModelSelectionSettingsEnabledEventHandler, a as addPHEventHandlers, ai as StaticPackageManager, an as setIsAddPublicDrivesEnabled, ar as useIsDeleteCloudDrivesEnabled, at as addIsAddCloudDrivesEnabledEventHandler, b as showRevisionHistory, bi as hasRevisionConflict, bn as setIsExternalRelationalProcessorsEnabled, br as useLocalDrivesEnabled, bt as addIsEditorReadModeEnabledEventHandler, c as addToastEventHandler, ci as prepareSignedActions, cn as setIsAnalyticsExternalProcessorsEnabled, cr as useIsDiffAnalyticsEnabled, ct as addIsAddPublicDrivesEnabledEventHandler, d as addSelectedTimelineRevisionEventHandler, di as MutateDocumentWithOperationsDocument, dn as setIsDeleteLocalDrivesEnabled, dr as useIsEditorDebugModeEnabled, dt as addIsAnalyticsExternalProcessorsEnabledEventHandler, ei as startDocumentChangesSubscription, en as setFileUploadOperationsChunkSize, er as useIsAddPublicDrivesEnabled, et as addDisabledEditorsEventHandler, f as setSelectedTimelineRevision, fi as ReactorOperationFieldsFragmentDoc, fn as setIsDeletePublicDrivesEnabled, fr as useIsEditorReadModeEnabled, ft as addIsCloudDrivesEnabledEventHandler, g as useSelectedTimelineItem, gi as ConflictError, gn as setIsEditorDebugModeEnabled, gr as useIsLocalDrivesEnabled, gt as addIsDiffAnalyticsEnabledEventHandler, h as setSelectedTimelineItem, hi as revisionMapFromRevisionsList, hn as setIsDriveAnalyticsEnabled, hr as useIsExternalRelationalProcessorsEnabled, ht as addIsDeletePublicDrivesEnabledEventHandler, i as useSwitchboardClient, ii as subgraphUrlFromGraphqlUrl, in as setIsAddLocalDrivesEnabled, ir as useIsCloudDrivesEnabled, it as addGaTrackingIdEventHandler, j as useSync, ji as loadFile, jn as setRequiresHardRefresh, jr as useStudioMode, jt as addRenownChainIdEventHandler, k as useReactorClient, ki as fetchDocumentOperations, kn as setRenownNetworkId, kr as useSentryEnv, kt as addLogLevelEventHandler, l as setPHToast, li as signStampedAction, ln as setIsCloudDrivesEnabled, lr as useIsDocumentModelSelectionSettingsEnabled, lt as addIsAnalyticsDatabaseWorkerEnabledEventHandler, m as addSelectedTimelineItemEventHandler, mi as phDocumentFromMutation, mn as setIsDocumentModelSelectionSettingsEnabled, mr as useIsExternalProcessorsEnabled, mt as addIsDeleteLocalDrivesEnabledEventHandler, n as GraphQLReactorProvider, ni as SubgraphSdkRegistry, nn as setIsAddCloudDrivesEnabled, nr as useIsAnalyticsEnabled, nt as addEnabledEditorsEventHandler, o as callEventHandlerRegisterFunctions, oi as packageFromDocumentModels, on as setIsAnalyticsDatabaseWorkerEnabled, or as useIsDeleteLocalDrivesEnabled, ot as addIsAddDriveEnabledEventHandler, p as useSelectedTimelineRevision, pi as phDocumentFromGetDocument, 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 describeGraphQLDocument, rn as setIsAddDriveEnabled, rr as useIsAnalyticsExternalProcessorsEnabled, rt as addFileUploadOperationsChunkSizeEventHandler, s as commonGlobalEventHandlerFunctions, si as resolveDocumentModelModule, sn as setIsAnalyticsEnabled, sr as useIsDeletePublicDrivesEnabled, st as addIsAddLocalDrivesEnabledEventHandler, t as useDocumentOperations, ti as subscriptionsUrlFromGraphqlUrl, tn as setGaTrackingId, tr as useIsAnalyticsDatabaseWorkerEnabled, tt as addDrivesPreserveStrategyEventHandler, u as usePHToast, ui as stampAction, un as setIsDeleteCloudDrivesEnabled, ur as useIsDriveAnalyticsEnabled, ut as addIsAnalyticsEnabledEventHandler, v as hideRevisionHistory, vi as convertRemoteOperations, vn as setIsExternalPackagesEnabled, vr as useIsRelationalProcessorsEnabled, vt as addIsDriveAnalyticsEnabledEventHandler, w as setReactorClient, wi as addFolder, wn as setIsSentryTracingEnabled, wr as useRenownNetworkId, wt as addIsLocalDrivesEnabledEventHandler, x as useRevisionHistoryVisible, xi as screamingSnakeToCamel, xn as setIsLocalDrivesEnabled, xr as useLogLevel, xt as addIsExternalPackagesEnabledEventHandler, y as setRevisionHistoryVisible, yi as extractRevisionMap, yn as setIsExternalProcessorsEnabled, yr as useIsSentryTracingEnabled, yt as addIsEditorDebugModeEnabledEventHandler, z as addDraggingNodeEventHandler, zi as addModalEventHandler, zn as setVersionCheckInterval, zr as isExternalControlsEnabledEventFunctions, zt as addStudioModeEventHandler } from "./document-operations-Bgo6A6W2.js";
5
- import { a as setGlobal, i as getGlobal, n as getAnalyticsStore, r as clearGlobal, t as createAnalyticsStore } from "./store-BJYcr_FL.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-D5QXcJbV.js";
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 { i as GetDocumentWithOperationsDocument, o as PropagationMode, t as createClient } from "./client-D66jVnot.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-BHxwP7xU.js";
9
- import { A as RENOWN_CHAIN_ID, C as logout, D as CREDENTIAL_TYPES, E as CREDENTIAL_SUBJECT_TYPE, M as RENOWN_URL, N as VERIFIABLE_CREDENTIAL_EIP712_TYPE, O as DOMAIN_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-BIEv6bSI.js";
10
- import { c as useSelectedDocument, d as useSelectedDocumentSafe, f as useDocumentOfType, l as useSelectedDocumentId, t as GQL_CHANNEL_SUFFIX, u as useSelectedDocumentOfType } from "./switchboard-D4-_jwk-.js";
11
- import { i as setPGliteDB, n as useRelationalQuery, r as useRelationalDb, t as createProcessorQuery } from "./relational-D4sxGPz7.js";
12
- import { a as getPackagesByDocumentType, i as getPackages, n as getPackageInfo, o as getPackagesForDocumentType, r as getPackagePage, s as trimTrailingSlash, t as RegistryClient } from "./client-DjK30EQ-.js";
13
- import { createZip, isDocumentZip, parseBulkArchive, toTransportAction, validateInitialState, validateModules, validateStateSchemaName, zipEntries } from "@powerhousedao/shared/document-model";
14
- import { DriveDocumentSchema, driveCreateDocument, getDescendants, getNextCopyNumber, isFileNode, isFolderNode, setAvailableOffline, setDriveIcon, setDriveName, setSharingType } from "@powerhousedao/shared/document-drive";
8
+ import { s as PropagationMode } from "./schema-D0G1oAo9.js";
9
+ import { t as createClient } from "./client-1n_ZUXeu.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-CWf5SRo7.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";
15
19
  import { allPass, filter, find, forEach, funnel, hasAtLeast, isArray, isDefined, isIncludedIn, isStrictEqual, isTruthy, last, map, mapToObj, once, pipe, prop, split, unique } from "remeda";
16
- import { pascalCase } from "change-case";
17
- import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
18
- import { AuthEnforcementDisabledError, ChannelScheme, DocumentChangeType, DocumentChangeType as DocumentChangeType$1, DocumentIntegrityService, DriveCollectionId, DriveCollectionId as DriveCollectionId$1, 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";
19
- import { Kind, parse } from "graphql";
20
+ import { ClientError } from "graphql-request";
20
21
  import { z } from "zod";
21
22
  import normalizeException from "normalize-exception";
22
- import lzString from "lz-string";
23
23
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
24
+ //#region src/actions/drive-info.ts
25
+ /**
26
+ * Reads a drive's info from a switchboard's REST endpoint.
27
+ *
28
+ * Drive discovery is the one read a client makes before it can authenticate
29
+ * anything else: `graphqlEndpoint` is what the sync remote is registered with,
30
+ * so nothing authenticated can happen until this call returns. That makes it
31
+ * the one request most likely to be sent logged-out — and it is exactly the
32
+ * call that must NOT be, because a switchboard running
33
+ * `DOCUMENT_PERMISSIONS` refuses a protected drive to an anonymous caller
34
+ * even when the logged-in user holds a grant on it.
35
+ *
36
+ * So the token goes out whenever there is one, with no `if (user)` guard: the
37
+ * provider already answers `undefined` when logged out, and an open
38
+ * switchboard serves that anonymously exactly as before.
39
+ *
40
+ * A failure throws `DriveRequestError` carrying the status, so
41
+ * `isDriveAuthError` can tell a refusal from an unreachable host and the
42
+ * caller can prompt for a login instead of reporting a network fault.
43
+ */
44
+ async function fetchDriveInfo(url, tokenProvider = ambientRenownTokenProvider) {
45
+ const token = await tokenProvider();
46
+ const response = await fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
47
+ if (!response.ok) throw new DriveRequestError(`Failed to resolve drive info from ${url}: HTTP ${response.status}`, response.status);
48
+ return await response.json();
49
+ }
50
+ //#endregion
24
51
  //#region src/actions/bulk-archive.ts
25
52
  /**
26
53
  * Expand a dropped file into import jobs. A single-document zip is passed
@@ -38,9 +65,8 @@ async function expandBulkArchive(file, driveId, targetParent) {
38
65
  }];
39
66
  const entries = await parseBulkArchive(data);
40
67
  if (!(await Promise.all(entries.map((entry) => isDocumentZip(entry.data)))).some(Boolean)) throw new Error("Archive contains no Powerhouse documents");
41
- const reactorClient = window.ph?.reactorClient;
42
- if (!reactorClient) throw new Error("ReactorClient not initialized");
43
- 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 })];
44
70
  const dirToNode = /* @__PURE__ */ new Map();
45
71
  const ensureDir = async (dirPath, parent) => {
46
72
  const cached = dirToNode.get(dirPath);
@@ -97,14 +123,14 @@ function segmentsBelow(root, node, allNodes) {
97
123
  * initialState (see downloadFolderZip).
98
124
  */
99
125
  async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
100
- const allNodes = drive.state.global.nodes;
126
+ const allNodes = await loadDriveNodes(drive.header.id, { refresh: true });
101
127
  const topName = sanitize(folderNode?.name ?? (drive.state.global.name || drive.header.name));
102
128
  const subtree = folderNode ? [folderNode, ...getDescendants(folderNode, allNodes)] : allNodes;
103
- const entries = { [topName + "/"]: new Uint8Array(0) };
129
+ const entries = { [topName + "/"]: /* @__PURE__ */ new Uint8Array(0) };
104
130
  for (const node of subtree) {
105
131
  if (!isFolderNode(node)) continue;
106
132
  const dir = [topName, ...segmentsBelow(folderNode, node, allNodes)].join("/");
107
- entries[dir + "/"] = new Uint8Array(0);
133
+ entries[dir + "/"] = /* @__PURE__ */ new Uint8Array(0);
108
134
  }
109
135
  const files = subtree.filter(isFileNode);
110
136
  const failed = [];
@@ -149,11 +175,11 @@ async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
149
175
  * showSaveFilePicker (fallback: blob download), mirroring exportFile.
150
176
  */
151
177
  async function downloadFolderZip(drive, folderNode, onProgress) {
152
- const reactorClient = window.ph?.reactorClient;
178
+ const reactorClient = getPHStore()?.reactorClient;
153
179
  if (!reactorClient) throw new Error("ReactorClient not initialized");
154
180
  const result = await buildFolderZip(drive, folderNode, async (id) => {
155
181
  const doc = await reactorClient.get(id);
156
- const operations = await fetchDocumentOperations(reactorClient, doc);
182
+ const operations = await fetchDocumentOperations(reactorClient.read, doc);
157
183
  const initialState = extractInitialState(operations["document"] ?? []);
158
184
  return {
159
185
  ...doc,
@@ -230,25 +256,44 @@ async function waitForDocumentReady(reactorClient, documentId, options) {
230
256
  async function addDrive(input, preferredEditor) {
231
257
  const { isAllowedToCreateDocuments } = getUserPermissions();
232
258
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create drives");
233
- const reactorClient = window.ph?.reactorClient;
259
+ const reactorClient = getPHStore()?.reactorClient;
234
260
  if (!reactorClient) throw new Error("ReactorClient not initialized");
235
- const driveDoc = driveCreateDocument({ global: {
236
- name: input.global.name || "",
237
- icon: input.global.icon ?? null,
238
- nodes: []
239
- } });
240
- if (input.id) driveDoc.header.id = input.id;
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,
268
+ id: input.id || void 0,
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
+ }
241
281
  if (preferredEditor) driveDoc.header.meta = { preferredEditor };
242
- 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();
243
284
  }
244
285
  async function addRemoteDrive(url, driveId, options) {
245
- const reactorClient = window.ph?.reactorClientModule?.client;
286
+ const reactorClient = getFullReactorClient();
246
287
  if (!reactorClient) throw new Error("ReactorClient not initialized");
247
- const sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
288
+ const sync = getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
248
289
  if (!sync) throw new Error("Sync not initialized");
249
- const response = await fetch(url);
250
- if (!response.ok) throw new Error(`Failed to resolve drive info from ${url}`);
251
- const driveInfo = await response.json();
290
+ let driveInfo;
291
+ try {
292
+ driveInfo = await fetchDriveInfo(url);
293
+ } catch (error) {
294
+ if (isDriveAuthError$1(error)) showPHModal({ type: "driveAuthRequired" });
295
+ throw error;
296
+ }
252
297
  const resolvedDriveId = driveId ?? driveInfo.id;
253
298
  const collectionId = DriveCollectionId$1.forDrive(resolvedDriveId);
254
299
  const inFlight = inFlightRemoteRegistrations.get(collectionId.key);
@@ -267,7 +312,7 @@ async function addRemoteDrive(url, driveId, options) {
267
312
  if (isDriveAuthError$1(error)) showPHModal({ type: "driveAuthRequired" });
268
313
  throw error;
269
314
  }
270
- if (options?.awaitInitialSync) await waitForDocumentReady(reactorClient, resolvedDriveId, {
315
+ if (options?.awaitInitialSync) await waitForDocumentReady(reactorClient.read, resolvedDriveId, {
271
316
  timeoutMs: options.initialSyncTimeoutMs,
272
317
  signal: options.signal
273
318
  });
@@ -276,55 +321,49 @@ async function addRemoteDrive(url, driveId, options) {
276
321
  async function deleteDrive(driveId) {
277
322
  const { isAllowedToCreateDocuments } = getUserPermissions();
278
323
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete drives");
279
- const reactorClient = window.ph?.reactorClient;
324
+ const reactorClient = getPHStore()?.reactorClient;
280
325
  if (!reactorClient) throw new Error("ReactorClient not initialized");
281
- const sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
326
+ const sync = getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
282
327
  if (sync) {
283
328
  const collectionId = DriveCollectionId$1.forDrive(driveId);
284
329
  const remotes = sync.list().filter((remote) => remote.meta.collectionId.equals(collectionId));
285
330
  for (const remote of remotes) await sync.remove(remote.meta.name);
286
331
  }
287
- await reactorClient.deleteDocument(driveId, PropagationMode$1.Cascade);
332
+ await (await reactorClient.write.deleteDocument(driveId, PropagationMode$1.Cascade)).readable;
288
333
  }
289
334
  async function renameDrive(driveId, name) {
290
335
  const { isAllowedToCreateDocuments } = getUserPermissions();
291
336
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename drives");
292
- const reactorClient = window.ph?.reactorClientModule?.client;
337
+ const reactorClient = getFullReactorClient();
293
338
  if (!reactorClient) throw new Error("ReactorClient not initialized");
294
- return await reactorClient.rename(driveId, name);
339
+ return await (await reactorClient.write.rename(driveId, name)).document();
295
340
  }
296
341
  async function setDriveAvailableOffline(driveId, availableOffline) {
297
342
  const { isAllowedToCreateDocuments } = getUserPermissions();
298
343
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to change drive availability");
299
- const reactorClient = window.ph?.reactorClient;
344
+ const reactorClient = getPHStore()?.reactorClient;
300
345
  if (!reactorClient) throw new Error("ReactorClient not initialized");
301
- return await reactorClient.execute(driveId, "main", [setAvailableOffline({ availableOffline })]);
346
+ return await (await reactorClient.write.execute(driveId, "main", [setAvailableOffline({ availableOffline })])).document();
302
347
  }
303
348
  async function setDriveSharingType(driveId, sharingType) {
304
349
  const { isAllowedToCreateDocuments } = getUserPermissions();
305
350
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to change drive sharing type");
306
- const reactorClient = window.ph?.reactorClient;
351
+ const reactorClient = getPHStore()?.reactorClient;
307
352
  if (!reactorClient) throw new Error("ReactorClient not initialized");
308
- return await reactorClient.execute(driveId, "main", [setSharingType({ type: sharingType })]);
353
+ return await (await reactorClient.write.execute(driveId, "main", [setSharingType({ type: sharingType })])).document();
309
354
  }
310
355
  async function setDriveMetadata(driveId, metadata) {
311
356
  const { isAllowedToCreateDocuments } = getUserPermissions();
312
357
  if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to update drive metadata");
313
- const reactorClient = window.ph?.reactorClient;
358
+ const reactorClient = getPHStore()?.reactorClient;
314
359
  if (!reactorClient) throw new Error("ReactorClient not initialized");
315
360
  const actions = [];
316
361
  if (metadata.name) actions.push(setDriveName({ name: metadata.name }));
317
362
  if (metadata.icon !== void 0) actions.push(setDriveIcon({ icon: metadata.icon }));
318
363
  if (actions.length === 0) return;
319
- return await reactorClient.execute(driveId, "main", actions);
364
+ return await (await reactorClient.write.execute(driveId, "main", actions)).document();
320
365
  }
321
366
  //#endregion
322
- //#region src/constants.ts
323
- const DEFAULT_DRIVE_EDITOR_ID = "powerhouse/generic-drive-explorer";
324
- const COMMON_PACKAGE_ID = "powerhouse/common";
325
- /** Document types that represent a "drive": a container of nodes. */
326
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
327
- //#endregion
328
367
  //#region src/graphql/adapters.ts
329
368
  function phDocumentFromQuery(document, documentSchema) {
330
369
  const phDocument = {
@@ -365,6 +404,10 @@ function identifierFromMutateDocumentOperationVariables(variables) {
365
404
  //#endregion
366
405
  //#region src/graphql/constants.ts
367
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
+ */
368
411
  const DEFAULT_SWITCHBOARD_URL = "http://localhost:4001/graphql";
369
412
  const graphqlEventsToSyncDrive = [
370
413
  "CreateEmptyDocument",
@@ -384,7 +427,7 @@ const graphqlDocumentsEvents = ["DeleteDocuments"];
384
427
  //#endregion
385
428
  //#region src/graphql/fetchers.ts
386
429
  async function reactorGraphqlFetchDocument(identifier, documentSchema) {
387
- const client = window.ph?.reactorGraphQLClient;
430
+ const client = getPHStore()?.reactorGraphQLClient;
388
431
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
389
432
  try {
390
433
  const document = (await client.GetDocument({ identifier })).document?.document;
@@ -395,7 +438,7 @@ async function reactorGraphqlFetchDocument(identifier, documentSchema) {
395
438
  }
396
439
  }
397
440
  async function reactorGraphqlBatchFetchDocuments(identifiers) {
398
- 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");
399
442
  const promises = map(identifiers, (identifier) => reactorGraphqlFetchDocument(identifier));
400
443
  return await Promise.all(promises);
401
444
  }
@@ -480,11 +523,34 @@ var DocumentFetcher = class {
480
523
  };
481
524
  //#endregion
482
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
+ }
529
+ async function fetchDocumentForRefetch(identifier) {
530
+ const client = getPHStore()?.reactorGraphQLClient;
531
+ if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
532
+ const notFound = (cause) => new Error(`Document not found: ${identifier}`, { cause });
533
+ let result;
534
+ try {
535
+ result = await client.GetDocument({ identifier });
536
+ } catch (error) {
537
+ if ((error instanceof ClientError ? (error.response.errors ?? []).map((e) => e.message) : []).some(isMissingDocumentMessage)) throw notFound(error);
538
+ throw error;
539
+ }
540
+ const document = result.document?.document;
541
+ if (!document) throw notFound();
542
+ return phDocumentFromQuery(document);
543
+ }
483
544
  var GraphQLClientDocumentCache = class {
484
545
  fetcher;
485
546
  documents = /* @__PURE__ */ new Map();
486
547
  batchPromises = /* @__PURE__ */ new Map();
487
548
  listeners = /* @__PURE__ */ new Map();
549
+ refetcher = new DocumentRefetcher({
550
+ documents: this.documents,
551
+ fetch: fetchDocumentForRefetch,
552
+ notify: (id) => this.notify(id)
553
+ });
488
554
  constructor() {
489
555
  this.fetcher = new DocumentFetcher();
490
556
  window.addEventListener("MutateDocument", (event) => {
@@ -496,10 +562,9 @@ var GraphQLClientDocumentCache = class {
496
562
  }
497
563
  get(id, refetch) {
498
564
  const current = this.documents.get(id);
499
- if (current) {
500
- if (current.status === "pending") return current;
501
- if (!refetch) return current;
502
- }
565
+ if (current && !refetch) return current;
566
+ if (current && current.status !== "rejected") return this.refetcher.refetch(id);
567
+ this.refetcher.forget(id);
503
568
  const promise = addPromiseState(this.fetcher.get(id).then((document) => {
504
569
  this.invalidateBatchesContaining(id);
505
570
  return document;
@@ -507,6 +572,9 @@ var GraphQLClientDocumentCache = class {
507
572
  this.documents.set(id, promise);
508
573
  return promise;
509
574
  }
575
+ getRefetchState(id) {
576
+ return this.refetcher.getState(id);
577
+ }
510
578
  getBatch(ids) {
511
579
  const key = ids.join(",");
512
580
  const cached = this.batchPromises.get(key);
@@ -559,12 +627,12 @@ var GraphQLClientDocumentCache = class {
559
627
  for (const listener of listeners) listener();
560
628
  }
561
629
  async handleDocumentMutated(id) {
562
- this.invalidateBatchesContaining(id);
563
- await this.get(id);
564
- this.notify(id);
630
+ if (!this.documents.has(id)) return;
631
+ await this.get(id, true);
565
632
  }
566
633
  handleDocumentDeleted(id) {
567
634
  this.documents.delete(id);
635
+ this.refetcher.forget(id);
568
636
  this.invalidateBatchesContaining(id);
569
637
  this.notify(id);
570
638
  }
@@ -575,7 +643,7 @@ var GraphQLClientDocumentCache = class {
575
643
  //#endregion
576
644
  //#region src/graphql/mutators.ts
577
645
  async function reactorGraphqlCreateDocument(document, parentIdentifier = DEFAULT_DRIVE_ID) {
578
- const client = window.ph?.reactorGraphQLClient;
646
+ const client = getPHStore()?.reactorGraphQLClient;
579
647
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
580
648
  return await client.CreateDocument({
581
649
  document,
@@ -583,17 +651,17 @@ async function reactorGraphqlCreateDocument(document, parentIdentifier = DEFAULT
583
651
  });
584
652
  }
585
653
  async function reactorGraphqlDeleteDocument(identifier) {
586
- const client = window.ph?.reactorGraphQLClient;
654
+ const client = getPHStore()?.reactorGraphQLClient;
587
655
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
588
656
  return await client.DeleteDocument({ identifier });
589
657
  }
590
658
  async function reactorGraphqlDeleteDocuments(identifiers) {
591
- const client = window.ph?.reactorGraphQLClient;
659
+ const client = getPHStore()?.reactorGraphQLClient;
592
660
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
593
661
  return await client.DeleteDocuments({ identifiers });
594
662
  }
595
663
  async function reactorGraphqlMutateDocument(documentIdentifier, ...actions) {
596
- const client = window.ph?.reactorGraphQLClient;
664
+ const client = getPHStore()?.reactorGraphQLClient;
597
665
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
598
666
  return await client.MutateDocument({
599
667
  documentIdentifier,
@@ -609,10 +677,38 @@ function useAllowedDocumentModelModules() {
609
677
  return documentModelModules?.filter((module) => allowedDocumentTypes.includes(module.documentModel.global.id));
610
678
  }
611
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
612
706
  //#region src/hooks/selected-folder.ts
613
- /** Returns the selected folder. */
707
+ /** Returns the selected folder: the drive app's open folder, else the app's. */
614
708
  function useSelectedFolder() {
709
+ const context = useDriveContext();
615
710
  const selectedNode = useSelectedNode();
711
+ if (context?.folder) return context.folder;
616
712
  if (isFolderNodeKind(selectedNode)) return selectedNode;
617
713
  }
618
714
  //#endregion
@@ -785,6 +881,91 @@ function buildSnapshot(syncManager) {
785
881
  return map;
786
882
  }
787
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
788
969
  //#region src/hooks/supported-document-types.ts
789
970
  /** Returns the supported document types for the reactor (derived from the document model modules) */
790
971
  function useSupportedDocumentTypesInReactor() {
@@ -794,13 +975,13 @@ function useSupportedDocumentTypesInReactor() {
794
975
  //#region src/hooks/document-types.ts
795
976
  /** Returns the document types a app supports.
796
977
  *
797
- * If present, uses the `allowedDocumentTypes` config value.
798
- * 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.
799
980
  */
800
981
  function useDocumentTypes() {
801
982
  const allowedDocumentTypes = useAllowedDocumentTypes();
802
983
  const supportedDocumentTypes = useSupportedDocumentTypesInReactor();
803
- return allowedDocumentTypes ?? supportedDocumentTypes;
984
+ return allowedDocumentTypes?.length ? allowedDocumentTypes : supportedDocumentTypes;
804
985
  }
805
986
  //#endregion
806
987
  //#region src/hooks/document-version-status.ts
@@ -982,6 +1163,14 @@ function useEditorModulesForDocumentType(documentType) {
982
1163
  if (!documentType) return void 0;
983
1164
  return editorModules?.filter((module) => module.documentTypes.includes(documentType));
984
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
+ }
985
1174
  //#endregion
986
1175
  //#region src/utils/preload-editor.ts
987
1176
  function preloadEditorModule(module) {
@@ -1111,7 +1300,8 @@ function useDropFile(handleAddFile) {
1111
1300
  //#endregion
1112
1301
  //#region src/hooks/folder-by-id.ts
1113
1302
  function useFolderById(id) {
1114
- return useFolderNodesInSelectedDrive()?.find((n) => n.id === id);
1303
+ const node = useNodeById(id);
1304
+ return isFolderNodeKind(node) ? node : void 0;
1115
1305
  }
1116
1306
  //#endregion
1117
1307
  //#region src/graphql/events.ts
@@ -1143,24 +1333,24 @@ function useInitReactorGraphqlClient(switchboardUrl = DEFAULT_SWITCHBOARD_URL, d
1143
1333
  return hasInit;
1144
1334
  }
1145
1335
  async function reactorGraphqlFetchDrive(identifier) {
1146
- const client = window.ph?.reactorGraphQLClient;
1336
+ const client = getPHStore()?.reactorGraphQLClient;
1147
1337
  if (!client) throw new Error("Please call `useInitReactorGraphqlClient` to use its functions");
1148
1338
  const result = await client.GetDocument({ identifier });
1149
1339
  if (!result.document?.document) throw new Error("Could not fetch drive with id: " + identifier);
1150
1340
  return phDocumentFromQuery(result.document.document, DriveDocumentSchema);
1151
1341
  }
1152
1342
  async function reactorGraphqlSyncDrive(driveId) {
1153
- 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");
1154
1344
  const drive = await reactorGraphqlFetchDrive(driveId);
1155
1345
  setDrives([drive]);
1156
- setSelectedDrive(drive);
1346
+ selectDrive(drive);
1157
1347
  }
1158
1348
  async function initGraphQLReactorClientWithDocumentCache(switchboardUrl, driveId) {
1159
- if (!window.ph) window.ph = {};
1160
1349
  callEventHandlerRegisterFunctions(commonGlobalEventHandlerFunctions);
1161
- setGraphQLReactorClient(createClient(switchboardUrl, documentCacheClientMiddleware));
1350
+ const client = createClient(switchboardUrl, documentCacheClientMiddleware);
1351
+ setGraphQLReactorClient(client);
1162
1352
  await reactorGraphqlSyncDrive(driveId);
1163
- setSelectedNode(void 0);
1353
+ selectNode(void 0);
1164
1354
  setDocumentCache(new GraphQLClientDocumentCache());
1165
1355
  forEach(graphqlEventsToSyncDrive, (name) => {
1166
1356
  window.addEventListener(name, () => {
@@ -1201,6 +1391,7 @@ function resolveNode(driveId, node) {
1201
1391
  return node?.id !== driveId ? node : void 0;
1202
1392
  }
1203
1393
  function useNodeActions() {
1394
+ const setSelectedNode = useSetSelectedNode();
1204
1395
  const [selectedDrive] = useSelectedDriveSafe();
1205
1396
  const selectedFolder = useSelectedFolder();
1206
1397
  const selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);
@@ -1208,7 +1399,8 @@ function useNodeActions() {
1208
1399
  const drives = useDrives();
1209
1400
  async function onAddFile(file, parent) {
1210
1401
  if (!selectedDriveId) return;
1211
- return addFileWithProgress(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id, void 0, void 0, "duplicate");
1402
+ const fileName = file.name.replace(/\..+/gim, "");
1403
+ return addFileWithProgress(file, selectedDriveId, fileName, resolveNode(selectedDriveId, parent)?.id, void 0, void 0, "duplicate");
1212
1404
  }
1213
1405
  async function onAddFolder(name, parent) {
1214
1406
  if (!selectedDriveId) return;
@@ -1229,7 +1421,8 @@ function useNodeActions() {
1229
1421
  console.error(`Node ${src.id} not found`);
1230
1422
  return;
1231
1423
  }
1232
- await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));
1424
+ const resolvedTarget = resolveNode(selectedDriveId, target);
1425
+ await copyNode$1(selectedDriveId, resolvedSrc, resolvedTarget);
1233
1426
  }
1234
1427
  async function onMoveNode(src, target) {
1235
1428
  if (!selectedDriveId) return;
@@ -1249,7 +1442,8 @@ function useNodeActions() {
1249
1442
  console.error(`Node ${src.id} not found`);
1250
1443
  return;
1251
1444
  }
1252
- await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));
1445
+ const target = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);
1446
+ await copyNode$1(selectedDriveId, resolvedSrc, target);
1253
1447
  }
1254
1448
  async function onAddAndSelectNewFolder(name) {
1255
1449
  if (!name) return;
@@ -1261,8 +1455,10 @@ function useNodeActions() {
1261
1455
  }
1262
1456
  async function onRenameDriveNodes(newName, nodeId) {
1263
1457
  if (!drives) return;
1264
- const drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));
1265
- 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)));
1266
1462
  }
1267
1463
  return {
1268
1464
  onAddFile,
@@ -1276,12 +1472,6 @@ function useNodeActions() {
1276
1472
  };
1277
1473
  }
1278
1474
  //#endregion
1279
- //#region src/hooks/node-by-id.ts
1280
- /** Returns a node in the selected drive by id. */
1281
- function useNodeById(id) {
1282
- return useNodesInSelectedDrive()?.find((n) => n.id === id);
1283
- }
1284
- //#endregion
1285
1475
  //#region src/hooks/node-path.ts
1286
1476
  /** Returns the path to a node in the selected drive */
1287
1477
  function useNodePathById(id) {
@@ -1309,6 +1499,56 @@ function useParentFolderForSelectedNode() {
1309
1499
  return useNodeParentFolderById(useSelectedNode()?.id);
1310
1500
  }
1311
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
1312
1552
  //#region src/hooks/subgraph-modules.ts
1313
1553
  function useSubgraphModules() {
1314
1554
  return useVetraPackages().flatMap((pkg) => pkg.subgraphs || []);
@@ -1672,17 +1912,38 @@ const syncStatusToUI = {
1672
1912
  async function getDrives(reactor) {
1673
1913
  return (await Promise.all(DRIVE_DOCUMENT_TYPES.map((type) => reactor.find({ type })))).flatMap((r) => r.results);
1674
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
+ }
1675
1932
  function getSyncStatus(documentId, sharingType) {
1676
1933
  return Promise.resolve(getSyncStatusSync(documentId, sharingType));
1677
1934
  }
1678
1935
  function getSyncStatusSync(documentId, sharingType) {
1679
- if (sharingType === "LOCAL") return;
1680
- const syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
1936
+ if (sharingType === "LOCAL" || typeof window === "undefined") return;
1937
+ const syncManager = getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
1681
1938
  if (!syncManager) return;
1682
1939
  const status = syncManager.getSyncStatus(documentId);
1683
1940
  if (status === void 0) return;
1684
1941
  return syncStatusToUI[status];
1685
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
+ }
1686
1947
  //#endregion
1687
1948
  //#region src/utils/get-revision-from-date.ts
1688
1949
  const getRevisionFromDate = (startDate, endDate, operations = []) => {
@@ -1694,186 +1955,8 @@ const getRevisionFromDate = (startDate, endDate, operations = []) => {
1694
1955
  return operation ? operation.index : 0;
1695
1956
  };
1696
1957
  //#endregion
1697
- //#region src/utils/switchboard.ts
1698
- async function getDriveIdBySlug(driveUrl, slug) {
1699
- if (!driveUrl) return;
1700
- const urlParts = driveUrl.split("/");
1701
- urlParts.pop();
1702
- urlParts.pop();
1703
- urlParts.push("drives");
1704
- const drivesUrl = urlParts.join("/");
1705
- return (await (await fetch(drivesUrl, {
1706
- method: "POST",
1707
- headers: { "Content-Type": "application/json" },
1708
- body: JSON.stringify({
1709
- query: `
1710
- query getDriveIdBySlug($slug: String!) {
1711
- driveIdBySlug(slug: $slug)
1712
- }
1713
- `,
1714
- variables: { slug }
1715
- })
1716
- })).json()).data.driveIdBySlug;
1717
- }
1718
- function getSlugFromDriveUrl(driveUrl) {
1719
- return driveUrl.split("/").pop();
1720
- }
1721
- function getSwitchboardGatewayUrlFromDriveUrl(driveUrl) {
1722
- const urlParts = driveUrl.split("/");
1723
- urlParts.pop();
1724
- urlParts.pop();
1725
- urlParts.push("graphql");
1726
- return urlParts.join("/");
1727
- }
1728
- function getDocumentGraphqlQuery() {
1729
- const loc = GetDocumentWithOperationsDocument.loc;
1730
- if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
1731
- return loc.source.body;
1732
- }
1733
- /**
1734
- * The base URL of the switchboard that serves a drive's GraphQL channel.
1735
- *
1736
- * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the
1737
- * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does
1738
- * not end with the suffix is unexpected — fall back to its origin.
1739
- */
1740
- function getSwitchboardBaseFromChannelUrl(channelUrl) {
1741
- if (channelUrl.endsWith("/graphql/r")) return channelUrl.slice(0, -GQL_CHANNEL_SUFFIX.length);
1742
- return new URL(channelUrl).origin;
1743
- }
1744
- /**
1745
- * The GraphQL name the switchboard exposes a document model under. Mirrors
1746
- * `getDocumentModelSchemaName` on the server (`create-schema.ts`): the root
1747
- * query field and the state type names are all derived from the model's
1748
- * `global.name`.
1749
- */
1750
- function getDocumentModelSchemaName(model) {
1751
- return pascalCase(model.documentModel.global.name.replaceAll("/", " "));
1752
- }
1753
- function buildStateTypeMap(definitions) {
1754
- const typeMap = /* @__PURE__ */ new Map();
1755
- for (const def of definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) typeMap.set(def.name.value, def);
1756
- return typeMap;
1757
- }
1758
- /**
1759
- * Recursively expands the fields of a state object type into a GraphQL
1760
- * selection. Objects expand their sub-selection (lists expand their item
1761
- * type); enums, scalars, and built-ins are leaves.
1762
- */
1763
- function expandStateFields(typeDef, typeMap) {
1764
- return (typeDef.fields ?? []).map((field) => {
1765
- const fieldName = field.name.value;
1766
- let typeNode = field.type;
1767
- if (typeNode.kind === Kind.NON_NULL_TYPE) typeNode = typeNode.type;
1768
- if (typeNode.kind === Kind.LIST_TYPE) {
1769
- let itemType = typeNode.type;
1770
- if (itemType.kind === Kind.NON_NULL_TYPE) itemType = itemType.type;
1771
- if (itemType.kind === Kind.LIST_TYPE) throw new Error(`Nested lists are not supported in state selections: ${fieldName}`);
1772
- if (itemType.kind !== Kind.NAMED_TYPE) return fieldName;
1773
- const itemTypeDef = typeMap.get(itemType.name.value);
1774
- if (!itemTypeDef) return fieldName;
1775
- return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;
1776
- }
1777
- if (typeNode.kind !== Kind.NAMED_TYPE) return fieldName;
1778
- const typeDef = typeMap.get(typeNode.name.value);
1779
- if (!typeDef) return fieldName;
1780
- return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;
1781
- }).join(" ");
1782
- }
1783
- /**
1784
- * Finds the root state object type in a state SDL. Root state types follow
1785
- * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last
1786
- * by convention — the same resolution order the server uses
1787
- * (`extractRootTypeName` in `create-schema.ts`).
1788
- */
1789
- function findRootStateType(definitions, candidates) {
1790
- let lastObjectType = null;
1791
- for (const def of definitions) {
1792
- if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
1793
- if (candidates.includes(def.name.value)) return def;
1794
- lastObjectType = def;
1795
- }
1796
- if (!lastObjectType) throw new Error("No root state type found in the document model schema");
1797
- return lastObjectType;
1798
- }
1799
- /**
1800
- * Derives the subselection for the document's `global` state scope from the
1801
- * model's state SDL (e.g. `name total`), expanding object fields
1802
- * recursively. Throws when the schema is missing, unparseable, or has no
1803
- * root object type — the caller falls back to the generic document query.
1804
- */
1805
- function getDocumentStateSelection(model) {
1806
- const schema = model.documentModel.global.specifications.at(-1)?.state.global.schema;
1807
- if (!schema || !schema.trim()) throw new Error("Document model has no global state schema");
1808
- const ast = parse(schema);
1809
- const typeMap = buildStateTypeMap(ast.definitions);
1810
- const documentName = getDocumentModelSchemaName(model);
1811
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}State`, `${documentName}GlobalState`]), typeMap);
1812
- }
1813
- function getLocalStateSelection(localSchema, documentName) {
1814
- const ast = parse(localSchema);
1815
- const typeMap = buildStateTypeMap(ast.definitions);
1816
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}LocalState`]), typeMap);
1817
- }
1818
- /**
1819
- * Builds a query scoped to a document type's own subgraph root field,
1820
- * selecting the document and its full typed state. The shape mirrors what
1821
- * the switchboard generates per model (`generateNewApiSchema` in
1822
- * `create-schema.ts`): `<Name> { document(identifier:) { document { ...
1823
- * state { auth document global local } } } childIds }`.
1824
- */
1825
- function buildModelScopedQuery(model) {
1826
- const globalState = model.documentModel.global;
1827
- const documentName = getDocumentModelSchemaName(model);
1828
- const globalSelection = getDocumentStateSelection(model);
1829
- const localSchema = globalState.specifications.at(-1)?.state.local.schema ?? "";
1830
- const localSelection = localSchema.includes(`type ${documentName}LocalState`) ? getLocalStateSelection(localSchema, documentName) : null;
1831
- return [
1832
- "query GetDocument($identifier: String!) {",
1833
- ` ${documentName} {`,
1834
- " document(identifier: $identifier) {",
1835
- " document {",
1836
- " id",
1837
- " name",
1838
- " documentType",
1839
- " state {",
1840
- " auth",
1841
- " document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }",
1842
- ` global { ${globalSelection} }`,
1843
- ` ${localSelection ? `local { ${localSelection} }` : "local"}`,
1844
- " }",
1845
- " }",
1846
- " childIds",
1847
- " }",
1848
- " }",
1849
- "}"
1850
- ].join("\n");
1851
- }
1852
- function buildDocumentSubgraphQuery(documentType, identifier, model, authToken) {
1853
- let query;
1854
- if (model && model.documentModel.global.id === documentType) try {
1855
- query = buildModelScopedQuery(model);
1856
- } catch (error) {
1857
- console.warn("Could not derive a document-scoped query from the document model, falling back to the generic document query:", error);
1858
- query = getDocumentGraphqlQuery();
1859
- }
1860
- else query = getDocumentGraphqlQuery();
1861
- const variables = { identifier };
1862
- const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
1863
- const payload = {
1864
- document: query.trim(),
1865
- variables: JSON.stringify(variables, null, 2)
1866
- };
1867
- if (headers) payload.headers = JSON.stringify(headers);
1868
- return lzString.compressToEncodedURIComponent(JSON.stringify(payload));
1869
- }
1870
- function buildDocumentSubgraphUrl(channelUrl, documentType, identifier, model, authToken) {
1871
- const encodedQuery = buildDocumentSubgraphQuery(documentType, identifier, model, authToken);
1872
- return `${getSwitchboardBaseFromChannelUrl(channelUrl)}/explorer?explorerURLState=${encodedQuery}`;
1873
- }
1874
- //#endregion
1875
1958
  //#region src/utils/upgrade-preview.ts
1876
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
1959
+ const NON_DOMAIN_SCOPES = /* @__PURE__ */ new Set(["auth", "document"]);
1877
1960
  function isPlainObject(value) {
1878
1961
  return typeof value === "object" && value !== null && !Array.isArray(value);
1879
1962
  }
@@ -1961,7 +2044,7 @@ function getDocumentUpgradePreview(document, registry) {
1961
2044
  }
1962
2045
  const addedFields = [];
1963
2046
  const removedFields = [];
1964
- const scopes = new Set([...Object.keys(document.state), ...Object.keys(upgraded.state)]);
2047
+ const scopes = /* @__PURE__ */ new Set([...Object.keys(document.state), ...Object.keys(upgraded.state)]);
1965
2048
  for (const scope of scopes) {
1966
2049
  if (NON_DOMAIN_SCOPES.has(scope)) continue;
1967
2050
  const beforeScope = document.state[scope];
@@ -2044,7 +2127,9 @@ const useOnDropFile = (documentTypesOverride) => {
2044
2127
  console.warn("No selected drive - upload skipped");
2045
2128
  return;
2046
2129
  }
2047
- return await addFileWithProgress(file, selectedDriveId, file.name.replace(/\..+/gim, ""), targetFolder?.id ?? selectedFolder?.id, onProgress, documentTypesOverride ?? documentTypes, resolveConflict);
2130
+ const fileName = file.name.replace(/\..+/gim, "");
2131
+ const targetNodeId = targetFolder?.id ?? selectedFolder?.id;
2132
+ return await addFileWithProgress(file, selectedDriveId, fileName, targetNodeId, onProgress, documentTypesOverride ?? documentTypes, resolveConflict);
2048
2133
  };
2049
2134
  return onDropFile;
2050
2135
  };
@@ -2063,6 +2148,19 @@ function useUserPermissions() {
2063
2148
  };
2064
2149
  }
2065
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
2066
2164
  //#region src/hooks/attachment-progress.ts
2067
2165
  const IDLE_PROGRESS = {
2068
2166
  percent: 0,
@@ -2158,6 +2256,11 @@ function useAttachments() {
2158
2256
  const service = useAttachmentService();
2159
2257
  return service ? clientFor(service) : void 0;
2160
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
+ }
2161
2264
  const DEFAULT_PREVIEW_RETRIES = 3;
2162
2265
  const DEFAULT_PREVIEW_RETRY_DELAY_MS = 3e3;
2163
2266
  const IDLE_PREVIEW = {
@@ -2305,7 +2408,7 @@ function useAttachmentUpload() {
2305
2408
  };
2306
2409
  }, []);
2307
2410
  return {
2308
- preprocess: useCallback(async (file) => {
2411
+ preprocess: useCallback(async (file, options) => {
2309
2412
  if (!client) throw new Error("AttachmentClient not available");
2310
2413
  const runId = ++runIdRef.current;
2311
2414
  setState({
@@ -2313,7 +2416,7 @@ function useAttachmentUpload() {
2313
2416
  stage: "hashing"
2314
2417
  });
2315
2418
  try {
2316
- return await client.preprocess(file);
2419
+ return await client.preprocess(file, options);
2317
2420
  } catch (err) {
2318
2421
  const error = err instanceof Error ? err : new Error(String(err));
2319
2422
  if (mountedRef.current && runId === runIdRef.current) setState((prev) => ({
@@ -2413,7 +2516,8 @@ async function dropAllReactorStorage(pg) {
2413
2516
  const DEFAULT_DEBOUNCE_DELAY_MS = 200;
2414
2517
  const DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;
2415
2518
  async function _refreshReactorData(reactor) {
2416
- setDrives(await getDrives(reactor));
2519
+ const drives = await getDrives(reactor);
2520
+ setDrives(drives);
2417
2521
  }
2418
2522
  async function _refreshReactorDataClient(reactor) {
2419
2523
  if (!reactor) return;
@@ -2459,6 +2563,331 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
2459
2563
  }
2460
2564
  const refreshReactorData = createDebouncedRefreshReactorData();
2461
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
+ }
2462
2891
  //#endregion
2463
2892
  //#region src/remote-controller/action-tracker.ts
2464
2893
  /**
@@ -2501,6 +2930,7 @@ var ActionTracker = class {
2501
2930
  */
2502
2931
  const DEFAULT_PAGE_SIZE = 100;
2503
2932
  var RemoteClient = class {
2933
+ client;
2504
2934
  pageSize;
2505
2935
  constructor(client, pageSize) {
2506
2936
  this.client = client;
@@ -2726,7 +3156,13 @@ var RemoteDocumentController = class RemoteDocumentController {
2726
3156
  tracker = new ActionTracker();
2727
3157
  options;
2728
3158
  documentId;
3159
+ /** The remote's id for the document; `documentId` may be a slug. */
3160
+ canonicalDocumentId;
2729
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;
2730
3166
  hasPulled = false;
2731
3167
  pushScheduled = false;
2732
3168
  pushQueue = Promise.resolve();
@@ -2735,6 +3171,7 @@ var RemoteDocumentController = class RemoteDocumentController {
2735
3171
  this.inner = inner;
2736
3172
  this.options = options;
2737
3173
  this.documentId = options.documentId ?? "";
3174
+ if (this.documentId === "") this.uncreated = uncreatedDocument(inner.document);
2738
3175
  this.remoteClient = new RemoteClient(options.client, options.operationsPageSize);
2739
3176
  this.setupActionInterceptors();
2740
3177
  }
@@ -2784,6 +3221,7 @@ var RemoteDocumentController = class RemoteDocumentController {
2784
3221
  try {
2785
3222
  await this.ensureRemoteDocument();
2786
3223
  if (this.options.onConflict && tracked.length > 0) tracked = await this.handleConflicts(tracked, this.options.onConflict);
3224
+ if (this.options.signer && tracked.length > 0) await this.resolveCanonicalDocumentId();
2787
3225
  } catch (error) {
2788
3226
  this.tracker.restore(tracked);
2789
3227
  throw error;
@@ -2814,35 +3252,115 @@ var RemoteDocumentController = class RemoteDocumentController {
2814
3252
  async pull() {
2815
3253
  if (this.documentId === "") throw new Error("Cannot pull: no document ID set");
2816
3254
  const { remoteDoc, operations } = await this.fetchDocumentAndOperations();
2817
- const pulledDocument = buildPulledDocument(remoteDoc, operations, this.inner.module.utils.createDocument(), this.options.branch ?? "main");
2818
- const ControllerClass = this.inner.constructor;
2819
- this.inner = new ControllerClass(pulledDocument);
2820
- this.setupActionInterceptors();
3255
+ this.canonicalDocumentId = remoteDoc.id;
3256
+ const initialDoc = this.inner.module.utils.createDocument();
3257
+ const pulledDocument = buildPulledDocument(remoteDoc, operations, initialDoc, this.options.branch ?? "main");
3258
+ this.replaceInner(pulledDocument);
2821
3259
  this.tracker.clear();
2822
3260
  this.remoteRevision = extractRevisionMap(remoteDoc.revisionsList);
2823
3261
  this.notifyListeners("pull");
2824
3262
  return remoteDoc;
2825
3263
  }
2826
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
+ /**
2827
3300
  * Pull an existing document from remote and create a controller for it.
2828
3301
  */
2829
3302
  static async pull(ControllerClass, options) {
2830
- const remote = new RemoteDocumentController(new ControllerClass(), options);
3303
+ const temp = new ControllerClass();
3304
+ const remote = new RemoteDocumentController(temp, options);
2831
3305
  if (options.documentId) await remote.pull();
3306
+ else await remote.headNewDocument();
2832
3307
  return remote;
2833
3308
  }
2834
3309
  /**
2835
3310
  * Wrap an existing controller instance with remote capabilities.
2836
3311
  * Pending local actions on the inner controller are NOT tracked
2837
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.
2838
3315
  */
2839
3316
  static from(controller, options) {
2840
- return new RemoteDocumentController(controller, options);
3317
+ const remote = new RemoteDocumentController(controller, options);
3318
+ remote.takesHostPolicy = remote.documentId === "";
3319
+ return remote;
3320
+ }
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);
2841
3339
  }
2842
- /** Create the document on the remote if it doesn't exist yet. */
3340
+ /** Creates the remote from the local header, so both run the versions its creator chose. */
2843
3341
  async ensureRemoteDocument() {
2844
3342
  if (this.documentId !== "") return;
2845
- this.documentId = (await this.remoteClient.createEmptyDocument(this.inner.header.documentType, this.options.parentIdentifier)).id;
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);
3348
+ this.documentId = remoteDoc.id;
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);
2846
3364
  }
2847
3365
  /** Set up interceptors for all action methods on the inner controller. */
2848
3366
  setupActionInterceptors() {
@@ -2850,25 +3368,45 @@ var RemoteDocumentController = class RemoteDocumentController {
2850
3368
  for (const actionType in module.actions) {
2851
3369
  if (actionType in RemoteDocumentController.prototype) continue;
2852
3370
  Object.defineProperty(this, actionType, {
2853
- value: (input) => {
2854
- const opCountsBefore = {};
2855
- for (const scope in this.inner.operations) opCountsBefore[scope] = this.inner.operations[scope].length;
2856
- this.inner[actionType](input);
2857
- const newOp = this.findNewOperation(opCountsBefore);
2858
- const prevOp = newOp ? this.getLastOperationInScope(newOp.action.scope, newOp) : void 0;
2859
- const prevOpHash = prevOp?.hash ?? "";
2860
- const prevOpIndex = prevOp?.index ?? -1;
2861
- if (!newOp) return this;
2862
- this.tracker.track(newOp.action, prevOpHash, prevOpIndex);
2863
- this.notifyListeners("action");
2864
- if (this.options.mode === "streaming") this.schedulePush();
2865
- return this;
2866
- },
3371
+ value: (input) => this.dispatchModelAction(actionType, input),
2867
3372
  enumerable: true,
2868
3373
  configurable: true
2869
3374
  });
2870
3375
  }
2871
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
+ }
2872
3410
  /**
2873
3411
  * Find the new operation added after applying an action,
2874
3412
  * by comparing current operation counts against a previous snapshot.
@@ -2897,6 +3435,7 @@ var RemoteDocumentController = class RemoteDocumentController {
2897
3435
  async handleConflicts(localTracked, strategy) {
2898
3436
  const remoteResult = await this.remoteClient.getDocument(this.documentId, this.options.branch);
2899
3437
  if (!remoteResult) throw new Error(`Document "${this.documentId}" not found on remote`);
3438
+ this.canonicalDocumentId ??= remoteResult.document.id;
2900
3439
  const currentRevision = extractRevisionMap(remoteResult.document.revisionsList);
2901
3440
  const localScopes = new Set(localTracked.map((t) => t.action.scope));
2902
3441
  if (!hasRevisionConflict(currentRevision, this.remoteRevision, localScopes)) return localTracked;
@@ -2921,13 +3460,34 @@ var RemoteDocumentController = class RemoteDocumentController {
2921
3460
  */
2922
3461
  async pullAndReplay(actions) {
2923
3462
  await this.pull();
3463
+ const replayedIds = /* @__PURE__ */ new Map();
2924
3464
  for (const action of actions) {
2925
- const methodName = screamingSnakeToCamel(action.type);
2926
- const method = this[methodName];
2927
- 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);
2928
3470
  }
2929
3471
  return this.tracker.flush();
2930
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
+ }
2931
3491
  /** Prepare actions for push, optionally signing them. */
2932
3492
  async prepareActionsForPush(tracked) {
2933
3493
  const actions = [];
@@ -2945,18 +3505,34 @@ var RemoteDocumentController = class RemoteDocumentController {
2945
3505
  }
2946
3506
  return actions;
2947
3507
  }
3508
+ /**
3509
+ * The remote's id for `documentId`, which may be a slug. A signature binds
3510
+ * the id the remote verifies against, so a slug is never signed.
3511
+ */
3512
+ async resolveCanonicalDocumentId() {
3513
+ if (this.canonicalDocumentId) return this.canonicalDocumentId;
3514
+ let result;
3515
+ try {
3516
+ result = await this.remoteClient.getDocument(this.documentId, this.options.branch);
3517
+ } catch (error) {
3518
+ throw new Error(`Cannot sign for "${this.documentId}": its document id could not be resolved on the remote`, { cause: error });
3519
+ }
3520
+ if (!result) throw new Error(`Cannot sign for "${this.documentId}": no document with that identifier on the remote`);
3521
+ this.canonicalDocumentId = result.document.id;
3522
+ return result.document.id;
3523
+ }
2948
3524
  /** Sign an action using the configured signer, preserving existing signatures. */
2949
3525
  async signAction(action) {
2950
3526
  const signer = this.options.signer;
2951
- const signature = await signer.signAction(action);
3527
+ const target = actionSigningTarget(action, await this.resolveCanonicalDocumentId(), this.options.branch ?? "main");
3528
+ const signature = await signer.signAction(action, target);
2952
3529
  const existingSignatures = action.context?.signer?.signatures ?? [];
2953
3530
  return {
2954
3531
  ...action,
2955
3532
  context: {
2956
3533
  ...action.context,
2957
3534
  signer: {
2958
- user: signer.user,
2959
- app: signer.app,
3535
+ ...actionSignerIdentity(signer),
2960
3536
  signatures: [...existingSignatures, signature]
2961
3537
  }
2962
3538
  }
@@ -3105,6 +3681,6 @@ var BrowserLocalStorage = class extends BaseStorage {
3105
3681
  }
3106
3682
  };
3107
3683
  //#endregion
3108
- 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, ISSUER_TYPE, InMemoryQueue, IntervalPollTimer, MutateDocumentWithOperationsDocument, NoSelectedDocumentError, PollBehavior, PropagationMode, REACTOR_SCHEMA, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, 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, 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, isDocumentTypeSupported, isDriveAuthError, isExternalControlsEnabledEventFunctions, isFileNodeKind, isFolderNodeKind, isGraphQLReactorClient, 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 };
3109
3685
 
3110
3686
  //# sourceMappingURL=index.js.map