castle-web-cli 0.4.225 → 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.
@@ -20,7 +20,6 @@ export interface CastleJson {
20
20
  main?: string;
21
21
  agent?: {
22
22
  plan?: 'on' | 'off';
23
- askCalls?: 'on' | 'off';
24
23
  playtest?: 'on' | 'off';
25
24
  };
26
25
  server?: {
package/dist/get-deck.js CHANGED
@@ -110,7 +110,10 @@ export async function getDeck(dir, options = {}) {
110
110
  }
111
111
  }
112
112
  fs.mkdirSync(targetDir, { recursive: true });
113
- await runTar(['-xzf', tmpFile, '-C', targetDir]);
113
+ // --no-same-owner: an archive saved on a laptop records the laptop's uid, and tar
114
+ // run as root (a cloud sandbox) keeps it; git then refuses the deck as "dubious
115
+ // ownership" and the cloud git attach fails. Same for every unpack of a deck archive.
116
+ await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', targetDir]);
114
117
  }
115
118
  finally {
116
119
  try {
@@ -247,7 +250,7 @@ async function getDeckSide(dir, options) {
247
250
  const staging = path.join(root, `.partial-${nanoid(8)}`);
248
251
  try {
249
252
  fs.mkdirSync(staging, { recursive: true });
250
- await runTar(['-xzf', tmpFile, '-C', staging]);
253
+ await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', staging]);
251
254
  fs.rmSync(dest, { recursive: true, force: true });
252
255
  fs.renameSync(staging, dest);
253
256
  }
@@ -18,7 +18,7 @@ import * as api from './api.js';
18
18
  import * as config from './config.js';
19
19
  import { runTar } from './save-deck.js';
20
20
  import { readCastleJson } from './castleJson.js';
21
- import { ImportError, addImportTo, importedDeckIds, parseDeckRef } from './imports.js';
21
+ import { ImportError, addImportTo, importedDeckIds, resolveDeckRef as resolveImportDeckRef, } from './imports.js';
22
22
  import { errorMessage, readRequestBody, sendJson } from './httpJson.js';
23
23
  export const IMPORT_API_PREFIX = '/__castle/import/';
24
24
  // Rows per list, and how many decks we are willing to ask the source question
@@ -136,13 +136,10 @@ export async function listImportable(deckDir, tab) {
136
136
  // NOT hide a deck with no source -- naming a specific deck and getting nothing
137
137
  // back says less than naming it and being told it was never saved.
138
138
  export async function resolveDeckRef(deckDir, ref) {
139
- const deckId = parseDeckRef(ref);
139
+ const deckId = await resolveImportDeckRef(ref);
140
140
  if (!deckId) {
141
141
  throw new ImportError('bad-deck-ref', `Not a deck id or a castle deck link: ${ref}`);
142
142
  }
143
- if (readCastleJson(deckDir)?.deckId === deckId) {
144
- throw new ImportError('self-import', `That is this deck -- a deck can't import itself.`);
145
- }
146
143
  const [rows, source] = await Promise.all([
147
144
  api.deckRows([deckId]),
148
145
  api.webDeckSource(deckId).catch(() => null),
@@ -150,7 +147,11 @@ export async function resolveDeckRef(deckDir, ref) {
150
147
  const row = rows[0];
151
148
  if (!row)
152
149
  throw new ImportError('bad-deck-ref', `No deck ${deckId} on the server.`);
153
- return stampImported(deckDir, [toCandidate(row, source !== null)])[0];
150
+ if (readCastleJson(deckDir)?.deckId === row.deckId) {
151
+ throw new ImportError('self-import', `That is this deck -- a deck can't import itself.`);
152
+ }
153
+ const canonicalSource = source ?? (row.deckId !== deckId ? await api.webDeckSource(row.deckId).catch(() => null) : null);
154
+ return stampImported(deckDir, [toCandidate(row, canonicalSource !== null)])[0];
154
155
  }
155
156
  // How many files a deck's source holds. Not on any list query, so it is counted
156
157
  // from the archive itself -- which means downloading it, which is why the picker
package/dist/imports.d.ts CHANGED
@@ -6,12 +6,13 @@ export interface ImportVersion {
6
6
  }
7
7
  export declare function writeImportVersion(importDir: string, value: ImportVersion): void;
8
8
  export declare function readImportVersion(deckDir: string, alias: string): ImportVersion | null;
9
- export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'no-such-dir' | 'self-import' | 'no-source' | 'bad-alias' | 'already-imported';
9
+ export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'not-a-deck-link' | 'link-unreachable' | 'no-such-dir' | 'self-import' | 'classic-deck' | 'no-source' | 'bad-alias' | 'already-imported';
10
10
  export declare class ImportError extends Error {
11
11
  code: ImportErrorCode;
12
12
  constructor(code: ImportErrorCode, message: string);
13
13
  }
14
14
  export declare function parseDeckRef(raw: string): string | null;
15
+ export declare function resolveDeckRef(raw: string): Promise<string | null>;
15
16
  export declare function lockImportTree(dir: string): void;
16
17
  export declare function syncImportDependencies(deckDir: string): string[];
17
18
  export declare function restoreMissingImports(deckDir: string): Promise<string[]>;
package/dist/imports.js CHANGED
@@ -61,11 +61,8 @@ export class ImportError extends Error {
61
61
  this.code = code;
62
62
  }
63
63
  }
64
- // What someone has in hand is a deck id or the URL of the page they were just
65
- // looking at, so both are accepted here rather than in a separate resolve step.
66
- // Recognized: a bare id, a deck page (`castle.xyz/d/<id>`), and the cloud editor
67
- // (`castle.xyz/admin/cloud/<id>`) -- for anything else the last path segment is
68
- // tried, since every castle deck URL ends in the id.
64
+ // Share links (s.castle.xyz) go through resolveDeckRef instead: their last
65
+ // segment is a short-link id, not a deck id.
69
66
  export function parseDeckRef(raw) {
70
67
  const trimmed = raw.trim();
71
68
  if (!trimmed)
@@ -79,11 +76,69 @@ export function parseDeckRef(raw) {
79
76
  catch {
80
77
  return null;
81
78
  }
79
+ if (url.hostname.toLowerCase() === 's.castle.xyz')
80
+ return null;
82
81
  const segments = url.pathname.split('/').filter(Boolean);
83
82
  const afterD = segments.indexOf('d');
84
83
  const candidate = afterD >= 0 ? segments[afterD + 1] : segments[segments.length - 1];
85
84
  return candidate && api.isDeckIdShaped(candidate) ? candidate : null;
86
85
  }
86
+ function castleDeckPageId(raw, base) {
87
+ let url;
88
+ try {
89
+ url = base ? new URL(raw, base) : new URL(raw);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ const hostname = url.hostname.toLowerCase();
95
+ if (hostname !== 'castle.xyz' && hostname !== 'www.castle.xyz')
96
+ return null;
97
+ const segments = url.pathname.split('/').filter(Boolean);
98
+ const candidate = segments[0] === 'd' ? segments[1] : null;
99
+ return candidate && api.isDeckIdShaped(candidate) ? candidate : null;
100
+ }
101
+ function notADeckLink() {
102
+ return new ImportError('not-a-deck-link', "That share link doesn't lead to a Castle deck. Pass a deck id or a castle.xyz/d/<id> deck link.");
103
+ }
104
+ export async function resolveDeckRef(raw) {
105
+ const trimmed = raw.trim();
106
+ let url = null;
107
+ if (trimmed.includes('/')) {
108
+ try {
109
+ url = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`);
110
+ }
111
+ catch {
112
+ url = null;
113
+ }
114
+ }
115
+ if (url?.hostname.toLowerCase() !== 's.castle.xyz')
116
+ return parseDeckRef(trimmed);
117
+ if (url.pathname === '/redirect') {
118
+ const app = url.searchParams.get('app');
119
+ const deckId = app ? castleDeckPageId(app, 'https://castle.xyz') : null;
120
+ if (!deckId)
121
+ throw notADeckLink();
122
+ return deckId;
123
+ }
124
+ let response;
125
+ try {
126
+ response = await fetch(url.href, {
127
+ redirect: 'manual',
128
+ signal: AbortSignal.timeout(15000),
129
+ });
130
+ }
131
+ catch {
132
+ throw new ImportError('link-unreachable', `Could not open the share link ${trimmed} to find its deck. Pass the deck's castle.xyz/d/<id> link instead.`);
133
+ }
134
+ if (response.status < 300 || response.status >= 400)
135
+ throw notADeckLink();
136
+ const location = response.headers.get('location');
137
+ const deckId = location ? castleDeckPageId(location, url.href) : null;
138
+ if (!deckId)
139
+ throw notADeckLink();
140
+ return deckId;
141
+ }
87
142
  // Only the `imports` key is ours; everything else in castle.json (deck identity,
88
143
  // editor config) is preserved as-is.
89
144
  function writeImportPin(dir, alias, pin) {
@@ -343,7 +398,7 @@ async function fetchDeckSourceInto(archiveUrl, destDir) {
343
398
  if (!res.ok)
344
399
  throw new Error(`Archive fetch failed: HTTP ${res.status}`);
345
400
  fs.writeFileSync(tmpFile, Buffer.from(await res.arrayBuffer()));
346
- await runTar(['-xzf', tmpFile, '-C', tmpDir]);
401
+ await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', tmpDir]);
347
402
  // The new copy is whole; only now is it safe to drop the old one.
348
403
  if (fs.existsSync(destDir)) {
349
404
  unlockImportTree(destDir);
@@ -527,12 +582,25 @@ async function placeFetchedImport(targetDir, deckId, givenAlias) {
527
582
  if (readCastleJson(targetDir)?.deckId === deckId) {
528
583
  throw new ImportError('self-import', `Deck ${deckId} is this deck -- a deck can't import itself.`);
529
584
  }
530
- const [source, meta] = await Promise.all([
585
+ const [initialSource, meta] = await Promise.all([
531
586
  api.webDeckSource(deckId),
532
587
  api.deckMeta(deckId).catch(() => null),
533
588
  ]);
589
+ const canonicalDeckId = meta?.deckId ?? deckId;
590
+ if (readCastleJson(targetDir)?.deckId === canonicalDeckId) {
591
+ throw new ImportError('self-import', `Deck ${canonicalDeckId} is this deck -- a deck can't import itself.`);
592
+ }
593
+ const source = !initialSource && canonicalDeckId !== deckId
594
+ ? await api.webDeckSource(canonicalDeckId)
595
+ : initialSource;
534
596
  if (!source) {
535
- throw new ImportError('no-source', `No source archive on the server for deck ${deckId}. ` +
597
+ if (meta && meta.initialCard?.type !== 'experimentalWeb') {
598
+ const title = meta.title?.trim();
599
+ const subject = title ? `"${title}"` : `Deck ${canonicalDeckId}`;
600
+ throw new ImportError('classic-deck', `${subject} is a classic Castle deck, made in the Castle app's editor. ` +
601
+ `Only web decks built with castle-web can be imported; a classic deck's scenes can't be.`);
602
+ }
603
+ throw new ImportError('no-source', `No source archive on the server for deck ${canonicalDeckId}. ` +
536
604
  'Its owner needs to run `castle-web save-deck` before it can be imported.');
537
605
  }
538
606
  const given = givenAlias ? slugifyGivenAlias(givenAlias) : '';
@@ -541,10 +609,11 @@ async function placeFetchedImport(targetDir, deckId, givenAlias) {
541
609
  }
542
610
  // An explicit `--as` is the caller's call, collision and all. A derived one
543
611
  // gets a number instead, since nothing asked for that particular name.
544
- const alias = given || availableAlias(targetDir, qualifiedAlias(meta, deckId), deckId);
545
- const { replaced } = await placeImport(targetDir, alias, deckId, source);
612
+ const alias = given ||
613
+ availableAlias(targetDir, qualifiedAlias(meta, canonicalDeckId), canonicalDeckId);
614
+ const { replaced } = await placeImport(targetDir, alias, canonicalDeckId, source);
546
615
  const transitive = await addTransitiveImports(targetDir, alias, importedDeckIds(targetDir));
547
- return { deckId, alias, replaced, transitive };
616
+ return { deckId: canonicalDeckId, alias, replaced, transitive };
548
617
  }
549
618
  // The import itself. Throws ImportError rather than exiting, because this also
550
619
  // runs inside the serve (from the editor's Import panel), where taking the
@@ -558,10 +627,10 @@ export async function addImportTo(dir, options = {}) {
558
627
  if (!fs.existsSync(targetDir)) {
559
628
  throw new ImportError('no-such-dir', `No such directory: ${targetDir}`);
560
629
  }
561
- // Before parseDeckRef: a kit's name is id-shaped, so the other order would
630
+ // Before resolveDeckRef: a kit's name is id-shaped, so the other order would
562
631
  // send `physics-2d` to the server as a deck id.
563
632
  const kit = shippedFrameworkKit(ref);
564
- const deckId = kit ? null : parseDeckRef(ref);
633
+ const deckId = kit ? null : await resolveDeckRef(ref);
565
634
  let placed;
566
635
  if (kit) {
567
636
  placed = await placeShippedKit(targetDir, kit, options.alias);
package/dist/init.js CHANGED
@@ -19,10 +19,13 @@ const DEFAULT_KIT = 'physics-2d';
19
19
  // A framework kit imports it too, so a kit deck has it as well.
20
20
  export const BASE_KIT = 'base';
21
21
  export const BASE_ALIAS = shippedKitAlias(BASE_KIT);
22
+ // A bare deck lays itself out, so it starts as a fill deck (platformDoc.ts,
23
+ // "Fit the stage"); a kit deck's entry is the kit's, and follows its guide.
22
24
  const INDEX_HTML = `<!DOCTYPE html>
23
25
  <html>
24
26
  <head>
25
27
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
28
+ <meta name="castle-display" content="layout=fill">
26
29
  <title>My Castle Game</title>
27
30
  </head>
28
31
  <body>
@@ -40,7 +43,7 @@ function startGame(card) {
40
43
  el.style.cssText = \`
41
44
  width: 100%; height: 100%;
42
45
  display: flex; align-items: center; justify-content: center;
43
- font-family: system-ui; color: #fff; font-size: 24px;
46
+ font-family: system-ui; color: #fff; font-size: calc(6 * var(--castle-unit));
44
47
  \`;
45
48
  el.textContent = 'Hello Castle!';
46
49
  card.appendChild(el);
@@ -51,10 +54,19 @@ function startGame(card) {
51
54
  // takes the false branch on the first line and loads none of it.
52
55
  if (!(await mountEditorRoute())) startGame(initCard());
53
56
  `;
57
+ // Every bare scaffold `init` has written, so isPristineBareDeck still knows an
58
+ // untouched deck made before the scaffold became a fill deck.
59
+ const BARE_SCAFFOLDS = [
60
+ { html: INDEX_HTML, js: GAME_JS },
61
+ {
62
+ html: INDEX_HTML.replace(' <meta name="castle-display" content="layout=fill">\n', ''),
63
+ js: GAME_JS.replace('calc(6 * var(--castle-unit))', '24px'),
64
+ },
65
+ ];
54
66
  // Registry version of castle-web-sdk to inject when scaffolding from a
55
67
  // globally-installed castle-web (not from inside the workspace). Bumped
56
68
  // alongside cli/sdk version bumps.
57
- const PUBLISHED_SDK_VERSION = '0.4.42';
69
+ const PUBLISHED_SDK_VERSION = '0.4.44';
58
70
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
59
71
  // face can ship without a cli release, and a caret range means an existing
60
72
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -180,8 +192,9 @@ export function ensureAgentsSymlink(projectDir) {
180
192
  // has actually worked in is never quietly taken over.
181
193
  export function isPristineBareDeck(dir) {
182
194
  try {
183
- return (fs.readFileSync(path.join(dir, 'index.html'), 'utf8') === INDEX_HTML &&
184
- fs.readFileSync(path.join(dir, 'game.js'), 'utf8') === GAME_JS);
195
+ const html = fs.readFileSync(path.join(dir, 'index.html'), 'utf8');
196
+ const js = fs.readFileSync(path.join(dir, 'game.js'), 'utf8');
197
+ return BARE_SCAFFOLDS.some((stub) => stub.html === html && stub.js === js);
185
198
  }
186
199
  catch {
187
200
  return false;
@@ -3,6 +3,7 @@ export declare const PLATFORM_DOC_REL: string;
3
3
  export declare const MULTIPLAYER_DOC_REL: string;
4
4
  export declare function everyDeckBullets(deckDir: string): string[];
5
5
  export declare const HOST_LIMIT_BULLETS: string[];
6
+ export declare const CASTLE_UI_BULLETS: string[];
6
7
  export type AgentRole = 'router' | 'task';
7
8
  export declare function roleLoadsClaudeMd(role: AgentRole): boolean;
8
9
  export declare function claudeContextEnv(role: AgentRole): NodeJS.ProcessEnv;
@@ -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 sets no CSP, so a remote URL that works there fails once published. Bundle the file, or let the player pick one with `<input type=\"file\">`.",
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 host limits, so they
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
- const hostLimits = HOST_LIMIT_BULLETS.join('\n');
122
- if (own.includes(RESTATEMENT_MARKER))
123
- return `${own}\n\n${hostLimits}`;
124
- const bullets = [...everyDeckBullets(deckDir), ...HOST_LIMIT_BULLETS].join('\n');
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 card
235
+ ## Fit the stage
223
236
 
224
- - **The deck plays inside a fixed 5:7 portrait card, not the full window.** The card is sized to fit the screen (at most about 450x630px), clips overflow, and does not scroll. Design the whole layout to fit inside that portrait box: size UI relative to the card with percentages, flex/grid, \`min()\`, \`clamp()\`, or viewport-relative units instead of fixed tall panels. Let playfields scale down on smaller cards rather than overflowing; anything outside the card edges is cut off. The SDK exports \`CARD_RATIO\` (= 5 / 7) if you need the exact ratio.
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')}
@@ -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
@@ -1,5 +1,6 @@
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 ";
@@ -9,7 +10,10 @@ export declare function runTar(args: string[], opts?: {
9
10
  }): Promise<string>;
10
11
  export declare function archiveSource(projectDir: string): Promise<Buffer>;
11
12
  export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string, log?: (line: string) => void): Promise<string>;
12
- export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null): Promise<api.WebDeckSource>;
13
+ export declare function packSourceForSave(projectDir: string, castleJson: string | null, { published }?: {
14
+ published?: boolean;
15
+ }): Promise<Buffer>;
16
+ export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null, archive?: Buffer): Promise<api.WebDeckSource>;
13
17
  export declare function checkSavePrecondition(projectDir: string, deckId: string, force: boolean): Promise<SavePrecondition>;
14
18
  export type SaveVisibility = 'unlisted' | 'private';
15
19
  export interface SaveDeckOptions {