@adea-ai/app-framework 0.25.1 → 0.27.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 (128) hide show
  1. package/README.md +163 -21
  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/framework-update-cli.js +16 -3
  21. package/dist/cli/release-step-cli.js +6 -1
  22. package/dist/desktop/application-command-client.d.ts +11 -1
  23. package/dist/desktop/application-command-client.js +66 -3
  24. package/dist/desktop/channel-handshake.d.ts +2 -1
  25. package/dist/desktop/channel-handshake.js +21 -5
  26. package/dist/desktop/client-asset-stream.d.ts +10 -0
  27. package/dist/desktop/client-asset-stream.js +97 -0
  28. package/dist/desktop/client-assets.d.ts +3 -1
  29. package/dist/desktop/client-assets.js +41 -6
  30. package/dist/desktop/desktop-client.d.ts +15 -1
  31. package/dist/desktop/desktop-client.js +235 -109
  32. package/dist/desktop/desktop-gateway.d.ts +2 -0
  33. package/dist/desktop/desktop-gateway.js +134 -22
  34. package/dist/desktop/desktop-host-websocket.d.ts +10 -0
  35. package/dist/desktop/desktop-host-websocket.js +28 -0
  36. package/dist/desktop/desktop-host.d.ts +9 -0
  37. package/dist/desktop/desktop-host.js +70 -61
  38. package/dist/desktop/desktop-port-file.d.ts +2 -0
  39. package/dist/desktop/desktop-port-file.js +23 -0
  40. package/dist/desktop/desktop-stream.d.ts +5 -0
  41. package/dist/desktop/desktop-stream.js +83 -15
  42. package/dist/desktop/gateway-limits.d.ts +2 -0
  43. package/dist/desktop/gateway-limits.js +6 -0
  44. package/dist/desktop/open-url-channel.d.ts +5 -3
  45. package/dist/desktop/open-url-channel.js +18 -5
  46. package/dist/desktop/typed-array-intrinsics.d.ts +6 -0
  47. package/dist/desktop/typed-array-intrinsics.js +19 -0
  48. package/dist/framework-source.json +1 -1
  49. package/dist/installer/installed-payload.js +1 -1
  50. package/dist/installer/installer-ci-bootstrap.js +2 -1
  51. package/dist/installer/installer-command.d.ts +13 -0
  52. package/dist/installer/installer-command.js +47 -0
  53. package/dist/installer/installer-extraction.js +27 -61
  54. package/dist/installer/installer-identity.d.ts +22 -3
  55. package/dist/installer/installer-identity.js +63 -72
  56. package/dist/installer/installer-image-mount.d.ts +48 -0
  57. package/dist/installer/installer-image-mount.js +347 -0
  58. package/dist/installer/installer-layout.d.ts +2 -0
  59. package/dist/installer/installer-layout.js +6 -2
  60. package/dist/installer/installer-process-cleanup.js +1 -1
  61. package/dist/installer/installer-renderer-evidence.js +6 -2
  62. package/dist/installer/upgrade-asset-download.js +30 -8
  63. package/dist/native/app-bundle.d.ts +2 -2
  64. package/dist/native/app-bundle.js +5 -4
  65. package/dist/native/cef-helper-download.d.ts +1 -0
  66. package/dist/native/cef-helper-download.js +35 -0
  67. package/dist/native/cef-helper.js +146 -61
  68. package/dist/native/exclusive-rename.d.ts +2 -0
  69. package/dist/native/exclusive-rename.js +52 -0
  70. package/dist/native/native-secret-store.js +5 -4
  71. package/dist/native/partitioned-window.d.ts +5 -2
  72. package/dist/native/partitioned-window.js +69 -9
  73. package/dist/native/sidecar-services.js +2 -2
  74. package/dist/native/sidecar.js +68 -25
  75. package/dist/native/window-bootstrap.js +2 -2
  76. package/dist/release/feed-state.js +2 -1
  77. package/dist/release/framework-update-lock.d.ts +2 -0
  78. package/dist/release/framework-update-lock.js +42 -0
  79. package/dist/release/framework-update.d.ts +6 -2
  80. package/dist/release/framework-update.js +165 -40
  81. package/dist/release/local-release.js +68 -39
  82. package/dist/release/release-config.js +1 -1
  83. package/dist/release/release-steps.d.ts +5 -0
  84. package/dist/release/release-steps.js +2 -1
  85. package/dist/shared/discard-stream.d.ts +4 -0
  86. package/dist/shared/discard-stream.js +9 -0
  87. package/dist/shell/app-shell.js +59 -7
  88. package/dist/shell/app-utilities.js +2 -2
  89. package/dist/shell/application-menu.d.ts +13 -0
  90. package/dist/shell/application-menu.js +21 -8
  91. package/dist/update-helper.bundle.js +40 -4
  92. package/dist/updates/channel-update-manager.d.ts +2 -0
  93. package/dist/updates/channel-update-manager.js +15 -3
  94. package/dist/updates/desktop-updater.d.ts +2 -0
  95. package/dist/updates/desktop-updater.js +36 -7
  96. package/dist/updates/linux-process-state.d.ts +2 -0
  97. package/dist/updates/linux-process-state.js +13 -0
  98. package/dist/updates/release-location.js +5 -4
  99. package/dist/updates/update-adapter.js +5 -0
  100. package/dist/updates/update-arm.d.ts +2 -0
  101. package/dist/updates/update-arm.js +58 -7
  102. package/dist/updates/update-discovery.js +2 -1
  103. package/dist/updates/update-download-cleanup.d.ts +7 -0
  104. package/dist/updates/update-download-cleanup.js +21 -0
  105. package/dist/updates/update-download.js +41 -20
  106. package/dist/updates/update-exclusive-rename.d.ts +3 -2
  107. package/dist/updates/update-exclusive-rename.js +3 -50
  108. package/dist/updates/update-extraction.js +1 -1
  109. package/dist/updates/update-manager.d.ts +17 -1
  110. package/dist/updates/update-manager.js +27 -8
  111. package/dist/updates/update-process-fence.js +18 -3
  112. package/dist/views/appearance-surface.js +51 -15
  113. package/package.json +8 -3
  114. package/src/app/application.tsx +49 -7
  115. package/src/appearance/custom-theme-import.ts +67 -7
  116. package/src/appearance/custom-theme-library.ts +391 -33
  117. package/src/appearance/editor.ts +49 -10
  118. package/src/appearance/theme-file-importer.ts +43 -12
  119. package/src/appearance/theme-library-action-fence.ts +28 -0
  120. package/src/desktop/client-asset-stream.ts +118 -0
  121. package/src/desktop/client-assets.ts +55 -5
  122. package/src/shell/app-shell.tsx +71 -8
  123. package/src/shell/app-utilities.tsx +2 -2
  124. package/src/updates/update-adapter.ts +5 -0
  125. package/src/views/appearance-surface.tsx +61 -29
  126. package/templates/application/README.md +5 -1
  127. package/templates/application/scripts/app-version.ts +7 -3
  128. package/templates/application/src/bun/index.ts +2 -0
@@ -1,4 +1,5 @@
1
1
  // src/native/sidecar.ts
2
+ var STOP_GRACE_PERIOD_MS = 1e3;
2
3
  var MAX_REQUEST_ID = Number.MAX_SAFE_INTEGER;
3
4
  var NEWLINE = 10;
4
5
  var fail = (reason, error) => ({
@@ -34,8 +35,18 @@ function createSidecar(options) {
34
35
  pending.resolve(fail(reason, error));
35
36
  }
36
37
  }
38
+ function retire(state, reason, error) {
39
+ if (running !== state || state.retiring) return;
40
+ state.retiring = true;
41
+ failAll(state, reason, error);
42
+ terminate(state);
43
+ }
37
44
  let hooked = false;
38
- const onHostExit = () => kill();
45
+ const onHostExit = () => {
46
+ stopped = true;
47
+ const state = running;
48
+ if (state) forceTerminate(state);
49
+ };
39
50
  const hook = (on) => {
40
51
  if (on === hooked) return;
41
52
  hooked = on;
@@ -46,7 +57,6 @@ function createSidecar(options) {
46
57
  const now = performance.now();
47
58
  starts = starts.filter((at) => now - at < windowMs);
48
59
  if (starts.length > maxRestarts) return fail("restart_limit", `The ${name} stopped repeatedly; try again shortly`);
49
- starts.push(now);
50
60
  let child;
51
61
  try {
52
62
  child = Bun.spawn({
@@ -60,14 +70,19 @@ function createSidecar(options) {
60
70
  note(`${name} failed to start: ${String(error)}`);
61
71
  return fail("unavailable", `The ${name} could not be started`);
62
72
  }
73
+ starts.push(now);
63
74
  const state = {
64
75
  process: child,
65
- pending: /* @__PURE__ */ new Map()
76
+ pending: /* @__PURE__ */ new Map(),
77
+ retiring: false,
78
+ exited: false
66
79
  };
67
80
  hook(true);
68
81
  readReplies(state);
69
82
  readStderr(child.stderr);
70
83
  child.exited.then((code) => {
84
+ state.exited = true;
85
+ if (state.killTimer) clearTimeout(state.killTimer);
71
86
  if (running === state) {
72
87
  running = void 0;
73
88
  hook(false);
@@ -84,8 +99,7 @@ function createSidecar(options) {
84
99
  let partial = 0;
85
100
  const tooLarge = () => {
86
101
  note(`${name} reply exceeded ${maxReplyBytes} bytes; restarting it`);
87
- failAll(state, "reply_too_large", `The ${name} sent an oversized reply`);
88
- state.process.kill();
102
+ retire(state, "reply_too_large", `The ${name} sent an oversized reply`);
89
103
  };
90
104
  try {
91
105
  for await (const chunk of state.process.stdout) {
@@ -119,6 +133,7 @@ function createSidecar(options) {
119
133
  } catch (error) {
120
134
  note(`${name} stdout failed: ${String(error)}`);
121
135
  }
136
+ retire(state, "exited", `The ${name} stopped before replying`);
122
137
  }
123
138
  function deliver(state, line) {
124
139
  if (!line.trim()) return;
@@ -148,36 +163,60 @@ function createSidecar(options) {
148
163
  async function readStderr(stream) {
149
164
  const decoder = new TextDecoder();
150
165
  let buffer = "";
166
+ const append = (text) => {
167
+ if (!text) return;
168
+ const tail = encoder.encode(stderrTail + text);
169
+ let offset = Math.max(0, tail.byteLength - maxStderrBytes);
170
+ while (offset < tail.byteLength && (tail[offset] & 192) === 128) offset++;
171
+ stderrTail = new TextDecoder().decode(tail.subarray(offset));
172
+ buffer += text;
173
+ const lines = buffer.split("\n");
174
+ buffer = lines.pop() ?? "";
175
+ if (encoder.encode(buffer).byteLength > maxStderrBytes) buffer = "";
176
+ for (const line of lines) if (line.trim()) note(`${name}: ${line.slice(0, 4096)}`);
177
+ };
151
178
  try {
152
- for await (const chunk of stream) {
153
- const text = decoder.decode(chunk, { stream: true });
154
- stderrTail += text;
155
- if (stderrTail.length > maxStderrBytes) stderrTail = stderrTail.slice(-maxStderrBytes);
156
- buffer += text;
157
- const lines = buffer.split("\n");
158
- buffer = lines.pop() ?? "";
159
- if (buffer.length > maxStderrBytes) buffer = "";
160
- for (const line of lines) if (line.trim()) note(`${name}: ${line.slice(0, 4096)}`);
161
- }
179
+ for await (const chunk of stream) append(decoder.decode(chunk, { stream: true }));
162
180
  } catch {}
181
+ append(decoder.decode());
182
+ if (buffer.trim()) note(`${name}: ${buffer.slice(0, 4096)}`);
163
183
  }
164
184
  function ensure() {
165
185
  if (stopped) return fail("stopped", `The ${name} is shut down`);
166
- if (running) return running;
186
+ if (running) {
187
+ if (running.retiring) return fail("exited", `The ${name} is not accepting requests`);
188
+ return running;
189
+ }
167
190
  const state = spawn();
168
191
  if ("process" in state) running = state;
169
192
  return state;
170
193
  }
194
+ function forceTerminate(state) {
195
+ if (state.exited) return;
196
+ if (state.killTimer) {
197
+ clearTimeout(state.killTimer);
198
+ state.killTimer = void 0;
199
+ }
200
+ try {
201
+ state.process.kill("SIGKILL");
202
+ } catch {}
203
+ }
204
+ function terminate(state) {
205
+ if (state.exited) return;
206
+ try {
207
+ state.process.stdin.end();
208
+ } catch {}
209
+ try {
210
+ state.process.kill();
211
+ } catch {}
212
+ state.killTimer ??= setTimeout(() => forceTerminate(state), STOP_GRACE_PERIOD_MS);
213
+ }
171
214
  function kill() {
172
215
  const state = running;
173
- running = void 0;
174
- hook(false);
175
216
  if (!state) return;
217
+ state.retiring = true;
176
218
  failAll(state, "stopped", `The ${name} is shut down`);
177
- try {
178
- state.process.stdin.end();
179
- } catch {}
180
- state.process.kill();
219
+ terminate(state);
181
220
  }
182
221
  function call(command, args, callOptions) {
183
222
  const signal = callOptions?.signal;
@@ -218,11 +257,15 @@ function createSidecar(options) {
218
257
  resolve,
219
258
  cleanup
220
259
  });
260
+ const writeFailed = () => {
261
+ if (running !== state || state.retiring) return;
262
+ retire(state, "exited", `The ${name} is not accepting requests`);
263
+ };
221
264
  try {
222
- state.process.stdin.write(line + "\n");
223
- Promise.resolve(state.process.stdin.flush()).catch(() => {});
265
+ Promise.resolve(state.process.stdin.write(line + "\n")).catch(writeFailed);
266
+ Promise.resolve(state.process.stdin.flush()).catch(writeFailed);
224
267
  } catch {
225
- settle(fail("exited", `The ${name} is not accepting requests`));
268
+ writeFailed();
226
269
  }
227
270
  });
228
271
  }
@@ -36,13 +36,13 @@ function createNativeWindowGrant(options) {
36
36
  const keyBytes = Uint8Array.from(atob(${JSON.stringify(secret.toString("base64"))}), c => c.charCodeAt(0));
37
37
  const nativeFetch = fetch.bind(window);
38
38
  const encode = bytes => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');
39
- Object.defineProperty(window, '__frameworkAcquireBootstrap', { configurable: false, value: async () => {
39
+ Object.defineProperty(window, '__frameworkAcquireBootstrap', { configurable: false, value: async signal => {
40
40
  const nonce = encode(crypto.getRandomValues(new Uint8Array(24)));
41
41
  const timestamp = String(Date.now());
42
42
  const fields = ['framework-window-bootstrap-v1', ${JSON.stringify(channelId)}, ${JSON.stringify(credentialId)}, nonce, timestamp, ${JSON.stringify(bodySha256)}];
43
43
  const key = await crypto.subtle.importKey('raw', keyBytes, {name:'HMAC', hash:'SHA-256'}, false, ['sign']);
44
44
  const proof = encode(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(fields.join('\\u001f'))));
45
- const response = await nativeFetch(${JSON.stringify(origin + "/__framework/bootstrap")}, {method:'POST', headers:{'content-type':'application/json', 'x-adea-channel':${JSON.stringify(channelId)}, 'x-adea-credential':${JSON.stringify(credentialId)}, 'x-adea-nonce':nonce, 'x-adea-timestamp':timestamp, 'x-adea-proof':proof}, body:'{}'});
45
+ const response = await nativeFetch(${JSON.stringify(origin + "/__framework/bootstrap")}, {method:'POST', headers:{'content-type':'application/json', 'x-adea-channel':${JSON.stringify(channelId)}, 'x-adea-credential':${JSON.stringify(credentialId)}, 'x-adea-nonce':nonce, 'x-adea-timestamp':timestamp, 'x-adea-proof':proof}, body:'{}', signal});
46
46
  if (!response.ok) throw new Error('Window bootstrap unavailable');
47
47
  return response.json();
48
48
  }});
@@ -1,6 +1,7 @@
1
1
  import { verifyReleaseDescriptor } from "../updates/signed-release.js";
2
2
  import { feedUrl, parseFeedRelease, parseReleaseLedger } from "../updates/release-feed.js";
3
3
  import { discoveryPolicies } from "./release-config.js";
4
+ import { discardStream } from "../shared/discard-stream.js";
4
5
  import { fetchReleaseLocation, readReleaseBytes } from "../updates/release-location.js";
5
6
  import { createHash } from "node:crypto";
6
7
  // src/release/feed-state.ts
@@ -10,7 +11,7 @@ var MAX_RELEASE_BYTES = 262144;
10
11
  async function readFeedObject(feed, path, fetcher, maximum) {
11
12
  const response = await fetchReleaseLocation(`${feedUrl(feed)}${path}`, feedUrl(feed), fetcher, AbortSignal.timeout(6e4));
12
13
  if (response.status === 404) {
13
- await response.body?.cancel();
14
+ discardStream(response.body);
14
15
  return null;
15
16
  }
16
17
  return readReleaseBytes(response, maximum);
@@ -0,0 +1,2 @@
1
+ /** Serialize cooperating framework updates in one Git worktree. */
2
+ export declare function withFrameworkUpdateLock<T>(path: string, run: () => Promise<T>): Promise<T>;
@@ -0,0 +1,42 @@
1
+ import { lstat, mkdir, rmdir } from "node:fs/promises";
2
+ // src/release/framework-update-lock.ts
3
+ /** Serialize cooperating framework updates in one Git worktree. */
4
+ async function withFrameworkUpdateLock(path, run) {
5
+ try {
6
+ await mkdir(path);
7
+ } catch (error) {
8
+ if (error.code === "EEXIST") throw new Error("A framework update is running or its lock remains; inspect the worktree lock", { cause: error });
9
+ throw error;
10
+ }
11
+ let owner;
12
+ try {
13
+ owner = await lstat(path);
14
+ if (!owner.isDirectory()) throw new Error("Framework update lock is not a directory");
15
+ } catch (error) {
16
+ throw new Error("Framework update lock identity could not be verified; inspect the lock", { cause: error });
17
+ }
18
+ let failure;
19
+ let operationFailed = false;
20
+ let result;
21
+ try {
22
+ result = await run();
23
+ } catch (error) {
24
+ failure = error;
25
+ operationFailed = true;
26
+ }
27
+ let releaseFailure;
28
+ let releaseFailed = false;
29
+ try {
30
+ const current = await lstat(path);
31
+ if (!current.isDirectory() || current.dev !== owner.dev || current.ino !== owner.ino) throw new Error("Framework update lock ownership changed");
32
+ await rmdir(path);
33
+ } catch (error) {
34
+ releaseFailure = error;
35
+ releaseFailed = true;
36
+ }
37
+ if (releaseFailed && operationFailed) throw new AggregateError([failure, releaseFailure], "Framework update lock could not be released", { cause: failure });
38
+ if (releaseFailed) throw new Error("Framework update lock could not be released", { cause: releaseFailure });
39
+ if (operationFailed) throw failure;
40
+ return result;
41
+ }
42
+ export { withFrameworkUpdateLock };
@@ -13,6 +13,8 @@ type FrameworkUpdateIo = {
13
13
  run(command: string[], cwd: string): Promise<number>;
14
14
  /** Repository-relative paths of tracked files. */
15
15
  files(root: string): Promise<string[]>;
16
+ /** Optional file writer for exercising partial-write and rollback failures. */
17
+ write?(path: string, content: string): Promise<void>;
16
18
  };
17
19
  /** The npm version to pin: `requested`, or the `latest` dist-tag. The tarball must be the
18
20
  * registry's own, match its sha512 integrity, contain the version it claims and record the
@@ -25,6 +27,8 @@ type FrameworkUpdate = {
25
27
  changed: string[];
26
28
  };
27
29
  /** Pin every app-framework reference in `root` to `release`, regenerate bun.lock and prove
28
- * it with a frozen install. Any failure restores every file it touched. */
29
- export declare function applyFrameworkUpdate(root: string, release: FrameworkRelease, io: Pick<FrameworkUpdateIo, 'run' | 'files'>): Promise<FrameworkUpdate>;
30
+ * it with a frozen install. On failure, attempt to restore touched files and report any
31
+ * incomplete rollback. Conflicting bytes are preserved when detected, but callers must
32
+ * still prevent concurrent edits: checking and writing are not an atomic transaction. */
33
+ export declare function applyFrameworkUpdate(root: string, release: FrameworkRelease, io: Pick<FrameworkUpdateIo, 'run' | 'files' | 'write'>): Promise<FrameworkUpdate>;
30
34
  export {};
@@ -1,15 +1,19 @@
1
- import { readFile, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { createHash } from "node:crypto";
1
+ import { lstat, open, readFile, rename, unlink } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  // src/release/framework-update.ts
5
- /** Moves a consumer's app-framework pin to one published npm version in a single step: the
6
- * exact version in every package.json, the bun.lock entry and the reusable-workflow pins
7
- * all name the same release, or nothing is written. */
5
+ /** Moves a consumer's app-framework pin to one published npm version: package manifests,
6
+ * bun.lock and reusable-workflow pins must all name the same verified release. */
8
7
  var packageName = "@adea-ai/app-framework";
9
8
  var registry = "https://registry.npmjs.org";
10
9
  var workflowPin = /(adea-ai\/app-framework\/\.github\/workflows\/[\w.-]+\.ya?ml)@(?:[0-9a-f]{40}(?: # v[\w.-]+)?|v\d+\.\d+\.\d+)/g;
11
10
  var version = /^\d+\.\d+\.\d+$/;
12
- var manifestPin = /("@adea-ai\/app-framework"\s*:\s*")\d+\.\d+\.\d+"/g;
11
+ var dependencyFields = /* @__PURE__ */ new Set([
12
+ "dependencies",
13
+ "devDependencies",
14
+ "peerDependencies",
15
+ "optionalDependencies"
16
+ ]);
13
17
  /** The npm version to pin: `requested`, or the `latest` dist-tag. The tarball must be the
14
18
  * registry's own, match its sha512 integrity, contain the version it claims and record the
15
19
  * commit it was built from. */
@@ -51,16 +55,45 @@ function readPackageFile(bytes, path) {
51
55
  }
52
56
  throw new Error(`The tarball has no ${path}`);
53
57
  }
54
- /** Comments bun drops when it rewrites bun.lock, such as release-please's version marker,
55
- * keyed by the workspace block and the line they trail. */
58
+ /** Identify each line by its enclosing lockfile objects, not just a workspace's name. */
59
+ function scopedLockLines(lock) {
60
+ const stack = [];
61
+ return lock.split("\n").map((line) => {
62
+ const trimmed = line.trim();
63
+ if (!trimmed || trimmed.startsWith("//")) return {
64
+ line,
65
+ scope: JSON.stringify(stack.map((entry) => entry.key))
66
+ };
67
+ const indent = line.length - line.trimStart().length;
68
+ if (/^\s*}\s*,?\s*(?:\/\/.*)?$/.test(line)) {
69
+ while (stack.length && stack[stack.length - 1].indent > indent) stack.pop();
70
+ const scope = JSON.stringify(stack.map((entry) => entry.key));
71
+ if (stack.length && stack[stack.length - 1].indent === indent) stack.pop();
72
+ return {
73
+ line,
74
+ scope
75
+ };
76
+ }
77
+ while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
78
+ const scope = JSON.stringify(stack.map((entry) => entry.key));
79
+ const opening = /^\s*("(?:\\.|[^"\\])*"):\s*\{\s*$/.exec(line);
80
+ if (opening) stack.push({
81
+ indent,
82
+ key: opening[1]
83
+ });
84
+ return {
85
+ line,
86
+ scope
87
+ };
88
+ });
89
+ }
90
+ /** Comments bun drops when it rewrites bun.lock, keyed by their enclosing objects and line. */
56
91
  function lockComments(lock) {
57
- let block = "";
58
92
  const comments = [];
59
- for (const line of lock.split("\n")) {
60
- if (/^ {4}"[^"]*": \{/.test(line)) block = line;
93
+ for (const { line, scope } of scopedLockLines(lock)) {
61
94
  const match = /^(.*?,)\s*(\/\/.*)$/.exec(line);
62
95
  if (match) comments.push({
63
- block,
96
+ scope,
64
97
  line: match[1],
65
98
  comment: match[2]
66
99
  });
@@ -68,21 +101,88 @@ function lockComments(lock) {
68
101
  return comments;
69
102
  }
70
103
  function restoreLockComments(lock, comments) {
71
- const lines = lock.split("\n");
72
- for (const { block, line, comment } of comments) {
73
- const start = lines.indexOf(block);
74
- const index = lines.findIndex((candidate, at) => at > start && candidate === line);
75
- if (start < 0 || index < 0) throw new Error(`bun.lock lost the line for "${comment}"`);
76
- lines[index] = `${line} ${comment}`;
104
+ const lines = scopedLockLines(lock);
105
+ for (const { scope, line, comment } of comments) {
106
+ const matches = lines.filter((candidate) => candidate.scope === scope && (candidate.line === line || candidate.line === `${line} ${comment}`));
107
+ if (matches.length !== 1) throw new Error(`bun.lock lost the line for "${comment}"`);
108
+ matches[0].line = `${line} ${comment}`;
109
+ }
110
+ return lines.map(({ line }) => line).join("\n");
111
+ }
112
+ /** Rewrite only direct dependency values, preserving all other JSON bytes. */
113
+ function updateManifest(text, path, target) {
114
+ JSON.parse(text);
115
+ const tokens = [...text.matchAll(/"(?:\\.|[^"\\])*"|[{}[\]:,]|[^{}[\]:,\s]+/g)];
116
+ const edits = [];
117
+ let position = 0;
118
+ function value(scope) {
119
+ if (scope.length > 256) throw new Error(`${path} exceeds the manifest nesting limit`);
120
+ const token = tokens[position++];
121
+ if (token[0] === "{") {
122
+ const seen = /* @__PURE__ */ new Set();
123
+ while (tokens[position][0] !== "}") {
124
+ const key = JSON.parse(tokens[position++][0]);
125
+ if ((scope.length === 0 && dependencyFields.has(key) || scope.length === 1 && dependencyFields.has(scope[0]) && key === packageName) && seen.has(key)) throw new Error(`${path} contains duplicate ${key} keys`);
126
+ seen.add(key);
127
+ position++;
128
+ const member = tokens[position];
129
+ if (scope.length === 1 && dependencyFields.has(scope[0]) && key === packageName) {
130
+ const pin = member[0].startsWith("\"") ? JSON.parse(member[0]) : void 0;
131
+ if (typeof pin !== "string" || !version.test(pin)) throw new Error(`${path} pins ${packageName} to ${String(pin)}`);
132
+ edits.push({
133
+ start: member.index,
134
+ end: member.index + member[0].length
135
+ });
136
+ }
137
+ value([...scope, key]);
138
+ if (tokens[position][0] === ",") position++;
139
+ }
140
+ position++;
141
+ } else if (token[0] === "[") {
142
+ while (tokens[position][0] !== "]") {
143
+ value([...scope, "[]"]);
144
+ if (tokens[position][0] === ",") position++;
145
+ }
146
+ position++;
147
+ }
148
+ }
149
+ value([]);
150
+ if (!edits.length) return void 0;
151
+ let result = text;
152
+ for (const edit of edits.toReversed()) result = result.slice(0, edit.start) + JSON.stringify(target) + result.slice(edit.end);
153
+ return result;
154
+ }
155
+ /** Replace a regular file without exposing a truncated intermediate version. */
156
+ async function writeAtomic(path, content) {
157
+ const info = await lstat(path);
158
+ if (!info.isFile()) throw new Error(`Cannot update non-regular file: ${path}`);
159
+ const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
160
+ const file = await open(temporary, "wx", info.mode & 511);
161
+ try {
162
+ await file.writeFile(content, "utf8");
163
+ await file.chmod(info.mode & 4095);
164
+ await file.close();
165
+ await rename(temporary, path);
166
+ } finally {
167
+ await file.close().catch(() => {});
168
+ await unlink(temporary).catch((error) => {
169
+ if (error.code !== "ENOENT") throw error;
170
+ });
77
171
  }
78
- return lines.join("\n");
79
172
  }
80
173
  /** Pin every app-framework reference in `root` to `release`, regenerate bun.lock and prove
81
- * it with a frozen install. Any failure restores every file it touched. */
174
+ * it with a frozen install. On failure, attempt to restore touched files and report any
175
+ * incomplete rollback. Conflicting bytes are preserved when detected, but callers must
176
+ * still prevent concurrent edits: checking and writing are not an atomic transaction. */
82
177
  async function applyFrameworkUpdate(root, release, io) {
178
+ const write = io.write ?? writeAtomic;
83
179
  const tracked = await io.files(root);
84
180
  const manifests = tracked.filter((path) => /(^|\/)package\.json$/.test(path));
85
181
  const workflows = tracked.filter((path) => /^\.github\/workflows\/[^/]+\.ya?ml$/.test(path));
182
+ const requireRegularLock = async () => {
183
+ if (!(await lstat(join(root, "bun.lock"))).isFile()) throw new Error("Cannot update non-regular file: bun.lock");
184
+ };
185
+ await requireRegularLock();
86
186
  const original = /* @__PURE__ */ new Map();
87
187
  for (const path of [
88
188
  ...manifests,
@@ -91,17 +191,8 @@ async function applyFrameworkUpdate(root, release, io) {
91
191
  ]) original.set(path, await readFile(join(root, path), "utf8"));
92
192
  const next = /* @__PURE__ */ new Map();
93
193
  for (const path of manifests) {
94
- const text = original.get(path);
95
- const dependency = JSON.parse(text);
96
- const declared = [
97
- "dependencies",
98
- "devDependencies",
99
- "peerDependencies",
100
- "optionalDependencies"
101
- ].map((field) => dependency[field]?.[packageName]).filter((value) => value !== void 0);
102
- if (!declared.length) continue;
103
- for (const value of declared) if (!version.test(value)) throw new Error(`${path} pins ${packageName} to ${value}`);
104
- next.set(path, text.replace(manifestPin, `$1${release.version}"`));
194
+ const updated = updateManifest(original.get(path), path, release.version);
195
+ if (updated !== void 0) next.set(path, updated);
105
196
  }
106
197
  for (const path of workflows) {
107
198
  const text = original.get(path);
@@ -110,16 +201,31 @@ async function applyFrameworkUpdate(root, release, io) {
110
201
  }
111
202
  if (![...next.keys()].some((path) => manifests.includes(path))) throw new Error(`No package.json depends on ${packageName}`);
112
203
  const written = [];
204
+ const expected = /* @__PURE__ */ new Map();
205
+ const ensureUnchanged = async (path, text) => {
206
+ if (await readFile(join(root, path), "utf8") !== text) throw new Error(`Concurrent modification of ${path}`);
207
+ };
113
208
  try {
114
209
  for (const [path, text] of next) {
115
210
  if (text === original.get(path)) continue;
116
- await writeFile(join(root, path), text);
211
+ await ensureUnchanged(path, original.get(path));
117
212
  written.push(path);
213
+ expected.set(path, text);
214
+ await write(join(root, path), text);
118
215
  }
216
+ await requireRegularLock();
217
+ await ensureUnchanged("bun.lock", original.get("bun.lock"));
119
218
  written.push("bun.lock");
219
+ expected.set("bun.lock", original.get("bun.lock"));
120
220
  if (await io.run(["bun", "install"], root) !== 0) throw new Error("bun install failed");
121
- const lock = restoreLockComments(await readFile(join(root, "bun.lock"), "utf8"), lockComments(original.get("bun.lock")));
122
- await writeFile(join(root, "bun.lock"), lock);
221
+ const installedLock = await readFile(join(root, "bun.lock"), "utf8");
222
+ expected.set("bun.lock", installedLock);
223
+ const lock = restoreLockComments(installedLock, lockComments(original.get("bun.lock")));
224
+ if (lock !== installedLock) {
225
+ await ensureUnchanged("bun.lock", installedLock);
226
+ expected.set("bun.lock", lock);
227
+ await write(join(root, "bun.lock"), lock);
228
+ }
123
229
  const entries = lock.split("\n").filter((line) => line.trimStart().startsWith(`"${packageName}": [`));
124
230
  if (entries.length !== 1 || !entries[0].trimStart().startsWith(`"${packageName}": ["${packageName}@${release.version}", "",`) || !entries[0].trimEnd().endsWith(`"${release.integrity}"],`)) throw new Error("bun.lock does not pin the verified npm package");
125
231
  if (await io.run([
@@ -127,13 +233,32 @@ async function applyFrameworkUpdate(root, release, io) {
127
233
  "install",
128
234
  "--frozen-lockfile"
129
235
  ], root) !== 0) throw new Error("The regenerated bun.lock does not pass a frozen install");
236
+ const finalLock = await readFile(join(root, "bun.lock"), "utf8");
237
+ if (finalLock !== lock) throw new Error("The frozen install changed bun.lock");
238
+ for (const [path, text] of next) await ensureUnchanged(path, text);
239
+ const changed = [];
240
+ for (const path of written) if ((path === "bun.lock" ? finalLock : await readFile(join(root, path), "utf8")) !== original.get(path)) changed.push(path);
241
+ return {
242
+ release,
243
+ changed
244
+ };
130
245
  } catch (error) {
131
- for (const path of written) await writeFile(join(root, path), original.get(path));
246
+ const rollbackErrors = [];
247
+ const conflicts = [];
248
+ for (const path of written) try {
249
+ const current = await readFile(join(root, path), "utf8");
250
+ if (current === original.get(path)) continue;
251
+ if (current !== expected.get(path)) {
252
+ conflicts.push(path);
253
+ rollbackErrors.push(/* @__PURE__ */ new Error(`Rollback preserved conflicting changes to ${path}`));
254
+ continue;
255
+ }
256
+ await write(join(root, path), original.get(path));
257
+ } catch (rollbackError) {
258
+ rollbackErrors.push(rollbackError);
259
+ }
260
+ if (rollbackErrors.length) throw new AggregateError([error, ...rollbackErrors], `Framework update rollback was incomplete${conflicts.length ? `; preserved: ${conflicts.join(", ")}` : ""}: ${error instanceof Error ? error.message : "unknown failure"}`, { cause: error });
132
261
  throw error;
133
262
  }
134
- return {
135
- release,
136
- changed: written
137
- };
138
263
  }
139
264
  export { applyFrameworkUpdate, readPackageFile, resolveFrameworkRelease };