sdd-engine 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +165 -2
  3. package/dist/engine/cli.js +95 -0
  4. package/dist/engine/simulate.js +214 -0
  5. package/dist/judge/conversation.js +45 -0
  6. package/dist/judge/judge.js +122 -0
  7. package/dist/judge/outcome.js +42 -0
  8. package/dist/judge/regrade.js +74 -0
  9. package/dist/pipeline/agent.js +78 -0
  10. package/dist/pipeline/agentstage.js +88 -0
  11. package/dist/pipeline/approve.js +68 -0
  12. package/dist/pipeline/cli.js +261 -0
  13. package/dist/pipeline/derive.js +287 -0
  14. package/dist/pipeline/designloop.js +385 -0
  15. package/dist/pipeline/facts.js +108 -0
  16. package/dist/pipeline/mock.js +253 -0
  17. package/dist/pipeline/project.js +79 -0
  18. package/dist/pipeline/render.js +95 -0
  19. package/dist/pipeline/spec.js +272 -0
  20. package/dist/pipeline/try.js +162 -0
  21. package/dist/runner/batch-lib.js +157 -0
  22. package/dist/runner/batch.js +56 -0
  23. package/dist/runner/cli.js +61 -0
  24. package/dist/runner/llm/claude-code.js +123 -0
  25. package/dist/runner/llm/index.js +12 -0
  26. package/dist/runner/llm/types.js +17 -0
  27. package/dist/runner/reader/answer.js +76 -0
  28. package/dist/runner/reader/extract.js +106 -0
  29. package/dist/runner/reader/run.js +111 -0
  30. package/dist/runner/reader/skim.js +115 -0
  31. package/dist/runner/rng.js +22 -0
  32. package/dist/runner/sandbox/cli.js +60 -0
  33. package/dist/runner/sandbox/sandbox.js +144 -0
  34. package/dist/runner/sandbox/server.js +64 -0
  35. package/dist/runner/spec.js +84 -0
  36. package/dist/runner/talker/decide.js +110 -0
  37. package/dist/runner/talker/run.js +159 -0
  38. package/dist/runner/talker/world.js +36 -0
  39. package/dist/runner/trace.js +130 -0
  40. package/dist/runner/visitor/decide.js +159 -0
  41. package/dist/runner/visitor/observe.js +102 -0
  42. package/dist/runner/visitor/run.js +296 -0
  43. package/dist/scorer/compare.js +119 -0
  44. package/dist/scorer/score.js +201 -0
  45. package/dist/scorer/spot-check-compare.js +41 -0
  46. package/dist/scorer/spot-check-view.js +45 -0
  47. package/dist/scorer/stats.js +45 -0
  48. package/dist/scorer/summary.js +62 -0
  49. package/package.json +49 -4
@@ -0,0 +1,130 @@
1
+ // Trace format: one JSON file per run, written once and never edited.
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { splitSentences } from "./reader/skim.js";
5
+ import { citeIsOnScreen } from "./visitor/decide.js";
6
+ /** Throws with every problem found. Checks shape and the rules a trace must obey. */
7
+ export function validateTrace(trace, questionIds) {
8
+ const problems = [];
9
+ const check = (ok, message) => {
10
+ if (!ok)
11
+ problems.push(message);
12
+ };
13
+ check(trace.schema === 'sdd-trace/1', 'schema is not sdd-trace/1');
14
+ check(Boolean(trace.runId && trace.experiment && trace.persona?.id), 'missing run, experiment, or persona id');
15
+ check(Number.isInteger(trace.seed), 'seed is not an integer');
16
+ check(/^[0-9a-f]{64}$/.test(trace.page?.sha256 ?? ''), 'page hash missing');
17
+ if (trace.mode === 'talker') {
18
+ validateTalker(trace, check);
19
+ if (problems.length > 0)
20
+ throw new Error(`Invalid trace ${trace.runId}:\n ${problems.join('\n ')}`);
21
+ return;
22
+ }
23
+ if (trace.mode === 'visitor') {
24
+ validateVisitor(trace, check);
25
+ if (problems.length > 0)
26
+ throw new Error(`Invalid trace ${trace.runId}:\n ${problems.join('\n ')}`);
27
+ return;
28
+ }
29
+ check(trace.steps.length > 0, 'no steps');
30
+ check(trace.sandbox.violations === 0, 'sandbox violations in a stored trace');
31
+ // Time moves forward and stays inside the budget.
32
+ let clock = 0;
33
+ for (const step of trace.steps) {
34
+ check(step.simulatedSecondsStart >= clock - 1e-9, `step ${step.index} starts before the previous one ended`);
35
+ check(step.simulatedSecondsEnd >= step.simulatedSecondsStart, `step ${step.index} ends before it starts`);
36
+ clock = step.simulatedSecondsEnd;
37
+ // Seen is a subset of visible.
38
+ for (const fragment of step.seen) {
39
+ const block = step.visible.find((b) => b.id === fragment.blockId);
40
+ check(Boolean(block?.text.includes(fragment.text)), `step ${step.index}: seen text not in a visible block`);
41
+ }
42
+ }
43
+ check(clock <= trace.dials.timeBudgetSeconds + 1e-9, 'simulated time exceeds the budget');
44
+ check(Math.abs(clock - trace.simulatedSeconds) < 1e-6, 'simulatedSeconds does not match the last step');
45
+ check(trace.steps.at(-1)?.action === 'stop', 'last step is not a stop');
46
+ // Recalled is a subset of seen.
47
+ const seen = trace.steps.flatMap((s) => s.seen);
48
+ for (const fragment of trace.recalled) {
49
+ check(seen.some((s) => s.blockId === fragment.blockId && s.text === fragment.text && s.t === fragment.t), `recalled fragment was never seen: "${fragment.text.slice(0, 40)}"`);
50
+ }
51
+ // One answer per question.
52
+ for (const id of questionIds) {
53
+ check(trace.answers.some((a) => a.id === id && typeof a.answer === 'string'), `no answer for "${id}"`);
54
+ }
55
+ // The answering prompt carries recalled text only. Any sentence that was on
56
+ // screen but not recalled must be absent from every persona prompt.
57
+ const recalledText = trace.recalled.map((f) => f.text);
58
+ const withheld = trace.steps
59
+ .flatMap((s) => s.visible)
60
+ .flatMap((b) => (b.kind === 'heading' ? [b.text] : splitSentences(b.text)))
61
+ .filter((text) => text.length >= 25 && !recalledText.some((r) => r.includes(text)));
62
+ const personaCalls = trace.llmCalls.filter((c) => c.request.role === 'persona');
63
+ check(personaCalls.length > 0, 'no persona call recorded');
64
+ for (const call of personaCalls) {
65
+ for (const text of withheld) {
66
+ check(!call.request.prompt.includes(text), `persona prompt leaks unseen text: "${text.slice(0, 40)}"`);
67
+ }
68
+ }
69
+ const usd = trace.llmCalls.reduce((sum, c) => sum + c.response.costUsd, 0);
70
+ check(Math.abs(usd - trace.cost.usd) < 1e-9, 'cost does not match the recorded calls');
71
+ if (problems.length > 0)
72
+ throw new Error(`Invalid trace ${trace.runId}:\n ${problems.join('\n ')}`);
73
+ }
74
+ function validateVisitor(trace, check) {
75
+ const steps = trace.visitorSteps ?? [];
76
+ check(steps.length > 0, 'no visitor steps');
77
+ check(trace.sandbox.violations === 0, 'sandbox violations in a stored trace');
78
+ let clock = 0;
79
+ for (const step of steps) {
80
+ check(step.simulatedSecondsStart >= clock - 1e-9 && step.simulatedSecondsEnd >= step.simulatedSecondsStart, `step ${step.index}: time goes backwards`);
81
+ clock = step.simulatedSecondsEnd;
82
+ // Seen is a subset of visible.
83
+ for (const seen of step.seenText)
84
+ check(step.visibleText.some((v) => v.text.includes(seen.text)), `step ${step.index}: seen text not on screen`);
85
+ // Anything but leaving rests on words that were on the screen.
86
+ if (!['leave', 'stop'].includes(step.action)) { // 'done' needs a quote too
87
+ check(citeIsOnScreen(step.cites, step.seenText, step.elements), `step ${step.index}: action "${step.action}" cites words that were not on screen`);
88
+ }
89
+ }
90
+ check(['completed', 'left', 'gave_up', 'time_up', 'thought_done'].includes(trace.outcome), 'visitor outcome missing');
91
+ check(trace.grades?.length === 1 && trace.grades[0].questionId === 'task', 'visitor trace needs one task grade');
92
+ check(trace.grades?.[0]?.pass === (trace.outcome === 'completed'), 'task grade does not match the outcome');
93
+ const usd = trace.llmCalls.reduce((sum, c) => sum + c.response.costUsd, 0);
94
+ check(Math.abs(usd - trace.cost.usd) < 1e-9, 'cost does not match the recorded calls');
95
+ }
96
+ function validateTalker(trace, check) {
97
+ const turns = trace.talkerTurns ?? [];
98
+ check(turns.length > 0, 'no talker turns');
99
+ check(turns[0]?.action === 'say', 'the conversation did not open with the person speaking');
100
+ let clock = 0;
101
+ let lastHeard = null;
102
+ for (const turn of turns) {
103
+ check(turn.simulatedSecondsStart >= clock - 1e-9 && turn.simulatedSecondsEnd >= turn.simulatedSecondsStart, `turn ${turn.index}: time goes backwards`);
104
+ clock = turn.simulatedSecondsEnd;
105
+ if (turn.action === 'say')
106
+ check(turn.said.trim().length > 0, `turn ${turn.index}: a spoken turn with no words`);
107
+ // After the first line, speaking again or claiming it worked rests on words that were heard.
108
+ if (lastHeard !== null && lastHeard.trim() && (turn.action === 'say' || turn.action === 'done')) {
109
+ check(citeIsOnScreen(turn.cites, [{ text: lastHeard }], []), `turn ${turn.index}: "${turn.action}" cites words that were not heard`);
110
+ }
111
+ if (lastHeard !== null && !lastHeard.trim())
112
+ check(turn.action !== 'done', `turn ${turn.index}: "done" after hearing nothing`);
113
+ if (turn.action === 'say')
114
+ lastHeard = turn.heard;
115
+ }
116
+ check(clock <= trace.dials.timeBudgetSeconds + 1e-9, 'simulated time exceeds the budget');
117
+ check(['completed', 'left', 'gave_up', 'time_up', 'thought_done'].includes(trace.outcome), 'talker outcome missing');
118
+ check(trace.grades?.length === 1 && trace.grades[0].questionId === 'task', 'talker trace needs one task grade');
119
+ check(trace.grades?.[0]?.pass === (trace.outcome === 'completed'), 'task grade does not match the outcome');
120
+ const usd = trace.llmCalls.reduce((sum, c) => sum + c.response.costUsd, 0);
121
+ check(Math.abs(usd - trace.cost.usd) < 1e-9, 'cost does not match the recorded calls');
122
+ }
123
+ /** Writes traces/<experiment>/<runId>.json. Fails if the file already exists. */
124
+ export async function writeTrace(tracesDir, trace) {
125
+ const dir = path.join(tracesDir, trace.experiment);
126
+ await mkdir(dir, { recursive: true });
127
+ const file = path.join(dir, `${trace.runId}.json`);
128
+ await writeFile(file, JSON.stringify(trace, null, 2) + '\n', { flag: 'wx' });
129
+ return file;
130
+ }
@@ -0,0 +1,159 @@
1
+ // The visitor's next move. One model call per screen.
2
+ //
3
+ // Simulated visitors are agreeable by default: left alone they keep going and
4
+ // sign up for anything. Three things push against that here.
5
+ // 1. The model predicts what a described person does. It is not asked to
6
+ // play the person or to complete anything.
7
+ // 2. Leaving is the default. Any other action must quote text that is on
8
+ // the screen right now, and the engine checks the quote (see citeIsOnScreen).
9
+ // 3. The model never learns what counts as success. The engine checks that.
10
+ import { storable } from "../llm/types.js";
11
+ const SYSTEM = `You predict what one specific person does next on a web page. You are not that person and you are not trying to help them or the site. You are forecasting behavior, and most real visitors leave.
12
+
13
+ You get a description of the person, what they did so far, and what is on their screen now: the text they took in and a numbered list of things they could click or type into.
14
+
15
+ Choose exactly one next action:
16
+ - "leave": they close the page or go back. This is the default, and it is what most people do on most screens.
17
+ - "scroll": they scroll down to see more.
18
+ - "click": they click one numbered element.
19
+ - "type": they type into one numbered input.
20
+ - "done": only if they were asked to try something, and they now believe they have finished it. They stop here.
21
+
22
+ Rules:
23
+ - To choose anything other than "leave", quote in "cites" the exact words on the screen that make this person take that action: text that speaks to one of their needs, answers one of their doubts, or plainly is the next step of what they are trying to do. Quote one short phrase, copied exactly. If you cannot quote such words, the answer is "leave".
24
+ - A doubt the page has not answered still counts against continuing. People do not give their details to a page they do not yet trust.
25
+ - People give up when they are confused, when the next step is not obvious, when a form asks for more than the thing is worth to them, or when they have scrolled and found nothing for them.
26
+ - People do not read everything. Use only the text listed as taken in.
27
+ - When typing, use made-up details that fit this person. Never use a real person's details.
28
+ - "reason" is one sentence in the third person saying why this person does this.
29
+ - For "done", quote the words on the screen that tell them it worked. People who see no confirmation are not sure they are done.
30
+ - For "leave", put in "cites" the words that put them off, or an empty string if nothing on screen held them.`;
31
+ const SCREEN_NOTE = `
32
+
33
+ You also get a picture of the screen. Use it for what the page looks like and what stands out. Body text in it is blurred because the person did not read it. Do not try to read blurred text.`;
34
+ function describeElement(e) {
35
+ const small = Math.min(e.width, e.height) < 32 ? ', small' : '';
36
+ if (e.kind === 'input')
37
+ return `[${e.n}] input (${e.inputType}) "${e.label}"${e.value ? `, now contains "${e.value}"` : ', empty'}`;
38
+ if (e.kind === 'link')
39
+ return `[${e.n}] link "${e.label}"${e.goesTo === 'outside' ? ', leaves this site' : ''}${small}`;
40
+ return `[${e.n}] ${e.kind} "${e.label}"${small}`;
41
+ }
42
+ export function buildDecisionRequest(input) {
43
+ const { persona, observation: o } = input;
44
+ const below = o.pageHeight - (o.scrollY + o.viewportHeight);
45
+ const prompt = `THE PERSON
46
+ ${persona.archetype}
47
+ Role: ${persona.profile.role}
48
+ Experience: ${persona.profile.experience}
49
+ Already uses: ${persona.profile.already_uses.join('; ')}
50
+ Came from: ${persona.arrival.source}, after seeing only this: "${persona.arrival.saw}"
51
+ Hoping to find: ${persona.needs.join('; ')}
52
+ Doubts going in: ${persona.objections.join('; ')}
53
+ ${input.instruction ? `They were asked to try this, and are willing to give it a fair go: ${input.instruction}` : 'Nobody asked them to do anything here. They are deciding whether this is worth their time.'}
54
+ Patience left: about ${Math.max(0, Math.round(input.secondsLeft))} seconds.
55
+
56
+ WHAT THEY HAVE DONE SO FAR
57
+ ${input.history.length ? input.history.map((h, i) => `${i + 1}. ${h.action} -> ${h.result}`).join('\n') : 'Nothing yet. They just arrived.'}
58
+
59
+ THE SCREEN NOW
60
+ Page: "${o.title}" at ${o.url}
61
+ ${below > 40 ? 'There is more page below.' : 'This is the bottom of the page.'}
62
+
63
+ Text they took in:
64
+ ${input.seenText.length ? input.seenText.map((t) => `- ${t.kind === 'heading' ? '[heading] ' : ''}${t.text}`).join('\n') : '(none)'}
65
+
66
+ Things they could act on:
67
+ ${o.elements.length ? o.elements.map(describeElement).join('\n') : '(nothing to click or type into on this screen)'}
68
+
69
+ What does this person do next?`;
70
+ return {
71
+ role: 'persona',
72
+ system: input.screenshot ? SYSTEM + SCREEN_NOTE : SYSTEM,
73
+ prompt,
74
+ ...(input.screenshot ? { images: [input.screenshot] } : {}),
75
+ schema: {
76
+ type: 'object',
77
+ properties: {
78
+ cites: { type: 'string' },
79
+ reason: { type: 'string' },
80
+ action: { type: 'string', enum: ['leave', 'scroll', 'click', 'type', 'done'] },
81
+ element: { type: 'integer' },
82
+ text: { type: 'string' },
83
+ },
84
+ required: ['cites', 'reason', 'action'],
85
+ },
86
+ };
87
+ }
88
+ const normal = (s) => s.toLowerCase().replace(/[^a-z0-9 ]+/g, ' ').replace(/\s+/g, ' ').trim();
89
+ /**
90
+ * True when the quoted words really are on the screen: in text the person
91
+ * took in, or in an element's label.
92
+ *
93
+ * Models often quote two or three phrases at once ("Get on the list" ...
94
+ * "Put me on the list"). Each phrase is checked on its own, and every one of
95
+ * them has to be on the screen. One invented phrase fails the whole quote.
96
+ */
97
+ export function citeIsOnScreen(cites, seenText, elements) {
98
+ const haystacks = [...seenText.map((t) => t.text), ...elements.map((e) => e.label)].map(normal);
99
+ const all = normal(haystacks.join(' '));
100
+ const found = (quote) => haystacks.some((h) => h.includes(quote)) || all.includes(quote);
101
+ const whole = normal(cites);
102
+ if (whole.length < 3)
103
+ return false;
104
+ if (found(whole))
105
+ return true;
106
+ const pieces = cites
107
+ .split(/\.\.\.|\u2026|[|"\u201c\u201d]|(?<=[.!?])\s+/)
108
+ .map(normal)
109
+ .filter((p) => p.length >= 3);
110
+ return pieces.length > 0 && pieces.every(found);
111
+ }
112
+ /** Why a proposed action cannot be carried out, or null if it can. */
113
+ export function problemWith(action, input) {
114
+ if (action.action === 'leave')
115
+ return null;
116
+ if (!citeIsOnScreen(action.cites, input.seenText, input.observation.elements)) {
117
+ return `"cites" must be an exact quote of words on the screen. "${action.cites.slice(0, 80)}" is not there.`;
118
+ }
119
+ if (action.action === 'done')
120
+ return input.instruction ? null : 'Nobody asked this person to do anything, so "done" is not an option. Choose another action.';
121
+ if (action.action === 'scroll')
122
+ return null;
123
+ const element = input.observation.elements.find((e) => e.n === action.element);
124
+ if (!element)
125
+ return `There is no element ${action.element} on the screen.`;
126
+ if (action.action === 'type' && element.kind !== 'input')
127
+ return `Element ${action.element} is not an input.`;
128
+ if (action.action === 'type' && !action.text)
129
+ return 'A "type" action needs the text to type.';
130
+ if (action.action === 'click' && element.kind === 'input')
131
+ return `Element ${action.element} is an input. Use "type" to fill it in.`;
132
+ return null;
133
+ }
134
+ /**
135
+ * Ask for the next action. An action that cannot be carried out, or that
136
+ * quotes words that are not on the screen, is sent back once. A second
137
+ * failure counts as leaving: no on-screen reason to continue was given.
138
+ */
139
+ export async function decide(llm, input) {
140
+ const calls = [];
141
+ let request = buildDecisionRequest(input);
142
+ let problem = '';
143
+ for (let attempt = 0; attempt < 2; attempt++) {
144
+ const response = await llm.complete(request);
145
+ calls.push({ request: storable(request), response });
146
+ const reply = response.structured;
147
+ if (reply && typeof reply.action === 'string' && ['leave', 'scroll', 'click', 'type', 'done'].includes(reply.action)) {
148
+ const action = { cites: '', reason: '', ...reply };
149
+ problem = problemWith(action, input) ?? '';
150
+ if (!problem)
151
+ return { action, calls, forcedLeave: false };
152
+ }
153
+ else {
154
+ problem = 'The reply had no valid action.';
155
+ }
156
+ request = { ...request, prompt: `${request.prompt}\n\nYOUR LAST ANSWER WAS NOT USABLE\n${problem}\nAnswer again. If there are no words on the screen to quote, the answer is "leave".` };
157
+ }
158
+ return { action: { action: 'leave', cites: '', reason: `No usable action with an on-screen reason was given. ${problem}` }, calls, forcedLeave: true };
159
+ }
@@ -0,0 +1,102 @@
1
+ // What a visitor can see and act on, on the current screen.
2
+ export async function observe(page) {
3
+ return page.evaluate(() => {
4
+ const vh = window.innerHeight;
5
+ const onScreen = (r) => r.width > 0 && r.height > 0 && r.top + r.height / 2 >= 0 && r.top + r.height / 2 <= vh;
6
+ const visible = (el) => {
7
+ const s = getComputedStyle(el);
8
+ return s.visibility !== 'hidden' && s.display !== 'none' && Number(s.opacity) > 0.05;
9
+ };
10
+ const clean = (s) => (s ?? '').replace(/\s+/g, ' ').trim();
11
+ // Text, with the same notion of "heading" the reader uses.
12
+ const bodySize = parseFloat(getComputedStyle(document.body).fontSize);
13
+ const text = [];
14
+ const seen = new Set();
15
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
16
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
17
+ if (!clean(node.textContent))
18
+ continue;
19
+ let el = node.parentElement;
20
+ if (!el || el.closest('script, style, noscript, template, button, a, label, select, option'))
21
+ continue;
22
+ while (el && getComputedStyle(el).display.startsWith('inline'))
23
+ el = el.parentElement;
24
+ if (!el || seen.has(el) || !visible(el))
25
+ continue;
26
+ seen.add(el);
27
+ const rect = el.getBoundingClientRect();
28
+ if (!onScreen(rect))
29
+ continue;
30
+ const own = clean(el.innerText);
31
+ if (!own)
32
+ continue;
33
+ const heading = Boolean(el.closest('h1, h2, h3, h4, h5, h6, [role="heading"]')) || parseFloat(getComputedStyle(el).fontSize) >= bodySize * 1.25;
34
+ text.push({ kind: heading ? 'heading' : 'body', text: own.slice(0, 600), top: rect.top });
35
+ }
36
+ text.sort((a, b) => a.top - b.top);
37
+ // Things to act on.
38
+ document.querySelectorAll('[data-sdd-el]').forEach((el) => el.removeAttribute('data-sdd-el'));
39
+ const elements = [];
40
+ const candidates = document.querySelectorAll('a[href], button, input, select, textarea, [role="button"], [role="link"], [onclick]');
41
+ for (const el of candidates) {
42
+ if (!visible(el))
43
+ continue;
44
+ const rect = el.getBoundingClientRect();
45
+ if (!onScreen(rect))
46
+ continue;
47
+ const input = el;
48
+ if (el.tagName === 'INPUT' && ['hidden', 'file'].includes(input.type))
49
+ continue;
50
+ if (input.disabled)
51
+ continue;
52
+ let kind = 'button';
53
+ if (el.tagName === 'A' || el.getAttribute('role') === 'link')
54
+ kind = 'link';
55
+ else if (el.tagName === 'SELECT')
56
+ kind = 'select';
57
+ else if (el.tagName === 'TEXTAREA')
58
+ kind = 'input';
59
+ else if (el.tagName === 'INPUT')
60
+ kind = ['checkbox', 'radio'].includes(input.type) ? 'checkbox' : ['submit', 'button', 'reset'].includes(input.type) ? 'button' : 'input';
61
+ const labelled = el.id ? document.querySelector(`label[for="${CSS.escape(el.id)}"]`) : null;
62
+ const label = clean(el.getAttribute('aria-label')) ||
63
+ clean(labelled?.textContent) ||
64
+ clean(el.closest('label')?.textContent) ||
65
+ clean(el.innerText) ||
66
+ clean(input.value && kind === 'button' ? input.value : '') ||
67
+ clean(el.getAttribute('placeholder')) ||
68
+ clean(el.getAttribute('title')) ||
69
+ clean(el.getAttribute('name')) ||
70
+ '(no label)';
71
+ const n = elements.length + 1;
72
+ el.setAttribute('data-sdd-el', String(n));
73
+ const item = { n, kind, label: label.slice(0, 120), width: Math.round(rect.width), height: Math.round(rect.height) };
74
+ if (kind === 'input') {
75
+ item.inputType = el.tagName === 'TEXTAREA' ? 'text' : input.type || 'text';
76
+ item.value = input.value;
77
+ }
78
+ if (kind === 'link') {
79
+ const href = el.href;
80
+ try {
81
+ const url = new URL(href, location.href);
82
+ item.goesTo = url.origin !== location.origin ? 'outside' : url.pathname === location.pathname ? 'same page' : 'another page';
83
+ if (item.goesTo === 'outside')
84
+ item.href = url.href;
85
+ }
86
+ catch {
87
+ item.goesTo = 'same page';
88
+ }
89
+ }
90
+ elements.push(item);
91
+ }
92
+ return {
93
+ url: location.pathname + location.search,
94
+ title: document.title,
95
+ scrollY: Math.round(window.scrollY),
96
+ viewportHeight: vh,
97
+ pageHeight: document.documentElement.scrollHeight,
98
+ text: text.map(({ kind, text }) => ({ kind, text })),
99
+ elements,
100
+ };
101
+ });
102
+ }