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.
- package/dist/agent-prompts.js +15 -0
- package/dist/agent.js +9 -0
- package/dist/api.js +4 -1
- package/dist/bundle.js +2 -2
- package/dist/castleJson.d.ts +4 -0
- package/dist/castleJson.js +5 -0
- package/dist/commonInstructions.d.ts +1 -1
- package/dist/commonInstructions.js +1 -1
- package/dist/filesChanged.d.ts +12 -2
- package/dist/filesChanged.js +48 -4
- package/dist/forks.d.ts +61 -0
- package/dist/forks.js +233 -0
- package/dist/ide.d.ts +5 -0
- package/dist/ide.js +81 -13
- package/dist/imports.d.ts +2 -1
- package/dist/imports.js +11 -3
- package/dist/index.js +24 -0
- package/dist/serve.js +110 -11
- package/dist/shell/assets/index-CAN0bnXn.css +1 -0
- package/dist/shell/assets/index-DDJUiBek.js +441 -0
- package/dist/shell/index.html +2 -2
- package/dist/vitePlugins.d.ts +1 -0
- package/dist/vitePlugins.js +58 -0
- package/dist/wsOrigin.d.ts +2 -0
- package/dist/wsOrigin.js +20 -0
- package/kits/physics-2d/castle.json +1 -1
- package/kits/physics-2d/editors/SingleEditor.jsx +43 -10
- package/kits/physics-3d/castle.json +1 -1
- package/package.json +1 -1
- package/dist/shell/assets/index-Bx4sNpO5.css +0 -1
- package/dist/shell/assets/index-DNDk8nRG.js +0 -441
package/dist/ide.js
CHANGED
|
@@ -12,10 +12,12 @@ import picomatch from 'picomatch';
|
|
|
12
12
|
import { fileURLToPath } from 'url';
|
|
13
13
|
import { createRequire } from 'module';
|
|
14
14
|
import { spawn as spawnPty } from '@lydell/node-pty';
|
|
15
|
+
import { isSameOriginUpgrade } from './wsOrigin.js';
|
|
15
16
|
import headlessPkg from '@xterm/headless';
|
|
16
17
|
import { SerializeAddon } from '@xterm/addon-serialize';
|
|
17
18
|
import { WebSocketServer } from 'ws';
|
|
18
19
|
import { IMPORTS_DIR, importStatuses, updateImport } from './imports.js';
|
|
20
|
+
import { FORKS_DIR, forkImportFile, forkStateOf, listOwnForks, ownForkFile, resolveForkedFile, revertImportFile, } from './forks.js';
|
|
19
21
|
import { ensureVisibleGlob, ensureVisiblePath } from './castleJson.js';
|
|
20
22
|
import { readEditorConfig, resolveFileTypes, } from './editorConfig.js';
|
|
21
23
|
import { UNSUPPORTED_MEDIA } from './unsupportedMedia.js';
|
|
@@ -155,7 +157,7 @@ export const COVER_API_PATH = '/__castle/cover';
|
|
|
155
157
|
export { COVER_FILE };
|
|
156
158
|
// Directories never surfaced in the file list / never read or written through
|
|
157
159
|
// the builtin editor: VCS, deck-private state, and dependency trees.
|
|
158
|
-
const FILES_IGNORE_DIRS = new Set(['.git', '.castle', 'node_modules', 'dist']);
|
|
160
|
+
const FILES_IGNORE_DIRS = new Set(['.git', '.castle', 'node_modules', 'dist', FORKS_DIR]);
|
|
159
161
|
// Never writable through the files API, whatever the tree shows. `.castle` holds
|
|
160
162
|
// the deck's private state, and since build 1 that includes the version store --
|
|
161
163
|
// the one place where losing bytes loses history rather than a file. The list
|
|
@@ -197,8 +199,8 @@ const RAW_MIME = {
|
|
|
197
199
|
// Files under `imports/` came from another deck. They are readable like any
|
|
198
200
|
// other deck file -- the engine, editors and pickers all reference them -- but a
|
|
199
201
|
// deck can't edit them, because editing one would mean editing somebody else's
|
|
200
|
-
// deck.
|
|
201
|
-
//
|
|
202
|
+
// deck. To change one, fork it: the deck's own copy lives under `forks/` and
|
|
203
|
+
// stands in for the imported path everywhere.
|
|
202
204
|
function isImportPath(rel) {
|
|
203
205
|
return rel === IMPORTS_DIR || rel.startsWith(`${IMPORTS_DIR}/`);
|
|
204
206
|
}
|
|
@@ -234,11 +236,24 @@ function resolveDeckPath(deckDir, requestedPath, opts = {}) {
|
|
|
234
236
|
return { ok: false, error: `Path outside the deck: ${requestedPath}` };
|
|
235
237
|
}
|
|
236
238
|
const relPosix = rel.split(path.sep).join('/');
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
239
|
+
// An imported path answers with whatever overrides it, keeping `rel` as the
|
|
240
|
+
// imports path -- that is what the deck calls this file everywhere else, and
|
|
241
|
+
// only the file on disk changes.
|
|
242
|
+
//
|
|
243
|
+
// This deck's OWN fork is writable: being editable is the whole reason to make
|
|
244
|
+
// one. A fork an import carries is not -- it belongs to that import, same as
|
|
245
|
+
// the file it overrides.
|
|
246
|
+
if (isImportPath(relPosix)) {
|
|
247
|
+
const own = ownForkFile(deckDir, relPosix);
|
|
248
|
+
if (own)
|
|
249
|
+
return { ok: true, abs: own, rel: relPosix };
|
|
250
|
+
if (opts.mutation) {
|
|
251
|
+
return {
|
|
252
|
+
ok: false,
|
|
253
|
+
error: `${relPosix} belongs to an imported deck and is read-only. Fork it to make changes.`,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
return { ok: true, abs: resolveForkedFile(deckDir, relPosix) ?? abs, rel: relPosix };
|
|
242
257
|
}
|
|
243
258
|
return { ok: true, abs, rel: relPosix };
|
|
244
259
|
}
|
|
@@ -494,8 +509,8 @@ function handleFilesMkdir(deckDir, req, res) {
|
|
|
494
509
|
// until then is what stops a deck's public cover running ahead of the version
|
|
495
510
|
// people can actually play.
|
|
496
511
|
function handleCoverApi(deckDir, req, res) {
|
|
497
|
-
if (req.method !==
|
|
498
|
-
sendJson(res, 405, { error:
|
|
512
|
+
if (req.method !== 'POST') {
|
|
513
|
+
sendJson(res, 405, { error: 'Use POST to store a cover.' });
|
|
499
514
|
return true;
|
|
500
515
|
}
|
|
501
516
|
void readRequestBuffer(req, MAX_UPLOAD_BYTES).then((bytes) => {
|
|
@@ -503,7 +518,7 @@ function handleCoverApi(deckDir, req, res) {
|
|
|
503
518
|
fs.writeFileSync(path.join(deckDir, COVER_FILE), bytes);
|
|
504
519
|
}
|
|
505
520
|
catch (err) {
|
|
506
|
-
return sendFailure(res,
|
|
521
|
+
return sendFailure(res, 'write', COVER_FILE, err);
|
|
507
522
|
}
|
|
508
523
|
return sendJson(res, 200, { ok: true, bytes: bytes.length });
|
|
509
524
|
}, () => {
|
|
@@ -695,7 +710,7 @@ function handleFilesDelete(deckDir, req, res) {
|
|
|
695
710
|
// The builtin Files + code-editor backend: list / read / write deck files and
|
|
696
711
|
// report kit-owned editor extensions. Paths are deck-relative; resolveDeckPath
|
|
697
712
|
// rejects traversal and protected dirs.
|
|
698
|
-
function handleFilesApi(deckDir, req, res, reqPath, restart) {
|
|
713
|
+
function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate) {
|
|
699
714
|
const action = reqPath.slice(FILES_API_PREFIX.length);
|
|
700
715
|
if (action === 'info') {
|
|
701
716
|
const config = readEditorConfig(deckDir);
|
|
@@ -753,6 +768,51 @@ function handleFilesApi(deckDir, req, res, reqPath, restart) {
|
|
|
753
768
|
})();
|
|
754
769
|
return true;
|
|
755
770
|
}
|
|
771
|
+
if (action === 'forks') {
|
|
772
|
+
// `?path=` asks about ONE path, forked or not -- how a caller that already
|
|
773
|
+
// knows which file it is showing gets an answer that includes whether the
|
|
774
|
+
// path may be forked at all. Same shape as the list so callers share a
|
|
775
|
+
// parser.
|
|
776
|
+
const asked = new URL(req.url ?? '', 'http://localhost').searchParams.get('path');
|
|
777
|
+
if (asked) {
|
|
778
|
+
sendJson(res, 200, { forks: [{ path: asked, ...forkStateOf(deckDir, asked) }] });
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
// Which imported paths this deck overrides, and whether the file each one
|
|
782
|
+
// was taken from has changed since.
|
|
783
|
+
const paths = listOwnForks(deckDir);
|
|
784
|
+
sendJson(res, 200, {
|
|
785
|
+
forks: paths.map((p) => ({ path: p, ...forkStateOf(deckDir, p) })),
|
|
786
|
+
});
|
|
787
|
+
return true;
|
|
788
|
+
}
|
|
789
|
+
if (action === 'fork' || action === 'revert-fork') {
|
|
790
|
+
void (async () => {
|
|
791
|
+
let body;
|
|
792
|
+
try {
|
|
793
|
+
body = JSON.parse(await readRequestBody(req));
|
|
794
|
+
}
|
|
795
|
+
catch {
|
|
796
|
+
return sendJson(res, 400, { error: 'Invalid JSON body.' });
|
|
797
|
+
}
|
|
798
|
+
if (typeof body.path !== 'string' || !body.path) {
|
|
799
|
+
return sendJson(res, 400, { error: 'Missing file path.' });
|
|
800
|
+
}
|
|
801
|
+
const forkPath = body.path;
|
|
802
|
+
const result = action === 'fork' ? forkImportFile(deckDir, forkPath) : revertImportFile(deckDir, forkPath);
|
|
803
|
+
if (!result.ok)
|
|
804
|
+
return sendJson(res, 400, { error: result.error });
|
|
805
|
+
sendJson(res, 200, { ok: true, path: forkPath, ...forkStateOf(deckDir, forkPath) });
|
|
806
|
+
// Which file an imported path resolves to just changed, and vite has the
|
|
807
|
+
// old answer cached -- after a revert it holds the id of a file that no
|
|
808
|
+
// longer exists and asks for it on the next request. Invalidate, but do
|
|
809
|
+
// NOT reload: the watcher announces the change under the imported path,
|
|
810
|
+
// and every panel decides for itself from there (Play offers a restart
|
|
811
|
+
// rather than taking one).
|
|
812
|
+
setImmediate(() => invalidate?.([forkPath]));
|
|
813
|
+
})();
|
|
814
|
+
return true;
|
|
815
|
+
}
|
|
756
816
|
if (action === 'versions') {
|
|
757
817
|
handleVersionsList(deckDir, res);
|
|
758
818
|
return true;
|
|
@@ -1048,6 +1108,14 @@ export function createIdeServer(opts) {
|
|
|
1048
1108
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
1049
1109
|
if (url.pathname !== PTY_WS_PATH)
|
|
1050
1110
|
return false;
|
|
1111
|
+
// The PTY is a root login shell — reject any upgrade that isn't same-origin (a
|
|
1112
|
+
// co-tenant reaching this port directly sends no browser Origin). Consumed either
|
|
1113
|
+
// way so a rejected upgrade never falls through to another handler.
|
|
1114
|
+
if (!isSameOriginUpgrade(req)) {
|
|
1115
|
+
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|
1116
|
+
socket.destroy();
|
|
1117
|
+
return true;
|
|
1118
|
+
}
|
|
1051
1119
|
wss.handleUpgrade(req, socket, head, (ws) => attachClient(ws));
|
|
1052
1120
|
return true;
|
|
1053
1121
|
}
|
|
@@ -1071,7 +1139,7 @@ export function createIdeServer(opts) {
|
|
|
1071
1139
|
return handleCoverApi(deckDir, req, res);
|
|
1072
1140
|
}
|
|
1073
1141
|
if (reqPath.startsWith(FILES_API_PREFIX)) {
|
|
1074
|
-
return handleFilesApi(deckDir, req, res, reqPath, opts.restart);
|
|
1142
|
+
return handleFilesApi(deckDir, req, res, reqPath, opts.restart, opts.invalidate);
|
|
1075
1143
|
}
|
|
1076
1144
|
if (reqPath.startsWith(IMPORT_API_PREFIX)) {
|
|
1077
1145
|
return handleImportApi(deckDir, req, res, reqPath, opts.restart);
|
package/dist/imports.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
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
|
|
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: {
|
|
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/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
|
-
|
|
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))
|
|
@@ -474,7 +551,11 @@ async function serveDetached(projectDir, options) {
|
|
|
474
551
|
throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
|
|
475
552
|
}
|
|
476
553
|
function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
|
|
477
|
-
|
|
554
|
+
// Bind to loopback: the only reachers are same-container callers — the Vite proxy
|
|
555
|
+
// (`/__castle/ws` -> `ws://localhost:${port}`) and node-side CLI clients that dial
|
|
556
|
+
// `ws://localhost:${port}`. Binding 0.0.0.0 also exposed this control channel to
|
|
557
|
+
// co-tenant containers across the shared Docker bridge.
|
|
558
|
+
const wss = new WebSocketServer({ port, host: '127.0.0.1' });
|
|
478
559
|
const clients = new Set();
|
|
479
560
|
const broadcast = (msg) => {
|
|
480
561
|
const data = JSON.stringify(msg);
|
|
@@ -651,9 +732,27 @@ function writeProjectFile(projectDir, requestedPath, contents) {
|
|
|
651
732
|
if (relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
652
733
|
return { ok: false, error: `Refusing to write outside the deck: ${requestedPath}` };
|
|
653
734
|
}
|
|
735
|
+
// Imported files belong to the deck that published them. This is the write
|
|
736
|
+
// path the kit editors use, and it had no check of its own -- it leaned on the
|
|
737
|
+
// read-only bits on disk, so a deck whose imports were never locked took the
|
|
738
|
+
// write, and a locked one failed with EACCES into the deck's log where nobody
|
|
739
|
+
// reads it. Decide it here instead, and send the write to this deck's fork
|
|
740
|
+
// when it has one, which is the whole point of having forked.
|
|
741
|
+
const relPosix = relative.split(path.sep).join('/');
|
|
742
|
+
let target = filepath;
|
|
743
|
+
if (relPosix.startsWith(`${IMPORTS_DIR}/`)) {
|
|
744
|
+
const fork = ownForkFile(projectDir, relPosix);
|
|
745
|
+
if (!fork) {
|
|
746
|
+
return {
|
|
747
|
+
ok: false,
|
|
748
|
+
error: `${relPosix} belongs to an imported deck and is read-only. Fork it to make changes.`,
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
target = fork;
|
|
752
|
+
}
|
|
654
753
|
try {
|
|
655
|
-
fs.mkdirSync(path.dirname(
|
|
656
|
-
fs.writeFileSync(
|
|
754
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
755
|
+
fs.writeFileSync(target, contents, 'utf-8');
|
|
657
756
|
return { ok: true, path: normalized };
|
|
658
757
|
}
|
|
659
758
|
catch (error) {
|