@adea-ai/app-framework 0.27.0 → 0.28.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 (118) hide show
  1. package/README.md +177 -15
  2. package/dist/app/create-application.d.ts +2 -0
  3. package/dist/app/create-application.js +6 -0
  4. package/dist/app/service-registry.js +4 -0
  5. package/dist/appearance/custom-theme-import.js +43 -7
  6. package/dist/appearance/custom-theme-library.d.ts +2 -0
  7. package/dist/appearance/custom-theme-library.js +5 -1
  8. package/dist/appearance/theme-record-adapter.js +4 -2
  9. package/dist/appearance/theme-registry.js +7 -1
  10. package/dist/cli/create-application-cli.js +4 -2
  11. package/dist/cli/update-helper-cli.js +28 -6
  12. package/dist/desktop/client-asset-manifest.d.ts +47 -0
  13. package/dist/desktop/client-asset-manifest.js +114 -0
  14. package/dist/desktop/client-asset-stream.d.ts +10 -0
  15. package/dist/desktop/client-asset-stream.js +138 -33
  16. package/dist/desktop/client-assets.d.ts +20 -0
  17. package/dist/desktop/client-assets.js +132 -22
  18. package/dist/desktop/client-response-lifecycle.d.ts +22 -0
  19. package/dist/desktop/client-response-lifecycle.js +233 -0
  20. package/dist/desktop/desktop-host.d.ts +40 -2
  21. package/dist/desktop/desktop-host.js +159 -9
  22. package/dist/framework-source.json +1 -1
  23. package/dist/installer/command-artifact.d.ts +4 -2
  24. package/dist/installer/command-artifact.js +119 -19
  25. package/dist/installer/linux-process-group.d.ts +13 -0
  26. package/dist/installer/linux-process-group.js +58 -0
  27. package/dist/native/darwin-sync.d.ts +7 -0
  28. package/dist/native/darwin-sync.js +43 -0
  29. package/dist/native/desktop-build-hook.js +7 -0
  30. package/dist/native/directory-exchange.d.ts +10 -0
  31. package/dist/native/directory-exchange.js +90 -0
  32. package/dist/native/electrobun-source-patch.d.ts +5 -0
  33. package/dist/native/electrobun-source-patch.js +19 -1
  34. package/dist/native/posix-launcher-build.d.ts +24 -0
  35. package/dist/native/posix-launcher-build.js +232 -0
  36. package/dist/native/posix-tree-removal.d.ts +36 -0
  37. package/dist/native/posix-tree-removal.js +425 -0
  38. package/dist/update-helper.bundle.js +1483 -105
  39. package/dist/updates/channel-update-manager.d.ts +5 -0
  40. package/dist/updates/channel-update-manager.js +13 -1
  41. package/dist/updates/desktop-updater.d.ts +78 -2
  42. package/dist/updates/desktop-updater.js +320 -37
  43. package/dist/updates/launch-environment.d.ts +2 -0
  44. package/dist/updates/launch-environment.js +4 -0
  45. package/dist/updates/native-file-lock.d.ts +15 -0
  46. package/dist/updates/native-file-lock.js +189 -0
  47. package/dist/updates/packaged-launch-admission.d.ts +13 -0
  48. package/dist/updates/packaged-launch-admission.js +45 -0
  49. package/dist/updates/packaged-release-config.d.ts +18 -0
  50. package/dist/updates/packaged-release-config.js +60 -0
  51. package/dist/updates/packaged-update-startup.d.ts +44 -0
  52. package/dist/updates/packaged-update-startup.js +81 -0
  53. package/dist/updates/update-arm.d.ts +9 -8
  54. package/dist/updates/update-arm.js +227 -62
  55. package/dist/updates/update-cleanup-error.d.ts +23 -0
  56. package/dist/updates/update-cleanup-error.js +65 -0
  57. package/dist/updates/update-download-cleanup.d.ts +11 -0
  58. package/dist/updates/update-download-cleanup.js +112 -2
  59. package/dist/updates/update-download-lock.d.ts +20 -0
  60. package/dist/updates/update-download-lock.js +73 -0
  61. package/dist/updates/update-download.d.ts +2 -0
  62. package/dist/updates/update-download.js +7 -3
  63. package/dist/updates/update-generation-lease.d.ts +6 -0
  64. package/dist/updates/update-generation-lease.js +14 -0
  65. package/dist/updates/update-helper.d.ts +11 -2
  66. package/dist/updates/update-helper.js +322 -13
  67. package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
  68. package/dist/updates/update-inherited-launch-lease.js +58 -0
  69. package/dist/updates/update-instance-lease.d.ts +15 -0
  70. package/dist/updates/update-instance-lease.js +25 -0
  71. package/dist/updates/update-launch-gate.d.ts +137 -0
  72. package/dist/updates/update-launch-gate.js +617 -0
  73. package/dist/updates/update-launch.js +3 -1
  74. package/dist/updates/update-lock.d.ts +12 -0
  75. package/dist/updates/update-lock.js +18 -0
  76. package/dist/updates/update-manager.d.ts +2 -0
  77. package/dist/updates/update-manager.js +9 -2
  78. package/dist/updates/update-marker.d.ts +7 -0
  79. package/dist/updates/update-marker.js +62 -0
  80. package/dist/updates/update-preflight-error.d.ts +7 -0
  81. package/dist/updates/update-preflight-error.js +11 -0
  82. package/dist/updates/update-process-fence.d.ts +4 -0
  83. package/dist/updates/update-process-fence.js +85 -73
  84. package/dist/updates/update-process-liveness.d.ts +2 -0
  85. package/dist/updates/update-process-liveness.js +11 -0
  86. package/dist/updates/update-resume.d.ts +37 -3
  87. package/dist/updates/update-resume.js +839 -23
  88. package/dist/updates/update-retention-marker.d.ts +67 -0
  89. package/dist/updates/update-retention-marker.js +165 -0
  90. package/dist/updates/update-retention-plan.d.ts +25 -0
  91. package/dist/updates/update-retention-plan.js +54 -0
  92. package/dist/updates/update-retention-sync.d.ts +34 -0
  93. package/dist/updates/update-retention-sync.js +83 -0
  94. package/dist/updates/update-retirement.d.ts +205 -0
  95. package/dist/updates/update-retirement.js +1485 -0
  96. package/dist/updates/update-shutdown.d.ts +16 -4
  97. package/dist/updates/update-shutdown.js +133 -8
  98. package/dist/updates/update-state-store.d.ts +58 -0
  99. package/dist/updates/update-state-store.js +139 -0
  100. package/dist/updates/update-swap-stage.d.ts +1 -1
  101. package/dist/updates/update-swap-stage.js +85 -14
  102. package/dist/updates/update-swap.d.ts +45 -2
  103. package/dist/updates/update-swap.js +207 -17
  104. package/package.json +31 -1
  105. package/src/appearance/custom-theme-import.ts +96 -14
  106. package/src/appearance/custom-theme-library.ts +5 -0
  107. package/src/appearance/theme-record-adapter.ts +15 -6
  108. package/src/appearance/theme-registry.ts +8 -1
  109. package/src/desktop/client-asset-manifest.ts +207 -0
  110. package/src/desktop/client-asset-stream.ts +193 -32
  111. package/src/desktop/client-assets.ts +210 -19
  112. package/src/desktop/client-response-lifecycle.ts +305 -0
  113. package/src/native/electrobun-posix-launch-lease.patch +398 -0
  114. package/templates/application/README.md +50 -0
  115. package/templates/application/electrobun.config.ts +5 -1
  116. package/templates/application/scripts/build-desktop.ts +4 -0
  117. package/templates/application/src/bun/index.ts +173 -16
  118. package/templates/application/vite.config.ts +112 -6
@@ -1,30 +1,220 @@
1
- import { renameUpdateExclusive } from "./update-exclusive-rename.js";
2
- import { rm } from "node:fs/promises";
1
+ import { exchangeDirectories, probeDirectoryExchange } from "../native/directory-exchange.js";
2
+ import { withUpdateLock } from "./update-state-store.js";
3
+ import { lstat, open, readFile, readdir, readlink } from "node:fs/promises";
3
4
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
+ import { constants as constants$1 } from "node:fs";
6
+ import { createHash } from "node:crypto";
4
7
  // src/updates/update-swap.ts
5
8
  /** The private staging directory the framework keeps beside an install. */
6
9
  function updateStagingFor(target) {
7
10
  if (typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target) throw new Error("Invalid update target");
8
11
  return join(dirname(target), `.${basename(target)}.framework-update`);
9
12
  }
13
+ /** Read a version marker from an app tree, returning undefined when it is absent or invalid. */
14
+ async function readUpdateTreeVersion(tree) {
15
+ const versionPath = join(tree, ...process.platform === "darwin" ? ["Contents", "Resources"] : ["Resources"], "version.json");
16
+ try {
17
+ const value = JSON.parse(await readFile(versionPath, "utf8"));
18
+ if (typeof value !== "object" || value === null || typeof value.version !== "string") return void 0;
19
+ return value.version;
20
+ } catch {
21
+ return;
22
+ }
23
+ }
24
+ /** Capture only the stable device/inode pair; timestamps may be ctime fallbacks. */
25
+ function updateTreeIdentityFromStat(info) {
26
+ if (!info.isDirectory() || info.isSymbolicLink() || info.dev <= 0n || info.ino <= 0n) return void 0;
27
+ return {
28
+ device: info.dev.toString(10),
29
+ inode: info.ino.toString(10)
30
+ };
31
+ }
32
+ /** Read a directory's device/inode identity without Number precision loss. */
33
+ async function readUpdateTreeIdentity(tree) {
34
+ return updateTreeIdentityFromStat(await lstat(tree, { bigint: true }));
35
+ }
36
+ function sameUpdateTreeIdentity(left, right) {
37
+ return left !== void 0 && right !== void 0 && left.device === right.device && left.inode === right.inode;
38
+ }
39
+ function sameTreeEntrySnapshot(left, right) {
40
+ return left.dev === right.dev && left.ino === right.ino && left.mode === right.mode && left.nlink === right.nlink && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
41
+ }
10
42
  /**
11
- * Move the staged `candidate` into the install location once the app has
12
- * exited. The old tree is moved aside into staging and deleted.
43
+ * Compute a deterministic integrity digest for a complete extracted app tree.
44
+ * The manifest binds relative names, entry types, permission/special mode bits,
45
+ * regular-file sizes and bytes, and symbolic-link targets. It deliberately
46
+ * excludes ownership and timestamps. This digest is not signed authenticity;
47
+ * the signed release descriptor and verified archive establish provenance.
48
+ *
49
+ * Reads are no-follow by entry type, use O_NOFOLLOW for regular files when the
50
+ * host provides it, and compare lstat/fstat metadata before and after reads.
51
+ * This detects ordinary concurrent changes by cooperating updater processes;
52
+ * it is not an atomic filesystem snapshot against a hostile same-user writer.
13
53
  */
14
- async function swapUpdateTree(options) {
15
- const { target, staging } = options;
16
- if (dirname(staging) !== dirname(target) || staging === target) throw new Error("Invalid update swap context");
17
- const old = join(staging, "old");
18
- renameUpdateExclusive(target, old);
54
+ async function readUpdateTreeDigest(tree) {
55
+ const hash = createHash("sha256");
56
+ hash.update("adea-framework-update-tree\0v1\0", "utf8");
57
+ const root = await lstat(tree, { bigint: true });
58
+ if (!root.isDirectory() || root.isSymbolicLink()) throw new Error("Update tree is not a real directory");
59
+ const rootDevice = root.dev;
60
+ let entryCount = 0n;
61
+ const writeRecord = (kind, relative, mode, size, linkTarget) => {
62
+ const name = Buffer.from(relative, "utf8");
63
+ if (name.length > 4294967295) throw new Error("Update tree path is too long");
64
+ const tag = kind === "directory" ? 68 : kind === "file" ? 70 : 76;
65
+ const header = Buffer.allocUnsafe(5 + name.length + 4 + 8);
66
+ header.writeUInt8(tag, 0);
67
+ header.writeUInt32BE(name.length, 1);
68
+ name.copy(header, 5);
69
+ header.writeUInt32BE(Number(mode & 4095n), 5 + name.length);
70
+ header.writeBigUInt64BE(size, 9 + name.length);
71
+ hash.update(header);
72
+ if (linkTarget) {
73
+ hash.update(linkTarget);
74
+ hash.update(Buffer.from([0]));
75
+ }
76
+ entryCount++;
77
+ };
78
+ const visit = async (path, relative) => {
79
+ const before = await lstat(path, { bigint: true });
80
+ if (relative === "" && !sameTreeEntrySnapshot(root, before)) throw new Error("Update tree root changed before its digest was computed");
81
+ if (before.dev !== rootDevice) throw new Error("Update tree crosses a filesystem device");
82
+ if (before.isSymbolicLink()) {
83
+ const target = Buffer.from(await readlink(path), "utf8");
84
+ if (!sameTreeEntrySnapshot(before, await lstat(path, { bigint: true }))) throw new Error("Update tree changed while reading a symbolic link");
85
+ writeRecord("symlink", relative, before.mode, BigInt(target.length), target);
86
+ return;
87
+ }
88
+ if (before.isDirectory()) {
89
+ writeRecord("directory", relative, before.mode, 0n);
90
+ const names = (await readdir(path)).toSorted((left, right) => Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")));
91
+ for (const name of names) {
92
+ const child = relative ? `${relative}/${name}` : name;
93
+ await visit(join(path, name), child);
94
+ }
95
+ if (!sameTreeEntrySnapshot(before, await lstat(path, { bigint: true }))) throw new Error("Update tree changed while reading a directory");
96
+ return;
97
+ }
98
+ if (!before.isFile() || before.nlink !== 1n || before.size < 0n) throw new Error("Update tree contains an unsupported filesystem entry");
99
+ writeRecord("file", relative, before.mode, before.size);
100
+ const noFollow = constants$1.O_NOFOLLOW ?? 0;
101
+ const file = await open(path, constants$1.O_RDONLY | noFollow | (constants$1.O_NONBLOCK ?? 0));
102
+ try {
103
+ const opened = await file.stat({ bigint: true });
104
+ if (!opened.isFile() || !sameTreeEntrySnapshot(before, opened)) throw new Error("Update tree changed before a file could be read");
105
+ let bytesRead = 0n;
106
+ const buffer = Buffer.allocUnsafe(131072);
107
+ for (;;) {
108
+ const result = await file.read(buffer, 0, buffer.length, null);
109
+ if (result.bytesRead === 0) break;
110
+ bytesRead += BigInt(result.bytesRead);
111
+ hash.update(buffer.subarray(0, result.bytesRead));
112
+ }
113
+ const afterOpen = await file.stat({ bigint: true });
114
+ const afterPath = await lstat(path, { bigint: true });
115
+ if (bytesRead !== before.size || !sameTreeEntrySnapshot(opened, afterOpen) || !sameTreeEntrySnapshot(before, afterPath)) throw new Error("Update tree changed while reading a file");
116
+ } finally {
117
+ await file.close();
118
+ }
119
+ };
120
+ await visit(tree, "");
121
+ if (!sameTreeEntrySnapshot(root, await lstat(tree, { bigint: true }))) throw new Error("Update tree changed while its digest was computed");
122
+ const count = Buffer.allocUnsafe(8);
123
+ count.writeBigUInt64BE(entryCount);
124
+ hash.update(count);
125
+ return hash.digest("hex");
126
+ }
127
+ function sameUpdateTreeDigest(left, right) {
128
+ return typeof left === "string" && typeof right === "string" && /^[0-9a-f]{64}$/.test(left) && left === right;
129
+ }
130
+ /** Sync a directory's entries to disk. */
131
+ async function syncDirectoryPath(path) {
132
+ const directory = await open(path, constants$1.O_RDONLY);
19
133
  try {
20
- renameUpdateExclusive(join(staging, "candidate"), target);
21
- } catch (error) {
22
- renameUpdateExclusive(old, target);
23
- throw error;
134
+ await directory.sync();
135
+ } finally {
136
+ await directory.close();
24
137
  }
25
- await rm(old, {
26
- recursive: true,
27
- force: true
138
+ }
139
+ /** Sync candidate file contents and directory entries before a gated schema-3 exchange. */
140
+ async function syncUpdateTree(tree) {
141
+ const root = await lstat(tree);
142
+ if (!root.isDirectory()) throw new Error("Update tree changed while syncing");
143
+ const rootDevice = root.dev;
144
+ const syncEntry = async (path) => {
145
+ const info = await lstat(path);
146
+ if (info.isSymbolicLink()) return;
147
+ if (info.dev !== rootDevice) throw new Error("Update tree crosses a filesystem device");
148
+ if (info.isDirectory()) {
149
+ for (const name of await readdir(path)) await syncEntry(join(path, name));
150
+ await syncDirectoryPath(path);
151
+ return;
152
+ }
153
+ if (!info.isFile()) throw new Error("Update tree contains an unsupported filesystem entry");
154
+ const file = await open(path, constants$1.O_RDONLY | (constants$1.O_NOFOLLOW ?? 0));
155
+ try {
156
+ if (!(await file.stat()).isFile()) throw new Error("Update tree changed while syncing");
157
+ await file.sync();
158
+ } finally {
159
+ await file.close();
160
+ }
161
+ };
162
+ await syncEntry(tree);
163
+ const final = await lstat(tree);
164
+ if (!final.isDirectory() || final.dev !== rootDevice) throw new Error("Update tree changed while syncing");
165
+ }
166
+ /** Sync parent directory entries after the atomic exchange has completed. */
167
+ async function syncUpdateTreeParent(target) {
168
+ const directory = await open(dirname(target), constants$1.O_RDONLY);
169
+ try {
170
+ await directory.sync();
171
+ } finally {
172
+ await directory.close();
173
+ }
174
+ }
175
+ async function exists(path) {
176
+ return lstat(path).then(() => true, (error) => {
177
+ if (error.code === "ENOENT") return false;
178
+ throw error;
28
179
  });
29
180
  }
30
- export { swapUpdateTree, updateStagingFor };
181
+ async function assertDirectory(path) {
182
+ const info = await lstat(path);
183
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("Update exchange requires real directories");
184
+ }
185
+ /**
186
+ * Exchange the staged `candidate` and the install location atomically. The
187
+ * previous install remains at `staging/candidate` for journaled cleanup.
188
+ */
189
+ async function swapUpdateTree(options) {
190
+ return withUpdateLock(options.target, () => swapUpdateTreeWhileLocked(options));
191
+ }
192
+ /** Swap while the caller holds the per-install update lock. */
193
+ async function swapUpdateTreeWhileLocked(options, exchangeOperation = exchangeDirectories) {
194
+ const { target, staging } = options;
195
+ if (dirname(staging) !== dirname(target) || staging === target) throw new Error("Invalid update swap context");
196
+ const candidate = join(staging, "candidate");
197
+ if (await exists(join(staging, "old"))) throw new Error("A legacy update tree requires recovery before another swap");
198
+ await assertDirectory(target);
199
+ await assertDirectory(staging);
200
+ await assertDirectory(candidate);
201
+ const [previousVersion, candidateVersion, previousIdentity, candidateIdentity] = await Promise.all([
202
+ readUpdateTreeVersion(target),
203
+ readUpdateTreeVersion(candidate),
204
+ readUpdateTreeIdentity(target),
205
+ readUpdateTreeIdentity(candidate)
206
+ ]);
207
+ if (!previousVersion || !candidateVersion || !previousIdentity || !candidateIdentity || sameUpdateTreeIdentity(previousIdentity, candidateIdentity)) throw new Error("Update exchange requires identifiable versioned app trees");
208
+ await probeDirectoryExchange(dirname(target), exchangeOperation);
209
+ exchangeOperation(target, candidate);
210
+ await assertDirectory(target);
211
+ await assertDirectory(candidate);
212
+ const [nextTargetVersion, nextCandidateVersion, nextTargetId, nextCandidateId] = await Promise.all([
213
+ readUpdateTreeVersion(target),
214
+ readUpdateTreeVersion(candidate),
215
+ readUpdateTreeIdentity(target),
216
+ readUpdateTreeIdentity(candidate)
217
+ ]);
218
+ if (nextTargetVersion !== candidateVersion || nextCandidateVersion !== previousVersion || !sameUpdateTreeIdentity(nextTargetId, candidateIdentity) || !sameUpdateTreeIdentity(nextCandidateId, previousIdentity)) throw new Error("Atomic update exchange did not preserve both app trees");
219
+ }
220
+ export { readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, swapUpdateTree, swapUpdateTreeWhileLocked, syncUpdateTree, syncUpdateTreeParent, updateStagingFor, updateTreeIdentityFromStat };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adea-ai/app-framework",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,6 +29,8 @@
29
29
  "src/appearance",
30
30
  "src/desktop/client-assets.ts",
31
31
  "src/desktop/client-asset-stream.ts",
32
+ "src/desktop/client-response-lifecycle.ts",
33
+ "src/desktop/client-asset-manifest.ts",
32
34
  "src/native/*.patch",
33
35
  "src/native/renderer-profile.ts",
34
36
  "src/native/window-options.ts",
@@ -46,6 +48,10 @@
46
48
  "type": "module",
47
49
  "exports": {
48
50
  "./client-assets": "./src/desktop/client-assets.ts",
51
+ "./client-asset-manifest": {
52
+ "types": "./dist/desktop/client-asset-manifest.d.ts",
53
+ "import": "./dist/desktop/client-asset-manifest.js"
54
+ },
49
55
  "./update-state": "./src/updates/update-state.ts",
50
56
  "./window-options": "./src/native/window-options.ts",
51
57
  "./release-version": "./src/updates/release-version.ts",
@@ -254,6 +260,30 @@
254
260
  "types": "./dist/updates/update-manager.d.ts",
255
261
  "import": "./dist/updates/update-manager.js"
256
262
  },
263
+ "./update-launch-gate": {
264
+ "types": "./dist/updates/update-launch-gate.d.ts",
265
+ "import": "./dist/updates/update-launch-gate.js"
266
+ },
267
+ "./update-inherited-launch-lease": {
268
+ "types": "./dist/updates/update-inherited-launch-lease.d.ts",
269
+ "import": "./dist/updates/update-inherited-launch-lease.js"
270
+ },
271
+ "./packaged-release-config": {
272
+ "types": "./dist/updates/packaged-release-config.d.ts",
273
+ "import": "./dist/updates/packaged-release-config.js"
274
+ },
275
+ "./packaged-update-startup": {
276
+ "types": "./dist/updates/packaged-update-startup.d.ts",
277
+ "import": "./dist/updates/packaged-update-startup.js"
278
+ },
279
+ "./packaged-launch-admission": {
280
+ "types": "./dist/updates/packaged-launch-admission.d.ts",
281
+ "import": "./dist/updates/packaged-launch-admission.js"
282
+ },
283
+ "./update-resume": {
284
+ "types": "./dist/updates/update-resume.d.ts",
285
+ "import": "./dist/updates/update-resume.js"
286
+ },
257
287
  "./update-channel-store": {
258
288
  "types": "./dist/updates/update-channel-store.d.ts",
259
289
  "import": "./dist/updates/update-channel-store.js"
@@ -4,8 +4,8 @@
4
4
  * The import is deliberately permissive. A file may carry the published
5
5
  * canonical schema (17 surface roles plus an ANSI ramp) or any subset of it;
6
6
  * missing roles are filled from the default theme of the same appearance, and
7
- * text roles that cannot reach a readable contrast against their own
8
- * background are repaired, with every adjustment reported back to the UI
7
+ * text, primary and explicit component pairs that miss their contrast floors
8
+ * are repaired, with every adjustment reported back to the UI
9
9
  * instead of silently altering the palette. Nothing here enforces provenance
10
10
  * or distribution terms: an imported theme is the user's own copy for their
11
11
  * own machine.
@@ -160,19 +160,88 @@ function repairToFloor(
160
160
  foreground: string,
161
161
  background: string,
162
162
  notes: string[],
163
- role: string
163
+ role: string,
164
+ minimum = 4.5
164
165
  ): string {
165
166
  const front = parseHex(foreground)
166
167
  const back = parseHex(background)
167
168
  if (!front || !back) return foreground
168
- if (contrastRatio(front, back) >= 4.5) return foreground
169
- // The host repair loops contrast margins and falls back to a guaranteed
170
- // foreground, so an import can never ship unreadable text.
171
- const repaired = ensureContrast(front, back, 4.5)
169
+ if (contrastRatio(front, back) >= minimum) return foreground
170
+ // The shared repair accounts for rounding and falls back to a contrasting color.
171
+ const repaired = ensureContrast(front, back, minimum)
172
172
  notes.push(`“${role}” was adjusted for readable contrast.`)
173
173
  return colorToHex(repaired)
174
174
  }
175
175
 
176
+ /** Repair the explicit component pairs after either projection has chosen their surfaces. */
177
+ function repairComponentContrast(variant: ThemeVariant, notes: string[]): ThemeVariant {
178
+ const colors = variant.colors
179
+ return {
180
+ ...variant,
181
+ colors: {
182
+ ...colors,
183
+ cardForeground: repairToFloor(colors.cardForeground, colors.card, notes, 'card foreground'),
184
+ popoverForeground: repairToFloor(
185
+ colors.popoverForeground,
186
+ colors.popover,
187
+ notes,
188
+ 'popover foreground'
189
+ ),
190
+ secondaryForeground: repairToFloor(
191
+ colors.secondaryForeground,
192
+ colors.secondary,
193
+ notes,
194
+ 'secondary foreground'
195
+ ),
196
+ accentForeground: repairToFloor(
197
+ colors.accentForeground,
198
+ colors.accent,
199
+ notes,
200
+ 'highlight foreground'
201
+ ),
202
+ // Muted foreground is also used directly on the main background. Keep
203
+ // that already-repaired text and adjust its component surface instead.
204
+ muted: repairToFloor(colors.muted, colors.mutedForeground, notes, 'muted surface'),
205
+ },
206
+ }
207
+ }
208
+
209
+ /** Preserve accessible sidebar pairs that the catalogue record would otherwise re-derive. */
210
+ function sidebarTokens(variant: ThemeVariant, notes: string[]): Record<string, string> {
211
+ const colors = variant.colors
212
+ return {
213
+ '--sidebar': colors.card,
214
+ '--sidebar-foreground': repairToFloor(
215
+ colors.cardForeground,
216
+ colors.card,
217
+ notes,
218
+ 'sidebar foreground'
219
+ ),
220
+ '--sidebar-muted-foreground': repairToFloor(
221
+ colors.mutedForeground,
222
+ colors.card,
223
+ notes,
224
+ 'sidebar muted foreground'
225
+ ),
226
+ '--sidebar-accent': colors.accent,
227
+ '--sidebar-accent-foreground': repairToFloor(
228
+ colors.accentForeground,
229
+ colors.accent,
230
+ notes,
231
+ 'sidebar accent foreground'
232
+ ),
233
+ '--sidebar-border': colors.border,
234
+ '--sidebar-primary': colors.primary,
235
+ '--sidebar-primary-foreground': repairToFloor(
236
+ colors.primaryForeground,
237
+ colors.primary,
238
+ notes,
239
+ 'sidebar primary foreground'
240
+ ),
241
+ '--sidebar-ring': colors.ring,
242
+ }
243
+ }
244
+
176
245
  function hexOf(value: string): string {
177
246
  const parsed = parseOklchColor(value)
178
247
  return parsed ? oklchToHex(parsed) : value
@@ -338,13 +407,19 @@ function prepareCustomTheme(
338
407
  notes.push('Missing roles were filled from the default theme.')
339
408
  }
340
409
 
341
- // Body and terminal foreground roles must stay readable against the
342
- // background we actually ship. The shared shadcn projection consumes `text`
343
- // for body copy, while the terminal adapter consumes `foreground` directly.
410
+ // Repair text and primary roles before projecting them to the UI and terminal.
411
+ // The shadcn projection consumes `text`; the terminal uses `foreground`.
344
412
  colors.foreground = repairToFloor(colors.foreground!, colors.background!, notes, 'foreground')
345
413
  colors.text = repairToFloor(colors.text!, colors.background!, notes, 'text')
346
414
  colors.textMuted = repairToFloor(colors.textMuted!, colors.background!, notes, 'muted text')
347
415
  colors.textSubtle = repairToFloor(colors.textSubtle!, colors.background!, notes, 'subtle text')
416
+ colors.accent = repairToFloor(colors.accent!, colors.background!, notes, 'accent', 3)
417
+ colors.accentForeground = repairToFloor(
418
+ colors.accentForeground!,
419
+ colors.accent,
420
+ notes,
421
+ 'accent foreground'
422
+ )
348
423
 
349
424
  const ansiRecord = (record.ansi ?? {}) as Record<string, unknown>
350
425
  const ansi = ANSI_KEYS.map((key) => {
@@ -372,9 +447,10 @@ function prepareCustomTheme(
372
447
  } catch {
373
448
  // The adapters refuse unencodable roles; fall back to a direct host
374
449
  // projection so the import still succeeds with a warning.
375
- variant = projectHostFallback(name, appearance, canonical.colors, ansi)
450
+ variant = projectHostFallback(name, appearance, canonical.colors, ansi, notes)
376
451
  notes.push('Syntax roles were approximated from the ANSI ramp.')
377
452
  }
453
+ variant = repairComponentContrast(variant, notes)
378
454
  variant = { ...variant, id: uniqueThemeId(name, existing), name }
379
455
 
380
456
  const issues = validateThemeRegistry([variant]).filter((issue) => issue.severity === 'error')
@@ -386,7 +462,7 @@ function prepareCustomTheme(
386
462
  appearance,
387
463
  importedAt: new Date().toISOString(),
388
464
  variant,
389
- flatTokens: flatVariantTokens(variant),
465
+ flatTokens: { ...flatVariantTokens(variant), ...sidebarTokens(variant, notes) },
390
466
  notes,
391
467
  }
392
468
  return { ok: true, theme: stored }
@@ -423,7 +499,8 @@ function projectHostFallback(
423
499
  name: string,
424
500
  appearance: 'light' | 'dark',
425
501
  colors: AdeaTheme['colors'],
426
- ansi: readonly string[]
502
+ ansi: readonly string[],
503
+ notes: string[]
427
504
  ): ThemeVariant {
428
505
  const ramp = (index: number): string => ansi[index] ?? colors.foreground
429
506
  const editor = Object.fromEntries(
@@ -458,7 +535,12 @@ function projectHostFallback(
458
535
  accentForeground: colors.text,
459
536
  destructive: colors.error,
460
537
  destructiveAction: colors.error,
461
- destructiveActionForeground: colors.accentForeground,
538
+ destructiveActionForeground: repairToFloor(
539
+ colors.accentForeground,
540
+ colors.error,
541
+ notes,
542
+ 'destructive action foreground'
543
+ ),
462
544
  success: colors.success,
463
545
  border: colors.border,
464
546
  input: colors.border,
@@ -449,6 +449,11 @@ export function customThemeVariants(): readonly StoredThemeVariant[] {
449
449
  return library().themes.map((theme) => theme.variant)
450
450
  }
451
451
 
452
+ /** Find one stored variant without projecting the rest of the imported library. */
453
+ export function customThemeVariantById(id: string): StoredThemeVariant | undefined {
454
+ return library().themes.find((theme) => theme.variant.id === id)?.variant
455
+ }
456
+
452
457
  /** The imported themes as shared-provider variants: what the provider's `themes` takes. */
453
458
  export function customUiVariants(): readonly UiThemeVariant[] {
454
459
  const state = library()
@@ -18,7 +18,11 @@ import {
18
18
  } from '@adea-ai/ui/lib/themes'
19
19
 
20
20
  import { APPEARANCE_ACCENT_CONTRAST_FLOOR } from './appearance-preferences'
21
- import { customThemeVariants, storedVariantRecord } from './custom-theme-library'
21
+ import {
22
+ customThemeVariantById,
23
+ customThemeVariants,
24
+ storedVariantRecord,
25
+ } from './custom-theme-library'
22
26
  import { themeRegistry } from './theme-registry'
23
27
 
24
28
  const adeaLight = defaultThemeRecord('light')
@@ -80,12 +84,17 @@ export function appearanceThemeForPreview(
80
84
  accent: string,
81
85
  pair?: { lightThemeId: string; darkThemeId: string }
82
86
  ): AdeaTheme {
83
- // Imported themes have no catalogue record; their stored variant projects to
84
- // one on the spot, so every record takes the same accent overlay path.
87
+ // Resolve only the selected imported theme. Re-projecting every imported
88
+ // record here made each preview allocate work proportional to library size.
89
+ const catalogueRecord = themeRecordById(variant.id)
90
+ const importedVariant = catalogueRecord ? undefined : customThemeVariantById(variant.id)
85
91
  const record =
86
- themeRecordById(variant.id) ??
87
- customThemeRecords().find((candidate) => candidate.id === variant.id) ??
88
- (variant.appearance === 'dark' ? adeaDark : adeaLight)
92
+ catalogueRecord ??
93
+ (importedVariant
94
+ ? storedVariantRecord(importedVariant)
95
+ : variant.appearance === 'dark'
96
+ ? adeaDark
97
+ : adeaLight)
89
98
  return withAccent(record, accent, pair)
90
99
  }
91
100
 
@@ -6,6 +6,8 @@ import { builtinThemes, type ThemeVariant } from '@adea-ai/ui/lib/themes'
6
6
 
7
7
  import { customUiVariants } from './custom-theme-library'
8
8
 
9
+ const registriesByCustomVariants = new WeakMap<readonly ThemeVariant[], readonly ThemeVariant[]>()
10
+
9
11
  /**
10
12
  * Every selectable theme: the catalogue first, then imported themes.
11
13
  *
@@ -16,5 +18,10 @@ import { customUiVariants } from './custom-theme-library'
16
18
  */
17
19
  export function themeRegistry(): readonly ThemeVariant[] {
18
20
  const custom = customUiVariants()
19
- return custom.length > 0 ? [...builtinThemes, ...custom] : builtinThemes
21
+ if (custom.length === 0) return builtinThemes
22
+ const cached = registriesByCustomVariants.get(custom)
23
+ if (cached) return cached
24
+ const registry = [...builtinThemes, ...custom]
25
+ registriesByCustomVariants.set(custom, registry)
26
+ return registry
20
27
  }