@adea-ai/app-framework 0.25.1 → 0.26.0

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 (138) hide show
  1. package/README.md +157 -19
  2. package/dist/app/application.d.ts +11 -4
  3. package/dist/app/application.js +24 -4
  4. package/dist/app/create-application.d.ts +9 -0
  5. package/dist/app/create-application.js +214 -143
  6. package/dist/app/private-group.d.ts +14 -0
  7. package/dist/app/private-group.js +39 -0
  8. package/dist/app/service-registry.d.ts +8 -4
  9. package/dist/app/service-registry.js +43 -6
  10. package/dist/appearance/custom-theme-import.d.ts +5 -7
  11. package/dist/appearance/custom-theme-import.js +66 -18
  12. package/dist/appearance/custom-theme-library.d.ts +51 -3
  13. package/dist/appearance/custom-theme-library.js +262 -33
  14. package/dist/appearance/editor.d.ts +3 -1
  15. package/dist/appearance/editor.js +37 -2
  16. package/dist/appearance/theme-file-importer.d.ts +7 -3
  17. package/dist/appearance/theme-file-importer.js +27 -7
  18. package/dist/appearance/theme-library-action-fence.d.ts +11 -0
  19. package/dist/appearance/theme-library-action-fence.js +29 -0
  20. package/dist/cli/cef-helper-cli.js +0 -0
  21. package/dist/cli/create-application-cli.js +0 -0
  22. package/dist/cli/electrobun-shortcut-patch-cli.js +0 -0
  23. package/dist/cli/framework-update-cli.js +16 -3
  24. package/dist/cli/macos-signing-cli.js +0 -0
  25. package/dist/cli/release-assets-plan-cli.js +0 -0
  26. package/dist/cli/release-cut-cli.js +0 -0
  27. package/dist/cli/release-descriptor-staging-cli.js +0 -0
  28. package/dist/cli/release-finalize-cli.js +0 -0
  29. package/dist/cli/release-promote-cli.js +0 -0
  30. package/dist/cli/release-publish-cli.js +0 -0
  31. package/dist/cli/release-sign-cli.js +0 -0
  32. package/dist/cli/release-step-cli.js +0 -0
  33. package/dist/cli/toolchain-identity-cli.js +0 -0
  34. package/dist/cli/windows-runtime-patch-cli.js +0 -0
  35. package/dist/desktop/application-command-client.d.ts +11 -1
  36. package/dist/desktop/application-command-client.js +66 -3
  37. package/dist/desktop/channel-handshake.d.ts +2 -1
  38. package/dist/desktop/channel-handshake.js +21 -5
  39. package/dist/desktop/client-asset-stream.d.ts +10 -0
  40. package/dist/desktop/client-asset-stream.js +97 -0
  41. package/dist/desktop/client-assets.d.ts +3 -1
  42. package/dist/desktop/client-assets.js +41 -6
  43. package/dist/desktop/desktop-client.d.ts +15 -1
  44. package/dist/desktop/desktop-client.js +235 -109
  45. package/dist/desktop/desktop-gateway.d.ts +2 -0
  46. package/dist/desktop/desktop-gateway.js +134 -22
  47. package/dist/desktop/desktop-host-websocket.d.ts +10 -0
  48. package/dist/desktop/desktop-host-websocket.js +28 -0
  49. package/dist/desktop/desktop-host.d.ts +9 -0
  50. package/dist/desktop/desktop-host.js +70 -61
  51. package/dist/desktop/desktop-port-file.d.ts +2 -0
  52. package/dist/desktop/desktop-port-file.js +23 -0
  53. package/dist/desktop/desktop-stream.d.ts +5 -0
  54. package/dist/desktop/desktop-stream.js +83 -15
  55. package/dist/desktop/gateway-limits.d.ts +2 -0
  56. package/dist/desktop/gateway-limits.js +6 -0
  57. package/dist/desktop/open-url-channel.d.ts +5 -3
  58. package/dist/desktop/open-url-channel.js +18 -5
  59. package/dist/desktop/typed-array-intrinsics.d.ts +6 -0
  60. package/dist/desktop/typed-array-intrinsics.js +19 -0
  61. package/dist/framework-source.json +1 -1
  62. package/dist/installer/installed-payload.js +1 -1
  63. package/dist/installer/installer-ci-bootstrap.js +2 -1
  64. package/dist/installer/installer-command.d.ts +13 -0
  65. package/dist/installer/installer-command.js +47 -0
  66. package/dist/installer/installer-extraction.js +27 -61
  67. package/dist/installer/installer-identity.d.ts +19 -3
  68. package/dist/installer/installer-identity.js +58 -70
  69. package/dist/installer/installer-image-mount.d.ts +48 -0
  70. package/dist/installer/installer-image-mount.js +347 -0
  71. package/dist/installer/installer-layout.js +1 -1
  72. package/dist/installer/installer-process-cleanup.js +1 -1
  73. package/dist/installer/installer-renderer-evidence.js +6 -2
  74. package/dist/installer/upgrade-asset-download.js +30 -8
  75. package/dist/native/app-bundle.d.ts +2 -2
  76. package/dist/native/app-bundle.js +5 -4
  77. package/dist/native/cef-helper-download.d.ts +1 -0
  78. package/dist/native/cef-helper-download.js +35 -0
  79. package/dist/native/cef-helper.js +146 -61
  80. package/dist/native/exclusive-rename.d.ts +2 -0
  81. package/dist/native/exclusive-rename.js +52 -0
  82. package/dist/native/native-secret-store.js +5 -4
  83. package/dist/native/partitioned-window.d.ts +5 -2
  84. package/dist/native/partitioned-window.js +69 -9
  85. package/dist/native/sidecar-services.js +2 -2
  86. package/dist/native/sidecar.js +68 -25
  87. package/dist/native/window-bootstrap.js +2 -2
  88. package/dist/release/feed-state.js +2 -1
  89. package/dist/release/framework-update-lock.d.ts +2 -0
  90. package/dist/release/framework-update-lock.js +42 -0
  91. package/dist/release/framework-update.d.ts +6 -2
  92. package/dist/release/framework-update.js +165 -40
  93. package/dist/release/local-release.js +68 -39
  94. package/dist/release/release-config.js +1 -1
  95. package/dist/shared/discard-stream.d.ts +4 -0
  96. package/dist/shared/discard-stream.js +9 -0
  97. package/dist/shell/app-shell.js +59 -7
  98. package/dist/shell/app-utilities.js +2 -2
  99. package/dist/shell/application-menu.d.ts +13 -0
  100. package/dist/shell/application-menu.js +21 -8
  101. package/dist/update-helper.bundle.js +40 -4
  102. package/dist/updates/channel-update-manager.d.ts +2 -0
  103. package/dist/updates/channel-update-manager.js +15 -3
  104. package/dist/updates/desktop-updater.d.ts +2 -0
  105. package/dist/updates/desktop-updater.js +36 -7
  106. package/dist/updates/linux-process-state.d.ts +2 -0
  107. package/dist/updates/linux-process-state.js +13 -0
  108. package/dist/updates/release-location.js +5 -4
  109. package/dist/updates/update-adapter.js +5 -0
  110. package/dist/updates/update-arm.d.ts +2 -0
  111. package/dist/updates/update-arm.js +58 -7
  112. package/dist/updates/update-discovery.js +2 -1
  113. package/dist/updates/update-download-cleanup.d.ts +7 -0
  114. package/dist/updates/update-download-cleanup.js +21 -0
  115. package/dist/updates/update-download.js +41 -20
  116. package/dist/updates/update-exclusive-rename.d.ts +3 -2
  117. package/dist/updates/update-exclusive-rename.js +3 -50
  118. package/dist/updates/update-extraction.js +1 -1
  119. package/dist/updates/update-manager.d.ts +17 -1
  120. package/dist/updates/update-manager.js +27 -8
  121. package/dist/updates/update-process-fence.js +18 -3
  122. package/dist/views/appearance-surface.js +51 -15
  123. package/package.json +8 -3
  124. package/src/app/application.tsx +49 -7
  125. package/src/appearance/custom-theme-import.ts +67 -7
  126. package/src/appearance/custom-theme-library.ts +391 -33
  127. package/src/appearance/editor.ts +49 -10
  128. package/src/appearance/theme-file-importer.ts +43 -12
  129. package/src/appearance/theme-library-action-fence.ts +28 -0
  130. package/src/desktop/client-asset-stream.ts +118 -0
  131. package/src/desktop/client-assets.ts +55 -5
  132. package/src/shell/app-shell.tsx +71 -8
  133. package/src/shell/app-utilities.tsx +2 -2
  134. package/src/updates/update-adapter.ts +5 -0
  135. package/src/views/appearance-surface.tsx +61 -29
  136. package/templates/application/README.md +5 -1
  137. package/templates/application/scripts/app-version.ts +7 -3
  138. package/templates/application/src/bun/index.ts +2 -0
@@ -3,6 +3,9 @@ var THEME_IMPORT_PENDING = "Importing theme…";
3
3
  var THEME_IMPORT_UNREADABLE = "That file could not be read.";
4
4
  var THEME_IMPORT_UNAVAILABLE = "The theme importer could not be loaded. Reload the app and try again.";
5
5
  var THEME_IMPORT_FAILED = "That theme could not be imported.";
6
+ /** A theme is a small JSON document; bound reads before allocating its text. */
7
+ var MAX_THEME_FILE_BYTES = 1048576;
8
+ var THEME_IMPORT_TOO_LARGE = "That theme file is too large. Choose one 1 MiB or smaller.";
6
9
  function createThemeFileImporter(host) {
7
10
  let latest = 0;
8
11
  let pending = false;
@@ -14,24 +17,38 @@ function createThemeFileImporter(host) {
14
17
  return {
15
18
  cancel() {
16
19
  latest += 1;
20
+ const run = latest;
17
21
  if (!pending) return;
18
22
  settle();
19
- host.onStatus("");
23
+ if (run === latest) host.onStatus("");
20
24
  },
21
25
  async importFile(file) {
22
26
  latest += 1;
23
27
  const run = latest;
24
28
  const current = () => run === latest;
29
+ const size = file.size;
30
+ if (!Number.isSafeInteger(size) || size < 0) {
31
+ settle();
32
+ if (current()) host.onStatus(THEME_IMPORT_UNREADABLE);
33
+ return;
34
+ }
35
+ if (size > 1048576) {
36
+ settle();
37
+ if (current()) host.onStatus(THEME_IMPORT_TOO_LARGE);
38
+ return;
39
+ }
25
40
  pending = true;
26
41
  host.onPending(true);
42
+ if (!current()) return;
27
43
  host.onStatus(THEME_IMPORT_PENDING);
44
+ if (!current()) return;
28
45
  let text;
29
46
  try {
30
47
  text = await file.text();
31
48
  } catch {
32
49
  if (!current()) return;
33
50
  settle();
34
- host.onStatus(THEME_IMPORT_UNREADABLE);
51
+ if (current()) host.onStatus(THEME_IMPORT_UNREADABLE);
35
52
  return;
36
53
  }
37
54
  if (!current()) return;
@@ -41,26 +58,29 @@ function createThemeFileImporter(host) {
41
58
  } catch {
42
59
  if (!current()) return;
43
60
  settle();
44
- host.onStatus(THEME_IMPORT_UNAVAILABLE);
61
+ if (current()) host.onStatus(THEME_IMPORT_UNAVAILABLE);
45
62
  return;
46
63
  }
47
64
  if (!current()) return;
48
65
  let result;
49
66
  try {
50
- result = importText(text);
67
+ result = await importText(text, current);
51
68
  } catch {
69
+ if (!current()) return;
52
70
  settle();
53
- host.onStatus(THEME_IMPORT_FAILED);
71
+ if (current()) host.onStatus(THEME_IMPORT_FAILED);
54
72
  return;
55
73
  }
74
+ if (!current()) return;
56
75
  settle();
76
+ if (!current()) return;
57
77
  if (!result.ok) {
58
78
  host.onStatus(result.error);
59
79
  return;
60
80
  }
61
81
  host.onStatus(`Imported “${result.theme.name}”.` + (result.theme.notes.length > 0 ? ` ${result.theme.notes.join(" ")}` : ""));
62
- host.onImported(result.theme);
82
+ if (current()) host.onImported(result.theme);
63
83
  }
64
84
  };
65
85
  }
66
- export { THEME_IMPORT_FAILED, THEME_IMPORT_PENDING, THEME_IMPORT_UNAVAILABLE, THEME_IMPORT_UNREADABLE, createThemeFileImporter };
86
+ export { MAX_THEME_FILE_BYTES, THEME_IMPORT_FAILED, THEME_IMPORT_PENDING, THEME_IMPORT_TOO_LARGE, THEME_IMPORT_UNAVAILABLE, THEME_IMPORT_UNREADABLE, createThemeFileImporter };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Owns status completions for asynchronous theme-library actions. Starting a newer
3
+ * import/removal invalidates older completions; disposal suppresses all later UI
4
+ * writes while allowing an already-started storage commit to finish.
5
+ */
6
+ export declare function createThemeLibraryActionFence(writeStatus: (status: string) => void): {
7
+ begin(): number;
8
+ isCurrent(token: number): boolean;
9
+ report(token: number, status: string): boolean;
10
+ dispose(): void;
11
+ };
@@ -0,0 +1,29 @@
1
+ // src/appearance/theme-library-action-fence.ts
2
+ /**
3
+ * Owns status completions for asynchronous theme-library actions. Starting a newer
4
+ * import/removal invalidates older completions; disposal suppresses all later UI
5
+ * writes while allowing an already-started storage commit to finish.
6
+ */
7
+ function createThemeLibraryActionFence(writeStatus) {
8
+ let revision = 0;
9
+ let disposed = false;
10
+ return {
11
+ begin() {
12
+ revision += 1;
13
+ return revision;
14
+ },
15
+ isCurrent(token) {
16
+ return !disposed && token === revision;
17
+ },
18
+ report(token, status) {
19
+ if (disposed || token !== revision) return false;
20
+ writeStatus(status);
21
+ return true;
22
+ },
23
+ dispose() {
24
+ disposed = true;
25
+ revision += 1;
26
+ }
27
+ };
28
+ }
29
+ export { createThemeLibraryActionFence };
File without changes
File without changes
File without changes
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env bun
2
2
  import { runCli } from "./cli-runner.js";
3
3
  import { applyFrameworkUpdate, resolveFrameworkRelease } from "../release/framework-update.js";
4
+ import { withFrameworkUpdateLock } from "../release/framework-update-lock.js";
5
+ import { resolve } from "node:path";
4
6
  // src/cli/framework-update-cli.ts
5
- await runCli((error) => `App-framework update failed; nothing was changed. ${error.message}`, async () => {
7
+ await runCli((error) => `App-framework update failed. ${error.message}`, async () => {
6
8
  const [requested, ...extra] = process.argv.slice(2);
7
9
  if (extra.length) throw new Error("Usage: adea-update-app-framework [version]");
8
10
  const release = await resolveFrameworkRelease({
@@ -18,7 +20,18 @@ await runCli((error) => `App-framework update failed; nothing was changed. ${err
18
20
  }
19
21
  }, requested);
20
22
  const root = process.cwd();
21
- const result = await applyFrameworkUpdate(root, release, {
23
+ const lockPath = Bun.spawnSync([
24
+ "git",
25
+ "rev-parse",
26
+ "--git-path",
27
+ "adea-framework-update.lock"
28
+ ], {
29
+ cwd: root,
30
+ stderr: "ignore"
31
+ });
32
+ const lockName = lockPath.stdout.toString().trim();
33
+ if (lockPath.exitCode !== 0 || !lockName) throw new Error("Cannot locate the Git worktree lock");
34
+ const result = await withFrameworkUpdateLock(resolve(root, lockName), () => applyFrameworkUpdate(root, release, {
22
35
  async run(command, cwd) {
23
36
  return Bun.spawn(command, {
24
37
  cwd,
@@ -35,6 +48,6 @@ await runCli((error) => `App-framework update failed; nothing was changed. ${err
35
48
  if (listing.exitCode !== 0) throw new Error("git ls-files failed");
36
49
  return listing.stdout.toString().split("\0").filter(Boolean);
37
50
  }
38
- });
51
+ }));
39
52
  process.stdout.write(JSON.stringify(result) + "\n");
40
53
  });
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -1,3 +1,4 @@
1
+ import type { DesktopStreamSession } from './desktop-client';
1
2
  /** The shared-surface commands `ApplicationUtilities` provides. */
2
3
  export type ApplicationCommandTarget = Readonly<{
3
4
  openAbout(): void;
@@ -9,7 +10,16 @@ type StreamClient = {
9
10
  openStream(name: string, input: unknown, onMessage: (payload: string | ArrayBuffer) => void, onClose?: () => void): Promise<{
10
11
  close(): void;
11
12
  }>;
13
+ isStreamSessionCurrent?(token: DesktopStreamSession): boolean;
14
+ openStreamForSession?(token: DesktopStreamSession, name: string, input: unknown, onMessage: (payload: string | ArrayBuffer) => void, onClose?: () => void): Promise<{
15
+ close(): void;
16
+ }>;
17
+ };
18
+ /** Existing callers can invoke this to disconnect. Resubscription is explicit. */
19
+ export type ApplicationCommandConnection = (() => void) & {
20
+ /** After explicit reconnect, attach with its token; concurrent calls are rejected. */
21
+ resubscribe(session: DesktopStreamSession): Promise<void>;
12
22
  };
13
23
  /** Route native menu commands from the desktop host to the shared surfaces. */
14
- export declare function connectApplicationCommands(client: StreamClient, commands: ApplicationCommandTarget): Promise<() => void>;
24
+ export declare function connectApplicationCommands(client: StreamClient, commands: ApplicationCommandTarget): Promise<ApplicationCommandConnection>;
15
25
  export {};
@@ -2,8 +2,13 @@ import { applicationCommandStream, applicationMenuCommands } from "../shell/appl
2
2
  // src/desktop/application-command-client.ts
3
3
  /** Route native menu commands from the desktop host to the shared surfaces. */
4
4
  async function connectApplicationCommands(client, commands) {
5
- const stream = await client.openStream(applicationCommandStream, null, (payload) => {
6
- if (typeof payload !== "string" || payload.length > 64) return;
5
+ let generation = 0;
6
+ let disposed = false;
7
+ let busy = false;
8
+ let current;
9
+ let boundSession;
10
+ const receive = (ticket) => (payload) => {
11
+ if (disposed || ticket !== generation || typeof payload !== "string" || payload.length > 64) return;
7
12
  let command;
8
13
  try {
9
14
  command = JSON.parse(payload).command;
@@ -15,7 +20,65 @@ async function connectApplicationCommands(client, commands) {
15
20
  else if (command === "settings") commands.openSettings();
16
21
  else if (command === "help") commands.openHelp();
17
22
  else commands.openUpdates();
23
+ };
24
+ let initial;
25
+ let initialClosed = false;
26
+ let initialAdmitted = false;
27
+ const initialReceive = receive(generation);
28
+ initial = await client.openStream(applicationCommandStream, null, (payload) => {
29
+ if (initialAdmitted) initialReceive(payload);
30
+ }, () => {
31
+ initialClosed = true;
32
+ initialAdmitted = false;
33
+ if (initial && current === initial) current = void 0;
18
34
  });
19
- return () => stream.close();
35
+ if (initialClosed) throw new Error("Application command stream closed during setup");
36
+ current = initial;
37
+ initialAdmitted = true;
38
+ const disconnect = () => {
39
+ if (disposed) return;
40
+ disposed = true;
41
+ generation++;
42
+ current?.close();
43
+ current = void 0;
44
+ };
45
+ disconnect.resubscribe = async (session) => {
46
+ if (disposed) throw new Error("Application command connection is closed");
47
+ if (busy) throw new Error("Application command resubscription is in progress");
48
+ if (!client.openStreamForSession || !client.isStreamSessionCurrent) throw new Error("Application command client does not support bound resubscription");
49
+ if (!client.isStreamSessionCurrent(session)) throw new Error("Desktop channel is no longer active");
50
+ if (boundSession === session) throw new Error("Application command session is already bound");
51
+ busy = true;
52
+ const ticket = generation + 1;
53
+ try {
54
+ let next;
55
+ let closed = false;
56
+ let admitted = false;
57
+ const candidateReceive = receive(ticket);
58
+ next = await client.openStreamForSession(session, applicationCommandStream, null, (payload) => {
59
+ if (admitted) candidateReceive(payload);
60
+ }, () => {
61
+ closed = true;
62
+ admitted = false;
63
+ if (next && current === next) {
64
+ current = void 0;
65
+ boundSession = void 0;
66
+ }
67
+ });
68
+ if (disposed || closed || !client.isStreamSessionCurrent(session)) {
69
+ next.close();
70
+ throw new Error("Application command resubscription was superseded");
71
+ }
72
+ const previous = current;
73
+ generation = ticket;
74
+ current = next;
75
+ boundSession = session;
76
+ admitted = true;
77
+ previous?.close();
78
+ } finally {
79
+ busy = false;
80
+ }
81
+ };
82
+ return disconnect;
20
83
  }
21
84
  export { connectApplicationCommands };
@@ -26,7 +26,8 @@ export declare function createChannelAuthority<Principal>(options?: {
26
26
  };
27
27
  resolve(identity: ChannelIdentity): VerifiedChannel<Principal> | undefined;
28
28
  revoke(identity: ChannelIdentity): void;
29
+ /** Block synchronous reissuance during notifications; later issuance remains allowed. */
29
30
  revokeAll(): void;
30
- /** Notify long-lived transports after a channel is removed. Expiry is swept on authority access. */
31
+ /** Notify after removal without waiting for observers. Expiry is swept on authority access. */
31
32
  onRevoke(listener: (identity: ChannelIdentity) => void): () => void;
32
33
  };
@@ -16,6 +16,8 @@ function createChannelAuthority(options = {}) {
16
16
  maxChannels
17
17
  ].every((value) => Number.isSafeInteger(value) && value > 0)) throw new Error("Invalid channel authority configuration");
18
18
  let launch;
19
+ let revokingAll = false;
20
+ let revocationEpoch = Symbol();
19
21
  const channels = /* @__PURE__ */ new Map();
20
22
  const listeners = /* @__PURE__ */ new Set();
21
23
  function remove(id, channel) {
@@ -23,10 +25,10 @@ function createChannelAuthority(options = {}) {
23
25
  channels.delete(id);
24
26
  channel.secret.fill(0);
25
27
  for (const listener of [...listeners]) try {
26
- listener({
28
+ Promise.resolve(listener({
27
29
  channelId: id,
28
30
  credentialId: channel.credentialId
29
- });
31
+ })).catch(() => {});
30
32
  } catch {}
31
33
  }
32
34
  function time() {
@@ -45,8 +47,11 @@ function createChannelAuthority(options = {}) {
45
47
  return {
46
48
  /** Invalidates an earlier unused bootstrap; the caller must keep the result secret. */
47
49
  issue(principal) {
50
+ if (revokingAll) throw new Error("Channel authority is revoking all channels");
51
+ const epoch = revocationEpoch;
48
52
  const at = time();
49
53
  sweep(at);
54
+ if (epoch !== revocationEpoch) throw new Error("Channel issuance was superseded by revocation");
50
55
  clearLaunch();
51
56
  const secret = randomBytes(32);
52
57
  launch = {
@@ -60,8 +65,11 @@ function createChannelAuthority(options = {}) {
60
65
  };
61
66
  },
62
67
  handshake(bootstrap) {
68
+ if (revokingAll) return { ok: false };
69
+ const epoch = revocationEpoch;
63
70
  const at = time();
64
71
  sweep(at);
72
+ if (epoch !== revocationEpoch) return { ok: false };
65
73
  if (!launch || typeof bootstrap !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(bootstrap)) return { ok: false };
66
74
  const supplied = Buffer.from(bootstrap, "base64url");
67
75
  if (supplied.length !== launch.secret.length || !timingSafeEqual(supplied, launch.secret) || channels.size >= maxChannels) return { ok: false };
@@ -95,11 +103,19 @@ function createChannelAuthority(options = {}) {
95
103
  const channel = channels.get(identity.channelId);
96
104
  if (channel && channel.credentialId === identity.credentialId) remove(identity.channelId, channel);
97
105
  },
106
+ /** Block synchronous reissuance during notifications; later issuance remains allowed. */
98
107
  revokeAll() {
99
- clearLaunch();
100
- for (const [id, channel] of channels) remove(id, channel);
108
+ if (revokingAll) return;
109
+ revokingAll = true;
110
+ revocationEpoch = Symbol();
111
+ try {
112
+ clearLaunch();
113
+ for (const [id, channel] of channels) remove(id, channel);
114
+ } finally {
115
+ revokingAll = false;
116
+ }
101
117
  },
102
- /** Notify long-lived transports after a channel is removed. Expiry is swept on authority access. */
118
+ /** Notify after removal without waiting for observers. Expiry is swept on authority access. */
103
119
  onRevoke(listener) {
104
120
  listeners.add(listener);
105
121
  return () => {
@@ -0,0 +1,10 @@
1
+ import type { Stats } from 'node:fs';
2
+ import { type FileHandle } from 'node:fs/promises';
3
+ type AssetFile = Pick<FileHandle, 'close' | 'stat' | 'read'>;
4
+ type OpenAsset = (path: string, flags: 'r') => Promise<AssetFile>;
5
+ /**
6
+ * Stream an immutable bundled asset. This is not a snapshot: detected file changes
7
+ * fail the stream, and a read error can surface after response headers have been sent.
8
+ */
9
+ export declare function createClientAssetStream(path: string, expected: Stats, openAsset?: OpenAsset): ReadableStream<Uint8Array>;
10
+ export {};
@@ -0,0 +1,97 @@
1
+ import { open } from "node:fs/promises";
2
+ import { Buffer } from "node:buffer";
3
+ // src/desktop/client-asset-stream.ts
4
+ var FILE_CHUNK_BYTES = 65536;
5
+ function sameFile(expected, actual) {
6
+ return actual.isFile() && expected.dev === actual.dev && expected.ino === actual.ino && expected.size === actual.size && expected.mtimeMs === actual.mtimeMs && expected.ctimeMs === actual.ctimeMs;
7
+ }
8
+ /**
9
+ * Stream an immutable bundled asset. This is not a snapshot: detected file changes
10
+ * fail the stream, and a read error can surface after response headers have been sent.
11
+ */
12
+ function createClientAssetStream(path, expected, openAsset = open) {
13
+ let file;
14
+ let opening;
15
+ let closing;
16
+ let cancelled = false;
17
+ let offset = 0;
18
+ const close = () => {
19
+ if (closing) return closing;
20
+ const current = file;
21
+ file = void 0;
22
+ if (!current) return Promise.resolve();
23
+ const pending = current.close();
24
+ closing = pending;
25
+ const clear = () => {
26
+ if (closing === pending) closing = void 0;
27
+ };
28
+ pending.then(clear, clear);
29
+ return pending;
30
+ };
31
+ const ensureOpen = () => {
32
+ if (cancelled || file) return Promise.resolve();
33
+ if (opening) return opening;
34
+ const pending = (async () => {
35
+ const opened = await openAsset(path, "r");
36
+ if (cancelled) {
37
+ await opened.close();
38
+ return;
39
+ }
40
+ file = opened;
41
+ const actual = await opened.stat();
42
+ if (cancelled) {
43
+ await close();
44
+ return;
45
+ }
46
+ if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
47
+ })().finally(() => {
48
+ if (opening === pending) opening = void 0;
49
+ });
50
+ opening = pending;
51
+ return pending;
52
+ };
53
+ return new ReadableStream({
54
+ async pull(controller) {
55
+ if (cancelled) return;
56
+ try {
57
+ await ensureOpen();
58
+ if (cancelled) return;
59
+ const current = file;
60
+ if (!current) return;
61
+ if (offset === expected.size) {
62
+ const actual = await current.stat();
63
+ if (cancelled) return;
64
+ if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
65
+ await close();
66
+ if (cancelled) return;
67
+ controller.close();
68
+ return;
69
+ }
70
+ const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, expected.size - offset));
71
+ const { bytesRead } = await current.read(buffer, 0, buffer.length, offset);
72
+ if (cancelled) return;
73
+ if (!bytesRead) throw new Error("Client asset changed during request");
74
+ offset += bytesRead;
75
+ if (offset === expected.size) {
76
+ const actual = await current.stat();
77
+ if (cancelled) return;
78
+ if (!sameFile(expected, actual)) throw new Error("Client asset changed during request");
79
+ await close();
80
+ if (cancelled) return;
81
+ controller.enqueue(buffer.subarray(0, bytesRead));
82
+ controller.close();
83
+ } else controller.enqueue(buffer.subarray(0, bytesRead));
84
+ } catch (error) {
85
+ await close().catch(() => {});
86
+ if (!cancelled) controller.error(error);
87
+ }
88
+ },
89
+ async cancel() {
90
+ cancelled = true;
91
+ const pending = opening;
92
+ if (pending) await pending.catch(() => {});
93
+ await close();
94
+ }
95
+ }, { highWaterMark: 0 });
96
+ }
97
+ export { createClientAssetStream };
@@ -2,6 +2,8 @@ export type ClientOptions = {
2
2
  root: string;
3
3
  deniedPaths?: readonly string[];
4
4
  transformHtml?: (html: string, request: Request) => string;
5
+ /** Stream GET bodies instead of buffered snapshots. Use only for immutable asset roots. */
6
+ streamAssets?: boolean;
5
7
  };
6
- /** Serve a bundled SPA without resolving links outside its client root. */
8
+ /** Serve a bundled SPA without resolving links outside its root. */
7
9
  export declare function serveClient(request: Request, options: ClientOptions): Promise<Response>;
@@ -1,9 +1,11 @@
1
- import { realpath, stat } from "node:fs/promises";
1
+ import { createClientAssetStream } from "./client-asset-stream.js";
2
+ import { open, realpath, stat } from "node:fs/promises";
2
3
  import { extname, join, posix, relative, resolve, sep } from "node:path";
3
4
  // src/desktop/client-assets.ts
4
5
  var MIME = {
5
6
  ".html": "text/html",
6
7
  ".js": "text/javascript",
8
+ ".mjs": "text/javascript",
7
9
  ".css": "text/css",
8
10
  ".svg": "image/svg+xml",
9
11
  ".json": "application/json",
@@ -16,8 +18,15 @@ var unavailable = (status = 404) => new Response(null, {
16
18
  status,
17
19
  headers: { "cache-control": "no-store" }
18
20
  });
19
- /** Serve a bundled SPA without resolving links outside its client root. */
21
+ /** Serve a bundled SPA without resolving links outside its root. */
20
22
  async function serveClient(request, options) {
23
+ if (request.method !== "GET" && request.method !== "HEAD") return new Response(null, {
24
+ status: 405,
25
+ headers: {
26
+ Allow: "GET, HEAD",
27
+ "cache-control": "no-store"
28
+ }
29
+ });
21
30
  let logical;
22
31
  try {
23
32
  logical = posix.normalize("/" + decodeURIComponent(new URL(request.url).pathname).replaceAll("\\", "/"));
@@ -44,16 +53,42 @@ async function serveClient(request, options) {
44
53
  const folded = logical.toLowerCase();
45
54
  if (folded === "/assets" || folded.startsWith("/assets/")) return unavailable();
46
55
  filePath = join(root, "index.html");
56
+ metadata = await stat(filePath).catch(() => null);
57
+ if (!metadata?.isFile()) return unavailable();
47
58
  }
48
59
  const physical = await realpath(filePath).catch(() => null);
49
60
  if (!physical) return unavailable();
50
61
  if (!inside(physical)) return unavailable(403);
51
62
  if (denied("/" + relative(root, physical).replaceAll("\\", "/"))) return unavailable();
63
+ const extension = extname(physical).toLowerCase();
64
+ const contentType = MIME[extension] ?? "application/octet-stream";
65
+ if (request.method === "HEAD" && !(extension === ".html" && options.transformHtml)) {
66
+ const file = await open(physical, "r");
67
+ let size;
68
+ try {
69
+ const fileMetadata = await file.stat();
70
+ if (!fileMetadata.isFile()) return unavailable();
71
+ size = fileMetadata.size;
72
+ } finally {
73
+ await file.close();
74
+ }
75
+ return new Response(null, { headers: {
76
+ "content-type": contentType,
77
+ "content-length": String(size),
78
+ "cache-control": "no-store"
79
+ } });
80
+ }
81
+ if (options.streamAssets === true && request.method === "GET" && !(extension === ".html" && options.transformHtml)) return new Response(createClientAssetStream(physical, metadata), { headers: {
82
+ "content-type": contentType,
83
+ "cache-control": "no-store",
84
+ "content-length": String(metadata.size)
85
+ } });
52
86
  let body = new Uint8Array(await Bun.file(physical).arrayBuffer());
53
- if (extname(physical).toLowerCase() === ".html" && options.transformHtml) body = new TextEncoder().encode(options.transformHtml(new TextDecoder().decode(body), request));
54
- return new Response(body, { headers: {
55
- "content-type": MIME[extname(physical).toLowerCase()] ?? "application/octet-stream",
56
- "cache-control": "no-store"
87
+ if (extension === ".html" && options.transformHtml) body = new TextEncoder().encode(options.transformHtml(new TextDecoder().decode(body), request));
88
+ return new Response(request.method === "HEAD" ? null : body, { headers: {
89
+ "content-type": contentType,
90
+ "cache-control": "no-store",
91
+ ...request.method === "HEAD" ? { "content-length": String(body.byteLength) } : {}
57
92
  } });
58
93
  }
59
94
  export { serveClient };
@@ -1,8 +1,13 @@
1
1
  import type { ServiceResult } from '../app/service-registry';
2
2
  import type { FetchFunction } from '../updates/release-location';
3
- type Bootstrap = () => Promise<{
3
+ type Bootstrap = (signal?: AbortSignal) => Promise<{
4
4
  bootstrap: string;
5
5
  }>;
6
+ declare const streamSessionBrand: unique symbol;
7
+ /** A token tied to one successful explicit reconnect on its originating client. */
8
+ export type DesktopStreamSession = Readonly<{
9
+ [streamSessionBrand]: true;
10
+ }>;
6
11
  /** Browser-side client for the authenticated desktop gateway. Share one client per window: acquiring a new bootstrap revokes the window's previous channel. */
7
12
  export declare function createDesktopClient(options?: {
8
13
  origin?: string;
@@ -18,6 +23,15 @@ export declare function createDesktopClient(options?: {
18
23
  }>;
19
24
  invoke(name: string, input: unknown): Promise<ServiceResult>;
20
25
  reconnect(): Promise<void>;
26
+ /** Explicitly reconnect and return a token tied to that exact channel. */
27
+ reconnectForStreams(): Promise<DesktopStreamSession>;
28
+ /** Check token provenance and currentness without acquiring credentials. */
29
+ isStreamSessionCurrent(token: DesktopStreamSession): boolean;
30
+ /** Attach only through a current token from this client; never renew credentials. */
31
+ openStreamForSession(token: DesktopStreamSession, name: string, input: unknown, onMessage: (payload: string | ArrayBuffer) => void, onClose?: () => void): Promise<{
32
+ send(payload: string | ArrayBuffer): boolean;
33
+ close(): void;
34
+ }>;
21
35
  dispose(): void;
22
36
  };
23
37
  export {};