@legendapp/spark 0.0.1-next.4 → 0.0.1-next.6

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 (132) hide show
  1. package/README.md +1 -1
  2. package/customize.ts +2 -0
  3. package/html.ts +1 -0
  4. package/markdown.ts +1 -0
  5. package/package.json +22 -13
  6. package/patches/dependencies.json +10 -4
  7. package/patches/react-native-enriched-html@1.1.1.patch +854 -0
  8. package/patches/{react-native-enriched-markdown@1.0.2.patch → react-native-enriched-markdown@1.1.1.patch} +2560 -1983
  9. package/schema.json +104 -0
  10. package/skills/spark/SKILL.md +56 -0
  11. package/skills/spark/UPGRADING.md +254 -0
  12. package/vendor/node_modules/@legendapp/spark-ai/package.json +4 -4
  13. package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.cjs +11 -0
  14. package/vendor/node_modules/@legendapp/spark-ai/src/invocation-command.d.cts +2 -0
  15. package/vendor/node_modules/@legendapp/spark-ai/src/invocations.ts +2 -19
  16. package/vendor/node_modules/@legendapp/spark-audio/package.json +3 -3
  17. package/vendor/node_modules/@legendapp/spark-auth-session/package.json +3 -3
  18. package/vendor/node_modules/@legendapp/spark-cli/dist/add-desktop.js +4 -4
  19. package/vendor/node_modules/@legendapp/spark-cli/dist/build.js +3 -0
  20. package/vendor/node_modules/@legendapp/spark-cli/dist/create.js +31 -11
  21. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-ai.cjs +108 -0
  22. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-artifacts.js +315 -0
  23. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-cli.cjs +75 -0
  24. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-github.cjs +133 -0
  25. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-policy.cjs +102 -0
  26. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-provider.cjs +2 -0
  27. package/vendor/node_modules/@legendapp/spark-cli/dist/customize-worker.cjs +273 -0
  28. package/vendor/node_modules/@legendapp/spark-cli/dist/dependency-pins.js +54 -29
  29. package/vendor/node_modules/@legendapp/spark-cli/dist/dev-command.js +2 -0
  30. package/vendor/node_modules/@legendapp/spark-cli/dist/enriched-html-pins.js +128 -0
  31. package/vendor/node_modules/@legendapp/spark-cli/dist/expo-dev-patch.cjs +30 -1
  32. package/vendor/node_modules/@legendapp/spark-cli/dist/index.js +16 -7
  33. package/vendor/node_modules/@legendapp/spark-cli/dist/init-template.d.cts +1 -0
  34. package/vendor/node_modules/@legendapp/spark-cli/dist/js-runtime.cjs +96 -0
  35. package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.cjs +152 -0
  36. package/vendor/node_modules/@legendapp/spark-cli/dist/migration-helpers.d.cts +15 -0
  37. package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.cjs +184 -0
  38. package/vendor/node_modules/@legendapp/spark-cli/dist/migrations.d.cts +16 -0
  39. package/vendor/node_modules/@legendapp/spark-cli/dist/native-patch-preflight.js +2 -0
  40. package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager-config.js +41 -0
  41. package/vendor/node_modules/@legendapp/spark-cli/dist/package-manager.js +13 -0
  42. package/vendor/node_modules/@legendapp/spark-cli/dist/project-version.js +12 -0
  43. package/vendor/node_modules/@legendapp/spark-cli/dist/project.js +40 -9
  44. package/vendor/node_modules/@legendapp/spark-cli/dist/release.json +19 -19
  45. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.ps1 +87 -0
  46. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-bootstrap.sh +107 -0
  47. package/vendor/node_modules/@legendapp/spark-cli/dist/runtime-downloads.tsv +13 -0
  48. package/vendor/node_modules/@legendapp/spark-cli/dist/sdk-install.js +8 -3
  49. package/vendor/node_modules/@legendapp/spark-cli/dist/upgrade.js +102 -0
  50. package/vendor/node_modules/@legendapp/spark-cli/package.json +6 -4
  51. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/.claude/skills/spark/SKILL.md +9 -0
  52. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/AGENTS.md +4 -0
  53. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/CLAUDE.md +4 -0
  54. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/README.md +15 -0
  55. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/package.json +46 -2
  56. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/.claude/skills/spark/SKILL.md +9 -0
  57. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/AGENTS.md +4 -0
  58. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/CLAUDE.md +4 -0
  59. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/README.md +15 -0
  60. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/package.json +45 -2
  61. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/.claude/skills/spark/SKILL.md +9 -0
  62. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/AGENTS.md +4 -0
  63. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/CLAUDE.md +4 -0
  64. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/README.md +15 -0
  65. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/package.json +46 -2
  66. package/vendor/node_modules/@legendapp/spark-clipboard/package.json +3 -3
  67. package/vendor/node_modules/@legendapp/spark-codex/package.json +3 -3
  68. package/vendor/node_modules/@legendapp/spark-commands/package.json +6 -6
  69. package/vendor/node_modules/@legendapp/spark-context-menu/package.json +3 -3
  70. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/RNDesktopApp.mm +14 -1
  71. package/vendor/node_modules/@legendapp/spark-desktop-app/package.json +2 -2
  72. package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize-hooks.ts +17 -0
  73. package/vendor/node_modules/@legendapp/spark-desktop-app/src/customize.ts +117 -0
  74. package/vendor/node_modules/@legendapp/spark-desktop-config/app.plugin.cjs +20 -1
  75. package/vendor/node_modules/@legendapp/spark-desktop-config/config.cjs +3 -2
  76. package/vendor/node_modules/@legendapp/spark-desktop-config/config.d.cts +14 -0
  77. package/vendor/node_modules/@legendapp/spark-desktop-config/customize-provider.cjs +16 -0
  78. package/vendor/node_modules/@legendapp/spark-desktop-config/customize.cjs +16 -0
  79. package/vendor/node_modules/@legendapp/spark-desktop-config/package.json +4 -4
  80. package/vendor/node_modules/@legendapp/spark-desktop-config/schema.json +104 -0
  81. package/vendor/node_modules/@legendapp/spark-desktop-host/SparkCustomize.mm +517 -0
  82. package/vendor/node_modules/@legendapp/spark-desktop-host/package.json +4 -3
  83. package/vendor/node_modules/@legendapp/spark-desktop-links/package.json +3 -3
  84. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/RNDesktopShortcuts.mm +3 -1
  85. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.h +3 -0
  86. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/macos/keyboard-manager/RNKeyboardManager.mm +1 -1
  87. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/package.json +3 -3
  88. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/window-manager/RNWindowManager.mm +5 -4
  89. package/vendor/node_modules/@legendapp/spark-desktop-windows/package.json +4 -4
  90. package/vendor/node_modules/@legendapp/spark-desktop-windows/src/api.ts +62 -25
  91. package/vendor/node_modules/@legendapp/spark-desktop-windows/src/macos-adapter.ts +7 -5
  92. package/vendor/node_modules/@legendapp/spark-documents/package.json +8 -8
  93. package/vendor/node_modules/@legendapp/spark-drag-drop/package.json +3 -3
  94. package/vendor/node_modules/@legendapp/spark-file-dialog/package.json +3 -3
  95. package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.h +1 -0
  96. package/vendor/node_modules/@legendapp/spark-file-system/macos/SparkFileMutations.mm +11 -10
  97. package/vendor/node_modules/@legendapp/spark-file-system/package.json +3 -3
  98. package/vendor/node_modules/@legendapp/spark-global-shortcuts/package.json +3 -3
  99. package/vendor/node_modules/@legendapp/spark-html/package.json +24 -0
  100. package/vendor/node_modules/@legendapp/spark-html/src/Html.tsx +22 -0
  101. package/vendor/node_modules/@legendapp/spark-html/src/HtmlInput.tsx +102 -0
  102. package/vendor/node_modules/@legendapp/spark-html/src/index.ts +4 -0
  103. package/vendor/node_modules/@legendapp/spark-html/src/types.ts +4 -0
  104. package/vendor/node_modules/@legendapp/spark-markdown/package.json +24 -0
  105. package/vendor/node_modules/@legendapp/spark-markdown/src/Markdown.tsx +24 -0
  106. package/vendor/node_modules/@legendapp/spark-markdown/src/MarkdownInput.tsx +111 -0
  107. package/vendor/node_modules/@legendapp/spark-markdown/src/index.ts +4 -0
  108. package/vendor/node_modules/@legendapp/spark-message-dialog/package.json +3 -3
  109. package/vendor/node_modules/@legendapp/spark-native-menu/package.json +3 -3
  110. package/vendor/node_modules/@legendapp/spark-notifications/package.json +3 -3
  111. package/vendor/node_modules/@legendapp/spark-processes/package.json +3 -3
  112. package/vendor/node_modules/@legendapp/spark-rich-text/package.json +18 -0
  113. package/vendor/node_modules/@legendapp/spark-rich-text/src/components.tsx +52 -0
  114. package/vendor/node_modules/@legendapp/spark-rich-text/src/index.ts +4 -0
  115. package/vendor/node_modules/@legendapp/spark-rich-text/src/types.ts +24 -0
  116. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.macos.ts +55 -0
  117. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputShortcuts.ts +13 -0
  118. package/vendor/node_modules/@legendapp/spark-rich-text/src/useInputValue.ts +14 -0
  119. package/vendor/node_modules/@legendapp/spark-rich-text/src/value.ts +16 -0
  120. package/vendor/node_modules/@legendapp/spark-secure-storage/package.json +3 -3
  121. package/vendor/node_modules/@legendapp/spark-settings/package.json +3 -3
  122. package/vendor/node_modules/@legendapp/spark-settings-ui/package.json +5 -5
  123. package/vendor/node_modules/@legendapp/spark-sqlite/package.json +3 -3
  124. package/vendor/node_modules/@legendapp/spark-system/package.json +3 -3
  125. package/vendor/node_modules/@legendapp/spark-tray/package.json +3 -3
  126. package/vendor/node_modules/@legendapp/spark-ui/macos/appkit-split-view/RNSidebarSplitViewComponent.mm +102 -14
  127. package/vendor/node_modules/@legendapp/spark-ui/package.json +3 -3
  128. package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/SidebarSplitViewNativeComponent.ts +5 -0
  129. package/vendor/node_modules/@legendapp/spark-ui/src/appkit-split-view/index.tsx +12 -4
  130. package/vendor/node_modules/@legendapp/spark-updates/package.json +3 -3
  131. package/vendor/node_modules/@legendapp/spark-webview/package.json +2 -2
  132. package/vendor/node_modules/@legendapp/spark-window-options/package.json +1 -1
@@ -0,0 +1,15 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
2
+ export type JsonObject = { [key: string]: JsonValue };
3
+ export interface FileChange { file: string; before: string | null; after: string | null }
4
+ export interface ManualStep { version: string; message: string; notes: string }
5
+ export interface MigrationContext {
6
+ readFile(file: string): string | null;
7
+ writeFile(file: string, content: string): void;
8
+ editJson<T extends object = JsonObject>(file: string, edit: (value: T) => void): void;
9
+ renameFile(from: string, to: string): void;
10
+ updateTemplate(file: string, previous: string, next: string): void;
11
+ replaceImport(from: string, to: string, names?: Readonly<Record<string, string>>): void;
12
+ manualStep(message: string): void;
13
+ }
14
+ export const upgradeNotesPath: string;
15
+ export function createMigrationContext(root: string, version: string, changes: Map<string, FileChange>, manualSteps: ManualStep[]): MigrationContext;
@@ -0,0 +1,184 @@
1
+ // @ts-check
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { createRequire } = require('node:module');
5
+ const { createMigrationContext } = require('./migration-helpers.cjs');
6
+
7
+ const skillPath = 'node_modules/@legendapp/spark/skills/spark/SKILL.md';
8
+ const start = '<!-- spark:skill:start -->';
9
+ const end = '<!-- spark:skill:end -->';
10
+ const pointer = `${start}\nFrom the app root, read [Spark's app development skill](${skillPath}) before working on this app.\nThe installed Spark version owns these instructions; do not copy them here.\n${end}`;
11
+ const claudePointer = `---\nname: spark\ndescription: Develop, build, diagnose, or upgrade a Legend Spark desktop app.\n---\n\n${pointer}\n`;
12
+
13
+ /** @param {string} source */
14
+ function mergePointer(source) {
15
+ const first = source.indexOf(start);
16
+ const last = source.indexOf(end);
17
+ if (first === -1 && last === -1) return source + (source ? (source.endsWith('\n') ? '\n' : '\n\n') : '') + pointer + '\n';
18
+ if (first === -1 || last < first || source.indexOf(start, first + start.length) !== -1 || source.indexOf(end, last + end.length) !== -1) {
19
+ throw new Error('Malformed Spark skill markers. Repair the spark:skill section, then run spark upgrade.');
20
+ }
21
+ return source.slice(0, first) + pointer + source.slice(last + end.length);
22
+ }
23
+
24
+ /** @param {import('./migration-helpers.cjs').MigrationContext} context */
25
+ function planPointers(context) {
26
+ const edits = ['AGENTS.md', 'CLAUDE.md'].map(name => {
27
+ const file = name;
28
+ const before = context.readFile(file) ?? '';
29
+ return { file, before, after: mergePointer(before) };
30
+ });
31
+ const file = '.claude/skills/spark/SKILL.md';
32
+ const before = context.readFile(file) ?? '';
33
+ // A pre-existing user skill keeps its frontmatter and instructions.
34
+ edits.push({ file, before, after: !before || before === claudePointer ? claudePointer : mergePointer(before) });
35
+ for (const { file, before, after } of edits) {
36
+ if (before === after) continue;
37
+ context.writeFile(file, after);
38
+ }
39
+ }
40
+
41
+ /** @param {string} root */
42
+ function refreshPointers(root) {
43
+ const changes = new Map();
44
+ planPointers(createMigrationContext(root, '', changes, []));
45
+ writeChanges(root, [...changes.values()]);
46
+ }
47
+
48
+ /** @param {import('./migration-helpers.cjs').MigrationContext} context */
49
+ function upgradeWindowConfig(context) {
50
+ for (const file of ['desktop.config.json', 'app.json']) {
51
+ context.editJson(file, /** @param {{ window?: import('./migration-helpers.cjs').JsonObject; expo?: { extra?: { spark?: { window?: import('./migration-helpers.cjs').JsonObject } } } }} config */ config => {
52
+ const options = file === 'desktop.config.json' ? config.window : config.expo?.extra?.spark?.window;
53
+ if (!options) return;
54
+ if (typeof options !== 'object' || Array.isArray(options)) { context.manualStep(`Repair window configuration in ${file}; expected an object.`); return; }
55
+ for (const [nested, width, height] of [['size', 'width', 'height'], ['minSize', 'minWidth', 'minHeight'], ['maxSize', 'maxWidth', 'maxHeight']]) {
56
+ if (!(width in options) && !(height in options)) continue;
57
+ if (typeof options[width] !== 'number' || typeof options[height] !== 'number' || options[nested] !== undefined) {
58
+ context.manualStep(`Merge legacy ${width}/${height} into window.${nested} in ${file}; incomplete or conflicting dimensions need review.`);
59
+ } else {
60
+ options[nested] = { width: options[width], height: options[height] };
61
+ delete options[width]; delete options[height];
62
+ }
63
+ }
64
+ if ('restoreFrame' in options) {
65
+ if ('restoreBounds' in options && options.restoreBounds !== options.restoreFrame) context.manualStep(`Resolve window.restoreFrame/restoreBounds in ${file}.`);
66
+ else { options.restoreBounds = options.restoreFrame; delete options.restoreFrame; }
67
+ }
68
+ for (const [legacy, nested] of [['material', 'backgroundMaterial'], ['trafficLights', 'titleBar']]) {
69
+ if (!(legacy in options)) continue;
70
+ const macos = /** @type {import('./migration-helpers.cjs').JsonObject} */ (options.macos ?? {});
71
+ if (typeof macos !== 'object' || Array.isArray(macos) || macos[nested] !== undefined) context.manualStep(`Merge window.${legacy} into window.macos.${nested} in ${file}.`);
72
+ else {
73
+ macos[nested] = legacy === 'trafficLights' ? { trafficLights: options[legacy] } : options[legacy];
74
+ options.macos = macos; delete options[legacy];
75
+ }
76
+ }
77
+ });
78
+ }
79
+ }
80
+
81
+ // Keep released migration versions fixed. New steps must be idempotent; only
82
+ // steps that preserve user configuration and need no install may run at startup.
83
+ /** @type {import('./migrations.cjs').Migration[]} */
84
+ const migrations = [
85
+ {
86
+ version: '0.0.1-next.3', automatic: false, breaking: true,
87
+ apply(context) {
88
+ upgradeWindowConfig(context);
89
+ context.replaceImport('@legendapp/spark/message-dialog', '@legendapp/spark/dialogs');
90
+ context.replaceImport('@legendapp/spark/expo-metro', '@legendapp/spark/metro');
91
+ context.manualStep('Review next.3 API contracts: dialogs/files, windows, registrations, settings, menus, shortcuts, processes, links, audio, notifications, updates, UI, removed universal tooling, and native lifecycle. Adapt arguments, results and cleanup; rebuild custom native modules.');
92
+ },
93
+ },
94
+ { version: '0.0.1-next.4', automatic: true, apply(context) {
95
+ planPointers(context);
96
+ context.manualStep('If the app uses a custom runtime, rebuild it for next.4 native dependency patches; review production module selection and affected SidebarSplitView/Windows native flows.');
97
+ } },
98
+ ];
99
+
100
+ /** @param {string} root */
101
+ function installedSparkVersion(root) {
102
+ const file = createRequire(path.join(root, 'package.json')).resolve('@legendapp/spark/package.json');
103
+ return JSON.parse(fs.readFileSync(file, 'utf8')).version;
104
+ }
105
+
106
+ /** @type {typeof import('./migrations.cjs').planMigrations} */
107
+ function planMigrations(root, version, { automatic = false, fromVersion } = {}) {
108
+ const { compare, valid } = createRequire(require.resolve('npm/package.json'))('semver');
109
+ const file = path.join(root, '.spark/version');
110
+ const previous = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : fromVersion;
111
+ if (!valid(version) || (previous !== undefined && (!valid(previous) || compare(previous, version) > 0))) {
112
+ throw new Error(`Spark project version ${previous ?? '(unrecorded)'} cannot migrate to ${version}. Run spark upgrade.`);
113
+ }
114
+ const pending = migrations.filter(step => (!previous || compare(step.version, previous) > 0) && compare(step.version, version) <= 0).sort((a, b) => compare(a.version, b.version));
115
+ if (automatic && pending.some(step => !step.automatic)) throw new Error('Spark has pending migrations that require an install or configuration changes. Run spark upgrade.');
116
+ const changes = new Map();
117
+ /** @type {import('./migration-helpers.cjs').ManualStep[]} */
118
+ const manualSteps = [];
119
+ for (const step of pending) step.apply(createMigrationContext(root, step.version, changes, manualSteps));
120
+ planPointers(createMigrationContext(root, version, changes, manualSteps));
121
+ if (manualSteps.length) {
122
+ const context = createMigrationContext(root, version, changes, manualSteps);
123
+ const notesFile = '.spark/upgrade-notes.md';
124
+ let notes = context.readFile(notesFile) ?? '# Spark upgrade manual steps\n\nComplete these steps using the installed version notes. Keep this file until reviewed.\n';
125
+ for (const step of manualSteps) {
126
+ const entry = `- [ ] [${step.version}](../${step.notes}): ${step.message}`;
127
+ if (!notes.replaceAll('- [x]', '- [ ]').includes(entry)) notes += '\n' + entry + '\n';
128
+ }
129
+ context.writeFile(notesFile, notes);
130
+ }
131
+ return { previous, version, versions: pending.map(step => step.version), changes: [...changes.values()].filter(change => change.before !== change.after), manualSteps };
132
+ }
133
+
134
+ /** @param {string} root @param {import('./migration-helpers.cjs').FileChange[]} changes */
135
+ function writeChanges(root, changes) {
136
+ const context = createMigrationContext(root, '', new Map(), []);
137
+ for (const change of changes) {
138
+ if (context.readFile(change.file) !== change.before) throw new Error(`Migration input changed: ${change.file}. Run spark upgrade again.`);
139
+ }
140
+ for (const { file, after } of changes) {
141
+ const destination = path.join(root, file);
142
+ if (after === null) fs.unlinkSync(destination);
143
+ else {
144
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
145
+ const temporary = `${destination}.${process.pid}.tmp`;
146
+ fs.writeFileSync(temporary, after);
147
+ fs.renameSync(temporary, destination);
148
+ }
149
+ }
150
+ }
151
+
152
+ /** @type {typeof import('./migrations.cjs').applyMigrationPlan} */
153
+ function applyMigrationPlan(root, plan, recordVersion = true) {
154
+ writeChanges(root, plan.changes);
155
+ if (recordVersion) recordProjectVersion(root, plan.version);
156
+ }
157
+
158
+ /** @type {typeof import('./migrations.cjs').recordProjectVersion} */
159
+ function recordProjectVersion(root, version) {
160
+ const file = path.join(root, '.spark/version');
161
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === version + '\n') return;
162
+ // Record only successful migrations. A failed/partial attempt is safe to retry.
163
+ fs.mkdirSync(path.dirname(file), { recursive: true });
164
+ const temporary = `${file}.${process.pid}.tmp`;
165
+ fs.writeFileSync(temporary, version + '\n');
166
+ fs.renameSync(temporary, file);
167
+ }
168
+
169
+ /** @type {typeof import('./migrations.cjs').migrateProject} */
170
+ function migrateProject(root, version, automatic = true, options = {}) {
171
+ const plan = planMigrations(root, version, { ...options, automatic });
172
+ applyMigrationPlan(root, plan);
173
+ return plan.versions;
174
+ }
175
+
176
+ /** @type {typeof import('./migrations.cjs').printMigrationPlan} */
177
+ function printMigrationPlan(plan) {
178
+ console.log(`Migrations: ${plan.versions.join(' → ') || '(none pending)'}`);
179
+ for (const change of plan.changes) console.log(` ${change.after === null ? 'Delete' : change.before === null ? 'Create' : 'Edit'} ${change.file}`);
180
+ for (const step of plan.manualSteps) console.log(`Manual step (${step.version}): ${step.message}\n See ${step.notes}`);
181
+ console.log('Review .spark/upgrade-notes.md for outstanding manual steps after upgrading.');
182
+ }
183
+
184
+ module.exports = { pointer, claudePointer, mergePointer, refreshPointers, migrations, installedSparkVersion, migrateProject, planMigrations, applyMigrationPlan, recordProjectVersion, printMigrationPlan };
@@ -0,0 +1,16 @@
1
+ export const pointer: string;
2
+ export const claudePointer: string;
3
+ export function mergePointer(source: string): string;
4
+ export function refreshPointers(root: string): void;
5
+ import type { FileChange, ManualStep, MigrationContext } from './migration-helpers.cjs';
6
+ export interface Migration { version: string; automatic: boolean; breaking?: boolean; apply(context: MigrationContext): void }
7
+ export interface MigrationPlan { previous?: string; version: string; versions: string[]; changes: FileChange[]; manualSteps: ManualStep[] }
8
+ export interface MigrationOptions { automatic?: boolean; fromVersion?: string }
9
+ export const migrations: Migration[];
10
+ export function installedSparkVersion(root: string): string;
11
+ export function planMigrations(root: string, version: string, options?: MigrationOptions): MigrationPlan;
12
+ export function applyMigrationPlan(root: string, plan: MigrationPlan, recordVersion?: boolean): void;
13
+ /** Upgrade calls this only after installation and initialization succeed. */
14
+ export function recordProjectVersion(root: string, version: string): void;
15
+ export function printMigrationPlan(plan: MigrationPlan): void;
16
+ export function migrateProject(root: string, version: string, automatic?: boolean, options?: Pick<MigrationOptions, 'fromVersion'>): string[];
@@ -1,3 +1,4 @@
1
+ import { assertEnrichedHtmlPins } from "./enriched-html-pins.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { existsSync, readFileSync } from "node:fs";
3
4
  import path from "node:path";
@@ -68,6 +69,7 @@ export function validateWorkspaceNativePatches(root, packages) {
68
69
  return errors;
69
70
  }
70
71
  export function assertNativePatchPreflight(root) {
72
+ assertEnrichedHtmlPins(root);
71
73
  prepareNativePatches(root);
72
74
  const packages = installedPackages(root);
73
75
  const framework = findFramework(root);
@@ -0,0 +1,41 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parseDocument } from "yaml";
4
+ import { writeJson } from "./json.js";
5
+ import { overridePackageName } from "./package-manager.js";
6
+ export function readPnpmConfig(root) {
7
+ const file = path.join(root, "pnpm-workspace.yaml");
8
+ const document = parseDocument(existsSync(file) ? readFileSync(file, "utf8") : "");
9
+ if (document.errors.length)
10
+ throw new Error(`Invalid pnpm configuration: ${document.errors[0].message}`);
11
+ return document;
12
+ }
13
+ /** pnpm 11 reads installer settings from YAML; retain package.json settings for pnpm 10. */
14
+ export function writePackageConfig(root, pkg, manager, installRoot = root, preservedOverrides = []) {
15
+ if (manager === "pnpm") {
16
+ const file = path.join(root, "pnpm-workspace.yaml");
17
+ const document = readPnpmConfig(root);
18
+ if (!document.has("nodeLinker"))
19
+ document.set("nodeLinker", "hoisted");
20
+ for (const [name, version] of Object.entries(pkg.pnpm?.overrides ?? {})) {
21
+ if (!overridePackageName(name, preservedOverrides) || !document.hasIn(["overrides", name]))
22
+ document.setIn(["overrides", name], version);
23
+ }
24
+ for (const name of [...(pkg.pnpm?.onlyBuiltDependencies ?? [])]) {
25
+ if (!document.hasIn(["allowBuilds", name]))
26
+ document.setIn(["allowBuilds", name], true);
27
+ const source = pkg.dependencies?.[name] ?? pkg.pnpm?.overrides?.[name];
28
+ if (typeof source === "string" && source.startsWith("file:")) {
29
+ const key = `${name}@file:${path.relative(installRoot, path.resolve(installRoot, source.slice(5))).replaceAll("\\", "/")}`;
30
+ if (!document.hasIn(["allowBuilds", key]))
31
+ document.setIn(["allowBuilds", key], document.getIn(["allowBuilds", name]));
32
+ if (document.getIn(["allowBuilds", key]) === true && !pkg.pnpm.onlyBuiltDependencies.includes(key))
33
+ pkg.pnpm.onlyBuiltDependencies.push(key);
34
+ }
35
+ }
36
+ if (pkg.pnpm?.onlyBuiltDependencies)
37
+ pkg.pnpm.onlyBuiltDependencies = pkg.pnpm.onlyBuiltDependencies.filter((name) => document.getIn(["allowBuilds", name]) !== false);
38
+ writeFileSync(file, document.toString());
39
+ }
40
+ writeJson(path.join(root, "package.json"), pkg);
41
+ }
@@ -30,6 +30,11 @@ export function managerCommand(manager, args, env = process.env) {
30
30
  : [manager, ...args];
31
31
  }
32
32
  export function applyOverrides(pkg, overrides, manager) {
33
+ // pnpm 10 can auto-install a registry peer beside an overridden file archive.
34
+ // Provide Nitro at the installation root so camera/runtimes peers share the patched copy.
35
+ const nitro = overrides["react-native-nitro-modules"];
36
+ if (manager === "pnpm" && nitro?.startsWith("file:"))
37
+ pkg.dependencies = { ...pkg.dependencies, "react-native-nitro-modules": nitro };
33
38
  const existing = { ...pkg.overrides, ...pkg.resolutions, ...pkg.pnpm?.overrides };
34
39
  delete pkg.overrides;
35
40
  delete pkg.resolutions;
@@ -43,3 +48,11 @@ export function applyOverrides(pkg, overrides, manager) {
43
48
  pkg.overrides = { ...existing, ...overrides };
44
49
  }
45
50
  export function localArchive(file) { return `file:${path.resolve(file).replaceAll("\\", "/")}`; }
51
+ /** Match Yarn paths, version-qualified npm selectors and pnpm parent>child selectors. */
52
+ export function overridePackageName(selector, checked) {
53
+ // Comparators after @, whitespace or || belong to the version range.
54
+ const child = selector.split(/(?<![@\s|])>(?=[@a-zA-Z])/).at(-1);
55
+ const segments = child.split("/");
56
+ const childName = segments.at(-2)?.startsWith("@") ? segments.slice(-2).join("/") : segments.at(-1);
57
+ return checked.find(name => childName === name || childName.startsWith(name + "@"));
58
+ }
@@ -0,0 +1,12 @@
1
+ import { initializeTemplate } from "./init-template.cjs";
2
+ import { installedSparkVersion, migrateProject } from "./migrations.cjs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { readJson } from "./json.js";
5
+ const version = readJson(fileURLToPath(new URL("../package.json", import.meta.url))).version;
6
+ export function ensureProjectVersion(root) {
7
+ const installed = installedSparkVersion(root);
8
+ if (installed !== version)
9
+ throw new Error(`This CLI is Spark ${version}, but the app has ${installed}. Run spark upgrade using the app's installed CLI.`);
10
+ migrateProject(root, installed);
11
+ initializeTemplate(root);
12
+ }
@@ -1,3 +1,4 @@
1
+ import { assertEnrichedHtmlPins } from "./enriched-html-pins.js";
1
2
  import { nativeWindowOptions } from "@legendapp/spark-window-options";
2
3
  import { prepareNativePatches } from "@legendapp/spark-desktop-config/native-patches.cjs";
3
4
  import { macOSReleaseSettings } from "./macos-release.js";
@@ -11,7 +12,7 @@ import { existsSync, readFileSync, readdirSync, realpathSync, } from "node:fs";
11
12
  import path from "node:path";
12
13
  import { readJson, writeJson } from "./json.js";
13
14
  export { readJson, writeJson };
14
- export const VERSION = "0.0.1-next.4";
15
+ export const VERSION = "0.0.1-next.6";
15
16
  export function digest(value) {
16
17
  return createHash("sha256").update(value).digest("hex");
17
18
  }
@@ -98,9 +99,11 @@ export function installedPackages(root) {
98
99
  }
99
100
  return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
100
101
  }
101
- export function hashFiles(root, entries, windows = false) {
102
+ export function hashFiles(root, entries, windows = false, excluded = [], nativeSignature = false) {
102
103
  const hash = createHash("sha256");
103
104
  function visit(relative) {
105
+ if (excluded.includes(relative.split(path.sep).join("/")))
106
+ return;
104
107
  const file = path.join(root, relative);
105
108
  if (!existsSync(file))
106
109
  return;
@@ -116,7 +119,21 @@ export function hashFiles(root, entries, windows = false) {
116
119
  catch (error) {
117
120
  if (error.code !== "ENOTDIR")
118
121
  throw error;
119
- hash.update(relative.split(path.sep).join("/")).update(readFileSync(file));
122
+ let content = readFileSync(file);
123
+ if (nativeSignature && relative === "package.json") {
124
+ // Installation receipts and lifecycle scripts differ between workspace and packed copies.
125
+ const manifest = JSON.parse(content.toString());
126
+ delete manifest.scripts;
127
+ if (manifest.spark) {
128
+ delete manifest.spark.workspacePatch;
129
+ delete manifest.spark.dependencyPatch;
130
+ delete manifest.spark.patchHash;
131
+ if (!Object.keys(manifest.spark).length)
132
+ delete manifest.spark;
133
+ }
134
+ content = JSON.stringify(manifest);
135
+ }
136
+ hash.update(relative.split(path.sep).join("/")).update(content);
120
137
  }
121
138
  }
122
139
  for (const entry of entries.sort())
@@ -124,6 +141,7 @@ export function hashFiles(root, entries, windows = false) {
124
141
  return hash.digest("hex");
125
142
  }
126
143
  export function nativePackages(root, { applyExcludes = true } = {}) {
144
+ assertEnrichedHtmlPins(root);
127
145
  prepareNativePatches(root);
128
146
  const installed = installedPackages(root);
129
147
  if (projectPlatform(root) === "windows")
@@ -146,7 +164,7 @@ export function nativePackages(root, { applyExcludes = true } = {}) {
146
164
  // Host/CNG code can change the native ABI without adding a TurboModule.
147
165
  // Fold it into the mandatory app module's compatibility signature for Go.
148
166
  const adapters = installed.filter(pkg => ["@legendapp/spark-desktop-host", "@legendapp/spark-desktop-config"].includes(pkg.name))
149
- .map(pkg => hashFiles(pkg.root, ["package.json", "AppDelegate.mm", ...readdirSync(pkg.root).filter(name => name.endsWith(".cjs"))])).join(":");
167
+ .map(pkg => hashFiles(pkg.root, ["package.json", "AppDelegate.mm", "SparkCustomize.mm", ...readdirSync(pkg.root).filter(name => name.endsWith(".cjs"))], false, [], true)).join(":");
150
168
  return installed.filter(pkg => !applyExcludes || !excluded.includes(pkg.name))
151
169
  .filter((pkg) => pkg.json.codegenConfig ||
152
170
  pkg.json.spark?.nativeModules ||
@@ -165,8 +183,11 @@ export function nativePackages(root, { applyExcludes = true } = {}) {
165
183
  "common", "nitrogen/generated", "nitro.json",
166
184
  "expo-module.config.json",
167
185
  "react-native.config.js",
186
+ ...(pkg.name === "react-native-enriched-markdown" ? ["ratex-version.json"] : []),
168
187
  ...readdirSync(pkg.root).filter((name) => name.endsWith(".podspec")),
169
- ])),
188
+ ], false, pkg.name === "react-native-enriched-markdown"
189
+ // Postinstall restores these assets; their pinned manifests are hashed above.
190
+ ? ["cpp/highlight/vendor/grammars", "cpp/highlight/vendor/tree-sitter", "ios/vendor"] : [], true)),
170
191
  }));
171
192
  }
172
193
  export function dependencyStamp(root) {
@@ -234,7 +255,7 @@ export function selection(packages, used, include = [], excluded = []) {
234
255
  export function hostSourceSignature(root) {
235
256
  return digest(JSON.stringify(installedPackages(root)
236
257
  .filter(pkg => ["@legendapp/spark-desktop-host", "@legendapp/spark-desktop-config"].includes(pkg.name))
237
- .map(pkg => [pkg.name, hashFiles(pkg.root, ["package.json", "AppDelegate.mm", "windows", ...readdirSync(pkg.root).filter(file => file.endsWith(".cjs"))])])));
258
+ .map(pkg => [pkg.name, hashFiles(pkg.root, ["package.json", "AppDelegate.mm", "SparkCustomize.mm", "windows", ...readdirSync(pkg.root).filter(file => file.endsWith(".cjs"))])])));
238
259
  }
239
260
  export function nativePreparationInputs(root, packages) {
240
261
  return {
@@ -287,6 +308,8 @@ export function runtimeFor(root, packages, mode) {
287
308
  "@legendapp/spark-desktop-config",
288
309
  ].includes(p.name))
289
310
  .map((p) => [p.name, p.json.version]);
311
+ const config = readAppConfig(root);
312
+ const customize = config.expo?.extra?.spark?.customize;
290
313
  return {
291
314
  schema: 1,
292
315
  framework: VERSION,
@@ -302,7 +325,13 @@ export function runtimeFor(root, packages, mode) {
302
325
  ...(platform === "macos" && mode === "release" ? { releaseSettings: macOSReleaseSettings } : {}),
303
326
  modules,
304
327
  pins,
305
- config: readAppConfig(root),
328
+ config,
329
+ customize: platform === "macos" && mode === "release" && customize ? {
330
+ source: hashFiles(path.resolve(root, customize.sourceRoot ?? "."), customize.files),
331
+ project: hashFiles(root, ["package.json", entryFile(root), ...readdirSync(root).filter(file => /(?:config\.|^\.babelrc)/.test(file))]),
332
+ tooling: hashFiles(import.meta.dirname, [...readdirSync(import.meta.dirname).filter(file => file.startsWith("customize-")), "js-runtime.cjs", "runtime-bootstrap.sh", "runtime-downloads.tsv"]),
333
+ ai: digest(readFileSync(createRequire(createRequire(path.join(root, "package.json")).resolve("@legendapp/spark/ai")).resolve("@legendapp/spark-ai/src/invocation-command.cjs"), "utf8")),
334
+ } : undefined,
306
335
  helpers: resolveHelpers(root, readAppConfig(root).expo?.extra?.spark?.helpers, platform).map(helper => ({ name: helper.name, contents: hashFiles(root, helper.files), modes: helper.modes, directories: helper.directories })),
307
336
  adapter: hostSourceSignature(root),
308
337
  })),
@@ -325,6 +354,8 @@ export function goConfigurationIssues(config) {
325
354
  issues.push("URL schemes and document associations require a custom runtime");
326
355
  if (expo.extra?.spark?.menuBarOnly)
327
356
  issues.push("Menu-bar-only activation requires a custom runtime");
357
+ if (expo.extra?.spark?.customize)
358
+ issues.push("Customizable apps require a custom release runtime");
328
359
  if (expo.extra?.spark?.updates)
329
360
  issues.push("Update feed configuration requires a custom runtime");
330
361
  if (Object.keys(expo.extra?.spark?.helpers ?? {}).length)
@@ -373,10 +404,10 @@ function windowsNativePackages(root, installed) {
373
404
  }
374
405
  }
375
406
  const adapter = installed.filter(pkg => ["@legendapp/spark-desktop-host", "@legendapp/spark-desktop-config"].includes(pkg.name))
376
- .map(pkg => hashFiles(pkg.root, ["package.json", "windows", ...readdirSync(pkg.root).filter(name => name.endsWith(".cjs"))], true)).join(":");
407
+ .map(pkg => hashFiles(pkg.root, ["package.json", "windows", ...readdirSync(pkg.root).filter(name => name.endsWith(".cjs"))], true, [], true)).join(":");
377
408
  const versions = installed.filter(pkg => ["react", "expo", "react-native", "react-native-windows"].includes(pkg.name)).map(pkg => [pkg.name, pkg.json.version]);
378
409
  return installed.filter(supported).map(pkg => ({ ...pkg,
379
410
  sdk: pkg.json.spark?.sdk === true || pkg.name === "@react-native-async-storage/async-storage", requires: pkg.json.spark?.requires ?? [],
380
- signature: digest(hashFiles(pkg.root, ["package.json", "windows", "src", "cpp", "common", "react-native.config.js"], true) + (pkg.name === "@legendapp/spark-desktop-host" ? adapter + JSON.stringify(versions) : "")),
411
+ signature: digest(hashFiles(pkg.root, ["package.json", "windows", "src", "cpp", "common", "react-native.config.js"], true, [], true) + (pkg.name === "@legendapp/spark-desktop-host" ? adapter + JSON.stringify(versions) : "")),
381
412
  }));
382
413
  }
@@ -1,42 +1,42 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "0.0.1-next.4",
4
- "revision": "23bfaba5d57e9eda98422f1187fd65037ac11d01",
3
+ "version": "0.0.1-next.6",
4
+ "revision": "155e88cb303e467315dbb65871422c92977665fa",
5
5
  "packages": {
6
6
  "@react-native-runtimes/core": {
7
- "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.4/runtimes-985164a87eb0.tgz",
7
+ "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.6/runtimes-985164a87eb0.tgz",
8
8
  "size": 53886,
9
9
  "sha256": "138644fcfaf60b172c9f206c66c6d160515dd8803c70264687d0f503294c9c0b"
10
10
  },
11
11
  "react-native-nitro-modules": {
12
- "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.4/react-native-nitro-modules-0.37.0-56a36548e4e3.tgz",
13
- "size": 145386,
14
- "sha256": "56a36548e4e3236d3805dc75774a1c293034318d2825580c0b86d4079cce80ae"
12
+ "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.6/react-native-nitro-modules-0.37.0-02b4dff54381.tgz",
13
+ "size": 145600,
14
+ "sha256": "02b4dff54381bbd4640eb4067e1dc82d7a79ff7e7f83b4357a4265177722d999"
15
15
  },
16
16
  "@op-engineering/op-sqlite": {
17
- "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.4/op-engineering-op-sqlite-18.2.1-809aacdae6a3.tgz",
18
- "size": 112508531,
19
- "sha256": "809aacdae6a375f1524022533800253ee89beb931cdb5ab02781acecfa53aeac"
17
+ "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.6/op-engineering-op-sqlite-18.2.1-dcc9490310bc.tgz",
18
+ "size": 112508535,
19
+ "sha256": "dcc9490310bc74c869ba7cf5e846a8966fab7c3871c4a536482c20be237894fd"
20
20
  },
21
21
  "react-native-webview": {
22
- "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.4/react-native-webview-16.0.0-bc2c08eb8de7.tgz",
23
- "size": 116287,
24
- "sha256": "bc2c08eb8de7b979d90a641ce63b3241c034f836c76c77b794716473b3b43216"
22
+ "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.6/react-native-webview-16.0.0-b887e540eca8.tgz",
23
+ "size": 116289,
24
+ "sha256": "b887e540eca87c6817de6b38c4e8f4076e3a65e0f7fa63f0c5882e1155447a59"
25
25
  },
26
26
  "expo-audio": {
27
- "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.4/expo-audio-1.1.1-c4ae56565c36.tgz",
28
- "size": 381084,
29
- "sha256": "c4ae56565c365086e134ab9edd15ce981a2149bda07d9e9553e151def5fe7fec"
27
+ "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.6/expo-audio-1.1.1-aff5604f2c4c.tgz",
28
+ "size": 381841,
29
+ "sha256": "aff5604f2c4cab23299a71e37e802a572b2e66e2e2250b20a261e664d5346693"
30
30
  }
31
31
  },
32
32
  "runners": {
33
33
  "macos-arm64": {
34
- "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.4/spark-runner-macos-arm64.zip",
35
- "size": 17395353,
36
- "sha256": "6334c66020c8ddd0ff3f6c154b8fb97e01ceb952a26254765b816bd6055dabb1",
34
+ "url": "https://github.com/LegendApp/legend-spark/releases/download/v0.0.1-next.6/spark-runner-macos-arm64.zip",
35
+ "size": 20509040,
36
+ "sha256": "02b2da92e3a6661e03cee55304a498d185b306f2df03d0909ac0a3553a2f7fff",
37
37
  "app": "SparkRunner.app",
38
38
  "teamId": "56DD97VT22",
39
- "fingerprint": "64932dc5718a49253e5f76a9ae26c3553059893b1e0c6dcff7b05f86c2c787e2"
39
+ "fingerprint": "83b0e267a932be31d5366ea61f40e3609f79a99c01bc7fd69bb966e683d9968b"
40
40
  }
41
41
  }
42
42
  }
@@ -0,0 +1,87 @@
1
+ param(
2
+ [Parameter(Mandatory = $true, Position = 0)][string]$Entry,
3
+ [Parameter(ValueFromRemainingArguments = $true)][string[]]$ScriptArgs
4
+ )
5
+ $ErrorActionPreference = 'Stop'
6
+ $platform = 'win32'
7
+ $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()
8
+ if ($arch -notin @('arm64', 'x64')) { throw "Unsupported runtime architecture: $arch" }
9
+ $sparkHome = if ($env:SPARK_HOME) { $env:SPARK_HOME } else { Join-Path $env:USERPROFILE '.spark' }
10
+ $cache = Join-Path $sparkHome 'tooling/runtimes'
11
+ $assets = Import-Csv (Join-Path $PSScriptRoot 'runtime-downloads.tsv') -Delimiter "`t"
12
+
13
+ function Test-Compatible([string]$Executable, [string]$Kind = '') {
14
+ if (-not (Test-Path -LiteralPath $Executable -PathType Leaf)) { return $false }
15
+ try {
16
+ & $Executable (Join-Path $PSScriptRoot 'js-runtime.cjs') $Kind 2>$null | Out-Null
17
+ return $LASTEXITCODE -eq 0
18
+ } catch { return $false }
19
+ }
20
+ function Start-Runtime([string]$Executable) {
21
+ $env:SPARK_JS_RUNTIME = $Executable
22
+ $env:PATH = "$(Split-Path -Parent $Executable);$env:PATH"
23
+ & $Executable $Entry @ScriptArgs
24
+ exit $LASTEXITCODE
25
+ }
26
+ function Get-Asset([string]$Kind) {
27
+ return $assets | Where-Object { $_.runtime -eq $Kind -and $_.platform -eq $platform -and $_.arch -eq $arch } | Select-Object -First 1
28
+ }
29
+ function Get-Destination($Asset) {
30
+ return Join-Path $cache "$($Asset.runtime)-$($Asset.version)-$platform-$arch-$($Asset.sha256)"
31
+ }
32
+ function Test-Cached($Asset) {
33
+ $destination = Get-Destination $Asset
34
+ $executable = Join-Path $destination $Asset.executable
35
+ $marker = Join-Path $destination '.binary-sha256'
36
+ return (Test-Path -LiteralPath $executable -PathType Leaf) -and (Test-Path -LiteralPath $marker -PathType Leaf) -and
37
+ ((Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash -eq (Get-Content -LiteralPath $marker -Raw).Trim()) -and (Test-Compatible $executable)
38
+ }
39
+
40
+ $requested = $env:SPARK_JS_RUNTIME
41
+ if ($requested -and $requested -notin @('node', 'bun')) {
42
+ if (-not (Test-Compatible $requested)) { throw "Unsupported or missing runtime: $requested" }
43
+ Start-Runtime $requested
44
+ }
45
+ $choices = if ($requested) { @($requested) } else { @('bun', 'node') }
46
+ foreach ($kind in $choices) {
47
+ $command = Get-Command "$kind.exe" -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
48
+ if ($command -and (Test-Compatible $command.Source $requested)) { Start-Runtime $command.Source }
49
+ $asset = Get-Asset $kind
50
+ if ($asset -and (Test-Cached $asset)) { Start-Runtime (Join-Path (Get-Destination $asset) $asset.executable) }
51
+ }
52
+ $download = if ($requested) { $requested } elseif ($env:SPARK_RUNTIME_DOWNLOAD) { $env:SPARK_RUNTIME_DOWNLOAD } else { 'bun' }
53
+ if ($download -notin @('node', 'bun')) { throw 'SPARK_RUNTIME_DOWNLOAD must be node or bun.' }
54
+ $asset = Get-Asset $download
55
+ if (-not $asset) { throw "No pinned $download download for $platform/$arch. Install a compatible runtime manually." }
56
+ $destination = Get-Destination $asset
57
+ New-Item -ItemType Directory -Path $cache -Force | Out-Null
58
+ $lock = $null
59
+ $staging = $null
60
+ try {
61
+ # An OS file lock is released even when installation is interrupted or crashes.
62
+ for ($attempt = 0; $attempt -lt 60 -and -not $lock; $attempt++) {
63
+ try { $lock = [IO.File]::Open("$destination.lock", [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) }
64
+ catch [IO.IOException] { Start-Sleep -Seconds 1 }
65
+ }
66
+ if (-not $lock) { throw "Another process is installing $download; retry shortly." }
67
+ if (-not (Test-Cached $asset)) {
68
+ $staging = Join-Path $cache ".install-$download-$([Guid]::NewGuid())"
69
+ New-Item -ItemType Directory -Path $staging | Out-Null
70
+ $archive = Join-Path $staging 'archive.zip'
71
+ Write-Host "Downloading Spark's private $download $($asset.version) runtime..."
72
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
73
+ Invoke-WebRequest -Uri $asset.url -OutFile $archive -UseBasicParsing -TimeoutSec 300
74
+ if ((Get-Item -LiteralPath $archive).Length -gt 134217728 -or (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $asset.sha256) { throw 'Runtime download checksum or size mismatch.' }
75
+ $unpacked = Join-Path $staging 'unpacked'
76
+ Expand-Archive -LiteralPath $archive -DestinationPath $unpacked
77
+ $executable = Join-Path $unpacked $asset.executable
78
+ if (-not (Test-Compatible $executable)) { throw 'Downloaded runtime cannot run on this machine.' }
79
+ (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash | Set-Content -LiteralPath (Join-Path $unpacked '.binary-sha256')
80
+ if (Test-Path -LiteralPath $destination) { Remove-Item -LiteralPath $destination -Recurse -Force }
81
+ Move-Item -LiteralPath $unpacked -Destination $destination
82
+ }
83
+ } finally {
84
+ if ($staging -and (Test-Path -LiteralPath $staging)) { Remove-Item -LiteralPath $staging -Recurse -Force }
85
+ if ($lock) { $lock.Dispose() }
86
+ }
87
+ Start-Runtime (Join-Path $destination $asset.executable)