@defold-typescript/cli 0.5.2 → 0.5.4

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
@@ -4,11 +4,16 @@ The end-user CLI for scaffolding and building [Defold](https://defold.com/)
4
4
  projects written in TypeScript, transpiled to Lua.
5
5
 
6
6
  ```sh
7
- bunx @defold-typescript/cli init # add TypeScript to a Defold project, or scaffold a new one
8
- bunx @defold-typescript/cli build # transpile src/ to Lua alongside your Defold sources
9
- bunx @defold-typescript/cli watch # rebuild on change
7
+ bunx @defold-typescript/cli@latest init # add TypeScript to a Defold project, or scaffold a new one
8
+ bun install # install the scaffolded devDependencies (types, biome)
9
+ bunx @defold-typescript/cli build # transpile src/ to Lua alongside your Defold sources
10
+ bunx @defold-typescript/cli watch # rebuild on change
10
11
  ```
11
12
 
13
+ Scaffold with the `@latest` tag — `init` writes your `@defold-typescript/types`
14
+ version pin, so a stale `bunx` cache would pin an older release. Run `bun install`
15
+ once after `init` to put the scaffolded dev dependencies on disk.
16
+
12
17
  The package name is scoped (`@defold-typescript/cli`); `bunx defold-typescript`
13
18
  without the scope resolves a different, nonexistent package. Install it to get
14
19
  the shorter `defold-typescript` binary on your `PATH` and pin the version:
package/dist/bin.js CHANGED
@@ -231,6 +231,169 @@ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, readFi
231
231
  import * as path6 from "node:path";
232
232
  import { fileURLToPath as fileURLToPath2 } from "node:url";
233
233
 
234
+ // src/debug-launcher.ts
235
+ var PLATFORM_TARGETS = {
236
+ darwin: { enginePlatform: "x86_64-darwin", buildFolder: "x86_64-osx", executable: "dmengine" },
237
+ linux: { enginePlatform: "x86_64-linux", buildFolder: "x86_64-linux", executable: "dmengine" },
238
+ win32: {
239
+ enginePlatform: "x86_64-win32",
240
+ buildFolder: "x86_64-win32",
241
+ executable: "dmengine.exe"
242
+ }
243
+ };
244
+ var ENGINE_INFO_URL = "https://d.defold.com/stable/info.json";
245
+ var ENGINE_ARCHIVE_BASE = "https://d.defold.com/archive/stable";
246
+ var DEBUG_LAUNCHER_REL = ".vscode/defold-debug.ts";
247
+ function debugLaunchConfig() {
248
+ return {
249
+ name: "Defold: Debug (TypeScript)",
250
+ type: "lua-local",
251
+ request: "launch",
252
+ stopOnEntry: false,
253
+ verbose: false,
254
+ internalConsoleOptions: "openOnSessionStart",
255
+ program: { command: "bun" },
256
+ args: [DEBUG_LAUNCHER_REL]
257
+ };
258
+ }
259
+ var VSCODE_LAUNCH_CONTENT = {
260
+ version: "0.2.0",
261
+ configurations: [debugLaunchConfig()]
262
+ };
263
+ function renderDebugLauncher() {
264
+ const targets = JSON.stringify(PLATFORM_TARGETS, null, 2);
265
+ return `import { chmodSync, copyFileSync, existsSync, mkdirSync } from "node:fs";
266
+ import * as path from "node:path";
267
+
268
+ // Windows only: paths to OpenAL32.dll and wrap_oal.dll from your Defold SDK
269
+ // (defoldsdk/ext/lib/x86_64-win32/). Leave empty on macOS/Linux.
270
+ const WINDOWS_OPENAL32_PATH = "";
271
+ const WINDOWS_WRAPOAL_PATH = "";
272
+
273
+ interface EngineTarget {
274
+ enginePlatform: string;
275
+ buildFolder: string;
276
+ executable: string;
277
+ }
278
+
279
+ const PLATFORM_TARGETS: Record<string, EngineTarget> = ${targets};
280
+
281
+ const ENGINE_INFO_URL = "${ENGINE_INFO_URL}";
282
+ const ENGINE_ARCHIVE_BASE = "${ENGINE_ARCHIVE_BASE}";
283
+
284
+ const target = PLATFORM_TARGETS[process.platform];
285
+ if (!target) {
286
+ console.error(\`Unsupported platform: \${process.platform}\`);
287
+ process.exit(1);
288
+ }
289
+
290
+ const here = path.dirname(new URL(import.meta.url).pathname);
291
+ const stockEnginePath = path.join(here, target.executable);
292
+
293
+ if (!existsSync(stockEnginePath)) {
294
+ const info = (await (await fetch(ENGINE_INFO_URL)).json()) as { sha1: string };
295
+ const url = \`\${ENGINE_ARCHIVE_BASE}/\${info.sha1}/engine/\${target.enginePlatform}/\${target.executable}\`;
296
+ console.log(\`Fetching \${url}\`);
297
+ const res = await fetch(url);
298
+ if (!res.ok) {
299
+ console.error(\`Engine download failed: \${res.status} \${res.statusText}\`);
300
+ process.exit(1);
301
+ }
302
+ await Bun.write(stockEnginePath, res);
303
+ }
304
+
305
+ const buildFolder = path.join("build", target.buildFolder);
306
+ const buildEnginePath = path.join(buildFolder, target.executable);
307
+ let enginePath = existsSync(buildEnginePath) ? buildEnginePath : stockEnginePath;
308
+
309
+ if (process.platform === "win32" && enginePath === buildEnginePath) {
310
+ for (const [src, name] of [
311
+ [WINDOWS_OPENAL32_PATH, "OpenAL32.dll"],
312
+ [WINDOWS_WRAPOAL_PATH, "wrap_oal.dll"],
313
+ ] as const) {
314
+ const dest = path.join(buildFolder, name);
315
+ if (src && !existsSync(dest)) {
316
+ copyFileSync(src, dest);
317
+ }
318
+ }
319
+ }
320
+
321
+ // macOS: a build engine launched in place attaches to the editor process; copy
322
+ // it aside first so it runs standalone.
323
+ if (process.platform === "darwin" && enginePath === buildEnginePath) {
324
+ const tempEngine = path.join(buildFolder, "temp", target.executable);
325
+ mkdirSync(path.dirname(tempEngine), { recursive: true });
326
+ copyFileSync(buildEnginePath, tempEngine);
327
+ enginePath = tempEngine;
328
+ }
329
+
330
+ if (process.platform !== "win32") {
331
+ chmodSync(enginePath, 0o755);
332
+ }
333
+
334
+ const projectc = path.join("build", "default", "game.projectc");
335
+ console.log(\`Launching \${enginePath} \${projectc}\`);
336
+ const proc = Bun.spawn([enginePath, projectc], {
337
+ stdio: ["inherit", "inherit", "inherit"],
338
+ });
339
+ process.exit(await proc.exited);
340
+ `;
341
+ }
342
+ var DEBUG_LAUNCHER_SOURCE = renderDebugLauncher();
343
+
344
+ // src/mise-scaffold.ts
345
+ var MANAGED_MARKER = "# managed by @defold-typescript";
346
+ var MISE_TASKS_TOML = `${MANAGED_MARKER}
347
+ [tasks."defold-typescript:build"]
348
+ description = "Build the TypeScript sources with the installed defold-typescript CLI"
349
+ run = "bunx --no-install defold-typescript build"
350
+
351
+ ${MANAGED_MARKER}
352
+ [tasks."defold-typescript:watch"]
353
+ description = "Watch and rebuild the TypeScript sources with the installed defold-typescript CLI"
354
+ run = "bunx --no-install defold-typescript watch"
355
+
356
+ ${MANAGED_MARKER}
357
+ [tasks."defold-typescript:upgrade"]
358
+ description = "Upgrade the defold-typescript CLI to its latest release and re-pin the types dependency"
359
+ run = ["bunx @defold-typescript/cli@latest init --force", "bun install"]
360
+ `;
361
+ function stripManagedBlocks(text) {
362
+ const lines = text.split(`
363
+ `);
364
+ const out = [];
365
+ let i = 0;
366
+ while (i < lines.length) {
367
+ const line = lines[i] ?? "";
368
+ if (line.trim() === MANAGED_MARKER) {
369
+ i += 1;
370
+ while (i < lines.length && (lines[i] ?? "").trim() !== "") {
371
+ i += 1;
372
+ }
373
+ if (i < lines.length) {
374
+ i += 1;
375
+ }
376
+ continue;
377
+ }
378
+ out.push(line);
379
+ i += 1;
380
+ }
381
+ return out.join(`
382
+ `);
383
+ }
384
+ function mergeMiseToml(existing) {
385
+ if (existing === undefined) {
386
+ return MISE_TASKS_TOML;
387
+ }
388
+ const userContent = stripManagedBlocks(existing).replace(/\s*$/, "");
389
+ if (userContent === "") {
390
+ return MISE_TASKS_TOML;
391
+ }
392
+ return `${userContent}
393
+
394
+ ${MISE_TASKS_TOML}`;
395
+ }
396
+
234
397
  // src/script-kind.ts
235
398
  var DEFAULT_TYPES_ENTRYPOINT = "@defold-typescript/types";
236
399
  var KIND_BY_EXT = {
@@ -342,43 +505,64 @@ var BIOME_JSON_CONTENT = {
342
505
  }
343
506
  };
344
507
  var VSCODE_EXTENSIONS_CONTENT = {
345
- recommendations: ["sumneko.lua", "astronachos.defold"],
508
+ recommendations: ["sumneko.lua", "astronachos.defold", "tomblind.local-lua-debugger-vscode"],
346
509
  unwantedRecommendations: ["johnnymorganz.luau-lsp"]
347
510
  };
348
511
  var VSCODE_SETTINGS_CONTENT = {
349
512
  "Lua.workspace.ignoreDir": ["src"]
350
513
  };
514
+ var HOOK_COMMENTS = {
515
+ init: "Initialize the component and return its state.",
516
+ update: "Update the component every frame; `dt` is the time step.",
517
+ fixed_update: "Update at the fixed physics time step.",
518
+ late_update: "Update every frame after `update`.",
519
+ on_message: "Handle an incoming message.",
520
+ on_input: "Handle input once input focus is acquired.",
521
+ final: "Clean up when the component is deleted.",
522
+ on_reload: "React to a hot reload of this script."
523
+ };
524
+ var HOOK_SIGNATURES = {
525
+ init: "",
526
+ update: "self, dt",
527
+ fixed_update: "self, dt",
528
+ late_update: "self, dt",
529
+ on_message: "self, message_id, message, sender",
530
+ on_input: "self, action_id, action",
531
+ final: "self",
532
+ on_reload: "self"
533
+ };
534
+ var SNIPPET_HOOK_ORDER = Object.keys(HOOK_SIGNATURES);
535
+ function hookLines(includeOnInput, startTabStop) {
536
+ const lines = [];
537
+ let tabStop = startTabStop;
538
+ for (const hook of SNIPPET_HOOK_ORDER) {
539
+ if (hook === "init") {
540
+ continue;
541
+ }
542
+ if (hook === "on_input" && !includeOnInput) {
543
+ continue;
544
+ }
545
+ lines.push(` // ${HOOK_COMMENTS[hook]}`);
546
+ lines.push(` ${hook}(${HOOK_SIGNATURES[hook]}) {$${tabStop}},`);
547
+ tabStop += 1;
548
+ }
549
+ return lines;
550
+ }
351
551
  function inlineSnippetBody(factory, includeOnInput) {
352
- const lines = [
552
+ return [
353
553
  `import { ${factory} } from "@defold-typescript/types";`,
354
554
  "",
355
555
  `export const script = ${factory}({`,
356
- " // Initialize the component and return its state.",
556
+ ` // ${HOOK_COMMENTS.init}`,
357
557
  " init() {",
358
558
  " return { $0 };",
359
559
  " },",
360
- " // Update the component every frame; `dt` is the time step.",
361
- " update(self, dt) {$1},",
362
- " // Update at the fixed physics time step.",
363
- " fixed_update(self, dt) {$2},",
364
- " // Update every frame after `update`.",
365
- " late_update(self, dt) {$3},",
366
- " // Handle an incoming message.",
367
- " on_message(self, message_id, message, sender) {$4},"
560
+ ...hookLines(includeOnInput, 1),
561
+ "});"
368
562
  ];
369
- if (includeOnInput) {
370
- lines.push(" // Handle input once input focus is acquired.");
371
- lines.push(" on_input(self, action_id, action) {$5},");
372
- }
373
- lines.push(" // Clean up when the component is deleted.");
374
- lines.push(" final(self) {$6},");
375
- lines.push(" // React to a hot reload of this script.");
376
- lines.push(" on_reload(self) {$7},");
377
- lines.push("});");
378
- return lines;
379
563
  }
380
564
  function typedSnippetBody(factory, includeOnInput) {
381
- const lines = [
565
+ return [
382
566
  `import { ${factory} } from "@defold-typescript/types";`,
383
567
  "",
384
568
  "type Self = {",
@@ -387,29 +571,13 @@ function typedSnippetBody(factory, includeOnInput) {
387
571
  "};",
388
572
  "",
389
573
  `export const script = ${factory}<Self>({`,
390
- " // Initialize the component and return its state.",
574
+ ` // ${HOOK_COMMENTS.init}`,
391
575
  " init(): Self {",
392
576
  " return { $0 };",
393
577
  " },",
394
- " // Update the component every frame; `dt` is the time step.",
395
- " update(self, dt) {$2},",
396
- " // Update at the fixed physics time step.",
397
- " fixed_update(self, dt) {$3},",
398
- " // Update every frame after `update`.",
399
- " late_update(self, dt) {$4},",
400
- " // Handle an incoming message.",
401
- " on_message(self, message_id, message, sender) {$5},"
578
+ ...hookLines(includeOnInput, 2),
579
+ "});"
402
580
  ];
403
- if (includeOnInput) {
404
- lines.push(" // Handle input once input focus is acquired.");
405
- lines.push(" on_input(self, action_id, action) {$6},");
406
- }
407
- lines.push(" // Clean up when the component is deleted.");
408
- lines.push(" final(self) {$7},");
409
- lines.push(" // React to a hot reload of this script.");
410
- lines.push(" on_reload(self) {$8},");
411
- lines.push("});");
412
- return lines;
413
581
  }
414
582
  var VSCODE_SNIPPETS_CONTENT = {
415
583
  "Defold script (inferred self)": {
@@ -480,12 +648,15 @@ function typesVersionSpec() {
480
648
  }
481
649
  var SCAFFOLD_DEV_DEPS = {
482
650
  "@defold-typescript/types": typesVersionSpec(),
651
+ "@defold-typescript/cli": typesVersionSpec(),
483
652
  "@biomejs/biome": "^2.2.0"
484
653
  };
485
654
  function repairManagedDevDeps(devDeps, force = false) {
486
655
  delete devDeps["@defold-typescript/transpiler"];
487
- if (force || devDeps["@defold-typescript/types"]?.startsWith("workspace:")) {
488
- devDeps["@defold-typescript/types"] = typesVersionSpec();
656
+ for (const name of ["@defold-typescript/types", "@defold-typescript/cli"]) {
657
+ if (force || devDeps[name]?.startsWith("workspace:")) {
658
+ devDeps[name] = typesVersionSpec();
659
+ }
489
660
  }
490
661
  }
491
662
  function writeJson(filePath, value) {
@@ -522,6 +693,12 @@ function writeBiome(cwd, written) {
522
693
  writeJson(biomePath, BIOME_JSON_CONTENT);
523
694
  written.push("biome.json");
524
695
  }
696
+ function writeMiseTasks(cwd, written) {
697
+ const misePath = path6.join(cwd, "mise.toml");
698
+ const existing = existsSync2(misePath) ? readFileSync5(misePath, "utf8") : undefined;
699
+ writeFileSync2(misePath, mergeMiseToml(existing));
700
+ written.push("mise.toml");
701
+ }
525
702
  function parseJsonc(text) {
526
703
  let out = "";
527
704
  let inString = false;
@@ -643,6 +820,39 @@ function writeVscodeSnippets(cwd, written) {
643
820
  writeJson(filePath, VSCODE_SNIPPETS_CONTENT);
644
821
  written.push(".vscode/defold-typescript.code-snippets");
645
822
  }
823
+ function writeVscodeLaunch(cwd, written) {
824
+ const dir = path6.join(cwd, ".vscode");
825
+ const filePath = path6.join(dir, "launch.json");
826
+ const ours = debugLaunchConfig();
827
+ if (existsSync2(filePath)) {
828
+ const existing = readVscodeJson(filePath);
829
+ if (existing === null) {
830
+ return;
831
+ }
832
+ const configs = Array.isArray(existing.configurations) ? [...existing.configurations] : [];
833
+ const names = new Set(configs.map((c) => isJsonObject(c) ? c.name : undefined));
834
+ if (!names.has(ours.name)) {
835
+ configs.push(ours);
836
+ }
837
+ existing.configurations = configs;
838
+ existing.version ??= VSCODE_LAUNCH_CONTENT.version;
839
+ writeJson(filePath, existing);
840
+ return;
841
+ }
842
+ mkdirSync2(dir, { recursive: true });
843
+ writeJson(filePath, VSCODE_LAUNCH_CONTENT);
844
+ written.push(".vscode/launch.json");
845
+ }
846
+ function writeVscodeDebugLauncher(cwd, written) {
847
+ const dir = path6.join(cwd, ".vscode");
848
+ const filePath = path6.join(dir, "defold-debug.ts");
849
+ if (existsSync2(filePath)) {
850
+ return;
851
+ }
852
+ mkdirSync2(dir, { recursive: true });
853
+ writeFileSync2(filePath, DEBUG_LAUNCHER_SOURCE);
854
+ written.push(".vscode/defold-debug.ts");
855
+ }
646
856
  function writeTsSurface(cwd, written, force = false) {
647
857
  mkdirSync2(path6.join(cwd, "src"), { recursive: true });
648
858
  writeFileSync2(path6.join(cwd, "src", "main.ts"), MAIN_TS_CONTENT);
@@ -684,9 +894,12 @@ function writeTsSurface(cwd, written, force = false) {
684
894
  writeGitignore(cwd);
685
895
  written.push(".gitignore");
686
896
  writeBiome(cwd, written);
897
+ writeMiseTasks(cwd, written);
687
898
  writeVscodeExtensions(cwd, written);
688
899
  writeVscodeSettings(cwd, written);
689
900
  writeVscodeSnippets(cwd, written);
901
+ writeVscodeLaunch(cwd, written);
902
+ writeVscodeDebugLauncher(cwd, written);
690
903
  return selectScriptKind(kinds);
691
904
  }
692
905
  function runNewProjectInit(cwd, force = false) {
@@ -769,7 +982,7 @@ function materializeApiSurface(opts) {
769
982
  const excluded = excludedModulesForKind(opts.scriptKind ?? null);
770
983
  const sources = listDts(sourceGeneratedDir).filter((file) => file !== "index.d.ts").filter((file) => !excluded.has(file.replace(/\.d\.ts$/, "")));
771
984
  const srcDir = path7.resolve(sourceGeneratedDir, "..", "src");
772
- const overloads = ["msg-overloads.d.ts", "go-overloads.d.ts"].filter((file) => existsSync3(path7.join(srcDir, file)));
985
+ const overloads = ["msg-overloads.d.ts", "message-guard.d.ts", "go-overloads.d.ts"].filter((file) => existsSync3(path7.join(srcDir, file)));
773
986
  const coreTypesSrc = path7.join(srcDir, "core-types.ts");
774
987
  const includeCoreTypes = overloads.length > 0 && existsSync3(coreTypesSrc);
775
988
  const engineGlobalsSrc = path7.join(srcDir, "engine-globals.d.ts");
@@ -844,12 +1057,16 @@ function ensureMaterializedReference(cwd, materializedDir) {
844
1057
  const tsconfigPath = path7.join(cwd, "tsconfig.json");
845
1058
  if (existsSync3(tsconfigPath)) {
846
1059
  const tsconfig = JSON.parse(readFileSync6(tsconfigPath, "utf8"));
847
- tsconfig.compilerOptions = {
848
- ...tsconfig.compilerOptions ?? {},
849
- typeRoots: [MATERIALIZED_ROOT],
850
- types: [surfaceId]
851
- };
852
- writeJson2(tsconfigPath, tsconfig);
1060
+ const current = tsconfig.compilerOptions ?? {};
1061
+ const alreadyRepointed = JSON.stringify(current.typeRoots) === JSON.stringify([MATERIALIZED_ROOT]) && JSON.stringify(current.types) === JSON.stringify([surfaceId]);
1062
+ if (!alreadyRepointed) {
1063
+ tsconfig.compilerOptions = {
1064
+ ...current,
1065
+ typeRoots: [MATERIALIZED_ROOT],
1066
+ types: [surfaceId]
1067
+ };
1068
+ writeJson2(tsconfigPath, tsconfig);
1069
+ }
853
1070
  }
854
1071
  ensureGitignoreLine(cwd, `${MATERIALIZED_ROOT}/`);
855
1072
  }
@@ -0,0 +1,43 @@
1
+ export interface EngineTarget {
2
+ readonly enginePlatform: string;
3
+ readonly buildFolder: string;
4
+ readonly executable: string;
5
+ }
6
+ export declare const DEBUG_LAUNCHER_REL = ".vscode/defold-debug.ts";
7
+ export declare function targetPlatform(platform: NodeJS.Platform): EngineTarget;
8
+ export declare function engineDownloadUrl(sha1: string, enginePlatform: string, executable: string): string;
9
+ export interface ResolveEngineOptions {
10
+ readonly cwd: string;
11
+ readonly target: EngineTarget;
12
+ readonly stockPath: string;
13
+ readonly probe: (candidate: string) => boolean;
14
+ }
15
+ export declare function resolveEnginePath(opts: ResolveEngineOptions): string;
16
+ export declare function debugLaunchConfig(): {
17
+ name: string;
18
+ type: string;
19
+ request: string;
20
+ stopOnEntry: boolean;
21
+ verbose: boolean;
22
+ internalConsoleOptions: string;
23
+ program: {
24
+ command: string;
25
+ };
26
+ args: string[];
27
+ };
28
+ export declare const VSCODE_LAUNCH_CONTENT: {
29
+ version: string;
30
+ configurations: {
31
+ name: string;
32
+ type: string;
33
+ request: string;
34
+ stopOnEntry: boolean;
35
+ verbose: boolean;
36
+ internalConsoleOptions: string;
37
+ program: {
38
+ command: string;
39
+ };
40
+ args: string[];
41
+ }[];
42
+ };
43
+ export declare const DEBUG_LAUNCHER_SOURCE: string;