castle-web-cli 0.4.138 → 0.4.140

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.
@@ -27,6 +27,7 @@ What a deck is: a normal web project served by vite -- index.html plus plain JS/
27
27
  Hard rules:
28
28
  - You NEVER edit files or run state-changing commands. All building and fixing happens through background task agents -- always hand the longer work to them.
29
29
  - IMPORTS ARE YOURS, and they are the one exception to the rule above. Run \`castle-web list-decks --kind kits\` (also \`mine\` and \`saved\`) to see what this deck can import, and \`castle-web add-import <deckIdOrUrl>\` to add one -- both directly, not through a task. Do NOT claim you can list or import anything until you have actually run these; do not describe imports you have not looked at. \`list-decks\` prints one deck per line starting with the id \`add-import\` takes, and marks the ones this deck already has. A pasted castle.xyz deck link works in place of an id. Everything else about a deck's files still goes to task agents.
30
+ - Imported files are READ-ONLY, which is what to say when the user asks whether they can change something a kit or another import gave them, or why an edit to one did not stick: the deck takes its own version of that one file -- a fork, stored beside the import and used in its place -- and that version is what runs. Forking is how their own data and code changes override an import's, and a task agent does it; the tradeoff, worth saying plainly, is that a file done this way stops picking up changes when the import itself is updated, so it stays to the few files the change actually needs. Often it does not come to a fork at all, which is the better thing to say first: a kit picks up the deck's own behaviors and systems, so new logic is usually just a new file in the deck.
30
31
  - You are the fast lane: get to your final reply as quickly as possible. When the user reports something broken, do NOT dig into the code to diagnose it first -- spawn a task whose job is to investigate AND fix it. Only read deck files when your reply itself needs them (answering a question about the deck, grounding a claim -- never make things up); never read as pre-work before spawning a task, and never read files just to learn conventions already covered by the Quick reference.
31
32
  - Launch a SET of small steps the user tests one by one -- a pipeline, never one big task they wait on, never untestable fragments. One interacting mechanic = one task (paddle + ball + bricks = one playable core, not three). First step = the smallest genuinely playable thing; later steps build it out. Match breadth to ambition ("basic" = a few steps; "go wild" = many). You're optimizing the user's taste and feedback -- more small testable steps = more points where they steer it into something theirs.
32
33
  - The whole goal: every piece of work TESTABLE in actual gameplay ASAP. Start every task as early as possible and run them in PARALLEL. Do NOT break tasks down by which files they touch, and never add \`after:\` just to avoid two tasks editing the same file -- tasks make surgical edits and overlap fine. The only real dependency between tasks is INFORMATION: a task is blocked only when it needs a fact it does not yet have.
@@ -917,6 +918,20 @@ Operating rules:
917
918
  - SAVE A VERSION when your change is done, so the user can see and undo it: \`castle-web save-version -m "<short description of what you changed>" <each path you touched>\`. Name those paths explicitly -- a bare \`save-version\` with no paths records the WHOLE deck, including files a sibling agent is still working on. One version for the whole task, at the end; not one per file.
918
919
  - Overlap with the other agents working in this deck is fine and expected -- do not try to avoid it or wait for them. Saving only your own paths is all that is asked of you; nothing anyone has written is lost by your save.
919
920
  - NEVER run \`restore-version\`. Going back to an earlier version is the user's decision alone -- not yours, not even to undo your own work. If your change is wrong, fix it forward.
921
+ - The deck's CLI is \`castle-web <command>\`, run in this directory. The commands that are yours:
922
+ - \`list-versions [version]\` -- the deck's version history, newest first (a version argument lists from there).
923
+ - \`show-version <version>\` -- what one version changed, as diffs of just those files. Reading history is free; use it when you need to know what recent work actually did.
924
+ - \`save-version -m "<message>" <paths...>\` -- as above: your own paths, named explicitly, once at the end.
925
+ - \`install\` -- npm install for the deck, after you add a dependency to \`package.json\`.
926
+ - \`fork-import-file <imports/...>\` and \`revert-import-file <imports/...>\` -- take or drop this deck's own version of one imported file (see below).
927
+ - \`screenshot [--out FILE]\` -- one frame of the running deck. The verification rule above still holds: rarely worth the time it costs the user.
928
+ - \`restart\` -- the same whole-experience reload as \`npm run restart\`, with the same caveat; \`--port PORT\` only if the serve is not the one in \`.castle/serve.json\`.
929
+ - Nothing else in the CLI is yours to run. \`init\`, \`serve\` and \`get-deck\` create, serve, or overwrite the deck the person is playing in right now; \`save-deck\` publishes it and \`login\` is their account, both their decisions; \`add-import\` and \`update-import\` belong to the conversation agent, which owns this deck's imports. \`restore-version\`: never, as above.
930
+ - \`imports/\` holds another deck's files and is locked read-only on disk (mode 0444 -- a write fails with \`EACCES\`, which is the lock working, not a broken checkout). To change one, FORK it: \`castle-web fork-import-file imports/<alias>/<path>\` copies that file to \`forks/<alias>/<path>\`, which the deck loads in place of the imported one everywhere. Nothing else has to change -- the code goes on referring to it as \`imports/<alias>/<path>\`. \`castle-web revert-import-file imports/<alias>/<path>\` drops the fork and the import's own file is live again.
931
+ - Fork when the user wants their own data or logic changes sitting on top of an import, and fork as FEW files as you can -- the one file that carries the change, not a batch of them at once. A forked file stops receiving that import's future updates, so every extra fork is one more file that will not improve when the import does.
932
+ - Before forking at all, check whether the DECK's own code can carry the change: a kit discovers deck-level files through its registries -- a new behavior in \`behaviors/\`, a new system in \`systems/\` -- so adding through that registration needs no fork, and a deck behavior reusing an imported one's behavior name replaces it outright. The deck's CLAUDE.md / AGENTS.md names these seams; look there before assuming a fork is the only way in.
933
+ - When a fork IS the way, prefer forking to open a SEAM: put a hook, registration, or override point in the forked file and keep the logic it calls in an ordinary deck file. Later changes then land in the deck instead of forcing more forks. Size that to the change though -- a one- or two-line tweak is just a direct edit to the fork; do not build an override system for it.
934
+ - A forked file exists on disk TWICE, and reading or grepping finds both copies. \`forks/<alias>/<path>\` is the live one -- edit that one. \`imports/<alias>/<path>\` is the version the fork was taken from; it is what the deck used to run, not what it runs now, and writing to it just fails.
920
935
  - Other task agents may be editing this same deck IN PARALLEL. When you change an existing file, READ it first and make a targeted edit to just the part you need -- never overwrite a whole file you have not read. A blind full-file rewrite clobbers other agents' in-flight changes. Being a bit slower and careful here is the right tradeoff.
921
936
  - Favor real, editable assets: for game objects, characters, and scenery, make pixel-art drawings and place them as real actors in the scene rather than code-drawn shapes -- it keeps the deck editable in the editor and remixable. (Data-driven UI like health bars, score/text, and HUD gauges, plus dynamic things like bullets/particles/effects, stay procedural -- don't force those into drawings.)
922
937
  - Respect art ownership: if YOUR task is to create art, make it as real, editable drawing files (NOT hand-written pixel grids or code-drawn shapes), following the deck's CLAUDE.md / AGENTS.md for the drawing format and exact command. But if your prompt only REFERENCES drawing names (a sibling task is creating them in parallel), point the scene at those names and do NOT create the drawing files yourself -- two agents drawing the same sprites clobber each other. The deck's CLAUDE.md / AGENTS.md is the source of truth for how to make art. Reference the intended drawing name from the scene right away (the actor renders a plain-block fallback until the file exists); a newly written drawing file shows up for the person on their next reload, which is theirs to trigger.
package/dist/agent.js CHANGED
@@ -16,6 +16,7 @@
16
16
  // --force. Claude support can slot in later behind runAgentCli.
17
17
  import { execFileSync, spawn } from 'child_process';
18
18
  import { IMPORTS_DIR } from './imports.js';
19
+ import { isSameOriginUpgrade } from './wsOrigin.js';
19
20
  import * as fs from 'fs';
20
21
  import * as os from 'os';
21
22
  import * as path from 'path';
@@ -4170,6 +4171,14 @@ export function createAgentServer(opts) {
4170
4171
  const url = new URL(req.url ?? '/', 'http://localhost');
4171
4172
  if (url.pathname !== AGENT_WS_PATH)
4172
4173
  return false;
4174
+ // The agent socket drives the coding agent (exec, file writes) — reject any upgrade
4175
+ // that isn't same-origin (a co-tenant reaching this port directly sends no browser
4176
+ // Origin). Consumed either way so a rejected upgrade never falls through.
4177
+ if (!isSameOriginUpgrade(req)) {
4178
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
4179
+ socket.destroy();
4180
+ return true;
4181
+ }
4173
4182
  wss.handleUpgrade(req, socket, head, (ws) => attachClient(ws));
4174
4183
  return true;
4175
4184
  }
package/dist/api.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import * as config from './config.js';
2
- const API_HOST = 'https://api.castle.xyz/graphql';
2
+ // CASTLE_API_URL reroutes API traffic to a local forwarding proxy inside Castle cloud
3
+ // sandboxes (which also set CASTLE_TOKEN to a sandbox-scoped credential). Unset anywhere
4
+ // else, so normal installs always talk to the real API.
5
+ const API_HOST = process.env.CASTLE_API_URL || 'https://api.castle.xyz/graphql';
3
6
  export async function graphql(query, variables) {
4
7
  const token = config.getToken();
5
8
  const headers = {
package/dist/bundle.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import * as path from 'path';
2
2
  import { build } from 'vite';
3
3
  import { viteSingleFile } from 'vite-plugin-singlefile';
4
- import { sceneFilesPlugin, importsAliasPlugin } from './vitePlugins.js';
4
+ import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin } from './vitePlugins.js';
5
5
  export async function bundleProject(dir) {
6
6
  const result = await build({
7
7
  root: dir,
8
- plugins: [importsAliasPlugin(), viteSingleFile(), sceneFilesPlugin()],
8
+ plugins: [forksOverlayPlugin(), importsAliasPlugin(), viteSingleFile(), sceneFilesPlugin()],
9
9
  build: {
10
10
  write: false,
11
11
  rollupOptions: {
@@ -1,9 +1,13 @@
1
+ export declare const IMPORTS_DIR = "imports";
1
2
  export interface DeckImport {
2
3
  deckId?: string;
3
4
  source?: 'builtin';
4
5
  kit?: string;
5
6
  via?: string;
6
7
  version: string;
8
+ forks?: Record<string, {
9
+ originalSha: string;
10
+ }>;
7
11
  }
8
12
  export interface CastleJson {
9
13
  deckId?: string;
@@ -1,6 +1,11 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import picomatch from 'picomatch';
4
+ // Where a deck's dependencies live, relative to its root. Defined here, in a
5
+ // module with no imports of its own, because both the import machinery and the
6
+ // fork overlay need it and importing it from either of those would close a
7
+ // cycle.
8
+ export const IMPORTS_DIR = 'imports';
4
9
  export const DEFAULT_STARTER_SCENE = 'scenes/main.scene';
5
10
  export function deckStarterScene(dir) {
6
11
  const declared = readCastleJson(dir)?.starterScene;
@@ -1 +1 @@
1
- export declare const COMMON_INSTRUCTIONS = "## Imports are read-only (every deck)\n\n- **`imports/` holds other decks' files and is locked read-only on disk.** Files are mode 0444 and directories 0555, so any shell command that writes, moves, or deletes inside `imports/` fails with `EACCES` / \"Permission denied\" \u2014 that is the lock working, not a broken checkout. Do not `chmod` around it, do not `sudo`, and do not retry the command a different way.\n- **Change an import through the CLI, never the filesystem.** `castle-web add-import <deckIdOrUrl>` adds one and `castle-web update-import [alias]` re-fetches it (`--check` to see if it is outdated, `--revert` to undo). These handle the unlock/relock themselves.\n- **`castle-web list-decks [--kind mine|saved|kits]` is how you find out WHAT can be imported** \u2014 one deck per line, starting with the id `add-import` takes, and marked when this deck already has it. `imports/` only shows what is here already; it is not a catalogue.\n- **To change an imported deck's behavior, copy what you need into this deck and edit the copy**, then reference your copy. Editing in place is not available, and an `update-import` would overwrite it anyway.\n- **Deleting the deck directory itself needs the lock released first** (`chmod -R u+w` on the deck dir) \u2014 that is the one legitimate reason to touch the modes, and only for a directory being thrown away.\n\n## Assets (every deck)\n\n- **Load static assets (drawings, audio, etc.) through the bundler \u2014 never runtime-`fetch` a loose file path.** Use a static `import`, `import.meta.glob('./drawings/*.svg', { eager: true, import: 'default' })`, or inline the asset directly. The dev serve happens to serve loose files over HTTP, so `fetch('drawings/qb.svg')` looks like it works locally \u2014 but `save-deck` bundles the whole deck into a single file, loose files are no longer served, and the fetch silently fails on every platform. Kit decks: use the kit's own drawing/asset-loading APIs instead of a raw `fetch`.\n\n## Touch controls (every deck)\n\n- **Playable on a touchscreen, with only the controls the game actually needs.** Castle decks are played on phones, so whatever input a game does use must work by touch \u2014 direct tap/drag on the game itself wherever possible, and on-screen buttons only where the mechanics genuinely call for them. Do NOT add controls a game doesn't need: never drop in a generic d-pad or movement overlay by default. Prefer touching the game directly over an overlay that just mirrors keyboard keys. Keyboard input is fine to support on top for desktop play. Match the controls to the actual mechanics \u2014 a game with no directional movement should have no movement controls at all.\n\n## Fit the card (every deck)\n\n- **The deck plays inside a fixed 5:7 portrait card, not the full window.** The card is sized to fit the screen (at most about 450x630px), clips overflow, and does not scroll. Design the whole layout to fit inside that portrait box: size UI relative to the card with percentages, flex/grid, `min()`, `clamp()`, or viewport-relative units instead of fixed tall panels. Let playfields scale down on smaller cards rather than overflowing; anything outside the card edges is cut off. The SDK exports `CARD_RATIO` (= 5 / 7) if you need the exact ratio.\n- **Hand-rolled `<canvas>` elements must account for devicePixelRatio, or the game looks blurry on phones.** Size the backing store to the CSS layout size times `devicePixelRatio` (e.g. `canvas.width = rect.width * dpr`), keep the CSS width/height as the layout size, and scale the 2D context (`ctx.scale(dpr, dpr)`) so drawing code stays in CSS units \u2014 re-apply on resize. Kit decks don't need to do this by hand; the kit's engine already configures its canvas for DPR.\n - Exception: deliberate pixel art wants a fixed low-resolution backing store with `image-rendering: pixelated` CSS instead \u2014 don't DPR-scale that; the crisp chunky look is the point.\n";
1
+ export declare const COMMON_INSTRUCTIONS = "## Imports are read-only (every deck)\n\n- **`imports/` holds other decks' files and is locked read-only on disk.** Files are mode 0444 and directories 0555, so any shell command that writes, moves, or deletes inside `imports/` fails with `EACCES` / \"Permission denied\" \u2014 that is the lock working, not a broken checkout. Do not `chmod` around it, do not `sudo`, and do not retry the command a different way.\n- **Change an import through the CLI, never the filesystem.** `castle-web add-import <deckIdOrUrl>` adds one and `castle-web update-import [alias]` re-fetches it (`--check` to see if it is outdated, `--revert` to undo). These handle the unlock/relock themselves.\n- **`castle-web list-decks [--kind mine|saved|kits]` is how you find out WHAT can be imported** \u2014 one deck per line, starting with the id `add-import` takes, and marked when this deck already has it. `imports/` only shows what is here already; it is not a catalogue.\n- **To change one file of an import, FORK it**: `castle-web fork-import-file <path>` takes this deck's own version of that file, and every reference to the imported path uses your version from then on (`castle-web revert-import-file <path>` drops it and goes back to the import's). Fork only what you actually need to change, and as few files as you can -- a forked file stops taking the import's updates, so the more you fork the less an `update-import` can give you. To build something of your own rather than change theirs, write an ordinary file in this deck instead -- and check first whether the kit already lets a deck file register what you want (its CLAUDE.md names those seams), since that path keeps taking updates and a fork does not. When you do fork, it is often worth forking only to add a hook or registration point and keeping the logic itself in a deck file, so later changes need no further forks; for a quick one-off tweak a plain direct fork is fine.\n- **Deleting the deck directory itself needs the lock released first** (`chmod -R u+w` on the deck dir) \u2014 that is the one legitimate reason to touch the modes, and only for a directory being thrown away.\n\n## Assets (every deck)\n\n- **Load static assets (drawings, audio, etc.) through the bundler \u2014 never runtime-`fetch` a loose file path.** Use a static `import`, `import.meta.glob('./drawings/*.svg', { eager: true, import: 'default' })`, or inline the asset directly. The dev serve happens to serve loose files over HTTP, so `fetch('drawings/qb.svg')` looks like it works locally \u2014 but `save-deck` bundles the whole deck into a single file, loose files are no longer served, and the fetch silently fails on every platform. Kit decks: use the kit's own drawing/asset-loading APIs instead of a raw `fetch`.\n\n## Touch controls (every deck)\n\n- **Playable on a touchscreen, with only the controls the game actually needs.** Castle decks are played on phones, so whatever input a game does use must work by touch \u2014 direct tap/drag on the game itself wherever possible, and on-screen buttons only where the mechanics genuinely call for them. Do NOT add controls a game doesn't need: never drop in a generic d-pad or movement overlay by default. Prefer touching the game directly over an overlay that just mirrors keyboard keys. Keyboard input is fine to support on top for desktop play. Match the controls to the actual mechanics \u2014 a game with no directional movement should have no movement controls at all.\n\n## Fit the card (every deck)\n\n- **The deck plays inside a fixed 5:7 portrait card, not the full window.** The card is sized to fit the screen (at most about 450x630px), clips overflow, and does not scroll. Design the whole layout to fit inside that portrait box: size UI relative to the card with percentages, flex/grid, `min()`, `clamp()`, or viewport-relative units instead of fixed tall panels. Let playfields scale down on smaller cards rather than overflowing; anything outside the card edges is cut off. The SDK exports `CARD_RATIO` (= 5 / 7) if you need the exact ratio.\n- **Hand-rolled `<canvas>` elements must account for devicePixelRatio, or the game looks blurry on phones.** Size the backing store to the CSS layout size times `devicePixelRatio` (e.g. `canvas.width = rect.width * dpr`), keep the CSS width/height as the layout size, and scale the 2D context (`ctx.scale(dpr, dpr)`) so drawing code stays in CSS units \u2014 re-apply on resize. Kit decks don't need to do this by hand; the kit's engine already configures its canvas for DPR.\n - Exception: deliberate pixel art wants a fixed low-resolution backing store with `image-rendering: pixelated` CSS instead \u2014 don't DPR-scale that; the crisp chunky look is the point.\n";
@@ -7,7 +7,7 @@ export const COMMON_INSTRUCTIONS = `## Imports are read-only (every deck)
7
7
  - **\`imports/\` holds other decks' files and is locked read-only on disk.** Files are mode 0444 and directories 0555, so any shell command that writes, moves, or deletes inside \`imports/\` fails with \`EACCES\` / "Permission denied" — that is the lock working, not a broken checkout. Do not \`chmod\` around it, do not \`sudo\`, and do not retry the command a different way.
8
8
  - **Change an import through the CLI, never the filesystem.** \`castle-web add-import <deckIdOrUrl>\` adds one and \`castle-web update-import [alias]\` re-fetches it (\`--check\` to see if it is outdated, \`--revert\` to undo). These handle the unlock/relock themselves.
9
9
  - **\`castle-web list-decks [--kind mine|saved|kits]\` is how you find out WHAT can be imported** — one deck per line, starting with the id \`add-import\` takes, and marked when this deck already has it. \`imports/\` only shows what is here already; it is not a catalogue.
10
- - **To change an imported deck's behavior, copy what you need into this deck and edit the copy**, then reference your copy. Editing in place is not available, and an \`update-import\` would overwrite it anyway.
10
+ - **To change one file of an import, FORK it**: \`castle-web fork-import-file <path>\` takes this deck's own version of that file, and every reference to the imported path uses your version from then on (\`castle-web revert-import-file <path>\` drops it and goes back to the import's). Fork only what you actually need to change, and as few files as you can -- a forked file stops taking the import's updates, so the more you fork the less an \`update-import\` can give you. To build something of your own rather than change theirs, write an ordinary file in this deck instead -- and check first whether the kit already lets a deck file register what you want (its CLAUDE.md names those seams), since that path keeps taking updates and a fork does not. When you do fork, it is often worth forking only to add a hook or registration point and keeping the logic itself in a deck file, so later changes need no further forks; for a quick one-off tweak a plain direct fork is fine.
11
11
  - **Deleting the deck directory itself needs the lock released first** (\`chmod -R u+w\` on the deck dir) — that is the one legitimate reason to touch the modes, and only for a directory being thrown away.
12
12
 
13
13
  ## Assets (every deck)
@@ -3,6 +3,13 @@ export interface FileChangeEntry {
3
3
  /** Deck-relative POSIX path. */
4
4
  path: string;
5
5
  event: 'add' | 'change' | 'delete';
6
+ /**
7
+ * The file was forked or reverted: it reads as a plain content change, since
8
+ * the imported path exists throughout, but which file is behind it moved. A
9
+ * consumer that only cares about contents can ignore this; one that shows fork
10
+ * state has no other way to know.
11
+ */
12
+ forkChanged?: boolean;
6
13
  /**
7
14
  * Deck-relative paths of modules affected via the Vite import graph: the
8
15
  * changed file itself (when it's part of the module graph) plus every
@@ -20,8 +27,11 @@ export declare function installFilesChangedWatcher(opts: {
20
27
  vite: ViteDevServer;
21
28
  projectDir: string;
22
29
  broadcast: (msg: FilesChangedMessage) => void;
23
- /** Drop Vite transform caches (so `import.meta.glob` rescans new files). */
24
- invalidate: () => void;
30
+ /**
31
+ * Drop Vite transform caches (so `import.meta.glob` rescans new files), and
32
+ * for any path named, its cached resolution too.
33
+ */
34
+ invalidate: (paths?: string[]) => void;
25
35
  /** Records what was broadcast, so we can see what fires and when. */
26
36
  log?: (line: string) => void;
27
37
  }): void;
@@ -6,7 +6,9 @@
6
6
  // file changed". Vite's own HMR stays fully OFF (`server.hmr: false` in
7
7
  // serve.ts) — reload decisions belong to consumers (the kit engine, editors,
8
8
  // the shell), not to Vite.
9
+ import * as fs from 'fs';
9
10
  import * as path from 'path';
11
+ import { FORKS_DIR, importedPathForFork } from './forks.js';
10
12
  const IGNORED_SEGMENTS = new Set(['node_modules', '.castle', '.git']);
11
13
  // Coalescing: a burst of writes (agent editing several files, an editor's
12
14
  // debounced saves landing together) becomes one message. DEBOUNCE resets per
@@ -31,14 +33,23 @@ export function installFilesChangedWatcher(opts) {
31
33
  .map(([relPath, change]) => ({
32
34
  path: relPath,
33
35
  event: change.event,
36
+ ...(change.forkChanged ? { forkChanged: true } : {}),
34
37
  affected: [...change.affected].sort(),
35
38
  }))
36
39
  .sort((a, b) => a.path.localeCompare(b.path));
37
40
  pending.clear();
38
41
  // New/deleted files can be picked up by `import.meta.glob` importers whose
39
42
  // cached transforms wouldn't rescan; drop caches like `restart` does.
40
- if (changes.some((c) => c.event !== 'change'))
41
- invalidate();
43
+ //
44
+ // A fork or revert has to name its path: it changes which FILE the imported
45
+ // path resolves to, which vite caches separately from the transform, and it
46
+ // arrives as a plain 'change' so the add/delete test alone would miss it.
47
+ // Driven from the watcher rather than the fork endpoint so it holds however
48
+ // the fork got there -- the CLI's `fork-import-file` runs in its own
49
+ // process and never touches this server.
50
+ const forked = changes.filter((c) => c.forkChanged).map((c) => c.path);
51
+ if (forked.length > 0 || changes.some((c) => c.event !== 'change'))
52
+ invalidate(forked);
42
53
  const affected = new Set();
43
54
  for (const change of changes) {
44
55
  affected.add(change.path);
@@ -59,7 +70,7 @@ export function installFilesChangedWatcher(opts) {
59
70
  maxTimer = setTimeout(flush, MAX_WAIT_MS);
60
71
  };
61
72
  vite.watcher.on('all', (watchEvent, absFile) => {
62
- const event = watchEvent === 'add' || watchEvent === 'change'
73
+ let event = watchEvent === 'add' || watchEvent === 'change'
63
74
  ? watchEvent
64
75
  : watchEvent === 'unlink'
65
76
  ? 'delete'
@@ -69,6 +80,13 @@ export function installFilesChangedWatcher(opts) {
69
80
  const relPath = deckRelative(projectDir, absFile);
70
81
  if (!relPath)
71
82
  return;
83
+ // Forking and reverting are add/unlink of a `forks/` file, but the path they
84
+ // are announced under is the imported one, which exists throughout. Only its
85
+ // contents moved, so say so -- a `delete` here would have consumers drop a
86
+ // file that is still there.
87
+ const forkChanged = isForkOfLivingImport(projectDir, absFile);
88
+ if (forkChanged)
89
+ event = 'change';
72
90
  // Compute the importer closure at event time: for deletes, Vite prunes the
73
91
  // file's graph entry shortly after the event, so waiting until flush would
74
92
  // lose the edges.
@@ -79,17 +97,24 @@ export function installFilesChangedWatcher(opts) {
79
97
  // 'add' for consumers; otherwise the newest event wins.
80
98
  if (!(existing.event === 'add' && event === 'change'))
81
99
  existing.event = event;
100
+ if (forkChanged)
101
+ existing.forkChanged = true;
82
102
  for (const p of affected)
83
103
  existing.affected.add(p);
84
104
  }
85
105
  else {
86
- pending.set(relPath, { event, affected: new Set(affected) });
106
+ pending.set(relPath, { event, forkChanged, affected: new Set(affected) });
87
107
  }
88
108
  schedule();
89
109
  });
90
110
  }
91
111
  // Deck-relative POSIX path, or null when the file is outside the deck or under
92
112
  // an ignored directory.
113
+ //
114
+ // A fork is reported under the IMPORTED path it stands in for, not its own. That
115
+ // imported path is what the deck calls the file everywhere -- it is the key in
116
+ // the kit's file map and the ref inside a scene -- so a change announced under
117
+ // `forks/...` matches nothing and a running deck never picks the edit up.
93
118
  function deckRelative(projectDir, absFile) {
94
119
  const rel = path.relative(projectDir, absFile);
95
120
  if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
@@ -97,8 +122,27 @@ function deckRelative(projectDir, absFile) {
97
122
  const posix = rel.split(path.sep).join('/');
98
123
  if (posix.split('/').some((segment) => IGNORED_SEGMENTS.has(segment)))
99
124
  return null;
125
+ if (posix.startsWith(`${FORKS_DIR}/`)) {
126
+ const imported = importedPathForFork(projectDir, absFile);
127
+ if (imported)
128
+ return path.relative(projectDir, imported).split(path.sep).join('/');
129
+ }
100
130
  return posix;
101
131
  }
132
+ // Whether a change to `absFile` is really a change to a path that still exists.
133
+ //
134
+ // Forking adds a file and reverting removes one, but the path consumers know --
135
+ // the imported one -- exists either way, and only its CONTENTS moved. Announcing
136
+ // the add/delete verbatim would have an editor drop the file from its map on a
137
+ // revert and show nothing, when what actually happened is that it went back to
138
+ // the import's copy.
139
+ function isForkOfLivingImport(projectDir, absFile) {
140
+ const rel = path.relative(projectDir, absFile).split(path.sep).join('/');
141
+ if (!rel.startsWith(`${FORKS_DIR}/`))
142
+ return false;
143
+ const imported = importedPathForFork(projectDir, absFile);
144
+ return !!imported && fs.existsSync(imported);
145
+ }
102
146
  function clientModuleGraph(vite) {
103
147
  try {
104
148
  const graph = vite
@@ -0,0 +1,61 @@
1
+ export declare const FORKS_DIR = "forks";
2
+ export interface ForkRecord {
3
+ /** The imported file's contents when the fork was taken. */
4
+ originalSha: string;
5
+ }
6
+ /** `imports/castle.physics-2d/engine/scene.js` -> alias + `engine/scene.js`. */
7
+ export declare function splitImportRel(relPosix: string): {
8
+ alias: string;
9
+ inner: string;
10
+ } | null;
11
+ export declare function sha(contents: Buffer | string): string;
12
+ /**
13
+ * The imported path a fork file stands in for: `.../forks/<alias>/<inner>` ->
14
+ * `<deck>/imports/<alias>/<inner>`. A fork's neighbours are the IMPORT's
15
+ * neighbours -- it is the same module with different bytes -- so a relative
16
+ * specifier inside one has to resolve from there, not from `forks/`.
17
+ */
18
+ export declare function importedPathForFork(deckDir: string, absFile: string): string | null;
19
+ /** This deck's own fork of an imported path, if it has one. */
20
+ export declare function ownForkFile(deckDir: string, relPosix: string): string | null;
21
+ /**
22
+ * The file that should actually be read for an imported path, or null for the
23
+ * import's own copy.
24
+ *
25
+ * Order: this deck's fork wins, then an importer's fork of a transitive
26
+ * dependency -- an import forked a file because its own code depends on the
27
+ * change, so ignoring that would run it against a file it was never tested
28
+ * against. Imports are walked in reverse declaration order and the first hit
29
+ * wins, matching the last-wins rule the registries already use.
30
+ */
31
+ export declare function resolveForkedFile(deckDir: string, relPosix: string): string | null;
32
+ export interface ForkState {
33
+ /** Whether anything overrides this imported path at all. */
34
+ forked: boolean;
35
+ /** Set when the fork is this deck's own, rather than one an import carries. */
36
+ ownFork: boolean;
37
+ /** The imported file's contents have changed since the fork was taken. */
38
+ originalChanged: boolean;
39
+ /** Whether this path may be forked at all -- see NON_FORKABLE. */
40
+ forkable: boolean;
41
+ }
42
+ /** Whether a path inside an import may be forked. */
43
+ export declare function isForkable(inner: string): boolean;
44
+ /**
45
+ * Fork state for an imported path. `originalChanged` compares contents rather
46
+ * than the import's version: an import can publish many versions without
47
+ * touching a given file, and saying it changed when it didn't is worse than
48
+ * saying nothing.
49
+ */
50
+ export declare function forkStateOf(deckDir: string, relPosix: string): ForkState;
51
+ /** Every imported path this deck has its own fork of. */
52
+ export declare function listOwnForks(deckDir: string): string[];
53
+ export interface ForkResult {
54
+ ok: boolean;
55
+ error?: string;
56
+ forkPath?: string;
57
+ }
58
+ /** Copy an imported file into `forks/` so this deck can change it. */
59
+ export declare function forkImportFile(deckDir: string, relPosix: string): ForkResult;
60
+ /** Drop this deck's fork, so the imported file is used again. */
61
+ export declare function revertImportFile(deckDir: string, relPosix: string): ForkResult;
package/dist/forks.js ADDED
@@ -0,0 +1,233 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { IMPORTS_DIR, readCastleJson } from './castleJson.js';
5
+ // A fork is this deck's own version of one file from an import, kept at the same
6
+ // path under `forks/` and substituted for the imported file wherever it is
7
+ // loaded. Same path, not a copy elsewhere, so every existing reference to it --
8
+ // a specifier, a glob key, a `@imports/...` string in a scene -- keeps resolving.
9
+ //
10
+ // `forks/` is deliberately NOT in SOURCE_ARCHIVE_EXCLUDES: unlike `imports/`,
11
+ // which a deck re-fetches from its pins, a fork exists nowhere else and has to
12
+ // travel with the deck.
13
+ export const FORKS_DIR = 'forks';
14
+ function isImportRel(relPosix) {
15
+ return relPosix.startsWith(`${IMPORTS_DIR}/`);
16
+ }
17
+ /** `imports/castle.physics-2d/engine/scene.js` -> alias + `engine/scene.js`. */
18
+ export function splitImportRel(relPosix) {
19
+ if (!isImportRel(relPosix))
20
+ return null;
21
+ const rest = relPosix.slice(IMPORTS_DIR.length + 1);
22
+ const slash = rest.indexOf('/');
23
+ if (slash <= 0)
24
+ return null;
25
+ return { alias: rest.slice(0, slash), inner: rest.slice(slash + 1) };
26
+ }
27
+ export function sha(contents) {
28
+ return crypto.createHash('sha256').update(contents).digest('hex');
29
+ }
30
+ function readPins(deckDir) {
31
+ return readCastleJson(deckDir)?.imports ?? {};
32
+ }
33
+ // Where a fork of `<alias>/<inner>` lives inside a given deck -- this deck, or
34
+ // an imported one that carries forks of its own.
35
+ function forkFileIn(deckRoot, alias, inner) {
36
+ return path.join(deckRoot, FORKS_DIR, alias, inner);
37
+ }
38
+ /**
39
+ * The imported path a fork file stands in for: `.../forks/<alias>/<inner>` ->
40
+ * `<deck>/imports/<alias>/<inner>`. A fork's neighbours are the IMPORT's
41
+ * neighbours -- it is the same module with different bytes -- so a relative
42
+ * specifier inside one has to resolve from there, not from `forks/`.
43
+ */
44
+ export function importedPathForFork(deckDir, absFile) {
45
+ const marker = `${path.sep}${FORKS_DIR}${path.sep}`;
46
+ const at = absFile.lastIndexOf(marker);
47
+ if (at < 0)
48
+ return null;
49
+ return path.join(deckDir, IMPORTS_DIR, absFile.slice(at + marker.length));
50
+ }
51
+ /** This deck's own fork of an imported path, if it has one. */
52
+ export function ownForkFile(deckDir, relPosix) {
53
+ const split = splitImportRel(relPosix);
54
+ if (!split)
55
+ return null;
56
+ const own = forkFileIn(deckDir, split.alias, split.inner);
57
+ return fs.existsSync(own) ? own : null;
58
+ }
59
+ /**
60
+ * The file that should actually be read for an imported path, or null for the
61
+ * import's own copy.
62
+ *
63
+ * Order: this deck's fork wins, then an importer's fork of a transitive
64
+ * dependency -- an import forked a file because its own code depends on the
65
+ * change, so ignoring that would run it against a file it was never tested
66
+ * against. Imports are walked in reverse declaration order and the first hit
67
+ * wins, matching the last-wins rule the registries already use.
68
+ */
69
+ export function resolveForkedFile(deckDir, relPosix) {
70
+ const split = splitImportRel(relPosix);
71
+ if (!split)
72
+ return null;
73
+ const own = forkFileIn(deckDir, split.alias, split.inner);
74
+ if (fs.existsSync(own))
75
+ return own;
76
+ const aliases = Object.keys(readPins(deckDir));
77
+ for (let i = aliases.length - 1; i >= 0; i--) {
78
+ const owner = aliases[i];
79
+ if (owner === split.alias)
80
+ continue;
81
+ const viaImport = forkFileIn(path.join(deckDir, IMPORTS_DIR, owner), split.alias, split.inner);
82
+ if (fs.existsSync(viaImport))
83
+ return viaImport;
84
+ }
85
+ return null;
86
+ }
87
+ // Files that describe an import rather than being part of what it does. The
88
+ // overlay is a VITE overlay: it redirects module resolution, so a file the deck
89
+ // only ever reads through Node -- an import's manifest, read by readCastleJson
90
+ // at its real path -- would be forked to no effect and no error. Refusing is the
91
+ // honest answer until forking one of these means something.
92
+ //
93
+ // Matched against the path INSIDE the import, so this is the import's own root
94
+ // manifest and not some `scenes/castle.json` a deck happens to have.
95
+ const NON_FORKABLE = new Set(['castle.json']);
96
+ /** Whether a path inside an import may be forked. */
97
+ export function isForkable(inner) {
98
+ return !NON_FORKABLE.has(inner);
99
+ }
100
+ /**
101
+ * Fork state for an imported path. `originalChanged` compares contents rather
102
+ * than the import's version: an import can publish many versions without
103
+ * touching a given file, and saying it changed when it didn't is worse than
104
+ * saying nothing.
105
+ */
106
+ export function forkStateOf(deckDir, relPosix) {
107
+ const split = splitImportRel(relPosix);
108
+ const none = { forked: false, ownFork: false, originalChanged: false, forkable: false };
109
+ if (!split)
110
+ return none;
111
+ const forkable = isForkable(split.inner);
112
+ const resolved = resolveForkedFile(deckDir, relPosix);
113
+ if (!resolved)
114
+ return { ...none, forkable };
115
+ const ownFork = resolved === forkFileIn(deckDir, split.alias, split.inner);
116
+ const record = readPins(deckDir)[split.alias]?.forks?.[split.inner];
117
+ let originalChanged = false;
118
+ if (ownFork && record?.originalSha) {
119
+ try {
120
+ originalChanged = sha(fs.readFileSync(path.join(deckDir, relPosix))) !== record.originalSha;
121
+ }
122
+ catch {
123
+ // The imported file is gone -- upstream deleted it. Nothing to compare,
124
+ // and the fork is now the only copy.
125
+ }
126
+ }
127
+ return { forked: true, ownFork, originalChanged, forkable };
128
+ }
129
+ /** Every imported path this deck has its own fork of. */
130
+ export function listOwnForks(deckDir) {
131
+ const out = [];
132
+ const root = path.join(deckDir, FORKS_DIR);
133
+ const walk = (dir, prefix) => {
134
+ let entries;
135
+ try {
136
+ entries = fs.readdirSync(dir, { withFileTypes: true });
137
+ }
138
+ catch {
139
+ return;
140
+ }
141
+ for (const entry of entries) {
142
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
143
+ if (entry.isDirectory())
144
+ walk(path.join(dir, entry.name), rel);
145
+ else
146
+ out.push(`${IMPORTS_DIR}/${rel}`);
147
+ }
148
+ };
149
+ walk(root, '');
150
+ return out.sort();
151
+ }
152
+ function writeForkRecord(deckDir, alias, inner, record) {
153
+ const existing = (readCastleJson(deckDir) ?? {});
154
+ const pins = { ...(existing.imports ?? {}) };
155
+ const pin = pins[alias];
156
+ if (!pin)
157
+ return;
158
+ const forks = { ...(pin.forks ?? {}) };
159
+ if (record)
160
+ forks[inner] = record;
161
+ else
162
+ delete forks[inner];
163
+ pins[alias] = Object.keys(forks).length ? { ...pin, forks } : stripForks(pin);
164
+ fs.writeFileSync(path.join(deckDir, 'castle.json'), JSON.stringify({ ...existing, imports: pins }, null, 2) + '\n', 'utf-8');
165
+ }
166
+ function stripForks(pin) {
167
+ const next = { ...pin };
168
+ delete next.forks;
169
+ return next;
170
+ }
171
+ /** Copy an imported file into `forks/` so this deck can change it. */
172
+ export function forkImportFile(deckDir, relPosix) {
173
+ const split = splitImportRel(relPosix);
174
+ if (!split)
175
+ return { ok: false, error: `${relPosix} is not a file from an import.` };
176
+ const source = path.join(deckDir, relPosix);
177
+ if (!fs.existsSync(source) || !fs.statSync(source).isFile()) {
178
+ return { ok: false, error: `No imported file at ${relPosix}.` };
179
+ }
180
+ if (!readPins(deckDir)[split.alias]) {
181
+ return { ok: false, error: `This deck has no import named "${split.alias}".` };
182
+ }
183
+ if (!isForkable(split.inner)) {
184
+ return {
185
+ ok: false,
186
+ error: `${split.inner} describes the import itself, so it can't be forked.`,
187
+ };
188
+ }
189
+ const dest = forkFileIn(deckDir, split.alias, split.inner);
190
+ if (fs.existsSync(dest))
191
+ return { ok: false, error: `${relPosix} is already forked.` };
192
+ const contents = fs.readFileSync(source);
193
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
194
+ fs.writeFileSync(dest, contents);
195
+ // Writable, unlike the import it came from -- being editable is the point.
196
+ fs.chmodSync(dest, 0o644);
197
+ writeForkRecord(deckDir, split.alias, split.inner, { originalSha: sha(contents) });
198
+ return { ok: true, forkPath: `${FORKS_DIR}/${split.alias}/${split.inner}` };
199
+ }
200
+ /** Drop this deck's fork, so the imported file is used again. */
201
+ export function revertImportFile(deckDir, relPosix) {
202
+ const split = splitImportRel(relPosix);
203
+ if (!split)
204
+ return { ok: false, error: `${relPosix} is not a file from an import.` };
205
+ const dest = forkFileIn(deckDir, split.alias, split.inner);
206
+ if (!fs.existsSync(dest))
207
+ return { ok: false, error: `${relPosix} is not forked in this deck.` };
208
+ fs.rmSync(dest);
209
+ pruneEmptyDirs(path.dirname(dest), path.join(deckDir, FORKS_DIR));
210
+ writeForkRecord(deckDir, split.alias, split.inner, null);
211
+ return { ok: true };
212
+ }
213
+ function pruneEmptyDirs(dir, stopAt) {
214
+ let current = dir;
215
+ while (current.startsWith(stopAt) && current !== stopAt) {
216
+ try {
217
+ if (fs.readdirSync(current).length > 0)
218
+ return;
219
+ fs.rmdirSync(current);
220
+ }
221
+ catch {
222
+ return;
223
+ }
224
+ current = path.dirname(current);
225
+ }
226
+ try {
227
+ if (fs.existsSync(stopAt) && fs.readdirSync(stopAt).length === 0)
228
+ fs.rmdirSync(stopAt);
229
+ }
230
+ catch {
231
+ /* leaving an empty forks/ behind is harmless */
232
+ }
233
+ }
package/dist/ide.d.ts CHANGED
@@ -23,4 +23,9 @@ export declare function createIdeServer(opts: {
23
23
  deckLabel: string;
24
24
  /** Drop transform caches and reload every open tab. */
25
25
  restart?: () => void;
26
+ /**
27
+ * Drop transform caches only, leaving open panels alone. `paths` are
28
+ * deck-relative paths whose resolution changed, not just their contents.
29
+ */
30
+ invalidate?: (paths?: string[]) => void;
26
31
  }): IdeServer;