@powerhousedao/connect 6.2.3 → 6.3.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -1
- package/dist/{AddDriveModal-DhNfP94R.js → AddDriveModal-zMepHdWt.js} +43 -17
- package/dist/AddDriveModal-zMepHdWt.js.map +1 -0
- package/dist/{ClearStorageModal-DyU-FIgY.js → ClearStorageModal-Br-y7qXc.js} +10 -12
- package/dist/ClearStorageModal-Br-y7qXc.js.map +1 -0
- package/dist/{ConfirmDocumentUpgradeModal-DcOZy20m.js → ConfirmDocumentUpgradeModal-CoixS60F.js} +4 -4
- package/dist/ConfirmDocumentUpgradeModal-CoixS60F.js.map +1 -0
- package/dist/{CookiesPolicyModal-BLw4pnhn.js → CookiesPolicyModal-BpFjYc7T.js} +4 -4
- package/dist/{CookiesPolicyModal-BLw4pnhn.js.map → CookiesPolicyModal-BpFjYc7T.js.map} +1 -1
- package/dist/CreateDocumentModal-CiIW3pzx.js +45 -0
- package/dist/CreateDocumentModal-CiIW3pzx.js.map +1 -0
- package/dist/{DebugSettingsModal-CwUN9gIr.js → DebugSettingsModal-FALLjVVv.js} +10 -10
- package/dist/DebugSettingsModal-FALLjVVv.js.map +1 -0
- package/dist/{DeleteDriveModal-CjGnG0ht.js → DeleteDriveModal-1pAIayG_.js} +5 -5
- package/dist/DeleteDriveModal-1pAIayG_.js.map +1 -0
- package/dist/{DeleteItemModal-BbY_4_xT.js → DeleteItemModal-BUpqmFxS.js} +6 -6
- package/dist/DeleteItemModal-BUpqmFxS.js.map +1 -0
- package/dist/{DisclaimerModal-DuglmEwL.js → DisclaimerModal-TIJXRYLF.js} +6 -6
- package/dist/DisclaimerModal-TIJXRYLF.js.map +1 -0
- package/dist/{DocumentVersionUnsupportedModal-C4fy7fZ6.js → DocumentVersionUnsupportedModal-DH9Zzsyw.js} +6 -6
- package/dist/DocumentVersionUnsupportedModal-DH9Zzsyw.js.map +1 -0
- package/dist/{DownloadDocumentWithErrorsModal-BsPQ5qgy.js → DownloadDocumentWithErrorsModal-Beh-xw8B.js} +5 -5
- package/dist/DownloadDocumentWithErrorsModal-Beh-xw8B.js.map +1 -0
- package/dist/{DriveAuthRequiredModal-CtsB0kwH.js → DriveAuthRequiredModal-XTcoJKvj.js} +6 -6
- package/dist/DriveAuthRequiredModal-XTcoJKvj.js.map +1 -0
- package/dist/DriveSettingsModal-CGZQhzBa.js +127 -0
- package/dist/DriveSettingsModal-CGZQhzBa.js.map +1 -0
- package/dist/FloatingTanStackRouterDevtools-CqogiFob-dxj8lrTP.js +2565 -0
- package/dist/FloatingTanStackRouterDevtools-CqogiFob-dxj8lrTP.js.map +1 -0
- package/dist/{InspectorModal-Cd8kbCV8.js → InspectorModal-xU_gCAhG.js} +20 -20
- package/dist/InspectorModal-xU_gCAhG.js.map +1 -0
- package/dist/{LoginModal-CI0ogC2-.js → LoginModal-O06ZvWFI.js} +7 -7
- package/dist/LoginModal-O06ZvWFI.js.map +1 -0
- package/dist/{OpenFileDocumentsModal-BQsaBP4x.js → OpenFileDocumentsModal-DJsC1oR1.js} +19 -14
- package/dist/OpenFileDocumentsModal-DJsC1oR1.js.map +1 -0
- package/dist/{UpgradeDriveModal-CXX6D5Au.js → UpgradeDriveModal-CCWKp5yn.js} +6 -6
- package/dist/UpgradeDriveModal-CCWKp5yn.js.map +1 -0
- package/dist/ai-tools-BGUMFEMV.js +42 -0
- package/dist/ai-tools-BGUMFEMV.js.map +1 -0
- package/dist/ai-tools-D_q-Whju.js +4 -0
- package/dist/app-loader-BQrucpDg.js +4 -0
- package/dist/app-loader-orww5vEA.js +1254 -0
- package/dist/app-loader-orww5vEA.js.map +1 -0
- package/dist/{app-skeleton--Me5zlSz.js → app-skeleton-CMUP2zaz.js} +36 -16
- package/dist/app-skeleton-CMUP2zaz.js.map +1 -0
- package/dist/app-skeleton-CdD1m8G3.js +4 -0
- package/dist/{boot-DPNEOI2A.js → boot-BBIArGAP.js} +32 -9
- package/dist/boot-BBIArGAP.js.map +1 -0
- package/dist/{build-info-BV8UtyA4.js → build-info-BTuoWZYI.js} +10 -6
- package/dist/build-info-BTuoWZYI.js.map +1 -0
- package/dist/components-B3kuhyeE.js +121 -0
- package/dist/components-B3kuhyeE.js.map +1 -0
- package/dist/{connect.config-CaXMoB42.js → connect.config-DL9nKtlW.js} +8 -7
- package/dist/connect.config-DL9nKtlW.js.map +1 -0
- package/dist/{connection-state-Eqc2izmt.js → connection-state-0ippUGEC.js} +28 -12
- package/dist/connection-state-0ippUGEC.js.map +1 -0
- package/dist/context-De2EB1AA-Ni0d829Q.js +1759 -0
- package/dist/context-De2EB1AA-Ni0d829Q.js.map +1 -0
- package/dist/{cookie-banner-BxXvPdIY.js → cookie-banner-NclLYtB0.js} +6 -6
- package/dist/{cookie-banner-BxXvPdIY.js.map → cookie-banner-NclLYtB0.js.map} +1 -1
- package/dist/document-editor-container-C91BsZkt.js +4 -0
- package/dist/document-editor-container-Dkk87_q1.js +311 -0
- package/dist/document-editor-container-Dkk87_q1.js.map +1 -0
- package/dist/drive-icon-BIpd8edR.js +49 -0
- package/dist/drive-icon-BIpd8edR.js.map +1 -0
- package/dist/drive-placements-DjeVpTTm.js +38 -0
- package/dist/drive-placements-DjeVpTTm.js.map +1 -0
- package/dist/error-boundary-BsUBww61.js +155 -0
- package/dist/error-boundary-BsUBww61.js.map +1 -0
- package/dist/esm-BDACZntJ.js +148 -0
- package/dist/esm-BDACZntJ.js.map +1 -0
- package/dist/generic.d.ts +140 -0
- package/dist/generic.d.ts.map +1 -0
- package/dist/generic.js +31 -0
- package/dist/generic.js.map +1 -0
- package/dist/{i18n-CTgT1HG-.js → i18n-D9WYPgk9.js} +4 -4
- package/dist/{i18n-CTgT1HG-.js.map → i18n-D9WYPgk9.js.map} +1 -1
- package/dist/index-D7c2WAbn.d.ts +4 -0
- package/dist/layout-Dj3_KscE.js +5 -0
- package/dist/layout.d.ts +3 -0
- package/dist/layout.js +4 -0
- package/dist/{load-ftpCX1HI.js → load-C0hy-vOY.js} +48 -48
- package/dist/load-C0hy-vOY.js.map +1 -0
- package/dist/load-runtime-config-BoDzcgEV.js +14 -0
- package/dist/load-runtime-config-BoDzcgEV.js.map +1 -0
- package/dist/main.js +2 -2
- package/dist/open-file-uploads-B5pr1sA2.js +183 -0
- package/dist/open-file-uploads-B5pr1sA2.js.map +1 -0
- package/dist/{package-manager-BbzIV9aN.js → package-manager-B1Nxbull.js} +96 -31
- package/dist/package-manager-B1Nxbull.js.map +1 -0
- package/dist/{pglite-major-p4_YefAE.js → pglite-major-pao-ozRo.js} +5 -5
- package/dist/pglite-major-pao-ozRo.js.map +1 -0
- package/dist/{pglite-migrate-core-BcXcImng.js → pglite-migrate-core-B6FqmhH8.js} +5 -5
- package/dist/pglite-migrate-core-B6FqmhH8.js.map +1 -0
- package/dist/{pglite-seed-Cl2d-iyl.js → pglite-seed-CZsMNsV8.js} +8 -4
- package/dist/pglite-seed-CZsMNsV8.js.map +1 -0
- package/dist/plugin-configs.d.ts +242 -0
- package/dist/plugin-configs.d.ts.map +1 -0
- package/dist/plugin-configs.js +26 -0
- package/dist/plugin-configs.js.map +1 -0
- package/dist/plugins--mJeXJ7w.js +264 -0
- package/dist/plugins--mJeXJ7w.js.map +1 -0
- package/dist/{preferences-store-DZUIAkHE.js → preferences-store-DxYAnGCc.js} +5 -5
- package/dist/preferences-store-DxYAnGCc.js.map +1 -0
- package/dist/prerender.d.ts +38 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +195 -0
- package/dist/prerender.js.map +1 -0
- package/dist/prerendered-shell-peKE7AqI.js +51 -0
- package/dist/prerendered-shell-peKE7AqI.js.map +1 -0
- package/dist/{pwa-manifest-link-DQRJpF0r.js → pwa-manifest-link-DNwWvnLV.js} +5 -5
- package/dist/{pwa-manifest-link-DQRJpF0r.js.map → pwa-manifest-link-DNwWvnLV.js.map} +1 -1
- package/dist/reactor-Drpw-sgc.js +1656 -0
- package/dist/reactor-Drpw-sgc.js.map +1 -0
- package/dist/reactor-chat-C6yp2S37.js +15 -0
- package/dist/reactor-chat-C6yp2S37.js.map +1 -0
- package/dist/reactor.worker.js +444 -168
- package/dist/reactor.worker.js.map +1 -1
- package/dist/{registerServiceWorker-smkROQhm.js → registerServiceWorker-OR8nokAn.js} +5 -5
- package/dist/{registerServiceWorker-smkROQhm.js.map → registerServiceWorker-OR8nokAn.js.map} +1 -1
- package/dist/root-v9fj27sn.js +27 -0
- package/dist/root-v9fj27sn.js.map +1 -0
- package/dist/route-tree.d.ts +2220 -0
- package/dist/route-tree.d.ts.map +1 -0
- package/dist/route-tree.js +135 -0
- package/dist/route-tree.js.map +1 -0
- package/dist/route-views-BovMNHyn.js +60 -0
- package/dist/route-views-BovMNHyn.js.map +1 -0
- package/dist/route-views-C-H3ofJW.js +4 -0
- package/dist/route-views-DzgRMAx8.js +55 -0
- package/dist/route-views-DzgRMAx8.js.map +1 -0
- package/dist/route-views.d.ts +7 -0
- package/dist/route-views.d.ts.map +1 -0
- package/dist/route-views.js +4 -0
- package/dist/router-CWIsjETx.js +54 -0
- package/dist/router-CWIsjETx.js.map +1 -0
- package/dist/router-CnWkTEey.js +4 -0
- package/dist/router.d.ts +2 -0
- package/dist/router.js +3 -0
- package/dist/sentry-Cuc_Nbba.js +22 -0
- package/dist/sentry-Cuc_Nbba.js.map +1 -0
- package/dist/settings-C0o6eJvm.js +1089 -0
- package/dist/settings-C0o6eJvm.js.map +1 -0
- package/dist/settings-tabs-1V-sBOlj.js +424 -0
- package/dist/settings-tabs-1V-sBOlj.js.map +1 -0
- package/dist/shell-core-head.html +2 -0
- package/dist/shell-core.html +1 -0
- package/dist/shell-head.html +2 -0
- package/dist/shell-plugins.json +1 -0
- package/dist/shell.html +1 -0
- package/dist/start-connect.d.ts +5 -6
- package/dist/start-connect.d.ts.map +1 -1
- package/dist/start-connect.js +8 -5
- package/dist/start-connect.js.map +1 -1
- package/dist/store-lock-Bi3B9VJD.js +159 -0
- package/dist/store-lock-Bi3B9VJD.js.map +1 -0
- package/dist/style.css +3510 -3667
- package/dist/ui-BITvvqdH.js +66 -0
- package/dist/ui-BITvvqdH.js.map +1 -0
- package/dist/ui-C1-l-Eyh.js +170 -0
- package/dist/ui-C1-l-Eyh.js.map +1 -0
- package/dist/{use-renown-login-BzOSQETV.js → use-renown-login-dPpDOYq5.js} +4 -4
- package/dist/use-renown-login-dPpDOYq5.js.map +1 -0
- package/dist/workflows-C3qEvx1R.js +63 -0
- package/dist/workflows-C3qEvx1R.js.map +1 -0
- package/fonts.css +177 -0
- package/generic-routes.json +9 -0
- package/package.json +82 -21
- package/scripts/assert-plugin-configs.mjs +47 -0
- package/scripts/prerender-shell.ts +51 -0
- package/skills/customize-connect/SKILL.md +80 -0
- package/skills/customize-connect/references/data-and-navigation.md +315 -0
- package/skills/customize-connect/references/drive-apps.md +44 -0
- package/skills/customize-connect/references/hosts-and-plugins.md +88 -0
- package/skills/customize-connect/references/layout.md +162 -0
- package/skills/customize-connect/references/modals.md +99 -0
- package/skills/customize-connect/references/overrides.md +177 -0
- package/skills/customize-connect/references/packages.md +41 -0
- package/skills/customize-connect/references/pages.md +141 -0
- package/skills/customize-connect/references/runtime-config.md +411 -0
- package/skills/customize-connect/references/styles-and-branding.md +76 -0
- package/skills/customize-connect/references/types-and-troubleshooting.md +64 -0
- package/src/route-tree.ts +3 -0
- package/src/routeTree.gen.ts +235 -0
- package/src/router/index.ts +2 -0
- package/src/router/register.ts +9 -0
- package/src/routes/__root.tsx +12 -0
- package/src/routes/_app/$.tsx +13 -0
- package/src/routes/_app/d/$driveSlug/{-$nodeSlug}.tsx +13 -0
- package/src/routes/_app/d/$driveSlug.tsx +13 -0
- package/src/routes/_app/index.tsx +13 -0
- package/src/routes/_app/settings/appearance.tsx +13 -0
- package/src/routes/_app/settings/packages.tsx +13 -0
- package/src/routes/_app/settings.tsx +13 -0
- package/src/routes/_app.tsx +13 -0
- package/style.css +6 -23
- package/tailwind.css +12 -0
- package/theme.css +5 -0
- package/dist/AddDriveModal-DhNfP94R.js.map +0 -1
- package/dist/ClearStorageModal-DyU-FIgY.js.map +0 -1
- package/dist/ConfirmDocumentUpgradeModal-DcOZy20m.js.map +0 -1
- package/dist/CreateDocumentModal-Bmv0V-kY.js +0 -36
- package/dist/CreateDocumentModal-Bmv0V-kY.js.map +0 -1
- package/dist/DebugSettingsModal-CwUN9gIr.js.map +0 -1
- package/dist/DeleteDriveModal-CjGnG0ht.js.map +0 -1
- package/dist/DeleteItemModal-BbY_4_xT.js.map +0 -1
- package/dist/DisclaimerModal-DuglmEwL.js.map +0 -1
- package/dist/DocumentVersionUnsupportedModal-C4fy7fZ6.js.map +0 -1
- package/dist/DownloadDocumentWithErrorsModal-BsPQ5qgy.js.map +0 -1
- package/dist/DriveAuthRequiredModal-CtsB0kwH.js.map +0 -1
- package/dist/DriveSettingsModal-d1L0eYof.js +0 -57
- package/dist/DriveSettingsModal-d1L0eYof.js.map +0 -1
- package/dist/InspectorModal-Cd8kbCV8.js.map +0 -1
- package/dist/LoginModal-CI0ogC2-.js.map +0 -1
- package/dist/MissingPackageModal-HFUPQMML.js +0 -49
- package/dist/MissingPackageModal-HFUPQMML.js.map +0 -1
- package/dist/OpenFileDocumentsModal-BQsaBP4x.js.map +0 -1
- package/dist/SettingsModal-CgjW-M2a.js +0 -571
- package/dist/SettingsModal-CgjW-M2a.js.map +0 -1
- package/dist/UpgradeDriveModal-CXX6D5Au.js.map +0 -1
- package/dist/app-loader-D2bV-77j.js +0 -4
- package/dist/app-loader-l5wtQh5z.js +0 -2283
- package/dist/app-loader-l5wtQh5z.js.map +0 -1
- package/dist/app-skeleton--Me5zlSz.js.map +0 -1
- package/dist/app-skeleton-CBN4tenZ.js +0 -4
- package/dist/boot-DPNEOI2A.js.map +0 -1
- package/dist/build-info-BV8UtyA4.js.map +0 -1
- package/dist/components-BH57lxCU.js +0 -5
- package/dist/connect.config-CaXMoB42.js.map +0 -1
- package/dist/connection-state-Eqc2izmt.js.map +0 -1
- package/dist/load-ftpCX1HI.js.map +0 -1
- package/dist/package-manager-BbzIV9aN.js.map +0 -1
- package/dist/pglite-major-p4_YefAE.js.map +0 -1
- package/dist/pglite-migrate-core-BcXcImng.js.map +0 -1
- package/dist/pglite-seed-Cl2d-iyl.js.map +0 -1
- package/dist/preferences-store-DZUIAkHE.js.map +0 -1
- package/dist/reactor-CItc8KaF.js +0 -1095
- package/dist/reactor-CItc8KaF.js.map +0 -1
- package/dist/renown-trust-DRgHpxlZ.js +0 -34
- package/dist/renown-trust-DRgHpxlZ.js.map +0 -1
- package/dist/runtime-config-DtJIUgYw.js +0 -24
- package/dist/runtime-config-DtJIUgYw.js.map +0 -1
- package/dist/sentry-jfDyrxdX.js +0 -15
- package/dist/sentry-jfDyrxdX.js.map +0 -1
- package/dist/use-renown-login-BzOSQETV.js.map +0 -1
- package/dist/useIsEmbedded-BWJ0qb7w.js +0 -26
- package/dist/useIsEmbedded-BWJ0qb7w.js.map +0 -1
- package/dist/useRegistryPackages-DuoU75ap.js +0 -453
- package/dist/useRegistryPackages-DuoU75ap.js.map +0 -1
|
@@ -0,0 +1,1656 @@
|
|
|
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]="9588eb8d-0c5c-508e-a6bf-c7fbd8b9e812")}catch(e){}}();
|
|
3
|
+
import { n as buildPHGlobalConfig, o as phGlobalConfig, r as connectConfig } from "./connect.config-DL9nKtlW.js";
|
|
4
|
+
import { a as isPackagedConnectDist, i as getVersion, n as getGitSha } from "./build-info-BTuoWZYI.js";
|
|
5
|
+
import { i as pageSharedImports, r as getSharedDeps, t as BrowserPackageManager } from "./package-manager-B1Nxbull.js";
|
|
6
|
+
import { r as toast } from "./toast-C6WW-_O-.js";
|
|
7
|
+
import { a as closeWithin, n as watchStoreLockWait, o as configureConnectChannelScheme, s as createConnectSignerConfig } from "./store-lock-Bi3B9VJD.js";
|
|
8
|
+
import { a as resolvePgMajorForRuntime, f as toStoredDocumentsRefused, r as loadPGliteModule } from "./pglite-major-pao-ozRo.js";
|
|
9
|
+
import { _ as RELATIONAL_PGLITE_NAME, g as REACTOR_STORE_IN_MEMORY, h as REACTOR_PGLITE_NAME, m as REACTOR_INSTANCE_NAMESPACE, n as getWorkerConnectionStatus, o as detectReactorPgMajor, r as setWorkerConnectionStatus, s as detectRelationalPgMajor, t as clearStorageHeld } from "./connection-state-0ippUGEC.js";
|
|
10
|
+
import { n as setDrivePlacements } from "./drive-placements-DjeVpTTm.js";
|
|
11
|
+
import { holdConnectRoutes } from "@powerhousedao/connect-core/router";
|
|
12
|
+
import { BrowserLocalStorage, DRIVE_DOCUMENT_TYPES, DocumentCache, DocumentChangeType, ReactorBuilder, ReactorClientBuilder, RegistryClient, addDrive, addPHEventHandlers, addRemoteDrive, createAnalyticsStore, createDriveChangeHandler, createSwitchboardDirectory, fetchDriveInfo, getFullReactorClient, getPHStore, isDriveAuthError, login, setAttachmentService, setDefaultPHGlobalConfig, setDocumentCache, setDriveMetadata, setDrives, setFeatures, setPGliteDB, setPHToast, setPackageDiscoveryService, setReactorClient, setReactorClientModule, setRenown, setSelectedDrive, setSelectedNode, setSwitchboards, setVetraPackageManager, trackDriveArrival, untilDriveListed, waitForDocumentReady } from "@powerhousedao/reactor-browser";
|
|
13
|
+
import { ConsoleLogger, logger, setLogLevel as setLogLevel$1 } from "document-model";
|
|
14
|
+
import { getConnectPluginUi } from "@powerhousedao/connect-core/plugins";
|
|
15
|
+
import { DrivePlacements, actionIdsFrom, caughtUp, createAppReactorClient, findServedDrive, getAppDrives, getRuntimeConfig, keepsLocalCopy, localDrivePlacements, planReactorClient, refreshAppDrives, relistAppDrives, resolveSwitchboardDrives, servedUrl, switchboardDrives } from "@powerhousedao/connect-core/runtime";
|
|
16
|
+
import { switchboardOfDrive } from "@powerhousedao/shared/host-tokens";
|
|
17
|
+
import { createRelationalDb } from "@powerhousedao/shared/processors";
|
|
18
|
+
import { DocumentModelRegistry, DocumentModelResolver, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, LocalChannelFactory, LocalChannelPortRegistry, PGLITE_IDB_STORAGE_FACTS, ReactorEventTypes, createReactorHostModuleBase, featureFlagFingerprint } from "@powerhousedao/reactor";
|
|
19
|
+
import { MessageRouter, RPC_PROTOCOL_VERSION, SYNC_REMOTES_CHANGED_EVENT, SyncManagerProxy, connectReactorClient, createInspectorProxy, createPortTransport, createReactorEventBusProxy, createRelationalPgliteProxy, createWorkerAdminClient, isFingerprintMismatchReload, postReactorIdentity } from "@powerhousedao/reactor-browser/rpc";
|
|
20
|
+
import { Kysely } from "kysely";
|
|
21
|
+
import { RoutingAttachmentService, createAttachmentClient, createRemoteAttachmentService, createXhrUploadTransport } from "@powerhousedao/reactor-attachments/client";
|
|
22
|
+
import { BrowserKeyStorage, RenownBuilder, RenownCryptoBuilder } from "@renown/sdk";
|
|
23
|
+
import { OpenFeature } from "@openfeature/web-sdk";
|
|
24
|
+
//#region src/utils/poisoned-store-budget.ts
|
|
25
|
+
const BUDGET_LIMIT = 2;
|
|
26
|
+
const POISONED_STORE = {
|
|
27
|
+
key: "ph-connect:poisoned-store-reloads",
|
|
28
|
+
quietMs: 6e5
|
|
29
|
+
};
|
|
30
|
+
const MISMATCH = {
|
|
31
|
+
key: "ph-connect:mismatch-reloads",
|
|
32
|
+
quietMs: 6e4
|
|
33
|
+
};
|
|
34
|
+
function sessionStore() {
|
|
35
|
+
try {
|
|
36
|
+
return globalThis.sessionStorage;
|
|
37
|
+
} catch {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function readRecord(raw) {
|
|
42
|
+
const record = raw ? JSON.parse(raw) : null;
|
|
43
|
+
return typeof record?.count === "number" && typeof record.lastAt === "number" ? {
|
|
44
|
+
count: record.count,
|
|
45
|
+
lastAt: record.lastAt
|
|
46
|
+
} : {
|
|
47
|
+
count: 0,
|
|
48
|
+
lastAt: 0
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function claimReload(budget, storage, now) {
|
|
52
|
+
if (storage === void 0) return false;
|
|
53
|
+
try {
|
|
54
|
+
const previous = readRecord(storage.getItem(budget.key));
|
|
55
|
+
const count = now - previous.lastAt >= budget.quietMs ? 0 : previous.count;
|
|
56
|
+
const allowed = count < BUDGET_LIMIT;
|
|
57
|
+
storage.setItem(budget.key, JSON.stringify({
|
|
58
|
+
count: allowed ? count + 1 : count,
|
|
59
|
+
lastAt: now
|
|
60
|
+
}));
|
|
61
|
+
return allowed;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** One page reload answers every budgeted reload the page hears, of either budget. */
|
|
67
|
+
let reloadRequested = false;
|
|
68
|
+
function reloadWithinBudget(budget, reload, pastBudget, storage = sessionStore(), now = Date.now()) {
|
|
69
|
+
if (reloadRequested) return;
|
|
70
|
+
if (claimReload(budget, storage, now)) {
|
|
71
|
+
reloadRequested = true;
|
|
72
|
+
reload();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
setWorkerConnectionStatus(pastBudget);
|
|
76
|
+
}
|
|
77
|
+
/** Past the budget a poisoned store stops reloading and shows storage-unusable, so clear storage stays reachable. */
|
|
78
|
+
function reloadForPoisonedStore(reload, storage, now) {
|
|
79
|
+
reloadWithinBudget(POISONED_STORE, reload, "storage-unusable", storage, now);
|
|
80
|
+
}
|
|
81
|
+
/** onPoisoned for an in-tab store: the page reload reopens it, within the poisoned-store budget. */
|
|
82
|
+
function reloadPageForPoisonedStore(cause, reload = () => window.location.reload()) {
|
|
83
|
+
console.error("[connect] PGlite session poisoned:", cause);
|
|
84
|
+
reloadForPoisonedStore(reload);
|
|
85
|
+
}
|
|
86
|
+
function reloadForWorker(reason, reload, storage, now) {
|
|
87
|
+
if (reason === "storage session poisoned") {
|
|
88
|
+
reloadForPoisonedStore(reload, storage, now);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (isFingerprintMismatchReload(reason)) {
|
|
92
|
+
reloadWithinBudget(MISMATCH, reload, "version-conflict", storage, now);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
reload();
|
|
96
|
+
}
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/pglite.db.ts
|
|
99
|
+
const REACTOR_STORAGE_FACTS = REACTOR_STORE_IN_MEMORY ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_IDB_STORAGE_FACTS;
|
|
100
|
+
async function createMainThreadPGlite(major, dbName, relaxedDurability) {
|
|
101
|
+
const { PGlite } = await loadPGliteModule(major);
|
|
102
|
+
const { live } = major === 16 ? await import("pglite-legacy-02/live") : await import("@electric-sql/pglite/live");
|
|
103
|
+
return new PGlite(REACTOR_STORE_IN_MEMORY ? "memory://" : `idb://${dbName}`, {
|
|
104
|
+
relaxedDurability,
|
|
105
|
+
extensions: { live }
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
let bootChain = Promise.resolve();
|
|
109
|
+
function chainedCreate(create) {
|
|
110
|
+
const pending = bootChain.then(create, create);
|
|
111
|
+
bootChain = pending.catch(() => void 0);
|
|
112
|
+
return pending;
|
|
113
|
+
}
|
|
114
|
+
const CLOSE_TIMEOUT_MS = 3e4;
|
|
115
|
+
function pgliteSingleton(opts) {
|
|
116
|
+
let cached;
|
|
117
|
+
let unusable;
|
|
118
|
+
return {
|
|
119
|
+
get() {
|
|
120
|
+
if (cached) return cached;
|
|
121
|
+
const pending = chainedCreate(async () => {
|
|
122
|
+
if (unusable) throw unusable;
|
|
123
|
+
const major = resolvePgMajorForRuntime(await opts.detectMajor());
|
|
124
|
+
if (major !== 17) console.warn(`[${opts.label}] Opening legacy Postgres ${major} data dir. Migrate to PG17 from the banner or the Inspector → Debug tab.`);
|
|
125
|
+
return createMainThreadPGlite(major, opts.dbName, opts.relaxedDurability);
|
|
126
|
+
});
|
|
127
|
+
cached = pending;
|
|
128
|
+
pending.catch(() => {
|
|
129
|
+
if (cached === pending) cached = void 0;
|
|
130
|
+
});
|
|
131
|
+
return pending;
|
|
132
|
+
},
|
|
133
|
+
async discard() {
|
|
134
|
+
const pending = cached;
|
|
135
|
+
if (!pending) return;
|
|
136
|
+
cached = void 0;
|
|
137
|
+
const closing = bootChain.then(async () => {
|
|
138
|
+
const pg = await pending;
|
|
139
|
+
let timer;
|
|
140
|
+
try {
|
|
141
|
+
await Promise.race([pg.close(), new Promise((resolve) => {
|
|
142
|
+
timer = setTimeout(() => {
|
|
143
|
+
unusable = /* @__PURE__ */ new Error(`[${opts.label}] PGlite did not close within ${CLOSE_TIMEOUT_MS}ms; reload the page to reopen its store`);
|
|
144
|
+
console.warn(unusable.message);
|
|
145
|
+
resolve();
|
|
146
|
+
}, CLOSE_TIMEOUT_MS);
|
|
147
|
+
})]);
|
|
148
|
+
} finally {
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
bootChain = closing.catch(() => void 0);
|
|
153
|
+
try {
|
|
154
|
+
await closing;
|
|
155
|
+
} catch (error) {
|
|
156
|
+
console.error(`[${opts.label}] closing PGlite failed:`, error);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const reactorPGlite = pgliteSingleton({
|
|
162
|
+
dbName: REACTOR_PGLITE_NAME,
|
|
163
|
+
detectMajor: detectReactorPgMajor,
|
|
164
|
+
label: "reactor",
|
|
165
|
+
relaxedDurability: false
|
|
166
|
+
});
|
|
167
|
+
const getReactorPGlite = reactorPGlite.get;
|
|
168
|
+
const discardReactorPGlite = reactorPGlite.discard;
|
|
169
|
+
const getRelationalPGlite = pgliteSingleton({
|
|
170
|
+
dbName: RELATIONAL_PGLITE_NAME,
|
|
171
|
+
detectMajor: detectRelationalPgMajor,
|
|
172
|
+
label: "relational",
|
|
173
|
+
relaxedDurability: true
|
|
174
|
+
}).get;
|
|
175
|
+
async function getDb() {
|
|
176
|
+
const pgLite = await getRelationalPGlite();
|
|
177
|
+
return {
|
|
178
|
+
pgLite,
|
|
179
|
+
relationalDb: createRelationalDb(new Kysely({ dialect: new HardenedPGliteDialect(pgLite, { onPoisoned: reloadPageForPoisonedStore }) }))
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
//#endregion
|
|
183
|
+
//#region src/utils/reactor.ts
|
|
184
|
+
/**
|
|
185
|
+
* Creates a Reactor that plugs into legacy storage but syncs through the new
|
|
186
|
+
* Reactor GQL API.
|
|
187
|
+
*/
|
|
188
|
+
async function createBrowserReactor(documentModelModules, upgradeManifests, renown, featureFlags, documentModelLoader, createSignaturePolicy, renownEndpoints = {}, unsupportedStoredDocuments, multiReactor = false) {
|
|
189
|
+
const signerConfig = await createConnectSignerConfig(renown.signer, featureFlags, renownEndpoints);
|
|
190
|
+
const jwtHandler = async (_url) => {
|
|
191
|
+
if (!renown.user) return;
|
|
192
|
+
return renown.getBearerToken({ expiresIn: 10 });
|
|
193
|
+
};
|
|
194
|
+
const pg = await getReactorPGlite();
|
|
195
|
+
const logger = new ConsoleLogger(["reactor-client"]);
|
|
196
|
+
const reactorBuilder = new ReactorBuilder().withDocumentModelSources(documentModelModules).withUpgradeManifests(upgradeManifests).withExecutorConfig({ featureFlags }).withJwtHandler(jwtHandler).withGroupCommitPGlite({
|
|
197
|
+
pg,
|
|
198
|
+
onUnrecoverable: reloadPageForPoisonedStore,
|
|
199
|
+
onDiagnostic: (message, error) => console.error(`[reactor] pglite: ${message}`, error)
|
|
200
|
+
}).withStorageFacts(REACTOR_STORAGE_FACTS);
|
|
201
|
+
configureConnectChannelScheme(reactorBuilder, {
|
|
202
|
+
multiReactor,
|
|
203
|
+
createLocalChannelFactory: () => new LocalChannelFactory(logger, new LocalChannelPortRegistry({ logger }).provider)
|
|
204
|
+
});
|
|
205
|
+
const builder = new ReactorClientBuilder().withLogger(logger).withSigner(signerConfig).withReactorBuilder(reactorBuilder);
|
|
206
|
+
if (documentModelLoader) builder.withDocumentModelLoader(documentModelLoader);
|
|
207
|
+
if (createSignaturePolicy) builder.withCreateSignaturePolicy(createSignaturePolicy);
|
|
208
|
+
if (unsupportedStoredDocuments) reactorBuilder.withUnsupportedStoredDocuments(unsupportedStoredDocuments);
|
|
209
|
+
let module;
|
|
210
|
+
try {
|
|
211
|
+
module = await builder.buildModule();
|
|
212
|
+
} catch (error) {
|
|
213
|
+
await discardReactorPGlite();
|
|
214
|
+
throw toStoredDocumentsRefused(error);
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
...module,
|
|
218
|
+
kind: "browser",
|
|
219
|
+
reactorModule: module.reactorModule ? {
|
|
220
|
+
...module.reactorModule,
|
|
221
|
+
pg
|
|
222
|
+
} : void 0
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function getDefaultDrives(runtimeConfig) {
|
|
226
|
+
return runtimeConfig.connect.drives?.defaultDrives ?? [];
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Add default drives for the new reactor via sync manager.
|
|
230
|
+
*
|
|
231
|
+
* Drives register concurrently so a slow or unreachable drive can't delay the
|
|
232
|
+
* others — in particular the one the URL slug resolves to. Remote drives
|
|
233
|
+
* retry with linear backoff to handle the common race where Connect's dev
|
|
234
|
+
* server is ready before the switchboard has finished binding its port.
|
|
235
|
+
*
|
|
236
|
+
* Each entry is either a remote drive (a URL registered with the sync
|
|
237
|
+
* manager, waited on for initial backfill) or a local drive (created once in
|
|
238
|
+
* this browser's local reactor; its fixed id makes later boots skip it).
|
|
239
|
+
*
|
|
240
|
+
* @param drives - Array of default-drive entries
|
|
241
|
+
* @returns The remote entries that were not added
|
|
242
|
+
*/
|
|
243
|
+
async function addDefaultDrivesForNewReactor(drives) {
|
|
244
|
+
return (await Promise.all(drives.map(async (drive) => {
|
|
245
|
+
if (!("url" in drive)) {
|
|
246
|
+
await addLocalDefaultDrive(drive);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
return await addRemoteDefaultDrive(drive) ? void 0 : drive;
|
|
250
|
+
}))).filter((drive) => drive !== void 0);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Adds the default drives, and again at sign-in those a signed-out person could
|
|
254
|
+
* not reach. A host behind sign-in answers 404 for a drive it will not show, so
|
|
255
|
+
* on a first run nothing can be added until the person has signed in, and
|
|
256
|
+
* nothing else would ask again before a reload.
|
|
257
|
+
*
|
|
258
|
+
* Someone signed in from the start was already refused with their credentials:
|
|
259
|
+
* signing in again cannot change that, so there is nothing to wait for.
|
|
260
|
+
*/
|
|
261
|
+
async function addDefaultDrivesThroughSignIn(renown, drives) {
|
|
262
|
+
const signedInAtStart = renown.user !== void 0;
|
|
263
|
+
const missed = await addDefaultDrivesForNewReactor(drives);
|
|
264
|
+
if (missed.length === 0 || signedInAtStart) return;
|
|
265
|
+
const addMissed = () => trackDriveArrival(addDefaultDrivesForNewReactor(missed));
|
|
266
|
+
if (renown.user) {
|
|
267
|
+
await addMissed();
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const unsubscribe = renown.on("user", (user) => {
|
|
271
|
+
if (!user) return;
|
|
272
|
+
unsubscribe();
|
|
273
|
+
addMissed().catch((error) => console.error("Failed to add default drives after sign-in:", error));
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
/** @returns Whether the drive was added. */
|
|
277
|
+
async function addRemoteDefaultDrive(drive) {
|
|
278
|
+
const MAX_ATTEMPTS = 3;
|
|
279
|
+
const BACKOFF_MS = 2e3;
|
|
280
|
+
let driveId;
|
|
281
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) try {
|
|
282
|
+
driveId = await addRemoteDrive(drive.url);
|
|
283
|
+
break;
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (isDriveAuthError(error)) break;
|
|
286
|
+
if (attempt === MAX_ATTEMPTS) console.error(`Failed to add default drive ${drive.url} after ${MAX_ATTEMPTS} attempts:`, error);
|
|
287
|
+
else {
|
|
288
|
+
const delay = BACKOFF_MS * attempt;
|
|
289
|
+
console.warn(`Default drive ${drive.url} not reachable (attempt ${attempt}/${MAX_ATTEMPTS}), retrying in ${delay}ms...`);
|
|
290
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const store = getPHStore();
|
|
294
|
+
if (driveId && store) await untilDriveListed(store, driveId);
|
|
295
|
+
if (driveId && (drive.name || drive.icon)) try {
|
|
296
|
+
const reactorClient = getFullReactorClient();
|
|
297
|
+
if (reactorClient) await waitForDocumentReady(reactorClient, driveId, { timeoutMs: 15e3 });
|
|
298
|
+
await setDriveMetadata(driveId, {
|
|
299
|
+
name: drive.name,
|
|
300
|
+
icon: drive.icon
|
|
301
|
+
});
|
|
302
|
+
} catch (error) {
|
|
303
|
+
console.warn(`Default drive ${drive.url} was added but metadata update failed:`, error);
|
|
304
|
+
}
|
|
305
|
+
return driveId !== void 0;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Create a configured local default drive in this browser's local reactor.
|
|
309
|
+
* The drive is only created when the configured id is not already taken, so
|
|
310
|
+
* repeated boots are idempotent and a drive the user deleted stays deleted.
|
|
311
|
+
* Name and icon are written straight into the created document's global state
|
|
312
|
+
* (no setDriveMetadata round-trip), and `app` maps to the drive's preferred
|
|
313
|
+
* editor.
|
|
314
|
+
*/
|
|
315
|
+
async function addLocalDefaultDrive(drive) {
|
|
316
|
+
if (!drive.id) {
|
|
317
|
+
console.error("Ignoring local default drive with no id:", JSON.stringify(drive));
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
const reactorClient = getFullReactorClient();
|
|
322
|
+
if (reactorClient) {
|
|
323
|
+
if (await reactorClient.write.isDocumentIdTaken(drive.id)) return;
|
|
324
|
+
}
|
|
325
|
+
await addDrive({
|
|
326
|
+
id: drive.id,
|
|
327
|
+
global: {
|
|
328
|
+
name: drive.name ?? "",
|
|
329
|
+
icon: drive.icon ?? null
|
|
330
|
+
}
|
|
331
|
+
}, drive.app);
|
|
332
|
+
} catch (error) {
|
|
333
|
+
console.error(`Failed to create local default drive ${drive.id}:`, error);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const COPY_TIMEOUT_MS = 3e4;
|
|
337
|
+
const COPY_RECHECK_MS = 250;
|
|
338
|
+
/** Adds what the copy here stored since the last read; false while it is not held here. */
|
|
339
|
+
async function readCopy(driveId, held, from) {
|
|
340
|
+
const local = getPHStore()?.reactorClientModule?.client;
|
|
341
|
+
if (!local) return false;
|
|
342
|
+
try {
|
|
343
|
+
for (const scope of Object.keys(held)) {
|
|
344
|
+
const read = await actionIdsFrom(local.read, driveId, scope, from[scope] ?? 0);
|
|
345
|
+
for (const id of read.ids) held[scope].add(id);
|
|
346
|
+
from[scope] = read.next;
|
|
347
|
+
}
|
|
348
|
+
return true;
|
|
349
|
+
} catch {
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** Resolves once the local copy holds what the switchboard held when called; rejects after the timeout. */
|
|
354
|
+
async function untilCaughtUp(driveId, remote) {
|
|
355
|
+
const backend = getFullReactorClient()?.backends.find((b) => b.name === remote);
|
|
356
|
+
if (!backend) throw new Error(`No switchboard named ${remote} to copy from`);
|
|
357
|
+
const scopes = Object.keys((await backend.api.get(driveId)).header.revision);
|
|
358
|
+
const source = {};
|
|
359
|
+
const held = {};
|
|
360
|
+
for (const scope of scopes) {
|
|
361
|
+
source[scope] = (await actionIdsFrom(backend.api, driveId, scope, 0)).ids;
|
|
362
|
+
held[scope] = /* @__PURE__ */ new Set();
|
|
363
|
+
}
|
|
364
|
+
const from = {};
|
|
365
|
+
const deadline = Date.now() + COPY_TIMEOUT_MS;
|
|
366
|
+
for (;;) {
|
|
367
|
+
if (await readCopy(driveId, held, from) && caughtUp(held, source)) return;
|
|
368
|
+
if (Date.now() >= deadline) throw new Error(`The copy in this browser did not catch up with ${remote} within ${COPY_TIMEOUT_MS / 1e3} s`);
|
|
369
|
+
await new Promise((resolve) => setTimeout(resolve, COPY_RECHECK_MS));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/** The tab's sync remotes, for moving a drive; a copy is ready once it holds what the switchboard holds. */
|
|
373
|
+
function placementSync() {
|
|
374
|
+
const syncManager = () => getPHStore()?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
|
|
375
|
+
return {
|
|
376
|
+
list: () => syncManager()?.list() ?? [],
|
|
377
|
+
remove: async (name) => {
|
|
378
|
+
await syncManager()?.remove(name);
|
|
379
|
+
},
|
|
380
|
+
add: async (url, driveId) => {
|
|
381
|
+
await addRemoteDrive(url, driveId);
|
|
382
|
+
},
|
|
383
|
+
untilCopied: (driveId, remote) => untilCaughtUp(driveId, remote)
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
//#endregion
|
|
387
|
+
//#region src/feature-flags.ts
|
|
388
|
+
/**
|
|
389
|
+
* QueryParamProvider reads feature flags from URL query parameters.
|
|
390
|
+
*
|
|
391
|
+
* Usage:
|
|
392
|
+
* const params = new URLSearchParams(window.location.search);
|
|
393
|
+
* const provider = new QueryParamProvider(params);
|
|
394
|
+
* await OpenFeature.setProviderAndWait(provider);
|
|
395
|
+
*
|
|
396
|
+
* Query parameter format:
|
|
397
|
+
* ?FEATURE_FOO=true&FEATURE_BAR=false
|
|
398
|
+
*/
|
|
399
|
+
var QueryParamProvider = class {
|
|
400
|
+
runsOn = "client";
|
|
401
|
+
metadata = { name: "QueryParamProvider" };
|
|
402
|
+
flags;
|
|
403
|
+
constructor(searchParams) {
|
|
404
|
+
this.flags = /* @__PURE__ */ new Map();
|
|
405
|
+
for (const [key, value] of searchParams.entries()) this.flags.set(key, value);
|
|
406
|
+
}
|
|
407
|
+
resolveBooleanEvaluation(flagKey, defaultValue) {
|
|
408
|
+
const value = this.flags.get(flagKey);
|
|
409
|
+
if (value === void 0) return {
|
|
410
|
+
value: defaultValue,
|
|
411
|
+
reason: "DEFAULT"
|
|
412
|
+
};
|
|
413
|
+
return {
|
|
414
|
+
value: value.toLowerCase() === "true" || value === "1",
|
|
415
|
+
reason: "STATIC",
|
|
416
|
+
variant: value
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
resolveStringEvaluation(flagKey, defaultValue) {
|
|
420
|
+
const value = this.flags.get(flagKey);
|
|
421
|
+
if (value === void 0) return {
|
|
422
|
+
value: defaultValue,
|
|
423
|
+
reason: "DEFAULT"
|
|
424
|
+
};
|
|
425
|
+
return {
|
|
426
|
+
value,
|
|
427
|
+
reason: "STATIC",
|
|
428
|
+
variant: value
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
resolveNumberEvaluation(flagKey, defaultValue) {
|
|
432
|
+
const value = this.flags.get(flagKey);
|
|
433
|
+
if (value === void 0) return {
|
|
434
|
+
value: defaultValue,
|
|
435
|
+
reason: "DEFAULT"
|
|
436
|
+
};
|
|
437
|
+
const numValue = Number(value);
|
|
438
|
+
if (isNaN(numValue)) return {
|
|
439
|
+
value: defaultValue,
|
|
440
|
+
reason: "ERROR",
|
|
441
|
+
errorCode: "PARSE_ERROR",
|
|
442
|
+
errorMessage: `Failed to parse "${value}" as a number`
|
|
443
|
+
};
|
|
444
|
+
return {
|
|
445
|
+
value: numValue,
|
|
446
|
+
reason: "STATIC",
|
|
447
|
+
variant: value
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
resolveObjectEvaluation(flagKey, defaultValue) {
|
|
451
|
+
const value = this.flags.get(flagKey);
|
|
452
|
+
if (value === void 0) return {
|
|
453
|
+
value: defaultValue,
|
|
454
|
+
reason: "DEFAULT"
|
|
455
|
+
};
|
|
456
|
+
try {
|
|
457
|
+
return {
|
|
458
|
+
value: JSON.parse(value),
|
|
459
|
+
reason: "STATIC",
|
|
460
|
+
variant: value
|
|
461
|
+
};
|
|
462
|
+
} catch (error) {
|
|
463
|
+
return {
|
|
464
|
+
value: defaultValue,
|
|
465
|
+
reason: "ERROR",
|
|
466
|
+
errorCode: "PARSE_ERROR",
|
|
467
|
+
errorMessage: `Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
/**
|
|
473
|
+
* Initialize OpenFeature with the QueryParamProvider.
|
|
474
|
+
* Reads feature flags from query parameters.
|
|
475
|
+
*/
|
|
476
|
+
async function initFeatureFlags(searchParams) {
|
|
477
|
+
const params = searchParams ?? (typeof window !== "undefined" ? new URLSearchParams(window.location.search) : new URLSearchParams());
|
|
478
|
+
const provider = new QueryParamProvider(params);
|
|
479
|
+
await OpenFeature.setProviderAndWait(provider);
|
|
480
|
+
const features = /* @__PURE__ */ new Map();
|
|
481
|
+
const logLevelParam = params.get("LOG_LEVEL");
|
|
482
|
+
if (logLevelParam) {
|
|
483
|
+
const validLogLevels = [
|
|
484
|
+
"verbose",
|
|
485
|
+
"debug",
|
|
486
|
+
"info",
|
|
487
|
+
"warn",
|
|
488
|
+
"error"
|
|
489
|
+
];
|
|
490
|
+
if (validLogLevels.includes(logLevelParam.toLowerCase())) {
|
|
491
|
+
setLogLevel$1(logLevelParam.toLowerCase());
|
|
492
|
+
logger.info("Log level set to @level via query param", logLevelParam.toLowerCase());
|
|
493
|
+
} else logger.warn("Invalid LOG_LEVEL query param: @param. Valid values: @validLevels", logLevelParam, validLogLevels.join(", "));
|
|
494
|
+
}
|
|
495
|
+
return features;
|
|
496
|
+
}
|
|
497
|
+
//#endregion
|
|
498
|
+
//#region src/no-registry-discovery.ts
|
|
499
|
+
/**
|
|
500
|
+
* Discovery service used when no package registry is configured. Every load
|
|
501
|
+
* for an unknown document type is recorded as a failure with reason
|
|
502
|
+
* "no-registry" so the UI can surface the issue; the modal install flow is a
|
|
503
|
+
* no-op because there is no registry to query.
|
|
504
|
+
*/
|
|
505
|
+
var NoRegistryDiscoveryService = class {
|
|
506
|
+
#packageManager;
|
|
507
|
+
#failed = /* @__PURE__ */ new Map();
|
|
508
|
+
#failedMemo = [];
|
|
509
|
+
#failedSubscribers = /* @__PURE__ */ new Set();
|
|
510
|
+
#eventSubscribers = /* @__PURE__ */ new Set();
|
|
511
|
+
constructor(packageManager) {
|
|
512
|
+
this.#packageManager = packageManager;
|
|
513
|
+
}
|
|
514
|
+
load(documentType) {
|
|
515
|
+
const existing = this.#findModuleInLoadedPackages(documentType);
|
|
516
|
+
if (existing) {
|
|
517
|
+
this.#clearFailed(documentType);
|
|
518
|
+
return Promise.resolve(existing);
|
|
519
|
+
}
|
|
520
|
+
this.#recordFailure(documentType);
|
|
521
|
+
return Promise.reject(/* @__PURE__ */ new Error(`No package registry configured; cannot resolve "${documentType}"`));
|
|
522
|
+
}
|
|
523
|
+
promptInstallation() {}
|
|
524
|
+
approveInstallation() {
|
|
525
|
+
return Promise.resolve();
|
|
526
|
+
}
|
|
527
|
+
dismissInstallation() {}
|
|
528
|
+
getPendingInstallations() {
|
|
529
|
+
return [];
|
|
530
|
+
}
|
|
531
|
+
subscribePending() {
|
|
532
|
+
return () => {};
|
|
533
|
+
}
|
|
534
|
+
getFailedInstallations() {
|
|
535
|
+
return this.#failedMemo;
|
|
536
|
+
}
|
|
537
|
+
subscribeFailed(listener) {
|
|
538
|
+
this.#failedSubscribers.add(listener);
|
|
539
|
+
return () => {
|
|
540
|
+
this.#failedSubscribers.delete(listener);
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
subscribeEvents(listener) {
|
|
544
|
+
this.#eventSubscribers.add(listener);
|
|
545
|
+
return () => {
|
|
546
|
+
this.#eventSubscribers.delete(listener);
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
retryInstallation(documentType) {
|
|
550
|
+
this.#recordFailure(documentType);
|
|
551
|
+
return Promise.resolve();
|
|
552
|
+
}
|
|
553
|
+
#findModuleInLoadedPackages(documentType) {
|
|
554
|
+
return this.#packageManager.packages.flatMap((p) => p.documentModels).find((m) => m.documentModel.global.id === documentType);
|
|
555
|
+
}
|
|
556
|
+
#recordFailure(documentType) {
|
|
557
|
+
this.#failed.set(documentType, {
|
|
558
|
+
documentType,
|
|
559
|
+
reason: "no-registry",
|
|
560
|
+
packageNames: [],
|
|
561
|
+
error: null
|
|
562
|
+
});
|
|
563
|
+
this.#emitEvent({
|
|
564
|
+
type: "load-failed",
|
|
565
|
+
documentType,
|
|
566
|
+
reason: "no-registry"
|
|
567
|
+
});
|
|
568
|
+
this.#notifyFailedChanged();
|
|
569
|
+
}
|
|
570
|
+
#clearFailed(documentType) {
|
|
571
|
+
if (this.#failed.delete(documentType)) this.#notifyFailedChanged();
|
|
572
|
+
}
|
|
573
|
+
#notifyFailedChanged() {
|
|
574
|
+
this.#failedMemo = Array.from(this.#failed.values());
|
|
575
|
+
for (const listener of this.#failedSubscribers) listener();
|
|
576
|
+
}
|
|
577
|
+
#emitEvent(event) {
|
|
578
|
+
for (const listener of this.#eventSubscribers) listener(event);
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
//#endregion
|
|
582
|
+
//#region src/package-discovery.ts
|
|
583
|
+
var PackageDiscoveryService = class {
|
|
584
|
+
#packageManager;
|
|
585
|
+
#registryClient;
|
|
586
|
+
#mode;
|
|
587
|
+
#deferred = /* @__PURE__ */ new Map();
|
|
588
|
+
#pending = /* @__PURE__ */ new Map();
|
|
589
|
+
#pendingMemo = [];
|
|
590
|
+
#pendingSubscribers = /* @__PURE__ */ new Set();
|
|
591
|
+
#failed = /* @__PURE__ */ new Map();
|
|
592
|
+
#failedMemo = [];
|
|
593
|
+
#failedSubscribers = /* @__PURE__ */ new Set();
|
|
594
|
+
#eventSubscribers = /* @__PURE__ */ new Set();
|
|
595
|
+
#dismissedStorage;
|
|
596
|
+
#discoveredTypes = /* @__PURE__ */ new Map();
|
|
597
|
+
constructor(packageManager, registryClient, options) {
|
|
598
|
+
this.#packageManager = packageManager;
|
|
599
|
+
this.#registryClient = registryClient;
|
|
600
|
+
this.#mode = options.mode;
|
|
601
|
+
this.#dismissedStorage = new BrowserLocalStorage(options.storageKey + ":PH_DISMISSED_TYPES");
|
|
602
|
+
}
|
|
603
|
+
load(documentType) {
|
|
604
|
+
const existing = this.#findModuleInLoadedPackages(documentType);
|
|
605
|
+
if (existing) {
|
|
606
|
+
this.#clearFailed(documentType);
|
|
607
|
+
return Promise.resolve(existing);
|
|
608
|
+
}
|
|
609
|
+
if (this.#dismissedStorage.has(documentType)) {
|
|
610
|
+
this.#recordFailure(documentType, "dismissed", [], null);
|
|
611
|
+
return Promise.reject(/* @__PURE__ */ new Error(`Document type "${documentType}" was dismissed`));
|
|
612
|
+
}
|
|
613
|
+
const tracked = this.#deferred.get(documentType);
|
|
614
|
+
if (tracked) return tracked.promise;
|
|
615
|
+
return this.#discover(documentType);
|
|
616
|
+
}
|
|
617
|
+
promptInstallation(documentType) {
|
|
618
|
+
const packageNames = this.#discoveredTypes.get(documentType);
|
|
619
|
+
if (!packageNames) return;
|
|
620
|
+
if (this.#pending.has(documentType)) return;
|
|
621
|
+
this.#discoveredTypes.delete(documentType);
|
|
622
|
+
this.#addToPending(documentType, packageNames);
|
|
623
|
+
}
|
|
624
|
+
async approveInstallation(packageName) {
|
|
625
|
+
const affectedTypes = this.#findTypesByPackage(packageName);
|
|
626
|
+
if (affectedTypes.length === 0) return;
|
|
627
|
+
const result = await this.#packageManager.addPackage(packageName);
|
|
628
|
+
if (result.type === "error") {
|
|
629
|
+
this.#emitEvent({
|
|
630
|
+
type: "installation-failed",
|
|
631
|
+
packageName,
|
|
632
|
+
error: result.error
|
|
633
|
+
});
|
|
634
|
+
for (const documentType of affectedTypes) {
|
|
635
|
+
const entry = this.#deferred.get(documentType);
|
|
636
|
+
if (entry) {
|
|
637
|
+
entry.reject(result.error);
|
|
638
|
+
this.#deferred.delete(documentType);
|
|
639
|
+
this.#pending.delete(documentType);
|
|
640
|
+
}
|
|
641
|
+
this.#recordFailure(documentType, "install-failed", [packageName], result.error);
|
|
642
|
+
}
|
|
643
|
+
this.#notifyPendingChanged();
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
this.#emitEvent({
|
|
647
|
+
type: "installation-approved",
|
|
648
|
+
packageName,
|
|
649
|
+
documentTypes: affectedTypes
|
|
650
|
+
});
|
|
651
|
+
for (const documentType of affectedTypes) {
|
|
652
|
+
const entry = this.#deferred.get(documentType);
|
|
653
|
+
if (!entry) continue;
|
|
654
|
+
const module = this.#findModuleInLoadedPackages(documentType);
|
|
655
|
+
if (module) {
|
|
656
|
+
entry.resolve(module);
|
|
657
|
+
this.#clearFailed(documentType);
|
|
658
|
+
} else {
|
|
659
|
+
const error = /* @__PURE__ */ new Error(`Package "${packageName}" installed but module for "${documentType}" not found`);
|
|
660
|
+
entry.reject(error);
|
|
661
|
+
this.#recordFailure(documentType, "install-failed", [packageName], error);
|
|
662
|
+
}
|
|
663
|
+
this.#deferred.delete(documentType);
|
|
664
|
+
this.#pending.delete(documentType);
|
|
665
|
+
}
|
|
666
|
+
this.#notifyPendingChanged();
|
|
667
|
+
}
|
|
668
|
+
dismissInstallation(packageName) {
|
|
669
|
+
const affectedTypes = this.#findTypesByPackage(packageName);
|
|
670
|
+
if (affectedTypes.length === 0) return;
|
|
671
|
+
for (const documentType of affectedTypes) {
|
|
672
|
+
this.#dismissedStorage.set(documentType, true);
|
|
673
|
+
const entry = this.#deferred.get(documentType);
|
|
674
|
+
if (entry) entry.reject(/* @__PURE__ */ new Error(`Document type "${documentType}" was dismissed`));
|
|
675
|
+
this.#deferred.delete(documentType);
|
|
676
|
+
this.#pending.delete(documentType);
|
|
677
|
+
this.#discoveredTypes.delete(documentType);
|
|
678
|
+
this.#recordFailure(documentType, "dismissed", [packageName], null);
|
|
679
|
+
}
|
|
680
|
+
this.#emitEvent({
|
|
681
|
+
type: "installation-dismissed",
|
|
682
|
+
packageName,
|
|
683
|
+
documentTypes: affectedTypes
|
|
684
|
+
});
|
|
685
|
+
this.#notifyPendingChanged();
|
|
686
|
+
}
|
|
687
|
+
getPendingInstallations() {
|
|
688
|
+
return this.#pendingMemo;
|
|
689
|
+
}
|
|
690
|
+
subscribePending(listener) {
|
|
691
|
+
this.#pendingSubscribers.add(listener);
|
|
692
|
+
return () => {
|
|
693
|
+
this.#pendingSubscribers.delete(listener);
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
getFailedInstallations() {
|
|
697
|
+
return this.#failedMemo;
|
|
698
|
+
}
|
|
699
|
+
subscribeFailed(listener) {
|
|
700
|
+
this.#failedSubscribers.add(listener);
|
|
701
|
+
return () => {
|
|
702
|
+
this.#failedSubscribers.delete(listener);
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
subscribeEvents(listener) {
|
|
706
|
+
this.#eventSubscribers.add(listener);
|
|
707
|
+
return () => {
|
|
708
|
+
this.#eventSubscribers.delete(listener);
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async retryInstallation(documentType) {
|
|
712
|
+
this.#dismissedStorage.delete(documentType);
|
|
713
|
+
this.#clearFailed(documentType);
|
|
714
|
+
try {
|
|
715
|
+
await this.#discover(documentType);
|
|
716
|
+
} catch {}
|
|
717
|
+
}
|
|
718
|
+
async #discover(documentType) {
|
|
719
|
+
if (typeof navigator !== "undefined" && navigator.onLine === false) {
|
|
720
|
+
this.#recordFailure(documentType, "offline", [], null);
|
|
721
|
+
return Promise.reject(/* @__PURE__ */ new Error(`Offline: cannot discover document type "${documentType}"`));
|
|
722
|
+
}
|
|
723
|
+
let packageNames;
|
|
724
|
+
try {
|
|
725
|
+
packageNames = await this.#registryClient.getPackagesByDocumentType(documentType);
|
|
726
|
+
} catch (error) {
|
|
727
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
728
|
+
this.#emitEvent({
|
|
729
|
+
type: "registry-query-failed",
|
|
730
|
+
documentType,
|
|
731
|
+
error: normalized
|
|
732
|
+
});
|
|
733
|
+
this.#recordFailure(documentType, "registry-error", [], normalized);
|
|
734
|
+
return Promise.reject(normalized);
|
|
735
|
+
}
|
|
736
|
+
if (packageNames.length === 0) {
|
|
737
|
+
this.#recordFailure(documentType, "not-in-registry", [], null);
|
|
738
|
+
return Promise.reject(/* @__PURE__ */ new Error(`No packages found for document type "${documentType}"`));
|
|
739
|
+
}
|
|
740
|
+
const entry = this.#createDeferredEntry(documentType, packageNames);
|
|
741
|
+
this.#emitEvent({
|
|
742
|
+
type: "type-discovered",
|
|
743
|
+
documentType,
|
|
744
|
+
packageNames
|
|
745
|
+
});
|
|
746
|
+
if (this.#mode === "immediate") this.#addToPending(documentType, packageNames);
|
|
747
|
+
else this.#discoveredTypes.set(documentType, packageNames);
|
|
748
|
+
return entry.promise;
|
|
749
|
+
}
|
|
750
|
+
#createDeferredEntry(documentType, packageNames) {
|
|
751
|
+
let resolve;
|
|
752
|
+
let reject;
|
|
753
|
+
const promise = new Promise((res, rej) => {
|
|
754
|
+
resolve = res;
|
|
755
|
+
reject = rej;
|
|
756
|
+
});
|
|
757
|
+
const entry = {
|
|
758
|
+
packageNames,
|
|
759
|
+
resolve,
|
|
760
|
+
reject,
|
|
761
|
+
promise
|
|
762
|
+
};
|
|
763
|
+
this.#deferred.set(documentType, entry);
|
|
764
|
+
return entry;
|
|
765
|
+
}
|
|
766
|
+
#addToPending(documentType, packageNames) {
|
|
767
|
+
const installation = {
|
|
768
|
+
documentType,
|
|
769
|
+
packageNames
|
|
770
|
+
};
|
|
771
|
+
this.#pending.set(documentType, installation);
|
|
772
|
+
this.#emitEvent({
|
|
773
|
+
type: "installation-prompted",
|
|
774
|
+
documentType,
|
|
775
|
+
packageNames
|
|
776
|
+
});
|
|
777
|
+
this.#notifyPendingChanged();
|
|
778
|
+
}
|
|
779
|
+
#findModuleInLoadedPackages(documentType) {
|
|
780
|
+
return this.#packageManager.packages.flatMap((p) => p.documentModels).find((m) => m.documentModel.global.id === documentType);
|
|
781
|
+
}
|
|
782
|
+
#findTypesByPackage(packageName) {
|
|
783
|
+
const types = [];
|
|
784
|
+
for (const [documentType, entry] of this.#deferred) if (entry.packageNames.includes(packageName)) types.push(documentType);
|
|
785
|
+
return types;
|
|
786
|
+
}
|
|
787
|
+
#notifyPendingChanged() {
|
|
788
|
+
this.#pendingMemo = Array.from(this.#pending.values());
|
|
789
|
+
for (const listener of this.#pendingSubscribers) listener();
|
|
790
|
+
}
|
|
791
|
+
#notifyFailedChanged() {
|
|
792
|
+
this.#failedMemo = Array.from(this.#failed.values());
|
|
793
|
+
for (const listener of this.#failedSubscribers) listener();
|
|
794
|
+
}
|
|
795
|
+
#recordFailure(documentType, reason, packageNames, error) {
|
|
796
|
+
this.#failed.set(documentType, {
|
|
797
|
+
documentType,
|
|
798
|
+
reason,
|
|
799
|
+
packageNames,
|
|
800
|
+
error
|
|
801
|
+
});
|
|
802
|
+
this.#emitEvent({
|
|
803
|
+
type: "load-failed",
|
|
804
|
+
documentType,
|
|
805
|
+
reason
|
|
806
|
+
});
|
|
807
|
+
this.#notifyFailedChanged();
|
|
808
|
+
}
|
|
809
|
+
#clearFailed(documentType) {
|
|
810
|
+
if (this.#failed.delete(documentType)) this.#notifyFailedChanged();
|
|
811
|
+
}
|
|
812
|
+
#emitEvent(event) {
|
|
813
|
+
for (const listener of this.#eventSubscribers) listener(event);
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
//#endregion
|
|
817
|
+
//#region src/reactor-worker-name.ts
|
|
818
|
+
const GEN_KEY_PREFIX = "ph-reactor-gen:";
|
|
819
|
+
function genStore() {
|
|
820
|
+
try {
|
|
821
|
+
return globalThis.localStorage;
|
|
822
|
+
} catch {
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
function workerNameForGen(namespace, gen) {
|
|
827
|
+
return gen ? `ph-reactor:${namespace}#${gen}` : `ph-reactor:${namespace}`;
|
|
828
|
+
}
|
|
829
|
+
function readWorkerGen(namespace, storage = genStore()) {
|
|
830
|
+
try {
|
|
831
|
+
return storage?.getItem(GEN_KEY_PREFIX + namespace) ?? null;
|
|
832
|
+
} catch {
|
|
833
|
+
return null;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Gens are unordered tokens, so a reload moves the gen on only from the one
|
|
838
|
+
* this tab's worker runs as; a stale worker's reload never undoes a newer one.
|
|
839
|
+
*/
|
|
840
|
+
function adoptWorkerGen(namespace, from, to, storage = genStore()) {
|
|
841
|
+
try {
|
|
842
|
+
if (storage?.getItem(GEN_KEY_PREFIX + namespace) !== from) return;
|
|
843
|
+
storage.setItem(GEN_KEY_PREFIX + namespace, to);
|
|
844
|
+
} catch {}
|
|
845
|
+
}
|
|
846
|
+
//#endregion
|
|
847
|
+
//#region src/reactor-worker-client.ts
|
|
848
|
+
const PING_INTERVAL_MS = 2e3;
|
|
849
|
+
const PING_DEADLINE_MS = 3e3;
|
|
850
|
+
const MAX_MISSED_PINGS = 2;
|
|
851
|
+
/** The hello fingerprint; a running worker with a different one retires. */
|
|
852
|
+
function buildWorkerVersion(args) {
|
|
853
|
+
const gitSha = getGitSha();
|
|
854
|
+
const buildId = gitSha !== "unknown" ? gitSha : getVersion();
|
|
855
|
+
return {
|
|
856
|
+
appBuildId: args.workerDigest ? `${buildId}+w.${args.workerDigest}` : buildId,
|
|
857
|
+
rpcProtocolVersion: RPC_PROTOCOL_VERSION,
|
|
858
|
+
models: args.documentModelModules.map((m) => ({
|
|
859
|
+
id: m.documentModel.global.id,
|
|
860
|
+
version: m.version ?? 1
|
|
861
|
+
})),
|
|
862
|
+
featureFlags: featureFlagFingerprint({
|
|
863
|
+
...args.featureFlags,
|
|
864
|
+
multiReactor: args.multiReactor,
|
|
865
|
+
storeInMemory: args.storeInMemory
|
|
866
|
+
})
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
/** What the worker's build reads; flags arrive here because it has no config. */
|
|
870
|
+
function buildWorkerConstruct(args) {
|
|
871
|
+
return {
|
|
872
|
+
namespace: args.namespace,
|
|
873
|
+
relationalNamespace: args.relationalNamespace,
|
|
874
|
+
cdnUrl: args.cdnUrl,
|
|
875
|
+
packageSpecs: args.packageSpecs,
|
|
876
|
+
sharedImports: args.sharedImports,
|
|
877
|
+
studioMode: args.studioMode,
|
|
878
|
+
workflowsEnabled: args.workflowsEnabled,
|
|
879
|
+
renownChainId: args.renownChainId,
|
|
880
|
+
featureFlags: args.featureFlags,
|
|
881
|
+
multiReactor: args.multiReactor,
|
|
882
|
+
storeInMemory: args.storeInMemory,
|
|
883
|
+
createSignaturePolicy: args.createSignaturePolicy,
|
|
884
|
+
unsupportedStoredDocuments: args.unsupportedStoredDocuments,
|
|
885
|
+
renownEndpoints: args.renownEndpoints,
|
|
886
|
+
packageSources: args.packageSources
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
function toReactorIdentity(user) {
|
|
890
|
+
if (!user) return null;
|
|
891
|
+
return {
|
|
892
|
+
address: user.address,
|
|
893
|
+
chainId: user.chainId,
|
|
894
|
+
networkId: user.networkId
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
function createWorkerReactorClientModule(args) {
|
|
898
|
+
const workerUrl = args.workerUrl ? new URL(args.workerUrl) : new URL("./reactor.worker.js", import.meta.url);
|
|
899
|
+
const workerGen = readWorkerGen(args.namespace);
|
|
900
|
+
const workerName = workerNameForGen(args.namespace, workerGen);
|
|
901
|
+
console.info(`[reactor-worker] constructing SharedWorker ${workerName} from ${workerUrl.href}`);
|
|
902
|
+
const worker = new SharedWorker(workerUrl, {
|
|
903
|
+
name: workerName,
|
|
904
|
+
type: "module"
|
|
905
|
+
});
|
|
906
|
+
worker.addEventListener("error", (event) => {
|
|
907
|
+
console.error(`[reactor-worker] SharedWorker failed to load from ${workerUrl.href}`, event.message || event);
|
|
908
|
+
setWorkerConnectionStatus("failed");
|
|
909
|
+
});
|
|
910
|
+
worker.port.onmessageerror = (event) => {
|
|
911
|
+
console.error("[reactor-worker] port message could not be deserialized", event);
|
|
912
|
+
};
|
|
913
|
+
const transport = createPortTransport(worker.port);
|
|
914
|
+
const router = new MessageRouter();
|
|
915
|
+
router.attach(transport);
|
|
916
|
+
const documentModelRegistry = new DocumentModelRegistry();
|
|
917
|
+
documentModelRegistry.registerModules(...args.documentModelModules);
|
|
918
|
+
documentModelRegistry.registerUpgradeManifests(...args.upgradeManifests);
|
|
919
|
+
const clientProxy = connectReactorClient(router, {
|
|
920
|
+
version: buildWorkerVersion(args),
|
|
921
|
+
construct: buildWorkerConstruct(args),
|
|
922
|
+
packages: args.packageSpecs
|
|
923
|
+
}, (reason, nextGen) => {
|
|
924
|
+
if (nextGen) adoptWorkerGen(args.namespace, workerGen, nextGen);
|
|
925
|
+
args.onReload(reason);
|
|
926
|
+
}, documentModelRegistry);
|
|
927
|
+
const busProxy = createReactorEventBusProxy(router);
|
|
928
|
+
const syncManagerProxy = new SyncManagerProxy(router, busProxy);
|
|
929
|
+
const modelResolver = new DocumentModelResolver(documentModelRegistry, args.documentModelLoader);
|
|
930
|
+
busProxy.subscribe(ReactorEventTypes.MODEL_LOADED, (_type, event) => {
|
|
931
|
+
const { documentType } = event;
|
|
932
|
+
modelResolver.ensureModelLoaded(documentType).catch((error) => {
|
|
933
|
+
console.error(`Failed to load model "${documentType}" into tab registry`, error);
|
|
934
|
+
});
|
|
935
|
+
});
|
|
936
|
+
setPGliteDB({
|
|
937
|
+
db: createRelationalPgliteProxy(router),
|
|
938
|
+
isLoading: false,
|
|
939
|
+
error: null
|
|
940
|
+
});
|
|
941
|
+
postReactorIdentity(router, toReactorIdentity(args.renown.user));
|
|
942
|
+
args.renown.on("user", (user) => postReactorIdentity(router, toReactorIdentity(user)));
|
|
943
|
+
const reactorClientModule = {
|
|
944
|
+
kind: "worker",
|
|
945
|
+
read: clientProxy.read,
|
|
946
|
+
write: clientProxy.write,
|
|
947
|
+
client: clientProxy,
|
|
948
|
+
adminClient: createWorkerAdminClient(router),
|
|
949
|
+
inspector: createInspectorProxy(router),
|
|
950
|
+
registerPackages: async (sources, specs = []) => {
|
|
951
|
+
await router.request((id) => ({
|
|
952
|
+
k: "register-packages",
|
|
953
|
+
id,
|
|
954
|
+
specs,
|
|
955
|
+
sources
|
|
956
|
+
}));
|
|
957
|
+
},
|
|
958
|
+
reactorModule: {
|
|
959
|
+
documentModelRegistry,
|
|
960
|
+
syncModule: { syncManager: syncManagerProxy },
|
|
961
|
+
eventBus: busProxy
|
|
962
|
+
}
|
|
963
|
+
};
|
|
964
|
+
let pingCounter = 0;
|
|
965
|
+
let missedPings = 0;
|
|
966
|
+
const pingDeadlines = /* @__PURE__ */ new Map();
|
|
967
|
+
router.on("pong", (msg) => {
|
|
968
|
+
const timer = pingDeadlines.get(msg.id);
|
|
969
|
+
if (timer === void 0) return;
|
|
970
|
+
clearTimeout(timer);
|
|
971
|
+
pingDeadlines.delete(msg.id);
|
|
972
|
+
missedPings = 0;
|
|
973
|
+
setWorkerConnectionStatus("connected");
|
|
974
|
+
});
|
|
975
|
+
const pingInterval = setInterval(() => {
|
|
976
|
+
const id = `ping${++pingCounter}`;
|
|
977
|
+
const timer = setTimeout(() => {
|
|
978
|
+
pingDeadlines.delete(id);
|
|
979
|
+
missedPings += 1;
|
|
980
|
+
if (missedPings >= MAX_MISSED_PINGS && getWorkerConnectionStatus() !== "failed") setWorkerConnectionStatus("lost");
|
|
981
|
+
}, PING_DEADLINE_MS);
|
|
982
|
+
pingDeadlines.set(id, timer);
|
|
983
|
+
router.post({
|
|
984
|
+
k: "ping",
|
|
985
|
+
id
|
|
986
|
+
});
|
|
987
|
+
}, PING_INTERVAL_MS);
|
|
988
|
+
const dispose = () => {
|
|
989
|
+
clearInterval(pingInterval);
|
|
990
|
+
for (const timer of pingDeadlines.values()) clearTimeout(timer);
|
|
991
|
+
pingDeadlines.clear();
|
|
992
|
+
};
|
|
993
|
+
return {
|
|
994
|
+
reactorClientModule,
|
|
995
|
+
syncManagerProxy,
|
|
996
|
+
dispose
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
//#endregion
|
|
1000
|
+
//#region src/utils/deleted-selection.ts
|
|
1001
|
+
/** Closes the drive or document a Deleted event removed, saying why. */
|
|
1002
|
+
function closeDeletedSelection(event, host) {
|
|
1003
|
+
if (event.type !== DocumentChangeType.Deleted) return;
|
|
1004
|
+
const deletedId = event.context?.childId;
|
|
1005
|
+
if (!deletedId) return;
|
|
1006
|
+
const gone = event.context?.purged ? "has been erased" : "has been deleted";
|
|
1007
|
+
if (host.selectedDriveId && deletedId === host.selectedDriveId) {
|
|
1008
|
+
host.closeDrive();
|
|
1009
|
+
host.notify(`The drive you were viewing ${gone}`);
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
if (host.selectedNodeId && deletedId === host.selectedNodeId) {
|
|
1013
|
+
host.closeNode();
|
|
1014
|
+
host.notify(`The document you were editing ${gone}`);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
//#endregion
|
|
1018
|
+
//#region src/utils/worker-startup.ts
|
|
1019
|
+
/** Runs the worker's startup seed, showing storage-held while its stores are locked elsewhere. */
|
|
1020
|
+
async function startupOwningStores(startup, namespaces, watchOptions) {
|
|
1021
|
+
const stopWatching = watchStoreLockWait(namespaces, (waiting) => waiting ? setWorkerConnectionStatus("storage-held") : clearStorageHeld(), watchOptions);
|
|
1022
|
+
try {
|
|
1023
|
+
await startup({ isWaiting: () => getWorkerConnectionStatus() === "storage-held" });
|
|
1024
|
+
clearStorageHeld();
|
|
1025
|
+
} finally {
|
|
1026
|
+
stopWatching();
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
//#endregion
|
|
1030
|
+
//#region src/utils/placement-idb.ts
|
|
1031
|
+
const DB_NAME = "ph-connect-drive-placement";
|
|
1032
|
+
const DB_VERSION = 1;
|
|
1033
|
+
const STORE = "moves";
|
|
1034
|
+
function open() {
|
|
1035
|
+
return new Promise((resolve, reject) => {
|
|
1036
|
+
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
|
1037
|
+
req.onupgradeneeded = () => {
|
|
1038
|
+
if (!req.result.objectStoreNames.contains(STORE)) req.result.createObjectStore(STORE, { keyPath: "slug" });
|
|
1039
|
+
};
|
|
1040
|
+
req.onerror = () => reject(req.error ?? /* @__PURE__ */ new Error(`${DB_NAME} open failed`));
|
|
1041
|
+
req.onblocked = () => reject(/* @__PURE__ */ new Error(`${DB_NAME} open blocked`));
|
|
1042
|
+
req.onsuccess = () => resolve(req.result);
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
async function run(mode, work) {
|
|
1046
|
+
const db = await open();
|
|
1047
|
+
try {
|
|
1048
|
+
return await new Promise((resolve, reject) => {
|
|
1049
|
+
const tx = db.transaction(STORE, mode);
|
|
1050
|
+
const req = work(tx.objectStore(STORE));
|
|
1051
|
+
tx.oncomplete = () => resolve(req.result);
|
|
1052
|
+
tx.onerror = () => reject(tx.error ?? /* @__PURE__ */ new Error(`${DB_NAME} failed`));
|
|
1053
|
+
tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error(`${DB_NAME} aborted`));
|
|
1054
|
+
});
|
|
1055
|
+
} finally {
|
|
1056
|
+
db.close();
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
function isEntry(value) {
|
|
1060
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1061
|
+
const entry = value;
|
|
1062
|
+
return typeof entry.slug === "string" && typeof entry.backend === "string" && typeof entry.configWas === "string";
|
|
1063
|
+
}
|
|
1064
|
+
/** This browser's drive moves, shared by its tabs. Empty without IndexedDB. */
|
|
1065
|
+
const placementIdb = {
|
|
1066
|
+
async list() {
|
|
1067
|
+
if (typeof indexedDB === "undefined") return [];
|
|
1068
|
+
return (await run("readonly", (store) => store.getAll())).filter(isEntry);
|
|
1069
|
+
},
|
|
1070
|
+
async put(entry) {
|
|
1071
|
+
await run("readwrite", (store) => store.put(entry));
|
|
1072
|
+
},
|
|
1073
|
+
async delete(slug) {
|
|
1074
|
+
await run("readwrite", (store) => store.delete(slug));
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
//#endregion
|
|
1078
|
+
//#region src/utils/reactor-worker-url.ts
|
|
1079
|
+
/**
|
|
1080
|
+
* Stable path of the prebuilt reactor SharedWorker bundle, relative to the
|
|
1081
|
+
* deploy base. `ph connect build` emits it next to `__vendor__/`; the dev
|
|
1082
|
+
* server serves it from the same path, building lazily on first request.
|
|
1083
|
+
*/
|
|
1084
|
+
const REACTOR_WORKER_BUNDLE_PATH = "__reactor_worker__/reactor.worker.js";
|
|
1085
|
+
/** Written beside the bundle by the prebuild; carries its `sourceDigest`. */
|
|
1086
|
+
const REACTOR_WORKER_META_PATH = "__reactor_worker__/worker-meta.json";
|
|
1087
|
+
/** `path` under the deploy base, absolute against `origin`. */
|
|
1088
|
+
function joinBase(baseUrl, path, origin) {
|
|
1089
|
+
return new URL(`${baseUrl}/${path}`.replace(/\/{2,}/g, "/"), origin);
|
|
1090
|
+
}
|
|
1091
|
+
/** The build's worker version, if it has one (dev serves unversioned URLs). */
|
|
1092
|
+
function reactorWorkerVersion() {
|
|
1093
|
+
return typeof PH_CONNECT_REACTOR_WORKER_VERSION !== "undefined" ? PH_CONNECT_REACTOR_WORKER_VERSION : void 0;
|
|
1094
|
+
}
|
|
1095
|
+
/** A `__reactor_worker__/` file's URL, versioned per build so no stale cache serves it. */
|
|
1096
|
+
function workerFileUrl(baseUrl, path, origin, version = reactorWorkerVersion()) {
|
|
1097
|
+
const url = joinBase(baseUrl, path, origin);
|
|
1098
|
+
if (version) url.searchParams.set("v", version);
|
|
1099
|
+
return url;
|
|
1100
|
+
}
|
|
1101
|
+
/** The bundle's URL under the deploy base, absolute against the page origin. */
|
|
1102
|
+
function packagedReactorWorkerUrl(baseUrl, origin) {
|
|
1103
|
+
return workerFileUrl(baseUrl, REACTOR_WORKER_BUNDLE_PATH, origin);
|
|
1104
|
+
}
|
|
1105
|
+
function isWorkerBundleResponse(probe) {
|
|
1106
|
+
return probe.ok && (probe.contentType ?? "").includes("javascript");
|
|
1107
|
+
}
|
|
1108
|
+
/** Null when the deployment serves no bundle metadata (SPA HTML, error status, bad JSON). */
|
|
1109
|
+
async function resolvePackagedReactorWorker(baseUrl) {
|
|
1110
|
+
const origin = window.location.origin;
|
|
1111
|
+
try {
|
|
1112
|
+
const res = await fetch(workerFileUrl(baseUrl, REACTOR_WORKER_META_PATH, origin), { cache: "no-cache" });
|
|
1113
|
+
if (!res.ok || !(res.headers.get("content-type") ?? "").includes("json")) return null;
|
|
1114
|
+
const meta = await res.json();
|
|
1115
|
+
if (typeof meta?.sourceDigest !== "string") return null;
|
|
1116
|
+
return {
|
|
1117
|
+
url: packagedReactorWorkerUrl(baseUrl, origin).href,
|
|
1118
|
+
sourceDigest: meta.sourceDigest
|
|
1119
|
+
};
|
|
1120
|
+
} catch {
|
|
1121
|
+
return null;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
function selectReactorWorkerSource({ packaged, bundle }) {
|
|
1125
|
+
if (bundle) return {
|
|
1126
|
+
kind: "bundle",
|
|
1127
|
+
url: bundle.url,
|
|
1128
|
+
digest: bundle.sourceDigest
|
|
1129
|
+
};
|
|
1130
|
+
return packaged ? { kind: "unavailable" } : { kind: "source" };
|
|
1131
|
+
}
|
|
1132
|
+
//#endregion
|
|
1133
|
+
//#region src/utils/worker-package-sources.ts
|
|
1134
|
+
/**
|
|
1135
|
+
* Where `ph connect build` publishes the prebuilt local-package model bundles
|
|
1136
|
+
* and the manifest naming them, next to the worker bundle itself.
|
|
1137
|
+
*/
|
|
1138
|
+
const WORKER_PACKAGES_DIR = "__reactor_worker__/packages/";
|
|
1139
|
+
const WORKER_PACKAGES_MANIFEST = `${WORKER_PACKAGES_DIR}manifest.json`;
|
|
1140
|
+
/**
|
|
1141
|
+
* The project's own models entry as the dev server serves it. Vite's
|
|
1142
|
+
* transform pipeline absolutizes its chunk imports and rewrites bare
|
|
1143
|
+
* specifiers to /node_modules/.vite/deps/ URLs, so the result is directly
|
|
1144
|
+
* importable from a worker - the dev server is the bundler.
|
|
1145
|
+
*/
|
|
1146
|
+
const DEV_PROJECT_MODELS_PATH = "dist/browser/document-models/index.js";
|
|
1147
|
+
/** Source name for the project's own package (vetra's local package). */
|
|
1148
|
+
const PROJECT_PACKAGE_SOURCE_NAME = "ph:project-package";
|
|
1149
|
+
async function probeJavaScript(url) {
|
|
1150
|
+
try {
|
|
1151
|
+
const res = await fetch(url, { method: "HEAD" });
|
|
1152
|
+
return isWorkerBundleResponse({
|
|
1153
|
+
ok: res.ok,
|
|
1154
|
+
contentType: res.headers.get("content-type")
|
|
1155
|
+
});
|
|
1156
|
+
} catch {
|
|
1157
|
+
return false;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
async function fetchManifest(baseUrl) {
|
|
1161
|
+
try {
|
|
1162
|
+
const res = await fetch(workerFileUrl(baseUrl, WORKER_PACKAGES_MANIFEST, window.location.origin));
|
|
1163
|
+
if (!res.ok) return [];
|
|
1164
|
+
const parsed = await res.json();
|
|
1165
|
+
if (!Array.isArray(parsed)) return [];
|
|
1166
|
+
return parsed.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.name === "string" && typeof entry.file === "string");
|
|
1167
|
+
} catch {
|
|
1168
|
+
return [];
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* The project's models source as served right now, with a cache-busting query
|
|
1173
|
+
* so a watch rebuild's re-registration imports the fresh file rather than the
|
|
1174
|
+
* worker's cached module. Null when the dev server does not serve one.
|
|
1175
|
+
*/
|
|
1176
|
+
async function resolveDevProjectSource(baseUrl) {
|
|
1177
|
+
const url = joinBase(baseUrl, DEV_PROJECT_MODELS_PATH, window.location.origin);
|
|
1178
|
+
if (!await probeJavaScript(url)) return null;
|
|
1179
|
+
url.searchParams.set("t", String(Date.now()));
|
|
1180
|
+
return {
|
|
1181
|
+
name: PROJECT_PACKAGE_SOURCE_NAME,
|
|
1182
|
+
url: url.href
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* URL-addressed packages the worker should load: the production manifest's
|
|
1187
|
+
* prebuilt bundles when deployed, plus the dev server's live project models
|
|
1188
|
+
* when present. Either list may be empty; both empty means this deployment
|
|
1189
|
+
* has no local packages (or predates the feature).
|
|
1190
|
+
*/
|
|
1191
|
+
async function resolveLocalPackageSources(baseUrl) {
|
|
1192
|
+
const [manifest, devProject] = await Promise.all([fetchManifest(baseUrl), resolveDevProjectSource(baseUrl)]);
|
|
1193
|
+
const sources = manifest.map((entry) => ({
|
|
1194
|
+
name: entry.name,
|
|
1195
|
+
version: entry.version,
|
|
1196
|
+
url: workerFileUrl(baseUrl, `${WORKER_PACKAGES_DIR}${entry.file}`, window.location.origin).href
|
|
1197
|
+
}));
|
|
1198
|
+
if (devProject) sources.push(devProject);
|
|
1199
|
+
return sources;
|
|
1200
|
+
}
|
|
1201
|
+
/** Calls `onChange` only when the local package is replaced (an HMR rebuild), not on every package notification. */
|
|
1202
|
+
function subscribeLocalPackageChanges(manager, onChange) {
|
|
1203
|
+
let last = manager.localPackage;
|
|
1204
|
+
return manager.subscribe(() => {
|
|
1205
|
+
const current = manager.localPackage;
|
|
1206
|
+
if (current === last) return;
|
|
1207
|
+
last = current;
|
|
1208
|
+
onChange();
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
//#endregion
|
|
1212
|
+
//#region src/utils/worker-registry-packages.ts
|
|
1213
|
+
/** The spec the worker loads a registry package by: `name@version`, or the bare name. */
|
|
1214
|
+
function registryPackageSpec(pkg) {
|
|
1215
|
+
return pkg.version ? `${pkg.name}@${pkg.version}` : pkg.name;
|
|
1216
|
+
}
|
|
1217
|
+
/** Calls `onChange` with the specs of registry packages added or re-versioned since subscribing. */
|
|
1218
|
+
function subscribeRegistryPackageChanges(manager, onChange) {
|
|
1219
|
+
const sent = new Map(manager.getRegistryPackages().map((pkg) => [pkg.name, pkg.version]));
|
|
1220
|
+
return manager.subscribe(() => {
|
|
1221
|
+
const changed = manager.getRegistryPackages().filter((pkg) => !sent.has(pkg.name) || sent.get(pkg.name) !== pkg.version);
|
|
1222
|
+
if (changed.length === 0) return;
|
|
1223
|
+
for (const pkg of changed) sent.set(pkg.name, pkg.version);
|
|
1224
|
+
onChange(changed.map(registryPackageSpec));
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
function typeOf(module) {
|
|
1228
|
+
return module.documentModel.global.id;
|
|
1229
|
+
}
|
|
1230
|
+
function keyOf(module) {
|
|
1231
|
+
return `${typeOf(module)}@${module.version ?? 1}`;
|
|
1232
|
+
}
|
|
1233
|
+
/** Adds the models the registry lacks, and replaces each type whose modules a package update swapped. */
|
|
1234
|
+
function syncRegistryModels(registry, models) {
|
|
1235
|
+
const current = new Map(registry.getAllModules().map((m) => [keyOf(m), m]));
|
|
1236
|
+
const replaced = new Set(models.filter((m) => current.has(keyOf(m)) && current.get(keyOf(m)) !== m).map(typeOf));
|
|
1237
|
+
if (replaced.size > 0) registry.unregisterModules(...replaced);
|
|
1238
|
+
const fresh = models.filter((m) => replaced.has(typeOf(m)) || !current.has(keyOf(m)));
|
|
1239
|
+
if (fresh.length > 0) registry.registerModules(...fresh);
|
|
1240
|
+
}
|
|
1241
|
+
//#endregion
|
|
1242
|
+
//#region src/store/processor-host-module.ts
|
|
1243
|
+
var NullAttachmentService = class {
|
|
1244
|
+
reserve() {
|
|
1245
|
+
return Promise.reject(/* @__PURE__ */ new Error("NullAttachmentService: no attachment service configured"));
|
|
1246
|
+
}
|
|
1247
|
+
stat() {
|
|
1248
|
+
return Promise.reject(/* @__PURE__ */ new Error("NullAttachmentService: no attachment service configured"));
|
|
1249
|
+
}
|
|
1250
|
+
get() {
|
|
1251
|
+
return Promise.reject(/* @__PURE__ */ new Error("NullAttachmentService: no attachment service configured"));
|
|
1252
|
+
}
|
|
1253
|
+
getDownloadTarget() {
|
|
1254
|
+
return Promise.reject(/* @__PURE__ */ new Error("NullAttachmentService: no attachment service configured"));
|
|
1255
|
+
}
|
|
1256
|
+
};
|
|
1257
|
+
/**
|
|
1258
|
+
* Builds the tab's processor host module over the reactor client module:
|
|
1259
|
+
* processors read through its read half and `dispatch` writes through its
|
|
1260
|
+
* write half; the facade stays on `client` for processors not yet moved.
|
|
1261
|
+
*/
|
|
1262
|
+
async function createProcessorHostModule(clients, readModels, attachmentService) {
|
|
1263
|
+
try {
|
|
1264
|
+
const { pgLite, relationalDb } = await getDb();
|
|
1265
|
+
setPGliteDB({
|
|
1266
|
+
db: pgLite,
|
|
1267
|
+
isLoading: false,
|
|
1268
|
+
error: null
|
|
1269
|
+
});
|
|
1270
|
+
const { store: analyticsStore } = await createAnalyticsStore({ pgLite });
|
|
1271
|
+
return {
|
|
1272
|
+
...createReactorHostModuleBase({
|
|
1273
|
+
client: clients.client,
|
|
1274
|
+
read: clients.read,
|
|
1275
|
+
write: clients.write,
|
|
1276
|
+
readModels,
|
|
1277
|
+
relationalDb,
|
|
1278
|
+
analyticsStore,
|
|
1279
|
+
processorApp: "connect"
|
|
1280
|
+
}),
|
|
1281
|
+
attachments: createAttachmentClient(attachmentService ?? new NullAttachmentService())
|
|
1282
|
+
};
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
console.error(`Failed to initialize processor host module:`);
|
|
1285
|
+
console.error(error);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
//#endregion
|
|
1289
|
+
//#region src/store/reactor.ts
|
|
1290
|
+
/**
|
|
1291
|
+
* Subscribe to ph-clint's `/__packages` SSE channel; each `packages-changed`
|
|
1292
|
+
* event sends the full live list, which we diff to add/remove packages.
|
|
1293
|
+
* Best-effort: no-ops when the endpoint is absent (e.g. vite dev).
|
|
1294
|
+
*/
|
|
1295
|
+
function subscribeToPackagesChannel(packageManager) {
|
|
1296
|
+
if (typeof window === "undefined" || typeof EventSource === "undefined") return;
|
|
1297
|
+
let source;
|
|
1298
|
+
try {
|
|
1299
|
+
source = new EventSource("/__packages");
|
|
1300
|
+
} catch (err) {
|
|
1301
|
+
console.debug("[Connect] /__packages subscribe failed:", err);
|
|
1302
|
+
return;
|
|
1303
|
+
}
|
|
1304
|
+
let firstEvent = true;
|
|
1305
|
+
source.addEventListener("packages-changed", (event) => {
|
|
1306
|
+
try {
|
|
1307
|
+
const payload = JSON.parse(event.data);
|
|
1308
|
+
if (!Array.isArray(payload.packages)) return;
|
|
1309
|
+
const next = payload.packages.filter((p) => typeof p === "string");
|
|
1310
|
+
const parseBare = (spec) => {
|
|
1311
|
+
const at = spec.startsWith("@") ? spec.lastIndexOf("@") : spec.indexOf("@");
|
|
1312
|
+
if (at > 0) return {
|
|
1313
|
+
bareName: spec.slice(0, at),
|
|
1314
|
+
version: spec.slice(at + 1)
|
|
1315
|
+
};
|
|
1316
|
+
return { bareName: spec };
|
|
1317
|
+
};
|
|
1318
|
+
const currentByName = new Map(packageManager.getRegistryPackages().map(({ name, version }) => [name, version]));
|
|
1319
|
+
const nextByName = /* @__PURE__ */ new Map();
|
|
1320
|
+
for (const spec of next) {
|
|
1321
|
+
const { bareName, version } = parseBare(spec);
|
|
1322
|
+
nextByName.set(bareName, version);
|
|
1323
|
+
}
|
|
1324
|
+
const isFirst = firstEvent;
|
|
1325
|
+
firstEvent = false;
|
|
1326
|
+
for (const name of currentByName.keys()) if (!nextByName.has(name)) {
|
|
1327
|
+
packageManager.removePackage(name);
|
|
1328
|
+
if (!isFirst) toast(`Removed package ${name}`, { type: "connect-deleted" });
|
|
1329
|
+
}
|
|
1330
|
+
for (const spec of next) {
|
|
1331
|
+
const { bareName, version } = parseBare(spec);
|
|
1332
|
+
const currentVersion = currentByName.get(bareName);
|
|
1333
|
+
const isKnown = currentByName.has(bareName);
|
|
1334
|
+
if (isKnown && (!version || !currentVersion || version === currentVersion)) continue;
|
|
1335
|
+
const isUpdate = isKnown;
|
|
1336
|
+
Promise.resolve(packageManager.addPackage(spec)).then((result) => {
|
|
1337
|
+
if (result.type === "error") {
|
|
1338
|
+
console.error(`[Connect] /__packages addPackage(${spec}) failed:`, result.error);
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
if (isFirst) return;
|
|
1342
|
+
const name = result.package.manifest.name;
|
|
1343
|
+
toast(isUpdate ? `Updated package ${name}` : `Installed package ${name}`, { type: "connect-success" });
|
|
1344
|
+
}, (err) => {
|
|
1345
|
+
console.error(`[Connect] /__packages addPackage(${spec}) threw:`, err);
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
} catch (err) {
|
|
1349
|
+
console.error("[Connect] /__packages event parse failed:", err);
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
source.addEventListener("error", () => {});
|
|
1353
|
+
}
|
|
1354
|
+
async function clearReactorStorage() {
|
|
1355
|
+
const module = getPHStore()?.reactorClientModule;
|
|
1356
|
+
if (module?.kind === "worker") {
|
|
1357
|
+
await module.adminClient.clearStorage();
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
if (module?.kind === "browser") {
|
|
1361
|
+
const reactorModule = module.reactorModule;
|
|
1362
|
+
await closeWithin(reactorModule?.groupCommitStorage ?? reactorModule?.pg);
|
|
1363
|
+
}
|
|
1364
|
+
if (REACTOR_STORE_IN_MEMORY) return;
|
|
1365
|
+
const targets = (await indexedDB.databases()).map((d) => d.name).filter((n) => !!n && !n.startsWith("ph-pglite-backup::") && /pglite|reactor/i.test(n));
|
|
1366
|
+
await Promise.all(targets.map((name) => new Promise((resolve) => {
|
|
1367
|
+
const req = indexedDB.deleteDatabase(name);
|
|
1368
|
+
req.onsuccess = req.onerror = req.onblocked = () => resolve();
|
|
1369
|
+
})));
|
|
1370
|
+
}
|
|
1371
|
+
async function createReactor(localPackage, store) {
|
|
1372
|
+
if (store.loading) return;
|
|
1373
|
+
store.loading = true;
|
|
1374
|
+
addPHEventHandlers();
|
|
1375
|
+
setPHToast(toast);
|
|
1376
|
+
store.aiTools = () => import("./ai-tools-D_q-Whju.js").then((tools) => tools.getConnectReactorTools());
|
|
1377
|
+
const features = await initFeatureFlags();
|
|
1378
|
+
logger.info("Features: @features", JSON.stringify(Object.fromEntries(features), null, 2));
|
|
1379
|
+
const renownChainId = getRuntimeConfig().connect.renown?.chainId;
|
|
1380
|
+
const keyPairStorage = await BrowserKeyStorage.create();
|
|
1381
|
+
const cryptoBuilder = new RenownCryptoBuilder().withKeyPairStorage(keyPairStorage);
|
|
1382
|
+
if (renownChainId !== void 0) cryptoBuilder.withChainId(renownChainId);
|
|
1383
|
+
const renownCrypto = await cryptoBuilder.build();
|
|
1384
|
+
const renown = await new RenownBuilder("connect", {
|
|
1385
|
+
basename: getRuntimeConfig().connect.renown?.namespace ?? phGlobalConfig.routerBasename,
|
|
1386
|
+
baseUrl: phGlobalConfig.renownUrl,
|
|
1387
|
+
switchboardUrl: phGlobalConfig.switchboardUrl,
|
|
1388
|
+
chainId: renownChainId
|
|
1389
|
+
}).withCrypto(renownCrypto).build();
|
|
1390
|
+
const runtimeConfig = getRuntimeConfig();
|
|
1391
|
+
const packageManager = new BrowserPackageManager(phGlobalConfig.routerBasename ?? "", runtimeConfig.packageRegistryUrl ?? null);
|
|
1392
|
+
setVetraPackageManager(packageManager);
|
|
1393
|
+
const releaseRoutes = holdConnectRoutes();
|
|
1394
|
+
await packageManager.init(localPackage, runtimeConfig.localPackage?.version, phGlobalConfig.studioMode, connectConfig.workflowsEnabled, getConnectPluginUi().commonEditors);
|
|
1395
|
+
const { default: registerBundledPackages } = await import("ph-bundled-packages-virtual");
|
|
1396
|
+
registerBundledPackages(packageManager);
|
|
1397
|
+
const remotePackages = runtimeConfig.packages.filter((p) => p.provider !== "local").map((p) => p.version ? `${p.packageName}@${p.version}` : p.packageName);
|
|
1398
|
+
(await packageManager.addPackages(remotePackages).finally(releaseRoutes)).map((r) => {
|
|
1399
|
+
if (r.type === "error") console.error(r.error);
|
|
1400
|
+
});
|
|
1401
|
+
if (runtimeConfig.connect?.packages?.liveReload) subscribeToPackagesChannel(packageManager);
|
|
1402
|
+
const loadedDocumentModels = () => packageManager.packages.flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);
|
|
1403
|
+
const documentModelModules = loadedDocumentModels();
|
|
1404
|
+
const upgradeManifests = packageManager.packages.flatMap((pkg) => pkg.upgradeManifests).filter((manifest, index, manifests) => manifest !== void 0 && manifests.findIndex((m) => m && m.documentType === manifest.documentType) === index);
|
|
1405
|
+
const discoveryService = packageManager.cdnUrl !== null ? new PackageDiscoveryService(packageManager, new RegistryClient(packageManager.cdnUrl), {
|
|
1406
|
+
mode: "immediate",
|
|
1407
|
+
storageKey: phGlobalConfig.routerBasename ?? ""
|
|
1408
|
+
}) : new NoRegistryDiscoveryService(packageManager);
|
|
1409
|
+
setPackageDiscoveryService(discoveryService);
|
|
1410
|
+
const reactorFeatureFlags = runtimeConfig.connect?.reactor?.featureFlags ?? {};
|
|
1411
|
+
const enabledReactorFlags = Object.entries(reactorFeatureFlags).filter(([, enabled]) => enabled).map(([name]) => name);
|
|
1412
|
+
if (enabledReactorFlags.length > 0) logger.info(`Reactor feature flags: ${enabledReactorFlags.join(", ")}`);
|
|
1413
|
+
const createSignaturePolicy = runtimeConfig.connect?.reactor?.createSignaturePolicy;
|
|
1414
|
+
const unsupportedStoredDocuments = runtimeConfig.connect?.reactor?.unsupportedStoredDocuments;
|
|
1415
|
+
const renownEndpoints = {
|
|
1416
|
+
renownUrl: phGlobalConfig.renownUrl,
|
|
1417
|
+
switchboardUrl: phGlobalConfig.switchboardUrl
|
|
1418
|
+
};
|
|
1419
|
+
const plan = planReactorClient();
|
|
1420
|
+
const { multiReactor } = plan;
|
|
1421
|
+
const routesDrives = plan.mode === "router";
|
|
1422
|
+
const placements = routesDrives || plan.mode === "remote" ? await DrivePlacements.load(switchboardDrives(runtimeConfig.connect), routesDrives ? placementIdb : NO_MOVES, placementSync()) : void 0;
|
|
1423
|
+
let routerReady = () => {};
|
|
1424
|
+
const routerBuilt = new Promise((resolve) => {
|
|
1425
|
+
routerReady = resolve;
|
|
1426
|
+
});
|
|
1427
|
+
const placementsResolved = resolveSwitchboardDrives(placements?.drives ?? [], (url) => fetchDriveInfo(url, async () => renown.user ? renown.getBearerToken({ expiresIn: 10 }) : void 0), { findServed: async (drive) => {
|
|
1428
|
+
const router = await routerBuilt;
|
|
1429
|
+
return router ? findServedDrive(router, drive) : void 0;
|
|
1430
|
+
} });
|
|
1431
|
+
const remoteBackends = runtimeConfig.connect.instance?.remoteBackends ?? [];
|
|
1432
|
+
const routerSettings = runtimeConfig.connect.instance?.router;
|
|
1433
|
+
const remoteDriveUrl = remoteBackends.at(0)?.url ?? phGlobalConfig.defaultDrivesUrl;
|
|
1434
|
+
const localReactor = async ({ localAsWorker }) => {
|
|
1435
|
+
if (!localAsWorker) return createBrowserReactor(documentModelModules, upgradeManifests, renown, reactorFeatureFlags, discoveryService, createSignaturePolicy, renownEndpoints, unsupportedStoredDocuments, multiReactor);
|
|
1436
|
+
const packageSpecs = packageManager.getRegistryPackages().map(registryPackageSpec);
|
|
1437
|
+
const registryClient = new RegistryClient(packageManager.cdnUrl ?? "");
|
|
1438
|
+
const documentModelLoader = { async load(documentType) {
|
|
1439
|
+
const names = packageManager.cdnUrl ? await registryClient.getPackagesByDocumentType(documentType) : [];
|
|
1440
|
+
for (const name of names) {
|
|
1441
|
+
const result = await packageManager.addPackage(name);
|
|
1442
|
+
if (result.type === "error") throw new Error(`Failed to install package "${name}" for document model: ${documentType}`, { cause: result.error });
|
|
1443
|
+
}
|
|
1444
|
+
const module = packageManager.packages.flatMap((p) => p.documentModels).find((m) => m.documentModel.global.id === documentType);
|
|
1445
|
+
if (!module) throw new Error(names.length > 0 ? `Installed [${names.join(", ")}] but document model not available: ${documentType}` : `No package found for document model: ${documentType} (cdnUrl: ${packageManager.cdnUrl ?? "none"})`);
|
|
1446
|
+
return module;
|
|
1447
|
+
} };
|
|
1448
|
+
const [sharedDeps, packagedWorker, packageSources] = await Promise.all([
|
|
1449
|
+
getSharedDeps(),
|
|
1450
|
+
resolvePackagedReactorWorker(import.meta.env.BASE_URL),
|
|
1451
|
+
resolveLocalPackageSources(import.meta.env.BASE_URL)
|
|
1452
|
+
]);
|
|
1453
|
+
const workerSource = selectReactorWorkerSource({
|
|
1454
|
+
packaged: isPackagedConnectDist(),
|
|
1455
|
+
bundle: packagedWorker
|
|
1456
|
+
});
|
|
1457
|
+
if (workerSource.kind === "unavailable") {
|
|
1458
|
+
store.loading = false;
|
|
1459
|
+
throw new Error("reactorWorker is enabled but this deployment serves no reactor worker bundle (__reactor_worker__/); rebuild with ph connect build or open with ?reactorWorker=false");
|
|
1460
|
+
}
|
|
1461
|
+
const workerClient = createWorkerReactorClientModule({
|
|
1462
|
+
workerUrl: workerSource.kind === "bundle" ? workerSource.url : void 0,
|
|
1463
|
+
workerDigest: workerSource.kind === "bundle" ? workerSource.digest : void 0,
|
|
1464
|
+
packageSources,
|
|
1465
|
+
namespace: REACTOR_INSTANCE_NAMESPACE,
|
|
1466
|
+
relationalNamespace: RELATIONAL_PGLITE_NAME,
|
|
1467
|
+
cdnUrl: packageManager.cdnUrl ?? "",
|
|
1468
|
+
packageSpecs,
|
|
1469
|
+
sharedImports: sharedDeps?.imports ?? pageSharedImports(),
|
|
1470
|
+
studioMode: phGlobalConfig.studioMode,
|
|
1471
|
+
workflowsEnabled: connectConfig.workflowsEnabled,
|
|
1472
|
+
renownChainId,
|
|
1473
|
+
featureFlags: reactorFeatureFlags,
|
|
1474
|
+
multiReactor,
|
|
1475
|
+
storeInMemory: REACTOR_STORE_IN_MEMORY,
|
|
1476
|
+
createSignaturePolicy,
|
|
1477
|
+
unsupportedStoredDocuments,
|
|
1478
|
+
renownEndpoints,
|
|
1479
|
+
documentModelModules,
|
|
1480
|
+
upgradeManifests,
|
|
1481
|
+
documentModelLoader,
|
|
1482
|
+
renown,
|
|
1483
|
+
onReload: (reason) => {
|
|
1484
|
+
logger.warn("Reactor worker requested reload: @reason", reason);
|
|
1485
|
+
reloadForWorker(reason, () => window.location.reload());
|
|
1486
|
+
}
|
|
1487
|
+
});
|
|
1488
|
+
const { registerPackages } = workerClient.reactorClientModule;
|
|
1489
|
+
subscribeLocalPackageChanges(packageManager, () => {
|
|
1490
|
+
(async () => {
|
|
1491
|
+
const source = await resolveDevProjectSource(import.meta.env.BASE_URL);
|
|
1492
|
+
if (!source) return;
|
|
1493
|
+
try {
|
|
1494
|
+
await registerPackages([source]);
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
logger.error("Failed to re-register project models in the reactor worker: @error", error);
|
|
1497
|
+
}
|
|
1498
|
+
})();
|
|
1499
|
+
});
|
|
1500
|
+
subscribeRegistryPackageChanges(packageManager, (specs) => {
|
|
1501
|
+
syncRegistryModels(workerClient.reactorClientModule.reactorModule.documentModelRegistry, loadedDocumentModels());
|
|
1502
|
+
registerPackages([], specs).catch((error) => {
|
|
1503
|
+
logger.error("Failed to load packages in the reactor worker: @error", error);
|
|
1504
|
+
});
|
|
1505
|
+
});
|
|
1506
|
+
try {
|
|
1507
|
+
await startupOwningStores((options) => workerClient.syncManagerProxy.startup(options), [REACTOR_INSTANCE_NAMESPACE, RELATIONAL_PGLITE_NAME]);
|
|
1508
|
+
} catch (error) {
|
|
1509
|
+
store.loading = false;
|
|
1510
|
+
logger.error("Reactor worker failed to start: @error", error);
|
|
1511
|
+
throw error;
|
|
1512
|
+
}
|
|
1513
|
+
return workerClient.reactorClientModule;
|
|
1514
|
+
};
|
|
1515
|
+
const { module: reactorClientModule, client: appReactorClient, router } = await createAppReactorClient({
|
|
1516
|
+
plan,
|
|
1517
|
+
localReactor,
|
|
1518
|
+
remoteDriveUrl,
|
|
1519
|
+
remoteBackends,
|
|
1520
|
+
collections: routerSettings?.newDrives ? localDrivePlacements(getDefaultDrives(runtimeConfig)) : void 0,
|
|
1521
|
+
router: routerSettings,
|
|
1522
|
+
signer: renown.signer,
|
|
1523
|
+
documentModelModules: loadedDocumentModels
|
|
1524
|
+
});
|
|
1525
|
+
routerReady(router);
|
|
1526
|
+
const drives = await getAppDrives(appReactorClient, reactorClientModule?.client ?? appReactorClient);
|
|
1527
|
+
await login(void 0, renown);
|
|
1528
|
+
const documentCache = new DocumentCache(appReactorClient);
|
|
1529
|
+
const basePath = phGlobalConfig.basePath ?? "/";
|
|
1530
|
+
const routerBasename = phGlobalConfig.routerBasename ?? "/";
|
|
1531
|
+
const mergedGlobalConfig = buildPHGlobalConfig(basePath, routerBasename, runtimeConfig.connect ?? {});
|
|
1532
|
+
setDefaultPHGlobalConfig(mergedGlobalConfig);
|
|
1533
|
+
setReactorClientModule(reactorClientModule);
|
|
1534
|
+
setReactorClient(appReactorClient);
|
|
1535
|
+
setSwitchboards(createSwitchboardDirectory({
|
|
1536
|
+
remoteBackends,
|
|
1537
|
+
router,
|
|
1538
|
+
syncManager: () => reactorClientModule?.reactorModule?.syncModule?.syncManager
|
|
1539
|
+
}));
|
|
1540
|
+
const switchboardOrigin = attachmentsOrigin(remoteBackends.at(0)?.url, phGlobalConfig.defaultDrivesUrl);
|
|
1541
|
+
if (switchboardOrigin) {
|
|
1542
|
+
const attachmentJwtHandler = async (_url) => {
|
|
1543
|
+
if (!renown.user) return void 0;
|
|
1544
|
+
return renown.getBearerToken({ expiresIn: 10 });
|
|
1545
|
+
};
|
|
1546
|
+
const attachmentServiceAt = (remoteUrl) => createRemoteAttachmentService({
|
|
1547
|
+
remoteUrl,
|
|
1548
|
+
jwtHandler: attachmentJwtHandler,
|
|
1549
|
+
uploadTransport: createXhrUploadTransport()
|
|
1550
|
+
});
|
|
1551
|
+
const fallback = attachmentServiceAt(switchboardOrigin);
|
|
1552
|
+
setAttachmentService(router && remoteBackends.length > 1 ? routeAttachments(router, remoteBackends, fallback, (base) => base === switchboardOrigin ? fallback : attachmentServiceAt(base)) : fallback);
|
|
1553
|
+
}
|
|
1554
|
+
setDocumentCache(documentCache);
|
|
1555
|
+
setRenown(renown);
|
|
1556
|
+
setFeatures(features);
|
|
1557
|
+
const addsDrives = plan.mode !== "remote";
|
|
1558
|
+
const defaultDrivesConfig = getDefaultDrives(runtimeConfig).filter((drive) => !routesDrives || (placements && "url" in drive ? placements.keepsCopy(drive.url) : keepsLocalCopy(drive)));
|
|
1559
|
+
if (addsDrives && defaultDrivesConfig.length > 0) trackDriveArrival(addDefaultDrivesThroughSignIn(renown, defaultDrivesConfig)).catch((error) => console.error("Failed to add default drives:", error));
|
|
1560
|
+
if (placements && placements.drives.length > 0) placementsResolved.then((resolved) => attachPlacements(placements, resolved, router, routesDrives)).catch((error) => logger.error("Failed to place switchboard drives: @error", error));
|
|
1561
|
+
if (routesDrives && placements) {
|
|
1562
|
+
setDrivePlacements(placements);
|
|
1563
|
+
reactorClientModule?.reactorModule?.eventBus.subscribe(SYNC_REMOTES_CHANGED_EVENT, () => {
|
|
1564
|
+
placements.reload().then((changed) => changed ? relistAppDrives() : void 0).catch((error) => logger.error("Failed to apply another tab's drive move: @error", error));
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
const remoteUrl = getDriveUrl();
|
|
1568
|
+
if (remoteUrl && !addsDrives) logger.warn("The remote reactor client ignores ?driveUrl=@url", remoteUrl);
|
|
1569
|
+
else if (remoteUrl) trackDriveArrival(addRemoteDrive(remoteUrl, void 0).then((driveId) => untilDriveListed(store, driveId))).catch((error) => console.error(`Failed to add remote drive from ${remoteUrl}:`, error));
|
|
1570
|
+
setDrives(drives);
|
|
1571
|
+
const reactorClient = appReactorClient;
|
|
1572
|
+
const onDriveChange = createDriveChangeHandler(reactorClient.read, { onError: (e) => logger.error("@error", e) });
|
|
1573
|
+
for (const driveType of DRIVE_DOCUMENT_TYPES) reactorClient.read.subscribe({ type: driveType }, (event) => {
|
|
1574
|
+
logger.verbose("ReactorClient subscription event: @event", event);
|
|
1575
|
+
onDriveChange(event);
|
|
1576
|
+
});
|
|
1577
|
+
reactorClient.read.subscribe({}, (event) => {
|
|
1578
|
+
closeDeletedSelection(event, {
|
|
1579
|
+
selectedDriveId: store.selectedDriveId,
|
|
1580
|
+
selectedNodeId: store.selectedNodeId,
|
|
1581
|
+
closeDrive: () => setSelectedDrive(void 0),
|
|
1582
|
+
closeNode: () => setSelectedNode(void 0),
|
|
1583
|
+
notify: (message) => toast(message)
|
|
1584
|
+
});
|
|
1585
|
+
});
|
|
1586
|
+
await refreshAppDrives(appReactorClient, reactorClientModule?.client ?? appReactorClient);
|
|
1587
|
+
const packagesWithProcessorFactories = packageManager.packages.filter((pkg) => pkg.processorFactory !== void 0);
|
|
1588
|
+
const reactorModule = reactorClientModule?.kind === "browser" ? reactorClientModule.reactorModule : void 0;
|
|
1589
|
+
if (packagesWithProcessorFactories.length > 0 && !reactorClientModule) logger.info("Remote reactor client: @count processor factory/ies run on the Switchboard, not in the tab", packagesWithProcessorFactories.length);
|
|
1590
|
+
else if (packagesWithProcessorFactories.length > 0 && !reactorModule) for (const pkg of packagesWithProcessorFactories) logger.warn("Skipping processor factory @name: processors are not supported on the worker reactor path yet", pkg.manifest.name);
|
|
1591
|
+
else if (packagesWithProcessorFactories.length > 0 && reactorModule && reactorClientModule) {
|
|
1592
|
+
const readModels = reactorModule.readModelCoordinator.readModels;
|
|
1593
|
+
const processorHostModule = await createProcessorHostModule(reactorClientModule, readModels, store.attachmentService);
|
|
1594
|
+
if (processorHostModule !== void 0) await Promise.all(packagesWithProcessorFactories.map(async (pkg) => {
|
|
1595
|
+
const { manifest, processorFactory } = pkg;
|
|
1596
|
+
const name = manifest.name;
|
|
1597
|
+
const id = manifest.name;
|
|
1598
|
+
const version = packageManager.getPackageVersion(name);
|
|
1599
|
+
const label = version ? `${name}@${version}` : name;
|
|
1600
|
+
logger.info("Loading processor factory: @label", label);
|
|
1601
|
+
try {
|
|
1602
|
+
const factory = await processorFactory?.(processorHostModule);
|
|
1603
|
+
if (!factory) return;
|
|
1604
|
+
await reactorModule.processorManager.registerFactory(id, factory);
|
|
1605
|
+
} catch (error) {
|
|
1606
|
+
logger.error(`Error registering processor: @label`, label);
|
|
1607
|
+
logger.error("@error", error);
|
|
1608
|
+
}
|
|
1609
|
+
}));
|
|
1610
|
+
}
|
|
1611
|
+
store.loading = false;
|
|
1612
|
+
}
|
|
1613
|
+
/** Remote mode: drives open on the switchboard, and nothing is moved. */
|
|
1614
|
+
const NO_MOVES = {
|
|
1615
|
+
list: () => Promise.resolve([]),
|
|
1616
|
+
put: () => Promise.resolve(),
|
|
1617
|
+
delete: () => Promise.resolve()
|
|
1618
|
+
};
|
|
1619
|
+
/** Runs after boot so a hung switchboard can't hold it; the relist shows placed drives from their switchboard. */
|
|
1620
|
+
async function attachPlacements(placements, resolved, router, syncsDrives) {
|
|
1621
|
+
const kept = await placements.start(router, resolved, syncsDrives);
|
|
1622
|
+
for (const drive of kept) {
|
|
1623
|
+
if (!drive.id) continue;
|
|
1624
|
+
trackDriveArrival(addRemoteDrive(servedUrl(drive), drive.id)).catch((error) => logger.error("Failed to keep a copy of @slug: @error", drive.slug, error));
|
|
1625
|
+
}
|
|
1626
|
+
if (router) await relistAppDrives();
|
|
1627
|
+
}
|
|
1628
|
+
/** Each switchboard's attachments by its backend; anything else uses `fallback`. */
|
|
1629
|
+
function routeAttachments(router, remoteBackends, fallback, serviceAt) {
|
|
1630
|
+
const byBackend = /* @__PURE__ */ new Map();
|
|
1631
|
+
for (const { name, url } of remoteBackends) {
|
|
1632
|
+
const base = switchboardOfDrive(url)?.base;
|
|
1633
|
+
if (base) byBackend.set(name, serviceAt(base));
|
|
1634
|
+
}
|
|
1635
|
+
return new RoutingAttachmentService((documentId, signal) => router.locate(documentId, signal), byBackend, fallback);
|
|
1636
|
+
}
|
|
1637
|
+
function getDriveUrl() {
|
|
1638
|
+
const driveUrl = new URLSearchParams(window.location.search).get("driveUrl");
|
|
1639
|
+
return driveUrl ? decodeURIComponent(driveUrl) : void 0;
|
|
1640
|
+
}
|
|
1641
|
+
/** The first remote backend's switchboard, else the first default drive's origin. */
|
|
1642
|
+
function attachmentsOrigin(remoteBackendUrl, defaultDrivesUrl) {
|
|
1643
|
+
const base = remoteBackendUrl && switchboardOfDrive(remoteBackendUrl)?.base;
|
|
1644
|
+
if (base) return base;
|
|
1645
|
+
if (!defaultDrivesUrl) return void 0;
|
|
1646
|
+
try {
|
|
1647
|
+
return new URL(defaultDrivesUrl).origin;
|
|
1648
|
+
} catch {
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
//#endregion
|
|
1653
|
+
export { createReactor as n, clearReactorStorage as t };
|
|
1654
|
+
|
|
1655
|
+
//# sourceMappingURL=reactor-Drpw-sgc.js.map
|
|
1656
|
+
//# debugId=9588eb8d-0c5c-508e-a6bf-c7fbd8b9e812
|