@skrr-ai/cli 0.1.162 → 0.1.164

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 (95) hide show
  1. package/dist/base-command.d.ts +5 -2
  2. package/dist/base-command.js +108 -39
  3. package/dist/commands/activity/list.d.ts +7 -0
  4. package/dist/commands/activity/list.js +17 -0
  5. package/dist/commands/activity/scan-older.d.ts +2 -2
  6. package/dist/commands/activity/scan-older.js +6 -5
  7. package/dist/commands/activity/show.d.ts +0 -2
  8. package/dist/commands/activity/show.js +21 -42
  9. package/dist/commands/agents/always-on/release-run.d.ts +3 -3
  10. package/dist/commands/agents/always-on/release-run.js +5 -6
  11. package/dist/commands/agents/mini-computer/app/reset.d.ts +1 -0
  12. package/dist/commands/agents/mini-computer/app/reset.js +5 -2
  13. package/dist/commands/agents/mini-computer/app/set.js +1 -1
  14. package/dist/commands/agents/mini-computer/show.js +10 -2
  15. package/dist/commands/agents/mini-computer/tasks-view.js +2 -2
  16. package/dist/commands/agents/supervision.d.ts +25 -0
  17. package/dist/commands/agents/supervision.js +129 -0
  18. package/dist/commands/agents/triggers/replay.js +1 -1
  19. package/dist/commands/agents/triggers/runs.d.ts +2 -3
  20. package/dist/commands/agents/triggers/runs.js +4 -5
  21. package/dist/commands/apps/auto-apply.js +31 -10
  22. package/dist/commands/apps/check.js +8 -0
  23. package/dist/commands/apps/data/batch.js +16 -5
  24. package/dist/commands/apps/data/collections.js +1 -1
  25. package/dist/commands/apps/data/delete.js +12 -4
  26. package/dist/commands/apps/data/patch.js +11 -4
  27. package/dist/commands/apps/data/put.js +13 -6
  28. package/dist/commands/apps/data/query.js +3 -3
  29. package/dist/commands/apps/install.js +24 -7
  30. package/dist/commands/apps/installations/events.d.ts +1 -0
  31. package/dist/commands/apps/installations/events.js +63 -10
  32. package/dist/commands/apps/installations/show.js +26 -5
  33. package/dist/commands/apps/installations/snapshot.js +1 -1
  34. package/dist/commands/apps/installations/versions.js +25 -9
  35. package/dist/commands/apps/logs.js +4 -1
  36. package/dist/commands/apps/push.js +10 -2
  37. package/dist/commands/apps/reconsent.js +7 -1
  38. package/dist/commands/apps/rollback.js +2 -2
  39. package/dist/commands/apps/settings/set.js +81 -4
  40. package/dist/commands/apps/settings/show.js +38 -7
  41. package/dist/commands/duties/action-proposal.js +19 -11
  42. package/dist/commands/duties/cadence-decisions.js +7 -0
  43. package/dist/commands/duties/status.js +20 -15
  44. package/dist/commands/duties/trigger-status.js +2 -2
  45. package/dist/commands/duties/wake-capabilities.js +12 -6
  46. package/dist/commands/outbox/drop.js +21 -15
  47. package/dist/commands/outbox/list.d.ts +2 -1
  48. package/dist/commands/outbox/list.js +20 -11
  49. package/dist/commands/outbox/retry.d.ts +8 -11
  50. package/dist/commands/outbox/retry.js +135 -92
  51. package/dist/commands/spaces/create.js +1 -1
  52. package/dist/commands/tasks/comments/add.js +1 -1
  53. package/dist/commands/triggers/audit.js +3 -5
  54. package/dist/commands/triggers/fire-detail.js +7 -1
  55. package/dist/commands/triggers/replay.js +1 -1
  56. package/dist/commands/triggers/runs.d.ts +2 -4
  57. package/dist/commands/triggers/runs.js +3 -5
  58. package/dist/generated/agent-guides.json +19 -19
  59. package/dist/lib/agent-activity.d.ts +21 -1
  60. package/dist/lib/agent-activity.js +98 -29
  61. package/dist/lib/api-fetch.d.ts +2 -0
  62. package/dist/lib/api-fetch.js +5 -5
  63. package/dist/lib/appData.d.ts +43 -5
  64. package/dist/lib/appData.js +117 -25
  65. package/dist/lib/appInstallations.d.ts +5 -5
  66. package/dist/lib/appInstallations.js +232 -74
  67. package/dist/lib/appSettings.d.ts +2 -0
  68. package/dist/lib/appSettings.js +36 -3
  69. package/dist/lib/apps-command.d.ts +9 -0
  70. package/dist/lib/apps-command.js +191 -7
  71. package/dist/lib/appsCheck.js +40 -3
  72. package/dist/lib/appsFs.d.ts +1 -1
  73. package/dist/lib/chat-supervision.d.ts +21 -0
  74. package/dist/lib/chat-supervision.js +37 -0
  75. package/dist/lib/duties.d.ts +4 -0
  76. package/dist/lib/json-output.d.ts +4 -0
  77. package/dist/lib/json-output.js +38 -0
  78. package/dist/lib/miniComputer.d.ts +1 -0
  79. package/dist/lib/miniComputer.js +16 -4
  80. package/dist/lib/miniComputerCommand.js +4 -1
  81. package/dist/lib/node-adapter.js +35 -2
  82. package/dist/lib/outbox.d.ts +20 -5
  83. package/dist/lib/outbox.js +233 -76
  84. package/dist/lib/rate-limit-retry.d.ts +3 -2
  85. package/dist/lib/rate-limit-retry.js +3 -2
  86. package/dist/lib/roles.d.ts +1 -1
  87. package/dist/lib/triggers.d.ts +3 -0
  88. package/dist/lib/triggers.js +10 -0
  89. package/dist/lib/widgetCheck.js +30 -4
  90. package/dist/lib/widgetStaticScan.d.ts +17 -6
  91. package/dist/lib/widgetStaticScan.js +336 -94
  92. package/dist/node_modules/@skrr-ai/data-provider/APP_HTML_PARSER_LICENSES.txt +36 -0
  93. package/dist/node_modules/@skrr-ai/data-provider/index.js +15543 -10133
  94. package/oclif.manifest.json +334 -47
  95. package/package.json +5 -3
@@ -1,11 +1,60 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkModuleSyntax = checkModuleSyntax;
3
4
  exports.lexJs = lexJs;
4
5
  exports.maskJsComments = maskJsComments;
5
6
  exports.maskCssComments = maskCssComments;
6
7
  exports.maskHtmlComments = maskHtmlComments;
7
8
  exports.classifyUrl = classifyUrl;
8
9
  exports.scanWidgetSource = scanWidgetSource;
10
+ /**
11
+ * Generative UI — a cheap, conservative static scan of a widget's CSS, HTML and
12
+ * JavaScript for things that predict a failure INSIDE the sandboxed frame.
13
+ *
14
+ * WHAT THIS IS NOT. It is not the frame. The frame's Content-Security-Policy and
15
+ * `sandbox="allow-scripts"` (packages/data-provider `generativeUi/csp.ts`) decide
16
+ * what actually runs; this module only reads source text and says what the frame
17
+ * would very likely refuse. Every finding is therefore tagged `heuristic` by the
18
+ * caller, and the wording never claims more than the text shows ("looks like a
19
+ * fetch() call"). A finding can be a false positive (a name inside a string that
20
+ * never runs); the ABSENCE of findings proves nothing, because a script can
21
+ * assemble `fetch` at run time. It exists so a harness can notice the likely
22
+ * mistake before it sends the message, when fixing it is free.
23
+ *
24
+ * Severity: `error` means "the frame's CSP or sandbox blocks this if it runs";
25
+ * `warn` means "this probably does not do what the author meant".
26
+ *
27
+ * It is a lexer-light scanner on purpose. JavaScript is read once into a CODE
28
+ * view (comments, string and template text and regular-expression bodies blanked,
29
+ * same length, line breaks kept) and a list of the string literals: the rules about
30
+ * calls and names run over the code view only, so `"eval( is blocked"` in a label and
31
+ * a comment that says "do not call fetch()" are not findings, and the rules about
32
+ * what a string SAYS (a URL, markup that loads one) run over the literals only. No
33
+ * regular expression here can backtrack on the size the widget limits allow, and
34
+ * HTML is walked with `indexOf`, not with a lazy regex.
35
+ *
36
+ * The eval's static checks (`api/.../eval/generativeUi/staticChecks.js`) ask most
37
+ * of the same questions with a lexer of their own (`sourceLexers.js`), because this
38
+ * package may not import from `api/`. `generativeUiScannerAgreement.spec.js` runs
39
+ * both over one corpus and fails when they disagree about what the frame refuses.
40
+ */
41
+ const data_provider_1 = require("@skrr-ai/data-provider");
42
+ const entities_1 = require("entities");
43
+ const decode_1 = require("entities/decode");
44
+ const acorn_1 = require("acorn");
45
+ /** Parse as an actual ECMAScript module without executing author code. */
46
+ function checkModuleSyntax(source) {
47
+ try {
48
+ (0, acorn_1.parse)(source, { ecmaVersion: 'latest', sourceType: 'module' });
49
+ return null;
50
+ }
51
+ catch (error) {
52
+ if (!(error instanceof SyntaxError))
53
+ throw error;
54
+ const location = error.loc;
55
+ return { message: error.message, ...(location?.line ? { line: location.line } : {}) };
56
+ }
57
+ }
9
58
  const IS_IDENT_CHAR_RE = /[A-Za-z0-9_$]/;
10
59
  const LEX_JS_RE = /[a-z]/i;
11
60
  const LEX_JS_RE_2 = /[A-Za-z_$]/;
@@ -17,8 +66,9 @@ const SCAN_CSS_INTO_RE_2 = /^['"]|['"]$/g;
17
66
  const CALLS_RE = /\b(?:window\s*\.\s*)?skrr\s*\.\s*app\s*\.\s*(?:http|service)\s*\.\s*fetch\s*\(/g;
18
67
  const BROKER_FETCH_OFFSETS_RE = /\s/;
19
68
  const SCAN_JS_INTO_RE = /\bopenLink\b/;
20
- const SCAN_JS_INTO_RE_2 = /<\/script/i;
21
- const SRCSET_URLS_RE = /\s+/;
69
+ const SCAN_JS_INTO_RE_2 = /<\/script(?=[\t\n\f\r />])/i;
70
+ const SRCSET_SPACE_RE = /[\t\n\f\r ]/;
71
+ const TEMPLATE_CONDITION = 'If this template content is inserted into the page: ';
22
72
  const OPEN_LINK = 'window.skrr.openLink(url)';
23
73
  // ── small text helpers ──────────────────────────────────────────────────────
24
74
  /** ASCII-only lowercase: the same length as the input, so offsets stay valid. */
@@ -36,10 +86,15 @@ function asciiLower(value) {
36
86
  }
37
87
  function lineStarts(text) {
38
88
  const starts = [0];
39
- let i = text.indexOf('\n');
40
- while (i !== -1) {
41
- starts.push(i + 1);
42
- i = text.indexOf('\n', i + 1);
89
+ for (let i = 0; i < text.length; i += 1) {
90
+ if (text[i] === '\r') {
91
+ if (text[i + 1] === '\n')
92
+ i += 1;
93
+ starts.push(i + 1);
94
+ }
95
+ else if (text[i] === '\n') {
96
+ starts.push(i + 1);
97
+ }
43
98
  }
44
99
  return starts;
45
100
  }
@@ -65,9 +120,9 @@ function isAsciiLetter(c) {
65
120
  }
66
121
  // ── comment masking ─────────────────────────────────────────────────────────
67
122
  /** Replace `from..to` with spaces, keeping line breaks so line numbers stay valid. */
68
- function blank(chars, from, to) {
123
+ function blank(chars, from, to, javascript = false) {
69
124
  for (let k = from; k < to; k += 1) {
70
- if (chars[k] !== '\n') {
125
+ if (chars[k] !== '\n' && chars[k] !== '\r' && !(javascript && (0, data_provider_1.isJsLineTerminator)(chars[k]))) {
71
126
  chars[k] = ' ';
72
127
  }
73
128
  }
@@ -88,7 +143,7 @@ const REGEX_PRECEDING_WORDS = new Set([
88
143
  'yield',
89
144
  'await',
90
145
  ]);
91
- const isIdentChar = (c) => IS_IDENT_CHAR_RE.test(c) || c > '\u007f';
146
+ const isIdentChar = (c) => !(0, data_provider_1.isJsLineTerminator)(c) && (IS_IDENT_CHAR_RE.test(c) || c > '\u007f');
92
147
  /**
93
148
  * Read a script once. Total and linear: it never throws, every loop advances, and
94
149
  * a misread costs a missed or an extra finding, never a hang. It is a heuristic
@@ -109,7 +164,7 @@ function lexJs(src) {
109
164
  let i = 0;
110
165
  const keep = (kind, open, start, end) => {
111
166
  literals.push({ kind, open, start, value: src.slice(start, end) });
112
- blank(code, start, end);
167
+ blank(code, start, end, true);
113
168
  };
114
169
  /** Template text from `from` to a closing backtick or a `${`; returns the next offset to read. */
115
170
  const readTemplate = (from, open) => {
@@ -141,18 +196,18 @@ function lexJs(src) {
141
196
  while (i < n) {
142
197
  const c = src.charAt(i);
143
198
  const d = src.charAt(i + 1);
144
- if (c === '/' && d === '/') {
145
- const end = src.indexOf('\n', i);
199
+ if ((i === 0 && c === '#' && d === '!') || (c === '/' && d === '/')) {
200
+ const end = (0, data_provider_1.nextJsLineTerminator)(src, i);
146
201
  const to = end === -1 ? n : end;
147
- blank(code, i, to);
148
- blank(commentless, i, to);
202
+ blank(code, i, to, true);
203
+ blank(commentless, i, to, true);
149
204
  i = to;
150
205
  }
151
206
  else if (c === '/' && d === '*') {
152
207
  const end = src.indexOf('*/', i + 2);
153
208
  const to = end === -1 ? n : end + 2;
154
- blank(code, i, to);
155
- blank(commentless, i, to);
209
+ blank(code, i, to, true);
210
+ blank(commentless, i, to, true);
156
211
  i = to;
157
212
  }
158
213
  else if (c === '"' || c === "'") {
@@ -179,8 +234,10 @@ function lexJs(src) {
179
234
  if (regexAllowed && i > regexBlockedUntil) {
180
235
  let j = i + 1;
181
236
  let inClass = false;
182
- while (j < n && src.charAt(j) !== '\n') {
237
+ while (j < n && !(0, data_provider_1.isJsLineTerminator)(src.charAt(j))) {
183
238
  const e = src.charAt(j);
239
+ if (e === '\\' && (0, data_provider_1.isJsLineTerminator)(src.charAt(j + 1)))
240
+ break;
184
241
  if (e === '\\') {
185
242
  j += 2;
186
243
  continue;
@@ -214,7 +271,7 @@ function lexJs(src) {
214
271
  regexAllowed = true;
215
272
  }
216
273
  }
217
- else if (LEX_JS_RE_2.test(c) || c > '\u007f') {
274
+ else if (!(0, data_provider_1.isJsLineTerminator)(c) && (LEX_JS_RE_2.test(c) || c > '\u007f')) {
218
275
  let j = i + 1;
219
276
  while (j < n && isIdentChar(src.charAt(j))) {
220
277
  j += 1;
@@ -232,7 +289,7 @@ function lexJs(src) {
232
289
  }
233
290
  else {
234
291
  // Whitespace says nothing about whether a `/` divides or starts a regular expression.
235
- if (!isSpace(src.charCodeAt(i))) {
292
+ if (!isSpace(src.charCodeAt(i)) && !(0, data_provider_1.isJsLineTerminator)(c)) {
236
293
  if (c === '{') {
237
294
  depth += 1;
238
295
  }
@@ -325,19 +382,31 @@ class Collector {
325
382
  constructor(section) {
326
383
  this.section = section;
327
384
  }
328
- add(severity, code, line, message, fix) {
385
+ add(severity, code, line, message, fix, conditional = false, provenance) {
329
386
  this.findings.push({
330
387
  severity,
331
388
  code,
332
389
  section: this.section,
333
- line,
390
+ ...(line === undefined ? {} : { line }),
334
391
  message,
335
392
  ...(fix ? { fix } : {}),
393
+ ...(conditional ? { conditional: true } : {}),
394
+ ...(provenance === undefined ? {} : { provenance }),
336
395
  });
337
396
  }
338
397
  }
398
+ /** Only a complete, safe app entry-file reference gets the app-specific exception.
399
+ * The app resolver still judges whether the file is declared and produces the hard error.
400
+ * This is never enabled for widgets or separately served modules.
401
+ */
402
+ function isAppLocalReference(value, enabled) {
403
+ const trimmed = value.trim();
404
+ return (enabled &&
405
+ trimmed.startsWith(data_provider_1.APP_FILE_REF_SCHEME) &&
406
+ (0, data_provider_1.isSafeAppPath)(trimmed.slice(data_provider_1.APP_FILE_REF_SCHEME.length)));
407
+ }
339
408
  // ── CSS ─────────────────────────────────────────────────────────────────────
340
- function scanCssInto(source, baseLine, out) {
409
+ function scanCssInto(source, baseLine, out, allowAppLocalReferences) {
341
410
  const masked = maskCssComments(source);
342
411
  const lower = asciiLower(masked);
343
412
  const starts = lineStarts(source);
@@ -347,9 +416,13 @@ function scanCssInto(source, baseLine, out) {
347
416
  const end = lower.indexOf(';', i);
348
417
  const statement = masked.slice(i, end === -1 ? undefined : end);
349
418
  const target = SCAN_CSS_INTO_RE.exec(statement);
350
- const kind = target ? classifyUrl(target[1]) : 'relative';
419
+ const kind = target && isAppLocalReference(target[1], allowAppLocalReferences)
420
+ ? 'inline'
421
+ : target
422
+ ? classifyUrl(target[1])
423
+ : 'relative';
351
424
  if (kind === 'external') {
352
- out.add('error', 'external-resource', lineOf(i), '@import of a URL: the frame allows no stylesheet from a URL, so the rules never load.', 'Write the rules inline in this section; there are no web fonts or remote stylesheets.');
425
+ out.add('error', 'external-resource', lineOf(i), '@import of a URL: the frame allows no stylesheet from a URL, so the rules never load.', 'Write the rules inline in this section; remote fonts and stylesheets are unavailable.');
353
426
  }
354
427
  else if (kind !== 'inline') {
355
428
  out.add('warn', 'relative-url', lineOf(i), '@import has nothing to resolve against inside the frame, so it loads nothing.', 'Write the rules inline.');
@@ -361,7 +434,9 @@ function scanCssInto(source, baseLine, out) {
361
434
  const close = masked.indexOf(')', u + 4);
362
435
  const inner = masked.slice(u + 4, close === -1 ? undefined : close).trim();
363
436
  const value = inner.replace(SCAN_CSS_INTO_RE_2, '');
364
- const kind = classifyUrl(value);
437
+ const kind = isAppLocalReference(value, allowAppLocalReferences)
438
+ ? 'inline'
439
+ : classifyUrl(value);
365
440
  if (kind === 'external') {
366
441
  out.add('error', 'external-resource', lineOf(u), 'url() of an external address: img-src and font-src allow only data: and blob: URLs here, so it is blocked.', 'Use inline SVG, a gradient, or a data: URI.');
367
442
  }
@@ -535,12 +610,23 @@ function brokerFetchOffsets(code) {
535
610
  }
536
611
  return offsets;
537
612
  }
538
- function scanJsInto(source, baseLine, out) {
613
+ function scanJsInto(source, baseLine, out, parsedFromHtml = false, sourceLines, sourceId) {
614
+ // HTML parsing and JavaScript both treat CR and CRLF as line breaks; use one
615
+ // form consistently in the lexer, comments, and its source-line lookups.
616
+ source = source.replace(/\r\n?/g, '\n');
539
617
  const { code, commentless, literals } = lexJs(source);
540
618
  const brokerFetches = brokerFetchOffsets(code);
541
- const starts = lineStarts(source);
542
- const lineOf = (index) => baseLine + lineAt(starts, index) - 1;
543
- const codeLines = code.split('\n');
619
+ const starts = (0, data_provider_1.jsLineStarts)(source);
620
+ const lineOf = (index) => {
621
+ const line = lineAt(starts, index);
622
+ return sourceLines === undefined ? baseLine + line - 1 : sourceLines?.[line - 1];
623
+ };
624
+ const addAt = (severity, code, index, message, fix) => {
625
+ const line = lineOf(index);
626
+ const provenance = sourceLines !== undefined ? `${sourceId ?? 'unknown'}:${lineAt(starts, index)}` : undefined;
627
+ out.add(severity, code, line, message, fix, false, provenance);
628
+ };
629
+ const codeLines = code.split(/\r\n?|[\n\u2028\u2029]/);
544
630
  const textual = literals.filter((literal) => literal.kind !== 'regex');
545
631
  const byOpen = new Map(textual.map((literal) => [literal.open, literal]));
546
632
  // What the code does: names and calls, over the code view, where a word inside a
@@ -549,7 +635,7 @@ function scanJsInto(source, baseLine, out) {
549
635
  for (const match of code.matchAll(rule.pattern)) {
550
636
  if (rule.code === 'network-api' && brokerFetches.has(match.index ?? 0))
551
637
  continue;
552
- out.add(rule.severity, rule.code, lineOf(match.index ?? 0), rule.message, rule.fix);
638
+ addAt(rule.severity, rule.code, match.index ?? 0, rule.message, rule.fix);
553
639
  }
554
640
  }
555
641
  // A call or assignment whose argument is a literal that names a URL.
@@ -558,7 +644,7 @@ function scanJsInto(source, baseLine, out) {
558
644
  const open = (match.index ?? 0) + match[0].length - 1;
559
645
  const literal = byOpen.get(open);
560
646
  if (literal && URL_START.test(literal.value)) {
561
- out.add('error', 'external-resource', lineOf(match.index ?? 0), rule.message, rule.fix);
647
+ addAt('error', 'external-resource', match.index ?? 0, rule.message, rule.fix);
562
648
  }
563
649
  }
564
650
  }
@@ -566,7 +652,7 @@ function scanJsInto(source, baseLine, out) {
566
652
  for (const literal of textual) {
567
653
  for (const rule of STRING_RULES) {
568
654
  for (const match of literal.value.matchAll(rule.pattern)) {
569
- out.add('error', 'external-resource', lineOf(literal.start + (match.index ?? 0)), rule.message, rule.fix);
655
+ addAt('error', 'external-resource', literal.start + (match.index ?? 0), rule.message, rule.fix);
570
656
  }
571
657
  }
572
658
  for (const match of literal.value.matchAll(URL_IN_STRING)) {
@@ -576,13 +662,14 @@ function scanJsInto(source, baseLine, out) {
576
662
  if (isNamespaceUrl(url) || SCAN_JS_INTO_RE.test(text)) {
577
663
  continue;
578
664
  }
579
- out.add('warn', 'external-url', lineOf(index), `A URL string (${url.length > 60 ? `${url.slice(0, 57)}...` : url}): the frame can load nothing from a URL.`, `If it is a link, pass it to ${OPEN_LINK}; if it is data or an image, inline it.`);
665
+ addAt('warn', 'external-url', index, `A URL string (${url.length > 60 ? `${url.slice(0, 57)}...` : url}): the frame can load nothing from a URL.`, `If it is a link, pass it to ${OPEN_LINK}; if it is data or an image, inline it.`);
580
666
  }
581
667
  }
582
668
  // The one rule that reads the text as the HTML parser would, and so reads strings too.
583
- if (SCAN_JS_INTO_RE_2.test(commentless)) {
584
- const at = asciiLower(commentless).indexOf('</script');
585
- out.add('warn', 'element-close', lineOf(at), 'The text contains a closing script tag, which can end the script early depending on how the frame embeds it.', 'Write it as <\\/script> inside a string.');
669
+ const closingScript = SCAN_JS_INTO_RE_2.exec(commentless);
670
+ if (closingScript && !parsedFromHtml) {
671
+ const at = closingScript.index;
672
+ addAt('warn', 'element-close', at, 'The text contains a closing script tag, which can end the script early depending on how the frame embeds it.', 'Write it as <\\/script> inside a string.');
586
673
  }
587
674
  }
588
675
  const RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title']);
@@ -594,8 +681,8 @@ function attr(tag, name) {
594
681
  }
595
682
  return undefined;
596
683
  }
597
- /** Walk the markup with indexOf: tags, their attributes, and the text of raw-text elements. */
598
- function walkHtml(html) {
684
+ /** Walk markup for best-effort resource and style heuristics. */
685
+ function walkHtml(html, scriptEnds) {
599
686
  const lower = asciiLower(html);
600
687
  const tags = [];
601
688
  const raws = [];
@@ -675,8 +762,20 @@ function walkHtml(html) {
675
762
  tags.push(tag);
676
763
  i = p;
677
764
  if (RAW_TEXT_ELEMENTS.has(tag.name)) {
678
- const close = lower.indexOf(`</${tag.name}`, p);
679
- const end = close === -1 ? n : close;
765
+ const endTag = `</${tag.name}`;
766
+ let close = lower.indexOf(endTag, p);
767
+ while (close !== -1) {
768
+ const boundary = lower.charAt(close + endTag.length);
769
+ if (boundary === '>' || boundary === '/' || isSpace(boundary.charCodeAt(0)))
770
+ break;
771
+ close = lower.indexOf(endTag, close + endTag.length);
772
+ }
773
+ // The browser's script-data tokenizer, unlike a substring search, keeps
774
+ // </script> inside double-escaped content. Avoid inventing tags there.
775
+ const parsedEnd = tag.name === 'script' ? scriptEnds.get(tag.index) : undefined;
776
+ // An offset from the parser is only an end if it is not before the text it ends: `end < p` would put `i` before this
777
+ // tag again and the walk would revisit it forever (one unclosed `<script>` used to exhaust the heap that way).
778
+ const end = parsedEnd !== undefined && parsedEnd >= p ? parsedEnd : close === -1 ? n : close;
680
779
  raws.push({ tag, content: html.slice(p, end), contentIndex: p });
681
780
  i = end;
682
781
  }
@@ -684,22 +783,93 @@ function walkHtml(html) {
684
783
  return { tags, raws };
685
784
  }
686
785
  const RESOURCE_ATTRIBUTES = ['src', 'srcset', 'poster', 'data', 'background', 'xlink:href', 'href'];
687
- /** The first URL of each `srcset` candidate. */
786
+ /** Decode once in HTML attribute mode and retain the raw source of every UTF-16 unit. */
787
+ function decodedAttribute(value) {
788
+ const parts = [];
789
+ const starts = [];
790
+ const ends = [];
791
+ const plain = (from, to) => {
792
+ parts.push(value.slice(from, to));
793
+ for (let i = from; i < to; i += 1) {
794
+ starts.push(i);
795
+ ends.push(i + 1);
796
+ }
797
+ };
798
+ let output = '';
799
+ const decoder = new decode_1.EntityDecoder(decode_1.htmlDecodeTree, (cp) => {
800
+ output += String.fromCodePoint(cp);
801
+ });
802
+ let position = 0;
803
+ while (position < value.length) {
804
+ const amp = value.indexOf('&', position);
805
+ if (amp < 0) {
806
+ plain(position, value.length);
807
+ break;
808
+ }
809
+ plain(position, amp);
810
+ output = '';
811
+ decoder.startEntity(decode_1.DecodingMode.Attribute);
812
+ let consumed = decoder.write(value, amp + 1);
813
+ if (consumed < 0)
814
+ consumed = decoder.end();
815
+ if (consumed === 0) {
816
+ plain(amp, amp + 1);
817
+ position = amp + 1;
818
+ continue;
819
+ }
820
+ parts.push(output);
821
+ for (let i = 0; i < output.length; i += 1) {
822
+ starts.push(amp);
823
+ ends.push(amp + consumed);
824
+ }
825
+ position = amp + consumed;
826
+ }
827
+ return { text: parts.join(''), starts, ends };
828
+ }
829
+ /** Extract candidate URLs and offsets without treating data URL commas as delimiters. */
688
830
  function srcsetUrls(value) {
689
- return value
690
- .split(',')
691
- .map((candidate) => candidate.trim().split(SRCSET_URLS_RE)[0])
692
- .filter(Boolean);
831
+ const urls = [];
832
+ let i = 0;
833
+ while (i < value.length) {
834
+ while (i < value.length && (value[i] === ',' || SRCSET_SPACE_RE.test(value[i])))
835
+ i += 1;
836
+ const start = i;
837
+ while (i < value.length && !SRCSET_SPACE_RE.test(value[i]))
838
+ i += 1;
839
+ const token = value.slice(start, i);
840
+ let end = token.length;
841
+ while (end > 0 && token[end - 1] === ',')
842
+ end -= 1;
843
+ const url = token.slice(0, end);
844
+ if (url)
845
+ urls.push({ url, start, end: start + end });
846
+ if (url.length !== token.length)
847
+ continue;
848
+ // Skip descriptors through the next candidate separator. A comma in a
849
+ // parenthesized descriptor is not a separator; malformed descriptors are
850
+ // still scanned conservatively rather than being treated as trusted URLs.
851
+ let inParens = false;
852
+ while (i < value.length) {
853
+ const char = value[i++];
854
+ if (char === '(')
855
+ inParens = true;
856
+ else if (char === ')')
857
+ inParens = false;
858
+ else if (char === ',' && !inParens)
859
+ break;
860
+ }
861
+ }
862
+ return urls;
693
863
  }
694
864
  const STYLESHEET_LIKE_REL = /\b(?:stylesheet|preload|modulepreload|prefetch|icon|manifest)\b/i;
695
- function scanTag(tag, line, out) {
865
+ function scanTag(tag, line, out, allowAppLocalReferences) {
696
866
  const name = tag.name;
697
867
  if (name === 'base') {
698
868
  out.add('error', 'base-element', line, 'The base element is blocked: base-uri is none in the frame.', 'Remove it; use absolute data: URIs or none at all.');
699
869
  return;
700
870
  }
701
871
  if (name === 'meta') {
702
- const equiv = asciiLower(attr(tag, 'http-equiv') ?? '').trim();
872
+ const equiv = asciiLower((0, entities_1.decodeHTMLAttribute)(attr(tag, 'http-equiv') ?? '')).trim();
703
873
  if (equiv === 'refresh') {
704
874
  out.add('error', 'navigation', line, 'A meta refresh navigates the frame itself: the host allows one load and removes the widget on the second.', 'Remove it; update the page with script instead.');
705
875
  }
@@ -716,7 +886,7 @@ function scanTag(tag, line, out) {
716
886
  return;
717
887
  }
718
888
  if (name === 'iframe' || name === 'frame') {
719
- const src = attr(tag, 'src') ?? '';
889
+ const src = (0, entities_1.decodeHTMLAttribute)(attr(tag, 'src') ?? '');
720
890
  const external = classifyUrl(src) === 'external';
721
891
  out.add(external ? 'error' : 'warn', 'nested-frame', line, external
722
892
  ? `<${name}> of a URL: frame-src is none in the frame, so it is blocked.`
@@ -728,17 +898,18 @@ function scanTag(tag, line, out) {
728
898
  out.add('error', 'form-action', line, 'formaction: form-action is none in the frame, so submitting is blocked.', 'Handle the click in script.');
729
899
  }
730
900
  if (name === 'a' || name === 'area') {
731
- const href = attr(tag, 'href');
901
+ const rawHref = attr(tag, 'href');
902
+ const href = rawHref === undefined ? undefined : (0, entities_1.decodeHTMLAttribute)(rawHref);
732
903
  if (href !== undefined && classifyUrl(href) === 'external') {
733
904
  out.add('warn', 'external-link', line, 'A link to a URL: following it would navigate the frame itself, and the host removes the widget on that second load.', `Use a button that calls ${OPEN_LINK}.`);
734
905
  }
735
- const target = asciiLower(attr(tag, 'target') ?? '').trim();
906
+ const target = asciiLower((0, entities_1.decodeHTMLAttribute)(attr(tag, 'target') ?? '')).trim();
736
907
  if (target === '_blank' || target === '_top' || target === '_parent') {
737
908
  out.add('warn', 'popup', line, `target="${target}": the sandbox has no allow-popups or top navigation, so nothing opens.`, `Use ${OPEN_LINK}.`);
738
909
  }
739
910
  return;
740
911
  }
741
- const rel = attr(tag, 'rel') ?? '';
912
+ const rel = (0, entities_1.decodeHTMLAttribute)(attr(tag, 'rel') ?? '');
742
913
  for (const attribute of RESOURCE_ATTRIBUTES) {
743
914
  const value = attr(tag, attribute);
744
915
  if (value === undefined) {
@@ -750,10 +921,22 @@ function scanTag(tag, line, out) {
750
921
  if (attribute === 'data' && name !== 'object') {
751
922
  continue;
752
923
  }
753
- for (const url of attribute === 'srcset' ? srcsetUrls(value) : [value]) {
754
- const kind = classifyUrl(url);
924
+ // HTML decodes character references before interpreting resource URLs. Only
925
+ // exempt literal app references: the package resolver reads the raw source
926
+ // and cannot promise to replace a reference written using entities.
927
+ const decoded = decodedAttribute(value);
928
+ const trimmed = decoded.text.trim();
929
+ const leading = decoded.text.length - decoded.text.trimStart().length;
930
+ const candidates = attribute === 'srcset'
931
+ ? srcsetUrls(decoded.text)
932
+ : [{ url: trimmed, start: leading, end: leading + trimmed.length }];
933
+ for (const { url, start, end } of candidates) {
934
+ const raw = end > start ? value.slice(decoded.starts[start], decoded.ends[end - 1]) : '';
935
+ const kind = isAppLocalReference(url, allowAppLocalReferences && raw === url)
936
+ ? 'inline'
937
+ : classifyUrl(url);
755
938
  if (kind === 'external' && !isNamespaceUrl(url)) {
756
- out.add('error', 'external-resource', line, `<${name} ${attribute}> loads from a URL: the frame allows no script, stylesheet, image or font from a URL.`, 'Inline it: markup, inline SVG, canvas, or a data: URI. Libraries come only by bare name through a dynamic import.');
939
+ out.add('error', 'external-resource', line, `<${name} ${attribute}> loads from a URL: the frame allows no script, stylesheet, image or font from a URL.`, 'Inline it: markup, inline SVG, canvas, or a data: URI. Use approved libraries by bare name.');
757
940
  }
758
941
  else if (kind === 'relative' && name !== 'a' && attribute !== 'href') {
759
942
  out.add('warn', 'relative-url', line, `<${name} ${attribute}> is a relative path, which has nothing to resolve against inside the frame.`, 'Inline it or use a data: URI.');
@@ -761,44 +944,88 @@ function scanTag(tag, line, out) {
761
944
  }
762
945
  }
763
946
  }
764
- function isClassicScript(tag) {
765
- const type = asciiLower(attr(tag, 'type') ?? '')
766
- .trim()
767
- .split(';')[0];
768
- return (type === '' ||
769
- type === 'text/javascript' ||
770
- type === 'application/javascript' ||
771
- type === 'text/ecmascript' ||
772
- type === 'application/ecmascript');
773
- }
774
- function isScannableScript(tag) {
775
- return isClassicScript(tag) || asciiLower(attr(tag, 'type') ?? '').trim() === 'module';
776
- }
777
- function scanHtmlInto(html, out) {
778
- const masked = maskHtmlComments(html);
947
+ function scanHtmlInto(html, out, allowAppLocalReferences) {
779
948
  const starts = lineStarts(html);
780
- const { tags, raws } = walkHtml(masked);
949
+ // walkHtml skips real markup comments while preserving script/style raw text;
950
+ // globally masking comments would erase `<!--` inside JavaScript strings.
951
+ const parsed = (0, data_provider_1.analyzeAppHtml)(html);
952
+ const parsedScripts = parsed.scripts;
953
+ const activeElements = new Map(parsed.elements.map((element) => [element.start, element.active]));
954
+ const { tags, raws } = walkHtml(html, new Map(parsedScripts.map((script) => [script.start, script.end])));
781
955
  const inlineScripts = [];
782
- for (const tag of tags) {
783
- scanTag(tag, lineAt(starts, tag.index), out);
784
- const style = attr(tag, 'style');
785
- if (style) {
786
- scanCssInto(style, lineAt(starts, tag.index), out);
956
+ const inlineModules = [];
957
+ let inlineCoverageComplete = true;
958
+ // Defer dormant findings so an active finding on the same line and with the
959
+ // same code wins deduplication even when both have warning severity.
960
+ const conditionalFindings = [];
961
+ const scanMarkupPart = (active, scan) => {
962
+ if (active) {
963
+ scan(out);
964
+ return;
787
965
  }
966
+ const conditional = new Collector('html');
967
+ scan(conditional);
968
+ for (const finding of conditional.findings) {
969
+ conditionalFindings.push({
970
+ ...finding,
971
+ severity: 'warn',
972
+ message: `${TEMPLATE_CONDITION}${finding.message}`,
973
+ });
974
+ }
975
+ };
976
+ for (const tag of tags) {
977
+ scanMarkupPart(activeElements.get(tag.index) !== false, (collector) => {
978
+ scanTag(tag, lineAt(starts, tag.index), collector, allowAppLocalReferences);
979
+ const style = attr(tag, 'style');
980
+ if (style)
981
+ scanCssInto(style, lineAt(starts, tag.index), collector, allowAppLocalReferences);
982
+ });
788
983
  }
789
984
  for (const raw of raws) {
790
985
  const line = lineAt(starts, raw.contentIndex);
791
986
  if (raw.tag.name === 'style') {
792
- scanCssInto(raw.content, line, out);
987
+ scanMarkupPart(activeElements.get(raw.tag.index) !== false, (collector) => scanCssInto(raw.content, line, collector, allowAppLocalReferences));
793
988
  }
794
- else if (raw.tag.name === 'script' && isScannableScript(raw.tag)) {
795
- scanJsInto(raw.content, line, out);
796
- if (isClassicScript(raw.tag) && raw.content.trim() !== '') {
797
- inlineScripts.push({ content: raw.content, line });
798
- }
989
+ }
990
+ // Script content must come from the HTML tokenizer, not the heuristic walker:
991
+ // a literal </script> can occur in script-data's double-escaped state.
992
+ for (const script of parsedScripts) {
993
+ // A foreign attribute such as xlink:type is not the DOM's "type" attribute.
994
+ const get = (name) => script.attributes.find((a) => a.name === name && !a.prefix && !a.namespace)?.value;
995
+ if (get('src') !== undefined || !script.content.trim())
996
+ continue;
997
+ const originalType = get('type') ?? '';
998
+ let type = asciiLower(originalType).trim();
999
+ // The frame also activates its inert marker if it was present in the input.
1000
+ if (originalType === 'text/x-skrr-inert')
1001
+ type = asciiLower(get('data-skrr-type') ?? '').trim();
1002
+ const module = type === 'module';
1003
+ const classicType = type.split(';')[0].trim();
1004
+ const classic = classicType === '' ||
1005
+ classicType === 'text/javascript' ||
1006
+ classicType === 'application/javascript' ||
1007
+ classicType === 'text/ecmascript' ||
1008
+ classicType === 'application/ecmascript';
1009
+ if (!classic && !module)
1010
+ continue;
1011
+ if (!script.active) {
1012
+ inlineCoverageComplete = false;
1013
+ continue;
799
1014
  }
1015
+ const line = lineAt(starts, script.offset);
1016
+ scanJsInto(script.content, line, out, true, script.sourceLines, script.start);
1017
+ if (script.sourceLines === null)
1018
+ out.add('warn', 'source-line-unavailable', undefined, 'Exact HTML source lines are unavailable for this script because parsing changed its text.');
1019
+ (module ? inlineModules : inlineScripts).push({
1020
+ content: script.content,
1021
+ line,
1022
+ sourceLines: script.sourceLines,
1023
+ });
1024
+ }
1025
+ for (const finding of conditionalFindings) {
1026
+ out.add(finding.severity, finding.code, finding.line, finding.message, finding.fix, true);
800
1027
  }
801
- return inlineScripts;
1028
+ return { inlineScripts, inlineModules, inlineCoverageComplete };
802
1029
  }
803
1030
  // ── entry point ─────────────────────────────────────────────────────────────
804
1031
  /** Findings per (section, code) before the rest collapse into one line. */
@@ -809,7 +1036,7 @@ function tidy(findings) {
809
1036
  // recognise the same call must not report it twice.
810
1037
  const best = new Map();
811
1038
  for (const f of findings) {
812
- const key = `${f.section}:${f.line}:${f.code}`;
1039
+ const key = `${f.section}:${f.provenance ?? f.line ?? 'unknown'}:${f.code}`;
813
1040
  const held = best.get(key);
814
1041
  if (!held || SEVERITY_RANK[f.severity] > SEVERITY_RANK[held.severity]) {
815
1042
  best.set(key, f);
@@ -817,10 +1044,16 @@ function tidy(findings) {
817
1044
  }
818
1045
  // A generic URL warning on a line that already has the specific error is noise.
819
1046
  const resourceLines = new Set([...best.values()]
820
- .filter((f) => f.code === 'external-resource')
821
- .map((f) => `${f.section}:${f.line}`));
822
- const kept = [...best.values()].filter((f) => !(f.code === 'external-url' && resourceLines.has(`${f.section}:${f.line}`)));
823
- kept.sort((a, b) => a.section.localeCompare(b.section) || a.line - b.line);
1047
+ .filter((f) => f.code === 'external-resource' && !f.conditional)
1048
+ .map((f) => `${f.section}:${f.provenance ?? f.line ?? 'unknown'}`));
1049
+ const kept = [...best.values()].filter((f) => !(f.code === 'external-url' &&
1050
+ resourceLines.has(`${f.section}:${f.provenance ?? f.line ?? 'unknown'}`)));
1051
+ // Keep the most serious occurrences before applying the per-code cap. A
1052
+ // conditional warning must not displace a later active error from the list.
1053
+ kept.sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] ||
1054
+ Number(Boolean(a.conditional)) - Number(Boolean(b.conditional)) ||
1055
+ a.section.localeCompare(b.section) ||
1056
+ (a.line ?? 0) - (b.line ?? 0));
824
1057
  const seen = new Map();
825
1058
  const out = [];
826
1059
  const dropped = new Map();
@@ -848,22 +1081,31 @@ function tidy(findings) {
848
1081
  const { count, ...rest } = entry;
849
1082
  out.push({ ...rest, message: `...and ${count} more of the same kind in ${rest.section}.` });
850
1083
  }
851
- return out;
1084
+ return out
1085
+ .sort((a, b) => a.section.localeCompare(b.section) || (a.line ?? 0) - (b.line ?? 0))
1086
+ .map((finding) => {
1087
+ const publicFinding = { ...finding };
1088
+ delete publicFinding.conditional;
1089
+ delete publicFinding.provenance;
1090
+ return publicFinding;
1091
+ });
852
1092
  }
853
1093
  /**
854
- * Scan one widget's three sections. Pure and total: it never throws and reads
855
- * only the strings it is given; the cost is linear in their length, which the
856
- * caller has already bounded by the widget limits.
1094
+ * Scan one widget's three sections without executing author code. The caller
1095
+ * must bound inputs and treat parser failures as an incomplete scan.
857
1096
  */
858
- function scanWidgetSource(source) {
1097
+ function scanWidgetSource(source, options = {}) {
859
1098
  const css = new Collector('css');
860
1099
  const html = new Collector('html');
861
1100
  const js = new Collector('js');
862
- scanCssInto(source.css, 1, css);
863
- const inlineScripts = scanHtmlInto(source.html, html);
1101
+ const allowAppLocalReferences = options.allowAppLocalReferences === true;
1102
+ scanCssInto(source.css, 1, css, allowAppLocalReferences);
1103
+ const { inlineScripts, inlineModules, inlineCoverageComplete } = scanHtmlInto(source.html, html, allowAppLocalReferences);
864
1104
  scanJsInto(source.js, 1, js);
865
1105
  return {
866
1106
  findings: tidy([...css.findings, ...html.findings, ...js.findings]),
867
1107
  inlineScripts,
1108
+ inlineModules,
1109
+ inlineCoverageComplete,
868
1110
  };
869
1111
  }