castle-web-cli 0.4.149 → 0.4.151

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.
Files changed (49) hide show
  1. package/dist/agent.d.ts +1 -0
  2. package/dist/agent.js +12 -4
  3. package/dist/api.d.ts +45 -1
  4. package/dist/api.js +34 -2
  5. package/dist/castle-host/host.d.ts +17 -0
  6. package/dist/castle-host/host.js +10 -7
  7. package/dist/castleJson.d.ts +15 -0
  8. package/dist/castleJson.js +36 -0
  9. package/dist/devSessionChild.d.ts +1 -0
  10. package/dist/devSessionChild.js +129 -0
  11. package/dist/devSessionServer.d.ts +19 -0
  12. package/dist/devSessionServer.js +511 -0
  13. package/dist/headlessCover.js +28 -0
  14. package/dist/index.js +8 -8
  15. package/dist/init.js +9 -1
  16. package/dist/list-decks.js +7 -6
  17. package/dist/native/playtest-remote.d.ts +3 -0
  18. package/dist/native/playtest-remote.js +113 -0
  19. package/dist/preview.d.ts +1 -1
  20. package/dist/preview.js +4 -2
  21. package/dist/save-deck.js +82 -16
  22. package/dist/serve.js +245 -88
  23. package/dist/serveSecurity.d.ts +7 -1
  24. package/dist/serveSecurity.js +61 -10
  25. package/dist/serverBundle.d.ts +8 -0
  26. package/dist/serverBundle.js +82 -0
  27. package/dist/shell/assets/{index-BzFzFtEP.js → index-Dlhc3eZW.js} +42 -42
  28. package/dist/shell/assets/index-DwezawBs.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/kits/blank/.castle/agent/children.json +1 -0
  31. package/kits/blank/.castle/agent/messages.json +9 -0
  32. package/kits/blank/.castle/agent/pending-sends.json +1 -0
  33. package/kits/blank/.castle/agent/tasks/index.md +2 -0
  34. package/kits/blank/.castle/docs/platform.md +36 -0
  35. package/kits/blank/castle.json +5 -2
  36. package/kits/blank/node_modules/.vite/deps/_metadata.json +8 -0
  37. package/kits/blank/node_modules/.vite/deps/package.json +3 -0
  38. package/kits/physics-2d/behaviors/Collider.jsx +1 -2
  39. package/kits/physics-2d/behaviors/Joints.jsx +1 -1
  40. package/kits/physics-2d/castle.json +1 -1
  41. package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
  42. package/kits/physics-2d/editors/SceneEditor.jsx +171 -57
  43. package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
  44. package/kits/physics-2d/engine/blueprint.js +106 -14
  45. package/kits/physics-2d/engine/scene.js +9 -2
  46. package/kits/physics-2d/engine/ui.jsx +30 -2
  47. package/kits/physics-2d/engine/ui.module.css +59 -0
  48. package/package.json +1 -1
  49. package/dist/shell/assets/index-DN8HQBnW.css +0 -1
@@ -0,0 +1,113 @@
1
+ import * as api from '../api.js';
2
+ import { PLAYTEST_VIEWPORT, } from './playtest.js';
3
+ const CONTENT_HOST_RE = /^(?<grant>[a-z0-9-]{1,63})\.sandboxes(?:-staging)?\.castlexyz\.com$/;
4
+ function failed(input, error) {
5
+ return {
6
+ ok: false,
7
+ error,
8
+ viewport: PLAYTEST_VIEWPORT,
9
+ frames: [],
10
+ console: [],
11
+ diagnostics: {
12
+ rafTicks: 0,
13
+ wallMs: 0,
14
+ framesRequested: input.timeline.filter((event) => event.kind === 'screenshot').length,
15
+ framesCaptured: 0,
16
+ hidden: false,
17
+ },
18
+ };
19
+ }
20
+ export function contentGrantFromBrowserUrl(value) {
21
+ try {
22
+ const url = new URL(value);
23
+ if (url.protocol !== 'https:')
24
+ return null;
25
+ return CONTENT_HOST_RE.exec(url.hostname)?.groups?.grant ?? null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ function operationFromTimeline(input) {
32
+ const actions = [];
33
+ const screenshots = [];
34
+ const keyDown = new Map();
35
+ for (const event of input.timeline) {
36
+ if (event.kind === 'screenshot') {
37
+ screenshots.push(event.t);
38
+ }
39
+ else if (event.kind === 'keydown') {
40
+ const times = keyDown.get(event.key) ?? [];
41
+ times.push(event.t);
42
+ keyDown.set(event.key, times);
43
+ }
44
+ else if (event.kind === 'keyup') {
45
+ const times = keyDown.get(event.key);
46
+ const startedAt = times?.shift();
47
+ if (startedAt !== undefined) {
48
+ actions.push({
49
+ t: startedAt,
50
+ type: 'key',
51
+ key: event.key,
52
+ durationMs: event.t - startedAt,
53
+ });
54
+ }
55
+ }
56
+ else {
57
+ if (!('x' in event))
58
+ continue;
59
+ actions.push({
60
+ t: event.t,
61
+ type: event.kind === 'mousedown'
62
+ ? 'down'
63
+ : event.kind === 'mouseup'
64
+ ? 'up'
65
+ : 'move',
66
+ x: event.x,
67
+ y: event.y,
68
+ });
69
+ }
70
+ }
71
+ actions.sort((a, b) => a.t - b.t);
72
+ return { kind: 'playtest', durationMs: input.durationMs, actions, screenshots };
73
+ }
74
+ function validRemoteResult(result) {
75
+ return (result.protocolVersion === 1 &&
76
+ result.operation === 'playtest' &&
77
+ result.ok === true &&
78
+ result.viewport?.width === PLAYTEST_VIEWPORT.width &&
79
+ result.viewport?.height === PLAYTEST_VIEWPORT.height &&
80
+ Array.isArray(result.frames) &&
81
+ Array.isArray(result.console) &&
82
+ Boolean(result.diagnostics));
83
+ }
84
+ export function createRemotePlaytestExecutor(browserContentUrl) {
85
+ return {
86
+ async runSession(input) {
87
+ const contentUrl = browserContentUrl();
88
+ const grant = contentUrl ? contentGrantFromBrowserUrl(contentUrl) : null;
89
+ if (!grant)
90
+ return failed(input, 'the serve could not mint a browser content grant');
91
+ try {
92
+ const result = (await api.runBrowserJob(grant, operationFromTimeline(input), input.signal));
93
+ if (!result.ok)
94
+ return failed(input, result.error ?? 'browser worker failed');
95
+ if (!validRemoteResult(result))
96
+ return failed(input, 'browser worker returned an invalid result');
97
+ return {
98
+ ok: true,
99
+ viewport: result.viewport,
100
+ frames: result.frames.map((frame) => ({
101
+ t: frame.t,
102
+ png: Buffer.from(frame.pngBase64, 'base64'),
103
+ })),
104
+ console: result.console,
105
+ diagnostics: result.diagnostics,
106
+ };
107
+ }
108
+ catch (error) {
109
+ return failed(input, error instanceof Error ? error.message : String(error));
110
+ }
111
+ },
112
+ };
113
+ }
package/dist/preview.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import type { WebSocket as WSClient } from 'ws';
2
- export declare function connectWS(wsPort: number): Promise<WSClient>;
2
+ export declare function connectWS(servePort: number): Promise<WSClient>;
3
3
  export declare function takeScreenshot(ws: WSClient): Promise<string>;
package/dist/preview.js CHANGED
@@ -1,7 +1,9 @@
1
- export async function connectWS(wsPort) {
1
+ export async function connectWS(servePort) {
2
2
  const { default: WS } = await import('ws');
3
3
  return new Promise((resolve, reject) => {
4
- const ws = new WS(`ws://localhost:${wsPort}`);
4
+ // Old serves proxy this path to their P+1 socket; new serves upgrade it on
5
+ // the main port. This makes CLI commands compatible across the transition.
6
+ const ws = new WS(`ws://localhost:${servePort}/__castle/ws`);
5
7
  ws.on('error', () => reject(new Error('Could not connect. Is castle-web serve running?')));
6
8
  ws.on('open', () => resolve(ws));
7
9
  });
package/dist/save-deck.js CHANGED
@@ -6,7 +6,9 @@ import { nanoid } from 'nanoid';
6
6
  import * as api from './api.js';
7
7
  import * as config from './config.js';
8
8
  import { bundleProject } from './bundle.js';
9
+ import { resolveServerConfig } from './castleJson.js';
9
10
  import { COVER_FILE } from './ide.js';
11
+ import { buildServerBundle } from './serverBundle.js';
10
12
  // `imports/` is derived state like node_modules: a dependency's files belong to
11
13
  // the deck that published them, and castle.json's import pins are enough to fetch
12
14
  // them again -- so they neither bloat this deck's archive nor get republished as
@@ -57,29 +59,81 @@ export async function archiveSource(projectDir) {
57
59
  }
58
60
  }
59
61
  }
62
+ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, label) {
63
+ const formData = new FormData();
64
+ formData.append('Content-Type', contentType);
65
+ for (const [key, value] of Object.entries(uploadConfig.postFields)) {
66
+ formData.append(key, String(value));
67
+ }
68
+ formData.append('file', file);
69
+ const response = await fetch(uploadConfig.postUrl, {
70
+ method: 'POST',
71
+ body: formData,
72
+ signal: AbortSignal.timeout(timeoutMs),
73
+ });
74
+ if (response.status >= 300)
75
+ throw new Error(`${label} failed: HTTP ${response.status}`);
76
+ }
60
77
  async function uploadSource(projectDir, deckId) {
61
78
  const archive = await archiveSource(projectDir);
62
79
  const sizeKB = archive.length / 1024;
63
80
  console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
64
81
  const uploadConfig = await api.createWebDeckSourceUploadConfig(deckId);
65
- const formData = new FormData();
66
- formData.append('Content-Type', 'application/gzip');
67
- for (const [k, v] of Object.entries(uploadConfig.postFields)) {
68
- formData.append(k, String(v));
69
- }
70
82
  // FormData expects a Blob; copy the Buffer's bytes so we don't share the underlying ArrayBuffer.
71
83
  const view = new Uint8Array(archive.byteLength);
72
84
  view.set(archive);
73
- formData.append('file', new Blob([view], { type: 'application/gzip' }));
74
- const s3Res = await fetch(uploadConfig.postUrl, {
75
- method: 'POST',
76
- body: formData,
77
- signal: AbortSignal.timeout(60000),
85
+ await uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload');
86
+ await api.saveWebDeckSource(deckId, uploadConfig.uploadId);
87
+ }
88
+ const SERVER_BUNDLE_STATE = path.join('.castle', 'published-server-bundle.json');
89
+ function readPublishedServerBundleState(projectDir) {
90
+ try {
91
+ const value = JSON.parse(fs.readFileSync(path.join(projectDir, SERVER_BUNDLE_STATE), 'utf8'));
92
+ return typeof value.deckId === 'string' && typeof value.sha256 === 'string'
93
+ ? { deckId: value.deckId, sha256: value.sha256 }
94
+ : null;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
100
+ function writePublishedServerBundleState(projectDir, state) {
101
+ const file = path.join(projectDir, SERVER_BUNDLE_STATE);
102
+ fs.mkdirSync(path.dirname(file), { recursive: true });
103
+ fs.writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
104
+ }
105
+ async function publishServerBundle(projectDir, deckId) {
106
+ const serverConfig = resolveServerConfig(projectDir);
107
+ if (!serverConfig) {
108
+ const prior = readPublishedServerBundleState(projectDir);
109
+ if (prior?.deckId !== deckId) {
110
+ console.log('Server bundle skipped: no server entry found.');
111
+ return;
112
+ }
113
+ await api.saveCauldronServerBundle(deckId, null);
114
+ fs.rmSync(path.join(projectDir, SERVER_BUNDLE_STATE), { force: true });
115
+ console.log('Cleared the previously published server bundle (no server entry found).');
116
+ return;
117
+ }
118
+ console.log(`Bundling server (${serverConfig.entry})...`);
119
+ const bundle = await buildServerBundle(projectDir);
120
+ if (!bundle)
121
+ throw new Error('Server entry disappeared while bundling.');
122
+ console.log(`Server bundle size: ${(bundle.sizeBytes / 1024).toFixed(1)}KB`);
123
+ const uploadConfig = await api.createCauldronServerBundleUploadConfig(deckId);
124
+ await uploadPresignedFile(uploadConfig, new Blob([bundle.code], { type: 'application/javascript' }), 'application/javascript', 60_000, 'Server bundle upload');
125
+ const saved = await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
126
+ tickRate: serverConfig.tickRate,
127
+ maxPlayers: serverConfig.maxPlayers,
78
128
  });
79
- if (s3Res.status >= 300) {
80
- throw new Error(`Source upload failed: HTTP ${s3Res.status}`);
129
+ // The server hashes what it actually stored. A mismatch means the bytes that
130
+ // will run in sessions are not the bytes we bundled.
131
+ if (saved && saved.sha256 !== bundle.sha256) {
132
+ throw new Error(`Published server bundle does not match what was built ` +
133
+ `(server ${saved.sha256}, local ${bundle.sha256}). The deck was not updated safely.`);
81
134
  }
82
- await api.saveWebDeckSource(deckId, uploadConfig.uploadId);
135
+ writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
136
+ console.log(`Server bundle published${saved ? ` as ${saved.version}` : ''} (sha256 ${bundle.sha256}).`);
83
137
  }
84
138
  // Publish the deck's local cover, if it has one, and return the file id for the
85
139
  // card. The editor writes `preview.png` as you play (see the serve's cover
@@ -90,13 +144,24 @@ async function uploadSource(projectDir, deckId) {
90
144
  // The deck's own serve, if one is running -- the URL a headless cover capture
91
145
  // loads. No serve means no deck to photograph, which is a normal state (a save
92
146
  // from a script), not an error.
93
- function runningServeUrl(projectDir) {
147
+ async function runningServeUrl(projectDir) {
94
148
  try {
95
149
  const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
96
150
  const parsed = JSON.parse(raw);
151
+ const port = parsed.port;
152
+ if (process.env.CASTLE_SANDBOX_ID && typeof port === 'number') {
153
+ try {
154
+ const response = await fetch(`http://localhost:${port}/__castle/browser-content-grant`, { signal: AbortSignal.timeout(2_000) });
155
+ const body = (await response.json());
156
+ if (response.ok && typeof body.url === 'string')
157
+ return body.url;
158
+ }
159
+ catch {
160
+ // Fall through to the existing best-effort local capture path.
161
+ }
162
+ }
97
163
  if (typeof parsed.contentPlayUrl === 'string')
98
164
  return parsed.contentPlayUrl;
99
- const port = parsed.port;
100
165
  return typeof port === 'number' ? `http://localhost:${port}` : null;
101
166
  }
102
167
  catch {
@@ -118,7 +183,7 @@ function runningServeUrl(projectDir) {
118
183
  // you never look at it, and nobody looks at an unattended capture. Writing to a
119
184
  // scratch file rather than over `preview.png` keeps that fallback intact.
120
185
  async function captureAutomaticCover(projectDir) {
121
- const serveUrl = runningServeUrl(projectDir);
186
+ const serveUrl = await runningServeUrl(projectDir);
122
187
  if (!serveUrl)
123
188
  return null;
124
189
  const outPath = path.join(projectDir, '.castle', 'headless-cover.png');
@@ -273,6 +338,7 @@ export async function saveDeck(dir, opts = {}) {
273
338
  else {
274
339
  console.log(`Saved "${title}" to Castle.`);
275
340
  }
341
+ await publishServerBundle(projectDir, result.deckId);
276
342
  console.log('Uploading source archive...');
277
343
  await uploadSource(projectDir, result.deckId);
278
344
  console.log('Source archive saved.');