castle-web-cli 0.4.212 → 0.4.214

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 (56) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +28 -6
  3. package/dist/agent.js +33 -2
  4. package/dist/cloudGit.d.ts +254 -0
  5. package/dist/cloudGit.js +1687 -0
  6. package/dist/cloudGitServe.d.ts +41 -0
  7. package/dist/cloudGitServe.js +318 -0
  8. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  9. package/dist/externalSourcemaps.js +2 -1
  10. package/dist/gitRemote.d.ts +4 -1
  11. package/dist/gitRemote.js +4 -2
  12. package/dist/ide.js +52 -7
  13. package/dist/index.js +149 -2
  14. package/dist/playCover/bridge.d.ts +6 -0
  15. package/dist/playCover/bridge.js +159 -0
  16. package/dist/playCover/builtins.d.ts +29 -0
  17. package/dist/playCover/builtins.js +189 -0
  18. package/dist/playCover/capture.d.ts +53 -0
  19. package/dist/playCover/capture.js +419 -0
  20. package/dist/playCover/clone.d.ts +40 -0
  21. package/dist/playCover/clone.js +317 -0
  22. package/dist/playCover/engine.d.ts +37 -0
  23. package/dist/playCover/engine.js +76 -0
  24. package/dist/playCover/errors.d.ts +6 -0
  25. package/dist/playCover/errors.js +18 -0
  26. package/dist/playCover/images.d.ts +21 -0
  27. package/dist/playCover/images.js +180 -0
  28. package/dist/playCover/instrument.d.ts +49 -0
  29. package/dist/playCover/instrument.js +334 -0
  30. package/dist/playCover/protocol.d.ts +14 -0
  31. package/dist/playCover/protocol.js +139 -0
  32. package/dist/playCover/rasterize.d.ts +21 -0
  33. package/dist/playCover/rasterize.js +408 -0
  34. package/dist/playCover/resources.d.ts +31 -0
  35. package/dist/playCover/resources.js +823 -0
  36. package/dist/playCover/scratchCanvas.d.ts +4 -0
  37. package/dist/playCover/scratchCanvas.js +16 -0
  38. package/dist/playCover/textSamples.d.ts +36 -0
  39. package/dist/playCover/textSamples.js +412 -0
  40. package/dist/playCover/validate.d.ts +79 -0
  41. package/dist/playCover/validate.js +883 -0
  42. package/dist/playCover/verify.d.ts +56 -0
  43. package/dist/playCover/verify.js +578 -0
  44. package/dist/playCover/verifyRecord.d.ts +71 -0
  45. package/dist/playCover/verifyRecord.js +243 -0
  46. package/dist/playCoverGate.d.ts +4 -0
  47. package/dist/playCoverGate.js +57 -0
  48. package/dist/playCoverPlacement.d.ts +11 -0
  49. package/dist/playCoverPlacement.js +110 -0
  50. package/dist/serve.d.ts +1 -0
  51. package/dist/serve.js +35 -17
  52. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  53. package/dist/shell/assets/{index-DzLbNBc7.js → index-BcslKMfS.js} +94 -92
  54. package/dist/shell/index.html +2 -2
  55. package/package.json +2 -2
  56. package/dist/shell/assets/index-BCrgYh76.css +0 -1
package/dist/ide.js CHANGED
@@ -28,7 +28,10 @@ import { recordParamsWrite } from './paramsWrites.js';
28
28
  import { applyDeckWrite } from './paramsTunes.js';
29
29
  import { PARAMS_DECLARATION, PARAMS_EXTS } from './paramsFile.js';
30
30
  import { applyVersionRestore, createVersion, NotOnThisLine, pendingChanges, UnsavedChanges, versionSummaries, } from './versions.js';
31
+ import { cloudGitModeAsync, EXIT_CONFLICT, gitVersionHistory } from './cloudGit.js';
32
+ import { runCastleWeb } from './cloudGitServe.js';
31
33
  import { envForUserShell, installCliShims } from './byo-auth.js';
34
+ import { playCoverOffered } from './playCoverGate.js';
32
35
  const HeadlessTerminal = headlessPkg.Terminal;
33
36
  const DIST_DIR = path.dirname(fileURLToPath(import.meta.url));
34
37
  // The bundled shell app (vite build output). `/` serves its index.html and
@@ -94,10 +97,10 @@ export function withShellAssetOrigin(html, origin) {
94
97
  return html;
95
98
  const local = (name) => `${IDE_ASSET_PREFIX}assets/${name}`;
96
99
  const isMovable = (name) => IMMUTABLE_SHELL_ASSET.test(`assets/${name}`);
97
- html = html.replace(/<script type="module" crossorigin src="\/__castle\/ide\/assets\/([^"\/]+)"><\/script>/g, (tag, name) => isMovable(name) && name.endsWith('.js')
100
+ html = html.replace(/<script type="module" crossorigin src="\/__castle\/ide\/assets\/([^"/]+)"><\/script>/g, (tag, name) => isMovable(name) && name.endsWith('.js')
98
101
  ? `<script type="module" crossorigin src="${origin}${local(name)}" onerror="var s=document.createElement('script');s.type='module';s.src='${local(name)}';document.head.appendChild(s)"></script>`
99
102
  : tag);
100
- return html.replace(/<link rel="stylesheet" crossorigin href="\/__castle\/ide\/assets\/([^"\/]+)">/g, (tag, name) => isMovable(name) && name.endsWith('.css')
103
+ return html.replace(/<link rel="stylesheet" crossorigin href="\/__castle\/ide\/assets\/([^"/]+)">/g, (tag, name) => isMovable(name) && name.endsWith('.css')
101
104
  ? `<link rel="stylesheet" crossorigin href="${origin}${local(name)}" onerror="this.onerror=null;this.href='${local(name)}'">`
102
105
  : tag);
103
106
  }
@@ -478,7 +481,13 @@ function withJsonBody(req, res, handler) {
478
481
  catch {
479
482
  return sendJson(res, 400, { error: 'Invalid JSON body.' });
480
483
  }
481
- handler(body);
484
+ try {
485
+ await handler(body);
486
+ }
487
+ catch (e) {
488
+ if (!res.headersSent)
489
+ sendJson(res, 500, { error: e instanceof Error ? e.message : String(e) });
490
+ }
482
491
  })();
483
492
  }
484
493
  // The shape every single-path mutation handler starts with: parse the body,
@@ -498,8 +507,15 @@ function sendFailure(res, action, rel, err) {
498
507
  // The version panel's three calls, on the same store the `save-version` /
499
508
  // `restore-version` commands use -- the editor is another way to run them, not
500
509
  // a second history.
501
- function handleVersionsList(deckDir, res) {
510
+ async function handleVersionsList(deckDir, res) {
502
511
  try {
512
+ if (await cloudGitModeAsync(deckDir)) {
513
+ // With git on, the history is the git log and "pending" is git status. The old
514
+ // store's versions stay listed as older versions: readable, never imported.
515
+ const { versions, pending } = await gitVersionHistory(deckDir);
516
+ const older = versionSummaries(deckDir).map((v) => ({ ...v, later: false, older: true }));
517
+ return sendJson(res, 200, { git: true, versions: [...versions, ...older], pending });
518
+ }
503
519
  // The history and what is outstanding against it, together: the panel shows
504
520
  // them as one picture, and two calls could disagree about the moment.
505
521
  sendJson(res, 200, { versions: versionSummaries(deckDir), pending: pendingChanges(deckDir) });
@@ -511,8 +527,14 @@ function handleVersionsList(deckDir, res) {
511
527
  // Saves everything dirty: the panel has no path selection, so partial saves
512
528
  // stay a CLI and agent thing.
513
529
  function handleVersionSave(deckDir, req, res) {
514
- withJsonBody(req, res, (body) => {
530
+ withJsonBody(req, res, async (body) => {
515
531
  const message = typeof body.message === 'string' ? body.message : '';
532
+ if (await cloudGitModeAsync(deckDir)) {
533
+ await gitPanelAction(res, ['commit', '--reason', 'manual', '-m', message, '--dir', deckDir], deckDir, (output) => {
534
+ sendJson(res, 200, { ok: true, id: /^Committed ([0-9a-f]{40})$/m.exec(output)?.[1] ?? null });
535
+ });
536
+ return;
537
+ }
516
538
  try {
517
539
  const { version } = createVersion(deckDir, { message });
518
540
  sendJson(res, 200, { ok: true, id: version?.id ?? null });
@@ -526,10 +548,21 @@ function handleVersionSave(deckDir, req, res) {
526
548
  // naming the files, which the panel shows -- saving a version first is the fix,
527
549
  // and it is one click away in the same panel.
528
550
  function handleVersionRestore(deckDir, req, res, restart) {
529
- withJsonBody(req, res, (body) => {
551
+ withJsonBody(req, res, async (body) => {
530
552
  if (typeof body.id !== 'string' || !body.id) {
531
553
  return sendJson(res, 400, { error: 'Missing version id.' });
532
554
  }
555
+ if (/^[0-9a-f]{7,40}$/.test(body.id) && (await cloudGitModeAsync(deckDir))) {
556
+ // A new commit restoring that tree: nothing is rewritten and pending work is committed
557
+ // first, so there is nothing to refuse over.
558
+ await gitPanelAction(res, ['restore-version', body.id, '--dir', deckDir], deckDir, (output) => {
559
+ const restored = /^Restored /m.test(output);
560
+ if (restored)
561
+ setImmediate(() => restart?.());
562
+ sendJson(res, 200, { ok: true, restored: restored ? 1 : 0, offChain: 0, alreadyThere: !restored });
563
+ });
564
+ return;
565
+ }
533
566
  try {
534
567
  const outcome = applyVersionRestore(deckDir, body.id);
535
568
  // A restore rewrites the deck wholesale, so every panel rendering it is
@@ -561,6 +594,14 @@ function handleVersionRestore(deckDir, req, res, restart) {
561
594
  }
562
595
  });
563
596
  }
597
+ // The panel's git actions run the CLI, which holds the deck's commit lock and pushes; a
598
+ // conflict still waiting on the agent is a refusal (409), anything else a fault.
599
+ async function gitPanelAction(res, args, deckDir, onSuccess) {
600
+ const { code, output } = await runCastleWeb(args, deckDir);
601
+ if (code === 0)
602
+ return onSuccess(output);
603
+ sendJson(res, code === EXIT_CONFLICT ? 409 : 500, { error: output || `castle-web ${args[0]} exited ${code}` });
604
+ }
564
605
  // `ifMatch` is optional and unchanged writes behave as they always did: a
565
606
  // client that names the text it edited gets a 409 instead of silently writing
566
607
  // over whatever landed in between, and the Parameters panel is the one that
@@ -835,6 +876,10 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate, tuneLed
835
876
  // the serve's business, not the shell's.
836
877
  hidesFiles: deckHidesFiles(deckDir),
837
878
  playSnap: playSnapEnabled(),
879
+ // The Play panel's Cover button, behind CASTLE_PLAY_COVER (playCoverGate.ts)
880
+ // -- true only when deck pages actually carry the capture bridge, so the
881
+ // shell never offers a button no deck can answer.
882
+ playCover: playCoverOffered(),
838
883
  // Formats the platform knows won't survive publishing. Sent alongside the
839
884
  // deck's own types rather than merged into them: these are not things the
840
885
  // deck understands, they are things this CLI refuses to let it ship.
@@ -926,7 +971,7 @@ function handleFilesApi(deckDir, req, res, reqPath, restart, invalidate, tuneLed
926
971
  return true;
927
972
  }
928
973
  if (action === 'versions') {
929
- handleVersionsList(deckDir, res);
974
+ void handleVersionsList(deckDir, res);
930
975
  return true;
931
976
  }
932
977
  if (action === 'save-version') {
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { listVersions, restoreVersion, saveVersion, showVersion } from './versio
17
17
  import { getKitsDir } from './localPaths.js';
18
18
  import * as api from './api.js';
19
19
  import * as config from './config.js';
20
+ import { CloudGitError } from './cloudGit.js';
20
21
  const args = process.argv.slice(2);
21
22
  const command = args[0];
22
23
  const FLAGS_WITH_VALUES = new Set([
@@ -33,6 +34,8 @@ const FLAGS_WITH_VALUES = new Set([
33
34
  '--dir',
34
35
  '--message',
35
36
  '-m',
37
+ '--reason',
38
+ '--remote',
36
39
  ]);
37
40
  // `--foo` is always a flag; a single dash only when it is one we know (`-m`).
38
41
  // Anything else starting with `-` is a positional -- a path can begin with one,
@@ -167,6 +170,9 @@ function usage() {
167
170
  castle-web restore-version <version> [--force] [--dir DIR]
168
171
  castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
169
172
  castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
173
+ castle-web git attach <dir> --remote <url> (cloud sandbox only: makes the deck a clone of its Castle repo)
174
+ castle-web git sync [--dir DIR] (cloud sandbox only: commit, merge the remote's main, push)
175
+ castle-web commit [-m MESSAGE] [--reason turn|task|leave|manual|sync] [--resolve] [paths...] [--dir DIR] (cloud sandbox only)
170
176
  castle-web login
171
177
  castle-web whoami
172
178
  castle-web --version
@@ -228,8 +234,15 @@ async function gitCommand() {
228
234
  process.stdout.write(answer.stdout);
229
235
  return;
230
236
  }
231
- if (sub !== 'init')
237
+ if (sub === 'attach' || sub === 'sync') {
238
+ await cloudGitCommand(sub);
239
+ return;
240
+ }
241
+ if (sub !== 'init') {
242
+ if (sub)
243
+ console.error(`Unknown command: git ${sub}`);
232
244
  usage();
245
+ }
233
246
  const initArgs = parseGitInitArgs();
234
247
  await gitRemote.gitInit(initArgs.dir, { environment: initArgs.staging ? 'staging' : 'production' }, {
235
248
  token: config.getToken(),
@@ -243,6 +256,131 @@ async function gitCommand() {
243
256
  warn: (message) => console.error(message),
244
257
  });
245
258
  }
259
+ // Strict parsing for the cloud git commands, which other programs call: an unknown flag or
260
+ // a flag missing its value is an error rather than a path.
261
+ function parseCloudArgs(from, valueFlags, booleanFlags = []) {
262
+ const flags = new Map();
263
+ const positionals = [];
264
+ let onlyPositionals = false;
265
+ for (let i = from; i < args.length; i++) {
266
+ const arg = args[i];
267
+ if (onlyPositionals) {
268
+ positionals.push(arg);
269
+ }
270
+ else if (arg === '--') {
271
+ onlyPositionals = true;
272
+ }
273
+ else if (valueFlags.includes(arg)) {
274
+ const value = args[++i];
275
+ if (value === undefined)
276
+ throw new Error(`${arg} needs a value.`);
277
+ flags.set(arg, value);
278
+ }
279
+ else if (booleanFlags.includes(arg)) {
280
+ flags.set(arg, 'true');
281
+ }
282
+ else if (arg.startsWith('-')) {
283
+ throw new Error(`Unknown option: ${arg}`);
284
+ }
285
+ else {
286
+ positionals.push(arg);
287
+ }
288
+ }
289
+ return { flags, positionals };
290
+ }
291
+ async function cloudGitDeps() {
292
+ const cloudGit = await import('./cloudGit.js');
293
+ return { cloudGit, deps: cloudGit.defaultCloudGitDeps(() => api.whoAmI()) };
294
+ }
295
+ function reportSync(sync, syncError) {
296
+ if (syncError)
297
+ console.error(`Not pushed yet (the next sync retries): ${syncError}`);
298
+ if (!sync)
299
+ return;
300
+ if (sync.merge === 'conflict') {
301
+ console.error('Merging the Castle remote left conflicts; the agent has been asked to resolve them.');
302
+ process.exitCode = 3;
303
+ return;
304
+ }
305
+ if (sync.merge === 'deferred') {
306
+ console.log(`${sync.pushed ? 'Pushed main. ' : ''}The remote has changes that are merged once the deck is idle.`);
307
+ return;
308
+ }
309
+ const merged = { none: '', 'fast-forward': 'Took changes from the remote. ', merged: 'Merged changes from the remote. ', seeded: '' }[sync.merge];
310
+ console.log(`${merged}${sync.pushed ? 'Pushed main.' : 'Up to date with the remote.'}`);
311
+ }
312
+ // `castle-web git attach <dir> --remote <url>` and `castle-web git sync [dir] [--dir DIR]`.
313
+ async function cloudGitCommand(sub) {
314
+ const { cloudGit, deps } = await cloudGitDeps();
315
+ const { flags, positionals } = parseCloudArgs(2, ['--remote', '--dir']);
316
+ if (sub === 'attach') {
317
+ const remote = flags.get('--remote');
318
+ const dir = positionals[0] ?? flags.get('--dir');
319
+ if (!remote || !dir || positionals.length > 1) {
320
+ throw new Error('Usage: castle-web git attach <dir> --remote <url>');
321
+ }
322
+ const outcome = await cloudGit.cloudAttach(dir, remote, deps);
323
+ console.log(`Attached ${path.resolve(dir)} to ${remote} (${outcome.repo} repo, ${outcome.outcome}).`);
324
+ if (outcome.backup)
325
+ console.log(`The cloud copy's differing files are saved in ${outcome.backup}.`);
326
+ reportSync(outcome.sync ?? null);
327
+ return;
328
+ }
329
+ if (positionals.length > 1)
330
+ throw new Error('Usage: castle-web git sync [dir] [--dir DIR]');
331
+ reportSync(await cloudGit.cloudSync(positionals[0] ?? flags.get('--dir') ?? '.', deps));
332
+ }
333
+ // `castle-web commit [-m MESSAGE] [--reason REASON] [--resolve] [paths...] [--dir DIR]`.
334
+ // --resolve concludes a conflicted merge (an agent's commit unless --reason says otherwise).
335
+ async function commitCommand() {
336
+ const { cloudGit, deps } = await cloudGitDeps();
337
+ const { flags, positionals } = parseCloudArgs(1, ['-m', '--message', '--reason', '--dir'], ['--resolve']);
338
+ const resolve = flags.has('--resolve');
339
+ const reason = flags.get('--reason') ?? (resolve ? 'task' : 'manual');
340
+ if (!cloudGit.COMMIT_REASONS.includes(reason)) {
341
+ throw new Error(`--reason must be one of ${cloudGit.COMMIT_REASONS.join(', ')}.`);
342
+ }
343
+ const outcome = await cloudGit.cloudCommit(flags.get('--dir') ?? '.', {
344
+ message: flags.get('-m') ?? flags.get('--message'),
345
+ reason: reason,
346
+ paths: positionals,
347
+ resolve,
348
+ }, deps);
349
+ console.log(outcome.sha ? `Committed ${outcome.sha}` : 'Nothing to commit.');
350
+ reportSync(outcome.sync, outcome.syncError);
351
+ }
352
+ // The version commands with git on (the serve's gate env plus an attached deck): a version
353
+ // is a commit, and the old store stops growing. A version id the old store has still goes
354
+ // there, so older versions stay readable. False when the command is the old store's.
355
+ const VERSION_COMMANDS = new Set(['save-version', 'list-versions', 'show-version', 'restore-version']);
356
+ async function gitVersionCommand(name) {
357
+ const dir = path.resolve(getFlagValue('--dir') ?? '.');
358
+ const target = readPositionals()[0];
359
+ const cloudGit = await import('./cloudGit.js');
360
+ if (!cloudGit.cloudGitMode(dir))
361
+ return false;
362
+ const store = await import('./versionStore.js');
363
+ if (target && name !== 'save-version' && store.versionExists(dir, target))
364
+ return false;
365
+ if (name === 'save-version') {
366
+ await commitCommand();
367
+ }
368
+ else if (name === 'list-versions') {
369
+ cloudGit.printGitLog(dir, target);
370
+ }
371
+ else if (name === 'show-version' && target) {
372
+ cloudGit.printGitShow(dir, target);
373
+ }
374
+ else if (name === 'restore-version' && target) {
375
+ const outcome = await cloudGit.cloudRestore(dir, target, cloudGit.defaultCloudGitDeps(() => api.whoAmI()));
376
+ console.log(outcome.sha ? `Restored ${target} as commit ${outcome.sha}` : `Already at ${target}.`);
377
+ reportSync(outcome.sync, outcome.syncError);
378
+ }
379
+ else {
380
+ return false;
381
+ }
382
+ return true;
383
+ }
246
384
  async function main() {
247
385
  // Before the switch: `--version` is a flag, not a command, and it has to work
248
386
  // when there is no command at all. Which version is installed is the first
@@ -251,6 +389,8 @@ async function main() {
251
389
  console.log(getCliVersion());
252
390
  return;
253
391
  }
392
+ if (VERSION_COMMANDS.has(command) && (await gitVersionCommand(command)))
393
+ return;
254
394
  switch (command) {
255
395
  case 'init': {
256
396
  const dir = findPositionalDir();
@@ -355,6 +495,9 @@ async function main() {
355
495
  // The version commands spend their positionals on their own arguments --
356
496
  // paths to save, a version to list from or restore to -- so the deck dir is
357
497
  // `--dir`, defaulting to the cwd.
498
+ case 'commit':
499
+ await commitCommand();
500
+ break;
358
501
  case 'save-version': {
359
502
  saveVersion(getFlagValue('--dir') ?? '.', {
360
503
  message: getFlagValue('-m') ?? getFlagValue('--message'),
@@ -437,10 +580,14 @@ async function main() {
437
580
  break;
438
581
  }
439
582
  default:
583
+ if (command)
584
+ console.error(`Unknown command: ${command}`);
440
585
  usage();
441
586
  }
442
587
  }
443
588
  main().catch((e) => {
444
589
  console.error(e instanceof Error ? e.message : String(e));
445
- process.exit(1);
590
+ // Only the cloud git commands' own errors carry an exit code (2: not enabled here, 3: a
591
+ // merge waiting on the agent); anything else is a plain failure.
592
+ process.exit(e instanceof CloudGitError ? e.exitCode : 1);
446
593
  });
@@ -0,0 +1,6 @@
1
+ declare global {
2
+ interface Window {
3
+ __castleShellOrigin?: string | null;
4
+ }
5
+ }
6
+ export {};
@@ -0,0 +1,159 @@
1
+ // The Play cover capture bridge: the script the serve injects at the top of a
2
+ // deck page's <head> when CASTLE_PLAY_COVER=on (see serve.ts). Bundled into one
3
+ // classic script at build time (vite.cover-bridge.config.ts).
4
+ //
5
+ // Inert everywhere but the editor's Play panel: it does nothing at all --
6
+ // installs no hook, listens for nothing -- unless this page is the play role
7
+ // (`?edit=0`) AND framed. There it installs the capture instrumentation before
8
+ // any deck code runs and answers exactly two messages from its parent (see
9
+ // protocol.ts), checked the same way as the serve's own readiness handler:
10
+ // the sender must be `window.parent`, and must be the shell's origin once the
11
+ // page knows it (`window.__castleShellOrigin`).
12
+ //
13
+ // Provenance: the capture mechanism is the reviewed visual-snapshot prototype
14
+ // (castle-sandboxes `scripts/visual-snapshot-prototype/serializer.js`, with its
15
+ // capture/retake/discard lifecycle from `play-mode-preview-browser.js`); the
16
+ // rasterizer is the SVG foreignObject path verified against that prototype's
17
+ // packets. Nothing here exposes the capture to the deck's own code.
18
+ // First: builtins.ts takes its copies of the built-ins before anything else runs.
19
+ import { assertBuiltinsIntact, snapshotBuiltins } from './builtins.js';
20
+ import { assertFrameUnchanged, captureNextFrame, prepareCapture, releaseActiveCapture, releaseCapture, } from './capture.js';
21
+ import { CoverCaptureError, errorCode } from './errors.js';
22
+ import { installInstrumentation } from './instrument.js';
23
+ import { runningInWebKit } from './engine.js';
24
+ import { BRIDGE_DEADLINE_MS, COVER_TARGET_SELECTOR, FRAME_TIMEOUT_MS, MAX_REQUEST_ID_LENGTH, PLAY_COVER_CANCEL, PLAY_COVER_CAPTURE, PLAY_COVER_RESULT, coverFailureSentence, } from './protocol.js';
25
+ import { rasterizePacket } from './rasterize.js';
26
+ let inflight = null;
27
+ function isPlayFrame() {
28
+ try {
29
+ if (window.parent === window)
30
+ return false;
31
+ return new URLSearchParams(location.search).get('edit') === '0';
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ function captureTarget() {
38
+ return document.querySelector(COVER_TARGET_SELECTOR) ?? document.body;
39
+ }
40
+ function reply(to, body) {
41
+ try {
42
+ window.parent.postMessage({ type: PLAY_COVER_RESULT, requestId: to.requestId, ...body }, to.replyTo);
43
+ }
44
+ catch {
45
+ /* the shell navigated away; nobody is waiting */
46
+ }
47
+ }
48
+ // `detail` is the capture's own diagnostic (which check failed, where); the
49
+ // shell never shows it, but a report or a test harness can.
50
+ function failureBody(error) {
51
+ const code = errorCode(error);
52
+ const detail = error instanceof CoverCaptureError ? error.message.slice(0, 400) : undefined;
53
+ return { ok: false, code, message: coverFailureSentence(code, runningInWebKit()), detail };
54
+ }
55
+ async function runCapture(job) {
56
+ assertBuiltinsIntact();
57
+ const session = await prepareCapture(captureTarget(), job.controller.signal, (held) => {
58
+ job.session = held;
59
+ });
60
+ try {
61
+ const packet = await captureNextFrame(session, FRAME_TIMEOUT_MS);
62
+ assertFrameUnchanged(session);
63
+ assertBuiltinsIntact();
64
+ // The packet is inert data now; the deck runs on while it is rasterized.
65
+ releaseCapture(session);
66
+ const image = await rasterizePacket(packet, job.controller.signal);
67
+ if (job.controller.signal.aborted)
68
+ throw new CoverCaptureError('CAPTURE_CANCELED', 'the capture was canceled');
69
+ assertBuiltinsIntact();
70
+ return image;
71
+ }
72
+ finally {
73
+ releaseCapture(session);
74
+ }
75
+ }
76
+ function withDeadline(job, work) {
77
+ let timer = 0;
78
+ const deadline = new Promise((_resolve, reject) => {
79
+ timer = window.setTimeout(() => {
80
+ // Only this job's own session. After a cancel the bridge is free and a
81
+ // Retake may own the active capture by now; releasing "whatever is
82
+ // active" would cancel it. A session still being prepared sees the abort
83
+ // and releases itself.
84
+ job.controller.abort();
85
+ if (job.session)
86
+ releaseCapture(job.session);
87
+ reject(new CoverCaptureError('CAPTURE_TIMEOUT', 'the capture exceeded its deadline'));
88
+ }, BRIDGE_DEADLINE_MS);
89
+ });
90
+ return Promise.race([work, deadline]).finally(() => window.clearTimeout(timer));
91
+ }
92
+ async function startCapture(requestId, replyTo) {
93
+ if (inflight) {
94
+ reply({ requestId, replyTo }, failureBody(new CoverCaptureError('CAPTURE_BUSY', 'a capture is running')));
95
+ return;
96
+ }
97
+ const job = { requestId, replyTo, controller: new AbortController(), session: null };
98
+ inflight = job;
99
+ try {
100
+ const image = await withDeadline(job, runCapture(job));
101
+ reply(job, {
102
+ ok: true,
103
+ dataUrl: image.dataUrl,
104
+ width: image.width,
105
+ height: image.height,
106
+ diagnostics: image.diagnostics,
107
+ });
108
+ }
109
+ catch (error) {
110
+ reply(job, failureBody(error));
111
+ }
112
+ finally {
113
+ if (inflight === job)
114
+ inflight = null;
115
+ }
116
+ }
117
+ // Cancel frees the bridge at once, so a Retake right after it is not refused as
118
+ // busy. Releasing here is synchronous -- the freeze and the RAF hold are gone
119
+ // before the next message is read -- and the canceled job's own later steps all
120
+ // check its aborted signal, so it cannot take the freeze again. Its eventual
121
+ // CAPTURE_CANCELED reply names its own request id, which the shell has dropped.
122
+ function cancelCapture(requestId) {
123
+ const job = inflight;
124
+ if (!job || job.requestId !== requestId)
125
+ return;
126
+ job.controller.abort();
127
+ inflight = null;
128
+ if (job.session)
129
+ releaseCapture(job.session);
130
+ }
131
+ function onMessage(event) {
132
+ if (event.source !== window.parent)
133
+ return;
134
+ const shellOrigin = window.__castleShellOrigin;
135
+ if (shellOrigin && event.origin !== shellOrigin)
136
+ return;
137
+ const data = event.data;
138
+ if (!data || typeof data !== 'object')
139
+ return;
140
+ const requestId = data.requestId;
141
+ if (typeof requestId !== 'string' || !requestId || requestId.length > MAX_REQUEST_ID_LENGTH)
142
+ return;
143
+ if (data.type === PLAY_COVER_CAPTURE)
144
+ void startCapture(requestId, event.origin);
145
+ else if (data.type === PLAY_COVER_CANCEL)
146
+ cancelCapture(requestId);
147
+ }
148
+ if (isPlayFrame()) {
149
+ installInstrumentation();
150
+ snapshotBuiltins();
151
+ window.addEventListener('message', onMessage);
152
+ // A page on its way out must not leave anything held: release on hide, and
153
+ // abandon the request -- the reply would have nobody to go to.
154
+ window.addEventListener('pagehide', () => {
155
+ inflight?.controller.abort();
156
+ inflight = null;
157
+ releaseActiveCapture();
158
+ });
159
+ }
@@ -0,0 +1,29 @@
1
+ /** The fetch the page had at load: a deck's later wrapper never sees ours. */
2
+ export declare const nativeFetch: typeof fetch;
3
+ /** String.prototype.trim as it was at load. */
4
+ export declare function trim(value: string): string;
5
+ /** A violation's fields, read through the getters captured at load. */
6
+ export declare function violationFields(event: Event): {
7
+ disposition: unknown;
8
+ effectiveDirective: unknown;
9
+ blockedURI: unknown;
10
+ } | null;
11
+ export interface ParsedUrl {
12
+ /** The URL as a CSP report names it: no fragment, no credentials. */
13
+ reported: string;
14
+ /** "https:", "data:", ... */
15
+ protocol: string;
16
+ origin: string;
17
+ }
18
+ /** Parses with the native URL, normalized the way violation reports are. */
19
+ export declare function parseReportedUrl(raw: string, base: string): ParsedUrl | null;
20
+ /** A string-keyed record with no prototype: no method a deck can replace. */
21
+ export declare function newRecord(): Record<string, true>;
22
+ /**
23
+ * Takes the watched built-ins as they are now. Called once the bridge has
24
+ * installed its own hooks (the canvas 2D wrappers are among the watched
25
+ * slots) and before any deck script runs.
26
+ */
27
+ export declare function snapshotBuiltins(): void;
28
+ /** Refuses the capture if a watched built-in was replaced since load. */
29
+ export declare function assertBuiltinsIntact(): void;