@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.
- package/bin/dithrkit.js +4 -0
- package/configs/eslint.config.js +96 -0
- package/configs/tsconfig.base.json +13 -0
- package/lib/binary.js +33 -0
- package/lib/build-helper.js +82 -0
- package/lib/cli.js +91 -0
- package/lib/commands/build.js +74 -0
- package/lib/commands/create.js +235 -0
- package/lib/commands/dev.js +145 -0
- package/lib/commands/export.js +164 -0
- package/lib/commands/run.js +83 -0
- package/lib/commands/serve.js +165 -0
- package/lib/commands/watch.js +447 -0
- package/lib/packager.js +159 -0
- package/package.json +52 -0
- package/templates/blank.js +14 -0
- package/templates/blank.ts +14 -0
- package/templates/platformer.js +53 -0
- package/templates/platformer.ts +53 -0
- package/templates/shell.html +77 -0
- package/types/dithr.d.ts +700 -0
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const http = require("node:http");
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const path = require("node:path");
|
|
7
|
+
const zlib = require("node:zlib");
|
|
8
|
+
const { execSync, spawn } = require("node:child_process");
|
|
9
|
+
const { detectBuild, buildSync } = require("../build-helper.js");
|
|
10
|
+
|
|
11
|
+
function usage() {
|
|
12
|
+
console.log("Usage: dithrkit watch [port] [options]");
|
|
13
|
+
console.log("");
|
|
14
|
+
console.log("Watch cart source directory, auto-rebuild, and serve with live reload.");
|
|
15
|
+
console.log("");
|
|
16
|
+
console.log("Options:");
|
|
17
|
+
console.log(" --port, -p <port> Port to serve on (default: 8080)");
|
|
18
|
+
console.log(" --help, -h Show help");
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const args = process.argv.slice(2);
|
|
23
|
+
if (args.includes("--help") || args.includes("-h")) usage();
|
|
24
|
+
|
|
25
|
+
let port = 8080;
|
|
26
|
+
for (let i = 0; i < args.length; i++) {
|
|
27
|
+
if (args[i] === "--port" || args[i] === "-p") {
|
|
28
|
+
port = parseInt(args[++i], 10);
|
|
29
|
+
} else if (!isNaN(parseInt(args[i], 10))) {
|
|
30
|
+
port = parseInt(args[i], 10);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const cartJson = path.resolve("cart.json");
|
|
35
|
+
if (!fs.existsSync(cartJson)) {
|
|
36
|
+
console.error("No cart.json found in current directory.");
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const cart = JSON.parse(fs.readFileSync(cartJson, "utf-8"));
|
|
41
|
+
const cartDir = path.dirname(cartJson);
|
|
42
|
+
const buildDir = path.resolve("build", "web");
|
|
43
|
+
|
|
44
|
+
// Determine JS entry point for hot-reload
|
|
45
|
+
let entryJs = null;
|
|
46
|
+
if (cart.code) {
|
|
47
|
+
entryJs = cart.code.replace(/\\/g, "/");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/* ------------------------------------------------------------------ */
|
|
51
|
+
/* SSE live-reload */
|
|
52
|
+
/* ------------------------------------------------------------------ */
|
|
53
|
+
|
|
54
|
+
/** @type {Set<import("node:http").ServerResponse>} */
|
|
55
|
+
const sseClients = new Set();
|
|
56
|
+
|
|
57
|
+
const RELOAD_SNIPPET = `
|
|
58
|
+
<script>
|
|
59
|
+
(function(){
|
|
60
|
+
var es = new EventSource("/__livereload");
|
|
61
|
+
es.addEventListener("reload", function(){ location.reload(); });
|
|
62
|
+
es.addEventListener("hotreload", function(e){
|
|
63
|
+
var jsPath = e.data;
|
|
64
|
+
if (!Module || !Module.FS) {
|
|
65
|
+
console.warn("[hot-reload] Module.FS not available, full reload");
|
|
66
|
+
location.reload();
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (typeof Module._dtr_wasm_reload !== "function") {
|
|
70
|
+
console.warn("[hot-reload] _dtr_wasm_reload not exported, full reload");
|
|
71
|
+
location.reload();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
fetch("/__cart/" + jsPath + "?t=" + Date.now())
|
|
75
|
+
.then(function(r){ return r.text(); })
|
|
76
|
+
.then(function(src){
|
|
77
|
+
var enc = new TextEncoder();
|
|
78
|
+
Module.FS.writeFile("/cart/" + jsPath, enc.encode(src));
|
|
79
|
+
Module._dtr_wasm_reload();
|
|
80
|
+
console.log("[hot-reload] reloaded " + jsPath);
|
|
81
|
+
})
|
|
82
|
+
.catch(function(err){ console.warn("[hot-reload] failed, full reload", err); location.reload(); });
|
|
83
|
+
});
|
|
84
|
+
es.addEventListener("assetreload", function(e){
|
|
85
|
+
var assetPath = e.data;
|
|
86
|
+
if (!Module || !Module.FS) {
|
|
87
|
+
console.warn("[asset-reload] Module.FS not available, full reload");
|
|
88
|
+
location.reload();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (typeof Module._dtr_wasm_reload_assets !== "function") {
|
|
92
|
+
console.warn("[asset-reload] _dtr_wasm_reload_assets not exported, full reload");
|
|
93
|
+
location.reload();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
fetch("/__cart/" + assetPath + "?t=" + Date.now())
|
|
97
|
+
.then(function(r){ return r.arrayBuffer(); })
|
|
98
|
+
.then(function(buf){
|
|
99
|
+
Module.FS.writeFile("/cart/" + assetPath, new Uint8Array(buf));
|
|
100
|
+
Module._dtr_wasm_reload_assets();
|
|
101
|
+
console.log("[asset-reload] reloaded " + assetPath);
|
|
102
|
+
})
|
|
103
|
+
.catch(function(err){ console.warn("[asset-reload] failed, full reload", err); location.reload(); });
|
|
104
|
+
});
|
|
105
|
+
es.onerror = function(){ es.close(); setTimeout(function(){ location.reload(); }, 2000); };
|
|
106
|
+
})();
|
|
107
|
+
</script>
|
|
108
|
+
</head>`;
|
|
109
|
+
|
|
110
|
+
/* ------------------------------------------------------------------ */
|
|
111
|
+
/* Static file server */
|
|
112
|
+
/* ------------------------------------------------------------------ */
|
|
113
|
+
|
|
114
|
+
const MIME_TYPES = {
|
|
115
|
+
".html": "text/html; charset=utf-8",
|
|
116
|
+
".js": "application/javascript; charset=utf-8",
|
|
117
|
+
".wasm": "application/wasm",
|
|
118
|
+
".data": "application/octet-stream",
|
|
119
|
+
".json": "application/json; charset=utf-8",
|
|
120
|
+
".css": "text/css; charset=utf-8",
|
|
121
|
+
".png": "image/png",
|
|
122
|
+
".ico": "image/x-icon",
|
|
123
|
+
".svg": "image/svg+xml",
|
|
124
|
+
".txt": "text/plain; charset=utf-8",
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
function getMime(fp) {
|
|
128
|
+
return MIME_TYPES[path.extname(fp).toLowerCase()] || "application/octet-stream";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function pickEncoding(accept) {
|
|
132
|
+
if (accept.includes("br")) return "br";
|
|
133
|
+
if (accept.includes("gzip")) return "gzip";
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function compressStream(enc) {
|
|
138
|
+
if (enc === "br") return zlib.createBrotliCompress();
|
|
139
|
+
if (enc === "gzip") return zlib.createGzip();
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const server = http.createServer((req, res) => {
|
|
144
|
+
const url = new URL(req.url, `http://localhost:${port}`);
|
|
145
|
+
let relPath = decodeURIComponent(url.pathname);
|
|
146
|
+
|
|
147
|
+
/* SSE endpoint for live reload */
|
|
148
|
+
if (relPath === "/__livereload") {
|
|
149
|
+
res.writeHead(200, {
|
|
150
|
+
"Content-Type": "text/event-stream",
|
|
151
|
+
"Cache-Control": "no-cache",
|
|
152
|
+
Connection: "keep-alive",
|
|
153
|
+
});
|
|
154
|
+
res.write(":\n\n");
|
|
155
|
+
sseClients.add(res);
|
|
156
|
+
req.on("close", () => sseClients.delete(res));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/* Serve raw cart files for hot reload */
|
|
161
|
+
if (relPath.startsWith("/__cart/")) {
|
|
162
|
+
const cartRel = relPath.slice("/__cart/".length);
|
|
163
|
+
const cartFile = path.resolve(cartDir, cartRel);
|
|
164
|
+
if (!cartFile.startsWith(cartDir + path.sep) && cartFile !== cartDir) {
|
|
165
|
+
res.writeHead(403);
|
|
166
|
+
res.end("Forbidden");
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
fs.stat(cartFile, (err, stat) => {
|
|
170
|
+
if (err || !stat.isFile()) {
|
|
171
|
+
res.writeHead(404);
|
|
172
|
+
res.end("Not Found");
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
res.setHeader("Content-Type", getMime(cartFile));
|
|
176
|
+
res.setHeader("Cache-Control", "no-store");
|
|
177
|
+
res.setHeader("Content-Length", stat.size);
|
|
178
|
+
res.writeHead(200);
|
|
179
|
+
fs.createReadStream(cartFile).pipe(res);
|
|
180
|
+
});
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (relPath === "/") relPath = "/index.html";
|
|
185
|
+
|
|
186
|
+
// Prevent path traversal
|
|
187
|
+
const filePath = path.resolve(buildDir, relPath.slice(1));
|
|
188
|
+
if (!filePath.startsWith(buildDir + path.sep) && filePath !== buildDir) {
|
|
189
|
+
res.writeHead(403);
|
|
190
|
+
res.end("Forbidden");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
fs.stat(filePath, (err, stat) => {
|
|
195
|
+
if (err || !stat.isFile()) {
|
|
196
|
+
res.writeHead(404);
|
|
197
|
+
res.end("Not Found");
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const mime = getMime(filePath);
|
|
202
|
+
const accept = req.headers["accept-encoding"] || "";
|
|
203
|
+
const encoding = pickEncoding(accept);
|
|
204
|
+
|
|
205
|
+
res.setHeader("Content-Type", mime);
|
|
206
|
+
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
|
|
207
|
+
res.setHeader("Pragma", "no-cache");
|
|
208
|
+
res.setHeader("Expires", "0");
|
|
209
|
+
/* Inject live-reload snippet into HTML */
|
|
210
|
+
if (mime.startsWith("text/html")) {
|
|
211
|
+
fs.readFile(filePath, "utf8", (readErr, html) => {
|
|
212
|
+
if (readErr) {
|
|
213
|
+
res.writeHead(500);
|
|
214
|
+
res.end("Read error");
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
html = html.replace("</head>", RELOAD_SNIPPET);
|
|
218
|
+
|
|
219
|
+
const buf = Buffer.from(html, "utf8");
|
|
220
|
+
const comp = compressStream(encoding);
|
|
221
|
+
if (comp) {
|
|
222
|
+
res.setHeader("Content-Encoding", encoding);
|
|
223
|
+
res.writeHead(200);
|
|
224
|
+
comp.end(buf);
|
|
225
|
+
comp.pipe(res);
|
|
226
|
+
} else {
|
|
227
|
+
res.setHeader("Content-Length", buf.length);
|
|
228
|
+
res.writeHead(200);
|
|
229
|
+
res.end(buf);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const stream = fs.createReadStream(filePath);
|
|
236
|
+
const comp = compressStream(encoding);
|
|
237
|
+
if (comp) {
|
|
238
|
+
res.setHeader("Content-Encoding", encoding);
|
|
239
|
+
res.writeHead(200);
|
|
240
|
+
stream.pipe(comp).pipe(res);
|
|
241
|
+
} else {
|
|
242
|
+
res.setHeader("Content-Length", stat.size);
|
|
243
|
+
res.writeHead(200);
|
|
244
|
+
stream.pipe(res);
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
/* ------------------------------------------------------------------ */
|
|
250
|
+
/* Auto-rebuild on cart file changes */
|
|
251
|
+
/* ------------------------------------------------------------------ */
|
|
252
|
+
|
|
253
|
+
let building = false;
|
|
254
|
+
let pendingRebuild = false;
|
|
255
|
+
|
|
256
|
+
function rebuild(openBrowser) {
|
|
257
|
+
if (building) {
|
|
258
|
+
pendingRebuild = true;
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
building = true;
|
|
262
|
+
console.log("\n[watch] Rebuilding web export…");
|
|
263
|
+
|
|
264
|
+
// Run dithrkit export --web
|
|
265
|
+
const dithrkit = process.argv[0];
|
|
266
|
+
const cliPath = path.join(__dirname, "..", "cli.js");
|
|
267
|
+
const proc = spawn(dithrkit, [cliPath, "export", "--web", "--out", buildDir], {
|
|
268
|
+
cwd: cartDir,
|
|
269
|
+
stdio: "inherit",
|
|
270
|
+
shell: false,
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
proc.on("close", (code) => {
|
|
274
|
+
building = false;
|
|
275
|
+
if (code === 0) {
|
|
276
|
+
console.log("[watch] Build succeeded");
|
|
277
|
+
if (openBrowser) {
|
|
278
|
+
startServer();
|
|
279
|
+
} else {
|
|
280
|
+
console.log("[watch] Reloading browser");
|
|
281
|
+
for (const client of sseClients) {
|
|
282
|
+
client.write("event: reload\ndata: rebuild\n\n");
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
console.log(`[watch] Build failed (exit ${code})`);
|
|
287
|
+
if (openBrowser) {
|
|
288
|
+
startServer();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (pendingRebuild) {
|
|
293
|
+
pendingRebuild = false;
|
|
294
|
+
rebuild(false);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/* Debounce */
|
|
300
|
+
let debounceTimer = null;
|
|
301
|
+
let pendingFiles = new Set();
|
|
302
|
+
|
|
303
|
+
function isIgnoredFile(filename) {
|
|
304
|
+
if (!filename) return true;
|
|
305
|
+
if (filename.endsWith("~") || filename.startsWith(".")) return true;
|
|
306
|
+
const ext = path.extname(filename).toLowerCase();
|
|
307
|
+
if (ext === ".tmp" || ext === ".swp" || ext === ".bak" || ext === ".crswap") return true;
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function onCartChange(eventType, filename) {
|
|
312
|
+
if (isIgnoredFile(filename)) return;
|
|
313
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
314
|
+
|
|
315
|
+
pendingFiles.add(filename.replace(/\\/g, "/"));
|
|
316
|
+
|
|
317
|
+
debounceTimer = setTimeout(() => {
|
|
318
|
+
const files = [...pendingFiles];
|
|
319
|
+
pendingFiles.clear();
|
|
320
|
+
|
|
321
|
+
const known = files.filter((f) => path.extname(f) !== "");
|
|
322
|
+
if (known.length === 0) return;
|
|
323
|
+
|
|
324
|
+
// Rebuild TypeScript if any .ts files changed
|
|
325
|
+
const hasTs = known.some((f) => f.endsWith(".ts"));
|
|
326
|
+
if (hasTs && detectBuild(cartDir)) {
|
|
327
|
+
console.log("[watch] TypeScript files changed — rebuilding…");
|
|
328
|
+
if (!buildSync(cartDir)) {
|
|
329
|
+
console.error("[watch] TypeScript build failed. Fix errors and save to retry.");
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const jsOnly = known.every((f) => f.endsWith(".js") || f.endsWith(".mjs"));
|
|
335
|
+
const isEntryChange =
|
|
336
|
+
jsOnly && entryJs != null && known.length === 1 && known[0] === entryJs;
|
|
337
|
+
|
|
338
|
+
const ASSET_EXTS = [".png", ".tmj", ".ldtk", ".wav", ".ogg", ".mp3"];
|
|
339
|
+
const assetOnly =
|
|
340
|
+
!jsOnly &&
|
|
341
|
+
known.every((f) => {
|
|
342
|
+
const ext = path.extname(f).toLowerCase();
|
|
343
|
+
return ASSET_EXTS.includes(ext);
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
if (isEntryChange) {
|
|
347
|
+
console.log(`[watch] JS entry changed: ${known.join(", ")} — hot-reloading`);
|
|
348
|
+
for (const client of sseClients) {
|
|
349
|
+
for (const f of known) {
|
|
350
|
+
client.write(`event: hotreload\ndata: ${f}\n\n`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
} else if (assetOnly) {
|
|
354
|
+
console.log(`[watch] Assets changed: ${known.join(", ")} — asset-reloading`);
|
|
355
|
+
for (const client of sseClients) {
|
|
356
|
+
for (const f of known) {
|
|
357
|
+
client.write(`event: assetreload\ndata: ${f}\n\n`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
} else {
|
|
361
|
+
rebuild(false);
|
|
362
|
+
}
|
|
363
|
+
}, 300);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const watcher = fs.watch(cartDir, { recursive: true }, onCartChange);
|
|
367
|
+
console.log(`[watch] Watching ${cartDir} for changes`);
|
|
368
|
+
|
|
369
|
+
/* ------------------------------------------------------------------ */
|
|
370
|
+
/* Graceful shutdown */
|
|
371
|
+
/* ------------------------------------------------------------------ */
|
|
372
|
+
|
|
373
|
+
function cleanup() {
|
|
374
|
+
watcher.close();
|
|
375
|
+
for (const client of sseClients) {
|
|
376
|
+
client.end();
|
|
377
|
+
}
|
|
378
|
+
sseClients.clear();
|
|
379
|
+
server.close();
|
|
380
|
+
process.exit(0);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
process.on("SIGINT", cleanup);
|
|
384
|
+
process.on("SIGTERM", cleanup);
|
|
385
|
+
|
|
386
|
+
/* ------------------------------------------------------------------ */
|
|
387
|
+
/* Start server */
|
|
388
|
+
/* ------------------------------------------------------------------ */
|
|
389
|
+
|
|
390
|
+
function startServer() {
|
|
391
|
+
server.listen(port, () => {
|
|
392
|
+
const url = `http://localhost:${port}`;
|
|
393
|
+
console.log(`[watch] Serving ${buildDir}`);
|
|
394
|
+
console.log(`[watch] → ${url}`);
|
|
395
|
+
console.log("[watch] Press Ctrl+C to stop.\n");
|
|
396
|
+
|
|
397
|
+
try {
|
|
398
|
+
const cmd =
|
|
399
|
+
process.platform === "win32"
|
|
400
|
+
? `start ${url}`
|
|
401
|
+
: process.platform === "darwin"
|
|
402
|
+
? `open ${url}`
|
|
403
|
+
: `xdg-open ${url}`;
|
|
404
|
+
execSync(cmd, { stdio: "ignore" });
|
|
405
|
+
} catch {
|
|
406
|
+
/* ignore */
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
server.on("error", (err) => {
|
|
411
|
+
if (err.code === "EADDRINUSE") {
|
|
412
|
+
console.log(`[watch] Port ${port} in use — killing previous process…`);
|
|
413
|
+
try {
|
|
414
|
+
if (process.platform === "win32") {
|
|
415
|
+
const out = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, {
|
|
416
|
+
encoding: "utf8",
|
|
417
|
+
});
|
|
418
|
+
const pids = new Set(
|
|
419
|
+
out
|
|
420
|
+
.trim()
|
|
421
|
+
.split(/\r?\n/)
|
|
422
|
+
.map((l) => l.trim().split(/\s+/).pop()),
|
|
423
|
+
);
|
|
424
|
+
for (const pid of pids) {
|
|
425
|
+
execSync(`taskkill /F /PID ${pid}`, { stdio: "ignore" });
|
|
426
|
+
}
|
|
427
|
+
} else {
|
|
428
|
+
execSync(`fuser -k ${port}/tcp`, { stdio: "ignore" });
|
|
429
|
+
}
|
|
430
|
+
} catch {
|
|
431
|
+
/* ignore */
|
|
432
|
+
}
|
|
433
|
+
setTimeout(startServer, 500);
|
|
434
|
+
} else {
|
|
435
|
+
throw err;
|
|
436
|
+
}
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Initial build + serve
|
|
441
|
+
if (detectBuild(cartDir)) {
|
|
442
|
+
console.log("[watch] Building TypeScript before initial export…");
|
|
443
|
+
if (!buildSync(cartDir)) {
|
|
444
|
+
console.error("[watch] TypeScript build failed. Fix errors and save to retry.");
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
rebuild(true);
|
package/lib/packager.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Pack a directory tree into the Emscripten preload data format.
|
|
8
|
+
*
|
|
9
|
+
* Emscripten's file_packager.py produces two files:
|
|
10
|
+
* - .data — concatenated raw file contents
|
|
11
|
+
* - .js — metadata (Remote package, file list with offsets/sizes)
|
|
12
|
+
*
|
|
13
|
+
* This module produces a compatible .data file and returns metadata
|
|
14
|
+
* that the export command uses to patch the Emscripten glue JS.
|
|
15
|
+
*
|
|
16
|
+
* The .data file is simply all files concatenated. Metadata records
|
|
17
|
+
* each file's virtual path, byte offset, and byte length.
|
|
18
|
+
*
|
|
19
|
+
* @param {string} dir Directory to pack (e.g. the cart directory)
|
|
20
|
+
* @param {string} mount Virtual mount point (e.g. "/cart")
|
|
21
|
+
* @returns {{ dataBuffer: Buffer, files: Array<{filename: string, start: number, end: number}> }}
|
|
22
|
+
*/
|
|
23
|
+
function packDirectory(dir, mount) {
|
|
24
|
+
const files = [];
|
|
25
|
+
const chunks = [];
|
|
26
|
+
let offset = 0;
|
|
27
|
+
|
|
28
|
+
function walk(currentDir, relPrefix) {
|
|
29
|
+
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
30
|
+
// Sort for deterministic output
|
|
31
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
32
|
+
|
|
33
|
+
for (const entry of entries) {
|
|
34
|
+
const fullPath = path.join(currentDir, entry.name);
|
|
35
|
+
const relPath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
|
|
36
|
+
|
|
37
|
+
if (entry.isDirectory()) {
|
|
38
|
+
walk(fullPath, relPath);
|
|
39
|
+
} else if (entry.isFile()) {
|
|
40
|
+
const data = fs.readFileSync(fullPath);
|
|
41
|
+
const virtualPath = `${mount}/${relPath}`;
|
|
42
|
+
|
|
43
|
+
files.push({
|
|
44
|
+
filename: virtualPath,
|
|
45
|
+
start: offset,
|
|
46
|
+
end: offset + data.length,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
chunks.push(data);
|
|
50
|
+
offset += data.length;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
walk(dir, "");
|
|
56
|
+
|
|
57
|
+
const dataBuffer = Buffer.concat(chunks);
|
|
58
|
+
return { dataBuffer, files };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Generate the Emscripten-compatible data package loader JS.
|
|
63
|
+
*
|
|
64
|
+
* This produces a self-contained script that:
|
|
65
|
+
* 1. Fetches the .data file
|
|
66
|
+
* 2. Registers each file into the Emscripten VFS at the correct path
|
|
67
|
+
*
|
|
68
|
+
* @param {string} dataFilename Name of the .data file (e.g. "dithr.data")
|
|
69
|
+
* @param {Array<{filename: string, start: number, end: number}>} files
|
|
70
|
+
* @returns {string} JavaScript source
|
|
71
|
+
*/
|
|
72
|
+
function generatePackageLoader(dataFilename, files) {
|
|
73
|
+
// Build the directory creation list
|
|
74
|
+
const dirs = new Set();
|
|
75
|
+
for (const f of files) {
|
|
76
|
+
const parts = f.filename.split("/");
|
|
77
|
+
for (let i = 1; i < parts.length; i++) {
|
|
78
|
+
dirs.add(parts.slice(0, i).join("/"));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const dirList = [...dirs].sort();
|
|
83
|
+
const fileEntries = files.map(
|
|
84
|
+
(f) => `{filename:"${f.filename}",start:${f.start},end:${f.end}}`,
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
return [
|
|
88
|
+
"var Module = typeof Module != 'undefined' ? Module : {};",
|
|
89
|
+
"",
|
|
90
|
+
"(function() {",
|
|
91
|
+
` var PACKAGE_PATH = '';`,
|
|
92
|
+
` var PACKAGE_NAME = '${dataFilename}';`,
|
|
93
|
+
` var REMOTE_PACKAGE_BASE = '${dataFilename}';`,
|
|
94
|
+
"",
|
|
95
|
+
" var PACKAGE_INFO = {",
|
|
96
|
+
` files: [${fileEntries.join(",")}]`,
|
|
97
|
+
" };",
|
|
98
|
+
"",
|
|
99
|
+
" function assert(check, msg) {",
|
|
100
|
+
" if (!check) throw msg + new Error().stack;",
|
|
101
|
+
" }",
|
|
102
|
+
"",
|
|
103
|
+
" function processPackageData(arrayBuffer) {",
|
|
104
|
+
" assert(arrayBuffer, 'Loading data file failed.');",
|
|
105
|
+
" assert(arrayBuffer.constructor.name === ArrayBuffer.name, 'bad input');",
|
|
106
|
+
" var byteArray = new Uint8Array(arrayBuffer);",
|
|
107
|
+
" var curr;",
|
|
108
|
+
"",
|
|
109
|
+
" // Create directories",
|
|
110
|
+
...dirList.map(
|
|
111
|
+
(d) =>
|
|
112
|
+
` Module['FS_createPath']('${path.dirname("/" + d).replace(/\\/g, "/")}', '${path.basename(d)}', true, true);`,
|
|
113
|
+
),
|
|
114
|
+
"",
|
|
115
|
+
" // Create files",
|
|
116
|
+
" PACKAGE_INFO.files.forEach(function(fileInfo) {",
|
|
117
|
+
" var data = byteArray.subarray(fileInfo.start, fileInfo.end);",
|
|
118
|
+
" var dir = fileInfo.filename.substring(0, fileInfo.filename.lastIndexOf('/'));",
|
|
119
|
+
" Module['FS_createDataFile'](dir, fileInfo.filename.split('/').pop(), data, true, true, true);",
|
|
120
|
+
" });",
|
|
121
|
+
" }",
|
|
122
|
+
"",
|
|
123
|
+
" var fetchedCallback = null;",
|
|
124
|
+
" var fetched = Module['getPreloadedPackage'] ? Module['getPreloadedPackage'](REMOTE_PACKAGE_BASE, " +
|
|
125
|
+
(files.length > 0 ? files[files.length - 1].end : 0) +
|
|
126
|
+
") : null;",
|
|
127
|
+
"",
|
|
128
|
+
" if (!fetched) {",
|
|
129
|
+
" fetchedCallback = function(data) { fetched = data; };",
|
|
130
|
+
" var url = PACKAGE_PATH + REMOTE_PACKAGE_BASE;",
|
|
131
|
+
" fetch(url).then(function(response) {",
|
|
132
|
+
" if (!response.ok) throw 'failed to load ' + url;",
|
|
133
|
+
" return response.arrayBuffer();",
|
|
134
|
+
" }).then(function(data) {",
|
|
135
|
+
" if (fetchedCallback) { fetchedCallback(data); fetchedCallback = null; }",
|
|
136
|
+
" else { fetched = data; }",
|
|
137
|
+
" });",
|
|
138
|
+
" }",
|
|
139
|
+
"",
|
|
140
|
+
" Module['calledRun'] = false;",
|
|
141
|
+
" function runWithFS() {",
|
|
142
|
+
" processPackageData(fetched);",
|
|
143
|
+
" }",
|
|
144
|
+
"",
|
|
145
|
+
" if (Module['calledRun']) {",
|
|
146
|
+
" runWithFS();",
|
|
147
|
+
" } else {",
|
|
148
|
+
" var old = Module['onRuntimeInitialized'];",
|
|
149
|
+
" Module['onRuntimeInitialized'] = function() {",
|
|
150
|
+
" if (old) old();",
|
|
151
|
+
" runWithFS();",
|
|
152
|
+
" };",
|
|
153
|
+
" }",
|
|
154
|
+
"})();",
|
|
155
|
+
"",
|
|
156
|
+
].join("\n");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = { packDirectory, generatePackageLoader };
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dithrkit/sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "SDK and CLI for the dithr fantasy console",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "dithrkit",
|
|
7
|
+
"homepage": "https://github.com/dithrkit/dithr",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/dithrkit/dithr/issues"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"dithr",
|
|
13
|
+
"fantasy-console",
|
|
14
|
+
"game-engine",
|
|
15
|
+
"retro",
|
|
16
|
+
"gamedev",
|
|
17
|
+
"sdk",
|
|
18
|
+
"cli"
|
|
19
|
+
],
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "https://github.com/dithrkit/dithr.git",
|
|
23
|
+
"directory": "packages/sdk"
|
|
24
|
+
},
|
|
25
|
+
"bin": {
|
|
26
|
+
"dithrkit": "bin/dithrkit.js"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
"./configs/tsconfig.base.json": "./configs/tsconfig.base.json",
|
|
30
|
+
"./configs/eslint": "./configs/eslint.config.js",
|
|
31
|
+
"./types/*": "./types/*"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin/",
|
|
35
|
+
"lib/",
|
|
36
|
+
"templates/",
|
|
37
|
+
"types/",
|
|
38
|
+
"configs/"
|
|
39
|
+
],
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=18"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"esbuild": "^0.24.0"
|
|
45
|
+
},
|
|
46
|
+
"optionalDependencies": {
|
|
47
|
+
"@dithrkit/win32-x64": "0.1.0",
|
|
48
|
+
"@dithrkit/linux-x64": "0.1.0",
|
|
49
|
+
"@dithrkit/darwin-arm64": "0.1.0",
|
|
50
|
+
"@dithrkit/wasm": "0.1.0"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Blank cart template — minimal starting point
|
|
2
|
+
|
|
3
|
+
export function _init(): void {
|
|
4
|
+
gfx.cls(0);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function _update(dt: number): void {
|
|
8
|
+
// Update logic here
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function _draw(): void {
|
|
12
|
+
gfx.cls(0);
|
|
13
|
+
gfx.print('hello, dithr!', 4, 4, 7);
|
|
14
|
+
}
|