@artis-lab/cli 0.8.0 → 0.10.0

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/README.md CHANGED
@@ -54,6 +54,20 @@ artis annotate artifact-slug --comment "Tighten this heading" --quote "Checkout
54
54
  artis reply annotation-123 --comment "Fixed in revision 2."
55
55
  ```
56
56
 
57
+ ## Check a page before publishing
58
+
59
+ ```bash
60
+ artis verify artifact.html # or a published artifact: artis verify artifact-slug
61
+ ```
62
+
63
+ `verify` renders the page in your system Chrome (or Edge) at 1280 and 390 px
64
+ in light and dark themes, served with the same Content-Security-Policy as
65
+ Artis, and reports horizontal overflow, clipped SVG, console errors and CSP
66
+ violations. It exits 8 when it finds any. It needs the optional
67
+ `playwright-core` dependency (installed with the CLI by default, about
68
+ 10 MB and no browser binaries) and a
69
+ Chromium-based browser; set `ARTIS_CHROME_PATH` to use a specific one.
70
+
57
71
  Run `artis help` for the full command and flag reference.
58
72
 
59
73
  ## Install the agent skill
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@artis-lab/cli",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Agent-first CLI for publishing, reviewing, and revising self-contained HTML artifacts on an Artis server.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -45,6 +45,9 @@
45
45
  "dependencies": {
46
46
  "tslib": "^2.3.0"
47
47
  },
48
+ "optionalDependencies": {
49
+ "playwright-core": "^1.64.1"
50
+ },
48
51
  "devDependencies": {
49
52
  "@artis/sdk": "0.0.1"
50
53
  },
package/src/bin.js CHANGED
@@ -3,8 +3,14 @@
3
3
  // symlink, so `import.meta.url` (realpath) never equals `process.argv[1]` (the
4
4
  // symlink) and any main-module guard here would silently do nothing.
5
5
  import { runArtisCli } from './lib/cli.js';
6
+ import { exitCodeFor } from './lib/exit-codes.js';
6
7
  runArtisCli().catch((error) => {
7
- console.error(error instanceof Error ? error.message : String(error));
8
- process.exitCode = 1;
8
+ const message = error instanceof Error ? error.message : String(error);
9
+ // An outcome already reported on stdout (verify's findings) carries no
10
+ // message; only the exit code is left to set.
11
+ if (message) {
12
+ console.error(message);
13
+ }
14
+ process.exitCode = exitCodeFor(error);
9
15
  });
10
16
  //# sourceMappingURL=bin.js.map
package/src/lib/cli.d.ts CHANGED
@@ -2,7 +2,7 @@ import { installSkillFromCli } from './skill-install.js';
2
2
  import { artisCliVersion } from './version.js';
3
3
  export { artisCliVersion };
4
4
  export { installSkillFromCli };
5
- export declare const commands: readonly ["annotate", "annotation", "artifact", "guidelines", "help", "install-skill", "login", "publish", "reply", "revise", "share", "version", "whoami"];
5
+ export declare const commands: readonly ["annotate", "annotation", "artifact", "guidelines", "help", "install-skill", "login", "publish", "reply", "revise", "share", "version", "watch", "whoami"];
6
6
  export type ArtisCommand = (typeof commands)[number];
7
7
  /**
8
8
  * Mirrors the sdk's `ArtifactVisibility`, deliberately re-declared instead of
@@ -47,6 +47,18 @@ export declare function getArtifactFromCli(args: string[]): Promise<void>;
47
47
  * `artis artifact html <id> --output report.html`, edit, then `artis revise`.
48
48
  */
49
49
  export declare function getArtifactHtmlFromCli(args: string[]): Promise<void>;
50
+ /**
51
+ * Render a local HTML file, or a published artifact's stored HTML, in the
52
+ * system Chrome at 1280 and 390 px in light and dark themes, and report
53
+ * horizontal overflow, clipped SVG, console errors and CSP violations.
54
+ * Exits 8 when it finds any.
55
+ */
56
+ export declare function verifyFromCli(args: string[]): Promise<void>;
57
+ /**
58
+ * List your own artifacts, newest first, optionally searched by title and
59
+ * description and filtered by kind and tag.
60
+ */
61
+ export declare function listArtifactsFromCli(args: string[]): Promise<void>;
50
62
  export declare function getArtifactFeedbackFromCli(args: string[]): Promise<void>;
51
63
  export declare function shareArtifactFromCli(args: string[]): Promise<void>;
52
64
  export declare function reviseArtifactFromCli(args: string[]): Promise<void>;
@@ -54,4 +66,12 @@ export declare function createAnnotationFromCli(args: string[]): Promise<void>;
54
66
  export declare function replyFromCli(args: string[]): Promise<void>;
55
67
  export declare function editAnnotationFromCli(args: string[]): Promise<void>;
56
68
  export declare function retractAnnotationFromCli(args: string[]): Promise<void>;
69
+ /**
70
+ * Wait for annotation events on one artifact caused by anyone but this API
71
+ * key, by long-polling `GET /api/artifacts/:id/events` from a feedback
72
+ * cursor. Streams one JSON line per event until stopped; `--once` prints the
73
+ * first batch as `{events, cursor}` and exits 0. Network drops and rate
74
+ * limits are retried from the last cursor, so no event is lost or repeated.
75
+ */
76
+ export declare function watchArtifactFromCli(args: string[]): Promise<void>;
57
77
  export declare function runArtisCli(args?: string[]): Promise<void>;
package/src/lib/cli.js CHANGED
@@ -9,6 +9,24 @@ function annotationIdFromIri(iri) {
9
9
  var _a;
10
10
  return (_a = iri.replace(/\/+$/, '').split('/').pop()) !== null && _a !== void 0 ? _a : iri;
11
11
  }
12
+ // Mirrors the sdk's formatRevisionConflictMessage.
13
+ function formatRevisionConflictMessage(message, details) {
14
+ var _a;
15
+ if (!(details === null || details === void 0 ? void 0 : details.currentRevisionId)) {
16
+ return message;
17
+ }
18
+ let text = `${message} Current revision: ${details.currentRevisionId}.`;
19
+ if (typeof details.currentVersion === 'number') {
20
+ const firstLine = ((_a = details.currentSummary) !== null && _a !== void 0 ? _a : '')
21
+ .split(/\r?\n/)
22
+ .map((line) => line.replace(/^\s*(?:[-*•]\s+)?/, '').trim())
23
+ .find(Boolean);
24
+ text += firstLine
25
+ ? ` Version ${details.currentVersion}: ${firstLine}`
26
+ : ` Version ${details.currentVersion}.`;
27
+ }
28
+ return text;
29
+ }
12
30
  function isRootAnnotation(annotation) {
13
31
  return annotation.motivation === 'commenting';
14
32
  }
@@ -17,6 +35,8 @@ import { getRememberedBase, rememberBase } from './revision-bases.js';
17
35
  import { installSkillFromCli } from './skill-install.js';
18
36
  import { artisCliVersion } from './version.js';
19
37
  import { collectFlagValues, hasFlag, parseFlagValue } from './args.js';
38
+ import { formatVerifyReport, verifyHtml, VerifyUnavailableError, } from './verify.js';
39
+ import { CliError, exitCodeForResponse, exitCodes, usageError, } from './exit-codes.js';
20
40
  export { artisCliVersion };
21
41
  export { installSkillFromCli };
22
42
  export const commands = [
@@ -32,6 +52,7 @@ export const commands = [
32
52
  'revise',
33
53
  'share',
34
54
  'version',
55
+ 'watch',
35
56
  'whoami',
36
57
  ];
37
58
  /**
@@ -77,16 +98,20 @@ const valueFlags = new Set([
77
98
  '--quote',
78
99
  '--quote-prefix',
79
100
  '--quote-suffix',
101
+ '--query',
80
102
  '--rect',
81
103
  '--requested-change',
82
104
  '--resolve',
83
105
  '--revision',
84
106
  '--role',
107
+ '--since',
85
108
  '--status',
86
109
  '--base',
87
110
  '--summary',
111
+ '--tag',
88
112
  '--text-end',
89
113
  '--text-start',
114
+ '--timeout',
90
115
  '--title',
91
116
  '--url',
92
117
  '--visibility',
@@ -114,25 +139,25 @@ function parseVisibility(value) {
114
139
  if (cliVisibilityOptions.includes(value)) {
115
140
  return value;
116
141
  }
117
- throw new Error(`Invalid visibility "${value}". Expected one of: ${cliVisibilityOptions.join(', ')}`);
142
+ throw usageError(`Invalid visibility "${value}". Expected one of: ${cliVisibilityOptions.join(', ')}`);
118
143
  }
119
144
  function parseKind(value) {
120
145
  if (cliArtifactKinds.includes(value)) {
121
146
  return value;
122
147
  }
123
- throw new Error(`Invalid kind "${value}". Expected one of: ${cliArtifactKinds.join(', ')}`);
148
+ throw usageError(`Invalid kind "${value}". Expected one of: ${cliArtifactKinds.join(', ')}`);
124
149
  }
125
150
  function parseAnnotationStatus(value) {
126
151
  if (cliAnnotationStatusOptions.includes(value)) {
127
152
  return value;
128
153
  }
129
- throw new Error(`Invalid status "${value}". Expected one of: ${cliAnnotationStatusOptions.join(', ')}`);
154
+ throw usageError(`Invalid status "${value}". Expected one of: ${cliAnnotationStatusOptions.join(', ')}`);
130
155
  }
131
156
  function parseShareRole(value) {
132
157
  if (cliShareRoleOptions.includes(value)) {
133
158
  return value;
134
159
  }
135
- throw new Error(`Invalid role "${value}". Expected one of: ${cliShareRoleOptions.join(', ')}`);
160
+ throw usageError(`Invalid role "${value}". Expected one of: ${cliShareRoleOptions.join(', ')}`);
136
161
  }
137
162
  /** Parse a `--rect x,y,w,h` percentage tuple into a Media Fragments
138
163
  * `xywh=percent:` FragmentSelector. Width/height default to 0 (a point pin). */
@@ -143,7 +168,7 @@ function parseRectSelector(value) {
143
168
  const parts = value.split(',').map((part) => Number(part.trim()));
144
169
  if ((parts.length !== 2 && parts.length !== 4) ||
145
170
  parts.some((part) => !Number.isFinite(part))) {
146
- throw new Error(`Invalid --rect "${value}". Expected "x,y" or "x,y,w,h" percentages.`);
171
+ throw usageError(`Invalid --rect "${value}". Expected "x,y" or "x,y,w,h" percentages.`);
147
172
  }
148
173
  const [x, y, width = 0, height = 0] = parts;
149
174
  return {
@@ -179,7 +204,7 @@ function buildAnnotationSelectors(args) {
179
204
  const start = Number(textStart);
180
205
  const end = Number(textEnd);
181
206
  if (!Number.isFinite(start) || !Number.isFinite(end)) {
182
- throw new Error('--text-start and --text-end must be numbers.');
207
+ throw usageError('--text-start and --text-end must be numbers.');
183
208
  }
184
209
  selectors.push({ type: 'TextPositionSelector', start, end });
185
210
  }
@@ -225,7 +250,7 @@ function resolveCredentials(args) {
225
250
  const baseUrl = resolveBaseUrl(args, config);
226
251
  const { apiKey } = resolveApiKey(args, config, baseUrl);
227
252
  if (!apiKey) {
228
- throw new Error(`Missing API key. Run "artis login --host ${baseUrl}" or set ARTIS_API_KEY.`);
253
+ throw new CliError(`Missing API key. Run "artis login --host ${baseUrl}" or set ARTIS_API_KEY.`, exitCodes.auth);
229
254
  }
230
255
  return { apiKey, baseUrl };
231
256
  });
@@ -251,7 +276,7 @@ export function guidelinesFromCli(args) {
251
276
  const response = yield fetch(`${baseUrl}/skills.md?section=${encodeURIComponent(section !== null && section !== void 0 ? section : 'index')}`);
252
277
  const text = yield response.text();
253
278
  if (!response.ok) {
254
- throw new Error(text.trim() || `Guidelines request failed with ${response.status}.`);
279
+ throw new CliError(text.trim() || `Guidelines request failed with ${response.status}.`, exitCodeForResponse(response.status));
255
280
  }
256
281
  process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
257
282
  });
@@ -261,7 +286,7 @@ function parsePublishOptions(args) {
261
286
  var _a, _b, _c, _d;
262
287
  const [filePath] = getPositionals(args);
263
288
  if (!filePath) {
264
- throw new Error('Missing artifact HTML file path.');
289
+ throw usageError('Missing artifact HTML file path.');
265
290
  }
266
291
  const credentials = yield resolveCredentials(args);
267
292
  const visibility = parseVisibility((_a = parseFlagValue(args, '--visibility')) !== null && _a !== void 0 ? _a : 'unlisted');
@@ -291,9 +316,7 @@ function apiFetch(credentials_1, path_1) {
291
316
  if (!response.ok) {
292
317
  const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Request failed with ${response.status}.`;
293
318
  // A revise conflict is only recoverable with the current revision id.
294
- throw new Error((payload === null || payload === void 0 ? void 0 : payload.currentRevisionId)
295
- ? `${message} Current revision: ${payload.currentRevisionId}.`
296
- : message);
319
+ throw new CliError(formatRevisionConflictMessage(message, payload), exitCodeForResponse(response.status, payload === null || payload === void 0 ? void 0 : payload.code));
297
320
  }
298
321
  return payload;
299
322
  });
@@ -319,7 +342,7 @@ function apiFetchOptional(target_1, path_1) {
319
342
  status = retryResponse.status;
320
343
  }
321
344
  if (status < 200 || status >= 300) {
322
- throw new Error((_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Request failed with ${status}.`);
345
+ throw new CliError((_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Request failed with ${status}.`, exitCodeForResponse(status, payload === null || payload === void 0 ? void 0 : payload.code));
323
346
  }
324
347
  return payload;
325
348
  });
@@ -399,12 +422,15 @@ Usage:
399
422
  artis artifact get <artifact-id-or-slug> [--json]
400
423
  artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>] [--json]
401
424
  artis artifact feedback <artifact-id-or-slug> [--json] [--revision <revision-id>]
425
+ artis artifact list [--query <text>] [--kind <value>] [--tag <tag>] [--json]
426
+ artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]
402
427
  artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter>] [--remove]
403
428
  artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>] [--resolve <annotation-id>]
404
429
  artis annotate <artifact-id-or-slug> --comment <text> [anchor options]
405
430
  artis reply <annotation-id> --comment <text>
406
431
  artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]
407
432
  artis annotation retract <annotation-id>
433
+ artis watch <artifact-id-or-slug> [--since <cursor>] [--once] [--timeout <duration>] [--include-self]
408
434
 
409
435
  Options:
410
436
  --api-key <key> API key. Defaults to ARTIS_API_KEY or ~/.artis/config.json. Run "artis login" to obtain one.
@@ -430,6 +456,8 @@ Options:
430
456
  --pin-label <text> Short label shown on the artifact canvas pin (annotate).
431
457
  --output <path> Write the artifact HTML to this file (artifact html). Without it, the document goes to stdout.
432
458
  --revision <revision-id> Revision to read (artifact html, artifact feedback). Defaults to the current revision.
459
+ --query <text> Text to find in your artifacts' titles and descriptions (artifact list).
460
+ --tag <tag> Only your artifacts carrying this tag (artifact list). --kind filters by kind.
433
461
  --email <email> Email address for artis share.
434
462
  --role <role> Share role: viewer or commenter. Defaults to viewer.
435
463
  --remove Remove the email from an artifact share list.
@@ -438,8 +466,15 @@ Options:
438
466
  --dir <path> Install the skill into a custom skills directory (install-skill).
439
467
  --force Overwrite an already-installed skill (install-skill).
440
468
  --list List harnesses, detection, and install paths (install-skill).
469
+ --since <cursor> Feedback cursor to watch from (watch). Defaults to now; 0 replays every event.
470
+ --once Exit after the first batch of events, printed as {events, cursor} (watch).
471
+ --timeout <duration> Give up after this long, e.g. 30s, 10m (watch). Exits 6 if nothing happened.
472
+ --include-self Also report events caused by this API key (watch).
441
473
  --json Print machine-readable JSON for supported commands.
442
474
 
475
+ Exit codes:
476
+ 0 success, 1 error, 2 usage, 3 auth, 4 not found, 5 revision conflict, 6 watch timeout, 7 rate limited, 8 verify found problems.
477
+
443
478
  Examples (--host is optional; without it commands target https://artis.xiispace.eu.org):
444
479
  artis publish report.html
445
480
  artis login
@@ -447,11 +482,13 @@ Examples (--host is optional; without it commands target https://artis.xiispace.
447
482
  artis share artifact-slug --host https://artis.example.com --email reviewer@example.com --role commenter
448
483
  artis artifact get artifact-slug --host https://artis.example.com --json
449
484
  artis artifact html artifact-slug --output report.html
485
+ artis verify report.html
450
486
  artis artifact feedback artifact-slug --host https://artis.example.com --json
451
487
  artis annotate artifact-slug --host https://artis.example.com --comment "Tighten this heading" --quote "Checkout latency" --requested-change "Add the affected checkout count"
452
488
  artis reply annotation-123 --host https://artis.example.com --comment "Addressed in the latest revision"
453
489
  artis annotation edit annotation-123 --host https://artis.example.com --comment "Corrected: the latency spike is on checkout, not search"
454
490
  artis annotation retract annotation-123 --host https://artis.example.com
491
+ artis watch artifact-slug --since 42
455
492
  artis guidelines authoring
456
493
  artis install-skill --yes
457
494
  artis revise artifact-slug report.html --host https://artis.example.com --summary "Addressed open feedback" --base revision-abc --resolve annotation-123`;
@@ -505,7 +542,7 @@ export function loginFromCli(args) {
505
542
  !login.userCode ||
506
543
  !login.verificationUrl ||
507
544
  !login.expiresAt) {
508
- throw new Error((_a = login === null || login === void 0 ? void 0 : login.error) !== null && _a !== void 0 ? _a : `Login failed with ${response.status}.`);
545
+ throw new CliError((_a = login === null || login === void 0 ? void 0 : login.error) !== null && _a !== void 0 ? _a : `Login failed with ${response.status}.`, exitCodeForResponse(response.status));
509
546
  }
510
547
  // Validate the host-controlled verification URL before opening a browser.
511
548
  // A non-default or compromised host could otherwise return a crafted URL
@@ -559,7 +596,7 @@ export function getArtifactFromCli(args) {
559
596
  var _a;
560
597
  const [artifactId] = getPositionals(args);
561
598
  if (!artifactId) {
562
- throw new Error('Missing artifact id or slug.');
599
+ throw usageError('Missing artifact id or slug.');
563
600
  }
564
601
  const target = yield resolveOptionalTarget(args);
565
602
  const result = yield apiFetchOptional(target, `/api/artifacts/${encodeURIComponent(artifactId)}`);
@@ -585,7 +622,7 @@ export function getArtifactHtmlFromCli(args) {
585
622
  return __awaiter(this, void 0, void 0, function* () {
586
623
  const [artifactId] = getPositionals(args);
587
624
  if (!artifactId) {
588
- throw new Error('Usage: artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>]');
625
+ throw usageError('Usage: artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>]');
589
626
  }
590
627
  const target = yield resolveOptionalTarget(args);
591
628
  const revisionId = parseFlagValue(args, '--revision');
@@ -598,6 +635,11 @@ export function getArtifactHtmlFromCli(args) {
598
635
  if (result === null || result === void 0 ? void 0 : result.revisionId) {
599
636
  yield rememberBase(target.baseUrl, [artifactId, result.artifactId], result.revisionId);
600
637
  }
638
+ // Stderr, so piped HTML or JSON on stdout is unaffected. Strictly false:
639
+ // an older server omits the field and must not trigger the hint.
640
+ if ((result === null || result === void 0 ? void 0 : result.isLatest) === false) {
641
+ console.error(`Note: version ${result.version} is not the latest. The latest is version ${result.latestVersion} (revision ${result.latestRevisionId}); a revise based on this one will be refused.`);
642
+ }
601
643
  if (hasFlag(args, '--json')) {
602
644
  console.log(JSON.stringify(result, null, 2));
603
645
  return;
@@ -618,11 +660,118 @@ export function getArtifactHtmlFromCli(args) {
618
660
  console.log(`Version: ${result.version}`);
619
661
  });
620
662
  }
663
+ /**
664
+ * Render a local HTML file, or a published artifact's stored HTML, in the
665
+ * system Chrome at 1280 and 390 px in light and dark themes, and report
666
+ * horizontal overflow, clipped SVG, console errors and CSP violations.
667
+ * Exits 8 when it finds any.
668
+ */
669
+ export function verifyFromCli(args) {
670
+ return __awaiter(this, void 0, void 0, function* () {
671
+ const [target] = getPositionals(args);
672
+ if (!target) {
673
+ throw usageError('Usage: artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]');
674
+ }
675
+ // Anything that looks like a path (a separator, or an .html/.htm name) is
676
+ // a local file, and a missing one is reported as such rather than sent to
677
+ // the API as an artifact id. A bare name that exists on disk is a file
678
+ // too; any other bare name is an artifact id or slug.
679
+ let html;
680
+ let label;
681
+ const looksLikePath = /[\\/]/.test(target) || /\.html?$/i.test(target);
682
+ const local = yield readFile(target, 'utf8').catch((error) => error);
683
+ if (typeof local === 'string' || looksLikePath) {
684
+ if (typeof local !== 'string') {
685
+ throw local.code === 'ENOENT'
686
+ ? new CliError(`File not found: ${target}`, exitCodes.notFound)
687
+ : usageError(`Cannot read ${target}: ${local.message}`);
688
+ }
689
+ if (parseFlagValue(args, '--revision')) {
690
+ throw usageError('--revision applies to a published artifact, not a local file.');
691
+ }
692
+ html = local;
693
+ label = target;
694
+ }
695
+ else {
696
+ const remote = yield resolveOptionalTarget(args);
697
+ const revisionId = parseFlagValue(args, '--revision');
698
+ const query = revisionId
699
+ ? `?revisionId=${encodeURIComponent(revisionId)}`
700
+ : '';
701
+ const result = yield apiFetchOptional(remote, `/api/artifacts/${encodeURIComponent(target)}/html${query}`);
702
+ if (!(result === null || result === void 0 ? void 0 : result.html)) {
703
+ throw new Error('Artifact response did not include revision HTML.');
704
+ }
705
+ html = result.html;
706
+ label = `${target} v${result.version}`;
707
+ }
708
+ let report;
709
+ try {
710
+ report = yield verifyHtml(html);
711
+ }
712
+ catch (error) {
713
+ if (error instanceof VerifyUnavailableError) {
714
+ throw new CliError(error.message, exitCodes.error);
715
+ }
716
+ throw error;
717
+ }
718
+ if (hasFlag(args, '--json')) {
719
+ console.log(JSON.stringify(report, null, 2));
720
+ }
721
+ else {
722
+ console.log(`Verified ${label}`);
723
+ for (const line of formatVerifyReport(report)) {
724
+ console.log(line);
725
+ }
726
+ }
727
+ if (!report.ok) {
728
+ throw new CliError('', exitCodes.verifyFailed);
729
+ }
730
+ });
731
+ }
732
+ /**
733
+ * List your own artifacts, newest first, optionally searched by title and
734
+ * description and filtered by kind and tag.
735
+ */
736
+ export function listArtifactsFromCli(args) {
737
+ return __awaiter(this, void 0, void 0, function* () {
738
+ var _a, _b;
739
+ const credentials = yield resolveCredentials(args);
740
+ const params = new URLSearchParams({ owner: 'me' });
741
+ const query = parseFlagValue(args, '--query');
742
+ const kind = parseFlagValue(args, '--kind');
743
+ const tag = parseFlagValue(args, '--tag');
744
+ if (query)
745
+ params.set('q', query);
746
+ if (kind)
747
+ params.set('kind', parseKind(kind));
748
+ if (tag)
749
+ params.set('tag', tag);
750
+ const result = yield apiFetch(credentials, `/api/artifacts?${params}`);
751
+ if (hasFlag(args, '--json')) {
752
+ console.log(JSON.stringify(result, null, 2));
753
+ return;
754
+ }
755
+ const artifacts = (_a = result === null || result === void 0 ? void 0 : result.artifacts) !== null && _a !== void 0 ? _a : [];
756
+ if (!artifacts.length) {
757
+ console.log(query || kind || tag
758
+ ? 'No artifacts match.'
759
+ : 'You have no artifacts yet.');
760
+ return;
761
+ }
762
+ for (const artifact of artifacts) {
763
+ const tags = ((_b = artifact.metadata.tags) === null || _b === void 0 ? void 0 : _b.length)
764
+ ? ` #${artifact.metadata.tags.join(' #')}`
765
+ : '';
766
+ console.log(`${artifact.slug} ${artifact.metadata.visibility} ${artifact.metadata.kind} ${artifact.metadata.title}${tags}`);
767
+ }
768
+ });
769
+ }
621
770
  export function getArtifactFeedbackFromCli(args) {
622
771
  return __awaiter(this, void 0, void 0, function* () {
623
772
  const [artifactId] = getPositionals(args);
624
773
  if (!artifactId) {
625
- throw new Error('Missing artifact id or slug.');
774
+ throw usageError('Missing artifact id or slug.');
626
775
  }
627
776
  const target = yield resolveOptionalTarget(args);
628
777
  const revisionId = parseFlagValue(args, '--revision');
@@ -638,6 +787,9 @@ export function getArtifactFeedbackFromCli(args) {
638
787
  throw new Error('Feedback response did not include a prompt.');
639
788
  }
640
789
  console.log(result.prompt);
790
+ if (result.cursor !== undefined) {
791
+ console.log(`\nFeedback cursor: ${result.cursor} (artis watch ${artifactId} --since ${result.cursor})`);
792
+ }
641
793
  });
642
794
  }
643
795
  export function shareArtifactFromCli(args) {
@@ -645,7 +797,7 @@ export function shareArtifactFromCli(args) {
645
797
  var _a, _b, _c;
646
798
  const [artifactId] = getPositionals(args);
647
799
  if (!artifactId) {
648
- throw new Error('Usage: artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter>] [--remove]');
800
+ throw usageError('Usage: artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter>] [--remove]');
649
801
  }
650
802
  const email = (_a = parseFlagValue(args, '--email')) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
651
803
  const credentials = yield resolveCredentials(args);
@@ -691,14 +843,14 @@ export function shareArtifactFromCli(args) {
691
843
  }
692
844
  export function reviseArtifactFromCli(args) {
693
845
  return __awaiter(this, void 0, void 0, function* () {
694
- var _a;
846
+ var _a, _b;
695
847
  const [artifactId, filePath] = getPositionals(args);
696
848
  const summary = parseFlagValue(args, '--summary');
697
849
  if (!artifactId || !filePath) {
698
- throw new Error('Usage: artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>]');
850
+ throw usageError('Usage: artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>]');
699
851
  }
700
852
  if (!summary) {
701
- throw new Error('Missing --summary for revision.');
853
+ throw usageError('Missing --summary for revision.');
702
854
  }
703
855
  const credentials = yield resolveCredentials(args);
704
856
  const html = yield readFile(filePath, 'utf8');
@@ -730,6 +882,18 @@ export function reviseArtifactFromCli(args) {
730
882
  }
731
883
  console.log(`Revision ${result.revision.id}`);
732
884
  console.log(`Version ${result.revision.version}`);
885
+ // The anchored text of these is gone: the agent should check whether the
886
+ // feedback was addressed or the text was lost by accident.
887
+ const orphaned = (_b = result.orphanedAnnotationIds) !== null && _b !== void 0 ? _b : [];
888
+ if (result.anchorStatusComputed === false) {
889
+ console.log('Anchor status: could not be computed for this revision; check open annotations by hand.');
890
+ }
891
+ else if (orphaned.length) {
892
+ console.log(`Orphaned annotations (anchored text removed): ${orphaned.length}`);
893
+ for (const id of orphaned) {
894
+ console.log(` ${id}`);
895
+ }
896
+ }
733
897
  if (baseRevisionId && !explicitBase) {
734
898
  console.log(`Base ${baseRevisionId} (remembered from this machine)`);
735
899
  }
@@ -744,7 +908,7 @@ export function createAnnotationFromCli(args) {
744
908
  const [artifactId] = getPositionals(args);
745
909
  const comment = parseFlagValue(args, '--comment');
746
910
  if (!artifactId || !comment) {
747
- throw new Error('Usage: artis annotate <artifact-id-or-slug> --comment <text> [--title <text>] [--quote <text>] [--css <selector>] [--text-start <n> --text-end <n>] [--rect <x,y,w,h>] [--pin-label <text>] [--requested-change <text>] [--status <open|needs-revision|resolved>]');
911
+ throw usageError('Usage: artis annotate <artifact-id-or-slug> --comment <text> [--title <text>] [--quote <text>] [--css <selector>] [--text-start <n> --text-end <n>] [--rect <x,y,w,h>] [--pin-label <text>] [--requested-change <text>] [--status <open|needs-revision|resolved>]');
748
912
  }
749
913
  const selectors = buildAnnotationSelectors(args);
750
914
  const credentials = yield resolveCredentials(args);
@@ -774,7 +938,7 @@ export function replyFromCli(args) {
774
938
  const [annotationId] = getPositionals(args);
775
939
  const comment = parseFlagValue(args, '--comment');
776
940
  if (!annotationId || !comment) {
777
- throw new Error('Usage: artis reply <annotation-id> --comment <text>');
941
+ throw usageError('Usage: artis reply <annotation-id> --comment <text>');
778
942
  }
779
943
  const credentials = yield resolveCredentials(args);
780
944
  const result = yield apiFetch(credentials, `/api/annotations/${encodeURIComponent(annotationId)}/replies`, {
@@ -801,7 +965,7 @@ export function editAnnotationFromCli(args) {
801
965
  (comment === undefined &&
802
966
  title === undefined &&
803
967
  requestedChange === undefined)) {
804
- throw new Error('Usage: artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]');
968
+ throw usageError('Usage: artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]');
805
969
  }
806
970
  const credentials = yield resolveCredentials(args);
807
971
  const result = yield apiFetch(credentials, `/api/annotations/${encodeURIComponent(annotationId)}`, {
@@ -818,7 +982,7 @@ export function retractAnnotationFromCli(args) {
818
982
  return __awaiter(this, void 0, void 0, function* () {
819
983
  const [annotationId] = getPositionals(args);
820
984
  if (!annotationId) {
821
- throw new Error('Usage: artis annotation retract <annotation-id>');
985
+ throw usageError('Usage: artis annotation retract <annotation-id>');
822
986
  }
823
987
  const credentials = yield resolveCredentials(args);
824
988
  const result = yield apiFetch(credentials, `/api/annotations/${encodeURIComponent(annotationId)}`, {
@@ -830,6 +994,124 @@ export function retractAnnotationFromCli(args) {
830
994
  console.log(`Annotation ${annotationIdFromIri(result.annotation.id)} retracted`);
831
995
  });
832
996
  }
997
+ const watchMaxWaitSeconds = 25;
998
+ const watchInitialBackoffMs = 1000;
999
+ const watchMaxBackoffMs = 60000;
1000
+ /** `30`, `30s`, `500ms`, `5m`, `1h` → milliseconds. A bare number is seconds. */
1001
+ function parseDuration(value) {
1002
+ var _a;
1003
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(value.trim());
1004
+ if (!match) {
1005
+ throw usageError(`Invalid duration "${value}". Use e.g. 30s, 5m, 1h, or 500ms.`);
1006
+ }
1007
+ const unitMs = { ms: 1, s: 1000, m: 60000, h: 3600000 }[((_a = match[2]) !== null && _a !== void 0 ? _a : 's')];
1008
+ return Number(match[1]) * unitMs;
1009
+ }
1010
+ /**
1011
+ * Wait for annotation events on one artifact caused by anyone but this API
1012
+ * key, by long-polling `GET /api/artifacts/:id/events` from a feedback
1013
+ * cursor. Streams one JSON line per event until stopped; `--once` prints the
1014
+ * first batch as `{events, cursor}` and exits 0. Network drops and rate
1015
+ * limits are retried from the last cursor, so no event is lost or repeated.
1016
+ */
1017
+ export function watchArtifactFromCli(args) {
1018
+ return __awaiter(this, void 0, void 0, function* () {
1019
+ var _a, _b, _c;
1020
+ const [artifactId] = getPositionals(args);
1021
+ if (!artifactId) {
1022
+ throw usageError('Usage: artis watch <artifact-id-or-slug> [--since <cursor>] [--once] [--timeout <duration>] [--include-self]');
1023
+ }
1024
+ let cursor = parseFlagValue(args, '--since');
1025
+ if (cursor !== undefined && !/^\d+$/.test(cursor)) {
1026
+ throw usageError(`Invalid --since "${cursor}". Pass a cursor from artifact feedback or a previous event.`);
1027
+ }
1028
+ const timeoutFlag = parseFlagValue(args, '--timeout');
1029
+ const deadline = timeoutFlag !== undefined
1030
+ ? Date.now() + parseDuration(timeoutFlag)
1031
+ : undefined;
1032
+ const once = hasFlag(args, '--once');
1033
+ const includeSelf = hasFlag(args, '--include-self');
1034
+ const credentials = yield resolveCredentials(args);
1035
+ let backoffMs = watchInitialBackoffMs;
1036
+ let delivered = false;
1037
+ const timedOut = () => new CliError(`No feedback events within ${timeoutFlag}.${cursor ? ` Resume with --since ${cursor}.` : ''}`, exitCodes.watchTimeout);
1038
+ // Sleep before retrying a transient failure. Returns false when the
1039
+ // deadline would pass first and the stream already delivered (a clean end).
1040
+ const backOff = () => __awaiter(this, void 0, void 0, function* () {
1041
+ const remaining = deadline === undefined ? Infinity : deadline - Date.now();
1042
+ if (remaining <= backoffMs) {
1043
+ if (delivered) {
1044
+ return false;
1045
+ }
1046
+ throw timedOut();
1047
+ }
1048
+ yield sleep(backoffMs);
1049
+ backoffMs = Math.min(backoffMs * 2, watchMaxBackoffMs);
1050
+ return true;
1051
+ });
1052
+ for (let attempt = 0;; attempt += 1) {
1053
+ const remainingMs = deadline === undefined ? Infinity : deadline - Date.now();
1054
+ // The first request always goes out, so a short --timeout still reports
1055
+ // auth or not-found errors. After that, under a second left would only
1056
+ // produce wait=0 requests in a tight loop.
1057
+ if (attempt > 0 && remainingMs < 1000) {
1058
+ // Exit 6 means "nothing happened"; a stream that delivered ends cleanly.
1059
+ if (delivered) {
1060
+ return;
1061
+ }
1062
+ throw timedOut();
1063
+ }
1064
+ const query = new URLSearchParams({
1065
+ wait: String(Math.min(watchMaxWaitSeconds, Math.floor(remainingMs / 1000))),
1066
+ });
1067
+ if (cursor !== undefined) {
1068
+ query.set('since', cursor);
1069
+ }
1070
+ if (includeSelf) {
1071
+ query.set('includeSelf', 'true');
1072
+ }
1073
+ let response;
1074
+ try {
1075
+ response = yield fetch(`${credentials.baseUrl}/api/artifacts/${encodeURIComponent(artifactId)}/events?${query}`, { headers: { authorization: `Bearer ${credentials.apiKey}` } });
1076
+ }
1077
+ catch (_d) {
1078
+ // Network drop: reconnect from the last cursor.
1079
+ if (yield backOff()) {
1080
+ continue;
1081
+ }
1082
+ return;
1083
+ }
1084
+ const payload = yield readJsonResponse(response);
1085
+ // Rate limits and server errors are transient for a long-running stream.
1086
+ if ((response.status === 429 || response.status >= 500) && !once) {
1087
+ if (yield backOff()) {
1088
+ continue;
1089
+ }
1090
+ return;
1091
+ }
1092
+ if (!response.ok) {
1093
+ const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Watch request failed with ${response.status}.`;
1094
+ throw new CliError(response.status === 410
1095
+ ? `${message} Re-read feedback (artis artifact feedback ${artifactId} --json) and watch from its cursor.`
1096
+ : message, exitCodeForResponse(response.status, payload === null || payload === void 0 ? void 0 : payload.code));
1097
+ }
1098
+ backoffMs = watchInitialBackoffMs;
1099
+ const events = (_b = payload === null || payload === void 0 ? void 0 : payload.events) !== null && _b !== void 0 ? _b : [];
1100
+ cursor = (_c = payload === null || payload === void 0 ? void 0 : payload.cursor) !== null && _c !== void 0 ? _c : cursor;
1101
+ if (events.length === 0) {
1102
+ continue;
1103
+ }
1104
+ if (once) {
1105
+ console.log(JSON.stringify({ events, cursor }));
1106
+ return;
1107
+ }
1108
+ for (const event of events) {
1109
+ process.stdout.write(`${JSON.stringify(event)}\n`);
1110
+ }
1111
+ delivered = true;
1112
+ }
1113
+ });
1114
+ }
833
1115
  export function runArtisCli() {
834
1116
  return __awaiter(this, arguments, void 0, function* (args = process.argv.slice(2)) {
835
1117
  const [command, ...rest] = args;
@@ -878,6 +1160,14 @@ export function runArtisCli() {
878
1160
  yield getArtifactHtmlFromCli(rest.slice(1));
879
1161
  return;
880
1162
  }
1163
+ if (command === 'verify') {
1164
+ yield verifyFromCli(rest);
1165
+ return;
1166
+ }
1167
+ if (command === 'artifact' && rest[0] === 'list') {
1168
+ yield listArtifactsFromCli(rest.slice(1));
1169
+ return;
1170
+ }
881
1171
  if (command === 'artifact' && rest[0] === 'feedback') {
882
1172
  yield getArtifactFeedbackFromCli(rest.slice(1));
883
1173
  return;
@@ -894,6 +1184,10 @@ export function runArtisCli() {
894
1184
  yield createAnnotationFromCli(rest);
895
1185
  return;
896
1186
  }
1187
+ if (command === 'watch') {
1188
+ yield watchArtifactFromCli(rest);
1189
+ return;
1190
+ }
897
1191
  if (command === 'reply') {
898
1192
  yield replyFromCli(rest);
899
1193
  return;
@@ -906,7 +1200,7 @@ export function runArtisCli() {
906
1200
  yield retractAnnotationFromCli(rest.slice(1));
907
1201
  return;
908
1202
  }
909
- throw new Error(`Unknown command "${args.join(' ')}". Run artis help.`);
1203
+ throw usageError(`Unknown command "${args.join(' ')}". Run artis help.`);
910
1204
  });
911
1205
  }
912
1206
  //# sourceMappingURL=cli.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The CLI's process exit codes, one table for every command so an agent can
3
+ * branch on the outcome without parsing messages. Documented in the `cli`
4
+ * guidelines section; keep the two in step.
5
+ */
6
+ export declare const exitCodes: {
7
+ readonly ok: 0;
8
+ readonly error: 1;
9
+ readonly usage: 2;
10
+ readonly auth: 3;
11
+ readonly notFound: 4;
12
+ readonly revisionConflict: 5;
13
+ readonly watchTimeout: 6;
14
+ readonly rateLimited: 7;
15
+ /** `artis verify` found problems in the rendered page. */
16
+ readonly verifyFailed: 8;
17
+ };
18
+ export type ExitCode = (typeof exitCodes)[keyof typeof exitCodes];
19
+ /** An error that knows which exit code it should end the process with. */
20
+ export declare class CliError extends Error {
21
+ readonly exitCode: ExitCode;
22
+ constructor(message: string, exitCode: ExitCode);
23
+ }
24
+ /** Bad or missing arguments: exit 2. */
25
+ export declare function usageError(message: string): CliError;
26
+ /** Exit code for a failed API response. */
27
+ export declare function exitCodeForResponse(status: number, code?: string): ExitCode;
28
+ export declare function exitCodeFor(error: unknown): ExitCode;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The CLI's process exit codes, one table for every command so an agent can
3
+ * branch on the outcome without parsing messages. Documented in the `cli`
4
+ * guidelines section; keep the two in step.
5
+ */
6
+ export const exitCodes = {
7
+ ok: 0,
8
+ error: 1,
9
+ usage: 2,
10
+ auth: 3,
11
+ notFound: 4,
12
+ revisionConflict: 5,
13
+ watchTimeout: 6,
14
+ rateLimited: 7,
15
+ /** `artis verify` found problems in the rendered page. */
16
+ verifyFailed: 8,
17
+ };
18
+ /** An error that knows which exit code it should end the process with. */
19
+ export class CliError extends Error {
20
+ constructor(message, exitCode) {
21
+ super(message);
22
+ this.name = 'CliError';
23
+ this.exitCode = exitCode;
24
+ }
25
+ }
26
+ /** Bad or missing arguments: exit 2. */
27
+ export function usageError(message) {
28
+ return new CliError(message, exitCodes.usage);
29
+ }
30
+ /** Exit code for a failed API response. */
31
+ export function exitCodeForResponse(status, code) {
32
+ if (status === 401 || status === 403) {
33
+ return exitCodes.auth;
34
+ }
35
+ if (status === 404) {
36
+ return exitCodes.notFound;
37
+ }
38
+ if (status === 409 && code === 'revision_conflict') {
39
+ return exitCodes.revisionConflict;
40
+ }
41
+ if (status === 429) {
42
+ return exitCodes.rateLimited;
43
+ }
44
+ return exitCodes.error;
45
+ }
46
+ export function exitCodeFor(error) {
47
+ return error instanceof CliError ? error.exitCode : exitCodes.error;
48
+ }
49
+ //# sourceMappingURL=exit-codes.js.map
@@ -0,0 +1,56 @@
1
+ export declare const verifyWidths: readonly [1280, 390];
2
+ export declare const verifyThemes: readonly ["light", "dark"];
3
+ export type VerifyTheme = (typeof verifyThemes)[number];
4
+ /** A copy of usercontent's artifact CSP (apps/usercontent/src/worker/csp.ts);
5
+ * scripts/verify-unit.mjs keeps the two identical. */
6
+ export declare function artifactContentSecurityPolicy(origin: string): string;
7
+ export interface OverflowFinding {
8
+ scrollWidth: number;
9
+ clientWidth: number;
10
+ /** `overflow-x: hidden` on <html>/<body>: no scrollbar, but the content
11
+ * past the edge is still cut off. */
12
+ hiddenByPage: boolean;
13
+ /** Elements reaching past the right edge, widest first (at most 5). */
14
+ offenders: Array<{
15
+ element: string;
16
+ right: number;
17
+ }>;
18
+ }
19
+ export interface ClippedSvgFinding {
20
+ element: string;
21
+ /** How far drawn content extends past the SVG viewport, per side. */
22
+ overflow: {
23
+ top: number;
24
+ right: number;
25
+ bottom: number;
26
+ left: number;
27
+ };
28
+ }
29
+ export interface CspViolation {
30
+ directive: string;
31
+ blocked: string;
32
+ }
33
+ export interface VerifyRun {
34
+ width: number;
35
+ theme: VerifyTheme;
36
+ overflow: OverflowFinding | null;
37
+ clippedSvgs: ClippedSvgFinding[];
38
+ consoleErrors: string[];
39
+ cspViolations: CspViolation[];
40
+ }
41
+ export interface VerifyReport {
42
+ ok: boolean;
43
+ runs: VerifyRun[];
44
+ }
45
+ export declare class VerifyUnavailableError extends Error {
46
+ }
47
+ /** Insert the theme boot as the first child of <head> — the same stamp
48
+ * usercontent's inline boot script applies for an explicit theme. Like
49
+ * usercontent (which injects through an HTMLRewriter `head` handler), a
50
+ * document without a `<head>` tag gets no stamp, only the matching
51
+ * `prefers-color-scheme`; prepending would also push the doctype out of
52
+ * first place and render in quirks mode. */
53
+ export declare function stampTheme(html: string, theme: VerifyTheme): string;
54
+ export declare function verifyHtml(html: string): Promise<VerifyReport>;
55
+ /** Human-readable report: one block per problem, listing the runs it hit. */
56
+ export declare function formatVerifyReport(report: VerifyReport): string[];
@@ -0,0 +1,395 @@
1
+ import { __awaiter } from "tslib";
2
+ import { createServer } from 'node:http';
3
+ /*
4
+ * `artis verify`: render an artifact the way viewers get it and report what
5
+ * an agent cannot see from the source. Runs locally in a headless browser
6
+ * (the system Chrome through the optional `playwright-core` dependency), so
7
+ * it needs no server or bridge support.
8
+ *
9
+ * The page is served from a local origin with the same Content-Security-
10
+ * Policy usercontent sends, and each theme is applied the way the bridge's
11
+ * theme boot does it (`data-theme` + `color-scheme` on <html>, plus the
12
+ * matching `prefers-color-scheme`).
13
+ */
14
+ export const verifyWidths = [1280, 390];
15
+ export const verifyThemes = ['light', 'dark'];
16
+ /** A copy of usercontent's artifact CSP (apps/usercontent/src/worker/csp.ts);
17
+ * scripts/verify-unit.mjs keeps the two identical. */
18
+ export function artifactContentSecurityPolicy(origin) {
19
+ return (`sandbox allow-scripts allow-forms; default-src 'none'; ` +
20
+ `script-src 'unsafe-inline' ${origin}; style-src 'unsafe-inline'; ` +
21
+ 'img-src data: blob:; font-src data:');
22
+ }
23
+ export class VerifyUnavailableError extends Error {
24
+ }
25
+ function launchBrowser() {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ let chromium;
28
+ try {
29
+ // A variable specifier keeps bundlers and tsc from requiring the
30
+ // optional dependency at build time.
31
+ const specifier = 'playwright-core';
32
+ ({ chromium } = yield import(specifier));
33
+ }
34
+ catch (_a) {
35
+ throw new VerifyUnavailableError('artis verify needs playwright-core. Install it next to the CLI: npm install -g playwright-core');
36
+ }
37
+ const executablePath = process.env['ARTIS_CHROME_PATH'];
38
+ const attempts = executablePath
39
+ ? [{ executablePath }]
40
+ : [{ channel: 'chrome' }, { channel: 'msedge' }, { channel: 'chromium' }];
41
+ for (const attempt of attempts) {
42
+ try {
43
+ return yield chromium.launch(Object.assign({ headless: true }, attempt));
44
+ }
45
+ catch (_b) {
46
+ // Try the next browser.
47
+ }
48
+ }
49
+ throw new VerifyUnavailableError(executablePath
50
+ ? `Could not launch the browser at ARTIS_CHROME_PATH (${executablePath}).`
51
+ : 'artis verify uses the system Google Chrome (or Edge). Install one, or set ARTIS_CHROME_PATH to a Chromium-based browser.');
52
+ });
53
+ }
54
+ /** Serve one document at `/` with the artifact CSP, the theme stamped the
55
+ * way usercontent's theme boot does it. */
56
+ function serveDocument(html) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ const server = createServer((request, response) => {
59
+ var _a;
60
+ const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://localhost');
61
+ const theme = url.searchParams.get('theme') === 'dark' ? 'dark' : 'light';
62
+ if (url.pathname !== '/') {
63
+ response.writeHead(404).end();
64
+ return;
65
+ }
66
+ const origin = `http://${request.headers.host}`;
67
+ response.writeHead(200, {
68
+ 'content-type': 'text/html; charset=utf-8',
69
+ 'content-security-policy': artifactContentSecurityPolicy(origin),
70
+ });
71
+ response.end(stampTheme(html, theme));
72
+ });
73
+ yield new Promise((resolve, reject) => {
74
+ server.once('error', reject);
75
+ server.listen(0, '127.0.0.1', () => {
76
+ server.off('error', reject);
77
+ resolve();
78
+ });
79
+ });
80
+ const { port } = server.address();
81
+ return {
82
+ server,
83
+ url: (theme) => `http://127.0.0.1:${port}/?theme=${theme}`,
84
+ };
85
+ });
86
+ }
87
+ /** Insert the theme boot as the first child of <head> — the same stamp
88
+ * usercontent's inline boot script applies for an explicit theme. Like
89
+ * usercontent (which injects through an HTMLRewriter `head` handler), a
90
+ * document without a `<head>` tag gets no stamp, only the matching
91
+ * `prefers-color-scheme`; prepending would also push the doctype out of
92
+ * first place and render in quirks mode. */
93
+ export function stampTheme(html, theme) {
94
+ const boot = `<script>document.documentElement.setAttribute('data-theme','${theme}');document.documentElement.style.colorScheme='${theme}';</script>`;
95
+ const head = /<head\b[^>]*>/i.exec(html);
96
+ if (!head) {
97
+ return html;
98
+ }
99
+ const at = head.index + head[0].length;
100
+ return html.slice(0, at) + boot + html.slice(at);
101
+ }
102
+ /** Records CSP violations the page itself observes. */
103
+ const RECORD_CSP_VIOLATIONS = `
104
+ window.__artisCsp = [];
105
+ document.addEventListener('securitypolicyviolation', (event) => {
106
+ window.__artisCsp.push({
107
+ directive: event.effectiveDirective || event.violatedDirective,
108
+ blocked: event.blockedURI || 'inline',
109
+ });
110
+ });`;
111
+ /** In-page checks, run after load. Kept as a string so it executes in the
112
+ * page untouched by the CLI's TypeScript build. */
113
+ const INSPECT_PAGE = `(() => {
114
+ const describe = (el) => {
115
+ let text = el.tagName.toLowerCase();
116
+ if (el.id) text += '#' + el.id;
117
+ const cls = typeof el.className === 'string' ? el.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2) : [];
118
+ if (cls.length) text += '.' + cls.join('.');
119
+ return text;
120
+ };
121
+ const root = document.documentElement;
122
+ const clientWidth = root.clientWidth;
123
+ const scrollWidth = Math.max(root.scrollWidth, document.body ? document.body.scrollWidth : 0);
124
+ let overflow = null;
125
+ if (scrollWidth > clientWidth + 1) {
126
+ // Elements past either edge whose own scroll container is the page:
127
+ // an element inside overflow-x: auto/hidden is contained, not the cause.
128
+ const scrolls = (el) => {
129
+ const ox = getComputedStyle(el).overflowX;
130
+ return ox === 'auto' || ox === 'scroll' || ox === 'hidden' || ox === 'clip';
131
+ };
132
+ const contained = (el) => {
133
+ for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
134
+ if (scrolls(p)) return true;
135
+ }
136
+ return false;
137
+ };
138
+ const rtl = getComputedStyle(root).direction === 'rtl';
139
+ const offenders = [];
140
+ for (const el of document.body ? document.body.querySelectorAll('*') : []) {
141
+ const rect = el.getBoundingClientRect();
142
+ const left = rect.left + window.scrollX;
143
+ const right = rect.right + window.scrollX;
144
+ // Past the left edge only counts in a right-to-left document: in LTR
145
+ // it is the usual off-screen pattern (skip links, visually-hidden
146
+ // text), which the page cannot scroll to anyway.
147
+ const past = rtl ? Math.max(right - clientWidth, -left) : right - clientWidth;
148
+ if (past > 1 && !contained(el)) offenders.push({ element: describe(el), right: Math.round(right), past });
149
+ }
150
+ offenders.sort((a, b) => b.past - a.past);
151
+ // overflow-x: hidden on <html>/<body> hides the scrollbar but still cuts
152
+ // the content off, so it is reported, flagged as hidden.
153
+ const hiddenBy = [root, document.body].find((el) => {
154
+ if (!el) return false;
155
+ const ox = getComputedStyle(el).overflowX;
156
+ return ox === 'hidden' || ox === 'clip';
157
+ });
158
+ overflow = {
159
+ scrollWidth,
160
+ clientWidth,
161
+ hiddenByPage: Boolean(hiddenBy),
162
+ offenders: offenders.slice(0, 5).map(({ element, right }) => ({ element, right })),
163
+ };
164
+ }
165
+
166
+ // Drawn content of an <svg>, in its user units: the union of its visible
167
+ // leaf shapes (with half their stroke), skipping anything under a
168
+ // clip-path or mask (clipped on purpose) and anything not painted.
169
+ const LEAVES = 'path, rect, circle, ellipse, line, polyline, polygon, text, image, use, foreignObject';
170
+ const drawnBox = (svg) => {
171
+ const toUser = svg.getScreenCTM();
172
+ if (!toUser) return null;
173
+ const inverse = toUser.inverse();
174
+ let box = null;
175
+ for (const leaf of svg.querySelectorAll(LEAVES)) {
176
+ if (leaf.closest('defs, clipPath, mask, marker, pattern, symbol, linearGradient, radialGradient')) continue;
177
+ // A nested <svg> clips its own content; it is checked on its own terms
178
+ // only when it is the outermost one.
179
+ if (leaf.parentElement && leaf.parentElement.closest('svg') !== svg) continue;
180
+ let hidden = false;
181
+ for (let el = leaf; el && el !== svg; el = el.parentElement) {
182
+ const cs = getComputedStyle(el);
183
+ if (el.hasAttribute('clip-path') || el.hasAttribute('mask') || (cs.clipPath && cs.clipPath !== 'none') || (cs.mask && cs.mask !== 'none') || cs.display === 'none' || Number(cs.opacity) === 0) {
184
+ hidden = true;
185
+ break;
186
+ }
187
+ }
188
+ const leafStyle = getComputedStyle(leaf);
189
+ if (hidden || leafStyle.visibility !== 'visible') continue;
190
+ // Paints nothing (a transparent hover overlay): not visible content.
191
+ const paints = (paint) => Boolean(paint) && paint !== 'none' && paint !== 'transparent' && !(paint.startsWith('rgba(') && paint.replace(/ /g, '').endsWith(',0)'));
192
+ if (leaf.tagName !== 'image' && leaf.tagName !== 'use' && leaf.tagName !== 'foreignObject' && !paints(leafStyle.fill) && !paints(leafStyle.stroke)) continue;
193
+ let b;
194
+ try { b = leaf.getBBox(); } catch { continue; }
195
+ if (b.width === 0 && b.height === 0) continue;
196
+ const half = leafStyle.stroke && leafStyle.stroke !== 'none' ? (parseFloat(leafStyle.strokeWidth) || 0) / 2 : 0;
197
+ const matrix = leaf.getScreenCTM();
198
+ if (!matrix) continue;
199
+ const m = inverse.multiply(matrix);
200
+ for (const [x, y] of [[b.x - half, b.y - half], [b.x + b.width + half, b.y - half], [b.x - half, b.y + b.height + half], [b.x + b.width + half, b.y + b.height + half]]) {
201
+ const px = m.a * x + m.c * y + m.e;
202
+ const py = m.b * x + m.d * y + m.f;
203
+ box = box
204
+ ? { x1: Math.min(box.x1, px), y1: Math.min(box.y1, py), x2: Math.max(box.x2, px), y2: Math.max(box.y2, py) }
205
+ : { x1: px, y1: py, x2: px, y2: py };
206
+ }
207
+ }
208
+ return box;
209
+ };
210
+
211
+ // The region of user space the SVG actually shows: the viewBox scaled into
212
+ // the element's box under preserveAspectRatio (meet shows more than the
213
+ // viewBox, slice less), or the box itself without a viewBox.
214
+ const visibleRegion = (svg) => {
215
+ const width = svg.clientWidth || svg.getBoundingClientRect().width;
216
+ const height = svg.clientHeight || svg.getBoundingClientRect().height;
217
+ if (!width || !height) return null;
218
+ const vb = svg.viewBox && svg.viewBox.baseVal;
219
+ if (!vb || !(vb.width > 0) || !(vb.height > 0)) return { x1: 0, y1: 0, x2: width, y2: height };
220
+ const par = svg.preserveAspectRatio.baseVal;
221
+ if (par.align === 1) return { x1: vb.x, y1: vb.y, x2: vb.x + vb.width, y2: vb.y + vb.height };
222
+ const scale = par.meetOrSlice === 2
223
+ ? Math.max(width / vb.width, height / vb.height)
224
+ : Math.min(width / vb.width, height / vb.height);
225
+ const shownWidth = width / scale;
226
+ const shownHeight = height / scale;
227
+ const xAlign = (par.align - 2) % 3;
228
+ const yAlign = Math.floor((par.align - 2) / 3);
229
+ const x1 = vb.x - ((shownWidth - vb.width) * xAlign) / 2;
230
+ const y1 = vb.y - ((shownHeight - vb.height) * yAlign) / 2;
231
+ return { x1, y1, x2: x1 + shownWidth, y2: y1 + shownHeight };
232
+ };
233
+
234
+ const clippedSvgs = [];
235
+ for (const svg of document.querySelectorAll('svg')) {
236
+ if (svg.parentElement && svg.parentElement.closest('svg')) continue;
237
+ const style = getComputedStyle(svg);
238
+ if (style.overflow === 'visible' || style.display === 'none') continue;
239
+ const shown = visibleRegion(svg);
240
+ const drawn = shown && drawnBox(svg);
241
+ if (!drawn) continue;
242
+ const tolerance = Math.max(1, (shown.x2 - shown.x1) / 500);
243
+ const over = {
244
+ top: Math.max(0, shown.y1 - drawn.y1),
245
+ right: Math.max(0, drawn.x2 - shown.x2),
246
+ bottom: Math.max(0, drawn.y2 - shown.y2),
247
+ left: Math.max(0, shown.x1 - drawn.x1),
248
+ };
249
+ if (Object.values(over).some((v) => v > tolerance)) {
250
+ const round = (v) => Math.round(v * 10) / 10;
251
+ clippedSvgs.push({
252
+ element: describe(svg),
253
+ overflow: { top: round(over.top), right: round(over.right), bottom: round(over.bottom), left: round(over.left) },
254
+ });
255
+ }
256
+ }
257
+
258
+ return { overflow, clippedSvgs, cspViolations: window.__artisCsp || [] };
259
+ })()`;
260
+ /** Chrome reports CSP blocks as console errors too; those are counted as
261
+ * CSP violations, not as script errors. */
262
+ function isCspConsoleMessage(text) {
263
+ return /Content Security Policy/i.test(text);
264
+ }
265
+ export function verifyHtml(html) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ // Server first, then the browser, each released in its own finally: a
268
+ // failed launch or close must never leave a listening server behind (it
269
+ // would keep the CLI process alive).
270
+ const { server, url } = yield serveDocument(html);
271
+ try {
272
+ const browser = yield launchBrowser();
273
+ try {
274
+ return yield runChecks(browser, url);
275
+ }
276
+ finally {
277
+ yield browser.close().catch(() => undefined);
278
+ }
279
+ }
280
+ finally {
281
+ yield new Promise((resolve) => server.close(resolve));
282
+ }
283
+ });
284
+ }
285
+ function runChecks(browser, url) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ const runs = [];
288
+ for (const width of verifyWidths) {
289
+ for (const theme of verifyThemes) {
290
+ const context = yield browser.newContext({
291
+ viewport: { width, height: 900 },
292
+ colorScheme: theme,
293
+ });
294
+ try {
295
+ const page = yield context.newPage();
296
+ const consoleErrors = [];
297
+ page.on('console', (message) => {
298
+ if (message.type() === 'error' &&
299
+ !isCspConsoleMessage(message.text())) {
300
+ consoleErrors.push(message.text());
301
+ }
302
+ });
303
+ page.on('pageerror', (error) => {
304
+ // eval / new Function blocked by the CSP throws an EvalError;
305
+ // the securitypolicyviolation event already records it.
306
+ if (!isCspConsoleMessage(error.message)) {
307
+ consoleErrors.push(error.message);
308
+ }
309
+ });
310
+ yield page.addInitScript(RECORD_CSP_VIOLATIONS);
311
+ yield page.goto(url(theme), { waitUntil: 'load', timeout: 15000 });
312
+ // Let late renders and web fonts settle.
313
+ yield page.waitForTimeout(400);
314
+ const findings = yield page.evaluate(INSPECT_PAGE);
315
+ runs.push({
316
+ width,
317
+ theme,
318
+ overflow: findings.overflow,
319
+ clippedSvgs: findings.clippedSvgs,
320
+ consoleErrors: [...new Set(consoleErrors)],
321
+ cspViolations: dedupe(findings.cspViolations),
322
+ });
323
+ }
324
+ finally {
325
+ yield context.close();
326
+ }
327
+ }
328
+ }
329
+ return {
330
+ ok: runs.every((run) => !run.overflow &&
331
+ !run.clippedSvgs.length &&
332
+ !run.consoleErrors.length &&
333
+ !run.cspViolations.length),
334
+ runs,
335
+ };
336
+ });
337
+ }
338
+ function dedupe(violations) {
339
+ const seen = new Set();
340
+ return violations.filter((violation) => {
341
+ const key = `${violation.directive} ${violation.blocked}`;
342
+ if (seen.has(key))
343
+ return false;
344
+ seen.add(key);
345
+ return true;
346
+ });
347
+ }
348
+ /** Human-readable report: one block per problem, listing the runs it hit. */
349
+ export function formatVerifyReport(report) {
350
+ if (report.ok) {
351
+ return [
352
+ `No problems found at ${verifyWidths.join(' and ')} px in light and dark themes.`,
353
+ ];
354
+ }
355
+ const lines = [];
356
+ const label = (run) => `${run.width}px ${run.theme}`;
357
+ const group = (pick, key) => {
358
+ var _a;
359
+ const byKey = new Map();
360
+ for (const run of report.runs) {
361
+ for (const item of pick(run)) {
362
+ const entry = (_a = byKey.get(key(item))) !== null && _a !== void 0 ? _a : { item, runs: [] };
363
+ entry.runs.push(label(run));
364
+ byKey.set(key(item), entry);
365
+ }
366
+ }
367
+ return [...byKey.values()];
368
+ };
369
+ for (const run of report.runs) {
370
+ if (run.overflow) {
371
+ const offenders = run.overflow.offenders
372
+ .map((o) => `${o.element} (to ${o.right}px)`)
373
+ .join(', ');
374
+ const hidden = run.overflow.hiddenByPage
375
+ ? ' (hidden by overflow-x on the page, so the content past the edge is cut off)'
376
+ : '';
377
+ lines.push(`Horizontal overflow at ${label(run)}: page is ${run.overflow.scrollWidth}px wide in a ${run.overflow.clientWidth}px viewport${hidden}${offenders ? `; widest: ${offenders}` : ''}.`);
378
+ }
379
+ }
380
+ for (const { item, runs } of group((run) => run.clippedSvgs, (svg) => `${svg.element} ${JSON.stringify(svg.overflow)}`)) {
381
+ const sides = Object.entries(item.overflow)
382
+ .filter(([, value]) => value > 0)
383
+ .map(([side, value]) => `${side} ${value}`)
384
+ .join(', ');
385
+ lines.push(`Clipped SVG ${item.element} (content past its viewport: ${sides}) at ${runs.join(', ')}.`);
386
+ }
387
+ for (const { item, runs } of group((run) => run.consoleErrors, (text) => text)) {
388
+ lines.push(`Console error at ${runs.join(', ')}: ${item}`);
389
+ }
390
+ for (const { item, runs } of group((run) => run.cspViolations, (violation) => `${violation.directive} ${violation.blocked}`)) {
391
+ lines.push(`CSP violation (${item.directive}) blocking ${item.blocked} at ${runs.join(', ')}. Artifacts may load nothing external: inline it or use a data: URL.`);
392
+ }
393
+ return lines;
394
+ }
395
+ //# sourceMappingURL=verify.js.map