@dithrkit/sdk 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.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ require("../lib/cli.js");
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ const js = require("@eslint/js");
4
+ const prettierConfig = require("eslint-config-prettier");
5
+
6
+ const DITHR_GLOBALS = {
7
+ cam: "readonly",
8
+ cart: "readonly",
9
+ col: "readonly",
10
+ evt: "readonly",
11
+ gfx: "readonly",
12
+ input: "readonly",
13
+ key: "readonly",
14
+ map: "readonly",
15
+ math: "readonly",
16
+ mouse: "readonly",
17
+ mus: "readonly",
18
+ pad: "readonly",
19
+ postfx: "readonly",
20
+ sfx: "readonly",
21
+ synth: "readonly",
22
+ sys: "readonly",
23
+ touch: "readonly",
24
+ tween: "readonly",
25
+ ui: "readonly",
26
+ };
27
+
28
+ const BASE_RULES = {
29
+ "no-var": "error",
30
+ "prefer-const": "error",
31
+ "prefer-template": "warn",
32
+ camelcase: ["error", { properties: "never" }],
33
+ eqeqeq: ["error", "always"],
34
+ "no-underscore-dangle": "off",
35
+ "no-plusplus": "off",
36
+ "no-bitwise": "off",
37
+ };
38
+
39
+ // JavaScript config
40
+ const jsConfig = [
41
+ js.configs.recommended,
42
+ prettierConfig,
43
+ {
44
+ files: ["src/**/*.js"],
45
+ languageOptions: {
46
+ ecmaVersion: 2020,
47
+ sourceType: "script",
48
+ globals: DITHR_GLOBALS,
49
+ },
50
+ rules: {
51
+ ...BASE_RULES,
52
+ "no-plusplus": ["error", { allowForLoopAfterthoughts: true }],
53
+ },
54
+ },
55
+ ];
56
+
57
+ // TypeScript config — lazily loads typescript-eslint
58
+ let _tsConfig = null;
59
+ Object.defineProperty(module.exports, "ts", {
60
+ get() {
61
+ if (_tsConfig) return _tsConfig;
62
+ let tseslint;
63
+ try {
64
+ tseslint = require("typescript-eslint");
65
+ } catch {
66
+ throw new Error(
67
+ "typescript-eslint is required for TypeScript linting. " +
68
+ "Install it: npm install -D typescript-eslint",
69
+ );
70
+ }
71
+ _tsConfig = [
72
+ js.configs.recommended,
73
+ ...tseslint.configs.recommended,
74
+ prettierConfig,
75
+ {
76
+ files: ["src/**/*.ts"],
77
+ languageOptions: {
78
+ ecmaVersion: 2020,
79
+ sourceType: "module",
80
+ globals: DITHR_GLOBALS,
81
+ },
82
+ rules: {
83
+ ...BASE_RULES,
84
+ "@typescript-eslint/no-unused-vars": [
85
+ "error",
86
+ { varsIgnorePattern: "^_", argsIgnorePattern: "^_" },
87
+ ],
88
+ },
89
+ },
90
+ ];
91
+ return _tsConfig;
92
+ },
93
+ enumerable: true,
94
+ });
95
+
96
+ module.exports.js = jsConfig;
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "rootDir": "src"
11
+ },
12
+ "include": ["src/**/*.ts", "node_modules/@dithrkit/sdk/types/**/*.d.ts"]
13
+ }
package/lib/binary.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ const PLATFORMS = {
4
+ "win32-x64": "@dithrkit/win32-x64",
5
+ "linux-x64": "@dithrkit/linux-x64",
6
+ "darwin-arm64": "@dithrkit/darwin-arm64",
7
+ };
8
+
9
+ /**
10
+ * Resolve the path to the native dithr binary for the current platform.
11
+ * @returns {string} Absolute path to the binary.
12
+ */
13
+ function getBinaryPath() {
14
+ const key = `${process.platform}-${process.arch}`;
15
+ const pkg = PLATFORMS[key];
16
+
17
+ if (!pkg) {
18
+ const supported = Object.keys(PLATFORMS).join(", ");
19
+ console.error(`Unsupported platform: ${key}`);
20
+ console.error(`dithr supports: ${supported}`);
21
+ process.exit(1);
22
+ }
23
+
24
+ try {
25
+ return require(pkg);
26
+ } catch {
27
+ console.error(`Platform package ${pkg} is not installed.`);
28
+ console.error(`Run: npm install ${pkg}`);
29
+ process.exit(1);
30
+ }
31
+ }
32
+
33
+ module.exports = { getBinaryPath, PLATFORMS };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { spawnSync } = require("node:child_process");
6
+
7
+ /**
8
+ * Detect whether a cart project needs a build step (TS → dist/).
9
+ * Returns { srcEntry, outFile } if a build is needed, or null otherwise.
10
+ */
11
+ function detectBuild(cartDir) {
12
+ const cartPath = path.resolve(cartDir, "cart.json");
13
+ if (!fs.existsSync(cartPath)) return null;
14
+
15
+ const cart = JSON.parse(fs.readFileSync(cartPath, "utf-8"));
16
+ const codeEntry = cart.code || "dist/main.js";
17
+
18
+ if (!codeEntry.startsWith("dist/")) return null;
19
+
20
+ const base = path.basename(codeEntry, ".js");
21
+ const tsFile = path.resolve(cartDir, "src", `${base}.ts`);
22
+ const jsFile = path.resolve(cartDir, "src", `${base}.js`);
23
+
24
+ let srcEntry;
25
+ if (fs.existsSync(tsFile)) {
26
+ srcEntry = tsFile;
27
+ } else if (fs.existsSync(jsFile)) {
28
+ srcEntry = jsFile;
29
+ } else {
30
+ return null;
31
+ }
32
+
33
+ return { srcEntry, outFile: path.resolve(cartDir, codeEntry) };
34
+ }
35
+
36
+ /**
37
+ * Find the esbuild binary.
38
+ * Returns the path to esbuild/bin/esbuild or null.
39
+ */
40
+ function findEsbuild() {
41
+ try {
42
+ return require.resolve("esbuild/bin/esbuild");
43
+ } catch {
44
+ const localBin = path.resolve("node_modules", ".bin", "esbuild");
45
+ if (fs.existsSync(localBin)) return localBin;
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Run a synchronous esbuild build.
52
+ * Returns true on success, false on failure.
53
+ */
54
+ function buildSync(cartDir) {
55
+ const info = detectBuild(cartDir);
56
+ if (!info) return true; // no build needed
57
+
58
+ const esbuildBin = findEsbuild();
59
+ if (!esbuildBin) {
60
+ console.error("esbuild not found. Install @dithrkit/sdk or run npm install.");
61
+ return false;
62
+ }
63
+
64
+ fs.mkdirSync(path.dirname(info.outFile), { recursive: true });
65
+
66
+ const esbuildArgs = [
67
+ info.srcEntry,
68
+ "--bundle",
69
+ "--format=esm",
70
+ "--target=es2020",
71
+ `--outfile=${info.outFile}`,
72
+ ];
73
+
74
+ const result = spawnSync(process.execPath, [esbuildBin, ...esbuildArgs], {
75
+ stdio: "inherit",
76
+ cwd: cartDir,
77
+ });
78
+
79
+ return result.status === 0;
80
+ }
81
+
82
+ module.exports = { detectBuild, findEsbuild, buildSync };
package/lib/cli.js ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+
3
+ function levenshtein(a, b) {
4
+ const m = a.length;
5
+ const n = b.length;
6
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
7
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
8
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
9
+ for (let i = 1; i <= m; i++) {
10
+ for (let j = 1; j <= n; j++) {
11
+ dp[i][j] = Math.min(
12
+ dp[i - 1][j] + 1,
13
+ dp[i][j - 1] + 1,
14
+ dp[i - 1][j - 1] + (a[i - 1] !== b[j - 1] ? 1 : 0),
15
+ );
16
+ }
17
+ }
18
+ return dp[m][n];
19
+ }
20
+
21
+ function didYouMean(input, candidates) {
22
+ let best = null;
23
+ let bestDist = Infinity;
24
+ for (const c of candidates) {
25
+ const d = levenshtein(input.toLowerCase(), c.toLowerCase());
26
+ if (d < bestDist) {
27
+ bestDist = d;
28
+ best = c;
29
+ }
30
+ }
31
+ // Only suggest if edit distance is at most 3
32
+ return bestDist <= 3 ? best : null;
33
+ }
34
+
35
+ const COMMANDS = {
36
+ create: "./commands/create.js",
37
+ build: "./commands/build.js",
38
+ run: "./commands/run.js",
39
+ dev: "./commands/dev.js",
40
+ serve: "./commands/serve.js",
41
+ watch: "./commands/watch.js",
42
+ export: "./commands/export.js",
43
+ };
44
+
45
+ function printUsage() {
46
+ console.log("Usage: dithrkit <command> [options]");
47
+ console.log("");
48
+ console.log("Commands:");
49
+ console.log(" create <name> Scaffold a new dithr project");
50
+ console.log(" build Bundle cart source via esbuild");
51
+ console.log(" run Launch the native dithr runtime");
52
+ console.log(" dev Build --watch + run (native dev loop)");
53
+ console.log(" serve [port] Start a WASM dev server");
54
+ console.log(" watch [port] Watch + live-reload WASM dev server");
55
+ console.log(" export Export cart for distribution");
56
+ console.log("");
57
+ console.log("Options:");
58
+ console.log(" --help, -h Show help");
59
+ console.log(" --version, -v Show version");
60
+ process.exit(1);
61
+ }
62
+
63
+ const args = process.argv.slice(2);
64
+
65
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
66
+ printUsage();
67
+ }
68
+
69
+ if (args[0] === "--version" || args[0] === "-v") {
70
+ const pkg = require("../package.json");
71
+ console.log(pkg.version);
72
+ process.exit(0);
73
+ }
74
+
75
+ const command = args[0];
76
+ const handler = COMMANDS[command];
77
+
78
+ if (!handler) {
79
+ console.error(`Unknown command: ${command}`);
80
+ const suggestion = didYouMean(command, Object.keys(COMMANDS));
81
+ if (suggestion) {
82
+ console.error(`Did you mean "${suggestion}"?`);
83
+ }
84
+ console.error('Run "dithrkit --help" for usage.');
85
+ process.exit(1);
86
+ }
87
+
88
+ // Remove command name from argv so sub-commands see their own args
89
+ process.argv.splice(2, 1);
90
+
91
+ require(handler);
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const { spawnSync } = require("node:child_process");
7
+ const { detectBuild, findEsbuild } = require("../build-helper.js");
8
+
9
+ function usage() {
10
+ console.log("Usage: dithrkit build [options]");
11
+ console.log("");
12
+ console.log("Bundle cart TypeScript/JavaScript source via esbuild.");
13
+ console.log("Reads cart.json in the current directory to determine the entry point.");
14
+ console.log("");
15
+ console.log("Options:");
16
+ console.log(" --watch, -w Watch for changes and rebuild");
17
+ console.log(" --help, -h Show help");
18
+ process.exit(1);
19
+ }
20
+
21
+ const args = process.argv.slice(2);
22
+ if (args.includes("--help") || args.includes("-h")) usage();
23
+
24
+ const watchMode = args.includes("--watch") || args.includes("-w");
25
+ const cartPath = path.resolve("cart.json");
26
+
27
+ if (!fs.existsSync(cartPath)) {
28
+ console.error("No cart.json found in current directory.");
29
+ console.error("Run this command from the root of a dithr project.");
30
+ process.exit(1);
31
+ }
32
+
33
+ const buildInfo = detectBuild(".");
34
+
35
+ if (!buildInfo) {
36
+ console.log("Cart code entry does not use dist/. No build required.");
37
+ process.exit(0);
38
+ }
39
+
40
+ const { srcEntry, outFile } = buildInfo;
41
+
42
+ // Ensure output directory exists
43
+ fs.mkdirSync(path.dirname(outFile), { recursive: true });
44
+
45
+ const esbuildArgs = [
46
+ srcEntry,
47
+ "--bundle",
48
+ "--format=esm",
49
+ "--target=es2020",
50
+ `--outfile=${outFile}`,
51
+ ];
52
+
53
+ if (watchMode) {
54
+ esbuildArgs.push("--watch");
55
+ }
56
+
57
+ // Find esbuild binary
58
+ const esbuildBin = findEsbuild();
59
+ if (!esbuildBin) {
60
+ console.error("esbuild not found. Install @dithrkit/sdk or run npm install.");
61
+ process.exit(1);
62
+ }
63
+
64
+ try {
65
+ const result = spawnSync(process.execPath, [esbuildBin, ...esbuildArgs], {
66
+ stdio: "inherit",
67
+ cwd: process.cwd(),
68
+ });
69
+ if (result.status !== 0) {
70
+ process.exit(result.status || 1);
71
+ }
72
+ } catch (err) {
73
+ process.exit(err.status || 1);
74
+ }
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+
7
+ const TEMPLATES_DIR = path.join(__dirname, "..", "..", "templates");
8
+
9
+ const TEMPLATES = {
10
+ blank: { js: "blank.js", ts: "blank.ts" },
11
+ platformer: { js: "platformer.js", ts: "platformer.ts" },
12
+ };
13
+
14
+ function usage() {
15
+ console.log("Usage: dithrkit create <name> [options]");
16
+ console.log("");
17
+ console.log("Options:");
18
+ console.log(" --template, -t <name> Template to use (blank, platformer)");
19
+ console.log(" --typescript, --ts Scaffold a TypeScript project");
20
+ console.log(" --help, -h Show help");
21
+ process.exit(1);
22
+ }
23
+
24
+ const args = process.argv.slice(2);
25
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") usage();
26
+
27
+ let name = null;
28
+ let template = "blank";
29
+ let useTypescript = false;
30
+
31
+ for (let i = 0; i < args.length; i++) {
32
+ if (args[i] === "--template" || args[i] === "-t") {
33
+ template = args[++i];
34
+ if (!TEMPLATES[template]) {
35
+ console.error(`Unknown template: ${template}`);
36
+ usage();
37
+ }
38
+ } else if (args[i] === "--typescript" || args[i] === "--ts") {
39
+ useTypescript = true;
40
+ } else if (!name) {
41
+ name = args[i];
42
+ }
43
+ }
44
+
45
+ if (!name) usage();
46
+
47
+ const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
48
+ const dir = path.resolve(safeName);
49
+
50
+ if (fs.existsSync(dir)) {
51
+ console.error(`Directory already exists: ${dir}`);
52
+ process.exit(1);
53
+ }
54
+
55
+ // Create directory structure
56
+ fs.mkdirSync(dir, { recursive: true });
57
+ fs.mkdirSync(path.join(dir, "src"), { recursive: true });
58
+ fs.mkdirSync(path.join(dir, "assets", "sprites"), { recursive: true });
59
+ fs.mkdirSync(path.join(dir, "assets", "maps"), { recursive: true });
60
+ fs.mkdirSync(path.join(dir, "assets", "sfx"), { recursive: true });
61
+ fs.mkdirSync(path.join(dir, "assets", "music"), { recursive: true });
62
+
63
+ const srcExt = useTypescript ? "ts" : "js";
64
+ const codeEntry = useTypescript ? "dist/main.js" : "src/main.js";
65
+
66
+ // cart.json
67
+ const cart = {
68
+ title: name,
69
+ author: "",
70
+ version: "1.0.0",
71
+ description: "",
72
+ display: { width: 320, height: 180, scale: 3 },
73
+ timing: { fps: 60 },
74
+ sprites: { tileW: 8, tileH: 8 },
75
+ audio: { channels: 8 },
76
+ input: {
77
+ default_mappings: {
78
+ left: ["KEY_LEFT", "KEY_A", "PAD_LEFT"],
79
+ right: ["KEY_RIGHT", "KEY_D", "PAD_RIGHT"],
80
+ up: ["KEY_UP", "KEY_W", "PAD_UP"],
81
+ down: ["KEY_DOWN", "KEY_S", "PAD_DOWN"],
82
+ jump: ["KEY_Z", "KEY_SPACE", "PAD_A"],
83
+ action: ["KEY_X", "PAD_B"],
84
+ },
85
+ },
86
+ code: codeEntry,
87
+ maps: [],
88
+ };
89
+ fs.writeFileSync(path.join(dir, "cart.json"), JSON.stringify(cart, null, 4) + "\n");
90
+
91
+ // src/main.{js,ts} from template
92
+ const tplFile = useTypescript ? TEMPLATES[template].ts : TEMPLATES[template].js;
93
+ const tplSrc = fs.readFileSync(path.join(TEMPLATES_DIR, tplFile), "utf-8");
94
+ fs.writeFileSync(path.join(dir, "src", `main.${srcExt}`), tplSrc);
95
+
96
+ // TypeScript-specific files
97
+ if (useTypescript) {
98
+ // tsconfig.json — extends the shared SDK config
99
+ const tsconfig = {
100
+ extends: "@dithrkit/sdk/configs/tsconfig.base.json",
101
+ include: ["src/**/*.ts"],
102
+ };
103
+ fs.writeFileSync(path.join(dir, "tsconfig.json"), JSON.stringify(tsconfig, null, 4) + "\n");
104
+ }
105
+
106
+ // .gitignore
107
+ const gitignoreLines = ["node_modules/", "build/", "*.baked.json", ".DS_Store"];
108
+ if (useTypescript) gitignoreLines.push("dist/");
109
+ gitignoreLines.push("");
110
+ fs.writeFileSync(path.join(dir, ".gitignore"), gitignoreLines.join("\n"));
111
+
112
+ // README.md
113
+ fs.writeFileSync(
114
+ path.join(dir, "README.md"),
115
+ [
116
+ `# ${name}`,
117
+ "",
118
+ `A game made with [dithr](https://github.com/dithrkit/dithr).`,
119
+ "",
120
+ "## Getting Started",
121
+ "",
122
+ "```bash",
123
+ "npm install",
124
+ useTypescript ? "npm start # builds TS in watch mode + runs dithr" : "npm start",
125
+ "```",
126
+ "",
127
+ ].join("\n"),
128
+ );
129
+
130
+ // package.json
131
+ const pkg = {
132
+ name: safeName,
133
+ version: "1.0.0",
134
+ private: true,
135
+ description: `${name} — dithr cart`,
136
+ scripts: {
137
+ start: useTypescript ? "dithrkit dev" : "dithrkit run",
138
+ build: useTypescript ? "dithrkit build" : undefined,
139
+ serve: "dithrkit serve",
140
+ watch: "dithrkit watch",
141
+ lint: "eslint src/",
142
+ "lint:fix": "eslint src/ --fix",
143
+ format: "prettier --write 'src/**/*.{js,ts,json}'",
144
+ "format:check": "prettier --check 'src/**/*.{js,ts,json}'",
145
+ typecheck: useTypescript ? "tsc --noEmit" : undefined,
146
+ },
147
+ devDependencies: {
148
+ "@dithrkit/sdk": "^0.1.0",
149
+ eslint: "^9.0.0",
150
+ prettier: "^3.0.0",
151
+ ...(useTypescript
152
+ ? {
153
+ typescript: "^5.0.0",
154
+ "typescript-eslint": "^8.0.0",
155
+ "eslint-config-prettier": "^10.0.0",
156
+ }
157
+ : {
158
+ "eslint-config-prettier": "^10.0.0",
159
+ }),
160
+ },
161
+ };
162
+ // Remove undefined scripts
163
+ Object.keys(pkg.scripts).forEach((k) => {
164
+ if (pkg.scripts[k] === undefined) delete pkg.scripts[k];
165
+ });
166
+ fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify(pkg, null, 4) + "\n");
167
+
168
+ // eslint.config.js — imports shared config from SDK
169
+ if (useTypescript) {
170
+ fs.writeFileSync(
171
+ path.join(dir, "eslint.config.js"),
172
+ [
173
+ 'const dithrConfig = require("@dithrkit/sdk/configs/eslint");',
174
+ "",
175
+ "module.exports = [",
176
+ " ...dithrConfig.ts,",
177
+ "];",
178
+ "",
179
+ ].join("\n"),
180
+ );
181
+ } else {
182
+ fs.writeFileSync(
183
+ path.join(dir, "eslint.config.js"),
184
+ [
185
+ 'const dithrConfig = require("@dithrkit/sdk/configs/eslint");',
186
+ "",
187
+ "module.exports = [",
188
+ " ...dithrConfig.js,",
189
+ "];",
190
+ "",
191
+ ].join("\n"),
192
+ );
193
+ }
194
+
195
+ // .editorconfig
196
+ fs.writeFileSync(
197
+ path.join(dir, ".editorconfig"),
198
+ [
199
+ "root = true",
200
+ "",
201
+ "[*]",
202
+ "charset = utf-8",
203
+ "end_of_line = lf",
204
+ "insert_final_newline = true",
205
+ "trim_trailing_whitespace = true",
206
+ "indent_style = space",
207
+ "indent_size = 4",
208
+ "",
209
+ "[*.json]",
210
+ "indent_size = 2",
211
+ "",
212
+ "[*.md]",
213
+ "trim_trailing_whitespace = false",
214
+ "",
215
+ ].join("\n"),
216
+ );
217
+
218
+ // .prettierrc
219
+ const prettierrc = {
220
+ printWidth: 100,
221
+ tabWidth: 4,
222
+ useTabs: false,
223
+ semi: true,
224
+ singleQuote: true,
225
+ trailingComma: "all",
226
+ bracketSpacing: true,
227
+ };
228
+ fs.writeFileSync(path.join(dir, ".prettierrc"), JSON.stringify(prettierrc, null, 4) + "\n");
229
+
230
+ console.log(`Created dithr project "${name}" in ${dir}/`);
231
+ console.log("");
232
+ console.log("Next steps:");
233
+ console.log(` cd ${safeName}`);
234
+ console.log(" npm install");
235
+ console.log(" npm start");