tolkira 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
+ import { realpathSync } from "node:fs";
4
5
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
5
6
  import path4 from "node:path";
6
- import { pathToFileURL } from "node:url";
7
+ import { fileURLToPath } from "node:url";
7
8
  import { parseArgs } from "node:util";
8
9
 
9
10
  // src/input/load.ts
@@ -431,7 +432,7 @@ function parseLegacyValue(parsed, source, options = {}) {
431
432
  );
432
433
  for (const [scenarioIndex, element] of scenarios.entries()) {
433
434
  const scenarioId = nextId("scenario");
434
- const scenarioTags = mapTags(element.tags, nextId);
435
+ const scenarioTags2 = mapTags(element.tags, nextId);
435
436
  const scenarioSteps = (element.steps ?? []).filter((step) => !isHook(step));
436
437
  const stepNodes = scenarioSteps.map((step) => mapStep(step, nextId));
437
438
  const backgroundInline = backgroundSteps.length > 0 && backgroundSteps.every(
@@ -444,7 +445,7 @@ function parseLegacyValue(parsed, source, options = {}) {
444
445
  const scenario = {
445
446
  id: scenarioId,
446
447
  location: location(element.line),
447
- tags: scenarioTags,
448
+ tags: scenarioTags2,
448
449
  keyword: (element.keyword ?? "Scenario").trim() || "Scenario",
449
450
  name: element.name ?? `Scenario ${scenarioIndex + 1}`,
450
451
  description: normalizeText(element.description),
@@ -472,7 +473,7 @@ function parseLegacyValue(parsed, source, options = {}) {
472
473
  name: scenario.name,
473
474
  language: "en",
474
475
  steps: pickleSteps,
475
- tags: [...featureTags, ...scenarioTags].map((tag) => ({
476
+ tags: [...featureTags, ...scenarioTags2].map((tag) => ({
476
477
  name: tag.name,
477
478
  astNodeId: tag.id
478
479
  })),
@@ -684,6 +685,118 @@ function secondsToNanoseconds(value) {
684
685
  const seconds = Number(value);
685
686
  return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1e9) : 0;
686
687
  }
688
+ function isXmlChar(code) {
689
+ return code === 9 || code === 10 || code === 13 || code >= 32 && code <= 55295 || code >= 57344 && code <= 65533 || code >= 65536 && code <= 1114111;
690
+ }
691
+ function checkEntityReferences(fragment, source, allowedNames) {
692
+ const entityPattern = /&([^;]{1,32});/g;
693
+ let match;
694
+ while ((match = entityPattern.exec(fragment)) !== null) {
695
+ const entity = match[1];
696
+ if (entity === "amp" || entity === "lt" || entity === "gt" || entity === "quot" || entity === "apos" || allowedNames.has(entity)) {
697
+ continue;
698
+ }
699
+ let code;
700
+ if (/^#\d+$/.test(entity)) {
701
+ code = Number.parseInt(entity.slice(1), 10);
702
+ } else if (/^#x[0-9a-fA-F]+$/.test(entity)) {
703
+ code = Number.parseInt(entity.slice(2), 16);
704
+ }
705
+ if (code === void 0 || !Number.isFinite(code) || !isXmlChar(code)) {
706
+ throw new Error(
707
+ `Invalid JUnit XML in ${source}: invalid entity reference &${entity};`
708
+ );
709
+ }
710
+ }
711
+ }
712
+ function assertValidEntities(content, source) {
713
+ const allowedNames = /* @__PURE__ */ new Set();
714
+ const scanTag = (start) => {
715
+ let index2 = start + 1;
716
+ let quote = "";
717
+ let valueStart = 0;
718
+ while (index2 < content.length) {
719
+ const char = content[index2];
720
+ if (quote) {
721
+ if (char === quote) {
722
+ checkEntityReferences(
723
+ content.slice(valueStart, index2),
724
+ source,
725
+ allowedNames
726
+ );
727
+ quote = "";
728
+ }
729
+ } else if (char === '"' || char === "'") {
730
+ quote = char;
731
+ valueStart = index2 + 1;
732
+ } else if (char === ">") {
733
+ return index2 + 1;
734
+ }
735
+ index2 += 1;
736
+ }
737
+ return index2;
738
+ };
739
+ const scanDoctype = (start) => {
740
+ let index2 = start + "<!DOCTYPE".length;
741
+ let quote = "";
742
+ let depth = 0;
743
+ while (index2 < content.length) {
744
+ const char = content[index2];
745
+ if (quote) {
746
+ if (char === quote) quote = "";
747
+ } else if (char === '"' || char === "'") {
748
+ quote = char;
749
+ } else if (char === "[") {
750
+ depth += 1;
751
+ } else if (char === "]") {
752
+ depth -= 1;
753
+ } else if (char === ">" && depth <= 0) {
754
+ const doctype = content.slice(start, index2 + 1);
755
+ for (const entity of doctype.matchAll(
756
+ /<!ENTITY\s+([A-Za-z_:][\w.:-]*)/g
757
+ )) {
758
+ const name = entity[1];
759
+ if (name) allowedNames.add(name);
760
+ }
761
+ return index2 + 1;
762
+ }
763
+ index2 += 1;
764
+ }
765
+ return index2;
766
+ };
767
+ let index = 0;
768
+ while (index < content.length) {
769
+ const start = content.indexOf("<", index);
770
+ if (start === -1) {
771
+ checkEntityReferences(content.slice(index), source, allowedNames);
772
+ return;
773
+ }
774
+ if (start > index) {
775
+ checkEntityReferences(
776
+ content.slice(index, start),
777
+ source,
778
+ allowedNames
779
+ );
780
+ }
781
+ if (content.startsWith("<!--", start)) {
782
+ const end = content.indexOf("-->", start + 4);
783
+ index = end === -1 ? content.length : end + 3;
784
+ } else if (content.startsWith("<![CDATA[", start)) {
785
+ const end = content.indexOf("]]>", start + 9);
786
+ index = end === -1 ? content.length : end + 3;
787
+ } else if (content.startsWith("<?", start)) {
788
+ const end = content.indexOf("?>", start + 2);
789
+ index = end === -1 ? content.length : end + 2;
790
+ } else if (content.startsWith("<!DOCTYPE", start)) {
791
+ index = scanDoctype(start);
792
+ } else if (content.startsWith("<!", start)) {
793
+ const end = content.indexOf(">", start + 2);
794
+ index = end === -1 ? content.length : end + 1;
795
+ } else {
796
+ index = scanTag(start);
797
+ }
798
+ }
799
+ }
687
800
  function collectSuites(parsed) {
688
801
  if (!isObject(parsed)) return [];
689
802
  const suites = [];
@@ -720,18 +833,21 @@ ${text}`;
720
833
  return text || attribute;
721
834
  }
722
835
  function elementFromTestcase(testcase, index) {
723
- const failure = [...asArray(testcase.failure), ...asArray(testcase.error)].find(
724
- isObject
725
- );
836
+ const failures = [
837
+ ...asArray(testcase.failure),
838
+ ...asArray(testcase.error)
839
+ ];
840
+ const failure = failures[0];
841
+ const hasFailure = failure !== void 0;
726
842
  const skipped = asArray(testcase.skipped).length > 0;
727
- const status = failure ? "failed" : skipped ? "skipped" : "passed";
843
+ const status = hasFailure ? "failed" : skipped ? "skipped" : "passed";
728
844
  const name = stringOf(testcase.name) || stringOf(testcase.classname) || `Test ${index + 1}`;
729
845
  const result = {
730
846
  status,
731
847
  duration: secondsToNanoseconds(testcase.time)
732
848
  };
733
- if (failure) {
734
- const message = failureMessage(failure);
849
+ if (hasFailure) {
850
+ const message = isObject(failure) ? failureMessage(failure) : textOf(failure).trim();
735
851
  if (message) result.error_message = message;
736
852
  }
737
853
  const embeddings = [];
@@ -778,12 +894,22 @@ function looksLikeJUnit(content) {
778
894
  return trimmed.startsWith("<") && /<testsuites?\b/i.test(trimmed);
779
895
  }
780
896
  async function parseJUnitXml(content, source) {
781
- const { XMLParser } = await import("fast-xml-parser");
897
+ const { XMLParser, XMLValidator } = await import("fast-xml-parser");
898
+ assertValidEntities(content, source);
899
+ const validation = XMLValidator.validate(content);
900
+ if (validation !== true) {
901
+ const line = Number.isFinite(validation.err.line) ? validation.err.line : 1;
902
+ const column = Number.isFinite(validation.err.col) ? validation.err.col : 1;
903
+ throw new Error(
904
+ `Invalid JUnit XML in ${source} at line ${line}, column ${column}: ${validation.err.msg}`
905
+ );
906
+ }
782
907
  const parser = new XMLParser({
783
908
  ignoreAttributes: false,
784
909
  attributeNamePrefix: "",
785
910
  parseTagValue: false,
786
911
  parseAttributeValue: false,
912
+ htmlEntities: true,
787
913
  isArray: (name) => ARRAY_TAGS.has(name)
788
914
  });
789
915
  let parsed;
@@ -2047,9 +2173,10 @@ var REPORT_CSS = `:root {
2047
2173
  html { background: var(--paper); scroll-padding-top: 4.5rem; scrollbar-gutter: stable; }
2048
2174
  body { margin: 0; color: var(--ink); background: var(--paper); font: 0.9375rem/1.55 var(--font-sans); -webkit-font-smoothing: antialiased; caret-color: var(--accent); }
2049
2175
  ::selection { background: color-mix(in oklab, var(--accent) 24%, transparent); }
2176
+ ::highlight(tolkira-search) { background-color: color-mix(in oklab, var(--accent) 42%, var(--paper)); color: var(--ink); }
2050
2177
  :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
2051
2178
  a { color: var(--accent-text); text-underline-offset: 0.16em; }
2052
- button, input { font: inherit; }
2179
+ button, input, select { font: inherit; }
2053
2180
  button { cursor: pointer; }
2054
2181
  img, video { max-width: 100%; height: auto; }
2055
2182
  .shell { max-width: 1320px; margin: 0 auto; padding: 0 2rem 6rem; container-type: inline-size; }
@@ -2084,6 +2211,10 @@ img, video { max-width: 100%; height: auto; }
2084
2211
  .search { flex: 1 1 18.75rem; display: flex; align-items: center; gap: 0.5rem; min-height: 2.125rem; padding: 0 0.625rem; border: 1px solid var(--line-strong); border-radius: var(--radius-control); background: var(--surface-3); }
2085
2212
  .search input { width: 100%; min-height: 2rem; border: 0; outline: 0; background: transparent; color: var(--ink); font-size: 0.875rem; }
2086
2213
  .search:focus-within { outline: 2px solid var(--accent); outline-offset: 1px; }
2214
+ .tagFilter { display: flex; align-items: center; gap: 0.375rem; min-height: 2.125rem; max-width: 100%; }
2215
+ .tagFilter > span { color: var(--muted); font-size: 0.75rem; }
2216
+ .tagFilter select { max-width: 100%; min-width: 0; min-height: 1.875rem; padding: 0 1.5rem 0 0.5rem; border: 1px solid var(--line-strong); border-radius: var(--radius-control); background: var(--paper); color: var(--ink-2); font-size: 0.75rem; }
2217
+ .tagFilter select:hover { color: var(--ink); }
2087
2218
  .filters { display: flex; gap: 0.375rem; flex-wrap: wrap; }
2088
2219
  .filter { min-height: 1.875rem; padding: 0 0.5625rem; border: 1px solid var(--line-strong); border-radius: var(--radius-control); background: var(--paper); color: var(--ink-2); font-size: 0.75rem; }
2089
2220
  .filter b { margin-left: 0.25rem; font-family: var(--font-mono); font-weight: 500; font-variant-numeric: tabular-nums; }
@@ -2126,6 +2257,9 @@ details[open] > summary.scenarioButton { background: var(--accent-soft); }
2126
2257
  .rowRight { color: var(--muted); font-family: var(--font-mono); font-size: 0.75rem; text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
2127
2258
  .detailInline { padding: 0.25rem 0 1.125rem 13rem; background: var(--surface-2); border-top: 1px solid var(--line); }
2128
2259
  .detailInline h4 { margin: 0.875rem 0 0.375rem; color: var(--muted); font-size: 0.8125rem; font-weight: 600; }
2260
+ .stepsHead { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.5rem 0.75rem; }
2261
+ .copyFailure { min-height: 1.75rem; padding: 0 0.5625rem; border: 1px solid var(--line-strong); border-radius: var(--radius-control); background: var(--paper); color: var(--ink-2); font-size: 0.6875rem; }
2262
+ .copyFailure:hover { border-color: var(--accent); background: var(--accent-soft); color: var(--ink); }
2129
2263
  .description { margin: 0.625rem 0 0; color: var(--muted); font-size: 0.875rem; line-height: 1.55; white-space: pre-line; }
2130
2264
  .steps { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--line); }
2131
2265
  .step { display: grid; grid-template-columns: 0.875rem minmax(0, 1fr) auto; gap: 0.5rem; padding: 0.4375rem 0; border-bottom: 1px solid var(--line); font-size: 0.8125rem; }
@@ -2233,6 +2367,7 @@ details[open] > summary.scenarioButton { background: var(--accent-soft); }
2233
2367
  @media (forced-colors: active) {
2234
2368
  .chev { background-color: CanvasText; }
2235
2369
  .stepMarker { border-color: CanvasText; color: CanvasText; }
2370
+ ::highlight(tolkira-search) { background-color: Highlight; color: HighlightText; }
2236
2371
  }
2237
2372
  @media (prefers-color-scheme: dark) {
2238
2373
  :root {
@@ -2341,6 +2476,11 @@ function renderAttachment(attachment, context) {
2341
2476
  }
2342
2477
  return `<span class="fileLink">${name} (${media}, ${attachment.bytes} bytes)</span>`;
2343
2478
  }
2479
+ function scenarioTags(model) {
2480
+ return [...new Set(model.scenarios.flatMap((scenario) => scenario.tags))].sort(
2481
+ (a, b) => a.localeCompare(b)
2482
+ );
2483
+ }
2344
2484
  function renderStep(step, scenarioName) {
2345
2485
  const docString = step.docString ? `<pre class="docString">${escapeHtml(step.docString)}</pre>` : "";
2346
2486
  const table = step.dataTable ? `<div class="tableWrap" tabindex="0" role="region" aria-label="Data table for: ${escapeHtml(step.text)}"><table class="dataTable"><tbody>${step.dataTable.map(
@@ -2351,7 +2491,7 @@ function renderStep(step, scenarioName) {
2351
2491
  const error = step.message ? `<pre class="error">${escapeHtml(step.message)}</pre>` : "";
2352
2492
  const context = `${scenarioName}: ${step.keyword.trim()} ${step.text}`;
2353
2493
  const attachments = step.attachments.map((attachment) => renderAttachment(attachment, context)).join("");
2354
- return `<li class="step"><span class="stepMarker ${statusClass(step.status)}"><span aria-hidden="true">${STEP_GLYPHS[step.status]}</span><span class="sr">${statusLabel(step.status)}</span></span><div><span class="kw">${escapeHtml(step.keyword)}</span> ${escapeHtml(step.text)}${error}${docString}${table}${attachments}</div><span class="dur">${durationLabel(step.durationMs)}</span></li>`;
2494
+ return `<li class="step"${step.status === "failed" ? ' data-status="failed"' : ""}><span class="stepMarker ${statusClass(step.status)}"><span aria-hidden="true">${STEP_GLYPHS[step.status]}</span><span class="sr">${statusLabel(step.status)}</span></span><div><span class="kw">${escapeHtml(step.keyword)}</span> ${escapeHtml(step.text)}${error}${docString}${table}${attachments}</div><span class="dur">${durationLabel(step.durationMs)}</span></li>`;
2355
2495
  }
2356
2496
  function scenarioText(scenario) {
2357
2497
  return [
@@ -2372,7 +2512,8 @@ function renderScenario(scenario) {
2372
2512
  const steps = scenario.steps.map((step) => renderStep(step, scenario.name)).join("");
2373
2513
  const description = scenario.description ? `<p class="description">${escapeHtml(scenario.description)}</p>` : "";
2374
2514
  const extraAttachments = scenario.extraAttachments.length ? `<h4>Attachments</h4>${scenario.extraAttachments.map((attachment) => renderAttachment(attachment, scenario.name)).join("")}` : "";
2375
- return `<details class="scenario" data-scenario data-status="${scenario.status}" data-search="${escapeHtml(scenarioText(scenario))}" ${open ? "open" : ""}><summary class="scenarioButton"><span class="statusCell"><span class="statusText ${statusClass(scenario.status)}">${statusLabel(scenario.status)}</span></span><span class="thumbCell">${image ? `<img class="thumb" src="${escapeHtml(image.dataUri ?? "")}" alt="" loading="lazy">` : ""}</span><span class="scenarioMain"><h3 class="scenarioName">${escapeHtml(scenario.name)}</h3><span class="scenarioSub">${scenario.steps.length} step${scenario.steps.length === 1 ? "" : "s"}${scenario.tags.length ? ` <span class="tags">${scenario.tags.map((tag) => `<span class="tag">${escapeHtml(tag)}</span>`).join("")}</span>` : ""}</span></span><span class="rowRight">${durationLabel(scenario.durationMs)}${scenario.attachments.length ? `<br>${scenario.attachments.length} attachment${scenario.attachments.length === 1 ? "" : "s"}` : ""}</span><span class="chev" aria-hidden="true"></span></summary><div class="detailInline">${description}<h4>Steps</h4><ol class="steps">${steps}</ol>${extraAttachments}<div class="detailMeta"><span>Feature: ${escapeHtml(scenario.featureName)}</span><span>Attempt: ${scenario.attempt + 1}</span>${scenario.startedAt ? `<span>Started: ${dateLabel(scenario.startedAt)}</span>` : ""}${scenario.ruleName ? `<span>Rule: ${escapeHtml(scenario.ruleName)}</span>` : ""}</div></div></details>`;
2515
+ const copyFailure = scenario.status === "failed" ? '<button class="copyFailure" type="button" data-copy-failure>Copy failure</button>' : "";
2516
+ return `<details class="scenario" data-scenario data-status="${scenario.status}" data-uri="${escapeHtml(scenario.uri)}" data-tags="${escapeHtml(scenario.tags.join(" "))}" data-search="${escapeHtml(scenarioText(scenario))}" ${open ? "open" : ""}><summary class="scenarioButton"><span class="statusCell"><span class="statusText ${statusClass(scenario.status)}">${statusLabel(scenario.status)}</span></span><span class="thumbCell">${image ? `<img class="thumb" src="${escapeHtml(image.dataUri ?? "")}" alt="" loading="lazy">` : ""}</span><span class="scenarioMain"><h3 class="scenarioName">${escapeHtml(scenario.name)}</h3><span class="scenarioSub">${scenario.steps.length} step${scenario.steps.length === 1 ? "" : "s"}${scenario.tags.length ? ` <span class="tags">${scenario.tags.map((tag) => `<span class="tag">${escapeHtml(tag)}</span>`).join("")}</span>` : ""}</span></span><span class="rowRight">${durationLabel(scenario.durationMs)}${scenario.attachments.length ? `<br>${scenario.attachments.length} attachment${scenario.attachments.length === 1 ? "" : "s"}` : ""}</span><span class="chev" aria-hidden="true"></span></summary><div class="detailInline">${description}<div class="stepsHead"><h4>Steps</h4>${copyFailure}</div><ol class="steps">${steps}</ol>${extraAttachments}<div class="detailMeta"><span>Feature: ${escapeHtml(scenario.featureName)}</span><span>Attempt: ${scenario.attempt + 1}</span>${scenario.startedAt ? `<span>Started: ${dateLabel(scenario.startedAt)}</span>` : ""}${scenario.ruleName ? `<span>Rule: ${escapeHtml(scenario.ruleName)}</span>` : ""}</div></div></details>`;
2376
2517
  }
2377
2518
  function renderFeature(feature) {
2378
2519
  const passed = feature.scenarios.filter((scenario) => scenario.status === "passed").length;
@@ -2394,9 +2535,11 @@ function renderReportView(model, options) {
2394
2535
  const meta = metadataLine(options.metadata);
2395
2536
  const date = dateLabel(model.startedAt);
2396
2537
  const features = model.features.map((feature) => renderFeature(feature)).join("");
2397
- return `<div class="tabPanel" id="report-view" role="tabpanel" aria-labelledby="view-report" tabindex="0"><main class="shell"><header class="runHead"><div><p class="path">${escapeHtml(model.source)} / ${escapeHtml(options.title)}</p><h1>${escapeHtml(options.title)}</h1><p class="meta">${date ? `<span>${date}</span>` : ""}<span>${model.counts.features} feature${model.counts.features === 1 ? "" : "s"}</span><span>${model.counts.scenarios.total} scenarios</span><span>${escapeHtml(model.source)}</span>${meta}</p></div><div class="health"><div class="healthTop"><strong>${percent}%</strong><span>${passed} of ${total} passed</span></div>${statusBar(model)}${countPills(model)}</div></header><div class="toolbar"><label class="search"><span aria-hidden="true">\u2315</span><input data-search type="search" placeholder="Search scenario, feature or tag" aria-label="Search scenarios"></label><div class="filters">${displayStatuses(model).map(
2538
+ const tags = scenarioTags(model);
2539
+ const tagFilter = tags.length ? `<label class="tagFilter"><span>Tag</span><select data-tag-filter><option value="">All tags</option>${tags.map((tag) => `<option value="${escapeHtml(tag)}">${escapeHtml(tag)}</option>`).join("")}</select></label>` : "";
2540
+ return `<div class="tabPanel" id="report-view" role="tabpanel" aria-labelledby="view-report" tabindex="0"><main class="shell"><header class="runHead"><div><p class="path">${escapeHtml(model.source)} / ${escapeHtml(options.title)}</p><h1>${escapeHtml(options.title)}</h1><p class="meta">${date ? `<span>${date}</span>` : ""}<span>${model.counts.features} feature${model.counts.features === 1 ? "" : "s"}</span><span>${model.counts.scenarios.total} scenarios</span><span>${escapeHtml(model.source)}</span>${meta}</p></div><div class="health"><div class="healthTop"><strong>${percent}%</strong><span>${passed} of ${total} passed</span></div>${statusBar(model)}${countPills(model)}</div></header><div class="toolbar"><label class="search"><span aria-hidden="true">\u2315</span><input data-search type="search" placeholder="Search scenario, feature or tag" aria-label="Search scenarios"></label>${tagFilter}<div class="filters">${displayStatuses(model).map(
2398
2541
  (status) => `<button class="filter" type="button" data-status="${status}" aria-pressed="true">${statusLabel(status)} <b>${model.counts.scenarios[status]}</b></button>`
2399
- ).join("")}</div><div class="expand"><button type="button" data-expand="all">Expand all</button><button type="button" data-expand="none">Collapse all</button></div></div><p class="live sr" id="tolkira-live" role="status" aria-live="polite" data-total="${total}"></p><div id="feature-list">${features || `<div class="empty">No scenarios in this report.</div>`}</div><div class="empty" id="empty-results" hidden>No scenarios match the current search or filters.</div><p class="foot">Generated by Tolkira. Single file. No network requests. Screenshots are embedded.</p></main></div>`;
2542
+ ).join("")}</div><div class="expand"><button type="button" data-expand="all">Expand all</button><button type="button" data-expand="none">Collapse all</button></div></div><p class="live sr" id="tolkira-live" role="status" aria-live="polite" data-total="${total}"></p><p class="sr" id="tolkira-copy-live" aria-live="polite"></p><div id="feature-list">${features || `<div class="empty">No scenarios in this report.</div>`}</div><div class="empty" id="empty-results" hidden>No scenarios match the current search or filters.</div><p class="foot">Generated by Tolkira. Single file. No network requests. Screenshots are embedded.</p></main></div>`;
2400
2543
  }
2401
2544
  function renderAnalysisView(model, options, summary) {
2402
2545
  const counts = model.counts.scenarios;
@@ -2451,17 +2594,20 @@ var SCRIPT = `<script>
2451
2594
  views[next].focus();
2452
2595
  showView(views[next].getAttribute('data-view'));
2453
2596
  });
2454
- var state = { query: '', hidden: new Set() };
2597
+ var state = { query: '', hidden: new Set(), tag: '' };
2455
2598
  var scenarios = Array.prototype.slice.call(document.querySelectorAll('[data-scenario]'));
2456
2599
  var features = Array.prototype.slice.call(document.querySelectorAll('[data-feature]'));
2457
2600
  var live = document.getElementById('tolkira-live');
2458
2601
  function apply() {
2459
2602
  var query = state.query.toLowerCase();
2603
+ var tag = state.tag;
2460
2604
  var visible = 0;
2461
2605
  scenarios.forEach(function (scenario) {
2462
2606
  var status = scenario.getAttribute('data-status');
2463
2607
  var text = (scenario.getAttribute('data-search') || '').toLowerCase();
2464
- var match = !state.hidden.has(status) && (!query || text.indexOf(query) !== -1);
2608
+ var tags = ' ' + (scenario.getAttribute('data-tags') || '') + ' ';
2609
+ var tagMatch = !tag || tags.indexOf(' ' + tag + ' ') !== -1;
2610
+ var match = !state.hidden.has(status) && tagMatch && (!query || text.indexOf(query) !== -1);
2465
2611
  scenario.hidden = !match;
2466
2612
  if (match) visible += 1;
2467
2613
  });
@@ -2469,7 +2615,7 @@ var SCRIPT = `<script>
2469
2615
  var children = feature.querySelectorAll('[data-scenario]');
2470
2616
  var any = Array.prototype.some.call(children, function (child) { return !child.hidden; });
2471
2617
  feature.hidden = !any;
2472
- if (any && (query || state.hidden.size)) feature.open = true;
2618
+ if (any && (query || state.hidden.size || tag)) feature.open = true;
2473
2619
  });
2474
2620
  if (query) {
2475
2621
  scenarios.forEach(function (scenario) {
@@ -2479,12 +2625,65 @@ var SCRIPT = `<script>
2479
2625
  if (live) live.textContent = visible + ' of ' + scenarios.length + ' scenarios visible';
2480
2626
  var empty = document.getElementById('empty-results');
2481
2627
  if (empty) empty.hidden = visible !== 0;
2628
+ highlightSearch();
2629
+ }
2630
+ function clearHighlights() {
2631
+ if (typeof CSS === 'undefined' || !CSS.highlights) return;
2632
+ CSS.highlights.delete('tolkira-search');
2633
+ }
2634
+ function escapeRegex(value) {
2635
+ var out = '';
2636
+ for (var i = 0; i < value.length; i++) {
2637
+ var code = value.charCodeAt(i);
2638
+ var ch = value.charAt(i);
2639
+ var special = code === 92 || code === 94 || code === 36 || code === 46 || code === 42 || code === 43 || code === 63 || code === 40 || code === 41 || code === 91 || code === 93 || code === 123 || code === 125 || code === 124;
2640
+ out += special ? String.fromCharCode(92) + ch : ch;
2641
+ }
2642
+ return out;
2643
+ }
2644
+ function highlightSearch() {
2645
+ if (typeof CSS === 'undefined' || !CSS.highlights || typeof Highlight === 'undefined') return;
2646
+ var needle = state.query.trim();
2647
+ if (needle.length < 2) { clearHighlights(); return; }
2648
+ try {
2649
+ var pattern = new RegExp(escapeRegex(needle), 'gi');
2650
+ var ranges = [];
2651
+ scenarios.forEach(function (scenario) {
2652
+ if (scenario.hidden || !scenario.open || ranges.length >= 200) return;
2653
+ var walker = document.createTreeWalker(scenario, NodeFilter.SHOW_TEXT, null);
2654
+ var node;
2655
+ while (ranges.length < 200 && (node = walker.nextNode())) {
2656
+ var value = node.nodeValue;
2657
+ if (!value) continue;
2658
+ var parent = node.parentElement;
2659
+ if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) continue;
2660
+ pattern.lastIndex = 0;
2661
+ var match;
2662
+ while (ranges.length < 200 && (match = pattern.exec(value)) !== null) {
2663
+ var range = document.createRange();
2664
+ range.setStart(node, match.index);
2665
+ range.setEnd(node, match.index + match[0].length);
2666
+ ranges.push(range);
2667
+ if (match[0].length === 0) pattern.lastIndex += 1;
2668
+ }
2669
+ }
2670
+ });
2671
+ clearHighlights();
2672
+ if (ranges.length) CSS.highlights.set('tolkira-search', new Highlight(...ranges));
2673
+ } catch (error) {
2674
+ clearHighlights();
2675
+ }
2482
2676
  }
2483
2677
  var search = document.querySelector('[data-search]');
2484
2678
  if (search) search.addEventListener('input', function () {
2485
2679
  state.query = search.value;
2486
2680
  apply();
2487
2681
  });
2682
+ var tagFilter = document.querySelector('[data-tag-filter]');
2683
+ if (tagFilter) tagFilter.addEventListener('change', function () {
2684
+ state.tag = tagFilter.value;
2685
+ apply();
2686
+ });
2488
2687
  Array.prototype.slice.call(document.querySelectorAll('button.filter[data-status]')).forEach(function (button) {
2489
2688
  button.addEventListener('click', function () {
2490
2689
  var status = button.getAttribute('data-status');
@@ -2501,6 +2700,94 @@ var SCRIPT = `<script>
2501
2700
  scenarios.forEach(function (scenario) { scenario.open = open; });
2502
2701
  });
2503
2702
  });
2703
+ var copyLive = document.getElementById('tolkira-copy-live');
2704
+ function legacyCopy(text) {
2705
+ var active = document.activeElement;
2706
+ var field = document.createElement('textarea');
2707
+ field.value = text;
2708
+ field.setAttribute('readonly', '');
2709
+ field.style.position = 'fixed';
2710
+ field.style.top = '-1000px';
2711
+ document.body.appendChild(field);
2712
+ var ok = false;
2713
+ try {
2714
+ field.select();
2715
+ ok = document.execCommand('copy');
2716
+ } catch (error) {
2717
+ ok = false;
2718
+ } finally {
2719
+ field.remove();
2720
+ if (active && typeof active.focus === 'function') active.focus();
2721
+ }
2722
+ return ok;
2723
+ }
2724
+ function writeClipboard(text, done) {
2725
+ var settled = false;
2726
+ function finish(ok) {
2727
+ if (settled) return;
2728
+ settled = true;
2729
+ done(ok);
2730
+ }
2731
+ function fallback() {
2732
+ finish(legacyCopy(text));
2733
+ }
2734
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
2735
+ try {
2736
+ navigator.clipboard.writeText(text).then(function () { finish(true); }, fallback);
2737
+ } catch (error) {
2738
+ fallback();
2739
+ }
2740
+ } else {
2741
+ fallback();
2742
+ }
2743
+ }
2744
+ function failureText(button) {
2745
+ var scenario = button.closest('[data-scenario]');
2746
+ if (!scenario) return '';
2747
+ var feature = scenario.closest('[data-feature]');
2748
+ var featureTitle = feature ? feature.querySelector('h2') : null;
2749
+ var scenarioTitle = scenario.querySelector('.scenarioName');
2750
+ var step = scenario.querySelector('.step[data-status="failed"]');
2751
+ var keyword = step && step.querySelector('.kw') ? step.querySelector('.kw').textContent.trim() : '';
2752
+ var body = step ? step.querySelector('div') : null;
2753
+ var text = '';
2754
+ if (body) {
2755
+ Array.prototype.forEach.call(body.childNodes, function (node) {
2756
+ if (node.nodeType === 3) text += node.nodeValue;
2757
+ });
2758
+ }
2759
+ var error = step ? step.querySelector('.error') : null;
2760
+ var stepLabel = keyword === 'Hook' ? text.trim() : (keyword + ' ' + text.trim()).trim();
2761
+ var lines = [
2762
+ 'Feature: ' + (featureTitle ? featureTitle.textContent : ''),
2763
+ 'Scenario: ' + (scenarioTitle ? scenarioTitle.textContent : ''),
2764
+ 'URI: ' + (scenario.getAttribute('data-uri') || ''),
2765
+ 'Step: ' + stepLabel
2766
+ ];
2767
+ if (error && error.textContent.trim()) {
2768
+ lines.push('Error:\\n' + error.textContent.trim());
2769
+ }
2770
+ return lines.join('\\n');
2771
+ }
2772
+ Array.prototype.slice.call(document.querySelectorAll('[data-copy-failure]')).forEach(function (button) {
2773
+ var labelTimer = null;
2774
+ button.addEventListener('click', function () {
2775
+ button.focus();
2776
+ writeClipboard(failureText(button), function (ok) {
2777
+ if (labelTimer) clearTimeout(labelTimer);
2778
+ button.textContent = ok ? 'Copied' : 'Copy failed';
2779
+ if (copyLive) {
2780
+ copyLive.textContent = ok
2781
+ ? 'Failure details copied to clipboard.'
2782
+ : 'Could not copy failure details.';
2783
+ }
2784
+ labelTimer = setTimeout(function () {
2785
+ button.textContent = 'Copy failure';
2786
+ if (copyLive) copyLive.textContent = '';
2787
+ }, 2000);
2788
+ });
2789
+ });
2790
+ });
2504
2791
  var lightbox = document.getElementById('tolkira-lightbox');
2505
2792
  if (lightbox) {
2506
2793
  var lightboxImage = lightbox.querySelector('img');
@@ -2570,7 +2857,7 @@ ${csp(hashes)}
2570
2857
  }
2571
2858
 
2572
2859
  // src/index.ts
2573
- var version = "0.1.0";
2860
+ var version = "0.1.2";
2574
2861
  async function generateReport(inputs, options = {}) {
2575
2862
  const envelopes = await loadEnvelopes(inputs);
2576
2863
  const summary = summarizeEnvelopes(envelopes);
@@ -2800,8 +3087,16 @@ ${USAGE}`);
2800
3087
  return 1;
2801
3088
  }
2802
3089
  }
2803
- var isMain = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href;
2804
- if (isMain) {
3090
+ function isMainModule() {
3091
+ const entry = process.argv[1];
3092
+ if (!entry) return false;
3093
+ try {
3094
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(entry);
3095
+ } catch {
3096
+ return false;
3097
+ }
3098
+ }
3099
+ if (isMainModule()) {
2805
3100
  runCli(process.argv.slice(2)).then((code) => {
2806
3101
  process.exitCode = code;
2807
3102
  });