castle-web-cli 0.4.135 → 0.4.137

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/init.js CHANGED
@@ -3,8 +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 { addImportTo, IMPORTS_DIR, lockImportTree } from './imports.js';
7
- import { declaresImportWhenRemixed, fetchParentSource, moveSourceInto, writeRemixIdentity, } from './remix.js';
6
+ import { addImportTo, IMPORTS_DIR, lockImportTree, restoreMissingImports, syncImportDependencies, } from './imports.js';
7
+ import { discardParentSource, fetchParentSource, unpackParentSource, writeRemixIdentity, } from './remix.js';
8
8
  import { getCliEntryPath, getKitsDir, getRepoRoot, getSdkPackagePath, toPosixPath, } from './localPaths.js';
9
9
  import { serve } from './serve.js';
10
10
  import { createVersion } from './versions.js';
@@ -461,20 +461,29 @@ function scaffoldFromKitImport(kit, projectDir) {
461
461
  // The import branch is deliberately thin: `addImportTo` already adopts a bare
462
462
  // deck's entry point, starter scene and theme.
463
463
  async function scaffoldFromRemix(parentDeckId, projectDir, identity) {
464
- const stageDir = await fetchParentSource(parentDeckId);
465
- let imported = false;
464
+ const source = await fetchParentSource(parentDeckId);
465
+ const imported = source.castleJson.importWhenRemixed === true;
466
466
  try {
467
- if (declaresImportWhenRemixed(stageDir)) {
467
+ if (imported) {
468
468
  scaffoldBare(projectDir);
469
469
  await addImportTo(projectDir, { deckRef: parentDeckId });
470
- imported = true;
471
470
  }
472
471
  else {
473
- moveSourceInto(stageDir, projectDir);
472
+ await unpackParentSource(source, projectDir);
473
+ // `imports/` is left out of the source archive, so a copied deck arrives
474
+ // with its pins and none of the files -- same as get-deck, which leaves
475
+ // this to `install`. Its declared deps then have to reach package.json
476
+ // before the install below.
477
+ for (const alias of await restoreMissingImports(projectDir)) {
478
+ console.log(`Restored import ${alias}`);
479
+ }
480
+ for (const dep of syncImportDependencies(projectDir)) {
481
+ console.log(`Added dependency ${dep} from an import`);
482
+ }
474
483
  }
475
484
  }
476
485
  finally {
477
- fs.rmSync(stageDir, { recursive: true, force: true });
486
+ discardParentSource(source);
478
487
  }
479
488
  writeRemixIdentity(projectDir, identity);
480
489
  console.log(`Created project in ${projectDir}/ (${imported ? 'importing' : 'copied from'} deck ${parentDeckId})`);
package/dist/remix.d.ts CHANGED
@@ -1,15 +1,24 @@
1
+ import type { CastleJson } from './castleJson.js';
1
2
  export interface RemixIdentity {
2
3
  deckId?: string;
3
4
  /** Without this a later save-deck mints a second card. */
4
5
  cardId?: string;
5
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
+ }
6
13
  /**
7
- * Unpack the parent's saved source into a temp dir -- temp because whether these
8
- * files are wanted at all depends on the castle.json among them.
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.
9
17
  */
10
- export declare function fetchParentSource(parentDeckId: string): Promise<string>;
11
- export declare function declaresImportWhenRemixed(sourceDir: string): boolean;
12
- export declare function moveSourceInto(sourceDir: string, projectDir: string): void;
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>;
13
22
  /**
14
23
  * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
15
24
  * whatever else the deck owns. With no identity passed (a local `init --remix`),
package/dist/remix.js CHANGED
@@ -15,19 +15,18 @@ const PARENT_ONLY_KEYS = [
15
15
  'publishedVersion',
16
16
  'autoUpdateWhenImported',
17
17
  ];
18
- function readJson(file) {
19
- if (!fs.existsSync(file))
20
- return null;
18
+ function parseJson(text) {
21
19
  try {
22
- return JSON.parse(fs.readFileSync(file, 'utf-8'));
20
+ return JSON.parse(text);
23
21
  }
24
22
  catch {
25
- return null;
23
+ return {};
26
24
  }
27
25
  }
28
26
  /**
29
- * Unpack the parent's saved source into a temp dir -- temp because whether these
30
- * files are wanted at all depends on the castle.json among them.
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.
31
30
  */
32
31
  export async function fetchParentSource(parentDeckId) {
33
32
  const source = await api.webDeckSource(parentDeckId);
@@ -42,30 +41,26 @@ export async function fetchParentSource(parentDeckId) {
42
41
  }
43
42
  const buf = Buffer.from(await res.arrayBuffer());
44
43
  console.log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
45
- const stageDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-remix-'));
46
- const tmpFile = path.join(os.tmpdir(), `castle-remix-${nanoid(8)}.tar.gz`);
47
- fs.writeFileSync(tmpFile, buf);
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) {
48
53
  try {
49
- await runTar(['-xzf', tmpFile, '-C', stageDir]);
54
+ fs.unlinkSync(source.archivePath);
50
55
  }
51
- finally {
52
- try {
53
- fs.unlinkSync(tmpFile);
54
- }
55
- catch {
56
- /* nothing to clean */
57
- }
56
+ catch {
57
+ /* nothing to clean */
58
58
  }
59
- return stageDir;
60
59
  }
61
- export function declaresImportWhenRemixed(sourceDir) {
62
- return readJson(path.join(sourceDir, 'castle.json'))?.importWhenRemixed === true;
63
- }
64
- export function moveSourceInto(sourceDir, projectDir) {
60
+ /** Unpack straight into the deck dir, the way get-deck does. */
61
+ export async function unpackParentSource(source, projectDir) {
65
62
  fs.mkdirSync(projectDir, { recursive: true });
66
- for (const entry of fs.readdirSync(sourceDir)) {
67
- fs.renameSync(path.join(sourceDir, entry), path.join(projectDir, entry));
68
- }
63
+ await runTar(['-xzf', source.archivePath, '-C', projectDir]);
69
64
  }
70
65
  /**
71
66
  * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
@@ -74,7 +69,8 @@ export function moveSourceInto(sourceDir, projectDir) {
74
69
  */
75
70
  export function writeRemixIdentity(projectDir, identity = {}) {
76
71
  const file = path.join(projectDir, 'castle.json');
77
- const next = { ...(readJson(file) ?? {}) };
72
+ const existing = fs.existsSync(file) ? parseJson(fs.readFileSync(file, 'utf-8')) : {};
73
+ const next = { ...existing };
78
74
  for (const key of PARENT_ONLY_KEYS)
79
75
  delete next[key];
80
76
  if (identity.deckId)
@@ -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.135",
3
+ "version": "0.4.137",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "castle-web": "./dist/index.js"