create-octane-xplat 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +2 -147
  2. package/compatibility.json +74 -61
  3. package/compatibility.ts +134 -79
  4. package/dist/compatibility.js +45 -13
  5. package/dist/index.js +127 -64
  6. package/dist/package-manager.js +62 -0
  7. package/dist/scaffold.js +362 -57
  8. package/index.ts +256 -156
  9. package/library-template/AGENTS.md +1 -1
  10. package/library-template/README.md +4 -3
  11. package/library-template/bunfig +4 -0
  12. package/library-template/package.json +73 -70
  13. package/library-template/patches/@nativescript-community__octane@0.2.5.patch +161 -24
  14. package/library-template/patches/@nativescript__core@9.1.3.patch +98 -0
  15. package/library-template/patches/@nativescript__vite@8.0.20.patch +532 -17
  16. package/library-template/patches/@octane-xplat__nativescript-mason-core@1.0.0-beta.7.patch +65 -0
  17. package/library-template/patches/octane@0.16.3.patch +56 -2
  18. package/library-template/src/Badge.tsx +5 -5
  19. package/library-template/src/Badge.web.tsx +5 -5
  20. package/library-template/src/Welcome.stories.tsx +12 -0
  21. package/library-template/src/normalizeBadgeLabel.ts +1 -1
  22. package/library-template/src/props.ts +11 -11
  23. package/library-template/tests/normalizeBadgeLabel.test.ts +1 -1
  24. package/library-template/tests/packed-consumer.mjs +140 -123
  25. package/library-template/tsconfig.envs.json +1 -0
  26. package/library-template/tsconfig.json +1 -0
  27. package/library-template/tsconfig.types.json +15 -1
  28. package/library-template/tsrx-typegen.json +1 -1
  29. package/library-template/workshop.config.ts +3 -0
  30. package/package-manager.ts +93 -0
  31. package/package.json +10 -5
  32. package/scaffold.ts +1061 -449
  33. package/template/.agents/skills/xplat/SKILL.md +1 -1
  34. package/template/.agents/skills/xplat/references/styling.md +10 -10
  35. package/template/AGENTS.md +2 -2
  36. package/template/bunfig +4 -0
  37. package/template/nativescript.config.ts +13 -13
  38. package/template/package.json +69 -64
  39. package/template/patches/@nativescript-community__octane@0.2.5.patch +161 -24
  40. package/template/patches/@nativescript__core@9.1.3.patch +98 -0
  41. package/template/patches/@nativescript__vite@8.0.20.patch +532 -17
  42. package/template/patches/@octane-xplat__nativescript-mason-core@1.0.0-beta.7.patch +65 -0
  43. package/template/patches/octane@0.16.3.patch +56 -2
  44. package/template/src/App.tsrx +66 -64
  45. package/template/src/Welcome.stories.tsx +22 -0
  46. package/template/src/app.spec.tsrx +168 -158
  47. package/template/src/app.web.test.tsx +18 -13
  48. package/template/src/failure-reporting.spec.ts +3 -3
  49. package/template/src/main.ts +14 -13
  50. package/template/src/main.tsrx +2 -0
  51. package/template/src/native-runtime.spec.ts +13 -11
  52. package/template/src/test-setup.web.ts +9 -8
  53. package/template/src/test.ts +6 -6
  54. package/template/tsconfig.json +17 -1
  55. package/template/vite.config.native.mts +1 -2
  56. package/template/vite.config.ts +29 -23
  57. package/template/vitest.config.mts +17 -17
  58. package/template/vitest.web.config.mts +7 -7
  59. package/template/workshop.config.ts +3 -0
  60. package/library-template/patches/@tsrx__typescript-plugin@0.4.11.patch +0 -11
  61. package/template/patches/@tsrx__typescript-plugin@0.4.11.patch +0 -11
  62. /package/library-template/patches/{@octanejs__tiptap@0.0.61.patch → @octanejs__tiptap@0.0.62.patch} +0 -0
  63. /package/template/patches/{@octanejs__tiptap@0.0.61.patch → @octanejs__tiptap@0.0.62.patch} +0 -0
package/scaffold.ts CHANGED
@@ -2,22 +2,35 @@
2
2
  // CLI's `xplat add`. compatibility.json owns version pins; the generated
3
3
  // templates own script bodies and the dependency set for each starter.
4
4
  import {
5
- cpSync,
6
- existsSync,
7
- mkdirSync,
8
- readdirSync,
9
- readFileSync,
10
- statSync,
11
- writeFileSync,
5
+ cpSync,
6
+ lstatSync,
7
+ existsSync,
8
+ mkdirSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ statSync,
12
+ writeFileSync,
12
13
  } from 'node:fs'
13
14
 
14
- import { basename, dirname, join, resolve } from 'node:path'
15
+ import { basename, dirname, join, resolve, relative, isAbsolute, sep } from 'node:path'
15
16
  import { fileURLToPath } from 'node:url'
16
- import { ensureCompatibilityCatalog, compatibilityRoot } from './compatibility.ts'
17
+ import { createHash } from 'node:crypto'
18
+ import { isMap, parseDocument, stringify } from 'yaml'
19
+ import {
20
+ compatibility,
21
+ mergeCompatibilityCatalog,
22
+ compatibilityRoot,
23
+ requestedCatalogPins,
24
+ } from './compatibility.ts'
25
+
26
+ import type { PackageManager } from './package-manager.ts'
27
+
28
+ export type { PackageManager } from './package-manager.ts'
17
29
 
18
30
  const moduleDir = dirname(fileURLToPath(import.meta.url))
19
31
  // dist/ emit sits one level deeper than the root sources it mirrors.
20
32
  const pkgRoot = basename(moduleDir) === 'dist' ? join(moduleDir, '..') : moduleDir
33
+
21
34
  export const TEMPLATE_DIR = join(pkgRoot, 'template')
22
35
  export const LIBRARY_TEMPLATE_DIR = join(pkgRoot, 'library-template')
23
36
 
@@ -26,75 +39,82 @@ export const LIBRARY_TEMPLATE_DIR = join(pkgRoot, 'library-template')
26
39
  * values come from template/package.json. `typecheck` contributes one clause
27
40
  * to the generated typecheck script. */
28
41
  export const targets: Record<string, any> = {
29
- web: {
30
- label: 'Web (Vite)',
31
- files: [
32
- 'index.html',
33
- 'vite.config.ts',
34
- 'src/main.web.tsrx',
35
- 'vitest.web.config.mts',
36
- 'src/app.web.test.tsx',
37
- 'src/test-setup.web.ts',
38
- ],
39
- scripts: ['dev', 'build', 'test', 'test:web'],
40
- devDeps: ['@octanejs/vite-plugin', 'jsdom'],
41
- },
42
- ios: {
43
- label: 'iOS (NativeScript)',
44
- requires: ['native-shared'],
45
- files: ['App_Resources/iOS'],
46
- scripts: ['dev:ios', 'build:ios', 'test:ios'],
47
- devDeps: ['@nativescript/ios'],
48
- note: 'needs macOS + Xcode — `bun run xplat doctor` checks the toolchain',
49
- },
50
- android: {
51
- label: 'Android (NativeScript)',
52
- requires: ['native-shared'],
53
- files: ['App_Resources/Android'],
54
- scripts: ['dev:android', 'build:android', 'test:android'],
55
- devDeps: ['@nativescript/android'],
56
- note: 'needs Android SDK + a compatible JDK — `bun run xplat doctor` checks the toolchain',
57
- },
58
- // Shared NativeScript machinery pulled in by ios/android. Not user-
59
- // selectable on its own. `patches` names the packages whose
60
- // patchedDependencies entries in package.json belong to this
61
- // fragment — Bun hard-fails installs on unused patch entries, so a
62
- // scaffold must not carry patches for deps it doesn't install.
63
- 'native-shared': {
64
- hidden: true,
65
- patches: [
66
- '@nativescript/core',
67
- '@nativescript/types',
68
- 'css',
69
- '@nativescript/vite',
70
- '@nativescript-community/octane',
71
- '@nativescript-community/vite-octane',
72
- ],
73
- files: [
74
- 'nativescript.config.ts',
75
- 'vite.config.native.mts',
76
- 'references.d.ts',
77
- 'src/main.ts',
78
- 'vitest.config.mts',
79
- 'src/test.ts',
80
- 'src/app.spec.tsrx',
81
- 'src/native-runtime.spec.ts',
82
- 'src/failure-reporting.spec.ts',
83
- ],
84
- deps: [
85
- '@nativescript-community/octane',
86
- '@nativescript/core',
87
- '@valor/nativescript-websockets',
88
- ],
89
- devDeps: [
90
- '@nativescript-community/vite-octane',
91
- '@nativescript/types',
92
- '@nativescript/unit-test-runner',
93
- '@nativescript/vite',
94
- 'nativescript',
95
- ],
96
- typecheck: 'xplat typecheck',
97
- },
42
+ web: {
43
+ label: 'Web (Vite)',
44
+ files: [
45
+ 'index.html',
46
+ 'vite.config.ts',
47
+ 'src/main.web.tsrx',
48
+ 'vitest.web.config.mts',
49
+ 'src/app.web.test.tsx',
50
+ 'src/test-setup.web.ts',
51
+ ],
52
+ scripts: ['dev', 'build', 'test', 'test:web', 'workshop'],
53
+ devDeps: ['@octanejs/vite-plugin', 'jsdom', '@octane-xplat/workshop'],
54
+ },
55
+ ios: {
56
+ label: 'iOS (NativeScript)',
57
+ requires: ['native-shared'],
58
+ files: ['App_Resources/iOS'],
59
+ scripts: ['dev:ios', 'build:ios', 'test:ios'],
60
+ devDeps: ['@nativescript/ios'],
61
+ note: 'needs macOS + Xcode — `bun run xplat doctor` checks the toolchain',
62
+ },
63
+ android: {
64
+ label: 'Android (NativeScript)',
65
+ requires: ['native-shared'],
66
+ files: ['App_Resources/Android'],
67
+ scripts: ['dev:android', 'build:android', 'test:android'],
68
+ devDeps: ['@nativescript/android'],
69
+ note: 'needs Android SDK + a compatible JDK — `bun run xplat doctor` checks the toolchain',
70
+ },
71
+ // Shared NativeScript machinery pulled in by ios/android. Not user-
72
+ // selectable on its own. `patches` names the packages whose
73
+ // patchedDependencies entries in package.json belong to this
74
+ // fragment — Bun hard-fails installs on unused patch entries, so a
75
+ // scaffold must not carry patches for deps it doesn't install.
76
+ 'native-shared': {
77
+ hidden: true,
78
+ // Build-script approvals claimed by this target — the scaffolded
79
+ // allowBuilds entry for `nativescript` only exists once native-shared
80
+ // resolves (web-only trees never install it).
81
+ builds: ['nativescript'],
82
+ patches: [
83
+ '@nativescript/core',
84
+ '@nativescript/types',
85
+ 'css',
86
+ '@nativescript/vite',
87
+ '@nativescript-community/octane',
88
+ '@nativescript-community/vite-octane',
89
+ ],
90
+ files: [
91
+ 'nativescript.config.ts',
92
+ 'vite.config.native.mts',
93
+ 'references.d.ts',
94
+ 'src/main.ts',
95
+ 'vitest.config.mts',
96
+ 'src/test.ts',
97
+ 'src/app.spec.tsrx',
98
+ 'src/native-runtime.spec.ts',
99
+ 'src/failure-reporting.spec.ts',
100
+ ],
101
+ deps: [
102
+ '@nativescript-community/octane',
103
+ '@nativescript/core',
104
+ '@valor/nativescript-websockets',
105
+ ],
106
+ devDeps: [
107
+ '@octane-xplat/workshop',
108
+ '@nativescript-community/vite-octane',
109
+ '@nativescript/types',
110
+ '@nativescript/unit-test-runner',
111
+ '@nativescript/vite',
112
+ 'nativescript',
113
+ // The classic-API checker path used by the native Vite plugin.
114
+ 'typescript-classic',
115
+ ],
116
+ typecheck: 'xplat typecheck',
117
+ },
98
118
  }
99
119
 
100
120
  export const selectableTargets = Object.keys(targets).filter((id) => !targets[id].hidden)
@@ -110,197 +130,383 @@ const BASE_SCRIPTS = ['xplat', 'lint', 'lint:fix', 'format']
110
130
 
111
131
  /** Expand `requires` edges, dependencies first. Throws on unknown ids. */
112
132
  export function resolveTargets(ids) {
113
- const resolved: string[] = []
114
- const visit = (id) => {
115
- const t = targets[id]
116
- if (!t) {
117
- throw new Error(`unknown target "${id}" — expected one of: ${selectableTargets.join(', ')}`)
118
- }
119
-
120
- for (const req of t.requires ?? []) {
121
- visit(req)
122
- }
123
-
124
- if (!resolved.includes(id)) {
125
- resolved.push(id)
126
- }
127
- }
128
-
129
- for (const id of ids) {
130
- visit(id)
131
- }
132
-
133
- return resolved
133
+ const resolved: string[] = []
134
+ const visit = (id) => {
135
+ const t = targets[id]
136
+
137
+ if (!t) {
138
+ throw new Error(`unknown target "${id}" — expected one of: ${selectableTargets.join(', ')}`)
139
+ }
140
+
141
+ for (const req of t.requires ?? []) {
142
+ visit(req)
143
+ }
144
+
145
+ if (!resolved.includes(id)) {
146
+ resolved.push(id)
147
+ }
148
+ }
149
+
150
+ for (const id of ids) {
151
+ visit(id)
152
+ }
153
+
154
+ return resolved
134
155
  }
135
156
 
136
157
  const templateManifest = () => JSON.parse(readFileSync(join(TEMPLATE_DIR, 'package.json'), 'utf8'))
137
158
 
138
159
  /** Which target claims a template-relative path (entries may be dirs). */
139
160
  function ownerOf(path) {
140
- for (const [id, t] of Object.entries(targets)) {
141
- for (const entry of t.files) {
142
- if (path === entry || path.startsWith(entry + '/')) {
143
- return id
144
- }
145
- }
146
- }
147
-
148
- return null
161
+ for (const [id, t] of Object.entries(targets)) {
162
+ for (const entry of t.files) {
163
+ if (path === entry || path.startsWith(entry + '/')) {
164
+ return id
165
+ }
166
+ }
167
+ }
168
+
169
+ return null
149
170
  }
150
171
 
151
172
  function walk(dir, prefix = '') {
152
- const out: string[] = []
153
- for (const name of readdirSync(dir)) {
154
- if (name === 'node_modules') {
155
- continue
156
- }
157
-
158
- const rel = prefix ? `${prefix}/${name}` : name
159
- if (statSync(join(dir, name)).isDirectory()) {
160
- out.push(...walk(join(dir, name), rel))
161
- } else {
162
- out.push(rel)
163
- }
164
- }
165
-
166
- return out
173
+ const out: string[] = []
174
+
175
+ for (const name of readdirSync(dir)) {
176
+ if (name === 'node_modules') {
177
+ continue
178
+ }
179
+
180
+ const rel = prefix ? `${prefix}/${name}` : name
181
+
182
+ if (statSync(join(dir, name)).isDirectory()) {
183
+ out.push(...walk(join(dir, name), rel))
184
+ } else {
185
+ out.push(rel)
186
+ }
187
+ }
188
+
189
+ return out
167
190
  }
168
191
 
169
192
  function pickKeys(source, names, label) {
170
- const out: Record<string, string> = {}
171
- for (const name of names) {
172
- if (source[name] === undefined) {
173
- throw new Error(`template/package.json has no ${label} entry "${name}"`)
174
- }
193
+ const out: Record<string, string> = {}
194
+
195
+ for (const name of names) {
196
+ if (source[name] === undefined) {
197
+ throw new Error(`template/package.json has no ${label} entry "${name}"`)
198
+ }
175
199
 
176
- out[name] = source[name]
177
- }
200
+ out[name] = source[name]
201
+ }
178
202
 
179
- return out
203
+ return out
180
204
  }
181
205
 
182
206
  /**
183
207
  * The package.json a given target set produces. With every target selected
184
- * this is identical to template/package.json.
208
+ * this is identical to template/package.json. For pnpm the Bun-config homes
209
+ * move to pnpm-workspace.yaml — composePnpmWorkspace emits the other half.
210
+ */
211
+ export function composeManifest(ids: string[], packageManager: PackageManager = 'bun') {
212
+ const resolved = resolveTargets(ids)
213
+ const tpl = templateManifest()
214
+ const manifest: Record<string, any> = { ...tpl }
215
+
216
+ for (const section of ['dependencies', 'devDependencies']) {
217
+ const key = section === 'dependencies' ? 'deps' : 'devDeps'
218
+ const wanted = new Set<string>()
219
+
220
+ for (const id of resolved) {
221
+ for (const name of targets[id][key] ?? []) {
222
+ wanted.add(name)
223
+ }
224
+ }
225
+
226
+ const next = {}
227
+
228
+ for (const [name, spec] of Object.entries(tpl[section] ?? {})) {
229
+ // Unclaimed entries are base; claimed entries follow their target.
230
+ const claimed = Object.keys(targets).some((id) => (targets[id][key] ?? []).includes(name))
231
+
232
+ if (!claimed || wanted.has(name)) {
233
+ next[name] = spec
234
+ }
235
+ }
236
+
237
+ manifest[section] = next
238
+ }
239
+
240
+ const wantedScripts = new Set(BASE_SCRIPTS)
241
+
242
+ for (const id of resolved) {
243
+ for (const name of targets[id].scripts ?? []) {
244
+ wantedScripts.add(name)
245
+ }
246
+ }
247
+
248
+ const scripts = pickKeys(tpl.scripts ?? {}, [...wantedScripts].sort(), 'script')
249
+ const typecheck: string[] = [BASE_TYPECHECK]
250
+
251
+ for (const id of resolved) {
252
+ if (targets[id].typecheck) {
253
+ typecheck.push(targets[id].typecheck)
254
+ }
255
+ }
256
+
257
+ scripts.typecheck = [...new Set(typecheck)].join(' && ')
258
+ // Keep the template's key order: scripts sit where they were.
259
+ manifest.scripts = {}
260
+ for (const name of Object.keys(tpl.scripts ?? {})) {
261
+ if (name === 'typecheck' || wantedScripts.has(name)) {
262
+ manifest.scripts[name] = scripts[name]
263
+ }
264
+ }
265
+
266
+ if (!resolved.includes('native-shared')) {
267
+ // "main" points at the native entry — meaningless without it.
268
+ delete manifest.main
269
+ }
270
+
271
+ const drop = new Set(
272
+ Object.entries(targets)
273
+ .filter(([id]) => !resolved.includes(id))
274
+ .flatMap(([, target]) => target.patches ?? []),
275
+ )
276
+
277
+ manifest.patchedDependencies = Object.fromEntries(
278
+ Object.entries(tpl.patchedDependencies).filter(
279
+ ([key]) => !drop.has(key.slice(0, key.indexOf('@', 1))),
280
+ ),
281
+ )
282
+
283
+ const used = new Set([
284
+ ...Object.keys(manifest.dependencies),
285
+ ...Object.keys(manifest.devDependencies),
286
+ ])
287
+
288
+ manifest.workspaces = {
289
+ ...tpl.workspaces,
290
+ catalogs: {
291
+ ...tpl.workspaces.catalogs,
292
+ xplat: Object.fromEntries(
293
+ Object.entries(tpl.workspaces.catalogs.xplat).filter(([name]) => used.has(name)),
294
+ ),
295
+ },
296
+ }
297
+
298
+ if (packageManager === 'bun') {
299
+ return manifest
300
+ }
301
+
302
+ return splitForPnpm(manifest, new Set(resolved)).manifest
303
+ }
304
+
305
+ // pnpm 11 fails an install when a dependency's build scripts are neither
306
+ // approved nor denied in allowBuilds, where Bun silently skips untrusted
307
+ // ones. These are the packages real pnpm installs reported that are not
308
+ // trusted — `target` scopes an entry to the target set whose dependency
309
+ // tree contains it. Approved entries are not listed here: they come from
310
+ // the manifest's trustedDependencies filtered by target `builds` claims.
311
+ const deniedBuilds: { name: string; target?: string }[] = [
312
+ // @octane-xplat/nativescript-mason-core pulls @nativescript/core into even
313
+ // the web-only tree; its build scripts are not trusted.
314
+ { name: '@nativescript/core' },
315
+ // onnxruntime-web (via @octane-xplat/docs-search) pulls protobufjs into the
316
+ // tree; its postinstall is a no-op and must not run.
317
+ { name: 'protobufjs' },
318
+ ]
319
+
320
+ /**
321
+ * The allowBuilds map for a resolved target set: trusted dependencies (with
322
+ * target claims applied) approve, everything pnpm reported denies.
185
323
  */
186
- export function composeManifest(ids) {
187
- const resolved = resolveTargets(ids)
188
- const tpl = templateManifest()
189
- const manifest: Record<string, any> = { ...tpl }
190
-
191
- for (const section of ['dependencies', 'devDependencies']) {
192
- const key = section === 'dependencies' ? 'deps' : 'devDeps'
193
- const wanted = new Set<string>()
194
- for (const id of resolved) {
195
- for (const name of targets[id][key] ?? []) {
196
- wanted.add(name)
197
- }
198
- }
199
-
200
- const next = {}
201
- for (const [name, spec] of Object.entries(tpl[section] ?? {})) {
202
- // Unclaimed entries are base; claimed entries follow their target.
203
- const claimed = Object.keys(targets).some((id) => (targets[id][key] ?? []).includes(name))
204
-
205
- if (!claimed || wanted.has(name)) {
206
- next[name] = spec
207
- }
208
- }
209
-
210
- manifest[section] = next
211
- }
212
-
213
- const wantedScripts = new Set(BASE_SCRIPTS)
214
- for (const id of resolved) {
215
- for (const name of targets[id].scripts ?? []) {
216
- wantedScripts.add(name)
217
- }
218
- }
219
-
220
- const scripts = pickKeys(tpl.scripts ?? {}, [...wantedScripts].sort(), 'script')
221
- const typecheck: string[] = [BASE_TYPECHECK]
222
- for (const id of resolved) {
223
- if (targets[id].typecheck) {
224
- typecheck.push(targets[id].typecheck)
225
- }
226
- }
227
-
228
- scripts.typecheck = [...new Set(typecheck)].join(' && ')
229
- // Keep the template's key order: scripts sit where they were.
230
- manifest.scripts = {}
231
- for (const name of Object.keys(tpl.scripts ?? {})) {
232
- if (name === 'typecheck' || wantedScripts.has(name)) {
233
- manifest.scripts[name] = scripts[name]
234
- }
235
- }
236
-
237
- if (!resolved.includes('native-shared')) {
238
- // "main" points at the native entry — meaningless without it.
239
- delete manifest.main
240
- }
241
-
242
- const drop = new Set(
243
- Object.entries(targets)
244
- .filter(([id]) => !resolved.includes(id))
245
- .flatMap(([, target]) => target.patches ?? []),
246
- )
247
- manifest.patchedDependencies = Object.fromEntries(
248
- Object.entries(tpl.patchedDependencies).filter(
249
- ([key]) => !drop.has(key.slice(0, key.indexOf('@', 1))),
250
- ),
251
- )
252
- const used = new Set([
253
- ...Object.keys(manifest.dependencies),
254
- ...Object.keys(manifest.devDependencies),
255
- ])
256
- manifest.workspaces = {
257
- ...tpl.workspaces,
258
- catalogs: {
259
- ...tpl.workspaces.catalogs,
260
- xplat: Object.fromEntries(
261
- Object.entries(tpl.workspaces.catalogs.xplat).filter(([name]) => used.has(name)),
262
- ),
263
- },
264
- }
265
- return manifest
324
+ function allowBuildsFor(manifest, resolved: Set<string>) {
325
+ const wanted = new Set<string>()
326
+
327
+ for (const id of resolved) {
328
+ for (const name of targets[id].builds ?? []) {
329
+ wanted.add(name)
330
+ }
331
+ }
332
+
333
+ const builds: Record<string, boolean> = {}
334
+
335
+ for (const name of manifest.trustedDependencies ?? []) {
336
+ const claimed = Object.values(targets).some((target) => (target.builds ?? []).includes(name))
337
+
338
+ if (!claimed || wanted.has(name)) {
339
+ builds[name] = true
340
+ }
341
+ }
342
+
343
+ for (const entry of deniedBuilds) {
344
+ if (!entry.target || resolved.has(entry.target)) {
345
+ builds[entry.name] = false
346
+ }
347
+ }
348
+
349
+ return Object.fromEntries(
350
+ Object.keys(builds)
351
+ .sort()
352
+ .map((name) => [name, builds[name]]),
353
+ )
266
354
  }
267
355
 
356
+ /**
357
+ * Move Bun's config homes — catalogs, overrides, patches, trusted
358
+ * dependencies, the bun engine — out of the composed manifest into the
359
+ * pnpm-workspace.yaml object. Both manager variants come from the same
360
+ * composed manifest so pins can never disagree.
361
+ */
362
+ function splitForPnpm(manifest, resolved: Set<string>) {
363
+ const next = { ...manifest }
364
+ const workspace: Record<string, any> = {}
365
+
366
+ workspace.packages = next.workspaces?.packages ?? []
367
+ if (next.workspaces?.catalogs) {
368
+ workspace.catalogs = next.workspaces.catalogs
369
+ }
370
+
371
+ delete next.workspaces
372
+ if (next.overrides) {
373
+ workspace.overrides = next.overrides
374
+ delete next.overrides
375
+ }
376
+
377
+ if (next.patchedDependencies) {
378
+ workspace.patchedDependencies = next.patchedDependencies
379
+ delete next.patchedDependencies
380
+ }
381
+
382
+ // Matches what `xplat upgrade` writes; shipped patch files may sit unused
383
+ // for a target set (tiptap, doctor, sqlite-bridge are always copied).
384
+ workspace.allowUnusedPatches = true
385
+ workspace.allowBuilds = allowBuildsFor(next, resolved)
386
+ delete next.trustedDependencies
387
+ // NativeScript resolves plugins from a flat tree — same reason bunfig sets
388
+ // the hoisted linker for Bun.
389
+ workspace.nodeLinker = 'hoisted'
390
+ workspace.saveExact = true
391
+ if (next.engines) {
392
+ delete next.engines.bun
393
+ if (Object.keys(next.engines).length === 0) {
394
+ delete next.engines
395
+ }
396
+ }
397
+
398
+ next.packageManager = `pnpm@${compatibility.tools.pnpm}`
399
+ return { manifest: next, workspace }
400
+ }
401
+
402
+ /** The pnpm-workspace.yaml a given target set produces. */
403
+ export function composePnpmWorkspace(ids: string[]): string {
404
+ const resolved = resolveTargets(ids)
405
+ const { workspace } = splitForPnpm(composeManifest(resolved), new Set(resolved))
406
+
407
+ return stringify(workspace)
408
+ }
409
+
410
+ /** Patch [specifier, path] entries the enabled targets need and `present` lacks. */
411
+ function neededPatchEntries(enabledIds, present: Set<string>): [string, string][] {
412
+ const needed = new Set(enabledIds.flatMap((id) => targets[id].patches ?? []))
413
+ const out: [string, string][] = []
414
+
415
+ for (const [specifier, path] of Object.entries(templateManifest().patchedDependencies) as [
416
+ string,
417
+ string,
418
+ ][]) {
419
+ const name = specifier.slice(0, specifier.indexOf('@', 1))
420
+
421
+ if (!needed.has(name) || present.has(name)) {
422
+ continue
423
+ }
424
+
425
+ out.push([specifier, path])
426
+ }
427
+
428
+ return out
429
+ }
430
+
431
+ /** Copy a canonical patch into the root patches/ dir unless it already matches. */
432
+ function stagePatchFile(root, path, read, write) {
433
+ const source = join(TEMPLATE_DIR, path)
434
+ const destination = join(root, path)
435
+ const before = read(destination)
436
+
437
+ if (before !== null && !readFileSync(source).equals(before)) {
438
+ throw new Error(
439
+ `Custom patch ${destination} differs from the framework patch; reconcile it first`,
440
+ )
441
+ }
442
+
443
+ write(destination, readFileSync(source), statSync(source).mode & 0o777)
444
+ }
445
+
446
+ const specifierName = (specifier: string) => specifier.slice(0, specifier.indexOf('@', 1))
447
+
268
448
  /** Add target-owned local patches before installing newly enabled dependencies. */
269
- function ensurePatchEntries(appRoot, enabledIds, manifest) {
270
- const root = compatibilityRoot(appRoot)
271
- const file = join(root, 'package.json')
272
- const pkg = root === resolve(appRoot) ? manifest : JSON.parse(readFileSync(file, 'utf8'))
273
- const needed = new Set(enabledIds.flatMap((id) => targets[id].patches ?? []))
274
- const template = templateManifest()
275
- const present = new Set(
276
- Object.keys(pkg.patchedDependencies ?? {}).map((key) => key.slice(0, key.indexOf('@', 1))),
277
- )
278
- let changed = false
279
- pkg.patchedDependencies ??= {}
280
- for (const [specifier, path] of Object.entries(template.patchedDependencies) as [
281
- string,
282
- string,
283
- ][]) {
284
- const name = specifier.slice(0, specifier.indexOf('@', 1))
285
- if (!needed.has(name) || present.has(name)) {
286
- continue
287
- }
288
- const source = join(TEMPLATE_DIR, path)
289
- const destination = join(root, path)
290
- if (existsSync(destination) && !readFileSync(source).equals(readFileSync(destination))) {
291
- throw new Error(
292
- `Custom patch ${destination} differs from the framework patch; reconcile it first`,
293
- )
294
- }
295
- mkdirSync(dirname(destination), { recursive: true })
296
- cpSync(source, destination)
297
- pkg.patchedDependencies[specifier] = path
298
- changed = true
299
- }
300
- if (changed && root !== resolve(appRoot)) {
301
- writeFileSync(file, JSON.stringify(pkg, null, '\t') + '\n')
302
- }
303
- return changed
449
+ function ensurePatchEntries(enabledIds, root, pkg, read, write) {
450
+ const present = new Set(Object.keys(pkg.patchedDependencies ?? {}).map(specifierName))
451
+
452
+ pkg.patchedDependencies ??= {}
453
+
454
+ let changed = false
455
+
456
+ for (const [specifier, path] of neededPatchEntries(enabledIds, present)) {
457
+ stagePatchFile(root, path, read, write)
458
+ pkg.patchedDependencies[specifier] = path
459
+ changed = true
460
+ }
461
+
462
+ return changed
463
+ }
464
+
465
+ /** The selected manager at a workspace root — mirrors the CLI's detection. */
466
+ function managerForRoot(root: string, pkg) {
467
+ const declared = pkg?.packageManager?.split('@')[0]
468
+
469
+ if (declared !== undefined) {
470
+ if (declared === 'bun' || declared === 'pnpm') {
471
+ return declared
472
+ }
473
+
474
+ throw new Error(`Xplat supports Bun and pnpm projects; found packageManager ${declared}.`)
475
+ }
476
+
477
+ const bun = existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb'))
478
+ const pnpm = existsSync(join(root, 'pnpm-lock.yaml'))
479
+
480
+ if (bun && pnpm) {
481
+ throw new Error(
482
+ 'Both Bun and pnpm lockfiles exist. Set packageManager in package.json or pass --package-manager.',
483
+ )
484
+ }
485
+
486
+ if (bun) {
487
+ return 'bun'
488
+ }
489
+
490
+ if (pnpm) {
491
+ return 'pnpm'
492
+ }
493
+
494
+ if (pkg?.patchedDependencies) {
495
+ return 'bun'
496
+ }
497
+
498
+ return existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm' : 'bun'
499
+ }
500
+
501
+ /**
502
+ * Native tsconfig `paths` pinning `@nativescript/core` to the app's own
503
+ * install. Without it, a `link:`/`file:`/`portal:` framework checkout's core
504
+ * imports resolve to that checkout's own copy and checkers see two distinct
505
+ * `View`/`Page`/`Color` type identities (private-member conflicts, issue #66).
506
+ */
507
+ export const nativeCorePaths = {
508
+ '@nativescript/core': ['./node_modules/@nativescript/core'],
509
+ '@nativescript/core/*': ['./node_modules/@nativescript/core/*'],
304
510
  }
305
511
 
306
512
  /**
@@ -309,118 +515,218 @@ function ensurePatchEntries(appRoot, enabledIds, manifest) {
309
515
  * scaffold just drops the native ambient root and entrypoint.
310
516
  */
311
517
  export function composeTsconfig(ids) {
312
- const resolved = new Set(resolveTargets(ids))
313
- const config = JSON.parse(readFileSync(join(TEMPLATE_DIR, 'tsconfig.json'), 'utf8'))
314
- if (!resolved.has('native-shared')) {
315
- delete config.files
316
- config.compilerOptions.types = (config.compilerOptions.types ?? []).filter(
317
- (t) => t !== '@nativescript/types',
318
- )
319
-
320
- config.exclude = [...new Set([...(config.exclude ?? []), 'src/main.ts'])]
321
- }
322
-
323
- return JSON.stringify(config, null, '\t') + '\n'
518
+ const resolved = new Set(resolveTargets(ids))
519
+ const config = JSON.parse(readFileSync(join(TEMPLATE_DIR, 'tsconfig.json'), 'utf8'))
520
+
521
+ if (!resolved.has('native-shared')) {
522
+ delete config.files
523
+ delete config.compilerOptions.paths
524
+ config.compilerOptions.types = (config.compilerOptions.types ?? []).filter(
525
+ (t) => t !== '@nativescript/types',
526
+ )
527
+
528
+ config.exclude = [...new Set([...(config.exclude ?? []), 'src/main.ts'])]
529
+ }
530
+
531
+ return JSON.stringify(config, null, '\t') + '\n'
532
+ }
533
+
534
+ /**
535
+ * Starter text files whose command forms follow the chosen package manager.
536
+ * Nothing under patches/ is ever transformed — patch bytes must equal the
537
+ * canonical copies.
538
+ */
539
+ const managerTextFiles = [
540
+ 'AGENTS.md',
541
+ 'README.md',
542
+ 'nativescript.config.ts',
543
+ 'vitest.config.mts',
544
+ 'src/app.spec.tsrx',
545
+ ]
546
+
547
+ const isManagerTextFile = (rel: string) =>
548
+ managerTextFiles.includes(rel) || rel.startsWith('.agents/skills/xplat/')
549
+
550
+ // Template file names that differ from their scaffolded names: dotfiles and
551
+ // bunfig ship without their final names because npm/bun packing drops them.
552
+ const renamedFiles: Record<string, string> = {
553
+ gitignore: '.gitignore',
554
+ bunfig: 'bunfig.toml',
555
+ }
556
+
557
+ const destName = (rel: string) => renamedFiles[rel] ?? rel
558
+
559
+ /**
560
+ * Rewrite the canonical Bun command forms in starter text for another
561
+ * manager. Applied only to managerTextFiles.
562
+ */
563
+ export function localizeCommands(text: string, manager: PackageManager): string {
564
+ if (manager === 'bun') {
565
+ return text
566
+ }
567
+
568
+ return (
569
+ text
570
+ // `bun run script -- args`: pnpm forwards a literal `--`, bun strips it.
571
+ .replace(/\bbun run (\S+) -- /g, 'pnpm run $1 ')
572
+ .replace(/\bbunx\b/g, 'pnpm dlx')
573
+ .replace(/\bbun pm pack\b/g, 'pnpm pack')
574
+ .replace(/\bbun run\b/g, 'pnpm run')
575
+ .replace(/\bbun add\b/g, 'pnpm add')
576
+ .replace(/\bbun install\b/g, 'pnpm install')
577
+ .replace(/packageManager: 'bun'/g, "packageManager: 'pnpm'")
578
+ )
324
579
  }
325
580
 
326
581
  /** Write a scaffold with tests for `ids` into `dir` (must not exist or be empty). */
327
- export function composeTargets(ids, dir) {
328
- const resolved = new Set(resolveTargets(ids))
329
- mkdirSync(dir, { recursive: true })
330
-
331
- for (const rel of walk(TEMPLATE_DIR)) {
332
- if (rel === 'package.json' || rel === 'tsconfig.json') {
333
- continue // generated below
334
- }
335
-
336
- const owner = ownerOf(rel)
337
- if (owner && !resolved.has(owner)) {
338
- continue
339
- }
340
-
341
- const dest = join(dir, rel === 'gitignore' ? '.gitignore' : rel)
342
- mkdirSync(dirname(dest), { recursive: true })
343
- cpSync(join(TEMPLATE_DIR, rel), dest, { recursive: true })
344
- }
345
-
346
- writeFileSync(join(dir, 'package.json'), JSON.stringify(composeManifest(ids), null, '\t') + '\n')
347
- writeFileSync(join(dir, 'tsconfig.json'), composeTsconfig(ids))
348
- return [...resolved]
582
+ export function composeTargets(ids, dir, options?: { packageManager?: PackageManager }) {
583
+ const packageManager = options?.packageManager ?? 'bun'
584
+ const resolved = new Set(resolveTargets(ids))
585
+
586
+ mkdirSync(dir, { recursive: true })
587
+
588
+ for (const rel of walk(TEMPLATE_DIR)) {
589
+ if (rel === 'package.json' || rel === 'tsconfig.json') {
590
+ continue // generated below
591
+ }
592
+
593
+ if (packageManager === 'pnpm' && rel === 'bunfig') {
594
+ continue
595
+ }
596
+
597
+ const owner = ownerOf(rel)
598
+
599
+ if (owner && !resolved.has(owner)) {
600
+ continue
601
+ }
602
+
603
+ const source = join(TEMPLATE_DIR, rel)
604
+ const dest = join(dir, destName(rel))
605
+
606
+ mkdirSync(dirname(dest), { recursive: true })
607
+ if (packageManager === 'pnpm' && isManagerTextFile(rel)) {
608
+ writeFileSync(dest, localizeCommands(readFileSync(source, 'utf8'), packageManager))
609
+ } else {
610
+ cpSync(source, dest, { recursive: true })
611
+ }
612
+ }
613
+
614
+ writeFileSync(
615
+ join(dir, 'package.json'),
616
+ JSON.stringify(composeManifest(ids, packageManager), null, '\t') + '\n',
617
+ )
618
+
619
+ writeFileSync(join(dir, 'tsconfig.json'), composeTsconfig(ids))
620
+ if (packageManager === 'pnpm') {
621
+ writeFileSync(join(dir, 'pnpm-workspace.yaml'), composePnpmWorkspace(ids))
622
+ }
623
+
624
+ return [...resolved]
349
625
  }
350
626
 
351
627
  /** Write the cross-platform library starter into `dir`. */
352
- export function composeLibrary(dir, packageName = basename(resolve(dir))) {
353
- if (
354
- packageName.length > 214 ||
355
- !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(packageName)
356
- ) {
357
- throw new Error(
358
- `invalid npm package name "${packageName}" — use lowercase letters, numbers, dots, underscores, or hyphens`,
359
- )
360
- }
361
-
362
- mkdirSync(dir, { recursive: true })
363
- for (const rel of walk(LIBRARY_TEMPLATE_DIR)) {
364
- if (rel === 'package.json') {
365
- continue
366
- }
367
-
368
- const dest = join(dir, rel === 'gitignore' ? '.gitignore' : rel)
369
- mkdirSync(dirname(dest), { recursive: true })
370
- const source = join(LIBRARY_TEMPLATE_DIR, rel)
371
- if (/\.(?:md|ts|tsx|mjs|json)$/.test(rel)) {
372
- const content = readFileSync(source, 'utf8').replaceAll('octane-xplat-library', packageName)
373
- writeFileSync(dest, content)
374
- } else {
375
- cpSync(source, dest, { recursive: true })
376
- }
377
- }
378
-
379
- const manifest = JSON.parse(readFileSync(join(LIBRARY_TEMPLATE_DIR, 'package.json'), 'utf8'))
380
- manifest.name = packageName
381
- writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest, null, '\t') + '\n')
628
+ export function composeLibrary(
629
+ dir,
630
+ packageName = basename(resolve(dir)),
631
+ options?: { packageManager?: PackageManager },
632
+ ) {
633
+ if (
634
+ packageName.length > 214 ||
635
+ !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(packageName)
636
+ ) {
637
+ throw new Error(
638
+ `invalid npm package name "${packageName}" — use lowercase letters, numbers, dots, underscores, or hyphens`,
639
+ )
640
+ }
641
+
642
+ const packageManager = options?.packageManager ?? 'bun'
643
+
644
+ mkdirSync(dir, { recursive: true })
645
+ for (const rel of walk(LIBRARY_TEMPLATE_DIR)) {
646
+ if (rel === 'package.json' || (packageManager === 'pnpm' && rel === 'bunfig')) {
647
+ continue
648
+ }
649
+
650
+ const dest = join(dir, destName(rel))
651
+
652
+ mkdirSync(dirname(dest), { recursive: true })
653
+
654
+ const source = join(LIBRARY_TEMPLATE_DIR, rel)
655
+
656
+ if (/\.(?:md|ts|tsx|mjs|json)$/.test(rel)) {
657
+ let content = readFileSync(source, 'utf8').replaceAll('octane-xplat-library', packageName)
658
+
659
+ if (packageManager === 'pnpm' && isManagerTextFile(rel)) {
660
+ content = localizeCommands(content, packageManager)
661
+ }
662
+
663
+ writeFileSync(dest, content)
664
+ } else {
665
+ cpSync(source, dest, { recursive: true })
666
+ }
667
+ }
668
+
669
+ const manifest = JSON.parse(readFileSync(join(LIBRARY_TEMPLATE_DIR, 'package.json'), 'utf8'))
670
+
671
+ manifest.name = packageName
672
+ if (packageManager === 'pnpm') {
673
+ for (const [name, script] of Object.entries(manifest.scripts ?? {})) {
674
+ manifest.scripts[name] = localizeCommands(String(script), packageManager)
675
+ }
676
+
677
+ // The library exercises web and native builds — its dependency tree spans
678
+ // the native toolchain, so target claims resolve as native-shared.
679
+ const { manifest: split, workspace } = splitForPnpm(manifest, new Set(['native-shared']))
680
+
681
+ writeFileSync(join(dir, 'package.json'), JSON.stringify(split, null, '\t') + '\n')
682
+ writeFileSync(join(dir, 'pnpm-workspace.yaml'), stringify(workspace))
683
+ return
684
+ }
685
+
686
+ writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest, null, '\t') + '\n')
382
687
  }
383
688
 
384
689
  const readJson = (file) => {
385
- try {
386
- return JSON.parse(readFileSync(file, 'utf8'))
387
- } catch {
388
- return null
389
- }
690
+ try {
691
+ return JSON.parse(readFileSync(file, 'utf8'))
692
+ } catch {
693
+ return null
694
+ }
390
695
  }
391
696
 
392
697
  /** Sentinel-based enablement check, mirroring the CLI's targets.mjs. */
393
698
  export function targetEnabled(appRoot, id) {
394
- if (id === 'web') {
395
- return (
396
- existsSync(join(appRoot, 'vite.config.ts')) || existsSync(join(appRoot, 'vite.config.mts'))
397
- )
398
- }
399
-
400
- if (id === 'native-shared') {
401
- return existsSync(join(appRoot, 'nativescript.config.ts'))
402
- }
403
-
404
- // ios/android: declared runtime devDep is the canonical signal — App_Resources
405
- // alone doesn't reach the bundler config.
406
- const manifest: Record<string, any> = readJson(join(appRoot, 'package.json')) ?? {}
407
- const declared = { ...manifest.dependencies, ...manifest.devDependencies }
408
- const runtime = { ios: '@nativescript/ios', android: '@nativescript/android' }[id]
409
- return runtime ? typeof declared[runtime] === 'string' : false
699
+ if (id === 'web') {
700
+ return (
701
+ existsSync(join(appRoot, 'vite.config.ts')) || existsSync(join(appRoot, 'vite.config.mts'))
702
+ )
703
+ }
704
+
705
+ if (id === 'native-shared') {
706
+ return existsSync(join(appRoot, 'nativescript.config.ts'))
707
+ }
708
+
709
+ // ios/android: declared runtime devDep is the canonical signal — App_Resources
710
+ // alone doesn't reach the bundler config.
711
+ const manifest: Record<string, any> = readJson(join(appRoot, 'package.json')) ?? {}
712
+ const declared = { ...manifest.dependencies, ...manifest.devDependencies }
713
+ const runtime = { ios: '@nativescript/ios', android: '@nativescript/android' }[id]
714
+
715
+ return runtime ? typeof declared[runtime] === 'string' : false
410
716
  }
411
717
 
412
718
  /** Copy a template file/dir into the app unless the destination exists. */
413
- function copyMissing(rel, appRoot, report) {
414
- const src = join(TEMPLATE_DIR, rel)
415
- const dest = join(appRoot, rel === 'gitignore' ? '.gitignore' : rel)
416
- if (existsSync(dest)) {
417
- report.skipped.push(rel)
418
- return
419
- }
420
-
421
- mkdirSync(dirname(dest), { recursive: true })
422
- cpSync(src, dest, { recursive: true })
423
- report.copied.push(rel)
719
+ function copyMissing(rel, appRoot, report, present, copy) {
720
+ const src = join(TEMPLATE_DIR, rel)
721
+ const dest = join(appRoot, destName(rel))
722
+
723
+ if (present(dest)) {
724
+ report.skipped.push(rel)
725
+ return
726
+ }
727
+
728
+ copy(src, dest)
729
+ report.copied.push(rel)
424
730
  }
425
731
 
426
732
  /**
@@ -429,115 +735,421 @@ function copyMissing(rel, appRoot, report) {
429
735
  * suffix — so enabling native means wiring the ambient declaration file and
430
736
  * the entrypoint into the app's own config.
431
737
  */
432
- function enableNativeInTsconfig(appRoot) {
433
- const path = join(appRoot, 'tsconfig.json')
434
- const text = existsSync(path) ? readFileSync(path, 'utf8') : ''
435
- const config = readJson(path)
436
- if (!config || typeof config !== 'object') {
437
- return false
438
- }
439
-
440
- const indent = text.match(/\n(\s+)"/)?.[1] ?? '\t'
441
- config.files = [...new Set(['references.d.ts', ...(config.files ?? [])])]
442
- config.exclude = (config.exclude ?? []).filter((e) => e !== 'src/main.ts')
443
-
444
- const types = config.compilerOptions?.types
445
- if (config.compilerOptions && Array.isArray(types) && !types.includes('@nativescript/types')) {
446
- config.compilerOptions.types = [...types, '@nativescript/types']
447
- }
448
-
449
- writeFileSync(path, JSON.stringify(config, null, indent) + '\n')
450
- return true
738
+ function enableNativeInTsconfig(appRoot, read, write) {
739
+ const path = join(appRoot, 'tsconfig.json')
740
+ const text = read(path)?.toString('utf8') ?? ''
741
+ let config
742
+
743
+ try {
744
+ config = JSON.parse(text)
745
+ } catch {
746
+ return false
747
+ }
748
+
749
+ if (!config || typeof config !== 'object') {
750
+ return false
751
+ }
752
+
753
+ const indent = text.match(/\n(\s+)"/)?.[1] ?? '\t'
754
+
755
+ config.files = [...new Set(['references.d.ts', ...(config.files ?? [])])]
756
+ config.exclude = (config.exclude ?? []).filter((e) => e !== 'src/main.ts')
757
+
758
+ const types = config.compilerOptions?.types
759
+
760
+ if (config.compilerOptions && Array.isArray(types) && !types.includes('@nativescript/types')) {
761
+ config.compilerOptions.types = [...types, '@nativescript/types']
762
+ }
763
+
764
+ // Pin core's type identity for linked checkouts; user-authored paths and
765
+ // an existing core mapping always win.
766
+ if (config.compilerOptions && typeof config.compilerOptions === 'object') {
767
+ const paths = (config.compilerOptions.paths ??= {})
768
+
769
+ for (const [key, value] of Object.entries(nativeCorePaths)) {
770
+ if (!(key in paths)) {
771
+ paths[key] = value
772
+ }
773
+ }
774
+ }
775
+
776
+ write(path, Buffer.from(JSON.stringify(config, null, indent) + '\n'), 0o644)
777
+ return true
451
778
  }
452
779
 
453
780
  /**
454
- * Enable `id` (plus unmet `requires`) inside an existing app at `appRoot`.
455
- * Additive only: existing files, scripts, and dep entries are skipped, never
456
- * overwritten. Returns a report for the caller to render.
781
+ * Plan enabling `id` and unmet requirements without writing. Existing target
782
+ * files, scripts and dependency choices stay intact; managed config and catalog
783
+ * changes carry raw-byte input hashes for the publisher.
457
784
  */
785
+ export function planTarget(appRoot, id) {
786
+ appRoot = resolve(appRoot)
787
+
788
+ const root = compatibilityRoot(appRoot)
789
+ const inputs = new Map<string, any>()
790
+ const contents = new Map<string, Buffer>()
791
+ const files = new Map<string, any>()
792
+ const directories = new Map<string, number>()
793
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
794
+ const within = (path) => {
795
+ const rel = relative(root, path)
796
+
797
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel))
798
+ }
799
+
800
+ const observe = (path) => {
801
+ path = resolve(path)
802
+ if (!within(path)) {
803
+ throw new Error(`Scaffold path leaves its workspace: ${path}`)
804
+ }
805
+
806
+ if (inputs.has(path)) {
807
+ return inputs.get(path)
808
+ }
809
+
810
+ let info
811
+
812
+ try {
813
+ info = lstatSync(path)
814
+ } catch (error) {
815
+ if (error.code !== 'ENOENT') {
816
+ throw error
817
+ }
818
+
819
+ const input = { path, kind: 'missing' }
820
+
821
+ inputs.set(path, input)
822
+ return input
823
+ }
824
+
825
+ if (info.isSymbolicLink() || (!info.isDirectory() && !info.isFile())) {
826
+ throw new Error(`Scaffold path must be an ordinary file or directory: ${path}`)
827
+ }
828
+
829
+ const input: Record<string, any> = {
830
+ path,
831
+ kind: info.isDirectory() ? 'directory' : 'file',
832
+ mode: info.mode & 0o777,
833
+ }
834
+
835
+ if (input.kind === 'file') {
836
+ if (info.size > 16 * 1024 * 1024) {
837
+ throw new Error(`Scaffold input exceeds 16 MiB: ${path}`)
838
+ }
839
+
840
+ const bytes = readFileSync(path)
841
+
842
+ input.sha256 = hash(bytes)
843
+ contents.set(path, bytes)
844
+ }
845
+
846
+ inputs.set(path, input)
847
+ return input
848
+ }
849
+
850
+ const read = (path) => {
851
+ const input = observe(path)
852
+
853
+ if (input.kind === 'missing') {
854
+ return null
855
+ }
856
+
857
+ if (input.kind !== 'file') {
858
+ throw new Error(`Expected scaffold file: ${path}`)
859
+ }
860
+
861
+ return contents.get(resolve(path))!
862
+ }
863
+
864
+ const directory = (path, mode = 0o755) => {
865
+ if (path === root || path === appRoot) {
866
+ return
867
+ }
868
+
869
+ const input = observe(path)
870
+
871
+ if (input.kind === 'directory') {
872
+ return
873
+ }
874
+
875
+ if (input.kind !== 'missing') {
876
+ throw new Error(`Expected scaffold directory: ${path}`)
877
+ }
878
+
879
+ directory(dirname(path))
880
+ directories.set(path, mode)
881
+ }
882
+
883
+ const write = (path, bytes, mode) => {
884
+ const before = read(path)
885
+
886
+ if (before !== null && before.equals(bytes)) {
887
+ return
888
+ }
889
+
890
+ directory(dirname(path))
891
+ files.set(path, {
892
+ path,
893
+ before: before === null ? null : hash(before),
894
+ content: bytes.toString('base64'),
895
+ mode: before === null ? mode : observe(path).mode,
896
+ })
897
+ }
898
+
899
+ const copy = (source, dest) => {
900
+ const info = lstatSync(source)
901
+
902
+ if (info.isDirectory()) {
903
+ directory(dest, info.mode & 0o777)
904
+ for (const name of readdirSync(source).sort()) {
905
+ copy(join(source, name), join(dest, name))
906
+ }
907
+ } else if (info.isFile()) {
908
+ write(dest, readFileSync(source), info.mode & 0o777)
909
+ } else {
910
+ throw new Error(`Scaffold template must not contain aliases: ${source}`)
911
+ }
912
+ }
913
+
914
+ const manifestPath = join(appRoot, 'package.json')
915
+ const raw = read(manifestPath)?.toString('utf8')
916
+
917
+ if (raw === undefined) {
918
+ throw new Error(`No package.json at ${appRoot}`)
919
+ }
920
+
921
+ const manifest: Record<string, any> = JSON.parse(raw)
922
+ const tpl = templateManifest()
923
+ const report: Record<string, any> = {
924
+ enabled: [],
925
+ already: [],
926
+ copied: [],
927
+ skipped: [],
928
+ scriptsAdded: [],
929
+ scriptsSkipped: [],
930
+ depsAdded: [],
931
+ }
932
+
933
+ for (const tid of resolveTargets([id])) {
934
+ const declared = { ...manifest.dependencies, ...manifest.devDependencies }
935
+ const runtime = { ios: '@nativescript/ios', android: '@nativescript/android' }[tid]
936
+ const enabled =
937
+ tid === 'web'
938
+ ? observe(join(appRoot, 'vite.config.ts')).kind !== 'missing' ||
939
+ observe(join(appRoot, 'vite.config.mts')).kind !== 'missing'
940
+ : tid === 'native-shared'
941
+ ? observe(join(appRoot, 'nativescript.config.ts')).kind !== 'missing'
942
+ : runtime !== undefined && typeof declared[runtime] === 'string'
943
+
944
+ if (enabled) {
945
+ report.already.push(tid)
946
+ continue
947
+ }
948
+
949
+ report.enabled.push(tid)
950
+
951
+ const t = targets[tid]
952
+
953
+ for (const rel of t.files) {
954
+ copyMissing(rel, appRoot, report, (path) => observe(path).kind !== 'missing', copy)
955
+ }
956
+
957
+ for (const [section, key] of [
958
+ ['dependencies', 'deps'],
959
+ ['devDependencies', 'devDeps'],
960
+ ]) {
961
+ for (const name of t[key] ?? []) {
962
+ manifest[section] ??= {}
963
+ if (manifest[section][name] === undefined) {
964
+ manifest[section][name] = tpl[section][name]
965
+ report.depsAdded.push(name)
966
+ }
967
+ }
968
+ }
969
+
970
+ manifest.scripts ??= {}
971
+ for (const name of t.scripts ?? []) {
972
+ if (manifest.scripts[name] === undefined) {
973
+ manifest.scripts[name] = tpl.scripts[name]
974
+ report.scriptsAdded.push(name)
975
+ } else if (manifest.scripts[name] !== tpl.scripts[name]) {
976
+ report.scriptsSkipped.push(name)
977
+ }
978
+ }
979
+
980
+ if (t.typecheck) {
981
+ const current = manifest.scripts.typecheck ?? ''
982
+
983
+ if (!current.includes(t.typecheck)) {
984
+ manifest.scripts.typecheck = current ? `${current} && ${t.typecheck}` : t.typecheck
985
+ report.scriptsAdded.push('typecheck')
986
+ }
987
+ }
988
+
989
+ if (tid === 'native-shared') {
990
+ if (manifest.main === undefined) {
991
+ manifest.main = tpl.main
992
+ }
993
+
994
+ // Native sources join the app's single typecheck program — pull the
995
+ // ambient declaration entry into the roots and un-exclude the
996
+ // NativeScript entry that a web-only scaffold skips.
997
+ report.tsconfigUpdated = enableNativeInTsconfig(appRoot, read, write)
998
+ }
999
+ }
1000
+
1001
+ // Newly enabled targets may carry patch entries the scaffolded
1002
+ // package.json never had — without them the next install misses the
1003
+ // framework patches. enabled+already covers the yaml-missing case, where
1004
+ // the file is regenerated for the whole enabled set.
1005
+ const enabledTargets = [...report.enabled, ...report.already]
1006
+ const manager = managerForRoot(
1007
+ root,
1008
+ root === appRoot
1009
+ ? manifest
1010
+ : JSON.parse(read(join(root, 'package.json'))?.toString('utf8') ?? 'null'),
1011
+ )
1012
+
1013
+ if (manager === 'pnpm') {
1014
+ const yamlPath = join(root, 'pnpm-workspace.yaml')
1015
+ const doc = parseDocument(read(yamlPath)?.toString('utf8') ?? 'packages: []\n')
1016
+ const { catalog, pins } = requestedCatalogPins(manifest)
1017
+
1018
+ for (const [name, spec] of Object.entries(pins)) {
1019
+ if (doc.getIn(['catalogs', catalog, name]) === undefined) {
1020
+ doc.setIn(['catalogs', catalog, name], spec)
1021
+ }
1022
+ }
1023
+
1024
+ const existing = doc.get('patchedDependencies')
1025
+ const present = new Set<string>(
1026
+ (isMap(existing) ? existing.items : []).map((pair) => specifierName(String(pair.key))),
1027
+ )
1028
+
1029
+ const patches = neededPatchEntries(enabledTargets, present)
1030
+
1031
+ for (const [specifier, path] of patches) {
1032
+ stagePatchFile(root, path, read, write)
1033
+ doc.setIn(['patchedDependencies', specifier], path)
1034
+ }
1035
+
1036
+ if (patches.length) {
1037
+ report.patchesAdded = true
1038
+ }
1039
+
1040
+ const resolved = new Set(resolveTargets(enabledTargets))
1041
+
1042
+ for (const id of resolved) {
1043
+ for (const name of targets[id].builds ?? []) {
1044
+ if (doc.getIn(['allowBuilds', name]) === undefined) {
1045
+ doc.setIn(['allowBuilds', name], true)
1046
+ report.allowBuildsAdded = true
1047
+ }
1048
+ }
1049
+ }
1050
+
1051
+ for (const entry of deniedBuilds) {
1052
+ if (
1053
+ (!entry.target || resolved.has(entry.target)) &&
1054
+ doc.getIn(['allowBuilds', entry.name]) === undefined
1055
+ ) {
1056
+ doc.setIn(['allowBuilds', entry.name], false)
1057
+ report.allowBuildsAdded = true
1058
+ }
1059
+ }
1060
+
1061
+ write(yamlPath, Buffer.from(String(doc)), 0o644)
1062
+ } else {
1063
+ const owner =
1064
+ root === appRoot ? manifest : JSON.parse(read(join(root, 'package.json'))!.toString('utf8'))
1065
+
1066
+ if (ensurePatchEntries(enabledTargets, root, owner, read, write)) {
1067
+ report.patchesAdded = true
1068
+ }
1069
+
1070
+ mergeCompatibilityCatalog(manifest, owner)
1071
+ if (root !== appRoot) {
1072
+ write(
1073
+ join(root, 'package.json'),
1074
+ Buffer.from(JSON.stringify(owner, null, '\t') + '\n'),
1075
+ 0o644,
1076
+ )
1077
+ }
1078
+ }
1079
+
1080
+ if (JSON.stringify(manifest) !== JSON.stringify(JSON.parse(raw))) {
1081
+ // Match the file's existing indent so diffs stay minimal.
1082
+ const indent = raw.match(/\n(\s+)"/)?.[1] ?? '\t'
1083
+
1084
+ write(manifestPath, Buffer.from(JSON.stringify(manifest, null, indent) + '\n'), 0o644)
1085
+ }
1086
+
1087
+ if (files.size > 8192 || inputs.size > 20000 || directories.size > 8192) {
1088
+ throw new Error('Scaffold plan exceeds inventory limits')
1089
+ }
1090
+
1091
+ let total = 0
1092
+
1093
+ for (const file of files.values()) {
1094
+ const bytes = Buffer.from(file.content, 'base64').length
1095
+
1096
+ total += bytes
1097
+ if (bytes > 16 * 1024 * 1024 || total > 32 * 1024 * 1024) {
1098
+ throw new Error('Scaffold plan exceeds byte limits')
1099
+ }
1100
+ }
1101
+
1102
+ return {
1103
+ version: 1,
1104
+ root,
1105
+ appRoot,
1106
+ id,
1107
+ files: [...files.values()],
1108
+ directories: [...directories].map(([path, mode]) => ({ path, mode })),
1109
+ inputs: [...inputs.values()],
1110
+ report,
1111
+ }
1112
+ }
1113
+
1114
+ /** Apply the same read-only plan used by native CLI orchestration. */
458
1115
  export function applyTarget(appRoot, id) {
459
- const manifestPath = join(appRoot, 'package.json')
460
- const raw = readFileSync(manifestPath, 'utf8')
461
- const manifest: Record<string, any> = JSON.parse(raw)
462
- const tpl = templateManifest()
463
- const report: Record<string, any> = {
464
- enabled: [],
465
- already: [],
466
- copied: [],
467
- skipped: [],
468
- scriptsAdded: [],
469
- scriptsSkipped: [],
470
- depsAdded: [],
471
- }
472
-
473
- for (const tid of resolveTargets([id])) {
474
- if (targetEnabled(appRoot, tid)) {
475
- report.already.push(tid)
476
- continue
477
- }
478
-
479
- report.enabled.push(tid)
480
- const t = targets[tid]
481
- for (const rel of t.files) {
482
- copyMissing(rel, appRoot, report)
483
- }
484
-
485
- for (const [section, key] of [
486
- ['dependencies', 'deps'],
487
- ['devDependencies', 'devDeps'],
488
- ]) {
489
- for (const name of t[key] ?? []) {
490
- manifest[section] ??= {}
491
- if (manifest[section][name] === undefined) {
492
- manifest[section][name] = tpl[section][name]
493
- report.depsAdded.push(name)
494
- }
495
- }
496
- }
497
-
498
- manifest.scripts ??= {}
499
- for (const name of t.scripts ?? []) {
500
- if (manifest.scripts[name] === undefined) {
501
- manifest.scripts[name] = tpl.scripts[name]
502
- report.scriptsAdded.push(name)
503
- } else if (manifest.scripts[name] !== tpl.scripts[name]) {
504
- report.scriptsSkipped.push(name)
505
- }
506
- }
507
-
508
- if (t.typecheck) {
509
- const current = manifest.scripts.typecheck ?? ''
510
- if (!current.includes(t.typecheck)) {
511
- manifest.scripts.typecheck = current ? `${current} && ${t.typecheck}` : t.typecheck
512
- report.scriptsAdded.push('typecheck')
513
- }
514
- }
515
-
516
- if (tid === 'native-shared') {
517
- if (manifest.main === undefined) {
518
- manifest.main = tpl.main
519
- }
520
-
521
- // Native sources join the app's single typecheck program — pull the
522
- // ambient declaration entry into the roots and un-exclude the
523
- // NativeScript entry that a web-only scaffold skips.
524
- report.tsconfigUpdated = enableNativeInTsconfig(appRoot)
525
- }
526
- }
527
-
528
- // Newly enabled targets may carry patch entries the scaffolded
529
- // package.json never had — without them the next install misses the
530
- // framework patches. enabled+already covers the yaml-missing case, where
531
- // the file is regenerated for the whole enabled set.
532
- if (ensurePatchEntries(appRoot, [...report.enabled, ...report.already], manifest)) {
533
- report.patchesAdded = true
534
- }
535
- ensureCompatibilityCatalog(appRoot, manifest)
536
-
537
- if (JSON.stringify(manifest) !== JSON.stringify(JSON.parse(raw))) {
538
- // Match the file's existing indent so diffs stay minimal.
539
- const indent = raw.match(/\n(\s+)"/)?.[1] ?? '\t'
540
- writeFileSync(manifestPath, JSON.stringify(manifest, null, indent) + '\n')
541
- }
542
- return report
1116
+ const plan = planTarget(appRoot, id)
1117
+
1118
+ for (const input of plan.inputs) {
1119
+ let info
1120
+
1121
+ try {
1122
+ info = lstatSync(input.path)
1123
+ } catch (error) {
1124
+ if (error.code !== 'ENOENT') {
1125
+ throw error
1126
+ }
1127
+ }
1128
+
1129
+ const kind = !info
1130
+ ? 'missing'
1131
+ : info.isFile()
1132
+ ? 'file'
1133
+ : info.isDirectory()
1134
+ ? 'directory'
1135
+ : 'alias'
1136
+
1137
+ if (
1138
+ kind !== input.kind ||
1139
+ (kind === 'file' &&
1140
+ createHash('sha256').update(readFileSync(input.path)).digest('hex') !== input.sha256)
1141
+ ) {
1142
+ throw new Error(`Scaffold input changed; retry: ${input.path}`)
1143
+ }
1144
+ }
1145
+
1146
+ for (const entry of plan.directories) {
1147
+ mkdirSync(entry.path, { recursive: true, mode: entry.mode })
1148
+ }
1149
+
1150
+ for (const entry of plan.files) {
1151
+ writeFileSync(entry.path, Buffer.from(entry.content, 'base64'), { mode: entry.mode })
1152
+ }
1153
+
1154
+ return plan.report
543
1155
  }