key-screen-framework 0.1.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 (113) hide show
  1. package/chunks/store-txJwmrlO.js +281 -0
  2. package/chunks/useArduinoBuild-CVr4XAsL.js +152 -0
  3. package/cli/check-arduino-bundle.mjs +157 -0
  4. package/cli/doctor-project.mjs +554 -0
  5. package/cli/generate-screen.mjs +286 -0
  6. package/cli/migrate-project.mjs +679 -0
  7. package/cli/new-project.mjs +344 -0
  8. package/cli/remove-screen.mjs +83 -0
  9. package/cli/screen-generation-contract.mjs +127 -0
  10. package/cli/screen-generation-renderers.mjs +71 -0
  11. package/cli/screen-module-utils.mjs +148 -0
  12. package/cli/screen-script-utils.mjs +92 -0
  13. package/cli/setup-arduino-cli.mjs +515 -0
  14. package/cli/source-module-specifiers.mjs +89 -0
  15. package/cli/sync-screens.mjs +48 -0
  16. package/main/index.js +2003 -0
  17. package/package.json +108 -0
  18. package/preload/index.js +69 -0
  19. package/renderer/components/VideoSceneScreen.js +160 -0
  20. package/renderer/hooks/index.js +6 -0
  21. package/renderer/index.js +3092 -0
  22. package/renderer/store.js +6 -0
  23. package/renderer/styles.css +1395 -0
  24. package/shared/arduino-board.js +136 -0
  25. package/shared/arduino-keyboard-shortcut.js +77 -0
  26. package/shared/index.js +25 -0
  27. package/shared/screen-catalog.js +35 -0
  28. package/shared/screen-shortcuts.js +164 -0
  29. package/shared/types.js +1 -0
  30. package/templates/project/README.md +45 -0
  31. package/templates/project/build/favicon-mac.png +0 -0
  32. package/templates/project/build/favicon.ico +0 -0
  33. package/templates/project/build/favicon.png +0 -0
  34. package/templates/project/e2e/smoke.spec.ts +10 -0
  35. package/templates/project/electron.vite.config.ts +40 -0
  36. package/templates/project/eslint.config.js +23 -0
  37. package/templates/project/gitignore +19 -0
  38. package/templates/project/media/audio/.gitkeep +1 -0
  39. package/templates/project/media/font/.gitkeep +1 -0
  40. package/templates/project/media/image/.gitkeep +1 -0
  41. package/templates/project/media/video/.gitkeep +1 -0
  42. package/templates/project/media/video/external-sample-30s.mp4 +0 -0
  43. package/templates/project/package.json +117 -0
  44. package/templates/project/playwright.config.ts +7 -0
  45. package/templates/project/postcss.config.js +6 -0
  46. package/templates/project/src/arduino-output-signals.ts +19 -0
  47. package/templates/project/src/assets/audio/.gitkeep +1 -0
  48. package/templates/project/src/assets/font/PretendardVariable.woff2 +0 -0
  49. package/templates/project/src/assets/image/.gitkeep +1 -0
  50. package/templates/project/src/assets/image/key-icon.png +0 -0
  51. package/templates/project/src/assets/video/.gitkeep +1 -0
  52. package/templates/project/src/assets/video/sample-30s.mp4 +0 -0
  53. package/templates/project/src/device-signal-handlers.test.ts +9 -0
  54. package/templates/project/src/device-signal-handlers.ts +14 -0
  55. package/templates/project/src/device-signal-targets.ts +3 -0
  56. package/templates/project/src/main/index.ts +17 -0
  57. package/templates/project/src/preload/index.ts +4 -0
  58. package/templates/project/src/project.config.ts +11 -0
  59. package/templates/project/src/renderer/index.html +16 -0
  60. package/templates/project/src/renderer/main.tsx +20 -0
  61. package/templates/project/src/renderer/vite-env.d.ts +1 -0
  62. package/templates/project/src/screen-definitions.ts +75 -0
  63. package/templates/project/src/screens/Screen001Black.test.tsx +21 -0
  64. package/templates/project/src/screens/Screen001Black.tsx +38 -0
  65. package/templates/project/src/screens/Screen002Video.test.tsx +18 -0
  66. package/templates/project/src/screens/Screen002Video.tsx +22 -0
  67. package/templates/project/src/screens/Screen003ExternalVideo.test.tsx +26 -0
  68. package/templates/project/src/screens/Screen003ExternalVideo.tsx +22 -0
  69. package/templates/project/src/store.test.ts +21 -0
  70. package/templates/project/src/store.ts +32 -0
  71. package/templates/project/src/styles.css +60 -0
  72. package/templates/project/tailwind.config.ts +69 -0
  73. package/templates/project/tsconfig.json +4 -0
  74. package/templates/project/tsconfig.node.json +32 -0
  75. package/templates/project/vitest.config.ts +20 -0
  76. package/templates/project/vitest.setup.ts +1 -0
  77. package/types/main/app-keyboard-shortcuts.d.ts +4 -0
  78. package/types/main/arduino-cli.d.ts +55 -0
  79. package/types/main/arduino-sketch-generator.d.ts +10 -0
  80. package/types/main/device-controller.d.ts +39 -0
  81. package/types/main/device-log-writer.d.ts +21 -0
  82. package/types/main/dtoa-dispatcher.d.ts +17 -0
  83. package/types/main/dtoa-handler.d.ts +9 -0
  84. package/types/main/game-session.d.ts +12 -0
  85. package/types/main/kiosk-quit.d.ts +5 -0
  86. package/types/main/media-manager.d.ts +17 -0
  87. package/types/main/runtime-paths.d.ts +10 -0
  88. package/types/main/serial-protocol.d.ts +29 -0
  89. package/types/main/start.d.ts +2 -0
  90. package/types/main/window-mode.d.ts +18 -0
  91. package/types/main/windows-key-lock.d.ts +3 -0
  92. package/types/preload/bridge.d.ts +4 -0
  93. package/types/renderer/src/App.d.ts +3 -0
  94. package/types/renderer/src/KeyScreenApp.d.ts +3 -0
  95. package/types/renderer/src/bridge.d.ts +3 -0
  96. package/types/renderer/src/components/DeviceLogOverlay.d.ts +7 -0
  97. package/types/renderer/src/components/ScreenRenderer.d.ts +7 -0
  98. package/types/renderer/src/components/SplashScreen.d.ts +7 -0
  99. package/types/renderer/src/components/VideoSceneScreen.d.ts +16 -0
  100. package/types/renderer/src/framework/AdminScreen.d.ts +3 -0
  101. package/types/renderer/src/hooks/index.d.ts +4 -0
  102. package/types/renderer/src/hooks/useArduinoBuild.d.ts +14 -0
  103. package/types/renderer/src/hooks/useAtodSignal.d.ts +12 -0
  104. package/types/renderer/src/index.d.ts +9 -0
  105. package/types/renderer/src/project-runtime.d.ts +10 -0
  106. package/types/renderer/src/screen-types.d.ts +24 -0
  107. package/types/renderer/src/store.d.ts +33 -0
  108. package/types/shared/arduino-board.d.ts +11 -0
  109. package/types/shared/arduino-keyboard-shortcut.d.ts +14 -0
  110. package/types/shared/index.d.ts +5 -0
  111. package/types/shared/screen-catalog.d.ts +19 -0
  112. package/types/shared/screen-shortcuts.d.ts +10 -0
  113. package/types/shared/types.d.ts +272 -0
@@ -0,0 +1,515 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process'
3
+ import { createWriteStream } from 'node:fs'
4
+ import { chmod, cp, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'
5
+ import { basename, dirname, join, resolve } from 'node:path'
6
+ import { spawn } from 'node:child_process'
7
+ import { Readable } from 'node:stream'
8
+ import { pipeline } from 'node:stream/promises'
9
+ import { isDirectExecution } from './screen-script-utils.mjs'
10
+
11
+ const ARDUINO_CLI_VERSION = process.env.ARDUINO_CLI_VERSION ?? '1.3.1'
12
+ const ARDUINO_AVR_VERSION = process.env.ARDUINO_AVR_VERSION ?? '1.8.8'
13
+ const RELEASE_API_URL = `https://api.github.com/repos/arduino/arduino-cli/releases/tags/v${ARDUINO_CLI_VERSION}`
14
+ const ARDUINO_PACKAGE_INDEX_URL = 'https://downloads.arduino.cc/packages/package_index.json'
15
+ const ARDUINO_LIBRARY_INDEX_URL = 'https://downloads.arduino.cc/libraries/library_index.json'
16
+ const BUILTIN_TOOL_NAMES = [
17
+ 'ctags',
18
+ 'dfu-discovery',
19
+ 'mdns-discovery',
20
+ 'serial-discovery',
21
+ 'serial-monitor'
22
+ ]
23
+ const projectRootInput = getOptionValue('--project-root')
24
+ const targetBundleId = getTargetBundleId()
25
+ const setupPaths = resolveArduinoSetupPaths({ projectRootInput, targetBundleId })
26
+ const { target } = setupPaths
27
+ const hostBundleId = getBundleId(process.platform, process.arch)
28
+ const { resourcesRoot, targetBinDir, dataDir, librariesDir, libraryTargetDir, setupTmpDir } =
29
+ setupPaths
30
+ const targetCliName = getCliExecutableName(target.platform)
31
+ const targetCliPath = join(targetBinDir, targetCliName)
32
+ const librarySourceDir = setupPaths.librarySourceDir
33
+ const dryRun = process.argv.includes('--dry-run')
34
+
35
+ export function resolveArduinoSetupPaths({
36
+ cwd = process.cwd(),
37
+ projectRootInput,
38
+ targetBundleId = getBundleId(process.platform, process.arch),
39
+ env = process.env
40
+ } = {}) {
41
+ const projectRoot = resolve(cwd, projectRootInput ?? '.')
42
+ const target = parseBundleId(targetBundleId)
43
+ const resourcesRoot = join(projectRoot, 'resources', 'arduino', targetBundleId)
44
+ const librariesDir = join(resourcesRoot, 'libraries')
45
+ const defaultLibrarySourceDir = resolve(
46
+ projectRoot,
47
+ '..',
48
+ 'arduino-lib',
49
+ 'libraries',
50
+ 'KeyescapeSerialProtocolBridge'
51
+ )
52
+
53
+ return {
54
+ projectRoot,
55
+ targetBundleId,
56
+ target,
57
+ resourcesRoot,
58
+ targetBinDir: join(resourcesRoot, 'bin'),
59
+ dataDir: join(resourcesRoot, 'data'),
60
+ librariesDir,
61
+ libraryTargetDir: join(librariesDir, 'KeyescapeSerialProtocolBridge'),
62
+ librarySourceDir: resolve(cwd, env.KEYESCAPE_ARDUINO_LIB_PATH ?? defaultLibrarySourceDir),
63
+ setupTmpDir: join(projectRoot, '.tmp', 'arduino-cli-setup')
64
+ }
65
+ }
66
+
67
+ function printHelp() {
68
+ console.log(`Usage: npm run setup:arduino-cli [-- --target <platform-arch>] [-- --project-root <path>] [-- --dry-run]
69
+
70
+ Downloads and prepares the offline Arduino bundle used by packaged apps.
71
+ By default it prepares the current host bundle. Use --target to prepare another bundle, e.g.
72
+ win32-x64 from macOS.
73
+
74
+ Environment:
75
+ ARDUINO_CLI_VERSION Arduino CLI release version. Default: ${ARDUINO_CLI_VERSION}
76
+ ARDUINO_AVR_VERSION Arduino AVR core version. Default: ${ARDUINO_AVR_VERSION}
77
+ ARDUINO_CLI_HOST_BIN Optional host-runnable arduino-cli path for core installation.
78
+ KEYESCAPE_ARDUINO_LIB_PATH Optional KeyescapeSerialProtocolBridge source directory.
79
+ `)
80
+ }
81
+
82
+ async function main() {
83
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
84
+ printHelp()
85
+ return
86
+ }
87
+
88
+ console.log(`Arduino CLI version: ${ARDUINO_CLI_VERSION}`)
89
+ console.log(`Host bundle: ${hostBundleId}`)
90
+ console.log(`Target bundle: ${targetBundleId}`)
91
+ console.log(`Bundle root: ${resourcesRoot}`)
92
+ console.log(`Library source: ${librarySourceDir}`)
93
+
94
+ if (dryRun) {
95
+ console.log('Dry run only. No files were downloaded or changed.')
96
+ return
97
+ }
98
+
99
+ await assertDirectory(librarySourceDir, 'KeyescapeSerialProtocolBridge source directory')
100
+ await rm(setupTmpDir, { recursive: true, force: true })
101
+ await mkdir(setupTmpDir, { recursive: true })
102
+ await mkdir(targetBinDir, { recursive: true })
103
+ await mkdir(dataDir, { recursive: true })
104
+
105
+ const release = await fetchRelease()
106
+ const cliAsset = findAsset(release, getCliAssetPattern(target.platform, target.arch))
107
+ const cliArchive = join(setupTmpDir, cliAsset.name)
108
+ await downloadAsset(cliAsset.browser_download_url, cliArchive)
109
+ await extractArchive(cliArchive, join(setupTmpDir, 'target-cli'))
110
+ const extractedCli = await findFile(join(setupTmpDir, 'target-cli'), targetCliName)
111
+ await cp(extractedCli, targetCliPath)
112
+ if (target.platform !== 'win32') {
113
+ await chmod(targetCliPath, 0o755)
114
+ }
115
+
116
+ if (targetBundleId === hostBundleId) {
117
+ const hostCliPath = process.env.ARDUINO_CLI_HOST_BIN
118
+ ? resolve(process.env.ARDUINO_CLI_HOST_BIN)
119
+ : targetCliPath
120
+ const userDir = join(setupTmpDir, 'arduino-cli-user')
121
+ await mkdir(userDir, { recursive: true })
122
+ await runArduinoCli(hostCliPath, ['core', 'update-index'], userDir)
123
+ await runArduinoCli(hostCliPath, ['core', 'install', `arduino:avr@${ARDUINO_AVR_VERSION}`], userDir)
124
+ await runArduinoCli(hostCliPath, ['lib', 'install', 'Keyboard'], userDir)
125
+ await copyInstalledLibrary(userDir, 'Keyboard')
126
+ } else {
127
+ await installCrossTargetBundle()
128
+ }
129
+
130
+ await rm(libraryTargetDir, { recursive: true, force: true })
131
+ await mkdir(dirname(libraryTargetDir), { recursive: true })
132
+ await cp(librarySourceDir, libraryTargetDir, {
133
+ recursive: true,
134
+ filter: (source) => !source.includes(`${basename(librarySourceDir)}/.git`)
135
+ })
136
+ await printSummary()
137
+ }
138
+
139
+ function getOptionValue(optionName) {
140
+ const inlinePrefix = `${optionName}=`
141
+ const inlineArgument = process.argv.find((argument) => argument.startsWith(inlinePrefix))
142
+ if (inlineArgument) {
143
+ const value = inlineArgument.slice(inlinePrefix.length)
144
+ if (!value) throw new Error(`${optionName} requires a value.`)
145
+ return value
146
+ }
147
+
148
+ const optionIndex = process.argv.indexOf(optionName)
149
+ const value = optionIndex >= 0 ? process.argv[optionIndex + 1] : undefined
150
+ if (optionIndex >= 0 && (!value || value.startsWith('--'))) {
151
+ throw new Error(`${optionName} requires a value.`)
152
+ }
153
+ return value
154
+ }
155
+
156
+ function getTargetBundleId() {
157
+ return getOptionValue('--target') ?? getBundleId(process.platform, process.arch)
158
+ }
159
+
160
+ function parseBundleId(value) {
161
+ const separatorIndex = value.indexOf('-')
162
+ if (separatorIndex < 0) {
163
+ throw new Error(`Invalid target bundle: ${value}`)
164
+ }
165
+
166
+ const platform = value.slice(0, separatorIndex)
167
+ const arch = value.slice(separatorIndex + 1)
168
+ if (getBundleId(platform, arch) !== value) {
169
+ throw new Error(`Unsupported target bundle: ${value}`)
170
+ }
171
+
172
+ return { platform, arch }
173
+ }
174
+
175
+ function getBundleId(platform, arch) {
176
+ if (platform === 'win32' && arch === 'x64') {
177
+ return 'win32-x64'
178
+ }
179
+ if (platform === 'darwin' && arch === 'arm64') {
180
+ return 'darwin-arm64'
181
+ }
182
+ if (platform === 'darwin' && arch === 'x64') {
183
+ return 'darwin-x64'
184
+ }
185
+ if (platform === 'linux' && arch === 'x64') {
186
+ return 'linux-x64'
187
+ }
188
+ if (platform === 'linux' && arch === 'arm64') {
189
+ return 'linux-arm64'
190
+ }
191
+ throw new Error(`Unsupported Arduino CLI host: ${platform}-${arch}`)
192
+ }
193
+
194
+ function getCliAssetPattern(platform, arch) {
195
+ if (platform === 'win32' && arch === 'x64') {
196
+ return /Windows_64bit\.zip$/
197
+ }
198
+ if (platform === 'darwin' && arch === 'arm64') {
199
+ return /macOS_ARM64\.tar\.gz$/
200
+ }
201
+ if (platform === 'darwin' && arch === 'x64') {
202
+ return /macOS_64bit\.tar\.gz$/
203
+ }
204
+ if (platform === 'linux' && arch === 'x64') {
205
+ return /Linux_64bit\.tar\.gz$/
206
+ }
207
+ if (platform === 'linux' && arch === 'arm64') {
208
+ return /Linux_ARM64\.tar\.gz$/
209
+ }
210
+ throw new Error(`Unsupported Arduino CLI asset host: ${platform}-${arch}`)
211
+ }
212
+
213
+ function getCliExecutableName(platform) {
214
+ return platform === 'win32' ? 'arduino-cli.exe' : 'arduino-cli'
215
+ }
216
+
217
+ function getArduinoSystemName(bundle) {
218
+ if (bundle.platform === 'win32' && bundle.arch === 'x64') {
219
+ return 'i686-mingw32'
220
+ }
221
+ if (bundle.platform === 'darwin' && bundle.arch === 'arm64') {
222
+ return 'arm64-apple-darwin'
223
+ }
224
+ if (bundle.platform === 'darwin' && bundle.arch === 'x64') {
225
+ return 'x86_64-apple-darwin'
226
+ }
227
+ if (bundle.platform === 'linux' && bundle.arch === 'x64') {
228
+ return 'x86_64-linux-gnu'
229
+ }
230
+ if (bundle.platform === 'linux' && bundle.arch === 'arm64') {
231
+ return 'aarch64-linux-gnu'
232
+ }
233
+ throw new Error(`Unsupported Arduino package system: ${bundle.platform}-${bundle.arch}`)
234
+ }
235
+
236
+ async function fetchRelease() {
237
+ const response = await fetch(RELEASE_API_URL, {
238
+ headers: {
239
+ Accept: 'application/vnd.github+json',
240
+ 'User-Agent': 'key-screen-framework-arduino-setup'
241
+ }
242
+ })
243
+
244
+ if (!response.ok) {
245
+ throw new Error(`Failed to fetch Arduino CLI release metadata: ${response.status} ${response.statusText}`)
246
+ }
247
+
248
+ return response.json()
249
+ }
250
+
251
+ async function fetchJson(url, outputPath) {
252
+ const response = await fetch(url, {
253
+ headers: {
254
+ 'User-Agent': 'key-screen-framework-arduino-setup'
255
+ }
256
+ })
257
+
258
+ if (!response.ok) {
259
+ throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`)
260
+ }
261
+
262
+ const json = await response.json()
263
+ await mkdir(dirname(outputPath), { recursive: true })
264
+ await writeFile(outputPath, `${JSON.stringify(json)}\n`, 'utf-8')
265
+ return json
266
+ }
267
+
268
+ async function installCrossTargetBundle() {
269
+ const systemName = getArduinoSystemName(target)
270
+ console.log(`Preparing cross-target AVR core for ${systemName}`)
271
+
272
+ const packageIndex = await fetchJson(ARDUINO_PACKAGE_INDEX_URL, join(dataDir, 'package_index.json'))
273
+ const arduinoPackage = packageIndex.packages?.find((item) => item.name === 'arduino')
274
+ const avrPlatform = arduinoPackage?.platforms?.find(
275
+ (platform) => platform.architecture === 'avr' && platform.version === ARDUINO_AVR_VERSION
276
+ )
277
+ if (!arduinoPackage || !avrPlatform) {
278
+ throw new Error(`Could not find arduino:avr@${ARDUINO_AVR_VERSION} in package index.`)
279
+ }
280
+
281
+ await downloadAndExtractFlattened(
282
+ avrPlatform.url,
283
+ join(setupTmpDir, 'packages', basename(avrPlatform.url)),
284
+ join(dataDir, 'packages', 'arduino', 'hardware', 'avr', avrPlatform.version)
285
+ )
286
+
287
+ for (const dependency of avrPlatform.toolsDependencies ?? []) {
288
+ const tool = arduinoPackage.tools?.find(
289
+ (candidate) => candidate.name === dependency.name && candidate.version === dependency.version
290
+ )
291
+ const toolRelease = tool?.systems?.find(
292
+ (system) => tool.version === dependency.version && system.host === systemName
293
+ )
294
+ if (!toolRelease) {
295
+ throw new Error(`Could not find ${dependency.name}@${dependency.version} for ${systemName}.`)
296
+ }
297
+
298
+ await downloadAndExtractFlattened(
299
+ toolRelease.url,
300
+ join(setupTmpDir, 'packages', basename(toolRelease.url)),
301
+ join(dataDir, 'packages', dependency.packager, 'tools', dependency.name, dependency.version)
302
+ )
303
+ }
304
+
305
+ const builtinPackage = packageIndex.packages?.find((item) => item.name === 'builtin')
306
+ if (!builtinPackage) {
307
+ throw new Error('Could not find builtin tools package in package index.')
308
+ }
309
+
310
+ for (const toolName of BUILTIN_TOOL_NAMES) {
311
+ const tool = findLatestTool(builtinPackage, toolName, systemName)
312
+ const toolRelease = tool.systems.find((system) => system.host === systemName)
313
+ await downloadAndExtractFlattened(
314
+ toolRelease.url,
315
+ join(setupTmpDir, 'packages', basename(toolRelease.url)),
316
+ join(dataDir, 'packages', 'builtin', 'tools', tool.name, tool.version)
317
+ )
318
+ }
319
+
320
+ const libraryIndex = await fetchJson(ARDUINO_LIBRARY_INDEX_URL, join(dataDir, 'library_index.json'))
321
+ const keyboardLibrary = findLatestLibrary(libraryIndex, 'Keyboard')
322
+ await downloadAndExtractFlattened(
323
+ keyboardLibrary.url,
324
+ join(setupTmpDir, 'libraries', basename(keyboardLibrary.url)),
325
+ join(librariesDir, 'Keyboard')
326
+ )
327
+ }
328
+
329
+ function findLatestTool(arduinoPackage, toolName, systemName) {
330
+ const tools = arduinoPackage.tools?.filter(
331
+ (tool) => tool.name === toolName && tool.systems?.some((system) => system.host === systemName)
332
+ ) ?? []
333
+ const latest = tools.sort((left, right) => compareSemver(right.version, left.version))[0]
334
+ if (!latest) {
335
+ throw new Error(`Could not find ${toolName} for ${systemName}.`)
336
+ }
337
+ return latest
338
+ }
339
+
340
+ function findLatestLibrary(libraryIndex, libraryName) {
341
+ const libraries = libraryIndex.libraries?.filter((library) => library.name === libraryName) ?? []
342
+ const latest = libraries.sort((left, right) => compareSemver(right.version, left.version))[0]
343
+ if (!latest?.url) {
344
+ throw new Error(`Could not find ${libraryName} in library index.`)
345
+ }
346
+ return latest
347
+ }
348
+
349
+ function compareSemver(left, right) {
350
+ const leftParts = left.split('.').map((part) => Number.parseInt(part, 10) || 0)
351
+ const rightParts = right.split('.').map((part) => Number.parseInt(part, 10) || 0)
352
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
353
+ const delta = (leftParts[index] ?? 0) - (rightParts[index] ?? 0)
354
+ if (delta !== 0) return delta
355
+ }
356
+ return 0
357
+ }
358
+
359
+ function findAsset(release, pattern) {
360
+ const asset = release.assets?.find((candidate) => pattern.test(candidate.name))
361
+ if (!asset) {
362
+ throw new Error(`Could not find Arduino CLI release asset matching ${pattern}.`)
363
+ }
364
+ return asset
365
+ }
366
+
367
+ async function downloadAsset(url, outputPath) {
368
+ console.log(`Downloading ${url}`)
369
+ const response = await fetch(url, {
370
+ headers: {
371
+ 'User-Agent': 'key-screen-framework-arduino-setup'
372
+ }
373
+ })
374
+
375
+ if (!response.ok || !response.body) {
376
+ throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`)
377
+ }
378
+
379
+ await mkdir(dirname(outputPath), { recursive: true })
380
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(outputPath))
381
+ }
382
+
383
+ async function extractArchive(archivePath, outputDir) {
384
+ await mkdir(outputDir, { recursive: true })
385
+ await spawnPromise('tar', ['-xf', archivePath, '-C', outputDir])
386
+ }
387
+
388
+ async function downloadAndExtractFlattened(url, archivePath, outputDir) {
389
+ await downloadAsset(url, archivePath)
390
+ await rm(outputDir, { recursive: true, force: true })
391
+ await mkdir(outputDir, { recursive: true })
392
+
393
+ const extractDir = `${outputDir}.extract`
394
+ await rm(extractDir, { recursive: true, force: true })
395
+ await mkdir(extractDir, { recursive: true })
396
+ await extractArchive(archivePath, extractDir)
397
+
398
+ const root = await findArchiveContentRoot(extractDir)
399
+ await cp(root, outputDir, { recursive: true })
400
+ await rm(extractDir, { recursive: true, force: true })
401
+ }
402
+
403
+ async function findArchiveContentRoot(extractDir) {
404
+ const entries = await readdir(extractDir, { withFileTypes: true })
405
+ const visibleEntries = entries.filter((entry) => !entry.name.startsWith('__MACOSX'))
406
+ if (visibleEntries.length === 1 && visibleEntries[0].isDirectory()) {
407
+ return join(extractDir, visibleEntries[0].name)
408
+ }
409
+ return extractDir
410
+ }
411
+
412
+ async function runArduinoCli(cliPath, args, userDir) {
413
+ console.log(`Running ${cliPath} ${args.join(' ')}`)
414
+ await spawnPromise(cliPath, args, {
415
+ env: {
416
+ ...process.env,
417
+ ARDUINO_DIRECTORIES_DATA: dataDir,
418
+ ARDUINO_DIRECTORIES_USER: userDir
419
+ }
420
+ })
421
+ }
422
+
423
+ async function copyInstalledLibrary(userDir, libraryName) {
424
+ const sourceDir = join(userDir, 'libraries', libraryName)
425
+ const targetDir = join(librariesDir, libraryName)
426
+ await assertDirectory(sourceDir, `${libraryName} Arduino library`)
427
+ await rm(targetDir, { recursive: true, force: true })
428
+ await mkdir(librariesDir, { recursive: true })
429
+ await cp(sourceDir, targetDir, { recursive: true })
430
+ }
431
+
432
+ async function spawnPromise(command, args, options = {}) {
433
+ await new Promise((resolvePromise, rejectPromise) => {
434
+ const child = spawn(command, args, {
435
+ stdio: 'inherit',
436
+ ...options
437
+ })
438
+ child.on('error', rejectPromise)
439
+ child.on('close', (exitCode) => {
440
+ if (exitCode) {
441
+ rejectPromise(new Error(`${command} exited with code ${exitCode}.`))
442
+ return
443
+ }
444
+ resolvePromise()
445
+ })
446
+ })
447
+ }
448
+
449
+ async function findFile(root, fileName) {
450
+ const entries = await readdir(root, { withFileTypes: true })
451
+ for (const entry of entries) {
452
+ const entryPath = join(root, entry.name)
453
+ if (entry.isFile() && entry.name === fileName) {
454
+ return entryPath
455
+ }
456
+ if (entry.isDirectory()) {
457
+ try {
458
+ return await findFile(entryPath, fileName)
459
+ } catch (error) {
460
+ if (!(error instanceof Error && error.message.startsWith('Could not find'))) {
461
+ throw error
462
+ }
463
+ }
464
+ }
465
+ }
466
+
467
+ throw new Error(`Could not find ${fileName} under ${root}.`)
468
+ }
469
+
470
+ async function assertDirectory(path, label) {
471
+ const info = await stat(path).catch(() => undefined)
472
+ if (!info?.isDirectory()) {
473
+ throw new Error(`${label} does not exist: ${path}`)
474
+ }
475
+ }
476
+
477
+ async function printSummary() {
478
+ const [fileCount, totalBytes] = await summarizeDirectory(resourcesRoot)
479
+ console.log(`Arduino bundle prepared: ${fileCount} files, ${formatBytes(totalBytes)}`)
480
+ }
481
+
482
+ async function summarizeDirectory(root) {
483
+ let fileCount = 0
484
+ let totalBytes = 0
485
+ const entries = await readdir(root, { withFileTypes: true })
486
+
487
+ for (const entry of entries) {
488
+ const entryPath = join(root, entry.name)
489
+ if (entry.isDirectory()) {
490
+ const [nestedCount, nestedBytes] = await summarizeDirectory(entryPath)
491
+ fileCount += nestedCount
492
+ totalBytes += nestedBytes
493
+ } else if (entry.isFile()) {
494
+ const info = await stat(entryPath)
495
+ fileCount += 1
496
+ totalBytes += info.size
497
+ }
498
+ }
499
+
500
+ return [fileCount, totalBytes]
501
+ }
502
+
503
+ function formatBytes(bytes) {
504
+ if (bytes < 1024 * 1024) {
505
+ return `${Math.round(bytes / 1024)} KiB`
506
+ }
507
+ return `${Math.round(bytes / 1024 / 1024)} MiB`
508
+ }
509
+
510
+ if (isDirectExecution(import.meta.url, process.argv[1])) {
511
+ main().catch((error) => {
512
+ console.error(error instanceof Error ? error.message : error)
513
+ process.exitCode = 1
514
+ })
515
+ }
@@ -0,0 +1,89 @@
1
+ import ts from 'typescript'
2
+
3
+ function scriptKindForPath(path) {
4
+ if (/\.tsx$/i.test(path)) return ts.ScriptKind.TSX
5
+ if (/\.[cm]?ts$/i.test(path)) return ts.ScriptKind.TS
6
+ if (/\.jsx$/i.test(path)) return ts.ScriptKind.JSX
7
+ return ts.ScriptKind.JS
8
+ }
9
+
10
+ export function collectModuleSpecifiers(source, path) {
11
+ const sourceFile = ts.createSourceFile(
12
+ path,
13
+ source,
14
+ ts.ScriptTarget.Latest,
15
+ true,
16
+ scriptKindForPath(path)
17
+ )
18
+ const specifiers = []
19
+
20
+ function visit(node) {
21
+ let specifier
22
+ let kind = 'import'
23
+ if (
24
+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
25
+ node.moduleSpecifier &&
26
+ ts.isStringLiteralLike(node.moduleSpecifier)
27
+ ) {
28
+ specifier = node.moduleSpecifier
29
+ if (ts.isImportDeclaration(node)) {
30
+ const clause = node.importClause
31
+ const onlyTypeSpecifiers =
32
+ !clause?.name &&
33
+ clause?.namedBindings &&
34
+ ts.isNamedImports(clause.namedBindings) &&
35
+ clause.namedBindings.elements.length > 0 &&
36
+ clause.namedBindings.elements.every((element) => element.isTypeOnly)
37
+ if (clause?.isTypeOnly || onlyTypeSpecifiers) kind = 'type'
38
+ } else {
39
+ const onlyTypeSpecifiers =
40
+ node.exportClause &&
41
+ ts.isNamedExports(node.exportClause) &&
42
+ node.exportClause.elements.length > 0 &&
43
+ node.exportClause.elements.every((element) => element.isTypeOnly)
44
+ if (node.isTypeOnly || onlyTypeSpecifiers) kind = 'type'
45
+ }
46
+ } else if (
47
+ ts.isImportEqualsDeclaration(node) &&
48
+ ts.isExternalModuleReference(node.moduleReference) &&
49
+ node.moduleReference.expression &&
50
+ ts.isStringLiteralLike(node.moduleReference.expression)
51
+ ) {
52
+ specifier = node.moduleReference.expression
53
+ kind = node.isTypeOnly ? 'type' : 'require'
54
+ } else if (
55
+ ts.isImportTypeNode(node) &&
56
+ ts.isLiteralTypeNode(node.argument) &&
57
+ ts.isStringLiteralLike(node.argument.literal)
58
+ ) {
59
+ specifier = node.argument.literal
60
+ kind = 'type'
61
+ } else if (
62
+ ts.isCallExpression(node) &&
63
+ node.arguments.length >= 1 &&
64
+ ts.isStringLiteralLike(node.arguments[0]) &&
65
+ ts.isPropertyAccessExpression(node.expression) &&
66
+ ts.isIdentifier(node.expression.expression) &&
67
+ ['vi', 'jest'].includes(node.expression.expression.text) &&
68
+ ['mock', 'doMock'].includes(node.expression.name.text)
69
+ ) {
70
+ specifier = node.arguments[0]
71
+ kind = 'mock'
72
+ } else if (
73
+ ts.isCallExpression(node) &&
74
+ node.arguments.length >= 1 &&
75
+ ts.isStringLiteralLike(node.arguments[0]) &&
76
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
77
+ (ts.isIdentifier(node.expression) && node.expression.text === 'require'))
78
+ ) {
79
+ specifier = node.arguments[0]
80
+ if (ts.isIdentifier(node.expression) && node.expression.text === 'require') kind = 'require'
81
+ }
82
+
83
+ if (specifier) specifiers.push({ node: specifier, value: specifier.text, sourceFile, kind })
84
+ ts.forEachChild(node, visit)
85
+ }
86
+
87
+ visit(sourceFile)
88
+ return specifiers
89
+ }
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process'
3
+ import { mkdir, writeFile } from 'node:fs/promises'
4
+ import { dirname } from 'node:path'
5
+ import { resolveScreenGenerationContract, SCREEN_GENERATION_OPTION_KEYS } from './screen-generation-contract.mjs'
6
+ import { renderGeneratedDefinitions, renderGeneratedRegistry } from './screen-generation-renderers.mjs'
7
+ import { loadSceneScreenModules } from './screen-module-utils.mjs'
8
+ import { assertKnownArgs, isDirectExecution, parseArgs } from './screen-script-utils.mjs'
9
+
10
+ export async function syncScreens(args, { cwd = process.cwd() } = {}) {
11
+ assertKnownArgs(args, SCREEN_GENERATION_OPTION_KEYS)
12
+ const contract = resolveScreenGenerationContract(args, { cwd })
13
+ const modules = await loadSceneScreenModules(contract.screenDirectory)
14
+ const seenIds = new Set()
15
+
16
+ for (const module of modules) {
17
+ if (seenIds.has(module.screen.id)) {
18
+ throw new Error(`Duplicate screen id: ${module.screen.id}`)
19
+ }
20
+
21
+ seenIds.add(module.screen.id)
22
+ }
23
+
24
+ await mkdir(dirname(contract.generatedDefinitionsPath), { recursive: true })
25
+ await Promise.all([
26
+ writeFile(
27
+ contract.generatedDefinitionsPath,
28
+ renderGeneratedDefinitions(modules, contract.importPaths)
29
+ ),
30
+ writeFile(contract.generatedRegistryPath, renderGeneratedRegistry(modules, contract.importPaths))
31
+ ])
32
+
33
+ return { contract, screenCount: modules.length }
34
+ }
35
+
36
+ async function main() {
37
+ const result = await syncScreens(parseArgs(process.argv.slice(2)))
38
+ process.stdout.write(
39
+ `Synced ${result.screenCount} scene screen module(s) to ${result.contract.outputDirectory}.\n`
40
+ )
41
+ }
42
+
43
+ if (isDirectExecution(import.meta.url, process.argv[1])) {
44
+ main().catch((error) => {
45
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
46
+ process.exitCode = 1
47
+ })
48
+ }