castle-web-cli 0.4.134 → 0.4.136

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.
@@ -14,6 +14,7 @@ export interface CastleJson {
14
14
  agent?: {
15
15
  plan?: 'on' | 'off';
16
16
  };
17
+ importWhenRemixed?: boolean;
17
18
  starterScene?: string;
18
19
  [key: string]: unknown;
19
20
  }
package/dist/index.js CHANGED
@@ -88,6 +88,7 @@ function getWsPort(dir) {
88
88
  function usage() {
89
89
  console.log(`Usage:
90
90
  castle-web init <dir> [--kit NAME] (kits: physics-2d (default), physics-3d, none)
91
+ castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] (starts from a published deck instead of a kit)
91
92
  castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
92
93
  castle-web restart [--port PORT]
93
94
  castle-web screenshot [--out FILE] [--port PORT]
@@ -124,11 +125,19 @@ async function main() {
124
125
  case 'init': {
125
126
  const dir = findPositionalDir();
126
127
  if (dir === '.') {
127
- console.error('Usage: castle-web init <dir> [--kit NAME]');
128
+ console.error('Usage: castle-web init <dir> [--kit NAME | --remix DECK_ID]');
128
129
  process.exit(1);
129
130
  }
130
131
  const kit = getFlagValue('--kit');
131
- await init(dir, { kit, serve: !hasFlag('--no-serve') });
132
+ await init(dir, {
133
+ kit,
134
+ serve: !hasFlag('--no-serve'),
135
+ remixOf: getFlagValue('--remix'),
136
+ // The identity the server minted for this remix. Omitted outside the
137
+ // cloud flow, where the next save-deck creates a deck of its own.
138
+ deckId: getFlagValue('--deck-id'),
139
+ cardId: getFlagValue('--card-id'),
140
+ });
132
141
  break;
133
142
  }
134
143
  case 'serve': {
package/dist/init.d.ts CHANGED
@@ -13,4 +13,9 @@ export declare function writeStarterTheme(projectDir: string, kitDir: string): v
13
13
  export declare function init(dir: string, opts?: {
14
14
  kit?: string;
15
15
  serve?: boolean;
16
+ /** Remix this published deck instead of starting from a kit. */
17
+ remixOf?: string;
18
+ /** The identity the server already minted for a remix. */
19
+ deckId?: string;
20
+ cardId?: string;
16
21
  }): Promise<void>;
package/dist/init.js CHANGED
@@ -3,7 +3,8 @@ import * as path from 'path';
3
3
  import { COMMON_INSTRUCTIONS } from './commonInstructions.js';
4
4
  import { installDeps } from './install.js';
5
5
  import { deckMainFile, deckStarterScene } from './castleJson.js';
6
- import { IMPORTS_DIR, lockImportTree } from './imports.js';
6
+ import { addImportTo, IMPORTS_DIR, lockImportTree } from './imports.js';
7
+ import { discardParentSource, fetchParentSource, unpackParentSource, writeRemixIdentity, } from './remix.js';
7
8
  import { getCliEntryPath, getKitsDir, getRepoRoot, getSdkPackagePath, toPosixPath, } from './localPaths.js';
8
9
  import { serve } from './serve.js';
9
10
  import { createVersion } from './versions.js';
@@ -457,6 +458,26 @@ function scaffoldFromKitImport(kit, projectDir) {
457
458
  // This is the ordinary save path with no parent -- `parentId: null` and every
458
459
  // file as an addition -- so the store has no special case for it. It composes
459
460
  // with the no-op rule for free: `save-version` straight after init records
461
+ // The import branch is deliberately thin: `addImportTo` already adopts a bare
462
+ // deck's entry point, starter scene and theme.
463
+ async function scaffoldFromRemix(parentDeckId, projectDir, identity) {
464
+ const source = await fetchParentSource(parentDeckId);
465
+ const imported = source.castleJson.importWhenRemixed === true;
466
+ try {
467
+ if (imported) {
468
+ scaffoldBare(projectDir);
469
+ await addImportTo(projectDir, { deckRef: parentDeckId });
470
+ }
471
+ else {
472
+ await unpackParentSource(source, projectDir);
473
+ }
474
+ }
475
+ finally {
476
+ discardParentSource(source);
477
+ }
478
+ writeRemixIdentity(projectDir, identity);
479
+ console.log(`Created project in ${projectDir}/ (${imported ? 'importing' : 'copied from'} deck ${parentDeckId})`);
480
+ }
460
481
  // nothing, so a fresh deck has exactly one version.
461
482
  //
462
483
  // The message is the only place a deck's kit lineage is recorded at all.
@@ -483,15 +504,27 @@ export async function init(dir, opts = {}) {
483
504
  console.error(`Directory "${dir}" is not empty.`);
484
505
  process.exit(1);
485
506
  }
507
+ if (opts.remixOf && opts.kit) {
508
+ console.error('Pass either --remix or --kit, not both.');
509
+ process.exit(1);
510
+ }
486
511
  const kit = opts.kit ?? DEFAULT_KIT;
487
512
  const bare = kit === 'none' || kit === 'bare';
488
- if (bare) {
513
+ if (opts.remixOf) {
514
+ await scaffoldFromRemix(opts.remixOf, projectDir, {
515
+ deckId: opts.deckId,
516
+ cardId: opts.cardId,
517
+ });
518
+ }
519
+ else if (bare) {
489
520
  scaffoldBare(projectDir);
490
521
  }
491
522
  else {
492
523
  scaffoldFromKitImport(kit, projectDir);
493
524
  }
494
- console.log(`Created project in ${projectDir}/${bare ? '' : ` (from kit "${kit}")`}`);
525
+ if (!opts.remixOf) {
526
+ console.log(`Created project in ${projectDir}/${bare ? '' : ` (from kit "${kit}")`}`);
527
+ }
495
528
  // Always install deps so the deck is ready to serve/edit immediately.
496
529
  // `--no-serve` only skips the serve step below (callers like the cloud
497
530
  // launcher run their own serve, but still want deps in place).
@@ -514,7 +547,7 @@ export async function init(dir, opts = {}) {
514
547
  catch {
515
548
  console.error('dependency install failed; re-run `pnpm install` (or `npm install`) in the deck.');
516
549
  }
517
- saveInitialVersion(projectDir, bare ? null : kit);
550
+ saveInitialVersion(projectDir, opts.remixOf ?? (bare ? null : kit));
518
551
  const autoServe = opts.serve !== false;
519
552
  if (autoServe && installed) {
520
553
  // Call serve() with detach so init returns once the server is up. serve()
@@ -0,0 +1,27 @@
1
+ import type { CastleJson } from './castleJson.js';
2
+ export interface RemixIdentity {
3
+ deckId?: string;
4
+ /** Without this a later save-deck mints a second card. */
5
+ cardId?: string;
6
+ }
7
+ export interface ParentSource {
8
+ /** The downloaded archive, on disk. Delete it with `discardParentSource`. */
9
+ archivePath: string;
10
+ /** The parent's own castle.json, read out of the archive without unpacking it. */
11
+ castleJson: CastleJson;
12
+ }
13
+ /**
14
+ * Fetch the parent's saved source and read its castle.json out of the tarball.
15
+ * Nothing is unpacked yet: whether these files are wanted at all depends on the
16
+ * `importWhenRemixed` in that castle.json.
17
+ */
18
+ export declare function fetchParentSource(parentDeckId: string): Promise<ParentSource>;
19
+ export declare function discardParentSource(source: ParentSource): void;
20
+ /** Unpack straight into the deck dir, the way get-deck does. */
21
+ export declare function unpackParentSource(source: ParentSource, projectDir: string): Promise<void>;
22
+ /**
23
+ * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
24
+ * whatever else the deck owns. With no identity passed (a local `init --remix`),
25
+ * the next save-deck creates a fresh deck with no lineage.
26
+ */
27
+ export declare function writeRemixIdentity(projectDir: string, identity?: RemixIdentity): void;
package/dist/remix.js ADDED
@@ -0,0 +1,82 @@
1
+ import * as fs from 'fs';
2
+ import * as os from 'os';
3
+ import * as path from 'path';
4
+ import { nanoid } from 'nanoid';
5
+ import * as api from './api.js';
6
+ import { runTar } from './save-deck.js';
7
+ // Scaffolding a deck from another published deck, for `init --remix`.
8
+ // Dropped from the copied castle.json. `autoUpdateWhenImported` is the parent's
9
+ // promise to ITS importers, which a remix hasn't made.
10
+ const PARENT_ONLY_KEYS = [
11
+ 'deckId',
12
+ 'cardId',
13
+ 'title',
14
+ 'caption',
15
+ 'publishedVersion',
16
+ 'autoUpdateWhenImported',
17
+ ];
18
+ function parseJson(text) {
19
+ try {
20
+ return JSON.parse(text);
21
+ }
22
+ catch {
23
+ return {};
24
+ }
25
+ }
26
+ /**
27
+ * Fetch the parent's saved source and read its castle.json out of the tarball.
28
+ * Nothing is unpacked yet: whether these files are wanted at all depends on the
29
+ * `importWhenRemixed` in that castle.json.
30
+ */
31
+ export async function fetchParentSource(parentDeckId) {
32
+ const source = await api.webDeckSource(parentDeckId);
33
+ if (!source) {
34
+ console.error(`Deck ${parentDeckId} has no saved source to remix. Only decks saved by the web CLI can be remixed.`);
35
+ process.exit(1);
36
+ }
37
+ console.log(`Fetching ${source.archiveUrl}`);
38
+ const res = await fetch(source.archiveUrl, { signal: AbortSignal.timeout(60000) });
39
+ if (!res.ok) {
40
+ throw new Error(`Archive fetch failed: HTTP ${res.status}`);
41
+ }
42
+ const buf = Buffer.from(await res.arrayBuffer());
43
+ console.log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
44
+ // Read and untarred out of, never moved out of: in a sandbox the deck is on a
45
+ // different filesystem from tmp, and a rename across that is EXDEV.
46
+ const archivePath = path.join(os.tmpdir(), `castle-remix-${nanoid(8)}.tar.gz`);
47
+ fs.writeFileSync(archivePath, buf);
48
+ // `./castle.json`, because archiveSource packs with `-C <dir> .`.
49
+ const text = await runTar(['-xzOf', archivePath, './castle.json'], { capture: true });
50
+ return { archivePath, castleJson: parseJson(text) };
51
+ }
52
+ export function discardParentSource(source) {
53
+ try {
54
+ fs.unlinkSync(source.archivePath);
55
+ }
56
+ catch {
57
+ /* nothing to clean */
58
+ }
59
+ }
60
+ /** Unpack straight into the deck dir, the way get-deck does. */
61
+ export async function unpackParentSource(source, projectDir) {
62
+ fs.mkdirSync(projectDir, { recursive: true });
63
+ await runTar(['-xzf', source.archivePath, '-C', projectDir]);
64
+ }
65
+ /**
66
+ * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
67
+ * whatever else the deck owns. With no identity passed (a local `init --remix`),
68
+ * the next save-deck creates a fresh deck with no lineage.
69
+ */
70
+ export function writeRemixIdentity(projectDir, identity = {}) {
71
+ const file = path.join(projectDir, 'castle.json');
72
+ const existing = fs.existsSync(file) ? parseJson(fs.readFileSync(file, 'utf-8')) : {};
73
+ const next = { ...existing };
74
+ for (const key of PARENT_ONLY_KEYS)
75
+ delete next[key];
76
+ if (identity.deckId)
77
+ next.deckId = identity.deckId;
78
+ if (identity.cardId)
79
+ next.cardId = identity.cardId;
80
+ fs.mkdirSync(projectDir, { recursive: true });
81
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n', 'utf-8');
82
+ }
@@ -26,9 +26,134 @@ Do you already know what you want to make, or do you want to figure it out toget
26
26
  - This kit is plain JavaScript. Use `.jsx` for files with JSX, `.js` otherwise; do not add TypeScript files or a new build step.
27
27
  - Do not reload the deck after an edit. Nothing auto-reloads any more: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control.
28
28
  - Space is reserved by the editor for play/stop; do not bind Space to gameplay.
29
- - Do not read `engine/`, `editors/`, or built-in behaviors (`Layout.jsx`, `Sprite.jsx`, `Collider.jsx`, `Camera.jsx`, and the physics ones — `RigidBody.jsx`, `Joints.jsx`, `Draggable.jsx`, `Slingshot.jsx`, `AnalogStick.jsx`) to build a game. Their public API is documented below.
29
+ - Do not read `engine/`, `editors/`, or built-in behaviors (`Layout.jsx`, `Sprite.jsx`, `Collider.jsx`, `Camera.jsx`, and the physics ones — `RigidBody.jsx`, `Joints.jsx`, `Draggable.jsx`, `Slingshot.jsx`, `AnalogStick.jsx`) to build a game. Their public API is documented below. Forking is the exception: when you're deliberately copying a kit file into the deck to change it — an editor (see `## Editors`) or a behavior you're shadowing — read the original. `engine/` stays off-limits either way.
30
+ - The deck can define its own editors: declare a file type in `castle.json` (`editor.fileTypes`: ext, label, icon, and an `editors/` module) and the Files panel opens that type in it — whole recipe in `## Editors` below. Kit editors under `imports/` are read-only; add or fork, don't edit.
31
+ - An editor is for content FILES the creator keeps coming back to (catalogs, dialogue, level tables) that nothing already opens. Scenes, sprites and styles have editors; per-actor settings belong on behavior props in the inspector — not in a new editor.
32
+ - Unprompted, an editor is an offer, never a build: when the same data keeps getting edited by hand, propose one and build on the user's yes. Never during a first build.
30
33
  - Details below: `## Behavior shape`, `## Scene file`, `## Blueprints`, `## Built-in behaviors`, `## Creating pixel art`, `## SceneRuntime API`, and `## Input shortcuts`.
31
34
 
35
+ ## Editors
36
+
37
+ An editor is a visual authoring surface for a file type — the scene editor
38
+ and sprite editor are just this mechanism used by the kit. The deck can add
39
+ its own: declare a file type in `castle.json`, write one React component, and
40
+ the Files panel opens that type in your editor with a code/visual toggle.
41
+ Reach for one when the deck accumulates content someone will keep iterating
42
+ on by hand — level layouts, dialogue, item or word catalogs, tuning values —
43
+ where editing raw JSON in the code editor is the bottleneck.
44
+
45
+ ### The three steps
46
+
47
+ 1. **Declare the type** in the deck's own `castle.json` under
48
+ `editor.fileTypes`:
49
+
50
+ ```json
51
+ "editor": {
52
+ "fileTypes": [
53
+ { "ext": ".dialogue", "label": "Dialogue", "new": "New dialogue",
54
+ "icon": "file", "editor": "editors/DialogueEditor.jsx", "data": "json" }
55
+ ]
56
+ }
57
+ ```
58
+
59
+ These are ALL the fields that exist — do not invent others:
60
+ - `ext` — the extension, with the dot. One entry per extension.
61
+ - `label` — display name in the tab and pickers.
62
+ - `new` — the entry in the Files panel's New menu; omit it and the type
63
+ can't be created there.
64
+ - `icon` — for that entry and the file's tree row. Use one the kit types
65
+ already use: `globe`, `layer-group`, `code`, `file`, `image`, `music`,
66
+ `film`. An unknown name falls back to a generic icon.
67
+ - `editor` — the module that edits this type, as a path from the deck
68
+ root, and it MUST live under `editors/` (that directory is the only
69
+ place the loader looks). Omit it to leave the type to the builtin code
70
+ editor. (The value `"kit"` is legacy — always name the module.)
71
+ - `data` — how the file behaves when a module imports it: `"json"` (a
72
+ module import yields the parsed object) or `"text"` (the raw string).
73
+ Omit for an ordinary JS module. Data files are the normal case for
74
+ editor-owned content.
75
+ - `unsupported` — a refusal: why this deck must NOT be built on this
76
+ format, shown when someone tries to upload one. Only for formats you
77
+ recognize and reject.
78
+
79
+ 2. **Write the module** at the declared path, default-exporting a component:
80
+
81
+ ```jsx
82
+ // editors/DialogueEditor.jsx
83
+ const EMPTY = { lines: [] };
84
+
85
+ export default function DialogueEditor({ path, text, onChange }) {
86
+ let doc;
87
+ try { doc = text.trim() ? JSON.parse(text) : EMPTY; } catch { doc = EMPTY; }
88
+ const save = (next) => onChange(JSON.stringify(next, null, 2));
89
+ // ...render doc, call save(next) on every edit...
90
+ }
91
+ ```
92
+
93
+ Props: `path` (deck-relative file path), `text` (current file text),
94
+ `onChange(nextText)` (replaces the whole file; the host debounces the
95
+ write and flushes before a restart — call it on every edit, don't build
96
+ your own save button), `files` (live map of every deck text file,
97
+ path → text), and `onChangeFile(path, nextText)` (edit another file, e.g.
98
+ a sub-document — same debounced save).
99
+
100
+ 3. **Make it visible.** If the deck's `castle.json` has
101
+ `editor.visiblePaths`, add your content directory (e.g. `"dialogue/**"`)
102
+ or the files won't appear in the Files panel. A brand-new editor module
103
+ is not in the loader's glob until the panel reloads — the person's next
104
+ reload picks it up; do not force one.
105
+
106
+ That's the whole integration: no entry-point changes, no registration call.
107
+ The kit's editor host dispatches any declared module, including ones the kit
108
+ has never heard of.
109
+
110
+ ### Gotchas
111
+
112
+ - **A `new:`-created file starts EMPTY.** The shell has starter content only
113
+ for the kit's own types. Your editor must render a sensible default on
114
+ empty text (as `EMPTY` above) and write the real document back on first
115
+ edit — a component that throws on `""` is a blank panel.
116
+ - **`imports/` is read-only — add or override, never edit.** To change how
117
+ an imported editor behaves, copy its module into your own `editors/`, edit
118
+ the copy, and declare the same `ext` yourself pointing at it: the deck's
119
+ own declaration always wins over an import's.
120
+ - **Editors are edit-time only.** They load lazily and never run in play, and
121
+ play code must never import from `editors/` (behaviors run in the play
122
+ runtime). Keep shared logic in a plain module both can import.
123
+ - **Reading media/binary files**: `text` and `files` carry text. For bytes,
124
+ point an `<img>`/`<audio>` at `fileUrl(path)` from `castle-web-sdk`. Like
125
+ `writeFile`, it only works while editing locally — which is the only place
126
+ an editor runs, so that's fine.
127
+ - **Play code reads your file by importing it** --
128
+ `import course from '../course/main.course'`, which yields the parsed object
129
+ for `"data": "json"` and the raw string for `"text"`. That import is what
130
+ carries the file into a published deck, so it is the right thing to write; it
131
+ is also frozen at page load, so a module-scope constant built from it only
132
+ changes when the page does. Play never folds a change into a running
133
+ session — an edit shows up there when the person applies it from the Play
134
+ panel's restart button, like any other change.
135
+ - **Design for a phone.** The editor renders in a panel that is often
136
+ phone-width. Touch first: direct tap/drag on the content, big hit targets,
137
+ no hover-only or keyboard-only affordances, no fixed-wide toolbars.
138
+ Scroll vertically inside the panel rather than overflowing it.
139
+ - **The code view stays reachable** (the tab's view toggle), so don't build
140
+ a raw-JSON fallback mode into the editor itself.
141
+
142
+ ### When to build one
143
+
144
+ Content the creator (or you) keeps returning to edit by hand — a catalog of
145
+ entities, level data, sequences — earns an editor once it's clear iteration
146
+ will continue. Content that already has an editor doesn't: in a kit deck,
147
+ levels are scenes and art is sprites; don't wrap a new editor around a type
148
+ the kit already opens. And a concept that lives on ACTORS — a movement
149
+ style, a per-thing setting, anything configured per instance — belongs in a
150
+ behavior, edited through the scene editor's inspector (props, `propertyMeta`
151
+ ranges and select options, or a `static Inspector` panel — see the kit's own
152
+ `Sound.jsx`/`Joints.jsx`), not in an editor of its own. An editor is for
153
+ content FILES the deck accumulates. Never let building one delay a playable
154
+ change the user asked for — it rides alongside, and it needs the user's yes
155
+ first.
156
+
32
157
  ## Files and imports
33
158
 
34
159
  One rule wherever a file is named -- JS imports, `"blueprint"` refs, `Sprite.file`,
@@ -48,6 +173,15 @@ don't edit them. `castle-web add-import <deckId>` adds one, `update-import`
48
173
  re-fetches it. `resolveDeckFile` from `castle-web-sdk` is the rule itself, if a
49
174
  behavior needs to resolve a path it was handed.
50
175
 
176
+ A data file the DECK declares itself (`castle.json` `editor.fileTypes`) is the
177
+ one case where a behavior SHOULD import a data file --
178
+ `import course from '../course/main.course'`, parsed when the type declares
179
+ `"data": "json"` -- because that import is the only thing that carries the file
180
+ into a published deck. The kit's own `.scene` / `.sprite` files are in its glob
181
+ and reach play without one, which is why importing those stays wrong. An
182
+ imported file's text is frozen at page load, like every other module's, so a
183
+ run picks up an edit when Play starts a fresh run -- not while one is going.
184
+
51
185
  ## Scope
52
186
 
53
187
  Write the smallest game that satisfies what the user asked for. No sound, particles, menus, multi-level progression, or visual polish unless they specifically asked for it. A typical behavior is 30–80 lines — if yours is hitting 200, you're over-engineering: cut feel-good extras, fewer fields on props, fewer edge cases, fewer comments. Ship the core loop first; the user can ask for more.
@@ -131,5 +131,5 @@
131
131
  "main": "main.jsx",
132
132
  "autoUpdateWhenImported": true,
133
133
  "title": "physics-2d",
134
- "publishedVersion": "2026-08-21T23:53:35.620Z"
134
+ "publishedVersion": "2026-08-22T01:06:16.224Z"
135
135
  }
@@ -265,6 +265,7 @@ export function SceneEditor({
265
265
  sceneData,
266
266
  sprites,
267
267
  files,
268
+ path,
268
269
  isPlaying,
269
270
  text,
270
271
  canvasRef,
@@ -1491,6 +1492,7 @@ function useScenePlayLoop({
1491
1492
  sceneData,
1492
1493
  sprites,
1493
1494
  files,
1495
+ path,
1494
1496
  isPlaying,
1495
1497
  text,
1496
1498
  canvasRef,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.134",
3
+ "version": "0.4.136",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "castle-web": "./dist/index.js"