@powerhousedao/connect-core 6.2.3-dev.78 → 6.2.3-dev.80

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 (110) hide show
  1. package/dist/backend-auth-gate-DNKg_v4Y.js +65 -0
  2. package/dist/backend-auth-gate-DNKg_v4Y.js.map +1 -0
  3. package/dist/backend-auth-gate-DiFpY5rt.d.ts +19 -0
  4. package/dist/backend-auth-gate-DiFpY5rt.d.ts.map +1 -0
  5. package/dist/{index-q4bHCPoJ.d.ts → index-BMlma368.d.ts} +30 -7
  6. package/dist/index-BMlma368.d.ts.map +1 -0
  7. package/dist/{index-DQ0nbYne.d.ts → index-Beqvfchq.d.ts} +16 -3
  8. package/dist/index-Beqvfchq.d.ts.map +1 -0
  9. package/dist/{index-Cm8rYUhs.d.ts → index-Bfl1VYdj.d.ts} +21 -2
  10. package/dist/index-Bfl1VYdj.d.ts.map +1 -0
  11. package/dist/index.d.ts +5 -4
  12. package/dist/index.js +10 -9
  13. package/dist/{multi-reactor-CCMzwoMi.js → multi-reactor-D_2B4jmu.js} +2 -2
  14. package/dist/multi-reactor-D_2B4jmu.js.map +1 -0
  15. package/dist/{plugin-host-HhfxwUZN.js → plugin-host-CMr7lN40.js} +2 -2
  16. package/dist/{plugin-host-HhfxwUZN.js.map → plugin-host-CMr7lN40.js.map} +1 -1
  17. package/dist/{plugin-ui-W0ma6oKJ.js → plugin-ui-DHlnXJmN.js} +3 -3
  18. package/dist/{plugin-ui-W0ma6oKJ.js.map → plugin-ui-DHlnXJmN.js.map} +1 -1
  19. package/dist/plugins.js +2 -2
  20. package/dist/route-tree-D0aszMrk.js.map +1 -1
  21. package/dist/route-tree.d.ts +16 -16
  22. package/dist/route-tree.d.ts.map +1 -1
  23. package/dist/{router-DHL9GT3P.js → router-C4hDJ4_J.js} +10 -4
  24. package/dist/router-C4hDJ4_J.js.map +1 -0
  25. package/dist/router.d.ts +2 -2
  26. package/dist/router.js +4 -4
  27. package/dist/routes/__root.d.ts +3 -3
  28. package/dist/routes/__root.d.ts.map +1 -1
  29. package/dist/routes/__root.js +3 -3
  30. package/dist/routes/__root.js.map +1 -1
  31. package/dist/routes/_app/$.d.ts +3 -3
  32. package/dist/routes/_app/$.d.ts.map +1 -1
  33. package/dist/routes/_app/$.js +3 -3
  34. package/dist/routes/_app/$.js.map +1 -1
  35. package/dist/routes/_app/d/$driveSlug/{-$nodeSlug}.d.ts +5 -5
  36. package/dist/routes/_app/d/$driveSlug/{-$nodeSlug}.d.ts.map +1 -1
  37. package/dist/routes/_app/d/$driveSlug/{-$nodeSlug}.js +3 -3
  38. package/dist/routes/_app/d/$driveSlug/{-$nodeSlug}.js.map +1 -1
  39. package/dist/routes/_app/d/$driveSlug.d.ts +4 -4
  40. package/dist/routes/_app/d/$driveSlug.d.ts.map +1 -1
  41. package/dist/routes/_app/d/$driveSlug.js +3 -3
  42. package/dist/routes/_app/d/$driveSlug.js.map +1 -1
  43. package/dist/routes/_app/index.d.ts +41 -2
  44. package/dist/routes/_app/index.d.ts.map +1 -1
  45. package/dist/routes/_app/index.js +2 -2
  46. package/dist/routes/_app/index.js.map +1 -1
  47. package/dist/routes/_app/settings/appearance.d.ts +3 -3
  48. package/dist/routes/_app/settings/appearance.d.ts.map +1 -1
  49. package/dist/routes/_app/settings/appearance.js +3 -3
  50. package/dist/routes/_app/settings/appearance.js.map +1 -1
  51. package/dist/routes/_app/settings/packages.d.ts +3 -3
  52. package/dist/routes/_app/settings/packages.d.ts.map +1 -1
  53. package/dist/routes/_app/settings/packages.js +3 -3
  54. package/dist/routes/_app/settings/packages.js.map +1 -1
  55. package/dist/routes/_app/settings.d.ts +3 -3
  56. package/dist/routes/_app/settings.d.ts.map +1 -1
  57. package/dist/routes/_app/settings.js +3 -3
  58. package/dist/routes/_app/settings.js.map +1 -1
  59. package/dist/routes/_app.d.ts +41 -2
  60. package/dist/routes/_app.d.ts.map +1 -1
  61. package/dist/routes/_app.js +2 -2
  62. package/dist/routes/_app.js.map +1 -1
  63. package/dist/{runtime-D5hpzfgT.js → runtime-D20_LlB_.js} +64 -14
  64. package/dist/runtime-D20_LlB_.js.map +1 -0
  65. package/dist/runtime-config-D3YPhYyj.d.ts.map +1 -1
  66. package/dist/runtime-config.js +11 -5
  67. package/dist/runtime-config.js.map +1 -1
  68. package/dist/{runtime-flag-U8y14Nth.js → runtime-flag-DvxW_SD4.js} +2 -2
  69. package/dist/{runtime-flag-U8y14Nth.js.map → runtime-flag-DvxW_SD4.js.map} +1 -1
  70. package/dist/runtime.d.ts +3 -2
  71. package/dist/runtime.js +5 -4
  72. package/dist/{sidebar-CRv_DvBV.js → sidebar-C2y4mZnX.js} +13 -2
  73. package/dist/{sidebar-CRv_DvBV.js.map → sidebar-C2y4mZnX.js.map} +1 -1
  74. package/dist/{views-anOyTI7u.js → views-BtUVboYl.js} +79 -6
  75. package/dist/views-BtUVboYl.js.map +1 -0
  76. package/dist/views.d.ts +3 -2
  77. package/dist/views.js +3 -2
  78. package/package.json +8 -8
  79. package/src/router/index.ts +14 -2
  80. package/src/router/modals.tsx +3 -3
  81. package/src/router/route-options.ts +16 -0
  82. package/src/router/sidebar.ts +22 -0
  83. package/src/routes/__root.tsx +3 -2
  84. package/src/routes/_app/$.tsx +3 -2
  85. package/src/routes/_app/d/$driveSlug/{-$nodeSlug}.tsx +3 -2
  86. package/src/routes/_app/d/$driveSlug.tsx +3 -2
  87. package/src/routes/_app/index.tsx +2 -2
  88. package/src/routes/_app/settings/appearance.tsx +3 -3
  89. package/src/routes/_app/settings/packages.tsx +3 -3
  90. package/src/routes/_app/settings.tsx +3 -2
  91. package/src/routes/_app.tsx +2 -2
  92. package/src/runtime/app-reactor-client.ts +63 -12
  93. package/src/runtime/backend-auth-gate.ts +57 -0
  94. package/src/runtime/drive-relist.ts +18 -0
  95. package/src/runtime/graphql-routable-backend.ts +2 -2
  96. package/src/runtime/index.ts +8 -1
  97. package/src/runtime/reactor-client-mode.ts +26 -9
  98. package/src/runtime/runtime-config.ts +12 -1
  99. package/src/views/backend-auth-gate.tsx +76 -0
  100. package/src/views/directory-listing.tsx +2 -2
  101. package/src/views/editor-host.tsx +3 -3
  102. package/src/views/index.ts +5 -0
  103. package/src/views/layout.tsx +6 -2
  104. package/dist/index-Cm8rYUhs.d.ts.map +0 -1
  105. package/dist/index-DQ0nbYne.d.ts.map +0 -1
  106. package/dist/index-q4bHCPoJ.d.ts.map +0 -1
  107. package/dist/multi-reactor-CCMzwoMi.js.map +0 -1
  108. package/dist/router-DHL9GT3P.js.map +0 -1
  109. package/dist/runtime-D5hpzfgT.js.map +0 -1
  110. package/dist/views-anOyTI7u.js.map +0 -1
@@ -1,10 +1,12 @@
1
1
  import type { IReactorClient } from "@powerhousedao/reactor";
2
2
  import {
3
3
  getDrives,
4
- refreshReactorDataClient,
4
+ getFullReactorClient,
5
+ getPHStore,
6
+ recordBackendAuthError,
7
+ setBackendAuth,
5
8
  setDrives,
6
9
  setFullReactorClient,
7
- getPHStore,
8
10
  } from "@powerhousedao/reactor-browser";
9
11
  import type { DocumentDriveDocument } from "@powerhousedao/shared/document-drive";
10
12
  import type { ISigner } from "@powerhousedao/shared/document-model";
@@ -17,6 +19,7 @@ import type {
17
19
  import type { ReactorClientMode } from "./reactor-client-mode.js";
18
20
  import { resolveReactorClientMode } from "./reactor-client-mode.js";
19
21
  import { isReactorWorkerEnabled } from "./reactor-worker-flag.js";
22
+ import { setDriveRelister } from "./drive-relist.js";
20
23
 
21
24
  type MultiReactorModule = typeof MultiReactor;
22
25
 
@@ -133,35 +136,83 @@ function requireModule(params: AppReactorClientParams): LocalReactorModule {
133
136
  return params.module;
134
137
  }
135
138
 
136
- /** A Switchboard that cannot answer must not fail boot: list the tab's drives. */
139
+ /**
140
+ * A Switchboard that cannot answer must not fail boot: list the tab's drives.
141
+ *
142
+ * A Switchboard that REFUSES the caller (401/403) must not fail boot either:
143
+ * the refusal is recorded (`backendAuth`) so the root view shows the sign-in
144
+ * gate, and the drive list is empty until the user is someone the backend
145
+ * accepts. A remote-only client has no local drives to fall back on.
146
+ */
137
147
  export async function getAppDrives(
138
148
  client: IReactorClient,
139
149
  local: IReactorClient,
140
150
  ): Promise<DocumentDriveDocument[]> {
141
151
  if (client === local) {
142
- return getDrives(local);
152
+ try {
153
+ const drives = await getDrives(local);
154
+ setBackendAuth(undefined);
155
+ return drives;
156
+ } catch (error) {
157
+ if (recordBackendAuthError(error, "switchboard")) {
158
+ logger.warn(
159
+ "The Switchboard refused this caller; showing the sign-in gate: @error",
160
+ error,
161
+ );
162
+ return [];
163
+ }
164
+ throw error;
165
+ }
143
166
  }
144
167
  try {
145
- return await getDrives(client);
168
+ const drives = await getDrives(client);
169
+ setBackendAuth(undefined);
170
+ return drives;
146
171
  } catch (error) {
147
- logger.warn(
148
- "Could not list drives through the router; listing the local reactor's: @error",
149
- error,
150
- );
172
+ if (recordBackendAuthError(error, "switchboard")) {
173
+ logger.warn(
174
+ "A remote backend refused this caller; listing the local reactor's drives: @error",
175
+ error,
176
+ );
177
+ } else {
178
+ logger.warn(
179
+ "Could not list drives through the router; listing the local reactor's: @error",
180
+ error,
181
+ );
182
+ }
151
183
  return getDrives(local);
152
184
  }
153
185
  }
154
186
 
187
+ /**
188
+ * The boot refresh of the drives store. It lists through `getAppDrives`
189
+ * whichever client is in use, so a Switchboard that refuses the caller is
190
+ * recorded for the sign-in gate here too: the remote-only client is its own
191
+ * `local`, and a bare `refreshReactorDataClient` would let the 401 escape
192
+ * and fail the boot before the gate can render.
193
+ */
155
194
  export async function refreshAppDrives(
156
195
  client: IReactorClient,
157
196
  local: IReactorClient,
158
197
  ): Promise<void> {
159
- if (client === local) {
160
- return refreshReactorDataClient(client);
161
- }
162
198
  setDrives(await getAppDrives(client, local));
163
199
  }
164
200
 
201
+ /**
202
+ * Lists the drives again as the caller the tab now is, through the clients
203
+ * boot left in the store: after a sign-in landing or a sign-out that followed
204
+ * a backend's refusal. Nothing to do before boot has set a client.
205
+ */
206
+ export async function relistAppDrives(): Promise<void> {
207
+ const client = getFullReactorClient();
208
+ if (!client) return;
209
+ const local = getPHStore()?.reactorClientModule?.client ?? client;
210
+ await refreshAppDrives(client, local);
211
+ }
212
+
213
+ // The backend auth gate relists through drive-relist (see there)
214
+ setDriveRelister(relistAppDrives);
215
+
165
216
  async function buildRouter(
166
217
  params: AppReactorClientParams,
167
218
  ): Promise<IReactorClient | undefined> {
@@ -0,0 +1,57 @@
1
+ import {
2
+ setBackendAuth,
3
+ useBackendAuth,
4
+ useUser,
5
+ } from "@powerhousedao/reactor-browser";
6
+ import { logger } from "document-model";
7
+ import { useEffect, useRef } from "react";
8
+ import { relistDrives } from "./drive-relist.js";
9
+
10
+ /** What the gate shows: nothing, a sign-in, or a "not allowed" notice. */
11
+ export type BackendAuthGateMode = "login" | "unauthorized" | null;
12
+
13
+ /**
14
+ * The gate decision for the app's backend: "login" when the backend refused
15
+ * an anonymous caller, "unauthorized" when it refused a signed-in one.
16
+ *
17
+ * A change of identity after the refusal (a sign-in landing, a sign-out)
18
+ * clears it and lists the drives again as the new caller; a refusal that
19
+ * stands is recorded afresh by that listing. The caller a refusal was seen
20
+ * for is kept in a ref rather than an effect cleanup: StrictMode runs
21
+ * cleanups on its simulated unmount at mount, which cleared a refusal
22
+ * recorded during boot before the root ever rendered the gate.
23
+ */
24
+ export function useBackendAuthGate(): BackendAuthGateMode {
25
+ const refusal = useBackendAuth();
26
+ const user = useUser();
27
+ const address = user?.address;
28
+ const refusedAt = refusal?.at;
29
+ const refusedAs = useRef<{ at: string; address: string | undefined }>(
30
+ undefined,
31
+ );
32
+ useEffect(() => {
33
+ if (!refusedAt) {
34
+ refusedAs.current = undefined;
35
+ return;
36
+ }
37
+ const seen = refusedAs.current;
38
+ if (seen?.at !== refusedAt) {
39
+ refusedAs.current = { at: refusedAt, address };
40
+ return;
41
+ }
42
+ if (seen.address === address) return;
43
+ refusedAs.current = undefined;
44
+ setBackendAuth(undefined);
45
+ relistDrives().catch((error: unknown) => {
46
+ logger.warn(
47
+ "Could not list the drives again after the identity changed: @error",
48
+ error,
49
+ );
50
+ });
51
+ }, [address, refusedAt]);
52
+ if (!refusal) return null;
53
+ // A 403 for a signed-in user is final until they switch account; a 401 for
54
+ // a signed-in user means the token did not reach the backend yet (a stale
55
+ // boot), which signing in again also fixes.
56
+ return address ? "unauthorized" : "login";
57
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Lists the app's drives again: `app-reactor-client` registers how when it
3
+ * loads, which boot does before anything can ask.
4
+ *
5
+ * The backend auth gate calls through here rather than importing the client:
6
+ * the client reaches the runtime config, which loads the plugin UI and with
7
+ * it core's views, and the gate is one of those views.
8
+ */
9
+ let relist: (() => Promise<void>) | undefined;
10
+
11
+ export function setDriveRelister(fn: () => Promise<void>): void {
12
+ relist = fn;
13
+ }
14
+
15
+ /** Nothing to do before the client registered: boot lists the drives itself. */
16
+ export function relistDrives(): Promise<void> {
17
+ return relist ? relist() : Promise.resolve();
18
+ }
@@ -138,8 +138,8 @@ export function createGraphQLRoutableBackend(
138
138
  subscribe: (search, callback, view) =>
139
139
  gql.subscribe(search, callback, view),
140
140
  getCreateSignaturePolicy: () => gql.getCreateSignaturePolicy(),
141
- getCreateProtocolVersions: (parent, signal) =>
142
- gql.getCreateProtocolVersions(parent, signal),
141
+ getCreateProtocolVersions: (options, signal) =>
142
+ gql.getCreateProtocolVersions(options, signal),
143
143
  create: async <TDocument extends PHDocument = PHDocument>(
144
144
  document: PHDocument,
145
145
  parent?: string,
@@ -14,15 +14,22 @@ export {
14
14
  resolveReactorWorkerEnabled,
15
15
  } from "./reactor-worker-flag.js";
16
16
  export type { ReactorWorkerFlagInput } from "./reactor-worker-flag.js";
17
- export { resolveReactorClientMode } from "./reactor-client-mode.js";
17
+ export {
18
+ REACTOR_CLIENT_QUERY_KEY,
19
+ REACTOR_CLIENT_STORAGE_KEY,
20
+ resolveReactorClientMode,
21
+ } from "./reactor-client-mode.js";
18
22
  export type { ReactorClientMode } from "./reactor-client-mode.js";
19
23
  export {
20
24
  createAppReactorClient,
21
25
  getAppDrives,
22
26
  planReactorClient,
23
27
  refreshAppDrives,
28
+ relistAppDrives,
24
29
  selectAppReactorClient,
25
30
  } from "./app-reactor-client.js";
31
+ export { useBackendAuthGate } from "./backend-auth-gate.js";
32
+ export type { BackendAuthGateMode } from "./backend-auth-gate.js";
26
33
  export type {
27
34
  AppReactorClientParams,
28
35
  CreateAppReactorClientOptions,
@@ -9,10 +9,11 @@ import { isReactorWorkerEnabled } from "./reactor-worker-flag.js";
9
9
  *
10
10
  * in-process | worker | remote | router
11
11
  *
12
- * Precedence: an explicit `?reactorClient=` query override (handy for a quick
13
- * check), then the served `connect.instance.reactorClient` (projected from the
14
- * host's reactor backends), then the LEGACY booleans — so a config that only
15
- * sets reactorWorker/multiReactor behaves exactly as before.
12
+ * Precedence: an explicit `?reactorClient=` query override (kept in
13
+ * localStorage so it survives a reload), then a stored override, then the
14
+ * served `connect.instance.reactorClient` (projected from the host's reactor
15
+ * backends), then the LEGACY booleans — so a config that only sets
16
+ * reactorWorker/multiReactor behaves exactly as before.
16
17
  *
17
18
  * `remote` is the only mode that builds NO local reactor (no PGlite): it is a
18
19
  * pure client to a remote Switchboard. `router` keeps the local reactor and
@@ -27,20 +28,36 @@ const MODES: ReadonlySet<string> = new Set([
27
28
  "router",
28
29
  ]);
29
30
 
30
- function fromQuery(): ReactorClientMode | undefined {
31
+ export const REACTOR_CLIENT_QUERY_KEY = "reactorClient";
32
+ export const REACTOR_CLIENT_STORAGE_KEY = "ph:reactorClient";
33
+
34
+ const asMode = (value: string | null | undefined) =>
35
+ value && MODES.has(value) ? (value as ReactorClientMode) : undefined;
36
+
37
+ function fromTab(): ReactorClientMode | undefined {
31
38
  if (typeof window === "undefined") return undefined;
39
+ let query: ReactorClientMode | undefined;
32
40
  try {
33
- const value = new URLSearchParams(window.location.search).get(
34
- "reactorClient",
41
+ query = asMode(
42
+ new URLSearchParams(window.location.search).get(REACTOR_CLIENT_QUERY_KEY),
35
43
  );
36
- return value && MODES.has(value) ? (value as ReactorClientMode) : undefined;
37
44
  } catch {
38
45
  return undefined;
39
46
  }
47
+ try {
48
+ if (query) {
49
+ window.localStorage.setItem(REACTOR_CLIENT_STORAGE_KEY, query);
50
+ return query;
51
+ }
52
+ return asMode(window.localStorage.getItem(REACTOR_CLIENT_STORAGE_KEY));
53
+ } catch {
54
+ // Blocked storage: the query still applies for this page load.
55
+ return query;
56
+ }
40
57
  }
41
58
 
42
59
  export function resolveReactorClientMode(): ReactorClientMode {
43
- const override = fromQuery();
60
+ const override = fromTab();
44
61
  if (override) return override;
45
62
  const configured = getRuntimeConfig().connect.instance?.reactorClient;
46
63
  if (configured && MODES.has(configured)) return configured;
@@ -2,6 +2,7 @@
2
2
  import type { RuntimePowerhouseConfig } from "@powerhousedao/shared/connect";
3
3
  import { ConfigLoader } from "@powerhousedao/shared/connect/config-loader";
4
4
  import { JsonConfigAdapter } from "@powerhousedao/shared/connect/json-adapter";
5
+ import { resolveOriginPlaceholders } from "@powerhousedao/shared/connect/origin-placeholder";
5
6
  import type { ConnectPluginDefinition } from "../plugins/types.js";
6
7
  import { getConnectRegistry } from "../registry.js";
7
8
 
@@ -38,7 +39,17 @@ export async function loadRuntimeConfig(
38
39
  // Handled here so a failed config read doesn't leave them unhandled.
39
40
  void pluginHost?.catch(() => undefined);
40
41
  void pluginUi?.catch(() => undefined);
41
- const config = (await loader().read()) as RuntimePowerhouseConfig;
42
+ let config = (await loader().read()) as RuntimePowerhouseConfig;
43
+ // A served config names a switchboard this page's server proxies as
44
+ // `${origin}` (the connect runner's `runner.proxy`): resolved here, once,
45
+ // against the page's origin, so every consumer sees absolute URLs and the
46
+ // same config holds from localhost and from a published site alike. Not
47
+ // in Node (the shell prerender): there is no page origin to resolve to.
48
+ const origin = globalThis.location?.origin;
49
+ if (origin) {
50
+ config = resolveOriginPlaceholders(config, origin);
51
+ loader().prime(config);
52
+ }
42
53
  // R3: a served composition (projected from host.js runner.plugins by the
43
54
  // uniform-runners connect runner) runs the plugin pipeline over the config
44
55
  // BEFORE the cache warms — every downstream consumer sees the transformed
@@ -0,0 +1,76 @@
1
+ import {
2
+ logout,
3
+ openRenown,
4
+ useBackendAuth,
5
+ useUser,
6
+ } from "@powerhousedao/reactor-browser";
7
+ import type { BackendAuthGateMode } from "../runtime/backend-auth-gate.js";
8
+
9
+ // The decision lives with the runtime, so a root view outside this chunk
10
+ // (Connect's own) can take it without loading every core view.
11
+ export { useBackendAuthGate } from "../runtime/backend-auth-gate.js";
12
+ export type { BackendAuthGateMode } from "../runtime/backend-auth-gate.js";
13
+
14
+ /**
15
+ * Full-page gate rendered by the root view in place of the routes when the
16
+ * backend refused the caller. Signing in goes through Renown's redirect, so
17
+ * the page comes back with the user and boots again as them.
18
+ */
19
+ export function BackendAuthGate({
20
+ mode,
21
+ }: {
22
+ mode: Exclude<BackendAuthGateMode, null>;
23
+ }) {
24
+ const user = useUser();
25
+ const refusal = useBackendAuth();
26
+ const where = refusal?.backend ? ` (${refusal.backend})` : "";
27
+ return (
28
+ <div
29
+ role="dialog"
30
+ aria-labelledby="backend-auth-gate-title"
31
+ className="flex h-full min-h-[60vh] items-center justify-center p-6"
32
+ >
33
+ <div className="flex w-full max-w-md flex-col gap-4 rounded-lg border border-core-border bg-core-bg p-6 text-core-fg">
34
+ {mode === "login" ? (
35
+ <>
36
+ <h1 id="backend-auth-gate-title" className="text-lg font-semibold">
37
+ Sign in to continue
38
+ </h1>
39
+ <p className="text-sm text-core-muted">
40
+ This server{where} only answers signed-in users. Sign in with
41
+ Renown to open it.
42
+ </p>
43
+ <button
44
+ type="button"
45
+ className="self-start rounded border border-core-border px-3 py-1 hover:bg-core-hover"
46
+ onClick={() => openRenown()}
47
+ >
48
+ Sign in with Renown
49
+ </button>
50
+ </>
51
+ ) : (
52
+ <>
53
+ <h1 id="backend-auth-gate-title" className="text-lg font-semibold">
54
+ This account is not allowed here
55
+ </h1>
56
+ <p className="text-sm text-core-muted">
57
+ You are signed in as{" "}
58
+ <code className="break-all">{user?.address}</code>, but this
59
+ server{where} does not accept that account. Ask its admin for
60
+ access, or switch to another account.
61
+ </p>
62
+ <button
63
+ type="button"
64
+ className="self-start rounded border border-core-border px-3 py-1 hover:bg-core-hover"
65
+ onClick={() => {
66
+ void logout().then(() => openRenown());
67
+ }}
68
+ >
69
+ Switch account
70
+ </button>
71
+ </>
72
+ )}
73
+ </div>
74
+ </div>
75
+ );
76
+ }
@@ -49,11 +49,11 @@ function HomeLink(props: { children: ReactNode }) {
49
49
 
50
50
  // A row's date is a nicety: it shows "-" when the document can't load.
51
51
  class Quiet extends Component<{ children: ReactNode }, { failed: boolean }> {
52
- state = { failed: false };
52
+ override state = { failed: false };
53
53
  static getDerivedStateFromError() {
54
54
  return { failed: true };
55
55
  }
56
- render() {
56
+ override render() {
57
57
  return this.state.failed ? "-" : this.props.children;
58
58
  }
59
59
  }
@@ -16,7 +16,7 @@ type BoundaryProps = {
16
16
  type BoundaryState = { error?: unknown; keys: readonly unknown[] };
17
17
 
18
18
  class EditorErrorBoundary extends Component<BoundaryProps, BoundaryState> {
19
- state: BoundaryState = { keys: this.props.resetKeys };
19
+ override state: BoundaryState = { keys: this.props.resetKeys };
20
20
 
21
21
  static getDerivedStateFromError(error: unknown): Partial<BoundaryState> {
22
22
  return { error };
@@ -33,11 +33,11 @@ class EditorErrorBoundary extends Component<BoundaryProps, BoundaryState> {
33
33
  return changed ? { error: undefined, keys: props.resetKeys } : null;
34
34
  }
35
35
 
36
- componentDidCatch(error: unknown, info: ErrorInfo) {
36
+ override componentDidCatch(error: unknown, info: ErrorInfo) {
37
37
  console.error(`[connect] ${this.props.label} failed:`, error, info);
38
38
  }
39
39
 
40
- render() {
40
+ override render() {
41
41
  const { error } = this.state;
42
42
  if (error === undefined) return this.props.children;
43
43
  return (
@@ -7,6 +7,11 @@ export { EditorHost } from "./editor-host.js";
7
7
  export type { DocumentEditorProps, EditorHostProps } from "./editor-host.js";
8
8
  export { DriveIndex } from "./home.js";
9
9
  export { formatModified } from "./index-table.js";
10
+ export {
11
+ BackendAuthGate,
12
+ useBackendAuthGate,
13
+ type BackendAuthGateMode,
14
+ } from "./backend-auth-gate.js";
10
15
  export { CoreHeader, CoreLayout, CoreRoot } from "./layout.js";
11
16
  export { DriveNotFoundPage, NotFoundPage } from "./not-found-page.js";
12
17
  export {
@@ -14,6 +14,7 @@ import { useIsEmbedded } from "../runtime/embedded.js";
14
14
  import { ThemeToggle } from "./theme-toggle.js";
15
15
  import { linkClass } from "./index-table.js";
16
16
  import * as modalViews from "./modals.js";
17
+ import { BackendAuthGate, useBackendAuthGate } from "./backend-auth-gate.js";
17
18
 
18
19
  // The layout shares the modals' chunk, so it renders them directly.
19
20
  const coreModals: ConnectModals = Object.fromEntries(
@@ -23,16 +24,19 @@ const coreModals: ConnectModals = Object.fromEntries(
23
24
  ]),
24
25
  );
25
26
 
26
- /** Core's root: the page, in the theme. */
27
+ /** Core's root: the page, in the theme. When the app's backend refused the
28
+ * caller, the sign-in gate stands in for every route, so a shell that
29
+ * replaces core's layout still gets it. */
27
30
  export function CoreRoot() {
28
31
  initTheme();
29
32
  useTheme();
33
+ const gate = useBackendAuthGate();
30
34
  return (
31
35
  <div className="h-screen overflow-auto bg-core-bg text-core-fg">
32
36
  {/* The matched routes' head: the document title. */}
33
37
  <HeadContent />
34
38
  <Suspense name="CoreRoot">
35
- <Outlet />
39
+ {gate ? <BackendAuthGate mode={gate} /> : <Outlet />}
36
40
  </Suspense>
37
41
  <ModalOutlet modals={coreModals} />
38
42
  </div>
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-Cm8rYUhs.d.ts","names":[],"sources":["../src/router/create-target.ts","../src/router/cold-start.ts","../src/router/app-router.ts","../src/router/navigation.ts","../src/router/perf-marks.ts","../src/router/core-views.tsx","../src/router/core-app.tsx","../src/router/modal-frame.tsx","../src/router/scroll.ts","../src/router/search.ts","../src/router/sidebar.ts","../src/router/settings.ts","../src/router/titles.ts"],"mappings":";;;;;;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KF;KAGR;EAAkB;EAAiB,YAAY;;;KAGxC,mBAAmB;EAC7B;EACA;EACA;;;iBAIc,eACd,eAAe,UACf,SAAS,uBACR;;iBAoBa,aAAa,QAAQ,YAAY;iBAWjC,mBAAe;;iBAOf,iBACd,kBAAkB,iBAClB,SAAS;;iBAUK,iBAAiB,QAAQ;;iBAKzB,wBACd,SACA;EAEA,kBAAkB;EAClB,SAAS;;;iBAYK,cAAc,8BAA8B;;;iBAM5C,qCAA2B;;iBAc3B,eAAe,gBAE0B;;;;iBC3IzC,SAAS;;iBAKT,cAAc;;iBAKd,WACd,OAAO,SACP,MAAM,4BACN"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-DQ0nbYne.d.ts","names":[],"sources":["../src/views/content.tsx","../src/views/directory-listing.tsx","../src/views/document-history.tsx","../src/views/document-json.tsx","../src/views/editor-host.tsx","../src/views/home.tsx","../src/views/index-table.tsx","../src/views/layout.tsx","../src/views/not-found-page.tsx","../src/views/modals.tsx","../src/views/route-views.tsx","../src/views/settings.tsx","../src/views/settings-packages.tsx","../src/views/theme-toggle.tsx"],"mappings":";;;;;;;iBAoBgB,eAAe;EAAc,UAAU;gCAAY,IAAA;;;iBAgCnD,2CAAW,IAAA;;iBAkCX,wCAAQ,IAAA;;;;iBCFR,mBAAmB,OAAO,QAAQ,YAAY,+EAAc,IAAA,UAAA,SAAA,aAAA,6CAAA,SAAA,6BAAA,+CAAA,8CAAA;;;;cCtE/D;;iBAmHG,kBAAkB,YAAY,gDAAiB,IAAA;;;;iBC1F/C,eAAe,YAAY,gDAAiB,IAAA;;;;KClChD,sBAAsB;EAChC;EACA;IAAY;IAAoB;;;KA8CtB;;EAEV;;EAEA;EACA,UAAU;;;iBAII,aACd,WACA,OACA,YACC,8CAAe,IAAA;;;;iBC1BF,0CAAU,IAAA;;;;iBCrCV,eAAe;;;;iBCuBf,wCAAQ,IAAA;;iBAgBR,0CAAU,IAAA;;;iBA8BV,0CAAU,IAAA;;;;iBCpEV,eAAe;EAAe;gCAAoB,IAAA;iBAyBlD,oBAAoB;EAAe;gCAAmB,IAAA;;;;;iBCmEtD,mDAAmB,IAAA;;iBAiGnB,0CAAU,IAAA;;iBAuCV,+CAAe,IAAA;;iBAqCf,2DAA2B,IAAA;;iBA0C3B,+DAA+B,IAAA;;iBAiC/B,+DAA+B,IAAA;;iBAgC/B,sDAAsB,IAAA;;;;iBCrXtB,iBAAiB,OAAO,SAAS,kDAAmB,IAAA;;;;iBC2BpD,gDAAgB,IAAA;;iBA+ChB,6CAAa,IAAA;;;;iBCyDb,2CAAW,IAAA;;;;iBCnIX,cAAc;EAAe;gCAAoB,IAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-q4bHCPoJ.d.ts","names":[],"sources":["../src/runtime/runtime-flag.ts","../src/runtime/multi-reactor-flag.ts","../src/runtime/reactor-worker-flag.ts","../src/runtime/reactor-client-mode.ts","../src/runtime/graphql-routable-backend.ts","../src/runtime/multi-reactor.ts","../src/runtime/app-reactor-client.ts","../src/runtime/ph-store.ts","../src/runtime/local-package.ts"],"mappings":";;;;;;;;;;KAAY;EACV;EACA;EACA;;iBAIc,mBAAmB,OAAO;KAY9B;EACV;EACA;EACA;;iBAKc,qBAAqB,MAAM;;;iBCxB3B;;;cCIH;cACA;KAED,yBAAyB;iBAErB,4BACd,OAAO;iBAKO;;;;;;;;;;;;;;;;;;KCEJ,oBAAoB;iBAqBhB,4BAA4B;;;KC4ChC,gCAAgC,KAC1C;KAIU;WACD,SAAS;;EAElB,QAAQ,QAAQ;;EAEhB;;;iBAIc,6BACd,SAAS,gCACR;;;;cCnEU;cACA;KAED,qBACR,6BACA;;cAQS,gBAAgB;iBAIb,WAAW,MAAM,6BAA6B;;iBAO9C,WACd,QAAQ,2BACD,QAAQ;;iBAcD,4BACd;;KAaU,gCACC,wCACO;KAER;;;EAGV,QAAQ;EACR;;EAEA,SAAS;;EAET,sBAAsB;EACtB,eAAe;;;;;cAMJ,iBAAiB;;cAwBjB,6BAA6B;mBACvB;EAEjB,YACE,mBAAmB,yBACnB,SAAS,sBACT,QAAQ,wBACR;;EAYF;;;;;;;;;iBAmBoB,wBACpB,QAAQ,qBACP,QAAQ;;;KCvJN,4BAA4B;KAErB;EACV,MAAM;;;EAGN,QAAQ;EACR;;EAEA,SAAS;EACT,sBAAsB;EACtB,mBAAmB,QAAQ;;;KAOjB;EACV,MAAM;;EAEN;EACA;;EAEA;;iBAGc,kBACd,OAAM,oBACL;;KAaS,uBACV,MAAM,sBACH,QAAQ;KAED,gCAAgC,KAC1C;EAGA,OAAO;;EAEP,eAAe;;;iBAIK,uBACpB,SAAS,gCAA6B;;;;;;;;;;;;iBA4BlB,uBACpB,QAAQ,yBACP,QAAQ;;iBA6BW,aACpB,QAAQ,gBACR,OAAO,iBACN,QAAQ;iBAeW,iBACpB,QAAQ,gBACR,OAAO,iBACN;;;;;iBCpJa,qBAAqB;;;;KCNzB,kBAAkB;GAC3B,OAAO;;KAGE,eAAe,wBAAwB;;KAGvC,qBAAqB,sBAAsB,QAAQ;;iBAG/C,iBACd,QAAQ,iCACP,mBAAmB,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"multi-reactor-CCMzwoMi.js","names":[],"sources":["../src/runtime/graphql-routable-backend.ts","../src/runtime/multi-reactor.ts"],"sourcesContent":["import {\n JOB_NOT_FOUND_ERROR_NAME,\n JobStatus,\n type PagedResults,\n type ReactorInfo,\n type ViewFilter,\n} from \"@powerhousedao/reactor\";\nimport {\n DRIVE_DOCUMENT_TYPES,\n findIsServableOverGraphQL,\n GraphQLReactorClient,\n type DriveIdCall,\n type GraphQLReactorClientOptions,\n} from \"@powerhousedao/reactor-browser\";\nimport type { IRoutableBackend } from \"@powerhousedao/reactor-router\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\n\nconst REMOTE_INFO_QUERY = /* GraphQL */ `\n query RemoteReactorInfo {\n inspection {\n info {\n storage {\n engine\n persistence\n durable\n selfHeal\n }\n workflows\n syncChannels\n }\n }\n }\n`;\n\ntype RemoteReactorInfo = {\n inspection: { info: Omit<ReactorInfo, \"access\"> };\n};\n\n/** Ids and slugs of documents this backend answered as drives, by drive id. */\nclass KnownDrives {\n private readonly ids = new Map<string, string>();\n\n learn<T extends PHDocument>(document: T): T {\n const { id, slug, documentType } = document.header;\n if ((DRIVE_DOCUMENT_TYPES as readonly string[]).includes(documentType)) {\n this.ids.set(id, id);\n if (slug) {\n this.ids.set(slug, id);\n }\n }\n return document;\n }\n\n learnPage<T extends PHDocument>(page: PagedResults<T>): PagedResults<T> {\n for (const document of page.results) {\n this.learn(document);\n }\n return page;\n }\n\n driveOf(identifier: string | undefined): string | undefined {\n return identifier === undefined ? undefined : this.ids.get(identifier);\n }\n\n /** Names a drive only when this backend proved it is one. */\n driveIdFor = (call: DriveIdCall): string | undefined => {\n switch (call.method) {\n case \"create\":\n case \"find\":\n return this.driveOf(call.parentId);\n case \"execute\":\n case \"deleteDocument\":\n return this.driveOf(call.documentId);\n case \"executeBatch\":\n for (const job of call.jobs ?? []) {\n const drive = this.driveOf(job.documentId);\n if (drive !== undefined) {\n return drive;\n }\n }\n return undefined;\n }\n };\n}\n\nexport type GraphQLRoutableBackendOptions = Omit<\n GraphQLReactorClientOptions,\n \"driveIdFor\"\n>;\n\nexport type GraphQLRoutableBackend = {\n readonly backend: IRoutableBackend;\n /** The Switchboard's own facts, from its inspection subgraph. */\n info(): Promise<ReactorInfo>;\n /** Reopens the realtime socket on the new credentials. */\n notifyCredentialsChanged(): void;\n};\n\n/** A Switchboard as a router backend; members GraphQL cannot serve are absent. */\nexport function createGraphQLRoutableBackend(\n options: GraphQLRoutableBackendOptions,\n): GraphQLRoutableBackend {\n const drives = new KnownDrives();\n const gql = new GraphQLReactorClient({\n ...options,\n driveIdFor: drives.driveIdFor,\n });\n const backend: IRoutableBackend = {\n supports: { find: findIsServableOverGraphQL, pointInTimeViews: false },\n drives: gql.read.drives,\n get: async <TDocument extends PHDocument>(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n ) => drives.learn(await gql.get<TDocument>(identifier, view, signal)),\n getMany: async <TDocument extends PHDocument>(\n ids: string[],\n view?: ViewFilter,\n signal?: AbortSignal,\n ) =>\n (await gql.getMany<TDocument>(ids, view, signal)).map((document) =>\n drives.learn(document),\n ),\n getOperations: (identifier, view, filter, paging, signal) =>\n gql.getOperations(identifier, view, filter, paging, signal),\n find: async (search, view, paging, signal) =>\n drives.learnPage(await gql.find(search, view, paging, signal)),\n isServed: (identifier, view, signal) =>\n gql.isServed(identifier, view, signal),\n getOutgoingRelationships: (source, type, view, paging, signal) =>\n gql.getOutgoingRelationships(source, type, view, paging, signal),\n getIncomingRelationships: (target, type, view, paging, signal) =>\n gql.getIncomingRelationships(target, type, view, paging, signal),\n getOutgoingRelationshipEdges: (source, type, view, paging, signal) =>\n gql.getOutgoingRelationshipEdges(source, type, view, paging, signal),\n getIncomingRelationshipEdges: (target, type, view, paging, signal) =>\n gql.getIncomingRelationshipEdges(target, type, view, paging, signal),\n subscribe: (search, callback, view) =>\n gql.subscribe(search, callback, view),\n getCreateSignaturePolicy: () => gql.getCreateSignaturePolicy(),\n getCreateProtocolVersions: (parent, signal) =>\n gql.getCreateProtocolVersions(parent, signal),\n create: async <TDocument extends PHDocument = PHDocument>(\n document: PHDocument,\n parent?: string,\n signal?: AbortSignal,\n ) => drives.learn(await gql.create<TDocument>(document, parent, signal)),\n execute: async <TDocument extends PHDocument>(\n identifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ) =>\n drives.learn(\n await gql.execute<TDocument>(identifier, branch, actions, signal),\n ),\n executeBatch: (request, signal) => gql.executeBatch(request, signal),\n deleteDocument: (identifier, propagate, signal) =>\n gql.deleteDocument(identifier, propagate, signal),\n setPreferredEditor: (identifier, editor, branch, signal) =>\n gql.setPreferredEditor(identifier, editor, branch, signal),\n getJob: async (jobId, signal) => {\n const job = await gql.getJob(jobId, signal);\n return job?.status === JobStatus.FAILED &&\n job.error?.name === JOB_NOT_FOUND_ERROR_NAME\n ? undefined\n : job;\n },\n waitForJob: (job, signal) => gql.waitForJob(job, signal),\n };\n return {\n backend,\n info: async () => {\n const result = await gql.request<RemoteReactorInfo>(REMOTE_INFO_QUERY);\n return {\n ...result.inspection.info,\n access: { admin: false, sql: false },\n };\n },\n notifyCredentialsChanged: () => gql.notifyCredentialsChanged(),\n };\n}\n","import {\n createReactorInspector,\n type ReactorInfo,\n} from \"@powerhousedao/reactor\";\nimport type {\n BrowserReactorClientModule,\n WorkerReactorClientModule,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n FanInPartialFailureError,\n fromReactorClient,\n RoutingReactorClient,\n type CollectionRequirementsInput,\n type ReactorReach,\n type RoutableBackendConfig,\n type RouterDiagnostic,\n type RoutingClientOptions,\n} from \"@powerhousedao/reactor-router\";\nimport type {\n DocumentModelModule,\n ISigner,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport {\n createGraphQLRoutableBackend,\n type GraphQLRoutableBackend,\n} from \"./graphql-routable-backend.js\";\n\nexport { createGraphQLRoutableBackend } from \"./graphql-routable-backend.js\";\nexport type {\n GraphQLRoutableBackend,\n GraphQLRoutableBackendOptions,\n} from \"./graphql-routable-backend.js\";\n\nexport const LOCAL_BACKEND_NAME = \"connect-local\";\nexport const REMOTE_BACKEND_NAME = \"switchboard-remote\";\n\nexport type LocalReactorModule =\n | BrowserReactorClientModule\n | WorkerReactorClientModule;\n\nconst REMOTE_REACH: ReactorReach = Object.freeze({\n hosting: \"remote\",\n inspection: \"none\",\n});\n\n/** Only the tab's reactor is inspectable here, so new collections land on it. */\nexport const PLACE_ON_LOCAL: CollectionRequirementsInput = Object.freeze({\n inspectable: true,\n});\n\nexport function localReach(kind: LocalReactorModule[\"kind\"]): ReactorReach {\n return kind === \"worker\"\n ? { hosting: \"worker\", inspection: \"rpc\" }\n : { hosting: \"in-process\", inspection: \"direct\" };\n}\n\n/** Read at every refresh, never kept: a rebuilt reactor reports its own. */\nexport function localFacts(\n module: LocalReactorModule,\n): () => Promise<ReactorInfo> {\n if (module.kind === \"worker\") {\n return () => module.inspector.info();\n }\n return async () => {\n const reactorModule = module.reactorModule;\n if (!reactorModule) {\n throw new Error(\"The in-tab reactor exposes no module to inspect\");\n }\n return createReactorInspector(reactorModule).info();\n };\n}\n\n/** `<origin>[/<prefix>]/d/<slug>` -> `<origin>[/<prefix>]/graphql`. */\nexport function deriveSwitchboardGraphqlUrl(\n remoteDriveUrl: string,\n): string | undefined {\n let parsed: URL;\n try {\n parsed = new URL(remoteDriveUrl);\n } catch {\n return undefined;\n }\n const prefix = /^(.*)\\/d\\/[^/]+\\/?$/.exec(parsed.pathname)?.[1];\n return prefix === undefined ? undefined : `${parsed.origin}${prefix}/graphql`;\n}\n\n/** The loaded document models, or a getter that reads the current ones. */\nexport type LoadedDocumentModels =\n | readonly DocumentModelModule[]\n | (() => readonly DocumentModelModule[]);\n\nexport type MultiReactorParams = {\n /** The local module, built and ready. Undefined builds a REMOTE-ONLY router\n * (no local backend → no local reactor, no PGlite): the `remote` client. */\n module: LocalReactorModule | undefined;\n remoteGraphqlUrl: string;\n /** Signs routed writes; unsigned (anonymous) without one. */\n signer?: ISigner;\n /** Signing models when the local module exposes no registry; the router asks the local reactor (or, remote-only, the loaded set). */\n documentModelModules: LoadedDocumentModels;\n onDiagnostic?: RouterDiagnostic;\n};\n\n/** Remote-only placement: the Switchboard serves every collection. (It offers\n * no inspection surface over GraphQL, so PLACE_ON_LOCAL's `inspectable`\n * requirement must NOT apply, or no backend would be eligible.) */\nexport const PLACE_ON_REMOTE: CollectionRequirementsInput = Object.freeze({});\n\n/**\n * The local answer stands when only the Switchboard could not answer -- but\n * only when there IS a local backend. Remote-only has nothing to fall back to,\n * so its errors surface. Installed as the router's `answerFailedIdCheck`, so\n * the facade and `write.isDocumentIdTaken` both apply it.\n */\nfunction localIdCheckAnswer(\n documentId: string,\n error: unknown,\n): boolean | undefined {\n if (!failedOnlyOnRemote(error)) {\n return undefined;\n }\n logger.warn(\n \"The Switchboard could not say whether @id is taken; using the local reactor's answer: @error\",\n documentId,\n error,\n );\n return false;\n}\n\n/** The router Connect installs, with Connect's handling of credentials and id checks. */\nexport class ConnectRoutingClient extends RoutingReactorClient {\n private readonly remote: GraphQLRoutableBackend;\n\n constructor(\n backends: readonly RoutableBackendConfig[],\n options: RoutingClientOptions,\n remote: GraphQLRoutableBackend,\n hasLocal: boolean,\n ) {\n super(backends, {\n ...options,\n answerFailedIdCheck: hasLocal\n ? localIdCheckAnswer\n : options.answerFailedIdCheck,\n });\n this.remote = remote;\n }\n\n /** Renown's sign-in and sign-out call this on whatever client is installed. */\n notifyCredentialsChanged(): void {\n this.remote.notifyCredentialsChanged();\n }\n}\n\nfunction failedOnlyOnRemote(error: unknown): boolean {\n return (\n error instanceof FanInPartialFailureError &&\n error.failures.every((failure) => failure.backend === REMOTE_BACKEND_NAME)\n );\n}\n\n/**\n * Build the Connect routing client. With a local `module` it is the router\n * over the tab's reactor (primary) and the Switchboard; WITHOUT one it is the\n * `remote` client — a remote-only router whose single backend is the\n * Switchboard, so no local reactor (and no PGlite) is built. Either way the\n * result is a full IReactorClient the app graph consumes unchanged.\n */\nexport async function buildMultiReactorClient(\n params: MultiReactorParams,\n): Promise<ConnectRoutingClient> {\n const module = params.module;\n const registry = module?.reactorModule?.documentModelRegistry;\n const loaded = params.documentModelModules;\n const loadedModules = typeof loaded === \"function\" ? loaded : () => loaded;\n const remote = createGraphQLRoutableBackend({\n url: params.remoteGraphqlUrl,\n documentModels: () => registry?.getAllModules() ?? loadedModules(),\n });\n const remoteBackend: RoutableBackendConfig = {\n name: REMOTE_BACKEND_NAME,\n backend: remote.backend,\n facts: () => remote.info(),\n reach: REMOTE_REACH,\n refusesMisroutes: false,\n };\n const backends: RoutableBackendConfig[] = module\n ? [\n {\n name: LOCAL_BACKEND_NAME,\n backend: fromReactorClient(module.client),\n facts: localFacts(module),\n reach: localReach(module.kind),\n refusesMisroutes: false,\n },\n remoteBackend,\n ]\n : [remoteBackend];\n const router = new ConnectRoutingClient(\n backends,\n {\n // Remote-only: the Switchboard is primary and serves every collection;\n // with a local reactor, new collections land on it (inspectable).\n primaryBackend: module ? LOCAL_BACKEND_NAME : REMOTE_BACKEND_NAME,\n defaultRequirements: module ? PLACE_ON_LOCAL : PLACE_ON_REMOTE,\n signer: params.signer,\n onDiagnostic: params.onDiagnostic,\n // The Switchboard serves no models over GraphQL; remote-only uses the loaded set.\n documentModelModules: module ? undefined : loadedModules,\n },\n remote,\n Boolean(module),\n );\n await router.refreshFacts();\n return router;\n}\n"],"mappings":";;;;;AAiBA,MAAM,oBAAkC;;;;;;;;;;;;;;;;;AAsBxC,IAAM,cAAN,MAAkB;CAChB,sBAAuB,IAAI,IAAoB;CAE/C,MAA4B,UAAgB;EAC1C,MAAM,EAAE,IAAI,MAAM,iBAAiB,SAAS;EAC5C,IAAK,qBAA2C,SAAS,YAAY,GAAG;GACtE,KAAK,IAAI,IAAI,IAAI,EAAE;GACnB,IAAI,MACF,KAAK,IAAI,IAAI,MAAM,EAAE;EAEzB;EACA,OAAO;CACT;CAEA,UAAgC,MAAwC;EACtE,KAAK,MAAM,YAAY,KAAK,SAC1B,KAAK,MAAM,QAAQ;EAErB,OAAO;CACT;CAEA,QAAQ,YAAoD;EAC1D,OAAO,eAAe,KAAA,IAAY,KAAA,IAAY,KAAK,IAAI,IAAI,UAAU;CACvE;;CAGA,cAAc,SAA0C;EACtD,QAAQ,KAAK,QAAb;GACE,KAAK;GACL,KAAK,QACH,OAAO,KAAK,QAAQ,KAAK,QAAQ;GACnC,KAAK;GACL,KAAK,kBACH,OAAO,KAAK,QAAQ,KAAK,UAAU;GACrC,KAAK;IACH,KAAK,MAAM,OAAO,KAAK,QAAQ,CAAC,GAAG;KACjC,MAAM,QAAQ,KAAK,QAAQ,IAAI,UAAU;KACzC,IAAI,UAAU,KAAA,GACZ,OAAO;IAEX;IACA;EACJ;CACF;AACF;;AAgBA,SAAgB,6BACd,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AAW,MAAM;EACxB,OAAO,WAAW,OAAO,IAAI;EAC7B,kBAAkB;CACpB,GACA,aACF,IACA,CAAC,aAAa,GAGhB;EAGE,gBAAgB,SAAS,qBAAqB;EAC9C,qBAAqB,SAAS,iBAAiB;EAC/C,QAAQ,OAAO;EACf,cAAc,OAAO;EAErB,sBAAsB,SAAS,KAAA,IAAY;CAC7C,GACA,QACA,QAAQ,MAAM,CAChB;CACA,MAAM,OAAO,aAAa;CAC1B,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"router-DHL9GT3P.js","names":[],"sources":["../src/router/perf-marks.ts","../src/router/scroll.ts","../src/router/search.ts","../src/router/navigation.ts","../src/router/connect-router.ts","../src/router/app-router.ts","../src/router/core-app.tsx"],"sourcesContent":["import type { AnyRouter } from \"@tanstack/react-router\";\n\n/** `localStorage[PERF_STORAGE_KEY] = \"1\"` or `?perf=1` turns the marks on in production. */\nexport const PERF_STORAGE_KEY = \"ph:perf\";\n\n/** The measures each navigation writes, as the bench reads them. */\nexport const ROUTER_MEASURES = {\n /** `navigation.open` to the router starting the navigation. */\n click: \"nav click\",\n /** Route loaders, until the router commits the matches. */\n loader: \"nav loader\",\n /** The commit until React has rendered it. */\n commit: \"nav commit\",\n /** The click (or the navigation's start) to the next frame after render. */\n total: \"nav total\",\n} as const;\n\n// Chrome's Performance panel shows these as \"Connect › Router\".\nconst DETAIL = {\n devtools: { dataType: \"track-entry\", track: \"Router\", trackGroup: \"Connect\" },\n} as const;\n\nlet marking = 0;\nlet clickedAt: number | undefined;\n\n/** On in dev builds; elsewhere only with the runtime flag. */\nexport function routerPerfEnabled(dev = !!import.meta.env?.DEV) {\n if (dev) return true;\n try {\n return (\n new URLSearchParams(location.search).get(\"perf\") === \"1\" ||\n localStorage.getItem(PERF_STORAGE_KEY) === \"1\"\n );\n } catch {\n return false;\n }\n}\n\n/** Marks a navigation's click; a no-op unless a router is being marked. */\nexport function markNavigationClick() {\n if (!marking) return;\n clickedAt = performance.now();\n performance.mark(\"nav:click\", { detail: DETAIL });\n}\n\nfunction measure(name: string, start: number | undefined, end: number) {\n if (start === undefined) return;\n performance.measure(name, { start, end, detail: DETAIL });\n}\n\n/** Writes each navigation's phases as performance measures; returns the unsubscribe. */\nexport function markRouterNavigations(\n router: Pick<AnyRouter, \"subscribe\">,\n enabled = routerPerfEnabled(),\n) {\n if (!enabled) return () => {};\n marking++;\n let generation = 0;\n let clicked: number | undefined;\n let navigated: number | undefined;\n let loading: number | undefined;\n let loaded: number | undefined;\n const unsubscribes = [\n router.subscribe(\"onBeforeNavigate\", () => {\n generation++;\n navigated = performance.now();\n clicked = clickedAt;\n clickedAt = undefined;\n measure(ROUTER_MEASURES.click, clicked, navigated);\n loading = loaded = undefined;\n }),\n router.subscribe(\"onBeforeLoad\", () => {\n loading = performance.now();\n }),\n router.subscribe(\"onLoad\", () => {\n loaded = performance.now();\n measure(ROUTER_MEASURES.loader, loading, loaded);\n }),\n router.subscribe(\"onRendered\", () => {\n measure(ROUTER_MEASURES.commit, loaded, performance.now());\n const current = generation;\n const start = clicked ?? navigated;\n // The frame after render, as close to paint as a script sees.\n requestAnimationFrame(() =>\n setTimeout(() => {\n if (current === generation) {\n measure(ROUTER_MEASURES.total, start, performance.now());\n }\n }),\n );\n }),\n ];\n return () => {\n marking--;\n for (const unsubscribe of unsubscribes) unsubscribe();\n };\n}\n","import type {\n AnyRouter,\n ParsedLocation,\n RouterHistory,\n} from \"@tanstack/react-router\";\n\ntype ScrollRouter = Pick<AnyRouter, \"subscribe\" | \"_scroll\" | \"options\"> & {\n history: RouterHistory;\n};\n\nconst TRAVERSALS = new Set([\"BACK\", \"FORWARD\", \"GO\"]);\nconst traversals = new WeakMap<object, { traversal: boolean }>();\n\n/** The router's `scrollRestoration`: on for back/forward only; other\n * navigations reset the content view in `bindConnectScroll`. */\nexport function connectScrollRestoration() {\n // The first load restores a reloaded page's scroll.\n const state = { traversal: true };\n const restore = ({ location }: { location: ParsedLocation }) =>\n state.traversal || !!location.hash;\n traversals.set(restore, state);\n return restore;\n}\n\n/** Tracks history actions, and resets a scrolled content view on new views. */\nexport function bindConnectScroll(router: ScrollRouter, contentViewId: string) {\n const state = traversals.get(router.options.scrollRestoration as object);\n if (!state) return () => {};\n const unsubscribeHistory = router.history.subscribe(({ action }) => {\n state.traversal = TRAVERSALS.has(action.type);\n });\n if (typeof document === \"undefined\") return unsubscribeHistory;\n\n // Read in the scroll event, where layout is clean, not at navigation.\n let scrolledView: Element | undefined;\n let windowScrolled = false;\n const onScroll = (event: Event) => {\n const target = event.target;\n if (target === document) {\n windowScrolled = window.scrollY > 0 || window.scrollX > 0;\n } else if (target instanceof Element && target.id === contentViewId) {\n scrolledView = target.scrollTop > 0 ? target : undefined;\n }\n };\n document.addEventListener(\"scroll\", onScroll, {\n capture: true,\n passive: true,\n });\n\n let resetScroll = true;\n const unsubscribes = [\n unsubscribeHistory,\n // The navigation's `resetScroll`, before the router clears it on render.\n router.subscribe(\"onBeforeRouteMount\", () => {\n resetScroll = router._scroll.n;\n }),\n router.subscribe(\"onRendered\", ({ toLocation }) => {\n if (state.traversal || toLocation.hash || !resetScroll) return;\n if (scrolledView?.isConnected) scrolledView.scrollTo(0, 0);\n if (windowScrolled) window.scrollTo(0, 0);\n scrolledView = undefined;\n windowScrolled = false;\n }),\n ];\n return () => {\n document.removeEventListener(\"scroll\", onScroll, { capture: true });\n for (const unsubscribe of unsubscribes) unsubscribe();\n };\n}\n","import {\n FEATURE_FLAG_PARAM_PREFIX,\n GLOBAL_SEARCH_PARAMS,\n parseRevisionHistoryPage,\n REVISION_HISTORY_PAGE_PARAM,\n REVISION_HISTORY_PARAM,\n searchParamsToString,\n} from \"@powerhousedao/reactor-browser\";\nimport type { SearchMiddleware } from \"@tanstack/react-router\";\nimport { retainSearchParams } from \"@tanstack/react-router\";\n\n// Shared with reactor-browser's fallback navigation.\nexport { FEATURE_FLAG_PARAM_PREFIX, GLOBAL_SEARCH_PARAMS };\n\n/** Connect's query params: plain strings, as in the URL. */\nexport type ConnectSearch = Record<string, string | undefined>;\n\nconst retainFeatureFlags: SearchMiddleware<ConnectSearch> = ({\n search,\n next,\n}) => {\n const result = { ...next(search) };\n for (const [key, value] of Object.entries(search)) {\n if (key.startsWith(FEATURE_FLAG_PARAM_PREFIX) && !(key in result)) {\n result[key] = value;\n }\n }\n return result;\n};\n\n/** The root route's middlewares; they apply to every navigation and redirect. */\nexport const connectSearchMiddlewares: SearchMiddleware<ConnectSearch>[] = [\n retainSearchParams<ConnectSearch>([...GLOBAL_SEARCH_PARAMS]),\n retainFeatureFlags,\n];\n\n/** Lets every param through; routes add none of their own. */\nexport function validateConnectSearch(\n search: Record<string, unknown>,\n): ConnectSearch {\n return search as ConnectSearch;\n}\n\n/** Parses a query string into plain string values, unlike the JSON default. */\nexport function parseConnectSearch(searchStr: string): ConnectSearch {\n return Object.fromEntries(new URLSearchParams(searchStr));\n}\n\n/** Writes plain `key=value` pairs, so other readers of the URL see strings. */\nexport function stringifyConnectSearch(search: Record<string, unknown>) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(search)) {\n if (value === undefined || value === null) continue;\n params.set(key, typeof value === \"string\" ? value : JSON.stringify(value));\n }\n const searchStr = searchParamsToString(params);\n return searchStr ? `?${searchStr}` : \"\";\n}\n\n/** The drive route's params: `?history` opens the document's revision history,\n * and `historyPage` (a positive integer; 1 is dropped) pages it. */\nexport function validateDriveSearch(\n search: Record<string, unknown>,\n): ConnectSearch {\n const result = { ...search } as ConnectSearch;\n if (result[REVISION_HISTORY_PARAM] === undefined) return result;\n result[REVISION_HISTORY_PARAM] = \"\";\n const page = parseRevisionHistoryPage(result[REVISION_HISTORY_PAGE_PARAM]);\n if (page > 1) result[REVISION_HISTORY_PAGE_PARAM] = String(page);\n // Undefined, not deleted: a route's search is merged over its parent's.\n else result[REVISION_HISTORY_PAGE_PARAM] = undefined;\n return result;\n}\n\n/** The defined values of `search`, for callers that take plain records. */\nexport function definedSearch(search: object): Record<string, string> {\n const record: Record<string, string> = {};\n for (const [key, value] of Object.entries(search)) {\n if (typeof value === \"string\") record[key] = value;\n else if (value !== undefined && value !== null) {\n record[key] = JSON.stringify(value);\n }\n }\n return record;\n}\n","import type {\n PHDriveTarget,\n PHNavigation,\n PHNavigationTarget,\n PHSettingsTarget,\n SetSearchParams,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n applySearchUpdate,\n findDriveBySlugOrId,\n isSettingsTarget,\n makeDriveSlug,\n OPENED_FROM_STATE_KEY,\n openedFromIndex,\n resolveSearchUpdate,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n AnyRouter,\n HistoryState,\n MakeRouteMatchUnion,\n} from \"@tanstack/react-router\";\nimport { useRouterState } from \"@tanstack/react-router\";\nimport { useMemo } from \"react\";\nimport type { ConnectRouterBundle } from \"./connect-router.js\";\nimport { markNavigationClick } from \"./perf-marks.js\";\nimport { definedSearch } from \"./search.js\";\nimport { keepOpenedFrom, settingsTabs } from \"./settings.js\";\n\n// Hover intent: a pointer passing over cards doesn't preload each of them.\nconst PRELOAD_DELAY_MS = 50;\n\n/** The PH navigation backed by `router`; its hooks take the router directly,\n * so they work outside the RouterProvider. */\nexport function createConnectNavigation(\n connectRouter: ConnectRouterBundle,\n): PHNavigation & { dispose(): void } {\n const { router, homeRoute, nodeRoute, settingsRoute } = connectRouter;\n // Settings tabs can come from a project's routes, unknown to Connect's types.\n const anyRouter = router as unknown as AnyRouter;\n\n // A listed drive is addressed by its canonical slug, whatever form came in.\n const driveParams = (target: PHDriveTarget) => {\n const drive = findDriveBySlugOrId(\n router.options.context.store,\n target.driveSlug,\n );\n return {\n driveSlug: drive ? makeDriveSlug(drive) : target.driveSlug,\n nodeSlug: target.nodeSlug || undefined,\n };\n };\n\n // `true` is the first tab, so the URL names a tab without a redirect.\n const settingsPath = ({ settings }: PHSettingsTarget) => {\n const tab =\n settings === true ? settingsTabs(anyRouter).at(0)?.id : settings;\n return tab ? `${settingsRoute.fullPath}/${tab}` : settingsRoute.fullPath;\n };\n\n // In-document writes keep the entry's state, so its opened-from index too.\n const setSearch: PHNavigation[\"setSearch\"] = (update, options) => {\n void router.navigate({\n to: \".\",\n search: (prev) => applySearchUpdate({}, update(definedSearch(prev))),\n state: true,\n replace: options?.replace,\n resetScroll: false,\n });\n };\n\n const showsSettings = () =>\n router.state.matches.some((match) => match.routeId === settingsRoute.id);\n\n // A push remembers the entry it leaves; a replace keeps what that one had,\n // as does a move between settings tabs.\n const openedFromState = (\n replace: boolean | undefined,\n target: PHNavigationTarget | undefined,\n ) => {\n const { state } = router.history.location;\n const next =\n replace || (isSettingsTarget(target) && showsSettings())\n ? keepOpenedFrom(state)\n : ({\n [OPENED_FROM_STATE_KEY]: state.__TSR_index,\n } as unknown as HistoryState);\n return () => next;\n };\n\n const targetKey = (target: PHNavigationTarget | undefined) => {\n if (!target) return homeRoute.id;\n if (isSettingsTarget(target)) return settingsPath(target);\n const { driveSlug, nodeSlug } = driveParams(target);\n return JSON.stringify([driveSlug, nodeSlug ?? \"\"]);\n };\n let keyedMatches: readonly MakeRouteMatchUnion[] | undefined;\n let matchesKey: string | undefined;\n const currentKey = (matches: readonly MakeRouteMatchUnion[]) => {\n if (matches === keyedMatches) return matchesKey;\n keyedMatches = matches;\n const drive = matches.find((match) => match.routeId === nodeRoute.id);\n const settings = matches.some(\n (match) => match.routeId === settingsRoute.id,\n );\n if (drive) {\n matchesKey = targetKey(drive.params as PHDriveTarget);\n } else if (settings) {\n // A tab's key is its path, as settingsPath builds it.\n matchesKey = matches.at(-1)?.fullPath.replace(/\\/$/, \"\");\n } else {\n matchesKey = matches.find(\n (match) => match.routeId === homeRoute.id,\n )?.routeId;\n }\n return matchesKey;\n };\n\n // Hrefs depend only on the target and the global params of the current search.\n const hrefs = new Map<string, string>();\n let hrefsSearch: string | undefined;\n\n const setSearchParams: SetSearchParams = (update, options) =>\n setSearch((prev) => resolveSearchUpdate(prev, update), options);\n\n let preloadTimer: ReturnType<typeof setTimeout> | undefined;\n return {\n location: () => router.history.location,\n // The root route's middlewares add the global params to `search`.\n open: (target, options) => {\n markNavigationClick();\n const search = applySearchUpdate({}, options?.search ?? {});\n const replace = options?.replace;\n const state = openedFromState(replace, target);\n if (!target) {\n void router.navigate({\n to: homeRoute.fullPath,\n search,\n replace,\n state,\n });\n return;\n }\n if (isSettingsTarget(target)) {\n void anyRouter.navigate({\n to: settingsPath(target),\n search,\n replace,\n state,\n });\n return;\n }\n void router.navigate({\n to: nodeRoute.fullPath,\n params: driveParams(target),\n search,\n replace,\n state,\n });\n },\n // The public href, base path included; global params as `open` keeps them.\n hrefFor: (target) => {\n const { searchStr } = router.latestLocation;\n if (searchStr !== hrefsSearch) {\n hrefs.clear();\n hrefsSearch = searchStr;\n }\n const key = targetKey(target);\n let href = hrefs.get(key);\n if (href === undefined) {\n const location = !target\n ? router.buildLocation({ to: homeRoute.fullPath, search: {} })\n : isSettingsTarget(target)\n ? anyRouter.buildLocation({ to: settingsPath(target), search: {} })\n : router.buildLocation({\n to: nodeRoute.fullPath,\n params: driveParams(target),\n search: {},\n });\n href = location.publicHref;\n hrefs.set(key, href);\n }\n return href;\n },\n // One key per shown matches, so each link's selector is a string compare.\n useIsCurrent: (target) => {\n // The settings page itself is current on any of its tabs.\n const anyTab = isSettingsTarget(target) && target.settings === true;\n const key = anyTab ? `${settingsRoute.fullPath}/` : targetKey(target);\n return useRouterState({\n router,\n select: (state) => {\n const current = currentKey(state.matches);\n return anyTab ? !!current?.startsWith(key) : current === key;\n },\n });\n },\n preload: (target) => {\n clearTimeout(preloadTimer);\n if (!target) return;\n preloadTimer = setTimeout(() => {\n const preloading = isSettingsTarget(target)\n ? anyRouter.preloadRoute({ to: settingsPath(target) })\n : router.preloadRoute({\n to: nodeRoute.fullPath,\n params: driveParams(target),\n });\n preloading.catch(() => undefined);\n }, PRELOAD_DELAY_MS);\n },\n setSearch,\n // The presented matches' params, else the location's.\n useSearchParams() {\n const search = useRouterState({\n router,\n select: (state) =>\n state.matches.at(-1)?.search ?? state.location.search,\n });\n return useMemo(() => definedSearch(search), [search]);\n },\n useSetSearchParams: () => setSearchParams,\n closeOpened: () => {\n const { state } = router.history.location;\n const from = openedFromIndex(state, state.__TSR_index);\n if (from === undefined) return false;\n router.history.go(from - state.__TSR_index);\n return true;\n },\n dispose: () => clearTimeout(preloadTimer),\n };\n}\n","import type { DriveArrivals, PHStore } from \"@powerhousedao/reactor-browser\";\nimport {\n getPHStoreSubscribe,\n isRoutedModal,\n modalFromSearch,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n AnyRoute,\n ErrorRouteComponent,\n NotFoundRouteComponent,\n RouteComponent,\n Router,\n RouterHistory,\n} from \"@tanstack/react-router\";\nimport { createRouter } from \"@tanstack/react-router\";\nimport type { ErrorInfo, PropsWithChildren, ReactElement } from \"react\";\nimport type { ConnectPluginUiSet } from \"../plugins/plugin-ui.js\";\nimport { applyConnectPluginUi } from \"../plugins/plugin-ui.js\";\nimport { markRouterNavigations } from \"./perf-marks.js\";\nimport { bindConnectScroll, connectScrollRestoration } from \"./scroll.js\";\nimport type { DriveRouteData } from \"./drive-route-loader.js\";\nimport type { ConnectRootRoute, ConnectRoutes } from \"./route-tree.js\";\nimport { createConnectNavigation } from \"./navigation.js\";\nimport { CoreError, CoreNotFound } from \"./core-views.js\";\nimport { CONTENT_VIEW_ID } from \"./route-components.js\";\nimport { addConnectRoutes, connectRoutes } from \"./route-tree.js\";\nimport { setSettingsRoute } from \"./settings.js\";\nimport { parseConnectSearch, stringifyConnectSearch } from \"./search.js\";\nimport { driveTitle } from \"./titles.js\";\n\nexport type ConnectRouterOptions = {\n store: PHStore;\n arrivals?: DriveArrivals;\n basepath?: string;\n history?: RouterHistory;\n InnerWrap?: (props: PropsWithChildren) => ReactElement;\n /** Shown while a route's loader or chunks are pending, after the router's `pendingMs`. */\n pendingComponent?: RouteComponent;\n /** Any route's loader or render error; the plugins', else core's error view. */\n errorComponent?: ErrorRouteComponent;\n /** The active plugins' UI, set on the routes that show core's views. */\n pluginUi?: ConnectPluginUiSet;\n /** Loaders' notFound(), e.g. a missing drive's; core's page by default. */\n notFoundComponent?: NotFoundRouteComponent;\n /** The tree to route with: `@powerhousedao/connect/route-tree`, core's or a project's. */\n routeTree: AnyRoute;\n /** Code routes added to the file routes; see `addConnectRoutes`. A function\n * receives the tree's core routes to attach to. */\n routes?:\n | readonly AnyRoute[]\n | ((routes: ConnectRoutes) => readonly AnyRoute[]);\n /** Reports a route's loader or render error; logged by default. */\n onCatch?: (error: unknown, info?: ErrorInfo) => void;\n /** Ends every document title; \"Connect\" without one. */\n appName?: string;\n /** Renders the loading shell: layouts show their pendingComponent, not their page. */\n shell?: boolean;\n};\n\nfunction reportRouteError(error: unknown, info?: ErrorInfo) {\n console.error(error, info?.componentStack ?? \"\");\n}\n\n/** The router over `TRouteTree`; a project's generated tree registers its own. */\nexport type ConnectRouterFor<TRouteTree extends AnyRoute> = Router<\n TRouteTree,\n \"never\",\n false,\n RouterHistory,\n Record<string, any>\n>;\n// Written out, not inferred; see ConnectRootRoute.\nexport type ConnectRouter = ConnectRouterFor<ConnectRootRoute>;\nexport type ConnectRouterBundle = Pick<\n ConnectRoutes,\n \"homeRoute\" | \"driveRoute\" | \"nodeRoute\" | \"settingsRoute\"\n> & { router: ConnectRouter };\n\nexport function createConnectRouter(\n options: ConnectRouterOptions,\n): ConnectRouterBundle {\n const { routeTree, homeRoute, driveRoute, nodeRoute, settingsRoute } =\n connectRoutes(options.routeTree);\n if (options.pluginUi) applyConnectPluginUi(routeTree, options.pluginUi);\n if (options.routes) {\n addConnectRoutes(\n typeof options.routes === \"function\"\n ? options.routes(connectRoutes(routeTree))\n : options.routes,\n );\n }\n setSettingsRoute(settingsRoute);\n const router = createRouter({\n routeTree,\n basepath: options.basepath,\n history: options.history,\n context: {\n store: options.store,\n arrivals: options.arrivals,\n appName: options.appName,\n shell: options.shell,\n },\n parseSearch: parseConnectSearch,\n stringifySearch: stringifyConnectSearch,\n scrollRestoration: connectScrollRestoration(),\n scrollToTopSelectors: [`#${CONTENT_VIEW_ID}`],\n InnerWrap: options.InnerWrap,\n defaultPendingComponent: options.pendingComponent,\n defaultErrorComponent:\n options.errorComponent ?? options.pluginUi?.errorComponent ?? CoreError,\n // Not per route: a route's notFoundComponent mounts a boundary that\n // re-renders on every navigation.\n defaultNotFoundComponent: options.notFoundComponent ?? CoreNotFound,\n defaultOnCatch: options.onCatch ?? reportRouteError,\n });\n return { router, homeRoute, driveRoute, nodeRoute, settingsRoute };\n}\n\nfunction writeSelection(store: PHStore, data: DriveRouteData | undefined) {\n // Drive first: a new drive resets the node.\n store.selectedDriveId = data?.driveId;\n store.selectedNodeId = data?.nodeId;\n}\n\n/** Makes `router` the store's navigation and writes the selection it commits. */\nexport function bindConnectRouter(\n connectRouter: ConnectRouterBundle,\n store: PHStore,\n) {\n const { router, nodeRoute } = connectRouter;\n\n // Only committed matches select; pending ones keep the open view.\n const commitSelection = () => {\n const matches = router.state.matches;\n const drive = matches.find((match) => match.routeId === nodeRoute.id);\n if (drive) {\n if (drive.status === \"success\" && drive.loaderData) {\n writeSelection(store, drive.loaderData);\n } else if (matches.some((match) => match.status === \"notFound\")) {\n // The drive's 404 page shows no drive.\n writeSelection(store, undefined);\n }\n return;\n }\n // Any other page (home, settings, a project's, a 404) shows no drive.\n const shown = matches.at(-1)?.status;\n if (shown === \"success\" || shown === \"notFound\") {\n writeSelection(store, undefined);\n }\n };\n\n // A routed modal is the URL's: the store holds what the location names,\n // unless a confirmation is open over it.\n const syncModal = () => {\n const routed = modalFromSearch(router.state.location.search);\n if (store.modal && !isRoutedModal(store.modal)) return;\n if (routed) {\n if (JSON.stringify(store.modal) !== JSON.stringify(routed)) {\n store.modal = routed;\n }\n } else if (isRoutedModal(store.modal)) {\n store.modal = undefined;\n }\n };\n\n // Set once, before the first render; selection setters navigate from the start.\n const navigation = createConnectNavigation(connectRouter);\n store.navigation = navigation;\n\n // The node route's head reads names from the store; a rename re-runs it.\n const shownTitle = () => {\n const node = router.state.matches.find((m) => m.routeId === nodeRoute.id);\n return driveTitle(store, node?.loaderData, router.options.context.appName);\n };\n let title = shownTitle();\n const retitle = () => {\n const next = shownTitle();\n if (next === title) return;\n title = next;\n void router.invalidate({ filter: (m) => m.routeId === nodeRoute.id });\n };\n\n // Before mount, so the view and scroll restoration see the new selection.\n const unsubscribes = [\n router.subscribe(\"onBeforeRouteMount\", commitSelection),\n router.subscribe(\"onResolved\", commitSelection),\n router.subscribe(\"onResolved\", () => {\n title = shownTitle();\n }),\n router.subscribe(\"onResolved\", syncModal),\n getPHStoreSubscribe(store, \"drives\")(retitle),\n getPHStoreSubscribe(store, \"driveNodes\")(retitle),\n markRouterNavigations(router),\n ];\n const unbindScroll = bindConnectScroll(router, CONTENT_VIEW_ID);\n commitSelection();\n syncModal();\n\n return () => {\n navigation.dispose();\n unbindScroll();\n for (const unsubscribe of unsubscribes) unsubscribe();\n if (store.navigation === navigation) store.navigation = undefined;\n };\n}\n","import type { PHStore } from \"@powerhousedao/reactor-browser\";\nimport { createDriveArrivals } from \"@powerhousedao/reactor-browser\";\nimport { getConnectPluginUi } from \"../plugins/plugin-ui.js\";\nimport { getConnectRegistry } from \"../registry.js\";\nimport type {\n ConnectRouterBundle,\n ConnectRouterOptions,\n} from \"./connect-router.js\";\nimport { bindConnectRouter, createConnectRouter } from \"./connect-router.js\";\nimport { resolveConnectRoutes } from \"./route-tree.js\";\n\nexport type ConnectAppRouterOptions = Omit<\n ConnectRouterOptions,\n \"store\" | \"arrivals\"\n>;\n\n/** The app's one router over `store`; created, and made the store's navigation,\n * on first use. Registered routes join `options.routes`. */\nexport function getConnectAppRouter(\n store: PHStore,\n options: () => ConnectAppRouterOptions,\n): ConnectRouterBundle {\n const registry = getConnectRegistry();\n const current = registry.app;\n if (current) {\n if (import.meta.env?.DEV && current.store !== store) {\n throw new Error(\"Connect's router is already bound to another PH store\");\n }\n return current.bundle;\n }\n const { routes, ...rest } = options();\n const bundle = createConnectRouter({\n store,\n arrivals: createDriveArrivals(store),\n pluginUi: getConnectPluginUi(),\n ...rest,\n routes: (tree) => [\n ...(routes ? resolveConnectRoutes(routes, tree.routeTree) : []),\n ...registry.routes.flatMap((entry) => {\n entry.added = [\n ...resolveConnectRoutes(entry.registration, tree.routeTree),\n ];\n return entry.added;\n }),\n ],\n });\n registry.app = { store, bundle, unbind: bindConnectRouter(bundle, store) };\n return bundle;\n}\n\n/** Stops the app's router writing the selection, e.g. on HMR. */\nexport function disposeConnectAppRouter() {\n const registry = getConnectRegistry();\n registry.app?.unbind();\n registry.app = undefined;\n}\n","import type { PHStore } from \"@powerhousedao/reactor-browser\";\nimport { PHStoreProvider } from \"@powerhousedao/reactor-browser\";\nimport type { AnyRoute } from \"@tanstack/react-router\";\nimport { RouterProvider } from \"@tanstack/react-router\";\nimport type { ConnectAppRouterOptions } from \"./app-router.js\";\nimport { getConnectAppRouter } from \"./app-router.js\";\n\n/** A core-only app: `routeTree`'s views over `store`. */\nexport function ConnectCoreApp(props: {\n store: PHStore;\n routeTree: AnyRoute;\n basepath?: string;\n options?: () => Omit<ConnectAppRouterOptions, \"routeTree\">;\n}) {\n const { router } = getConnectAppRouter(props.store, () => ({\n basepath: props.basepath,\n ...props.options?.(),\n routeTree: props.routeTree,\n }));\n return (\n <PHStoreProvider store={props.store}>\n <RouterProvider router={router} />\n </PHStoreProvider>\n );\n}\n"],"mappings":";;;;;;;;;;AAGA,MAAa,mBAAmB;;AAGhC,MAAa,kBAAkB;;CAE7B,OAAO;;CAEP,QAAQ;;CAER,QAAQ;;CAER,OAAO;AACT;AAGA,MAAM,SAAS,EACb,UAAU;CAAE,UAAU;CAAe,OAAO;CAAU,YAAY;AAAU,EAC9E;AAEA,IAAI,UAAU;AACd,IAAI;;AAGJ,SAAgB,kBAAkB,MAAM,CAAC,CAAC,YAAY,KAAK,KAAK;CAC9D,IAAI,KAAK,OAAO;CAChB,IAAI;EACF,OACE,IAAI,gBAAgB,SAAS,MAAM,CAAC,CAAC,IAAI,MAAM,MAAM,O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