castle-web-cli 0.4.226 → 0.4.227
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 +5 -0
- package/dist/agent-prompts.js +7 -7
- package/dist/agent.d.ts +1 -0
- package/dist/agent.js +54 -46
- package/dist/api.d.ts +3 -0
- package/dist/api.js +3 -3
- package/dist/get-deck.js +5 -2
- package/dist/importBrowse.js +7 -6
- package/dist/imports.d.ts +2 -1
- package/dist/imports.js +82 -13
- package/dist/init.js +17 -4
- package/dist/platformDoc.d.ts +1 -0
- package/dist/platformDoc.js +31 -9
- package/dist/playPagePolicy.js +35 -1
- package/dist/remix.js +1 -1
- package/dist/save-deck.d.ts +1 -7
- package/dist/save-deck.js +18 -26
- package/dist/saveFailure.d.ts +26 -0
- package/dist/saveFailure.js +102 -0
- package/dist/shell/assets/{index-4G5NKIQ8.css → index-BxDYy_-C.css} +1 -1
- package/dist/shell/assets/{index-C7ksEq3_.js → index-D006JHww.js} +94 -94
- package/dist/shell/index.html +2 -2
- package/kits/base/CLAUDE.md +2 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +49 -0
- package/kits/base/sdk/castle.d.ts +2 -0
- package/kits/base/sdk/castle.js +1 -0
- package/kits/base/sdk/display.d.ts +36 -0
- package/kits/base/sdk/display.js +96 -0
- package/kits/base/sdk/runtime.js +35 -17
- package/package.json +2 -2
package/dist/platformDoc.js
CHANGED
|
@@ -79,9 +79,18 @@ export function everyDeckBullets(deckDir) {
|
|
|
79
79
|
export const HOST_LIMIT_BULLETS = [
|
|
80
80
|
"- **Where a deck runs decides what it can do.** The Play panel runs it from this serve; players run the published deck in the Castle app (iOS, Android) or castle.xyz's web player. When something works in one and fails in another, check it against the limits below before another fix: if one covers it, name that limit instead of retrying, and ask where they run it if you do not know. If none does, it is an ordinary deck bug (a runtime `fetch` of a loose file, a control that only answers a mouse) and gets fixed.",
|
|
81
81
|
"- **Microphone and camera are blocked in the Play panel and on castle.xyz**: neither frame is granted them, so `getUserMedia` rejects with `NotAllowedError` whatever the person allows, and no deck change helps. The Android app's published deck can use them; the iOS app is untested.",
|
|
82
|
-
"- **A published deck loads almost nothing from the network.** Its CSP allows images, audio and video only from the deck itself, `data:` or `blob:`, `fetch` only to esm.sh, cdnjs.cloudflare.com and Castle's multiplayer hosts, and no iframes. The Play panel
|
|
82
|
+
"- **A published deck loads almost nothing from the network.** Its CSP allows images, audio and video only from the deck itself, `data:` or `blob:`, `fetch` only to esm.sh, cdnjs.cloudflare.com and Castle's multiplayer hosts, and no iframes. The Play panel enforces the same CSP, so a URL it blocks fails in Play too, and `.castle/logs.txt` names each URL and directive the page blocked with a `[csp] blocked` line. Bundle the file, or let the player pick one with `<input type=\"file\">`.",
|
|
83
83
|
"- **An older Castle app build rejects SDK commands newer than the build**, with a `CastleError` whose `code` is `UNKNOWN_COMMAND`; only an app update fixes that, so the deck should catch it and keep working. Which commands need which app build, and every other limit of a Castle service, is in the SDK reference, `imports/castle.base/sdk/README.md`.",
|
|
84
84
|
];
|
|
85
|
+
// The frustration survey found the router inventing Upload buttons and offering
|
|
86
|
+
// video through image-only chat attach. Each control named here carries a comment
|
|
87
|
+
// pointing back, so moving or renaming one means updating this too.
|
|
88
|
+
export const CASTLE_UI_BULLETS = [
|
|
89
|
+
"- **Upload is not its own button.** Files go into the deck from the Files panel: **New** → **Upload files…**, the last item of that menu. On a phone, switch to the Files panel first. The **Import** button beside New adds another Castle deck as an import; it does not upload files.",
|
|
90
|
+
"- **Chat attach takes images only.** The attach control under the message box accepts image files. Audio, video, 3D models and any other file go in through Files → New → Upload files…, never through chat.",
|
|
91
|
+
"- **An imported file opens read-only**, under a banner naming the import it came from. Where the file can be forked (nearly all can; an import's `castle.json` cannot), the banner's **Fork** button (also Fork in that file's menu in the Files panel) gives this deck its own editable copy; **Drop fork** goes back to the import's version.",
|
|
92
|
+
"- **Describe only the Castle controls named here or in the deck's guide.** If you do not know where something is in Castle's UI, say so -- never name a button, menu or location you have not seen described.",
|
|
93
|
+
];
|
|
85
94
|
// The line has to stand on its own to count: this repo's CLAUDE.md names the
|
|
86
95
|
// path inside a sentence, and prose about the import must not read as a deck
|
|
87
96
|
// carrying one.
|
|
@@ -114,14 +123,18 @@ function deckLoadsGuide(deckDir) {
|
|
|
114
123
|
const RESTATEMENT_MARKER = '**Supported media formats are exactly**';
|
|
115
124
|
// The every-deck bullets after a quick reference that lacks them. Skipped when
|
|
116
125
|
// the deck's kit is pinned to a version that still restates them, which would
|
|
117
|
-
// otherwise say all of it twice. No kit ever restated the
|
|
118
|
-
// come either way.
|
|
126
|
+
// otherwise say all of it twice. No kit ever restated the Castle UI bullets or
|
|
127
|
+
// host limits, so they come either way.
|
|
119
128
|
function withEveryDeckBullets(deckDir, quickReference) {
|
|
120
129
|
const own = quickReference.trim();
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const bullets = [
|
|
130
|
+
if (own.includes(RESTATEMENT_MARKER)) {
|
|
131
|
+
return `${own}\n\n${[...CASTLE_UI_BULLETS, ...HOST_LIMIT_BULLETS].join('\n')}`;
|
|
132
|
+
}
|
|
133
|
+
const bullets = [
|
|
134
|
+
...everyDeckBullets(deckDir),
|
|
135
|
+
...CASTLE_UI_BULLETS,
|
|
136
|
+
...HOST_LIMIT_BULLETS,
|
|
137
|
+
].join('\n');
|
|
125
138
|
return own ? `${own}\n\n${bullets}` : bullets;
|
|
126
139
|
}
|
|
127
140
|
// Whether a role's claude process auto-loads the deck's CLAUDE.md, and with it
|
|
@@ -219,9 +232,14 @@ const COMMON_SECTIONS = `## Imports are read-only
|
|
|
219
232
|
|
|
220
233
|
- **Playable on a touchscreen, with only the controls the game actually needs.** Castle decks are played on phones, so whatever input a game does use must work by touch — direct tap/drag on the game itself wherever possible, and on-screen buttons only where the mechanics genuinely call for them. Do NOT add controls a game doesn't need: never drop in a generic d-pad or movement overlay by default. Prefer touching the game directly over an overlay that just mirrors keyboard keys. Keyboard input is fine to support on top for desktop play. Match the controls to the actual mechanics — a game with no directional movement should have no movement controls at all.
|
|
221
234
|
|
|
222
|
-
## Fit the
|
|
235
|
+
## Fit the stage
|
|
223
236
|
|
|
224
|
-
- **
|
|
237
|
+
- **A deck plays inside a stage that clips overflow and does not scroll.** By default the stage is a 5:7 portrait card sized to fit the screen (at most about 450x630px). A deck that declares \`<meta name="castle-display" content="layout=fill">\` in its \`index.html\` \`<head>\` instead gets whatever box the host can give it -- a wide stage on desktop, the full height of a tall phone, the whole screen in fullscreen -- as long as the box's width / height is inside its range (default 9/21 to 21/9; narrow it with \`min-aspect=\` / \`max-aspect=\`, as \`16/9\`, \`16:9\` or \`1.78\`). Outside the range the deck gets the largest in-range box, centered. The SDK exports \`CARD_RATIO\` (= 5 / 7) if you need the exact ratio.
|
|
238
|
+
- **Declare fill for a deck you lay out yourself**, unless it is built around a fixed portrait board (a card game, a vertical puzzle) that would only gain empty margins: that is the default for new bare decks, and Castle's web player gives a fill deck a bigger stage and a fullscreen button. A kit deck keeps whatever its kit guide says; don't add the tag to a kit deck whose guide doesn't mention it. Fullscreen belongs to the host: never build a fullscreen button or call \`requestFullscreen\` in a deck.
|
|
239
|
+
- **A fill deck has no fixed shape, and must look right at every shape in its range -- including 5:7, which it still gets from hosts that ignore the tag.** Lay out with flex/grid against the stage -- the element \`initCard()\` returns (its \`clientWidth\`/\`clientHeight\`), or \`var(--castle-card-w)\`/\`var(--castle-card-h)\` in CSS -- not against the window: the stage is smaller than the window whenever the host frame is outside the deck's range, and inside \`castle-web serve\`'s own page. Re-layout on \`resize\`; let the playfield use the extra room (a wider view of the world, a bigger board), and anchor HUD to the stage's edges and corners. Don't letterbox the game back into a 5:7 box inside a fill stage -- that just gives up the space.
|
|
240
|
+
- **A deck that lays itself out sizes HUD, buttons and text in the card unit, \`var(--castle-unit)\`, not \`vw\`, \`vh\` or \`cqw\`**: \`font-size: calc(5 * var(--castle-unit))\`. It is 1% of the width of the largest 5:7 card that fits in the stage -- the same as \`1vw\` on a card -- so a HUD keeps its card size on a wide stage, where anything in \`vw\` grows to fill a monitor. Canvas code gets the same px value from \`cardUnit(width, height)\` of the stage. A kit deck sizes things the way its kit guide says: a kit's scene editor draws the stage smaller inside the editor, where the unit follows the window instead.
|
|
241
|
+
- **A 3D camera keeps its framing across shapes with \`fovForAspect(fov, aspect)\`**: \`camera.fov = fovForAspect(50, width / height)\` on every resize. It keeps \`fov\` at 5:7 and wider and widens it on a stage taller than 5:7, so a tall phone doesn't crop the sides of the scene.
|
|
242
|
+
- **The Play panel shows a 5:7 stage** (\`npm run screenshot\` captures whatever shape the open deck tab has). For a fill deck that is one shape of many: make the layout's rules (anchors, the card unit, the camera) hold at any shape rather than tuning it pixel by pixel to what the Play panel shows.
|
|
225
243
|
- **Hand-rolled \`<canvas>\` elements must account for devicePixelRatio, or the game looks blurry on phones.** Size the backing store to the CSS layout size times \`devicePixelRatio\` (e.g. \`canvas.width = rect.width * dpr\`), keep the CSS width/height as the layout size, and scale the 2D context (\`ctx.scale(dpr, dpr)\`) so drawing code stays in CSS units — re-apply on resize. Kit decks don't need to do this by hand; the kit's engine already configures its canvas for DPR.
|
|
226
244
|
- Exception: deliberate pixel art wants a fixed low-resolution backing store with \`image-rendering: pixelated\` CSS instead — don't DPR-scale that; the crisp chunky look is the point.
|
|
227
245
|
- **A WebGL canvas must be created with \`preserveDrawingBuffer: true\`, or every in-page capture of the deck comes back blank** — the Play panel's Snap and \`npm run screenshot\` both read the canvas after the frame has been shown, and by then the browser has cleared it, so the image is just the card's background. Pass it through whatever library makes the canvas: \`new THREE.WebGLRenderer({ preserveDrawingBuffer: true })\`, PixiJS \`app.init({ preserveDrawingBuffer: true })\`, or \`canvas.getContext('webgl2', { preserveDrawingBuffer: true })\`. A 2D canvas needs nothing, and kit decks already set it.
|
|
@@ -289,6 +307,10 @@ ${everyDeckBullets(deckDir).filter((b) => !b.includes('PARAMS')).join('\n')}
|
|
|
289
307
|
|
|
290
308
|
${everyDeckBullets(deckDir).filter((b) => b.includes('PARAMS')).join('\n')}
|
|
291
309
|
|
|
310
|
+
## Castle UI
|
|
311
|
+
|
|
312
|
+
${CASTLE_UI_BULLETS.join('\n')}
|
|
313
|
+
|
|
292
314
|
## Host limits
|
|
293
315
|
|
|
294
316
|
${HOST_LIMIT_BULLETS.join('\n')}
|
package/dist/playPagePolicy.js
CHANGED
|
@@ -21,6 +21,40 @@ const DECK_CSP = [
|
|
|
21
21
|
].join('; ');
|
|
22
22
|
// A <meta> policy binds only what follows it, so it goes first in <head>.
|
|
23
23
|
const DECK_CSP_TAG = `<meta http-equiv="Content-Security-Policy" content="${DECK_CSP}">`;
|
|
24
|
+
// Lines are held until DOMContentLoaded because a request blocked while the
|
|
25
|
+
// parser is still ahead of the deck's module fires before the SDK has wrapped
|
|
26
|
+
// console, and only that wrapper writes .castle/logs.txt.
|
|
27
|
+
const CSP_LOG_SCRIPT = `<script>
|
|
28
|
+
(function () {
|
|
29
|
+
if (window.__castleCspLogInstalled) return;
|
|
30
|
+
window.__castleCspLogInstalled = true;
|
|
31
|
+
var seen = Object.create(null);
|
|
32
|
+
var count = 0;
|
|
33
|
+
var held = [];
|
|
34
|
+
var warn = function (line) {
|
|
35
|
+
if (held) held.push(line);
|
|
36
|
+
else console.warn(line);
|
|
37
|
+
};
|
|
38
|
+
document.addEventListener('DOMContentLoaded', function () {
|
|
39
|
+
setTimeout(function () {
|
|
40
|
+
var lines = held;
|
|
41
|
+
held = null;
|
|
42
|
+
for (var i = 0; i < lines.length; i++) console.warn(lines[i]);
|
|
43
|
+
}, 0);
|
|
44
|
+
});
|
|
45
|
+
document.addEventListener('securitypolicyviolation', function (event) {
|
|
46
|
+
if (event.disposition && event.disposition !== 'enforce') return;
|
|
47
|
+
if (count >= 20) return;
|
|
48
|
+
var directive = event.effectiveDirective || event.violatedDirective || 'unknown';
|
|
49
|
+
var rawUri = String(event.blockedURI || 'empty');
|
|
50
|
+
var key = directive + '\\n' + rawUri;
|
|
51
|
+
if (seen[key]) return;
|
|
52
|
+
seen[key] = true;
|
|
53
|
+
count += 1;
|
|
54
|
+
warn('[csp] blocked ' + rawUri.slice(0, 200) + ' (' + directive + ') -- a published deck blocks this too');
|
|
55
|
+
}, true);
|
|
56
|
+
})();
|
|
57
|
+
</script>`;
|
|
24
58
|
// Copy of EXPERIMENTAL_WEB_IFRAME_BLOCK_SCRIPT in castle-client
|
|
25
59
|
// `mobile/js/common/experimentalWebHardening.ts`: the mobile app removes every
|
|
26
60
|
// frame element from a deck. One change: html2canvas composites a card through
|
|
@@ -77,5 +111,5 @@ export function isPlayPageUrl(url) {
|
|
|
77
111
|
}
|
|
78
112
|
}
|
|
79
113
|
export function playPageHeadInjection() {
|
|
80
|
-
return `\n ${DECK_CSP_TAG}\n ${IFRAME_BLOCK_SCRIPT}`;
|
|
114
|
+
return `\n ${DECK_CSP_TAG}\n ${CSP_LOG_SCRIPT}\n ${IFRAME_BLOCK_SCRIPT}`;
|
|
81
115
|
}
|
package/dist/remix.js
CHANGED
|
@@ -51,7 +51,7 @@ export function discardParentSource(source) {
|
|
|
51
51
|
/** Unpack straight into the deck dir, the way get-deck does. */
|
|
52
52
|
export async function unpackParentSource(source, projectDir) {
|
|
53
53
|
fs.mkdirSync(projectDir, { recursive: true });
|
|
54
|
-
await runTar(['-xzf', source.archivePath, '-C', projectDir]);
|
|
54
|
+
await runTar(['-xzf', source.archivePath, '--no-same-owner', '-C', projectDir]);
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
57
|
* Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
|
package/dist/save-deck.d.ts
CHANGED
|
@@ -1,19 +1,13 @@
|
|
|
1
1
|
import * as api from './api.js';
|
|
2
2
|
import { type SavePrecondition } from './webSourceSync.js';
|
|
3
|
+
export { DeckTooLargeError, MAX_SCENE_DATA_BYTES, MAX_SOURCE_ARCHIVE_BYTES, sceneTooLargeMessage, sourceTooLargeMessage, } from './saveFailure.js';
|
|
3
4
|
export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
|
|
4
5
|
export declare const SAVE_STAGE_TELEMETRY_PREFIX = "CASTLE_SAVE_TELEMETRY ";
|
|
5
6
|
export declare const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = "CASTLE_SAVE_COVER_SELECTION ";
|
|
6
|
-
export declare const MAX_SCENE_DATA_BYTES: number;
|
|
7
|
-
export declare const MAX_SOURCE_ARCHIVE_BYTES: number;
|
|
8
7
|
export type SaveStage = 'bundle' | 'cover' | 'scene_upload_config' | 'scene_upload' | 'content_publish' | 'server_publish' | 'source_archive' | 'source_upload_config' | 'source_upload' | 'source_commit';
|
|
9
8
|
export declare function runTar(args: string[], opts?: {
|
|
10
9
|
capture?: boolean;
|
|
11
10
|
}): Promise<string>;
|
|
12
|
-
export declare function sceneTooLargeMessage(bytes: number): string;
|
|
13
|
-
export declare function sourceTooLargeMessage(bytes: number, largest: {
|
|
14
|
-
file: string;
|
|
15
|
-
bytes: number;
|
|
16
|
-
}[], published?: boolean): string;
|
|
17
11
|
export declare function archiveSource(projectDir: string): Promise<Buffer>;
|
|
18
12
|
export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string, log?: (line: string) => void): Promise<string>;
|
|
19
13
|
export declare function packSourceForSave(projectDir: string, castleJson: string | null, { published }?: {
|
package/dist/save-deck.js
CHANGED
|
@@ -11,6 +11,8 @@ import { selectSaveCover } from './saveCover.js';
|
|
|
11
11
|
import { COVER_FILE } from './localPaths.js';
|
|
12
12
|
import { buildServerBundle } from './serverBundle.js';
|
|
13
13
|
import { decideSavePrecondition, EXIT_SAVED_DECK_NEWER, fetchServerSourceVersion, readSyncMarker, saveRefusedLine, saveRefusedMessage, WEB_DECK_SOURCE_STALE_CODE, writeSyncMarker, } from './webSourceSync.js';
|
|
14
|
+
import { DeckTooLargeError, MAX_SCENE_DATA_BYTES, MAX_SOURCE_ARCHIVE_BYTES, SAVE_FAILURE_ENV, classifySaveFailure, saveFailedLine, sceneTooLargeMessage, sourceTooLargeMessage, } from './saveFailure.js';
|
|
15
|
+
export { DeckTooLargeError, MAX_SCENE_DATA_BYTES, MAX_SOURCE_ARCHIVE_BYTES, sceneTooLargeMessage, sourceTooLargeMessage, } from './saveFailure.js';
|
|
14
16
|
// `imports/` is derived state like node_modules: a dependency's files belong to
|
|
15
17
|
// the deck that published them, and castle.json's import pins are enough to fetch
|
|
16
18
|
// them again -- so they neither bloat this deck's archive nor get republished as
|
|
@@ -23,14 +25,9 @@ export const SOURCE_ARCHIVE_EXCLUDES = ['node_modules', 'dist', '.castle', '.git
|
|
|
23
25
|
// independently deployable.
|
|
24
26
|
export const SAVE_STAGE_TELEMETRY_PREFIX = 'CASTLE_SAVE_TELEMETRY ';
|
|
25
27
|
export const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = 'CASTLE_SAVE_COVER_SELECTION ';
|
|
26
|
-
// Ghost's upload ceilings, enforced by S3 in the presigned POST policies (diy.ts
|
|
27
|
-
// MAX_SCENE_DATA_BYTES, webDeckSource.ts MAX_ARCHIVE_BYTES). Mirrored here so an oversized deck
|
|
28
|
-
// is refused before anything is uploaded: past the cap S3 answers only an opaque HTTP 400, and the
|
|
29
|
-
// source upload runs after the deck has already gone live. Keep these in step with ghost.
|
|
30
|
-
export const MAX_SCENE_DATA_BYTES = 50 * 1024 * 1024;
|
|
31
|
-
export const MAX_SOURCE_ARCHIVE_BYTES = 100 * 1024 * 1024;
|
|
32
28
|
// Long enough to move a payload at either cap over a slow uplink (100 MB at ~3 Mbit/s).
|
|
33
29
|
const LARGE_UPLOAD_TIMEOUT_MS = 300_000;
|
|
30
|
+
let failedStage = null;
|
|
34
31
|
function emitSaveStage(stage, outcome, startedAtMs, fields = {}) {
|
|
35
32
|
if (process.env.CASTLE_SAVE_STAGE_TELEMETRY !== '1')
|
|
36
33
|
return;
|
|
@@ -53,6 +50,7 @@ async function traceSaveStage(stage, operation, fields) {
|
|
|
53
50
|
return result;
|
|
54
51
|
}
|
|
55
52
|
catch (error) {
|
|
53
|
+
failedStage = stage;
|
|
56
54
|
emitSaveStage(stage, 'failure', startedAtMs);
|
|
57
55
|
throw error;
|
|
58
56
|
}
|
|
@@ -82,9 +80,6 @@ export function runTar(args, opts = {}) {
|
|
|
82
80
|
});
|
|
83
81
|
});
|
|
84
82
|
}
|
|
85
|
-
function formatMB(bytes) {
|
|
86
|
-
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
87
|
-
}
|
|
88
83
|
// The biggest files the source archive would carry, as a hint for what to shrink. Skips what the
|
|
89
84
|
// archive excludes and never follows a symlink; unreadable entries are left out.
|
|
90
85
|
function largestSourceFiles(projectDir, count) {
|
|
@@ -116,21 +111,6 @@ function largestSourceFiles(projectDir, count) {
|
|
|
116
111
|
walk('');
|
|
117
112
|
return found.sort((a, b) => b.bytes - a.bytes).slice(0, count);
|
|
118
113
|
}
|
|
119
|
-
export function sceneTooLargeMessage(bytes) {
|
|
120
|
-
return (`This deck is too large to save: its game bundle is ${formatMB(bytes)}, and Castle accepts at ` +
|
|
121
|
-
`most ${formatMB(MAX_SCENE_DATA_BYTES)}. Nothing was published. Images, audio and models are ` +
|
|
122
|
-
'packed into the bundle, so shrink or remove the largest assets and save again.');
|
|
123
|
-
}
|
|
124
|
-
export function sourceTooLargeMessage(bytes, largest, published = false) {
|
|
125
|
-
const list = largest.map((f) => `${f.file} (${formatMB(f.bytes)})`).join(', ');
|
|
126
|
-
return (`This deck's source is too large to save: compressed, it is ${formatMB(bytes)}, and Castle ` +
|
|
127
|
-
`accepts at most ${formatMB(MAX_SOURCE_ARCHIVE_BYTES)}. ` +
|
|
128
|
-
(published
|
|
129
|
-
? 'The playable deck was updated, but its source was not saved.'
|
|
130
|
-
: 'Nothing was published.') +
|
|
131
|
-
(list ? ` Largest files: ${list}.` : '') +
|
|
132
|
-
' Remove or shrink files the deck does not need and save again.');
|
|
133
|
-
}
|
|
134
114
|
export async function archiveSource(projectDir) {
|
|
135
115
|
const tmpFile = path.join(os.tmpdir(), `castle-source-${nanoid(8)}.tar.gz`);
|
|
136
116
|
const args = ['-czf', tmpFile];
|
|
@@ -211,7 +191,7 @@ export async function packSourceForSave(projectDir, castleJson, { published = fa
|
|
|
211
191
|
await runTar(args);
|
|
212
192
|
const archive = fs.readFileSync(outFile);
|
|
213
193
|
if (archive.byteLength > MAX_SOURCE_ARCHIVE_BYTES) {
|
|
214
|
-
throw new
|
|
194
|
+
throw new DeckTooLargeError('source', archive.byteLength, MAX_SOURCE_ARCHIVE_BYTES, sourceTooLargeMessage(archive.byteLength, largestSourceFiles(projectDir, 3), published));
|
|
215
195
|
}
|
|
216
196
|
console.log(`Source archive: ${(archive.length / 1024).toFixed(1)}KB`);
|
|
217
197
|
return archive;
|
|
@@ -376,6 +356,18 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
376
356
|
console.error(`No index.html found in ${projectDir}`);
|
|
377
357
|
process.exit(1);
|
|
378
358
|
}
|
|
359
|
+
failedStage = null;
|
|
360
|
+
try {
|
|
361
|
+
await saveDeckAfterValidation(dir, opts, projectDir, visibility);
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
if (process.env[SAVE_FAILURE_ENV] === '1') {
|
|
365
|
+
console.log(saveFailedLine(classifySaveFailure(failedStage, error)));
|
|
366
|
+
}
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async function saveDeckAfterValidation(dir, opts, projectDir, visibility) {
|
|
379
371
|
const castleJson = readCastleJson(projectDir);
|
|
380
372
|
const existingDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
|
|
381
373
|
// A deck without an id is new: the source commit sends no precondition, as before.
|
|
@@ -407,7 +399,7 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
407
399
|
const sceneBytes = Buffer.byteLength(sceneJson);
|
|
408
400
|
if (sceneBytes > MAX_SCENE_DATA_BYTES) {
|
|
409
401
|
// Reported as the stage that would have failed, so castle-www's failed_at stays comparable.
|
|
410
|
-
await traceSaveStage('scene_upload', () => Promise.reject(new
|
|
402
|
+
await traceSaveStage('scene_upload', () => Promise.reject(new DeckTooLargeError('bundle', sceneBytes, MAX_SCENE_DATA_BYTES, sceneTooLargeMessage(sceneBytes))));
|
|
411
403
|
}
|
|
412
404
|
const isNew = !castleJson;
|
|
413
405
|
const cardId = castleJson?.cardId ?? nanoid(12);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const MAX_SCENE_DATA_BYTES: number;
|
|
2
|
+
export declare const MAX_SOURCE_ARCHIVE_BYTES: number;
|
|
3
|
+
export declare const SAVE_FAILED_PREFIX = "CASTLE_SAVE_FAILED ";
|
|
4
|
+
export declare const SAVE_FAILURE_ENV = "CASTLE_SAVE_FAILURE_REPORT";
|
|
5
|
+
export type SaveFailureReason = 'too_large' | 'upload_timeout' | 'network' | 'build' | 'unknown';
|
|
6
|
+
export interface SaveFailure {
|
|
7
|
+
reason: SaveFailureReason;
|
|
8
|
+
stage?: string;
|
|
9
|
+
part?: 'bundle' | 'source';
|
|
10
|
+
bytes?: number;
|
|
11
|
+
limitBytes?: number;
|
|
12
|
+
}
|
|
13
|
+
export declare function sceneTooLargeMessage(bytes: number): string;
|
|
14
|
+
export declare function sourceTooLargeMessage(bytes: number, largest: {
|
|
15
|
+
file: string;
|
|
16
|
+
bytes: number;
|
|
17
|
+
}[], published?: boolean): string;
|
|
18
|
+
export declare class DeckTooLargeError extends Error {
|
|
19
|
+
readonly part: 'bundle' | 'source';
|
|
20
|
+
readonly bytes: number;
|
|
21
|
+
readonly limitBytes: number;
|
|
22
|
+
readonly name = "DeckTooLargeError";
|
|
23
|
+
constructor(part: 'bundle' | 'source', bytes: number, limitBytes: number, message: string);
|
|
24
|
+
}
|
|
25
|
+
export declare function classifySaveFailure(stage: string | null, error: unknown): SaveFailure;
|
|
26
|
+
export declare function saveFailedLine(failure: SaveFailure): string;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Ghost's upload ceilings, enforced by S3 in the presigned POST policies (diy.ts
|
|
2
|
+
// MAX_SCENE_DATA_BYTES, webDeckSource.ts MAX_ARCHIVE_BYTES). Mirrored here so an oversized deck
|
|
3
|
+
// is refused before anything is uploaded: past the cap S3 answers only an opaque HTTP 400, and the
|
|
4
|
+
// source upload runs after the deck has already gone live. Keep these in step with ghost.
|
|
5
|
+
export const MAX_SCENE_DATA_BYTES = 50 * 1024 * 1024;
|
|
6
|
+
export const MAX_SOURCE_ARCHIVE_BYTES = 100 * 1024 * 1024;
|
|
7
|
+
export const SAVE_FAILED_PREFIX = 'CASTLE_SAVE_FAILED ';
|
|
8
|
+
export const SAVE_FAILURE_ENV = 'CASTLE_SAVE_FAILURE_REPORT';
|
|
9
|
+
function formatMB(bytes) {
|
|
10
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
11
|
+
}
|
|
12
|
+
export function sceneTooLargeMessage(bytes) {
|
|
13
|
+
return (`This deck is too large to save: its game bundle is ${formatMB(bytes)}, and Castle accepts at ` +
|
|
14
|
+
`most ${formatMB(MAX_SCENE_DATA_BYTES)}. Nothing was published. Images, audio and models are ` +
|
|
15
|
+
'packed into the bundle, so shrink or remove the largest assets and save again.');
|
|
16
|
+
}
|
|
17
|
+
export function sourceTooLargeMessage(bytes, largest, published = false) {
|
|
18
|
+
const list = largest.map((file) => `${file.file} (${formatMB(file.bytes)})`).join(', ');
|
|
19
|
+
return (`This deck's source is too large to save: compressed, it is ${formatMB(bytes)}, and Castle ` +
|
|
20
|
+
`accepts at most ${formatMB(MAX_SOURCE_ARCHIVE_BYTES)}. ` +
|
|
21
|
+
(published
|
|
22
|
+
? 'The playable deck was updated, but its source was not saved.'
|
|
23
|
+
: 'Nothing was published.') +
|
|
24
|
+
(list ? ` Largest files: ${list}.` : '') +
|
|
25
|
+
' Remove or shrink files the deck does not need and save again.');
|
|
26
|
+
}
|
|
27
|
+
export class DeckTooLargeError extends Error {
|
|
28
|
+
part;
|
|
29
|
+
bytes;
|
|
30
|
+
limitBytes;
|
|
31
|
+
name = 'DeckTooLargeError';
|
|
32
|
+
constructor(part, bytes, limitBytes, message) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.part = part;
|
|
35
|
+
this.bytes = bytes;
|
|
36
|
+
this.limitBytes = limitBytes;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function errorCause(error) {
|
|
40
|
+
return typeof error === 'object' && error !== null && 'cause' in error
|
|
41
|
+
? error.cause
|
|
42
|
+
: undefined;
|
|
43
|
+
}
|
|
44
|
+
function errorName(error) {
|
|
45
|
+
return typeof error === 'object' && error !== null && 'name' in error
|
|
46
|
+
? error.name
|
|
47
|
+
: undefined;
|
|
48
|
+
}
|
|
49
|
+
function errorCode(error) {
|
|
50
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
51
|
+
? error.code
|
|
52
|
+
: undefined;
|
|
53
|
+
}
|
|
54
|
+
function withStage(reason, stage) {
|
|
55
|
+
return { reason, ...(stage === null ? {} : { stage }) };
|
|
56
|
+
}
|
|
57
|
+
export function classifySaveFailure(stage, error) {
|
|
58
|
+
if (error instanceof DeckTooLargeError) {
|
|
59
|
+
return {
|
|
60
|
+
...withStage('too_large', stage),
|
|
61
|
+
part: error.part,
|
|
62
|
+
bytes: error.bytes,
|
|
63
|
+
limitBytes: error.limitBytes,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (stage === 'bundle')
|
|
67
|
+
return withStage('build', stage);
|
|
68
|
+
const errors = [error, errorCause(error)];
|
|
69
|
+
if (errors.some((candidate) => {
|
|
70
|
+
const name = errorName(candidate);
|
|
71
|
+
return name === 'TimeoutError' || name === 'AbortError';
|
|
72
|
+
})) {
|
|
73
|
+
return withStage('upload_timeout', stage);
|
|
74
|
+
}
|
|
75
|
+
const networkCodes = new Set([
|
|
76
|
+
'ECONNRESET',
|
|
77
|
+
'ECONNREFUSED',
|
|
78
|
+
'ENOTFOUND',
|
|
79
|
+
'EAI_AGAIN',
|
|
80
|
+
'ETIMEDOUT',
|
|
81
|
+
'EPIPE',
|
|
82
|
+
]);
|
|
83
|
+
const fetchFailed = errors.some((candidate) => candidate instanceof TypeError && candidate.message === 'fetch failed');
|
|
84
|
+
const codedNetworkFailure = errors.some((candidate) => {
|
|
85
|
+
const code = errorCode(candidate);
|
|
86
|
+
return typeof code === 'string' && (networkCodes.has(code) || code.startsWith('UND_ERR_'));
|
|
87
|
+
});
|
|
88
|
+
if (fetchFailed || codedNetworkFailure)
|
|
89
|
+
return withStage('network', stage);
|
|
90
|
+
return withStage('unknown', stage);
|
|
91
|
+
}
|
|
92
|
+
export function saveFailedLine(failure) {
|
|
93
|
+
return (SAVE_FAILED_PREFIX +
|
|
94
|
+
JSON.stringify({
|
|
95
|
+
event: 'castle_web_save_failed',
|
|
96
|
+
reason: failure.reason,
|
|
97
|
+
...(failure.stage === undefined ? {} : { stage: failure.stage }),
|
|
98
|
+
...(failure.part === undefined ? {} : { part: failure.part }),
|
|
99
|
+
...(failure.bytes === undefined ? {} : { bytes: failure.bytes }),
|
|
100
|
+
...(failure.limitBytes === undefined ? {} : { limitBytes: failure.limitBytes }),
|
|
101
|
+
}));
|
|
102
|
+
}
|