@powerhousedao/connect 6.2.3-dev.67 → 6.2.3-dev.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/{ClearStorageModal-_03VgDb5.js → ClearStorageModal-tBOi6FhW.js} +4 -4
  2. package/dist/{ClearStorageModal-_03VgDb5.js.map → ClearStorageModal-tBOi6FhW.js.map} +1 -1
  3. package/dist/{DebugSettingsModal-CGScJ_r2.js → DebugSettingsModal-BBGE669G.js} +4 -4
  4. package/dist/{DebugSettingsModal-CGScJ_r2.js.map → DebugSettingsModal-BBGE669G.js.map} +1 -1
  5. package/dist/{InspectorModal-DA_TGmM6.js → InspectorModal-ClrhUznk.js} +4 -4
  6. package/dist/{InspectorModal-DA_TGmM6.js.map → InspectorModal-ClrhUznk.js.map} +1 -1
  7. package/dist/app-loader-BImUNqTK.js +4 -0
  8. package/dist/{app-loader-CEN_4I3I.js → app-loader-Ctuh_wUx.js} +4 -4
  9. package/dist/{app-loader-CEN_4I3I.js.map → app-loader-Ctuh_wUx.js.map} +1 -1
  10. package/dist/{boot-JTGLJtmJ.js → boot-BhAEKTca.js} +4 -4
  11. package/dist/{boot-JTGLJtmJ.js.map → boot-BhAEKTca.js.map} +1 -1
  12. package/dist/{build-info-DkY9PU7c.js → build-info-D1Gpyvek.js} +5 -5
  13. package/dist/{build-info-DkY9PU7c.js.map → build-info-D1Gpyvek.js.map} +1 -1
  14. package/dist/{components-2wvJ3_Ho.js → components-Dan37g4U.js} +4 -4
  15. package/dist/{components-2wvJ3_Ho.js.map → components-Dan37g4U.js.map} +1 -1
  16. package/dist/generic.js +1 -1
  17. package/dist/{load-CCCHqC0d.js → load-4y9lctgm.js} +6 -6
  18. package/dist/{load-CCCHqC0d.js.map → load-4y9lctgm.js.map} +1 -1
  19. package/dist/{load-runtime-config-Dhy-b5wT.js → load-runtime-config-BvMss48m.js} +4 -4
  20. package/dist/{load-runtime-config-Dhy-b5wT.js.map → load-runtime-config-BvMss48m.js.map} +1 -1
  21. package/dist/main.js +2 -2
  22. package/dist/{plugins-B9VBgzio.js → plugins-Yr4sDuPn.js} +4 -4
  23. package/dist/{plugins-B9VBgzio.js.map → plugins-Yr4sDuPn.js.map} +1 -1
  24. package/dist/prerender.js +1 -1
  25. package/dist/{reactor-BmI-D8O-.js → reactor-CHUe2JgO.js} +4 -4
  26. package/dist/{reactor-BmI-D8O-.js.map → reactor-CHUe2JgO.js.map} +1 -1
  27. package/dist/{settings-DjQfTrBe.js → settings-C1Pb6U4P.js} +5 -5
  28. package/dist/{settings-DjQfTrBe.js.map → settings-C1Pb6U4P.js.map} +1 -1
  29. package/dist/{settings-tabs-iTlo2pYz.js → settings-tabs-CyzuB1lF.js} +4 -4
  30. package/dist/{settings-tabs-iTlo2pYz.js.map → settings-tabs-CyzuB1lF.js.map} +1 -1
  31. package/dist/start-connect.js +2 -2
  32. package/dist/{ui-b6sMhi5V.js → ui-C06Mxkd-.js} +7 -7
  33. package/dist/{ui-b6sMhi5V.js.map → ui-C06Mxkd-.js.map} +1 -1
  34. package/package.json +16 -16
  35. package/dist/app-loader-Cj2p8L1I.js +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"app-loader-CEN_4I3I.js","sources":["../src/hooks/useFailedInstallations.ts","../src/hooks/useInitSentry.ts","../src/hooks/usePendingInstallations.ts","../src/services/openpanel/client.ts","../src/services/openpanel/events.json","../src/services/openpanel/events.ts","../src/services/openpanel/processor.ts","../src/services/openpanel/factory.ts","../src/components/analytics.tsx","../src/components/openpanel-traits.ts","../src/components/openpanel.tsx","../src/context/sentry-provider.tsx","../src/utils/document-editor-debug-tools.ts","../src/utils/pglite-migration.ts","../src/components/missing-model-banner.tsx","../src/components/open-file-upload-list.tsx","../src/components/package-install-prompt.tsx","../src/components/renown-adapter-descriptors.ts","../src/components/renown-wallet-providers.tsx","../src/components/app.tsx","../src/components/connection-banner.tsx","../src/components/cookie-consent.tsx","../src/components/plugin-roots.tsx","../src/components/migration-banner.tsx","../src/components/service-worker-update-prompt.tsx","../src/components/stored-documents-refused.tsx","../src/components/app-loader.tsx"],"sourcesContent":["import {\n usePackageDiscoveryService,\n type FailedInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\n\nconst emptyArray: FailedInstallation[] = [];\n\nexport function useFailedInstallations() {\n const discoveryService = usePackageDiscoveryService();\n return useSyncExternalStore(\n (cb) => discoveryService?.subscribeFailed(cb) ?? (() => {}),\n () => discoveryService?.getFailedInstallations() ?? emptyArray,\n );\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\n\nimport type { BrowserOptions } from \"@sentry/react\";\n\nimport { childLogger } from \"document-model\";\nimport { useEffect } from \"react\";\nimport { setSentryModule } from \"../services/sentry.js\";\nimport { useAcceptedCookies } from \"./preferences-store.js\";\n\nconst logger = childLogger([\"sentry\"]);\n\nlet clientStarted = false;\n\nasync function getSentry() {\n return await import(\"@sentry/react\");\n}\n\nasync function initSentry() {\n const Sentry = await getSentry();\n const integrations: BrowserOptions[\"integrations\"] = [\n Sentry.httpClientIntegration(),\n Sentry.extraErrorDataIntegration({ depth: 5 }),\n Sentry.replayIntegration(),\n Sentry.captureConsoleIntegration({ levels: [\"error\"] }),\n ];\n if (connectConfig.sentry.tracing) {\n // Dynamic import: the router module pulls in the app's component tree.\n const { getConnectRouter } = await import(\"../components/router.js\");\n integrations.push(\n Sentry.tanstackRouterBrowserTracingIntegration(getConnectRouter()),\n );\n }\n\n Sentry.init({\n release: connectConfig.sentry.release,\n dsn: connectConfig.sentry.dsn ?? undefined,\n environment: connectConfig.sentry.env,\n integrations,\n ignoreErrors: [\n \"User is not allowed to create files\",\n \"User is not allowed to move documents\",\n \"The user aborted a request.\",\n ],\n sendDefaultPii: true,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n beforeSend(event, hint) {\n const error = hint.originalException;\n if (\n error instanceof TypeError &&\n error.message.includes(\"Failed to fetch\") &&\n !navigator.onLine\n ) {\n // If fetch fails because user is offline then ignores the error\n return null;\n }\n return event;\n },\n });\n\n setSentryModule(Sentry);\n clientStarted = true;\n}\n\nasync function closeClient() {\n if (!clientStarted) {\n return;\n }\n const sentry = await getSentry();\n setSentryModule(undefined);\n const client = sentry.getClient();\n return client?.close();\n}\n\nexport function useInitSentry() {\n const [acceptedCookies] = useAcceptedCookies();\n const { analytics } = acceptedCookies;\n\n useEffect(() => {\n if (!analytics) {\n closeClient().catch((error: unknown) => logger.error(\"@error\", error));\n return;\n }\n\n // Sentry is disabled when `dsn` is null, undefined, or an empty\n // string — covers both the new schema default (`null`) and any\n // hand-edited config that omits the DSN.\n if (\n clientStarted ||\n connectConfig.sentry.dsn === null ||\n connectConfig.sentry.dsn === undefined ||\n connectConfig.sentry.dsn === \"\"\n ) {\n return;\n }\n\n initSentry().catch((error: unknown) => logger.error(\"@error\", error));\n }, [analytics]);\n}\n","import {\n usePackageDiscoveryService,\n type PendingInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst emptyArray: readonly PendingInstallation[] = [];\n\nexport function usePendingInstallations() {\n const discoveryService = usePackageDiscoveryService();\n const cacheRef = useRef<readonly PendingInstallation[]>(emptyArray);\n\n const getSnapshot = useCallback(() => {\n if (!discoveryService) return emptyArray;\n const next = discoveryService.getPendingInstallations() ?? emptyArray;\n const prev = cacheRef.current;\n if (\n next === prev ||\n (next.length === prev.length && next.every((p, i) => p === prev[i]))\n ) {\n return prev;\n }\n cacheRef.current = next;\n return next;\n }, [discoveryService]);\n\n return useSyncExternalStore(\n (cb) => discoveryService?.subscribePending(cb) ?? (() => {}),\n getSnapshot,\n );\n}\n","import type { OpenPanel } from \"@openpanel/web\";\n\nimport { clearOpenPanelBuffer, drainOpenPanelBuffer } from \"./buffer.js\";\nimport type { OpenPanelConfig } from \"./types.js\";\n\nlet client: OpenPanel | undefined;\n\n/**\n * Returns the cached `OpenPanel` singleton, building it on first call.\n *\n * When `config.clientId` is empty it returns `undefined` without importing\n * `@openpanel/web`, so the bundler can tree-shake the SDK out of production.\n */\nexport async function getOpenPanelClient(\n config: OpenPanelConfig,\n): Promise<OpenPanel | undefined> {\n if (!config.clientId) {\n return undefined;\n }\n\n if (client) {\n return client;\n }\n\n // Dynamic import keeps @openpanel/web out of the initial chunk.\n const { OpenPanel: OpenPanelClass } = await import(\"@openpanel/web\");\n\n client = new OpenPanelClass({\n clientId: config.clientId,\n ...(config.apiUrl ? { apiUrl: config.apiUrl } : {}),\n trackScreenViews: true,\n trackOutgoingLinks: true,\n });\n\n // The web SDK has no `globalProperties` constructor option.\n client.setGlobalProperties({ app: \"connect\" });\n\n // Runs once (the `if (client)` guard above), so the buffer is never\n // double-drained.\n drainOpenPanelBuffer(client);\n\n return client;\n}\n\n/**\n * Clears the cached singleton and the pre-init buffer. Call on consent\n * revocation or during tests; buffered events are discarded, not replayed.\n */\nexport function resetOpenPanelClient(): void {\n client = undefined;\n clearOpenPanelBuffer();\n}\n","","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\n\nimport type { OpenPanelEventMapping } from \"./types.js\";\nimport rawEvents from \"./events.json\" with { type: \"json\" };\n\nconst EventMappingSchema = z\n .object({\n documentType: z.string().min(1),\n actionTypes: z.array(z.string().min(1)).min(1),\n alias: z.string().optional(),\n })\n .strict();\n\nconst EventMappingsSchema = z.array(EventMappingSchema).readonly();\n\n/**\n * Parses and validates the event mapping table, returning the validated array\n * and an O(1) lookup map. Accepts a `raw` override for tests. Throws on zod\n * failures and on duplicate `(documentType, actionType)` pairs.\n */\nexport function loadEvents(raw: unknown = rawEvents): {\n mappings: readonly OpenPanelEventMapping[];\n lookupMap: Map<string, Map<string, OpenPanelEventMapping>>;\n} {\n const result = EventMappingsSchema.safeParse(raw);\n if (!result.success) {\n throw new Error(`Invalid OpenPanel events.json: ${result.error.message}`);\n }\n\n const mappings = result.data as readonly OpenPanelEventMapping[];\n const lookupMap = new Map<string, Map<string, OpenPanelEventMapping>>();\n\n for (const mapping of mappings) {\n let inner = lookupMap.get(mapping.documentType);\n if (!inner) {\n inner = new Map<string, OpenPanelEventMapping>();\n lookupMap.set(mapping.documentType, inner);\n }\n\n for (const actionType of mapping.actionTypes) {\n if (inner.has(actionType)) {\n throw new Error(\n `Duplicate OpenPanel event mapping for ${mapping.documentType}/${actionType}`,\n );\n }\n inner.set(actionType, mapping);\n }\n }\n\n return { mappings, lookupMap };\n}\n\nconst { mappings: defaultMappings, lookupMap: defaultLookupMap } = loadEvents();\n\n/** Validated mapping array from the bundled events.json. */\nexport const eventMappings: readonly OpenPanelEventMapping[] = defaultMappings;\n\n/** O(1) lookup map: documentType → actionType → mapping. */\nexport const eventLookupMap: Map<\n string,\n Map<string, OpenPanelEventMapping>\n> = defaultLookupMap;\n\n/**\n * Normalizes a document type into a safe event-name segment: lowercased, `/`\n * replaced with `.`, and any character outside `[a-z0-9._-]` stripped.\n * e.g. `powerhouse/document-drive` → `powerhouse.document-drive`.\n */\nexport function normalize(documentType: string): string {\n return documentType\n .toLowerCase()\n .replace(/\\//g, \".\")\n .replace(/[^a-z0-9._-]/g, \"\");\n}\n\n/**\n * Derives the OpenPanel event name: `mapping.alias` when present, otherwise\n * `${normalize(documentType)}.${actionType.toLowerCase()}`.\n */\nexport function deriveEventName(\n mapping: OpenPanelEventMapping,\n op: OperationWithContext,\n): string {\n if (mapping.alias) {\n return mapping.alias;\n }\n return `${normalize(op.context.documentType)}.${op.operation.action.type.toLowerCase()}`;\n}\n\n/**\n * Builds the default properties attached to every OpenPanel event. The `app`\n * property is stamped globally by the client, not here.\n */\nexport function buildDefaultProperties(op: OperationWithContext): {\n documentType: string;\n actionType: string;\n documentId: string;\n scope: string;\n branch: string;\n} {\n return {\n documentType: op.context.documentType,\n actionType: op.operation.action.type,\n documentId: op.context.documentId,\n scope: op.context.scope,\n branch: op.context.branch,\n };\n}\n","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport type { IProcessor } from \"@powerhousedao/shared/processors\";\n\nimport { buildDefaultProperties, deriveEventName } from \"./events.js\";\nimport type { OpenPanelEventMapping } from \"./types.js\";\n\n/**\n * Minimal structural type for the injected analytics client. Keeps\n * `@openpanel/web` out of the runtime import graph and makes test fakes\n * trivial; the real `OpenPanel` instance satisfies it structurally.\n */\nexport type OpenPanelTracker = {\n track: (name: string, properties?: Record<string, unknown>) => unknown;\n flush?: () => void;\n};\n\n/**\n * Read-only reactor `IProcessor` that translates matching document operations\n * into OpenPanel analytics events. Operations whose `(documentType, actionType)`\n * pair is absent from the lookup map are skipped; per-operation errors are\n * routed to `onError` and never thrown back to the manager.\n */\nexport class OpenPanelProcessor implements IProcessor {\n constructor(\n private readonly client: OpenPanelTracker,\n private readonly lookupMap: Map<string, Map<string, OpenPanelEventMapping>>,\n private readonly onError: (\n err: unknown,\n op?: OperationWithContext,\n ) => void = (err) =>\n console.warn(\"[OpenPanelProcessor] Error tracking event:\", err),\n ) {}\n\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n for (const op of operations) {\n const inner = this.lookupMap.get(op.context.documentType);\n if (!inner) continue;\n\n const mapping = inner.get(op.operation.action.type);\n if (!mapping) continue;\n\n const name = deriveEventName(mapping, op);\n const payload = buildDefaultProperties(op);\n\n try {\n await this.client.track(name, payload);\n } catch (err) {\n this.onError(err, op);\n }\n }\n }\n\n onDisconnect(): Promise<void> {\n this.client.flush?.();\n return Promise.resolve();\n }\n}\n","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport type { PHDocumentHeader } from \"@powerhousedao/shared/document-model\";\nimport type {\n ProcessorFactory,\n ProcessorRecord,\n} from \"@powerhousedao/shared/processors\";\n\nimport { OpenPanelProcessor, type OpenPanelTracker } from \"./processor.js\";\nimport type { OpenPanelEventMapping } from \"./types.js\";\n\nexport type OpenPanelProcessorFactoryConfig = {\n /** The initialized analytics client to forward events to. */\n client: OpenPanelTracker;\n\n /** Loaded event mapping data, as returned by `loadEvents()`. */\n events: {\n mappings: readonly OpenPanelEventMapping[];\n lookupMap: Map<string, Map<string, OpenPanelEventMapping>>;\n };\n\n /** Replay window. Defaults to `\"current\"` (no historical replay). */\n startFrom?: \"current\" | \"beginning\";\n\n /** Error handler; defaults to `console.warn`. */\n onError?: (err: unknown, op?: OperationWithContext) => void;\n};\n\n/**\n * Returns a `ProcessorFactory` that, for each drive, creates a single\n * `OpenPanelProcessor` record whose `filter.documentType` is the union of all\n * document types present in the event mapping table.\n */\nexport function createOpenPanelProcessorFactory(\n config: OpenPanelProcessorFactoryConfig,\n): ProcessorFactory {\n return function openPanelProcessorFactory(\n _driveHeader: PHDocumentHeader,\n ): ProcessorRecord[] {\n const documentType = Array.from(config.events.lookupMap.keys());\n\n const processor = new OpenPanelProcessor(\n config.client,\n config.events.lookupMap,\n config.onError,\n );\n\n const record: ProcessorRecord = {\n processor,\n filter: { documentType },\n startFrom: config.startFrom ?? \"current\",\n };\n\n return [record];\n };\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useAcceptedCookies } from \"../hooks/preferences-store.js\";\nimport { useEffect } from \"react\";\n\ndeclare global {\n interface Window {\n gtag?: (...args: any[]) => void;\n dataLayer?: any[];\n }\n}\n\nfunction gtag(...args: (string | Date)[]) {\n window.dataLayer?.push(...args);\n}\n\nexport const Analytics = () => {\n const gaTrackingId = connectConfig.gaTrackingId;\n const [{ analytics }] = useAcceptedCookies();\n const useAnalytics = gaTrackingId && analytics;\n\n useEffect(() => {\n if (useAnalytics) {\n // Create the GA script tag\n const script = document.createElement(\"script\");\n script.src = `https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`;\n script.async = true;\n document.head.appendChild(script);\n\n // Initialize GA\n window.dataLayer = window.dataLayer || [];\n\n gtag(\"js\", new Date());\n gtag(\"config\", gaTrackingId);\n\n // Clean up the script if no longer enabled\n return () => {\n document.head.removeChild(script);\n };\n }\n }, [useAnalytics, gaTrackingId]);\n\n return null;\n};\n","import type { User } from \"@renown/sdk\";\n\n/**\n * Builds the OpenPanel identity traits from a renown User.\n *\n * Canonical trait schema (shared with Renown and Vetra — each app sends every\n * field it has data for, under these names):\n * - `address`, `did`, `networkId`, `chainId`, `caip2` — wallet/chain facts.\n * - `ensName`, `ensAvatar` — raw ENS facts.\n * - `username`, `userImage`, `profileDocumentId`, `profileCreatedAt` — raw\n * Renown profile facts.\n * - `accountType` — wallet-adapter concept; only Renown has it.\n *\n * Rules:\n * - `credential` (contains a JWT) is **never** forwarded.\n * - Traits carry raw facts only; resolved presentation values (avatar,\n * display name) go in OpenPanel's native identify fields — see\n * {@link buildIdentifyPayload}.\n * - Optional fields (`ens`, `profile`) are only included when their value is\n * non-nullish (guards against `null` from `RenownProfile` fields as well\n * as plain `undefined`).\n *\n * Mirror the Sentry pattern in `store/user.ts`: destructure off `credential`\n * first, then assemble the trait payload from the remainder.\n */\nexport function buildTraits(user: User): Record<string, unknown> {\n // Destructure credential off so it can never accidentally make it into the\n // returned object.\n const { credential: _credential, ...rest } = user;\n\n const traits: Record<string, unknown> = {\n address: rest.address,\n did: rest.did,\n networkId: rest.networkId,\n chainId: rest.chainId,\n caip2: `${rest.networkId}:${rest.chainId}`,\n };\n\n // ens fields — optional on the User type\n if (rest.ens?.name != null) {\n traits.ensName = rest.ens.name;\n }\n if (rest.ens?.avatarUrl != null) {\n traits.ensAvatar = rest.ens.avatarUrl;\n }\n\n // profile fields — optional on InternalUser; RenownProfile members can be\n // null, so guard with != null (catches both null and undefined)\n if (rest.profile?.username != null) {\n traits.username = rest.profile.username;\n }\n if (rest.profile?.userImage != null) {\n traits.userImage = rest.profile.userImage;\n }\n if (rest.profile?.documentId != null) {\n traits.profileDocumentId = rest.profile.documentId;\n }\n if (rest.profile?.createdAt != null) {\n traits.profileCreatedAt = rest.profile.createdAt;\n }\n\n return traits;\n}\n\n/**\n * Builds the full `identify()` payload:\n * - `profileId` is the wallet address — the cross-app profile key shared with\n * Renown and Vetra.\n * - `avatar` / `firstName` are OpenPanel's native profile fields (they drive\n * the picture and name in the dashboard UI), resolved as\n * `userImage ?? ensAvatar` and `ensName ?? username`.\n * - `properties` are the raw traits from {@link buildTraits}.\n */\nexport function buildIdentifyPayload(user: User): {\n profileId: string;\n avatar?: string;\n firstName?: string;\n properties: Record<string, unknown>;\n} {\n const avatar = user.profile?.userImage ?? user.ens?.avatarUrl;\n const firstName = user.ens?.name ?? user.profile?.username;\n\n return {\n profileId: user.address,\n ...(avatar != null ? { avatar } : {}),\n ...(firstName != null ? { firstName } : {}),\n properties: buildTraits(user),\n };\n}\n","import type { OpenPanel as OpenPanelClient } from \"@openpanel/web\";\nimport { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useAcceptedCookies } from \"../hooks/preferences-store.js\";\nimport {\n createOpenPanelProcessorFactory,\n eventLookupMap,\n eventMappings,\n getOpenPanelClient,\n resetOpenPanelClient,\n} from \"@powerhousedao/connect/services\";\nimport {\n useReactorClientModule,\n useUser,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { buildIdentifyPayload } from \"./openpanel-traits.js\";\n\ndeclare global {\n interface Window {\n openPanel?: OpenPanelClient;\n }\n}\n\n/**\n * `OpenPanel` is a `null`-rendering component that manages the full lifecycle\n * of the OpenPanel analytics subsystem.\n *\n * Gates:\n * - `useAcceptedCookies().analytics === true` — the existing analytics cookie.\n * - `connectConfig.openPanel.clientId` non-empty — no client ID → no-op.\n *\n * Behaviour when both gates pass:\n * 1. Lazy-imports `@openpanel/web` and builds the singleton via\n * `getOpenPanelClient(connectConfig.openPanel)`.\n * 2. Exposes the client on `window.openPanel` for the card-6\n * `useOpenPanelAnalytics()` hook to consume.\n * 3. If `connectConfig.openPanel.trackOperations`, registers the processor\n * factory against `processorManager` so document operations are forwarded.\n * 4. Calls `client.identify()` when the renown user transitions from\n * `undefined` → defined (login). The profile ID is the wallet address —\n * the cross-app key shared with Renown and Vetra.\n * 5. Calls `client.clear()` when the user transitions from defined →\n * `undefined` (logout).\n *\n * Teardown (unmount **or** consent revocation):\n * - `unregisterFactory(\"openpanel\")` to remove the processor.\n * - `resetOpenPanelClient()` to clear the singleton.\n * - `window.openPanel` is cleared.\n *\n * Mirrors the Sentry pattern in `store/user.ts` for login/logout detection.\n * Analytics failures are caught and forwarded to `console.warn` — they must\n * never throw into the application.\n *\n * Mounted next to `<Analytics />` in `app.tsx`.\n */\nexport function OpenPanel(): null {\n const [{ analytics }] = useAcceptedCookies();\n const user = useUser();\n const module = useReactorClientModule();\n const reactorClientModule = module?.kind === \"browser\" ? module : undefined;\n\n const [client, setClient] = useState<OpenPanelClient | undefined>();\n\n /**\n * Tracks the previous `user` value so we can detect the two transitions:\n * undefined → defined (login)\n * defined → undefined (logout)\n */\n const prevUserRef = useRef<ReturnType<typeof useUser>>(undefined);\n\n const enabled = analytics && !!connectConfig.openPanel.clientId;\n const processorManager = reactorClientModule?.reactorModule?.processorManager;\n\n useEffect(() => {\n if (!enabled) return;\n\n let cancelled = false;\n\n // Read via a call — TS would otherwise narrow direct reads to always-false.\n const isCancelled = () => cancelled;\n\n const setup = async () => {\n let builtClient: OpenPanelClient | undefined;\n try {\n builtClient = await getOpenPanelClient(connectConfig.openPanel);\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to build client:\", err);\n return;\n }\n\n if (isCancelled() || !builtClient) return;\n\n setClient(builtClient);\n window.openPanel = builtClient;\n\n if (connectConfig.openPanel.trackOperations && processorManager) {\n try {\n await processorManager.registerFactory(\n \"openpanel\",\n createOpenPanelProcessorFactory({\n client: builtClient,\n events: { mappings: eventMappings, lookupMap: eventLookupMap },\n startFrom: \"current\",\n }),\n );\n // Guard against teardown happening while registerFactory was in flight.\n if (isCancelled()) {\n await processorManager\n .unregisterFactory(\"openpanel\")\n .catch((err: unknown) =>\n console.warn(\n \"[OpenPanel] Failed to unregister factory after cancellation:\",\n err,\n ),\n );\n }\n } catch (err) {\n console.warn(\n \"[OpenPanel] Failed to register processor factory:\",\n err,\n );\n }\n }\n };\n\n void setup();\n\n return () => {\n cancelled = true;\n\n // Reset the user-tracking ref so that when consent is re-granted (and a\n // new client is built) any currently-logged-in user is re-identified.\n prevUserRef.current = undefined;\n\n if (connectConfig.openPanel.trackOperations && processorManager) {\n void processorManager\n .unregisterFactory(\"openpanel\")\n .catch((err: unknown) =>\n console.warn(\n \"[OpenPanel] Failed to unregister processor factory:\",\n err,\n ),\n );\n }\n\n resetOpenPanelClient();\n window.openPanel = undefined;\n setClient(undefined);\n };\n }, [enabled, processorManager]);\n\n // detect login/logout transitions\n useEffect(() => {\n if (!enabled || !client) return;\n\n const prev = prevUserRef.current;\n prevUserRef.current = user;\n\n if (!prev && user) {\n // Login: undefined → defined (or client became available with user\n // already logged in — prevUserRef is undefined in both cases).\n try {\n void client.identify(buildIdentifyPayload(user));\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to identify user:\", err);\n }\n } else if (prev && !user) {\n // Logout: defined → undefined\n try {\n void client.clear();\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to clear user:\", err);\n }\n }\n }, [client, user, enabled]);\n\n return null;\n}\n","import { useInitSentry } from \"../hooks/useInitSentry.js\";\n\ninterface SentryProviderProps {\n children?: React.ReactNode;\n}\n\nexport const SentryProvider: React.FC<SentryProviderProps> = ({ children }) => {\n useInitSentry();\n\n return children;\n};\n","import type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\n\nexport class DocumentEditorDebugTools {\n private document: PHDocument | undefined;\n private operations: Operation[] = [];\n\n constructor(document?: PHDocument) {\n if (document) {\n this.document = document;\n }\n }\n\n private operationsToTableObject(operations: Operation[]) {\n return operations.map((op) => ({\n ...op,\n input: JSON.stringify(op.action.input),\n }));\n }\n\n public setDocument(document: PHDocument) {\n this.document = document;\n }\n\n public getDocument() {\n return this.document;\n }\n\n public getOperations() {\n return this.operations;\n }\n\n public pushOperation(operation: Operation) {\n this.operations.push(operation);\n }\n\n public operationsTable() {\n if (!this.document) {\n console.warn(\"No document\");\n }\n const ops = Object.values(this.document?.operations || {})\n .filter((array): array is Operation[] => array !== undefined)\n .flatMap((array) => array)\n .sort((a, b) => a.index - b.index);\n\n console.table(this.operationsToTableObject(ops));\n }\n\n public scopeOperationsTable(scope: string) {\n if (!this.document) {\n console.warn(\"No document\");\n }\n const ops = this.document?.operations[scope] || [];\n console.table(this.operationsToTableObject(ops));\n }\n\n public operationsLog() {\n console.log(this.operations);\n }\n\n public operationsLogTable() {\n console.table(this.operationsToTableObject(this.operations));\n }\n\n public clear() {\n this.operations = [];\n this.document = undefined;\n }\n}\n","import { setMigrationStatus } from \"../components/migration-status.js\";\nimport { idbError } from \"./pglite-idb.js\";\nimport {\n type BackupStrategy,\n cloneFileData,\n migrateIdb,\n} from \"./pglite-migrate-core.js\";\nimport { PRIMARY_IDB_NAMES } from \"./storage-namespace.js\";\n\nconst BACKUP_PREFIX = \"ph-pglite-backup::\";\nconst BACKUP_INDEX_KEY = \"ph:pglite-backups\";\nconst BACKUP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype BackupRecord = { name: string; idbName: string; createdAt: number };\n\nfunction deleteIdb(name: string, timeoutMs = 15_000): Promise<void> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.deleteDatabase(name);\n let settled = false;\n const done = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n const timer = setTimeout(\n () =>\n done(() =>\n reject(\n new Error(`IDB delete timed out for ${name} after ${timeoutMs}ms`),\n ),\n ),\n timeoutMs,\n );\n req.onsuccess = () =>\n done(() => {\n clearTimeout(timer);\n resolve();\n });\n req.onerror = () =>\n done(() => {\n clearTimeout(timer);\n reject(idbError(req, `IDB delete failed for ${name}`));\n });\n });\n}\n\nfunction readBackupIndex(): BackupRecord[] {\n try {\n const raw = localStorage.getItem(BACKUP_INDEX_KEY);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as BackupRecord[]) : [];\n } catch {\n return [];\n }\n}\n\nfunction writeBackupIndex(records: BackupRecord[]): void {\n try {\n localStorage.setItem(BACKUP_INDEX_KEY, JSON.stringify(records));\n } catch {\n // ignore quota errors — janitor is best-effort\n }\n}\n\nfunction registerBackup(rec: BackupRecord): void {\n writeBackupIndex([...readBackupIndex(), rec]);\n}\n\nfunction forgetBackup(name: string): void {\n writeBackupIndex(readBackupIndex().filter((r) => r.name !== name));\n}\n\nasync function janitor(): Promise<void> {\n const cutoff = Date.now() - BACKUP_RETENTION_MS;\n const keep: BackupRecord[] = [];\n for (const rec of readBackupIndex()) {\n if (rec.createdAt >= cutoff) {\n keep.push(rec);\n continue;\n }\n try {\n await deleteIdb(rec.name);\n } catch (err) {\n console.warn(`Failed to delete expired pglite backup ${rec.name}`, err);\n keep.push(rec);\n }\n }\n writeBackupIndex(keep);\n}\n\n// Persistent backup to an IDB dir, indexed in localStorage with 30-day\n// retention (the janitor reaps expired ones); success keeps the backup.\nfunction createPersistentBackup(): BackupStrategy {\n return {\n snapshot: async (idbName) => {\n const backupName = `${BACKUP_PREFIX}${idbName}::${new Date().toISOString()}`;\n await cloneFileData(idbName, backupName);\n registerBackup({ name: backupName, idbName, createdAt: Date.now() });\n return backupName;\n },\n rollback: async (handle, idbName, cause) => {\n const backupName = handle as string;\n try {\n // clone clears-and-replaces in one txn; no pre-clear (which could empty the dir).\n await cloneFileData(backupName, idbName);\n } catch (rollbackErr) {\n console.error(\n `PGlite migration rollback failed for ${idbName}; backup ${backupName} retained. Primary migration error:`,\n cause,\n \"Rollback error:\",\n rollbackErr,\n );\n return;\n }\n await deleteIdb(backupName).catch(() => undefined);\n forgetBackup(backupName);\n },\n discard: async (handle) => {\n const backupName = handle as string;\n await deleteIdb(backupName).catch(() => undefined);\n forgetBackup(backupName);\n },\n commit: () => Promise.resolve(),\n };\n}\n\nasync function migrateAllLocked(): Promise<void> {\n const backup = createPersistentBackup();\n try {\n for (const idbName of PRIMARY_IDB_NAMES) {\n await migrateIdb(\n idbName,\n (phase) => setMigrationStatus({ idbName, phase }),\n backup,\n );\n }\n } finally {\n setMigrationStatus(null);\n }\n}\n\nexport async function migrateAllIfNeeded(): Promise<void> {\n janitor().catch((err) => console.warn(\"PGlite backup janitor failed\", err));\n\n const hasLocks =\n typeof navigator !== \"undefined\" &&\n \"locks\" in navigator &&\n typeof navigator.locks.request === \"function\";\n\n if (!hasLocks) {\n await migrateAllLocked();\n return;\n }\n\n await navigator.locks.request(\n \"ph-pglite-migration\",\n { mode: \"exclusive\" },\n async () => {\n await migrateAllLocked();\n },\n );\n}\n","import { Icon, Modal } from \"@powerhousedao/design-system\";\nimport {\n usePackageDiscoveryService,\n type FailedInstallation,\n type FailedInstallationReason,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useState } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useFailedInstallations } from \"../hooks/useFailedInstallations.js\";\n\nconst reasonLabels: Record<FailedInstallationReason, string> = {\n \"no-registry\": \"No package registry is configured.\",\n \"not-in-registry\": \"No matching package found in the registry.\",\n \"registry-error\": \"Couldn't reach the package registry.\",\n \"install-failed\": \"Package failed to install.\",\n dismissed: \"Installation was dismissed.\",\n offline: \"You're offline — this package can't be loaded until you reconnect.\",\n};\n\nfunction canRetry(reason: FailedInstallationReason): boolean {\n return reason !== \"no-registry\";\n}\n\nexport function MissingModelBanner() {\n const failed = useFailedInstallations();\n const discoveryService = usePackageDiscoveryService();\n const [open, setOpen] = useState(false);\n const [dismissed, setDismissed] = useState(false);\n\n useEffect(() => {\n return discoveryService?.subscribeEvents((event) => {\n if (event.type === \"load-failed\") {\n setDismissed(false);\n }\n });\n }, [discoveryService]);\n\n if (failed.length === 0) return null;\n\n return (\n <>\n {dismissed ? null : (\n <div className=\"absolute inset-x-0 top-0 z-200 bg-background\">\n <div className=\"flex items-center justify-between gap-3 bg-warning/10 px-4 py-2 text-sm text-warning\">\n <span>\n {failed.length === 1\n ? \"1 document type couldn't load (missing model).\"\n : `${failed.length} document types couldn't load (missing models).`}\n </span>\n <div className=\"flex items-center gap-2\">\n <button\n type=\"button\"\n onClick={() => setOpen(true)}\n className=\"rounded-md border border-warning bg-background px-3 py-1 text-warning hover:hover-effect\"\n >\n View\n </button>\n <button\n type=\"button\"\n onClick={() => setDismissed(true)}\n aria-label=\"Dismiss\"\n className=\"flex items-center text-warning hover:hover-effect\"\n >\n <Icon name=\"XmarkLight\" size={16} />\n </button>\n </div>\n </div>\n </div>\n )}\n <MissingModelDetailsModal\n open={open}\n failed={failed}\n onClose={() => setOpen(false)}\n />\n </>\n );\n}\n\ntype DetailsProps = {\n readonly open: boolean;\n readonly failed: FailedInstallation[];\n readonly onClose: () => void;\n};\n\nfunction MissingModelDetailsModal(props: DetailsProps) {\n const { open, failed, onClose } = props;\n const discoveryService = usePackageDiscoveryService();\n const [retrying, setRetrying] = useState<Set<string>>(() => new Set());\n\n async function handleRetry(documentType: string) {\n if (!discoveryService) return;\n setRetrying((prev) => new Set(prev).add(documentType));\n try {\n await discoveryService.retryInstallation(documentType);\n } finally {\n setRetrying((prev) => {\n const next = new Set(prev);\n next.delete(documentType);\n return next;\n });\n }\n }\n\n return (\n <Modal\n open={open}\n onOpenChange={(isOpen) => {\n if (!isOpen) onClose();\n }}\n contentProps={{ className: \"rounded-3xl\" }}\n >\n <div className=\"w-[520px] max-w-[90vw] bg-background p-6\">\n <div className=\"border-b border-border pb-2 text-2xl font-bold text-foreground\">\n Missing document models\n </div>\n <div className=\"my-4 text-sm text-foreground\">\n The following document types couldn't be loaded. Documents using them\n won't display until the underlying package is installed.\n </div>\n {failed.length === 0 ? (\n <div className=\"rounded-xl bg-background p-4 text-sm text-foreground\">\n No outstanding failures.\n </div>\n ) : (\n <div className=\"flex max-h-[60vh] flex-col gap-3 overflow-y-auto\">\n {failed.map((entry) => {\n const isRetrying = retrying.has(entry.documentType);\n const retryDisabled = !canRetry(entry.reason) || isRetrying;\n return (\n <div\n key={entry.documentType}\n className=\"rounded-xl bg-background p-4\"\n >\n <div className=\"mb-1 font-mono text-sm font-semibold text-foreground\">\n {entry.documentType}\n </div>\n <div className=\"mb-2 text-xs text-foreground\">\n {reasonLabels[entry.reason]}\n </div>\n {entry.packageNames.length > 0 ? (\n <div className=\"mb-2 text-xs text-muted-foreground\">\n Package{entry.packageNames.length > 1 ? \"s\" : \"\"}:{\" \"}\n {entry.packageNames.join(\", \")}\n </div>\n ) : null}\n {entry.error ? (\n <div className=\"mb-2 font-mono text-xs wrap-break-word text-destructive\">\n {entry.error.message}\n </div>\n ) : null}\n <div className=\"flex justify-end\">\n <button\n type=\"button\"\n onClick={() => void handleRetry(entry.documentType)}\n disabled={retryDisabled}\n title={\n canRetry(entry.reason)\n ? undefined\n : \"No registry is configured; nothing to retry against.\"\n }\n className={twMerge(\n \"min-h-[32px] rounded-xl px-3 py-1 text-sm font-semibold text-foreground transition-all hover:hover-effect\",\n retryDisabled\n ? \"cursor-not-allowed bg-secondary hover:hover-effect\"\n : \"bg-primary text-primary-foreground active:active-effect\",\n )}\n >\n {isRetrying ? \"Retrying...\" : \"Try install again\"}\n </button>\n </div>\n </div>\n );\n })}\n </div>\n )}\n <div className=\"mt-4 flex justify-end\">\n <button\n type=\"button\"\n onClick={onClose}\n className=\"min-h-[36px] rounded-xl border border-border bg-background px-4 py-2 text-sm font-semibold text-foreground hover:hover-effect\"\n >\n Close\n </button>\n </div>\n </div>\n </Modal>\n );\n}\n","import {\n clearOpenFileUploads,\n getOpenFileUploads,\n removeOpenFileUpload,\n subscribeOpenFileUploads,\n} from \"@powerhousedao/connect/utils\";\nimport { UploadFileListContainer } from \"@powerhousedao/design-system/connect\";\nimport { setSelectedNode } from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\n\n// The floating \"Uploading N documents\" panel for files opened through the OS\n// file association — the same design-system panel drag-and-drop uses, driven\n// by the open-file upload store instead of DropZone's instance-local tracker.\n// Renders nothing while no uploads are tracked.\nexport function OpenFileUploadList() {\n const uploads = useSyncExternalStore(\n subscribeOpenFileUploads,\n getOpenFileUploads,\n );\n\n return (\n <UploadFileListContainer\n uploadsArray={uploads}\n uploadsCount={uploads.length}\n removeUpload={removeOpenFileUpload}\n clearAllUploads={clearOpenFileUploads}\n setSelectedNode={setSelectedNode}\n />\n );\n}\n","import {\n PackageInstallModal,\n type PendingPackageInstallation,\n} from \"@powerhousedao/design-system/connect\";\nimport { usePackageDiscoveryService } from \"@powerhousedao/reactor-browser\";\nimport { usePendingInstallations } from \"../hooks/usePendingInstallations.js\";\n\nexport function PackageInstallPrompt() {\n const pendingInstallations = usePendingInstallations();\n const discoveryService = usePackageDiscoveryService();\n\n if (!discoveryService || pendingInstallations.length === 0) return null;\n\n const installations: PendingPackageInstallation[] =\n pendingInstallations.flatMap((p) =>\n p.packageNames.map((packageName) => ({\n documentType: p.documentType,\n packageName,\n })),\n );\n\n return (\n <PackageInstallModal\n pendingInstallations={installations}\n onInstall={(packageName) =>\n discoveryService.approveInstallation(packageName)\n }\n onDismiss={(packageName) =>\n discoveryService.dismissInstallation(packageName)\n }\n />\n );\n}\n","import type { PHConnectRenownAdapters } from \"@powerhousedao/shared/clis\";\nimport type { WalletAdapterDescriptor } from \"@renown/sdk/wallet\";\nimport {\n mockAdapter,\n type MockLoginMethod,\n type PHRenownMockAdapterConfig,\n} from \"@renown/sdk/wallet/mock\";\nimport { privyAdapter, type PrivyLoginMethod } from \"@renown/sdk/wallet/privy\";\nimport { rainbowAdapter } from \"@renown/sdk/wallet/rainbow\";\nimport {\n arbitrum,\n base,\n type Chain,\n mainnet,\n optimism,\n polygon,\n sepolia,\n} from \"wagmi/chains\";\n\n// `mock` is deliberately absent from the published config schema (TEST/DEV only\n// — it signs with a well-known key), so it is read off the runtime config here.\nexport type ConnectRenownAdapters = PHConnectRenownAdapters & {\n mock?: PHRenownMockAdapterConfig;\n};\n\n// Adapters validate `methods` eagerly and throw on one they can't drive. This\n// runs during render, so a config typo costs one button, not the whole app.\nfunction describe(\n id: string,\n build: () => WalletAdapterDescriptor,\n): WalletAdapterDescriptor[] {\n try {\n return [build()];\n } catch (error) {\n console.error(\n `[connect] Ignoring the \"${id}\" wallet adapter: connect.renown.adapters.${id} was rejected.`,\n error,\n );\n return [];\n }\n}\n\n// `connect.renown.chainId` is an id, but the adapter needs the chain object, so\n// only a listed chain can be offered.\nconst CHAINS_BY_ID = new Map<number, Chain>(\n [mainnet, sepolia, polygon, optimism, arbitrum, base].map((chain) => [\n chain.id,\n chain,\n ]),\n);\n\n// Renown issues on one chain and rejects a session from any other, so the wallet\n// UI has to offer that chain and no other.\nfunction chainsFor(\n chainId: number | undefined,\n): readonly [Chain, ...Chain[]] | undefined {\n if (chainId === undefined) return undefined;\n const chain = CHAINS_BY_ID.get(chainId);\n if (!chain) {\n console.error(\n `[connect] connect.renown.chainId ${chainId} is not a chain Connect can offer, so in-page sign-in will be rejected. Supported: ${[...CHAINS_BY_ID.keys()].join(\", \")}.`,\n );\n return undefined;\n }\n return [chain];\n}\n\n/** Map Connect's declarative `connect.renown.adapters` config to the descriptors `RenownWalletProvider` takes. Array order sets the order of the login buttons. A rejected adapter config is dropped (logged), leaving the others working. `chainId` is `connect.renown.chainId`, the chain Renown issues credentials on. */\nexport function configToDescriptors(\n config: ConnectRenownAdapters | undefined,\n chainId?: number,\n): WalletAdapterDescriptor[] {\n if (!config) return [];\n const { rainbow, privy, mock } = config;\n const descriptors: WalletAdapterDescriptor[] = [];\n const chains = chainsFor(chainId);\n // Every adapter Connect can offer is imported statically (hence Connect\n // installs all their peers), but each library stays behind a lazy loader.\n if (rainbow) {\n descriptors.push(\n ...describe(\"rainbow\", () =>\n rainbowAdapter({ ...rainbow, ...(chains ? { chains } : {}) })),\n );\n }\n if (privy) {\n // appId is optional in the config schema but required by the adapter: an\n // operator who enables privy without one gets no privy login, not a crash.\n const { appId, clientId, methods } = privy;\n if (appId) {\n descriptors.push(\n ...describe(\"privy\", () =>\n privyAdapter({\n appId,\n clientId,\n // Methods come from JSON, so unvalidated here; the adapter's\n // resolver rejects anything it can't drive.\n methods: methods as PrivyLoginMethod[] | undefined,\n chain: chains?.[0],\n })),\n );\n }\n }\n if (mock) {\n descriptors.push(\n ...describe(\"mock\", () =>\n mockAdapter({\n ...mock,\n methods: mock.methods as MockLoginMethod[] | undefined,\n })),\n );\n }\n return descriptors;\n}\n","import { RenownWalletProvider, useTheme } from \"@powerhousedao/reactor-browser\";\nimport type { WalletTheme } from \"@renown/sdk/wallet\";\nimport { useMemo, type ReactNode } from \"react\";\nimport { getRuntimeConfig } from \"@powerhousedao/connect-core/runtime-config\";\nimport {\n configToDescriptors,\n type ConnectRenownAdapters,\n} from \"./renown-adapter-descriptors.js\";\n\n// Resolve a CSS color expression (a theme token) to a concrete color via a\n// hidden probe, so adapters receive Connect's palette without reading the DOM.\nfunction resolveColor(expr: string, fallback: string): string {\n if (typeof document === \"undefined\") return fallback;\n const probe = document.createElement(\"span\");\n probe.style.color = fallback;\n probe.style.color = expr;\n probe.style.display = \"none\";\n document.body.appendChild(probe);\n const resolved = getComputedStyle(probe).color;\n probe.remove();\n return resolved || fallback;\n}\n\n// Thin Connect wrapper over the shared RenownWalletProvider primitive: supplies\n// the configured adapters and Connect's runtime theme (mode + accent colors).\nexport function RenownWalletProviders({ children }: { children: ReactNode }) {\n const config = getRuntimeConfig().connect.renown?.adapters as\n | ConnectRenownAdapters\n | undefined;\n const chainId = getRuntimeConfig().connect.renown?.chainId;\n const { theme } = useTheme();\n // Descriptors carry only eager metadata; no wallet library loads here.\n const adapters = useMemo(\n () => configToDescriptors(config, chainId),\n [config, chainId],\n );\n\n // Resolve colors (forced style reads) only when an adapter is configured,\n // so a wallet-less deployment does no probing work at mount.\n const walletTheme = useMemo<WalletTheme | undefined>(\n () =>\n adapters.length > 0\n ? {\n mode: theme,\n accentColor: resolveColor(\"var(--primary)\", \"#0084ff\"),\n accentColorForeground: resolveColor(\n \"var(--primary-foreground)\",\n \"#ffffff\",\n ),\n }\n : undefined,\n [theme, adapters],\n );\n\n // No adapters configured: the provider's activator/effects are inert, so skip\n // it entirely and keep the wallet controller module off the render path.\n if (adapters.length === 0) return <>{children}</>;\n\n return (\n <RenownWalletProvider adapters={adapters} theme={walletTheme}>\n {children}\n </RenownWalletProvider>\n );\n}\n","import { Analytics } from \"./analytics.js\";\nimport { OpenPanel } from \"./openpanel.js\";\nimport { Router } from \"./router.js\";\n\nimport { connectConfig } from \"@powerhousedao/connect/config\";\nimport { SentryProvider } from \"../context/sentry-provider.js\";\nimport {\n DocumentEditorDebugTools,\n initLaunchQueueFileHandling,\n serviceWorkerManager,\n} from \"@powerhousedao/connect/utils\";\nimport { useEditorPreloader, useTheme } from \"@powerhousedao/reactor-browser\";\nimport { lazy, Suspense, useEffect } from \"react\";\nimport { ToastContainer } from \"../services/toast.js\";\nimport { MissingModelBanner } from \"./missing-model-banner.js\";\nimport { OpenFileUploadList } from \"./open-file-upload-list.js\";\nimport { PackageInstallPrompt } from \"./package-install-prompt.js\";\nimport { RenownWalletProviders } from \"./renown-wallet-providers.js\";\n\n// Its AI and MCP packages load only when the assistant is on.\nconst ConnectReactorChatFab = lazy(() =>\n import(\"./reactor-chat.js\").then((m) => ({\n default: m.ConnectReactorChatFab,\n })),\n);\n\nexport const App = () => {\n useTheme(); // keeps the OS-preference change listener active\n useEditorPreloader(); // warms editor chunks during idle time\n\n // refresh page on vite preload error due to outdated chunks — but only when\n // the failing dynamic import is one of Connect's own chunks. External\n // dynamic imports (e.g. the package manager loading a package from the\n // configured CDN) should let the error propagate so the caller can surface\n // it; reloading here drops any open state and hides the real failure.\n useEffect(() => {\n const handlePreloadError = (event: Event) => {\n const payload = (event as Event & { payload?: unknown }).payload;\n const message =\n payload instanceof Error\n ? payload.message\n : typeof payload === \"string\"\n ? payload\n : \"\";\n const failedUrl = message.match(/https?:\\/\\/[^\\s\"']+/)?.[0];\n\n if (failedUrl && !failedUrl.startsWith(window.location.origin)) {\n console.debug(\n `[Connect] Skipping reload — vite:preloadError for off-origin URL: ${failedUrl}`,\n );\n return;\n }\n\n console.log(\"Outdated chunks detected, reloading page...\");\n window.location.reload();\n };\n\n window.addEventListener(\"vite:preloadError\", handlePreloadError);\n\n return () => {\n window.removeEventListener(\"vite:preloadError\", handlePreloadError);\n };\n }, []);\n\n useEffect(() => {\n if (import.meta.env.MODE === \"development\") {\n window.documentEditorDebugTools = new DocumentEditorDebugTools();\n } else if (connectConfig.offline) {\n serviceWorkerManager.registerServiceWorker(false);\n } else {\n // Offline disabled — drop any worker a previous offline build left running.\n void serviceWorkerManager.unregisterAll();\n }\n }, []);\n\n // Files the OS opens with the installed PWA (manifest file_handlers).\n // launchQueue buffers launches until a consumer registers, so nothing is lost\n // by wiring it on mount; a no-op where the API doesn't exist.\n useEffect(() => {\n initLaunchQueueFileHandling();\n }, []);\n\n return (\n <SentryProvider>\n <RenownWalletProviders>\n <ToastContainer position=\"bottom-right\" />\n {connectConfig.aiAssistantEnabled && (\n <Suspense name=\"ReactorChat\" fallback={null}>\n <ConnectReactorChatFab />\n </Suspense>\n )}\n <MissingModelBanner />\n <Router />\n <OpenFileUploadList />\n <PackageInstallPrompt />\n <Analytics />\n <OpenPanel />\n </RenownWalletProviders>\n </SentryProvider>\n );\n};\n","import { showPHModal } from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n getWorkerConnectionStatus,\n subscribeWorkerConnection,\n type WorkerConnectionStatus,\n} from \"../connection-state.js\";\n\nconst CONNECTED: WorkerConnectionStatus = \"connected\";\n\nconst BANNER_TEXT: Record<\n Exclude<WorkerConnectionStatus, \"connected\">,\n { title: string; detail: string }\n> = {\n failed: {\n title: \"Reactor worker failed to load\",\n detail:\n \"The background worker script could not be loaded. Reload to retry.\",\n },\n lost: {\n title: \"Lost connection to the reactor\",\n detail: \"The background worker stopped responding. Reload to reconnect.\",\n },\n \"storage-held\": {\n title: \"Waiting for another Connect tab\",\n detail:\n \"Another Connect tab still holds local storage. Close or reload the other Connect tabs to continue.\",\n },\n \"version-conflict\": {\n title: \"Connect tabs are on different builds\",\n detail:\n \"Open tabs keep restarting the reactor. Close the other Connect tabs, then reload.\",\n },\n \"storage-unusable\": {\n title: \"Local storage is unusable\",\n detail:\n \"The local database stopped responding. Clear storage to start over, or reload to retry.\",\n },\n};\n\nexport const ConnectionBanner: React.FC = () => {\n const status = useSyncExternalStore(\n subscribeWorkerConnection,\n getWorkerConnectionStatus,\n () => CONNECTED,\n );\n\n if (status === \"connected\") {\n return null;\n }\n\n const { title, detail } = BANNER_TEXT[status];\n\n return (\n <div className=\"absolute inset-x-0 top-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-destructive bg-warning px-4 py-3 text-sm text-warning-foreground shadow-lg\">\n <div className=\"flex-1\">\n <div className=\"font-semibold\">{title}</div>\n <div className=\"text-foreground\">{detail}</div>\n </div>\n {status === \"storage-unusable\" && (\n <button\n type=\"button\"\n onClick={() => showPHModal({ type: \"clearStorage\" })}\n className=\"rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect\"\n >\n Clear storage\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => window.location.reload()}\n className=\"rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect\"\n >\n Reload\n </button>\n </div>\n </div>\n );\n};\n","import { lazy, Suspense } from \"react\";\nimport { ErrorBoundary } from \"./error-boundary.js\";\n\nconst CookieBanner = lazy(() =>\n import(\"./cookie-banner.js\").then((m) => ({ default: m.CookieBanner })),\n);\n\n/** Asks for the analytics consent that active plugins need; without one, consent stays rejected. */\nexport function CookieConsent() {\n // An optional, ad-blocker-vulnerable chunk: if blocked, the app runs with analytics off.\n return (\n <ErrorBoundary variant=\"silent\" loggerContext={[\"Connect\", \"CookieBanner\"]}>\n <Suspense fallback={null} name=\"CookieBanner\">\n <CookieBanner />\n </Suspense>\n </ErrorBoundary>\n );\n}\n","import { getConnectPluginUi } from \"@powerhousedao/connect-core/plugins\";\nimport { CookieConsent } from \"./cookie-consent.js\";\n\n/** What the active plugins render beside the app, and the consent banner when one needs it. */\nexport function PluginRoots() {\n const { roots, consent } = getConnectPluginUi();\n return (\n <>\n {consent && <CookieConsent />}\n {roots.map((Root, i) => (\n <Root key={i} />\n ))}\n </>\n );\n}\n","import {\n CURRENT_PG_MAJOR,\n getCachedMigrationMajor,\n migrateAllIfNeeded,\n subscribeMigrationMajor,\n} from \"@powerhousedao/connect/utils\";\nimport { useReactorClientModule } from \"@powerhousedao/reactor-browser\";\nimport type { IWorkerAdminClient } from \"@powerhousedao/reactor-browser/rpc\";\nimport { useState, useSyncExternalStore } from \"react\";\n\nfunction BannerShell({\n title,\n body,\n error,\n children,\n}: {\n title: string;\n body: string;\n error?: string | null;\n children?: React.ReactNode;\n}) {\n return (\n <div className=\"absolute inset-x-0 top-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-warning bg-warning px-4 py-3 text-sm text-warning-foreground shadow-lg\">\n <div className=\"flex-1\">\n <div className=\"font-semibold\">{title}</div>\n <div className=\"text-foreground\">{body}</div>\n {error && (\n <div className=\"mt-2 font-medium text-destructive\">\n Migration failed: {error}\n </div>\n )}\n </div>\n {children}\n </div>\n </div>\n );\n}\n\nconst actionButton =\n \"rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect disabled:disabled-effect\";\nconst dismissButton =\n \"rounded-sm border border-foreground bg-transparent px-3 py-1 text-sm font-medium text-foreground hover:hover-effect disabled:disabled-effect\";\n\nlet browserDismissed = false;\nconst browserListeners = new Set<() => void>();\n\nfunction WorkerMigrationBanner({\n adminClient,\n}: {\n adminClient: IWorkerAdminClient;\n}) {\n const state = useSyncExternalStore(\n (cb) => adminClient.subscribeMigration(cb),\n () => adminClient.getMigrationState(),\n );\n const [dismissed, setDismissed] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n if (state.status === \"idle\") return null;\n if (state.status === \"needed\" && dismissed) return null;\n\n const migrating = state.status === \"migrating\";\n const handleMigrate = () => {\n setError(null);\n adminClient.migrate().catch((err: unknown) => {\n setError(err instanceof Error ? err.message : String(err));\n });\n };\n\n return (\n <BannerShell\n title={\n migrating\n ? `Migrating to Postgres ${CURRENT_PG_MAJOR}…`\n : `Your local database uses Postgres ${state.legacyMajor ?? \"?\"}.`\n }\n body={\n migrating\n ? `Working (${state.phase ?? \"starting\"}). Your data is backed up first.`\n : `Migrate to Postgres ${CURRENT_PG_MAJOR} to pick up the latest features. Your data will be backed up first.`\n }\n error={error ?? (state.status === \"failed\" ? state.error : null)}\n >\n {!migrating && (\n <button type=\"button\" onClick={handleMigrate} className={actionButton}>\n {state.status === \"failed\" ? \"Retry\" : \"Migrate now\"}\n </button>\n )}\n {state.status === \"needed\" && (\n <button\n type=\"button\"\n onClick={() => setDismissed(true)}\n className={dismissButton}\n >\n Dismiss\n </button>\n )}\n </BannerShell>\n );\n}\n\nfunction BrowserMigrationBanner() {\n const isDismissed = useSyncExternalStore(\n (cb) => {\n browserListeners.add(cb);\n return () => browserListeners.delete(cb);\n },\n () => browserDismissed,\n () => false,\n );\n const major = useSyncExternalStore(\n subscribeMigrationMajor,\n getCachedMigrationMajor,\n () => undefined,\n );\n const [migrating, setMigrating] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n if (major === undefined || major === null || major === CURRENT_PG_MAJOR) {\n return null;\n }\n if (isDismissed) return null;\n\n const handleMigrate = () => {\n setError(null);\n setMigrating(true);\n migrateAllIfNeeded()\n .then(() => window.location.reload())\n .catch((err: unknown) => {\n setError(err instanceof Error ? err.message : String(err));\n setMigrating(false);\n });\n };\n\n return (\n <BannerShell\n title={`Your local database uses Postgres ${major}.`}\n body={`Migrate to Postgres ${CURRENT_PG_MAJOR} to pick up the latest features. Your data will be backed up first.`}\n error={error}\n >\n <button\n type=\"button\"\n disabled={migrating}\n onClick={handleMigrate}\n className={actionButton}\n >\n {migrating ? \"Migrating…\" : \"Migrate now\"}\n </button>\n <button\n type=\"button\"\n disabled={migrating}\n onClick={() => {\n browserDismissed = true;\n for (const l of browserListeners) l();\n }}\n className={dismissButton}\n >\n Dismiss\n </button>\n </BannerShell>\n );\n}\n\nexport const MigrationBanner: React.FC = () => {\n const module = useReactorClientModule();\n if (module?.kind === \"worker\") {\n return <WorkerMigrationBanner adminClient={module.adminClient} />;\n }\n return <BrowserMigrationBanner />;\n};\n","import {\n getServiceWorkerUpdateAvailable,\n serviceWorkerManager,\n subscribeServiceWorkerUpdate,\n} from \"@powerhousedao/connect/utils\";\nimport { useSyncExternalStore } from \"react\";\n\n// Prompts the user to load a waiting service-worker update, so a new version\n// never reloads over in-progress work.\nexport const ServiceWorkerUpdatePrompt: React.FC = () => {\n const updateAvailable = useSyncExternalStore(\n subscribeServiceWorkerUpdate,\n getServiceWorkerUpdateAvailable,\n () => false,\n );\n\n if (!updateAvailable) return null;\n\n return (\n <div className=\"absolute inset-x-0 bottom-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-foreground bg-primary px-4 py-3 text-sm text-primary-foreground shadow-lg\">\n <div className=\"flex-1 font-medium\">\n A new version of Connect is available.\n </div>\n <button\n type=\"button\"\n onClick={() => serviceWorkerManager.applyUpdate()}\n className=\"rounded-sm bg-primary-foreground px-3 py-1 text-sm font-medium text-primary hover:hover-effect\"\n >\n Refresh\n </button>\n </div>\n </div>\n );\n};\n","import { Icon, PowerhouseButton } from \"@powerhousedao/design-system\";\n\n/** Boot screen for a reactor that refused this browser's stored documents. */\nexport function StoredDocumentsRefusedFallback({ error }: { error: Error }) {\n return (\n <div className=\"z-10 mx-auto flex max-w-[80%] flex-1 items-center justify-center p-6\">\n <div\n role=\"alert\"\n className=\"w-full max-w-lg rounded-lg border border-border bg-card p-6 text-foreground shadow-sm\"\n >\n <div className=\"mb-3 flex items-center gap-2\">\n <Icon name=\"Error\" className=\"size-5 shrink-0 text-destructive\" />\n <h1 className=\"text-lg font-semibold text-foreground\">\n Connect cannot open this browser&apos;s documents\n </h1>\n </div>\n <p className=\"mb-4 text-sm wrap-break-word text-foreground\">\n {error.message}\n </p>\n <PowerhouseButton\n type=\"button\"\n onClick={() => {\n window.location.reload();\n }}\n className=\"px-3 py-1.5 text-base font-medium\"\n >\n Reload\n </PowerhouseButton>\n </div>\n </div>\n );\n}\n","import \"@powerhousedao/connect/i18n\";\nimport { getConnectPHStore } from \"@powerhousedao/connect-core/runtime\";\nimport { PHStoreProvider } from \"@powerhousedao/reactor-browser\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { lazy, StrictMode, Suspense } from \"react\";\nimport AppSkeleton from \"./app-skeleton.js\";\nimport { DetailedFallback, ErrorBoundary } from \"./error-boundary.js\";\nimport { App } from \"./app.js\";\nimport { ConnectionBanner } from \"./connection-banner.js\";\nimport { PluginRoots } from \"./plugin-roots.js\";\nimport { MigrationBanner } from \"./migration-banner.js\";\nimport { LoadingShell } from \"./prerendered-shell.js\";\nimport { ServiceWorkerUpdatePrompt } from \"./service-worker-update-prompt.js\";\nimport { StoredDocumentsRefusedFallback } from \"./stored-documents-refused.js\";\nimport { isStoredDocumentsRefused } from \"../utils/stored-documents-refused.js\";\n\nexport const AppLoader = (props: {\n localPackage?: DocumentModelLib | Promise<DocumentModelLib>;\n}) => {\n const phStore = getConnectPHStore();\n const Load = lazy(() =>\n import(\"./load.js\").then((m) =>\n m.loadComponent(props.localPackage, phStore),\n ),\n );\n return (\n <StrictMode>\n <PHStoreProvider store={phStore}>\n <ErrorBoundary\n fallbackRender={(props) => (\n <AppSkeleton\n children={\n isStoredDocumentsRefused(props.error) ? (\n <StoredDocumentsRefusedFallback error={props.error} />\n ) : (\n <DetailedFallback {...props} />\n )\n }\n />\n )}\n resetKeys={[props.localPackage]}\n loggerContext={[\"Connect\"]}\n >\n <Suspense\n fallback={<LoadingShell Fallback={AppSkeleton} />}\n name=\"AppLoader\"\n >\n {/* eslint-disable-next-line react-hooks-extra/static-components */}\n <Load {...props}>\n <App />\n <PluginRoots />\n </Load>\n </Suspense>\n <MigrationBanner />\n <ServiceWorkerUpdatePrompt />\n <ConnectionBanner />\n </ErrorBoundary>\n </PHStoreProvider>\n </StrictMode>\n );\n};\n"],"names":["emptyArray","logger","rawEvents","CookieBanner"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAMA,eAAmC,CAAC;AAE1C,SAAgB,yBAAyB;CACvC,MAAM,mBAAmB,2BAA2B;CACpD,OAAO,sBACJ,OAAO,kBAAkB,gBAAgB,EAAE,YAAY,CAAC,UACnD,kBAAkB,uBAAuB,KAAKA,YACtD;AACF;;;ACLA,MAAMC,WAAS,YAAY,CAAC,QAAQ,CAAC;AAErC,IAAI,gBAAgB;AAEpB,eAAe,YAAY;CACzB,OAAO,MAAM,OAAO;AACtB;AAEA,eAAe,aAAa;CAC1B,MAAM,SAAS,MAAM,UAAU;CAC/B,MAAM,eAA+C;EACnD,OAAO,sBAAsB;EAC7B,OAAO,0BAA0B,EAAE,OAAO,EAAE,CAAC;EAC7C,OAAO,kBAAkB;EACzB,OAAO,0BAA0B,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CACxD;CACA,IAAI,cAAc,OAAO,SAAS;EAEhC,MAAM,EAAE,qBAAqB,MAAM,OAAO;EAC1C,aAAa,KACX,OAAO,wCAAwC,iBAAiB,CAAC,CACnE;CACF;CAEA,OAAO,KAAK;EACV,SAAS,cAAc,OAAO;EAC9B,KAAK,cAAc,OAAO,OAAO,KAAA;EACjC,aAAa,cAAc,OAAO;EAClC;EACA,cAAc;GACZ;GACA;GACA;EACF;EACA,gBAAgB;EAChB,kBAAkB;EAClB,0BAA0B;EAC1B,0BAA0B;EAC1B,WAAW,OAAO,MAAM;GACtB,MAAM,QAAQ,KAAK;GACnB,IACE,iBAAiB,aACjB,MAAM,QAAQ,SAAS,iBAAiB,KACxC,CAAC,UAAU,QAGX,OAAO;GAET,OAAO;EACT;CACF,CAAC;CAED,gBAAgB,MAAM;CACtB,gBAAgB;AAClB;AAEA,eAAe,cAAc;CA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E,MAAK;KACL,eAAe;MACb,OAAO,SAAS,OAAO;KACzB;KACA,WAAU;KACX,UAAA;IAEiB,CAAA;GACf;;CACF,CAAA;AAET;;;ACfA,MAAa,aAAa,UAEpB;CACJ,MAAM,UAAU,kBAAkB;CAClC,MAAM,OAAO,WACX,OAAO,qBAAY,CAAC,MAAM,MACxB,EAAE,cAAc,MAAM,cAAc,OAAO,CAC7C,CACF;CACA,OACE,oBAAC,YAAD,EAAA,UACE,oBAAC,iBAAD;EAAiB,OAAO;EACtB,UAAA,qBAAC,eAAD;GACE,iBAAiB,UACf,oBAAC,aAAD,EACE,UACE,yBAAyB,MAAM,KAAK,IAClC,oBAAC,gCAAD,EAAgC,OAAO,MAAM,MAAQ,CAAA,IAErD,oBAAC,kBAAD,EAAkB,GAAI,MAAQ,CAAA,EAGnC,CAAA;GAEH,WAAW,CAAC,MAAM,YAAY;GAC9B,eAAe,CAAC,SAAS;GAb3B,UAAA;IAeE,oBAAC,UAAD;KACE,UAAU,oBAAC,cAAD,EAAc,UAAU,YAAc,CAAA;KAChD,MAAK;KAGL,UAAA,qBAAC,MAAD;MAAM,GAAI;MAAV,UAAA,CACE,oBAAC,KAAD,CAAM,CAAA,GACN,oBAAC,aAAD,CAAc,CAAA,CACV;;IACE,CAAA;IACV,oBAAC,iBAAD,CAAkB,CAAA;IAClB,oBAAC,2BAAD,CAA4B,CAAA;IAC5B,oBAAC,kBAAD,CAAmB,CAAA;GACN;;CACA,CAAA,EACP,CAAA;AAEhB","debug_id":"ea69e200-b283-5f92-abc7-6e1158293abf"}
1
+ {"version":3,"file":"app-loader-Ctuh_wUx.js","sources":["../src/hooks/useFailedInstallations.ts","../src/hooks/useInitSentry.ts","../src/hooks/usePendingInstallations.ts","../src/services/openpanel/client.ts","../src/services/openpanel/events.json","../src/services/openpanel/events.ts","../src/services/openpanel/processor.ts","../src/services/openpanel/factory.ts","../src/components/analytics.tsx","../src/components/openpanel-traits.ts","../src/components/openpanel.tsx","../src/context/sentry-provider.tsx","../src/utils/document-editor-debug-tools.ts","../src/utils/pglite-migration.ts","../src/components/missing-model-banner.tsx","../src/components/open-file-upload-list.tsx","../src/components/package-install-prompt.tsx","../src/components/renown-adapter-descriptors.ts","../src/components/renown-wallet-providers.tsx","../src/components/app.tsx","../src/components/connection-banner.tsx","../src/components/cookie-consent.tsx","../src/components/plugin-roots.tsx","../src/components/migration-banner.tsx","../src/components/service-worker-update-prompt.tsx","../src/components/stored-documents-refused.tsx","../src/components/app-loader.tsx"],"sourcesContent":["import {\n usePackageDiscoveryService,\n type FailedInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\n\nconst emptyArray: FailedInstallation[] = [];\n\nexport function useFailedInstallations() {\n const discoveryService = usePackageDiscoveryService();\n return useSyncExternalStore(\n (cb) => discoveryService?.subscribeFailed(cb) ?? (() => {}),\n () => discoveryService?.getFailedInstallations() ?? emptyArray,\n );\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\n\nimport type { BrowserOptions } from \"@sentry/react\";\n\nimport { childLogger } from \"document-model\";\nimport { useEffect } from \"react\";\nimport { setSentryModule } from \"../services/sentry.js\";\nimport { useAcceptedCookies } from \"./preferences-store.js\";\n\nconst logger = childLogger([\"sentry\"]);\n\nlet clientStarted = false;\n\nasync function getSentry() {\n return await import(\"@sentry/react\");\n}\n\nasync function initSentry() {\n const Sentry = await getSentry();\n const integrations: BrowserOptions[\"integrations\"] = [\n Sentry.httpClientIntegration(),\n Sentry.extraErrorDataIntegration({ depth: 5 }),\n Sentry.replayIntegration(),\n Sentry.captureConsoleIntegration({ levels: [\"error\"] }),\n ];\n if (connectConfig.sentry.tracing) {\n // Dynamic import: the router module pulls in the app's component tree.\n const { getConnectRouter } = await import(\"../components/router.js\");\n integrations.push(\n Sentry.tanstackRouterBrowserTracingIntegration(getConnectRouter()),\n );\n }\n\n Sentry.init({\n release: connectConfig.sentry.release,\n dsn: connectConfig.sentry.dsn ?? undefined,\n environment: connectConfig.sentry.env,\n integrations,\n ignoreErrors: [\n \"User is not allowed to create files\",\n \"User is not allowed to move documents\",\n \"The user aborted a request.\",\n ],\n sendDefaultPii: true,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n beforeSend(event, hint) {\n const error = hint.originalException;\n if (\n error instanceof TypeError &&\n error.message.includes(\"Failed to fetch\") &&\n !navigator.onLine\n ) {\n // If fetch fails because user is offline then ignores the error\n return null;\n }\n return event;\n },\n });\n\n setSentryModule(Sentry);\n clientStarted = true;\n}\n\nasync function closeClient() {\n if (!clientStarted) {\n return;\n }\n const sentry = await getSentry();\n setSentryModule(undefined);\n const client = sentry.getClient();\n return client?.close();\n}\n\nexport function useInitSentry() {\n const [acceptedCookies] = useAcceptedCookies();\n const { analytics } = acceptedCookies;\n\n useEffect(() => {\n if (!analytics) {\n closeClient().catch((error: unknown) => logger.error(\"@error\", error));\n return;\n }\n\n // Sentry is disabled when `dsn` is null, undefined, or an empty\n // string — covers both the new schema default (`null`) and any\n // hand-edited config that omits the DSN.\n if (\n clientStarted ||\n connectConfig.sentry.dsn === null ||\n connectConfig.sentry.dsn === undefined ||\n connectConfig.sentry.dsn === \"\"\n ) {\n return;\n }\n\n initSentry().catch((error: unknown) => logger.error(\"@error\", error));\n }, [analytics]);\n}\n","import {\n usePackageDiscoveryService,\n type PendingInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst emptyArray: readonly PendingInstallation[] = [];\n\nexport function usePendingInstallations() {\n const discoveryService = usePackageDiscoveryService();\n const cacheRef = useRef<readonly PendingInstallation[]>(emptyArray);\n\n const getSnapshot = useCallback(() => {\n if (!discoveryService) return emptyArray;\n const next = discoveryService.getPendingInstallations() ?? emptyArray;\n const prev = cacheRef.current;\n if (\n next === prev ||\n (next.length === prev.length && next.every((p, i) => p === prev[i]))\n ) {\n return prev;\n }\n cacheRef.current = next;\n return next;\n }, [discoveryService]);\n\n return useSyncExternalStore(\n (cb) => discoveryService?.subscribePending(cb) ?? (() => {}),\n getSnapshot,\n );\n}\n","import type { OpenPanel } from \"@openpanel/web\";\n\nimport { clearOpenPanelBuffer, drainOpenPanelBuffer } from \"./buffer.js\";\nimport type { OpenPanelConfig } from \"./types.js\";\n\nlet client: OpenPanel | undefined;\n\n/**\n * Returns the cached `OpenPanel` singleton, building it on first call.\n *\n * When `config.clientId` is empty it returns `undefined` without importing\n * `@openpanel/web`, so the bundler can tree-shake the SDK out of production.\n */\nexport async function getOpenPanelClient(\n config: OpenPanelConfig,\n): Promise<OpenPanel | undefined> {\n if (!config.clientId) {\n return undefined;\n }\n\n if (client) {\n return client;\n }\n\n // Dynamic import keeps @openpanel/web out of the initial chunk.\n const { OpenPanel: OpenPanelClass } = await import(\"@openpanel/web\");\n\n client = new OpenPanelClass({\n clientId: config.clientId,\n ...(config.apiUrl ? { apiUrl: config.apiUrl } : {}),\n trackScreenViews: true,\n trackOutgoingLinks: true,\n });\n\n // The web SDK has no `globalProperties` constructor option.\n client.setGlobalProperties({ app: \"connect\" });\n\n // Runs once (the `if (client)` guard above), so the buffer is never\n // double-drained.\n drainOpenPanelBuffer(client);\n\n return client;\n}\n\n/**\n * Clears the cached singleton and the pre-init buffer. Call on consent\n * revocation or during tests; buffered events are discarded, not replayed.\n */\nexport function resetOpenPanelClient(): void {\n client = undefined;\n clearOpenPanelBuffer();\n}\n","","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\n\nimport type { OpenPanelEventMapping } from \"./types.js\";\nimport rawEvents from \"./events.json\" with { type: \"json\" };\n\nconst EventMappingSchema = z\n .object({\n documentType: z.string().min(1),\n actionTypes: z.array(z.string().min(1)).min(1),\n alias: z.string().optional(),\n })\n .strict();\n\nconst EventMappingsSchema = z.array(EventMappingSchema).readonly();\n\n/**\n * Parses and validates the event mapping table, returning the validated array\n * and an O(1) lookup map. Accepts a `raw` override for tests. Throws on zod\n * failures and on duplicate `(documentType, actionType)` pairs.\n */\nexport function loadEvents(raw: unknown = rawEvents): {\n mappings: readonly OpenPanelEventMapping[];\n lookupMap: Map<string, Map<string, OpenPanelEventMapping>>;\n} {\n const result = EventMappingsSchema.safeParse(raw);\n if (!result.success) {\n throw new Error(`Invalid OpenPanel events.json: ${result.error.message}`);\n }\n\n const mappings = result.data as readonly OpenPanelEventMapping[];\n const lookupMap = new Map<string, Map<string, OpenPanelEventMapping>>();\n\n for (const mapping of mappings) {\n let inner = lookupMap.get(mapping.documentType);\n if (!inner) {\n inner = new Map<string, OpenPanelEventMapping>();\n lookupMap.set(mapping.documentType, inner);\n }\n\n for (const actionType of mapping.actionTypes) {\n if (inner.has(actionType)) {\n throw new Error(\n `Duplicate OpenPanel event mapping for ${mapping.documentType}/${actionType}`,\n );\n }\n inner.set(actionType, mapping);\n }\n }\n\n return { mappings, lookupMap };\n}\n\nconst { mappings: defaultMappings, lookupMap: defaultLookupMap } = loadEvents();\n\n/** Validated mapping array from the bundled events.json. */\nexport const eventMappings: readonly OpenPanelEventMapping[] = defaultMappings;\n\n/** O(1) lookup map: documentType → actionType → mapping. */\nexport const eventLookupMap: Map<\n string,\n Map<string, OpenPanelEventMapping>\n> = defaultLookupMap;\n\n/**\n * Normalizes a document type into a safe event-name segment: lowercased, `/`\n * replaced with `.`, and any character outside `[a-z0-9._-]` stripped.\n * e.g. `powerhouse/document-drive` → `powerhouse.document-drive`.\n */\nexport function normalize(documentType: string): string {\n return documentType\n .toLowerCase()\n .replace(/\\//g, \".\")\n .replace(/[^a-z0-9._-]/g, \"\");\n}\n\n/**\n * Derives the OpenPanel event name: `mapping.alias` when present, otherwise\n * `${normalize(documentType)}.${actionType.toLowerCase()}`.\n */\nexport function deriveEventName(\n mapping: OpenPanelEventMapping,\n op: OperationWithContext,\n): string {\n if (mapping.alias) {\n return mapping.alias;\n }\n return `${normalize(op.context.documentType)}.${op.operation.action.type.toLowerCase()}`;\n}\n\n/**\n * Builds the default properties attached to every OpenPanel event. The `app`\n * property is stamped globally by the client, not here.\n */\nexport function buildDefaultProperties(op: OperationWithContext): {\n documentType: string;\n actionType: string;\n documentId: string;\n scope: string;\n branch: string;\n} {\n return {\n documentType: op.context.documentType,\n actionType: op.operation.action.type,\n documentId: op.context.documentId,\n scope: op.context.scope,\n branch: op.context.branch,\n };\n}\n","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport type { IProcessor } from \"@powerhousedao/shared/processors\";\n\nimport { buildDefaultProperties, deriveEventName } from \"./events.js\";\nimport type { OpenPanelEventMapping } from \"./types.js\";\n\n/**\n * Minimal structural type for the injected analytics client. Keeps\n * `@openpanel/web` out of the runtime import graph and makes test fakes\n * trivial; the real `OpenPanel` instance satisfies it structurally.\n */\nexport type OpenPanelTracker = {\n track: (name: string, properties?: Record<string, unknown>) => unknown;\n flush?: () => void;\n};\n\n/**\n * Read-only reactor `IProcessor` that translates matching document operations\n * into OpenPanel analytics events. Operations whose `(documentType, actionType)`\n * pair is absent from the lookup map are skipped; per-operation errors are\n * routed to `onError` and never thrown back to the manager.\n */\nexport class OpenPanelProcessor implements IProcessor {\n constructor(\n private readonly client: OpenPanelTracker,\n private readonly lookupMap: Map<string, Map<string, OpenPanelEventMapping>>,\n private readonly onError: (\n err: unknown,\n op?: OperationWithContext,\n ) => void = (err) =>\n console.warn(\"[OpenPanelProcessor] Error tracking event:\", err),\n ) {}\n\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n for (const op of operations) {\n const inner = this.lookupMap.get(op.context.documentType);\n if (!inner) continue;\n\n const mapping = inner.get(op.operation.action.type);\n if (!mapping) continue;\n\n const name = deriveEventName(mapping, op);\n const payload = buildDefaultProperties(op);\n\n try {\n await this.client.track(name, payload);\n } catch (err) {\n this.onError(err, op);\n }\n }\n }\n\n onDisconnect(): Promise<void> {\n this.client.flush?.();\n return Promise.resolve();\n }\n}\n","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport type { PHDocumentHeader } from \"@powerhousedao/shared/document-model\";\nimport type {\n ProcessorFactory,\n ProcessorRecord,\n} from \"@powerhousedao/shared/processors\";\n\nimport { OpenPanelProcessor, type OpenPanelTracker } from \"./processor.js\";\nimport type { OpenPanelEventMapping } from \"./types.js\";\n\nexport type OpenPanelProcessorFactoryConfig = {\n /** The initialized analytics client to forward events to. */\n client: OpenPanelTracker;\n\n /** Loaded event mapping data, as returned by `loadEvents()`. */\n events: {\n mappings: readonly OpenPanelEventMapping[];\n lookupMap: Map<string, Map<string, OpenPanelEventMapping>>;\n };\n\n /** Replay window. Defaults to `\"current\"` (no historical replay). */\n startFrom?: \"current\" | \"beginning\";\n\n /** Error handler; defaults to `console.warn`. */\n onError?: (err: unknown, op?: OperationWithContext) => void;\n};\n\n/**\n * Returns a `ProcessorFactory` that, for each drive, creates a single\n * `OpenPanelProcessor` record whose `filter.documentType` is the union of all\n * document types present in the event mapping table.\n */\nexport function createOpenPanelProcessorFactory(\n config: OpenPanelProcessorFactoryConfig,\n): ProcessorFactory {\n return function openPanelProcessorFactory(\n _driveHeader: PHDocumentHeader,\n ): ProcessorRecord[] {\n const documentType = Array.from(config.events.lookupMap.keys());\n\n const processor = new OpenPanelProcessor(\n config.client,\n config.events.lookupMap,\n config.onError,\n );\n\n const record: ProcessorRecord = {\n processor,\n filter: { documentType },\n startFrom: config.startFrom ?? \"current\",\n };\n\n return [record];\n };\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useAcceptedCookies } from \"../hooks/preferences-store.js\";\nimport { useEffect } from \"react\";\n\ndeclare global {\n interface Window {\n gtag?: (...args: any[]) => void;\n dataLayer?: any[];\n }\n}\n\nfunction gtag(...args: (string | Date)[]) {\n window.dataLayer?.push(...args);\n}\n\nexport const Analytics = () => {\n const gaTrackingId = connectConfig.gaTrackingId;\n const [{ analytics }] = useAcceptedCookies();\n const useAnalytics = gaTrackingId && analytics;\n\n useEffect(() => {\n if (useAnalytics) {\n // Create the GA script tag\n const script = document.createElement(\"script\");\n script.src = `https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`;\n script.async = true;\n document.head.appendChild(script);\n\n // Initialize GA\n window.dataLayer = window.dataLayer || [];\n\n gtag(\"js\", new Date());\n gtag(\"config\", gaTrackingId);\n\n // Clean up the script if no longer enabled\n return () => {\n document.head.removeChild(script);\n };\n }\n }, [useAnalytics, gaTrackingId]);\n\n return null;\n};\n","import type { User } from \"@renown/sdk\";\n\n/**\n * Builds the OpenPanel identity traits from a renown User.\n *\n * Canonical trait schema (shared with Renown and Vetra — each app sends every\n * field it has data for, under these names):\n * - `address`, `did`, `networkId`, `chainId`, `caip2` — wallet/chain facts.\n * - `ensName`, `ensAvatar` — raw ENS facts.\n * - `username`, `userImage`, `profileDocumentId`, `profileCreatedAt` — raw\n * Renown profile facts.\n * - `accountType` — wallet-adapter concept; only Renown has it.\n *\n * Rules:\n * - `credential` (contains a JWT) is **never** forwarded.\n * - Traits carry raw facts only; resolved presentation values (avatar,\n * display name) go in OpenPanel's native identify fields — see\n * {@link buildIdentifyPayload}.\n * - Optional fields (`ens`, `profile`) are only included when their value is\n * non-nullish (guards against `null` from `RenownProfile` fields as well\n * as plain `undefined`).\n *\n * Mirror the Sentry pattern in `store/user.ts`: destructure off `credential`\n * first, then assemble the trait payload from the remainder.\n */\nexport function buildTraits(user: User): Record<string, unknown> {\n // Destructure credential off so it can never accidentally make it into the\n // returned object.\n const { credential: _credential, ...rest } = user;\n\n const traits: Record<string, unknown> = {\n address: rest.address,\n did: rest.did,\n networkId: rest.networkId,\n chainId: rest.chainId,\n caip2: `${rest.networkId}:${rest.chainId}`,\n };\n\n // ens fields — optional on the User type\n if (rest.ens?.name != null) {\n traits.ensName = rest.ens.name;\n }\n if (rest.ens?.avatarUrl != null) {\n traits.ensAvatar = rest.ens.avatarUrl;\n }\n\n // profile fields — optional on InternalUser; RenownProfile members can be\n // null, so guard with != null (catches both null and undefined)\n if (rest.profile?.username != null) {\n traits.username = rest.profile.username;\n }\n if (rest.profile?.userImage != null) {\n traits.userImage = rest.profile.userImage;\n }\n if (rest.profile?.documentId != null) {\n traits.profileDocumentId = rest.profile.documentId;\n }\n if (rest.profile?.createdAt != null) {\n traits.profileCreatedAt = rest.profile.createdAt;\n }\n\n return traits;\n}\n\n/**\n * Builds the full `identify()` payload:\n * - `profileId` is the wallet address — the cross-app profile key shared with\n * Renown and Vetra.\n * - `avatar` / `firstName` are OpenPanel's native profile fields (they drive\n * the picture and name in the dashboard UI), resolved as\n * `userImage ?? ensAvatar` and `ensName ?? username`.\n * - `properties` are the raw traits from {@link buildTraits}.\n */\nexport function buildIdentifyPayload(user: User): {\n profileId: string;\n avatar?: string;\n firstName?: string;\n properties: Record<string, unknown>;\n} {\n const avatar = user.profile?.userImage ?? user.ens?.avatarUrl;\n const firstName = user.ens?.name ?? user.profile?.username;\n\n return {\n profileId: user.address,\n ...(avatar != null ? { avatar } : {}),\n ...(firstName != null ? { firstName } : {}),\n properties: buildTraits(user),\n };\n}\n","import type { OpenPanel as OpenPanelClient } from \"@openpanel/web\";\nimport { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useAcceptedCookies } from \"../hooks/preferences-store.js\";\nimport {\n createOpenPanelProcessorFactory,\n eventLookupMap,\n eventMappings,\n getOpenPanelClient,\n resetOpenPanelClient,\n} from \"@powerhousedao/connect/services\";\nimport {\n useReactorClientModule,\n useUser,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { buildIdentifyPayload } from \"./openpanel-traits.js\";\n\ndeclare global {\n interface Window {\n openPanel?: OpenPanelClient;\n }\n}\n\n/**\n * `OpenPanel` is a `null`-rendering component that manages the full lifecycle\n * of the OpenPanel analytics subsystem.\n *\n * Gates:\n * - `useAcceptedCookies().analytics === true` — the existing analytics cookie.\n * - `connectConfig.openPanel.clientId` non-empty — no client ID → no-op.\n *\n * Behaviour when both gates pass:\n * 1. Lazy-imports `@openpanel/web` and builds the singleton via\n * `getOpenPanelClient(connectConfig.openPanel)`.\n * 2. Exposes the client on `window.openPanel` for the card-6\n * `useOpenPanelAnalytics()` hook to consume.\n * 3. If `connectConfig.openPanel.trackOperations`, registers the processor\n * factory against `processorManager` so document operations are forwarded.\n * 4. Calls `client.identify()` when the renown user transitions from\n * `undefined` → defined (login). The profile ID is the wallet address —\n * the cross-app key shared with Renown and Vetra.\n * 5. Calls `client.clear()` when the user transitions from defined →\n * `undefined` (logout).\n *\n * Teardown (unmount **or** consent revocation):\n * - `unregisterFactory(\"openpanel\")` to remove the processor.\n * - `resetOpenPanelClient()` to clear the singleton.\n * - `window.openPanel` is cleared.\n *\n * Mirrors the Sentry pattern in `store/user.ts` for login/logout detection.\n * Analytics failures are caught and forwarded to `console.warn` — they must\n * never throw into the application.\n *\n * Mounted next to `<Analytics />` in `app.tsx`.\n */\nexport function OpenPanel(): null {\n const [{ analytics }] = useAcceptedCookies();\n const user = useUser();\n const module = useReactorClientModule();\n const reactorClientModule = module?.kind === \"browser\" ? module : undefined;\n\n const [client, setClient] = useState<OpenPanelClient | undefined>();\n\n /**\n * Tracks the previous `user` value so we can detect the two transitions:\n * undefined → defined (login)\n * defined → undefined (logout)\n */\n const prevUserRef = useRef<ReturnType<typeof useUser>>(undefined);\n\n const enabled = analytics && !!connectConfig.openPanel.clientId;\n const processorManager = reactorClientModule?.reactorModule?.processorManager;\n\n useEffect(() => {\n if (!enabled) return;\n\n let cancelled = false;\n\n // Read via a call — TS would otherwise narrow direct reads to always-false.\n const isCancelled = () => cancelled;\n\n const setup = async () => {\n let builtClient: OpenPanelClient | undefined;\n try {\n builtClient = await getOpenPanelClient(connectConfig.openPanel);\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to build client:\", err);\n return;\n }\n\n if (isCancelled() || !builtClient) return;\n\n setClient(builtClient);\n window.openPanel = builtClient;\n\n if (connectConfig.openPanel.trackOperations && processorManager) {\n try {\n await processorManager.registerFactory(\n \"openpanel\",\n createOpenPanelProcessorFactory({\n client: builtClient,\n events: { mappings: eventMappings, lookupMap: eventLookupMap },\n startFrom: \"current\",\n }),\n );\n // Guard against teardown happening while registerFactory was in flight.\n if (isCancelled()) {\n await processorManager\n .unregisterFactory(\"openpanel\")\n .catch((err: unknown) =>\n console.warn(\n \"[OpenPanel] Failed to unregister factory after cancellation:\",\n err,\n ),\n );\n }\n } catch (err) {\n console.warn(\n \"[OpenPanel] Failed to register processor factory:\",\n err,\n );\n }\n }\n };\n\n void setup();\n\n return () => {\n cancelled = true;\n\n // Reset the user-tracking ref so that when consent is re-granted (and a\n // new client is built) any currently-logged-in user is re-identified.\n prevUserRef.current = undefined;\n\n if (connectConfig.openPanel.trackOperations && processorManager) {\n void processorManager\n .unregisterFactory(\"openpanel\")\n .catch((err: unknown) =>\n console.warn(\n \"[OpenPanel] Failed to unregister processor factory:\",\n err,\n ),\n );\n }\n\n resetOpenPanelClient();\n window.openPanel = undefined;\n setClient(undefined);\n };\n }, [enabled, processorManager]);\n\n // detect login/logout transitions\n useEffect(() => {\n if (!enabled || !client) return;\n\n const prev = prevUserRef.current;\n prevUserRef.current = user;\n\n if (!prev && user) {\n // Login: undefined → defined (or client became available with user\n // already logged in — prevUserRef is undefined in both cases).\n try {\n void client.identify(buildIdentifyPayload(user));\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to identify user:\", err);\n }\n } else if (prev && !user) {\n // Logout: defined → undefined\n try {\n void client.clear();\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to clear user:\", err);\n }\n }\n }, [client, user, enabled]);\n\n return null;\n}\n","import { useInitSentry } from \"../hooks/useInitSentry.js\";\n\ninterface SentryProviderProps {\n children?: React.ReactNode;\n}\n\nexport const SentryProvider: React.FC<SentryProviderProps> = ({ children }) => {\n useInitSentry();\n\n return children;\n};\n","import type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\n\nexport class DocumentEditorDebugTools {\n private document: PHDocument | undefined;\n private operations: Operation[] = [];\n\n constructor(document?: PHDocument) {\n if (document) {\n this.document = document;\n }\n }\n\n private operationsToTableObject(operations: Operation[]) {\n return operations.map((op) => ({\n ...op,\n input: JSON.stringify(op.action.input),\n }));\n }\n\n public setDocument(document: PHDocument) {\n this.document = document;\n }\n\n public getDocument() {\n return this.document;\n }\n\n public getOperations() {\n return this.operations;\n }\n\n public pushOperation(operation: Operation) {\n this.operations.push(operation);\n }\n\n public operationsTable() {\n if (!this.document) {\n console.warn(\"No document\");\n }\n const ops = Object.values(this.document?.operations || {})\n .filter((array): array is Operation[] => array !== undefined)\n .flatMap((array) => array)\n .sort((a, b) => a.index - b.index);\n\n console.table(this.operationsToTableObject(ops));\n }\n\n public scopeOperationsTable(scope: string) {\n if (!this.document) {\n console.warn(\"No document\");\n }\n const ops = this.document?.operations[scope] || [];\n console.table(this.operationsToTableObject(ops));\n }\n\n public operationsLog() {\n console.log(this.operations);\n }\n\n public operationsLogTable() {\n console.table(this.operationsToTableObject(this.operations));\n }\n\n public clear() {\n this.operations = [];\n this.document = undefined;\n }\n}\n","import { setMigrationStatus } from \"../components/migration-status.js\";\nimport { idbError } from \"./pglite-idb.js\";\nimport {\n type BackupStrategy,\n cloneFileData,\n migrateIdb,\n} from \"./pglite-migrate-core.js\";\nimport { PRIMARY_IDB_NAMES } from \"./storage-namespace.js\";\n\nconst BACKUP_PREFIX = \"ph-pglite-backup::\";\nconst BACKUP_INDEX_KEY = \"ph:pglite-backups\";\nconst BACKUP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype BackupRecord = { name: string; idbName: string; createdAt: number };\n\nfunction deleteIdb(name: string, timeoutMs = 15_000): Promise<void> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.deleteDatabase(name);\n let settled = false;\n const done = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n const timer = setTimeout(\n () =>\n done(() =>\n reject(\n new Error(`IDB delete timed out for ${name} after ${timeoutMs}ms`),\n ),\n ),\n timeoutMs,\n );\n req.onsuccess = () =>\n done(() => {\n clearTimeout(timer);\n resolve();\n });\n req.onerror = () =>\n done(() => {\n clearTimeout(timer);\n reject(idbError(req, `IDB delete failed for ${name}`));\n });\n });\n}\n\nfunction readBackupIndex(): BackupRecord[] {\n try {\n const raw = localStorage.getItem(BACKUP_INDEX_KEY);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as BackupRecord[]) : [];\n } catch {\n return [];\n }\n}\n\nfunction writeBackupIndex(records: BackupRecord[]): void {\n try {\n localStorage.setItem(BACKUP_INDEX_KEY, JSON.stringify(records));\n } catch {\n // ignore quota errors — janitor is best-effort\n }\n}\n\nfunction registerBackup(rec: BackupRecord): void {\n writeBackupIndex([...readBackupIndex(), rec]);\n}\n\nfunction forgetBackup(name: string): void {\n writeBackupIndex(readBackupIndex().filter((r) => r.name !== name));\n}\n\nasync function janitor(): Promise<void> {\n const cutoff = Date.now() - BACKUP_RETENTION_MS;\n const keep: BackupRecord[] = [];\n for (const rec of readBackupIndex()) {\n if (rec.createdAt >= cutoff) {\n keep.push(rec);\n continue;\n }\n try {\n await deleteIdb(rec.name);\n } catch (err) {\n console.warn(`Failed to delete expired pglite backup ${rec.name}`, err);\n keep.push(rec);\n }\n }\n writeBackupIndex(keep);\n}\n\n// Persistent backup to an IDB dir, indexed in localStorage with 30-day\n// retention (the janitor reaps expired ones); success keeps the backup.\nfunction createPersistentBackup(): BackupStrategy {\n return {\n snapshot: async (idbName) => {\n const backupName = `${BACKUP_PREFIX}${idbName}::${new Date().toISOString()}`;\n await cloneFileData(idbName, backupName);\n registerBackup({ name: backupName, idbName, createdAt: Date.now() });\n return backupName;\n },\n rollback: async (handle, idbName, cause) => {\n const backupName = handle as string;\n try {\n // clone clears-and-replaces in one txn; no pre-clear (which could empty the dir).\n await cloneFileData(backupName, idbName);\n } catch (rollbackErr) {\n console.error(\n `PGlite migration rollback failed for ${idbName}; backup ${backupName} retained. Primary migration error:`,\n cause,\n \"Rollback error:\",\n rollbackErr,\n );\n return;\n }\n await deleteIdb(backupName).catch(() => undefined);\n forgetBackup(backupName);\n },\n discard: async (handle) => {\n const backupName = handle as string;\n await deleteIdb(backupName).catch(() => undefined);\n forgetBackup(backupName);\n },\n commit: () => Promise.resolve(),\n };\n}\n\nasync function migrateAllLocked(): Promise<void> {\n const backup = createPersistentBackup();\n try {\n for (const idbName of PRIMARY_IDB_NAMES) {\n await migrateIdb(\n idbName,\n (phase) => setMigrationStatus({ idbName, phase }),\n backup,\n );\n }\n } finally {\n setMigrationStatus(null);\n }\n}\n\nexport async function migrateAllIfNeeded(): Promise<void> {\n janitor().catch((err) => console.warn(\"PGlite backup janitor failed\", err));\n\n const hasLocks =\n typeof navigator !== \"undefined\" &&\n \"locks\" in navigator &&\n typeof navigator.locks.request === \"function\";\n\n if (!hasLocks) {\n await migrateAllLocked();\n return;\n }\n\n await navigator.locks.request(\n \"ph-pglite-migration\",\n { mode: \"exclusive\" },\n async () => {\n await migrateAllLocked();\n },\n );\n}\n","import { Icon, Modal } from \"@powerhousedao/design-system\";\nimport {\n usePackageDiscoveryService,\n type FailedInstallation,\n type FailedInstallationReason,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useState } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useFailedInstallations } from \"../hooks/useFailedInstallations.js\";\n\nconst reasonLabels: Record<FailedInstallationReason, string> = {\n \"no-registry\": \"No package registry is configured.\",\n \"not-in-registry\": \"No matching package found in the registry.\",\n \"registry-error\": \"Couldn't reach the package registry.\",\n \"install-failed\": \"Package failed to install.\",\n dismissed: \"Installation was dismissed.\",\n offline: \"You're offline — this package can't be loaded until you reconnect.\",\n};\n\nfunction canRetry(reason: FailedInstallationReason): boolean {\n return reason !== \"no-registry\";\n}\n\nexport function MissingModelBanner() {\n const failed = useFailedInstallations();\n const discoveryService = usePackageDiscoveryService();\n const [open, setOpen] = useState(false);\n const [dismissed, setDismissed] = useState(false);\n\n useEffect(() => {\n return discoveryService?.subscribeEvents((event) => {\n if (event.type === \"load-failed\") {\n setDismissed(false);\n }\n });\n }, [discoveryService]);\n\n if (failed.length === 0) return null;\n\n return (\n <>\n {dismissed ? null : (\n <div className=\"absolute inset-x-0 top-0 z-200 bg-background\">\n <div className=\"flex items-center justify-between gap-3 bg-warning/10 px-4 py-2 text-sm text-warning\">\n <span>\n {failed.length === 1\n ? \"1 document type couldn't load (missing model).\"\n : `${failed.length} document types couldn't load (missing models).`}\n </span>\n <div className=\"flex items-center gap-2\">\n <button\n type=\"button\"\n onClick={() => setOpen(true)}\n className=\"rounded-md border border-warning bg-background px-3 py-1 text-warning hover:hover-effect\"\n >\n View\n </button>\n <button\n type=\"button\"\n onClick={() => setDismissed(true)}\n aria-label=\"Dismiss\"\n className=\"flex items-center text-warning hover:hover-effect\"\n >\n <Icon name=\"XmarkLight\" size={16} />\n </button>\n </div>\n </div>\n </div>\n )}\n <MissingModelDetailsModal\n open={open}\n failed={failed}\n onClose={() => setOpen(false)}\n />\n </>\n );\n}\n\ntype DetailsProps = {\n readonly open: boolean;\n readonly failed: FailedInstallation[];\n readonly onClose: () => void;\n};\n\nfunction MissingModelDetailsModal(props: DetailsProps) {\n const { open, failed, onClose } = props;\n const discoveryService = usePackageDiscoveryService();\n const [retrying, setRetrying] = useState<Set<string>>(() => new Set());\n\n async function handleRetry(documentType: string) {\n if (!discoveryService) return;\n setRetrying((prev) => new Set(prev).add(documentType));\n try {\n await discoveryService.retryInstallation(documentType);\n } finally {\n setRetrying((prev) => {\n const next = new Set(prev);\n next.delete(documentType);\n return next;\n });\n }\n }\n\n return (\n <Modal\n open={open}\n onOpenChange={(isOpen) => {\n if (!isOpen) onClose();\n }}\n contentProps={{ className: \"rounded-3xl\" }}\n >\n <div className=\"w-[520px] max-w-[90vw] bg-background p-6\">\n <div className=\"border-b border-border pb-2 text-2xl font-bold text-foreground\">\n Missing document models\n </div>\n <div className=\"my-4 text-sm text-foreground\">\n The following document types couldn't be loaded. Documents using them\n won't display until the underlying package is installed.\n </div>\n {failed.length === 0 ? (\n <div className=\"rounded-xl bg-background p-4 text-sm text-foreground\">\n No outstanding failures.\n </div>\n ) : (\n <div className=\"flex max-h-[60vh] flex-col gap-3 overflow-y-auto\">\n {failed.map((entry) => {\n const isRetrying = retrying.has(entry.documentType);\n const retryDisabled = !canRetry(entry.reason) || isRetrying;\n return (\n <div\n key={entry.documentType}\n className=\"rounded-xl bg-background p-4\"\n >\n <div className=\"mb-1 font-mono text-sm font-semibold text-foreground\">\n {entry.documentType}\n </div>\n <div className=\"mb-2 text-xs text-foreground\">\n {reasonLabels[entry.reason]}\n </div>\n {entry.packageNames.length > 0 ? (\n <div className=\"mb-2 text-xs text-muted-foreground\">\n Package{entry.packageNames.length > 1 ? \"s\" : \"\"}:{\" \"}\n {entry.packageNames.join(\", \")}\n </div>\n ) : null}\n {entry.error ? (\n <div className=\"mb-2 font-mono text-xs wrap-break-word text-destructive\">\n {entry.error.message}\n </div>\n ) : null}\n <div className=\"flex justify-end\">\n <button\n type=\"button\"\n onClick={() => void handleRetry(entry.documentType)}\n disabled={retryDisabled}\n title={\n canRetry(entry.reason)\n ? undefined\n : \"No registry is configured; nothing to retry against.\"\n }\n className={twMerge(\n \"min-h-[32px] rounded-xl px-3 py-1 text-sm font-semibold text-foreground transition-all hover:hover-effect\",\n retryDisabled\n ? \"cursor-not-allowed bg-secondary hover:hover-effect\"\n : \"bg-primary text-primary-foreground active:active-effect\",\n )}\n >\n {isRetrying ? \"Retrying...\" : \"Try install again\"}\n </button>\n </div>\n </div>\n );\n })}\n </div>\n )}\n <div className=\"mt-4 flex justify-end\">\n <button\n type=\"button\"\n onClick={onClose}\n className=\"min-h-[36px] rounded-xl border border-border bg-background px-4 py-2 text-sm font-semibold text-foreground hover:hover-effect\"\n >\n Close\n </button>\n </div>\n </div>\n </Modal>\n );\n}\n","import {\n clearOpenFileUploads,\n getOpenFileUploads,\n removeOpenFileUpload,\n subscribeOpenFileUploads,\n} from \"@powerhousedao/connect/utils\";\nimport { UploadFileListContainer } from \"@powerhousedao/design-system/connect\";\nimport { setSelectedNode } from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\n\n// The floating \"Uploading N documents\" panel for files opened through the OS\n// file association — the same design-system panel drag-and-drop uses, driven\n// by the open-file upload store instead of DropZone's instance-local tracker.\n// Renders nothing while no uploads are tracked.\nexport function OpenFileUploadList() {\n const uploads = useSyncExternalStore(\n subscribeOpenFileUploads,\n getOpenFileUploads,\n );\n\n return (\n <UploadFileListContainer\n uploadsArray={uploads}\n uploadsCount={uploads.length}\n removeUpload={removeOpenFileUpload}\n clearAllUploads={clearOpenFileUploads}\n setSelectedNode={setSelectedNode}\n />\n );\n}\n","import {\n PackageInstallModal,\n type PendingPackageInstallation,\n} from \"@powerhousedao/design-system/connect\";\nimport { usePackageDiscoveryService } from \"@powerhousedao/reactor-browser\";\nimport { usePendingInstallations } from \"../hooks/usePendingInstallations.js\";\n\nexport function PackageInstallPrompt() {\n const pendingInstallations = usePendingInstallations();\n const discoveryService = usePackageDiscoveryService();\n\n if (!discoveryService || pendingInstallations.length === 0) return null;\n\n const installations: PendingPackageInstallation[] =\n pendingInstallations.flatMap((p) =>\n p.packageNames.map((packageName) => ({\n documentType: p.documentType,\n packageName,\n })),\n );\n\n return (\n <PackageInstallModal\n pendingInstallations={installations}\n onInstall={(packageName) =>\n discoveryService.approveInstallation(packageName)\n }\n onDismiss={(packageName) =>\n discoveryService.dismissInstallation(packageName)\n }\n />\n );\n}\n","import type { PHConnectRenownAdapters } from \"@powerhousedao/shared/clis\";\nimport type { WalletAdapterDescriptor } from \"@renown/sdk/wallet\";\nimport {\n mockAdapter,\n type MockLoginMethod,\n type PHRenownMockAdapterConfig,\n} from \"@renown/sdk/wallet/mock\";\nimport { privyAdapter, type PrivyLoginMethod } from \"@renown/sdk/wallet/privy\";\nimport { rainbowAdapter } from \"@renown/sdk/wallet/rainbow\";\nimport {\n arbitrum,\n base,\n type Chain,\n mainnet,\n optimism,\n polygon,\n sepolia,\n} from \"wagmi/chains\";\n\n// `mock` is deliberately absent from the published config schema (TEST/DEV only\n// — it signs with a well-known key), so it is read off the runtime config here.\nexport type ConnectRenownAdapters = PHConnectRenownAdapters & {\n mock?: PHRenownMockAdapterConfig;\n};\n\n// Adapters validate `methods` eagerly and throw on one they can't drive. This\n// runs during render, so a config typo costs one button, not the whole app.\nfunction describe(\n id: string,\n build: () => WalletAdapterDescriptor,\n): WalletAdapterDescriptor[] {\n try {\n return [build()];\n } catch (error) {\n console.error(\n `[connect] Ignoring the \"${id}\" wallet adapter: connect.renown.adapters.${id} was rejected.`,\n error,\n );\n return [];\n }\n}\n\n// `connect.renown.chainId` is an id, but the adapter needs the chain object, so\n// only a listed chain can be offered.\nconst CHAINS_BY_ID = new Map<number, Chain>(\n [mainnet, sepolia, polygon, optimism, arbitrum, base].map((chain) => [\n chain.id,\n chain,\n ]),\n);\n\n// Renown issues on one chain and rejects a session from any other, so the wallet\n// UI has to offer that chain and no other.\nfunction chainsFor(\n chainId: number | undefined,\n): readonly [Chain, ...Chain[]] | undefined {\n if (chainId === undefined) return undefined;\n const chain = CHAINS_BY_ID.get(chainId);\n if (!chain) {\n console.error(\n `[connect] connect.renown.chainId ${chainId} is not a chain Connect can offer, so in-page sign-in will be rejected. Supported: ${[...CHAINS_BY_ID.keys()].join(\", \")}.`,\n );\n return undefined;\n }\n return [chain];\n}\n\n/** Map Connect's declarative `connect.renown.adapters` config to the descriptors `RenownWalletProvider` takes. Array order sets the order of the login buttons. A rejected adapter config is dropped (logged), leaving the others working. `chainId` is `connect.renown.chainId`, the chain Renown issues credentials on. */\nexport function configToDescriptors(\n config: ConnectRenownAdapters | undefined,\n chainId?: number,\n): WalletAdapterDescriptor[] {\n if (!config) return [];\n const { rainbow, privy, mock } = config;\n const descriptors: WalletAdapterDescriptor[] = [];\n const chains = chainsFor(chainId);\n // Every adapter Connect can offer is imported statically (hence Connect\n // installs all their peers), but each library stays behind a lazy loader.\n if (rainbow) {\n descriptors.push(\n ...describe(\"rainbow\", () =>\n rainbowAdapter({ ...rainbow, ...(chains ? { chains } : {}) })),\n );\n }\n if (privy) {\n // appId is optional in the config schema but required by the adapter: an\n // operator who enables privy without one gets no privy login, not a crash.\n const { appId, clientId, methods } = privy;\n if (appId) {\n descriptors.push(\n ...describe(\"privy\", () =>\n privyAdapter({\n appId,\n clientId,\n // Methods come from JSON, so unvalidated here; the adapter's\n // resolver rejects anything it can't drive.\n methods: methods as PrivyLoginMethod[] | undefined,\n chain: chains?.[0],\n })),\n );\n }\n }\n if (mock) {\n descriptors.push(\n ...describe(\"mock\", () =>\n mockAdapter({\n ...mock,\n methods: mock.methods as MockLoginMethod[] | undefined,\n })),\n );\n }\n return descriptors;\n}\n","import { RenownWalletProvider, useTheme } from \"@powerhousedao/reactor-browser\";\nimport type { WalletTheme } from \"@renown/sdk/wallet\";\nimport { useMemo, type ReactNode } from \"react\";\nimport { getRuntimeConfig } from \"@powerhousedao/connect-core/runtime-config\";\nimport {\n configToDescriptors,\n type ConnectRenownAdapters,\n} from \"./renown-adapter-descriptors.js\";\n\n// Resolve a CSS color expression (a theme token) to a concrete color via a\n// hidden probe, so adapters receive Connect's palette without reading the DOM.\nfunction resolveColor(expr: string, fallback: string): string {\n if (typeof document === \"undefined\") return fallback;\n const probe = document.createElement(\"span\");\n probe.style.color = fallback;\n probe.style.color = expr;\n probe.style.display = \"none\";\n document.body.appendChild(probe);\n const resolved = getComputedStyle(probe).color;\n probe.remove();\n return resolved || fallback;\n}\n\n// Thin Connect wrapper over the shared RenownWalletProvider primitive: supplies\n// the configured adapters and Connect's runtime theme (mode + accent colors).\nexport function RenownWalletProviders({ children }: { children: ReactNode }) {\n const config = getRuntimeConfig().connect.renown?.adapters as\n | ConnectRenownAdapters\n | undefined;\n const chainId = getRuntimeConfig().connect.renown?.chainId;\n const { theme } = useTheme();\n // Descriptors carry only eager metadata; no wallet library loads here.\n const adapters = useMemo(\n () => configToDescriptors(config, chainId),\n [config, chainId],\n );\n\n // Resolve colors (forced style reads) only when an adapter is configured,\n // so a wallet-less deployment does no probing work at mount.\n const walletTheme = useMemo<WalletTheme | undefined>(\n () =>\n adapters.length > 0\n ? {\n mode: theme,\n accentColor: resolveColor(\"var(--primary)\", \"#0084ff\"),\n accentColorForeground: resolveColor(\n \"var(--primary-foreground)\",\n \"#ffffff\",\n ),\n }\n : undefined,\n [theme, adapters],\n );\n\n // No adapters configured: the provider's activator/effects are inert, so skip\n // it entirely and keep the wallet controller module off the render path.\n if (adapters.length === 0) return <>{children}</>;\n\n return (\n <RenownWalletProvider adapters={adapters} theme={walletTheme}>\n {children}\n </RenownWalletProvider>\n );\n}\n","import { Analytics } from \"./analytics.js\";\nimport { OpenPanel } from \"./openpanel.js\";\nimport { Router } from \"./router.js\";\n\nimport { connectConfig } from \"@powerhousedao/connect/config\";\nimport { SentryProvider } from \"../context/sentry-provider.js\";\nimport {\n DocumentEditorDebugTools,\n initLaunchQueueFileHandling,\n serviceWorkerManager,\n} from \"@powerhousedao/connect/utils\";\nimport { useEditorPreloader, useTheme } from \"@powerhousedao/reactor-browser\";\nimport { lazy, Suspense, useEffect } from \"react\";\nimport { ToastContainer } from \"../services/toast.js\";\nimport { MissingModelBanner } from \"./missing-model-banner.js\";\nimport { OpenFileUploadList } from \"./open-file-upload-list.js\";\nimport { PackageInstallPrompt } from \"./package-install-prompt.js\";\nimport { RenownWalletProviders } from \"./renown-wallet-providers.js\";\n\n// Its AI and MCP packages load only when the assistant is on.\nconst ConnectReactorChatFab = lazy(() =>\n import(\"./reactor-chat.js\").then((m) => ({\n default: m.ConnectReactorChatFab,\n })),\n);\n\nexport const App = () => {\n useTheme(); // keeps the OS-preference change listener active\n useEditorPreloader(); // warms editor chunks during idle time\n\n // refresh page on vite preload error due to outdated chunks — but only when\n // the failing dynamic import is one of Connect's own chunks. External\n // dynamic imports (e.g. the package manager loading a package from the\n // configured CDN) should let the error propagate so the caller can surface\n // it; reloading here drops any open state and hides the real failure.\n useEffect(() => {\n const handlePreloadError = (event: Event) => {\n const payload = (event as Event & { payload?: unknown }).payload;\n const message =\n payload instanceof Error\n ? payload.message\n : typeof payload === \"string\"\n ? payload\n : \"\";\n const failedUrl = message.match(/https?:\\/\\/[^\\s\"']+/)?.[0];\n\n if (failedUrl && !failedUrl.startsWith(window.location.origin)) {\n console.debug(\n `[Connect] Skipping reload — vite:preloadError for off-origin URL: ${failedUrl}`,\n );\n return;\n }\n\n console.log(\"Outdated chunks detected, reloading page...\");\n window.location.reload();\n };\n\n window.addEventListener(\"vite:preloadError\", handlePreloadError);\n\n return () => {\n window.removeEventListener(\"vite:preloadError\", handlePreloadError);\n };\n }, []);\n\n useEffect(() => {\n if (import.meta.env.MODE === \"development\") {\n window.documentEditorDebugTools = new DocumentEditorDebugTools();\n } else if (connectConfig.offline) {\n serviceWorkerManager.registerServiceWorker(false);\n } else {\n // Offline disabled — drop any worker a previous offline build left running.\n void serviceWorkerManager.unregisterAll();\n }\n }, []);\n\n // Files the OS opens with the installed PWA (manifest file_handlers).\n // launchQueue buffers launches until a consumer registers, so nothing is lost\n // by wiring it on mount; a no-op where the API doesn't exist.\n useEffect(() => {\n initLaunchQueueFileHandling();\n }, []);\n\n return (\n <SentryProvider>\n <RenownWalletProviders>\n <ToastContainer position=\"bottom-right\" />\n {connectConfig.aiAssistantEnabled && (\n <Suspense name=\"ReactorChat\" fallback={null}>\n <ConnectReactorChatFab />\n </Suspense>\n )}\n <MissingModelBanner />\n <Router />\n <OpenFileUploadList />\n <PackageInstallPrompt />\n <Analytics />\n <OpenPanel />\n </RenownWalletProviders>\n </SentryProvider>\n );\n};\n","import { showPHModal } from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n getWorkerConnectionStatus,\n subscribeWorkerConnection,\n type WorkerConnectionStatus,\n} from \"../connection-state.js\";\n\nconst CONNECTED: WorkerConnectionStatus = \"connected\";\n\nconst BANNER_TEXT: Record<\n Exclude<WorkerConnectionStatus, \"connected\">,\n { title: string; detail: string }\n> = {\n failed: {\n title: \"Reactor worker failed to load\",\n detail:\n \"The background worker script could not be loaded. Reload to retry.\",\n },\n lost: {\n title: \"Lost connection to the reactor\",\n detail: \"The background worker stopped responding. Reload to reconnect.\",\n },\n \"storage-held\": {\n title: \"Waiting for another Connect tab\",\n detail:\n \"Another Connect tab still holds local storage. Close or reload the other Connect tabs to continue.\",\n },\n \"version-conflict\": {\n title: \"Connect tabs are on different builds\",\n detail:\n \"Open tabs keep restarting the reactor. Close the other Connect tabs, then reload.\",\n },\n \"storage-unusable\": {\n title: \"Local storage is unusable\",\n detail:\n \"The local database stopped responding. Clear storage to start over, or reload to retry.\",\n },\n};\n\nexport const ConnectionBanner: React.FC = () => {\n const status = useSyncExternalStore(\n subscribeWorkerConnection,\n getWorkerConnectionStatus,\n () => CONNECTED,\n );\n\n if (status === \"connected\") {\n return null;\n }\n\n const { title, detail } = BANNER_TEXT[status];\n\n return (\n <div className=\"absolute inset-x-0 top-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-destructive bg-warning px-4 py-3 text-sm text-warning-foreground shadow-lg\">\n <div className=\"flex-1\">\n <div className=\"font-semibold\">{title}</div>\n <div className=\"text-foreground\">{detail}</div>\n </div>\n {status === \"storage-unusable\" && (\n <button\n type=\"button\"\n onClick={() => showPHModal({ type: \"clearStorage\" })}\n className=\"rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect\"\n >\n Clear storage\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => window.location.reload()}\n className=\"rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect\"\n >\n Reload\n </button>\n </div>\n </div>\n );\n};\n","import { lazy, Suspense } from \"react\";\nimport { ErrorBoundary } from \"./error-boundary.js\";\n\nconst CookieBanner = lazy(() =>\n import(\"./cookie-banner.js\").then((m) => ({ default: m.CookieBanner })),\n);\n\n/** Asks for the analytics consent that active plugins need; without one, consent stays rejected. */\nexport function CookieConsent() {\n // An optional, ad-blocker-vulnerable chunk: if blocked, the app runs with analytics off.\n return (\n <ErrorBoundary variant=\"silent\" loggerContext={[\"Connect\", \"CookieBanner\"]}>\n <Suspense fallback={null} name=\"CookieBanner\">\n <CookieBanner />\n </Suspense>\n </ErrorBoundary>\n );\n}\n","import { getConnectPluginUi } from \"@powerhousedao/connect-core/plugins\";\nimport { CookieConsent } from \"./cookie-consent.js\";\n\n/** What the active plugins render beside the app, and the consent banner when one needs it. */\nexport function PluginRoots() {\n const { roots, consent } = getConnectPluginUi();\n return (\n <>\n {consent && <CookieConsent />}\n {roots.map((Root, i) => (\n <Root key={i} />\n ))}\n </>\n );\n}\n","import {\n CURRENT_PG_MAJOR,\n getCachedMigrationMajor,\n migrateAllIfNeeded,\n subscribeMigrationMajor,\n} from \"@powerhousedao/connect/utils\";\nimport { useReactorClientModule } from \"@powerhousedao/reactor-browser\";\nimport type { IWorkerAdminClient } from \"@powerhousedao/reactor-browser/rpc\";\nimport { useState, useSyncExternalStore } from \"react\";\n\nfunction BannerShell({\n title,\n body,\n error,\n children,\n}: {\n title: string;\n body: string;\n error?: string | null;\n children?: React.ReactNode;\n}) {\n return (\n <div className=\"absolute inset-x-0 top-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-warning bg-warning px-4 py-3 text-sm text-warning-foreground shadow-lg\">\n <div className=\"flex-1\">\n <div className=\"font-semibold\">{title}</div>\n <div className=\"text-foreground\">{body}</div>\n {error && (\n <div className=\"mt-2 font-medium text-destructive\">\n Migration failed: {error}\n </div>\n )}\n </div>\n {children}\n </div>\n </div>\n );\n}\n\nconst actionButton =\n \"rounded-sm bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:hover-effect disabled:disabled-effect\";\nconst dismissButton =\n \"rounded-sm border border-foreground bg-transparent px-3 py-1 text-sm font-medium text-foreground hover:hover-effect disabled:disabled-effect\";\n\nlet browserDismissed = false;\nconst browserListeners = new Set<() => void>();\n\nfunction WorkerMigrationBanner({\n adminClient,\n}: {\n adminClient: IWorkerAdminClient;\n}) {\n const state = useSyncExternalStore(\n (cb) => adminClient.subscribeMigration(cb),\n () => adminClient.getMigrationState(),\n );\n const [dismissed, setDismissed] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n if (state.status === \"idle\") return null;\n if (state.status === \"needed\" && dismissed) return null;\n\n const migrating = state.status === \"migrating\";\n const handleMigrate = () => {\n setError(null);\n adminClient.migrate().catch((err: unknown) => {\n setError(err instanceof Error ? err.message : String(err));\n });\n };\n\n return (\n <BannerShell\n title={\n migrating\n ? `Migrating to Postgres ${CURRENT_PG_MAJOR}…`\n : `Your local database uses Postgres ${state.legacyMajor ?? \"?\"}.`\n }\n body={\n migrating\n ? `Working (${state.phase ?? \"starting\"}). Your data is backed up first.`\n : `Migrate to Postgres ${CURRENT_PG_MAJOR} to pick up the latest features. Your data will be backed up first.`\n }\n error={error ?? (state.status === \"failed\" ? state.error : null)}\n >\n {!migrating && (\n <button type=\"button\" onClick={handleMigrate} className={actionButton}>\n {state.status === \"failed\" ? \"Retry\" : \"Migrate now\"}\n </button>\n )}\n {state.status === \"needed\" && (\n <button\n type=\"button\"\n onClick={() => setDismissed(true)}\n className={dismissButton}\n >\n Dismiss\n </button>\n )}\n </BannerShell>\n );\n}\n\nfunction BrowserMigrationBanner() {\n const isDismissed = useSyncExternalStore(\n (cb) => {\n browserListeners.add(cb);\n return () => browserListeners.delete(cb);\n },\n () => browserDismissed,\n () => false,\n );\n const major = useSyncExternalStore(\n subscribeMigrationMajor,\n getCachedMigrationMajor,\n () => undefined,\n );\n const [migrating, setMigrating] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n if (major === undefined || major === null || major === CURRENT_PG_MAJOR) {\n return null;\n }\n if (isDismissed) return null;\n\n const handleMigrate = () => {\n setError(null);\n setMigrating(true);\n migrateAllIfNeeded()\n .then(() => window.location.reload())\n .catch((err: unknown) => {\n setError(err instanceof Error ? err.message : String(err));\n setMigrating(false);\n });\n };\n\n return (\n <BannerShell\n title={`Your local database uses Postgres ${major}.`}\n body={`Migrate to Postgres ${CURRENT_PG_MAJOR} to pick up the latest features. Your data will be backed up first.`}\n error={error}\n >\n <button\n type=\"button\"\n disabled={migrating}\n onClick={handleMigrate}\n className={actionButton}\n >\n {migrating ? \"Migrating…\" : \"Migrate now\"}\n </button>\n <button\n type=\"button\"\n disabled={migrating}\n onClick={() => {\n browserDismissed = true;\n for (const l of browserListeners) l();\n }}\n className={dismissButton}\n >\n Dismiss\n </button>\n </BannerShell>\n );\n}\n\nexport const MigrationBanner: React.FC = () => {\n const module = useReactorClientModule();\n if (module?.kind === \"worker\") {\n return <WorkerMigrationBanner adminClient={module.adminClient} />;\n }\n return <BrowserMigrationBanner />;\n};\n","import {\n getServiceWorkerUpdateAvailable,\n serviceWorkerManager,\n subscribeServiceWorkerUpdate,\n} from \"@powerhousedao/connect/utils\";\nimport { useSyncExternalStore } from \"react\";\n\n// Prompts the user to load a waiting service-worker update, so a new version\n// never reloads over in-progress work.\nexport const ServiceWorkerUpdatePrompt: React.FC = () => {\n const updateAvailable = useSyncExternalStore(\n subscribeServiceWorkerUpdate,\n getServiceWorkerUpdateAvailable,\n () => false,\n );\n\n if (!updateAvailable) return null;\n\n return (\n <div className=\"absolute inset-x-0 bottom-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-foreground bg-primary px-4 py-3 text-sm text-primary-foreground shadow-lg\">\n <div className=\"flex-1 font-medium\">\n A new version of Connect is available.\n </div>\n <button\n type=\"button\"\n onClick={() => serviceWorkerManager.applyUpdate()}\n className=\"rounded-sm bg-primary-foreground px-3 py-1 text-sm font-medium text-primary hover:hover-effect\"\n >\n Refresh\n </button>\n </div>\n </div>\n );\n};\n","import { Icon, PowerhouseButton } from \"@powerhousedao/design-system\";\n\n/** Boot screen for a reactor that refused this browser's stored documents. */\nexport function StoredDocumentsRefusedFallback({ error }: { error: Error }) {\n return (\n <div className=\"z-10 mx-auto flex max-w-[80%] flex-1 items-center justify-center p-6\">\n <div\n role=\"alert\"\n className=\"w-full max-w-lg rounded-lg border border-border bg-card p-6 text-foreground shadow-sm\"\n >\n <div className=\"mb-3 flex items-center gap-2\">\n <Icon name=\"Error\" className=\"size-5 shrink-0 text-destructive\" />\n <h1 className=\"text-lg font-semibold text-foreground\">\n Connect cannot open this browser&apos;s documents\n </h1>\n </div>\n <p className=\"mb-4 text-sm wrap-break-word text-foreground\">\n {error.message}\n </p>\n <PowerhouseButton\n type=\"button\"\n onClick={() => {\n window.location.reload();\n }}\n className=\"px-3 py-1.5 text-base font-medium\"\n >\n Reload\n </PowerhouseButton>\n </div>\n </div>\n );\n}\n","import \"@powerhousedao/connect/i18n\";\nimport { getConnectPHStore } from \"@powerhousedao/connect-core/runtime\";\nimport { PHStoreProvider } from \"@powerhousedao/reactor-browser\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { lazy, StrictMode, Suspense } from \"react\";\nimport AppSkeleton from \"./app-skeleton.js\";\nimport { DetailedFallback, ErrorBoundary } from \"./error-boundary.js\";\nimport { App } from \"./app.js\";\nimport { ConnectionBanner } from \"./connection-banner.js\";\nimport { PluginRoots } from \"./plugin-roots.js\";\nimport { MigrationBanner } from \"./migration-banner.js\";\nimport { LoadingShell } from \"./prerendered-shell.js\";\nimport { ServiceWorkerUpdatePrompt } from \"./service-worker-update-prompt.js\";\nimport { StoredDocumentsRefusedFallback } from \"./stored-documents-refused.js\";\nimport { isStoredDocumentsRefused } from \"../utils/stored-documents-refused.js\";\n\nexport const AppLoader = (props: {\n localPackage?: DocumentModelLib | Promise<DocumentModelLib>;\n}) => {\n const phStore = getConnectPHStore();\n const Load = lazy(() =>\n import(\"./load.js\").then((m) =>\n m.loadComponent(props.localPackage, phStore),\n ),\n );\n return (\n <StrictMode>\n <PHStoreProvider store={phStore}>\n <ErrorBoundary\n fallbackRender={(props) => (\n <AppSkeleton\n children={\n isStoredDocumentsRefused(props.error) ? (\n <StoredDocumentsRefusedFallback error={props.error} />\n ) : (\n <DetailedFallback {...props} />\n )\n }\n />\n )}\n resetKeys={[props.localPackage]}\n loggerContext={[\"Connect\"]}\n >\n <Suspense\n fallback={<LoadingShell Fallback={AppSkeleton} />}\n name=\"AppLoader\"\n >\n {/* eslint-disable-next-line react-hooks-extra/static-components */}\n <Load {...props}>\n <App />\n <PluginRoots />\n </Load>\n </Suspense>\n <MigrationBanner />\n <ServiceWorkerUpdatePrompt />\n <ConnectionBanner />\n </ErrorBoundary>\n </PHStoreProvider>\n </StrictMode>\n );\n};\n"],"names":["emptyArray","logger","rawEvents","CookieBanner"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAMA,eAAmC,CAAC;AAE1C,SAAgB,yBAAyB;CACvC,MAAM,mBAAmB,2BAA2B;CACpD,OAAO,sBACJ,OAAO,kBAAkB,gBAAgB,EAAE,YAAY,CAAC,UACnD,kBAAkB,uBAAuB,KAAKA,YACtD;AACF;;;ACLA,MAAMC,WAAS,YAAY,CAAC,QAAQ,CAAC;AAErC,IAAI,gBAAgB;AAEpB,eAAe,YAAY;CACzB,OAAO,MAAM,OAAO;AACtB;AAEA,eAAe,aAAa;CAC1B,MAAM,SAAS,MAAM,UAAU;CAC/B,MAAM,eAA+C;EACnD,OAAO,sBAAsB;EAC7B,OAAO,0BAA0B,EAAE,OAAO,EAAE,CAAC;EAC7C,OAAO,kBAAkB;EACzB,OAAO,0BAA0B,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CACxD;CACA,IAAI,cAAc,OAAO,SAAS;EAEhC,MAAM,EAAE,qBAAqB,MAAM,OAAO;EAC1C,aAAa,KACX,OAAO,wCAAwC,iBAAiB,CAAC,CACnE;CACF;CAEA,OAAO,KAAK;EACV,SAAS,cAAc,OAAO;EAC9B,KAAK,cAAc,OAAO,OAAO,KAAA;EACjC,aAAa,cAAc,OAAO;EAClC;EACA,cAAc;GACZ;GACA;GACA;EACF;EACA,gBAAgB;EAChB,kBAAkB;EAClB,0BAA0B;EAC1B,0BAA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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]="8ec25d8b-a631-5bd4-bd14-4c3812a6b0c5")}catch(e){}}();
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]="d85bcd1c-9589-5251-a788-1f47f4ce367c")}catch(e){}}();
3
3
  import { i as hasPrerenderedShell, r as adoptPrerenderedShell } from "./prerendered-shell-peKE7AqI.js";
4
- import { t as loadRuntimeConfig } from "./load-runtime-config-Dhy-b5wT.js";
4
+ import { t as loadRuntimeConfig } from "./load-runtime-config-BvMss48m.js";
5
5
  import { r as track } from "./buffer-DNTcuap_.js";
6
6
  import "@powerhousedao/connect/fonts.css";
7
7
  import { createRoot } from "react-dom/client";
@@ -229,5 +229,5 @@ async function bootConnect(overrides = {}) {
229
229
  //#endregion
230
230
  export { bootConnect as t };
231
231
 
232
- //# sourceMappingURL=boot-JTGLJtmJ.js.map
233
- //# debugId=8ec25d8b-a631-5bd4-bd14-4c3812a6b0c5
232
+ //# sourceMappingURL=boot-BhAEKTca.js.map
233
+ //# debugId=d85bcd1c-9589-5251-a788-1f47f4ce367c
@@ -1 +1 @@
1
- {"version":3,"file":"boot-JTGLJtmJ.js","sources":["../src/utils/performance-observer.ts","../src/warm-modules.ts","../src/boot.tsx"],"sourcesContent":["import { track } from \"../services/openpanel/buffer.js\";\nimport type { PHGlobal } from \"@powerhousedao/reactor-browser\";\n\n/**\n * Startup performance measurement.\n *\n * Captures First Contentful Paint (FCP) and Largest Contentful Paint (LCP) via\n * the Performance API and reports each to the OpenPanel analytics buffer (a\n * consent-gated, never-throwing queue). Call {@link initPerformanceObserver}\n * at the very top of the entry module, before the runtime config is fetched,\n * so FCP is caught even if the browser has already painted — a\n * `PerformanceObserver` with `buffered: true` replays entries that fired\n * before `observe()` was called.\n *\n * This module is intentionally dependency-light (only the OpenPanel event\n * buffer, which has no runtime imports of its own) so it is safe to load\n * before the runtime config is fetched. Every API access is guarded: nothing\n * here may throw into the application.\n */\n\nfunction navigationType(): string | undefined {\n try {\n const entry = performance.getEntriesByType(\"navigation\")[0] as\n | PerformanceNavigationTiming\n | undefined;\n return entry?.type; // \"navigate\" | \"reload\" | \"back_forward\" | \"prerender\"\n } catch {\n return undefined;\n }\n}\n\n// window.ph is the app's global bag (PHGlobal). This module owns a\n// `performance` sub-object it writes into; `PhWithPerformance` is a named\n// stand-in for that write so it type-checks without touching the shared\n// PHGlobal definition.\ntype PhWithPerformance = PHGlobal & { performance?: Record<string, number> };\n\n/**\n * Mirror the metric on `window.ph.performance` for devtools inspection. Only\n * writes to an already-existing `window.ph` (owned by the entry module) —\n * never creates or replaces it, so it can't clobber the app's global state.\n */\nfunction storeOnWindow(name: string, value: number): void {\n try {\n const ph = window.ph as PhWithPerformance | undefined;\n if (!ph) return;\n ph.performance = ph.performance ?? {};\n ph.performance[name] = value;\n } catch {\n // devtools mirror is best-effort only\n }\n}\n\nfunction report(name: string, ms: number): void {\n const value = Math.round(ms);\n const props: Record<string, unknown> = { ms: value };\n const navType = navigationType();\n if (navType) props.navigation = navType;\n\n storeOnWindow(name, value);\n\n // The console summary is a developer aid. In a production build it is noise\n // in every user's console and in every support screenshot, so it is gated\n // out of the bundle there.\n if (!import.meta.env.PROD) {\n try {\n console.info(`[connect:performance] ${name}: ${value}ms`, props);\n } catch {\n // console is best-effort only\n }\n }\n\n try {\n track(`performance.${name}`, props);\n } catch {\n // analytics must never throw into the app\n }\n}\n\n/**\n * Starts the observers. Returns a disposer that detaches all of them. The app\n * never needs it — the observers live as long as the page does — but it keeps\n * the module testable and leaves no listener behind.\n */\nexport function initPerformanceObserver(): () => void {\n if (\n typeof window === \"undefined\" ||\n typeof PerformanceObserver === \"undefined\"\n ) {\n return () => undefined;\n }\n\n const teardown: Array<() => void> = [];\n\n /** Registers a listener and queues its removal on dispose. */\n const listen = (\n target: EventTarget,\n type: string,\n handler: () => void,\n once = true,\n ): void => {\n target.addEventListener(type, handler, { once });\n teardown.push(() => target.removeEventListener(type, handler));\n };\n\n // FCP — from the \"paint\" buffer. It fires once, so stop observing after it.\n try {\n const fcpObserver = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n if (entry.name === \"first-contentful-paint\") {\n fcpObserver.disconnect();\n report(\"first_contentful_paint\", entry.startTime);\n }\n }\n });\n fcpObserver.observe({ type: \"paint\", buffered: true });\n teardown.push(() => fcpObserver.disconnect());\n } catch (err) {\n console.warn(\"[connect:performance] FCP observer failed:\", err);\n }\n\n // LCP — the final value only settles on an interaction or page hide, so latch\n // the latest candidate and report on the first terminal signal.\n let lcpMs = 0;\n let lcpReported = false;\n let lcpObserver: PerformanceObserver | undefined;\n\n /** Latches the newest candidate of a batch. The last entry is the newest. */\n const latch = (entries: ArrayLike<{ startTime: number }>): void => {\n if (entries.length > 0) {\n lcpMs = entries[entries.length - 1].startTime;\n }\n };\n\n const reportLcp = (): void => {\n // Several terminal signals can fire in one session (a click, then the page\n // hiding, then pagehide). The metric is sent for the first one only: every\n // repeat would be a double-count downstream.\n if (lcpReported) return;\n lcpReported = true;\n\n // A PerformanceObserver delivers entries in a task of its own, so a\n // terminal signal early in the page's life arrives while the newest\n // candidate is still buffered. Drain it before disconnecting — otherwise\n // an early click costs the session its LCP entirely.\n try {\n latch(lcpObserver?.takeRecords() ?? []);\n } catch {\n // draining is best-effort; report whatever was already delivered\n }\n\n lcpObserver?.disconnect();\n if (lcpMs > 0) report(\"largest_contentful_paint\", lcpMs);\n };\n\n try {\n lcpObserver = new PerformanceObserver((list) => {\n latch(list.getEntries());\n });\n lcpObserver.observe({ type: \"largest-contentful-paint\", buffered: true });\n teardown.push(() => lcpObserver?.disconnect());\n\n listen(window, \"pagehide\", reportLcp);\n listen(window, \"pointerdown\", reportLcp);\n listen(window, \"keydown\", reportLcp);\n // Not `once`: a page that loads in a background tab, or that the user tabs\n // away from and back, fires visibilitychange more than once, and only the\n // transition to \"hidden\" is terminal. A one-shot listener would be spent\n // on an earlier \"visible\" event and never see the hide.\n listen(\n document,\n \"visibilitychange\",\n () => {\n if (document.visibilityState === \"hidden\") reportLcp();\n },\n false,\n );\n } catch (err) {\n console.warn(\"[connect:performance] LCP observer failed:\", err);\n }\n\n return () => {\n for (const detach of teardown) {\n try {\n detach();\n } catch {\n // teardown is best-effort only\n }\n }\n teardown.length = 0;\n };\n}\n","// The app graph's largest packages; none reads the runtime config when evaluated.\nconst STAGES: (() => Promise<unknown>)[] = [\n () => import(\"@powerhousedao/reactor-browser\"),\n () => import(\"@powerhousedao/design-system/connect\"),\n];\n\nconst nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));\n\n/** Evaluates them one task each; imported with the app they'd be one long task. */\nexport async function warmModules(stages = STAGES) {\n for (const stage of stages) {\n await nextTask();\n // The app's own import reports a failure.\n await stage().catch(() => undefined);\n }\n}\n","// Imported by package name so projects resolve its fonts from Connect's dependencies.\nimport \"@powerhousedao/connect/fonts.css\";\nimport type { ComponentType, PropsWithChildren, ReactNode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport {\n adoptPrerenderedShell,\n hasPrerenderedShell,\n} from \"./components/prerendered-shell.js\";\nimport { loadRuntimeConfig } from \"./load-runtime-config.js\";\nimport { initPerformanceObserver } from \"./utils/performance-observer.js\";\nimport { warmModules } from \"./warm-modules.js\";\n\n/**\n * The two-phase startup shared by both entry points.\n *\n * Phase 1 paints the config-independent skeleton, so first contentful paint\n * does not wait on the `powerhouse.config.json` round-trip. Phase 2 awaits the\n * config and hands the caller back the root to render the config-dependent app\n * into — every module that reads the runtime config at module-evaluation\n * throws if the cache isn't warm, so the app graph may only be imported after\n * this resolves.\n *\n * Kept dependency-light on purpose: it loads before the config is fetched, so\n * nothing in its import graph may read the config.\n */\n\n/** All the bootstrap needs of a React root — and all a test has to stand in for. */\ntype RenderTarget = { render: (node: ReactNode) => void };\n\nexport type BootDeps = {\n loadConfig: () => Promise<unknown>;\n importSkeleton: () => Promise<{ default: ComponentType<PropsWithChildren> }>;\n createRoot: () => RenderTarget;\n initObserver: () => () => void;\n /** True when #root holds a prerendered shell, which stays until the app renders. */\n adoptShell: () => boolean;\n /** Evaluates the app's large packages while the config loads. */\n warmModules: () => Promise<unknown>;\n};\n\nconst defaultDeps: BootDeps = {\n loadConfig: () => loadRuntimeConfig(),\n importSkeleton: () => import(\"./components/app-skeleton.js\"),\n createRoot: () => createRoot(document.getElementById(\"root\")!),\n initObserver: initPerformanceObserver,\n adoptShell: () => {\n adoptPrerenderedShell(document.getElementById(\"root\"));\n return hasPrerenderedShell();\n },\n warmModules: () => warmModules(),\n};\n\n/**\n * Shown when startup cannot proceed. Deliberately built from plain elements:\n * this renders precisely when the runtime config is unavailable, so it must\n * not depend on anything that reads it.\n */\nfunction BootError({ error }: { error: unknown }): ReactNode {\n const message = error instanceof Error ? error.message : String(error);\n return (\n <div\n role=\"alert\"\n className=\"flex h-screen flex-col items-center justify-center gap-3 bg-background p-6 text-center\"\n >\n <h1 className=\"text-lg font-semibold text-foreground\">\n Connect could not start\n </h1>\n <p className=\"max-w-prose text-sm text-foreground\">\n Its runtime configuration could not be loaded. This is usually temporary\n — reloading often resolves it.\n </p>\n <pre className=\"max-w-prose overflow-x-auto rounded-sm bg-card px-3 py-2 text-left text-xs text-foreground\">\n {message}\n </pre>\n <button\n type=\"button\"\n className=\"rounded-sm bg-card px-4 py-2 text-sm font-medium text-foreground shadow-sm\"\n onClick={() => {\n window.location.reload();\n }}\n >\n Reload\n </button>\n </div>\n );\n}\n\n/**\n * Paints the skeleton, then waits for the runtime config.\n *\n * Returns the root to render the app into, or `null` when startup failed — in\n * which case the error state is already painted and the caller must not import\n * the config-dependent app. It resolves rather than rejecting on failure: both\n * entry points await this at their module's top level, where a rejection would\n * surface only as an unhandled rejection behind a skeleton that never goes\n * away.\n */\nexport async function bootConnect(\n overrides: Partial<BootDeps> = {},\n): Promise<RenderTarget | null> {\n const {\n loadConfig,\n importSkeleton,\n createRoot: makeRoot,\n initObserver,\n adoptShell,\n warmModules: warm,\n } = { ...defaultDeps, ...overrides };\n\n if (!window.ph) {\n window.ph = {};\n }\n\n // Before anything else: the observers use `buffered: true`, so they catch\n // the browser's paint even when setup runs a tick after it fired.\n initObserver();\n\n // Started here and awaited at the bottom. The config fetch and the skeleton\n // chunk are independent round-trips, so they overlap; awaiting the chunk\n // first would put the config fetch — and with it everything the app needs —\n // behind it, which measured ~180ms of extra time-to-usable on a 150ms-RTT\n // connection. Mapping the rejection to a value here also means a config\n // failure is handled from the start, never an unhandled rejection.\n const config = loadConfig().then(\n () => ({ ok: true }) as const,\n (error: unknown) => ({ ok: false, error }) as const,\n );\n\n const hasShell = adoptShell();\n const root = makeRoot();\n\n try {\n // The prerendered shell is already painted; the skeleton would replace it.\n if (!hasShell) {\n const { default: AppSkeleton } = await importSkeleton();\n root.render(<AppSkeleton />);\n }\n } catch (error) {\n console.error(\"[connect:boot] the app skeleton failed to load:\", error);\n root.render(<BootError error={error} />);\n return null;\n }\n\n const warmed = warm().catch(() => undefined);\n const result = await config;\n if (!result.ok) {\n console.error(\n \"[connect:boot] the runtime config failed to load:\",\n result.error,\n );\n root.render(<BootError error={result.error} />);\n return null;\n }\n // The app imports these modules anyway; warmed, they evaluate in tasks of their own.\n await warmed;\n\n return root;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,iBAAqC;CAC5C,IAAI;EAIF,OAHc,YAAY,iBAAiB,YAAY,CAAC,CAAC,EAG7C,EAAE;CAChB,QAAQ;EACN;CACF;AACF;;;;;;AAaA,SAAS,cAAc,MAAc,OAAqB;CACxD,IAAI;EACF,MAAM,KAAK,OAAO;EAClB,IAAI,CAAC,IAAI;EACT,GAAG,cAAc,GAAG,eAAe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id":"8ec25d8b-a631-5bd4-bd14-4c3812a6b0c5"}
1
+ {"version":3,"file":"boot-BhAEKTca.js","sources":["../src/utils/performance-observer.ts","../src/warm-modules.ts","../src/boot.tsx"],"sourcesContent":["import { track } from \"../services/openpanel/buffer.js\";\nimport type { PHGlobal } from \"@powerhousedao/reactor-browser\";\n\n/**\n * Startup performance measurement.\n *\n * Captures First Contentful Paint (FCP) and Largest Contentful Paint (LCP) via\n * the Performance API and reports each to the OpenPanel analytics buffer (a\n * consent-gated, never-throwing queue). Call {@link initPerformanceObserver}\n * at the very top of the entry module, before the runtime config is fetched,\n * so FCP is caught even if the browser has already painted — a\n * `PerformanceObserver` with `buffered: true` replays entries that fired\n * before `observe()` was called.\n *\n * This module is intentionally dependency-light (only the OpenPanel event\n * buffer, which has no runtime imports of its own) so it is safe to load\n * before the runtime config is fetched. Every API access is guarded: nothing\n * here may throw into the application.\n */\n\nfunction navigationType(): string | undefined {\n try {\n const entry = performance.getEntriesByType(\"navigation\")[0] as\n | PerformanceNavigationTiming\n | undefined;\n return entry?.type; // \"navigate\" | \"reload\" | \"back_forward\" | \"prerender\"\n } catch {\n return undefined;\n }\n}\n\n// window.ph is the app's global bag (PHGlobal). This module owns a\n// `performance` sub-object it writes into; `PhWithPerformance` is a named\n// stand-in for that write so it type-checks without touching the shared\n// PHGlobal definition.\ntype PhWithPerformance = PHGlobal & { performance?: Record<string, number> };\n\n/**\n * Mirror the metric on `window.ph.performance` for devtools inspection. Only\n * writes to an already-existing `window.ph` (owned by the entry module) —\n * never creates or replaces it, so it can't clobber the app's global state.\n */\nfunction storeOnWindow(name: string, value: number): void {\n try {\n const ph = window.ph as PhWithPerformance | undefined;\n if (!ph) return;\n ph.performance = ph.performance ?? {};\n ph.performance[name] = value;\n } catch {\n // devtools mirror is best-effort only\n }\n}\n\nfunction report(name: string, ms: number): void {\n const value = Math.round(ms);\n const props: Record<string, unknown> = { ms: value };\n const navType = navigationType();\n if (navType) props.navigation = navType;\n\n storeOnWindow(name, value);\n\n // The console summary is a developer aid. In a production build it is noise\n // in every user's console and in every support screenshot, so it is gated\n // out of the bundle there.\n if (!import.meta.env.PROD) {\n try {\n console.info(`[connect:performance] ${name}: ${value}ms`, props);\n } catch {\n // console is best-effort only\n }\n }\n\n try {\n track(`performance.${name}`, props);\n } catch {\n // analytics must never throw into the app\n }\n}\n\n/**\n * Starts the observers. Returns a disposer that detaches all of them. The app\n * never needs it — the observers live as long as the page does — but it keeps\n * the module testable and leaves no listener behind.\n */\nexport function initPerformanceObserver(): () => void {\n if (\n typeof window === \"undefined\" ||\n typeof PerformanceObserver === \"undefined\"\n ) {\n return () => undefined;\n }\n\n const teardown: Array<() => void> = [];\n\n /** Registers a listener and queues its removal on dispose. */\n const listen = (\n target: EventTarget,\n type: string,\n handler: () => void,\n once = true,\n ): void => {\n target.addEventListener(type, handler, { once });\n teardown.push(() => target.removeEventListener(type, handler));\n };\n\n // FCP — from the \"paint\" buffer. It fires once, so stop observing after it.\n try {\n const fcpObserver = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n if (entry.name === \"first-contentful-paint\") {\n fcpObserver.disconnect();\n report(\"first_contentful_paint\", entry.startTime);\n }\n }\n });\n fcpObserver.observe({ type: \"paint\", buffered: true });\n teardown.push(() => fcpObserver.disconnect());\n } catch (err) {\n console.warn(\"[connect:performance] FCP observer failed:\", err);\n }\n\n // LCP — the final value only settles on an interaction or page hide, so latch\n // the latest candidate and report on the first terminal signal.\n let lcpMs = 0;\n let lcpReported = false;\n let lcpObserver: PerformanceObserver | undefined;\n\n /** Latches the newest candidate of a batch. The last entry is the newest. */\n const latch = (entries: ArrayLike<{ startTime: number }>): void => {\n if (entries.length > 0) {\n lcpMs = entries[entries.length - 1].startTime;\n }\n };\n\n const reportLcp = (): void => {\n // Several terminal signals can fire in one session (a click, then the page\n // hiding, then pagehide). The metric is sent for the first one only: every\n // repeat would be a double-count downstream.\n if (lcpReported) return;\n lcpReported = true;\n\n // A PerformanceObserver delivers entries in a task of its own, so a\n // terminal signal early in the page's life arrives while the newest\n // candidate is still buffered. Drain it before disconnecting — otherwise\n // an early click costs the session its LCP entirely.\n try {\n latch(lcpObserver?.takeRecords() ?? []);\n } catch {\n // draining is best-effort; report whatever was already delivered\n }\n\n lcpObserver?.disconnect();\n if (lcpMs > 0) report(\"largest_contentful_paint\", lcpMs);\n };\n\n try {\n lcpObserver = new PerformanceObserver((list) => {\n latch(list.getEntries());\n });\n lcpObserver.observe({ type: \"largest-contentful-paint\", buffered: true });\n teardown.push(() => lcpObserver?.disconnect());\n\n listen(window, \"pagehide\", reportLcp);\n listen(window, \"pointerdown\", reportLcp);\n listen(window, \"keydown\", reportLcp);\n // Not `once`: a page that loads in a background tab, or that the user tabs\n // away from and back, fires visibilitychange more than once, and only the\n // transition to \"hidden\" is terminal. A one-shot listener would be spent\n // on an earlier \"visible\" event and never see the hide.\n listen(\n document,\n \"visibilitychange\",\n () => {\n if (document.visibilityState === \"hidden\") reportLcp();\n },\n false,\n );\n } catch (err) {\n console.warn(\"[connect:performance] LCP observer failed:\", err);\n }\n\n return () => {\n for (const detach of teardown) {\n try {\n detach();\n } catch {\n // teardown is best-effort only\n }\n }\n teardown.length = 0;\n };\n}\n","// The app graph's largest packages; none reads the runtime config when evaluated.\nconst STAGES: (() => Promise<unknown>)[] = [\n () => import(\"@powerhousedao/reactor-browser\"),\n () => import(\"@powerhousedao/design-system/connect\"),\n];\n\nconst nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));\n\n/** Evaluates them one task each; imported with the app they'd be one long task. */\nexport async function warmModules(stages = STAGES) {\n for (const stage of stages) {\n await nextTask();\n // The app's own import reports a failure.\n await stage().catch(() => undefined);\n }\n}\n","// Imported by package name so projects resolve its fonts from Connect's dependencies.\nimport \"@powerhousedao/connect/fonts.css\";\nimport type { ComponentType, PropsWithChildren, ReactNode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport {\n adoptPrerenderedShell,\n hasPrerenderedShell,\n} from \"./components/prerendered-shell.js\";\nimport { loadRuntimeConfig } from \"./load-runtime-config.js\";\nimport { initPerformanceObserver } from \"./utils/performance-observer.js\";\nimport { warmModules } from \"./warm-modules.js\";\n\n/**\n * The two-phase startup shared by both entry points.\n *\n * Phase 1 paints the config-independent skeleton, so first contentful paint\n * does not wait on the `powerhouse.config.json` round-trip. Phase 2 awaits the\n * config and hands the caller back the root to render the config-dependent app\n * into — every module that reads the runtime config at module-evaluation\n * throws if the cache isn't warm, so the app graph may only be imported after\n * this resolves.\n *\n * Kept dependency-light on purpose: it loads before the config is fetched, so\n * nothing in its import graph may read the config.\n */\n\n/** All the bootstrap needs of a React root — and all a test has to stand in for. */\ntype RenderTarget = { render: (node: ReactNode) => void };\n\nexport type BootDeps = {\n loadConfig: () => Promise<unknown>;\n importSkeleton: () => Promise<{ default: ComponentType<PropsWithChildren> }>;\n createRoot: () => RenderTarget;\n initObserver: () => () => void;\n /** True when #root holds a prerendered shell, which stays until the app renders. */\n adoptShell: () => boolean;\n /** Evaluates the app's large packages while the config loads. */\n warmModules: () => Promise<unknown>;\n};\n\nconst defaultDeps: BootDeps = {\n loadConfig: () => loadRuntimeConfig(),\n importSkeleton: () => import(\"./components/app-skeleton.js\"),\n createRoot: () => createRoot(document.getElementById(\"root\")!),\n initObserver: initPerformanceObserver,\n adoptShell: () => {\n adoptPrerenderedShell(document.getElementById(\"root\"));\n return hasPrerenderedShell();\n },\n warmModules: () => warmModules(),\n};\n\n/**\n * Shown when startup cannot proceed. Deliberately built from plain elements:\n * this renders precisely when the runtime config is unavailable, so it must\n * not depend on anything that reads it.\n */\nfunction BootError({ error }: { error: unknown }): ReactNode {\n const message = error instanceof Error ? error.message : String(error);\n return (\n <div\n role=\"alert\"\n className=\"flex h-screen flex-col items-center justify-center gap-3 bg-background p-6 text-center\"\n >\n <h1 className=\"text-lg font-semibold text-foreground\">\n Connect could not start\n </h1>\n <p className=\"max-w-prose text-sm text-foreground\">\n Its runtime configuration could not be loaded. This is usually temporary\n — reloading often resolves it.\n </p>\n <pre className=\"max-w-prose overflow-x-auto rounded-sm bg-card px-3 py-2 text-left text-xs text-foreground\">\n {message}\n </pre>\n <button\n type=\"button\"\n className=\"rounded-sm bg-card px-4 py-2 text-sm font-medium text-foreground shadow-sm\"\n onClick={() => {\n window.location.reload();\n }}\n >\n Reload\n </button>\n </div>\n );\n}\n\n/**\n * Paints the skeleton, then waits for the runtime config.\n *\n * Returns the root to render the app into, or `null` when startup failed — in\n * which case the error state is already painted and the caller must not import\n * the config-dependent app. It resolves rather than rejecting on failure: both\n * entry points await this at their module's top level, where a rejection would\n * surface only as an unhandled rejection behind a skeleton that never goes\n * away.\n */\nexport async function bootConnect(\n overrides: Partial<BootDeps> = {},\n): Promise<RenderTarget | null> {\n const {\n loadConfig,\n importSkeleton,\n createRoot: makeRoot,\n initObserver,\n adoptShell,\n warmModules: warm,\n } = { ...defaultDeps, ...overrides };\n\n if (!window.ph) {\n window.ph = {};\n }\n\n // Before anything else: the observers use `buffered: true`, so they catch\n // the browser's paint even when setup runs a tick after it fired.\n initObserver();\n\n // Started here and awaited at the bottom. The config fetch and the skeleton\n // chunk are independent round-trips, so they overlap; awaiting the chunk\n // first would put the config fetch — and with it everything the app needs —\n // behind it, which measured ~180ms of extra time-to-usable on a 150ms-RTT\n // connection. Mapping the rejection to a value here also means a config\n // failure is handled from the start, never an unhandled rejection.\n const config = loadConfig().then(\n () => ({ ok: true }) as const,\n (error: unknown) => ({ ok: false, error }) as const,\n );\n\n const hasShell = adoptShell();\n const root = makeRoot();\n\n try {\n // The prerendered shell is already painted; the skeleton would replace it.\n if (!hasShell) {\n const { default: AppSkeleton } = await importSkeleton();\n root.render(<AppSkeleton />);\n }\n } catch (error) {\n console.error(\"[connect:boot] the app skeleton failed to load:\", error);\n root.render(<BootError error={error} />);\n return null;\n }\n\n const warmed = warm().catch(() => undefined);\n const result = await config;\n if (!result.ok) {\n console.error(\n \"[connect:boot] the runtime config failed to load:\",\n result.error,\n );\n root.render(<BootError error={result.error} />);\n return null;\n }\n // The app imports these modules anyway; warmed, they evaluate in tasks of their own.\n await warmed;\n\n return root;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,iBAAqC;CAC5C,IAAI;EAIF,OAHc,YAAY,iBAAiB,YAAY,CAAC,CAAC,EAG7C,EAAE;CAChB,QAAQ;EACN;CACF;AACF;;;;;;AAaA,SAAS,cAAc,MAAc,OAAqB;CACxD,IAAI;EACF,MAAM,KAAK,OAAO;EAClB,IAAI,CAAC,IAAI;EACT,GAAG,cAAc,GAAG,eAAe,CAAC;EACpC,GAAG,YAAY,QAAQ;CACzB,QAAQ,CAER;AACF;AAEA,SAAS,OAAO,MAAc,IAAkB;CAC9C,MAAM,QAAQ,KAAK,MAAM,EAAE;CAC3B,MAAM,QAAiC,EAAE,IAAI,MAAM;CACnD,MAAM,UAAU,eAAe;CAC/B,IAAI,SAAS,MAAM,aAAa;CAEhC,cAAc,MAAM,KAAK;CAKzB,IAAI,CAAC,YAAY,IAAI,MACnB,IAAI;EACF,QAAQ,KAAK,yBAAyB,KAAK,IAAI,MAAM,KAAK,KAAK;CACjE,QAAQ,CAER;CAGF,IAAI;EACF,MAAM,eAAe,QAAQ,KAAK;CACpC,QAAQ,CAER;AACF;;;;;;AAOA,SAAgB,0BAAsC;CACpD,IACE,OAAO,WAAW,eAClB,OAAO,wBAAwB,aAE/B,aAAa,KAAA;CAGf,MAAM,WAA8B,CAAC;;CAGrC,MAAM,UACJ,QACA,MACA,SACA,OAAO,SACE;EACT,OAAO,iBAAiB,MAAM,SAAS,EAAE,KAAK,CAAC;EAC/C,SAAS,WAAW,OAAO,oBAAoB,MAAM,OAAO,CAAC;CAC/D;CAGA,IAAI;EACF,MAAM,cAAc,IAAI,qBAAqB,SAAS;GACpD,KAAK,MAAM,SAAS,KAAK,WAAW,GAClC,IAAI,MAAM,SAAS,0BAA0B;IAC3C,YAAY,WAAW;IACvB,OAAO,0BAA0B,MAAM,SAAS;GACl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AAQ,MAAM,mDAAmD,KAAK;EACtE,KAAK,OAAO,oBAAC,WAAD,EAAkB,MAAQ,CAAA,CAAC;EACvC,OAAO;CACT;CAEA,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS;CAC3C,MAAM,SAAS,MAAM;CACrB,IAAI,CAAC,OAAO,IAAI;EACd,QAAQ,MACN,qDACA,OAAO,KACT;EACA,KAAK,OAAO,oBAAC,WAAD,EAAW,OAAO,OAAO,MAAQ,CAAA,CAAC;EAC9C,OAAO;CACT;CAEA,MAAM;CAEN,OAAO;AACT","debug_id":"d85bcd1c-9589-5251-a788-1f47f4ce367c"}
@@ -1,16 +1,16 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3e0972e1-aadd-58e8-be92-9244739ec183")}catch(e){}}();
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]="c99d9eba-de5e-562d-98d2-9ce94e1244f7")}catch(e){}}();
3
3
  import { buildTreeUrl, shortGitSha } from "@powerhousedao/shared";
4
4
  //#region src/utils/build-info.ts
5
5
  function getVersion() {
6
- return "6.2.3-dev.67";
6
+ return "6.2.3-dev.69";
7
7
  }
8
8
  /** True in the tsdown dist projects install; false in the monorepo app, where Vite bundles the worker. */
9
9
  function isPackagedConnectDist() {
10
10
  return true;
11
11
  }
12
12
  function getGitSha() {
13
- return "76485cea40bab93b3afb9bfe1a165587c814f5e1";
13
+ return "6d0605063a54a899881e2c9c04c85ae1158a1fb2";
14
14
  }
15
15
  /**
16
16
  * Build identity baked in at build time (define PH_CONNECT_BUILD_HASH —
@@ -28,5 +28,5 @@ function getGitUrl() {
28
28
  //#endregion
29
29
  export { isPackagedConnectDist as a, getVersion as i, getGitSha as n, shortGitSha as o, getGitUrl as r, getBuildHash as t };
30
30
 
31
- //# sourceMappingURL=build-info-DkY9PU7c.js.map
32
- //# debugId=3e0972e1-aadd-58e8-be92-9244739ec183
31
+ //# sourceMappingURL=build-info-D1Gpyvek.js.map
32
+ //# debugId=c99d9eba-de5e-562d-98d2-9ce94e1244f7
@@ -1 +1 @@
1
- {"version":3,"file":"build-info-DkY9PU7c.js","sources":["../src/utils/build-info.ts"],"sourcesContent":["import { buildTreeUrl, shortGitSha } from \"@powerhousedao/shared\";\nimport { packageJson } from \"./package-json.js\";\n\nexport { shortGitSha };\n\ndeclare const CONNECT_VERSION: string | undefined;\ndeclare const CONNECT_GIT_SHA: string | undefined;\ndeclare const PH_CONNECT_BUILD_HASH: string | undefined;\ndeclare const CONNECT_PACKAGED_DIST: boolean | undefined;\n\nexport function getVersion(): string {\n if (typeof CONNECT_VERSION !== \"undefined\") return CONNECT_VERSION;\n return (\n process.env.WORKSPACE_VERSION ??\n process.env.npm_package_version ??\n packageJson.version\n );\n}\n\n/** True in the tsdown dist projects install; false in the monorepo app, where Vite bundles the worker. */\nexport function isPackagedConnectDist(): boolean {\n return typeof CONNECT_PACKAGED_DIST !== \"undefined\" && CONNECT_PACKAGED_DIST;\n}\n\nexport function getGitSha(): string {\n if (typeof CONNECT_GIT_SHA !== \"undefined\") return CONNECT_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA ?? \"unknown\";\n}\n\n/**\n * Build identity baked in at build time (define PH_CONNECT_BUILD_HASH —\n * see builder-tools' connectBuildHashPlugin). Identical builds of the same\n * inputs produce the same hash; any change to the deployed content (Connect\n * version, project config, package list, build options) changes it.\n */\nexport function getBuildHash(): string {\n if (typeof PH_CONNECT_BUILD_HASH !== \"undefined\")\n return PH_CONNECT_BUILD_HASH;\n return \"unknown\";\n}\n\nexport function getGitUrl(): string | null {\n return buildTreeUrl(getGitSha());\n}\n"],"names":[],"mappings":";;;;AAUA,SAAgB,aAAqB;CACS,OAAA;AAM9C;;AAGA,SAAgB,wBAAiC;CAC/C,OAAA;AACF;AAEA,SAAgB,YAAoB;CACU,OAAA;AAE9C;;;;;;;AAQA,SAAgB,eAAuB;CACrC,IAAI,OAAO,0BAA0B,aACnC,OAAO;CACT,OAAO;AACT;AAEA,SAAgB,YAA2B;CACzC,OAAO,aAAa,UAAU,CAAC;AACjC","debug_id":"3e0972e1-aadd-58e8-be92-9244739ec183"}
1
+ {"version":3,"file":"build-info-D1Gpyvek.js","sources":["../src/utils/build-info.ts"],"sourcesContent":["import { buildTreeUrl, shortGitSha } from \"@powerhousedao/shared\";\nimport { packageJson } from \"./package-json.js\";\n\nexport { shortGitSha };\n\ndeclare const CONNECT_VERSION: string | undefined;\ndeclare const CONNECT_GIT_SHA: string | undefined;\ndeclare const PH_CONNECT_BUILD_HASH: string | undefined;\ndeclare const CONNECT_PACKAGED_DIST: boolean | undefined;\n\nexport function getVersion(): string {\n if (typeof CONNECT_VERSION !== \"undefined\") return CONNECT_VERSION;\n return (\n process.env.WORKSPACE_VERSION ??\n process.env.npm_package_version ??\n packageJson.version\n );\n}\n\n/** True in the tsdown dist projects install; false in the monorepo app, where Vite bundles the worker. */\nexport function isPackagedConnectDist(): boolean {\n return typeof CONNECT_PACKAGED_DIST !== \"undefined\" && CONNECT_PACKAGED_DIST;\n}\n\nexport function getGitSha(): string {\n if (typeof CONNECT_GIT_SHA !== \"undefined\") return CONNECT_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA ?? \"unknown\";\n}\n\n/**\n * Build identity baked in at build time (define PH_CONNECT_BUILD_HASH —\n * see builder-tools' connectBuildHashPlugin). Identical builds of the same\n * inputs produce the same hash; any change to the deployed content (Connect\n * version, project config, package list, build options) changes it.\n */\nexport function getBuildHash(): string {\n if (typeof PH_CONNECT_BUILD_HASH !== \"undefined\")\n return PH_CONNECT_BUILD_HASH;\n return \"unknown\";\n}\n\nexport function getGitUrl(): string | null {\n return buildTreeUrl(getGitSha());\n}\n"],"names":[],"mappings":";;;;AAUA,SAAgB,aAAqB;CACS,OAAA;AAM9C;;AAGA,SAAgB,wBAAiC;CAC/C,OAAA;AACF;AAEA,SAAgB,YAAoB;CACU,OAAA;AAE9C;;;;;;;AAQA,SAAgB,eAAuB;CACrC,IAAI,OAAO,0BAA0B,aACnC,OAAO;CACT,OAAO;AACT;AAEA,SAAgB,YAA2B;CACzC,OAAO,aAAa,UAAU,CAAC;AACjC","debug_id":"c99d9eba-de5e-562d-98d2-9ce94e1244f7"}