@legendapp/spark 0.0.1-next.3 → 0.0.1-next.5

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/README.md +1 -1
  2. package/camera.ts +13 -0
  3. package/customize.ts +2 -0
  4. package/html.ts +1 -0
  5. package/markdown.ts +1 -0
  6. package/package.json +34 -15
  7. package/patches/camera/react-native-nitro-image.patch +320 -0
  8. package/patches/camera/react-native-nitro-modules.patch +50 -0
  9. package/patches/camera/react-native-vision-camera.patch +2662 -0
  10. package/patches/camera/upstream.json +22 -0
  11. package/patches/dependencies.json +14 -0
  12. package/patches/react-native-enriched-html@1.1.1.patch +854 -0
  13. package/patches/react-native-enriched-markdown@1.1.1.patch +9261 -0
  14. package/postinstall.cjs +1 -0
  15. package/schema.json +104 -0
  16. package/skills/spark/SKILL.md +56 -0
  17. package/skills/spark/UPGRADING.md +246 -0
  18. package/ui-swipe.ts +1 -0
  19. package/vendor/node_modules/@legendapp/spark-ai/package.json +4 -4
  20. package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.cjs +11 -0
  21. package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.d.cts +2 -0
  22. package/vendor/node_modules/@legendapp/spark-ai/src/invocations.ts +2 -19
  23. package/vendor/node_modules/@legendapp/spark-audio/package.json +3 -3
  24. package/vendor/node_modules/@legendapp/spark-auth-session/package.json +3 -3
  25. package/vendor/node_modules/@legendapp/spark-cli/dist/add-desktop.js +4 -4
  26. package/vendor/node_modules/@legendapp/spark-cli/dist/build.js +65 -11
  27. package/vendor/node_modules/@legendapp/spark-cli/dist/cli-arguments.js +2 -1
  28. package/vendor/node_modules/@legendapp/spark-cli/dist/commands.js +3 -2
  29. package/vendor/node_modules/@legendapp/spark-cli/dist/create.js +36 -13
  30. package/vendor/node_modules/@legendapp/spark-cli/dist/credentials.js +41 -26
  31. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-ai.cjs +108 -0
  32. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-artifacts.js +315 -0
  33. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-cli.cjs +75 -0
  34. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-github.cjs +133 -0
  35. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-policy.cjs +102 -0
  36. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-provider.cjs +2 -0
  37. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-worker.cjs +273 -0
  38. package/vendor/node_modules/@legendapp/spark-cli/dist/dependency-pins.js +157 -0
  39. package/vendor/node_modules/@legendapp/spark-cli/dist/dev-command.js +3 -1
  40. package/vendor/node_modules/@legendapp/spark-cli/dist/dev.js +1 -1
  41. package/vendor/node_modules/@legendapp/spark-cli/dist/enriched-html-pins.js +128 -0
  42. package/vendor/node_modules/@legendapp/spark-cli/dist/errors.js +100 -0
  43. package/vendor/node_modules/@legendapp/spark-cli/dist/examples.js +1 -1
  44. package/vendor/node_modules/@legendapp/spark-cli/dist/expo-dev-patch.cjs +30 -1
  45. package/vendor/node_modules/@legendapp/spark-cli/dist/expo-native.cjs +5 -1
  46. package/vendor/node_modules/@legendapp/spark-cli/dist/helpers.js +1 -1
  47. package/vendor/node_modules/@legendapp/spark-cli/dist/index.js +52 -7
  48. package/vendor/node_modules/@legendapp/spark-cli/dist/init-template.d.cts +1 -0
  49. package/vendor/node_modules/@legendapp/spark-cli/dist/js-runtime.cjs +96 -0
  50. package/vendor/node_modules/@legendapp/spark-cli/dist/json.js +16 -0
  51. package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.cjs +152 -0
  52. package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.d.cts +15 -0
  53. package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.cjs +184 -0
  54. package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.d.cts +16 -0
  55. package/vendor/node_modules/@legendapp/spark-cli/dist/native-patch-preflight.js +5 -1
  56. package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager-config.js +41 -0
  57. package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager.js +13 -0
  58. package/vendor/node_modules/@legendapp/spark-cli/dist/process.js +7 -0
  59. package/vendor/node_modules/@legendapp/spark-cli/dist/project-version.js +12 -0
  60. package/vendor/node_modules/@legendapp/spark-cli/dist/project.js +66 -30
  61. package/vendor/node_modules/@legendapp/spark-cli/dist/release.js +2 -1
  62. package/vendor/node_modules/@legendapp/spark-cli/dist/release.json +20 -20
  63. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.ps1 +87 -0
  64. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.sh +107 -0
  65. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-downloads.tsv +13 -0
  66. package/vendor/node_modules/@legendapp/spark-cli/dist/sdk-install.js +8 -3
  67. package/vendor/node_modules/@legendapp/spark-cli/dist/universal.cjs +2 -1
  68. package/vendor/node_modules/@legendapp/spark-cli/dist/upgrade.js +102 -0
  69. package/vendor/node_modules/@legendapp/spark-cli/dist/windows.js +1 -8
  70. package/vendor/node_modules/@legendapp/spark-cli/package.json +6 -4
  71. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/.claude/skills/spark/SKILL.md +9 -0
  72. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/AGENTS.md +4 -0
  73. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/CLAUDE.md +4 -0
  74. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/README.md +15 -0
  75. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/package.json +47 -3
  76. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/.claude/skills/spark/SKILL.md +9 -0
  77. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/AGENTS.md +4 -0
  78. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/CLAUDE.md +4 -0
  79. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/README.md +15 -0
  80. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/package.json +46 -3
  81. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/.claude/skills/spark/SKILL.md +9 -0
  82. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/AGENTS.md +4 -0
  83. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/CLAUDE.md +4 -0
  84. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/README.md +15 -0
  85. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/package.json +47 -3
  86. package/vendor/node_modules/@legendapp/spark-clipboard/package.json +3 -3
  87. package/vendor/node_modules/@legendapp/spark-codex/package.json +4 -4
  88. package/vendor/node_modules/@legendapp/spark-commands/package.json +6 -6
  89. package/vendor/node_modules/@legendapp/spark-context-menu/package.json +3 -3
  90. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/RNDesktopApp.mm +14 -1
  91. package/vendor/node_modules/@legendapp/spark-desktop-app/package.json +2 -2
  92. package/vendor/node_modules/@legendapp/spark-desktop-app/src/contracts/menu.ts +6 -4
  93. package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize-hooks.ts +17 -0
  94. package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize.ts +117 -0
  95. package/vendor/node_modules/@legendapp/spark-desktop-config/app.plugin.cjs +20 -1
  96. package/vendor/node_modules/@legendapp/spark-desktop-config/config.cjs +5 -2
  97. package/vendor/node_modules/@legendapp/spark-desktop-config/config.d.cts +14 -0
  98. package/vendor/node_modules/@legendapp/spark-desktop-config/customize-provider.cjs +16 -0
  99. package/vendor/node_modules/@legendapp/spark-desktop-config/customize.cjs +16 -0
  100. package/vendor/node_modules/@legendapp/spark-desktop-config/expo.cjs +1 -0
  101. package/vendor/node_modules/@legendapp/spark-desktop-config/native-patches.cjs +106 -0
  102. package/vendor/node_modules/@legendapp/spark-desktop-config/native-patches.d.cts +1 -0
  103. package/vendor/node_modules/@legendapp/spark-desktop-config/package.json +5 -4
  104. package/vendor/node_modules/@legendapp/spark-desktop-config/schema.json +104 -0
  105. package/vendor/node_modules/@legendapp/spark-desktop-host/SparkCustomize.mm +517 -0
  106. package/vendor/node_modules/@legendapp/spark-desktop-host/package.json +4 -3
  107. package/vendor/node_modules/@legendapp/spark-desktop-links/package.json +3 -3
  108. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/RNDesktopShortcuts.mm +3 -1
  109. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.h +3 -0
  110. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.mm +1 -1
  111. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/package.json +3 -3
  112. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/window-manager/RNWindowManager.mm +44 -4
  113. package/vendor/node_modules/@legendapp/spark-desktop-windows/package.json +4 -4
  114. package/vendor/node_modules/@legendapp/spark-desktop-windows/src/api.ts +65 -26
  115. package/vendor/node_modules/@legendapp/spark-desktop-windows/src/macos-adapter.ts +8 -6
  116. package/vendor/node_modules/@legendapp/spark-documents/package.json +8 -8
  117. package/vendor/node_modules/@legendapp/spark-drag-drop/package.json +3 -3
  118. package/vendor/node_modules/@legendapp/spark-file-dialog/package.json +3 -3
  119. package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.h +1 -0
  120. package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.mm +11 -10
  121. package/vendor/node_modules/@legendapp/spark-file-system/package.json +3 -3
  122. package/vendor/node_modules/@legendapp/spark-global-shortcuts/package.json +3 -3
  123. package/vendor/node_modules/@legendapp/spark-html/package.json +24 -0
  124. package/vendor/node_modules/@legendapp/spark-html/src/Html.tsx +22 -0
  125. package/vendor/node_modules/@legendapp/spark-html/src/HtmlInput.tsx +102 -0
  126. package/vendor/node_modules/@legendapp/spark-html/src/index.ts +4 -0
  127. package/vendor/node_modules/@legendapp/spark-html/src/types.ts +4 -0
  128. package/vendor/node_modules/@legendapp/spark-markdown/package.json +24 -0
  129. package/vendor/node_modules/@legendapp/spark-markdown/src/Markdown.tsx +24 -0
  130. package/vendor/node_modules/@legendapp/spark-markdown/src/MarkdownInput.tsx +111 -0
  131. package/vendor/node_modules/@legendapp/spark-markdown/src/index.ts +4 -0
  132. package/vendor/node_modules/@legendapp/spark-message-dialog/package.json +3 -3
  133. package/vendor/node_modules/@legendapp/spark-native-menu/package.json +3 -3
  134. package/vendor/node_modules/@legendapp/spark-notifications/package.json +3 -3
  135. package/vendor/node_modules/@legendapp/spark-notifications/windows/SparkNotifications/SparkNotifications.h +16 -11
  136. package/vendor/node_modules/@legendapp/spark-processes/package.json +3 -3
  137. package/vendor/node_modules/@legendapp/spark-rich-text/package.json +18 -0
  138. package/vendor/node_modules/@legendapp/spark-rich-text/src/components.tsx +52 -0
  139. package/vendor/node_modules/@legendapp/spark-rich-text/src/index.ts +4 -0
  140. package/vendor/node_modules/@legendapp/spark-rich-text/src/types.ts +24 -0
  141. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.macos.ts +55 -0
  142. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.ts +13 -0
  143. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputValue.ts +14 -0
  144. package/vendor/node_modules/@legendapp/spark-rich-text/src/value.ts +16 -0
  145. package/vendor/node_modules/@legendapp/spark-secure-storage/package.json +3 -3
  146. package/vendor/node_modules/@legendapp/spark-settings/package.json +3 -3
  147. package/vendor/node_modules/@legendapp/spark-settings-ui/package.json +5 -5
  148. package/vendor/node_modules/@legendapp/spark-sqlite/package.json +3 -3
  149. package/vendor/node_modules/@legendapp/spark-system/package.json +3 -3
  150. package/vendor/node_modules/@legendapp/spark-tray/package.json +3 -3
  151. package/vendor/node_modules/@legendapp/spark-ui/macos/appkit-split-view/RNSidebarSplitViewComponent.mm +360 -35
  152. package/vendor/node_modules/@legendapp/spark-ui/macos/swipe-actions/RNSwipeActions.h +10 -0
  153. package/vendor/node_modules/@legendapp/spark-ui/macos/swipe-actions/RNSwipeActions.mm +422 -0
  154. package/vendor/node_modules/@legendapp/spark-ui/package.json +4 -3
  155. package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/SidebarSplitViewNativeComponent.ts +11 -0
  156. package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/index.tsx +30 -13
  157. package/vendor/node_modules/@legendapp/spark-ui/src/swipe-actions/SwipeActionsNativeComponent.ts +11 -0
  158. package/vendor/node_modules/@legendapp/spark-ui/src/swipe-actions/index.tsx +41 -0
  159. package/vendor/node_modules/@legendapp/spark-updates/package.json +3 -3
  160. package/vendor/node_modules/@legendapp/spark-webview/package.json +2 -2
  161. package/vendor/node_modules/@legendapp/spark-window-options/package.json +1 -1
@@ -0,0 +1,2 @@
1
+ // The release toolkit gets its own copy so it remains independent of Spark's install.
2
+ module.exports = require('@legendapp/spark-desktop-config/customize-provider.cjs');
@@ -0,0 +1,273 @@
1
+ // Downloadable customize worker. No toolchain code is linked into the application.
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const { createRequire } = require('node:module');
6
+ const { spawn } = require('node:child_process');
7
+ const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
8
+ const read = file => JSON.parse(fs.readFileSync(file, 'utf8'));
9
+ function write(file, value) {
10
+ fs.mkdirSync(path.dirname(file), { recursive: true });
11
+ const temporary = `${file}.${process.pid}.tmp`;
12
+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
13
+ fs.renameSync(temporary, file);
14
+ }
15
+ function safe(root, relative) {
16
+ if (typeof relative !== 'string' || !relative || path.isAbsolute(relative) || relative.split(/[\\/]/).some(p => !p || p === '.' || p === '..' || p === 'node_modules' || p.startsWith('.spark'))) throw new Error('Invalid workspace path');
17
+ const file = path.join(root, relative);
18
+ let current = root;
19
+ for (const part of relative.split('/')) {
20
+ current = path.join(current, part);
21
+ if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink()) throw new Error('Workspace symlinks are not editable');
22
+ }
23
+ return file;
24
+ }
25
+ function snapshot(root) {
26
+ const result = {};
27
+ function visit(relative) {
28
+ for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a,b) => a.name.localeCompare(b.name))) {
29
+ if (['node_modules', '.spark', '.expo', '.threaded-runtime', '.git'].includes(entry.name)) continue;
30
+ const name = path.posix.join(relative, entry.name), file = path.join(root, name);
31
+ if (entry.isSymbolicLink()) throw new Error(`Source symlink: ${name}`);
32
+ if (entry.isDirectory()) visit(name);
33
+ else if (entry.isFile()) result[name] = fs.readFileSync(file).toString('base64');
34
+ }
35
+ }
36
+ visit(''); return result;
37
+ }
38
+ function restore(root, files) {
39
+ fs.mkdirSync(root, { recursive: true });
40
+ for (const [name, bytes] of Object.entries(files)) {
41
+ const file = safe(root, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, Buffer.from(bytes, 'base64'));
42
+ }
43
+ }
44
+ function patch(base, modified) {
45
+ return Object.keys({ ...base, ...modified }).sort().filter(name => base[name] !== modified[name]).map(name => ({ path: name, before: base[name] ?? null, after: modified[name] ?? null }));
46
+ }
47
+ function text(bytes) {
48
+ const value = Buffer.from(bytes, 'base64');
49
+ if (value.includes(0)) return undefined;
50
+ const decoded = value.toString('utf8');
51
+ return Buffer.from(decoded).equals(value) ? decoded : undefined;
52
+ }
53
+ function reviewPatch(changes) {
54
+ const { createTwoFilesPatch } = require('diff');
55
+ return changes.map(change => {
56
+ const before = change.before === null ? '' : text(change.before), after = change.after === null ? '' : text(change.after);
57
+ return before === undefined || after === undefined ? `${change.path}: binary file changed\n` : createTwoFilesPatch(change.path, change.path, before, after);
58
+ }).join('\n');
59
+ }
60
+ function mergeText(base, ours, theirs) {
61
+ const { diffArrays } = require('diff');
62
+ const lines = value => value.match(/[^\n]*\n|[^\n]+$/g) ?? [];
63
+ const original = lines(base);
64
+ function edits(value) {
65
+ let offset = 0, pending;
66
+ const output = [];
67
+ for (const part of diffArrays(original, lines(value))) {
68
+ if (!part.added && !part.removed) { if (pending) output.push(pending); pending = undefined; offset += part.count; }
69
+ else {
70
+ pending ??= { start: offset, end: offset, lines: [] };
71
+ if (part.removed) { offset += part.count; pending.end = offset; }
72
+ else pending.lines.push(...part.value);
73
+ }
74
+ }
75
+ if (pending) output.push(pending);
76
+ return output;
77
+ }
78
+ const left = edits(ours), right = edits(theirs), all = [...left];
79
+ for (const edit of right) {
80
+ let identical = false;
81
+ for (const existing of left) {
82
+ if (JSON.stringify(edit) === JSON.stringify(existing)) { identical = true; break; }
83
+ // Adjacent changes can be merged; insertions at a changed boundary are conservative conflicts.
84
+ if (Math.max(edit.start, existing.start) < Math.min(edit.end, existing.end) ||
85
+ (edit.start === edit.end && edit.start >= existing.start && edit.start <= existing.end) ||
86
+ (existing.start === existing.end && existing.start >= edit.start && existing.start <= edit.end)) return undefined;
87
+ }
88
+ if (!identical) all.push(edit);
89
+ }
90
+ let output = '', offset = 0;
91
+ for (const edit of all.sort((a,b) => a.start - b.start)) { output += original.slice(offset, edit.start).join('') + edit.lines.join(''); offset = edit.end; }
92
+ return output + original.slice(offset).join('');
93
+ }
94
+ function merge(base, ours, theirs) {
95
+ const files = {}, conflicts = [];
96
+ for (const name of Object.keys({ ...base, ...ours, ...theirs }).sort()) {
97
+ const b = base[name], o = ours[name], t = theirs[name];
98
+ let value;
99
+ if (o === b || o === t) value = t;
100
+ else if (t === b) value = o;
101
+ else if (b !== undefined && o !== undefined && t !== undefined && [b,o,t].every(v => text(v) !== undefined)) {
102
+ const merged = mergeText(text(b), text(o), text(t));
103
+ if (merged !== undefined) value = Buffer.from(merged).toString('base64');
104
+ else conflicts.push(name);
105
+ } else conflicts.push(name);
106
+ // Keep the new upstream file in conflicts. Original and modified versions remain in the request.
107
+ if (conflicts.at(-1) === name) value = t;
108
+ if (value !== undefined) files[name] = value;
109
+ }
110
+ return { files, conflicts };
111
+ }
112
+ function validateManifest(manifest) {
113
+ if (manifest.schema !== 1 || !/^[a-f0-9]{64}$/.test(manifest.release) || manifest.runtime?.platform !== 'macos' || manifest.runtime?.mode !== 'release' || !manifest.project || !manifest.version) throw new Error('Invalid customize manifest');
114
+ for (const asset of [manifest.source, manifest.toolkit]) if (!asset || !/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/releases\/download\/[\w.-]+\/[\w.-]+$/.test(asset.url) || !/^[a-f0-9]{64}$/.test(asset.sha256) || !Number.isSafeInteger(asset.size) || asset.size <= 0) throw new Error('Invalid customize asset');
115
+ if (manifest.projectRoot !== undefined && manifest.projectRoot !== '.') safe('/snapshot', manifest.projectRoot);
116
+ safe('/snapshot', manifest.entry);
117
+ return manifest;
118
+ }
119
+ function prepare(manifest, source, toolkit, support) {
120
+ validateManifest(manifest);
121
+ const directory = path.join(support, 'releases', manifest.release);
122
+ if (fs.existsSync(path.join(directory, 'state.json'))) {
123
+ const accepting = path.join(directory, 'accepting.json');
124
+ if (fs.existsSync(accepting)) {
125
+ const pending = read(accepting);
126
+ for (const file of [pending.backup, pending.staged]) if (path.dirname(file) !== directory) throw new Error('Invalid acceptance recovery path');
127
+ if (!fs.existsSync(path.join(directory, 'work')) && fs.existsSync(pending.backup)) fs.renameSync(pending.backup, path.join(directory, 'work'));
128
+ fs.rmSync(accepting, { force: true });
129
+ }
130
+ const state = read(path.join(directory, 'state.json'));
131
+ if (state.toolkit !== toolkit) { state.toolkit = toolkit; write(path.join(directory, 'state.json'), state); }
132
+ return directory;
133
+ }
134
+ const stage = `${directory}.pending-${process.pid}`;
135
+ fs.mkdirSync(stage, { recursive: true });
136
+ try {
137
+ const base = snapshot(source);
138
+ restore(path.join(stage, 'base'), base); restore(path.join(stage, 'work'), base);
139
+ write(path.join(stage, 'manifest.json'), manifest);
140
+ write(path.join(stage, 'state.json'), { schema: 1, toolkit, created: new Date().toISOString(), history: [], status: 'original' });
141
+ fs.mkdirSync(path.dirname(directory), { recursive: true }); fs.renameSync(stage, directory);
142
+ } finally { fs.rmSync(stage, { recursive: true, force: true }); }
143
+ return directory;
144
+ }
145
+ function migrate(from, to) {
146
+ const previous = read(path.join(from, 'manifest.json')), current = read(path.join(to, 'manifest.json'));
147
+ if (previous.project !== current.project || previous.release === current.release) throw new Error('Migration requires two releases of the same app');
148
+ const state = read(path.join(to, 'state.json'));
149
+ if (state.history.length || state.migration) throw new Error('This release already has edits or a migration; preserve it before preparing another');
150
+ const base = snapshot(path.join(from, 'base')), ours = snapshot(path.join(from, 'work')), theirs = snapshot(path.join(to, 'base'));
151
+ const result = merge(base, ours, theirs);
152
+ const id = crypto.randomUUID(), candidate = path.join(to, 'candidates', id);
153
+ restore(candidate, result.files);
154
+ const history = read(path.join(from, 'state.json')).history;
155
+ state.inheritedPrompts = [...(read(path.join(from, 'state.json')).inheritedPrompts ?? []), ...history.filter(item => item.status === 'accepted').map(item => ({ prompt: item.prompt, baseRelease: item.baseRelease, patch: item.patch }))];
156
+ const request = { schema: 1, kind: 'migration', from: previous.release, to: current.release,
157
+ prompts: [...state.inheritedPrompts, ...history.filter(item => item.status !== 'accepted')].map(item => ({ prompt: item.prompt, status: item.status, patch: item.patch })), patch: patch(base, ours),
158
+ upstream: patch(base, theirs), conflicts: result.conflicts };
159
+ write(path.join(to, 'migration.json'), request);
160
+ fs.writeFileSync(path.join(to, 'review.txt'), 'Migration from ' + previous.version + ' to ' + current.version + '\n\nConflicts: ' + (result.conflicts.join(', ') || 'none') + '\n\nContributing prompts\n\n' + state.inheritedPrompts.map(item => item.prompt).join('\n\n') + '\n\nChanges from accepted source\n\n' + reviewPatch(patch(snapshot(path.join(to, 'work')), result.files)));
161
+ state.migration = { from: previous.release, candidate: id, conflicts: result.conflicts, status: 'needs-review' };
162
+ write(path.join(to, 'state.json'), state);
163
+ return state.migration;
164
+ }
165
+ const children = new Set();
166
+ async function execute(command, args, options = {}) {
167
+ return new Promise((resolve, reject) => {
168
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], ...options });
169
+ children.add(child); child.once('close', () => children.delete(child));
170
+ let output = '';
171
+ for (const stream of [child.stdout, child.stderr]) stream.on('data', value => { output = (output + value).slice(-20000); });
172
+ child.on('error', reject);
173
+ child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`${path.basename(command)} exited ${code}\n${output}`)));
174
+ });
175
+ }
176
+ function attachDependencies(workspace, toolkit) {
177
+ const modules = path.join(workspace, 'node_modules');
178
+ if (!fs.existsSync(modules)) fs.symlinkSync(path.join(toolkit, 'node_modules'), modules);
179
+ }
180
+ async function build(directory, candidate = 'work') {
181
+ fs.rmSync(path.join(directory, 'ready.json'), { force: true });
182
+ const state = read(path.join(directory, 'state.json')), manifest = validateManifest(read(path.join(directory, 'manifest.json')));
183
+ const workspace = candidate === 'work' ? path.join(directory, 'work') : safe(path.join(directory, 'candidates'), candidate);
184
+ const toolkit = state.toolkit, metadata = read(path.join(toolkit, 'toolkit.json'));
185
+ if (metadata.arch !== process.arch || metadata.framework !== manifest.runtime.framework || hash(fs.readFileSync(path.join(toolkit, 'hermesc'))) !== metadata.compiler) throw new Error('Incompatible customize toolkit');
186
+ require('./customize-policy.cjs').assertCustomizeChanges(snapshot(path.join(directory, 'base')), snapshot(workspace), manifest.customize?.trustedFiles);
187
+ attachDependencies(workspace, toolkit);
188
+ const project = !manifest.projectRoot || manifest.projectRoot === '.' ? workspace : safe(workspace, manifest.projectRoot);
189
+ attachDependencies(project, toolkit);
190
+ const req = createRequire(path.join(project, 'package.json'));
191
+ const expoPackage = req.resolve('expo/package.json'), expo = read(expoPackage);
192
+ const bin = path.resolve(path.dirname(expoPackage), typeof expo.bin === 'string' ? expo.bin : expo.bin.expo);
193
+ const id = crypto.randomUUID(), output = path.join(directory, 'builds', id);
194
+ fs.mkdirSync(output, { recursive: true });
195
+ const env = { ...process.env, CI: '1', NODE_ENV: 'production', SPARK_PLATFORM: 'macos', EXPO_NO_TELEMETRY: '1' };
196
+ // Discover worker roots using the same two-pass pipeline as Spark's release build.
197
+ // One worker avoids Bun's jest-worker fork/IPC incompatibility and keeps memory bounded.
198
+ const args = ['export:embed', '--platform', 'macos', '--entry-file', manifest.entry, '--bundle-output', path.join(output, 'app.js'), '--sourcemap-output', path.join(output, 'app.map'), '--assets-dest', output, '--dev', 'false', '--minify', 'true', '--max-workers', '1'];
199
+ await execute(process.execPath, [bin, ...args], { cwd: project, env: { ...env, SPARK_RUNTIME_DISCOVERY: '1' } });
200
+ const sources = read(path.join(output, 'app.map')).sources;
201
+ const roots = sources.map(source => fs.existsSync(path.resolve(project, source)) ? path.resolve(project, source) : path.resolve(project, source.replace(/^\//, ''))).filter(file => fs.existsSync(file) && /\.[jt]sx?$/.test(file) && !file.endsWith('.d.ts'));
202
+ const runtimeSources = path.join(output, 'runtime-sources.json');
203
+ write(runtimeSources, { enabled: sources.some(source => source.includes('@react-native-runtimes/core/') && !source.endsWith('secondary-runtime-polyfill.js')), roots });
204
+ await execute(process.execPath, [bin, ...args], { cwd: project, env: { ...env, SPARK_RUNTIME_SOURCES: runtimeSources } });
205
+ // A production edit may only import native modules present in the frozen shell.
206
+ const selected = manifest.runtime.modules;
207
+ for (const source of read(path.join(output, 'app.map')).sources) {
208
+ const file = fs.existsSync(path.resolve(project, source)) ? path.resolve(project, source) : path.resolve(project, source.replace(/^\//, ''));
209
+ if (!fs.existsSync(file)) continue;
210
+ let folder = path.dirname(fs.realpathSync(file));
211
+ while (folder !== path.dirname(folder)) {
212
+ const packageFile = path.join(folder, 'package.json');
213
+ if (fs.existsSync(packageFile)) {
214
+ const pkg = read(packageFile);
215
+ if ((pkg.codegenConfig || pkg.spark?.nativeModules || fs.existsSync(path.join(folder, 'expo-module.config.json'))) && !selected[pkg.name]) throw new Error(`Native module is not available in this shell: ${pkg.name}`);
216
+ break;
217
+ }
218
+ folder = path.dirname(folder);
219
+ }
220
+ }
221
+ await execute(path.join(toolkit, 'hermesc'), ['-O', '-emit-binary', '-out', path.join(output, 'main.jsbundle'), path.join(output, 'app.js')]);
222
+ const record = { schema: 1, release: manifest.release, fingerprint: manifest.runtime.fingerprint, build: id, bundleHash: hash(fs.readFileSync(path.join(output, 'main.jsbundle'))), candidate, sourceHash: hash(JSON.stringify(snapshot(workspace))) };
223
+ write(path.join(directory, 'ready.json'), record);
224
+ return record;
225
+ }
226
+ function verify(directory) {
227
+ const ready = read(path.join(directory, 'ready.json'));
228
+ const manifest = validateManifest(read(path.join(directory, 'manifest.json')));
229
+ const workspace = ready.candidate === 'work' ? path.join(directory, 'work') : safe(path.join(directory, 'candidates'), ready.candidate);
230
+ if (ready.release !== manifest.release || ready.sourceHash !== hash(JSON.stringify(snapshot(workspace)))) throw new Error('Source changed after validation; rebuild before accepting');
231
+ if (ready.fingerprint !== manifest.runtime.fingerprint || !/^[a-f0-9-]{36}$/.test(ready.build) || hash(fs.readFileSync(path.join(directory, 'builds', ready.build, 'main.jsbundle'))) !== ready.bundleHash) throw new Error('Compiled candidate is incompatible or corrupted');
232
+ return ready;
233
+ }
234
+ function accept(directory) {
235
+ const ready = verify(directory);
236
+ const workspace = ready.candidate === 'work' ? path.join(directory, 'work') : safe(path.join(directory, 'candidates'), ready.candidate);
237
+ const state = read(path.join(directory, 'state.json'));
238
+ if (ready.candidate !== 'work') {
239
+ const staged = path.join(directory, 'accept-' + crypto.randomUUID());
240
+ fs.cpSync(workspace, staged, { recursive: true, verbatimSymlinks: true });
241
+ const backup = path.join(directory, 'work-before-' + crypto.randomUUID());
242
+ write(path.join(directory, 'accepting.json'), { backup, staged });
243
+ fs.renameSync(path.join(directory, 'work'), backup);
244
+ try { fs.renameSync(staged, path.join(directory, 'work')); fs.rmSync(path.join(directory, 'accepting.json'), { force: true }); }
245
+ catch (error) { fs.rmSync(path.join(directory, 'work'), { recursive: true, force: true }); fs.renameSync(backup, path.join(directory, 'work')); throw error; }
246
+ const event = state.history.find(item => item.candidate === ready.candidate);
247
+ for (const item of state.history) if (item.candidate === ready.candidate || event?.ancestors?.includes(item.id)) item.status = 'accepted';
248
+ if (state.migration?.candidate === ready.candidate) state.migration.status = 'accepted';
249
+ }
250
+ state.status = 'customized';
251
+ write(path.join(directory, 'patch.json'), patch(snapshot(path.join(directory, 'base')), snapshot(path.join(directory, 'work'))));
252
+ write(path.join(directory, 'state.json'), state);
253
+ // Native host owns activation/recovery. Never modify a signed application from the worker.
254
+ return ready;
255
+ }
256
+ module.exports = { reviewPatch, safe, snapshot, restore, patch, merge, mergeText, validateManifest, prepare, migrate, execute, build, verify, accept, read, write, hash };
257
+ if (require.main === module) {
258
+ const initialize = require('./js-runtime.cjs').initializeRuntime;
259
+ (async () => {
260
+ await initialize();
261
+ for (const signal of ['SIGTERM','SIGINT']) process.once(signal, () => { for (const child of children) child.kill(signal); setTimeout(() => process.exit(signal === 'SIGINT' ? 130 : 143), 300).unref(); });
262
+ const [command, ...args] = process.argv.slice(2);
263
+ let result;
264
+ if (command === 'prepare') result = prepare(read(args[0]), args[1], args[2], args[3]);
265
+ else if (command === 'migrate') result = migrate(args[0], args[1]);
266
+ else if (command === 'build') result = await build(args[0], args[1]);
267
+ else if (command === 'verify') result = verify(args[0]);
268
+ else if (command === 'accept') result = accept(args[0]);
269
+ else if (command === 'prompt') result = await require('./customize-ai.cjs').prompt(args[0], read(args[1]));
270
+ else throw new Error('Expected prepare, migrate, prompt, build, verify, or accept');
271
+ console.log(JSON.stringify(result));
272
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
273
+ }
@@ -0,0 +1,157 @@
1
+ import { overridePackageName } from "./package-manager.js";
2
+ import { readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import ts from "typescript";
5
+ import { supportedPlatforms } from "@legendapp/spark-desktop-config/config.cjs";
6
+ const packages = ["react", "react-native", "react-native-macos", "expo"];
7
+ // create/refreshLocalPackages use this starter's tested compatibility matrix too.
8
+ const defaults = JSON.parse(readFileSync(new URL("../templates/blank-typescript/package.json", import.meta.url), "utf8"));
9
+ export const expectedDependencyPins = Object.fromEntries(packages.map(name => [name, defaults.dependencies[name]]));
10
+ export function dependencyPinIssues(pkg, platforms, expected = expectedDependencyPins) {
11
+ const required = [...packages, ...(expected["@legendapp/spark"] ? ["@legendapp/spark"] : [])].filter(name => name !== "react-native-macos" || platforms.includes("macos"));
12
+ const checked = Object.keys(expected).filter(name => name !== "react-native-macos" || platforms.includes("macos"));
13
+ const issues = [];
14
+ function check(name, value, where) {
15
+ // npm and pnpm permit an override to reference a direct dependency's spec.
16
+ const resolved = ["overrides", "pnpm"].includes(where[0]) && typeof value === "string" && value.startsWith("$")
17
+ ? pkg.dependencies?.[value.slice(1)] ?? pkg.devDependencies?.[value.slice(1)] : value;
18
+ if (typeof resolved === "string" && /^(catalog|workspace):/.test(resolved)) {
19
+ console.log(`Skipping dependency pin check for ${where.join(" → ")}: ${resolved} is managed by the catalog or workspace.`);
20
+ return;
21
+ }
22
+ if (resolved !== expected[name])
23
+ issues.push({ package: name, found: typeof value === "string" ? value : JSON.stringify(value), expected: expected[name], where });
24
+ }
25
+ for (const name of checked) {
26
+ let present = false;
27
+ for (const section of ["dependencies", "devDependencies"]) {
28
+ if (Object.hasOwn(pkg[section] ?? {}, name)) {
29
+ present = true;
30
+ check(name, pkg[section][name], [section, name]);
31
+ }
32
+ }
33
+ if (!present && required.includes(name))
34
+ issues.push({ package: name, found: "(missing)", expected: expected[name], where: ["dependencies", name], missing: true });
35
+ }
36
+ function overrides(entries, where, parent) {
37
+ for (const [selector, value] of Object.entries(entries ?? {})) {
38
+ const name = selector === "." ? parent : overridePackageName(selector, checked);
39
+ const location = [...where, selector];
40
+ if (value && typeof value === "object" && !Array.isArray(value))
41
+ overrides(value, location, name);
42
+ else if (name)
43
+ check(name, value, location);
44
+ }
45
+ }
46
+ overrides(pkg.overrides, ["overrides"]);
47
+ overrides(pkg.resolutions, ["resolutions"]);
48
+ overrides(pkg.pnpm?.overrides, ["pnpm", "overrides"]);
49
+ return issues;
50
+ }
51
+ export function printDependencyPins(issues) {
52
+ if (!issues.length) {
53
+ console.log("Dependency pins match Spark's expected versions.");
54
+ return;
55
+ }
56
+ const rows = [["Package", "Found", "Expected", "Where"], ...issues.map(issue => [issue.package, issue.found, issue.expected, issue.where.join(" → ")])];
57
+ const widths = rows[0].map((_, column) => Math.max(...rows.map(row => row[column].length)));
58
+ for (const row of rows)
59
+ console.log(row.map((value, column) => value.padEnd(widths[column])).join(" ").trimEnd());
60
+ }
61
+ /** Edit only mismatched values and insert missing pins, preserving existing formatting. */
62
+ export function upgradeDependencyPins(root, dryRun = false, expected = expectedDependencyPins, requiredOverrides) {
63
+ const file = path.join(root, "package.json");
64
+ let source = readFileSync(file, "utf8");
65
+ const pkg = JSON.parse(source);
66
+ const parsed = ts.parseJsonText(file, source);
67
+ const object = parsed.statements[0].expression;
68
+ function property(object, key) {
69
+ return object.properties.find(p => ts.isPropertyAssignment(p) && ts.isStringLiteral(p.name) && p.name.text === key);
70
+ }
71
+ function rejectDuplicates(node, where, nested = true) {
72
+ if (!node || !ts.isObjectLiteralExpression(node))
73
+ return;
74
+ const keys = new Set();
75
+ for (const entry of node.properties) {
76
+ if (!ts.isPropertyAssignment(entry) || !ts.isStringLiteral(entry.name))
77
+ continue;
78
+ const key = entry.name.text;
79
+ if (keys.has(key))
80
+ throw new Error(`package.json has duplicate key ${JSON.stringify(key)} in ${where.join(" → ") || "root"}. No files were changed.`);
81
+ keys.add(key);
82
+ if (nested)
83
+ rejectDuplicates(entry.initializer, [...where, key]);
84
+ }
85
+ }
86
+ rejectDuplicates(object, [], false);
87
+ for (const section of ["dependencies", "devDependencies", "overrides", "resolutions"])
88
+ rejectDuplicates(property(object, section)?.initializer, [section]);
89
+ const pnpm = property(object, "pnpm")?.initializer;
90
+ rejectDuplicates(pnpm, ["pnpm"], false);
91
+ if (pnpm && ts.isObjectLiteralExpression(pnpm))
92
+ rejectDuplicates(property(pnpm, "overrides")?.initializer, ["pnpm", "overrides"]);
93
+ const issues = dependencyPinIssues(pkg, supportedPlatforms(root), expected);
94
+ if (requiredOverrides) {
95
+ let entries = pkg;
96
+ for (const key of requiredOverrides.where)
97
+ entries = entries?.[key];
98
+ for (const [name, version] of Object.entries(requiredOverrides.pins)) {
99
+ if (!Object.hasOwn(entries ?? {}, name))
100
+ issues.push({ package: name, found: "(missing)", expected: version, where: [...requiredOverrides.where, name], missing: true });
101
+ }
102
+ }
103
+ if (!issues.length)
104
+ return issues;
105
+ const edits = [];
106
+ const missing = issues.filter(issue => issue.missing);
107
+ if (missing.length) {
108
+ const indent = source.match(/^[\t ]+(?=")/m)?.[0] ?? " ";
109
+ const newline = source.includes("\r\n") ? "\r\n" : "\n";
110
+ const additions = {};
111
+ for (const issue of missing) {
112
+ let entries = additions;
113
+ for (const key of issue.where.slice(0, -1))
114
+ entries = entries[key] ??= {};
115
+ entries[issue.where.at(-1)] = issue.expected;
116
+ }
117
+ function insert(target, additions, where) {
118
+ const entries = [];
119
+ for (const [key, value] of Object.entries(additions)) {
120
+ const existing = property(target, key)?.initializer;
121
+ if (existing) {
122
+ if (!ts.isObjectLiteralExpression(existing))
123
+ throw new Error(`package.json ${[...where, key].join(" → ")} must be an object. No files were changed.`);
124
+ insert(existing, value, [...where, key]);
125
+ }
126
+ else
127
+ entries.push(`${JSON.stringify(key)}: ${JSON.stringify(value, null, indent)}`);
128
+ }
129
+ if (!entries.length)
130
+ return;
131
+ const last = target.properties.at(-1);
132
+ const baseIndent = source.slice(0, target.getStart(parsed)).match(/(?:^|\n)([\t ]*)[^\n]*$/)[1];
133
+ const multiline = !last || source.slice(target.getStart(parsed), target.end).includes("\n");
134
+ const separator = multiline ? newline + baseIndent + indent : " ";
135
+ const text = entries.map(entry => entry.replaceAll("\n", newline + baseIndent + indent)).join("," + separator);
136
+ edits.push(last ? { start: last.end, end: last.end, text: "," + separator + text }
137
+ : { start: target.getStart(parsed) + 1, end: target.end - 1, text: separator + text + newline + baseIndent });
138
+ }
139
+ insert(object, additions, []);
140
+ }
141
+ for (const issue of issues) {
142
+ if (issue.missing)
143
+ continue;
144
+ // Fixing the referenced direct dependency also fixes npm/pnpm's $ref override.
145
+ if (["overrides", "pnpm"].includes(issue.where[0]) && issue.found.startsWith("$") && issues.some(direct => ["dependencies", "devDependencies"].includes(direct.where[0]) && direct.package === issue.found.slice(1) && direct.expected === issue.expected))
146
+ continue;
147
+ let node = object;
148
+ for (const key of issue.where)
149
+ node = property(node, key).initializer;
150
+ edits.push({ start: node.getStart(parsed), end: node.end, text: JSON.stringify(issue.expected) });
151
+ }
152
+ for (const edit of edits.sort((a, b) => b.start - a.start))
153
+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);
154
+ if (!dryRun)
155
+ writeFileSync(file, source);
156
+ return issues;
157
+ }
@@ -1,10 +1,11 @@
1
1
  import { spawnProcess } from "./process.js";
2
2
  import path from "node:path";
3
3
  import { prepareConfig, selectTarget, supportedPlatforms } from "@legendapp/spark-desktop-config/config.cjs";
4
+ import { ensureProjectVersion } from "./project-version.js";
4
5
  import { dev } from "./dev.js";
5
6
  import { findProject } from "./local.js";
6
7
  import { hostPlatform } from "./platform.js";
7
- import { nodeCommand } from "./windows.js";
8
+ import { nodeCommand } from "./process.js";
8
9
  // Consume only spark options. Expo validates its flags, aliases and values.
9
10
  export function devArguments(args) {
10
11
  const spark = {};
@@ -59,6 +60,7 @@ export async function devCommand(args) {
59
60
  return;
60
61
  }
61
62
  const root = findProject(start);
63
+ ensureProjectVersion(root);
62
64
  const { desktop, initial } = devTargets(supportedPlatforms(root), options.platform ?? process.env.SPARK_PLATFORM);
63
65
  // This selects only desktop build/signature state in the supervisor. Expo's
64
66
  // child uses shared development config and chooses each JS graph per request.
@@ -3,7 +3,7 @@ import { acquireRunner } from "./runner-install.js";
3
3
  import { spawnProcess } from "./process.js";
4
4
  import { windowsMetroPort, stopWindowsMetro } from "./windows-metro.js";
5
5
  import { architecture, projectPlatform } from "./platform.js";
6
- import { nodeCommand } from "./windows.js";
6
+ import { nodeCommand } from "./process.js";
7
7
  import { readAppConfig } from "./project.js";
8
8
  import { existsSync, rmSync, watch } from "node:fs";
9
9
  import path from "node:path";
@@ -0,0 +1,128 @@
1
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { readJson, writeJson } from "./json.js";
5
+ import { readPnpmConfig } from "./package-manager-config.js";
6
+ import { packageManager, managerCommand } from "./package-manager.js";
7
+ import { run } from "./commands.js";
8
+ const defaults = JSON.parse(readFileSync(new URL("../templates/blank-typescript/package.json", import.meta.url), "utf8"));
9
+ export function enrichedHtmlPinPolicy(overrides) {
10
+ return Object.fromEntries(Object.entries(overrides).filter(([name]) => name === "dompurify" || name.startsWith("@tiptap/")));
11
+ }
12
+ export const enrichedHtmlPins = enrichedHtmlPinPolicy(defaults.overrides);
13
+ function semver() {
14
+ return createRequire(createRequire(import.meta.url).resolve("npm/package.json"))("semver");
15
+ }
16
+ // Read installed manifests even when exports hides package.json. Real paths retain
17
+ // the importer's dependency context in pnpm's isolated layout.
18
+ function manifestFrom(root, name) {
19
+ const req = createRequire(path.join(root, "package.json"));
20
+ const file = req.resolve.paths(name)?.map(base => path.join(base, name, "package.json")).find(existsSync);
21
+ return file ? realpathSync(file) : undefined;
22
+ }
23
+ export function enrichedHtmlPinIssues(root, policy = enrichedHtmlPins) {
24
+ const sdk = manifestFrom(root, "@legendapp/spark");
25
+ const html = [manifestFrom(root, "react-native-enriched-html"), sdk && manifestFrom(path.resolve(path.dirname(sdk), readJson(sdk).spark?.bundledModuleRoot ?? "."), "react-native-enriched-html")].filter((file) => !!file);
26
+ if (!html.length)
27
+ return [];
28
+ const { valid, lt } = semver();
29
+ const react = manifestFrom(root, "react");
30
+ if (!react)
31
+ throw new Error("Install the app's React dependency before checking enriched-html web dependencies.");
32
+ const expected = { ...policy, "react-dom": readJson(react).version };
33
+ const issues = [];
34
+ const queue = [...html], visited = new Set();
35
+ while (queue.length) {
36
+ const file = queue.shift();
37
+ if (visited.has(file))
38
+ continue;
39
+ visited.add(file);
40
+ const pkg = readJson(file);
41
+ if (pkg.name in expected) {
42
+ const version = expected[pkg.name];
43
+ if (!valid(pkg.version) || (pkg.name === "react-dom" ? pkg.version !== version : lt(pkg.version, version)))
44
+ issues.push({ package: pkg.name, found: pkg.version, expected: version, where: [file] });
45
+ }
46
+ for (const name of Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies, ...pkg.optionalDependencies, "react-dom": "*" })) {
47
+ if (!(name in expected))
48
+ continue;
49
+ const dependency = manifestFrom(path.dirname(file), name);
50
+ if (dependency)
51
+ queue.push(dependency);
52
+ }
53
+ }
54
+ return issues;
55
+ }
56
+ /** App-owned solver policy; never edits enriched-html or its installed metadata. */
57
+ export function repairEnrichedHtmlPins(root, manager, dryRun = false, policy = enrichedHtmlPins) {
58
+ const issues = enrichedHtmlPinIssues(root, policy);
59
+ if (!issues.length)
60
+ return issues;
61
+ const { validRange, lt, minVersion } = semver();
62
+ function preservePin(spec, version, name) {
63
+ if (typeof spec !== "string" || !validRange(spec))
64
+ return false;
65
+ const minimum = minVersion(spec);
66
+ return !!minimum && !lt(minimum, version) && (name !== "react-dom" || spec === version || lt(version, minimum));
67
+ }
68
+ const pkg = readJson(path.join(root, "package.json"));
69
+ const yaml = manager === "pnpm" ? readPnpmConfig(root) : undefined;
70
+ const field = manager === "yarn" ? "resolutions" : "overrides";
71
+ const owner = manager === "pnpm" ? (pkg.pnpm ??= {}) : pkg;
72
+ const pins = owner[field] ??= {};
73
+ const expected = { ...policy, "react-dom": readJson(manifestFrom(root, "react")).version };
74
+ let changed = false, yamlChanged = false;
75
+ for (const [name, version] of Object.entries(expected)) {
76
+ if (!version)
77
+ continue;
78
+ // pnpm 11's YAML wins; mirror it for pnpm 10 without downgrading either pin.
79
+ const yamlPin = yaml?.getIn(["overrides", name]);
80
+ const direct = pkg.dependencies?.[name] ?? pkg.devDependencies?.[name];
81
+ const entry = pins[name];
82
+ const value = entry && typeof entry === "object" ? entry["."] : entry;
83
+ const current = typeof value === "string" && value.startsWith("$") ? pkg.dependencies?.[value.slice(1)] ?? pkg.devDependencies?.[value.slice(1)] : value;
84
+ const candidates = [yamlPin, current, direct].filter(spec => preservePin(spec, version, name));
85
+ const target = candidates.reduce((best, spec) => lt(minVersion(best), minVersion(spec)) ? spec : best, candidates[0] ?? version);
86
+ if (!preservePin(current, version, name)) {
87
+ if (entry && typeof entry === "object")
88
+ entry["."] = target;
89
+ else
90
+ pins[name] = target;
91
+ changed = true;
92
+ }
93
+ if (yaml && !preservePin(yamlPin, version, name)) {
94
+ yaml.setIn(["overrides", name], target);
95
+ yamlChanged = true;
96
+ }
97
+ // npm rejects overrides that differ from a direct dependency's spec.
98
+ for (const section of ["dependencies", "devDependencies"]) {
99
+ if (pkg[section]?.[name] && !preservePin(pkg[section][name], version, name)) {
100
+ pkg[section][name] = target;
101
+ changed = true;
102
+ }
103
+ }
104
+ }
105
+ if (!dryRun) {
106
+ if (changed)
107
+ writeJson(path.join(root, "package.json"), pkg);
108
+ if (yamlChanged)
109
+ writeFileSync(path.join(root, "pnpm-workspace.yaml"), yaml.toString());
110
+ }
111
+ return issues;
112
+ }
113
+ export function assertEnrichedHtmlPins(root, policy = enrichedHtmlPins) {
114
+ const issues = enrichedHtmlPinIssues(root, policy);
115
+ if (!issues.length)
116
+ return;
117
+ const manager = packageManager(root);
118
+ repairEnrichedHtmlPins(root, manager, false, policy);
119
+ throw new Error(`Enriched HTML web dependency pins need installation (${[...new Set(issues.map(issue => `${issue.package}@${issue.found} → ${issue.expected}`))].join(", ")}). App-level pins checked and repaired; newer explicit pins preserved. Run ${manager} install, then retry. If versions still differ, align your explicit pins with the app's React and Spark's web dependency policy.`);
120
+ }
121
+ /** Existing install paths can also repair a newly introduced enriched-html graph. */
122
+ export async function installWithEnrichedHtmlPins(root, manager, policy = enrichedHtmlPins) {
123
+ repairEnrichedHtmlPins(root, manager, false, policy);
124
+ await run(root, managerCommand(manager, ["install"]));
125
+ if (repairEnrichedHtmlPins(root, manager, false, policy).length)
126
+ await run(root, managerCommand(manager, ["install"]));
127
+ assertEnrichedHtmlPins(root, policy);
128
+ }