@geastack/cli 0.1.95 → 0.1.99

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.
package/README.md CHANGED
@@ -227,3 +227,69 @@ reload. Browser previews use simulated device APIs and browser layout; use the
227
227
  WASM renderer or a physical device to validate embedded rendering.
228
228
 
229
229
  Native compiler, UI, renderer, and display settings belong in the app manifest. See [Native build settings](docs/NATIVE-BUILD-CONFIG.md) for precedence, board overrides, and `gea config --board <alias>`.
230
+
231
+
232
+ ## Chrome DevTools debugger
233
+
234
+ `gea run --debug --target macos` builds and launches a native Gea app with CDP
235
+ at `127.0.0.1:9222`, then opens Chrome DevTools. A declared macOS deployment
236
+ target is not required for debugging; the source manifest is unchanged. On Mac,
237
+ `gea run --debug` defaults to native for an app that already declares macOS.
238
+ `gea run --debug --target web` uses the existing DOM/CSS runtime with Vite HMR.
239
+
240
+ Elements inspects the native tree, authored class CSS, common inline/computed
241
+ styles, text, attributes and layout. Inline CSS and tree edits affect the actual
242
+ AppKit window. The Console runs JavaScriptCore scripts with `document`, `$0`,
243
+ selectors, style edits, element creation/removal and click dispatch wired to the
244
+ native tree. Compiled C++ app modules/stores are not console globals; source
245
+ breakpoints, arbitrary class stylesheet edits and promise awaiting are not yet
246
+ implemented. Runtime edits do not save to source and can be replaced by app code.
247
+
248
+ Use `--debug-port 9223` for CDP and `--port 5182` for the DOM server. Native
249
+ `--no-open` exposes CDP without opening Chrome. Ctrl-C or closing the owned app
250
+ or browser stops the session. Other native targets, WASM and
251
+ direct AppKit widget graphs outside the Gea retained tree remain unsupported.
252
+
253
+ The CLI installs `@geastack/debugger` automatically. Debugging requires Node.js
254
+ 22 or later and Chrome/Chromium. Native builds need matching compiler and target
255
+ runtimes with debugger instrumentation; this release ships the host adapter and
256
+ CLI integration. `GEA_DEBUGGER_DIR` selects a development checkout;
257
+ contributor native launches use sibling Apple,
258
+ core/plugin packages and the shared compiler; explicit overrides win. Set
259
+ `GEA_CHROME_PATH` for a custom browser. Chrome uses its own app profile inside
260
+ `.gea/build/web`.
261
+
262
+
263
+ From your app directory, `gea run --debug --board amoled --debug-fps 10` builds and flashes debug
264
+ firmware on the registered AMOLED 2.06, then opens Chrome DevTools through USB.
265
+ Other ESP32 aliases use the same adapter. `--attach` connects to already-running
266
+ debug firmware without flashing; regular firmware is rejected before JTAG or
267
+ Chrome starts. `--no-open` exposes only the CDP endpoint.
268
+ `--port` selects the USB device when using `--board`, while `--debug-port` selects
269
+ CDP. The debugger owns the serial stream; stop it before using `gea devctl` or
270
+ `gea monitor` on that port.
271
+
272
+ Device builds retain engine CSS features and authored rules for runtime edits.
273
+ The board contains no JavaScript VM. Its Console evaluates JavaScript on the
274
+ host against a snapshot; supported mutations are acknowledged by the device
275
+ before evaluation returns. A following evaluation reads fresh device state.
276
+ Use an async function and `await document.createElement(...)` to create nodes.
277
+ On ESP32-S3, add `--debug-sources` to explicitly start USB JTAG for original
278
+ TypeScript source maps, line/column hardware breakpoints and Step Over/Into/Out. Scope
279
+ shows native C++ locals; paused-frame evaluation accepts GDB C++ expressions.
280
+ The board has two breakpoint slots. Its matching ELF is verified before attach;
281
+ older firmware needs a fresh build. Tree/style inspection does not start JTAG
282
+ by default. `GEA_DEBUGGER_JTAG=1` also opts in; `--no-debug-sources` overrides it.
283
+ Native Mac source stepping is not implemented yet. Inline
284
+ styles, authored class rules, attributes, text, append/remove and compiled event clicks affect the
285
+ actual device. Live changes are sampled every 750 ms. See the debugger README
286
+ for supported properties, USB bounds, and example scripts.
287
+
288
+ Add `--debug-fps 30` (or `--debug-fps 10`) to a board debug launch to reserve
289
+ more time for inspection and editing. Values are integers from 1 to 120. Debug
290
+ firmware enforces the cap across timer, TE and input/catch-up frame paths; app
291
+ FPS settings cannot exceed it. Use `--attach --debug-fps 10` to change the cap
292
+ on current debug firmware without rebuilding/flashing. Omitting the flag leaves
293
+ an existing attached app's cap alone; a fresh build defaults to normal pacing.
294
+ The cap persists after disconnecting. Firmware from before snapshot integrity
295
+ and FPS control support needs one rebuild.
@@ -0,0 +1,37 @@
1
+ # Custom QSPI panel startup
2
+
3
+ Custom ESP32-S3 boards can select the `co5300` or `sh8601` display binding and supply panel-specific startup settings under `chips.display.panel`:
4
+
5
+ ```json
6
+ {
7
+ "driver": "sh8601",
8
+ "interface": "qspi",
9
+ "width": 410,
10
+ "height": 502,
11
+ "pclkHz": 40000000,
12
+ "panel": {
13
+ "transferMode": "bitmap",
14
+ "xGap": 22,
15
+ "yGap": 0,
16
+ "initCommands": [
17
+ { "command": 17, "delayMs": 120 },
18
+ { "command": 196, "data": [128] },
19
+ { "command": 41, "delayMs": 10 }
20
+ ]
21
+ }
22
+ }
23
+ ```
24
+
25
+ This shortened list illustrates the schema; use the panel manufacturer's complete sequence. Commands and data are byte values; each command permits up to 32 bytes and a delay of 0–65535 ms. The list must contain 1–256 commands. Omitted data means a zero-length payload, not a zero byte.
26
+
27
+ `initCommands` replaces the binding's vendor initialization list. The ESP-IDF component still initializes pixel format and color order. Omit the list to retain the binding's existing startup behavior. Each omitted gap retains the binding's existing offset.
28
+
29
+ `pclkHz` optionally selects the QSPI clock from 1–80 MHz. Omit it to preserve the base target clock.
30
+
31
+ Offsets apply to both ESP-IDF bitmap draws and Gea's streamed address windows. They are added once; they do not change the logical width or height.
32
+
33
+ Register the profile using a local board entry with `targetDefinition` relative to `.gea/boards.json`, `appPlatform: "esp32"`, and its USB serial identity. Build and flash with `gea flash --board <alias> --app <id>`.
34
+
35
+ `panel.transferMode` selects `bitmap` (ESP-IDF sets each chunk window), `stream` (RAMWR/RAMWRC continuations), or `cs-held` (data-only continuations with chip select held). Omit it to preserve the base target mode. Use bitmap when reproducing a vendor reference before testing streaming optimizations.
36
+
37
+ `panel.minChunkRows` can be 1 or 2. Set it to 2 for panels whose address windows require even row starts and row counts; the flush pipeline must retain that minimum when reserving RAM for radios.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/cli",
3
- "version": "0.1.95",
3
+ "version": "0.1.99",
4
4
  "description": "Command-line front door for GeaStack apps, targets, and local toolchains.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -8,7 +8,7 @@
8
8
  "url": "git+https://github.com/geastack/cli.git"
9
9
  },
10
10
  "engines": {
11
- "node": ">=20.19"
11
+ "node": ">=22"
12
12
  },
13
13
  "type": "module",
14
14
  "bin": {
@@ -37,14 +37,15 @@
37
37
  ],
38
38
  "dependencies": {
39
39
  "@clack/prompts": "^1.8.0",
40
+ "@geastack/debugger": "^0.1.0",
40
41
  "@geastack/simulator": "^0.1.14",
41
- "@geastack/targets": "^0.1.93",
42
+ "@geastack/targets": "^0.1.98",
42
43
  "picocolors": "^1.1.1",
43
44
  "serialport": "^13.0.0"
44
45
  },
45
46
  "starterDependencies": {
46
47
  "@geastack/core": "^0.1.34",
47
- "@geastack/targets": "^0.1.88",
48
+ "@geastack/targets": "^0.1.98",
48
49
  "@geastack/apple": "^0.2.13"
49
50
  },
50
51
  "scripts": {
@@ -95,6 +95,24 @@ export const knownBoards = Object.freeze([
95
95
  gps: false
96
96
  }
97
97
  },
98
+ {
99
+ id: 'waveshare-lcd-154',
100
+ label: 'Waveshare ESP32-S3 Touch LCD 1.54',
101
+ alias: 'waveshare-154',
102
+ target: 'esp32-s3-touch-lcd-1.54',
103
+ adapter: 'esp32-idf',
104
+ mcu: 'ESP32-S3',
105
+ capabilities: {
106
+ display: '1.54 inch ST7789 LCD 240x240',
107
+ touch: 'CST816 capacitive touch',
108
+ wireless: ['WiFi', 'BLE'],
109
+ storage: ['flash', 'PSRAM', 'microSD'],
110
+ audio: ['ES8311 speaker', 'ES7210 microphone'],
111
+ imu: 'QMI8658 accelerometer and gyroscope',
112
+ battery: 'ADC voltage and charging status',
113
+ gps: false
114
+ }
115
+ },
98
116
  {
99
117
  id: 'esp32-s3-epaper-154',
100
118
  label: 'ESP32-S3 e-paper 1.54',
@@ -143,6 +161,22 @@ export const knownBoards = Object.freeze([
143
161
  gps: false
144
162
  }
145
163
  },
164
+ {
165
+ id: 'm5stack-stopwatch',
166
+ label: 'M5Stack StopWatch (C152)',
167
+ alias: 'stopwatch',
168
+ target: 'esp32-s3-m5stack-stopwatch',
169
+ adapter: 'esp32-idf',
170
+ mcu: 'ESP32-S3R8',
171
+ capabilities: {
172
+ display: '1.75 inch 466x466 round AMOLED (CO5300 QSPI)',
173
+ touch: 'CST820B capacitive touch',
174
+ wireless: ['WiFi', 'BLE'],
175
+ storage: ['16 MB flash', '8 MB PSRAM'],
176
+ audio: [],
177
+ gps: false
178
+ }
179
+ },
146
180
  {
147
181
  id: 'm5stack-tab5',
148
182
  label: 'M5Stack Tab5',
@@ -210,6 +210,25 @@ export function normalizeCustomTarget(raw, catalog) {
210
210
  throw new Error(`psram.speed must be 40, 80 or 120 MHz, not ${psramSpeed}.`)
211
211
  }
212
212
 
213
+ const panel = displayInterface === 'qspi' && !absent(display.panel) ? object(display.panel, 'chips.display.panel') : null
214
+ if (panel && !['co5300', 'sh8601'].includes(display.driver)) throw new Error('Panel startup settings currently support co5300 and sh8601 bindings.')
215
+ if (displayInterface !== 'qspi' && display?.panel !== undefined) throw new Error('Panel startup settings require a QSPI display.')
216
+ const panelConfig = panel ? {
217
+ ...(panel.minChunkRows === undefined ? {} : { minChunkRows: integer(panel.minChunkRows, 'panel.minChunkRows', { min: 1, max: 2 }) }),
218
+ ...(panel.transferMode === undefined ? {} : { transferMode: (() => { if (!['bitmap', 'stream', 'cs-held'].includes(panel.transferMode)) throw new Error('panel.transferMode must be bitmap, stream or cs-held.'); return panel.transferMode })() }),
219
+ ...(panel.xGap === undefined ? {} : { xGap: integer(panel.xGap, 'panel.xGap', { min: 0, max: 4095 }) }),
220
+ ...(panel.yGap === undefined ? {} : { yGap: integer(panel.yGap, 'panel.yGap', { min: 0, max: 4095 }) }),
221
+ ...(panel.initCommands === undefined ? {} : { initCommands: (() => {
222
+ if (!Array.isArray(panel.initCommands) || !panel.initCommands.length || panel.initCommands.length > 256) throw new Error('panel.initCommands must contain 1 through 256 commands.')
223
+ return panel.initCommands.map((entry, index) => {
224
+ object(entry, `panel.initCommands[${index}]`)
225
+ const data = entry.data ?? []
226
+ if (!Array.isArray(data) || data.length > 32) throw new Error('Panel command data must contain at most 32 bytes.')
227
+ return { command: integer(entry.command, 'panel command', { min: 0, max: 255 }), data: data.map(value => integer(value, 'panel data', { min: 0, max: 255 })), delayMs: integer(entry.delayMs ?? 0, 'panel delayMs', { min: 0, max: 65535 }) }
228
+ })
229
+ })() })
230
+ } : null
231
+
213
232
  const controller = display && !absent(display.controller) ? object(display.controller, 'chips.display.controller') : null
214
233
  if (controller && (displayInterface !== 'rgb' || !expander)) throw new Error('RGB controller initialization requires an I/O expander.')
215
234
  const byte = (value, label) => integer(value, label, { min: 0, max: 255 })
@@ -288,6 +307,8 @@ export function normalizeCustomTarget(raw, catalog) {
288
307
  } : {
289
308
  driver: display.driver,
290
309
  interface: 'qspi',
310
+ panel: panelConfig,
311
+ pclkHz: display.pclkHz === undefined ? null : integer(display.pclkHz, 'chips.display.pclkHz', { min: 1000000, max: 80000000 }),
291
312
  width: integer(display.width, 'chips.display.width', { min: 1, max: 4096 }),
292
313
  height: integer(display.height, 'chips.display.height', { min: 1, max: 4096 }),
293
314
  spiHost,
@@ -541,6 +562,27 @@ ${rgb.controller.commands.map(command => ` { ${command.command}, { ${command.da
541
562
  `
542
563
  }
543
564
 
565
+ // The bindings instantiate the same command list with their component's command type.
566
+ export function renderQspiPanelHeader(target) {
567
+ const panel = target.chips.display?.panel
568
+ const commands = panel?.initCommands
569
+ return `#pragma once
570
+ #include <array>
571
+ #include <cstdint>
572
+ ${panel?.xGap === undefined ? '' : `#define GEA_QSPI_PANEL_X_GAP ${panel.xGap}`}
573
+ ${panel?.yGap === undefined ? '' : `#define GEA_QSPI_PANEL_Y_GAP ${panel.yGap}`}
574
+ ${commands ? `#define GEA_QSPI_PANEL_HAS_INIT_COMMANDS 1
575
+ namespace gea::platform::custom_panel {
576
+ ${commands.map((entry, i) => entry.data.length ? `inline constexpr std::uint8_t data${i}[] = { ${entry.data.join(', ')} };` : '').join('\n')}
577
+ template<class Command> inline auto initCommands() {
578
+ return std::array<Command, ${commands.length}>{{
579
+ ${commands.map((entry, i) => ` { ${entry.command}, ${entry.data.length ? `data${i}` : 'nullptr'}, ${entry.data.length}, ${entry.delayMs} },`).join('\n')}
580
+ }};
581
+ }
582
+ }
583
+ ` : ''}`
584
+ }
585
+
544
586
  function cmakeQuote(value) {
545
587
  return `"${String(value).replace(/\\/g, '/').replace(/"/g, '\\"')}"`
546
588
  }
@@ -592,9 +634,13 @@ export function renderTargetCmake(target, includeDir, appDefines = new Set()) {
592
634
  // The QSPI panels take byte-swapped RGB565 over the wire and the base
593
635
  // stores it that way; an RGB panel's DMA reads the framebuffer as-is, so
594
636
  // it stores native order -- exactly what the Elecrow rotary target does.
637
+ display?.panel ? boardDefine('GEA_CUSTOM_QSPI_PANEL_CONFIG', 1) : '',
638
+ display?.panel?.minChunkRows ? boardDefine('GEA_EMBEDDED_DISPLAY_FLUSH_CHUNK_MIN', display.panel.minChunkRows) : '',
595
639
  display && display.interface === 'rgb' ? boardDefine('GEA_EMBEDDED_PIXEL_PANEL_ENDIAN', 0) : ''
596
640
  ].join('')
597
641
  return `set(GEA_CUSTOM_TARGET_ACTIVE 1)
642
+ ${display?.panel?.transferMode ? `set(GEA_CUSTOM_QSPI_TRANSFER_MODE \"${display.panel.transferMode}\")` : ''}
643
+ ${display?.interface === 'qspi' && display.pclkHz ? `set(GEA_CUSTOM_QSPI_PCLK_HZ ${display.pclkHz})` : ''}
598
644
  set(GEA_CUSTOM_TARGET_INCLUDE_DIR ${cmakeQuote(includeDir)})
599
645
  set(GEA_CUSTOM_TARGET_HAS_DISPLAY ${display ? 1 : 0})
600
646
  set(GEA_CUSTOM_TARGET_HAS_TOUCH ${touch ? 1 : 0})
@@ -620,6 +666,7 @@ export function writeCustomTarget({ definitionPath, outDir, catalog, appDefines
620
666
  const headerPath = path.join(outDir, 'board.h')
621
667
  const cmakePath = path.join(outDir, 'target.cmake')
622
668
  writeIfChanged(headerPath, renderBoardHeader(target))
669
+ writeIfChanged(path.join(outDir, 'gea_qspi_panel_config.h'), renderQspiPanelHeader(target))
623
670
  writeIfChanged(cmakePath, renderTargetCmake(target, outDir, appDefines))
624
671
  let partitionCsv = ''
625
672
  if (target.partitions) {
@@ -276,3 +276,19 @@ export function nativeScriptBuildEnv(app, platform, env, { dryRun = false, build
276
276
  const json = dryRun ? path.join(directory, 'gea-build-config.json') : writeBuildConfig(directory, resolved).json
277
277
  return { ...env, GEA_BUILD_CONFIG_JSON: json, GEA_CLI_BIN: fileURLToPath(new URL('../bin/gea.mjs', import.meta.url)) }
278
278
  }
279
+
280
+
281
+ // A debug launch can compile a Gea app natively without adding a deployment
282
+ // target to its source manifest. Keep authored CSS available for inspection.
283
+ export function appForNativeDebugger(app, platform) {
284
+ if (!['macos', 'esp32'].includes(platform)) fail('Native debugger build configuration requires macOS or ESP32')
285
+ const manifest = app.manifest || {}
286
+ const target = isObject(manifest.targets?.[platform]) ? manifest.targets[platform] : {}
287
+ const debugTarget = { ...target, build: { ...target.build, ...(platform === 'esp32' ? { renderer: { ...target.build?.renderer, recordInlinePositions: true } } : {}), compiler: {
288
+ ...target.build?.compiler, staticCssRules: false, staticCssTape: false, ...(platform === 'esp32' ? { generatedCodeOptimization: 'Og' } : {})
289
+ } } }
290
+ if (isObject(target.boards)) debugTarget.boards = Object.fromEntries(Object.entries(target.boards).map(([name, value]) => [name, isObject(value) ? { ...value, build: { ...value.build, ...(platform === 'esp32' ? { renderer: { ...value.build?.renderer, recordInlinePositions: true } } : {}), compiler: { ...value.build?.compiler, staticCssRules: false, staticCssTape: false, ...(platform === 'esp32' ? { generatedCodeOptimization: 'Og' } : {}) } } } : value]))
291
+ return { ...app, targets: { ...app.targets, [platform]: true }, manifest: {
292
+ ...manifest, targets: { ...manifest.targets, [platform]: debugTarget }
293
+ } }
294
+ }
@@ -169,7 +169,7 @@ async function flashEsp32(ctx, parsed, rest, options, selection, { monitor }) {
169
169
  const eraseSlotName = option(parsed, 'erase-slot', '')
170
170
  const slot = option(parsed, 'slot', '')
171
171
  const explicitImage = option(parsed, 'image', '')
172
- const app = explicitImage && !option(parsed, 'app') && !rest[0] ? null : optionalApp(ctx, parsed, rest, selection, { required: !explicitImage && !slotImages.length && !eraseSlotName && !flag(parsed, 'restore-boot') })
172
+ const app = options.debugApp || (explicitImage && !option(parsed, 'app') && !rest[0] ? null : optionalApp(ctx, parsed, rest, selection, { required: !explicitImage && !slotImages.length && !eraseSlotName && !flag(parsed, 'restore-boot') }))
173
173
 
174
174
  const buildDir = esp32BuildDir(ctx, selection, app?.id, flashEnv)
175
175
  const images = { ...buildImages(buildDir), buildDir }
@@ -1,14 +1,15 @@
1
- import { option } from '../args.mjs'
1
+ import { flag, option } from '../args.mjs'
2
2
  import { selectBoard } from './board.mjs'
3
3
  import { assertValidApp, assertTargetEnabled, resolveRequestedApp, knownPlatforms } from '../manifest.mjs'
4
- import { resolveAppBuildConfig } from '../build-config.mjs'
4
+ import { appForNativeDebugger, resolveAppBuildConfig } from '../build-config.mjs'
5
5
 
6
6
  export function configCommand(ctx, parsed, rest, { stdout, env }) {
7
- const app = resolveRequestedApp(ctx, parsed, rest)
7
+ let app = resolveRequestedApp(ctx, parsed, rest)
8
8
  assertValidApp(app)
9
9
  const requested = option(parsed, 'target', '')
10
10
  const selection = knownPlatforms.includes(requested) ? { target: '', appPlatform: requested } : selectBoard(ctx, parsed)
11
11
  const platform = selection.appPlatform || (selection.adapter === 'rp2350-pico' ? 'rp2350' : 'esp32')
12
+ if (flag(parsed, 'debug')) app = appForNativeDebugger(app, platform)
12
13
  assertTargetEnabled(ctx, app, selection.boardName || selection.target || platform)
13
14
  const resolved = resolveAppBuildConfig({ app, platform, board: selection.target, targetBase: selection.targetBase, targetsRoot: ctx.targetsRoot, env })
14
15
  stdout(JSON.stringify(resolved, null, 2))
@@ -0,0 +1,8 @@
1
+ import { fail, ExitCode } from './errors.mjs'
2
+
3
+ export function debugFps(value) {
4
+ if (value === undefined || value === '') return 0
5
+ const fps = Number(value)
6
+ if (typeof value === 'boolean' || !Number.isInteger(fps) || fps < 1 || fps > 120) fail('--debug-fps must be an integer from 1 to 120.', ExitCode.usage)
7
+ return fps
8
+ }
@@ -0,0 +1,24 @@
1
+ import { existsSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { esp32BuildDir } from './esp32/build.mjs'
4
+
5
+ // Attach can run from an app after its firmware was built from a workspace root.
6
+ // Return complete candidates; the relay verifies their hashes against firmware.
7
+ export function nativeDebugBuilds(ctx, selection, app, env = ctx.env || {}, hasFile = existsSync) {
8
+ const roots = new Set([ctx.buildRoot])
9
+ if (!env.GEA_PROJECT_BUILD_ROOT) {
10
+ let directory = path.resolve(app.root)
11
+ while (true) {
12
+ roots.add(path.join(directory, '.gea', 'build'))
13
+ const parent = path.dirname(directory)
14
+ if (parent === directory) break
15
+ directory = parent
16
+ }
17
+ }
18
+ return [...roots].flatMap((buildRoot) => {
19
+ const directory = esp32BuildDir({ ...ctx, buildRoot }, selection, app.id, env)
20
+ const elf = path.join(directory, 'gea_embedded.elf')
21
+ const metadata = path.join(directory, 'apps', app.id, 'gea-debug-source.json')
22
+ return hasFile(elf) && hasFile(metadata) ? [{ elf, metadata }] : []
23
+ })
24
+ }
@@ -0,0 +1,141 @@
1
+ import { existsSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { createRequire } from 'node:module'
4
+ import { fileURLToPath, pathToFileURL } from 'node:url'
5
+ import { CliError, ExitCode, fail } from './errors.mjs'
6
+ import { formatCommand } from './run.mjs'
7
+ import { appForNativeDebugger } from './build-config.mjs'
8
+ import { debugFps } from './debug-fps.mjs'
9
+ import { runMacos } from './macos/adapter.mjs'
10
+ import { resolveSimulatorDir } from './web/adapter.mjs'
11
+ import { option } from './args.mjs'
12
+
13
+ export function debuggerEntry(env, module = 'launch.mjs', {
14
+ hasFile = existsSync,
15
+ resolvePackage = specifier => createRequire(import.meta.url).resolve(specifier)
16
+ } = {}) {
17
+ if (Number(process.versions.node.split('.')[0]) < 22)
18
+ fail('The debugger requires Node.js 22 or later.', ExitCode.missingDependency)
19
+ const root = env.GEA_DEBUGGER_DIR
20
+ ? path.resolve(env.GEA_DEBUGGER_DIR)
21
+ : path.resolve(fileURLToPath(new URL('../..', import.meta.url)), 'debugger')
22
+ let entry = path.join(root, 'src', module)
23
+ if (!hasFile(entry)) {
24
+ if (env.GEA_DEBUGGER_DIR)
25
+ fail(`GEA_DEBUGGER_DIR does not contain src/${module}: ${root}`, ExitCode.missingDependency)
26
+ try {
27
+ entry = path.join(path.dirname(resolvePackage('@geastack/debugger/package.json')), 'src', module)
28
+ } catch {
29
+ fail('Debugger package not found. Install @geastack/debugger or set GEA_DEBUGGER_DIR.', ExitCode.missingDependency)
30
+ }
31
+ }
32
+ if (!hasFile(entry)) fail(`Debugger module not found: ${entry}`, ExitCode.missingDependency)
33
+ return entry
34
+ }
35
+
36
+ export function sourceDebuggingRequested(parsed, env = process.env) {
37
+ const value = option(parsed, 'debug-sources')
38
+ if (value !== undefined) {
39
+ if (value !== true && value !== false)
40
+ fail('Use --debug-sources or --no-debug-sources without a value.', ExitCode.usage)
41
+ return value
42
+ }
43
+ return env.GEA_DEBUGGER_JTAG === '1'
44
+ }
45
+
46
+ export async function runDebug({ app, env, dryRun = false, stdout, port = 5181, debugPort = 9222, target = 'web', open = true }) {
47
+ if (app.runtime !== 'gea') fail(`Debugger requires the gea runtime; '${app.id}' uses '${app.runtime}'.`, ExitCode.usage)
48
+ const entry = debuggerEntry(env)
49
+ try {
50
+ const { launchDebugger, chromeArgs, chromeExecutable, portNumber } = await import(pathToFileURL(entry).href)
51
+ port = portNumber(port, '--port')
52
+ debugPort = portNumber(debugPort, '--debug-port')
53
+ if (target === 'macos') {
54
+ if (process.platform !== 'darwin') fail('Native macOS debugging requires a Mac.', ExitCode.usage)
55
+ const debuggerRoot = path.resolve(path.dirname(entry), '..')
56
+ const source = path.join(debuggerRoot, 'native/macos.mm')
57
+ if (!existsSync(source)) fail(`Native debugger source not found: ${source}`, ExitCode.missingDependency)
58
+ const nativeEnv = { ...env, GEA_NATIVE_DEBUGGER: '1', GEA_DEBUGGER_NATIVE_SOURCE: source }
59
+ // Contributor checkouts use one source stack and the shared compiler.
60
+ // Explicit overrides win; installed packages retain npm resolution.
61
+ const stack = path.resolve(debuggerRoot, '..')
62
+ for (const [key, relative, marker] of [
63
+ ['GEA_APPLE_ROOT', 'apple/packages/geastack-apple', 'targets/macos/build-macos.sh'],
64
+ ['GEA_CORE', 'core/packages/core', 'gea_sources.mjs'],
65
+ ['GEA_COMPILER', 'compiler', 'dist/cli.js'],
66
+ ['GEA_PLUGIN', 'core/packages/geatsc-plugin-gea', 'dist/index.js']
67
+ ]) {
68
+ const directory = path.join(stack, relative)
69
+ if (!nativeEnv[key] && existsSync(path.join(directory, marker))) nativeEnv[key] = directory
70
+ }
71
+ if (!nativeEnv.GEA_GEATSC_BIN && nativeEnv.GEA_COMPILER) nativeEnv.GEA_GEATSC_BIN = path.join(nativeEnv.GEA_COMPILER, 'dist/cli.js')
72
+ await runMacos({ app: appForNativeDebugger(app, 'macos'), env: nativeEnv, dryRun, stdout })
73
+ const outputRoot = path.resolve(app.root, env.GEA_MACOS_OUTPUT_DIR || 'dist/macos')
74
+ const subpath = env.GEA_MACOS_OUTPUT_TAG ? path.join('.namespaces', env.GEA_MACOS_OUTPUT_TAG, app.id) : app.id
75
+ const executable = path.join(outputRoot, subpath, `${app.name}.app`, 'Contents/MacOS', app.name)
76
+ if (dryRun) { stdout(formatCommand([executable])); stdout(`Native CDP: ws://127.0.0.1:${debugPort}/devtools/page/gea`); return 0 }
77
+ if (!existsSync(executable)) fail(`Built native executable not found: ${executable}`, ExitCode.buildFailed)
78
+ const { launchNativeDebugger } = await import(pathToFileURL(path.join(debuggerRoot, 'src/native.mjs')).href)
79
+ return await launchNativeDebugger({ executable, appRoot: app.root, title: app.name, env, debugPort, stdout, open })
80
+ }
81
+ const script = path.join(resolveSimulatorDir(env), 'targets/web/dev-web.mjs')
82
+ if (!existsSync(script)) fail(`Web dev server not found: ${script}`, ExitCode.missingDependency)
83
+ if (port === debugPort) fail('--port and --debug-port must differ.', ExitCode.usage)
84
+ if (dryRun) {
85
+ stdout(formatCommand([process.execPath, script, '--app-dir', app.root, '--port', String(port), '--host', '127.0.0.1']))
86
+ stdout(formatCommand([chromeExecutable(env), ...chromeArgs({ appRoot: app.root, url: `http://127.0.0.1:${port}/`, debugPort })]))
87
+ return 0
88
+ }
89
+ return await launchDebugger({ appRoot: app.root, script, env, port, debugPort, stdout })
90
+ } catch (error) {
91
+ if (error instanceof CliError) throw error
92
+ throw new CliError(error.message, ExitCode.generic)
93
+ }
94
+ }
95
+
96
+ // Build/flash through the canonical board adapter, then give one relay exclusive
97
+ // ownership of its USB request stream. --attach reuses debug-enabled firmware.
98
+ export async function runBoardDebug({ ctx, parsed, rest, options, app }) {
99
+ if (app.runtime !== 'gea') fail(`Debugger requires the gea runtime; '${app.id}' uses '${app.runtime}'.`, ExitCode.usage)
100
+ const { selectBoard, flashCommand } = await import('./commands/board.mjs')
101
+ const { flag, option } = await import('./args.mjs')
102
+ const { openDevice } = await import('./device/device.mjs')
103
+ const { encodePng } = await import('./device/image.mjs')
104
+ const entry = debuggerEntry(options.env, 'device.mjs')
105
+ const root = path.resolve(path.dirname(entry), '..')
106
+ const fps = debugFps(option(parsed, 'debug-fps'))
107
+ const env = { ...options.env, GEA_NATIVE_DEBUGGER: '1', GEA_DEBUGGER_FPS: String(fps), GEA_GEATSC_DEBUG_INFO: '1' }
108
+ const stack = path.resolve(root, '..')
109
+ const debugCtx = { ...ctx, env }
110
+ for (const [field, key, relative] of [
111
+ ['targetsRoot', 'GEA_TARGETS_ROOT', 'targets'],
112
+ ['compilerPackageDir', 'GEA_COMPILER_DIR', 'compiler'],
113
+ ...['core', 'engine', 'host', 'chips', 'elements', 'geaos'].map(name => [name + 'PackageDir', 'GEA_' + name.toUpperCase() + (name === 'geaos' ? '_PACKAGE_DIR' : '_DIR'), 'core/packages/' + name]),
114
+ ['pluginPackageDir', 'GEA_PLUGIN_DIR', 'core/packages/geatsc-plugin-gea']
115
+ ]) { const directory = path.join(stack, relative); if (!env[key] && existsSync(path.join(directory, 'package.json'))) debugCtx[field] = directory }
116
+ const selection = selectBoard(debugCtx, parsed, { usb: true })
117
+ if (selection.adapter !== 'esp32-idf') fail('--debug board support currently requires an ESP32 target.', ExitCode.usage)
118
+ const sources = sourceDebuggingRequested(parsed, env)
119
+ if (sources && (selection.idfTarget || 'esp32s3') !== 'esp32s3')
120
+ fail('--debug-sources requires an ESP32-S3 board with USB JTAG.', ExitCode.usage)
121
+ const { portNumber, chromeExecutable } = await import(pathToFileURL(path.join(root, 'src/launch.mjs')).href)
122
+ const debugPort = portNumber(option(parsed, 'debug-port', 9222), '--debug-port')
123
+ if (option(parsed, 'open', true) !== false) chromeExecutable(env)
124
+ const { launchDeviceDebugger } = await import(pathToFileURL(entry).href)
125
+ if (!flag(parsed, 'attach')) await flashCommand(debugCtx, parsed, rest, { ...options, env, debugApp: appForNativeDebugger(app, 'esp32') }, { monitor: false })
126
+ if (flag(parsed, 'dry-run')) { options.stdout(`Device CDP: ws://127.0.0.1:${debugPort}/devtools/page/gea`); if(fps)options.stdout(`Device debug FPS cap: ${fps}`); if(sources)options.stdout('Native Sources: USB JTAG requested.'); return 0 }
127
+ let nativeDebug
128
+ if (sources) {
129
+ const { nativeDebugBuilds } = await import('./debugger-builds.mjs')
130
+ const builds = nativeDebugBuilds(debugCtx, selection, app, env)
131
+ if (builds.length) {
132
+ const { activateEspIdf } = await import('./esp32/idf-env.mjs')
133
+ const idf = activateEspIdf({env})
134
+ nativeDebug = {builds,serial:selection.usbSerial,env:idf.env,
135
+ gdbExecutable:env.GEA_GDB_BIN || 'xtensa-esp32s3-elf-gdb',openocdExecutable:env.GEA_OPENOCD_BIN || 'openocd'}
136
+ } else fail('--debug-sources requires matching local ELF/source metadata. Rebuild without --attach to generate source debugging files.', ExitCode.missingDependency)
137
+ } else options.stdout('Native Sources: disabled; --debug-sources explicitly enables USB JTAG for breakpoints and stepping.')
138
+ const device = await openDevice({ selection, transport: 'usb', env, stderr: options.stderr, waitSeconds: 15 })
139
+ try { return await launchDeviceDebugger({ serial: device.serial, screenshot: async () => { const shot = await device.screenshot(); return encodePng(shot.width, shot.height, shot.rgb).toString('base64') }, appRoot: app.root, title: app.name, env, debugPort, debugFps: fps, nativeDebug, stdout: options.stdout, open: option(parsed, 'open', true) !== false }) }
140
+ finally { await device.close() }
141
+ }
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { mkdirSync, writeFileSync } from 'node:fs'
3
3
  import path from 'node:path'
4
+ import { execFileSync } from 'node:child_process'
4
5
 
5
6
  import { crc32, decodeRgb565Raw, decodeRgb565Rle } from './image.mjs'
6
7
 
@@ -64,9 +65,41 @@ export class SerialDevice {
64
65
  }
65
66
 
66
67
  static async open({ path: devicePath, baudRate = 115200, trace = false, stderr }) {
68
+ // Older clients and serial monitors may not take an advisory lock. On macOS,
69
+ // check both names of the device before opening; flock handles racing clients.
70
+ if (process.platform === 'darwin' && /^\/dev\/(cu|tty)\./.test(devicePath)) {
71
+ let owners = ''
72
+ try {
73
+ owners = execFileSync('/usr/sbin/lsof', [
74
+ '-t',
75
+ devicePath.replace('/dev/tty.', '/dev/cu.'),
76
+ devicePath.replace('/dev/cu.', '/dev/tty.')
77
+ ], {
78
+ encoding: 'utf8',
79
+ timeout: 2000,
80
+ stdio: ['ignore', 'pipe', 'ignore']
81
+ }).trim()
82
+ } catch (error) {
83
+ if (error.status !== 1 && error.code !== 'ENOENT') {
84
+ throw new Error(`Could not check serial ownership for ${devicePath}`, { cause: error })
85
+ }
86
+ owners = error.stdout?.toString().trim() || ''
87
+ }
88
+ if (owners) {
89
+ const pids = [...new Set(owners.split(/\s+/))].join(', ')
90
+ throw new Error(`Serial port ${devicePath} is already in use (PID ${pids}). Close its debugger or serial monitor before attaching.`)
91
+ }
92
+ }
67
93
  const { SerialPort } = await loadSerialport()
68
- const port = new SerialPort({ path: devicePath, baudRate, autoOpen: false, hupcl: false, lock: false })
69
- await new Promise((resolve, reject) => port.open((error) => (error ? reject(error) : resolve())))
94
+ const port = new SerialPort({ path: devicePath, baudRate, autoOpen: false, hupcl: false, lock: true })
95
+ try {
96
+ await new Promise((resolve, reject) => port.open((error) => (error ? reject(error) : resolve())))
97
+ } catch (error) {
98
+ if (/cannot lock port|resource (?:temporarily unavailable|busy)|sharing violation/i.test(error.message)) {
99
+ throw new Error(`Serial port ${devicePath} is already in use. Close its debugger or serial monitor before attaching.`, { cause: error })
100
+ }
101
+ throw error
102
+ }
70
103
  return new SerialDevice(port, { path: devicePath, trace, stderr })
71
104
  }
72
105
 
@@ -76,17 +109,22 @@ export class SerialDevice {
76
109
  for (const waiter of waiters) waiter()
77
110
  }
78
111
 
79
- waitForData(timeoutMs) {
80
- return new Promise((resolve) => {
112
+ waitForData(timeoutMs, signal) {
113
+ return new Promise((resolve, reject) => {
114
+ signal?.throwIfAborted()
115
+ const abort = () => { clearTimeout(timer); this.waiters = this.waiters.filter(waiter => waiter !== done); reject(signal.reason) }
81
116
  const timer = setTimeout(() => {
117
+ signal?.removeEventListener('abort', abort)
82
118
  this.waiters = this.waiters.filter((waiter) => waiter !== done)
83
119
  resolve(false)
84
120
  }, Math.max(0, timeoutMs))
85
121
  const done = () => {
122
+ signal?.removeEventListener('abort', abort)
86
123
  clearTimeout(timer)
87
124
  resolve(true)
88
125
  }
89
126
  this.waiters.push(done)
127
+ signal?.addEventListener('abort', abort, { once: true })
90
128
  })
91
129
  }
92
130
 
@@ -135,9 +173,10 @@ export class SerialDevice {
135
173
  })
136
174
  }
137
175
 
138
- async readLine(timeoutMs) {
176
+ async readLine(timeoutMs, signal) {
139
177
  const deadline = Date.now() + timeoutMs
140
178
  while (true) {
179
+ signal?.throwIfAborted()
141
180
  const newline = this.buffer.indexOf(0x0a)
142
181
  if (newline >= 0) {
143
182
  const raw = this.buffer.subarray(0, newline)
@@ -148,7 +187,7 @@ export class SerialDevice {
148
187
  if (this.closed) return null
149
188
  const remaining = deadline - Date.now()
150
189
  if (remaining <= 0) return null
151
- await this.waitForData(remaining)
190
+ await this.waitForData(remaining, signal)
152
191
  }
153
192
  }
154
193
 
@@ -178,13 +217,13 @@ export class SerialDevice {
178
217
  }
179
218
  }
180
219
 
181
- async command(line, prefixes, timeoutMs = 5000) {
220
+ async command(line, prefixes, timeoutMs = 5000, signal) {
182
221
  await this.writeLine(line)
183
222
  const deadline = Date.now() + timeoutMs
184
223
  while (true) {
185
224
  const remaining = deadline - Date.now()
186
225
  if (remaining <= 0) throw new Error(`timed out waiting for response to ${JSON.stringify(line)}`)
187
- const received = await this.readLine(remaining)
226
+ const received = await this.readLine(remaining, signal)
188
227
  if (received === null) throw new Error(`timed out waiting for response to ${JSON.stringify(line)}`)
189
228
  if (this.trace) this.stderr(received)
190
229
  const frame = geadevFragment(received)
@@ -193,7 +232,7 @@ export class SerialDevice {
193
232
  }
194
233
  }
195
234
 
196
- async collect(line, { begin = null, data = 'GEADEV:DATA ', end, error = ['GEADEV:ERR'], timeoutMs = 8000 }) {
235
+ async collect(line, { begin = null, data = 'GEADEV:DATA ', end, error = ['GEADEV:ERR'], timeoutMs = 8000, signal }) {
197
236
  await this.writeLine(line)
198
237
  const deadline = Date.now() + timeoutMs
199
238
  const chunks = []
@@ -202,13 +241,13 @@ export class SerialDevice {
202
241
  while (true) {
203
242
  const remaining = deadline - Date.now()
204
243
  if (remaining <= 0) throw new Error(`timed out waiting for ${line}`)
205
- const received = await this.readLine(remaining)
244
+ const received = await this.readLine(remaining, signal)
206
245
  if (received === null) throw new Error(`timed out waiting for ${line}`)
207
246
  const frame = geadevFragment(received)
208
247
  if (this.trace && !frame.startsWith(data)) this.stderr(received)
209
248
  if (error.some((prefix) => frame.startsWith(prefix))) throw new Error(frame)
210
249
  if (begin && beginFrame === null) {
211
- if (frame.startsWith(begin)) beginFrame = frame
250
+ if (typeof begin === 'function' ? begin(frame) : frame.startsWith(begin)) beginFrame = frame
212
251
  continue
213
252
  }
214
253
  if (frame.startsWith(data)) {
@@ -1,5 +1,6 @@
1
+ import { debugFps } from '../debug-fps.mjs'
1
2
  import { spawnSync } from 'node:child_process'
2
- import { resolveBuildConfig, writeBuildConfig } from '../build-config.mjs'
3
+ import { appForNativeDebugger, resolveBuildConfig, writeBuildConfig } from '../build-config.mjs'
3
4
  import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
4
5
  import path from 'node:path'
5
6
 
@@ -325,7 +326,10 @@ export function prepareEsp32Build({ ctx, selection, app = null, env = ctx.env ||
325
326
  }
326
327
  const capabilities = app ? resolveAppCapabilities(ctx, app, { env }) : { network: false, ble: false, bleApi: false, audio: false, bindings: [], features: [] }
327
328
  if (bleOta) capabilities.ble = true
328
- const resolvedBuild = resolveBuildConfig({ app, platform: 'esp32', board: selection.target, targetBase: selection.targetBase, targetsRoot: ctx.targetsRoot, env, capabilities })
329
+ // Console-created native nodes require the retained runtime even when the
330
+ // app's original source could use the direct-canvas specialization.
331
+ const buildCapabilities = env.GEA_NATIVE_DEBUGGER === '1' ? { ...capabilities, features: capabilities.features.filter(f => !f.startsWith('runtime-analysis-')) } : capabilities
332
+ const resolvedBuild = resolveBuildConfig({ app: env.GEA_NATIVE_DEBUGGER === '1' ? appForNativeDebugger(app, 'esp32') : app, platform: 'esp32', board: selection.target, targetBase: selection.targetBase, targetsRoot: ctx.targetsRoot, env, capabilities: buildCapabilities })
329
333
  const idfTarget = selection.idfTarget || 'esp32s3'
330
334
  const buildDir = esp32BuildDir(ctx, selection, app?.id, env)
331
335
  // gea.targets.esp32.sdkconfig: the app's own Kconfig defaults, layered over
@@ -429,7 +433,7 @@ function preparePartitions(app, config, buildDir, targetId) {
429
433
  // `set(... CACHE STRING ...)`, so a -D of the same name, which exists before
430
434
  // the board's CMakeLists runs, wins without the board knowing about apps.
431
435
  const cssDpr = cssDevicePixelRatioLiteral(resolvedBuild.cssDevicePixelRatio)
432
- const appDefines = [withRendererFeatureDefines(resolvedBuild.defines.join(';'), capabilities.features, { devicePixelRatio: cssDpr ? Number(cssDpr) : undefined }), cssDpr && `GEA_EMBEDDED_CSS_LAYOUT_DEVICE_PIXEL_RATIO=${cssDpr}`]
436
+ const appDefines = [env.GEA_NATIVE_DEBUGGER === '1' && 'GEA_NATIVE_DEBUGGER=1', env.GEA_NATIVE_DEBUGGER === '1' && `GEA_NATIVE_DEBUGGER_FPS=${debugFps(env.GEA_DEBUGGER_FPS === '0' ? undefined : env.GEA_DEBUGGER_FPS)}`, withRendererFeatureDefines(resolvedBuild.defines.join(';'), env.GEA_NATIVE_DEBUGGER === '1' ? capabilities.features.filter(f => f === 'worker-realms') : capabilities.features, { devicePixelRatio: cssDpr ? Number(cssDpr) : undefined }), cssDpr && `GEA_EMBEDDED_CSS_LAYOUT_DEVICE_PIXEL_RATIO=${cssDpr}`]
433
437
  .filter(Boolean)
434
438
  .join(';')
435
439
  const esp32Config = appEsp32Config
package/src/gea.mjs CHANGED
@@ -58,6 +58,25 @@ export async function runGea(argv, io = {}) {
58
58
  // "latest release" lookup without touching the network.
59
59
  const options = { stdout, stderr, env, stdin, output, prompt, probeSerialDevice: io.probeSerialDevice, fetchEspIdfLatest: io.fetchEspIdfLatest }
60
60
 
61
+ if (option(parsed, 'debug-fps') !== undefined && !flag(parsed, 'debug')) fail('--debug-fps requires --debug.', ExitCode.usage)
62
+ if (flag(parsed, 'debug-sources') && !flag(parsed, 'debug')) fail('--debug-sources requires --debug with an ESP32-S3 board.', ExitCode.usage)
63
+
64
+ if (['run', 'dev', 'simulate'].includes(command) && flag(parsed, 'debug')) {
65
+ const target = option(parsed, 'target', '')
66
+ if (option(parsed, 'board') || target === 'esp32') {
67
+ const { runBoardDebug } = await import('./debugger.mjs')
68
+ return runBoardDebug({ ctx, parsed, rest, options, app: webApp(ctx, parsed, rest, cwd) })
69
+ }
70
+ if ((target && !['web', 'macos'].includes(target)) || option(parsed, 'renderer', 'dom') !== 'dom') {
71
+ fail('--debug supports the DOM runtime, native macOS, and ESP32 boards over USB.', ExitCode.usage)
72
+ }
73
+ if (option(parsed, 'debug-fps') !== undefined) fail('--debug-fps currently requires --debug with an ESP32 board.', ExitCode.usage)
74
+ if (flag(parsed, 'debug-sources')) fail('--debug-sources requires --debug with an ESP32-S3 board.', ExitCode.usage)
75
+ const app = webApp(ctx, parsed, rest, cwd)
76
+ const { runDebug } = await import('./debugger.mjs')
77
+ return runDebug({ app, env, dryRun: flag(parsed, 'dry-run'), stdout, port: option(parsed, 'port', 5181), debugPort: option(parsed, 'debug-port', 9222), target: target || (command === 'run' && process.platform === 'darwin' && app.targets?.macos ? 'macos' : 'web'), open: option(parsed, 'open', true) !== false })
78
+ }
79
+
61
80
  // Xbox is both a platform and a concrete built-in UWP target.
62
81
  const target = option(parsed, 'target', '')
63
82
  // macOS never reaches board selection: it has no alias and no catalog entry,
@@ -247,6 +266,7 @@ ${heading('Usage:')}
247
266
  gea doctor [--json] [--strict] check packages and toolchains
248
267
 
249
268
  ${heading('Run on this machine (no board needed):')}
269
+ gea run [app] --debug [--debug-port N] live tree/CSS in Chrome DevTools [--target macos|web|esp32] [--board alias] [--attach] [--debug-fps 1..120] [--debug-sources]
250
270
  gea simulate [app] [--port N] DOM emulator with HMR [--renderer dom|wasm] [--no-open] [--width W --height H --dpr D --zoom Z]
251
271
  gea dev [app] [--port N] real DOM + CSS dev server with HMR (same as --target web)
252
272
  gea build --target web [app] [--out-dir d] build the app as a real web app
@@ -14,7 +14,7 @@ import { formatCommand } from '../run.mjs'
14
14
  // app's own module resolution is what finds it. An app declares `targets.macos`
15
15
  // and nothing else; the script reads the rest from the same manifest.
16
16
  export function runMacos({ app, env, dryRun = false, stdout }) {
17
- const { script, require } = appleTargetScript(app, 'macos', 'build-macos.sh')
17
+ const { script, require } = appleTargetScript(app, 'macos', 'build-macos.sh', env)
18
18
  const childEnv = appleChildEnv(app, nativeScriptBuildEnv(app, 'macos', env, { dryRun }), require)
19
19
  if (dryRun) {
20
20
  stdout(formatCommand(['bash', script, app.id]))
@@ -29,11 +29,11 @@ export function runMacos({ app, env, dryRun = false, stdout }) {
29
29
  // Both Apple targets ship as one script each inside @geastack/apple, and both
30
30
  // resolve it the same way: through the app's own dependencies. iOS reuses this
31
31
  // from src/ios/adapter.mjs rather than restating the resolution.
32
- export function appleTargetScript(app, platform, scriptName) {
32
+ export function appleTargetScript(app, platform, scriptName, env = process.env) {
33
33
  const require = createRequire(path.join(app.root, 'package.json'))
34
- let appleRoot = ''
34
+ let appleRoot = env.GEA_APPLE_ROOT ? path.resolve(env.GEA_APPLE_ROOT) : ''
35
35
  try {
36
- appleRoot = path.dirname(require.resolve('@geastack/apple/package.json'))
36
+ if (!appleRoot) appleRoot = path.dirname(require.resolve('@geastack/apple/package.json'))
37
37
  } catch {
38
38
  fail(`'${app.id}' targets ${platformLabel(platform)} but @geastack/apple is not installed in ${app.root} — run npm install there.`, ExitCode.missingDependency)
39
39
  }
@@ -37,18 +37,26 @@ function toolchainHasRuntime(root) {
37
37
  return false
38
38
  }
39
39
 
40
- function globDirs(pattern) {
41
- const parent = path.dirname(pattern)
42
- const prefix = path.basename(pattern).replace(/\*.*$/, '')
43
- const suffix = pattern.includes('*') ? pattern.slice(pattern.indexOf('*') + 1) : ''
44
- try {
45
- return readdirSync(parent)
46
- .filter((name) => name.startsWith(prefix))
47
- .map((name) => path.join(parent, name, suffix))
48
- .filter((dir) => existsSync(dir))
49
- } catch {
50
- return []
40
+ // Expands `*` in any path segment, one directory level per segment:
41
+ // `~/Tools/arm-gnu-toolchain-*/extract/Payload` matches every installed version.
42
+ export function globDirs(pattern) {
43
+ const segments = pattern.split(path.sep)
44
+ let matches = [segments[0] || path.sep]
45
+ for (const segment of segments.slice(1)) {
46
+ if (!segment.includes('*')) {
47
+ matches = matches.map((dir) => path.join(dir, segment))
48
+ continue
49
+ }
50
+ const re = new RegExp(`^${segment.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`)
51
+ matches = matches.flatMap((dir) => {
52
+ try {
53
+ return readdirSync(dir).filter((name) => re.test(name)).sort().map((name) => path.join(dir, name))
54
+ } catch {
55
+ return []
56
+ }
57
+ })
51
58
  }
59
+ return matches.filter((dir) => existsSync(dir))
52
60
  }
53
61
 
54
62
  export function prepareArmToolchain(env, stderr = () => {}) {