castle-web-cli 0.4.137 → 0.4.139

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/ide.js CHANGED
@@ -16,6 +16,7 @@ import headlessPkg from '@xterm/headless';
16
16
  import { SerializeAddon } from '@xterm/addon-serialize';
17
17
  import { WebSocketServer } from 'ws';
18
18
  import { IMPORTS_DIR, importStatuses, updateImport } from './imports.js';
19
+ import { FORKS_DIR, forkImportFile, forkStateOf, listOwnForks, ownForkFile, resolveForkedFile, revertImportFile, } from './forks.js';
19
20
  import { ensureVisibleGlob, ensureVisiblePath } from './castleJson.js';
20
21
  import { readEditorConfig, resolveFileTypes, } from './editorConfig.js';
21
22
  import { UNSUPPORTED_MEDIA } from './unsupportedMedia.js';
@@ -155,7 +156,7 @@ export const COVER_API_PATH = '/__castle/cover';
155
156
  export { COVER_FILE };
156
157
  // Directories never surfaced in the file list / never read or written through
157
158
  // the builtin editor: VCS, deck-private state, and dependency trees.
158
- const FILES_IGNORE_DIRS = new Set(['.git', '.castle', 'node_modules', 'dist']);
159
+ const FILES_IGNORE_DIRS = new Set(['.git', '.castle', 'node_modules', 'dist', FORKS_DIR]);
159
160
  // Never writable through the files API, whatever the tree shows. `.castle` holds
160
161
  // the deck's private state, and since build 1 that includes the version store --
161
162
  // the one place where losing bytes loses history rather than a file. The list
@@ -197,8 +198,8 @@ const RAW_MIME = {
197
198
  // Files under `imports/` came from another deck. They are readable like any
198
199
  // other deck file -- the engine, editors and pickers all reference them -- but a
199
200
  // deck can't edit them, because editing one would mean editing somebody else's
200
- // deck. (Keeping your own version of a dependency's file is forking, a later
201
- // feature; copying it out into the deck works meanwhile.)
201
+ // deck. To change one, fork it: the deck's own copy lives under `forks/` and
202
+ // stands in for the imported path everywhere.
202
203
  function isImportPath(rel) {
203
204
  return rel === IMPORTS_DIR || rel.startsWith(`${IMPORTS_DIR}/`);
204
205
  }
@@ -234,11 +235,24 @@ function resolveDeckPath(deckDir, requestedPath, opts = {}) {
234
235
  return { ok: false, error: `Path outside the deck: ${requestedPath}` };
235
236
  }
236
237
  const relPosix = rel.split(path.sep).join('/');
237
- if (opts.mutation && isImportPath(relPosix)) {
238
- return {
239
- ok: false,
240
- error: `${relPosix} belongs to an imported deck and is read-only.`,
241
- };
238
+ // An imported path answers with whatever overrides it, keeping `rel` as the
239
+ // imports path -- that is what the deck calls this file everywhere else, and
240
+ // only the file on disk changes.
241
+ //
242
+ // This deck's OWN fork is writable: being editable is the whole reason to make
243
+ // one. A fork an import carries is not -- it belongs to that import, same as
244
+ // the file it overrides.
245
+ if (isImportPath(relPosix)) {
246
+ const own = ownForkFile(deckDir, relPosix);
247
+ if (own)
248
+ return { ok: true, abs: own, rel: relPosix };
249
+ if (opts.mutation) {
250
+ return {
251
+ ok: false,
252
+ error: `${relPosix} belongs to an imported deck and is read-only. Fork it to make changes.`,
253
+ };
254
+ }
255
+ return { ok: true, abs: resolveForkedFile(deckDir, relPosix) ?? abs, rel: relPosix };
242
256
  }
243
257
  return { ok: true, abs, rel: relPosix };
244
258
  }
@@ -494,8 +508,8 @@ function handleFilesMkdir(deckDir, req, res) {
494
508
  // until then is what stops a deck's public cover running ahead of the version
495
509
  // people can actually play.
496
510
  function handleCoverApi(deckDir, req, res) {
497
- if (req.method !== "POST") {
498
- sendJson(res, 405, { error: "Use POST to store a cover." });
511
+ if (req.method !== 'POST') {
512
+ sendJson(res, 405, { error: 'Use POST to store a cover.' });
499
513
  return true;
500
514
  }
501
515
  void readRequestBuffer(req, MAX_UPLOAD_BYTES).then((bytes) => {
@@ -503,7 +517,7 @@ function handleCoverApi(deckDir, req, res) {
503
517
  fs.writeFileSync(path.join(deckDir, COVER_FILE), bytes);
504
518
  }
505
519
  catch (err) {
506
- return sendFailure(res, "write", COVER_FILE, err);
520
+ return sendFailure(res, 'write', COVER_FILE, err);
507
521
  }
508
522
  return sendJson(res, 200, { ok: true, bytes: bytes.length });
509
523
  }, () => {
@@ -695,7 +709,7 @@ function handleFilesDelete(deckDir, req, res) {
695
709
  // The builtin Files + code-editor backend: list / read / write deck files and
696
710
  // report kit-owned editor extensions. Paths are deck-relative; resolveDeckPath
697
711
  // rejects traversal and protected dirs.
698
- function handleFilesApi(deckDir, req, res, reqPath, restart) {
712
+ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
699
713
  const action = reqPath.slice(FILES_API_PREFIX.length);
700
714
  if (action === 'info') {
701
715
  const config = readEditorConfig(deckDir);
@@ -753,6 +767,51 @@ function handleFilesApi(deckDir, req, res, reqPath, restart) {
753
767
  })();
754
768
  return true;
755
769
  }
770
+ if (action === 'forks') {
771
+ // `?path=` asks about ONE path, forked or not -- how a caller that already
772
+ // knows which file it is showing gets an answer that includes whether the
773
+ // path may be forked at all. Same shape as the list so callers share a
774
+ // parser.
775
+ const asked = new URL(req.url ?? '', 'http://localhost').searchParams.get('path');
776
+ if (asked) {
777
+ sendJson(res, 200, { forks: [{ path: asked, ...forkStateOf(deckDir, asked) }] });
778
+ return true;
779
+ }
780
+ // Which imported paths this deck overrides, and whether the file each one
781
+ // was taken from has changed since.
782
+ const paths = listOwnForks(deckDir);
783
+ sendJson(res, 200, {
784
+ forks: paths.map((p) => ({ path: p, ...forkStateOf(deckDir, p) })),
785
+ });
786
+ return true;
787
+ }
788
+ if (action === 'fork' || action === 'revert-fork') {
789
+ void (async () => {
790
+ let body;
791
+ try {
792
+ body = JSON.parse(await readRequestBody(req));
793
+ }
794
+ catch {
795
+ return sendJson(res, 400, { error: 'Invalid JSON body.' });
796
+ }
797
+ if (typeof body.path !== 'string' || !body.path) {
798
+ return sendJson(res, 400, { error: 'Missing file path.' });
799
+ }
800
+ const forkPath = body.path;
801
+ const result = action === 'fork' ? forkImportFile(deckDir, forkPath) : revertImportFile(deckDir, forkPath);
802
+ if (!result.ok)
803
+ return sendJson(res, 400, { error: result.error });
804
+ sendJson(res, 200, { ok: true, path: forkPath, ...forkStateOf(deckDir, forkPath) });
805
+ // Which file an imported path resolves to just changed, and vite has the
806
+ // old answer cached -- after a revert it holds the id of a file that no
807
+ // longer exists and asks for it on the next request. Invalidate, but do
808
+ // NOT reload: the watcher announces the change under the imported path,
809
+ // and every panel decides for itself from there (Play offers a restart
810
+ // rather than taking one).
811
+ setImmediate(() => invalidate?.([forkPath]));
812
+ })();
813
+ return true;
814
+ }
756
815
  if (action === 'versions') {
757
816
  handleVersionsList(deckDir, res);
758
817
  return true;
@@ -1071,7 +1130,7 @@ export function createIdeServer(opts) {
1071
1130
  return handleCoverApi(deckDir, req, res);
1072
1131
  }
1073
1132
  if (reqPath.startsWith(FILES_API_PREFIX)) {
1074
- return handleFilesApi(deckDir, req, res, reqPath, opts.restart);
1133
+ return handleFilesApi(deckDir, req, res, reqPath, opts.restart, opts.invalidate);
1075
1134
  }
1076
1135
  if (reqPath.startsWith(IMPORT_API_PREFIX)) {
1077
1136
  return handleImportApi(deckDir, req, res, reqPath, opts.restart);
package/dist/imports.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export declare const IMPORTS_DIR = "imports";
1
+ import { IMPORTS_DIR } from './castleJson.js';
2
+ export { IMPORTS_DIR };
2
3
  export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'no-such-dir' | 'self-import' | 'no-source' | 'bad-alias';
3
4
  export declare class ImportError extends Error {
4
5
  code: ImportErrorCode;
package/dist/imports.js CHANGED
@@ -5,7 +5,7 @@ import * as api from './api.js';
5
5
  import { runTar } from './save-deck.js';
6
6
  import { normalizeDeckPackageJson } from './normalize.js';
7
7
  import { getKitsDir } from './localPaths.js';
8
- import { ensureVisibleGlob, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
8
+ import { ensureVisibleGlob, IMPORTS_DIR, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
9
9
  // Adding another deck as a dependency (`castle-web add-import`; removing one is a
10
10
  // later command). Deliberately NOT `get-deck`: that one
11
11
  // replaces THIS deck's own source from the server (and carries guards for the
@@ -24,7 +24,7 @@ import { ensureVisibleGlob, readCastleJson as tryReadCastleJson, readCastleJsonO
24
24
  // dependency, and the files are re-fetchable from them -- same treatment
25
25
  // node_modules gets. That also means `get-deck` leaves an existing `imports/`
26
26
  // alone when it refreshes a deck.
27
- export const IMPORTS_DIR = 'imports';
27
+ export { IMPORTS_DIR };
28
28
  export class ImportError extends Error {
29
29
  code;
30
30
  constructor(code, message) {
@@ -60,9 +60,17 @@ export function parseDeckRef(raw) {
60
60
  // editor config) is preserved as-is.
61
61
  function writeImportPin(dir, alias, pin) {
62
62
  const existing = readCastleJson(dir) ?? {};
63
+ // Forks belong to the DECK, not to the pin: the files live in its own forks/
64
+ // and an import update or restore doesn't touch them. Writing a fresh pin over
65
+ // the old one would drop the map while leaving the files, so the deck keeps
66
+ // reading its forks with nothing left to say the originals had moved.
67
+ const carried = existing.imports?.[alias]?.forks;
63
68
  const next = {
64
69
  ...existing,
65
- imports: { ...(existing.imports ?? {}), [alias]: pin },
70
+ imports: {
71
+ ...(existing.imports ?? {}),
72
+ [alias]: pin.forks || !carried ? pin : { ...pin, forks: carried },
73
+ },
66
74
  };
67
75
  fs.writeFileSync(path.join(dir, 'castle.json'), JSON.stringify(next, null, 2) + '\n', 'utf-8');
68
76
  }
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { addImport, updateImport } from './imports.js';
9
9
  import { listDecks } from './list-decks.js';
10
10
  import { getCliVersion, init } from './init.js';
11
11
  import { install } from './install.js';
12
+ import { forkImportFile, revertImportFile } from './forks.js';
12
13
  import { connectWS, takeScreenshot } from './preview.js';
13
14
  import { listVersions, restoreVersion, saveVersion, showVersion } from './versions.js';
14
15
  const args = process.argv.slice(2);
@@ -96,6 +97,8 @@ function usage() {
96
97
  castle-web get-deck [dir] [--deck-id ID] [--force] (replaces the source if the deck is already there)
97
98
  castle-web list-decks [dir] [--kind mine|saved|kits] (decks this one could import; ids are what add-import takes)
98
99
  castle-web add-import <deckId|url> [dir] [--as ALIAS] (adds another deck as a read-only dependency in imports/)
100
+ castle-web fork-import-file <imports/...> [dir] (this deck's own version of one imported file)
101
+ castle-web revert-import-file <imports/...> [dir]
99
102
  castle-web update-import [alias] [dir] [--check] [--revert] (re-fetches imports; no alias means all)
100
103
  castle-web install [dir]
101
104
  castle-web save-version [-m MESSAGE] [paths...] [--dir DIR] (no paths saves the whole deck)
@@ -170,6 +173,27 @@ async function main() {
170
173
  await listDecks(findPositionalDir(), { kind: getFlagValue('--kind') });
171
174
  break;
172
175
  }
176
+ case 'fork-import-file': {
177
+ // `castle-web fork-import-file <imports/...> [dir]`
178
+ const positionals = readPositionals();
179
+ const result = forkImportFile(path.resolve(positionals[1] ?? '.'), positionals[0] ?? '');
180
+ if (!result.ok) {
181
+ console.error(result.error);
182
+ process.exit(1);
183
+ }
184
+ console.log(`Forked to ${result.forkPath}`);
185
+ break;
186
+ }
187
+ case 'revert-import-file': {
188
+ const positionals = readPositionals();
189
+ const result = revertImportFile(path.resolve(positionals[1] ?? '.'), positionals[0] ?? '');
190
+ if (!result.ok) {
191
+ console.error(result.error);
192
+ process.exit(1);
193
+ }
194
+ console.log('Reverted to the imported file.');
195
+ break;
196
+ }
173
197
  case 'add-import': {
174
198
  // The deck -- an id or the link to its page -- is the first positional;
175
199
  // the importing deck's dir is an optional second, defaulting to the cwd.
package/dist/save-deck.js CHANGED
@@ -17,11 +17,17 @@ export const SOURCE_ARCHIVE_EXCLUDES = ['node_modules', 'dist', '.castle', '.git
17
17
  // (`-tzf`), where the output IS the answer. Packing and unpacking ignore it.
18
18
  export function runTar(args, opts = {}) {
19
19
  return new Promise((resolve, reject) => {
20
- const child = spawn('tar', args, { stdio: ['ignore', opts.capture ? 'pipe' : 'ignore', 'pipe'] });
20
+ const child = spawn('tar', args, {
21
+ stdio: ['ignore', opts.capture ? 'pipe' : 'ignore', 'pipe'],
22
+ });
21
23
  let stdout = '';
22
24
  let stderr = '';
23
- child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
24
- child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
25
+ child.stdout?.on('data', (chunk) => {
26
+ stdout += chunk.toString();
27
+ });
28
+ child.stderr?.on('data', (chunk) => {
29
+ stderr += chunk.toString();
30
+ });
25
31
  child.on('error', reject);
26
32
  child.on('close', (code) => {
27
33
  if (code !== 0) {
@@ -46,7 +52,9 @@ export async function archiveSource(projectDir) {
46
52
  try {
47
53
  fs.unlinkSync(tmpFile);
48
54
  }
49
- catch { /* nothing to clean */ }
55
+ catch {
56
+ /* nothing to clean */
57
+ }
50
58
  }
51
59
  }
52
60
  async function uploadSource(projectDir, deckId) {
@@ -175,8 +183,8 @@ export async function saveDeck(dir, opts = {}) {
175
183
  }
176
184
  // `--visibility` arrives as an unchecked string from the command line, so the
177
185
  // declared type is no guarantee -- widen to validate what actually came in.
178
- const requested = opts.visibility ?? 'unlisted';
179
- if (requested !== 'unlisted' && requested !== 'private') {
186
+ const requested = opts.visibility;
187
+ if (requested !== undefined && requested !== 'unlisted' && requested !== 'private') {
180
188
  console.error(`Invalid visibility "${requested}". Use unlisted or private.`);
181
189
  process.exit(1);
182
190
  }
@@ -220,7 +228,15 @@ export async function saveDeck(dir, opts = {}) {
220
228
  throw new Error(`Upload failed: HTTP ${s3Res.status}`);
221
229
  }
222
230
  const title = opts.title ?? castleJson?.title ?? path.basename(path.resolve(projectDir));
223
- const deckInput = { deckId, title, visibility };
231
+ const deckInput = { deckId, title };
232
+ // Omitted unless asked for, or the deck is new and needs one: updateDeckV2
233
+ // only touches visibility when it is sent, so a deck the creator published
234
+ // from the app stays public instead of being knocked down to unlisted by a
235
+ // routine save. This CLI still cannot make a deck public.
236
+ if (visibility)
237
+ deckInput.visibility = visibility;
238
+ else if (isNew)
239
+ deckInput.visibility = 'unlisted';
224
240
  if (opts.caption !== undefined)
225
241
  deckInput.caption = opts.caption;
226
242
  const backgroundImageFileId = await uploadLocalCover(projectDir);
package/dist/serve.js CHANGED
@@ -2,13 +2,14 @@ import * as fs from 'fs';
2
2
  import * as net from 'net';
3
3
  import * as path from 'path';
4
4
  import { spawn } from 'child_process';
5
- import { createServer } from 'vite';
5
+ import { createServer, } from 'vite';
6
6
  import { WebSocketServer, WebSocket } from 'ws';
7
7
  import { createIdeServer, FAVICON_LINK_TAGS } from './ide.js';
8
8
  import { createAgentServer } from './agent.js';
9
- import { sceneFilesPlugin, importsAliasPlugin } from './vitePlugins.js';
9
+ import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin } from './vitePlugins.js';
10
10
  import { installFilesChangedWatcher } from './filesChanged.js';
11
- import { autoUpdateImports } from './imports.js';
11
+ import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
12
+ import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
12
13
  import * as config from './config.js';
13
14
  import { graphql as castleGraphql } from './api.js';
14
15
  import { executeCommand } from './castle-host/host.js';
@@ -213,6 +214,26 @@ function existingServe(projectDir) {
213
214
  return null;
214
215
  return info;
215
216
  }
217
+ function lockExistingImports(projectDir) {
218
+ const importsDir = path.join(projectDir, IMPORTS_DIR);
219
+ let aliases;
220
+ try {
221
+ aliases = fs.readdirSync(importsDir);
222
+ }
223
+ catch {
224
+ return;
225
+ }
226
+ for (const alias of aliases) {
227
+ const dir = path.join(importsDir, alias);
228
+ try {
229
+ if (fs.statSync(dir).isDirectory())
230
+ lockImportTree(dir);
231
+ }
232
+ catch {
233
+ /* a raced removal is not a reason to refuse to serve */
234
+ }
235
+ }
236
+ }
216
237
  export async function serve(dir, options = {}) {
217
238
  const projectDir = path.resolve(dir);
218
239
  if (!fs.existsSync(projectDir)) {
@@ -223,6 +244,11 @@ export async function serve(dir, options = {}) {
223
244
  console.error(`No index.html found in ${projectDir}`);
224
245
  process.exit(1);
225
246
  }
247
+ // Imports are locked where they are placed, but nothing re-locks one that is
248
+ // already here -- so a deck whose imports arrived any other way, or from a CLI
249
+ // that predates the locking, stayed writable forever. That is why edits to an
250
+ // imported file stuck on some decks and not others. Cheap and idempotent.
251
+ lockExistingImports(projectDir);
226
252
  // If a live serve is already running for this deck, reuse it. Skip the
227
253
  // dedup when --port / --host are passed (caller wants those specifics, so
228
254
  // start a fresh serve even if another is up).
@@ -324,6 +350,11 @@ export async function serve(dir, options = {}) {
324
350
  invalidateModuleCaches(viteHolder.vite);
325
351
  broadcast({ type: 'restart' });
326
352
  },
353
+ // Invalidation WITHOUT the reload, for a change that alters what a path
354
+ // resolves to but is not a reason to pull a panel out from under anyone --
355
+ // the watcher's files_changed already tells the shell, and the panels decide
356
+ // for themselves what to do with it.
357
+ invalidate: (paths) => invalidateModuleCaches(viteHolder.vite, paths),
327
358
  });
328
359
  process.on('exit', () => ideServer.shutdown());
329
360
  // The agent panel backend: router conversation + background task agents,
@@ -349,6 +380,7 @@ export async function serve(dir, options = {}) {
349
380
  root: projectDir,
350
381
  plugins: [
351
382
  castlePlugin(wsPort, ideServer, agentServer),
383
+ forksOverlayPlugin(),
352
384
  importsAliasPlugin(),
353
385
  sceneFilesPlugin(),
354
386
  ],
@@ -378,7 +410,7 @@ export async function serve(dir, options = {}) {
378
410
  vite,
379
411
  projectDir,
380
412
  broadcast,
381
- invalidate: () => invalidateModuleCaches(vite),
413
+ invalidate: (paths) => invalidateModuleCaches(vite, paths),
382
414
  log: (line) => appendCapped(logFile, line),
383
415
  });
384
416
  await vite.listen();
@@ -398,20 +430,65 @@ export async function serve(dir, options = {}) {
398
430
  // (e.g. a new behavior in `behaviors/`) would otherwise be missed because the
399
431
  // cached glob importer is re-served as-is. Invalidating the graph forces every
400
432
  // module to re-transform on the next request, so the glob is rescanned.
401
- function invalidateModuleCaches(vite) {
433
+ //
434
+ // `paths` are deck-relative paths whose RESOLUTION changed, not just their
435
+ // contents -- forking and reverting move an imported path between the import's
436
+ // file and the fork's, and invalidateAll does not touch that mapping.
437
+ function invalidateModuleCaches(vite, paths) {
402
438
  if (!vite)
403
439
  return;
404
440
  try {
405
441
  const clientGraph = vite.environments?.client?.moduleGraph;
406
- if (clientGraph)
407
- clientGraph.invalidateAll();
408
- else
442
+ if (!clientGraph) {
409
443
  vite.moduleGraph.invalidateAll();
444
+ return;
445
+ }
446
+ clientGraph.invalidateAll();
447
+ for (const rel of paths ?? [])
448
+ forgetResolution(clientGraph, rel);
410
449
  }
411
450
  catch {
412
451
  // Vite changed its graph shape between minor versions — best-effort
413
452
  }
414
453
  }
454
+ // Drop every module node reached by a deck-relative path, so the next request
455
+ // for it resolves from scratch. Both ends of a fork are dropped: the imported
456
+ // path is what the browser asks for, and the fork's own path is what the node
457
+ // behind it points at.
458
+ //
459
+ // `_unresolvedUrlToModuleMap` is the one that matters and it is internal to
460
+ // vite, hence the cast -- it is consulted BEFORE resolveId runs, so a plugin
461
+ // that would now answer differently never gets asked.
462
+ function forgetResolution(graph, relPosix) {
463
+ const split = splitImportRel(relPosix);
464
+ const urls = new Set([`/${relPosix}`]);
465
+ if (split)
466
+ urls.add(`/${FORKS_DIR}/${split.alias}/${split.inner}`);
467
+ const unresolved = graph
468
+ ._unresolvedUrlToModuleMap;
469
+ const stale = new Set();
470
+ // Keys carry the query the file was asked for with (`?raw` for every data file
471
+ // a kit reaches through import.meta.glob), so match on the path alone.
472
+ const collect = (map) => {
473
+ for (const key of [...map.keys()]) {
474
+ if (!urls.has(key.split('?')[0]))
475
+ continue;
476
+ const mod = map.get(key);
477
+ map.delete(key);
478
+ if (mod && typeof mod.id === 'string') {
479
+ stale.add(mod);
480
+ }
481
+ }
482
+ };
483
+ collect(unresolved);
484
+ collect(graph.urlToModuleMap);
485
+ for (const mod of stale) {
486
+ if (mod.id)
487
+ graph.idToModuleMap.delete(mod.id);
488
+ if (mod.file)
489
+ graph.fileToModulesMap.get(mod.file)?.delete(mod);
490
+ }
491
+ }
415
492
  async function serveDetached(projectDir, options) {
416
493
  const castleDir = path.join(projectDir, '.castle');
417
494
  if (!fs.existsSync(castleDir))
@@ -651,9 +728,27 @@ function writeProjectFile(projectDir, requestedPath, contents) {
651
728
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
652
729
  return { ok: false, error: `Refusing to write outside the deck: ${requestedPath}` };
653
730
  }
731
+ // Imported files belong to the deck that published them. This is the write
732
+ // path the kit editors use, and it had no check of its own -- it leaned on the
733
+ // read-only bits on disk, so a deck whose imports were never locked took the
734
+ // write, and a locked one failed with EACCES into the deck's log where nobody
735
+ // reads it. Decide it here instead, and send the write to this deck's fork
736
+ // when it has one, which is the whole point of having forked.
737
+ const relPosix = relative.split(path.sep).join('/');
738
+ let target = filepath;
739
+ if (relPosix.startsWith(`${IMPORTS_DIR}/`)) {
740
+ const fork = ownForkFile(projectDir, relPosix);
741
+ if (!fork) {
742
+ return {
743
+ ok: false,
744
+ error: `${relPosix} belongs to an imported deck and is read-only. Fork it to make changes.`,
745
+ };
746
+ }
747
+ target = fork;
748
+ }
654
749
  try {
655
- fs.mkdirSync(path.dirname(filepath), { recursive: true });
656
- fs.writeFileSync(filepath, contents, 'utf-8');
750
+ fs.mkdirSync(path.dirname(target), { recursive: true });
751
+ fs.writeFileSync(target, contents, 'utf-8');
657
752
  return { ok: true, path: normalized };
658
753
  }
659
754
  catch (error) {