@adea-ai/app-framework 0.37.0 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/appearance/appearance-host.js +2 -1
  2. package/dist/appearance/custom-theme-import.js +3 -1
  3. package/dist/appearance/custom-theme-library.d.ts +6 -185
  4. package/dist/appearance/custom-theme-library.js +3 -621
  5. package/dist/appearance/theme-library-mutation.d.ts +42 -0
  6. package/dist/appearance/theme-library-mutation.js +172 -0
  7. package/dist/appearance/theme-library-schema.d.ts +108 -0
  8. package/dist/appearance/theme-library-schema.js +189 -0
  9. package/dist/appearance/theme-library-store.d.ts +61 -0
  10. package/dist/appearance/theme-library-store.js +268 -0
  11. package/dist/appearance/theme-record-adapter.js +3 -1
  12. package/dist/appearance/theme-registry.js +2 -1
  13. package/dist/cli/update-helper-cli.js +1 -1
  14. package/dist/desktop/desktop-client.d.ts +1 -1
  15. package/dist/framework-source.json +1 -1
  16. package/dist/installer/installed-payload.js +2 -2
  17. package/dist/installer/{installer-archive.js → installer-archive-members.js} +2 -2
  18. package/dist/installer/installer-extraction.js +2 -2
  19. package/dist/installer/installer-fetch-guard.d.ts +1 -1
  20. package/dist/installer/installer-identity.js +2 -2
  21. package/dist/installer/installer-observation.d.ts +1 -1
  22. package/dist/installer/installer-observation.js +2 -2
  23. package/dist/installer/installer-upgrade-command.d.ts +2 -2
  24. package/dist/installer/installer-upgrade-command.js +5 -5
  25. package/dist/installer/linux-process-group.js +1 -1
  26. package/dist/installer/upgrade-asset-download.d.ts +1 -1
  27. package/dist/installer/upgrade-asset-download.js +2 -2
  28. package/dist/native/posix-tree-removal.d.ts +1 -1
  29. package/dist/release/feed-release-cut.d.ts +1 -1
  30. package/dist/release/feed-state.d.ts +2 -2
  31. package/dist/release/feed-state.js +3 -3
  32. package/dist/release/github-release-cut.js +1 -1
  33. package/dist/release/github-release-promotion.js +1 -1
  34. package/dist/release/github-release-publisher.js +1 -1
  35. package/dist/release/github-release-qualification.js +1 -1
  36. package/dist/release/local-release.d.ts +2 -2
  37. package/dist/release/local-release.js +3 -3
  38. package/dist/release/release-artifact.d.ts +1 -1
  39. package/dist/release/release-artifact.js +2 -2
  40. package/dist/release/release-assets-plan.js +1 -1
  41. package/dist/release/release-config.d.ts +1 -1
  42. package/dist/release/release-config.js +1 -1
  43. package/dist/release/release-descriptor-staging.js +3 -3
  44. package/dist/release/release-finalize.js +1 -1
  45. package/dist/release/release-promotion.js +1 -1
  46. package/dist/release/release-publication.d.ts +1 -1
  47. package/dist/release/release-publication.js +2 -2
  48. package/dist/release/release-publish-command.js +2 -2
  49. package/dist/update-helper.bundle.js +18 -18
  50. package/dist/updates/channel-update-manager.d.ts +3 -3
  51. package/dist/updates/channel-update-manager.js +2 -2
  52. package/dist/updates/desktop-updater.d.ts +10 -83
  53. package/dist/updates/desktop-updater.js +14 -217
  54. package/dist/updates/{packaged-release-config.js → feed/packaged-release-config.js} +5 -5
  55. package/dist/updates/{release-feed.js → feed/release-feed.js} +2 -2
  56. package/dist/updates/{release-location.js → feed/release-location.js} +2 -2
  57. package/dist/updates/{release-version.js → feed/release-version.js} +1 -1
  58. package/dist/updates/{signed-release.js → feed/signed-release.js} +2 -2
  59. package/dist/updates/{update-discovery.js → feed/update-discovery.js} +1 -1
  60. package/dist/updates/helper/launch-gate-recovery.d.ts +8 -0
  61. package/dist/updates/{update-resume.js → helper/launch-gate-recovery.js} +13 -423
  62. package/dist/updates/helper/resume-staging.d.ts +22 -0
  63. package/dist/updates/helper/resume-staging.js +180 -0
  64. package/dist/updates/{update-helper.d.ts → helper/update-helper.d.ts} +1 -1
  65. package/dist/updates/{update-helper.js → helper/update-helper.js} +9 -9
  66. package/dist/updates/{update-resume.d.ts → helper/update-resume.d.ts} +4 -10
  67. package/dist/updates/helper/update-resume.js +252 -0
  68. package/dist/updates/{update-shutdown.js → helper/update-shutdown.js} +2 -2
  69. package/dist/updates/{update-arm.d.ts → install/update-arm.d.ts} +2 -2
  70. package/dist/updates/{update-arm.js → install/update-arm.js} +9 -9
  71. package/dist/updates/{update-download-cleanup.d.ts → install/update-download-cleanup.d.ts} +1 -1
  72. package/dist/updates/{update-download-cleanup.js → install/update-download-cleanup.js} +3 -3
  73. package/dist/updates/{update-download.d.ts → install/update-download.d.ts} +2 -2
  74. package/dist/updates/{update-download.js → install/update-download.js} +3 -3
  75. package/dist/updates/{update-extraction.d.ts → install/update-extraction.d.ts} +2 -2
  76. package/dist/updates/{update-extraction.js → install/update-extraction.js} +6 -6
  77. package/dist/updates/{update-handoff-plan.d.ts → install/update-handoff-plan.d.ts} +2 -2
  78. package/dist/updates/{update-handoff-plan.js → install/update-handoff-plan.js} +5 -5
  79. package/dist/updates/{update-marker.js → install/update-marker.js} +2 -2
  80. package/dist/updates/{update-swap-stage.d.ts → install/update-swap-stage.d.ts} +2 -2
  81. package/dist/updates/{update-swap-stage.js → install/update-swap-stage.js} +7 -6
  82. package/dist/updates/{update-swap.d.ts → install/update-swap.d.ts} +1 -1
  83. package/dist/updates/{update-swap.js → install/update-swap.js} +5 -5
  84. package/dist/updates/install-target.d.ts +8 -0
  85. package/dist/updates/install-target.js +27 -0
  86. package/dist/updates/{launch-environment.js → launch/launch-environment.js} +1 -1
  87. package/dist/updates/{packaged-launch-admission.js → launch/packaged-launch-admission.js} +4 -4
  88. package/dist/updates/{packaged-update-startup.d.ts → launch/packaged-update-startup.d.ts} +3 -3
  89. package/dist/updates/{packaged-update-startup.js → launch/packaged-update-startup.js} +10 -7
  90. package/dist/updates/{update-launch-gate.d.ts → launch/update-launch-gate.d.ts} +1 -1
  91. package/dist/updates/{update-launch-gate.js → launch/update-launch-gate.js} +9 -9
  92. package/dist/updates/{update-launch.d.ts → launch/update-launch.d.ts} +1 -1
  93. package/dist/updates/{update-launch.js → launch/update-launch.js} +2 -2
  94. package/dist/updates/{linux-process-state.js → locks/linux-process-state.js} +1 -1
  95. package/dist/updates/{native-file-lock.js → locks/native-file-lock.js} +1 -1
  96. package/dist/updates/{stable-file.js → locks/stable-file.js} +2 -2
  97. package/dist/updates/{update-download-lock.js → locks/update-download-lock.js} +1 -1
  98. package/dist/updates/{update-generation-lease.js → locks/update-generation-lease.js} +3 -3
  99. package/dist/updates/{update-inherited-launch-lease.d.ts → locks/update-inherited-launch-lease.d.ts} +1 -1
  100. package/dist/updates/{update-inherited-launch-lease.js → locks/update-inherited-launch-lease.js} +2 -2
  101. package/dist/updates/{update-instance-lease.js → locks/update-instance-lease.js} +2 -2
  102. package/dist/updates/{update-lock.js → locks/update-lock.js} +2 -2
  103. package/dist/updates/{update-process-fence.js → locks/update-process-fence.js} +3 -3
  104. package/dist/updates/{update-process-liveness.js → locks/update-process-liveness.js} +2 -2
  105. package/dist/updates/retained-client-assets.d.ts +60 -0
  106. package/dist/updates/retained-client-assets.js +116 -0
  107. package/dist/updates/retention/retention-cleanup.d.ts +103 -0
  108. package/dist/updates/retention/retention-cleanup.js +439 -0
  109. package/dist/updates/retention/retention-prune-progress.d.ts +27 -0
  110. package/dist/updates/retention/retention-prune-progress.js +203 -0
  111. package/dist/updates/retention/retirement-inventory.d.ts +93 -0
  112. package/dist/updates/retention/retirement-inventory.js +373 -0
  113. package/dist/updates/retention/retirement-records.d.ts +75 -0
  114. package/dist/updates/retention/retirement-records.js +309 -0
  115. package/dist/updates/{update-retention-marker.d.ts → retention/update-retention-marker.d.ts} +1 -1
  116. package/dist/updates/{update-retention-marker.js → retention/update-retention-marker.js} +3 -3
  117. package/dist/updates/{update-retention-plan.d.ts → retention/update-retention-plan.d.ts} +1 -1
  118. package/dist/updates/{update-retention-plan.js → retention/update-retention-plan.js} +2 -2
  119. package/dist/updates/{update-retention-sync.d.ts → retention/update-retention-sync.d.ts} +1 -1
  120. package/dist/updates/{update-retention-sync.js → retention/update-retention-sync.js} +2 -2
  121. package/dist/updates/retention/update-retirement.d.ts +26 -0
  122. package/dist/updates/retention/update-retirement.js +205 -0
  123. package/dist/updates/update-adapter.js +1 -1
  124. package/dist/updates/update-channel-store.d.ts +1 -1
  125. package/dist/updates/update-channel-store.js +2 -2
  126. package/dist/updates/update-manager.d.ts +4 -4
  127. package/dist/updates/update-manager.js +5 -5
  128. package/dist/updates/update-services.d.ts +15 -0
  129. package/dist/updates/update-services.js +77 -0
  130. package/dist/updates/update-state-store.d.ts +2 -2
  131. package/dist/updates/update-state-store.js +2 -2
  132. package/dist/views/appearance-surface.js +3 -1
  133. package/package.json +29 -29
  134. package/src/appearance/custom-theme-library.ts +42 -956
  135. package/src/appearance/theme-library-mutation.ts +288 -0
  136. package/src/appearance/theme-library-schema.ts +347 -0
  137. package/src/appearance/theme-library-store.ts +379 -0
  138. package/src/updates/update-adapter.ts +1 -1
  139. package/dist/updates/update-retirement.d.ts +0 -205
  140. package/dist/updates/update-retirement.js +0 -1485
  141. /package/dist/installer/{installer-archive.d.ts → installer-archive-members.d.ts} +0 -0
  142. /package/dist/updates/{packaged-release-config.d.ts → feed/packaged-release-config.d.ts} +0 -0
  143. /package/dist/updates/{release-feed.d.ts → feed/release-feed.d.ts} +0 -0
  144. /package/dist/updates/{release-location.d.ts → feed/release-location.d.ts} +0 -0
  145. /package/dist/updates/{release-version.d.ts → feed/release-version.d.ts} +0 -0
  146. /package/dist/updates/{signed-release.d.ts → feed/signed-release.d.ts} +0 -0
  147. /package/dist/updates/{update-discovery.d.ts → feed/update-discovery.d.ts} +0 -0
  148. /package/dist/updates/{update-shutdown.d.ts → helper/update-shutdown.d.ts} +0 -0
  149. /package/dist/updates/{update-marker.d.ts → install/update-marker.d.ts} +0 -0
  150. /package/dist/updates/{launch-environment.d.ts → launch/launch-environment.d.ts} +0 -0
  151. /package/dist/updates/{packaged-launch-admission.d.ts → launch/packaged-launch-admission.d.ts} +0 -0
  152. /package/dist/updates/{linux-process-state.d.ts → locks/linux-process-state.d.ts} +0 -0
  153. /package/dist/updates/{native-file-lock.d.ts → locks/native-file-lock.d.ts} +0 -0
  154. /package/dist/updates/{stable-file.d.ts → locks/stable-file.d.ts} +0 -0
  155. /package/dist/updates/{update-download-lock.d.ts → locks/update-download-lock.d.ts} +0 -0
  156. /package/dist/updates/{update-generation-lease.d.ts → locks/update-generation-lease.d.ts} +0 -0
  157. /package/dist/updates/{update-instance-lease.d.ts → locks/update-instance-lease.d.ts} +0 -0
  158. /package/dist/updates/{update-lock.d.ts → locks/update-lock.d.ts} +0 -0
  159. /package/dist/updates/{update-process-fence.d.ts → locks/update-process-fence.d.ts} +0 -0
  160. /package/dist/updates/{update-process-liveness.d.ts → locks/update-process-liveness.d.ts} +0 -0
  161. /package/src/updates/{release-version.ts → feed/release-version.ts} +0 -0
@@ -0,0 +1,288 @@
1
+ /*
2
+ * Copyright (c) 2026 Wing
3
+ * Licensed under the MIT License.
4
+ *
5
+ * The custom theme library keeps the registry-validation rules of Adea's accepted
6
+ * port of Zeron's theme registry (https://github.com/zeronsh/zeron). The library is
7
+ * Adea's own product schema (declared-license imports, a stored `variant` per
8
+ * theme); the shared ThemeProvider receives it as extra variants. See NOTICE and
9
+ * the repository history for source and behavior provenance.
10
+ */
11
+ import type { CustomThemeStored } from './theme-library-schema'
12
+ import {
13
+ type AppearanceStorage,
14
+ CUSTOM_THEME_LIBRARY_STORAGE_KEY,
15
+ CUSTOM_THEME_LIBRARY_VERSION,
16
+ library,
17
+ namespaceCustomThemes,
18
+ notifyCustomThemes,
19
+ parseLibrary,
20
+ preserveLibrary,
21
+ replaceThemes,
22
+ setCustomThemes,
23
+ } from './theme-library-store'
24
+
25
+ /** A cross-context lock used to serialize theme-library read/modify/write operations. */
26
+ export type ThemeLibraryAtomicLock = Readonly<{
27
+ withExclusiveLock<T>(name: string, operation: () => T): Promise<T>
28
+ }>
29
+
30
+ export type ThemeLibraryMutationOptions = Readonly<{
31
+ /** Override the browser lock provider in tests or embedder adapters. `null` means unavailable. */
32
+ lock?: ThemeLibraryAtomicLock | null
33
+ }>
34
+
35
+ export type ThemeLibraryMutation<T> = Readonly<{
36
+ themes: readonly CustomThemeStored[]
37
+ value: T
38
+ /** Leave storage and subscribers untouched for rejected or idempotent operations. */
39
+ commit?: boolean
40
+ }>
41
+
42
+ export type ThemeLibraryMutationFailureReason =
43
+ | 'atomic_unavailable'
44
+ | 'storage_failed'
45
+ | 'recovery_unavailable'
46
+ | 'changed_during_mutation'
47
+
48
+ export type ThemeLibraryMutationResult<T> =
49
+ | { ok: true; committed: boolean; value: T }
50
+ | { ok: false; reason: ThemeLibraryMutationFailureReason; error: string }
51
+
52
+ /** Origin-wide lock name shared by all cooperating framework builds. */
53
+ export const CUSTOM_THEME_LIBRARY_LOCK_NAME = 'adea:appearance.library:mutation:v1'
54
+
55
+ const CUSTOM_THEME_LIBRARY_LOCK_DB = 'adea:appearance-library-coordination:v1'
56
+
57
+ const CUSTOM_THEME_LIBRARY_LOCK_STORE = 'locks'
58
+
59
+ export const CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE =
60
+ 'This app cannot safely save theme changes in this environment. Your library was not changed.'
61
+
62
+ export const CUSTOM_THEME_LIBRARY_MUTATION_FAILED =
63
+ 'The theme could not be saved. Check your storage and try again.'
64
+
65
+ /*
66
+ * Registry validation, ported from Zeron `ThemeRegistry::validate`: core text and
67
+ * muted text must reach 4.5:1, the accent 3:1, on-accent 4.5:1, the terminal
68
+ * foreground 4.5:1, and every chromatic ANSI slot 3:1 (slots 0 and 8 are
69
+ * structural black/dim colors). Import runs it over the one variant it just built.
70
+ */
71
+
72
+ function withIndexedDbMutationLock<T>(name: string, operation: () => T): Promise<T> {
73
+ const factory = globalThis.indexedDB
74
+ if (!factory) return Promise.reject(new Error('IndexedDB is unavailable'))
75
+
76
+ return new Promise<T>((resolve, reject) => {
77
+ const open = factory.open(CUSTOM_THEME_LIBRARY_LOCK_DB, 1)
78
+ open.addEventListener('upgradeneeded', () => {
79
+ if (!open.result.objectStoreNames.contains(CUSTOM_THEME_LIBRARY_LOCK_STORE))
80
+ open.result.createObjectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE)
81
+ })
82
+ open.addEventListener('error', () =>
83
+ reject(open.error ?? new Error('Could not open theme coordination database'))
84
+ )
85
+ open.addEventListener('success', () => {
86
+ const database = open.result
87
+ database.addEventListener('versionchange', () => database.close())
88
+ let transaction: IDBTransaction
89
+ try {
90
+ transaction = database.transaction(CUSTOM_THEME_LIBRARY_LOCK_STORE, 'readwrite')
91
+ } catch (error) {
92
+ database.close()
93
+ reject(error)
94
+ return
95
+ }
96
+
97
+ let result: T
98
+ let ran = false
99
+ let operationError: unknown
100
+ const close = () => database.close()
101
+ transaction.addEventListener('complete', () => {
102
+ close()
103
+ if (operationError !== undefined) reject(operationError)
104
+ else if (ran) resolve(result)
105
+ else reject(new Error('Theme library lock transaction did not run'))
106
+ })
107
+ transaction.addEventListener('abort', () => {
108
+ close()
109
+ // This transaction is only the cross-context mutex; it does not store
110
+ // application data. If the synchronous critical section completed, it
111
+ // already verified the localStorage result before the abort event could
112
+ // run. Report that result rather than claiming the persisted mutation
113
+ // failed after it and its notifications have already committed.
114
+ if (ran) {
115
+ resolve(result)
116
+ return
117
+ }
118
+ reject(
119
+ operationError ?? transaction.error ?? new Error('Theme library lock transaction aborted')
120
+ )
121
+ })
122
+
123
+ try {
124
+ const lockRequest = transaction.objectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE).get(name)
125
+ lockRequest.addEventListener('success', () => {
126
+ try {
127
+ // Keep the read/write transaction active while the synchronous localStorage
128
+ // read/modify/write runs. IndexedDB serializes overlapping transactions
129
+ // across WebViews even where their Web Lock managers are not shared.
130
+ result = operation()
131
+ ran = true
132
+ } catch (error) {
133
+ operationError = error
134
+ transaction.abort()
135
+ }
136
+ })
137
+ } catch (error) {
138
+ operationError = error
139
+ transaction.abort()
140
+ }
141
+ })
142
+ })
143
+ }
144
+
145
+ function browserThemeLibraryAtomicLock(): ThemeLibraryAtomicLock | undefined {
146
+ if (!globalThis.indexedDB) return undefined
147
+ const locks = globalThis.navigator?.locks
148
+ return {
149
+ withExclusiveLock: (name, operation) =>
150
+ locks && typeof locks.request === 'function'
151
+ ? locks.request(name, { mode: 'exclusive' }, () =>
152
+ withIndexedDbMutationLock(name, operation)
153
+ )
154
+ : withIndexedDbMutationLock(name, operation),
155
+ }
156
+ }
157
+
158
+ function mutationFailure<T>(
159
+ reason: ThemeLibraryMutationFailureReason,
160
+ error: string
161
+ ): ThemeLibraryMutationResult<T> {
162
+ return { ok: false, reason, error }
163
+ }
164
+
165
+ /**
166
+ * Coordinate a storage-backed library read/modify/write across cooperating contexts.
167
+ * The callback reads the current v1 record while holding an origin-wide IndexedDB
168
+ * read/write transaction (and a Web Lock where available), then writes and verifies
169
+ * the v1 record before updating this tab's in-memory registry. Older builds and
170
+ * direct `setCustomThemes` storage writes do not acquire these locks and can still
171
+ * race; this API does not claim cross-version atomicity. If IndexedDB is unavailable,
172
+ * durable mutations fail closed.
173
+ */
174
+ export async function mutateCustomThemeLibrary<T>(
175
+ storage: AppearanceStorage | undefined,
176
+ update: (themes: readonly CustomThemeStored[]) => ThemeLibraryMutation<T>,
177
+ options: ThemeLibraryMutationOptions = {}
178
+ ): Promise<ThemeLibraryMutationResult<T>> {
179
+ if (!storage) {
180
+ try {
181
+ const mutation = update(library().themes)
182
+ if (mutation.commit === false) return { ok: true, committed: false, value: mutation.value }
183
+ const safe = namespaceCustomThemes(mutation.themes)
184
+ if (!setCustomThemes(safe, undefined))
185
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
186
+ return { ok: true, committed: true, value: mutation.value }
187
+ } catch {
188
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
189
+ }
190
+ }
191
+
192
+ const lock = options.lock === undefined ? browserThemeLibraryAtomicLock() : options.lock
193
+ if (!lock) return mutationFailure('atomic_unavailable', CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE)
194
+
195
+ let enteredLock = false
196
+ try {
197
+ return await lock.withExclusiveLock(CUSTOM_THEME_LIBRARY_LOCK_NAME, () => {
198
+ enteredLock = true
199
+ const state = library()
200
+ state.atomicMutationDepth = (state.atomicMutationDepth ?? 0) + 1
201
+ try {
202
+ let raw: string | null
203
+ let themes: readonly CustomThemeStored[]
204
+ try {
205
+ raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY)
206
+ const parsed = raw ? parseLibrary(raw) : { themes: [] as CustomThemeStored[] }
207
+ themes = parsed.themes
208
+ if (raw && parsed.reason && !preserveLibrary(storage, raw, parsed.reason))
209
+ return mutationFailure(
210
+ 'recovery_unavailable',
211
+ 'The stored theme library could not be preserved, so this change was not saved.'
212
+ )
213
+ // Detect synchronous/reentrant adapters that change the record while it
214
+ // is read. The shared lock covers current builds; this check also exposes
215
+ // adapters and old clients that bypass it without claiming a CAS.
216
+ if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw)
217
+ return mutationFailure(
218
+ 'changed_during_mutation',
219
+ 'The theme library changed while it was being read. Try again.'
220
+ )
221
+ } catch {
222
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
223
+ }
224
+
225
+ let mutation: ThemeLibraryMutation<T>
226
+ try {
227
+ mutation = update(themes)
228
+ // The updater is synchronous, but an older build can still write
229
+ // localStorage outside this lock while the callback runs. Recheck before
230
+ // committing so a snapshot changed during update is not overwritten.
231
+ if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw)
232
+ return mutationFailure(
233
+ 'changed_during_mutation',
234
+ 'The theme library changed while this change was being prepared. Try again.'
235
+ )
236
+ } catch {
237
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
238
+ }
239
+ if (mutation.commit === false) return { ok: true, committed: false, value: mutation.value }
240
+
241
+ const safe = namespaceCustomThemes(mutation.themes)
242
+ const serialized = JSON.stringify({ version: CUSTOM_THEME_LIBRARY_VERSION, themes: safe })
243
+ try {
244
+ storage.setItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY, serialized)
245
+ if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== serialized)
246
+ return mutationFailure(
247
+ 'changed_during_mutation',
248
+ 'The theme library changed while it was being saved. Try again.'
249
+ )
250
+ } catch {
251
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
252
+ }
253
+
254
+ replaceThemes(safe)
255
+ notifyCustomThemes()
256
+ return { ok: true, committed: true, value: mutation.value }
257
+ } finally {
258
+ state.atomicMutationDepth = Math.max(0, (state.atomicMutationDepth ?? 1) - 1)
259
+ }
260
+ })
261
+ } catch {
262
+ return mutationFailure(
263
+ enteredLock ? 'storage_failed' : 'atomic_unavailable',
264
+ enteredLock ? CUSTOM_THEME_LIBRARY_MUTATION_FAILED : CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE
265
+ )
266
+ }
267
+ }
268
+
269
+ /** Remove from the latest persisted snapshot, not a possibly stale UI snapshot. */
270
+ export async function removeCustomThemeAtomically(
271
+ id: string,
272
+ storage: AppearanceStorage | undefined,
273
+ options: ThemeLibraryMutationOptions = {}
274
+ ): Promise<ThemeLibraryMutationResult<boolean>> {
275
+ return mutateCustomThemeLibrary(
276
+ storage,
277
+ (themes) => {
278
+ const remaining = themes.filter((theme) => theme.id !== id)
279
+ return {
280
+ themes: remaining,
281
+ value: true,
282
+ // Removing an already-removed id is a successful idempotent operation.
283
+ commit: remaining.length !== themes.length,
284
+ }
285
+ },
286
+ options
287
+ )
288
+ }
@@ -0,0 +1,347 @@
1
+ /*
2
+ * Copyright (c) 2026 Wing
3
+ * Licensed under the MIT License.
4
+ *
5
+ * The custom theme library keeps the registry-validation rules of Adea's accepted
6
+ * port of Zeron's theme registry (https://github.com/zeronsh/zeron). The library is
7
+ * Adea's own product schema (declared-license imports, a stored `variant` per
8
+ * theme); the shared ThemeProvider receives it as extra variants. See NOTICE and
9
+ * the repository history for source and behavior provenance.
10
+ */
11
+ import type { AdeaTheme, AdeaThemeRecord } from '@adea-ai/ui/lib/theme-records'
12
+ import { contrastRatio } from '@adea-ai/ui/lib/accent-roles'
13
+ import { defaultVariantFor } from '@adea-ai/ui/lib/theme-defaults'
14
+ import { variantFromRecord } from '@adea-ai/ui/lib/theme-records'
15
+ import type { ThemeVariant as UiThemeVariant } from '@adea-ai/ui/lib/themes'
16
+ import { LEGACY_IMPORTED_THEME_TOKEN_PROJECTION_FALLBACKS } from './legacy-imported-theme-token-projection'
17
+
18
+ export type StoredThemeAppearance = 'light' | 'dark'
19
+
20
+ export type StoredThemeTerminal = Readonly<{
21
+ background: string
22
+ foreground: string
23
+ cursor: string
24
+ selection: string
25
+ /** The 16 xterm ANSI slots, in protocol order. */
26
+ ansi: readonly string[]
27
+ }>
28
+
29
+ export type StoredThemeEditorRoles = Readonly<{
30
+ keyword: string
31
+ string: string
32
+ number: string
33
+ comment: string
34
+ function: string
35
+ variable: string
36
+ type: string
37
+ tag: string
38
+ attribute: string
39
+ operator: string
40
+ heading: string
41
+ link: string
42
+ diffAdd: string
43
+ diffDelete: string
44
+ diffHunk: string
45
+ searchMatch: string
46
+ }>
47
+
48
+ export type StoredThemeChartRoles = Readonly<{
49
+ chart1: string
50
+ chart2: string
51
+ chart3: string
52
+ chart4: string
53
+ chart5: string
54
+ chart6: string
55
+ }>
56
+
57
+ export type StoredThemeColors = Readonly<{
58
+ background: string
59
+ foreground: string
60
+ card: string
61
+ cardForeground: string
62
+ popover: string
63
+ popoverForeground: string
64
+ primary: string
65
+ primaryForeground: string
66
+ secondary: string
67
+ secondaryForeground: string
68
+ muted: string
69
+ mutedForeground: string
70
+ accent: string
71
+ accentForeground: string
72
+ destructive: string
73
+ destructiveAction: string
74
+ destructiveActionForeground: string
75
+ success: string
76
+ border: string
77
+ input: string
78
+ ring: string
79
+ }>
80
+
81
+ /** The variant shape the library has always stored for an imported theme. */
82
+ export type StoredThemeVariant = Readonly<{
83
+ id: string
84
+ familyId: string
85
+ familyName: string
86
+ name: string
87
+ appearance: StoredThemeAppearance
88
+ colors: StoredThemeColors
89
+ terminal: StoredThemeTerminal
90
+ editor: StoredThemeEditorRoles
91
+ charts: StoredThemeChartRoles
92
+ }>
93
+
94
+ export type CustomThemeStored = Readonly<{
95
+ /** Stable id, namespaced so it can never collide with a catalogue id. */
96
+ id: string
97
+ name: string
98
+ appearance: StoredThemeAppearance
99
+ importedAt: string
100
+ variant: StoredThemeVariant
101
+ /** The verbatim imported map; projection may supply absent sources from `variant`. */
102
+ flatTokens: Readonly<Record<string, string>>
103
+ /** Non-fatal adjustments made while normalizing the file, for the UI. */
104
+ notes: readonly string[]
105
+ }>
106
+
107
+ export type ValidationIssue = Readonly<{
108
+ variantId: string
109
+ severity: 'error' | 'warning'
110
+ message: string
111
+ }>
112
+
113
+ export function validateThemeRegistry(registry: readonly StoredThemeVariant[]): ValidationIssue[] {
114
+ const issues: ValidationIssue[] = []
115
+ const seen = new Set<string>()
116
+ for (const variant of registry) {
117
+ if (variant.id.trim().length === 0 || seen.has(variant.id)) {
118
+ issues.push({
119
+ variantId: variant.id,
120
+ severity: 'error',
121
+ message: 'variant id must be unique',
122
+ })
123
+ }
124
+ seen.add(variant.id)
125
+ const check = (role: string, foreground: string, background: string, minimum: number) => {
126
+ const actual = contrastRatio(foreground, background)
127
+ if (actual < minimum) {
128
+ issues.push({
129
+ variantId: variant.id,
130
+ severity: 'error',
131
+ message: `${role} contrast is ${actual.toFixed(2)}:1; expected ${minimum.toFixed(1)}:1`,
132
+ })
133
+ }
134
+ }
135
+ check('text', variant.colors.foreground, variant.colors.background, 4.5)
136
+ check('muted text', variant.colors.mutedForeground, variant.colors.background, 4.5)
137
+ check('primary', variant.colors.primary, variant.colors.background, 3)
138
+ check('on-primary', variant.colors.primaryForeground, variant.colors.primary, 4.5)
139
+ check('terminal foreground', variant.terminal.foreground, variant.terminal.background, 4.5)
140
+ for (const [index, color] of variant.terminal.ansi.entries()) {
141
+ if (index % 8 === 0) continue
142
+ const actual = contrastRatio(color, variant.terminal.background)
143
+ if (actual < 3) {
144
+ issues.push({
145
+ variantId: variant.id,
146
+ severity: 'warning',
147
+ message: `terminal ANSI slot ${index} is below 3:1`,
148
+ })
149
+ }
150
+ }
151
+ check('editor comment', variant.editor.comment, variant.colors.background, 4.5)
152
+ check('diff delete', variant.editor.diffDelete, variant.colors.background, 3)
153
+ check('diff add', variant.editor.diffAdd, variant.colors.background, 3)
154
+ }
155
+ return issues
156
+ }
157
+
158
+ /*
159
+ * The flat token map: the custom properties an imported theme owns. It is stored
160
+ * with the theme (`flatTokens`) so the pre-paint script can apply it without the
161
+ * library's code, and the provider writes it verbatim over everything it derives.
162
+ */
163
+
164
+ const ANSI_NAMES = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
165
+
166
+ function kebabCase(value: string): string {
167
+ return value.replaceAll(/[A-Z]/g, (character) => `-${character.toLocaleLowerCase()}`)
168
+ }
169
+
170
+ function terminalTokens(palette: StoredThemeTerminal): Record<string, string> {
171
+ const tokens: Record<string, string> = {
172
+ '--terminal-background': palette.background,
173
+ '--terminal-foreground': palette.foreground,
174
+ '--terminal-cursor': palette.cursor,
175
+ '--terminal-selection': palette.selection,
176
+ }
177
+ for (const [index, color] of palette.ansi.entries()) {
178
+ const name = ANSI_NAMES[index % 8]!
179
+ tokens[index < 8 ? `--terminal-ansi-${name}` : `--terminal-ansi-bright-${name}`] = color
180
+ }
181
+ return tokens
182
+ }
183
+
184
+ /** The custom properties an imported variant owns, as a flat map. */
185
+ export function flatVariantTokens(variant: StoredThemeVariant): Record<string, string> {
186
+ const tokens: Record<string, string> = {}
187
+ for (const [role, value] of Object.entries(variant.colors)) {
188
+ tokens[`--${kebabCase(role)}`] = value
189
+ }
190
+ Object.assign(tokens, terminalTokens(variant.terminal))
191
+ for (const [role, value] of Object.entries(variant.editor)) {
192
+ tokens[`--editor-${kebabCase(role)}`] = value
193
+ }
194
+ for (const [index, value] of Object.values(variant.charts).entries()) {
195
+ tokens[`--chart-${index + 1}`] = value
196
+ }
197
+ return tokens
198
+ }
199
+
200
+ /*
201
+ * The shared variant for a stored theme.
202
+ *
203
+ * The stored variant is lossy against the catalogue's record shape (it has no
204
+ * warning, info or hover roles), so the record is reconstructed from it, the same
205
+ * reconstruction the appearance editor previews. The shared provider derives what
206
+ * the import never stored (status hues, sidebar, hover) from that record, and then
207
+ * writes `flatTokens` verbatim over the derivation: every stored key paints exactly
208
+ * what the user imported.
209
+ */
210
+
211
+ const IMPORTED_PROVENANCE = {
212
+ project: 'Adea themes catalogue',
213
+ url: 'https://github.com/adea-ai/themes',
214
+ license: 'Apache-2.0',
215
+ } as const
216
+
217
+ function ansiRamp(variant: StoredThemeVariant): AdeaTheme['ansi'] {
218
+ const [
219
+ black,
220
+ red,
221
+ green,
222
+ yellow,
223
+ blue,
224
+ magenta,
225
+ cyan,
226
+ white,
227
+ brightBlack,
228
+ brightRed,
229
+ brightGreen,
230
+ brightYellow,
231
+ brightBlue,
232
+ brightMagenta,
233
+ brightCyan,
234
+ brightWhite,
235
+ ] = variant.terminal.ansi
236
+ return {
237
+ black: black!,
238
+ red: red!,
239
+ green: green!,
240
+ yellow: yellow!,
241
+ blue: blue!,
242
+ magenta: magenta!,
243
+ cyan: cyan!,
244
+ white: white!,
245
+ brightBlack: brightBlack!,
246
+ brightRed: brightRed!,
247
+ brightGreen: brightGreen!,
248
+ brightYellow: brightYellow!,
249
+ brightBlue: brightBlue!,
250
+ brightMagenta: brightMagenta!,
251
+ brightCyan: brightCyan!,
252
+ brightWhite: brightWhite!,
253
+ }
254
+ }
255
+
256
+ /**
257
+ * The catalogue-shaped record for an imported variant. The editor reads only its
258
+ * surface, text, border and accent roles; warning and info are the ANSI yellow and
259
+ * blue because the stored variant has no such roles.
260
+ */
261
+ export function storedVariantRecord(variant: StoredThemeVariant): AdeaThemeRecord {
262
+ const colors = variant.colors
263
+ const ansi = ansiRamp(variant)
264
+ const theme: AdeaTheme = {
265
+ id: variant.id,
266
+ name: variant.name,
267
+ appearance: variant.appearance,
268
+ colors: {
269
+ background: colors.background,
270
+ foreground: colors.foreground,
271
+ surface: colors.card,
272
+ surfaceElevated: colors.popover,
273
+ surfaceHover: colors.accent,
274
+ surfaceActive: colors.border,
275
+ border: colors.border,
276
+ borderMuted: colors.border,
277
+ text: colors.foreground,
278
+ textMuted: colors.mutedForeground,
279
+ textSubtle: colors.mutedForeground,
280
+ accent: colors.primary,
281
+ accentForeground: colors.primaryForeground,
282
+ success: colors.success,
283
+ warning: ansi.yellow,
284
+ error: colors.destructive,
285
+ info: ansi.blue,
286
+ },
287
+ ansi,
288
+ cursor: variant.terminal.cursor,
289
+ selection: variant.terminal.selection,
290
+ }
291
+ return {
292
+ ...theme,
293
+ family: variant.familyId,
294
+ familyLabel: variant.familyName,
295
+ label: variant.name,
296
+ description: `${variant.name}, imported into your library.`,
297
+ provenance: IMPORTED_PROVENANCE,
298
+ tags: ['imported', variant.appearance],
299
+ }
300
+ }
301
+
302
+ /**
303
+ * The shared-provider variant for a stored theme: derived roles from the
304
+ * reconstructed record, missing sidebar projection sources from the stored variant,
305
+ * then every stored flat token verbatim.
306
+ *
307
+ * A record the shared projection cannot map falls back to the default theme of the
308
+ * same appearance under the stored identity, so an import that the projection
309
+ * rejects still paints from its tokens instead of vanishing.
310
+ */
311
+ export function toUiVariant(stored: CustomThemeStored): UiThemeVariant {
312
+ const { variant } = stored
313
+ let base: UiThemeVariant
314
+ try {
315
+ base = variantFromRecord(storedVariantRecord(variant))
316
+ } catch {
317
+ // The shipped default of the appearance: the provider's own start-up data, so the
318
+ // shell never imports the themes catalogue to repair an import.
319
+ base = {
320
+ ...defaultVariantFor(variant.appearance),
321
+ id: variant.id,
322
+ family: variant.familyId,
323
+ familyLabel: variant.familyName,
324
+ label: variant.name,
325
+ description: `${variant.name}, imported into your library.`,
326
+ provenance: {
327
+ source: IMPORTED_PROVENANCE.project,
328
+ url: IMPORTED_PROVENANCE.url,
329
+ license: IMPORTED_PROVENANCE.license,
330
+ },
331
+ }
332
+ }
333
+ const projectionSources: Record<string, string> = {}
334
+ for (const fallback of LEGACY_IMPORTED_THEME_TOKEN_PROJECTION_FALLBACKS) {
335
+ if (Object.hasOwn(stored.flatTokens, fallback.token)) continue
336
+ // Read-only walk over own properties of the stored record.
337
+ const value = fallback.path.reduce<unknown>(
338
+ (node, key) =>
339
+ node && typeof node === 'object' && Object.hasOwn(node, key)
340
+ ? (node as Record<string, unknown>)[key]
341
+ : undefined,
342
+ stored
343
+ )
344
+ if (typeof value === 'string') projectionSources[fallback.token] = value
345
+ }
346
+ return { ...base, tokens: { ...projectionSources, ...stored.flatTokens } }
347
+ }