castle-web-cli 0.4.193 → 0.4.195
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/dist/agent-prompts.d.ts +1 -0
- package/dist/agent-prompts.js +14 -5
- package/dist/agent.js +101 -4
- package/dist/api.d.ts +1 -0
- package/dist/api.js +5 -0
- package/dist/bundle.js +2 -1
- package/dist/castleJson.d.ts +1 -2
- package/dist/castleJson.js +0 -39
- package/dist/check.js +14 -6
- package/dist/devSessionFrameBudget.d.ts +14 -0
- package/dist/devSessionFrameBudget.js +64 -0
- package/dist/devSessionServer.d.ts +6 -0
- package/dist/devSessionServer.js +38 -1
- package/dist/editorConfig.d.ts +1 -1
- package/dist/editorConfig.js +12 -4
- package/dist/filesChanged.js +7 -3
- package/dist/ide.js +28 -59
- package/dist/importUpdateHook.d.ts +31 -0
- package/dist/importUpdateHook.js +135 -0
- package/dist/importUpdateHookRunner.d.ts +2 -0
- package/dist/importUpdateHookRunner.js +24 -0
- package/dist/imports.js +58 -10
- package/dist/index.js +58 -7
- package/dist/init.d.ts +1 -0
- package/dist/init.js +15 -9
- package/dist/multiplayerDoc.d.ts +1 -0
- package/dist/multiplayerDoc.js +228 -0
- package/dist/native/loop.js +29 -9
- package/dist/platformDoc.d.ts +1 -0
- package/dist/platformDoc.js +25 -6
- package/dist/remix.js +4 -1
- package/dist/scriptErrors.d.ts +23 -0
- package/dist/scriptErrors.js +147 -0
- package/dist/serve.js +366 -36
- package/dist/serverBundle.js +1 -1
- package/dist/shell/assets/index-kMH1qj6D.js +449 -0
- package/dist/shell/index.html +1 -1
- package/dist/versions.d.ts +14 -0
- package/dist/versions.js +21 -0
- package/dist/viteClientStub.d.ts +18 -0
- package/dist/viteClientStub.js +193 -0
- package/dist/vitePlugins.d.ts +1 -0
- package/dist/vitePlugins.js +18 -0
- package/kits/base/CLAUDE.md +3 -3
- package/kits/base/castle.json +1 -3
- package/kits/base/sdk/README.md +17 -0
- package/kits/multiplayer-2d/CLAUDE.md +9 -2
- package/kits/multiplayer-2d/blueprints/crate.scene +32 -4
- package/kits/multiplayer-2d/blueprints/other-player.scene +31 -4
- package/kits/multiplayer-2d/blueprints/player.scene +38 -6
- package/kits/multiplayer-2d/blueprints/wall.scene +25 -3
- package/kits/multiplayer-2d/castle.json +3 -12
- package/kits/multiplayer-2d/test/two-client-test.mjs +4 -4
- package/kits/multiplayer-3d/CLAUDE.md +5 -2
- package/kits/multiplayer-3d/castle.json +3 -11
- package/kits/multiplayer-3d/scenes/main.scene +128 -0
- package/kits/physics-2d/CLAUDE.md +16 -11
- package/kits/physics-2d/behaviors/Camera.jsx +5 -6
- package/kits/physics-2d/behaviors/Goal.jsx +5 -2
- package/kits/physics-2d/behaviors/Joints.jsx +4 -3
- package/kits/physics-2d/behaviors/Layout.jsx +120 -3
- package/kits/physics-2d/behaviors/Sprite.jsx +9 -9
- package/kits/physics-2d/behaviors/Style.jsx +22 -15
- package/kits/physics-2d/behaviors/Text.jsx +7 -6
- package/kits/physics-2d/blueprints/ball.scene +27 -5
- package/kits/physics-2d/blueprints/block.scene +16 -3
- package/kits/physics-2d/blueprints/cauldron.scene +3 -1
- package/kits/physics-2d/blueprints/crate.scene +23 -4
- package/kits/physics-2d/blueprints/goal.scene +12 -2
- package/kits/physics-2d/blueprints/text.scene +13 -3
- package/kits/physics-2d/castle.json +2 -11
- package/kits/physics-2d/editors/SceneEditor.jsx +68 -5
- package/kits/physics-2d/editors/SelectionOverlay.jsx +27 -20
- package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
- package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
- package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
- package/kits/physics-2d/engine/blueprint.js +111 -54
- package/kits/physics-2d/engine/blueprintCore.js +59 -0
- package/kits/physics-2d/engine/collider.js +28 -17
- package/kits/physics-2d/engine/layout.js +61 -0
- package/kits/physics-2d/engine/layoutOriginMigration.js +223 -0
- package/kits/physics-2d/engine/liveReload.js +5 -4
- package/kits/physics-2d/engine/physics/PhysicsSystem.js +11 -7
- package/kits/physics-2d/engine/physics/controls.js +4 -8
- package/kits/physics-2d/engine/physics/matterBridge.js +13 -8
- package/kits/physics-2d/engine/scene.js +38 -34
- package/kits/physics-2d/engine/spriteGeometry.js +17 -9
- package/kits/physics-2d/engine/tap.js +4 -3
- package/kits/physics-2d/scenes/main.scene +59 -6
- package/kits/physics-2d/scenes/sandbox.scene +69 -7
- package/kits/physics-2d/scripts/onUpdate.mjs +199 -0
- package/kits/physics-3d/castle.json +0 -11
- package/kits/real-time/castle.json +2 -8
- package/kits/real-time/code/server/persist.js +14 -0
- package/kits/turn-based/CLAUDE.md +18 -10
- package/kits/turn-based/blueprints/board.scene +3 -1
- package/kits/turn-based/blueprints/square.scene +3 -1
- package/kits/turn-based/castle.json +3 -14
- package/kits/turn-based/code/behaviors/Board.jsx +33 -21
- package/package.json +1 -1
- package/dist/shell/assets/index-ColHKJYj.js +0 -449
package/dist/ide.js
CHANGED
|
@@ -19,12 +19,11 @@ import { WebSocketServer } from 'ws';
|
|
|
19
19
|
import { rawDataToString } from './rawData.js';
|
|
20
20
|
import { IMPORTS_DIR, IMPORT_VERSION_FILE, importStatuses, updateImport, } from './imports.js';
|
|
21
21
|
import { FORKS_DIR, forkImportFile, forkStateOf, listOwnForks, ownForkFile, resolveForkedFile, revertImportFile, } from './forks.js';
|
|
22
|
-
import {
|
|
23
|
-
import { readEditorConfig, resolveFileTypes, } from './editorConfig.js';
|
|
22
|
+
import { deckHidesFiles, readEditorConfig, resolveFileTypes, } from './editorConfig.js';
|
|
24
23
|
import { UNSUPPORTED_MEDIA } from './unsupportedMedia.js';
|
|
25
24
|
import { IMPORT_API_PREFIX, handleImportApi } from './importBrowse.js';
|
|
26
25
|
import { readRequestBody, sendJson } from './httpJson.js';
|
|
27
|
-
import { COVER_FILE
|
|
26
|
+
import { COVER_FILE } from './localPaths.js';
|
|
28
27
|
import { applyVersionRestore, createVersion, NotOnThisLine, pendingChanges, UnsavedChanges, versionSummaries, } from './versions.js';
|
|
29
28
|
import { envForUserShell, installCliShims } from './byo-auth.js';
|
|
30
29
|
const HeadlessTerminal = headlessPkg.Terminal;
|
|
@@ -334,34 +333,18 @@ function kitEditorExtensions(config, fileTypes) {
|
|
|
334
333
|
// A deck saved before file types existed named its kit extensions directly.
|
|
335
334
|
return config.extensions ?? [];
|
|
336
335
|
}
|
|
337
|
-
//
|
|
338
|
-
//
|
|
339
|
-
//
|
|
340
|
-
// the list passes through unchanged.
|
|
336
|
+
// Drop the files a deck's `editor.hiddenPaths` globs name (deck-relative POSIX
|
|
337
|
+
// paths). Nothing is hidden unless a deck says so, so no globs -> the list
|
|
338
|
+
// passes through unchanged.
|
|
341
339
|
function filterDeckFiles(files, config) {
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
347
|
-
if (config.hiddenPaths && config.hiddenPaths.length > 0) {
|
|
348
|
-
const isHidden = picomatch(config.hiddenPaths);
|
|
349
|
-
result = result.filter((f) => !isHidden(f));
|
|
350
|
-
}
|
|
351
|
-
return result;
|
|
352
|
-
}
|
|
353
|
-
// The deck's own files, curated. The plan is exempt: it is the platform's file,
|
|
354
|
-
// not one a kit's visiblePaths were written to name, so a curated deck would
|
|
355
|
-
// hide it by omission -- it shows whenever it exists.
|
|
356
|
-
function filterOwnFiles(files, config) {
|
|
357
|
-
const result = filterDeckFiles(files, config);
|
|
358
|
-
if (files.includes(PLAN_FILE) && !result.includes(PLAN_FILE))
|
|
359
|
-
result.push(PLAN_FILE);
|
|
360
|
-
return result;
|
|
340
|
+
if (!config.hiddenPaths || config.hiddenPaths.length === 0)
|
|
341
|
+
return files;
|
|
342
|
+
const isHidden = picomatch(config.hiddenPaths);
|
|
343
|
+
return files.filter((f) => !isHidden(f));
|
|
361
344
|
}
|
|
362
345
|
// Filter each import by the editor config of the deck it came from: strip the
|
|
363
|
-
// `imports/<alias>/` prefix so the dependency's own
|
|
364
|
-
//
|
|
346
|
+
// `imports/<alias>/` prefix so the dependency's own hidden globs match the paths
|
|
347
|
+
// they were written against, then put it back.
|
|
365
348
|
function filterImportedFiles(deckDir, imported) {
|
|
366
349
|
const byAlias = new Map();
|
|
367
350
|
for (const file of imported) {
|
|
@@ -383,16 +366,15 @@ function filterImportedFiles(deckDir, imported) {
|
|
|
383
366
|
}
|
|
384
367
|
return out;
|
|
385
368
|
}
|
|
386
|
-
// The deck's files as the Files panel sees them
|
|
387
|
-
//
|
|
388
|
-
//
|
|
389
|
-
//
|
|
390
|
-
// from, which is the deck that knows which of its files are worth showing.
|
|
369
|
+
// The deck's files as the Files panel sees them: all of them, minus what each
|
|
370
|
+
// deck hides of its own. The importing deck's `hiddenPaths` name its own dirs,
|
|
371
|
+
// so an import is filtered by the config of the deck it came from -- the deck
|
|
372
|
+
// that knows which of its files are worth showing.
|
|
391
373
|
function curatedDeckFiles(deckDir) {
|
|
392
374
|
const listed = listDeckFiles(deckDir);
|
|
393
375
|
const own = listed.filter((f) => !isImportPath(f));
|
|
394
376
|
return [
|
|
395
|
-
...
|
|
377
|
+
...filterDeckFiles(own, readEditorConfig(deckDir)),
|
|
396
378
|
...filterImportedFiles(deckDir, listed.filter(isImportPath)),
|
|
397
379
|
].sort((a, b) => a.localeCompare(b));
|
|
398
380
|
}
|
|
@@ -408,9 +390,11 @@ const PARAMS_DECLARATION = /\bconst\s+PARAMS\b/;
|
|
|
408
390
|
// Which of the deck's files declare params. Scanning here rather than in the
|
|
409
391
|
// browser because a physics-2d deck carries a hundred-plus files under
|
|
410
392
|
// `imports/`, and reading each one over HTTP to open a panel is the wrong cost.
|
|
393
|
+
// Unfiltered on purpose: a file a deck keeps out of its Files tree still holds
|
|
394
|
+
// tunable values, and the Parameters panel is the one place all of them show.
|
|
411
395
|
function filesDeclaringParams(deckDir) {
|
|
412
396
|
const out = [];
|
|
413
|
-
for (const rel of
|
|
397
|
+
for (const rel of listDeckFiles(deckDir)) {
|
|
414
398
|
if (!PARAMS_EXTS.has(path.extname(rel).toLowerCase()))
|
|
415
399
|
continue;
|
|
416
400
|
const resolved = resolveDeckPath(deckDir, rel);
|
|
@@ -542,15 +526,6 @@ function handleVersionRestore(deckDir, req, res, restart) {
|
|
|
542
526
|
}
|
|
543
527
|
});
|
|
544
528
|
}
|
|
545
|
-
// A curated deck hides anything not covered by editor.visiblePaths. Writes,
|
|
546
|
-
// moves, and uploads already mkdir parent dirs; they also have to register the
|
|
547
|
-
// dest folder or a new path lands on disk and stays invisible in Files.
|
|
548
|
-
function ensureFileParentVisible(deckDir, rel) {
|
|
549
|
-
const dir = path.posix.dirname(rel);
|
|
550
|
-
if (dir === '.')
|
|
551
|
-
return ensureVisibleGlob(deckDir, rel, rel);
|
|
552
|
-
return ensureVisiblePath(deckDir, dir);
|
|
553
|
-
}
|
|
554
529
|
function handleFilesWrite(deckDir, req, res) {
|
|
555
530
|
withMutationPath(deckDir, req, res, (target, body) => {
|
|
556
531
|
if (typeof body.contents !== 'string') {
|
|
@@ -559,8 +534,7 @@ function handleFilesWrite(deckDir, req, res) {
|
|
|
559
534
|
try {
|
|
560
535
|
fs.mkdirSync(path.dirname(target.abs), { recursive: true });
|
|
561
536
|
fs.writeFileSync(target.abs, body.contents, 'utf8');
|
|
562
|
-
|
|
563
|
-
sendJson(res, 200, { ok: true, path: target.rel, visiblePathAdded });
|
|
537
|
+
sendJson(res, 200, { ok: true, path: target.rel });
|
|
564
538
|
}
|
|
565
539
|
catch (err) {
|
|
566
540
|
sendFailure(res, 'write', target.rel, err);
|
|
@@ -575,8 +549,7 @@ function handleFilesMkdir(deckDir, req, res) {
|
|
|
575
549
|
catch (err) {
|
|
576
550
|
return sendFailure(res, 'create folder', target.rel, err);
|
|
577
551
|
}
|
|
578
|
-
|
|
579
|
-
sendJson(res, 200, { ok: true, path: target.rel, visiblePathAdded });
|
|
552
|
+
sendJson(res, 200, { ok: true, path: target.rel });
|
|
580
553
|
});
|
|
581
554
|
}
|
|
582
555
|
// Upload one file from the user's device: `POST files/upload?path=<rel>` with
|
|
@@ -584,10 +557,6 @@ function handleFilesMkdir(deckDir, req, res) {
|
|
|
584
557
|
// request per file, so the path is all the metadata there is to carry). Refuses
|
|
585
558
|
// to clobber: the client picks a free name first and a collision here means
|
|
586
559
|
// something else took it in between.
|
|
587
|
-
//
|
|
588
|
-
// A curated deck (non-empty visiblePaths) also gets the destination registered,
|
|
589
|
-
// the same way mkdir does -- otherwise an upload lands on disk and is invisible
|
|
590
|
-
// in the very panel that put it there.
|
|
591
560
|
// Store the deck's local cover (`preview.png`), overwriting whatever was there.
|
|
592
561
|
//
|
|
593
562
|
// The cover is captured continuously while someone plays their deck, but it is
|
|
@@ -641,8 +610,7 @@ function handleFilesUpload(deckDir, req, res) {
|
|
|
641
610
|
catch (err) {
|
|
642
611
|
return sendFailure(res, 'upload', target.rel, err);
|
|
643
612
|
}
|
|
644
|
-
|
|
645
|
-
sendJson(res, 200, { ok: true, path: target.rel, visiblePathAdded });
|
|
613
|
+
sendJson(res, 200, { ok: true, path: target.rel });
|
|
646
614
|
}, (err) => {
|
|
647
615
|
if (err instanceof RangeError)
|
|
648
616
|
return tooBig();
|
|
@@ -770,8 +738,7 @@ function handleFilesRename(deckDir, req, res) {
|
|
|
770
738
|
try {
|
|
771
739
|
fs.mkdirSync(path.dirname(to.abs), { recursive: true });
|
|
772
740
|
fs.renameSync(from.abs, to.abs);
|
|
773
|
-
|
|
774
|
-
sendJson(res, 200, { ok: true, path: to.rel, visiblePathAdded });
|
|
741
|
+
sendJson(res, 200, { ok: true, path: to.rel });
|
|
775
742
|
}
|
|
776
743
|
catch (err) {
|
|
777
744
|
sendFailure(res, 'rename', from.rel, err);
|
|
@@ -810,8 +777,10 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
|
|
|
810
777
|
fileTypes,
|
|
811
778
|
defaultPlayFile: config.defaultPlayFile ?? null,
|
|
812
779
|
initialPanels: config.initialPanels ?? null,
|
|
813
|
-
|
|
814
|
-
|
|
780
|
+
// Whether the Files panel offers its show-hidden control at all: a deck
|
|
781
|
+
// that hides nothing has nothing to reveal, and the globs themselves are
|
|
782
|
+
// the serve's business, not the shell's.
|
|
783
|
+
hidesFiles: deckHidesFiles(deckDir),
|
|
815
784
|
// Formats the platform knows won't survive publishing. Sent alongside the
|
|
816
785
|
// deck's own types rather than merged into them: these are not things the
|
|
817
786
|
// deck understands, they are things this CLI refuses to let it ship.
|
|
@@ -917,7 +886,7 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
|
|
|
917
886
|
if (action === 'list') {
|
|
918
887
|
// `?all=1` returns the unfiltered listing (the "show hidden files & folders"
|
|
919
888
|
// toggle) -- still minus the always-ignored dirs (node_modules/.castle/...),
|
|
920
|
-
// just without the deck's
|
|
889
|
+
// just without the deck's hidden-path globs.
|
|
921
890
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
922
891
|
const all = url.searchParams.get('all') === '1';
|
|
923
892
|
sendJson(res, 200, { files: all ? listDeckFiles(deckDir) : curatedDeckFiles(deckDir) });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** What a hook is handed, plus the module to run. */
|
|
2
|
+
export interface ImportUpdateHook {
|
|
3
|
+
/** The declared module, resolved to an absolute path. */
|
|
4
|
+
modulePath: string;
|
|
5
|
+
deckDir: string;
|
|
6
|
+
importDir: string;
|
|
7
|
+
alias: string;
|
|
8
|
+
/** The version the deck was pinned at -- what the hook gates on. */
|
|
9
|
+
from: string;
|
|
10
|
+
to: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The hook module `imports/<alias>` declares, or null when it declares none or
|
|
14
|
+
* the path it names is not usable. Read from the copy ON DISK, which is the
|
|
15
|
+
* incoming version -- an update's hook is the new code's own migration, so it
|
|
16
|
+
* has to be the new copy's.
|
|
17
|
+
*/
|
|
18
|
+
export declare function findImportUpdateHook(deckDir: string, alias: string): string | null;
|
|
19
|
+
/**
|
|
20
|
+
* Save a version, run the hook, and put the deck's files back if it fails.
|
|
21
|
+
*
|
|
22
|
+
* A child process rather than an in-process `import()`: `updateImport` is called
|
|
23
|
+
* from inside the running serve, and a child buys a fresh module graph on every
|
|
24
|
+
* run (so a rewritten hook is the one that runs), a timeout, and isolation from
|
|
25
|
+
* a `process.exit` in kit code -- none of which are available in-process.
|
|
26
|
+
*
|
|
27
|
+
* The version is the recovery path, and it is saved even when the hook is about
|
|
28
|
+
* to succeed: a migration that ran correctly and is not what the creator wanted
|
|
29
|
+
* is the same problem as one that ran wrong.
|
|
30
|
+
*/
|
|
31
|
+
export declare function runImportUpdateHook(hook: ImportUpdateHook, log: (message: string) => void): Promise<void>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Running an import's `onUpdate` hook: the one moment code that knows a kit's
|
|
2
|
+
// own vocabulary gets to touch a deck's files.
|
|
3
|
+
//
|
|
4
|
+
// The CLI knows nothing about what a hook does. It resolves the module the
|
|
5
|
+
// INCOMING copy declares (castle.json `onUpdate`, see castleJson.ts for the
|
|
6
|
+
// contract), saves a version of the deck first, runs it, and rolls the deck's
|
|
7
|
+
// files back if it fails. Everything about `.scene`, origins, or any other kit
|
|
8
|
+
// concept lives on the other side of that boundary.
|
|
9
|
+
import { execFile } from 'child_process';
|
|
10
|
+
import * as fs from 'fs';
|
|
11
|
+
import * as path from 'path';
|
|
12
|
+
import { fileURLToPath } from 'url';
|
|
13
|
+
import { promisify } from 'util';
|
|
14
|
+
import { IMPORTS_DIR, readCastleJson } from './castleJson.js';
|
|
15
|
+
import { createVersion, discardPendingChanges } from './versions.js';
|
|
16
|
+
import { readHead } from './versionStore.js';
|
|
17
|
+
const execFileAsync = promisify(execFile);
|
|
18
|
+
const DIST_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
19
|
+
const RUNNER = path.join(DIST_DIR, 'importUpdateHookRunner.js');
|
|
20
|
+
// A hook is somebody else's code with the deck's files in front of it, so it
|
|
21
|
+
// gets a wall clock rather than the chance to hang a serve start forever. The
|
|
22
|
+
// env override exists for the test that proves the clock works
|
|
23
|
+
// (scripts/tests/import-update-hook.mjs); nothing else should set it.
|
|
24
|
+
function hookTimeoutMs() {
|
|
25
|
+
const raw = Number(process.env.CASTLE_IMPORT_HOOK_TIMEOUT_MS);
|
|
26
|
+
return Number.isFinite(raw) && raw > 0 ? raw : 120_000;
|
|
27
|
+
}
|
|
28
|
+
// stdout can carry a whole migration's worth of per-file lines, so the default
|
|
29
|
+
// 1MB pipe buffer is not enough of a margin to be worth the risk.
|
|
30
|
+
const MAX_HOOK_OUTPUT = 8 * 1024 * 1024;
|
|
31
|
+
// Only the fields the contract names cross into the child. `modulePath` is the
|
|
32
|
+
// CLI's business, not the hook's.
|
|
33
|
+
function childContext(hook) {
|
|
34
|
+
return {
|
|
35
|
+
deckDir: hook.deckDir,
|
|
36
|
+
importDir: hook.importDir,
|
|
37
|
+
alias: hook.alias,
|
|
38
|
+
from: hook.from,
|
|
39
|
+
to: hook.to,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
// A declared path names a file inside the import's own tree and nothing else: it
|
|
43
|
+
// is written by whoever published that deck, and the module runs with the
|
|
44
|
+
// deck's files in reach, so `../../…` or an absolute path would be a way to run
|
|
45
|
+
// code from anywhere on the machine. POSIX-relative because that is how every
|
|
46
|
+
// other path in a castle.json is written.
|
|
47
|
+
function resolveHookModule(importDir, declared) {
|
|
48
|
+
const rel = declared.trim();
|
|
49
|
+
if (!rel || rel.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(rel) || rel.includes('\\'))
|
|
50
|
+
return null;
|
|
51
|
+
if (rel.split('/').includes('..'))
|
|
52
|
+
return null;
|
|
53
|
+
const abs = path.resolve(importDir, rel);
|
|
54
|
+
const inside = path.relative(importDir, abs);
|
|
55
|
+
if (!inside || inside.startsWith('..') || path.isAbsolute(inside))
|
|
56
|
+
return null;
|
|
57
|
+
try {
|
|
58
|
+
return fs.statSync(abs).isFile() ? abs : null;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The hook module `imports/<alias>` declares, or null when it declares none or
|
|
66
|
+
* the path it names is not usable. Read from the copy ON DISK, which is the
|
|
67
|
+
* incoming version -- an update's hook is the new code's own migration, so it
|
|
68
|
+
* has to be the new copy's.
|
|
69
|
+
*/
|
|
70
|
+
export function findImportUpdateHook(deckDir, alias) {
|
|
71
|
+
const importDir = path.join(deckDir, IMPORTS_DIR, alias);
|
|
72
|
+
const declared = readCastleJson(importDir)?.onUpdate;
|
|
73
|
+
if (typeof declared !== 'string' || !declared.trim())
|
|
74
|
+
return null;
|
|
75
|
+
const resolved = resolveHookModule(importDir, declared);
|
|
76
|
+
if (!resolved) {
|
|
77
|
+
console.warn(`"${alias}" declares an update hook at "${declared}", which is not a file inside it -- skipping it.`);
|
|
78
|
+
}
|
|
79
|
+
return resolved;
|
|
80
|
+
}
|
|
81
|
+
function outputLines(text) {
|
|
82
|
+
return text.split('\n').map((line) => line.trimEnd()).filter(Boolean);
|
|
83
|
+
}
|
|
84
|
+
// The last few lines of stderr are what says WHY a hook failed; the whole stack
|
|
85
|
+
// of a 200-line module is not.
|
|
86
|
+
function failureDetail(e) {
|
|
87
|
+
const stderr = e?.stderr ?? '';
|
|
88
|
+
const tail = outputLines(stderr).slice(-8).join('\n');
|
|
89
|
+
if (tail)
|
|
90
|
+
return tail;
|
|
91
|
+
if (e?.killed)
|
|
92
|
+
return `it did not finish in ${hookTimeoutMs()}ms`;
|
|
93
|
+
return e instanceof Error ? e.message : String(e);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Save a version, run the hook, and put the deck's files back if it fails.
|
|
97
|
+
*
|
|
98
|
+
* A child process rather than an in-process `import()`: `updateImport` is called
|
|
99
|
+
* from inside the running serve, and a child buys a fresh module graph on every
|
|
100
|
+
* run (so a rewritten hook is the one that runs), a timeout, and isolation from
|
|
101
|
+
* a `process.exit` in kit code -- none of which are available in-process.
|
|
102
|
+
*
|
|
103
|
+
* The version is the recovery path, and it is saved even when the hook is about
|
|
104
|
+
* to succeed: a migration that ran correctly and is not what the creator wanted
|
|
105
|
+
* is the same problem as one that ran wrong.
|
|
106
|
+
*/
|
|
107
|
+
export async function runImportUpdateHook(hook, log) {
|
|
108
|
+
const { version } = createVersion(hook.deckDir, {
|
|
109
|
+
message: `before ${hook.alias} update ${hook.from} -> ${hook.to}`,
|
|
110
|
+
});
|
|
111
|
+
// A deck with nothing outstanding records no new version, and does not need
|
|
112
|
+
// one: head already describes the tree the hook is about to change. Either
|
|
113
|
+
// way there is one id to name, and naming it is the whole recovery story.
|
|
114
|
+
const restorePoint = version?.id ?? readHead(hook.deckDir);
|
|
115
|
+
if (restorePoint) {
|
|
116
|
+
const lead = version
|
|
117
|
+
? `Saved version ${restorePoint}`
|
|
118
|
+
: `This deck is already saved at version ${restorePoint}`;
|
|
119
|
+
log(`${lead} before letting ${hook.alias} migrate this deck's files ` +
|
|
120
|
+
`(\`castle-web restore-version ${restorePoint}\` puts them back).`);
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const { stdout, stderr } = await execFileAsync(process.execPath, [RUNNER, hook.modulePath, JSON.stringify(childContext(hook))], { cwd: hook.deckDir, timeout: hookTimeoutMs(), maxBuffer: MAX_HOOK_OUTPUT });
|
|
124
|
+
for (const line of [...outputLines(stdout), ...outputLines(stderr)]) {
|
|
125
|
+
log(`${hook.alias} hook: ${line}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
// The version above is head, so head describes the deck as the hook found
|
|
130
|
+
// it -- whatever it managed to write goes away.
|
|
131
|
+
const discarded = discardPendingChanges(hook.deckDir);
|
|
132
|
+
const undone = discarded.length > 0 ? ` Undid ${discarded.length} file write(s).` : '';
|
|
133
|
+
throw new Error(`${hook.alias}'s update hook failed.${undone}\n${failureDetail(e)}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The child process one import's `onUpdate` hook runs in. Why a child at all is
|
|
3
|
+
// in importUpdateHook.ts; this is only the entry point.
|
|
4
|
+
//
|
|
5
|
+
// argv: the hook module's absolute path, then its context as JSON. `log` is
|
|
6
|
+
// supplied here rather than serialized, because a function cannot cross the
|
|
7
|
+
// process boundary -- the parent reads stdout back and labels it.
|
|
8
|
+
import { pathToFileURL } from 'url';
|
|
9
|
+
async function main() {
|
|
10
|
+
const [modulePath, contextJson] = process.argv.slice(2);
|
|
11
|
+
if (!modulePath || !contextJson) {
|
|
12
|
+
throw new Error('usage: importUpdateHookRunner <module> <contextJson>');
|
|
13
|
+
}
|
|
14
|
+
const mod = (await import(pathToFileURL(modulePath).href));
|
|
15
|
+
if (typeof mod.default !== 'function') {
|
|
16
|
+
throw new Error(`${modulePath} does not default-export a function.`);
|
|
17
|
+
}
|
|
18
|
+
const hook = mod.default;
|
|
19
|
+
await hook({ ...JSON.parse(contextJson), log: (message) => console.log(message) });
|
|
20
|
+
}
|
|
21
|
+
main().catch((e) => {
|
|
22
|
+
console.error(e instanceof Error ? (e.stack ?? e.message) : String(e));
|
|
23
|
+
process.exit(1);
|
|
24
|
+
});
|
package/dist/imports.js
CHANGED
|
@@ -7,7 +7,8 @@ import { normalizeDeckPackageJson } from './normalize.js';
|
|
|
7
7
|
import { getKitsDir } from './localPaths.js';
|
|
8
8
|
import { SDK_PACKAGE } from './sdkResolve.js';
|
|
9
9
|
import { writePlatformDocs } from './platformDoc.js';
|
|
10
|
-
import {
|
|
10
|
+
import { findImportUpdateHook, runImportUpdateHook, } from './importUpdateHook.js';
|
|
11
|
+
import { IMPORTS_DIR, IMPORT_VERSION_FILE, STARTER_THEME_FILES, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
|
|
11
12
|
// Adding another deck as a dependency (`castle-web add-import`; removing one is a
|
|
12
13
|
// later command). Deliberately NOT `get-deck`: that one
|
|
13
14
|
// replaces THIS deck's own source from the server (and carries guards for the
|
|
@@ -642,8 +643,7 @@ export async function addImport(dir, options = {}) {
|
|
|
642
643
|
// from the deck root only -- it is the creator's file, like scenes/ -- so
|
|
643
644
|
// without this, decks scaffolded before the kit shipped one would never get
|
|
644
645
|
// it. Never overwrites: a deck that has the file keeps it, whatever the kit
|
|
645
|
-
// ships.
|
|
646
|
-
// shows in the Files tree (the same courtesy mkdir/upload extend).
|
|
646
|
+
// ships.
|
|
647
647
|
function seedKitTheme(deckDir, alias, log) {
|
|
648
648
|
const importDir = path.join(deckDir, IMPORTS_DIR, alias);
|
|
649
649
|
// Only kits (imports that declare an entry in castle.json `main`) seed deck
|
|
@@ -665,17 +665,60 @@ function seedKitTheme(deckDir, alias, log) {
|
|
|
665
665
|
console.warn(`Could not seed ${name} from ${alias}: ${e instanceof Error ? e.message : String(e)}`);
|
|
666
666
|
continue;
|
|
667
667
|
}
|
|
668
|
-
ensureVisibleGlob(deckDir, name, name);
|
|
669
668
|
seeded.push(name);
|
|
670
669
|
}
|
|
671
670
|
if (seeded.length === 0)
|
|
672
671
|
return;
|
|
673
672
|
log(`Seeded ${seeded.join(' + ')} from ${alias} (new in this version; the deck's to edit)`);
|
|
674
673
|
}
|
|
674
|
+
// An update's hook, if the incoming copy declares one and the account gate lets
|
|
675
|
+
// it run. The gate is the same leash `autoUpdateImports` is under, for a bigger
|
|
676
|
+
// reason: a hook is code from another deck writing THIS deck's files. Resolved
|
|
677
|
+
// lazily -- `autoUpdateImports` has already answered the question, and
|
|
678
|
+
// `updateImport` must not pay a lookup for the overwhelming majority of updates
|
|
679
|
+
// that carry no hook at all.
|
|
680
|
+
//
|
|
681
|
+
// Untrusted plus a hook keeps the update and skips the hook: the files are
|
|
682
|
+
// already in place and refetching them is what the person asked for, so the
|
|
683
|
+
// honest outcome is new code against un-migrated data, said out loud.
|
|
684
|
+
async function resolveUpdateHook(deckDir, alias, update, to, log) {
|
|
685
|
+
const modulePath = findImportUpdateHook(deckDir, alias);
|
|
686
|
+
if (!modulePath)
|
|
687
|
+
return null;
|
|
688
|
+
const trusted = update.trusted ?? (await importIsOnTrustedAccount(update.deckId));
|
|
689
|
+
if (!trusted) {
|
|
690
|
+
log(`${alias} ships an update hook, which only runs for imports on the ${AUTO_UPDATE_ACCOUNT} ` +
|
|
691
|
+
`account -- skipped. Its new files are in place; this deck's own files were not migrated.`);
|
|
692
|
+
return null;
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
modulePath,
|
|
696
|
+
deckDir,
|
|
697
|
+
importDir: path.join(deckDir, IMPORTS_DIR, alias),
|
|
698
|
+
alias,
|
|
699
|
+
from: update.from,
|
|
700
|
+
to,
|
|
701
|
+
};
|
|
702
|
+
}
|
|
675
703
|
async function applyImportUpdate(deckDir, alias, update, source, log) {
|
|
676
704
|
await placeImport(deckDir, alias, update.deckId, source, update.via);
|
|
677
705
|
log(`Updated ${alias} (${update.from} -> ${source.updatedAt})`);
|
|
706
|
+
const hook = await resolveUpdateHook(deckDir, alias, update, source.updatedAt, log);
|
|
707
|
+
// Before the hook, so a migration sees the deck the new code will run
|
|
708
|
+
// against, seeded files included.
|
|
678
709
|
seedKitTheme(deckDir, alias, log);
|
|
710
|
+
if (hook) {
|
|
711
|
+
try {
|
|
712
|
+
await runImportUpdateHook(hook, log);
|
|
713
|
+
}
|
|
714
|
+
catch (e) {
|
|
715
|
+
// Put the import back at the version whose data this deck still has. The
|
|
716
|
+
// hook already rolled the deck's own files back, so the pair stays
|
|
717
|
+
// consistent -- old kit, old data -- and the caller reports why.
|
|
718
|
+
revertImport(deckDir, alias, log);
|
|
719
|
+
throw e;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
679
722
|
// Its own dependencies may have moved too.
|
|
680
723
|
const transitive = await addTransitiveImports(deckDir, alias, importedDeckIds(deckDir));
|
|
681
724
|
for (const t of transitive)
|
|
@@ -762,7 +805,10 @@ export async function autoUpdateImports(deckDir) {
|
|
|
762
805
|
// current version, so a marker that doesn't match is reason to refetch.
|
|
763
806
|
if (source.updatedAt === pin.version && importFilesMatchPin(deckDir, alias, pin))
|
|
764
807
|
continue;
|
|
765
|
-
await applyImportUpdate(deckDir, alias,
|
|
808
|
+
await applyImportUpdate(deckDir, alias,
|
|
809
|
+
// The account gate is already satisfied above, so an `onUpdate` hook
|
|
810
|
+
// does not pay for the same lookup a second time.
|
|
811
|
+
{ deckId: pin.deckId, from: pin.version, via: pin.via, trusted: true }, source, (message) => console.log(`auto-update: ${message}`));
|
|
766
812
|
updated.push({ alias, from: pin.version, to: source.updatedAt });
|
|
767
813
|
}
|
|
768
814
|
catch (e) {
|
|
@@ -799,7 +845,7 @@ export async function updateImport(dir, options = {}) {
|
|
|
799
845
|
}
|
|
800
846
|
if (options.revert) {
|
|
801
847
|
for (const alias of aliases)
|
|
802
|
-
revertImport(deckDir, alias);
|
|
848
|
+
revertImport(deckDir, alias, (message) => console.log(message));
|
|
803
849
|
await installAddedDependencies(deckDir, syncImportDependencies(deckDir));
|
|
804
850
|
writePlatformDocs(deckDir);
|
|
805
851
|
return;
|
|
@@ -850,8 +896,10 @@ export async function updateImport(dir, options = {}) {
|
|
|
850
896
|
writePlatformDocs(deckDir);
|
|
851
897
|
console.log('Play the deck to check the update before saving; `--revert` puts the old version back.');
|
|
852
898
|
}
|
|
853
|
-
// Restore the copy taken when this import was last replaced.
|
|
854
|
-
|
|
899
|
+
// Restore the copy taken when this import was last replaced. `log` labels the
|
|
900
|
+
// lines, because this is reached both from `--revert` (bare) and from an update
|
|
901
|
+
// whose hook failed (where the caller is already prefixing its output).
|
|
902
|
+
function revertImport(deckDir, alias, log) {
|
|
855
903
|
const backup = backupPath(deckDir, alias);
|
|
856
904
|
if (!fs.existsSync(backup)) {
|
|
857
905
|
console.error(`No previous version of "${alias}" is kept here -- nothing to revert to.`);
|
|
@@ -883,8 +931,8 @@ function revertImport(deckDir, alias) {
|
|
|
883
931
|
fs.rmSync(backup, { recursive: true, force: true });
|
|
884
932
|
lockImportTree(destDir);
|
|
885
933
|
clearStatusCache(deckDir);
|
|
886
|
-
|
|
934
|
+
log(`Reverted ${alias} to its previous version.`);
|
|
887
935
|
if (!fs.existsSync(path.join(destDir, IMPORT_VERSION_FILE))) {
|
|
888
|
-
|
|
936
|
+
log(`That copy predates version records; run \`castle-web update-import ${alias}\` to refetch it before it can be published.`);
|
|
889
937
|
}
|
|
890
938
|
}
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,9 @@ import { check } from './check.js';
|
|
|
13
13
|
import { forkImportFile, revertImportFile } from './forks.js';
|
|
14
14
|
import { connectWS, takeScreenshot } from './preview.js';
|
|
15
15
|
import { listVersions, restoreVersion, saveVersion, showVersion } from './versions.js';
|
|
16
|
+
import { getKitsDir } from './localPaths.js';
|
|
17
|
+
import * as api from './api.js';
|
|
18
|
+
import * as config from './config.js';
|
|
16
19
|
const args = process.argv.slice(2);
|
|
17
20
|
const command = args[0];
|
|
18
21
|
const FLAGS_WITH_VALUES = new Set([
|
|
@@ -91,10 +94,49 @@ function getServeSocketPort(dir) {
|
|
|
91
94
|
return fromServe;
|
|
92
95
|
return 3738;
|
|
93
96
|
}
|
|
97
|
+
const FALLBACK_KITS = [
|
|
98
|
+
'base',
|
|
99
|
+
'multiplayer-2d',
|
|
100
|
+
'multiplayer-3d',
|
|
101
|
+
'physics-2d',
|
|
102
|
+
'physics-3d',
|
|
103
|
+
'real-time',
|
|
104
|
+
'turn-based',
|
|
105
|
+
];
|
|
106
|
+
const KIT_DESCRIPTIONS = {
|
|
107
|
+
base: 'Library kit: shared SDK, editor host, and authoring guide imported by every deck.',
|
|
108
|
+
'multiplayer-2d': 'Real-time multiplayer over physics-2d: a shared matter world with an authoritative server already written.',
|
|
109
|
+
'multiplayer-3d': 'Real-time multiplayer over physics-3d: a shared rapier world with an authoritative server already written.',
|
|
110
|
+
'physics-2d': 'Actor / behavior / scene framework for 2D games with matter-js physics. Default if --kit is omitted.',
|
|
111
|
+
'physics-3d': 'The same model in 3D with three.js rendering, rapier physics, and scene and model editors.',
|
|
112
|
+
'real-time': 'Library kit: shared transport, clock, smoothing, ownership, and session process for the multiplayer kits.',
|
|
113
|
+
'turn-based': 'Seats, spectators, and reconnects for games where players take turns, over physics-2d.',
|
|
114
|
+
};
|
|
115
|
+
function availableKits() {
|
|
116
|
+
try {
|
|
117
|
+
const kitsDir = getKitsDir();
|
|
118
|
+
return fs
|
|
119
|
+
.readdirSync(kitsDir, { withFileTypes: true })
|
|
120
|
+
.filter((entry) => entry.isDirectory())
|
|
121
|
+
.map((entry) => entry.name)
|
|
122
|
+
.sort();
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return FALLBACK_KITS;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
94
128
|
function usage() {
|
|
129
|
+
const kits = availableKits();
|
|
130
|
+
const scaffoldKits = kits.filter((kit) => kit !== 'base' && kit !== 'real-time');
|
|
131
|
+
const initKits = [...scaffoldKits, 'none'].join(', ');
|
|
132
|
+
const kitNameWidth = Math.max('none'.length, ...kits.map((kit) => kit.length));
|
|
133
|
+
const kitLines = [
|
|
134
|
+
...kits.map((kit) => ` ${kit.padEnd(kitNameWidth)} ${KIT_DESCRIPTIONS[kit] ?? 'Scaffold kit.'}`),
|
|
135
|
+
` ${'none'.padEnd(kitNameWidth)} Minimal vite + canvas setup with the castle-web SDK and no kit.`,
|
|
136
|
+
].join('\n');
|
|
95
137
|
console.log(`Usage:
|
|
96
|
-
castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME] (kits:
|
|
97
|
-
castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] (starts from a published deck instead of a kit)
|
|
138
|
+
castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME] [--port PORT] (kits: ${initKits}; default physics-2d)
|
|
139
|
+
castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] [--port PORT] (starts from a published deck instead of a kit)
|
|
98
140
|
castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
|
|
99
141
|
castle-web restart [--port PORT]
|
|
100
142
|
castle-web screenshot [--out FILE] [--port PORT]
|
|
@@ -106,18 +148,17 @@ function usage() {
|
|
|
106
148
|
castle-web revert-import-file <imports/...> [dir]
|
|
107
149
|
castle-web update-import [alias] [dir] [--check] [--revert] (re-fetches imports; no alias means all)
|
|
108
150
|
castle-web install [dir]
|
|
109
|
-
castle-web check [dir] (bundles the deck, the same
|
|
151
|
+
castle-web check [dir] (bundles the deck and its server, the same builds save-deck runs)
|
|
110
152
|
castle-web save-version [-m MESSAGE] [paths...] [--dir DIR] (no paths saves the whole deck)
|
|
111
153
|
castle-web list-versions [version] [--dir DIR] (defaults to the latest version)
|
|
112
154
|
castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
|
|
113
155
|
castle-web restore-version <version> [--force] [--dir DIR]
|
|
114
156
|
castle-web login
|
|
157
|
+
castle-web whoami
|
|
115
158
|
castle-web --version
|
|
116
159
|
|
|
117
160
|
Kits:
|
|
118
|
-
|
|
119
|
-
physics-3d The same model in 3D: three.js rendering and rapier physics, with a scene editor and a model editor. Built on physics-2d, which it imports.
|
|
120
|
-
none Minimal vite + canvas setup with the castle-web SDK and no kit.
|
|
161
|
+
${kitLines}
|
|
121
162
|
|
|
122
163
|
After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide.`);
|
|
123
164
|
process.exit(1);
|
|
@@ -134,13 +175,14 @@ async function main() {
|
|
|
134
175
|
case 'init': {
|
|
135
176
|
const dir = findPositionalDir();
|
|
136
177
|
if (dir === '.') {
|
|
137
|
-
console.error('Usage: castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME | --remix DECK_ID]');
|
|
178
|
+
console.error('Usage: castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME | --remix DECK_ID] [--port PORT]');
|
|
138
179
|
process.exit(1);
|
|
139
180
|
}
|
|
140
181
|
const kit = getFlagValue('--kit');
|
|
141
182
|
await init(dir, {
|
|
142
183
|
kit,
|
|
143
184
|
serve: !hasFlag('--no-serve'),
|
|
185
|
+
port: getFlagValue('--port'),
|
|
144
186
|
remixOf: getFlagValue('--remix'),
|
|
145
187
|
// The identity the server minted for this remix. Omitted outside the
|
|
146
188
|
// cloud flow, where the next save-deck creates a deck of its own.
|
|
@@ -301,6 +343,15 @@ async function main() {
|
|
|
301
343
|
case 'login':
|
|
302
344
|
await login();
|
|
303
345
|
break;
|
|
346
|
+
case 'whoami': {
|
|
347
|
+
if (!config.getToken())
|
|
348
|
+
throw new Error('Not logged in. Run `castle-web login`.');
|
|
349
|
+
const user = await api.whoAmI();
|
|
350
|
+
if (!user)
|
|
351
|
+
throw new Error('Not logged in. Run `castle-web login`.');
|
|
352
|
+
console.log(`Logged in as @${user.username} (userId: ${user.userId})`);
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
304
355
|
default:
|
|
305
356
|
usage();
|
|
306
357
|
}
|
package/dist/init.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export declare function retargetBareClaudeMd(deckDir: string, alias: string): vo
|
|
|
17
17
|
export declare function init(dir: string, opts?: {
|
|
18
18
|
kit?: string;
|
|
19
19
|
serve?: boolean;
|
|
20
|
+
port?: string;
|
|
20
21
|
/** Remix this published deck instead of starting from a kit. */
|
|
21
22
|
remixOf?: string;
|
|
22
23
|
/** The identity the server already minted for this new deck. */
|