castle-web-cli 0.4.133 → 0.4.135

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 { declaresImportWhenRemixed, fetchParentSource, moveSourceInto, 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,27 @@ 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 stageDir = await fetchParentSource(parentDeckId);
465
+ let imported = false;
466
+ try {
467
+ if (declaresImportWhenRemixed(stageDir)) {
468
+ scaffoldBare(projectDir);
469
+ await addImportTo(projectDir, { deckRef: parentDeckId });
470
+ imported = true;
471
+ }
472
+ else {
473
+ moveSourceInto(stageDir, projectDir);
474
+ }
475
+ }
476
+ finally {
477
+ fs.rmSync(stageDir, { recursive: true, force: true });
478
+ }
479
+ writeRemixIdentity(projectDir, identity);
480
+ console.log(`Created project in ${projectDir}/ (${imported ? 'importing' : 'copied from'} deck ${parentDeckId})`);
481
+ }
460
482
  // nothing, so a fresh deck has exactly one version.
461
483
  //
462
484
  // The message is the only place a deck's kit lineage is recorded at all.
@@ -483,15 +505,27 @@ export async function init(dir, opts = {}) {
483
505
  console.error(`Directory "${dir}" is not empty.`);
484
506
  process.exit(1);
485
507
  }
508
+ if (opts.remixOf && opts.kit) {
509
+ console.error('Pass either --remix or --kit, not both.');
510
+ process.exit(1);
511
+ }
486
512
  const kit = opts.kit ?? DEFAULT_KIT;
487
513
  const bare = kit === 'none' || kit === 'bare';
488
- if (bare) {
514
+ if (opts.remixOf) {
515
+ await scaffoldFromRemix(opts.remixOf, projectDir, {
516
+ deckId: opts.deckId,
517
+ cardId: opts.cardId,
518
+ });
519
+ }
520
+ else if (bare) {
489
521
  scaffoldBare(projectDir);
490
522
  }
491
523
  else {
492
524
  scaffoldFromKitImport(kit, projectDir);
493
525
  }
494
- console.log(`Created project in ${projectDir}/${bare ? '' : ` (from kit "${kit}")`}`);
526
+ if (!opts.remixOf) {
527
+ console.log(`Created project in ${projectDir}/${bare ? '' : ` (from kit "${kit}")`}`);
528
+ }
495
529
  // Always install deps so the deck is ready to serve/edit immediately.
496
530
  // `--no-serve` only skips the serve step below (callers like the cloud
497
531
  // launcher run their own serve, but still want deps in place).
@@ -514,7 +548,7 @@ export async function init(dir, opts = {}) {
514
548
  catch {
515
549
  console.error('dependency install failed; re-run `pnpm install` (or `npm install`) in the deck.');
516
550
  }
517
- saveInitialVersion(projectDir, bare ? null : kit);
551
+ saveInitialVersion(projectDir, opts.remixOf ?? (bare ? null : kit));
518
552
  const autoServe = opts.serve !== false;
519
553
  if (autoServe && installed) {
520
554
  // Call serve() with detach so init returns once the server is up. serve()
@@ -0,0 +1,18 @@
1
+ export interface RemixIdentity {
2
+ deckId?: string;
3
+ /** Without this a later save-deck mints a second card. */
4
+ cardId?: string;
5
+ }
6
+ /**
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.
9
+ */
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;
13
+ /**
14
+ * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
15
+ * whatever else the deck owns. With no identity passed (a local `init --remix`),
16
+ * the next save-deck creates a fresh deck with no lineage.
17
+ */
18
+ export declare function writeRemixIdentity(projectDir: string, identity?: RemixIdentity): void;
package/dist/remix.js ADDED
@@ -0,0 +1,86 @@
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 readJson(file) {
19
+ if (!fs.existsSync(file))
20
+ return null;
21
+ try {
22
+ return JSON.parse(fs.readFileSync(file, 'utf-8'));
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /**
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.
31
+ */
32
+ export async function fetchParentSource(parentDeckId) {
33
+ const source = await api.webDeckSource(parentDeckId);
34
+ if (!source) {
35
+ console.error(`Deck ${parentDeckId} has no saved source to remix. Only decks saved by the web CLI can be remixed.`);
36
+ process.exit(1);
37
+ }
38
+ console.log(`Fetching ${source.archiveUrl}`);
39
+ const res = await fetch(source.archiveUrl, { signal: AbortSignal.timeout(60000) });
40
+ if (!res.ok) {
41
+ throw new Error(`Archive fetch failed: HTTP ${res.status}`);
42
+ }
43
+ const buf = Buffer.from(await res.arrayBuffer());
44
+ 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);
48
+ try {
49
+ await runTar(['-xzf', tmpFile, '-C', stageDir]);
50
+ }
51
+ finally {
52
+ try {
53
+ fs.unlinkSync(tmpFile);
54
+ }
55
+ catch {
56
+ /* nothing to clean */
57
+ }
58
+ }
59
+ return stageDir;
60
+ }
61
+ export function declaresImportWhenRemixed(sourceDir) {
62
+ return readJson(path.join(sourceDir, 'castle.json'))?.importWhenRemixed === true;
63
+ }
64
+ export function moveSourceInto(sourceDir, projectDir) {
65
+ 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
+ }
69
+ }
70
+ /**
71
+ * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
72
+ * whatever else the deck owns. With no identity passed (a local `init --remix`),
73
+ * the next save-deck creates a fresh deck with no lineage.
74
+ */
75
+ export function writeRemixIdentity(projectDir, identity = {}) {
76
+ const file = path.join(projectDir, 'castle.json');
77
+ const next = { ...(readJson(file) ?? {}) };
78
+ for (const key of PARENT_ONLY_KEYS)
79
+ delete next[key];
80
+ if (identity.deckId)
81
+ next.deckId = identity.deckId;
82
+ if (identity.cardId)
83
+ next.cardId = identity.cardId;
84
+ fs.mkdirSync(projectDir, { recursive: true });
85
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n', 'utf-8');
86
+ }
@@ -131,5 +131,5 @@
131
131
  "main": "main.jsx",
132
132
  "autoUpdateWhenImported": true,
133
133
  "title": "physics-2d",
134
- "publishedVersion": "2026-08-21T23:15:26.298Z"
134
+ "publishedVersion": "2026-08-21T23:53:35.620Z"
135
135
  }
@@ -70,7 +70,7 @@ async function readDeckFile(path) {
70
70
  // no serve, a race with a delete, or a declared type that is binary (an image
71
71
  // the deck claims) -- the serve flags those rather than mangling them, and an
72
72
  // image decoded as utf-8 is nothing.
73
- async function readDeclaredFile(file) {
73
+ export async function readDeclaredFile(file) {
74
74
  try {
75
75
  const res = await fetch(`/__castle/files/read?path=${encodeURIComponent(file)}`);
76
76
  if (!res.ok) return null;
@@ -82,7 +82,12 @@ async function readDeclaredFile(file) {
82
82
  }
83
83
  }
84
84
 
85
- async function hydrateDeclaredFiles(ensurePath) {
85
+ // `knownExts` / `knownFiles` are the CALLER's, because each kit globs a
86
+ // different set: physics-3d also knows `.pxmodel`, and a type one kit already
87
+ // handles is not a declared type that needs fetching. Returns the extensions
88
+ // found as well as the files, so the caller can teach its own change
89
+ // classifier about them.
90
+ export async function hydrateDeclaredFiles({ knownExts, knownFiles, ensurePath }) {
86
91
  let info;
87
92
  let listing;
88
93
  try {
@@ -97,11 +102,10 @@ async function hydrateDeclaredFiles(ensurePath) {
97
102
  const exts = (info.fileTypes ?? [])
98
103
  .filter((type) => type.data || (typeof type.editor === 'string' && type.editor !== 'kit'))
99
104
  .map((type) => type.ext)
100
- .filter((ext) => typeof ext === 'string' && ext && !DATA_EXTS.includes(ext));
105
+ .filter((ext) => typeof ext === 'string' && ext && !knownExts.includes(ext));
101
106
  if (exts.length === 0) return null;
102
- for (const ext of exts) declaredDataExts.add(ext);
103
107
  const paths = (listing.files ?? []).filter(
104
- (file) => initialFiles[file] === undefined && exts.some((ext) => file.endsWith(ext))
108
+ (file) => knownFiles[file] === undefined && exts.some((ext) => file.endsWith(ext))
105
109
  );
106
110
  const entries = await Promise.all(
107
111
  paths.map(async (file) => {
@@ -114,11 +118,11 @@ async function hydrateDeclaredFiles(ensurePath) {
114
118
  // of visiblePaths is not in it. The shell can still open that file by path,
115
119
  // and an editor handed '' for it would be back to the original bug -- so make
116
120
  // sure whatever was actually opened is present, curated or not.
117
- if (ensurePath && initialFiles[ensurePath] === undefined && extra[ensurePath] === undefined) {
121
+ if (ensurePath && knownFiles[ensurePath] === undefined && extra[ensurePath] === undefined) {
118
122
  const one = await readDeclaredFile(ensurePath);
119
123
  if (one !== null) extra[ensurePath] = one;
120
124
  }
121
- return Object.keys(extra).length ? extra : null;
125
+ return { extra, exts };
122
126
  }
123
127
 
124
128
  // Deck files as live state: starts from the build-time glob snapshot, fills in
@@ -142,11 +146,20 @@ export function useLiveDeckFiles({ shouldSkipPath, ensurePath, live = true } = {
142
146
 
143
147
  useEffect(() => {
144
148
  let alive = true;
145
- void hydrateDeclaredFiles(ensurePath).then((extra) => {
149
+ void hydrateDeclaredFiles({
150
+ knownExts: DATA_EXTS,
151
+ knownFiles: initialFiles,
152
+ ensurePath,
153
+ }).then((found) => {
146
154
  if (!alive) return;
147
- // `current` wins: by the time this lands the editor may already have made
148
- // an optimistic edit, and the disk copy behind it is stale.
149
- if (extra) setFiles((current) => ({ ...extra, ...current }));
155
+ if (found) {
156
+ for (const ext of found.exts) declaredDataExts.add(ext);
157
+ // `current` wins: by the time this lands the editor may already have
158
+ // made an optimistic edit, and the disk copy behind it is stale.
159
+ if (Object.keys(found.extra).length) {
160
+ setFiles((current) => ({ ...found.extra, ...current }));
161
+ }
162
+ }
150
163
  setHydrated(true);
151
164
  });
152
165
  return () => {
@@ -25,7 +25,8 @@
25
25
  "scenes/**",
26
26
  "blueprints/**",
27
27
  "behaviors/**",
28
- "assets/**"
28
+ "assets/**",
29
+ "theme.style"
29
30
  ],
30
31
  "fileTypes": [
31
32
  {
@@ -64,12 +65,12 @@
64
65
  "imports": {
65
66
  "castle.physics-2d": {
66
67
  "deckId": "ckRZGFW4iPrx",
67
- "version": "2026-08-14T21:20:31.152Z"
68
+ "version": "2026-08-21T23:52:56.888Z"
68
69
  }
69
70
  },
70
71
  "main": "main.jsx",
71
72
  "autoUpdateWhenImported": true,
72
73
  "deckId": "JH0SclbPVP0y",
73
74
  "cardId": "eXfAaUdbSU5A",
74
- "publishedVersion": "2026-08-21T23:15:28.646Z"
75
+ "publishedVersion": "2026-08-21T23:53:37.801Z"
75
76
  }
@@ -66,8 +66,9 @@ function descendantIds(parts, rootId) {
66
66
 
67
67
  export function PxModelEditor({ path }) {
68
68
  const saver = useFileSaver3D();
69
- const { files, setFiles, dataVersion } = useLiveDeckFiles3D({
69
+ const { files, setFiles, dataVersion, hydrated } = useLiveDeckFiles3D({
70
70
  shouldSkipPath: saver.hasPending,
71
+ ensurePath: path,
71
72
  });
72
73
  const text = files[path];
73
74
  useEffect(() => {
@@ -265,6 +266,16 @@ export function PxModelEditor({ path }) {
265
266
  );
266
267
  }
267
268
 
269
+ if (!hydrated && files[path] === undefined) {
270
+ return (
271
+ <div className={styles.panelBare}>
272
+ <MainEditor>
273
+ <EditorBody>loading…</EditorBody>
274
+ </MainEditor>
275
+ </div>
276
+ );
277
+ }
278
+
268
279
  return (
269
280
  <div className={styles.panelBare}>
270
281
  <MainEditor>
@@ -65,8 +65,9 @@ export function Scene3DEditor({ path }) {
65
65
  const stashKey = `scene3d-editor:${path}`;
66
66
  const [stash] = useState(() => takeReloadState(stashKey));
67
67
  const saver = useFileSaver3D();
68
- const { files, setFiles, dataVersion } = useLiveDeckFiles3D({
68
+ const { files, setFiles, dataVersion, hydrated } = useLiveDeckFiles3D({
69
69
  shouldSkipPath: saver.hasPending,
70
+ ensurePath: path,
70
71
  });
71
72
  const text = files[path] ?? '';
72
73
  const onChangeText = (next) => {
@@ -305,6 +306,16 @@ export function Scene3DEditor({ path }) {
305
306
  onSelectActorIds([]);
306
307
  };
307
308
 
309
+ if (!hydrated && files[path] === undefined) {
310
+ return (
311
+ <div className={styles.panelBare}>
312
+ <MainEditor>
313
+ <EditorBody>loading…</EditorBody>
314
+ </MainEditor>
315
+ </div>
316
+ );
317
+ }
318
+
308
319
  return (
309
320
  <div className={styles.panelBare}>
310
321
  <MainEditor>
@@ -8,6 +8,7 @@
8
8
  import { useEffect, useRef, useState } from 'react';
9
9
  import { onFilesChanged } from 'castle-web-sdk';
10
10
  import { initialFiles, initialMedia, isImageFile } from '@imports/castle.physics-2d/engine/files';
11
+ import { hydrateDeclaredFiles } from '@imports/castle.physics-2d/engine/liveReload';
11
12
  import { parseFull } from '@imports/castle.physics-2d/engine/pxart';
12
13
  import { imageArt } from '@imports/castle.physics-2d/engine/art';
13
14
 
@@ -31,8 +32,15 @@ export const initialFiles3D = {
31
32
  const DATA_EXTS = ['.scene', '.pxart', '.drawing', '.pxmodel'];
32
33
  const CODE_EXTS = ['.js', '.jsx', '.ts', '.tsx', '.css'];
33
34
 
35
+ // Extensions the DECK declared that this kit has never heard of, learned from
36
+ // the serve at mount. Module-level because the change classifier runs per
37
+ // event, with no state to thread through -- same shape as the imported kit's.
38
+ const declaredDataExts = new Set();
39
+
34
40
  export function isDataFile3D(path) {
35
- return DATA_EXTS.some((ext) => path.endsWith(ext));
41
+ if (DATA_EXTS.some((ext) => path.endsWith(ext))) return true;
42
+ for (const ext of declaredDataExts) if (path.endsWith(ext)) return true;
43
+ return false;
36
44
  }
37
45
 
38
46
  function needsContextReload(change) {
@@ -81,8 +89,12 @@ async function applyDataChanges(changes, setFiles, setDataVersion) {
81
89
  // A code change does nothing here, matching the imported hook: only a page
82
90
  // reload picks up new code, and throwing one at a panel someone is working in
83
91
  // loses their place, so the panel header offers it instead.
84
- export function useLiveDeckFiles3D({ shouldSkipPath } = {}) {
92
+ export function useLiveDeckFiles3D({ shouldSkipPath, ensurePath } = {}) {
85
93
  const [files, setFiles] = useState(initialFiles3D);
94
+ // False until the declared-type read has settled. An editor mounted before
95
+ // then would be handed '' for a file that exists, and an edit made in that
96
+ // window writes its empty document over the real one.
97
+ const [hydrated, setHydrated] = useState(false);
86
98
  // Bumped on every applied data change. The editors watch it to re-apply when
87
99
  // a file they REFERENCE changed -- their own `text` is unchanged then, so it
88
100
  // is the only signal that the drawing under an actor moved.
@@ -90,6 +102,30 @@ export function useLiveDeckFiles3D({ shouldSkipPath } = {}) {
90
102
  const skipRef = useRef(shouldSkipPath);
91
103
  skipRef.current = shouldSkipPath;
92
104
 
105
+ // Same gap, same fix as the imported kit: the glob above is a compile-time
106
+ // transform, so a type the DECK declares is invisible to it. `initialFiles3D`
107
+ // is what this kit already knows, models included.
108
+ useEffect(() => {
109
+ let alive = true;
110
+ void hydrateDeclaredFiles({
111
+ knownExts: DATA_EXTS,
112
+ knownFiles: initialFiles3D,
113
+ ensurePath,
114
+ }).then((found) => {
115
+ if (!alive) return;
116
+ if (found) {
117
+ for (const ext of found.exts) declaredDataExts.add(ext);
118
+ if (Object.keys(found.extra).length) {
119
+ setFiles((current) => ({ ...found.extra, ...current }));
120
+ }
121
+ }
122
+ setHydrated(true);
123
+ });
124
+ return () => {
125
+ alive = false;
126
+ };
127
+ }, [ensurePath]);
128
+
93
129
  useEffect(
94
130
  () =>
95
131
  onFilesChanged((event) => {
@@ -102,7 +138,7 @@ export function useLiveDeckFiles3D({ shouldSkipPath } = {}) {
102
138
  []
103
139
  );
104
140
 
105
- return { files, setFiles, dataVersion };
141
+ return { files, setFiles, dataVersion, hydrated };
106
142
  }
107
143
 
108
144
  // The sprites map with parsed pxarts CACHED BY TEXT: re-parsing every file on
@@ -0,0 +1,3 @@
1
+ {
2
+ "palette": "endesga-64"
3
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.133",
3
+ "version": "0.4.135",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "castle-web": "./dist/index.js"