@powerhousedao/connect 6.2.3-dev.6 → 6.2.3-dev.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/dist/{AddDriveModal-xAw48kdl.js → AddDriveModal-C5odBO8y.js} +6 -6
  2. package/dist/AddDriveModal-C5odBO8y.js.map +1 -0
  3. package/dist/{ClearStorageModal-B9bF7a7q.js → ClearStorageModal-DE2TKUfn.js} +6 -6
  4. package/dist/{ClearStorageModal-B9bF7a7q.js.map → ClearStorageModal-DE2TKUfn.js.map} +1 -1
  5. package/dist/{ConfirmDocumentUpgradeModal-FUOhZsk7.js → ConfirmDocumentUpgradeModal-k79v2wM6.js} +7 -6
  6. package/dist/{ConfirmDocumentUpgradeModal-FUOhZsk7.js.map → ConfirmDocumentUpgradeModal-k79v2wM6.js.map} +1 -1
  7. package/dist/{CookiesPolicyModal-BpyPPyxS.js → CookiesPolicyModal-BLw4pnhn.js} +4 -4
  8. package/dist/{CookiesPolicyModal-BpyPPyxS.js.map → CookiesPolicyModal-BLw4pnhn.js.map} +1 -1
  9. package/dist/{CreateDocumentModal-C45W8J0V.js → CreateDocumentModal-Bmv0V-kY.js} +6 -5
  10. package/dist/{CreateDocumentModal-C45W8J0V.js.map → CreateDocumentModal-Bmv0V-kY.js.map} +1 -1
  11. package/dist/{DebugSettingsModal-C6kwYM5N.js → DebugSettingsModal-BYrr41NU.js} +7 -7
  12. package/dist/{DebugSettingsModal-C6kwYM5N.js.map → DebugSettingsModal-BYrr41NU.js.map} +1 -1
  13. package/dist/{DeleteDriveModal-Dug84t1j.js → DeleteDriveModal-CjGnG0ht.js} +5 -5
  14. package/dist/{DeleteDriveModal-Dug84t1j.js.map → DeleteDriveModal-CjGnG0ht.js.map} +1 -1
  15. package/dist/{DeleteItemModal-mMzy3V8o.js → DeleteItemModal-BbY_4_xT.js} +5 -5
  16. package/dist/{DeleteItemModal-mMzy3V8o.js.map → DeleteItemModal-BbY_4_xT.js.map} +1 -1
  17. package/dist/{DisclaimerModal-DvpD5dPM.js → DisclaimerModal-DuglmEwL.js} +4 -4
  18. package/dist/{DisclaimerModal-DvpD5dPM.js.map → DisclaimerModal-DuglmEwL.js.map} +1 -1
  19. package/dist/{DocumentVersionUnsupportedModal-C3Q0V75l.js → DocumentVersionUnsupportedModal-C4fy7fZ6.js} +4 -4
  20. package/dist/{DocumentVersionUnsupportedModal-C3Q0V75l.js.map → DocumentVersionUnsupportedModal-C4fy7fZ6.js.map} +1 -1
  21. package/dist/{DownloadDocumentWithErrorsModal-IKl0ljQb.js → DownloadDocumentWithErrorsModal-BsPQ5qgy.js} +6 -5
  22. package/dist/{DownloadDocumentWithErrorsModal-IKl0ljQb.js.map → DownloadDocumentWithErrorsModal-BsPQ5qgy.js.map} +1 -1
  23. package/dist/{DriveAuthRequiredModal-DVK7ZQzO.js → DriveAuthRequiredModal-CtsB0kwH.js} +5 -5
  24. package/dist/{DriveAuthRequiredModal-DVK7ZQzO.js.map → DriveAuthRequiredModal-CtsB0kwH.js.map} +1 -1
  25. package/dist/{DriveSettingsModal-C6-mRQiv.js → DriveSettingsModal-d1L0eYof.js} +4 -4
  26. package/dist/{DriveSettingsModal-C6-mRQiv.js.map → DriveSettingsModal-d1L0eYof.js.map} +1 -1
  27. package/dist/{InspectorModal-BDLUQ91R.js → InspectorModal-CpqAS_PY.js} +62 -22
  28. package/dist/InspectorModal-CpqAS_PY.js.map +1 -0
  29. package/dist/{LoginModal-CybbOm3N.js → LoginModal-CI0ogC2-.js} +5 -5
  30. package/dist/{LoginModal-CybbOm3N.js.map → LoginModal-CI0ogC2-.js.map} +1 -1
  31. package/dist/{MissingPackageModal-nBnExqO0.js → MissingPackageModal-DS3dgJ1K.js} +5 -5
  32. package/dist/{MissingPackageModal-nBnExqO0.js.map → MissingPackageModal-DS3dgJ1K.js.map} +1 -1
  33. package/dist/{OpenFileDocumentsModal-OPmSKJ4w.js → OpenFileDocumentsModal-C9vyTb6I.js} +8 -7
  34. package/dist/{OpenFileDocumentsModal-OPmSKJ4w.js.map → OpenFileDocumentsModal-C9vyTb6I.js.map} +1 -1
  35. package/dist/{SettingsModal-BY2USww8.js → SettingsModal-_hk8S-ey.js} +19 -15
  36. package/dist/{SettingsModal-BY2USww8.js.map → SettingsModal-_hk8S-ey.js.map} +1 -1
  37. package/dist/{UpgradeDriveModal-_8t9slxQ.js → UpgradeDriveModal-CXX6D5Au.js} +4 -4
  38. package/dist/{UpgradeDriveModal-_8t9slxQ.js.map → UpgradeDriveModal-CXX6D5Au.js.map} +1 -1
  39. package/dist/{app-loader-CgBHl_w5.js → app-loader-C_y2O5-k.js} +1257 -1122
  40. package/dist/app-loader-C_y2O5-k.js.map +1 -0
  41. package/dist/app-loader-DthM3kLU.js +4 -0
  42. package/dist/app-skeleton--Me5zlSz.js +112 -0
  43. package/dist/app-skeleton--Me5zlSz.js.map +1 -0
  44. package/dist/app-skeleton-CBN4tenZ.js +4 -0
  45. package/dist/boot-CNW7ypcB.js +210 -0
  46. package/dist/boot-CNW7ypcB.js.map +1 -0
  47. package/dist/buffer-DNTcuap_.js +66 -0
  48. package/dist/buffer-DNTcuap_.js.map +1 -0
  49. package/dist/{build-info-DKQqI_sg.js → build-info-CRwnXFRI.js} +10 -6
  50. package/dist/build-info-CRwnXFRI.js.map +1 -0
  51. package/dist/components-DVQlpeR0.js +5 -0
  52. package/dist/{connect.config-DaHDEUrw.js → connect.config-CB78ZsFz.js} +26 -14
  53. package/dist/connect.config-CB78ZsFz.js.map +1 -0
  54. package/dist/{connection-state-3w4liC1X.js → connection-state-BDikOGKo.js} +20 -9
  55. package/dist/{connection-state-3w4liC1X.js.map → connection-state-BDikOGKo.js.map} +1 -1
  56. package/dist/{cookie-banner-BH6bIq24.js → cookie-banner-D05DZRqY.js} +6 -6
  57. package/dist/{cookie-banner-BH6bIq24.js.map → cookie-banner-D05DZRqY.js.map} +1 -1
  58. package/dist/{i18n-CWO0vYVd.js → i18n-CTgT1HG-.js} +3 -3
  59. package/dist/{i18n-CWO0vYVd.js.map → i18n-CTgT1HG-.js.map} +1 -1
  60. package/dist/{load-VdwMO26x.js → load-BO0qVu72.js} +14 -12
  61. package/dist/{load-VdwMO26x.js.map → load-BO0qVu72.js.map} +1 -1
  62. package/dist/main.d.ts +2 -1
  63. package/dist/main.js +8 -8
  64. package/dist/main.js.map +1 -1
  65. package/dist/multi-reactor-BG-DqUcm.js +217 -0
  66. package/dist/multi-reactor-BG-DqUcm.js.map +1 -0
  67. package/dist/package-manager-BPVMRBoV.js +488 -0
  68. package/dist/package-manager-BPVMRBoV.js.map +1 -0
  69. package/dist/{pglite-major-B39aOEiE.js → pglite-major-p4_YefAE.js} +23 -5
  70. package/dist/pglite-major-p4_YefAE.js.map +1 -0
  71. package/dist/{pglite-migrate-core-Boxqqx-c.js → pglite-migrate-core-BcXcImng.js} +8 -6
  72. package/dist/{pglite-migrate-core-Boxqqx-c.js.map → pglite-migrate-core-BcXcImng.js.map} +1 -1
  73. package/dist/{pglite-seed-BqAUvNFw.js → pglite-seed-CQJ97bEt.js} +4 -4
  74. package/dist/{pglite-seed-BqAUvNFw.js.map → pglite-seed-CQJ97bEt.js.map} +1 -1
  75. package/dist/pglite.worker.d.ts +2 -1
  76. package/dist/pglite.worker.js +4 -3
  77. package/dist/pglite.worker.js.map +1 -1
  78. package/dist/pglite.worker.legacy.d.ts +2 -1
  79. package/dist/pglite.worker.legacy.js +4 -3
  80. package/dist/pglite.worker.legacy.js.map +1 -1
  81. package/dist/plugin-host--lBWChr9.js +254 -0
  82. package/dist/plugin-host--lBWChr9.js.map +1 -0
  83. package/dist/{preferences-store-_5Cw4_YV.js → preferences-store-Cm0BoiHA.js} +6 -25
  84. package/dist/preferences-store-Cm0BoiHA.js.map +1 -0
  85. package/dist/{pwa-manifest-link-DIgOSo2Q.js → pwa-manifest-link-DQRJpF0r.js} +3 -3
  86. package/dist/{pwa-manifest-link-DIgOSo2Q.js.map → pwa-manifest-link-DQRJpF0r.js.map} +1 -1
  87. package/dist/{reactor-D3o30osB.js → reactor-B8Sh7Et8.js} +611 -532
  88. package/dist/reactor-B8Sh7Et8.js.map +1 -0
  89. package/dist/reactor.worker.d.ts +2 -1
  90. package/dist/reactor.worker.js +413 -149
  91. package/dist/reactor.worker.js.map +1 -1
  92. package/dist/{registerServiceWorker-BSzbNfvz.js → registerServiceWorker-DT6t8wjg.js} +5 -5
  93. package/dist/{registerServiceWorker-BSzbNfvz.js.map → registerServiceWorker-DT6t8wjg.js.map} +1 -1
  94. package/dist/{runtime-config-DL3QjcfM.js → runtime-config-DI5OfIC6.js} +17 -4
  95. package/dist/runtime-config-DI5OfIC6.js.map +1 -0
  96. package/dist/runtime-flag-B8IYhkz-.js +4 -0
  97. package/dist/runtime-flag-CT5OKujT.js +45 -0
  98. package/dist/runtime-flag-CT5OKujT.js.map +1 -0
  99. package/dist/{sentry-QXKgQmr2.js → sentry-jfDyrxdX.js} +3 -3
  100. package/dist/{sentry-QXKgQmr2.js.map → sentry-jfDyrxdX.js.map} +1 -1
  101. package/dist/start-connect.d.ts +4 -5
  102. package/dist/start-connect.d.ts.map +1 -1
  103. package/dist/start-connect.js +6 -8
  104. package/dist/start-connect.js.map +1 -1
  105. package/dist/store-lock-Bi3B9VJD.js +159 -0
  106. package/dist/store-lock-Bi3B9VJD.js.map +1 -0
  107. package/dist/style.css +3288 -1
  108. package/dist/{toast-BXIGd4Eb.js → toast-C6WW-_O-.js} +3 -3
  109. package/dist/{toast-BXIGd4Eb.js.map → toast-C6WW-_O-.js.map} +1 -1
  110. package/dist/{use-renown-login-Cf3va6u_.js → use-renown-login-BzOSQETV.js} +3 -3
  111. package/dist/{use-renown-login-Cf3va6u_.js.map → use-renown-login-BzOSQETV.js.map} +1 -1
  112. package/dist/useIsEmbedded-BWJ0qb7w.js +26 -0
  113. package/dist/useIsEmbedded-BWJ0qb7w.js.map +1 -0
  114. package/dist/{useRegistryPackages-BnUcL_nZ.js → useRegistryPackages-3EcR3GOh.js} +75 -13
  115. package/dist/useRegistryPackages-3EcR3GOh.js.map +1 -0
  116. package/package.json +21 -19
  117. package/style.css +7 -5
  118. package/dist/AddDriveModal-xAw48kdl.js.map +0 -1
  119. package/dist/InspectorModal-BDLUQ91R.js.map +0 -1
  120. package/dist/app-loader-CgBHl_w5.js.map +0 -1
  121. package/dist/app-loader-CxVV3sev.js +0 -4
  122. package/dist/build-info-DKQqI_sg.js.map +0 -1
  123. package/dist/components-DIrmDBOB.js +0 -4
  124. package/dist/connect.config-DaHDEUrw.js.map +0 -1
  125. package/dist/pglite-major-B39aOEiE.js.map +0 -1
  126. package/dist/preferences-store-_5Cw4_YV.js.map +0 -1
  127. package/dist/reactor-D3o30osB.js.map +0 -1
  128. package/dist/runtime-config-DL3QjcfM.js.map +0 -1
  129. package/dist/useRegistryPackages-BnUcL_nZ.js.map +0 -1
@@ -1,27 +1,32 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e39d56db-24be-5b7a-9426-5cc7cfc525d3")}catch(e){}}();
3
- import { n as getRuntimeConfig } from "./runtime-config-DL3QjcfM.js";
4
- import { c as idbError } from "./pglite-major-B39aOEiE.js";
5
- import { n as cloneFileData, r as migrateIdb } from "./pglite-migrate-core-Boxqqx-c.js";
6
- import { a as defaultPHDocumentEditorConfig, i as defaultPHAppConfig, r as connectConfig } from "./connect.config-DaHDEUrw.js";
7
- import { f as PRIMARY_IDB_NAMES, r as subscribeWorkerConnection, s as getCachedMigrationMajor, t as getWorkerConnectionStatus, u as subscribeMigrationMajor } from "./connection-state-3w4liC1X.js";
8
- import { n as serviceWorkerManager, r as subscribeServiceWorkerUpdate, t as getServiceWorkerUpdateAvailable } from "./registerServiceWorker-BSzbNfvz.js";
9
- import { t as setSentryModule } from "./sentry-QXKgQmr2.js";
10
- import { i as useIsEmbedded, r as getIsEmbedded, t as useAcceptedCookies } from "./preferences-store-_5Cw4_YV.js";
11
- import { n as dismissToast, r as toast, t as ToastContainer } from "./toast-BXIGd4Eb.js";
12
- import { t as useOpenRenownLogin } from "./use-renown-login-Cf3va6u_.js";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8a3a3353-4e2f-5ff5-b61c-ae9890df9cec")}catch(e){}}();
3
+ import { n as getRuntimeConfig } from "./runtime-config-DI5OfIC6.js";
4
+ import { n as drainOpenPanelBuffer, t as clearOpenPanelBuffer } from "./buffer-DNTcuap_.js";
5
+ import { c as idbError, d as isStoredDocumentsRefused } from "./pglite-major-p4_YefAE.js";
6
+ import { n as cloneFileData, r as migrateIdb } from "./pglite-migrate-core-BcXcImng.js";
7
+ import "./i18n-CTgT1HG-.js";
8
+ import { n as setMigrationStatus, t as AppSkeleton } from "./app-skeleton--Me5zlSz.js";
9
+ import { n as useIsEmbedded } from "./useIsEmbedded-BWJ0qb7w.js";
10
+ import { a as defaultPHDocumentEditorConfig, i as defaultPHAppConfig, r as connectConfig } from "./connect.config-CB78ZsFz.js";
11
+ import { n as useAcceptedCookies, t as setBannerShown } from "./preferences-store-Cm0BoiHA.js";
12
+ import { t as setSentryModule } from "./sentry-jfDyrxdX.js";
13
+ import { n as dismissToast, r as toast, t as ToastContainer } from "./toast-C6WW-_O-.js";
14
+ import { c as getCachedMigrationMajor, d as subscribeMigrationMajor, i as subscribeWorkerConnection, n as getWorkerConnectionStatus, p as PRIMARY_IDB_NAMES } from "./connection-state-BDikOGKo.js";
15
+ import { n as serviceWorkerManager, r as subscribeServiceWorkerUpdate, t as getServiceWorkerUpdateAvailable } from "./registerServiceWorker-DT6t8wjg.js";
16
+ import { t as useOpenRenownLogin } from "./use-renown-login-BzOSQETV.js";
13
17
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
14
- import { useTranslation } from "react-i18next";
15
- import React, { StrictMode, Suspense, createElement, lazy, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
16
- import { DriveCollectionId, RenownWalletProvider, addFileWithProgress, getRevisionFromDate, initTheme, logout, setPHAppConfig, setPHDocumentEditorConfig, setRevisionHistoryVisible, setSelectedDrive, setSelectedNode, showPHModal, useAppModuleById, useConnectionStates, useDefaultAppModule, useDocumentById, useDocumentModelModuleById, useDocumentOperations, useDocumentVersionStatus, useDrives, useEditorModuleById, useEditorPreloader, useFallbackEditorModule, useIsAddDriveEnabled, useNodeParentFolderById, usePHModal, usePackageDiscoveryService, useReactorClientModule, useRevisionHistoryVisible, useSelectedDocument, useSelectedDocumentId, useSelectedDriveId, useSelectedDriveSafe, useSelectedFolder, useSelectedTimelineItem, useSync, useSyncList, useTheme, useUser, useVetraPackageManager, useVetraPackages } from "@powerhousedao/reactor-browser";
17
18
  import { childLogger } from "document-model";
18
- import { ConnectSidebar, ConnectTooltipProvider, DefaultEditorLoader, DriveAuthGate, DropZoneWrapper, HomeScreen, HomeScreenAddDriveItem, HomeScreenItem, LogoAnimation, PackageInstallModal, RevisionHistory, SidebarAddDriveItem, SidebarItem, UploadFileListContainer, formatFileSize, mapProgressStageToStatus, useEns } from "@powerhousedao/design-system/connect";
19
- import { Outlet, RouterProvider, createBrowserRouter, createRoutesFromChildren, matchRoutes, useLocation, useNavigationType } from "react-router-dom";
20
- import { useHotkeys } from "react-hotkeys-hook";
19
+ import { Trans, useTranslation } from "react-i18next";
20
+ import React, { StrictMode, Suspense, createElement, lazy, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
21
+ import { ConnectSearchBar, ConnectSidebar, ConnectTooltipProvider, DefaultEditorLoader, DriveAuthGate, DropZoneWrapper, Footer, FooterLink, HomeScreen, HomeScreenAddDriveItem, HomeScreenItem, PackageInstallModal, RevisionHistory, SidebarAddDriveItem, SidebarItem, UploadFileListContainer, formatFileSize, mapProgressStageToStatus, useEns } from "@powerhousedao/design-system/connect";
22
+ import { DriveCollectionId, RenownWalletProvider, addFileWithProgress, getRevisionFromDate, logout, setPHAppConfig, setPHDocumentEditorConfig, setRevisionHistoryVisible, setSelectedDrive, setSelectedNode, showPHModal, useAppModuleById, useConnectionStates, useDefaultAppModule, useDocumentById, useDocumentModelModuleById, useDocumentOperations, useDocumentVersionStatus, useDrives, useEditorModuleById, useEditorPreloader, useFallbackEditorModule, useIsAddDriveEnabled, useNodeParentFolderById, usePHModal, usePackageDiscoveryService, useReactorClientModule, useRevisionHistoryVisible, useSelectedDocument, useSelectedDocumentId, useSelectedDriveId, useSelectedDriveSafe, useSelectedFolder, useSelectedTimelineItem, useSync, useSyncList, useTheme, useUser, useVetraPackageManager, useVetraPackages } from "@powerhousedao/reactor-browser";
21
23
  import { Icon, Modal, PowerhouseButton } from "@powerhousedao/design-system";
22
24
  import { ErrorBoundary } from "react-error-boundary";
23
25
  import { z } from "zod";
24
26
  import { GenericDriveExplorer } from "@powerhousedao/powerhouse-vetra-packages/editors";
27
+ import { Outlet, RouterProvider, createBrowserRouter, createRoutesFromChildren, matchRoutes, useLocation, useNavigationType } from "react-router-dom";
28
+ import { redo, undo } from "@powerhousedao/shared/document-model";
29
+ import { useHotkeys } from "react-hotkeys-hook";
25
30
  import { createReactorMcpProvider } from "@powerhousedao/reactor-mcp/tools";
26
31
  import { ReactorChatFab, createSwitchboardSchemaTool } from "@powerhousedao/reactor-browser/ai";
27
32
  import { twMerge } from "tailwind-merge";
@@ -29,491 +34,724 @@ import { mockAdapter } from "@renown/sdk/wallet/mock";
29
34
  import { privyAdapter } from "@renown/sdk/wallet/privy";
30
35
  import { rainbowAdapter } from "@renown/sdk/wallet/rainbow";
31
36
  import { arbitrum, base, mainnet, optimism, polygon, sepolia } from "wagmi/chains";
32
- import { redo, undo } from "@powerhousedao/shared/document-model";
33
- //#region src/utils/browser.ts
34
- function getBasePath() {
35
- if (typeof document === "undefined") return "/";
36
- return document.querySelector("base")?.getAttribute("href") || "/";
37
- }
38
- //#endregion
39
- //#region src/utils/document-editor-debug-tools.ts
40
- var DocumentEditorDebugTools = class {
41
- document;
42
- operations = [];
43
- constructor(document) {
44
- if (document) this.document = document;
45
- }
46
- operationsToTableObject(operations) {
47
- return operations.map((op) => ({
48
- ...op,
49
- input: JSON.stringify(op.action.input)
50
- }));
51
- }
52
- setDocument(document) {
53
- this.document = document;
54
- }
55
- getDocument() {
56
- return this.document;
57
- }
58
- getOperations() {
59
- return this.operations;
60
- }
61
- pushOperation(operation) {
62
- this.operations.push(operation);
63
- }
64
- operationsTable() {
65
- if (!this.document) console.warn("No document");
66
- const ops = Object.values(this.document?.operations || {}).filter((array) => array !== void 0).flatMap((array) => array).sort((a, b) => a.index - b.index);
67
- console.table(this.operationsToTableObject(ops));
68
- }
69
- scopeOperationsTable(scope) {
70
- if (!this.document) console.warn("No document");
71
- const ops = this.document?.operations[scope] || [];
72
- console.table(this.operationsToTableObject(ops));
73
- }
74
- operationsLog() {
75
- console.log(this.operations);
76
- }
77
- operationsLogTable() {
78
- console.table(this.operationsToTableObject(this.operations));
79
- }
80
- clear() {
81
- this.operations = [];
82
- this.document = void 0;
83
- }
84
- };
85
- //#endregion
86
- //#region src/utils/launch-queue.ts
87
- let pendingImportFiles = [];
88
- const pendingListeners = /* @__PURE__ */ new Set();
89
- function notifyPendingListeners() {
90
- for (const listener of pendingListeners) listener();
91
- }
92
- function getPendingImportFiles() {
93
- return pendingImportFiles;
37
+ //#region src/components/error-boundary.tsx
38
+ const logger$2 = childLogger(["Connect"]);
39
+ function hasCustomFallback(props) {
40
+ return "fallbackRender" in props;
94
41
  }
95
- /** Stable identity of a pending file (also the picker's pre-check cache key). */
96
- function pendingFileKey(file) {
97
- return `${file.name}|${file.size}|${file.lastModified}`;
42
+ function SilentFallback() {
43
+ return null;
98
44
  }
99
- function addPendingImportFiles(files) {
100
- const seen = new Set(pendingImportFiles.map(pendingFileKey));
101
- const fresh = files.filter((file) => {
102
- const key = pendingFileKey(file);
103
- if (seen.has(key)) return false;
104
- seen.add(key);
105
- return true;
45
+ /**
46
+ * Simple text-based fallback component.
47
+ * Displays a centered message when an error occurs.
48
+ */
49
+ function TextFallback({ message = "Something went wrong" }) {
50
+ return /* @__PURE__ */ jsx("div", {
51
+ className: "text-center wrap-break-word text-foreground",
52
+ children: message
106
53
  });
107
- if (fresh.length === 0) return;
108
- pendingImportFiles = [...pendingImportFiles, ...fresh];
109
- notifyPendingListeners();
110
54
  }
111
- function clearPendingImportFiles() {
112
- if (pendingImportFiles.length === 0) return;
113
- pendingImportFiles = [];
114
- notifyPendingListeners();
55
+ /**
56
+ * Detailed fallback component showing full error information.
57
+ * Displays error message with a collapsible details section.
58
+ * Useful for development and debugging purposes.
59
+ */
60
+ function DetailedFallback({ error, resetErrorBoundary }) {
61
+ const errorMessage = error instanceof Error ? error.message : String(error);
62
+ const errorDetails = error instanceof Error ? error.stack ?? String(error.cause) : JSON.stringify(error, null, 2);
63
+ return /* @__PURE__ */ jsx("div", {
64
+ className: "z-10 mx-auto flex max-w-[80%] flex-1 items-center justify-center p-6",
65
+ children: /* @__PURE__ */ jsxs("div", {
66
+ className: "w-full max-w-lg rounded-lg border border-border bg-card p-6 text-foreground shadow-sm",
67
+ children: [
68
+ /* @__PURE__ */ jsxs("div", {
69
+ className: "mb-3 flex items-center gap-2",
70
+ children: [/* @__PURE__ */ jsx(Icon, {
71
+ name: "Error",
72
+ className: "size-5 shrink-0 text-destructive"
73
+ }), /* @__PURE__ */ jsx("h1", {
74
+ className: "text-lg font-semibold text-foreground",
75
+ children: "Something went wrong"
76
+ })]
77
+ }),
78
+ /* @__PURE__ */ jsx("p", {
79
+ className: "mb-4 text-sm wrap-break-word text-foreground",
80
+ children: errorMessage
81
+ }),
82
+ errorDetails !== "{}" && /* @__PURE__ */ jsxs("details", {
83
+ className: "group",
84
+ children: [/* @__PURE__ */ jsx("summary", {
85
+ className: "cursor-pointer text-sm font-medium text-foreground underline select-none hover:hover-effect",
86
+ children: "Show details"
87
+ }), /* @__PURE__ */ jsx("pre", {
88
+ className: "mt-2 max-h-48 overflow-auto rounded-sm bg-muted p-3 text-xs text-foreground",
89
+ children: errorDetails
90
+ })]
91
+ }),
92
+ /* @__PURE__ */ jsx(PowerhouseButton, {
93
+ type: "button",
94
+ onClick: resetErrorBoundary,
95
+ className: "mt-4 px-3 py-1.5 text-base font-medium",
96
+ children: "Try again"
97
+ })
98
+ ]
99
+ })
100
+ });
115
101
  }
116
- function subscribePendingImportFiles(cb) {
117
- pendingListeners.add(cb);
118
- return () => {
119
- pendingListeners.delete(cb);
120
- };
102
+ /**
103
+ * Centered error message fallback component.
104
+ * Displays the error message in a centered, full-size container.
105
+ * Suitable for use as a custom fallbackRender when you need simple error display.
106
+ */
107
+ function CenteredErrorMessage({ error }) {
108
+ const errorMessage = error instanceof Error ? error.message : String(error);
109
+ return /* @__PURE__ */ jsx("div", {
110
+ className: "flex size-full items-center justify-center p-6",
111
+ children: /* @__PURE__ */ jsx("h3", {
112
+ className: "max-w-lg min-w-0 text-center text-lg font-semibold wrap-break-word text-foreground",
113
+ children: errorMessage
114
+ })
115
+ });
121
116
  }
122
- async function handleLaunchParams(params) {
123
- const handles = params.files.filter((handle) => handle.kind === "file");
124
- if (handles.length === 0) return;
125
- const files = [];
126
- for (const handle of handles) try {
127
- files.push(await handle.getFile());
128
- } catch (error) {
129
- console.error("Failed to read launched file:", handle.name, error);
117
+ function getFallbackComponent(variant, fallbackMessage) {
118
+ switch (variant) {
119
+ case "silent": return SilentFallback;
120
+ case "text": return () => /* @__PURE__ */ jsx(TextFallback, { message: fallbackMessage });
121
+ case "detailed": return DetailedFallback;
122
+ default: return CenteredErrorMessage;
130
123
  }
131
- if (files.length === 0) return;
132
- addPendingImportFiles(files);
133
- showPHModal({ type: "openFileDocuments" });
134
124
  }
135
- function maybeReopenImportModal() {
136
- if (getPendingImportFiles().length === 0) return;
137
- if (window.ph?.modal !== void 0) return;
138
- showPHModal({ type: "openFileDocuments" });
139
- }
140
- let initialized = false;
141
125
  /**
142
- * Register the launchQueue consumer that receives files opened with Connect
143
- * through the OS file association. Idempotent (safe under StrictMode double
144
- * effects) and a no-op where the File Handling API doesn't exist — Firefox,
145
- * Safari, and any context without an installed PWA manifest simply never
146
- * deliver launches.
126
+ * Unified error boundary component for catching and handling React errors.
127
+ *
128
+ * Built on top of `react-error-boundary`, this component provides:
129
+ * - Automatic error logging with configurable context
130
+ * - Multiple fallback UI variants (silent, text, detailed)
131
+ * - Support for custom fallback render functions
132
+ * - Reset capability via `resetKeys`
133
+ *
134
+ * @example
135
+ * // Using a predefined variant
136
+ * <ErrorBoundary variant="detailed" loggerContext={["Connect", "Editor"]}>
137
+ * <EditorComponent />
138
+ * </ErrorBoundary>
139
+ *
140
+ * @example
141
+ * // Using a custom message with the text variant
142
+ * <ErrorBoundary variant="text" fallbackMessage="Failed to load drives">
143
+ * <DrivesList />
144
+ * </ErrorBoundary>
145
+ *
146
+ * @example
147
+ * // Using a custom fallback render
148
+ * <ErrorBoundary
149
+ * fallbackRender={CenteredErrorMessage}
150
+ * onError={(error) => trackError(error)}
151
+ * >
152
+ * <MyComponent />
153
+ * </ErrorBoundary>
154
+ *
155
+ * @example
156
+ * // Silent mode for modals (renders null on error)
157
+ * <ErrorBoundary variant="silent" loggerContext={["Connect", "Modals"]}>
158
+ * <ModalContent />
159
+ * </ErrorBoundary>
147
160
  */
148
- function initLaunchQueueFileHandling() {
149
- if (initialized) return;
150
- initialized = true;
151
- window.addEventListener("ph:modalUpdated", maybeReopenImportModal);
152
- window.launchQueue?.setConsumer((params) => {
153
- handleLaunchParams(params);
161
+ function ErrorBoundary$1(props) {
162
+ const { children, onError, resetKeys, loggerContext } = props;
163
+ const handleError = (error, info) => {
164
+ if (error.message.includes("Failed to fetch dynamically imported module") && error.message.includes("node_modules/.vite")) {
165
+ console.error(error);
166
+ console.log("Outdated chunk detected, reloading page...");
167
+ window.location.reload();
168
+ return;
169
+ }
170
+ (loggerContext ? childLogger(loggerContext) : logger$2).error("@error @info", error, info);
171
+ onError?.(error, info);
172
+ };
173
+ const fallbackRender = hasCustomFallback(props) ? props.fallbackRender : getFallbackComponent(props.variant, props.fallbackMessage);
174
+ return /* @__PURE__ */ jsx(ErrorBoundary, {
175
+ fallbackRender,
176
+ onError: handleError,
177
+ resetKeys,
178
+ children
154
179
  });
155
180
  }
156
181
  //#endregion
157
- //#region src/utils/open-file-uploads.ts
158
- let uploads = [];
159
- const listeners$1 = /* @__PURE__ */ new Set();
160
- function notifyUploadListeners() {
161
- for (const listener of listeners$1) listener();
162
- }
163
- function getOpenFileUploads() {
164
- return uploads;
165
- }
166
- function subscribeOpenFileUploads(cb) {
167
- listeners$1.add(cb);
168
- return () => {
169
- listeners$1.delete(cb);
170
- };
182
+ //#region src/components/analytics.tsx
183
+ function gtag(...args) {
184
+ window.dataLayer?.push(...args);
171
185
  }
172
- function removeOpenFileUpload(id) {
173
- const next = uploads.filter((upload) => upload.id !== id);
174
- if (next.length === uploads.length) return;
175
- uploads = next;
176
- notifyUploadListeners();
186
+ const Analytics = () => {
187
+ const gaTrackingId = connectConfig.gaTrackingId;
188
+ const [{ analytics }] = useAcceptedCookies();
189
+ const useAnalytics = gaTrackingId && analytics;
190
+ useEffect(() => {
191
+ if (useAnalytics) {
192
+ const script = document.createElement("script");
193
+ script.src = `https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`;
194
+ script.async = true;
195
+ document.head.appendChild(script);
196
+ window.dataLayer = window.dataLayer || [];
197
+ gtag("js", /* @__PURE__ */ new Date());
198
+ gtag("config", gaTrackingId);
199
+ return () => {
200
+ document.head.removeChild(script);
201
+ };
202
+ }
203
+ }, [useAnalytics, gaTrackingId]);
204
+ return null;
205
+ };
206
+ //#endregion
207
+ //#region src/hooks/usePluginComposition.ts
208
+ /**
209
+ * Plugin-presence reads for the UI (rewire R3, step toward generic-shell
210
+ * deletability). The served runtime config carries `connect.composition` — the
211
+ * list of plugins the host declared — when uniform runners project it. UI can
212
+ * gate on a plugin being present ("presence is activation").
213
+ *
214
+ * Classic semantics are preserved: when there is NO declared composition
215
+ * (flag-off, or a host without a plugins list), `null` is returned and every
216
+ * plugin is treated as active — so the classic chrome renders exactly as
217
+ * before. Gating only hides something when a composition IS declared and the
218
+ * plugin is absent from it.
219
+ */
220
+ function getActivePluginModules() {
221
+ try {
222
+ const composition = getRuntimeConfig().connect?.composition;
223
+ if (!composition) return null;
224
+ return new Set(composition.map((entry) => entry.module));
225
+ } catch {
226
+ return null;
227
+ }
177
228
  }
178
- function clearOpenFileUploads() {
179
- if (uploads.length === 0) return;
180
- uploads = [];
181
- notifyUploadListeners();
229
+ function isPluginActive(module) {
230
+ const active = getActivePluginModules();
231
+ return active === null ? true : active.has(module);
182
232
  }
183
- function addOpenFileUploads(rows) {
184
- uploads = [...uploads, ...rows];
185
- notifyUploadListeners();
233
+ /** Hook form; the composition is fixed for the page's lifetime, so this is a
234
+ * plain synchronous read (no subscription needed). */
235
+ function useIsPluginActive(module) {
236
+ return isPluginActive(module);
186
237
  }
187
- function patchOpenFileUpload(id, patch) {
188
- uploads = uploads.map((upload) => upload.id === id ? {
189
- ...upload,
190
- ...patch
191
- } : upload);
192
- notifyUploadListeners();
238
+ //#endregion
239
+ //#region src/components/if-plugin.tsx
240
+ /**
241
+ * Renders its children only when a plugin is present in the served
242
+ * composition — the runtime gate for generic-chrome deletability (rewire R3).
243
+ *
244
+ * This is the demonstration step ahead of extracting the generic components
245
+ * into their own package: it makes "remove the generic plugin → the chrome is
246
+ * gone" true at render time while the code still lives in the Connect app.
247
+ * When those components move to `@powerhousedao/connect-generic`, this gate
248
+ * becomes the seam where the package is dynamically imported (or not) instead
249
+ * of merely not rendered.
250
+ *
251
+ * Presence is activation, classic-preserving: with no declared composition,
252
+ * every plugin reads active, so the chrome renders unchanged.
253
+ */
254
+ function IfPlugin(props) {
255
+ return useIsPluginActive(props.module) ? props.children : props.fallback ?? null;
193
256
  }
194
- let uploadCounter = 0;
195
- let importChain = Promise.resolve();
257
+ //#endregion
258
+ //#region src/services/openpanel/client.ts
259
+ let client;
196
260
  /**
197
- * Import one file and resolve once the flow truly ends. Completion is
198
- * tracked through the progress stages, NOT the returned promise — the
199
- * package-discovery retry path resolves early and keeps reporting through
200
- * the callback. `resolveConflict: "duplicate"` is always passed: duplicates
201
- * were resolved in the picker (rename), so the conflict stage must never
202
- * fire — this also covers a duplicate appearing between pre-check and import.
261
+ * Returns the cached `OpenPanel` singleton, building it on first call.
262
+ *
263
+ * When `config.clientId` is empty it returns `undefined` without importing
264
+ * `@openpanel/web`, so the bundler can tree-shake the SDK out of production.
203
265
  */
204
- function importOne(row, driveId, documentTypes) {
205
- return new Promise((resolve) => {
206
- let settled = false;
207
- const settle = (fileNode) => {
208
- if (settled) return;
209
- settled = true;
210
- resolve(fileNode);
211
- };
212
- addFileWithProgress(row.file, driveId, row.name, void 0, (progress) => {
213
- patchOpenFileUpload(row.id, {
214
- status: mapProgressStageToStatus(progress.stage),
215
- progress: progress.progress,
216
- ...progress.error ? { errorDetails: progress.error } : {},
217
- ...progress.documentType ? { documentType: progress.documentType } : {},
218
- ...progress.fileNode ? { fileNode: progress.fileNode } : {}
219
- });
220
- switch (progress.stage) {
221
- case "complete":
222
- settle(progress.fileNode);
223
- break;
224
- case "failed":
225
- case "unsupported-document-type":
226
- settle(void 0);
227
- break;
228
- default: break;
229
- }
230
- }, documentTypes, "duplicate").catch(() => {
231
- settle(void 0);
232
- });
266
+ async function getOpenPanelClient(config) {
267
+ if (!config.clientId) return;
268
+ if (client) return client;
269
+ const { OpenPanel: OpenPanelClass } = await import("@openpanel/web");
270
+ client = new OpenPanelClass({
271
+ clientId: config.clientId,
272
+ ...config.apiUrl ? { apiUrl: config.apiUrl } : {},
273
+ trackScreenViews: true,
274
+ trackOutgoingLinks: true
233
275
  });
276
+ client.setGlobalProperties({ app: "connect" });
277
+ drainOpenPanelBuffer(client);
278
+ return client;
234
279
  }
235
280
  /**
236
- * Run a confirmed batch of imports into a drive, feeding the floating upload
237
- * panel. Rows appear immediately (queued), files import sequentially, and a
238
- * single-file batch that succeeds opens its document in the editor.
281
+ * Clears the cached singleton and the pre-init buffer. Call on consent
282
+ * revocation or during tests; buffered events are discarded, not replayed.
239
283
  */
240
- function runOpenFileImports(args) {
241
- const { driveId, imports, documentTypes } = args;
242
- if (imports.length === 0) return importChain;
243
- const rows = imports.map(({ file, name }) => ({
244
- id: `open-file-${++uploadCounter}`,
245
- file,
246
- name
247
- }));
248
- addOpenFileUploads(rows.map((row) => ({
249
- id: row.id,
250
- fileName: row.name,
251
- fileSize: formatFileSize(row.file.size),
252
- status: "pending",
253
- progress: 0
254
- })));
255
- const run = async () => {
256
- const results = [];
257
- for (const row of rows) results.push(await importOne(row, driveId, documentTypes));
258
- if (rows.length === 1 && results[0]) setSelectedNode(results[0]);
259
- };
260
- importChain = importChain.then(run, run);
261
- return importChain;
284
+ function resetOpenPanelClient() {
285
+ client = void 0;
286
+ clearOpenPanelBuffer();
262
287
  }
263
288
  //#endregion
264
- //#region src/components/migration-status.ts
265
- let current = null;
266
- const listeners = /* @__PURE__ */ new Set();
267
- function setMigrationStatus(status) {
268
- current = status;
269
- for (const l of listeners) l();
289
+ //#region src/services/openpanel/events.json
290
+ var events_default = [
291
+ {
292
+ "documentType": "powerhouse/document-drive",
293
+ "actionTypes": [
294
+ "ADD_FOLDER",
295
+ "DELETE_NODE",
296
+ "ADD_FILE",
297
+ "UPDATE_FILE",
298
+ "COPY_NODE",
299
+ "MOVE_NODE",
300
+ "SET_DRIVE_NAME",
301
+ "SET_DRIVE_ICON"
302
+ ]
303
+ },
304
+ {
305
+ "documentType": "powerhouse/document-model",
306
+ "actionTypes": [
307
+ "SET_MODEL_NAME",
308
+ "SET_MODEL_ID",
309
+ "ADD_MODULE",
310
+ "DELETE_MODULE",
311
+ "ADD_OPERATION",
312
+ "DELETE_OPERATION"
313
+ ]
314
+ },
315
+ {
316
+ "documentType": "powerhouse/reactor-drive",
317
+ "actionTypes": [
318
+ "ADD_FOLDER",
319
+ "REMOVE_FOLDER",
320
+ "UPDATE_FOLDER"
321
+ ]
322
+ }
323
+ ];
324
+ //#endregion
325
+ //#region src/services/openpanel/events.ts
326
+ const EventMappingSchema = z.object({
327
+ documentType: z.string().min(1),
328
+ actionTypes: z.array(z.string().min(1)).min(1),
329
+ alias: z.string().optional()
330
+ }).strict();
331
+ const EventMappingsSchema = z.array(EventMappingSchema).readonly();
332
+ /**
333
+ * Parses and validates the event mapping table, returning the validated array
334
+ * and an O(1) lookup map. Accepts a `raw` override for tests. Throws on zod
335
+ * failures and on duplicate `(documentType, actionType)` pairs.
336
+ */
337
+ function loadEvents(raw = events_default) {
338
+ const result = EventMappingsSchema.safeParse(raw);
339
+ if (!result.success) throw new Error(`Invalid OpenPanel events.json: ${result.error.message}`);
340
+ const mappings = result.data;
341
+ const lookupMap = /* @__PURE__ */ new Map();
342
+ for (const mapping of mappings) {
343
+ let inner = lookupMap.get(mapping.documentType);
344
+ if (!inner) {
345
+ inner = /* @__PURE__ */ new Map();
346
+ lookupMap.set(mapping.documentType, inner);
347
+ }
348
+ for (const actionType of mapping.actionTypes) {
349
+ if (inner.has(actionType)) throw new Error(`Duplicate OpenPanel event mapping for ${mapping.documentType}/${actionType}`);
350
+ inner.set(actionType, mapping);
351
+ }
352
+ }
353
+ return {
354
+ mappings,
355
+ lookupMap
356
+ };
357
+ }
358
+ const { mappings: defaultMappings, lookupMap: defaultLookupMap } = loadEvents();
359
+ /** Validated mapping array from the bundled events.json. */
360
+ const eventMappings = defaultMappings;
361
+ /** O(1) lookup map: documentType → actionType → mapping. */
362
+ const eventLookupMap = defaultLookupMap;
363
+ /**
364
+ * Normalizes a document type into a safe event-name segment: lowercased, `/`
365
+ * replaced with `.`, and any character outside `[a-z0-9._-]` stripped.
366
+ * e.g. `powerhouse/document-drive` → `powerhouse.document-drive`.
367
+ */
368
+ function normalize(documentType) {
369
+ return documentType.toLowerCase().replace(/\//g, ".").replace(/[^a-z0-9._-]/g, "");
270
370
  }
271
- function getMigrationStatus() {
272
- return current;
371
+ /**
372
+ * Derives the OpenPanel event name: `mapping.alias` when present, otherwise
373
+ * `${normalize(documentType)}.${actionType.toLowerCase()}`.
374
+ */
375
+ function deriveEventName(mapping, op) {
376
+ if (mapping.alias) return mapping.alias;
377
+ return `${normalize(op.context.documentType)}.${op.operation.action.type.toLowerCase()}`;
273
378
  }
274
- function subscribeMigrationStatus(cb) {
275
- listeners.add(cb);
276
- return () => {
277
- listeners.delete(cb);
379
+ /**
380
+ * Builds the default properties attached to every OpenPanel event. The `app`
381
+ * property is stamped globally by the client, not here.
382
+ */
383
+ function buildDefaultProperties(op) {
384
+ return {
385
+ documentType: op.context.documentType,
386
+ actionType: op.operation.action.type,
387
+ documentId: op.context.documentId,
388
+ scope: op.context.scope,
389
+ branch: op.context.branch
278
390
  };
279
391
  }
280
392
  //#endregion
281
- //#region src/utils/pglite-migration.ts
282
- const BACKUP_PREFIX = "ph-pglite-backup::";
283
- const BACKUP_INDEX_KEY = "ph:pglite-backups";
284
- const BACKUP_RETENTION_MS = 720 * 60 * 60 * 1e3;
285
- function deleteIdb(name, timeoutMs = 15e3) {
286
- return new Promise((resolve, reject) => {
287
- const req = indexedDB.deleteDatabase(name);
288
- let settled = false;
289
- const done = (fn) => {
290
- if (settled) return;
291
- settled = true;
292
- fn();
293
- };
294
- const timer = setTimeout(() => done(() => reject(/* @__PURE__ */ new Error(`IDB delete timed out for ${name} after ${timeoutMs}ms`))), timeoutMs);
295
- req.onsuccess = () => done(() => {
296
- clearTimeout(timer);
297
- resolve();
298
- });
299
- req.onerror = () => done(() => {
300
- clearTimeout(timer);
301
- reject(idbError(req, `IDB delete failed for ${name}`));
302
- });
303
- });
304
- }
305
- function readBackupIndex() {
306
- try {
307
- const raw = localStorage.getItem(BACKUP_INDEX_KEY);
308
- if (!raw) return [];
309
- const parsed = JSON.parse(raw);
310
- return Array.isArray(parsed) ? parsed : [];
311
- } catch {
312
- return [];
313
- }
314
- }
315
- function writeBackupIndex(records) {
316
- try {
317
- localStorage.setItem(BACKUP_INDEX_KEY, JSON.stringify(records));
318
- } catch {}
319
- }
320
- function registerBackup(rec) {
321
- writeBackupIndex([...readBackupIndex(), rec]);
322
- }
323
- function forgetBackup(name) {
324
- writeBackupIndex(readBackupIndex().filter((r) => r.name !== name));
325
- }
326
- async function janitor() {
327
- const cutoff = Date.now() - BACKUP_RETENTION_MS;
328
- const keep = [];
329
- for (const rec of readBackupIndex()) {
330
- if (rec.createdAt >= cutoff) {
331
- keep.push(rec);
332
- continue;
333
- }
334
- try {
335
- await deleteIdb(rec.name);
336
- } catch (err) {
337
- console.warn(`Failed to delete expired pglite backup ${rec.name}`, err);
338
- keep.push(rec);
339
- }
393
+ //#region src/services/openpanel/processor.ts
394
+ /**
395
+ * Read-only reactor `IProcessor` that translates matching document operations
396
+ * into OpenPanel analytics events. Operations whose `(documentType, actionType)`
397
+ * pair is absent from the lookup map are skipped; per-operation errors are
398
+ * routed to `onError` and never thrown back to the manager.
399
+ */
400
+ var OpenPanelProcessor = class {
401
+ client;
402
+ lookupMap;
403
+ onError;
404
+ constructor(client, lookupMap, onError = (err) => console.warn("[OpenPanelProcessor] Error tracking event:", err)) {
405
+ this.client = client;
406
+ this.lookupMap = lookupMap;
407
+ this.onError = onError;
340
408
  }
341
- writeBackupIndex(keep);
342
- }
343
- function createPersistentBackup() {
344
- return {
345
- snapshot: async (idbName) => {
346
- const backupName = `${BACKUP_PREFIX}${idbName}::${(/* @__PURE__ */ new Date()).toISOString()}`;
347
- await cloneFileData(idbName, backupName);
348
- registerBackup({
349
- name: backupName,
350
- idbName,
351
- createdAt: Date.now()
352
- });
353
- return backupName;
354
- },
355
- rollback: async (handle, idbName, cause) => {
356
- const backupName = handle;
409
+ async onOperations(operations) {
410
+ for (const op of operations) {
411
+ const inner = this.lookupMap.get(op.context.documentType);
412
+ if (!inner) continue;
413
+ const mapping = inner.get(op.operation.action.type);
414
+ if (!mapping) continue;
415
+ const name = deriveEventName(mapping, op);
416
+ const payload = buildDefaultProperties(op);
357
417
  try {
358
- await cloneFileData(backupName, idbName);
359
- } catch (rollbackErr) {
360
- console.error(`PGlite migration rollback failed for ${idbName}; backup ${backupName} retained. Primary migration error:`, cause, "Rollback error:", rollbackErr);
361
- return;
418
+ await this.client.track(name, payload);
419
+ } catch (err) {
420
+ this.onError(err, op);
362
421
  }
363
- await deleteIdb(backupName).catch(() => void 0);
364
- forgetBackup(backupName);
365
- },
366
- discard: async (handle) => {
367
- const backupName = handle;
368
- await deleteIdb(backupName).catch(() => void 0);
369
- forgetBackup(backupName);
370
- },
371
- commit: () => Promise.resolve()
372
- };
373
- }
374
- async function migrateAllLocked() {
375
- const backup = createPersistentBackup();
376
- try {
377
- for (const idbName of PRIMARY_IDB_NAMES) await migrateIdb(idbName, (phase) => setMigrationStatus({
378
- idbName,
379
- phase
380
- }), backup);
381
- } finally {
382
- setMigrationStatus(null);
422
+ }
383
423
  }
384
- }
385
- async function migrateAllIfNeeded() {
386
- janitor().catch((err) => console.warn("PGlite backup janitor failed", err));
387
- if (!(typeof navigator !== "undefined" && "locks" in navigator && typeof navigator.locks.request === "function")) {
388
- await migrateAllLocked();
389
- return;
424
+ onDisconnect() {
425
+ this.client.flush?.();
426
+ return Promise.resolve();
390
427
  }
391
- await navigator.locks.request("ph-pglite-migration", { mode: "exclusive" }, async () => {
392
- await migrateAllLocked();
393
- });
394
- }
395
- //#endregion
396
- //#region src/hooks/useFailedInstallations.ts
397
- const emptyArray$1 = [];
398
- function useFailedInstallations() {
399
- const discoveryService = usePackageDiscoveryService();
400
- return useSyncExternalStore((cb) => discoveryService?.subscribeFailed(cb) ?? (() => {}), () => discoveryService?.getFailedInstallations() ?? emptyArray$1);
401
- }
402
- //#endregion
403
- //#region src/hooks/useInitSentry.ts
404
- const logger$2 = childLogger(["sentry"]);
405
- let clientStarted = false;
406
- async function getSentry() {
407
- return await import("@sentry/react");
408
- }
409
- async function initSentry() {
410
- const Sentry = await getSentry();
411
- const integrations = [
412
- Sentry.httpClientIntegration(),
413
- Sentry.extraErrorDataIntegration({ depth: 5 }),
414
- Sentry.replayIntegration(),
415
- Sentry.captureConsoleIntegration({ levels: ["error"] })
416
- ];
417
- if (connectConfig.sentry.tracing) integrations.push(Sentry.reactRouterV6BrowserTracingIntegration({
418
- useEffect: React.useEffect,
419
- useLocation,
420
- useNavigationType,
421
- createRoutesFromChildren,
422
- matchRoutes
423
- }));
424
- Sentry.init({
425
- release: connectConfig.sentry.release,
426
- dsn: connectConfig.sentry.dsn ?? void 0,
427
- environment: connectConfig.sentry.env,
428
- integrations,
429
- ignoreErrors: [
430
- "User is not allowed to create files",
431
- "User is not allowed to move documents",
432
- "The user aborted a request."
433
- ],
434
- sendDefaultPii: true,
435
- tracesSampleRate: 1,
436
- replaysSessionSampleRate: .1,
437
- replaysOnErrorSampleRate: 1,
438
- beforeSend(event, hint) {
439
- const error = hint.originalException;
440
- if (error instanceof TypeError && error.message.includes("Failed to fetch") && !navigator.onLine) return null;
441
- return event;
442
- }
443
- });
444
- setSentryModule(Sentry);
445
- clientStarted = true;
446
- }
447
- async function closeClient() {
448
- if (!clientStarted) return;
449
- const sentry = await getSentry();
450
- setSentryModule(void 0);
451
- return sentry.getClient()?.close();
452
- }
453
- function useInitSentry() {
454
- const [acceptedCookies] = useAcceptedCookies();
455
- const { analytics } = acceptedCookies;
456
- useEffect(() => {
457
- if (!analytics) {
458
- closeClient().catch((error) => logger$2.error("@error", error));
459
- return;
460
- }
461
- if (clientStarted || connectConfig.sentry.dsn === null || connectConfig.sentry.dsn === void 0 || connectConfig.sentry.dsn === "") return;
462
- initSentry().catch((error) => logger$2.error("@error", error));
463
- }, [analytics]);
464
- }
428
+ };
465
429
  //#endregion
466
- //#region src/services/openpanel/buffer.ts
467
- const buffer = [];
468
- let errorHandler;
469
- function defaultOnError(err) {
470
- console.warn("[useOpenPanelAnalytics] track failed:", err);
471
- }
430
+ //#region src/services/openpanel/factory.ts
472
431
  /**
473
- * Forward a single event to the active client, swallowing any throw.
474
- *
475
- * The outer try/catch handles synchronous throws from `client.track`; the
476
- * inner `.catch()` handles rejected promises. Both are needed because
477
- * `Promise.resolve(x).catch()` cannot catch a throw from evaluating `x`.
432
+ * Returns a `ProcessorFactory` that, for each drive, creates a single
433
+ * `OpenPanelProcessor` record whose `filter.documentType` is the union of all
434
+ * document types present in the event mapping table.
478
435
  */
479
- function forward(client, name, props) {
480
- try {
481
- Promise.resolve(client.track(name, props)).catch((err) => (errorHandler ?? defaultOnError)(err));
482
- } catch (err) {
483
- (errorHandler ?? defaultOnError)(err);
484
- }
436
+ function createOpenPanelProcessorFactory(config) {
437
+ return function openPanelProcessorFactory(_driveHeader) {
438
+ const documentType = Array.from(config.events.lookupMap.keys());
439
+ return [{
440
+ processor: new OpenPanelProcessor(config.client, config.events.lookupMap, config.onError),
441
+ filter: { documentType },
442
+ startFrom: config.startFrom ?? "current"
443
+ }];
444
+ };
485
445
  }
446
+ //#endregion
447
+ //#region src/components/openpanel-traits.ts
486
448
  /**
487
- * Drain the pre-init buffer in FIFO order through `client.track`, then forward
488
- * subsequent events directly. Called once from `getOpenPanelClient()`.
449
+ * Builds the OpenPanel identity traits from a renown User.
450
+ *
451
+ * Canonical trait schema (shared with Renown and Vetra — each app sends every
452
+ * field it has data for, under these names):
453
+ * - `address`, `did`, `networkId`, `chainId`, `caip2` — wallet/chain facts.
454
+ * - `ensName`, `ensAvatar` — raw ENS facts.
455
+ * - `username`, `userImage`, `profileDocumentId`, `profileCreatedAt` — raw
456
+ * Renown profile facts.
457
+ * - `accountType` — wallet-adapter concept; only Renown has it.
458
+ *
459
+ * Rules:
460
+ * - `credential` (contains a JWT) is **never** forwarded.
461
+ * - Traits carry raw facts only; resolved presentation values (avatar,
462
+ * display name) go in OpenPanel's native identify fields — see
463
+ * {@link buildIdentifyPayload}.
464
+ * - Optional fields (`ens`, `profile`) are only included when their value is
465
+ * non-nullish (guards against `null` from `RenownProfile` fields as well
466
+ * as plain `undefined`).
467
+ *
468
+ * Mirror the Sentry pattern in `store/user.ts`: destructure off `credential`
469
+ * first, then assemble the trait payload from the remainder.
489
470
  */
490
- function drainOpenPanelBuffer(client, onError) {
491
- errorHandler = onError;
492
- const pending = buffer.splice(0, buffer.length);
493
- for (const [name, props] of pending) forward(client, name, props);
471
+ function buildTraits(user) {
472
+ const { credential: _credential, ...rest } = user;
473
+ const traits = {
474
+ address: rest.address,
475
+ did: rest.did,
476
+ networkId: rest.networkId,
477
+ chainId: rest.chainId,
478
+ caip2: `${rest.networkId}:${rest.chainId}`
479
+ };
480
+ if (rest.ens?.name != null) traits.ensName = rest.ens.name;
481
+ if (rest.ens?.avatarUrl != null) traits.ensAvatar = rest.ens.avatarUrl;
482
+ if (rest.profile?.username != null) traits.username = rest.profile.username;
483
+ if (rest.profile?.userImage != null) traits.userImage = rest.profile.userImage;
484
+ if (rest.profile?.documentId != null) traits.profileDocumentId = rest.profile.documentId;
485
+ if (rest.profile?.createdAt != null) traits.profileCreatedAt = rest.profile.createdAt;
486
+ return traits;
494
487
  }
495
488
  /**
496
- * Clear the buffer and reset the active client. Buffered pre-consent events
497
- * are discarded so they are not replayed if the user later re-accepts.
489
+ * Builds the full `identify()` payload:
490
+ * - `profileId` is the wallet address — the cross-app profile key shared with
491
+ * Renown and Vetra.
492
+ * - `avatar` / `firstName` are OpenPanel's native profile fields (they drive
493
+ * the picture and name in the dashboard UI), resolved as
494
+ * `userImage ?? ensAvatar` and `ensName ?? username`.
495
+ * - `properties` are the raw traits from {@link buildTraits}.
498
496
  */
499
- function clearOpenPanelBuffer() {
500
- buffer.length = 0;
501
- errorHandler = void 0;
497
+ function buildIdentifyPayload(user) {
498
+ const avatar = user.profile?.userImage ?? user.ens?.avatarUrl;
499
+ const firstName = user.ens?.name ?? user.profile?.username;
500
+ return {
501
+ profileId: user.address,
502
+ ...avatar != null ? { avatar } : {},
503
+ ...firstName != null ? { firstName } : {},
504
+ properties: buildTraits(user)
505
+ };
502
506
  }
503
507
  //#endregion
504
- //#region src/hooks/usePendingInstallations.ts
505
- const emptyArray = [];
508
+ //#region src/components/openpanel.tsx
509
+ /**
510
+ * `OpenPanel` is a `null`-rendering component that manages the full lifecycle
511
+ * of the OpenPanel analytics subsystem.
512
+ *
513
+ * Gates:
514
+ * - `useAcceptedCookies().analytics === true` — the existing analytics cookie.
515
+ * - `connectConfig.openPanel.clientId` non-empty — no client ID → no-op.
516
+ *
517
+ * Behaviour when both gates pass:
518
+ * 1. Lazy-imports `@openpanel/web` and builds the singleton via
519
+ * `getOpenPanelClient(connectConfig.openPanel)`.
520
+ * 2. Exposes the client on `window.openPanel` for the card-6
521
+ * `useOpenPanelAnalytics()` hook to consume.
522
+ * 3. If `connectConfig.openPanel.trackOperations`, registers the processor
523
+ * factory against `processorManager` so document operations are forwarded.
524
+ * 4. Calls `client.identify()` when the renown user transitions from
525
+ * `undefined` → defined (login). The profile ID is the wallet address —
526
+ * the cross-app key shared with Renown and Vetra.
527
+ * 5. Calls `client.clear()` when the user transitions from defined →
528
+ * `undefined` (logout).
529
+ *
530
+ * Teardown (unmount **or** consent revocation):
531
+ * - `unregisterFactory("openpanel")` to remove the processor.
532
+ * - `resetOpenPanelClient()` to clear the singleton.
533
+ * - `window.openPanel` is cleared.
534
+ *
535
+ * Mirrors the Sentry pattern in `store/user.ts` for login/logout detection.
536
+ * Analytics failures are caught and forwarded to `console.warn` — they must
537
+ * never throw into the application.
538
+ *
539
+ * Mounted next to `<Analytics />` in `app.tsx`.
540
+ */
541
+ function OpenPanel() {
542
+ const [{ analytics }] = useAcceptedCookies();
543
+ const user = useUser();
544
+ const module = useReactorClientModule();
545
+ const reactorClientModule = module?.kind === "browser" ? module : void 0;
546
+ const [client, setClient] = useState();
547
+ /**
548
+ * Tracks the previous `user` value so we can detect the two transitions:
549
+ * undefined → defined (login)
550
+ * defined → undefined (logout)
551
+ */
552
+ const prevUserRef = useRef(void 0);
553
+ const enabled = analytics && !!connectConfig.openPanel.clientId;
554
+ const processorManager = reactorClientModule?.reactorModule?.processorManager;
555
+ useEffect(() => {
556
+ if (!enabled) return;
557
+ let cancelled = false;
558
+ const isCancelled = () => cancelled;
559
+ const setup = async () => {
560
+ let builtClient;
561
+ try {
562
+ builtClient = await getOpenPanelClient(connectConfig.openPanel);
563
+ } catch (err) {
564
+ console.warn("[OpenPanel] Failed to build client:", err);
565
+ return;
566
+ }
567
+ if (isCancelled() || !builtClient) return;
568
+ setClient(builtClient);
569
+ window.openPanel = builtClient;
570
+ if (connectConfig.openPanel.trackOperations && processorManager) try {
571
+ await processorManager.registerFactory("openpanel", createOpenPanelProcessorFactory({
572
+ client: builtClient,
573
+ events: {
574
+ mappings: eventMappings,
575
+ lookupMap: eventLookupMap
576
+ },
577
+ startFrom: "current"
578
+ }));
579
+ if (isCancelled()) await processorManager.unregisterFactory("openpanel").catch((err) => console.warn("[OpenPanel] Failed to unregister factory after cancellation:", err));
580
+ } catch (err) {
581
+ console.warn("[OpenPanel] Failed to register processor factory:", err);
582
+ }
583
+ };
584
+ setup();
585
+ return () => {
586
+ cancelled = true;
587
+ prevUserRef.current = void 0;
588
+ if (connectConfig.openPanel.trackOperations && processorManager) processorManager.unregisterFactory("openpanel").catch((err) => console.warn("[OpenPanel] Failed to unregister processor factory:", err));
589
+ resetOpenPanelClient();
590
+ window.openPanel = void 0;
591
+ setClient(void 0);
592
+ };
593
+ }, [enabled, processorManager]);
594
+ useEffect(() => {
595
+ if (!enabled || !client) return;
596
+ const prev = prevUserRef.current;
597
+ prevUserRef.current = user;
598
+ if (!prev && user) try {
599
+ client.identify(buildIdentifyPayload(user));
600
+ } catch (err) {
601
+ console.warn("[OpenPanel] Failed to identify user:", err);
602
+ }
603
+ else if (prev && !user) try {
604
+ client.clear();
605
+ } catch (err) {
606
+ console.warn("[OpenPanel] Failed to clear user:", err);
607
+ }
608
+ }, [
609
+ client,
610
+ user,
611
+ enabled
612
+ ]);
613
+ return null;
614
+ }
615
+ //#endregion
616
+ //#region src/components/document-editor-container.tsx
617
+ function DocumentEditorContainer() {
618
+ const [selectedDocument] = useSelectedDocument();
619
+ const parentFolder = useNodeParentFolderById(selectedDocument.header.id);
620
+ useMemo(() => {
621
+ return async () => {};
622
+ }, []);
623
+ useCallback(() => {
624
+ setSelectedNode(parentFolder);
625
+ }, [parentFolder]);
626
+ return /* @__PURE__ */ jsx("div", {
627
+ id: "document-editor-container",
628
+ className: "flex-1",
629
+ "data-document-type": selectedDocument.header.documentType,
630
+ children: /* @__PURE__ */ jsx(DocumentEditor, { document: selectedDocument })
631
+ });
632
+ }
633
+ //#endregion
634
+ //#region src/components/editor-loader.tsx
635
+ function EditorLoader(props) {
636
+ const [showLoading, setShowLoading] = useState(false);
637
+ useEffect(() => {
638
+ setTimeout(() => {
639
+ setShowLoading(true);
640
+ }, props.loadingTimeout ?? 200);
641
+ }, [props]);
642
+ if (!showLoading) return null;
643
+ const { customEditorLoader, ...defaultProps } = props;
644
+ if (customEditorLoader) return /* @__PURE__ */ jsx(Fragment, { children: customEditorLoader });
645
+ return /* @__PURE__ */ jsx(DefaultEditorLoader, { ...defaultProps });
646
+ }
647
+ //#endregion
648
+ //#region src/components/app-container.tsx
649
+ function AppContainer() {
650
+ const [selectedDrive] = useSelectedDriveSafe();
651
+ const selectedDocumentId = useSelectedDocumentId();
652
+ const app = useAppModuleById(selectedDrive?.header.meta?.preferredEditor);
653
+ const defaultApp = useDefaultAppModule();
654
+ if (!selectedDrive) return /* @__PURE__ */ jsx(EditorLoader, {});
655
+ const AppComponent = app?.Component ?? defaultApp?.Component ?? GenericDriveExplorer.Component;
656
+ if (!AppComponent) throw new Error("No app component found");
657
+ return /* @__PURE__ */ jsx(ErrorBoundary$1, {
658
+ variant: "detailed",
659
+ resetKeys: [selectedDrive.header.id],
660
+ loggerContext: ["Connect", "App"],
661
+ children: /* @__PURE__ */ jsx(Suspense, {
662
+ fallback: /* @__PURE__ */ jsx(EditorLoader, {}),
663
+ children: /* @__PURE__ */ jsx(DropZoneWrapper, {
664
+ className: "flex h-full flex-col overflow-auto",
665
+ children: /* @__PURE__ */ jsx(AppComponent, { children: selectedDocumentId ? /* @__PURE__ */ jsx(DocumentEditorContainer, {}) : null })
666
+ })
667
+ })
668
+ });
669
+ }
670
+ //#endregion
671
+ //#region src/hooks/useFailedInstallations.ts
672
+ const emptyArray$1 = [];
673
+ function useFailedInstallations() {
674
+ const discoveryService = usePackageDiscoveryService();
675
+ return useSyncExternalStore((cb) => discoveryService?.subscribeFailed(cb) ?? (() => {}), () => discoveryService?.getFailedInstallations() ?? emptyArray$1);
676
+ }
677
+ //#endregion
678
+ //#region src/hooks/useInitSentry.ts
679
+ const logger$1 = childLogger(["sentry"]);
680
+ let clientStarted = false;
681
+ async function getSentry() {
682
+ return await import("@sentry/react");
683
+ }
684
+ async function initSentry() {
685
+ const Sentry = await getSentry();
686
+ const integrations = [
687
+ Sentry.httpClientIntegration(),
688
+ Sentry.extraErrorDataIntegration({ depth: 5 }),
689
+ Sentry.replayIntegration(),
690
+ Sentry.captureConsoleIntegration({ levels: ["error"] })
691
+ ];
692
+ if (connectConfig.sentry.tracing) integrations.push(Sentry.reactRouterV6BrowserTracingIntegration({
693
+ useEffect: React.useEffect,
694
+ useLocation,
695
+ useNavigationType,
696
+ createRoutesFromChildren,
697
+ matchRoutes
698
+ }));
699
+ Sentry.init({
700
+ release: connectConfig.sentry.release,
701
+ dsn: connectConfig.sentry.dsn ?? void 0,
702
+ environment: connectConfig.sentry.env,
703
+ integrations,
704
+ ignoreErrors: [
705
+ "User is not allowed to create files",
706
+ "User is not allowed to move documents",
707
+ "The user aborted a request."
708
+ ],
709
+ sendDefaultPii: true,
710
+ tracesSampleRate: 1,
711
+ replaysSessionSampleRate: .1,
712
+ replaysOnErrorSampleRate: 1,
713
+ beforeSend(event, hint) {
714
+ const error = hint.originalException;
715
+ if (error instanceof TypeError && error.message.includes("Failed to fetch") && !navigator.onLine) return null;
716
+ return event;
717
+ }
718
+ });
719
+ setSentryModule(Sentry);
720
+ clientStarted = true;
721
+ }
722
+ async function closeClient() {
723
+ if (!clientStarted) return;
724
+ const sentry = await getSentry();
725
+ setSentryModule(void 0);
726
+ return sentry.getClient()?.close();
727
+ }
728
+ function useInitSentry() {
729
+ const [acceptedCookies] = useAcceptedCookies();
730
+ const { analytics } = acceptedCookies;
731
+ useEffect(() => {
732
+ if (!analytics) {
733
+ closeClient().catch((error) => logger$1.error("@error", error));
734
+ return;
735
+ }
736
+ if (clientStarted || connectConfig.sentry.dsn === null || connectConfig.sentry.dsn === void 0 || connectConfig.sentry.dsn === "") return;
737
+ initSentry().catch((error) => logger$1.error("@error", error));
738
+ }, [analytics]);
739
+ }
740
+ //#endregion
741
+ //#region src/hooks/usePendingInstallations.ts
742
+ const emptyArray = [];
506
743
  function usePendingInstallations() {
507
744
  const discoveryService = usePackageDiscoveryService();
508
745
  const cacheRef = useRef(emptyArray);
509
- return useSyncExternalStore((cb) => discoveryService?.subscribePending(cb) ?? (() => {}), useCallback(() => {
746
+ const getSnapshot = useCallback(() => {
510
747
  if (!discoveryService) return emptyArray;
511
748
  const next = discoveryService.getPendingInstallations() ?? emptyArray;
512
749
  const prev = cacheRef.current;
513
750
  if (next === prev || next.length === prev.length && next.every((p, i) => p === prev[i])) return prev;
514
751
  cacheRef.current = next;
515
752
  return next;
516
- }, [discoveryService]));
753
+ }, [discoveryService]);
754
+ return useSyncExternalStore((cb) => discoveryService?.subscribePending(cb) ?? (() => {}), getSnapshot);
517
755
  }
518
756
  //#endregion
519
757
  //#region src/hooks/useUndoRedoShortcuts.ts
@@ -536,666 +774,353 @@ const useUndoRedoShortcuts = (props) => {
536
774
  }, {}, [canRedo, redo]);
537
775
  };
538
776
  //#endregion
539
- //#region src/components/app-skeleton.tsx
540
- const LOADER_DELAY = 250;
541
- const PHASE_LABEL = {
542
- clone: "Backing up local database…",
543
- dump: "Exporting data from previous version…",
544
- restore: "Restoring data into the new database…"
545
- };
546
- const MigrationOverlay = () => {
547
- const status = useSyncExternalStore(subscribeMigrationStatus, getMigrationStatus, () => null);
548
- if (!status) return null;
549
- return /* @__PURE__ */ jsx("div", {
550
- className: "absolute inset-0 z-20 flex items-center justify-center",
551
- children: /* @__PURE__ */ jsxs("div", {
552
- className: "rounded-lg bg-card/90 px-6 py-4 text-sm text-foreground shadow-lg",
553
- children: [/* @__PURE__ */ jsx("div", {
554
- className: "font-medium",
555
- children: "Upgrading local database…"
556
- }), /* @__PURE__ */ jsx("div", {
557
- className: "text-foreground",
558
- children: PHASE_LABEL[status.phase]
559
- })]
560
- })
561
- });
562
- };
563
- const Loader = ({ delay = LOADER_DELAY }) => {
564
- const isSSR = typeof window === "undefined";
565
- const showInitialLoader = typeof document !== "undefined" && document.body.getAttribute("data-show-loader") === "true";
566
- if (!isSSR) initTheme();
567
- const [showLoading, setShowLoading] = useState(!delay || showInitialLoader);
568
- useEffect(() => {
569
- const id = setTimeout(() => {
570
- setShowLoading(true);
571
- }, delay);
572
- return () => clearTimeout(id);
573
- }, []);
574
- return /* @__PURE__ */ jsxs("div", {
575
- className: `skeleton-loader absolute inset-0 z-10 flex items-center justify-center ${showLoading ? "" : "hidden"}`,
576
- children: [/* @__PURE__ */ jsx("div", {
577
- className: "animate-pulse overflow-hidden rounded-full shadow-lg",
578
- children: /* @__PURE__ */ jsx(LogoAnimation, {})
579
- }), isSSR ? /* @__PURE__ */ jsx("script", { dangerouslySetInnerHTML: { __html: `setTimeout(() => {
580
- document.querySelector('.skeleton-loader')?.classList.remove('hidden');
581
- document.body.setAttribute('data-show-loader', 'true');
582
- }, ${delay})` } }) : null]
583
- });
584
- };
585
- const AppSkeleton = (props) => {
586
- const isSSR = typeof window === "undefined";
587
- const isHomeScreen = !isSSR && window.location.pathname === getBasePath();
588
- return /* @__PURE__ */ jsxs("div", {
589
- className: "flex h-screen overflow-hidden bg-background",
590
- children: [
591
- !(!isSSR && getIsEmbedded()) && /* @__PURE__ */ jsx(ConnectSidebar, {
592
- className: "animate-pulse",
593
- onLogin: void 0,
594
- onDisconnect: void 0,
595
- onClickSettings: void 0,
596
- address: void 0
597
- }),
598
- /* @__PURE__ */ jsx(HomeScreen, {
599
- containerClassName: isSSR || !isHomeScreen ? "home-screen hidden" : void 0,
600
- children: props.children ?? null
601
- }),
602
- isSSR ? /* @__PURE__ */ jsx("script", { dangerouslySetInnerHTML: { __html: `
603
- const baseEl = document.querySelector('base');
604
- const href = baseEl?.getAttribute('href');
605
- const basePath = href || '/';
606
- if (window.location.pathname === basePath) {
607
- document.querySelector('.home-screen')?.classList.remove('hidden')
608
- }` } }) : null,
609
- !props.children ? /* @__PURE__ */ jsx(Loader, {}) : null,
610
- /* @__PURE__ */ jsx(MigrationOverlay, {})
611
- ]
612
- });
777
+ //#region src/context/sentry-provider.tsx
778
+ const SentryProvider = ({ children }) => {
779
+ useInitSentry();
780
+ return children;
613
781
  };
614
782
  //#endregion
615
- //#region src/components/error-boundary.tsx
616
- const logger$1 = childLogger(["Connect"]);
617
- function hasCustomFallback(props) {
618
- return "fallbackRender" in props;
783
+ //#region src/utils/document-editor-debug-tools.ts
784
+ var DocumentEditorDebugTools = class {
785
+ document;
786
+ operations = [];
787
+ constructor(document) {
788
+ if (document) this.document = document;
789
+ }
790
+ operationsToTableObject(operations) {
791
+ return operations.map((op) => ({
792
+ ...op,
793
+ input: JSON.stringify(op.action.input)
794
+ }));
795
+ }
796
+ setDocument(document) {
797
+ this.document = document;
798
+ }
799
+ getDocument() {
800
+ return this.document;
801
+ }
802
+ getOperations() {
803
+ return this.operations;
804
+ }
805
+ pushOperation(operation) {
806
+ this.operations.push(operation);
807
+ }
808
+ operationsTable() {
809
+ if (!this.document) console.warn("No document");
810
+ const ops = Object.values(this.document?.operations || {}).filter((array) => array !== void 0).flatMap((array) => array).sort((a, b) => a.index - b.index);
811
+ console.table(this.operationsToTableObject(ops));
812
+ }
813
+ scopeOperationsTable(scope) {
814
+ if (!this.document) console.warn("No document");
815
+ const ops = this.document?.operations[scope] || [];
816
+ console.table(this.operationsToTableObject(ops));
817
+ }
818
+ operationsLog() {
819
+ console.log(this.operations);
820
+ }
821
+ operationsLogTable() {
822
+ console.table(this.operationsToTableObject(this.operations));
823
+ }
824
+ clear() {
825
+ this.operations = [];
826
+ this.document = void 0;
827
+ }
828
+ };
829
+ //#endregion
830
+ //#region src/utils/launch-queue.ts
831
+ let pendingImportFiles = [];
832
+ const pendingListeners = /* @__PURE__ */ new Set();
833
+ function notifyPendingListeners() {
834
+ for (const listener of pendingListeners) listener();
619
835
  }
620
- function SilentFallback() {
621
- return null;
836
+ function getPendingImportFiles() {
837
+ return pendingImportFiles;
622
838
  }
623
- /**
624
- * Simple text-based fallback component.
625
- * Displays a centered message when an error occurs.
626
- */
627
- function TextFallback({ message = "Something went wrong" }) {
628
- return /* @__PURE__ */ jsx("div", {
629
- className: "text-center wrap-break-word text-foreground",
630
- children: message
631
- });
839
+ /** Stable identity of a pending file (also the picker's pre-check cache key). */
840
+ function pendingFileKey(file) {
841
+ return `${file.name}|${file.size}|${file.lastModified}`;
632
842
  }
633
- /**
634
- * Detailed fallback component showing full error information.
635
- * Displays error message with a collapsible details section.
636
- * Useful for development and debugging purposes.
637
- */
638
- function DetailedFallback({ error, resetErrorBoundary }) {
639
- const errorMessage = error instanceof Error ? error.message : String(error);
640
- const errorDetails = error instanceof Error ? error.stack ?? String(error.cause) : JSON.stringify(error, null, 2);
641
- return /* @__PURE__ */ jsx("div", {
642
- className: "z-10 mx-auto flex max-w-[80%] flex-1 items-center justify-center p-6",
643
- children: /* @__PURE__ */ jsxs("div", {
644
- className: "w-full max-w-lg rounded-lg border border-border bg-card p-6 text-foreground shadow-sm",
645
- children: [
646
- /* @__PURE__ */ jsxs("div", {
647
- className: "mb-3 flex items-center gap-2",
648
- children: [/* @__PURE__ */ jsx(Icon, {
649
- name: "Error",
650
- className: "size-5 shrink-0 text-destructive"
651
- }), /* @__PURE__ */ jsx("h1", {
652
- className: "text-lg font-semibold text-foreground",
653
- children: "Something went wrong"
654
- })]
655
- }),
656
- /* @__PURE__ */ jsx("p", {
657
- className: "mb-4 text-sm wrap-break-word text-foreground",
658
- children: errorMessage
659
- }),
660
- errorDetails !== "{}" && /* @__PURE__ */ jsxs("details", {
661
- className: "group",
662
- children: [/* @__PURE__ */ jsx("summary", {
663
- className: "cursor-pointer text-sm font-medium text-foreground underline select-none hover:hover-effect",
664
- children: "Show details"
665
- }), /* @__PURE__ */ jsx("pre", {
666
- className: "mt-2 max-h-48 overflow-auto rounded-sm bg-muted p-3 text-xs text-foreground",
667
- children: errorDetails
668
- })]
669
- }),
670
- /* @__PURE__ */ jsx(PowerhouseButton, {
671
- type: "button",
672
- onClick: resetErrorBoundary,
673
- className: "mt-4 px-3 py-1.5 text-base font-medium",
674
- children: "Try again"
675
- })
676
- ]
677
- })
843
+ function addPendingImportFiles(files) {
844
+ const seen = new Set(pendingImportFiles.map(pendingFileKey));
845
+ const fresh = files.filter((file) => {
846
+ const key = pendingFileKey(file);
847
+ if (seen.has(key)) return false;
848
+ seen.add(key);
849
+ return true;
678
850
  });
851
+ if (fresh.length === 0) return;
852
+ pendingImportFiles = [...pendingImportFiles, ...fresh];
853
+ notifyPendingListeners();
679
854
  }
680
- /**
681
- * Centered error message fallback component.
682
- * Displays the error message in a centered, full-size container.
683
- * Suitable for use as a custom fallbackRender when you need simple error display.
684
- */
685
- function CenteredErrorMessage({ error }) {
686
- return /* @__PURE__ */ jsx("div", {
687
- className: "flex size-full items-center justify-center p-6",
688
- children: /* @__PURE__ */ jsx("h3", {
689
- className: "max-w-lg min-w-0 text-center text-lg font-semibold wrap-break-word text-foreground",
690
- children: error instanceof Error ? error.message : String(error)
691
- })
692
- });
855
+ function clearPendingImportFiles() {
856
+ if (pendingImportFiles.length === 0) return;
857
+ pendingImportFiles = [];
858
+ notifyPendingListeners();
693
859
  }
694
- function getFallbackComponent(variant, fallbackMessage) {
695
- switch (variant) {
696
- case "silent": return SilentFallback;
697
- case "text": return () => /* @__PURE__ */ jsx(TextFallback, { message: fallbackMessage });
698
- case "detailed": return DetailedFallback;
699
- default: return CenteredErrorMessage;
860
+ function subscribePendingImportFiles(cb) {
861
+ pendingListeners.add(cb);
862
+ return () => {
863
+ pendingListeners.delete(cb);
864
+ };
865
+ }
866
+ async function handleLaunchParams(params) {
867
+ const handles = params.files.filter((handle) => handle.kind === "file");
868
+ if (handles.length === 0) return;
869
+ const files = [];
870
+ for (const handle of handles) try {
871
+ files.push(await handle.getFile());
872
+ } catch (error) {
873
+ console.error("Failed to read launched file:", handle.name, error);
700
874
  }
875
+ if (files.length === 0) return;
876
+ addPendingImportFiles(files);
877
+ showPHModal({ type: "openFileDocuments" });
878
+ }
879
+ function maybeReopenImportModal() {
880
+ if (getPendingImportFiles().length === 0) return;
881
+ if (window.ph?.modal !== void 0) return;
882
+ showPHModal({ type: "openFileDocuments" });
701
883
  }
884
+ let initialized = false;
702
885
  /**
703
- * Unified error boundary component for catching and handling React errors.
704
- *
705
- * Built on top of `react-error-boundary`, this component provides:
706
- * - Automatic error logging with configurable context
707
- * - Multiple fallback UI variants (silent, text, detailed)
708
- * - Support for custom fallback render functions
709
- * - Reset capability via `resetKeys`
710
- *
711
- * @example
712
- * // Using a predefined variant
713
- * <ErrorBoundary variant="detailed" loggerContext={["Connect", "Editor"]}>
714
- * <EditorComponent />
715
- * </ErrorBoundary>
716
- *
717
- * @example
718
- * // Using a custom message with the text variant
719
- * <ErrorBoundary variant="text" fallbackMessage="Failed to load drives">
720
- * <DrivesList />
721
- * </ErrorBoundary>
722
- *
723
- * @example
724
- * // Using a custom fallback render
725
- * <ErrorBoundary
726
- * fallbackRender={CenteredErrorMessage}
727
- * onError={(error) => trackError(error)}
728
- * >
729
- * <MyComponent />
730
- * </ErrorBoundary>
731
- *
732
- * @example
733
- * // Silent mode for modals (renders null on error)
734
- * <ErrorBoundary variant="silent" loggerContext={["Connect", "Modals"]}>
735
- * <ModalContent />
736
- * </ErrorBoundary>
886
+ * Register the launchQueue consumer that receives files opened with Connect
887
+ * through the OS file association. Idempotent (safe under StrictMode double
888
+ * effects) and a no-op where the File Handling API doesn't exist — Firefox,
889
+ * Safari, and any context without an installed PWA manifest simply never
890
+ * deliver launches.
737
891
  */
738
- function ErrorBoundary$1(props) {
739
- const { children, onError, resetKeys, loggerContext } = props;
740
- const handleError = (error, info) => {
741
- if (error.message.includes("Failed to fetch dynamically imported module") && error.message.includes("node_modules/.vite")) {
742
- console.error(error);
743
- console.log("Outdated chunk detected, reloading page...");
744
- window.location.reload();
745
- return;
746
- }
747
- (loggerContext ? childLogger(loggerContext) : logger$1).error("@error @info", error, info);
748
- onError?.(error, info);
749
- };
750
- return /* @__PURE__ */ jsx(ErrorBoundary, {
751
- fallbackRender: hasCustomFallback(props) ? props.fallbackRender : getFallbackComponent(props.variant, props.fallbackMessage),
752
- onError: handleError,
753
- resetKeys,
754
- children
892
+ function initLaunchQueueFileHandling() {
893
+ if (initialized) return;
894
+ initialized = true;
895
+ window.addEventListener("ph:modalUpdated", maybeReopenImportModal);
896
+ window.launchQueue?.setConsumer((params) => {
897
+ handleLaunchParams(params);
755
898
  });
756
899
  }
757
900
  //#endregion
758
- //#region src/components/analytics.tsx
759
- function gtag(...args) {
760
- window.dataLayer?.push(...args);
901
+ //#region src/utils/open-file-uploads.ts
902
+ let uploads = [];
903
+ const listeners = /* @__PURE__ */ new Set();
904
+ function notifyUploadListeners() {
905
+ for (const listener of listeners) listener();
761
906
  }
762
- const Analytics = () => {
763
- const gaTrackingId = connectConfig.gaTrackingId;
764
- const [{ analytics }] = useAcceptedCookies();
765
- const useAnalytics = gaTrackingId && analytics;
766
- useEffect(() => {
767
- if (useAnalytics) {
768
- const script = document.createElement("script");
769
- script.src = `https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`;
770
- script.async = true;
771
- document.head.appendChild(script);
772
- window.dataLayer = window.dataLayer || [];
773
- gtag("js", /* @__PURE__ */ new Date());
774
- gtag("config", gaTrackingId);
775
- return () => {
776
- document.head.removeChild(script);
777
- };
778
- }
779
- }, [useAnalytics, gaTrackingId]);
780
- return null;
781
- };
782
- //#endregion
783
- //#region src/services/openpanel/client.ts
784
- let client;
785
- /**
786
- * Returns the cached `OpenPanel` singleton, building it on first call.
787
- *
788
- * When `config.clientId` is empty it returns `undefined` without importing
789
- * `@openpanel/web`, so the bundler can tree-shake the SDK out of production.
790
- */
791
- async function getOpenPanelClient(config) {
792
- if (!config.clientId) return;
793
- if (client) return client;
794
- const { OpenPanel: OpenPanelClass } = await import("@openpanel/web");
795
- client = new OpenPanelClass({
796
- clientId: config.clientId,
797
- ...config.apiUrl ? { apiUrl: config.apiUrl } : {},
798
- trackScreenViews: true,
799
- trackOutgoingLinks: true
800
- });
801
- client.setGlobalProperties({ app: "connect" });
802
- drainOpenPanelBuffer(client);
803
- return client;
804
- }
805
- /**
806
- * Clears the cached singleton and the pre-init buffer. Call on consent
807
- * revocation or during tests; buffered events are discarded, not replayed.
808
- */
809
- function resetOpenPanelClient() {
810
- client = void 0;
811
- clearOpenPanelBuffer();
907
+ function getOpenFileUploads() {
908
+ return uploads;
812
909
  }
813
- //#endregion
814
- //#region src/services/openpanel/events.json
815
- var events_default = [
816
- {
817
- "documentType": "powerhouse/document-drive",
818
- "actionTypes": [
819
- "ADD_FOLDER",
820
- "DELETE_NODE",
821
- "ADD_FILE",
822
- "UPDATE_FILE",
823
- "COPY_NODE",
824
- "MOVE_NODE",
825
- "SET_DRIVE_NAME",
826
- "SET_DRIVE_ICON"
827
- ]
828
- },
829
- {
830
- "documentType": "powerhouse/document-model",
831
- "actionTypes": [
832
- "SET_MODEL_NAME",
833
- "SET_MODEL_ID",
834
- "ADD_MODULE",
835
- "DELETE_MODULE",
836
- "ADD_OPERATION",
837
- "DELETE_OPERATION"
838
- ]
839
- },
840
- {
841
- "documentType": "powerhouse/reactor-drive",
842
- "actionTypes": [
843
- "ADD_FOLDER",
844
- "REMOVE_FOLDER",
845
- "UPDATE_FOLDER"
846
- ]
847
- }
848
- ];
849
- //#endregion
850
- //#region src/services/openpanel/events.ts
851
- const EventMappingSchema = z.object({
852
- documentType: z.string().min(1),
853
- actionTypes: z.array(z.string().min(1)).min(1),
854
- alias: z.string().optional()
855
- }).strict();
856
- const EventMappingsSchema = z.array(EventMappingSchema).readonly();
857
- /**
858
- * Parses and validates the event mapping table, returning the validated array
859
- * and an O(1) lookup map. Accepts a `raw` override for tests. Throws on zod
860
- * failures and on duplicate `(documentType, actionType)` pairs.
861
- */
862
- function loadEvents(raw = events_default) {
863
- const result = EventMappingsSchema.safeParse(raw);
864
- if (!result.success) throw new Error(`Invalid OpenPanel events.json: ${result.error.message}`);
865
- const mappings = result.data;
866
- const lookupMap = /* @__PURE__ */ new Map();
867
- for (const mapping of mappings) {
868
- let inner = lookupMap.get(mapping.documentType);
869
- if (!inner) {
870
- inner = /* @__PURE__ */ new Map();
871
- lookupMap.set(mapping.documentType, inner);
872
- }
873
- for (const actionType of mapping.actionTypes) {
874
- if (inner.has(actionType)) throw new Error(`Duplicate OpenPanel event mapping for ${mapping.documentType}/${actionType}`);
875
- inner.set(actionType, mapping);
876
- }
877
- }
878
- return {
879
- mappings,
880
- lookupMap
910
+ function subscribeOpenFileUploads(cb) {
911
+ listeners.add(cb);
912
+ return () => {
913
+ listeners.delete(cb);
881
914
  };
882
915
  }
883
- const { mappings: defaultMappings, lookupMap: defaultLookupMap } = loadEvents();
884
- /** Validated mapping array from the bundled events.json. */
885
- const eventMappings = defaultMappings;
886
- /** O(1) lookup map: documentType → actionType → mapping. */
887
- const eventLookupMap = defaultLookupMap;
888
- /**
889
- * Normalizes a document type into a safe event-name segment: lowercased, `/`
890
- * replaced with `.`, and any character outside `[a-z0-9._-]` stripped.
891
- * e.g. `powerhouse/document-drive` → `powerhouse.document-drive`.
892
- */
893
- function normalize(documentType) {
894
- return documentType.toLowerCase().replace(/\//g, ".").replace(/[^a-z0-9._-]/g, "");
916
+ function removeOpenFileUpload(id) {
917
+ const next = uploads.filter((upload) => upload.id !== id);
918
+ if (next.length === uploads.length) return;
919
+ uploads = next;
920
+ notifyUploadListeners();
895
921
  }
896
- /**
897
- * Derives the OpenPanel event name: `mapping.alias` when present, otherwise
898
- * `${normalize(documentType)}.${actionType.toLowerCase()}`.
899
- */
900
- function deriveEventName(mapping, op) {
901
- if (mapping.alias) return mapping.alias;
902
- return `${normalize(op.context.documentType)}.${op.operation.action.type.toLowerCase()}`;
922
+ function clearOpenFileUploads() {
923
+ if (uploads.length === 0) return;
924
+ uploads = [];
925
+ notifyUploadListeners();
903
926
  }
904
- /**
905
- * Builds the default properties attached to every OpenPanel event. The `app`
906
- * property is stamped globally by the client, not here.
907
- */
908
- function buildDefaultProperties(op) {
909
- return {
910
- documentType: op.context.documentType,
911
- actionType: op.operation.action.type,
912
- documentId: op.context.documentId,
913
- scope: op.context.scope,
914
- branch: op.context.branch
915
- };
927
+ function addOpenFileUploads(rows) {
928
+ uploads = [...uploads, ...rows];
929
+ notifyUploadListeners();
916
930
  }
917
- //#endregion
918
- //#region src/services/openpanel/processor.ts
919
- /**
920
- * Read-only reactor `IProcessor` that translates matching document operations
921
- * into OpenPanel analytics events. Operations whose `(documentType, actionType)`
922
- * pair is absent from the lookup map are skipped; per-operation errors are
923
- * routed to `onError` and never thrown back to the manager.
924
- */
925
- var OpenPanelProcessor = class {
926
- constructor(client, lookupMap, onError = (err) => console.warn("[OpenPanelProcessor] Error tracking event:", err)) {
927
- this.client = client;
928
- this.lookupMap = lookupMap;
929
- this.onError = onError;
930
- }
931
- async onOperations(operations) {
932
- for (const op of operations) {
933
- const inner = this.lookupMap.get(op.context.documentType);
934
- if (!inner) continue;
935
- const mapping = inner.get(op.operation.action.type);
936
- if (!mapping) continue;
937
- const name = deriveEventName(mapping, op);
938
- const payload = buildDefaultProperties(op);
939
- try {
940
- await this.client.track(name, payload);
941
- } catch (err) {
942
- this.onError(err, op);
943
- }
944
- }
945
- }
946
- onDisconnect() {
947
- this.client.flush?.();
948
- return Promise.resolve();
949
- }
950
- };
951
- //#endregion
952
- //#region src/services/openpanel/factory.ts
953
- /**
954
- * Returns a `ProcessorFactory` that, for each drive, creates a single
955
- * `OpenPanelProcessor` record whose `filter.documentType` is the union of all
956
- * document types present in the event mapping table.
957
- */
958
- function createOpenPanelProcessorFactory(config) {
959
- return function openPanelProcessorFactory(_driveHeader) {
960
- const documentType = Array.from(config.events.lookupMap.keys());
961
- return [{
962
- processor: new OpenPanelProcessor(config.client, config.events.lookupMap, config.onError),
963
- filter: { documentType },
964
- startFrom: config.startFrom ?? "current"
965
- }];
966
- };
931
+ function patchOpenFileUpload(id, patch) {
932
+ uploads = uploads.map((upload) => upload.id === id ? {
933
+ ...upload,
934
+ ...patch
935
+ } : upload);
936
+ notifyUploadListeners();
967
937
  }
968
- //#endregion
969
- //#region src/components/openpanel-traits.ts
938
+ let uploadCounter = 0;
939
+ let importChain = Promise.resolve();
970
940
  /**
971
- * Builds the OpenPanel identity traits from a renown User.
972
- *
973
- * Canonical trait schema (shared with Renown and Vetra — each app sends every
974
- * field it has data for, under these names):
975
- * - `address`, `did`, `networkId`, `chainId`, `caip2` — wallet/chain facts.
976
- * - `ensName`, `ensAvatar` — raw ENS facts.
977
- * - `username`, `userImage`, `profileDocumentId`, `profileCreatedAt` — raw
978
- * Renown profile facts.
979
- * - `accountType` — wallet-adapter concept; only Renown has it.
980
- *
981
- * Rules:
982
- * - `credential` (contains a JWT) is **never** forwarded.
983
- * - Traits carry raw facts only; resolved presentation values (avatar,
984
- * display name) go in OpenPanel's native identify fields — see
985
- * {@link buildIdentifyPayload}.
986
- * - Optional fields (`ens`, `profile`) are only included when their value is
987
- * non-nullish (guards against `null` from `RenownProfile` fields as well
988
- * as plain `undefined`).
989
- *
990
- * Mirror the Sentry pattern in `store/user.ts`: destructure off `credential`
991
- * first, then assemble the trait payload from the remainder.
941
+ * Import one file and resolve once the flow truly ends. Completion is
942
+ * tracked through the progress stages, NOT the returned promise — the
943
+ * package-discovery retry path resolves early and keeps reporting through
944
+ * the callback. `resolveConflict: "duplicate"` is always passed: duplicates
945
+ * were resolved in the picker (rename), so the conflict stage must never
946
+ * fire — this also covers a duplicate appearing between pre-check and import.
992
947
  */
993
- function buildTraits(user) {
994
- const { credential: _credential, ...rest } = user;
995
- const traits = {
996
- address: rest.address,
997
- did: rest.did,
998
- networkId: rest.networkId,
999
- chainId: rest.chainId,
1000
- caip2: `${rest.networkId}:${rest.chainId}`
1001
- };
1002
- if (rest.ens?.name != null) traits.ensName = rest.ens.name;
1003
- if (rest.ens?.avatarUrl != null) traits.ensAvatar = rest.ens.avatarUrl;
1004
- if (rest.profile?.username != null) traits.username = rest.profile.username;
1005
- if (rest.profile?.userImage != null) traits.userImage = rest.profile.userImage;
1006
- if (rest.profile?.documentId != null) traits.profileDocumentId = rest.profile.documentId;
1007
- if (rest.profile?.createdAt != null) traits.profileCreatedAt = rest.profile.createdAt;
1008
- return traits;
948
+ function importOne(row, driveId, documentTypes) {
949
+ return new Promise((resolve) => {
950
+ let settled = false;
951
+ const settle = (fileNode) => {
952
+ if (settled) return;
953
+ settled = true;
954
+ resolve(fileNode);
955
+ };
956
+ addFileWithProgress(row.file, driveId, row.name, void 0, (progress) => {
957
+ patchOpenFileUpload(row.id, {
958
+ status: mapProgressStageToStatus(progress.stage),
959
+ progress: progress.progress,
960
+ ...progress.error ? { errorDetails: progress.error } : {},
961
+ ...progress.documentType ? { documentType: progress.documentType } : {},
962
+ ...progress.fileNode ? { fileNode: progress.fileNode } : {}
963
+ });
964
+ switch (progress.stage) {
965
+ case "complete":
966
+ settle(progress.fileNode);
967
+ break;
968
+ case "failed":
969
+ case "unsupported-document-type": settle(void 0);
970
+ }
971
+ }, documentTypes, "duplicate").catch(() => {
972
+ settle(void 0);
973
+ });
974
+ });
1009
975
  }
1010
976
  /**
1011
- * Builds the full `identify()` payload:
1012
- * - `profileId` is the wallet address — the cross-app profile key shared with
1013
- * Renown and Vetra.
1014
- * - `avatar` / `firstName` are OpenPanel's native profile fields (they drive
1015
- * the picture and name in the dashboard UI), resolved as
1016
- * `userImage ?? ensAvatar` and `ensName ?? username`.
1017
- * - `properties` are the raw traits from {@link buildTraits}.
977
+ * Run a confirmed batch of imports into a drive, feeding the floating upload
978
+ * panel. Rows appear immediately (queued), files import sequentially, and a
979
+ * single-file batch that succeeds opens its document in the editor.
1018
980
  */
1019
- function buildIdentifyPayload(user) {
1020
- const avatar = user.profile?.userImage ?? user.ens?.avatarUrl;
1021
- const firstName = user.ens?.name ?? user.profile?.username;
1022
- return {
1023
- profileId: user.address,
1024
- ...avatar != null ? { avatar } : {},
1025
- ...firstName != null ? { firstName } : {},
1026
- properties: buildTraits(user)
981
+ function runOpenFileImports(args) {
982
+ const { driveId, imports, documentTypes } = args;
983
+ if (imports.length === 0) return importChain;
984
+ const rows = imports.map(({ file, name }) => ({
985
+ id: `open-file-${++uploadCounter}`,
986
+ file,
987
+ name
988
+ }));
989
+ addOpenFileUploads(rows.map((row) => ({
990
+ id: row.id,
991
+ fileName: row.name,
992
+ fileSize: formatFileSize(row.file.size),
993
+ status: "pending",
994
+ progress: 0
995
+ })));
996
+ const run = async () => {
997
+ const results = [];
998
+ for (const row of rows) results.push(await importOne(row, driveId, documentTypes));
999
+ if (rows.length === 1 && results[0]) setSelectedNode(results[0]);
1027
1000
  };
1001
+ importChain = importChain.then(run, run);
1002
+ return importChain;
1028
1003
  }
1029
1004
  //#endregion
1030
- //#region src/components/openpanel.tsx
1031
- /**
1032
- * `OpenPanel` is a `null`-rendering component that manages the full lifecycle
1033
- * of the OpenPanel analytics subsystem.
1034
- *
1035
- * Gates:
1036
- * - `useAcceptedCookies().analytics === true` — the existing analytics cookie.
1037
- * - `connectConfig.openPanel.clientId` non-empty — no client ID → no-op.
1038
- *
1039
- * Behaviour when both gates pass:
1040
- * 1. Lazy-imports `@openpanel/web` and builds the singleton via
1041
- * `getOpenPanelClient(connectConfig.openPanel)`.
1042
- * 2. Exposes the client on `window.openPanel` for the card-6
1043
- * `useOpenPanelAnalytics()` hook to consume.
1044
- * 3. If `connectConfig.openPanel.trackOperations`, registers the processor
1045
- * factory against `processorManager` so document operations are forwarded.
1046
- * 4. Calls `client.identify()` when the renown user transitions from
1047
- * `undefined` → defined (login). The profile ID is the wallet address —
1048
- * the cross-app key shared with Renown and Vetra.
1049
- * 5. Calls `client.clear()` when the user transitions from defined →
1050
- * `undefined` (logout).
1051
- *
1052
- * Teardown (unmount **or** consent revocation):
1053
- * - `unregisterFactory("openpanel")` to remove the processor.
1054
- * - `resetOpenPanelClient()` to clear the singleton.
1055
- * - `window.openPanel` is cleared.
1056
- *
1057
- * Mirrors the Sentry pattern in `store/user.ts` for login/logout detection.
1058
- * Analytics failures are caught and forwarded to `console.warn` — they must
1059
- * never throw into the application.
1060
- *
1061
- * Mounted next to `<Analytics />` in `app.tsx`.
1062
- */
1063
- function OpenPanel() {
1064
- const [{ analytics }] = useAcceptedCookies();
1065
- const user = useUser();
1066
- const module = useReactorClientModule();
1067
- const reactorClientModule = module?.kind === "browser" ? module : void 0;
1068
- const [client, setClient] = useState();
1069
- /**
1070
- * Tracks the previous `user` value so we can detect the two transitions:
1071
- * undefined → defined (login)
1072
- * defined → undefined (logout)
1073
- */
1074
- const prevUserRef = useRef(void 0);
1075
- const enabled = analytics && !!connectConfig.openPanel.clientId;
1076
- const processorManager = reactorClientModule?.reactorModule?.processorManager;
1077
- useEffect(() => {
1078
- if (!enabled) return;
1079
- let cancelled = false;
1080
- const isCancelled = () => cancelled;
1081
- const setup = async () => {
1082
- let builtClient;
1083
- try {
1084
- builtClient = await getOpenPanelClient(connectConfig.openPanel);
1085
- } catch (err) {
1086
- console.warn("[OpenPanel] Failed to build client:", err);
1087
- return;
1088
- }
1089
- if (isCancelled() || !builtClient) return;
1090
- setClient(builtClient);
1091
- window.openPanel = builtClient;
1092
- if (connectConfig.openPanel.trackOperations && processorManager) try {
1093
- await processorManager.registerFactory("openpanel", createOpenPanelProcessorFactory({
1094
- client: builtClient,
1095
- events: {
1096
- mappings: eventMappings,
1097
- lookupMap: eventLookupMap
1098
- },
1099
- startFrom: "current"
1100
- }));
1101
- if (isCancelled()) await processorManager.unregisterFactory("openpanel").catch((err) => console.warn("[OpenPanel] Failed to unregister factory after cancellation:", err));
1102
- } catch (err) {
1103
- console.warn("[OpenPanel] Failed to register processor factory:", err);
1104
- }
1105
- };
1106
- setup();
1107
- return () => {
1108
- cancelled = true;
1109
- prevUserRef.current = void 0;
1110
- if (connectConfig.openPanel.trackOperations && processorManager) processorManager.unregisterFactory("openpanel").catch((err) => console.warn("[OpenPanel] Failed to unregister processor factory:", err));
1111
- resetOpenPanelClient();
1112
- window.openPanel = void 0;
1113
- setClient(void 0);
1114
- };
1115
- }, [enabled, processorManager]);
1116
- useEffect(() => {
1117
- if (!enabled || !client) return;
1118
- const prev = prevUserRef.current;
1119
- prevUserRef.current = user;
1120
- if (!prev && user) try {
1121
- client.identify(buildIdentifyPayload(user));
1122
- } catch (err) {
1123
- console.warn("[OpenPanel] Failed to identify user:", err);
1005
+ //#region src/utils/openUrl.ts
1006
+ const openBrowserUrl = (url) => window.open(url, "_blank");
1007
+ const openUrl = openBrowserUrl;
1008
+ //#endregion
1009
+ //#region src/utils/pglite-migration.ts
1010
+ const BACKUP_PREFIX = "ph-pglite-backup::";
1011
+ const BACKUP_INDEX_KEY = "ph:pglite-backups";
1012
+ const BACKUP_RETENTION_MS = 2592e6;
1013
+ function deleteIdb(name, timeoutMs = 15e3) {
1014
+ return new Promise((resolve, reject) => {
1015
+ const req = indexedDB.deleteDatabase(name);
1016
+ let settled = false;
1017
+ const done = (fn) => {
1018
+ if (settled) return;
1019
+ settled = true;
1020
+ fn();
1021
+ };
1022
+ const timer = setTimeout(() => done(() => reject(/* @__PURE__ */ new Error(`IDB delete timed out for ${name} after ${timeoutMs}ms`))), timeoutMs);
1023
+ req.onsuccess = () => done(() => {
1024
+ clearTimeout(timer);
1025
+ resolve();
1026
+ });
1027
+ req.onerror = () => done(() => {
1028
+ clearTimeout(timer);
1029
+ reject(idbError(req, `IDB delete failed for ${name}`));
1030
+ });
1031
+ });
1032
+ }
1033
+ function readBackupIndex() {
1034
+ try {
1035
+ const raw = localStorage.getItem(BACKUP_INDEX_KEY);
1036
+ if (!raw) return [];
1037
+ const parsed = JSON.parse(raw);
1038
+ return Array.isArray(parsed) ? parsed : [];
1039
+ } catch {
1040
+ return [];
1041
+ }
1042
+ }
1043
+ function writeBackupIndex(records) {
1044
+ try {
1045
+ localStorage.setItem(BACKUP_INDEX_KEY, JSON.stringify(records));
1046
+ } catch {}
1047
+ }
1048
+ function registerBackup(rec) {
1049
+ writeBackupIndex([...readBackupIndex(), rec]);
1050
+ }
1051
+ function forgetBackup(name) {
1052
+ writeBackupIndex(readBackupIndex().filter((r) => r.name !== name));
1053
+ }
1054
+ async function janitor() {
1055
+ const cutoff = Date.now() - BACKUP_RETENTION_MS;
1056
+ const keep = [];
1057
+ for (const rec of readBackupIndex()) {
1058
+ if (rec.createdAt >= cutoff) {
1059
+ keep.push(rec);
1060
+ continue;
1124
1061
  }
1125
- else if (prev && !user) try {
1126
- client.clear();
1062
+ try {
1063
+ await deleteIdb(rec.name);
1127
1064
  } catch (err) {
1128
- console.warn("[OpenPanel] Failed to clear user:", err);
1065
+ console.warn(`Failed to delete expired pglite backup ${rec.name}`, err);
1066
+ keep.push(rec);
1129
1067
  }
1130
- }, [
1131
- client,
1132
- user,
1133
- enabled
1134
- ]);
1135
- return null;
1068
+ }
1069
+ writeBackupIndex(keep);
1136
1070
  }
1137
- //#endregion
1138
- //#region src/components/document-editor-container.tsx
1139
- function DocumentEditorContainer() {
1140
- const [selectedDocument] = useSelectedDocument();
1141
- const parentFolder = useNodeParentFolderById(selectedDocument.header.id);
1142
- useMemo(() => {
1143
- return async () => {};
1144
- }, []);
1145
- useCallback(() => {
1146
- setSelectedNode(parentFolder);
1147
- }, [parentFolder]);
1148
- return /* @__PURE__ */ jsx("div", {
1149
- id: "document-editor-container",
1150
- className: "flex-1",
1151
- "data-document-type": selectedDocument.header.documentType,
1152
- children: /* @__PURE__ */ jsx(DocumentEditor, { document: selectedDocument })
1153
- });
1071
+ function createPersistentBackup() {
1072
+ return {
1073
+ snapshot: async (idbName) => {
1074
+ const backupName = `${BACKUP_PREFIX}${idbName}::${(/* @__PURE__ */ new Date()).toISOString()}`;
1075
+ await cloneFileData(idbName, backupName);
1076
+ registerBackup({
1077
+ name: backupName,
1078
+ idbName,
1079
+ createdAt: Date.now()
1080
+ });
1081
+ return backupName;
1082
+ },
1083
+ rollback: async (handle, idbName, cause) => {
1084
+ const backupName = handle;
1085
+ try {
1086
+ await cloneFileData(backupName, idbName);
1087
+ } catch (rollbackErr) {
1088
+ console.error(`PGlite migration rollback failed for ${idbName}; backup ${backupName} retained. Primary migration error:`, cause, "Rollback error:", rollbackErr);
1089
+ return;
1090
+ }
1091
+ await deleteIdb(backupName).catch(() => void 0);
1092
+ forgetBackup(backupName);
1093
+ },
1094
+ discard: async (handle) => {
1095
+ const backupName = handle;
1096
+ await deleteIdb(backupName).catch(() => void 0);
1097
+ forgetBackup(backupName);
1098
+ },
1099
+ commit: () => Promise.resolve()
1100
+ };
1154
1101
  }
1155
- //#endregion
1156
- //#region src/components/editor-loader.tsx
1157
- function EditorLoader(props) {
1158
- const [showLoading, setShowLoading] = useState(false);
1159
- useEffect(() => {
1160
- setTimeout(() => {
1161
- setShowLoading(true);
1162
- }, props.loadingTimeout ?? 200);
1163
- }, [props]);
1164
- if (!showLoading) return null;
1165
- const { customEditorLoader, ...defaultProps } = props;
1166
- if (customEditorLoader) return /* @__PURE__ */ jsx(Fragment, { children: customEditorLoader });
1167
- return /* @__PURE__ */ jsx(DefaultEditorLoader, { ...defaultProps });
1102
+ async function migrateAllLocked() {
1103
+ const backup = createPersistentBackup();
1104
+ try {
1105
+ for (const idbName of PRIMARY_IDB_NAMES) await migrateIdb(idbName, (phase) => setMigrationStatus({
1106
+ idbName,
1107
+ phase
1108
+ }), backup);
1109
+ } finally {
1110
+ setMigrationStatus(null);
1111
+ }
1168
1112
  }
1169
- //#endregion
1170
- //#region src/components/app-container.tsx
1171
- function AppContainer() {
1172
- const [selectedDrive] = useSelectedDriveSafe();
1173
- const selectedDocumentId = useSelectedDocumentId();
1174
- const app = useAppModuleById(selectedDrive?.header.meta?.preferredEditor);
1175
- const defaultApp = useDefaultAppModule();
1176
- if (!selectedDrive) return /* @__PURE__ */ jsx(EditorLoader, {});
1177
- const AppComponent = app?.Component ?? defaultApp?.Component ?? GenericDriveExplorer.Component;
1178
- if (!AppComponent) throw new Error("No app component found");
1179
- return /* @__PURE__ */ jsx(ErrorBoundary$1, {
1180
- variant: "detailed",
1181
- resetKeys: [selectedDrive.header.id],
1182
- loggerContext: ["Connect", "App"],
1183
- children: /* @__PURE__ */ jsx(Suspense, {
1184
- fallback: /* @__PURE__ */ jsx(EditorLoader, {}),
1185
- children: /* @__PURE__ */ jsx(DropZoneWrapper, {
1186
- className: "flex h-full flex-col overflow-auto",
1187
- children: /* @__PURE__ */ jsx(AppComponent, { children: selectedDocumentId ? /* @__PURE__ */ jsx(DocumentEditorContainer, {}) : null })
1188
- })
1189
- })
1113
+ async function migrateAllIfNeeded() {
1114
+ janitor().catch((err) => console.warn("PGlite backup janitor failed", err));
1115
+ if (!(typeof navigator !== "undefined" && "locks" in navigator && typeof navigator.locks.request === "function")) {
1116
+ await migrateAllLocked();
1117
+ return;
1118
+ }
1119
+ await navigator.locks.request("ph-pglite-migration", { mode: "exclusive" }, async () => {
1120
+ await migrateAllLocked();
1190
1121
  });
1191
1122
  }
1192
1123
  //#endregion
1193
- //#region src/context/sentry-provider.tsx
1194
- const SentryProvider = ({ children }) => {
1195
- useInitSentry();
1196
- return children;
1197
- };
1198
- //#endregion
1199
1124
  //#region src/components/reactor-chat.tsx
1200
1125
  /**
1201
1126
  * Resolves the reactor tool descriptors for the chat agent from the
@@ -1401,11 +1326,12 @@ function PackageInstallPrompt() {
1401
1326
  const pendingInstallations = usePendingInstallations();
1402
1327
  const discoveryService = usePackageDiscoveryService();
1403
1328
  if (!discoveryService || pendingInstallations.length === 0) return null;
1329
+ const installations = pendingInstallations.flatMap((p) => p.packageNames.map((packageName) => ({
1330
+ documentType: p.documentType,
1331
+ packageName
1332
+ })));
1404
1333
  return /* @__PURE__ */ jsx(PackageInstallModal, {
1405
- pendingInstallations: pendingInstallations.flatMap((p) => p.packageNames.map((packageName) => ({
1406
- documentType: p.documentType,
1407
- packageName
1408
- }))),
1334
+ pendingInstallations: installations,
1409
1335
  onInstall: (packageName) => discoveryService.approveInstallation(packageName),
1410
1336
  onDismiss: (packageName) => discoveryService.dismissInstallation(packageName)
1411
1337
  });
@@ -1533,19 +1459,37 @@ const App = () => {
1533
1459
  ] }) });
1534
1460
  };
1535
1461
  //#endregion
1462
+ //#region src/components/dots-loader.tsx
1463
+ const DotsLoader = () => {
1464
+ const [dots, setDots] = useState(0);
1465
+ useEffect(() => {
1466
+ const id = setInterval(() => {
1467
+ setDots((dots) => dots === 3 ? 0 : dots + 1);
1468
+ }, 200);
1469
+ return () => {
1470
+ clearInterval(id);
1471
+ };
1472
+ }, []);
1473
+ return /* @__PURE__ */ jsx("span", { children: new Array(dots).fill(".").join("") });
1474
+ };
1475
+ //#endregion
1536
1476
  //#region src/components/drive-icon.tsx
1537
1477
  function DriveIcon({ drive }) {
1538
1478
  const remotes = useSyncList();
1479
+ const { theme } = useTheme();
1539
1480
  const isRemoteDrive = useMemo(() => {
1540
1481
  if (!drive) return false;
1541
1482
  return remotes.some((remote) => remote.meta.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)));
1542
1483
  }, [remotes, drive]);
1543
1484
  const driveIconSrc = drive?.state.global.icon;
1544
- if (driveIconSrc) return /* @__PURE__ */ jsx("img", {
1485
+ const [failedSrc, setFailedSrc] = useState(null);
1486
+ if (driveIconSrc && driveIconSrc !== failedSrc) return /* @__PURE__ */ jsx("img", {
1545
1487
  src: driveIconSrc,
1546
1488
  alt: drive.header.name,
1547
1489
  height: 32,
1548
- width: 32
1490
+ width: 32,
1491
+ style: { colorScheme: theme },
1492
+ onError: () => setFailedSrc(driveIconSrc)
1549
1493
  });
1550
1494
  if (!isRemoteDrive) return /* @__PURE__ */ jsx(Icon, {
1551
1495
  name: "Hdd",
@@ -1597,6 +1541,9 @@ function EditorError({ title, children }) {
1597
1541
  })
1598
1542
  });
1599
1543
  }
1544
+ function defaultScope(scopes) {
1545
+ return scopes.includes("global") ? "global" : scopes[0];
1546
+ }
1600
1547
  function OpenPackageManagerButton() {
1601
1548
  return /* @__PURE__ */ jsx(PowerhouseButton, {
1602
1549
  className: "px-3 py-1.5 text-base font-medium",
@@ -1616,10 +1563,30 @@ const DocumentEditor = (props) => {
1616
1563
  const documentName = document?.header.name ?? void 0;
1617
1564
  const documentType = document?.header.documentType ?? void 0;
1618
1565
  const preferredEditor = document?.header.meta?.preferredEditor ?? void 0;
1619
- const { globalOperations, localOperations, isLoading: isLoadingOperations, refetch: refetchOperations } = useDocumentOperations(documentId);
1566
+ const scopes = useMemo(() => {
1567
+ const keys = Object.keys(document?.header.revision ?? {});
1568
+ return keys.length > 0 ? keys : ["global"];
1569
+ }, [document?.header.revision]);
1570
+ const [operationScope, setOperationScope] = useState(() => defaultScope(scopes));
1571
+ const selectedScope = scopes.includes(operationScope) ? operationScope : defaultScope(scopes);
1572
+ const { operations: historyOperations, isLoading: isLoadingHistory, hasNextPage: historyHasNextPage, fetchNextPage: fetchNextHistoryPage, error: historyError } = useDocumentOperations(documentId, selectedScope, {
1573
+ enabled: revisionHistoryVisible,
1574
+ limit: 500
1575
+ });
1576
+ const { operations: globalOperations, hasNextPage: globalHasNextPage, isLoading: isLoadingGlobal, fetchNextPage: fetchNextGlobalPage, error: globalError } = useDocumentOperations(documentId, "global", {
1577
+ enabled: !!selectedTimelineItem,
1578
+ limit: 500
1579
+ });
1620
1580
  useEffect(() => {
1621
- if (revisionHistoryVisible) refetchOperations();
1622
- }, [revisionHistoryVisible, refetchOperations]);
1581
+ if (!globalHasNextPage || isLoadingGlobal || globalError) return;
1582
+ const handle = window.setTimeout(fetchNextGlobalPage, 0);
1583
+ return () => window.clearTimeout(handle);
1584
+ }, [
1585
+ globalHasNextPage,
1586
+ isLoadingGlobal,
1587
+ fetchNextGlobalPage,
1588
+ globalError
1589
+ ]);
1623
1590
  const globalRevisionNumber = document?.header.revision.global ?? 0;
1624
1591
  const localRevisionNumber = document?.header.revision.local ?? 0;
1625
1592
  const documentModelModule = useDocumentModelModuleById(documentType);
@@ -1725,11 +1692,17 @@ const DocumentEditor = (props) => {
1725
1692
  id: "document-editor-context",
1726
1693
  "data-editor": editorModule.config.id,
1727
1694
  "data-document-type": documentType,
1728
- children: revisionHistoryVisible ? isLoadingOperations ? /* @__PURE__ */ jsx(EditorLoader, { message: "Loading operations" }) : /* @__PURE__ */ jsx(RevisionHistory, {
1695
+ children: revisionHistoryVisible ? /* @__PURE__ */ jsx(RevisionHistory, {
1729
1696
  documentTitle: documentName ?? "",
1730
1697
  documentId: documentId ?? "",
1731
- globalOperations,
1732
- localOperations,
1698
+ operations: historyOperations,
1699
+ isLoading: isLoadingHistory,
1700
+ hasNextPage: historyHasNextPage,
1701
+ onLoadNextPage: fetchNextHistoryPage,
1702
+ error: historyError,
1703
+ scopes,
1704
+ scope: selectedScope,
1705
+ onScopeChange: setOperationScope,
1733
1706
  onClose: () => setRevisionHistoryVisible(false),
1734
1707
  documentState: document.state,
1735
1708
  onCopyState: () => {
@@ -1749,7 +1722,7 @@ const DocumentEditor = (props) => {
1749
1722
  children: !editorError?.error && /* @__PURE__ */ jsx(EditorComponent, {
1750
1723
  context: {
1751
1724
  readMode: !!selectedTimelineItem,
1752
- selectedTimelineRevision: getRevisionFromDate(selectedTimelineItem?.startDate, selectedTimelineItem?.endDate, globalOperations)
1725
+ selectedTimelineRevision: (isLoadingGlobal || globalHasNextPage) && !globalError ? void 0 : getRevisionFromDate(selectedTimelineItem?.startDate, selectedTimelineItem?.endDate, globalOperations)
1753
1726
  },
1754
1727
  documentId: document.header.id
1755
1728
  }, `${editorBundleKey}:${documentId}`)
@@ -1758,8 +1731,37 @@ const DocumentEditor = (props) => {
1758
1731
  });
1759
1732
  };
1760
1733
  //#endregion
1734
+ //#region src/components/footer.tsx
1735
+ const Footer$1 = () => {
1736
+ return /* @__PURE__ */ jsxs(Footer, { children: [
1737
+ /* @__PURE__ */ jsx(FooterLink, {
1738
+ onClick: () => setBannerShown(true),
1739
+ children: /* @__PURE__ */ jsx(Trans, { i18nKey: "footer.cookiePolicy" })
1740
+ }),
1741
+ /* @__PURE__ */ jsx(FooterLink, {
1742
+ onClick: () => showPHModal({ type: "disclaimer" }),
1743
+ children: /* @__PURE__ */ jsx(Trans, { i18nKey: "footer.disclaimer" })
1744
+ }),
1745
+ /* @__PURE__ */ jsx(FooterLink, {
1746
+ id: "ph-logo-link",
1747
+ onClick: () => openUrl("https://www.powerhouse.inc/"),
1748
+ children: /* @__PURE__ */ jsx(Trans, {
1749
+ i18nKey: "footer.builtWith",
1750
+ components: { icon: /* @__PURE__ */ jsx(Icon, {
1751
+ name: "PowerhouseLogoSmall",
1752
+ size: 16,
1753
+ className: "mx-1"
1754
+ }) }
1755
+ })
1756
+ })
1757
+ ] });
1758
+ };
1759
+ //#endregion
1761
1760
  //#region src/components/root.tsx
1761
+ /** The generic shell's module id; the sidebar is its most visible surface. */
1762
+ const GENERIC_PLUGIN = "@powerhousedao/connect/plugins/generic";
1762
1763
  function Root() {
1764
+ const isEmbedded = useIsEmbedded();
1763
1765
  return /* @__PURE__ */ jsx("div", {
1764
1766
  className: "h-screen bg-background",
1765
1767
  children: /* @__PURE__ */ jsx("div", {
@@ -1768,7 +1770,10 @@ function Root() {
1768
1770
  tabIndex: 0,
1769
1771
  children: /* @__PURE__ */ jsxs(Suspense, {
1770
1772
  name: "Root",
1771
- children: [!useIsEmbedded() && /* @__PURE__ */ jsx(Sidebar, {}), /* @__PURE__ */ jsx("div", {
1773
+ children: [!isEmbedded && /* @__PURE__ */ jsx(IfPlugin, {
1774
+ module: GENERIC_PLUGIN,
1775
+ children: /* @__PURE__ */ jsx(Sidebar, {})
1776
+ }), /* @__PURE__ */ jsx("div", {
1772
1777
  className: "relative flex-1 overflow-auto",
1773
1778
  children: /* @__PURE__ */ jsx(Outlet, {})
1774
1779
  })]
@@ -1888,7 +1893,10 @@ function Content() {
1888
1893
  onLogout: () => void logout(),
1889
1894
  onClose: dismiss
1890
1895
  })
1891
- }) : !selectedDocumentId && !selectedDrive && !selectedFolder ? /* @__PURE__ */ jsx(HomeScreenContainer, {}) : /* @__PURE__ */ jsx(AppContainer, {}) });
1896
+ }) : !selectedDocumentId && !selectedDrive && !selectedFolder ? /* @__PURE__ */ jsx(IfPlugin, {
1897
+ module: "@powerhousedao/connect/plugins/generic",
1898
+ children: /* @__PURE__ */ jsx(HomeScreenContainer, {})
1899
+ }) : /* @__PURE__ */ jsx(AppContainer, {}) });
1892
1900
  }
1893
1901
  function ContentContainer({ children }) {
1894
1902
  return /* @__PURE__ */ jsx("div", {
@@ -1950,6 +1958,64 @@ const Router = () => {
1950
1958
  return /* @__PURE__ */ jsx(RouterProvider, { router });
1951
1959
  };
1952
1960
  //#endregion
1961
+ //#region src/components/search-bar.tsx
1962
+ const defaultFilterItems = [
1963
+ {
1964
+ id: "project",
1965
+ label: ".project",
1966
+ icon: /* @__PURE__ */ jsx(Icon, {
1967
+ name: "Project",
1968
+ color: "#FF6A55",
1969
+ size: 16
1970
+ })
1971
+ },
1972
+ {
1973
+ id: "budget",
1974
+ label: ".budget",
1975
+ icon: /* @__PURE__ */ jsx(Icon, {
1976
+ name: "BarChart",
1977
+ color: "#8E55EA",
1978
+ size: 16
1979
+ })
1980
+ },
1981
+ {
1982
+ id: "profile",
1983
+ label: ".profile",
1984
+ icon: /* @__PURE__ */ jsx(Icon, {
1985
+ name: "Person",
1986
+ color: "#3E90F0",
1987
+ size: 16
1988
+ })
1989
+ },
1990
+ {
1991
+ id: "legal",
1992
+ label: ".legal",
1993
+ icon: /* @__PURE__ */ jsx(Icon, {
1994
+ name: "Briefcase",
1995
+ color: "#4BAB71",
1996
+ size: 16
1997
+ })
1998
+ },
1999
+ {
2000
+ id: "atlas",
2001
+ label: ".Atlas",
2002
+ icon: /* @__PURE__ */ jsx(Icon, {
2003
+ name: "Globe",
2004
+ color: "#FF8A00",
2005
+ size: 16
2006
+ })
2007
+ }
2008
+ ];
2009
+ const SearchBar = () => {
2010
+ const { t } = useTranslation();
2011
+ return /* @__PURE__ */ jsx(ConnectSearchBar, {
2012
+ className: "m-4 shrink-0 bg-muted",
2013
+ placeholder: t("searchbar.placeholder"),
2014
+ filterLabel: t("searchbar.filterLabel"),
2015
+ filterItems: defaultFilterItems
2016
+ });
2017
+ };
2018
+ //#endregion
1953
2019
  //#region src/components/sidebar.tsx
1954
2020
  function Sidebar() {
1955
2021
  const user = useUser();
@@ -1998,27 +2064,60 @@ function Sidebar() {
1998
2064
  //#endregion
1999
2065
  //#region src/components/connection-banner.tsx
2000
2066
  const CONNECTED = "connected";
2067
+ const BANNER_TEXT = {
2068
+ failed: {
2069
+ title: "Reactor worker failed to load",
2070
+ detail: "The background worker script could not be loaded. Reload to retry."
2071
+ },
2072
+ lost: {
2073
+ title: "Lost connection to the reactor",
2074
+ detail: "The background worker stopped responding. Reload to reconnect."
2075
+ },
2076
+ "storage-held": {
2077
+ title: "Waiting for another Connect tab",
2078
+ detail: "Another Connect tab still holds local storage. Close or reload the other Connect tabs to continue."
2079
+ },
2080
+ "version-conflict": {
2081
+ title: "Connect tabs are on different builds",
2082
+ detail: "Open tabs keep restarting the reactor. Close the other Connect tabs, then reload."
2083
+ },
2084
+ "storage-unusable": {
2085
+ title: "Local storage is unusable",
2086
+ detail: "The local database stopped responding. Clear storage to start over, or reload to retry."
2087
+ }
2088
+ };
2001
2089
  const ConnectionBanner = () => {
2002
- if (useSyncExternalStore(subscribeWorkerConnection, getWorkerConnectionStatus, () => CONNECTED) !== "lost") return null;
2090
+ const status = useSyncExternalStore(subscribeWorkerConnection, getWorkerConnectionStatus, () => CONNECTED);
2091
+ if (status === "connected") return null;
2092
+ const { title, detail } = BANNER_TEXT[status];
2003
2093
  return /* @__PURE__ */ jsx("div", {
2004
2094
  className: "absolute inset-x-0 top-0 z-30 flex justify-center p-3",
2005
2095
  children: /* @__PURE__ */ jsxs("div", {
2006
2096
  className: "flex max-w-3xl items-center gap-3 rounded-lg border border-destructive bg-warning px-4 py-3 text-sm text-warning-foreground shadow-lg",
2007
- children: [/* @__PURE__ */ jsxs("div", {
2008
- className: "flex-1",
2009
- children: [/* @__PURE__ */ jsx("div", {
2010
- className: "font-semibold",
2011
- children: "Lost connection to the reactor"
2012
- }), /* @__PURE__ */ jsx("div", {
2013
- className: "text-foreground",
2014
- children: "The background worker stopped responding. Reload to reconnect."
2015
- })]
2016
- }), /* @__PURE__ */ jsx("button", {
2017
- type: "button",
2018
- onClick: () => window.location.reload(),
2019
- className: "rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect",
2020
- children: "Reload"
2021
- })]
2097
+ children: [
2098
+ /* @__PURE__ */ jsxs("div", {
2099
+ className: "flex-1",
2100
+ children: [/* @__PURE__ */ jsx("div", {
2101
+ className: "font-semibold",
2102
+ children: title
2103
+ }), /* @__PURE__ */ jsx("div", {
2104
+ className: "text-foreground",
2105
+ children: detail
2106
+ })]
2107
+ }),
2108
+ status === "storage-unusable" && /* @__PURE__ */ jsx("button", {
2109
+ type: "button",
2110
+ onClick: () => showPHModal({ type: "clearStorage" }),
2111
+ className: "rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect",
2112
+ children: "Clear storage"
2113
+ }),
2114
+ /* @__PURE__ */ jsx("button", {
2115
+ type: "button",
2116
+ onClick: () => window.location.reload(),
2117
+ className: "rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect",
2118
+ children: "Reload"
2119
+ })
2120
+ ]
2022
2121
  })
2023
2122
  });
2024
2123
  };
@@ -2130,20 +2229,20 @@ const MigrationBanner = () => {
2130
2229
  };
2131
2230
  //#endregion
2132
2231
  //#region src/components/modal/modals-container.tsx
2133
- const AddDriveModal$1 = lazy(() => import("./AddDriveModal-xAw48kdl.js").then((m) => ({ default: m.AddDriveModal })));
2134
- const ClearStorageModal = lazy(() => import("./ClearStorageModal-B9bF7a7q.js").then((m) => ({ default: m.ClearStorageModal })));
2135
- const CookiesPolicyModal = lazy(() => import("./CookiesPolicyModal-BpyPPyxS.js").then((m) => ({ default: m.CookiesPolicyModal })));
2136
- const CreateDocumentModal$1 = lazy(() => import("./CreateDocumentModal-C45W8J0V.js").then((m) => ({ default: m.CreateDocumentModal })));
2137
- const DebugSettingsModal = lazy(() => import("./DebugSettingsModal-C6kwYM5N.js").then((m) => ({ default: m.DebugSettingsModal })));
2138
- const DeleteDriveModal = lazy(() => import("./DeleteDriveModal-Dug84t1j.js").then((m) => ({ default: m.DeleteDriveModal })));
2139
- const DeleteItemModal = lazy(() => import("./DeleteItemModal-mMzy3V8o.js").then((m) => ({ default: m.DeleteItemModal })));
2140
- const DisclaimerModal = lazy(() => import("./DisclaimerModal-DvpD5dPM.js").then((m) => ({ default: m.DisclaimerModal })));
2141
- const DriveSettingsModal$1 = lazy(() => import("./DriveSettingsModal-C6-mRQiv.js").then((m) => ({ default: m.DriveSettingsModal })));
2142
- const DownloadDocumentWithErrorsModal = lazy(() => import("./DownloadDocumentWithErrorsModal-IKl0ljQb.js").then((m) => ({ default: m.DownloadDocumentWithErrorsModal })));
2143
- const DocumentVersionUnsupportedModal = lazy(() => import("./DocumentVersionUnsupportedModal-C3Q0V75l.js").then((m) => ({ default: m.DocumentVersionUnsupportedModal })));
2144
- const ConfirmDocumentUpgradeModal = lazy(() => import("./ConfirmDocumentUpgradeModal-FUOhZsk7.js").then((m) => ({ default: m.ConfirmDocumentUpgradeModal })));
2145
- const SettingsModal$1 = lazy(() => import("./SettingsModal-BY2USww8.js").then((m) => ({ default: m.SettingsModal })));
2146
- const UpgradeDriveModal = lazy(() => import("./UpgradeDriveModal-_8t9slxQ.js").then((m) => ({ default: m.UpgradeDriveModal })));
2232
+ const AddDriveModal$1 = lazy(() => import("./AddDriveModal-C5odBO8y.js").then((m) => ({ default: m.AddDriveModal })));
2233
+ const ClearStorageModal = lazy(() => import("./ClearStorageModal-DE2TKUfn.js").then((m) => ({ default: m.ClearStorageModal })));
2234
+ const CookiesPolicyModal = lazy(() => import("./CookiesPolicyModal-BLw4pnhn.js").then((m) => ({ default: m.CookiesPolicyModal })));
2235
+ const CreateDocumentModal$1 = lazy(() => import("./CreateDocumentModal-Bmv0V-kY.js").then((m) => ({ default: m.CreateDocumentModal })));
2236
+ const DebugSettingsModal = lazy(() => import("./DebugSettingsModal-BYrr41NU.js").then((m) => ({ default: m.DebugSettingsModal })));
2237
+ const DeleteDriveModal = lazy(() => import("./DeleteDriveModal-CjGnG0ht.js").then((m) => ({ default: m.DeleteDriveModal })));
2238
+ const DeleteItemModal = lazy(() => import("./DeleteItemModal-BbY_4_xT.js").then((m) => ({ default: m.DeleteItemModal })));
2239
+ const DisclaimerModal = lazy(() => import("./DisclaimerModal-DuglmEwL.js").then((m) => ({ default: m.DisclaimerModal })));
2240
+ const DriveSettingsModal$1 = lazy(() => import("./DriveSettingsModal-d1L0eYof.js").then((m) => ({ default: m.DriveSettingsModal })));
2241
+ const DownloadDocumentWithErrorsModal = lazy(() => import("./DownloadDocumentWithErrorsModal-BsPQ5qgy.js").then((m) => ({ default: m.DownloadDocumentWithErrorsModal })));
2242
+ const DocumentVersionUnsupportedModal = lazy(() => import("./DocumentVersionUnsupportedModal-C4fy7fZ6.js").then((m) => ({ default: m.DocumentVersionUnsupportedModal })));
2243
+ const ConfirmDocumentUpgradeModal = lazy(() => import("./ConfirmDocumentUpgradeModal-k79v2wM6.js").then((m) => ({ default: m.ConfirmDocumentUpgradeModal })));
2244
+ const SettingsModal$1 = lazy(() => import("./SettingsModal-_hk8S-ey.js").then((m) => ({ default: m.SettingsModal })));
2245
+ const UpgradeDriveModal = lazy(() => import("./UpgradeDriveModal-CXX6D5Au.js").then((m) => ({ default: m.UpgradeDriveModal })));
2147
2246
  const modalComponents = {
2148
2247
  addDrive: AddDriveModal$1,
2149
2248
  clearStorage: ClearStorageModal,
@@ -2157,13 +2256,13 @@ const modalComponents = {
2157
2256
  downloadDocumentWithErrors: DownloadDocumentWithErrorsModal,
2158
2257
  documentVersionUnsupported: DocumentVersionUnsupportedModal,
2159
2258
  confirmDocumentUpgrade: ConfirmDocumentUpgradeModal,
2160
- inspector: lazy(() => import("./InspectorModal-BDLUQ91R.js").then((m) => ({ default: m.InspectorModal }))),
2259
+ inspector: lazy(() => import("./InspectorModal-CpqAS_PY.js").then((m) => ({ default: m.InspectorModal }))),
2161
2260
  settings: SettingsModal$1,
2162
2261
  upgradeDrive: UpgradeDriveModal,
2163
- missingPackage: lazy(() => import("./MissingPackageModal-nBnExqO0.js").then((m) => ({ default: m.ConnectMissingPackageModal }))),
2164
- driveAuthRequired: lazy(() => import("./DriveAuthRequiredModal-DVK7ZQzO.js").then((m) => ({ default: m.DriveAuthRequiredModal }))),
2165
- openFileDocuments: lazy(() => import("./OpenFileDocumentsModal-OPmSKJ4w.js").then((m) => ({ default: m.OpenFileDocumentsModal }))),
2166
- login: lazy(() => import("./LoginModal-CybbOm3N.js").then((m) => ({ default: m.LoginModal })))
2262
+ missingPackage: lazy(() => import("./MissingPackageModal-DS3dgJ1K.js").then((m) => ({ default: m.ConnectMissingPackageModal }))),
2263
+ driveAuthRequired: lazy(() => import("./DriveAuthRequiredModal-CtsB0kwH.js").then((m) => ({ default: m.DriveAuthRequiredModal }))),
2264
+ openFileDocuments: lazy(() => import("./OpenFileDocumentsModal-C9vyTb6I.js").then((m) => ({ default: m.OpenFileDocumentsModal }))),
2265
+ login: lazy(() => import("./LoginModal-CI0ogC2-.js").then((m) => ({ default: m.LoginModal })))
2167
2266
  };
2168
2267
  const ModalsContainer = lazy(() => {
2169
2268
  return Promise.resolve({ default: () => {
@@ -2201,12 +2300,48 @@ const ServiceWorkerUpdatePrompt = () => {
2201
2300
  });
2202
2301
  };
2203
2302
  //#endregion
2303
+ //#region src/components/stored-documents-refused.tsx
2304
+ /** Boot screen for a reactor that refused this browser's stored documents. */
2305
+ function StoredDocumentsRefusedFallback({ error }) {
2306
+ return /* @__PURE__ */ jsx("div", {
2307
+ className: "z-10 mx-auto flex max-w-[80%] flex-1 items-center justify-center p-6",
2308
+ children: /* @__PURE__ */ jsxs("div", {
2309
+ role: "alert",
2310
+ className: "w-full max-w-lg rounded-lg border border-border bg-card p-6 text-foreground shadow-sm",
2311
+ children: [
2312
+ /* @__PURE__ */ jsxs("div", {
2313
+ className: "mb-3 flex items-center gap-2",
2314
+ children: [/* @__PURE__ */ jsx(Icon, {
2315
+ name: "Error",
2316
+ className: "size-5 shrink-0 text-destructive"
2317
+ }), /* @__PURE__ */ jsx("h1", {
2318
+ className: "text-lg font-semibold text-foreground",
2319
+ children: "Connect cannot open this browser's documents"
2320
+ })]
2321
+ }),
2322
+ /* @__PURE__ */ jsx("p", {
2323
+ className: "mb-4 text-sm wrap-break-word text-foreground",
2324
+ children: error.message
2325
+ }),
2326
+ /* @__PURE__ */ jsx(PowerhouseButton, {
2327
+ type: "button",
2328
+ onClick: () => {
2329
+ window.location.reload();
2330
+ },
2331
+ className: "px-3 py-1.5 text-base font-medium",
2332
+ children: "Reload"
2333
+ })
2334
+ ]
2335
+ })
2336
+ });
2337
+ }
2338
+ //#endregion
2204
2339
  //#region src/components/app-loader.tsx
2205
- const CookieBanner$1 = lazy(() => import("./cookie-banner-BH6bIq24.js").then((m) => ({ default: m.CookieBanner })));
2340
+ const CookieBanner$1 = lazy(() => import("./cookie-banner-D05DZRqY.js").then((m) => ({ default: m.CookieBanner })));
2206
2341
  const AppLoader = (props) => {
2207
- const Load = lazy(() => import("./load-VdwMO26x.js").then((m) => m.loadComponent(props.localPackage)));
2342
+ const Load = lazy(() => import("./load-BO0qVu72.js").then((m) => m.loadComponent(props.localPackage)));
2208
2343
  return /* @__PURE__ */ jsx(StrictMode, { children: /* @__PURE__ */ jsxs(ErrorBoundary$1, {
2209
- fallbackRender: (props) => /* @__PURE__ */ jsx(AppSkeleton, { children: /* @__PURE__ */ jsx(DetailedFallback, { ...props }) }),
2344
+ fallbackRender: (props) => /* @__PURE__ */ jsx(AppSkeleton, { children: isStoredDocumentsRefused(props.error) ? /* @__PURE__ */ jsx(StoredDocumentsRefusedFallback, { error: props.error }) : /* @__PURE__ */ jsx(DetailedFallback, { ...props }) }),
2210
2345
  resetKeys: [props.localPackage],
2211
2346
  loggerContext: ["Connect"],
2212
2347
  children: [
@@ -2238,7 +2373,7 @@ const AppLoader = (props) => {
2238
2373
  }) });
2239
2374
  };
2240
2375
  //#endregion
2241
- export { pendingFileKey as _, DocumentEditor as a, AppContainer as c, OpenPanel as d, Analytics as f, getPendingImportFiles as g, clearPendingImportFiles as h, Root as i, EditorLoader as l, runOpenFileImports as m, Sidebar as n, DriveIcon as o, AppSkeleton as p, Router as r, App as s, AppLoader as t, DocumentEditorContainer as u, subscribePendingImportFiles as v };
2376
+ export { EditorLoader as _, Root as a, IfPlugin as b, DriveIcon as c, runOpenFileImports as d, clearPendingImportFiles as f, AppContainer as g, subscribePendingImportFiles as h, Router as i, DotsLoader as l, pendingFileKey as m, Sidebar as n, Footer$1 as o, getPendingImportFiles as p, SearchBar as r, DocumentEditor as s, AppLoader as t, App as u, DocumentEditorContainer as v, Analytics as x, OpenPanel as y };
2242
2377
 
2243
- //# sourceMappingURL=app-loader-CgBHl_w5.js.map
2244
- //# debugId=e39d56db-24be-5b7a-9426-5cc7cfc525d3
2378
+ //# sourceMappingURL=app-loader-C_y2O5-k.js.map
2379
+ //# debugId=8a3a3353-4e2f-5ff5-b61c-ae9890df9cec