castle-web-cli 0.4.163 → 0.4.165
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.d.ts +3 -0
- package/dist/agent-prompts.js +14 -6
- package/dist/agent.js +14 -1
- package/dist/castle-host/host.js +276 -0
- package/dist/devSessionChild.js +66 -1
- package/dist/devSessionServer.js +21 -2
- package/dist/devSessionStorage.d.ts +9 -0
- package/dist/devSessionStorage.js +139 -0
- package/dist/forks.js +1 -1
- package/dist/headlessCover.js +12 -1
- package/dist/ide.d.ts +0 -2
- package/dist/ide.js +1 -7
- package/dist/imports.js +5 -0
- package/dist/init.js +1 -1
- package/dist/platformDoc.js +18 -3
- package/dist/rawData.d.ts +2 -0
- package/dist/rawData.js +10 -0
- package/dist/save-deck.d.ts +2 -0
- package/dist/save-deck.js +53 -20
- package/dist/serve.js +98 -0
- package/dist/shell/assets/index-CG9TrvCm.js +444 -0
- package/dist/shell/assets/index-CIRBt1qf.css +1 -0
- package/dist/shell/index.html +2 -2
- package/kits/base/CLAUDE.md +1 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/node_modules/.package-lock.json +28 -0
- package/kits/base/node_modules/castle-web-fonts/README.md +114 -0
- package/kits/base/node_modules/castle-web-fonts/dist/catalog.d.ts +18 -0
- package/kits/base/node_modules/castle-web-fonts/dist/catalog.js +142 -0
- package/kits/base/node_modules/castle-web-fonts/dist/face.d.ts +1 -0
- package/kits/base/node_modules/castle-web-fonts/dist/face.js +52 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Bore.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/DMSans.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Glacier.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Synco.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/Tektur.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +3 -0
- package/kits/base/node_modules/castle-web-fonts/dist/faces/YatraOne.js +10 -0
- package/kits/base/node_modules/castle-web-fonts/dist/index.d.ts +16 -0
- package/kits/base/node_modules/castle-web-fonts/dist/index.js +15 -0
- package/kits/base/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +393 -0
- package/kits/base/node_modules/castle-web-fonts/licenses/FONTS.md +64 -0
- package/kits/base/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +95 -0
- package/kits/base/node_modules/castle-web-fonts/package.json +47 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/SOURCE.txt +2 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
- package/kits/base/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
- package/kits/base/package-lock.json +1 -1
- package/kits/base/sdk/README.md +184 -38
- package/kits/base/sdk/castle.d.ts +2 -0
- package/kits/base/sdk/castle.js +1 -0
- package/kits/base/sdk/chunk.d.ts +1 -0
- package/kits/base/sdk/chunk.js +15 -0
- package/kits/base/sdk/commands.d.ts +86 -0
- package/kits/base/sdk/runtime.js +21 -12
- package/kits/base/sdk/server/platformHandle.d.ts +10 -0
- package/kits/base/sdk/server/storage.d.ts +46 -0
- package/kits/base/sdk/server/storage.js +218 -0
- package/kits/base/sdk/server/wrapper.d.ts +14 -1
- package/kits/base/sdk/server/wrapper.js +4 -1
- package/kits/base/sdk/storage.d.ts +15 -0
- package/kits/base/sdk/storage.js +29 -86
- package/kits/base/sdk/storageJson.d.ts +5 -0
- package/kits/base/sdk/storageJson.js +69 -0
- package/kits/base/sdk/store.d.ts +67 -0
- package/kits/base/sdk/store.js +313 -0
- package/kits/base/sdk/unloadFlush.d.ts +3 -0
- package/kits/base/sdk/unloadFlush.js +30 -0
- package/kits/blank/node_modules/.package-lock.json +13 -0
- package/kits/blank/node_modules/castle-web-fonts/README.md +114 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/catalog.d.ts +18 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/catalog.js +142 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/face.d.ts +1 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/face.js +52 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Bore.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/DMSans.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Glacier.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Synco.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/Tektur.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +3 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/faces/YatraOne.js +10 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/index.d.ts +16 -0
- package/kits/blank/node_modules/castle-web-fonts/dist/index.js +15 -0
- package/kits/blank/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +393 -0
- package/kits/blank/node_modules/castle-web-fonts/licenses/FONTS.md +64 -0
- package/kits/blank/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +95 -0
- package/kits/blank/node_modules/castle-web-fonts/package.json +47 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/SOURCE.txt +2 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
- package/kits/blank/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
- package/kits/physics-2d/castle.json +1 -1
- package/kits/physics-2d/editors/SceneEditor.jsx +2 -1
- package/kits/physics-2d/engine/blueprint.js +29 -28
- package/kits/physics-2d/engine/ui.jsx +24 -0
- package/kits/physics-2d/engine/ui.module.css +5 -0
- package/kits/physics-2d/package-lock.json +1 -6
- package/package.json +3 -2
- package/dist/shell/assets/index-BJO7LVCM.js +0 -422
- package/dist/shell/assets/index-DfZmu3XC.css +0 -1
- package/kits/blank/.castle/agent/children.json +0 -1
- package/kits/blank/.castle/agent/messages.json +0 -9
- package/kits/blank/.castle/agent/pending-sends.json +0 -1
- package/kits/blank/.castle/agent/tasks/index.md +0 -2
- package/kits/blank/.castle/docs/platform.md +0 -36
- package/kits/blank/node_modules/.vite/deps/_metadata.json +0 -8
- package/kits/blank/node_modules/.vite/deps/package.json +0 -3
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { graphql } from './api.js';
|
|
2
|
+
const SCOPE_ARGS = `
|
|
3
|
+
$deckId: ID!
|
|
4
|
+
$scope: CauldronStorageScope!
|
|
5
|
+
$subject: ID
|
|
6
|
+
`;
|
|
7
|
+
const OPERATIONS = {
|
|
8
|
+
get: {
|
|
9
|
+
field: 'cauldronStorageGet',
|
|
10
|
+
query: `query CastleDevStorageGet(${SCOPE_ARGS} $keys: [String!]!) {
|
|
11
|
+
cauldronStorageGet(deckId: $deckId, scope: $scope, subject: $subject, keys: $keys) {
|
|
12
|
+
key
|
|
13
|
+
value
|
|
14
|
+
}
|
|
15
|
+
}`,
|
|
16
|
+
},
|
|
17
|
+
list: {
|
|
18
|
+
field: 'cauldronStorageList',
|
|
19
|
+
query: `query CastleDevStorageList(${SCOPE_ARGS} $prefix: String, $limit: Int, $cursor: String) {
|
|
20
|
+
cauldronStorageList(
|
|
21
|
+
deckId: $deckId
|
|
22
|
+
scope: $scope
|
|
23
|
+
subject: $subject
|
|
24
|
+
prefix: $prefix
|
|
25
|
+
limit: $limit
|
|
26
|
+
cursor: $cursor
|
|
27
|
+
) {
|
|
28
|
+
entries {
|
|
29
|
+
key
|
|
30
|
+
value
|
|
31
|
+
}
|
|
32
|
+
cursor
|
|
33
|
+
}
|
|
34
|
+
}`,
|
|
35
|
+
},
|
|
36
|
+
set: {
|
|
37
|
+
field: 'cauldronStorageSet',
|
|
38
|
+
query: `mutation CastleDevStorageSet(${SCOPE_ARGS} $entries: [CauldronStorageEntryInput!]!) {
|
|
39
|
+
cauldronStorageSet(
|
|
40
|
+
deckId: $deckId
|
|
41
|
+
scope: $scope
|
|
42
|
+
subject: $subject
|
|
43
|
+
entries: $entries
|
|
44
|
+
asServer: true
|
|
45
|
+
) {
|
|
46
|
+
rowCount
|
|
47
|
+
byteCount
|
|
48
|
+
}
|
|
49
|
+
}`,
|
|
50
|
+
},
|
|
51
|
+
delete: {
|
|
52
|
+
field: 'cauldronStorageDelete',
|
|
53
|
+
query: `mutation CastleDevStorageDelete(${SCOPE_ARGS} $keys: [String!]!) {
|
|
54
|
+
cauldronStorageDelete(
|
|
55
|
+
deckId: $deckId
|
|
56
|
+
scope: $scope
|
|
57
|
+
subject: $subject
|
|
58
|
+
keys: $keys
|
|
59
|
+
asServer: true
|
|
60
|
+
) {
|
|
61
|
+
rowCount
|
|
62
|
+
byteCount
|
|
63
|
+
}
|
|
64
|
+
}`,
|
|
65
|
+
},
|
|
66
|
+
increment: {
|
|
67
|
+
field: 'cauldronStorageIncrement',
|
|
68
|
+
query: `mutation CastleDevStorageIncrement(${SCOPE_ARGS} $key: String!, $delta: Float!) {
|
|
69
|
+
cauldronStorageIncrement(
|
|
70
|
+
deckId: $deckId
|
|
71
|
+
scope: $scope
|
|
72
|
+
subject: $subject
|
|
73
|
+
key: $key
|
|
74
|
+
delta: $delta
|
|
75
|
+
asServer: true
|
|
76
|
+
)
|
|
77
|
+
}`,
|
|
78
|
+
},
|
|
79
|
+
boardSubmit: {
|
|
80
|
+
field: 'cauldronStorageBoardSubmit',
|
|
81
|
+
query: `mutation CastleDevStorageBoardSubmit($deckId: ID!, $board: String!, $subject: ID, $score: Float!) {
|
|
82
|
+
cauldronStorageBoardSubmit(
|
|
83
|
+
deckId: $deckId
|
|
84
|
+
board: $board
|
|
85
|
+
subject: $subject
|
|
86
|
+
score: $score
|
|
87
|
+
asServer: true
|
|
88
|
+
) {
|
|
89
|
+
subject
|
|
90
|
+
score
|
|
91
|
+
updatedAt
|
|
92
|
+
}
|
|
93
|
+
}`,
|
|
94
|
+
},
|
|
95
|
+
boardTop: {
|
|
96
|
+
field: 'cauldronStorageBoardTop',
|
|
97
|
+
query: `query CastleDevStorageBoardTop($deckId: ID!, $board: String!, $limit: Int) {
|
|
98
|
+
cauldronStorageBoardTop(deckId: $deckId, board: $board, limit: $limit) {
|
|
99
|
+
subject
|
|
100
|
+
score
|
|
101
|
+
updatedAt
|
|
102
|
+
}
|
|
103
|
+
}`,
|
|
104
|
+
},
|
|
105
|
+
boardGet: {
|
|
106
|
+
field: 'cauldronStorageBoardGet',
|
|
107
|
+
query: `query CastleDevStorageBoardGet($deckId: ID!, $board: String!, $subject: ID) {
|
|
108
|
+
cauldronStorageBoardGet(deckId: $deckId, board: $board, subject: $subject) {
|
|
109
|
+
subject
|
|
110
|
+
score
|
|
111
|
+
updatedAt
|
|
112
|
+
}
|
|
113
|
+
}`,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
export async function runDevStorageOperation(deckId, op, args) {
|
|
117
|
+
const operation = OPERATIONS[op];
|
|
118
|
+
if (!operation) {
|
|
119
|
+
return failure('CAULDRON_STORAGE_INVALID_ARGUMENT', `unknown storage operation ${op}`);
|
|
120
|
+
}
|
|
121
|
+
if (!deckId || deckId === 'dev') {
|
|
122
|
+
return failure('CAULDRON_STORAGE_UNAVAILABLE', 'Storage needs a published deck. Run `castle-web save-deck` first, then restart serve.');
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const response = await graphql(operation.query, { ...args, deckId });
|
|
126
|
+
const error = response.errors?.[0];
|
|
127
|
+
if (error) {
|
|
128
|
+
const code = error.extensions?.code;
|
|
129
|
+
return failure(typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE', error.message ?? 'storage request failed');
|
|
130
|
+
}
|
|
131
|
+
return { ok: true, value: response.data?.[operation.field] ?? null };
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
return failure('CAULDRON_STORAGE_UNAVAILABLE', error instanceof Error ? error.message : 'storage request failed');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function failure(code, message) {
|
|
138
|
+
return { ok: false, error: { code, message } };
|
|
139
|
+
}
|
package/dist/forks.js
CHANGED
|
@@ -150,7 +150,7 @@ export function listOwnForks(deckDir) {
|
|
|
150
150
|
return out.sort();
|
|
151
151
|
}
|
|
152
152
|
function writeForkRecord(deckDir, alias, inner, record) {
|
|
153
|
-
const existing =
|
|
153
|
+
const existing = readCastleJson(deckDir) ?? {};
|
|
154
154
|
const pins = { ...(existing.imports ?? {}) };
|
|
155
155
|
const pin = pins[alias];
|
|
156
156
|
if (!pin)
|
package/dist/headlessCover.js
CHANGED
|
@@ -41,6 +41,10 @@ const SETTLE_MS = 3_500;
|
|
|
41
41
|
// watch a spinner for. Whatever is unfinished at this point is abandoned and
|
|
42
42
|
// the save proceeds without a cover.
|
|
43
43
|
const CAPTURE_BUDGET_MS = 60_000;
|
|
44
|
+
// Remote workers normally finish comfortably inside this window. A cover is best-effort and the
|
|
45
|
+
// editor capture remains available as a fallback, so a queue or worker problem must not hold the
|
|
46
|
+
// synchronous save path until the GraphQL client's much larger generic browser-job timeout.
|
|
47
|
+
const REMOTE_CAPTURE_BUDGET_MS = 15_000;
|
|
44
48
|
// The card the SDK mounts (`initCard`) or a deck marks itself. Falling back to
|
|
45
49
|
// the whole viewport keeps a deck that does neither from getting no cover at
|
|
46
50
|
// all -- the viewport IS the card in play mode.
|
|
@@ -91,8 +95,9 @@ export async function captureCoverHeadless(opts) {
|
|
|
91
95
|
}
|
|
92
96
|
}
|
|
93
97
|
async function captureCoverRemote(contentGrant, outPath) {
|
|
98
|
+
const signal = AbortSignal.timeout(REMOTE_CAPTURE_BUDGET_MS);
|
|
94
99
|
try {
|
|
95
|
-
const result = await api.runBrowserJob(contentGrant, { kind: 'cover' });
|
|
100
|
+
const result = await api.runBrowserJob(contentGrant, { kind: 'cover' }, signal);
|
|
96
101
|
const pngBase64 = result.pngBase64;
|
|
97
102
|
if (result.protocolVersion !== 1 ||
|
|
98
103
|
result.operation !== 'cover' ||
|
|
@@ -109,6 +114,12 @@ async function captureCoverRemote(contentGrant, outPath) {
|
|
|
109
114
|
return { ok: true, outPath };
|
|
110
115
|
}
|
|
111
116
|
catch (error) {
|
|
117
|
+
if (signal.aborted) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
error: `remote cover gave up after ${REMOTE_CAPTURE_BUDGET_MS / 1000}s`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
112
123
|
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
113
124
|
}
|
|
114
125
|
}
|
package/dist/ide.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import * as http from 'http';
|
|
2
2
|
import { Duplex } from 'stream';
|
|
3
|
-
import { type RawData } from 'ws';
|
|
4
3
|
import { COVER_FILE } from './localPaths.js';
|
|
5
4
|
export declare const IDE_ASSET_PREFIX = "/__castle/ide/";
|
|
6
5
|
export declare const PTY_WS_PATH = "/__castle/pty";
|
|
@@ -10,7 +9,6 @@ export declare const FAVICON_LINK_TAGS: string;
|
|
|
10
9
|
export declare const FILES_API_PREFIX = "/__castle/files/";
|
|
11
10
|
export declare const COVER_API_PATH = "/__castle/cover";
|
|
12
11
|
export { COVER_FILE };
|
|
13
|
-
export declare function rawDataToString(data: RawData): string;
|
|
14
12
|
export interface IdeServer {
|
|
15
13
|
/** Serve the IDE page + its static assets. Returns true if it handled the request. */
|
|
16
14
|
handleHttpRequest(req: http.IncomingMessage, res: http.ServerResponse, reqPath: string): boolean;
|
package/dist/ide.js
CHANGED
|
@@ -16,6 +16,7 @@ import { isSameOriginUpgrade } from './wsOrigin.js';
|
|
|
16
16
|
import headlessPkg from '@xterm/headless';
|
|
17
17
|
import { SerializeAddon } from '@xterm/addon-serialize';
|
|
18
18
|
import { WebSocketServer } from 'ws';
|
|
19
|
+
import { rawDataToString } from './rawData.js';
|
|
19
20
|
import { IMPORTS_DIR, importStatuses, updateImport } from './imports.js';
|
|
20
21
|
import { FORKS_DIR, forkImportFile, forkStateOf, listOwnForks, ownForkFile, resolveForkedFile, revertImportFile, } from './forks.js';
|
|
21
22
|
import { ensureVisibleGlob, ensureVisiblePath } from './castleJson.js';
|
|
@@ -966,13 +967,6 @@ function clampSize(value, fallback) {
|
|
|
966
967
|
return fallback;
|
|
967
968
|
return Math.max(2, Math.min(1000, Math.floor(n)));
|
|
968
969
|
}
|
|
969
|
-
export function rawDataToString(data) {
|
|
970
|
-
if (Array.isArray(data))
|
|
971
|
-
return Buffer.concat(data).toString('utf8');
|
|
972
|
-
if (Buffer.isBuffer(data))
|
|
973
|
-
return data.toString('utf8');
|
|
974
|
-
return Buffer.from(new Uint8Array(data)).toString('utf8');
|
|
975
|
-
}
|
|
976
970
|
function send(socket, body) {
|
|
977
971
|
if (socket.readyState === socket.OPEN)
|
|
978
972
|
socket.send(JSON.stringify(body));
|
package/dist/imports.js
CHANGED
|
@@ -389,6 +389,11 @@ function backupImport(deckDir, alias) {
|
|
|
389
389
|
}
|
|
390
390
|
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
391
391
|
fs.cpSync(src, dest, { recursive: true, verbatimSymlinks: true });
|
|
392
|
+
// The copy comes out locked, because the import it was taken from is. Unlock
|
|
393
|
+
// it: the pin below is written INTO it, and a read-only directory refuses
|
|
394
|
+
// that -- which failed the whole update, backup included, rather than the one
|
|
395
|
+
// write.
|
|
396
|
+
unlockImportTree(dest);
|
|
392
397
|
const pin = (readCastleJson(deckDir)?.imports ?? {})[alias];
|
|
393
398
|
if (pin) {
|
|
394
399
|
fs.writeFileSync(path.join(dest, '.castle-import-pin.json'), JSON.stringify(pin, null, 2), 'utf-8');
|
package/dist/init.js
CHANGED
|
@@ -55,7 +55,7 @@ if (!(await mountEditorRoute())) startGame(initCard());
|
|
|
55
55
|
// Registry version of castle-web-sdk to inject when scaffolding from a
|
|
56
56
|
// globally-installed castle-web (not from inside the workspace). Bumped
|
|
57
57
|
// alongside cli/sdk version bumps.
|
|
58
|
-
const PUBLISHED_SDK_VERSION = '0.4.
|
|
58
|
+
const PUBLISHED_SDK_VERSION = '0.4.26';
|
|
59
59
|
// Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
|
|
60
60
|
// face can ship without a cli release, and a caret range means an existing
|
|
61
61
|
// deck's next install picks it up. Nothing here has to move when it does.
|
package/dist/platformDoc.js
CHANGED
|
@@ -53,6 +53,9 @@ export function everyDeckBullets(deckDir) {
|
|
|
53
53
|
"- Do not reload the deck after an edit. Nothing auto-reloads: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control. `npm run restart` reloads every open panel at once and breaks their flow — only when asked.",
|
|
54
54
|
"- The deck can define its own editors: declare a file type in `castle.json` (`editor.fileTypes`: ext, label, icon, and an `editors/` module) and the Files panel opens that type in it — whole recipe under `## Editors` in the deck's guide (its kit's `CLAUDE.md` under `imports/`). Editors under `imports/` are read-only; add or fork, don't edit.",
|
|
55
55
|
'- An editor is for content FILES the creator keeps coming back to (catalogs, dialogue, level tables) that nothing already opens. One-off or generated data stays code.',
|
|
56
|
+
"- **Put the values someone would tune while playtesting in a `PARAMS` object**: `export const PARAMS = { jumpHeight: 4.2, coyoteTime: 0.08 };` near the top of the file that uses them. Every `.js` / `.jsx` / `.ts` / `.tsx` file has a Params view beside its Code view that renders those values as fields -- a number scrubs, a boolean toggles, a `'#rrggbb'` string opens a color picker -- and writes the edit back into the file. That is how a creator tunes a game on a phone without putting a cursor inside an expression. Nested one level deep (`player: { speed: 5 }`) renders as a group; a value that is an expression (`speed: BASE * 2`) still shows, read-only.",
|
|
57
|
+
'- **This is for the handful of numbers someone would actually reach for between playtests, not every constant in the file.** A `PARAMS` with sixty keys is a wall nobody can scan, which is how a creator stops opening the pane at all. A magic number that only ever has one right value is not a param.',
|
|
58
|
+
"- **Read them through the object where they are used** -- `PARAMS.jumpHeight`, not `const { jumpHeight } = PARAMS` at module load. A destructured copy is taken once when the module loads and can never track a later change, so keeping the read at the use site is what leaves a tuned value able to reach the running deck.",
|
|
56
59
|
MODE_BULLET,
|
|
57
60
|
];
|
|
58
61
|
}
|
|
@@ -197,10 +200,11 @@ const COMMON_SECTIONS = `## Imports are read-only
|
|
|
197
200
|
onMessage(session, player, data) {}, // data is what the client sent, already parsed
|
|
198
201
|
onTick(session, dtSeconds) {}, // only when castle.json sets server.tickRate > 0
|
|
199
202
|
onReplaced(session) {}, // you published a new version; this session keeps the old one
|
|
203
|
+
async onShutdown(session) {}, // the session is ending; awaited, so a save here lands
|
|
200
204
|
};
|
|
201
205
|
\`\`\`
|
|
202
206
|
|
|
203
|
-
\`session\` gives you \`send(playerId, data)\`, \`broadcast(data, { except })\`, \`disconnect(playerId, reason)\`, \`players\`, \`sessionId\`, \`deckId\`, and \`
|
|
207
|
+
\`session\` gives you \`send(playerId, data)\`, \`broadcast(data, { except })\`, \`disconnect(playerId, reason)\`, \`players\`, \`sessionId\`, \`deckId\`, \`mode\`, and \`storage\`.
|
|
204
208
|
- **Player identity comes from Castle, not from the client.** The \`player\` passed to your callbacks is authenticated by the platform, so a client cannot claim to be someone else by putting a name in a message. Trust \`player.userId\`; never trust identity inside \`data\`.
|
|
205
209
|
- **The server is authoritative — put the rules there.** Deck code runs on the player's phone and can be modified, so validate every move on the server and send back state for clients to render. \`playerId\` identifies a connection (stable across a reconnect) while \`userId\` identifies the account, and one account can be in a session twice from two tabs.
|
|
206
210
|
- **The client joins with \`Multiplayer.join\`:**
|
|
@@ -216,8 +220,19 @@ const COMMON_SECTIONS = `## Imports are read-only
|
|
|
216
220
|
|
|
217
221
|
\`named\` puts everyone passing the same \`key\` in one session, which is how you build room codes and invite links. \`public\` drops a player into a shared session for the deck; \`party\` uses the Castle party they are already in.
|
|
218
222
|
- **Always handle \`conn.isSolo\`.** When a player cannot join — signed out, blocked, private deck, or no capacity free — the SDK returns a working single-player connection instead of throwing. Keep the deck playable on its own rather than gating the whole game behind other people showing up.
|
|
219
|
-
- **What the server may and may not do.** Roughly 128MB of memory, no filesystem that survives, and **no network access at all**: no \`fetch\`, no database, no third-party API. Keep state in memory and send it to clients. A session ends once its last player leaves and
|
|
220
|
-
-
|
|
223
|
+
- **What the server may and may not do.** Roughly 128MB of memory, no filesystem that survives, and **no network access at all**: no \`fetch\`, no database, no third-party API. Keep state in memory and send it to clients. A session ends once its last player leaves and its memory goes with it.
|
|
224
|
+
- **\`session.storage\` is what outlives a session**, and it is the same store the deck's clients see through \`Store\`:
|
|
225
|
+
|
|
226
|
+
\`\`\`js
|
|
227
|
+
const { wins = 0 } = await session.storage.deck.get(['wins']);
|
|
228
|
+
await session.storage.deck.set({ wins: wins + 1 });
|
|
229
|
+
await session.storage.user(player.userId).set({ lastSeen: Date.now() });
|
|
230
|
+
await session.storage.board('high').submit(player.userId, score);
|
|
231
|
+
\`\`\`
|
|
232
|
+
|
|
233
|
+
Publishing a server takes ownership of \`deck\` scope: from then on clients read that data but no longer write it, which is what lets you keep authoritative state players cannot forge. A server can write any player's public bucket and submit any player's score, so name the player — there is no \`storage.me\`. It can never read \`private\` storage, not even for its own players.
|
|
234
|
+
- **Save as things change, not only at the end.** \`onShutdown\` is awaited and a save made there does land, but it only runs on a clean stop: an out-of-memory kill or a host failing sends no shutdown at all. Treat it as the last chance rather than the plan.
|
|
235
|
+
- **Limits worth designing around.** Client→server messages are capped at 16 KB and about 30 per second; server→client messages are capped at 64 KB. These limits apply to both JSON and binary frames and are measured on the frame, so a binary frame's one-byte protocol tag leaves you one byte under the cap for payload. Sending 20–30 updates per second means sending deltas rather than whole-world snapshots, and every player's phone pays for whatever you broadcast.
|
|
221
236
|
- **Binary messages are opt-in per payload.** Pass any typed array, \`DataView\`, or \`ArrayBuffer\` to client \`send\`, server \`send\`, or server \`broadcast\` to send its raw bytes. \`onMessage\` always receives those bytes as a \`Uint8Array\`, while every other payload continues to use JSON. Reconstruct another view type such as \`Float32Array\` on receipt; multi-byte values use the sender platform's byte order.
|
|
222
237
|
- **Test multiplayer locally with no setup.** \`castle-web serve\` runs your server file alongside the deck; open the play URL in two tabs and they share a session. Editing anything under \`server/\` restarts it and clients reconnect, so you exercise your reconnect path constantly. Server \`console.log\` goes to the serve's logs, not the browser console.
|
|
223
238
|
- **Publishing does not disturb games in progress.** \`save-deck\` bundles and publishes \`server/\`, but sessions already running keep the code they started with (they get \`onReplaced\`, so you can prompt players), and the next new session picks up the new version.
|
package/dist/rawData.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// A `ws` text frame arrives as a Buffer, a Buffer[] or an ArrayBuffer, and only
|
|
2
|
+
// the first two stringify to their contents -- an ArrayBuffer would decode as
|
|
3
|
+
// "[object ArrayBuffer]". Every text protocol in here goes through this.
|
|
4
|
+
export function rawDataToString(data) {
|
|
5
|
+
if (Array.isArray(data))
|
|
6
|
+
return Buffer.concat(data).toString('utf8');
|
|
7
|
+
if (Buffer.isBuffer(data))
|
|
8
|
+
return data.toString('utf8');
|
|
9
|
+
return Buffer.from(new Uint8Array(data)).toString('utf8');
|
|
10
|
+
}
|
package/dist/save-deck.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
|
|
2
|
+
export declare const SAVE_STAGE_TELEMETRY_PREFIX = "CASTLE_SAVE_TELEMETRY ";
|
|
3
|
+
export type SaveStage = 'bundle' | 'cover' | 'scene_upload_config' | 'scene_upload' | 'content_publish' | 'server_publish' | 'source_archive' | 'source_upload_config' | 'source_upload' | 'source_commit';
|
|
2
4
|
export declare function runTar(args: string[], opts?: {
|
|
3
5
|
capture?: boolean;
|
|
4
6
|
}): Promise<string>;
|
package/dist/save-deck.js
CHANGED
|
@@ -15,6 +15,37 @@ import { buildServerBundle } from './serverBundle.js';
|
|
|
15
15
|
// part of it. (Being on this list also means `get-deck` leaves an existing
|
|
16
16
|
// `imports/` in place when it refreshes a deck.)
|
|
17
17
|
export const SOURCE_ARCHIVE_EXCLUDES = ['node_modules', 'dist', '.castle', '.git', 'imports'];
|
|
18
|
+
// CastleWWW requests these records through CASTLE_SAVE_STAGE_TELEMETRY and recognizes only this
|
|
19
|
+
// prefix plus a fixed stage schema before relaying them to central logs. Keeping them opt-in avoids
|
|
20
|
+
// adding machine output to interactive local saves. Old CLIs ignore the env, so releases remain
|
|
21
|
+
// independently deployable.
|
|
22
|
+
export const SAVE_STAGE_TELEMETRY_PREFIX = 'CASTLE_SAVE_TELEMETRY ';
|
|
23
|
+
function emitSaveStage(stage, outcome, startedAtMs, fields = {}) {
|
|
24
|
+
if (process.env.CASTLE_SAVE_STAGE_TELEMETRY !== '1')
|
|
25
|
+
return;
|
|
26
|
+
console.log(`${SAVE_STAGE_TELEMETRY_PREFIX}${JSON.stringify({
|
|
27
|
+
event: 'castle_web_save_stage_completed',
|
|
28
|
+
stage,
|
|
29
|
+
outcome,
|
|
30
|
+
duration_ms: Math.max(0, Date.now() - startedAtMs),
|
|
31
|
+
...(fields.bytes === undefined ? {} : { bytes: fields.bytes }),
|
|
32
|
+
...(fields.coverUploaded === undefined
|
|
33
|
+
? {}
|
|
34
|
+
: { cover_uploaded: fields.coverUploaded }),
|
|
35
|
+
})}`);
|
|
36
|
+
}
|
|
37
|
+
async function traceSaveStage(stage, operation, fields) {
|
|
38
|
+
const startedAtMs = Date.now();
|
|
39
|
+
try {
|
|
40
|
+
const result = await operation();
|
|
41
|
+
emitSaveStage(stage, 'success', startedAtMs, fields?.(result));
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
emitSaveStage(stage, 'failure', startedAtMs);
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
18
49
|
// `capture` keeps tar's stdout and resolves with it -- for listing an archive
|
|
19
50
|
// (`-tzf`), where the output IS the answer. Packing and unpacking ignore it.
|
|
20
51
|
export function runTar(args, opts = {}) {
|
|
@@ -75,15 +106,15 @@ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, l
|
|
|
75
106
|
throw new Error(`${label} failed: HTTP ${response.status}`);
|
|
76
107
|
}
|
|
77
108
|
async function uploadSource(projectDir, deckId) {
|
|
78
|
-
const archive = await archiveSource(projectDir);
|
|
109
|
+
const archive = await traceSaveStage('source_archive', () => archiveSource(projectDir), (value) => ({ bytes: value.byteLength }));
|
|
79
110
|
const sizeKB = archive.length / 1024;
|
|
80
111
|
console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
|
|
81
|
-
const uploadConfig = await api.createWebDeckSourceUploadConfig(deckId);
|
|
112
|
+
const uploadConfig = await traceSaveStage('source_upload_config', () => api.createWebDeckSourceUploadConfig(deckId));
|
|
82
113
|
// FormData expects a Blob; copy the Buffer's bytes so we don't share the underlying ArrayBuffer.
|
|
83
114
|
const view = new Uint8Array(archive.byteLength);
|
|
84
115
|
view.set(archive);
|
|
85
|
-
await uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload');
|
|
86
|
-
await api.saveWebDeckSource(deckId, uploadConfig.uploadId);
|
|
116
|
+
await traceSaveStage('source_upload', () => uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload'));
|
|
117
|
+
await traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId));
|
|
87
118
|
}
|
|
88
119
|
const SERVER_BUNDLE_STATE = path.join('.castle', 'published-server-bundle.json');
|
|
89
120
|
function readPublishedServerBundleState(projectDir) {
|
|
@@ -264,7 +295,7 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
264
295
|
}
|
|
265
296
|
const castleJson = readCastleJson(projectDir);
|
|
266
297
|
console.log('Bundling...');
|
|
267
|
-
const bundle = await bundleProject(projectDir);
|
|
298
|
+
const bundle = await traceSaveStage('bundle', () => bundleProject(projectDir), (value) => ({ bytes: Buffer.byteLength(value) }));
|
|
268
299
|
const sizeKB = bundle.length / 1024;
|
|
269
300
|
console.log(`Bundle size: ${sizeKB.toFixed(1)}KB`);
|
|
270
301
|
if (sizeKB > 1024) {
|
|
@@ -278,13 +309,14 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
278
309
|
// soon as the bundle has passed, while the independent scene upload is being authorized and
|
|
279
310
|
// transferred. The promise is deliberately non-throwing: a thumbnail must never make the
|
|
280
311
|
// content upload fail or create an unhandled rejection if that upload exits early.
|
|
281
|
-
const backgroundImageFileIdPromise = uploadLocalCover(projectDir);
|
|
312
|
+
const backgroundImageFileIdPromise = traceSaveStage('cover', () => uploadLocalCover(projectDir), (value) => ({ coverUploaded: value !== null }));
|
|
282
313
|
// Upload scene data to S3
|
|
283
|
-
const configs = await
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
314
|
+
const configs = await traceSaveStage('scene_upload_config', async () => {
|
|
315
|
+
const result = await api.createSceneDataUploadConfig([cardId]);
|
|
316
|
+
if (!result?.length)
|
|
317
|
+
throw new Error('Failed to get upload config.');
|
|
318
|
+
return result;
|
|
319
|
+
});
|
|
288
320
|
const uploadConfig = configs[0];
|
|
289
321
|
const formData = new FormData();
|
|
290
322
|
formData.append('Content-Type', 'application/json');
|
|
@@ -292,14 +324,15 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
292
324
|
formData.append(k, String(v));
|
|
293
325
|
}
|
|
294
326
|
formData.append('file', new Blob([JSON.stringify(sceneData)]));
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
327
|
+
await traceSaveStage('scene_upload', async () => {
|
|
328
|
+
const response = await fetch(uploadConfig.postUrl, {
|
|
329
|
+
method: 'POST',
|
|
330
|
+
body: formData,
|
|
331
|
+
signal: AbortSignal.timeout(30000),
|
|
332
|
+
});
|
|
333
|
+
if (response.status >= 300)
|
|
334
|
+
throw new Error(`Upload failed: HTTP ${response.status}`);
|
|
299
335
|
});
|
|
300
|
-
if (s3Res.status >= 300) {
|
|
301
|
-
throw new Error(`Upload failed: HTTP ${s3Res.status}`);
|
|
302
|
-
}
|
|
303
336
|
const title = opts.title ?? castleJson?.title ?? path.basename(path.resolve(projectDir));
|
|
304
337
|
const deckInput = { deckId, title };
|
|
305
338
|
// Omitted unless asked for, or the deck is new and needs one: updateDeckV2
|
|
@@ -327,7 +360,7 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
327
360
|
// here can never overwrite their choice.
|
|
328
361
|
if (backgroundImageFileId)
|
|
329
362
|
cardInput.backgroundImageFileId = backgroundImageFileId;
|
|
330
|
-
const result = await api.updateCardAndDeckV2(deckInput, cardInput);
|
|
363
|
+
const result = await traceSaveStage('content_publish', () => api.updateCardAndDeckV2(deckInput, cardInput));
|
|
331
364
|
// Preserve any deck-owned config already in castle.json (notably the
|
|
332
365
|
// `editor` block); save-deck only owns the identity fields below.
|
|
333
366
|
const newCastleJson = {
|
|
@@ -343,7 +376,7 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
343
376
|
else {
|
|
344
377
|
console.log(`Saved "${title}" to Castle.`);
|
|
345
378
|
}
|
|
346
|
-
await publishServerBundle(projectDir, result.deckId);
|
|
379
|
+
await traceSaveStage('server_publish', () => publishServerBundle(projectDir, result.deckId));
|
|
347
380
|
console.log('Uploading source archive...');
|
|
348
381
|
await uploadSource(projectDir, result.deckId);
|
|
349
382
|
console.log('Source archive saved.');
|
package/dist/serve.js
CHANGED
|
@@ -527,6 +527,7 @@ const BRIDGED_CONTENT_MESSAGES = new Set([
|
|
|
527
527
|
'log',
|
|
528
528
|
'screenshot_response',
|
|
529
529
|
'write_file',
|
|
530
|
+
'rename_file',
|
|
530
531
|
'castle_command',
|
|
531
532
|
]);
|
|
532
533
|
const LEGACY_CONTENT_MESSAGES = new Set([...BRIDGED_CONTENT_MESSAGES, 'ping']);
|
|
@@ -631,6 +632,9 @@ export async function serve(dir, options = {}) {
|
|
|
631
632
|
// dedup above normally returns before here, but an explicit --port/--host
|
|
632
633
|
// asks for a second serve, and a second serve is not a reason to replace
|
|
633
634
|
// files under the first one's session.
|
|
635
|
+
//
|
|
636
|
+
// Also skipped when CASTLE_NO_AUTO_UPDATE is set (local kit development:
|
|
637
|
+
// keep hand-synced imports/ instead of pulling published kits).
|
|
634
638
|
if (!existingServe(projectDir)) {
|
|
635
639
|
// A failure to check must never keep the deck from opening.
|
|
636
640
|
await autoUpdateImports(projectDir).catch((e) => {
|
|
@@ -1245,6 +1249,23 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
|
|
|
1245
1249
|
...response,
|
|
1246
1250
|
}));
|
|
1247
1251
|
}
|
|
1252
|
+
if (msg.type === 'rename_file') {
|
|
1253
|
+
if ((bridgeRole ?? legacyRole) === 'play') {
|
|
1254
|
+
ws.send(JSON.stringify({
|
|
1255
|
+
type: 'rename_file_response',
|
|
1256
|
+
requestId: msg.requestId,
|
|
1257
|
+
ok: false,
|
|
1258
|
+
error: 'Play frames cannot rename deck files.',
|
|
1259
|
+
}));
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
const response = renameProjectFile(projectDir, msg.from, msg.to);
|
|
1263
|
+
ws.send(JSON.stringify({
|
|
1264
|
+
type: 'rename_file_response',
|
|
1265
|
+
requestId: msg.requestId,
|
|
1266
|
+
...response,
|
|
1267
|
+
}));
|
|
1268
|
+
}
|
|
1248
1269
|
// SDK command from a locally-served deck. The dev server is the host:
|
|
1249
1270
|
// it runs the command via the SDK host executor with the CLI's login
|
|
1250
1271
|
// token, then replies to just this socket. See castle-web-sdk's
|
|
@@ -1352,3 +1373,80 @@ function writeProjectFile(projectDir, requestedPath, contents) {
|
|
|
1352
1373
|
return { ok: false, error: `Could not write ${requestedPath}: ${message}` };
|
|
1353
1374
|
}
|
|
1354
1375
|
}
|
|
1376
|
+
// Resolve a deck-relative path for a mutating op (write/rename). Same guards as
|
|
1377
|
+
// `writeProjectFile`: no traversal, no protected dirs, imports only via an own
|
|
1378
|
+
// fork. Returns the absolute target plus the deck-relative POSIX path clients
|
|
1379
|
+
// keep using.
|
|
1380
|
+
function resolveMutableProjectPath(projectDir, requestedPath) {
|
|
1381
|
+
if (typeof requestedPath !== 'string' || requestedPath.trim() === '') {
|
|
1382
|
+
return { ok: false, error: 'Missing file path.' };
|
|
1383
|
+
}
|
|
1384
|
+
const normalized = path.normalize(requestedPath.replace(/\\/g, '/'));
|
|
1385
|
+
if (normalized === '.') {
|
|
1386
|
+
return { ok: false, error: 'Missing file path.' };
|
|
1387
|
+
}
|
|
1388
|
+
if (path.isAbsolute(normalized) ||
|
|
1389
|
+
normalized === '..' ||
|
|
1390
|
+
normalized.startsWith(`..${path.sep}`)) {
|
|
1391
|
+
return { ok: false, error: `Refusing to write outside the deck: ${requestedPath}` };
|
|
1392
|
+
}
|
|
1393
|
+
const parts = normalized.split(path.sep);
|
|
1394
|
+
if (parts.includes('.git') || parts.includes('.castle') || parts.includes('node_modules')) {
|
|
1395
|
+
return { ok: false, error: `Refusing to write protected deck path: ${requestedPath}` };
|
|
1396
|
+
}
|
|
1397
|
+
const filepath = path.resolve(projectDir, normalized);
|
|
1398
|
+
const relative = path.relative(projectDir, filepath);
|
|
1399
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
1400
|
+
return { ok: false, error: `Refusing to write outside the deck: ${requestedPath}` };
|
|
1401
|
+
}
|
|
1402
|
+
const relPosix = relative.split(path.sep).join('/');
|
|
1403
|
+
if (relPosix === IMPORTS_DIR || relPosix.startsWith(`${IMPORTS_DIR}/`)) {
|
|
1404
|
+
const fork = ownForkFile(projectDir, relPosix);
|
|
1405
|
+
if (!fork) {
|
|
1406
|
+
return {
|
|
1407
|
+
ok: false,
|
|
1408
|
+
error: `${relPosix} belongs to an imported deck and is read-only. Fork it to make changes.`,
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
return { ok: true, abs: fork, rel: relPosix };
|
|
1412
|
+
}
|
|
1413
|
+
if (relPosix === FORKS_DIR || relPosix.startsWith(`${FORKS_DIR}/`)) {
|
|
1414
|
+
return { ok: false, error: `Protected deck path: ${requestedPath}` };
|
|
1415
|
+
}
|
|
1416
|
+
return { ok: true, abs: filepath, rel: relPosix };
|
|
1417
|
+
}
|
|
1418
|
+
function isSameProjectFile(a, b) {
|
|
1419
|
+
try {
|
|
1420
|
+
const sa = fs.statSync(a);
|
|
1421
|
+
const sb = fs.statSync(b);
|
|
1422
|
+
return sa.ino === sb.ino && sa.dev === sb.dev;
|
|
1423
|
+
}
|
|
1424
|
+
catch {
|
|
1425
|
+
return false;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
// Bridge counterpart of the HTTP files/rename handler. Same collision and
|
|
1429
|
+
// import/fork rules; returns a LocalResponse-shaped result for the SDK.
|
|
1430
|
+
function renameProjectFile(projectDir, fromPath, toPath) {
|
|
1431
|
+
const from = resolveMutableProjectPath(projectDir, fromPath);
|
|
1432
|
+
if (!from.ok)
|
|
1433
|
+
return from;
|
|
1434
|
+
const to = resolveMutableProjectPath(projectDir, toPath);
|
|
1435
|
+
if (!to.ok)
|
|
1436
|
+
return to;
|
|
1437
|
+
if (!fs.existsSync(from.abs)) {
|
|
1438
|
+
return { ok: false, error: `Not found: ${from.rel}` };
|
|
1439
|
+
}
|
|
1440
|
+
if (from.abs !== to.abs && fs.existsSync(to.abs) && !isSameProjectFile(from.abs, to.abs)) {
|
|
1441
|
+
return { ok: false, error: `Already exists: ${to.rel}` };
|
|
1442
|
+
}
|
|
1443
|
+
try {
|
|
1444
|
+
fs.mkdirSync(path.dirname(to.abs), { recursive: true });
|
|
1445
|
+
fs.renameSync(from.abs, to.abs);
|
|
1446
|
+
return { ok: true, path: to.rel };
|
|
1447
|
+
}
|
|
1448
|
+
catch (error) {
|
|
1449
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1450
|
+
return { ok: false, error: `Could not rename ${from.rel}: ${message}` };
|
|
1451
|
+
}
|
|
1452
|
+
}
|