@pi-chamber/web 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +22 -6
  2. package/bin/cli.js +11 -1
  3. package/bin/cli.test.js +18 -0
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +7 -3
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +6 -0
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-logs.js +22 -4
  12. package/bin/lib/commands-serve.js +10 -2
  13. package/bin/lib/commands-tunnel.js +14 -0
  14. package/bin/lib/commands-update.js +18 -14
  15. package/bin/lib/commands-update.test.js +2 -1
  16. package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DoEOH0hY.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-y9Ystuhv.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-ScM4XoqZ.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CjkhMFqJ.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Bqi6H8I-.js} +3 -3
  21. package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-ClnfJJ2J.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
  27. package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Cy9tmnMg.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-DJNcTQNp.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-DxgVLhi9.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-CIFSGjJs.js} +1 -1
  36. package/dist/assets/{index-yWgKW2Fx.js → index-D2C3q2xD.js} +4 -4
  37. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  38. package/dist/assets/{index-D1IaU-Q7.js → index-DmNPBaSo.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-CrvpUauF.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CKvhS32g.js} +1 -1
  41. package/dist/assets/{main-DhvLreEl.js → main-BFv8slLp.js} +2 -2
  42. package/dist/assets/{main-DcAMXRSi.js → main-CjM7g4Gq.js} +7 -7
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-DKrraAqT.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-hQnLS5mt.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-DuXOBGs_.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DofX2wjB.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-BZeYg6eN.js} +3 -3
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-C7CBxDbh.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-BEoW7LlC.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-Dy-Tz_LJ.js} +2 -2
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +3 -3
  60. package/server/index.js +26 -7
  61. package/server/lib/client-auth/pairing.js +13 -2
  62. package/server/lib/client-auth/remote-clients.js +13 -2
  63. package/server/lib/fs/DOCUMENTATION.md +3 -1
  64. package/server/lib/fs/routes.test.js +74 -0
  65. package/server/lib/git/DOCUMENTATION.md +1 -1
  66. package/server/lib/git/identity-storage.js +10 -1
  67. package/server/lib/package-manager.js +1 -1
  68. package/server/lib/package-manager.test.js +11 -0
  69. package/server/lib/pi/archive-store.js +3 -2
  70. package/server/lib/pi/model-config-store.js +6 -2
  71. package/server/lib/pi/routes.js +11 -2
  72. package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
  73. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  74. package/server/lib/pi/session-daemon/session-daemon.js +226 -40
  75. package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
  76. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  77. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  78. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  79. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  80. package/server/lib/pi/session-folders-store.js +20 -2
  81. package/server/lib/pi/session-folders-store.test.js +17 -0
  82. package/server/lib/pi/settings-store.js +3 -2
  83. package/server/lib/pi/snippets-store.js +4 -1
  84. package/server/lib/pi/ui-settings-store.js +3 -2
  85. package/server/lib/server/cross-process-lock.js +112 -0
  86. package/server/lib/server/cross-process-lock.test.js +70 -0
  87. package/server/lib/server/server-profile.js +110 -0
  88. package/server/lib/server/server-profile.test.js +58 -0
  89. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  90. package/server/lib/server/tunnel-service.js +8 -1
  91. package/server/lib/stt/config-store.js +3 -2
  92. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  93. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  94. package/server/lib/ui-auth/ui-auth.js +9 -2
  95. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  96. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  97. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  98. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  99. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  100. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  101. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
@@ -0,0 +1,110 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+
3
+ const PROFILE_KEY_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
4
+ const MAX_EXPLICIT_LENGTH = 128;
5
+
6
+ export const isValidProfileKey = (value) => typeof value === 'string' && PROFILE_KEY_PATTERN.test(value);
7
+
8
+ const hashSeed = (seed) => createHash('sha256').update(seed).digest('hex').slice(0, 16);
9
+
10
+ const sanitizePortSegment = (port) => {
11
+ if (port === 0) return 'pauto';
12
+ if (Number.isInteger(port) && port > 0 && port <= 65535) return `p${port}`;
13
+ return '';
14
+ };
15
+
16
+ const resolveRuntime = ({ env = {}, runtime } = {}) => {
17
+ const fromEnv = typeof env.PICHAMBER_RUNTIME === 'string' ? env.PICHAMBER_RUNTIME.trim() : '';
18
+ if (fromEnv === 'desktop' || fromEnv === 'web') return fromEnv;
19
+ if (runtime === 'desktop' || runtime === 'web') return runtime;
20
+ return 'web';
21
+ };
22
+
23
+ const isDesktopDev = ({ env = {} } = {}) => {
24
+ const flag = typeof env.PICHAMBER_ELECTRON_DEV === 'string' ? env.PICHAMBER_ELECTRON_DEV.trim().toLowerCase() : '';
25
+ return flag === '1' || flag === 'true';
26
+ };
27
+
28
+ const isWebDev = ({ env = {} } = {}) => {
29
+ const kind = typeof env.PICHAMBER_SERVER_PROFILE_KIND === 'string' ? env.PICHAMBER_SERVER_PROFILE_KIND.trim().toLowerCase() : '';
30
+ if (kind === 'dev') return true;
31
+ const legacy = typeof env.PICHAMBER_DEV_SERVER === 'string' ? env.PICHAMBER_DEV_SERVER.trim().toLowerCase() : '';
32
+ return legacy === '1' || legacy === 'true';
33
+ };
34
+
35
+ /**
36
+ * Resolve the stable daemon profile for one PiChamber server.
37
+ *
38
+ * The profile key is stable across restarts of the same logical server and
39
+ * distinct across development, installed, desktop, and port-separated web
40
+ * servers. The server instance id is unique per launch and is used to prove
41
+ * which server currently owns a profile daemon.
42
+ */
43
+ export const resolveServerProfile = ({
44
+ env = process.env,
45
+ port,
46
+ runtime,
47
+ version,
48
+ serverInstanceId,
49
+ } = {}) => {
50
+ const safeEnv = env && typeof env === 'object' ? env : {};
51
+ const explicit = typeof safeEnv.PICHAMBER_SERVER_PROFILE === 'string'
52
+ ? safeEnv.PICHAMBER_SERVER_PROFILE.trim()
53
+ : '';
54
+ const effectiveRuntime = resolveRuntime({ env: safeEnv, runtime });
55
+ const development = effectiveRuntime === 'desktop'
56
+ ? isDesktopDev({ env: safeEnv })
57
+ : isWebDev({ env: safeEnv });
58
+ const instanceId = typeof serverInstanceId === 'string' && serverInstanceId.length > 0
59
+ ? serverInstanceId
60
+ : randomUUID();
61
+ const buildId = typeof version === 'string' && version.trim().length > 0 ? version.trim() : 'unknown';
62
+
63
+ if (explicit.length > 0) {
64
+ if (explicit.length > MAX_EXPLICIT_LENGTH) {
65
+ throw new Error('PICHAMBER_SERVER_PROFILE is too long.');
66
+ }
67
+ return {
68
+ profileKey: `custom-${hashSeed(`explicit:${explicit}`)}`,
69
+ profileLabel: explicit.slice(0, MAX_EXPLICIT_LENGTH),
70
+ serverInstanceId: instanceId,
71
+ runtime: effectiveRuntime,
72
+ source: 'custom',
73
+ development,
74
+ port: Number.isInteger(port) ? port : null,
75
+ buildId,
76
+ };
77
+ }
78
+
79
+ if (effectiveRuntime === 'desktop') {
80
+ const dev = development;
81
+ return {
82
+ profileKey: dev ? 'desktop-dev' : 'desktop',
83
+ profileLabel: dev ? 'desktop development' : 'desktop',
84
+ serverInstanceId: instanceId,
85
+ runtime: 'desktop',
86
+ source: dev ? 'desktop-dev' : 'desktop-installed',
87
+ development: dev,
88
+ port: Number.isInteger(port) ? port : null,
89
+ buildId,
90
+ };
91
+ }
92
+
93
+ const dev = development;
94
+ const portSegment = sanitizePortSegment(port);
95
+ const base = dev ? 'web-dev' : 'web';
96
+ const profileKey = portSegment ? `${base}-${portSegment}` : base;
97
+ const numericPort = Number.isInteger(port) ? port : null;
98
+ return {
99
+ profileKey,
100
+ profileLabel: numericPort === null
101
+ ? `${dev ? 'web development' : 'web'} server`
102
+ : `${dev ? 'web development' : 'web'} server on port ${numericPort}`,
103
+ serverInstanceId: instanceId,
104
+ runtime: 'web',
105
+ source: dev ? 'web-dev' : 'web-installed',
106
+ development: dev,
107
+ port: numericPort,
108
+ buildId,
109
+ };
110
+ };
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { isValidProfileKey, resolveServerProfile } from './server-profile.js';
4
+
5
+ describe('server profile', () => {
6
+ it('separates installed and development web servers on the same port', () => {
7
+ const installed = resolveServerProfile({ env: {}, port: 3000, runtime: 'web', version: '0.9.0' });
8
+ const dev = resolveServerProfile({
9
+ env: { PICHAMBER_SERVER_PROFILE_KIND: 'dev' },
10
+ port: 3000,
11
+ runtime: 'web',
12
+ version: '0.9.0',
13
+ });
14
+ expect(installed.profileKey).toBe('web-p3000');
15
+ expect(dev.profileKey).toBe('web-dev-p3000');
16
+ expect(installed.profileKey).not.toBe(dev.profileKey);
17
+ expect(installed.serverInstanceId).not.toBe(dev.serverInstanceId);
18
+ });
19
+
20
+ it('separates web servers on different ports', () => {
21
+ const a = resolveServerProfile({ env: {}, port: 3000 });
22
+ const b = resolveServerProfile({ env: {}, port: 3902 });
23
+ expect(a.profileKey).not.toBe(b.profileKey);
24
+ });
25
+
26
+ it('uses stable desktop profiles without ports', () => {
27
+ const installed = resolveServerProfile({ env: { PICHAMBER_RUNTIME: 'desktop' } });
28
+ const dev = resolveServerProfile({ env: { PICHAMBER_RUNTIME: 'desktop', PICHAMBER_ELECTRON_DEV: '1' } });
29
+ expect(installed.profileKey).toBe('desktop');
30
+ expect(dev.profileKey).toBe('desktop-dev');
31
+ });
32
+
33
+ it('hashes explicit profile overrides instead of using them as paths', () => {
34
+ const profile = resolveServerProfile({ env: { PICHAMBER_SERVER_PROFILE: '../../evil' }, port: 3000 });
35
+ expect(isValidProfileKey(profile.profileKey)).toBe(true);
36
+ expect(profile.profileKey).toMatch(/^custom-[0-9a-f]{16}$/);
37
+ expect(profile.profileKey).not.toContain('.');
38
+ });
39
+
40
+ it('preserves development replacement behavior for explicit profiles', () => {
41
+ const profile = resolveServerProfile({
42
+ env: {
43
+ PICHAMBER_SERVER_PROFILE: 'isolated-dev',
44
+ PICHAMBER_SERVER_PROFILE_KIND: 'dev',
45
+ },
46
+ port: 3000,
47
+ });
48
+ expect(profile.source).toBe('custom');
49
+ expect(profile.development).toBe(true);
50
+ });
51
+
52
+ it('keeps the profile key stable for one logical server across launches', () => {
53
+ const first = resolveServerProfile({ env: {}, port: 3000 });
54
+ const second = resolveServerProfile({ env: {}, port: 3000 });
55
+ expect(first.profileKey).toBe(second.profileKey);
56
+ expect(first.serverInstanceId).not.toBe(second.serverInstanceId);
57
+ });
58
+ });
@@ -1,6 +1,6 @@
1
1
  # Cloudflare Tunnel Service
2
2
 
3
- PiChamber exposes a PiChamber-hosted Cloudflare Tunnel that lets a browser or mobile client reach a private PiChamber server without opening inbound ports. The server dials outbound to Cloudflare with `cloudflared`; the public hostname then proxies to the local PiChamber HTTP endpoint.
3
+ PiChamber can manage a Cloudflare Tunnel that lets a browser or mobile client reach a private PiChamber server without opening inbound ports. The server dials outbound to Cloudflare with `cloudflared`; the public hostname then proxies to the local PiChamber HTTP endpoint.
4
4
 
5
5
  ## Modes
6
6
 
@@ -64,11 +64,10 @@ The PiChamber `pichamber.service` itself already supports both user (`~/.config/
64
64
  - `tunnel-service.test.js` covers validation (missing token/hostname, unsupported mode), status shape, secret redaction, and that `missing_dependency` is reported when `cloudflared` is absent.
65
65
  - Integration smoke against a real `cloudflared` binary is manual: install `cloudflared`, run `pichamber serve`, `curl /api/pichamber/tunnel/check`, start a quick tunnel, verify `status.url` appears and `curl -H "Host: $url-host"` reaches the server through the tunnel with `Authorization` still required.
66
66
 
67
- ## Cloudflare permissions for API-token flow
67
+ ## Cloudflare credentials
68
68
 
69
- If the operator wants PiChamber to create a tunnel automatically (rather than pasting a token), the Cloudflare API token needs:
70
-
71
- - `Zone:Read`, `DNS:Edit` on the zone that will host the hostname
72
- - `Account:Cloudflare Tunnel:Edit` (to create/list tunnels)
73
-
74
- PiChamber never asks for the Cloudflare account password. The manual token flow is the default; the API-token flow is an optional convenience that calls `https://api.cloudflare.com/client/v4/accounts/{accountId}/cfd_tunnel` with the scoped token. Secrets are still stored with `0600` and never returned in API responses.
69
+ PiChamber uses a manual Cloudflare tunnel token for `managed-remote` mode and
70
+ an existing `cloudflared` config for `managed-local` mode. It does not ask for a
71
+ Cloudflare account password and does not create tunnels through a Cloudflare
72
+ API-token wizard. Secrets are stored with `0600` and never returned in API
73
+ responses.
@@ -52,7 +52,14 @@ export const createTunnelService = ({
52
52
  const writeTokenStore = (token, hostname) => {
53
53
  try {
54
54
  fs.mkdirSync(path.dirname(tokenPath), { recursive: true, mode: 0o700 });
55
- fs.writeFileSync(tokenPath, JSON.stringify({ token, hostname }), { mode: 0o600 });
55
+ // Atomic replace so a concurrent server never reads a torn token.
56
+ const temporary = `${tokenPath}.tmp-${process.pid}-${Date.now()}`;
57
+ try {
58
+ fs.writeFileSync(temporary, JSON.stringify({ token, hostname }), { mode: 0o600 });
59
+ fs.renameSync(temporary, tokenPath);
60
+ } catch {
61
+ try { fs.rmSync(temporary, { force: true }); } catch {}
62
+ }
56
63
  } catch {}
57
64
  };
58
65
 
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
 
5
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
5
6
  import { DEFAULT_LOCAL_STT_MODEL, isLocalSttModelId } from './local/model-catalog.js';
6
7
 
7
8
  const DEFAULT_CONFIG = Object.freeze({ enabled: false, providerConfigId: 'local', language: '', localModelId: DEFAULT_LOCAL_STT_MODEL, providers: [] });
@@ -51,7 +52,7 @@ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rena
51
52
  catch (error) { if (error?.code === 'ENOENT') return { ...DEFAULT_CONFIG, providers: [] }; throw new Error('STT configuration is invalid'); }
52
53
  };
53
54
  const write = async (changes) => {
54
- const operation = mutation.then(async () => {
55
+ const operation = mutation.then(() => withCrossProcessLock(`${file}.lock`, async () => {
55
56
  const current = await read();
56
57
  let providers = current.providers;
57
58
  if (changes?.remoteProvider) {
@@ -73,7 +74,7 @@ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rena
73
74
  await fs.rm(temporary, { force: true }).catch(() => {});
74
75
  throw error;
75
76
  }
76
- });
77
+ }));
77
78
  mutation = operation.catch(() => {});
78
79
  return operation;
79
80
  };
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Ownership
4
4
 
5
- `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
5
+ `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron, hosted mobile, and Capacitor clients use this same server runtime through the shared authenticated transport.
6
6
 
7
7
  ## Protocol
8
8
 
@@ -1,32 +1,52 @@
1
- # Tunnels Module Documentation
1
+ # Tunnels module documentation
2
2
 
3
3
  ## Purpose
4
+
4
5
  This module contains the shared tunnel support surface for PiChamber: provider
5
- capability metadata, tunnel types/normalization helpers, cross-platform
6
+ capability metadata, tunnel types and normalization helpers, cross-platform
6
7
  executable discovery, and dependency install-help metadata.
7
8
 
8
- The tunnel start implementation lives in
9
- `packages/web/server/lib/cloudflare-tunnel.js`; CLI orchestration lives in
10
- `packages/web/bin/lib/commands-tunnel.js`.
9
+ The Cloudflare provider implementation lives in
10
+ `packages/web/server/lib/cloudflare-tunnel.js`. The server-owned lifecycle is
11
+ `packages/web/server/lib/server/tunnel-service.js`, and CLI orchestration lives
12
+ in `packages/web/bin/lib/commands-tunnel.js`.
11
13
 
12
- > Wiring note: the previous service orchestration entrypoint
13
- > (`tunnels/index.js`, `createTunnelService`) was removed as dead code — no
14
- > runtime entrypoint registered tunnel routes or started a tunnel service.
15
- > The remaining files are consumed by the CLI capability surface and by the
16
- > Cloudflare tunnel provider implementation, not by a tunnel orchestration runtime.
14
+ `startWebUiServer` creates the tunnel service and registers its authenticated
15
+ routes. Tunnel startup is intentionally separate from `pichamber serve` startup:
16
+ use `pichamber tunnel start` after the server is running.
17
17
 
18
18
  ## Entrypoints and structure
19
- - `packages/web/server/lib/tunnels/executable-search.js`: cross-platform executable discovery, including Windows Store app aliases. Consumed by the tunnel providers and `packages/web/server/lib/workspace/host.js`.
20
- - `packages/web/server/lib/tunnels/install-help.js`: provider/platform install command metadata (`getTunnelDependencyInstallInfo`) for missing tunnel dependencies.
21
- - `packages/web/server/lib/tunnels/types.js`: shared tunnel provider, mode, and intent constants plus the shared `TunnelServiceError` class.
19
+
20
+ - `executable-search.js` discovers provider executables across platforms,
21
+ including Windows Store app aliases. The workspace host and tunnel providers
22
+ use it.
23
+ - `install-help.js` provides provider and platform install guidance for missing
24
+ dependencies.
25
+ - `types.js` defines provider, mode, intent, and `TunnelServiceError` values.
26
+ - `../cloudflare-tunnel.js` starts Cloudflare Quick, Managed Remote, and Managed
27
+ Local children and reports their public hostname.
28
+ - `../server/tunnel-service.js` owns one active child, token storage, public URL
29
+ state, and tunnel-auth registration.
22
30
 
23
31
  ## Public exports
32
+
24
33
  - `install-help.js` → `getTunnelDependencyInstallInfo(provider, platform)`
25
- - `executable-search.js` → `getExecutableSearchDirectories`, `createExecutableSearchEnv`, `findExecutableOnPath`, `resolveExecutableLaunchTarget`
26
- - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`, `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`, `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`, `TunnelServiceError`
34
+ - `executable-search.js` → `getExecutableSearchDirectories`,
35
+ `createExecutableSearchEnv`, `findExecutableOnPath`,
36
+ `resolveExecutableLaunchTarget`
37
+ - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`,
38
+ `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`,
39
+ `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`,
40
+ `TunnelServiceError`
27
41
 
28
42
  ## Consumers
29
- - `packages/web/bin/lib/cli-tunnel-capabilities.js`: provider capability metadata for CLI tunnel commands (Cloudflare only).
30
- - `packages/web/server/lib/cloudflare-tunnel.js`: executable discovery, install-help metadata, and provider constants.
31
- - `packages/web/server/lib/workspace/host.js`: executable discovery.
32
43
 
44
+ - `packages/web/bin/lib/cli-tunnel-capabilities.js` provides Cloudflare
45
+ capability metadata to the CLI.
46
+ - `packages/web/bin/lib/commands-tunnel.js` validates flags, presents prompts,
47
+ and calls the server lifecycle routes.
48
+ - `packages/web/server/index.js` creates the tunnel service and registers the
49
+ authenticated routes.
50
+ - `packages/ui/src/components/sections/pichamber/tunnel/` renders status,
51
+ setup, profiles, and one-time connect links.
52
+ - `packages/electron/main.mjs` reads tunnel status for native quit-risk UI.
@@ -369,8 +369,15 @@ function getOrCreateJwtSecret() {
369
369
  const secret = crypto.randomBytes(32).toString('hex');
370
370
  try {
371
371
  fs.mkdirSync(PICHAMBER_DATA_DIR, { recursive: true });
372
- fs.writeFileSync(JWT_SECRET_FILE, secret, { mode: 0o600 });
373
- console.log('[JWT] Generated and persisted new secret to', JWT_SECRET_FILE);
372
+ // Exclusive create: a concurrent server creating its first secret at the
373
+ // same instant re-reads the winner instead of overwriting it.
374
+ try {
375
+ fs.writeFileSync(JWT_SECRET_FILE, secret, { mode: 0o600, flag: 'wx' });
376
+ console.log('[JWT] Generated and persisted new secret to', JWT_SECRET_FILE);
377
+ } catch (error) {
378
+ if (error?.code !== 'EEXIST') throw error;
379
+ return new TextEncoder().encode(fs.readFileSync(JWT_SECRET_FILE, 'utf8').trim());
380
+ }
374
381
  } catch (e) {
375
382
  console.warn('[JWT] Failed to persist secret:', e.message);
376
383
  }
@@ -126,7 +126,15 @@ export const createUiPasskeys = ({
126
126
 
127
127
  const persistStore = (store) => {
128
128
  ensureStoreDirectory();
129
- fs.writeFileSync(storeFile, JSON.stringify(store, null, 2));
129
+ // Atomic replace so a concurrent server never reads a torn store.
130
+ const temporary = `${storeFile}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
131
+ try {
132
+ fs.writeFileSync(temporary, JSON.stringify(store, null, 2), { mode: 0o600 });
133
+ fs.renameSync(temporary, storeFile);
134
+ } catch (error) {
135
+ try { fs.rmSync(temporary, { force: true }); } catch {}
136
+ throw error;
137
+ }
130
138
  };
131
139
 
132
140
  const createEmptyStore = () => ({
@@ -1 +0,0 @@
1
- import{y as A,aG as Z,aH as Fe,ab as Ce,aI as ke,aJ as Ie,aK as ze,aL as Ne,ac as Oe,U as ee,I as te,aM as Ve}from"./useAppFontEffects-BgK55NDM.js";import{b as ie,s as Pe,c as Se,d as ne,e as ve,f as Be,h as re,g as I,i as De,j as Ue,k as _e,l as We,R as Ge,I as je,p as se,m as $e,n as Ke,o as qe,q as Je,w as Ye,r as ae,u as Xe,t as Qe,v as Ze,x as et,y as oe,S as tt,z as it,A as nt,B as rt,a as ye,C as he,F as st}from"./web-components-DAkBDXRk.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-BSHVMKgK.js";import{j as C,r as k,R as L}from"./vendor-react-B5Z1Mdn3.js";import{o as ut,g as j,l as M,h as ft,q as de,s as pt,t as ce,j as gt,u as ue,a as mt,w as B,x as fe}from"./computeVirtualFileMetrics-3H6mg13G.js";import{a as F,i as q,l as pe,h as Ct,r as St}from"./isFilePlainText-XdCAgm8R.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:A},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??A)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!q(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=A,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Pe(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!M(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||q(i)||$(s.length,this.getTokenizeMaxLength()),h=!M(i,this.renderCache.file),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!M(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&M(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:A},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??A)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||Mt(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!M(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||q(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:Ke(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=qe();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Je(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Ye(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??A,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Ze(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const At=5e3;let Ht=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++Ht}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!M(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%At===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:u+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,O,V,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(V??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(O==null)if(y)O=0,V=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};V??=O;const W=Math.round(V-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),J=G*a,Y=W<0?v+W*a:v,Me=N[G]??0,Ae=J===0?0:u+Me,X=G+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Ae,bufferAfter:Math.max(0,He)}}};function Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(K({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(K({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=K({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function K({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function Ut({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const _t=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand All"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse All"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Ve,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{Ut as F,_t as J};