usepilot 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/cli/index.js +1829 -186
- package/dist/{mount-CLRI4wJ5.js → mount-DXYP_y3R.js} +13246 -9356
- package/dist/pilot-auto.js +1 -1
- package/dist/pilot.js +1 -1
- package/package.json +3 -1
package/cli/index.js
CHANGED
|
@@ -10,10 +10,34 @@ import { statSync } from "fs";
|
|
|
10
10
|
import { homedir } from "os";
|
|
11
11
|
import { delimiter, join } from "path";
|
|
12
12
|
var AGENT_KINDS = ["claude", "codex", "cursor"];
|
|
13
|
+
var NOTHING_PRINTED = "The agent printed nothing.";
|
|
14
|
+
function refusedOf(value) {
|
|
15
|
+
if (!Array.isArray(value)) return [];
|
|
16
|
+
return value.flatMap((v) => {
|
|
17
|
+
const r = v;
|
|
18
|
+
const text = (k) => typeof r?.[k] === "string" && r[k].trim() ? r[k].trim().slice(0, 200) : null;
|
|
19
|
+
const mcp = text("mcp");
|
|
20
|
+
const command2 = text("command");
|
|
21
|
+
const web = text("web");
|
|
22
|
+
const tool = text("tool");
|
|
23
|
+
return mcp ? [{ mcp }] : command2 ? [{ command: command2 }] : web ? [{ web }] : tool ? [{ tool }] : [];
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function denialOf(d) {
|
|
27
|
+
if (typeof d?.tool_name !== "string") return [];
|
|
28
|
+
const input = d.tool_input && typeof d.tool_input === "object" ? d.tool_input : {};
|
|
29
|
+
const mcp = /^mcp__(.+?)__/.exec(d.tool_name);
|
|
30
|
+
if (mcp?.[1]) return [{ mcp: mcp[1] }];
|
|
31
|
+
if (d.tool_name === "Bash" && typeof input.command === "string" && input.command.trim()) return [{ command: input.command.trim() }];
|
|
32
|
+
const host = typeof input.url === "string" ? /^https?:\/\/([^/:]+)/.exec(input.url)?.[1] : void 0;
|
|
33
|
+
if (d.tool_name === "WebFetch" && host) return [{ web: host }];
|
|
34
|
+
return [{ tool: d.tool_name }];
|
|
35
|
+
}
|
|
13
36
|
function parseStream(stdout) {
|
|
14
37
|
let session;
|
|
15
38
|
let reply;
|
|
16
39
|
let error;
|
|
40
|
+
let refused;
|
|
17
41
|
for (const line of stdout.split("\n")) {
|
|
18
42
|
const event = jsonLine(line);
|
|
19
43
|
if (!event) continue;
|
|
@@ -25,10 +49,11 @@ function parseStream(stdout) {
|
|
|
25
49
|
if (event.type === "result") {
|
|
26
50
|
if (event.is_error) error = String(event.result ?? event.error ?? "The agent stopped with an error.");
|
|
27
51
|
else if (!reply && typeof event.result === "string" && event.result.trim()) reply = event.result.trim();
|
|
52
|
+
if (Array.isArray(event.permission_denials)) refused = event.permission_denials.flatMap(denialOf);
|
|
28
53
|
}
|
|
29
54
|
}
|
|
30
|
-
if (!session && !reply && !error) error = lastLines(stdout) ||
|
|
31
|
-
return { session, reply, error };
|
|
55
|
+
if (!session && !reply && !error) error = lastLines(stdout) || NOTHING_PRINTED;
|
|
56
|
+
return { session, reply, error, ...refused?.length ? { refused } : {} };
|
|
32
57
|
}
|
|
33
58
|
function parseCodex(stdout) {
|
|
34
59
|
let session;
|
|
@@ -45,9 +70,49 @@ function parseCodex(stdout) {
|
|
|
45
70
|
error = String(event.message ?? e?.message ?? "The agent stopped with an error.");
|
|
46
71
|
}
|
|
47
72
|
}
|
|
48
|
-
if (!session && !reply && !error) error = lastLines(stdout) ||
|
|
73
|
+
if (!session && !reply && !error) error = lastLines(stdout) || NOTHING_PRINTED;
|
|
49
74
|
return { session, reply, error };
|
|
50
75
|
}
|
|
76
|
+
function refusedNote(cli, refused) {
|
|
77
|
+
const servers = /* @__PURE__ */ new Set();
|
|
78
|
+
const sites = /* @__PURE__ */ new Set();
|
|
79
|
+
const programs = /* @__PURE__ */ new Set();
|
|
80
|
+
const files = /* @__PURE__ */ new Set();
|
|
81
|
+
for (const r of refused ?? []) {
|
|
82
|
+
if ("mcp" in r) servers.add(r.mcp);
|
|
83
|
+
else if ("web" in r) sites.add(r.web);
|
|
84
|
+
else if ("command" in r) programs.add(program(r.command));
|
|
85
|
+
else files.add(FILE_TOOLS[r.tool] ?? `using ${r.tool}`);
|
|
86
|
+
}
|
|
87
|
+
const allowable = [
|
|
88
|
+
...[...servers].map((m) => ({ ask: `the ${m} MCP server`, said: `the \`${m}\` MCP server` })),
|
|
89
|
+
...[...sites].map((w) => ({ ask: `fetching ${w}`, said: `fetching \`${w}\`` }))
|
|
90
|
+
];
|
|
91
|
+
const said = [...allowable.map((a) => a.said), ...programs.size ? [`running ${list([...programs].map((p) => `\`${p}\``))}`] : [], ...files];
|
|
92
|
+
if (!said.length) return null;
|
|
93
|
+
const head = `**Not allowed in this run** (${cli.label} can't ask you here, as in its chat): ${list(said)}.`;
|
|
94
|
+
if (!allowable.length) return { note: head };
|
|
95
|
+
const them = allowable.length > 1 ? "them" : "it";
|
|
96
|
+
return {
|
|
97
|
+
note: `${head} To allow ${allowable.length > 1 ? "the MCP servers and sites" : servers.size ? "the MCP server" : "the site"}, copy the instructions for ${cli.label}.`,
|
|
98
|
+
allow: `Allow ${list(allowable.map((a) => a.ask))} in this project's ${cli.label} settings (${cli.projectSettings}), so Pilot's runs here can use ${them}.`
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
var FILE_TOOLS = {
|
|
102
|
+
Write: "writing files outside the project",
|
|
103
|
+
Edit: "editing files outside the project",
|
|
104
|
+
MultiEdit: "editing files outside the project",
|
|
105
|
+
NotebookEdit: "editing files outside the project",
|
|
106
|
+
Read: "reading files outside the project"
|
|
107
|
+
};
|
|
108
|
+
function list(items) {
|
|
109
|
+
return items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
|
|
110
|
+
}
|
|
111
|
+
function program(command2) {
|
|
112
|
+
const words = command2.trim().split(/\s+/);
|
|
113
|
+
const first = words.find((w) => !/^[A-Za-z_]\w*=/.test(w)) ?? words[0] ?? command2;
|
|
114
|
+
return (first.split("/").pop() || first).replace(/^["']|["']$/g, "").slice(0, 40);
|
|
115
|
+
}
|
|
51
116
|
var AGENTS = {
|
|
52
117
|
claude: {
|
|
53
118
|
kind: "claude",
|
|
@@ -55,16 +120,20 @@ var AGENTS = {
|
|
|
55
120
|
bins: ["claude"],
|
|
56
121
|
install: "curl -fsSL https://claude.ai/install.sh | bash",
|
|
57
122
|
signIn: "claude auth login",
|
|
123
|
+
update: "claude update",
|
|
124
|
+
help: ["--help"],
|
|
58
125
|
status: { args: ["auth", "status"], ok: (out) => /"loggedIn"\s*:\s*true/.test(out) },
|
|
59
126
|
// The designer's own settings (allow rules, MCP servers, skills), edits in the project accepted.
|
|
60
127
|
// A run can't prompt: `-p` refuses what would ask (checked; `--permission-prompts none` says the
|
|
61
128
|
// same, but older versions don't know it). Reading the user's skills is allowed, read-only: its
|
|
62
129
|
// chat would ask before a skill reads its other files there, and a run can't answer.
|
|
130
|
+
// Partial messages: its output comes while it thinks too, so Pilot sees a long think isn't a stalled run (Job.activeAt).
|
|
63
131
|
args: ({ resume, readDirs = [] }) => [
|
|
64
132
|
"-p",
|
|
65
133
|
"--output-format",
|
|
66
134
|
"stream-json",
|
|
67
135
|
"--verbose",
|
|
136
|
+
"--include-partial-messages",
|
|
68
137
|
"--permission-mode",
|
|
69
138
|
"acceptEdits",
|
|
70
139
|
"--allowedTools",
|
|
@@ -74,7 +143,8 @@ var AGENTS = {
|
|
|
74
143
|
],
|
|
75
144
|
parse: parseStream,
|
|
76
145
|
skills: { project: [".claude/skills"], home: [".claude/skills"] },
|
|
77
|
-
invokeSkill: (name) => `/${name}
|
|
146
|
+
invokeSkill: (name) => `/${name}`,
|
|
147
|
+
projectSettings: ".claude/settings.local.json"
|
|
78
148
|
},
|
|
79
149
|
codex: {
|
|
80
150
|
kind: "codex",
|
|
@@ -82,6 +152,8 @@ var AGENTS = {
|
|
|
82
152
|
bins: ["codex"],
|
|
83
153
|
install: "npm install -g @openai/codex",
|
|
84
154
|
signIn: "codex login",
|
|
155
|
+
update: "npm install -g @openai/codex@latest",
|
|
156
|
+
help: ["exec", "--help"],
|
|
85
157
|
status: { args: ["login", "status"], ok: (_out, code) => code === 0 },
|
|
86
158
|
// Its sandbox in the mode its chat uses for a project (writes in the project), with the designer's
|
|
87
159
|
// own settings for the rest (network, web search, rules). `exec` never asks: what would is refused.
|
|
@@ -99,7 +171,8 @@ var AGENTS = {
|
|
|
99
171
|
],
|
|
100
172
|
parse: parseCodex,
|
|
101
173
|
skills: { project: [".agents/skills"], home: [".agents/skills", ".codex/skills"] },
|
|
102
|
-
invokeSkill: (name) => "$" + name
|
|
174
|
+
invokeSkill: (name) => "$" + name,
|
|
175
|
+
projectSettings: ".codex/config.toml"
|
|
103
176
|
},
|
|
104
177
|
cursor: {
|
|
105
178
|
kind: "cursor",
|
|
@@ -107,6 +180,8 @@ var AGENTS = {
|
|
|
107
180
|
bins: ["cursor-agent", "agent"],
|
|
108
181
|
install: "curl https://cursor.com/install -fsS | bash",
|
|
109
182
|
signIn: "cursor-agent login",
|
|
183
|
+
update: "cursor-agent update",
|
|
184
|
+
help: ["--help"],
|
|
110
185
|
status: { args: ["status"], ok: (out) => /logged in/i.test(out) && !/not logged in/i.test(out) },
|
|
111
186
|
keyEnv: "CURSOR_API_KEY",
|
|
112
187
|
// Its allowlist mode, not its sandbox: the sandbox doesn't exist on Windows and fails on Ubuntu's
|
|
@@ -115,7 +190,8 @@ var AGENTS = {
|
|
|
115
190
|
args: ({ resume }) => ["-p", "--output-format", "stream-json", "--trust", "--sandbox", "disabled", ...resume ? ["--resume", resume] : []],
|
|
116
191
|
parse: parseStream,
|
|
117
192
|
skills: { project: [".agents/skills", ".cursor/skills"], home: [".cursor/skills"] },
|
|
118
|
-
invokeSkill: (name) => `/${name}
|
|
193
|
+
invokeSkill: (name) => `/${name}`,
|
|
194
|
+
projectSettings: ".cursor/cli.json"
|
|
119
195
|
}
|
|
120
196
|
};
|
|
121
197
|
function isAgentKind(value) {
|
|
@@ -144,6 +220,22 @@ function agentFromEnv(env = process.env) {
|
|
|
144
220
|
if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED || env.CODEX_MANAGED_BY_NPM || env.CODEX_THREAD_ID) return "codex";
|
|
145
221
|
return null;
|
|
146
222
|
}
|
|
223
|
+
async function missingFlags(cli, bin, run2 = exec) {
|
|
224
|
+
const flags = [...new Set(cli.args({ resume: "session", readDirs: ["dir"], images: ["image.png"] }).filter((a) => a.startsWith("--")))];
|
|
225
|
+
let help;
|
|
226
|
+
try {
|
|
227
|
+
help = await run2(bin, cli.help, { timeoutMs: 15e3 });
|
|
228
|
+
} catch {
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
const text = `${help.stdout}
|
|
232
|
+
${help.stderr}`;
|
|
233
|
+
if (help.killed || !text.trim() || !flags.some((f) => listed(text, f))) return null;
|
|
234
|
+
return flags.filter((f) => !listed(text, f));
|
|
235
|
+
}
|
|
236
|
+
function listed(text, flag2) {
|
|
237
|
+
return new RegExp(`(^|[^\\w-])${flag2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`).test(text);
|
|
238
|
+
}
|
|
147
239
|
async function detectAgents(kinds = AGENT_KINDS) {
|
|
148
240
|
const found = await Promise.all(
|
|
149
241
|
kinds.map(async (kind) => {
|
|
@@ -158,7 +250,7 @@ async function detectAgents(kinds = AGENT_KINDS) {
|
|
|
158
250
|
return found.filter((a) => !!a);
|
|
159
251
|
}
|
|
160
252
|
function exec(bin, args, options = {}) {
|
|
161
|
-
return new Promise((
|
|
253
|
+
return new Promise((resolve5) => {
|
|
162
254
|
const shell = process.platform === "win32" && /\.(cmd|bat)$/i.test(bin);
|
|
163
255
|
const child = shell ? spawn([bin, ...args].map(quoteForCmd).join(" "), { cwd: options.cwd, shell: true, windowsHide: true, env: options.env ?? childEnv() }) : spawn(bin, args, { cwd: options.cwd, windowsHide: true, env: options.env ?? childEnv() });
|
|
164
256
|
let stdout = "";
|
|
@@ -179,7 +271,7 @@ function exec(bin, args, options = {}) {
|
|
|
179
271
|
const finish = (code) => {
|
|
180
272
|
if (timer) clearTimeout(timer);
|
|
181
273
|
options.signal?.removeEventListener("abort", kill);
|
|
182
|
-
|
|
274
|
+
resolve5({ stdout, stderr, code, killed });
|
|
183
275
|
};
|
|
184
276
|
child.on("error", (e) => {
|
|
185
277
|
stderr += String(e);
|
|
@@ -269,7 +361,7 @@ function requestTargets(request) {
|
|
|
269
361
|
}
|
|
270
362
|
|
|
271
363
|
// ../protocol/src/format.ts
|
|
272
|
-
function formatPrompt(changeSet) {
|
|
364
|
+
function formatPrompt(changeSet, options = {}) {
|
|
273
365
|
if (changeSet.request?.kind === "responsive") return formatResponsive(changeSet, changeSet.request);
|
|
274
366
|
if (changeSet.request?.kind === "break-and-fix") return formatBreakFix(changeSet, changeSet.request);
|
|
275
367
|
if (changeSet.request?.kind === "comment") return formatComment(changeSet, changeSet.request);
|
|
@@ -280,8 +372,7 @@ function formatPrompt(changeSet) {
|
|
|
280
372
|
"",
|
|
281
373
|
"A designer adjusted the UI below in the browser with Pilot. Apply these changes to the source code.",
|
|
282
374
|
"",
|
|
283
|
-
"Guidelines:",
|
|
284
|
-
...editGuidelines(),
|
|
375
|
+
...options.guidelinesKnown ? ["Guidelines: the same as for the earlier edits in this session (design intent, the project's own conventions, no builds or browser)."] : ["Guidelines:", ...editGuidelines()],
|
|
285
376
|
"",
|
|
286
377
|
`Page: ${page.url} (${page.title || "untitled"}) at ${page.viewport.width}x${page.viewport.height}`
|
|
287
378
|
];
|
|
@@ -329,11 +420,14 @@ function sharedChoiceMeaning(answer) {
|
|
|
329
420
|
}
|
|
330
421
|
function sharedCode() {
|
|
331
422
|
return [
|
|
332
|
-
`**Shared code, only some copies:** an element's "Look-alikes" line counts the elements like it that this job leaves out (other instances of its component, or the same part of other copies). If they come from the same code (a shared component, a loop over data), and the designer didn't say which they meant, don't guess: do the rest of the job, leave that part, and ask in one short sentence, the component's name in **bold**, with three choices, your suggestion first: "${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}" (as the question in your reply's \`pilot\` block). Their answer comes back to you as this job.`,
|
|
423
|
+
`**Shared code, only some copies:** an element's "Look-alikes" line counts the elements like it that this job leaves out (other instances of its component, or the same part of other copies). If they come from the same code (a shared component, a loop over data), and the designer didn't say which they meant, don't guess: do the rest of the job, leave that part, and ask in one short sentence, the component's name in **bold**, with three choices, your suggestion first: "${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}" (as the question in your reply's \`pilot\` block). Their answer comes back to you as this job. You can ask once per job: when it changes some copies of several components (or several parts that repeat), ask one question naming each in **bold** ("Every **PlanCard** and **FeatureCard**, or only the ones you changed?"), leave all those parts until the answer, and apply it to each.`,
|
|
333
424
|
...Object.values(SHARED_CHOICES).map((c) => `**${c.label}**: ${c.means}`),
|
|
334
|
-
`Don't ask when the designer already said (in the comment or note: "only here", "every card", "as a variant"),
|
|
425
|
+
`Don't ask when the designer already said (in the comment or note: "only here", "every card", "as a variant"), or when nothing else uses that code: just change it.`,
|
|
426
|
+
`**Every copy in the job:** an element's "Every instance" line means the designer picked every instance of its component on the page together (with Pilot's Select similar, or one by one): they mean the component. Change the component itself, in its own file, so the change reaches wherever it's used, other pages included: not each instance where it's used, not a new variant, and don't ask. An "Every copy" line (no component: copies Pilot matched by the page's structure, plain HTML) means every one on this page only: change them here; if the only way is code other pages share too (a class in a global stylesheet, a partial or include), ask first, with the three choices above, before changing it there.`
|
|
335
427
|
].join(" ");
|
|
336
428
|
}
|
|
429
|
+
var UNCLEAR_ASK = '**Unclear, or already done:** if the comment could mean more than one thing ("make this square": square corners, or a 1:1 shape?), or the element already seems to be what it asks, don\'t search for what the designer meant and don\'t guess: leave that part, and ask them in your notes, in one short sentence naming the options ("Square corners, or a 1:1 shape?"). Their answer comes back as their next comment in this thread. (Your notes, not the `pilot` block: that one is for the shared-code question below.) What they meant is in the comment, the elements above and the code, nowhere else: not in git history, other agent sessions or the web.';
|
|
430
|
+
var COMMENT_WINS = `**The comment was written after these edits, so it wins:** where it asks for something else for the same property (an edit sets a margin, the comment says "10\xD7 the spacing"), do what the comment asks for that property and say so in your notes. Pilot's check may then find the edit's value missing and send it back once: keep what the comment asked.`;
|
|
337
431
|
function editGuidelines() {
|
|
338
432
|
return [
|
|
339
433
|
`- ${DESIGN_INTENT}`,
|
|
@@ -379,10 +473,10 @@ function formatProps(changeSet, request) {
|
|
|
379
473
|
"## What to list",
|
|
380
474
|
"",
|
|
381
475
|
"- **The props that change how it looks or what it shows:** variants, sizes, tones, on-off flags (`disabled`, `loading`), short texts (a label, a title), numbers (a count). Not event handlers, refs, children, class names or styles.",
|
|
382
|
-
|
|
476
|
+
"- **For each:** `name`; `type`: `options` (one of a set of values), `boolean`, `text` or `number`; for `options`, every value it accepts, from its types (a union like `\"primary\" | \"ghost\"`), its variants config (cva, tailwind-variants, a variants object), its prop validation (a Vue `validator`, `PropTypes.oneOf`), or how the component uses it; `default` when it has one; `description` in a few words when the name doesn't say, with what it takes when its type doesn't say (a number's range, `how full the bar is, 0\u2013100`; a text's form, `the fill, a Tailwind bg class`).",
|
|
383
477
|
"- The most useful first (the main variant, then the size, then the rest); 12 at most.",
|
|
384
478
|
"",
|
|
385
|
-
|
|
479
|
+
'Reply with one short sentence for the designer, like a chat message ("Button has 3 props you can change"), without describing them (Pilot lists them right under it), and the list as `props` in your reply\'s `pilot` block. Pilot lists the props under your sentence, each with its value on this instance and what it takes; the designer changes one by replying with a `name: value` line (`tone: dark`), which comes back to you as their comment, to set where this instance is written. If none is worth listing, say so and leave the block out.'
|
|
386
480
|
];
|
|
387
481
|
return `${lines.join("\n")}
|
|
388
482
|
`;
|
|
@@ -523,6 +617,8 @@ function formatComment(changeSet, request) {
|
|
|
523
617
|
"",
|
|
524
618
|
`Before writing it, the designer changed these in Pilot's editor: apply them too, exactly, as design edits. The comment may be about them ("like this, on mobile too"). Pilot checks them on the page when you're done.`,
|
|
525
619
|
"",
|
|
620
|
+
COMMENT_WINS,
|
|
621
|
+
"",
|
|
526
622
|
"Guidelines:",
|
|
527
623
|
...editGuidelines()
|
|
528
624
|
);
|
|
@@ -543,6 +639,7 @@ function formatComment(changeSet, request) {
|
|
|
543
639
|
"",
|
|
544
640
|
"- **A specific, small ask** (a color, a size, a spacing, a text): make it right away, in the project's conventions (its tokens, utilities, components). Speed matters: no screenshots or builds.",
|
|
545
641
|
"- **An open-ended ask that needs design judgment** (make it calmer, rework this layout): it's an advanced task. If you can hand work to a more capable model than the one you run on (a subagent, or another model your agent offers), do: give it this prompt (with the job id), and report back with its notes.",
|
|
642
|
+
`- ${UNCLEAR_ASK}`,
|
|
546
643
|
`- The designer was looking at the page ${page.viewport.width}px wide. If the comment is about how it looks at that width only, scope the change with the project's breakpoints; otherwise it's for every width.`,
|
|
547
644
|
`- ${PROJECT_CODE}`,
|
|
548
645
|
several > 1 ? "- Change only what the comment is about, on each of these elements." : "- Change only what the comment is about.",
|
|
@@ -631,8 +728,23 @@ function targetLines(target) {
|
|
|
631
728
|
const of = target.lookAlikesOf ? `other instances of \`${target.lookAlikesOf}\`, the same part of each` : "the same part of other copies";
|
|
632
729
|
out.push(`- Look-alikes: ${target.lookAlikes} more on the page (${of}), not in this job`);
|
|
633
730
|
}
|
|
731
|
+
if (target.everyCopy) {
|
|
732
|
+
out.push(
|
|
733
|
+
target.everyCopy.of ? `- Every instance of \`${target.everyCopy.of}\` on the page is in this job (the same part of each): change the component itself, wherever it's used` : "- Every copy on the page is in this job (the same part of each, matched by the page's structure; no component): keep the change to this page"
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
if (target.style?.length) out.push("- Its style now, as the page has it (no need to look it up; what each comes to after `=`):", ...target.style.map((st) => ` - ${styleLine(st)}`));
|
|
634
737
|
return out;
|
|
635
738
|
}
|
|
739
|
+
function styleLine(st) {
|
|
740
|
+
const value = `\`${st.property}: ${st.value}\`${st.computed ? ` = \`${st.computed}\`` : ""}`;
|
|
741
|
+
const source = st.source;
|
|
742
|
+
if (!source) return value;
|
|
743
|
+
if (source.kind === "inherited") return `${value}, inherited`;
|
|
744
|
+
if (source.kind === "inline") return `${value}, in its \`style\` attribute`;
|
|
745
|
+
const shared = source.elements && source.elements > 1 ? `, which matches ${source.elements} elements` : "";
|
|
746
|
+
return `${value}, from \`${source.selector}\`${source.media ? ` in \`@media ${source.media}\`` : ""}${shared}`;
|
|
747
|
+
}
|
|
636
748
|
function formatEdit(edit, n) {
|
|
637
749
|
const { target, changes, texts } = edit;
|
|
638
750
|
const out = [`## ${n}. \`${target.path}\``, "", ...targetLines(target)];
|
|
@@ -650,7 +762,7 @@ function formatEdit(edit, n) {
|
|
|
650
762
|
const widths = c.widths ? describeWidths(c.widths) : "every width";
|
|
651
763
|
out.push(`| \`${c.property}\` | ${from} | ${to} | ${widths} |${withStates ? ` ${describeStates(c.states)} |` : ""}`);
|
|
652
764
|
}
|
|
653
|
-
const notes = changes.flatMap((c) => [c.removed && removalNote(c), mediaNote(c)].filter((n2) => !!n2));
|
|
765
|
+
const notes = changes.flatMap((c) => [c.removed && removalNote(c), mediaNote(c), equivalentsNote(c)].filter((n2) => !!n2));
|
|
654
766
|
if (notes.length) out.push("", ...notes.map((n2) => `- ${n2}`));
|
|
655
767
|
return out;
|
|
656
768
|
}
|
|
@@ -670,13 +782,24 @@ function mediaNote(c) {
|
|
|
670
782
|
const today = `\`${c.property}\` is set inside \`@media ${media}\` today.`;
|
|
671
783
|
return c.widths ? `${today} The change is for ${describeWidths(c.widths)}.` : `${today} The change is for every width, so that media query shouldn't override it.`;
|
|
672
784
|
}
|
|
785
|
+
function equivalentsNote(c) {
|
|
786
|
+
const e = c.equivalents;
|
|
787
|
+
if (!e || !e.tokens.length && !e.classes.length) return null;
|
|
788
|
+
const code = (list2) => list2.map((x) => `\`${x}\``).join(", ");
|
|
789
|
+
const parts = [
|
|
790
|
+
e.tokens.length ? `the page's ${e.tokens.length > 1 ? "tokens" : "token"} ${code(e.tokens)}${e.fluid ? " (fluid: equal at the page's current width only, so check it's the one meant)" : ""}` : "",
|
|
791
|
+
e.classes.length ? `${e.classes.length > 1 ? "the classes" : "the class"} ${code(e.classes)}, which set${e.classes.length > 1 ? "" : "s"} just \`${c.property}\`` : ""
|
|
792
|
+
].filter(Boolean);
|
|
793
|
+
return `\`${c.property}: ${c.to}\` is ${parts.join(", and ")}: use one where it fits, as this project writes it.`;
|
|
794
|
+
}
|
|
673
795
|
function removalNote(c) {
|
|
674
796
|
const note = `\`${c.property}\` is removed: this element shouldn't set it (not \`0\` or \`none\`), so it gets what the cascade gives without it (another rule, the inherited value, or the default).`;
|
|
675
797
|
const source = c.source;
|
|
676
798
|
if (!source) return note;
|
|
677
799
|
if (source.kind === "inline") return `${note} It's set in the element's own \`style\` attribute.`;
|
|
678
800
|
const shared = source.elements && source.elements > 1 ? `, which matches ${source.elements} elements on the page: remove it for this element only, unless the designer's note says otherwise` : "";
|
|
679
|
-
|
|
801
|
+
const also = source.also?.length ? `, and from ${source.also.map((s) => `\`${s}\``).join(", ")}, which declare${source.also.length > 1 ? "" : "s"} the same value: remove it from ${source.also.length > 1 ? "them" : "it"} too` : "";
|
|
802
|
+
return `${note} It comes from \`${source.selector}\`${shared}${also}.`;
|
|
680
803
|
}
|
|
681
804
|
|
|
682
805
|
// ../protocol/src/bridge.ts
|
|
@@ -688,7 +811,8 @@ function questionOf(value) {
|
|
|
688
811
|
const q = value;
|
|
689
812
|
if (typeof q?.text !== "string" || !q.text.trim()) return void 0;
|
|
690
813
|
const choices = (Array.isArray(q.choices) ? q.choices : []).filter((c) => typeof c === "string").map((c) => c.trim().slice(0, 60)).filter(Boolean).slice(0, MAX_CHOICES);
|
|
691
|
-
|
|
814
|
+
const element = Number.isInteger(q.element) && q.element >= 1 && q.element <= 1e3 ? q.element : void 0;
|
|
815
|
+
return { text: q.text.trim().slice(0, 500), ...choices.length ? { choices } : {}, ...element ? { element } : {} };
|
|
692
816
|
}
|
|
693
817
|
function sessionOf(value) {
|
|
694
818
|
const s = value;
|
|
@@ -696,6 +820,11 @@ function sessionOf(value) {
|
|
|
696
820
|
if (typeof s.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9-]{7,99}$/.test(s.id)) return void 0;
|
|
697
821
|
return { agent: s.agent, id: s.id };
|
|
698
822
|
}
|
|
823
|
+
function allowOf(value) {
|
|
824
|
+
if (typeof value !== "string") return void 0;
|
|
825
|
+
const text = value.replace(/\s+/g, " ").trim();
|
|
826
|
+
return text ? text.slice(0, 500) : void 0;
|
|
827
|
+
}
|
|
699
828
|
function jobErrorOf(value) {
|
|
700
829
|
const e = value;
|
|
701
830
|
if (typeof e?.title !== "string" || !e.title.trim()) return void 0;
|
|
@@ -775,6 +904,17 @@ function saveAgent(folder, agent, file = configFile()) {
|
|
|
775
904
|
writeFileSync(file, `${JSON.stringify(projects, null, 2)}
|
|
776
905
|
`);
|
|
777
906
|
}
|
|
907
|
+
function savedSessions(folder, file = configFile()) {
|
|
908
|
+
const list2 = read(file)[resolve(folder)]?.editor;
|
|
909
|
+
return Array.isArray(list2) ? list2.filter((s) => s && isAgentKind(s.agent) && typeof s.id === "string") : [];
|
|
910
|
+
}
|
|
911
|
+
function saveSessions(folder, sessions, file = configFile()) {
|
|
912
|
+
const projects = read(file);
|
|
913
|
+
projects[resolve(folder)] = { ...projects[resolve(folder)], editor: sessions };
|
|
914
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
915
|
+
writeFileSync(file, `${JSON.stringify(projects, null, 2)}
|
|
916
|
+
`);
|
|
917
|
+
}
|
|
778
918
|
function projectName(folder) {
|
|
779
919
|
try {
|
|
780
920
|
const name = projectNameOf(JSON.parse(readFileSync(join2(folder, "package.json"), "utf8")).name);
|
|
@@ -878,7 +1018,7 @@ function readJson(file) {
|
|
|
878
1018
|
}
|
|
879
1019
|
|
|
880
1020
|
// src/version.ts
|
|
881
|
-
var VERSION = "0.
|
|
1021
|
+
var VERSION = "0.16.0";
|
|
882
1022
|
function olderThan(a, b) {
|
|
883
1023
|
const parts = (v) => v.replace(/^[^\d]*/, "").split(/[.-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0);
|
|
884
1024
|
const [x, y] = [parts(a), parts(b)];
|
|
@@ -1028,6 +1168,8 @@ function detectFramework(cwd, deps) {
|
|
|
1028
1168
|
if (has("@sveltejs/kit")) return result("sveltekit", first("src/hooks.client.ts", "src/hooks.client.js"));
|
|
1029
1169
|
if (has("astro")) return result("astro");
|
|
1030
1170
|
if (has("@react-router/dev") || has("@remix-run/react")) return result("react-router", first("app/root.tsx", "app/root.jsx"));
|
|
1171
|
+
if (has("@angular/core")) return result("angular", first("src/main.ts"));
|
|
1172
|
+
if (has("gatsby")) return result("gatsby", first(...GATSBY_BROWSER));
|
|
1031
1173
|
if (has("vite") || Object.keys(deps).some((d) => d.startsWith("@vitejs/"))) {
|
|
1032
1174
|
const entry = viteEntry(cwd);
|
|
1033
1175
|
if (entry) return result("vite", entry);
|
|
@@ -1037,7 +1179,9 @@ function detectFramework(cwd, deps) {
|
|
|
1037
1179
|
}
|
|
1038
1180
|
return result("vite");
|
|
1039
1181
|
}
|
|
1040
|
-
if (has("
|
|
1182
|
+
if (has("@rsbuild/core")) return result("rsbuild", first(...JS_ENTRIES));
|
|
1183
|
+
if (has("parcel")) return result("parcel", parcelEntry(cwd));
|
|
1184
|
+
if (has("react-scripts") || has("webpack") || has("@vue/cli-service") || has("@rspack/core") || has("@rspack/cli")) {
|
|
1041
1185
|
return result(
|
|
1042
1186
|
"webpack",
|
|
1043
1187
|
first("src/index.tsx", "src/index.ts", "src/index.jsx", "src/index.js", "src/main.tsx", "src/main.ts", "src/main.js")
|
|
@@ -1045,6 +1189,21 @@ function detectFramework(cwd, deps) {
|
|
|
1045
1189
|
}
|
|
1046
1190
|
return { kind: "unknown", loads };
|
|
1047
1191
|
}
|
|
1192
|
+
var GATSBY_BROWSER = ["gatsby-browser.tsx", "gatsby-browser.ts", "gatsby-browser.jsx", "gatsby-browser.js"];
|
|
1193
|
+
var JS_ENTRIES = ["src/index.tsx", "src/index.ts", "src/index.jsx", "src/index.js", "src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js"];
|
|
1194
|
+
function parcelEntry(cwd) {
|
|
1195
|
+
const source = readJson2(join4(cwd, "package.json"))?.source;
|
|
1196
|
+
const page = [...typeof source === "string" ? [source] : Array.isArray(source) ? source.filter((s) => typeof s === "string") : [], "index.html", "src/index.html"].map((f) => join4(cwd, f)).find((f) => f.endsWith(".html") && existsSync2(f));
|
|
1197
|
+
if (page) {
|
|
1198
|
+
for (const tag of readFileSync3(page, "utf8").match(/<script\b[^>]*>/gi) ?? []) {
|
|
1199
|
+
const src = /src=["']([^"'?#]+)/i.exec(tag)?.[1];
|
|
1200
|
+
const file = src && !/^[a-z]+:|^\/\//i.test(src) ? join4(src.startsWith("/") ? cwd : dirname2(page), src) : void 0;
|
|
1201
|
+
if (file && existsSync2(file)) return file;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
if (typeof source === "string" && /\.[mc]?[jt]sx?$/.test(source) && existsSync2(join4(cwd, source))) return join4(cwd, source);
|
|
1205
|
+
return JS_ENTRIES.map((f) => join4(cwd, f)).find((f) => existsSync2(f));
|
|
1206
|
+
}
|
|
1048
1207
|
function viteEntry(cwd) {
|
|
1049
1208
|
const html = join4(cwd, "index.html");
|
|
1050
1209
|
if (existsSync2(html)) {
|
|
@@ -1080,7 +1239,7 @@ function findLoader(cwd) {
|
|
|
1080
1239
|
}
|
|
1081
1240
|
return void 0;
|
|
1082
1241
|
};
|
|
1083
|
-
for (const name of ["index.html", "vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]) {
|
|
1242
|
+
for (const name of ["index.html", "vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs", ...GATSBY_BROWSER]) {
|
|
1084
1243
|
const file = join4(cwd, name);
|
|
1085
1244
|
if (existsSync2(file) && /usepilot/.test(readText2(file))) return file;
|
|
1086
1245
|
}
|
|
@@ -1176,8 +1335,23 @@ export function Pilot() {
|
|
|
1176
1335
|
if (import.meta.env.DEV) import("usepilot/auto");
|
|
1177
1336
|
}, []);`
|
|
1178
1337
|
)}`;
|
|
1338
|
+
case "angular":
|
|
1339
|
+
return `${intro} It's Angular: in ${at(framework.file, "the file that bootstraps the app (`src/main.ts`)")}, after the bootstrap, add:${code("ts", 'if (typeof ngDevMode === "undefined" || ngDevMode) import("usepilot/auto");')}
|
|
1340
|
+
|
|
1341
|
+
Use \`ngDevMode\`, not \`isDevMode()\`: Angular's production build sets \`ngDevMode\` to false and drops Pilot from the bundle, while \`isDevMode()\` is decided in the browser and leaves Pilot's files in the build.`;
|
|
1342
|
+
case "gatsby":
|
|
1343
|
+
return `${intro} It's Gatsby: in ${at(framework.file, "`gatsby-browser.js` at the app's root (create it if there's none)")}, in its \`onClientEntry\` (add the export if there's none, keep the others):${code(
|
|
1344
|
+
"js",
|
|
1345
|
+
`export const onClientEntry = () => {
|
|
1346
|
+
if (process.env.NODE_ENV === "development") import("usepilot/auto");
|
|
1347
|
+
};`
|
|
1348
|
+
)}`;
|
|
1349
|
+
case "rsbuild":
|
|
1350
|
+
return `${intro} It's Rsbuild: in its entry module, ${at(framework.file, "the one `source.entry` in its config names (`src/index` by default)")}, add:${code("ts", 'if (import.meta.env.DEV) import("usepilot/auto");')}`;
|
|
1351
|
+
case "parcel":
|
|
1352
|
+
return `${intro} It's Parcel: in the script its HTML page loads, ${at(framework.file, "the `<script src>` of the page Parcel builds")}, add:${code("js", 'if (process.env.NODE_ENV === "development") import("usepilot/auto");')}`;
|
|
1179
1353
|
case "webpack":
|
|
1180
|
-
return `${intro}
|
|
1354
|
+
return `${intro} It's webpack, or a tool built on it (Create React App, Vue CLI, Rspack): in the app's entry file, ${at(framework.file, "the one its bundler config starts from")}, add:${code("js", 'if (process.env.NODE_ENV === "development") import("usepilot/auto");')}`;
|
|
1181
1355
|
default:
|
|
1182
1356
|
return `${intro} With no bundler Pilot knows (a server-rendered site: PHP, Rails, Django, plain HTML), add it to the layout every page shares (Pilot works on every page), as one tag pointing at Pilot's file where the dev server serves it: \`<script type="module" src="\u2026/node_modules/usepilot/dist/pilot-auto.js"></script>\`. **It must never be output on a server, whatever a request says.** Print it only when both hold: Pilot's own file is on disk (\`node_modules/usepilot/dist/pilot-auto.js\`: a dev dependency, never on a server, as long as the deploy leaves \`node_modules\` out or installs without dev dependencies: check the project's deploy rules, and ask the user if you can't tell), and the project's own development setting says so (an environment variable like \`APP_ENV=local\`, or the local config file that isn't deployed; ask the user if there's none). Never decide from the request (the Host header, the client's IP): a proxy or a client can make them say anything. For example, in PHP:${code(
|
|
1183
1357
|
"php",
|
|
@@ -1224,8 +1398,8 @@ function runCommand(command2, args, cwd) {
|
|
|
1224
1398
|
|
|
1225
1399
|
// src/run.ts
|
|
1226
1400
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
1227
|
-
import { existsSync as
|
|
1228
|
-
import { basename as
|
|
1401
|
+
import { existsSync as existsSync9 } from "fs";
|
|
1402
|
+
import { basename as basename7 } from "path";
|
|
1229
1403
|
|
|
1230
1404
|
// src/server.ts
|
|
1231
1405
|
import { createServer } from "http";
|
|
@@ -1516,21 +1690,25 @@ function findSkills(folders) {
|
|
|
1516
1690
|
if (!meta) continue;
|
|
1517
1691
|
const name = meta.name || entry;
|
|
1518
1692
|
if (!SKILL_NAME.test(name) || found.has(name)) continue;
|
|
1519
|
-
found.set(name, { name, ...meta.description ? { description: meta.description } : {} });
|
|
1693
|
+
found.set(name, { name, ...meta.description ? { description: meta.description } : {}, ...meta.author ? { author: meta.author } : {} });
|
|
1520
1694
|
}
|
|
1521
1695
|
}
|
|
1522
1696
|
return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
1523
1697
|
}
|
|
1524
1698
|
var MAX_SKILL_BYTES = 256e3;
|
|
1525
1699
|
var MAX_DESCRIPTION = 300;
|
|
1700
|
+
var MAX_AUTHOR = 60;
|
|
1526
1701
|
function readSkill(file) {
|
|
1527
1702
|
try {
|
|
1528
1703
|
if (statSync3(file).size > MAX_SKILL_BYTES) return null;
|
|
1529
|
-
const
|
|
1704
|
+
const text = readFileSync5(file, "utf8");
|
|
1705
|
+
const meta = frontmatter(text);
|
|
1530
1706
|
const description = meta.description?.replace(/\s+/g, " ").trim();
|
|
1707
|
+
const author = (meta.author ?? metadataValue(text, "author"))?.replace(/\s+/g, " ").trim().slice(0, MAX_AUTHOR);
|
|
1531
1708
|
return {
|
|
1532
1709
|
name: meta.name?.trim(),
|
|
1533
|
-
description: description && description.length > MAX_DESCRIPTION ? `${description.slice(0, MAX_DESCRIPTION - 1).trimEnd()}\u2026` : description
|
|
1710
|
+
description: description && description.length > MAX_DESCRIPTION ? `${description.slice(0, MAX_DESCRIPTION - 1).trimEnd()}\u2026` : description,
|
|
1711
|
+
...author ? { author } : {}
|
|
1534
1712
|
};
|
|
1535
1713
|
} catch {
|
|
1536
1714
|
return null;
|
|
@@ -1554,6 +1732,19 @@ function frontmatter(text) {
|
|
|
1554
1732
|
}
|
|
1555
1733
|
return out;
|
|
1556
1734
|
}
|
|
1735
|
+
function metadataValue(text, key) {
|
|
1736
|
+
const block = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)?.[1];
|
|
1737
|
+
if (block === void 0) return void 0;
|
|
1738
|
+
const lines = block.split(/\r?\n/);
|
|
1739
|
+
const start = lines.findIndex((l) => /^metadata:[ \t]*$/.test(l));
|
|
1740
|
+
if (start < 0) return void 0;
|
|
1741
|
+
for (const line of lines.slice(start + 1)) {
|
|
1742
|
+
if (!/^[ \t]+\S/.test(line)) break;
|
|
1743
|
+
const pair = new RegExp(`^[ \\t]+${key}:[ \\t]*(.+)$`).exec(line);
|
|
1744
|
+
if (pair) return unquote(pair[1].trim());
|
|
1745
|
+
}
|
|
1746
|
+
return void 0;
|
|
1747
|
+
}
|
|
1557
1748
|
function unquote(value) {
|
|
1558
1749
|
if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/g, "'");
|
|
1559
1750
|
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) return value.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\n/g, "\n");
|
|
@@ -1746,7 +1937,7 @@ var Hub = class {
|
|
|
1746
1937
|
this.agents.delete(agentId);
|
|
1747
1938
|
for (const w of this.waiters.filter((w2) => w2.agentId === agentId)) this.endWait(w, null);
|
|
1748
1939
|
for (const job of this.jobs.values()) {
|
|
1749
|
-
if (job.status === "working" && job.agent?.id === agentId) this.update(job, { status: "queued", takenAt: void 0 });
|
|
1940
|
+
if (job.status === "working" && job.agent?.id === agentId) this.update(job, { status: "queued", takenAt: void 0, activeAt: void 0 });
|
|
1750
1941
|
}
|
|
1751
1942
|
this.notifyAgents(agent.origin);
|
|
1752
1943
|
this.dispatch(agent.origin);
|
|
@@ -1809,14 +2000,14 @@ var Hub = class {
|
|
|
1809
2000
|
const key = originKey(origin);
|
|
1810
2001
|
const queued = this.oldestQueued(key);
|
|
1811
2002
|
if (queued) return Promise.resolve({ job: this.take(queued, this.shown(info)) });
|
|
1812
|
-
return new Promise((
|
|
2003
|
+
return new Promise((resolve5) => {
|
|
1813
2004
|
const waiter = {
|
|
1814
2005
|
agentId: info.id,
|
|
1815
2006
|
origin: key,
|
|
1816
2007
|
resolve: (job) => {
|
|
1817
2008
|
clearTimeout(timer);
|
|
1818
2009
|
signal?.removeEventListener("abort", onAbort);
|
|
1819
|
-
|
|
2010
|
+
resolve5({ job });
|
|
1820
2011
|
}
|
|
1821
2012
|
};
|
|
1822
2013
|
const timer = setTimeout(() => this.endWait(waiter, null), timeoutMs);
|
|
@@ -1837,17 +2028,18 @@ var Hub = class {
|
|
|
1837
2028
|
if (!job || job.status === "cancelled") return null;
|
|
1838
2029
|
const agent = this.agents.get(agentId)?.info ?? job.agent;
|
|
1839
2030
|
const asks = question && !job.answer ? { question } : {};
|
|
1840
|
-
const
|
|
2031
|
+
const listed2 = props?.length && job.changeSet.request?.kind === "props" ? { props } : {};
|
|
1841
2032
|
this.update(job, {
|
|
1842
2033
|
status: "done",
|
|
1843
2034
|
agent,
|
|
1844
2035
|
notes: notes?.trim() || void 0,
|
|
1845
2036
|
doneAt: new Date(this.now()).toISOString(),
|
|
1846
2037
|
...asks,
|
|
1847
|
-
...
|
|
2038
|
+
...listed2,
|
|
1848
2039
|
// The session to resume for its follow-up (kept from the first run when a later one has none), and the run's error or none.
|
|
1849
2040
|
session: extra.session ?? job.session,
|
|
1850
|
-
error: extra.error
|
|
2041
|
+
error: extra.error,
|
|
2042
|
+
allow: extra.allow
|
|
1851
2043
|
});
|
|
1852
2044
|
return job;
|
|
1853
2045
|
}
|
|
@@ -1873,12 +2065,12 @@ var Hub = class {
|
|
|
1873
2065
|
const job = this.jobs.get(jobId);
|
|
1874
2066
|
if (!job) return Promise.resolve(null);
|
|
1875
2067
|
const requestId = randomUUID();
|
|
1876
|
-
return new Promise((
|
|
2068
|
+
return new Promise((resolve5) => {
|
|
1877
2069
|
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
1878
2070
|
const finish = (check) => {
|
|
1879
2071
|
clearTimeout(timer);
|
|
1880
2072
|
this.checks.delete(requestId);
|
|
1881
|
-
|
|
2073
|
+
resolve5(check);
|
|
1882
2074
|
};
|
|
1883
2075
|
this.checks.set(requestId, { origin: job.origin, resolve: finish });
|
|
1884
2076
|
if (!this.sendTo(job.origin, { type: "check", requestId, jobId })) finish(null);
|
|
@@ -1968,9 +2160,15 @@ var Hub = class {
|
|
|
1968
2160
|
return [...this.jobs.values()].filter((j) => j.origin === origin && j.status === "queued").sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
|
|
1969
2161
|
}
|
|
1970
2162
|
take(job, agent) {
|
|
1971
|
-
this.update(job, { status: "working", agent, takenAt: new Date(this.now()).toISOString() });
|
|
2163
|
+
this.update(job, { status: "working", agent, takenAt: new Date(this.now()).toISOString(), activeAt: void 0 });
|
|
1972
2164
|
return job;
|
|
1973
2165
|
}
|
|
2166
|
+
/** The agent running `jobId` is at work (its output came): the page sees the run isn't quiet. Ignored for another agent's job, or one not running. */
|
|
2167
|
+
activity(agentId, jobId) {
|
|
2168
|
+
const job = this.jobs.get(jobId);
|
|
2169
|
+
if (!job || job.status !== "working" || job.agent?.id !== agentId) return;
|
|
2170
|
+
this.update(job, { activeAt: new Date(this.now()).toISOString() });
|
|
2171
|
+
}
|
|
1974
2172
|
/**
|
|
1975
2173
|
* Gives the oldest queued job of `origin` to the agent waiting longest
|
|
1976
2174
|
* there; a follow-up to the agent that did the job, if it's waiting.
|
|
@@ -2024,14 +2222,14 @@ function startHub(port, hub = new Hub(), options = {}) {
|
|
|
2024
2222
|
});
|
|
2025
2223
|
const sweep = setInterval(() => hub.sweep(localAgents), 5e3);
|
|
2026
2224
|
sweep.unref();
|
|
2027
|
-
return new Promise((
|
|
2225
|
+
return new Promise((resolve5, reject) => {
|
|
2028
2226
|
server.once("error", (error) => {
|
|
2029
2227
|
clearInterval(sweep);
|
|
2030
2228
|
reject(error);
|
|
2031
2229
|
});
|
|
2032
2230
|
server.listen(port, "127.0.0.1", () => {
|
|
2033
2231
|
const address = server.address();
|
|
2034
|
-
|
|
2232
|
+
resolve5({
|
|
2035
2233
|
hub,
|
|
2036
2234
|
server,
|
|
2037
2235
|
port: typeof address === "object" && address ? address.port : port,
|
|
@@ -2151,8 +2349,12 @@ async function handleAgent(hub, action, data, req, res) {
|
|
|
2151
2349
|
case "done":
|
|
2152
2350
|
if (!d.jobId) return json(res, 400, { error: "jobId needed" });
|
|
2153
2351
|
return json(res, 200, {
|
|
2154
|
-
job: hub.done(d.agent.id, d.jobId, d.notes, questionOf(d.question), propsOf(d.props), { session: sessionOf(d.session), error: jobErrorOf(d.error) })
|
|
2352
|
+
job: hub.done(d.agent.id, d.jobId, d.notes, questionOf(d.question), propsOf(d.props), { session: sessionOf(d.session), error: jobErrorOf(d.error), allow: allowOf(d.allow) })
|
|
2155
2353
|
});
|
|
2354
|
+
case "activity":
|
|
2355
|
+
if (!d.jobId) return json(res, 400, { error: "jobId needed" });
|
|
2356
|
+
hub.activity(d.agent.id, d.jobId);
|
|
2357
|
+
return json(res, 200, {});
|
|
2156
2358
|
case "job":
|
|
2157
2359
|
if (!d.jobId) return json(res, 400, { error: "jobId needed" });
|
|
2158
2360
|
return json(res, 200, { job: hub.job(d.jobId) ?? null });
|
|
@@ -2178,7 +2380,7 @@ function json(res, status, data) {
|
|
|
2178
2380
|
res.end(JSON.stringify(data));
|
|
2179
2381
|
}
|
|
2180
2382
|
function rawBody(req, max) {
|
|
2181
|
-
return new Promise((
|
|
2383
|
+
return new Promise((resolve5, reject) => {
|
|
2182
2384
|
const chunks = [];
|
|
2183
2385
|
let size = 0;
|
|
2184
2386
|
let over = false;
|
|
@@ -2187,20 +2389,20 @@ function rawBody(req, max) {
|
|
|
2187
2389
|
size += chunk.length;
|
|
2188
2390
|
if (size > max) {
|
|
2189
2391
|
over = true;
|
|
2190
|
-
|
|
2392
|
+
resolve5(null);
|
|
2191
2393
|
req.resume();
|
|
2192
2394
|
return;
|
|
2193
2395
|
}
|
|
2194
2396
|
chunks.push(chunk);
|
|
2195
2397
|
});
|
|
2196
2398
|
req.on("end", () => {
|
|
2197
|
-
if (!over)
|
|
2399
|
+
if (!over) resolve5(Buffer.concat(chunks));
|
|
2198
2400
|
});
|
|
2199
2401
|
req.on("error", reject);
|
|
2200
2402
|
});
|
|
2201
2403
|
}
|
|
2202
2404
|
function body(req) {
|
|
2203
|
-
return new Promise((
|
|
2405
|
+
return new Promise((resolve5, reject) => {
|
|
2204
2406
|
let text = "";
|
|
2205
2407
|
req.setEncoding("utf8");
|
|
2206
2408
|
req.on("data", (chunk) => {
|
|
@@ -2209,9 +2411,9 @@ function body(req) {
|
|
|
2209
2411
|
});
|
|
2210
2412
|
req.on("end", () => {
|
|
2211
2413
|
try {
|
|
2212
|
-
|
|
2414
|
+
resolve5(text ? JSON.parse(text) : {});
|
|
2213
2415
|
} catch {
|
|
2214
|
-
|
|
2416
|
+
resolve5({});
|
|
2215
2417
|
}
|
|
2216
2418
|
});
|
|
2217
2419
|
req.on("error", reject);
|
|
@@ -2245,6 +2447,9 @@ var LocalApi = class {
|
|
|
2245
2447
|
async job(_agent, jobId) {
|
|
2246
2448
|
return this.hub.job(jobId) ?? null;
|
|
2247
2449
|
}
|
|
2450
|
+
async activity(agent, jobId) {
|
|
2451
|
+
this.hub.activity(agent.id, jobId);
|
|
2452
|
+
}
|
|
2248
2453
|
check(_agent, jobId, timeoutMs) {
|
|
2249
2454
|
return this.hub.check(jobId, timeoutMs);
|
|
2250
2455
|
}
|
|
@@ -2291,6 +2496,13 @@ var RemoteApi = class {
|
|
|
2291
2496
|
async job(agent, jobId) {
|
|
2292
2497
|
return (await this.post("job", { agent, jobId })).job;
|
|
2293
2498
|
}
|
|
2499
|
+
async activity(agent, jobId) {
|
|
2500
|
+
try {
|
|
2501
|
+
await this.post("activity", { agent, jobId });
|
|
2502
|
+
} catch (error) {
|
|
2503
|
+
if (isConnectionError(error)) throw error;
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2294
2506
|
async check(agent, jobId, timeoutMs) {
|
|
2295
2507
|
return (await this.post("check", { agent, jobId, timeoutMs })).check;
|
|
2296
2508
|
}
|
|
@@ -2348,6 +2560,10 @@ var Bridge = class {
|
|
|
2348
2560
|
job(jobId) {
|
|
2349
2561
|
return this.call((api) => api.job(this.agent, jobId));
|
|
2350
2562
|
}
|
|
2563
|
+
/** The agent is at work on `jobId`: its output came (see Job.activeAt). */
|
|
2564
|
+
activity(jobId) {
|
|
2565
|
+
return this.call((api) => api.activity(this.agent, jobId));
|
|
2566
|
+
}
|
|
2351
2567
|
/** Pilot's width check of a task's element, measured by the page (null: no page answered). */
|
|
2352
2568
|
check(jobId, timeoutMs = CHECK_TIMEOUT) {
|
|
2353
2569
|
return this.call((api) => api.check(this.agent, jobId, timeoutMs));
|
|
@@ -2437,9 +2653,13 @@ function isConnectionError(error) {
|
|
|
2437
2653
|
return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "UND_ERR_SOCKET" || /fetch failed|socket hang up|other side closed/i.test(e?.message ?? "");
|
|
2438
2654
|
}
|
|
2439
2655
|
|
|
2440
|
-
// src/
|
|
2441
|
-
import { existsSync as
|
|
2442
|
-
import {
|
|
2656
|
+
// src/facts.ts
|
|
2657
|
+
import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
|
|
2658
|
+
import { dirname as dirname7, join as join11, relative as relative6, resolve as resolve4, sep } from "path";
|
|
2659
|
+
|
|
2660
|
+
// src/sources.ts
|
|
2661
|
+
import { readdirSync as readdirSync5, readFileSync as readFileSync7, statSync as statSync5 } from "fs";
|
|
2662
|
+
import { extname as extname3, join as join9, relative as relative4 } from "path";
|
|
2443
2663
|
var SKIP2 = /* @__PURE__ */ new Set([
|
|
2444
2664
|
"node_modules",
|
|
2445
2665
|
"dist",
|
|
@@ -2447,6 +2667,7 @@ var SKIP2 = /* @__PURE__ */ new Set([
|
|
|
2447
2667
|
"out",
|
|
2448
2668
|
"coverage",
|
|
2449
2669
|
"vendor",
|
|
2670
|
+
"bower_components",
|
|
2450
2671
|
".git",
|
|
2451
2672
|
".next",
|
|
2452
2673
|
".nuxt",
|
|
@@ -2475,113 +2696,1375 @@ var EXTENSIONS2 = /* @__PURE__ */ new Set([
|
|
|
2475
2696
|
".liquid",
|
|
2476
2697
|
".twig"
|
|
2477
2698
|
]);
|
|
2478
|
-
var
|
|
2699
|
+
var STYLESHEETS = /* @__PURE__ */ new Set([".css", ".scss", ".sass", ".less", ".styl"]);
|
|
2700
|
+
var MAX_FILES3 = 5e4;
|
|
2479
2701
|
var MAX_FILE_BYTES3 = 512e3;
|
|
2480
|
-
var
|
|
2481
|
-
var
|
|
2702
|
+
var FRESH_MS = 2e3;
|
|
2703
|
+
var Index = class {
|
|
2704
|
+
constructor(root) {
|
|
2705
|
+
this.root = root;
|
|
2706
|
+
}
|
|
2707
|
+
root;
|
|
2708
|
+
entries = /* @__PURE__ */ new Map();
|
|
2709
|
+
/** Every walked file, markup or not (componentFile looks at all scripts). */
|
|
2710
|
+
paths = [];
|
|
2711
|
+
/** Every stylesheet walked (not read): CSS, Sass, Less, Stylus. */
|
|
2712
|
+
styles = [];
|
|
2713
|
+
/** How many lines of the markup files hold each word, and how many lines they have. */
|
|
2714
|
+
counts = /* @__PURE__ */ new Map();
|
|
2715
|
+
lines = 0;
|
|
2716
|
+
walkedAt = 0;
|
|
2717
|
+
get sources() {
|
|
2718
|
+
const out = [];
|
|
2719
|
+
for (const e of this.entries.values()) if (e.source) out.push(e.source);
|
|
2720
|
+
return out;
|
|
2721
|
+
}
|
|
2722
|
+
refresh() {
|
|
2723
|
+
if (Date.now() - this.walkedAt < FRESH_MS) return;
|
|
2724
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2725
|
+
const paths = [];
|
|
2726
|
+
const styles = [];
|
|
2727
|
+
const walk = (dir) => {
|
|
2728
|
+
let names;
|
|
2729
|
+
try {
|
|
2730
|
+
names = readdirSync5(dir);
|
|
2731
|
+
} catch {
|
|
2732
|
+
return;
|
|
2733
|
+
}
|
|
2734
|
+
for (const name of names) {
|
|
2735
|
+
if (paths.length >= MAX_FILES3) return;
|
|
2736
|
+
if (SKIP2.has(name) || name.startsWith(".")) continue;
|
|
2737
|
+
const path = join9(dir, name);
|
|
2738
|
+
let stat2;
|
|
2739
|
+
try {
|
|
2740
|
+
stat2 = statSync5(path);
|
|
2741
|
+
} catch {
|
|
2742
|
+
continue;
|
|
2743
|
+
}
|
|
2744
|
+
if (stat2.isDirectory()) {
|
|
2745
|
+
walk(path);
|
|
2746
|
+
continue;
|
|
2747
|
+
}
|
|
2748
|
+
if (STYLESHEETS.has(extname3(name)) && stat2.size <= MAX_FILE_BYTES3) styles.push(path);
|
|
2749
|
+
if (!EXTENSIONS2.has(extname3(name)) || stat2.size > MAX_FILE_BYTES3) continue;
|
|
2750
|
+
paths.push(path);
|
|
2751
|
+
seen.add(path);
|
|
2752
|
+
const known = this.entries.get(path);
|
|
2753
|
+
if (known && known.mtime === stat2.mtimeMs && known.size === stat2.size) continue;
|
|
2754
|
+
if (known?.source) this.count(known.source, -1);
|
|
2755
|
+
const source = this.read(path);
|
|
2756
|
+
if (source) this.count(source, 1);
|
|
2757
|
+
this.entries.set(path, { mtime: stat2.mtimeMs, size: stat2.size, source });
|
|
2758
|
+
}
|
|
2759
|
+
};
|
|
2760
|
+
walk(this.root);
|
|
2761
|
+
for (const [path, e] of this.entries) {
|
|
2762
|
+
if (seen.has(path)) continue;
|
|
2763
|
+
if (e.source) this.count(e.source, -1);
|
|
2764
|
+
this.entries.delete(path);
|
|
2765
|
+
}
|
|
2766
|
+
this.paths = paths;
|
|
2767
|
+
this.styles = styles;
|
|
2768
|
+
this.walkedAt = Date.now();
|
|
2769
|
+
}
|
|
2770
|
+
read(path) {
|
|
2771
|
+
let content;
|
|
2772
|
+
try {
|
|
2773
|
+
content = readFileSync7(path, "utf8");
|
|
2774
|
+
} catch {
|
|
2775
|
+
return null;
|
|
2776
|
+
}
|
|
2777
|
+
if (!/<[A-Za-z][\w.:-]*[\s>/]/.test(content)) return null;
|
|
2778
|
+
const lines = content.split("\n");
|
|
2779
|
+
const lineCounts = /* @__PURE__ */ new Map();
|
|
2780
|
+
for (const line of lines) for (const w of new Set(wordsOf(line))) lineCounts.set(w, (lineCounts.get(w) ?? 0) + 1);
|
|
2781
|
+
return { path, rel: relative4(this.root, path), content, lines, words: new Set(lineCounts.keys()), lineCounts };
|
|
2782
|
+
}
|
|
2783
|
+
count(source, by) {
|
|
2784
|
+
this.lines += by * source.lines.length;
|
|
2785
|
+
for (const [w, lines] of source.lineCounts) {
|
|
2786
|
+
const n = (this.counts.get(w) ?? 0) + by * lines;
|
|
2787
|
+
if (n > 0) this.counts.set(w, n);
|
|
2788
|
+
else this.counts.delete(w);
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
};
|
|
2792
|
+
function wordsOf(text) {
|
|
2793
|
+
return text.split(/[\s"'`<>{}=]+/).filter((w) => w.length > 0);
|
|
2794
|
+
}
|
|
2795
|
+
var indexes = /* @__PURE__ */ new Map();
|
|
2796
|
+
function indexOf(root) {
|
|
2797
|
+
let index = indexes.get(root);
|
|
2798
|
+
if (!index) {
|
|
2799
|
+
index = new Index(root);
|
|
2800
|
+
indexes.set(root, index);
|
|
2801
|
+
}
|
|
2802
|
+
index.refresh();
|
|
2803
|
+
return index;
|
|
2804
|
+
}
|
|
2805
|
+
function markupSources(root) {
|
|
2806
|
+
const index = indexOf(root);
|
|
2807
|
+
const scale2 = 6 / Math.log2(index.lines + 2);
|
|
2808
|
+
return {
|
|
2809
|
+
sources: index.sources,
|
|
2810
|
+
rarity: (word) => Math.max(0, Math.min(6, Math.log2((index.lines + 2) / ((index.counts.get(word) ?? 0) + 1)) * scale2))
|
|
2811
|
+
};
|
|
2812
|
+
}
|
|
2813
|
+
function styleFiles(root) {
|
|
2814
|
+
return indexOf(root).styles;
|
|
2815
|
+
}
|
|
2482
2816
|
function sourceFiles(root) {
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2817
|
+
return indexOf(root).paths;
|
|
2818
|
+
}
|
|
2819
|
+
function warmSources(root) {
|
|
2820
|
+
indexOf(root);
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
// src/styles.ts
|
|
2824
|
+
import { existsSync as existsSync6, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
|
|
2825
|
+
import { basename as basename5, extname as extname4, join as join10, relative as relative5 } from "path";
|
|
2826
|
+
var STYLE_EXTENSIONS = /* @__PURE__ */ new Set([".css", ".scss", ".sass", ".less", ".styl"]);
|
|
2827
|
+
var PREPROCESSED = /* @__PURE__ */ new Set([".scss", ".sass", ".less", ".styl"]);
|
|
2828
|
+
var TEMPLATES = /^@(mixin|function|each|for|while|if|else|keyframes|-webkit-keyframes|font-face|property|page|counter-style|theme|utility|variant|custom-variant)\b/;
|
|
2829
|
+
var parsed = /* @__PURE__ */ new Map();
|
|
2830
|
+
function rulesOf(path, root) {
|
|
2831
|
+
let stat2;
|
|
2832
|
+
try {
|
|
2833
|
+
stat2 = statSync6(path);
|
|
2834
|
+
} catch {
|
|
2835
|
+
return [];
|
|
2836
|
+
}
|
|
2837
|
+
const known = parsed.get(path);
|
|
2838
|
+
if (known && known.mtime === stat2.mtimeMs && known.size === stat2.size) return known.rules;
|
|
2839
|
+
let rules = [];
|
|
2840
|
+
try {
|
|
2841
|
+
const text = readFileSync8(path, "utf8");
|
|
2842
|
+
if (!text.split("\n", 50).some((l) => l.length > 3e3)) rules = parseStylesheet(text, relative5(root, path));
|
|
2843
|
+
} catch {
|
|
2844
|
+
}
|
|
2845
|
+
parsed.set(path, { mtime: stat2.mtimeMs, size: stat2.size, rules });
|
|
2846
|
+
return rules;
|
|
2847
|
+
}
|
|
2848
|
+
function withoutComments(text, lineComments) {
|
|
2849
|
+
let out = "";
|
|
2850
|
+
let quote2 = "";
|
|
2851
|
+
for (let i = 0; i < text.length; i++) {
|
|
2852
|
+
const ch = text[i];
|
|
2853
|
+
if (quote2) {
|
|
2854
|
+
out += ch;
|
|
2855
|
+
if (ch === "\\") out += text[++i] ?? "";
|
|
2856
|
+
else if (ch === quote2) quote2 = "";
|
|
2857
|
+
continue;
|
|
2858
|
+
}
|
|
2859
|
+
if (ch === '"' || ch === "'") {
|
|
2860
|
+
quote2 = ch;
|
|
2861
|
+
out += ch;
|
|
2862
|
+
continue;
|
|
2863
|
+
}
|
|
2864
|
+
if (ch === "/" && text[i + 1] === "*") {
|
|
2865
|
+
const end = text.indexOf("*/", i + 2);
|
|
2866
|
+
const stop = end < 0 ? text.length : end + 2;
|
|
2867
|
+
out += text.slice(i, stop).replace(/[^\n]/g, " ");
|
|
2868
|
+
i = stop - 1;
|
|
2869
|
+
continue;
|
|
2870
|
+
}
|
|
2871
|
+
if (lineComments && ch === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
|
|
2872
|
+
const end = text.indexOf("\n", i);
|
|
2873
|
+
const stop = end < 0 ? text.length : end;
|
|
2874
|
+
out += " ".repeat(stop - i);
|
|
2875
|
+
i = stop - 1;
|
|
2876
|
+
continue;
|
|
2877
|
+
}
|
|
2878
|
+
out += ch;
|
|
2879
|
+
}
|
|
2880
|
+
return out;
|
|
2881
|
+
}
|
|
2882
|
+
function splitTopLevel(text, sep2) {
|
|
2883
|
+
const out = [];
|
|
2884
|
+
let depth = 0;
|
|
2885
|
+
let start = 0;
|
|
2886
|
+
for (let i = 0; i < text.length; i++) {
|
|
2887
|
+
const ch = text[i];
|
|
2888
|
+
if (ch === "(" || ch === "[") depth++;
|
|
2889
|
+
else if (ch === ")" || ch === "]") depth--;
|
|
2890
|
+
else if (ch === sep2 && depth === 0) {
|
|
2891
|
+
out.push(text.slice(start, i));
|
|
2892
|
+
start = i + 1;
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
out.push(text.slice(start));
|
|
2896
|
+
return out.map((s) => s.trim()).filter(Boolean);
|
|
2897
|
+
}
|
|
2898
|
+
function normalSelector(selector) {
|
|
2899
|
+
return selector.replace(/\s+/g, " ").replace(/\s*([>+~])\s*/g, "$1").replace(/\[\s*([\w-]+)\s*([~|^$*]?=)\s*(["'])([\w-]+)\3\s*\]/g, "[$1$2$4]").replace(/\[\s*([\w-]+)\s*\]/g, "[$1]").trim();
|
|
2900
|
+
}
|
|
2901
|
+
function resolve3(parents, own) {
|
|
2902
|
+
if (!parents.length) return own;
|
|
2903
|
+
const out = [];
|
|
2904
|
+
for (const p of parents) for (const s of own) out.push(s.includes("&") ? s.replaceAll("&", p) : `${p} ${s}`);
|
|
2905
|
+
return out;
|
|
2906
|
+
}
|
|
2907
|
+
function parseStylesheet(text, file) {
|
|
2908
|
+
const ext = extname4(file);
|
|
2909
|
+
const css = withoutComments(text, ext !== ".css");
|
|
2910
|
+
const rules = [];
|
|
2911
|
+
const stack = [];
|
|
2912
|
+
let start = 0;
|
|
2913
|
+
let line = 1;
|
|
2914
|
+
let startLine = 1;
|
|
2915
|
+
const top = () => stack[stack.length - 1];
|
|
2916
|
+
const inTemplate = () => stack.some((b) => b.template);
|
|
2917
|
+
for (let i = 0; i < css.length; i++) {
|
|
2918
|
+
const ch = css[i];
|
|
2919
|
+
if (ch === "\n") line++;
|
|
2920
|
+
if (ch === "{" && css[i - 1] === "#") {
|
|
2921
|
+
const close = css.indexOf("}", i);
|
|
2922
|
+
if (close > 0) {
|
|
2923
|
+
line += (css.slice(i, close).match(/\n/g) ?? []).length;
|
|
2924
|
+
i = close;
|
|
2925
|
+
}
|
|
2926
|
+
continue;
|
|
2927
|
+
}
|
|
2928
|
+
if (ch === "{") {
|
|
2929
|
+
const prelude = css.slice(start, i).trim();
|
|
2930
|
+
const preludeLine = startLine + (css.slice(start, i).match(/^\s*/)?.[0].match(/\n/g) ?? []).length;
|
|
2931
|
+
const parent = top();
|
|
2932
|
+
if (prelude.startsWith("@")) {
|
|
2933
|
+
const own = /^@media\s+(.+)$/.exec(prelude)?.[1]?.trim();
|
|
2934
|
+
const media = own && parent?.media ? `${parent.media} and ${own}` : own ?? parent?.media;
|
|
2935
|
+
const template = TEMPLATES.test(prelude);
|
|
2936
|
+
const rule = parent?.rule && own ? { file, line: preludeLine, selectors: parent.selectors, declarations: [], ...media ? { media } : {} } : parent?.rule;
|
|
2937
|
+
if (rule && rule !== parent?.rule && !template && !inTemplate()) rules.push(rule);
|
|
2938
|
+
stack.push({ selectors: parent?.selectors ?? [], ...rule ? { rule } : {}, ...media ? { media } : {}, template });
|
|
2939
|
+
} else {
|
|
2940
|
+
const selectors = resolve3(parent?.selectors ?? [], splitTopLevel(prelude, ",")).map(normalSelector);
|
|
2941
|
+
const rule = { file, line: preludeLine, selectors, declarations: [], ...parent?.media ? { media: parent.media } : {} };
|
|
2942
|
+
if (!inTemplate() && !/^(from|to|\d+%)$/.test(prelude)) rules.push(rule);
|
|
2943
|
+
stack.push({ selectors, rule, ...parent?.media ? { media: parent.media } : {} });
|
|
2944
|
+
}
|
|
2945
|
+
start = i + 1;
|
|
2946
|
+
startLine = line;
|
|
2947
|
+
continue;
|
|
2948
|
+
}
|
|
2949
|
+
if (ch === ";" || ch === "}") {
|
|
2950
|
+
const statement = css.slice(start, i);
|
|
2951
|
+
const m = /^\s*(-?[A-Za-z][\w-]*|--[\w-]+)\s*:(?!:)\s*([\s\S]+?)\s*$/.exec(statement);
|
|
2952
|
+
const block = top();
|
|
2953
|
+
if (m && block?.rule && !inTemplate()) {
|
|
2954
|
+
const at = startLine + (statement.match(/^\s*/)?.[0].match(/\n/g) ?? []).length;
|
|
2955
|
+
block.rule.declarations.push({ property: m[1].toLowerCase(), value: m[2].replace(/\s+/g, " "), line: at });
|
|
2956
|
+
}
|
|
2957
|
+
if (ch === "}") stack.pop();
|
|
2958
|
+
start = i + 1;
|
|
2959
|
+
startLine = line;
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
return rules;
|
|
2963
|
+
}
|
|
2964
|
+
function componentStyles(path, root) {
|
|
2965
|
+
let text;
|
|
2966
|
+
try {
|
|
2967
|
+
text = readFileSync8(path, "utf8");
|
|
2968
|
+
} catch {
|
|
2969
|
+
return [];
|
|
2970
|
+
}
|
|
2971
|
+
const out = [];
|
|
2972
|
+
for (const m of text.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/g)) {
|
|
2973
|
+
const before = text.slice(0, m.index + m[0].indexOf(">") + 1);
|
|
2974
|
+
const offset = (before.match(/\n/g) ?? []).length;
|
|
2975
|
+
const lang = /lang=["'](\w+)["']/.exec(m[1])?.[1] ?? "css";
|
|
2976
|
+
const file = relative5(root, path);
|
|
2977
|
+
for (const r of parseStylesheet(m[2], `${file}.${lang}`))
|
|
2978
|
+
out.push({ ...r, file, line: r.line + offset, declarations: r.declarations.map((d) => ({ ...d, line: d.line + offset })) });
|
|
2979
|
+
}
|
|
2980
|
+
return out;
|
|
2981
|
+
}
|
|
2982
|
+
function moduleClass(hashed) {
|
|
2983
|
+
let m = /^([A-Za-z][\w-]*?)_([\w-]+?)__[\w-]{5,}$/.exec(hashed);
|
|
2984
|
+
if (m) return { file: m[1], local: m[2] };
|
|
2985
|
+
m = /^_([\w-]+?)_[a-z0-9]{5,}(_\d+)?$/.exec(hashed);
|
|
2986
|
+
if (m) return { local: m[1] };
|
|
2987
|
+
return null;
|
|
2988
|
+
}
|
|
2989
|
+
function asWritten(selector) {
|
|
2990
|
+
let module;
|
|
2991
|
+
let hashed = false;
|
|
2992
|
+
const out = selector.replace(/\.(-?[_A-Za-z][\w-]*)/g, (whole, cls) => {
|
|
2993
|
+
const m = moduleClass(cls);
|
|
2994
|
+
if (!m) return whole;
|
|
2995
|
+
hashed = true;
|
|
2996
|
+
module = module ?? m.file;
|
|
2997
|
+
return `.${m.local}`;
|
|
2998
|
+
});
|
|
2999
|
+
return { selector: normalSelector(out), ...module ? { module } : {}, hashed };
|
|
3000
|
+
}
|
|
3001
|
+
function warmStyles(root) {
|
|
3002
|
+
for (const path of styleFiles(root)) if (STYLE_EXTENSIONS.has(extname4(path))) rulesOf(path, root);
|
|
3003
|
+
}
|
|
3004
|
+
function ruleSource(selector, property, root, near = [], media) {
|
|
3005
|
+
const wanted = asWritten(selector);
|
|
3006
|
+
const files = styleFiles(root);
|
|
3007
|
+
const found = [];
|
|
3008
|
+
const consider = (rules) => {
|
|
3009
|
+
for (const rule of rules) {
|
|
3010
|
+
if (!rule.selectors.includes(wanted.selector)) continue;
|
|
3011
|
+
const declaration = [...rule.declarations].reverse().find((d) => d.property === property || shorthandOf(property).includes(d.property));
|
|
3012
|
+
found.push({ rule, ...declaration ? { declaration } : {} });
|
|
3013
|
+
}
|
|
3014
|
+
};
|
|
3015
|
+
const sources = new Set(files.filter((f) => PREPROCESSED.has(extname4(f))).map((f) => basename5(f).replace(/^_/, "").replace(/\.\w+$/, "")));
|
|
3016
|
+
for (const path of files) {
|
|
3017
|
+
const ext = extname4(path);
|
|
3018
|
+
if (!STYLE_EXTENSIONS.has(ext)) continue;
|
|
3019
|
+
if (ext === ".css" && compiled(path, sources)) continue;
|
|
3020
|
+
if (wanted.hashed && !/\.module\.\w+$/.test(path)) continue;
|
|
3021
|
+
if (wanted.module && !basename5(path).startsWith(`${wanted.module}.`)) continue;
|
|
3022
|
+
consider(rulesOf(path, root));
|
|
3023
|
+
}
|
|
3024
|
+
if (!found.length && !wanted.hashed) {
|
|
3025
|
+
for (const path of sourceFiles(root)) if (/\.(vue|svelte|astro)$/.test(path)) consider(componentStyles(path, root));
|
|
3026
|
+
}
|
|
3027
|
+
const sites = new Set(near.map((f) => siteOf(f, root)));
|
|
3028
|
+
const kept = sites.size ? found.filter((s) => sites.has(siteOf(s.rule.file, root))) : found;
|
|
3029
|
+
if (!kept.length) return null;
|
|
3030
|
+
if (!sites.size && new Set(kept.map((s) => siteOf(s.rule.file, root))).size > 1) return null;
|
|
3031
|
+
const score = (s) => {
|
|
3032
|
+
const ext = extname4(s.rule.file);
|
|
3033
|
+
const dir = s.rule.file.split(/[\\/]/).slice(0, -1);
|
|
3034
|
+
const shared = Math.max(
|
|
3035
|
+
0,
|
|
3036
|
+
...near.map((f) => {
|
|
3037
|
+
const parts = f.split(/[\\/]/);
|
|
3038
|
+
let n = 0;
|
|
3039
|
+
while (n < dir.length && dir[n] === parts[n]) n++;
|
|
3040
|
+
return n;
|
|
3041
|
+
})
|
|
3042
|
+
);
|
|
3043
|
+
return (PREPROCESSED.has(ext) || !STYLE_EXTENSIONS.has(ext) ? 100 : 0) + (s.declaration ? 50 : 0) + ((s.rule.media ?? "") === (media ?? "") ? 20 : 0) + shared;
|
|
3044
|
+
};
|
|
3045
|
+
return kept.sort((a, b) => score(b) - score(a))[0];
|
|
3046
|
+
}
|
|
3047
|
+
var SITE_FILES = ["index.html", "index.htm", "index.php", "package.json"];
|
|
3048
|
+
var siteCache = /* @__PURE__ */ new Map();
|
|
3049
|
+
function siteOf(file, root) {
|
|
3050
|
+
const parts = file.split(/[\\/]/).slice(0, -1);
|
|
3051
|
+
for (let n = parts.length; n > 0; n--) {
|
|
3052
|
+
const dir = parts.slice(0, n).join("/");
|
|
3053
|
+
const key = `${root}\0${dir}`;
|
|
3054
|
+
let site = siteCache.get(key);
|
|
3055
|
+
if (site === void 0) {
|
|
3056
|
+
site = SITE_FILES.some((f) => existsSync6(join10(root, dir, f))) ? dir : "";
|
|
3057
|
+
siteCache.set(key, site);
|
|
3058
|
+
}
|
|
3059
|
+
if (site) return site;
|
|
3060
|
+
}
|
|
3061
|
+
return "";
|
|
3062
|
+
}
|
|
3063
|
+
function compiled(path, sources) {
|
|
3064
|
+
if (existsSync6(`${path}.map`)) return true;
|
|
3065
|
+
if (sources.has(basename5(path, ".css"))) return true;
|
|
3066
|
+
try {
|
|
3067
|
+
const text = readFileSync8(path, "utf8");
|
|
3068
|
+
return /\/\*#\s*sourceMappingURL=/.test(text.slice(-500));
|
|
3069
|
+
} catch {
|
|
3070
|
+
return false;
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
function shorthandOf(property) {
|
|
3074
|
+
const out = [];
|
|
3075
|
+
const m = /^(padding|margin|inset|border|border-radius|gap|flex|grid|font|background|outline|transition|animation)/.exec(property);
|
|
3076
|
+
if (m && m[1] !== property) out.push(m[1]);
|
|
3077
|
+
if (/^(row|column)-gap$/.test(property)) out.push("gap");
|
|
3078
|
+
if (/^(padding|margin)-(inline|block)/.test(property)) out.push(property.replace(/-(start|end)$/, ""));
|
|
3079
|
+
if (property === "background-color") out.push("background");
|
|
3080
|
+
return out;
|
|
3081
|
+
}
|
|
3082
|
+
|
|
3083
|
+
// src/facts.ts
|
|
3084
|
+
var REM = 16;
|
|
3085
|
+
var DEFAULTS = new Map(
|
|
3086
|
+
Object.entries({
|
|
3087
|
+
spacing: "0.25rem",
|
|
3088
|
+
...prefixed("breakpoint", { sm: "40rem", md: "48rem", lg: "64rem", xl: "80rem", "2xl": "96rem" }),
|
|
3089
|
+
...prefixed("container", {
|
|
3090
|
+
"3xs": "16rem",
|
|
3091
|
+
"2xs": "18rem",
|
|
3092
|
+
xs: "20rem",
|
|
3093
|
+
sm: "24rem",
|
|
3094
|
+
md: "28rem",
|
|
3095
|
+
lg: "32rem",
|
|
3096
|
+
xl: "36rem",
|
|
3097
|
+
"2xl": "42rem",
|
|
3098
|
+
"3xl": "48rem",
|
|
3099
|
+
"4xl": "56rem",
|
|
3100
|
+
"5xl": "64rem",
|
|
3101
|
+
"6xl": "72rem",
|
|
3102
|
+
"7xl": "80rem"
|
|
3103
|
+
}),
|
|
3104
|
+
...prefixed("text", {
|
|
3105
|
+
xs: "0.75rem",
|
|
3106
|
+
sm: "0.875rem",
|
|
3107
|
+
base: "1rem",
|
|
3108
|
+
lg: "1.125rem",
|
|
3109
|
+
xl: "1.25rem",
|
|
3110
|
+
"2xl": "1.5rem",
|
|
3111
|
+
"3xl": "1.875rem",
|
|
3112
|
+
"4xl": "2.25rem",
|
|
3113
|
+
"5xl": "3rem",
|
|
3114
|
+
"6xl": "3.75rem",
|
|
3115
|
+
"7xl": "4.5rem",
|
|
3116
|
+
"8xl": "6rem",
|
|
3117
|
+
"9xl": "8rem"
|
|
3118
|
+
}),
|
|
3119
|
+
...prefixed("font-weight", {
|
|
3120
|
+
thin: "100",
|
|
3121
|
+
extralight: "200",
|
|
3122
|
+
light: "300",
|
|
3123
|
+
normal: "400",
|
|
3124
|
+
medium: "500",
|
|
3125
|
+
semibold: "600",
|
|
3126
|
+
bold: "700",
|
|
3127
|
+
extrabold: "800",
|
|
3128
|
+
black: "900"
|
|
3129
|
+
}),
|
|
3130
|
+
...prefixed("tracking", { tighter: "-0.05em", tight: "-0.025em", normal: "0em", wide: "0.025em", wider: "0.05em", widest: "0.1em" }),
|
|
3131
|
+
...prefixed("leading", { tight: "1.25", snug: "1.375", normal: "1.5", relaxed: "1.625", loose: "2" }),
|
|
3132
|
+
...prefixed("radius", { xs: "0.125rem", sm: "0.25rem", md: "0.375rem", lg: "0.5rem", xl: "0.75rem", "2xl": "1rem", "3xl": "1.5rem", "4xl": "2rem" })
|
|
3133
|
+
})
|
|
3134
|
+
);
|
|
3135
|
+
function prefixed(namespace, values) {
|
|
3136
|
+
return Object.fromEntries(Object.entries(values).map(([k, v]) => [`${namespace}-${k}`, v]));
|
|
3137
|
+
}
|
|
3138
|
+
function tailwindOf(root, near = [], url) {
|
|
3139
|
+
const entries = styleFiles(root).filter((f) => importsTailwind(f));
|
|
3140
|
+
if (!entries.length) return null;
|
|
3141
|
+
const route = routeParts(url);
|
|
3142
|
+
const closeness = (entry2) => {
|
|
3143
|
+
const dir = relative6(root, dirname7(entry2)).split(sep).filter(Boolean);
|
|
3144
|
+
const shared = (file) => {
|
|
3145
|
+
const parts = file.split(/[\\/]/);
|
|
3146
|
+
let n = 0;
|
|
3147
|
+
while (n < dir.length && dir[n] === parts[n]) n++;
|
|
3148
|
+
return n;
|
|
3149
|
+
};
|
|
3150
|
+
return Math.max(0, ...near.map(shared)) * 10 + (route.includes(dir[0] ?? "") ? 1 : 0);
|
|
3151
|
+
};
|
|
3152
|
+
const entry = [...entries].sort((a, b) => closeness(b) - closeness(a))[0];
|
|
3153
|
+
const pkg = nearestPackage(dirname7(entry), root);
|
|
3154
|
+
const version = installedVersion2(dirname7(entry), root) ?? declaredVersion(pkg);
|
|
3155
|
+
if (version && !version.replace(/^[^\d]*/, "").startsWith("4")) return null;
|
|
3156
|
+
const theme = /* @__PURE__ */ new Map();
|
|
3157
|
+
const defaults = findUp(dirname7(entry), root, join11("node_modules", "tailwindcss", "theme.css"));
|
|
3158
|
+
if (defaults) readTheme(defaults, theme, 0);
|
|
3159
|
+
else for (const [k, v] of DEFAULTS) theme.set(k, v);
|
|
3160
|
+
const own = /* @__PURE__ */ new Set();
|
|
3161
|
+
readTheme(entry, theme, 0, own);
|
|
3162
|
+
return { entry: relative6(root, entry), ...version ? { version } : {}, theme, own };
|
|
3163
|
+
}
|
|
3164
|
+
function importsTailwind(file) {
|
|
3165
|
+
try {
|
|
3166
|
+
return /@import\s+(url\()?["']tailwindcss["']/.test(readFileSync9(file, "utf8"));
|
|
3167
|
+
} catch {
|
|
3168
|
+
return false;
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
function routeParts(url) {
|
|
3172
|
+
try {
|
|
3173
|
+
return url ? new URL(url).pathname.split("/").filter(Boolean) : [];
|
|
3174
|
+
} catch {
|
|
3175
|
+
return [];
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
function findUp(dir, root, name) {
|
|
3179
|
+
for (let d = resolve4(dir); ; d = dirname7(d)) {
|
|
3180
|
+
const path = join11(d, name);
|
|
3181
|
+
if (existsSync7(path)) return path;
|
|
3182
|
+
if (d === resolve4(root) || d === dirname7(d)) return null;
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
function nearestPackage(dir, root) {
|
|
3186
|
+
return findUp(dir, root, "package.json");
|
|
3187
|
+
}
|
|
3188
|
+
function installedVersion2(dir, root) {
|
|
3189
|
+
const pkg = findUp(dir, root, join11("node_modules", "tailwindcss", "package.json"));
|
|
3190
|
+
try {
|
|
3191
|
+
return pkg ? JSON.parse(readFileSync9(pkg, "utf8")).version : void 0;
|
|
3192
|
+
} catch {
|
|
3193
|
+
return void 0;
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
3196
|
+
function declaredVersion(pkg) {
|
|
3197
|
+
try {
|
|
3198
|
+
if (!pkg) return void 0;
|
|
3199
|
+
const p = JSON.parse(readFileSync9(pkg, "utf8"));
|
|
3200
|
+
return p.dependencies?.tailwindcss ?? p.devDependencies?.tailwindcss;
|
|
3201
|
+
} catch {
|
|
3202
|
+
return void 0;
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
function readTheme(file, theme, depth, own) {
|
|
3206
|
+
let css;
|
|
3207
|
+
try {
|
|
3208
|
+
css = readFileSync9(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
3209
|
+
} catch {
|
|
3210
|
+
return;
|
|
3211
|
+
}
|
|
3212
|
+
if (depth < 3)
|
|
3213
|
+
for (const m of css.matchAll(/@import\s+(?:url\()?["'](\.{1,2}\/[^"']+\.css)["']/g)) readTheme(resolve4(dirname7(file), m[1]), theme, depth + 1, own);
|
|
3214
|
+
for (const block of themeBlocks(css)) {
|
|
3215
|
+
for (const m of block.matchAll(/--([\w-]+|\*)(-\*)?\s*:\s*([^;]+);/g)) {
|
|
3216
|
+
const name = m[1];
|
|
3217
|
+
const value = m[3].replace(/\s+/g, " ").trim();
|
|
3218
|
+
if (value === "initial" && (m[2] || name === "*")) {
|
|
3219
|
+
for (const key of [...theme.keys()]) if (name === "*" || key.startsWith(`${name}-`)) theme.delete(key);
|
|
3220
|
+
own?.add(`${name}-*`);
|
|
3221
|
+
continue;
|
|
3222
|
+
}
|
|
3223
|
+
theme.set(name, value);
|
|
3224
|
+
own?.add(name);
|
|
3225
|
+
}
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
function themeBlocks(css) {
|
|
3229
|
+
const blocks = [];
|
|
3230
|
+
for (const m of css.matchAll(/@theme\b[^{]*\{/g)) {
|
|
3231
|
+
let depth = 1;
|
|
3232
|
+
let i = m.index + m[0].length;
|
|
3233
|
+
const start = i;
|
|
3234
|
+
for (; i < css.length && depth; i++) {
|
|
3235
|
+
if (css[i] === "{") depth++;
|
|
3236
|
+
else if (css[i] === "}") depth--;
|
|
3237
|
+
}
|
|
3238
|
+
blocks.push(css.slice(start, i - 1));
|
|
3239
|
+
}
|
|
3240
|
+
return blocks;
|
|
3241
|
+
}
|
|
3242
|
+
function rebuildOf(pkg, root) {
|
|
3243
|
+
const read4 = (file) => {
|
|
2487
3244
|
try {
|
|
2488
|
-
|
|
3245
|
+
return file ? JSON.parse(readFileSync9(file, "utf8")) : {};
|
|
2489
3246
|
} catch {
|
|
2490
|
-
return;
|
|
3247
|
+
return {};
|
|
2491
3248
|
}
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
3249
|
+
};
|
|
3250
|
+
const escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3251
|
+
for (const file of [.../* @__PURE__ */ new Set([pkg, join11(root, "package.json")])]) {
|
|
3252
|
+
const p = read4(file);
|
|
3253
|
+
const scripts = p.scripts ?? {};
|
|
3254
|
+
const where = file && file !== join11(root, "package.json") ? ` in \`${relative6(root, dirname7(file))}\`` : "";
|
|
3255
|
+
const runner = (name) => Object.entries(scripts).find(([other, cmd]) => other !== name && new RegExp(`(npm run|pnpm( run)?|yarn|bun run|npm:)\\s*${escape2(name)}\\b`).test(cmd))?.[0];
|
|
3256
|
+
const said = (name) => {
|
|
3257
|
+
const by = runner(name);
|
|
3258
|
+
return by ? `\`npm run ${by}\`${where} (its \`${name}\`)` : `\`npm run ${name}\`${where}`;
|
|
3259
|
+
};
|
|
3260
|
+
const gulpWatches = (() => {
|
|
2497
3261
|
try {
|
|
2498
|
-
|
|
3262
|
+
return /\bwatch\s*\(/.test(readFileSync9(join11(file ? dirname7(file) : root, "gulpfile.js"), "utf8"));
|
|
2499
3263
|
} catch {
|
|
2500
|
-
|
|
3264
|
+
return false;
|
|
3265
|
+
}
|
|
3266
|
+
})();
|
|
3267
|
+
const watch = Object.entries(scripts).find(
|
|
3268
|
+
([, cmd]) => /\b(tailwindcss|sass|node-sass|postcss|lessc|stylus)\b/.test(cmd) && /(--watch|\s-w)\b/.test(cmd) || /\bgulp\b/.test(cmd) && (/\bwatch\b/.test(cmd) || gulpWatches)
|
|
3269
|
+
);
|
|
3270
|
+
if (watch) return { by: said(watch[0]), css: true };
|
|
3271
|
+
const server = Object.entries(scripts).find(([, cmd]) => /\b(vite|next dev|nuxt|astro dev|svelte-kit|remix|react-router dev|webpack serve|webpack-dev-server|parcel|eleventy --serve|ng serve|vue-cli-service serve)\b/.test(cmd));
|
|
3272
|
+
if (server) return { by: `its dev server (${said(server[0])})`, css: false };
|
|
3273
|
+
const deps = { ...p.dependencies, ...p.devDependencies };
|
|
3274
|
+
if (deps["@tailwindcss/vite"] || deps["@tailwindcss/postcss"]) return { by: "its dev server", css: false };
|
|
3275
|
+
}
|
|
3276
|
+
return void 0;
|
|
3277
|
+
}
|
|
3278
|
+
function toPx(value, theme, depth = 0) {
|
|
3279
|
+
const v = value.trim();
|
|
3280
|
+
if (depth > 5) return null;
|
|
3281
|
+
let m = /^(-?[\d.]+)(px|rem)?$/.exec(v);
|
|
3282
|
+
if (m) return m[2] === "rem" ? Number(m[1]) * REM : m[2] === "px" || Number(m[1]) === 0 ? Number(m[1]) : null;
|
|
3283
|
+
m = /^var\(--([\w-]+)(?:\s*,\s*(.+))?\)$/.exec(v);
|
|
3284
|
+
if (m) {
|
|
3285
|
+
const own = theme.get(m[1]);
|
|
3286
|
+
return own !== void 0 ? toPx(own, theme, depth + 1) : m[2] ? toPx(m[2], theme, depth + 1) : null;
|
|
3287
|
+
}
|
|
3288
|
+
m = /^calc\((.+)\)$/.exec(v);
|
|
3289
|
+
if (m) {
|
|
3290
|
+
const parts = m[1].split(/\s*([*/])\s*/);
|
|
3291
|
+
let px2 = null;
|
|
3292
|
+
let factor = 1;
|
|
3293
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
3294
|
+
const part = parts[i].trim();
|
|
3295
|
+
const op = i ? parts[i - 1] : "*";
|
|
3296
|
+
const resolved = /^var\(/.test(part) ? theme.get(/^var\(--([\w-]+)/.exec(part)?.[1] ?? "") ?? /,\s*(.+)\)$/.exec(part)?.[1] ?? "" : part;
|
|
3297
|
+
const n = /^-?[\d.]+$/.test(resolved.trim()) ? Number(resolved) : null;
|
|
3298
|
+
const len = n === null ? toPx(resolved, theme, depth + 1) : null;
|
|
3299
|
+
if (n !== null) factor = op === "/" ? factor / n : factor * n;
|
|
3300
|
+
else if (len !== null && px2 === null && op === "*") px2 = len;
|
|
3301
|
+
else return null;
|
|
3302
|
+
}
|
|
3303
|
+
return px2 === null ? null : px2 * factor;
|
|
3304
|
+
}
|
|
3305
|
+
return null;
|
|
3306
|
+
}
|
|
3307
|
+
function rgbOf(value) {
|
|
3308
|
+
const v = value.trim().toLowerCase();
|
|
3309
|
+
let m = /^#([0-9a-f]{3,8})$/.exec(v);
|
|
3310
|
+
if (m) {
|
|
3311
|
+
let h = m[1];
|
|
3312
|
+
if (h.length === 3 || h.length === 4) h = [...h].map((c) => c + c).join("");
|
|
3313
|
+
if (h.length !== 6 && h.length !== 8) return null;
|
|
3314
|
+
return { hex: `#${h.slice(0, 6)}`, alpha: h.length === 8 ? Number.parseInt(h.slice(6), 16) / 255 : 1 };
|
|
3315
|
+
}
|
|
3316
|
+
m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(v);
|
|
3317
|
+
if (m) {
|
|
3318
|
+
const hex = `#${[m[1], m[2], m[3]].map((c) => Math.round(Number(c)).toString(16).padStart(2, "0")).join("")}`;
|
|
3319
|
+
const a = m[4] ? m[4].endsWith("%") ? Number(m[4].slice(0, -1)) / 100 : Number(m[4]) : 1;
|
|
3320
|
+
return { hex, alpha: a };
|
|
3321
|
+
}
|
|
3322
|
+
return null;
|
|
3323
|
+
}
|
|
3324
|
+
var normal = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
|
|
3325
|
+
var SPACING = {
|
|
3326
|
+
padding: "p",
|
|
3327
|
+
"padding-top": "pt",
|
|
3328
|
+
"padding-right": "pr",
|
|
3329
|
+
"padding-bottom": "pb",
|
|
3330
|
+
"padding-left": "pl",
|
|
3331
|
+
"padding-inline": "px",
|
|
3332
|
+
"padding-block": "py",
|
|
3333
|
+
"padding-inline-start": "ps",
|
|
3334
|
+
"padding-inline-end": "pe",
|
|
3335
|
+
margin: "m",
|
|
3336
|
+
"margin-top": "mt",
|
|
3337
|
+
"margin-right": "mr",
|
|
3338
|
+
"margin-bottom": "mb",
|
|
3339
|
+
"margin-left": "ml",
|
|
3340
|
+
"margin-inline": "mx",
|
|
3341
|
+
"margin-block": "my",
|
|
3342
|
+
"margin-inline-start": "ms",
|
|
3343
|
+
"margin-inline-end": "me",
|
|
3344
|
+
gap: "gap",
|
|
3345
|
+
"row-gap": "gap-y",
|
|
3346
|
+
"column-gap": "gap-x",
|
|
3347
|
+
width: "w",
|
|
3348
|
+
height: "h",
|
|
3349
|
+
"min-width": "min-w",
|
|
3350
|
+
"max-width": "max-w",
|
|
3351
|
+
"min-height": "min-h",
|
|
3352
|
+
"max-height": "max-h",
|
|
3353
|
+
inset: "inset",
|
|
3354
|
+
"inset-inline": "inset-x",
|
|
3355
|
+
"inset-block": "inset-y",
|
|
3356
|
+
top: "top",
|
|
3357
|
+
right: "right",
|
|
3358
|
+
bottom: "bottom",
|
|
3359
|
+
left: "left",
|
|
3360
|
+
"text-indent": "indent"
|
|
3361
|
+
};
|
|
3362
|
+
var COLORS = {
|
|
3363
|
+
color: "text",
|
|
3364
|
+
"background-color": "bg",
|
|
3365
|
+
"border-color": "border",
|
|
3366
|
+
"border-top-color": "border-t",
|
|
3367
|
+
"border-right-color": "border-r",
|
|
3368
|
+
"border-bottom-color": "border-b",
|
|
3369
|
+
"border-left-color": "border-l",
|
|
3370
|
+
"outline-color": "outline",
|
|
3371
|
+
fill: "fill",
|
|
3372
|
+
stroke: "stroke",
|
|
3373
|
+
"text-decoration-color": "decoration",
|
|
3374
|
+
"accent-color": "accent",
|
|
3375
|
+
"caret-color": "caret"
|
|
3376
|
+
};
|
|
3377
|
+
var NAMED = {
|
|
3378
|
+
"border-radius": ["rounded", "radius"],
|
|
3379
|
+
"border-top-left-radius": ["rounded-tl", "radius"],
|
|
3380
|
+
"border-top-right-radius": ["rounded-tr", "radius"],
|
|
3381
|
+
"border-bottom-right-radius": ["rounded-br", "radius"],
|
|
3382
|
+
"border-bottom-left-radius": ["rounded-bl", "radius"],
|
|
3383
|
+
"font-size": ["text", "text"],
|
|
3384
|
+
"font-weight": ["font", "font-weight"],
|
|
3385
|
+
"letter-spacing": ["tracking", "tracking"],
|
|
3386
|
+
"line-height": ["leading", "leading"],
|
|
3387
|
+
"box-shadow": ["shadow", "shadow"]
|
|
3388
|
+
};
|
|
3389
|
+
function scale(theme, namespace) {
|
|
3390
|
+
const out = [];
|
|
3391
|
+
for (const [key, value] of theme) {
|
|
3392
|
+
if (!key.startsWith(`${namespace}-`) || key.includes("--")) continue;
|
|
3393
|
+
const name = key.slice(namespace.length + 1);
|
|
3394
|
+
if (namespace === "text" && /^shadow/.test(name)) continue;
|
|
3395
|
+
out.push([name, value]);
|
|
3396
|
+
}
|
|
3397
|
+
return out;
|
|
3398
|
+
}
|
|
3399
|
+
var px = (n) => `${Math.round(n * 100) / 100}px`;
|
|
3400
|
+
function classFor(property, value, theme) {
|
|
3401
|
+
const v = value.trim();
|
|
3402
|
+
if (!v) return null;
|
|
3403
|
+
const variable = /^var\(--([\w-]+)\)$/.exec(v)?.[1];
|
|
3404
|
+
const spacingUtility = SPACING[property];
|
|
3405
|
+
if (spacingUtility) {
|
|
3406
|
+
if (v === "auto") return { exact: `${spacingUtility}-auto` };
|
|
3407
|
+
if (v === "100%" && /^(w|h|min-w|max-w|min-h|max-h|inset|top|right|bottom|left)/.test(spacingUtility)) return { exact: `${spacingUtility}-full` };
|
|
3408
|
+
const frac = /^([\d.]+)%$/.exec(v);
|
|
3409
|
+
if (frac && /^[wh]$/.test(spacingUtility)) {
|
|
3410
|
+
const f = Number(frac[1]) / 100;
|
|
3411
|
+
for (let q = 2; q <= 12; q++) for (let p = 1; p < q; p++) if (Math.abs(p / q - f) < 5e-4) return { exact: `${spacingUtility}-${p}/${q}` };
|
|
3412
|
+
}
|
|
3413
|
+
if (spacingUtility === "max-w") {
|
|
3414
|
+
const named2 = scale(theme, "container").find(([, size]) => toPx(size, theme) === toPx(v, theme));
|
|
3415
|
+
if (named2) return { exact: `max-w-${named2[0]}` };
|
|
3416
|
+
}
|
|
3417
|
+
const n2 = toPx(v, theme);
|
|
3418
|
+
const step = toPx(theme.get("spacing") ?? "0.25rem", theme);
|
|
3419
|
+
if (n2 === null || !step) return null;
|
|
3420
|
+
const negative = n2 < 0 && /^(m|inset|top|right|bottom|left)/.test(spacingUtility) ? "-" : "";
|
|
3421
|
+
const steps = Math.abs(n2) / step;
|
|
3422
|
+
if (Math.abs(n2) === 1 && step !== 1) return { exact: `${negative}${spacingUtility}-px` };
|
|
3423
|
+
if (Math.abs(steps * 4 - Math.round(steps * 4)) < 1e-6) return { exact: `${negative}${spacingUtility}-${Math.round(steps * 100) / 100}` };
|
|
3424
|
+
return { exact: `${negative}${spacingUtility}-[${px(Math.abs(n2))}]` };
|
|
3425
|
+
}
|
|
3426
|
+
const colorUtility = COLORS[property];
|
|
3427
|
+
if (colorUtility) {
|
|
3428
|
+
if (variable?.startsWith("color-")) return { exact: `${colorUtility}-${variable.slice(6)}` };
|
|
3429
|
+
if (/^(transparent|currentcolor|inherit)$/i.test(v)) return { exact: `${colorUtility}-${v.toLowerCase() === "currentcolor" ? "current" : v.toLowerCase()}` };
|
|
3430
|
+
const rgb = rgbOf(v);
|
|
3431
|
+
for (const [name, color] of scale(theme, "color")) {
|
|
3432
|
+
const own = rgbOf(color);
|
|
3433
|
+
if (rgb && own && own.hex === rgb.hex) {
|
|
3434
|
+
const alpha = Math.round(rgb.alpha * 100);
|
|
3435
|
+
return { exact: `${colorUtility}-${name}${alpha < 100 ? `/${alpha}` : ""}` };
|
|
2501
3436
|
}
|
|
2502
|
-
if (
|
|
2503
|
-
else if (EXTENSIONS2.has(extname3(name)) && stat2.size <= MAX_FILE_BYTES3) files.push(path);
|
|
3437
|
+
if (!rgb && normal(color) === normal(v)) return { exact: `${colorUtility}-${name}` };
|
|
2504
3438
|
}
|
|
3439
|
+
return { exact: `${colorUtility}-[${v.replace(/\s+/g, "_")}]`, note: "no color of the theme" };
|
|
3440
|
+
}
|
|
3441
|
+
if (property === "opacity") {
|
|
3442
|
+
const n2 = /^([\d.]+)(%)?$/.exec(v);
|
|
3443
|
+
if (n2) return { exact: `opacity-${Math.round(Number(n2[1]) * (n2[2] ? 1 : 100))}` };
|
|
3444
|
+
return null;
|
|
3445
|
+
}
|
|
3446
|
+
if (property === "z-index" && /^-?\d+$/.test(v)) return { exact: `${v.startsWith("-") ? "-" : ""}z-${v.replace("-", "")}` };
|
|
3447
|
+
if (property === "font-family") {
|
|
3448
|
+
const first = normal(v.split(",")[0]).replace(/["']/g, "");
|
|
3449
|
+
const named2 = scale(theme, "font").find(([name, family]) => !name.startsWith("weight") && normal(family.split(",")[0]).replace(/["']/g, "") === first);
|
|
3450
|
+
return named2 ? { exact: `font-${named2[0]}` } : null;
|
|
3451
|
+
}
|
|
3452
|
+
const named = NAMED[property];
|
|
3453
|
+
if (!named) return null;
|
|
3454
|
+
const [utility, namespace] = named;
|
|
3455
|
+
if (variable?.startsWith(`${namespace}-`)) return { exact: `${utility}-${variable.slice(namespace.length + 1)}` };
|
|
3456
|
+
const values = scale(theme, namespace);
|
|
3457
|
+
if (namespace === "shadow") {
|
|
3458
|
+
const same = values.find(([, s]) => normal(s) === normal(v));
|
|
3459
|
+
return same ? { exact: `shadow-${same[0]}` } : null;
|
|
3460
|
+
}
|
|
3461
|
+
if (namespace === "radius") {
|
|
3462
|
+
if (/^(0|0px)$/.test(v)) return { exact: `${utility}-none` };
|
|
3463
|
+
if (/^(9999px|calc\(infinity \* 1px\)|50%)$/.test(v)) return { exact: `${utility}-full` };
|
|
3464
|
+
}
|
|
3465
|
+
if (namespace === "tracking") {
|
|
3466
|
+
const same = values.find(([, s]) => s.trim() === v || /^-?0(em)?$/.test(s.trim()) && /^-?0(em|px)?$/.test(v));
|
|
3467
|
+
return same ? { exact: `tracking-${same[0]}` } : { exact: `tracking-[${v}]` };
|
|
3468
|
+
}
|
|
3469
|
+
if (namespace === "font-weight" || namespace === "leading") {
|
|
3470
|
+
const same = values.find(([, s]) => s.trim() === v);
|
|
3471
|
+
if (same) return { exact: `${utility}-${same[0]}` };
|
|
3472
|
+
if (namespace === "font-weight") return /^\d+$/.test(v) ? { exact: `font-[${v}]` } : null;
|
|
3473
|
+
const n2 = toPx(v, theme);
|
|
3474
|
+
const step = toPx(theme.get("spacing") ?? "0.25rem", theme);
|
|
3475
|
+
if (n2 !== null && step && Math.abs(n2 / step * 4 - Math.round(n2 / step * 4)) < 1e-6) return { exact: `leading-${Math.round(n2 / step * 100) / 100}` };
|
|
3476
|
+
return { exact: `leading-[${v}]` };
|
|
3477
|
+
}
|
|
3478
|
+
const n = toPx(v, theme);
|
|
3479
|
+
if (n === null) return null;
|
|
3480
|
+
let best = null;
|
|
3481
|
+
for (const [name, size] of values) {
|
|
3482
|
+
const p = toPx(size, theme);
|
|
3483
|
+
if (p === null) continue;
|
|
3484
|
+
if (Math.abs(p - n) < 0.01) return { exact: `${utility}-${name}` };
|
|
3485
|
+
if (!best || Math.abs(p - n) < Math.abs(best.px - n)) best = { name, px: p };
|
|
3486
|
+
}
|
|
3487
|
+
const arbitrary = `${utility}-[${px(n)}]`;
|
|
3488
|
+
return best ? { exact: arbitrary, closest: { cls: `${utility}-${best.name}`, px: best.px } } : { exact: arbitrary };
|
|
3489
|
+
}
|
|
3490
|
+
function prefixFor(change, theme) {
|
|
3491
|
+
const widths = change.widths;
|
|
3492
|
+
const points = scale(theme, "breakpoint").map(([name, size]) => ({ name, px: toPx(size, theme) })).filter((b) => b.px !== null);
|
|
3493
|
+
let prefix = "";
|
|
3494
|
+
if (widths?.min !== void 0) prefix += `${points.find((b) => b.px === widths.min)?.name ?? `min-[${widths.min}px]`}:`;
|
|
3495
|
+
if (widths?.max !== void 0) {
|
|
3496
|
+
const at = points.find((b) => b.px === widths.max + 1);
|
|
3497
|
+
prefix += `max-${at ? at.name : `[${widths.max + 1}px]`}:`;
|
|
3498
|
+
}
|
|
3499
|
+
for (const s of change.states ?? []) prefix += `${s}:`;
|
|
3500
|
+
return prefix;
|
|
3501
|
+
}
|
|
3502
|
+
function factsSection(job, root, near = []) {
|
|
3503
|
+
const lines = [];
|
|
3504
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3505
|
+
const add = (line) => {
|
|
3506
|
+
if (!seen.has(line)) lines.push(line);
|
|
3507
|
+
seen.add(line);
|
|
2505
3508
|
};
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
3509
|
+
let tw = null;
|
|
3510
|
+
try {
|
|
3511
|
+
tw = tailwindOf(root, near, job.changeSet.page?.url);
|
|
3512
|
+
} catch {
|
|
3513
|
+
}
|
|
3514
|
+
if (tw) {
|
|
3515
|
+
const step = toPx(tw.theme.get("spacing") ?? "0.25rem", tw.theme);
|
|
3516
|
+
add(`- Tailwind CSS ${tw.version?.replace(/^[^\d]*/, "") ?? "4"}, its theme in \`${tw.entry}\` (\`@theme\`) and Tailwind's defaults; spacing steps of ${step ? px(step) : "0.25rem"} (\`--spacing\`).`);
|
|
3517
|
+
}
|
|
3518
|
+
for (const edit of job.changeSet.edits) {
|
|
3519
|
+
for (const change of edit.changes) {
|
|
3520
|
+
if (tw && !change.removed) {
|
|
3521
|
+
const cls = classFor(change.property, change.to, tw.theme);
|
|
3522
|
+
if (cls) {
|
|
3523
|
+
const prefix = prefixFor(change, tw.theme);
|
|
3524
|
+
add(
|
|
3525
|
+
`- \`${change.property}: ${change.to}\`${prefix ? ` (${prefix.slice(0, -1).replaceAll(":", ", ")})` : ""} is \`${prefix}${cls.exact}\`${cls.closest ? `, no step of the scale; its closest is \`${prefix}${cls.closest.cls}\` (${px(cls.closest.px)})` : ""}${cls.note ? ` (${cls.note})` : ""}.`
|
|
3526
|
+
);
|
|
3527
|
+
}
|
|
3528
|
+
}
|
|
3529
|
+
const source = change.source;
|
|
3530
|
+
if (source?.kind !== "rule") continue;
|
|
3531
|
+
let at = null;
|
|
3532
|
+
try {
|
|
3533
|
+
at = ruleSource(source.selector, change.property, root, near, source.media);
|
|
3534
|
+
} catch {
|
|
3535
|
+
}
|
|
3536
|
+
if (!at) continue;
|
|
3537
|
+
const d = at.declaration;
|
|
3538
|
+
add(
|
|
3539
|
+
d ? `- \`${change.property}\` is set by \`${source.selector}\` in \`${at.rule.file}:${d.line}\`: \`${d.property}: ${d.value};\`.` : `- \`${change.property}\` is set by \`${source.selector}\`, the rule at \`${at.rule.file}:${at.rule.line}\` (not written in it as is: a mixin or an include gives it).`
|
|
3540
|
+
);
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
const request = job.changeSet.request;
|
|
3544
|
+
if (request && request.kind !== "props") {
|
|
3545
|
+
for (const target of [request.target, ...request.others ?? []]) {
|
|
3546
|
+
for (const st of target.style ?? []) {
|
|
3547
|
+
if (st.source?.kind !== "rule") continue;
|
|
3548
|
+
let at = null;
|
|
3549
|
+
try {
|
|
3550
|
+
at = ruleSource(st.source.selector, st.property, root, near, st.source.media);
|
|
3551
|
+
} catch {
|
|
3552
|
+
}
|
|
3553
|
+
if (at?.declaration) add(`- \`${target.path}\`'s \`${st.property}\` is set in \`${at.rule.file}:${at.declaration.line}\`: \`${at.declaration.property}: ${at.declaration.value};\`.`);
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
if (tw) lines.push(...tailwindScales(tw));
|
|
3557
|
+
else lines.push(...tokenScales(job.changeSet.tokens ?? []));
|
|
3558
|
+
}
|
|
3559
|
+
const pkg = near.length ? nearestPackage(dirname7(join11(root, near[0])), root) : null;
|
|
3560
|
+
const rebuild = rebuildOf(pkg ?? (tw ? nearestPackage(dirname7(join11(root, tw.entry)), root) : null), root);
|
|
3561
|
+
if (rebuild)
|
|
3562
|
+
add(
|
|
3563
|
+
rebuild.css ? `- Its CSS is rebuilt on save by ${rebuild.by}, so a change works at once: don't build it or check the compiled CSS.` : `- ${rebuild.by[0]?.toUpperCase()}${rebuild.by.slice(1)} updates the page on save: don't build it or check the compiled output.`
|
|
3564
|
+
);
|
|
3565
|
+
return lines.length ? ["## The project", "", ...lines].join("\n") : "";
|
|
3566
|
+
}
|
|
3567
|
+
var MAX_STEPS = 16;
|
|
3568
|
+
var MAX_SCALES = 14;
|
|
3569
|
+
function scaleLine(tw, namespace, label) {
|
|
3570
|
+
const steps = scale(tw.theme, namespace).filter(([name]) => !(namespace === "font" && name.startsWith("weight")));
|
|
3571
|
+
if (!steps.length) return null;
|
|
3572
|
+
const shown = steps.slice(0, MAX_STEPS).map(([name, value]) => {
|
|
3573
|
+
const n = /rem$|^calc\(/.test(value) ? toPx(value, tw.theme) : null;
|
|
3574
|
+
const v = namespace === "font" ? value.split(",")[0].replace(/["']/g, "").trim() : n !== null ? px(n) : value;
|
|
3575
|
+
return `\`${name}\` ${v}`;
|
|
3576
|
+
});
|
|
3577
|
+
return ` - ${label}: ${shown.join(", ")}${steps.length > MAX_STEPS ? ", \u2026" : ""}`;
|
|
2509
3578
|
}
|
|
2510
|
-
function
|
|
2511
|
-
|
|
3579
|
+
function tailwindScales(tw) {
|
|
3580
|
+
const colors = scale(tw.theme, "color").filter(([name]) => tw.own.has(`color-${name}`));
|
|
3581
|
+
const lines = [
|
|
3582
|
+
scaleLine(tw, "tracking", "letter spacing (`tracking-`)"),
|
|
3583
|
+
scaleLine(tw, "font-weight", "font weight (`font-`)"),
|
|
3584
|
+
scaleLine(tw, "text", "font size (`text-`)"),
|
|
3585
|
+
scaleLine(tw, "leading", "line height (`leading-`)"),
|
|
3586
|
+
scaleLine(tw, "radius", "radius (`rounded-`)"),
|
|
3587
|
+
scaleLine(tw, "font", "font family (`font-`)"),
|
|
3588
|
+
scaleLine(tw, "breakpoint", "breakpoints"),
|
|
3589
|
+
colors.length ? ` - the project's colors (\`text-\`, \`bg-\`\u2026): ${colors.slice(0, 24).map(([name, value]) => `\`${name}\` ${value}`).join(", ")}${colors.length > 24 ? ", \u2026" : ""}` : null
|
|
3590
|
+
].filter((l) => !!l);
|
|
3591
|
+
return lines.length ? ["- Its theme's scales (only these exist, with the spacing steps above and Tailwind's palette):", ...lines] : [];
|
|
3592
|
+
}
|
|
3593
|
+
function tokenScales(tokens) {
|
|
3594
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3595
|
+
for (const t of tokens) {
|
|
3596
|
+
const m = /^(--[\w-]*?)-?([\w]+)$/.exec(t.name);
|
|
3597
|
+
const group = m && m[1] && m[1] !== "--" ? `${m[1]}-*` : t.name;
|
|
3598
|
+
const step = m && m[1] && m[1] !== "--" ? m[2] : "";
|
|
3599
|
+
const value = t.now ?? (t.value.length > 40 ? `${t.value.slice(0, 39)}\u2026` : t.value);
|
|
3600
|
+
groups.set(group, [...groups.get(group) ?? [], step ? `${step} ${value}` : value]);
|
|
3601
|
+
}
|
|
3602
|
+
const lines = [...groups].filter(([, steps]) => steps.length > 1).slice(0, MAX_SCALES).map(([group, steps]) => ` - \`${group}\`: ${steps.slice(0, MAX_STEPS).join(", ")}${steps.length > MAX_STEPS ? ", \u2026" : ""}`);
|
|
3603
|
+
return lines.length ? ["- The page's tokens, by scale (what each comes to at this width): use these rather than raw values", ...lines] : [];
|
|
2512
3604
|
}
|
|
3605
|
+
|
|
3606
|
+
// src/locate.ts
|
|
3607
|
+
import { existsSync as existsSync8, readdirSync as readdirSync6, readFileSync as readFileSync10, statSync as statSync7 } from "fs";
|
|
3608
|
+
import { basename as basename6, extname as extname5, isAbsolute, join as join12, relative as relative7 } from "path";
|
|
2513
3609
|
var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
3610
|
+
var BUDGET_MS3 = 800;
|
|
3611
|
+
var CANDIDATE_FILES = 60;
|
|
3612
|
+
var PARENT_LINES = 400;
|
|
3613
|
+
var BODY_LINES = 80;
|
|
3614
|
+
var NEAR_LINES = 30;
|
|
3615
|
+
function searchable(cwd) {
|
|
3616
|
+
return existsSync8(join12(cwd, "package.json")) || existsSync8(join12(cwd, ".git"));
|
|
3617
|
+
}
|
|
3618
|
+
var ENTITIES = {
|
|
3619
|
+
amp: "&",
|
|
3620
|
+
nbsp: " ",
|
|
3621
|
+
quot: '"',
|
|
3622
|
+
apos: "'",
|
|
3623
|
+
lt: "<",
|
|
3624
|
+
gt: ">",
|
|
3625
|
+
rsquo: "'",
|
|
3626
|
+
lsquo: "'",
|
|
3627
|
+
ldquo: '"',
|
|
3628
|
+
rdquo: '"',
|
|
3629
|
+
mdash: "\u2014",
|
|
3630
|
+
ndash: "\u2013",
|
|
3631
|
+
hellip: "\u2026",
|
|
3632
|
+
copy: "\xA9",
|
|
3633
|
+
reg: "\xAE",
|
|
3634
|
+
trade: "\u2122",
|
|
3635
|
+
times: "\xD7",
|
|
3636
|
+
middot: "\xB7",
|
|
3637
|
+
rarr: "\u2192",
|
|
3638
|
+
larr: "\u2190"
|
|
3639
|
+
};
|
|
3640
|
+
function plain(s) {
|
|
3641
|
+
return s.replace(/&(#\d+|#x[0-9a-f]+|[a-z]+);/gi, (m, e) => {
|
|
3642
|
+
if (e[0] === "#") {
|
|
3643
|
+
const code = e[1] === "x" || e[1] === "X" ? Number.parseInt(e.slice(2), 16) : Number(e.slice(1));
|
|
3644
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : m;
|
|
3645
|
+
}
|
|
3646
|
+
return ENTITIES[e.toLowerCase()] ?? m;
|
|
3647
|
+
}).replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, " ");
|
|
3648
|
+
}
|
|
3649
|
+
function* tagsOn(line) {
|
|
3650
|
+
const re = /<([A-Za-z][\w.:-]*)(?=[\s>/]|$)/g;
|
|
3651
|
+
for (let m = re.exec(line); m; m = re.exec(line)) yield { name: m[1], column: m.index };
|
|
3652
|
+
}
|
|
3653
|
+
var indentOf = (line) => /^\s*/.exec(line)[0].length;
|
|
3654
|
+
var isPlain = (name) => name === name.toLowerCase() && !name.includes(".");
|
|
3655
|
+
function needlesOf(target, url, root, rarity) {
|
|
3656
|
+
const own = target.text?.replace(/…$/, "").trim();
|
|
3657
|
+
const texts = [];
|
|
3658
|
+
const usable = (t) => {
|
|
3659
|
+
const text = t ? plain(t).trim() : "";
|
|
3660
|
+
return text.length >= 2 && text.length <= 80 ? text : void 0;
|
|
3661
|
+
};
|
|
3662
|
+
for (const t of [own, ...target.context?.texts ?? []]) {
|
|
3663
|
+
const text = usable(t);
|
|
3664
|
+
if (text && !texts.includes(text)) texts.push(text);
|
|
3665
|
+
}
|
|
3666
|
+
let route = [];
|
|
3667
|
+
try {
|
|
3668
|
+
if (url)
|
|
3669
|
+
route = new URL(url).pathname.split("/").map((p) => decodeURIComponent(p).replace(/\.[a-z]+$/i, "")).filter((p) => p && p !== "index");
|
|
3670
|
+
} catch {
|
|
3671
|
+
}
|
|
3672
|
+
const served = route.find((p) => !/[\\/]|^\.+$/.test(p) && isFolder(join12(root, p)));
|
|
3673
|
+
const otherSites = /* @__PURE__ */ new Set();
|
|
3674
|
+
if (served) {
|
|
3675
|
+
for (const name of safeList(root))
|
|
3676
|
+
if (name !== served && INDEX_FILES.some((f) => existsSync8(join12(root, name, f)))) otherSites.add(name);
|
|
3677
|
+
}
|
|
3678
|
+
const before = usable(target.context?.before);
|
|
3679
|
+
const after = usable(target.context?.after);
|
|
3680
|
+
const heading = usable(target.context?.heading);
|
|
2517
3681
|
return {
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
3682
|
+
tag: target.tag.toLowerCase(),
|
|
3683
|
+
...target.id ? { id: target.id } : {},
|
|
3684
|
+
classes: target.classes.filter((c) => c.length >= 2),
|
|
3685
|
+
texts,
|
|
3686
|
+
attrs: (target.context?.attrs ?? []).map(plain),
|
|
3687
|
+
...before ? { before } : {},
|
|
3688
|
+
...after ? { after } : {},
|
|
3689
|
+
...heading ? { heading } : {},
|
|
3690
|
+
parents: target.context?.parents ?? [],
|
|
3691
|
+
route,
|
|
3692
|
+
...served ? { served } : {},
|
|
3693
|
+
otherSites,
|
|
3694
|
+
empty: !own && !texts.length && !!target.context,
|
|
3695
|
+
...own && !target.text?.endsWith("\u2026") ? { own: plain(own).trim() } : {},
|
|
3696
|
+
rarity
|
|
2524
3697
|
};
|
|
2525
3698
|
}
|
|
2526
|
-
function
|
|
2527
|
-
const
|
|
3699
|
+
function textWeight(n, text) {
|
|
3700
|
+
const words = wordsOf(text);
|
|
3701
|
+
if (!words.length) return 0;
|
|
3702
|
+
const rarest = Math.max(...words.map(n.rarity));
|
|
3703
|
+
return Math.min(8, Math.max(0.5, rarest) + Math.min(3, (words.length - 1) * 0.5));
|
|
3704
|
+
}
|
|
3705
|
+
function textFound(body2, text) {
|
|
3706
|
+
if (body2.includes(text)) return 1;
|
|
3707
|
+
const words = text.split(" ");
|
|
3708
|
+
if (words.length < 6) return 0;
|
|
3709
|
+
const run2 = (from) => words.slice(from, from + 5).join(" ");
|
|
3710
|
+
return body2.includes(run2(1)) || body2.includes(run2(words.length - 6)) || body2.includes(run2(words.length >> 1)) ? 0.7 : 0;
|
|
3711
|
+
}
|
|
3712
|
+
function writtenText(code) {
|
|
3713
|
+
return plain(
|
|
3714
|
+
code.replace(/<\?[\s\S]*?(\?>|$)|<%[\s\S]*?(%>|$)|\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\{[^}]*\}/g, " ").replace(/<!--[\s\S]*?-->/g, " ").replace(/<\/?[A-Za-z][^>]*>?/g, " ")
|
|
3715
|
+
).trim();
|
|
3716
|
+
}
|
|
3717
|
+
function openingAt(lines, index, column) {
|
|
3718
|
+
let text = "";
|
|
3719
|
+
let quote2 = "";
|
|
3720
|
+
let braces = 0;
|
|
3721
|
+
for (let j = index; j < Math.min(lines.length, index + 16); j++) {
|
|
3722
|
+
const line = j === index ? lines[j].slice(column) : lines[j];
|
|
3723
|
+
for (let k = j === index ? 1 : 0; k < line.length; k++) {
|
|
3724
|
+
const ch = line[k];
|
|
3725
|
+
if (ch === "<" && (line[k + 1] === "?" || line[k + 1] === "%")) {
|
|
3726
|
+
const close = line.indexOf(line[k + 1] === "?" ? "?>" : "%>", k + 2);
|
|
3727
|
+
if (close < 0) break;
|
|
3728
|
+
k = close + 1;
|
|
3729
|
+
continue;
|
|
3730
|
+
}
|
|
3731
|
+
if (quote2) {
|
|
3732
|
+
if (ch === quote2) quote2 = "";
|
|
3733
|
+
} else if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
|
|
3734
|
+
else if (ch === "{") braces++;
|
|
3735
|
+
else if (ch === "}") braces = Math.max(0, braces - 1);
|
|
3736
|
+
else if (ch === ">" && !braces) return { text: text + line.slice(0, k + 1), end: j };
|
|
3737
|
+
}
|
|
3738
|
+
text += `${line}
|
|
3739
|
+
`;
|
|
3740
|
+
}
|
|
3741
|
+
return { text, end: index };
|
|
3742
|
+
}
|
|
3743
|
+
function classAttrOf(opening) {
|
|
3744
|
+
const re = /(?<![\w-]):?(?:class|className)\s*=\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`|\{([\s\S]*?)\}(?=\s|\/?>|$))/g;
|
|
3745
|
+
let words = null;
|
|
3746
|
+
let dynamic = false;
|
|
3747
|
+
for (let m = re.exec(opening); m; m = re.exec(opening)) {
|
|
3748
|
+
const quoted = m[1] ?? m[2] ?? m[3];
|
|
3749
|
+
let value;
|
|
3750
|
+
if (quoted !== void 0 && !m[0].startsWith(":")) {
|
|
3751
|
+
value = quoted.replace(/<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\$\{[^}]*\}|\{[^}]*\}/g, () => {
|
|
3752
|
+
dynamic = true;
|
|
3753
|
+
return " ";
|
|
3754
|
+
});
|
|
3755
|
+
} else {
|
|
3756
|
+
dynamic = true;
|
|
3757
|
+
value = [...(quoted ?? m[4] ?? "").matchAll(/["'`]([^"'`]*)["'`]/g)].map((s) => s[1]).join(" ");
|
|
3758
|
+
}
|
|
3759
|
+
words = [...words ?? [], ...wordsOf(value)];
|
|
3760
|
+
}
|
|
3761
|
+
return words ? { words, dynamic } : null;
|
|
3762
|
+
}
|
|
3763
|
+
function classesScore(n, classes, opening) {
|
|
3764
|
+
const facts = [];
|
|
3765
|
+
if (!classes.length) return { score: 0, clear: false, facts };
|
|
3766
|
+
const words = new Set(wordsOf(opening));
|
|
3767
|
+
let matched = 0;
|
|
3768
|
+
let score = 0;
|
|
3769
|
+
for (const c of classes) {
|
|
3770
|
+
if (!words.has(c)) continue;
|
|
3771
|
+
matched++;
|
|
3772
|
+
facts.push(`class:${c}`);
|
|
3773
|
+
score += Math.max(0.2, n.rarity(c));
|
|
3774
|
+
}
|
|
3775
|
+
if (!matched) return { score: 0, clear: false, facts };
|
|
3776
|
+
const attr = classAttrOf(opening);
|
|
3777
|
+
let consistent = false;
|
|
3778
|
+
if (attr?.words.length) {
|
|
3779
|
+
const extras = attr.words.filter((c) => !classes.includes(c));
|
|
3780
|
+
const extra = extras.length;
|
|
3781
|
+
for (const c of extras) facts.push(`-class:${c}`);
|
|
3782
|
+
if (!attr.dynamic) {
|
|
3783
|
+
if (extra && classes.length - matched >= 2) return { score: -8, clear: false, facts: [...facts, "-classes"] };
|
|
3784
|
+
score -= Math.min(9, extra * 3);
|
|
3785
|
+
if (!extra && matched === classes.length) {
|
|
3786
|
+
score += 3;
|
|
3787
|
+
facts.push("classes-exact");
|
|
3788
|
+
}
|
|
3789
|
+
} else if (extra > attr.words.length / 2) score -= Math.min(4, extra);
|
|
3790
|
+
consistent = extra === 0;
|
|
3791
|
+
}
|
|
3792
|
+
const clear = matched >= Math.ceil(classes.length * 0.6) || consistent && attr?.dynamic === true || score >= 6;
|
|
3793
|
+
return { score, clear, facts };
|
|
3794
|
+
}
|
|
3795
|
+
function bodyEnd(lines, index, openingEnd) {
|
|
3796
|
+
const indent = indentOf(lines[index]);
|
|
3797
|
+
const last = Math.min(lines.length - 1, index + BODY_LINES);
|
|
3798
|
+
for (let j = openingEnd + 1; j <= last; j++) {
|
|
3799
|
+
const line = lines[j];
|
|
3800
|
+
if (!line.trim()) continue;
|
|
3801
|
+
const ind = indentOf(line);
|
|
3802
|
+
if (ind < indent) return j - 1;
|
|
3803
|
+
if (ind === indent) return /^\s*<\//.test(line) ? j : j - 1;
|
|
3804
|
+
}
|
|
3805
|
+
return last;
|
|
3806
|
+
}
|
|
3807
|
+
function scoreAt(n, file, beside, index, column, name) {
|
|
3808
|
+
const lower = name.toLowerCase();
|
|
3809
|
+
if (lower !== n.tag && isPlain(name)) return null;
|
|
3810
|
+
const { lines } = file;
|
|
3811
|
+
const opening = openingAt(lines, index, column);
|
|
3812
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
3813
|
+
const facts = new Set(lower === n.tag ? ["tag"] : []);
|
|
3814
|
+
let score = lower === n.tag ? 1 : 0;
|
|
3815
|
+
if (n.id && opening.text.includes(n.id) && new RegExp(`\\bid\\s*=\\s*[{"'\`]*${escape(n.id)}["'\`}]`).test(opening.text)) {
|
|
3816
|
+
score += 8;
|
|
3817
|
+
kinds.add("id");
|
|
3818
|
+
facts.add("id");
|
|
3819
|
+
}
|
|
3820
|
+
const classes = classesScore(n, n.classes, opening.text);
|
|
3821
|
+
if (classes.clear) kinds.add("classes");
|
|
3822
|
+
for (const f of classes.facts) facts.add(f);
|
|
3823
|
+
score += classes.score;
|
|
3824
|
+
if (n.classes.length && !classes.score && !kinds.has("id") && classAttrOf(opening.text)?.words.length) return null;
|
|
3825
|
+
const end = bodyEnd(lines, index, opening.end);
|
|
3826
|
+
if (!n.texts.length && !n.empty) {
|
|
3827
|
+
} else if (n.empty) {
|
|
3828
|
+
const code = [lines[index].slice(column), ...lines.slice(index + 1, end + 1)].join("\n");
|
|
3829
|
+
if (writtenText(code).length >= 2) {
|
|
3830
|
+
score -= 4;
|
|
3831
|
+
facts.add("-text");
|
|
3832
|
+
}
|
|
3833
|
+
}
|
|
3834
|
+
if (n.texts.length || n.attrs.length) {
|
|
3835
|
+
const code = [lines[index].slice(column), ...lines.slice(index + 1, end + 1)].join("\n");
|
|
3836
|
+
const body2 = plain(code);
|
|
3837
|
+
let texts = 0;
|
|
3838
|
+
for (const t of n.texts) {
|
|
3839
|
+
const found = textFound(body2, t);
|
|
3840
|
+
if (found) facts.add(`text:${t}`);
|
|
3841
|
+
texts += found * textWeight(n, t);
|
|
3842
|
+
}
|
|
3843
|
+
if (texts) {
|
|
3844
|
+
score += Math.min(14, texts);
|
|
3845
|
+
kinds.add("text");
|
|
3846
|
+
}
|
|
3847
|
+
const written = n.texts.length ? writtenText(code) : "";
|
|
3848
|
+
if (written && n.own && written.length <= 120 && !n.own.includes(written) && !body2.includes(n.own)) {
|
|
3849
|
+
score -= 4;
|
|
3850
|
+
facts.add("-text");
|
|
3851
|
+
}
|
|
3852
|
+
let attrs = 0;
|
|
3853
|
+
for (const a of n.attrs)
|
|
3854
|
+
if (body2.includes(a)) {
|
|
3855
|
+
facts.add(`attr:${a}`);
|
|
3856
|
+
attrs += Math.min(6, Math.max(1, textWeight(n, a)));
|
|
3857
|
+
}
|
|
3858
|
+
if (attrs) {
|
|
3859
|
+
score += Math.min(10, attrs);
|
|
3860
|
+
kinds.add("attrs");
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
let near = 0;
|
|
3864
|
+
const within = (at, from, to) => at.some((i) => i >= from && i <= to);
|
|
3865
|
+
if (n.before && (within(beside.before, index - NEAR_LINES, index - 1) || beside.before.includes(index) && plain(lines[index].slice(0, column)).includes(n.before))) {
|
|
3866
|
+
near += Math.min(5, textWeight(n, n.before));
|
|
3867
|
+
facts.add("before");
|
|
3868
|
+
}
|
|
3869
|
+
if (n.after && within(beside.after, end, end + NEAR_LINES)) {
|
|
3870
|
+
near += Math.min(5, textWeight(n, n.after));
|
|
3871
|
+
facts.add("after");
|
|
3872
|
+
}
|
|
3873
|
+
if (n.heading) {
|
|
3874
|
+
let h = -1;
|
|
3875
|
+
for (const i of beside.headings) if (i < index) h = i;
|
|
3876
|
+
let last = h;
|
|
3877
|
+
while (h >= 0 && last < Math.min(h + 2, index - 1) && !/<\/h[1-6]>/i.test(lines[last])) last++;
|
|
3878
|
+
if (h >= 0 && plain(lines.slice(h, last + 1).join(" ")).includes(n.heading)) {
|
|
3879
|
+
near += Math.min(4, textWeight(n, n.heading));
|
|
3880
|
+
facts.add("heading");
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
if (near) {
|
|
3884
|
+
score += near;
|
|
3885
|
+
kinds.add("near");
|
|
3886
|
+
}
|
|
3887
|
+
const parents = parentsScore(n, lines, index, column);
|
|
3888
|
+
if (parents.score) {
|
|
3889
|
+
score += parents.score;
|
|
3890
|
+
kinds.add("parents");
|
|
3891
|
+
for (let i = 0; i < parents.found; i++) facts.add(`parent:${i}`);
|
|
3892
|
+
}
|
|
3893
|
+
return { file, index, column, score, classScore: classes.score, kinds, facts };
|
|
3894
|
+
}
|
|
3895
|
+
var VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
|
3896
|
+
function selfClosing(lines, index, column) {
|
|
3897
|
+
const rest = lines[index].slice(column);
|
|
3898
|
+
const end = rest.indexOf(">");
|
|
3899
|
+
if (end > 0 && !/["'`{]/.test(rest.slice(0, end))) return rest[end - 1] === "/";
|
|
3900
|
+
return /\/>$/.test(openingAt(lines, index, column).text);
|
|
3901
|
+
}
|
|
3902
|
+
function parentOf(lines, index, column) {
|
|
3903
|
+
const open = [];
|
|
3904
|
+
for (let j = index; j >= Math.max(0, index - PARENT_LINES); j--) {
|
|
3905
|
+
const line = j === index ? lines[j].slice(0, column) : lines[j];
|
|
3906
|
+
if (!line.includes("<")) continue;
|
|
3907
|
+
const tags = [...line.matchAll(/<(\/?)([A-Za-z][\w.:-]*)(?=[\s>/]|$)/g)];
|
|
3908
|
+
for (let t = tags.length - 1; t >= 0; t--) {
|
|
3909
|
+
const m = tags[t];
|
|
3910
|
+
const name = m[2].toLowerCase();
|
|
3911
|
+
if (m[1]) {
|
|
3912
|
+
open.push(name);
|
|
3913
|
+
continue;
|
|
3914
|
+
}
|
|
3915
|
+
if (VOID.has(name) || selfClosing(lines, j, m.index)) continue;
|
|
3916
|
+
const closed = open.lastIndexOf(name);
|
|
3917
|
+
if (closed >= 0) {
|
|
3918
|
+
open.length = closed;
|
|
3919
|
+
continue;
|
|
3920
|
+
}
|
|
3921
|
+
return { index: j, column: m.index, name: m[2] };
|
|
3922
|
+
}
|
|
3923
|
+
}
|
|
3924
|
+
return null;
|
|
3925
|
+
}
|
|
3926
|
+
function parentsScore(n, lines, index, column) {
|
|
3927
|
+
let score = 0;
|
|
3928
|
+
let found = 0;
|
|
3929
|
+
let at = { index, column };
|
|
3930
|
+
for (const p of n.parents) {
|
|
3931
|
+
const parent = parentOf(lines, at.index, at.column);
|
|
3932
|
+
if (!parent || isPlain(parent.name) && parent.name !== p.tag) break;
|
|
3933
|
+
const opening = openingAt(lines, parent.index, parent.column).text;
|
|
3934
|
+
if (p.id && opening.includes(p.id)) score += 4;
|
|
3935
|
+
else if (p.classes.length) {
|
|
3936
|
+
const classes = classesScore(n, p.classes, opening);
|
|
3937
|
+
if (!classes.clear) break;
|
|
3938
|
+
score += Math.min(4, 1 + Math.max(0, classes.score) / 2);
|
|
3939
|
+
} else if (classAttrOf(opening)?.words.length) break;
|
|
3940
|
+
else score += 0.5;
|
|
3941
|
+
at = parent;
|
|
3942
|
+
found++;
|
|
3943
|
+
}
|
|
3944
|
+
return { score, found };
|
|
3945
|
+
}
|
|
3946
|
+
function routeOf(n, rel) {
|
|
3947
|
+
if (!n.route.length) return { score: 0, facts: [] };
|
|
3948
|
+
const parts = rel.split(/[\\/]/);
|
|
3949
|
+
const names = new Set(parts.map((p) => p.replace(/\.[a-z]+$/i, "")));
|
|
3950
|
+
const like = n.route.filter((p) => names.has(p));
|
|
3951
|
+
const score = Math.min(5, like.length * 2.5);
|
|
3952
|
+
const facts = like.map((p) => `route:${p}`);
|
|
3953
|
+
if (parts.length > 1 && n.otherSites.has(parts[0])) return { score: score - 20, facts: [...facts, "-site"] };
|
|
3954
|
+
if (n.served && parts.length > 1 && parts[0] !== n.served) return { score: score - 3, facts: [...facts, "-folder"] };
|
|
3955
|
+
return { score, facts };
|
|
3956
|
+
}
|
|
3957
|
+
var INDEX_FILES = ["index.php", "index.html", "index.htm"];
|
|
3958
|
+
var safeList = (dir) => {
|
|
3959
|
+
try {
|
|
3960
|
+
return readdirSync6(dir).filter((name) => !name.startsWith(".") && isFolder(join12(dir, name)));
|
|
3961
|
+
} catch {
|
|
3962
|
+
return [];
|
|
3963
|
+
}
|
|
3964
|
+
};
|
|
3965
|
+
var isFolder = (path) => {
|
|
3966
|
+
try {
|
|
3967
|
+
return statSync7(path).isDirectory();
|
|
3968
|
+
} catch {
|
|
3969
|
+
return false;
|
|
3970
|
+
}
|
|
3971
|
+
};
|
|
3972
|
+
function fileScore(n, file) {
|
|
3973
|
+
let score = 0;
|
|
3974
|
+
if (n.id && file.words.has(n.id)) score += 8;
|
|
3975
|
+
for (const c of n.classes) if (file.words.has(c)) score += n.rarity(c);
|
|
3976
|
+
for (const t of [...n.texts, ...n.attrs]) {
|
|
3977
|
+
const words = wordsOf(t);
|
|
3978
|
+
if (words.length && words.every((w) => file.words.has(w))) score += textWeight(n, t);
|
|
3979
|
+
}
|
|
3980
|
+
return score;
|
|
3981
|
+
}
|
|
3982
|
+
function besideOf(n, file) {
|
|
3983
|
+
const beside = { before: [], after: [], headings: [] };
|
|
3984
|
+
const lead = (t) => t?.split(" ")[0];
|
|
3985
|
+
const firstBefore = lead(n.before);
|
|
3986
|
+
const firstAfter = lead(n.after);
|
|
3987
|
+
file.lines.forEach((line, i) => {
|
|
3988
|
+
if (n.heading && /<h[1-6][\s>]/i.test(line)) beside.headings.push(i);
|
|
3989
|
+
if (firstBefore && line.includes(firstBefore) && plain(line).includes(n.before)) beside.before.push(i);
|
|
3990
|
+
if (firstAfter && line.includes(firstAfter) && plain(line).includes(n.after)) beside.after.push(i);
|
|
3991
|
+
});
|
|
3992
|
+
return beside;
|
|
3993
|
+
}
|
|
3994
|
+
function scoreFile(n, file, from = 0, to = file.lines.length) {
|
|
3995
|
+
const out = [];
|
|
3996
|
+
const beside = besideOf(n, file);
|
|
3997
|
+
for (let i = from; i < Math.min(to, file.lines.length); i++) {
|
|
3998
|
+
const line = file.lines[i];
|
|
3999
|
+
if (!line.includes("<")) continue;
|
|
4000
|
+
for (const { name, column } of tagsOn(line)) {
|
|
4001
|
+
const found = scoreAt(n, file, beside, i, column, name);
|
|
4002
|
+
if (found?.kinds.size) out.push(found);
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
return out;
|
|
4006
|
+
}
|
|
4007
|
+
function convincing(c) {
|
|
4008
|
+
if (c.kinds.has("id")) return c.score >= 9;
|
|
4009
|
+
if (c.kinds.size >= 2) return c.score >= 10;
|
|
4010
|
+
return c.kinds.has("classes") && c.classScore >= 12;
|
|
4011
|
+
}
|
|
4012
|
+
var MARGIN = 4;
|
|
4013
|
+
function locate(target, root, options = {}) {
|
|
4014
|
+
const found = candidates(target, root, options);
|
|
4015
|
+
if (!found) return null;
|
|
4016
|
+
if ("known" in found) return found.known;
|
|
4017
|
+
const all = found.list;
|
|
4018
|
+
const best = all[0];
|
|
4019
|
+
if (!best || !convincing(best)) return null;
|
|
4020
|
+
const at = (c) => ({ file: c.file.rel, line: c.index + 1, snippet: snippetAt(c.file.lines, c.index) });
|
|
4021
|
+
const apart = (a, b) => a.file !== b.file || a.index !== b.index || a.column !== b.column;
|
|
4022
|
+
const elsewhere = all.filter((c) => apart(c, best));
|
|
4023
|
+
const second = elsewhere[0];
|
|
4024
|
+
if (!second || clearlyAhead(best, second)) return at(best);
|
|
4025
|
+
const third = elsewhere.find((c) => apart(c, second));
|
|
4026
|
+
if (convincing(second) && (!third || clearlyAhead(best, third))) return { ...at(best), also: at(second) };
|
|
4027
|
+
return null;
|
|
4028
|
+
}
|
|
4029
|
+
function clearlyAhead(best, other) {
|
|
4030
|
+
const diff = best.score - other.score;
|
|
4031
|
+
if (diff >= MARGIN) return true;
|
|
4032
|
+
if (diff <= 0) return false;
|
|
4033
|
+
const pro = (c) => [...c.facts].filter((f) => !f.startsWith("-"));
|
|
4034
|
+
const con = (c) => [...c.facts].filter((f) => f.startsWith("-"));
|
|
4035
|
+
return pro(other).every((f) => best.facts.has(f)) && con(best).every((f) => other.facts.has(f)) && pro(best).length + con(other).length > pro(other).length + con(best).length;
|
|
4036
|
+
}
|
|
4037
|
+
function candidates(target, root, options = {}) {
|
|
4038
|
+
const { sources, rarity } = markupSources(root);
|
|
4039
|
+
const deadline = options.deadline ?? Date.now() + BUDGET_MS3;
|
|
4040
|
+
const n = needlesOf(target, options.url, root, rarity);
|
|
2528
4041
|
const known = target.source?.file && target.source.line ? sourcePath(target.source.file, root) : null;
|
|
2529
4042
|
if (known && target.source?.line) {
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
const own =
|
|
4043
|
+
const from = target.source.line - 1;
|
|
4044
|
+
const file = sources.find((s) => s.rel === known);
|
|
4045
|
+
if (file) {
|
|
4046
|
+
const own = scoreFile(n, file, from, from + 200).sort((a, b) => b.score - a.score)[0];
|
|
2534
4047
|
const index = own && own.score >= 2 ? own.index : from;
|
|
2535
|
-
return { file: known, line: index + 1, snippet: snippetAt(lines, index) };
|
|
2536
|
-
} catch {
|
|
4048
|
+
return { known: { file: known, line: index + 1, snippet: snippetAt(file.lines, index) } };
|
|
2537
4049
|
}
|
|
2538
4050
|
}
|
|
2539
|
-
if (!n.id && !n.
|
|
2540
|
-
|
|
2541
|
-
|
|
4051
|
+
if (!n.id && !n.texts.length && !n.attrs.length && !n.classes.length) return null;
|
|
4052
|
+
const files = sources.map((file) => ({ file, score: fileScore(n, file) })).filter((f) => f.score > 0).sort((a, b) => b.score - a.score).slice(0, CANDIDATE_FILES);
|
|
4053
|
+
const list2 = [];
|
|
4054
|
+
for (const { file } of files) {
|
|
2542
4055
|
if (Date.now() > deadline) break;
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
content = readFileSync7(file, "utf8");
|
|
2546
|
-
} catch {
|
|
2547
|
-
continue;
|
|
2548
|
-
}
|
|
2549
|
-
if (!(n.id && content.includes(target.id)) && !(n.text && content.includes(n.text)) && !(n.lead && content.includes(n.lead))) {
|
|
2550
|
-
if (n.classes.length < 3) continue;
|
|
2551
|
-
}
|
|
2552
|
-
const lines = content.split("\n");
|
|
2553
|
-
const found = bestLine(n, lines);
|
|
2554
|
-
if (found && (!best || found.score > best.score)) best = { file, line: found.index, score: found.score, lines };
|
|
4056
|
+
const route = routeOf(n, file.rel);
|
|
4057
|
+
for (const c of scoreFile(n, file)) list2.push({ ...c, score: c.score + route.score, facts: /* @__PURE__ */ new Set([...c.facts, ...route.facts]) });
|
|
2555
4058
|
}
|
|
2556
|
-
|
|
2557
|
-
if (!best || !enough) return null;
|
|
2558
|
-
return { file: relative4(root, best.file), line: best.line + 1, snippet: snippetAt(best.lines, best.line) };
|
|
2559
|
-
}
|
|
2560
|
-
function bestLine(n, lines, from = 0) {
|
|
2561
|
-
const classesOn = (i) => lines[i] === void 0 ? 0 : n.classes.filter((re) => re.test(lines[i])).length;
|
|
2562
|
-
let best = null;
|
|
2563
|
-
for (let i = from; i < lines.length; i++) {
|
|
2564
|
-
const line = lines[i];
|
|
2565
|
-
let score = 0;
|
|
2566
|
-
if (n.id?.test(line)) score += 8;
|
|
2567
|
-
if (n.text && line.includes(n.text)) score += 6;
|
|
2568
|
-
else if (n.lead && line.includes(n.lead)) score += 4;
|
|
2569
|
-
let classes = 0;
|
|
2570
|
-
for (let j = Math.max(from, i - 3); j <= i; j++) classes = Math.max(classes, classesOn(j));
|
|
2571
|
-
score += classes;
|
|
2572
|
-
if (n.classes.length && classes === n.classes.length) score += 2;
|
|
2573
|
-
if (n.tag.test(line)) score += 1;
|
|
2574
|
-
if (!best || score > best.score) best = { index: i, score };
|
|
2575
|
-
}
|
|
2576
|
-
return best;
|
|
4059
|
+
return { list: list2.sort((a, b) => b.score - a.score) };
|
|
2577
4060
|
}
|
|
2578
4061
|
function snippetAt(lines, index) {
|
|
2579
4062
|
return lines.slice(Math.max(0, index - 2), index + 3).map((l) => l.length > 160 ? `${l.slice(0, 159)}\u2026` : l).join("\n");
|
|
2580
4063
|
}
|
|
2581
4064
|
function sourcePath(file, root) {
|
|
2582
|
-
const rel = isAbsolute(file) ?
|
|
4065
|
+
const rel = isAbsolute(file) ? relative7(root, file) : file.replace(/^\.\//, "");
|
|
2583
4066
|
if (rel.startsWith("..") || isAbsolute(rel)) return null;
|
|
2584
|
-
return
|
|
4067
|
+
return existsSync8(join12(root, rel)) ? rel : null;
|
|
2585
4068
|
}
|
|
2586
4069
|
function componentFile(name, root, deadline = Date.now() + BUDGET_MS3, within) {
|
|
2587
4070
|
if (!/^[A-Za-z_$][\w$]*$/.test(name)) return null;
|
|
@@ -2589,13 +4072,13 @@ function componentFile(name, root, deadline = Date.now() + BUDGET_MS3, within) {
|
|
|
2589
4072
|
`^\\s*(export\\s+(?:default\\s+)?)?(?:(?:async\\s+)?function\\s*\\*?\\s+${name}\\b|class\\s+${name}\\b|(?:const|let|var)\\s+${name}\\s*[:=])`
|
|
2590
4073
|
);
|
|
2591
4074
|
let best = null;
|
|
2592
|
-
const files = within ? [
|
|
4075
|
+
const files = within ? [join12(root, within)] : sourceFiles(root);
|
|
2593
4076
|
for (const file of files) {
|
|
2594
4077
|
if (Date.now() > deadline) break;
|
|
2595
4078
|
if (!/\.[jt]sx?$|\.mjs$/.test(file)) continue;
|
|
2596
4079
|
let content;
|
|
2597
4080
|
try {
|
|
2598
|
-
content =
|
|
4081
|
+
content = readFileSync10(file, "utf8");
|
|
2599
4082
|
} catch {
|
|
2600
4083
|
continue;
|
|
2601
4084
|
}
|
|
@@ -2604,12 +4087,12 @@ function componentFile(name, root, deadline = Date.now() + BUDGET_MS3, within) {
|
|
|
2604
4087
|
for (let i = 0; i < lines.length; i++) {
|
|
2605
4088
|
const m = declaration.exec(lines[i]);
|
|
2606
4089
|
if (!m) continue;
|
|
2607
|
-
const score = (
|
|
4090
|
+
const score = (basename6(file).replace(/\.[^.]+$/, "") === name ? 2 : 0) + (m[1] ? 1 : 0);
|
|
2608
4091
|
if (!best || score > best.score) best = { file, line: i + 1, score };
|
|
2609
4092
|
break;
|
|
2610
4093
|
}
|
|
2611
4094
|
}
|
|
2612
|
-
return best ? { file:
|
|
4095
|
+
return best ? { file: relative7(root, best.file), line: best.line } : null;
|
|
2613
4096
|
}
|
|
2614
4097
|
function withComponentFiles(job, root) {
|
|
2615
4098
|
if (!searchable(root)) return job;
|
|
@@ -2625,11 +4108,11 @@ function withComponentFiles(job, root) {
|
|
|
2625
4108
|
const workspace = workspaceRoot(root);
|
|
2626
4109
|
const declared = (name) => {
|
|
2627
4110
|
const found = componentFile(name, workspace, deadline);
|
|
2628
|
-
return found ? { file:
|
|
4111
|
+
return found ? { file: relative7(root, join12(workspace, found.file)), line: found.line } : null;
|
|
2629
4112
|
};
|
|
2630
4113
|
const local = (file) => {
|
|
2631
|
-
const path =
|
|
2632
|
-
return
|
|
4114
|
+
const path = join12(workspace, file);
|
|
4115
|
+
return existsSync8(path) ? relative7(root, path) : file;
|
|
2633
4116
|
};
|
|
2634
4117
|
const mention = (r) => {
|
|
2635
4118
|
if (r.kind === "token") return r.source ? { ...r, source: { ...r.source, file: local(r.source.file) } } : r;
|
|
@@ -2640,8 +4123,8 @@ function withComponentFiles(job, root) {
|
|
|
2640
4123
|
}
|
|
2641
4124
|
if (r.kind !== "component") return r;
|
|
2642
4125
|
if (r.source) {
|
|
2643
|
-
const path =
|
|
2644
|
-
return
|
|
4126
|
+
const path = join12(workspace, r.source.file);
|
|
4127
|
+
return existsSync8(path) ? { ...r, source: { ...r.source, file: relative7(root, path) } } : r;
|
|
2645
4128
|
}
|
|
2646
4129
|
if (r.target?.source?.file) return { ...r, target: fill(r.target) };
|
|
2647
4130
|
const source = declared(r.name);
|
|
@@ -2667,36 +4150,125 @@ function withComponentFiles(job, root) {
|
|
|
2667
4150
|
}
|
|
2668
4151
|
};
|
|
2669
4152
|
}
|
|
2670
|
-
function
|
|
2671
|
-
if (!searchable(root)) return
|
|
4153
|
+
function jobLocations(job, root) {
|
|
4154
|
+
if (!searchable(root)) return [];
|
|
2672
4155
|
const targets = job.changeSet.request ? requestTargets(job.changeSet.request) : job.changeSet.edits.map((e) => e.target);
|
|
4156
|
+
markupSources(root);
|
|
2673
4157
|
const deadline = Date.now() + BUDGET_MS3;
|
|
2674
4158
|
const found = [];
|
|
2675
4159
|
for (const target of targets) {
|
|
2676
|
-
const at = locate(target, root, deadline);
|
|
2677
|
-
if (
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
4160
|
+
const at = locate(target, root, { url: job.changeSet.page?.url, deadline });
|
|
4161
|
+
if (at) found.push({ target, at });
|
|
4162
|
+
}
|
|
4163
|
+
return found;
|
|
4164
|
+
}
|
|
4165
|
+
function whereSection(job, root, located = jobLocations(job, root)) {
|
|
4166
|
+
if (!searchable(root)) return "";
|
|
4167
|
+
const found = [];
|
|
4168
|
+
for (const { target, at } of located) {
|
|
4169
|
+
const snippet = (place) => [
|
|
2681
4170
|
"",
|
|
2682
|
-
` \`\`\`${
|
|
2683
|
-
...
|
|
4171
|
+
` \`\`\`${extname5(place.file).slice(1) || "text"}`,
|
|
4172
|
+
...place.snippet.split("\n").map((l) => ` ${l}`),
|
|
2684
4173
|
" ```"
|
|
2685
|
-
|
|
4174
|
+
];
|
|
4175
|
+
if (at.also)
|
|
4176
|
+
found.push(
|
|
4177
|
+
`- \`${target.path}\` \u2192 one of these two (the same markup in both; the page doesn't say which):`,
|
|
4178
|
+
"",
|
|
4179
|
+
` \`${at.file}:${at.line}\`:`,
|
|
4180
|
+
...snippet(at),
|
|
4181
|
+
"",
|
|
4182
|
+
` \`${at.also.file}:${at.also.line}\`:`,
|
|
4183
|
+
...snippet(at.also)
|
|
4184
|
+
);
|
|
4185
|
+
else found.push(`- \`${target.path}\` \u2192 \`${at.file}:${at.line}\`:`, ...snippet(at));
|
|
2686
4186
|
}
|
|
2687
4187
|
if (!found.length) return "";
|
|
2688
4188
|
return [
|
|
2689
4189
|
"## Where the code probably is",
|
|
2690
4190
|
"",
|
|
2691
|
-
"Pilot searched the project for these elements (by component,
|
|
4191
|
+
"Pilot searched the project for these elements (by component, and by their classes, texts, attributes and parents together). Start there; if it isn't the right place (the text comes from a prop, a translation, a CMS), search as usual.",
|
|
2692
4192
|
"",
|
|
2693
4193
|
...found
|
|
2694
4194
|
].join("\n");
|
|
2695
4195
|
}
|
|
2696
4196
|
|
|
4197
|
+
// src/pool.ts
|
|
4198
|
+
var MAX_JOBS = 20;
|
|
4199
|
+
var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
4200
|
+
var SessionPool = class {
|
|
4201
|
+
constructor(folder, agent, file, now = Date.now) {
|
|
4202
|
+
this.folder = folder;
|
|
4203
|
+
this.agent = agent;
|
|
4204
|
+
this.file = file;
|
|
4205
|
+
this.now = now;
|
|
4206
|
+
this.sessions = this.fresh(savedSessions(folder, file).filter((s) => s.agent === agent));
|
|
4207
|
+
}
|
|
4208
|
+
folder;
|
|
4209
|
+
agent;
|
|
4210
|
+
file;
|
|
4211
|
+
now;
|
|
4212
|
+
sessions;
|
|
4213
|
+
busy = /* @__PURE__ */ new Set();
|
|
4214
|
+
waiters = /* @__PURE__ */ new Map();
|
|
4215
|
+
/** The sessions still usable (not retired), for tests and the log. */
|
|
4216
|
+
get kept() {
|
|
4217
|
+
return this.sessions;
|
|
4218
|
+
}
|
|
4219
|
+
/** A free session for a new job, else none (a new one starts). */
|
|
4220
|
+
take() {
|
|
4221
|
+
this.sessions = this.fresh(this.sessions);
|
|
4222
|
+
const free = this.sessions.find((s) => !this.busy.has(s.id));
|
|
4223
|
+
if (free) this.busy.add(free.id);
|
|
4224
|
+
return this.leaseOf(free?.id);
|
|
4225
|
+
}
|
|
4226
|
+
/** The session `id` for a follow-up of its job: when another job has it, once it's free. Not one of the pool's: just a lease on it. */
|
|
4227
|
+
async takeOwn(id) {
|
|
4228
|
+
while (this.busy.has(id)) await new Promise((resolve5) => this.waiters.set(id, [...this.waiters.get(id) ?? [], resolve5]));
|
|
4229
|
+
this.busy.add(id);
|
|
4230
|
+
return this.leaseOf(id);
|
|
4231
|
+
}
|
|
4232
|
+
leaseOf(resume) {
|
|
4233
|
+
let released = false;
|
|
4234
|
+
return {
|
|
4235
|
+
...resume ? { resume } : {},
|
|
4236
|
+
release: (session) => {
|
|
4237
|
+
if (released) return;
|
|
4238
|
+
released = true;
|
|
4239
|
+
if (resume) this.free(resume);
|
|
4240
|
+
if (resume && session !== resume) this.sessions = this.sessions.filter((s) => s.id !== resume);
|
|
4241
|
+
if (session) {
|
|
4242
|
+
const known = this.sessions.find((s) => s.id === session);
|
|
4243
|
+
if (known) known.jobs++;
|
|
4244
|
+
else this.sessions.push({ agent: this.agent, id: session, jobs: 1, since: this.now() });
|
|
4245
|
+
}
|
|
4246
|
+
this.sessions = this.fresh(this.sessions);
|
|
4247
|
+
this.save();
|
|
4248
|
+
}
|
|
4249
|
+
};
|
|
4250
|
+
}
|
|
4251
|
+
free(id) {
|
|
4252
|
+
this.busy.delete(id);
|
|
4253
|
+
const next = this.waiters.get(id)?.shift();
|
|
4254
|
+
if (next) next();
|
|
4255
|
+
}
|
|
4256
|
+
/** Without the retired ones. */
|
|
4257
|
+
fresh(sessions) {
|
|
4258
|
+
return sessions.filter((s) => s.jobs < MAX_JOBS && this.now() - s.since < MAX_AGE_MS);
|
|
4259
|
+
}
|
|
4260
|
+
save() {
|
|
4261
|
+
try {
|
|
4262
|
+
const others = savedSessions(this.folder, this.file).filter((s) => s.agent !== this.agent);
|
|
4263
|
+
saveSessions(this.folder, [...others, ...this.sessions], this.file);
|
|
4264
|
+
} catch {
|
|
4265
|
+
}
|
|
4266
|
+
}
|
|
4267
|
+
};
|
|
4268
|
+
|
|
2697
4269
|
// src/prompt.ts
|
|
2698
|
-
function jobPrompt(job, where = "") {
|
|
2699
|
-
const body2 = job.attempt === 2 && job.issues?.length ? taskFollowUp(job) : job.attempt === 2 && job.differences?.length ? followUp(job) : job.answer && job.question ? answered(job) : formatPrompt(job.changeSet);
|
|
4270
|
+
function jobPrompt(job, where = "", options = {}) {
|
|
4271
|
+
const body2 = job.attempt === 2 && job.issues?.length ? taskFollowUp(job) : job.attempt === 2 && job.differences?.length ? followUp(job) : job.answer && job.question ? answered(job) : formatPrompt(job.changeSet, options);
|
|
2700
4272
|
return `${body2}${where ? `
|
|
2701
4273
|
${where}
|
|
2702
4274
|
` : ""}
|
|
@@ -2706,15 +4278,28 @@ ${runFooter(job)}
|
|
|
2706
4278
|
}
|
|
2707
4279
|
function runFooter(job) {
|
|
2708
4280
|
const props = job.changeSet.request?.kind === "props";
|
|
4281
|
+
const { request, edits } = job.changeSet;
|
|
4282
|
+
const several = (request ? requestTargets(request) : edits).length > 1;
|
|
2709
4283
|
return [
|
|
2710
|
-
skillOf(job) ? `When you're done, reply with your notes for the designer: ${notesFor(job)}. Pilot shows them to the designer in the element's thread.` : `When you're done, reply with your notes for the designer: ${notesFor(job)}. Concise, no headings ("Done." when there's nothing to add): Pilot shows them to the designer in a small box, and checks the page itself, so don't open a browser, start a dev server, or run builds or tests.`,
|
|
4284
|
+
skillOf(job) ? `When you're done, reply with your notes for the designer: ${notesFor(job)}. Pilot shows them to the designer in the element's thread.` : `When you're done, reply with your notes for the designer: ${notesFor(job)}. Concise, no headings ("Done." when there's nothing to add): Pilot shows them to the designer in a small box, and checks the page itself, so don't open a browser, start a dev server, or run builds or tests, and don't check your edit afterwards (no git diff, script or second read of the file): Pilot does.`,
|
|
2711
4285
|
"",
|
|
2712
4286
|
props ? "Put the props in a block at the very end of your reply, after your notes, as JSON:" : "If you ask the designer a question (only where this job says to), put it in a block at the very end of your reply, after your notes, as JSON:",
|
|
2713
4287
|
"",
|
|
2714
4288
|
"```pilot",
|
|
2715
|
-
props ? `{"props": [{"name": "tone", "type": "options", "options": ["light", "dark"], "default": "light", "description": "a few words, when the name doesn't say"}]}` : '{"question": {"text": "One short sentence?", "choices": ["Your suggestion", "Another"]}}',
|
|
4289
|
+
props ? `{"props": [{"name": "tone", "type": "options", "options": ["light", "dark"], "default": "light", "description": "a few words, when the name doesn't say"}]}` : several ? '{"question": {"text": "One short sentence?", "choices": ["Your suggestion", "Another"], "element": 2}}' : '{"question": {"text": "One short sentence?", "choices": ["Your suggestion", "Another"]}}',
|
|
2716
4290
|
"```",
|
|
2717
|
-
...props ? ["", "`type` is one of `options`, `boolean`, `text`, `number`; `options` only for `options`."] : []
|
|
4291
|
+
...props ? ["", "`type` is one of `options`, `boolean`, `text`, `number`; `options` only for `options`."] : [],
|
|
4292
|
+
...!props && several ? ["", "`element`: the number of the element it's about (its heading's), so the designer sees it there; leave it out when it's about all of them."] : [],
|
|
4293
|
+
"",
|
|
4294
|
+
// What runs were refused most, for nothing (a skill's checks): reading with `cat`, fetching the page with `curl`.
|
|
4295
|
+
"Read and search files with your own file tools, not shell commands (`cat`, `cd`, `grep`), and don't fetch or open the page (`curl`, a browser): Pilot checks it itself.",
|
|
4296
|
+
"",
|
|
4297
|
+
// Refused stays refused however it's put: a run tried `git show` five ways, a model round each.
|
|
4298
|
+
"If you were refused something you needed (a tool, a command, a website: it would have asked the designer, and no one can answer in this run), list it in that block as `refused`, and do without it: it stays refused however you put it, so don't retry it another way. Pilot tells the designer how to allow it, so don't explain that yourself:",
|
|
4299
|
+
"",
|
|
4300
|
+
"```pilot",
|
|
4301
|
+
`{"refused": [{"mcp": "the MCP server's name"}, {"command": "the command, as you ran it"}, {"web": "the site's domain"}, {"tool": "any other tool's name"}]}`,
|
|
4302
|
+
"```"
|
|
2718
4303
|
].join("\n");
|
|
2719
4304
|
}
|
|
2720
4305
|
function answered(job) {
|
|
@@ -2752,6 +4337,11 @@ function followUp(job) {
|
|
|
2752
4337
|
"",
|
|
2753
4338
|
"Fix them: the usual causes are a rule that overrides yours (more specific, later, or in a media query), an edit in the wrong file or component, or a missed change. If you chose a different value on purpose (a token or the nearest step in the project's scale), keep it and say so in your notes. Pilot takes what the code gives after this."
|
|
2754
4339
|
);
|
|
4340
|
+
if (job.changeSet.request?.kind === "comment")
|
|
4341
|
+
lines.push(
|
|
4342
|
+
"",
|
|
4343
|
+
"These edits came with the designer's comment, which was written after them. Where you did what the comment asked instead of an edit's value, that's right: keep it, don't switch to the edit's value, and say so in your notes."
|
|
4344
|
+
);
|
|
2755
4345
|
return lines.join("\n");
|
|
2756
4346
|
}
|
|
2757
4347
|
function notesFor(job) {
|
|
@@ -2809,8 +4399,9 @@ function skillOf(job) {
|
|
|
2809
4399
|
}
|
|
2810
4400
|
|
|
2811
4401
|
// src/run.ts
|
|
2812
|
-
var SLOTS =
|
|
4402
|
+
var SLOTS = 5;
|
|
2813
4403
|
var CANCEL_POLL_MS = 2e3;
|
|
4404
|
+
var ACTIVITY_EVERY_MS = 15e3;
|
|
2814
4405
|
var RUN_TIMEOUT_MS = 20 * 6e4;
|
|
2815
4406
|
var WAIT_MS = 10 * 6e4;
|
|
2816
4407
|
var RunnerError = class extends Error {
|
|
@@ -2824,11 +4415,20 @@ async function startRunner(options) {
|
|
|
2824
4415
|
throw new RunnerError(`${project} isn't a project folder (no package.json or .git). Run npx usepilot in your project's folder.`);
|
|
2825
4416
|
}
|
|
2826
4417
|
const { cli, bin } = await pickAgent(options, choose2, out);
|
|
2827
|
-
const
|
|
4418
|
+
const checkFlags = options.bin ? void 0 : () => missingFlags(cli, bin).catch(() => null);
|
|
4419
|
+
void checkFlags?.().then((missing) => {
|
|
4420
|
+
if (missing?.length) out(outdatedNote(cli, missing));
|
|
4421
|
+
});
|
|
4422
|
+
const agent = { id: randomUUID2(), label: `${cli.label} \xB7 ${basename7(project)}`, folder: project, kind: cli.kind };
|
|
2828
4423
|
const bridge = new Bridge(agent, options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT));
|
|
2829
4424
|
const origin = await pickSite(bridge, options, out);
|
|
2830
4425
|
await bridge.launch(origin);
|
|
2831
4426
|
out(`Pilot is on ${origin}, every page, with ${cli.label}. Send from the toolbar; jobs show here. Ctrl+C stops.`);
|
|
4427
|
+
setImmediate(() => {
|
|
4428
|
+
warmSources(project);
|
|
4429
|
+
warmStyles(project);
|
|
4430
|
+
});
|
|
4431
|
+
const pool = new SessionPool(project, cli.kind, options.configFile);
|
|
2832
4432
|
const stop = new AbortController();
|
|
2833
4433
|
const runs = /* @__PURE__ */ new Set();
|
|
2834
4434
|
const slots = options.slots ?? SLOTS;
|
|
@@ -2844,7 +4444,7 @@ async function startRunner(options) {
|
|
|
2844
4444
|
await sleep(2e3, stop.signal);
|
|
2845
4445
|
continue;
|
|
2846
4446
|
}
|
|
2847
|
-
if (job && !stop.signal.aborted) await runJob(job, { bridge, cli, bin, project, out, signal: stop.signal });
|
|
4447
|
+
if (job && !stop.signal.aborted) await runJob(job, { bridge, cli, bin, project, out, signal: stop.signal, pool, checkFlags });
|
|
2848
4448
|
}
|
|
2849
4449
|
})();
|
|
2850
4450
|
runs.add(loop);
|
|
@@ -2924,6 +4524,9 @@ async function pickSite(bridge, options, out) {
|
|
|
2924
4524
|
await sleep(1e3);
|
|
2925
4525
|
}
|
|
2926
4526
|
}
|
|
4527
|
+
function isEditorJob(job) {
|
|
4528
|
+
return !job.changeSet.request && !job.answer;
|
|
4529
|
+
}
|
|
2927
4530
|
async function runJob(job, ctx) {
|
|
2928
4531
|
const { bridge, cli, out } = ctx;
|
|
2929
4532
|
const started = Date.now();
|
|
@@ -2937,30 +4540,45 @@ async function runJob(job, ctx) {
|
|
|
2937
4540
|
}).catch(() => {
|
|
2938
4541
|
});
|
|
2939
4542
|
}, CANCEL_POLL_MS);
|
|
4543
|
+
let lease;
|
|
4544
|
+
let ended;
|
|
2940
4545
|
try {
|
|
2941
|
-
|
|
2942
|
-
|
|
4546
|
+
if (ctx.pool && isEditorJob(job)) {
|
|
4547
|
+
const own = sessionOf(job.session);
|
|
4548
|
+
if (job.attempt !== 2) lease = ctx.pool.take();
|
|
4549
|
+
else if (own?.agent === cli.kind) lease = await ctx.pool.takeOwn(own.id);
|
|
4550
|
+
}
|
|
4551
|
+
const resume = lease ? lease.resume : sessionToResume(job, cli.kind);
|
|
4552
|
+
const known = !!lease?.resume && job.attempt !== 2;
|
|
4553
|
+
const prompt = await promptFor(job, ctx.project, cli, { guidelinesKnown: known });
|
|
2943
4554
|
const images = newAttachments(job).map((f) => f.path).filter((p) => /\.(png|jpe?g|gif|webp)$/i.test(p));
|
|
2944
|
-
|
|
4555
|
+
const active = activityOf(bridge, job.id);
|
|
4556
|
+
let result = await runAgent(ctx, prompt, { resume, images, signal: stop.signal, onOutput: active });
|
|
2945
4557
|
if (!stop.signal.aborted && !result.reply && !signInProblem(result.error)) {
|
|
2946
|
-
result = await runAgent(ctx, prompt, { images, signal: stop.signal });
|
|
4558
|
+
result = await runAgent(ctx, known ? await promptFor(job, ctx.project, cli) : prompt, { images, signal: stop.signal, onOutput: active });
|
|
2947
4559
|
}
|
|
2948
4560
|
if (stop.signal.aborted) {
|
|
4561
|
+
ended = lease?.resume;
|
|
2949
4562
|
out(`\u25A0 Stopped: ${describeJob(job)}`);
|
|
2950
4563
|
return;
|
|
2951
4564
|
}
|
|
4565
|
+
if (result.reply) ended = result.session;
|
|
2952
4566
|
const seconds = Math.round((Date.now() - started) / 1e3);
|
|
2953
4567
|
if (!result.reply) {
|
|
2954
|
-
const error = errorFor(cli, result.error);
|
|
4568
|
+
const error = errorFor(cli, result.error, await ctx.checkFlags?.() ?? void 0);
|
|
2955
4569
|
await bridge.done(job.id, void 0, void 0, void 0, { error });
|
|
2956
|
-
|
|
2957
|
-
|
|
4570
|
+
const said = (result.error ?? "").split("\n").map((l) => l.trim()).filter(Boolean).slice(-8);
|
|
4571
|
+
out(`\u2717 ${error.title}. ${error.detail}${said.length && !signInProblem(result.error) ? `
|
|
4572
|
+
${said.map((l) => ` ${l}`).join("\n")}` : ""}`);
|
|
2958
4573
|
return;
|
|
2959
4574
|
}
|
|
2960
4575
|
const reply = replyOf(result.reply);
|
|
2961
4576
|
const session = result.session ? { agent: cli.kind, id: result.session } : void 0;
|
|
2962
|
-
|
|
4577
|
+
const refused = refusedNote(cli, [...result.refused ?? [], ...reply.refused ?? []]);
|
|
4578
|
+
const notes = refused ? [reply.notes, refused.note].filter(Boolean).join("\n\n") : reply.notes;
|
|
4579
|
+
await bridge.done(job.id, notes, reply.question, reply.props, { session, ...refused?.allow ? { allow: refused.allow } : {} });
|
|
2963
4580
|
out(`\u2713 ${seconds}s \xB7 ${firstLine(reply.notes) || "Done."}`);
|
|
4581
|
+
if (refused) out(`! ${[refused.note, refused.allow].filter(Boolean).join(" ").replaceAll("**", "").replaceAll("`", "")}`);
|
|
2964
4582
|
} catch (error) {
|
|
2965
4583
|
if (!stop.signal.aborted) {
|
|
2966
4584
|
const jobError = { title: `Pilot couldn't run ${cli.label}`, detail: error.message };
|
|
@@ -2969,31 +4587,45 @@ async function runJob(job, ctx) {
|
|
|
2969
4587
|
out(`\u2717 ${jobError.title}: ${jobError.detail}`);
|
|
2970
4588
|
}
|
|
2971
4589
|
} finally {
|
|
4590
|
+
lease?.release(ended);
|
|
2972
4591
|
clearInterval(watch);
|
|
2973
4592
|
ctx.signal.removeEventListener("abort", onStop);
|
|
2974
4593
|
}
|
|
2975
4594
|
}
|
|
4595
|
+
function activityOf(bridge, jobId, every = ACTIVITY_EVERY_MS, now = Date.now) {
|
|
4596
|
+
let last = Number.NEGATIVE_INFINITY;
|
|
4597
|
+
return () => {
|
|
4598
|
+
if (now() - last < every) return;
|
|
4599
|
+
last = now();
|
|
4600
|
+
bridge.activity(jobId).catch(() => {
|
|
4601
|
+
});
|
|
4602
|
+
};
|
|
4603
|
+
}
|
|
2976
4604
|
async function runAgent(ctx, prompt, options) {
|
|
2977
4605
|
const { cli } = ctx;
|
|
2978
|
-
if (!
|
|
4606
|
+
if (!existsSync9(ctx.bin)) return { error: `${cli.label}'s command-line tool isn't installed any more.` };
|
|
4607
|
+
options.onOutput?.();
|
|
2979
4608
|
const run2 = await exec(ctx.bin, cli.args({ resume: options.resume, readDirs: [attachmentsDir()], images: options.images }), {
|
|
2980
4609
|
cwd: ctx.project,
|
|
2981
4610
|
input: prompt,
|
|
2982
4611
|
signal: options.signal,
|
|
2983
|
-
timeoutMs: RUN_TIMEOUT_MS
|
|
4612
|
+
timeoutMs: RUN_TIMEOUT_MS,
|
|
4613
|
+
...options.onOutput ? { onStdout: options.onOutput } : {}
|
|
2984
4614
|
});
|
|
2985
|
-
const
|
|
2986
|
-
if (!
|
|
2987
|
-
if (!
|
|
4615
|
+
const parsed2 = cli.parse(run2.stdout);
|
|
4616
|
+
if (!parsed2.reply && !parsed2.error) parsed2.error = run2.stderr.trim().split("\n").slice(-3).join("\n") || `exit code ${run2.code}`;
|
|
4617
|
+
if (!parsed2.reply && run2.stderr && !parsed2.error?.includes(run2.stderr.trim().slice(0, 40))) parsed2.error = `${parsed2.error}
|
|
2988
4618
|
${run2.stderr.trim().slice(-500)}`;
|
|
2989
|
-
|
|
4619
|
+
if (!parsed2.reply && !run2.stderr.trim() && parsed2.error === NOTHING_PRINTED) parsed2.error = `${NOTHING_PRINTED} (exit code ${run2.code}${run2.killed ? ", stopped" : ""})`;
|
|
4620
|
+
return parsed2;
|
|
2990
4621
|
}
|
|
2991
|
-
async function promptFor(job, project, cli) {
|
|
4622
|
+
async function promptFor(job, project, cli, options = {}) {
|
|
2992
4623
|
const j = withComponentFiles(job, project);
|
|
2993
|
-
const
|
|
4624
|
+
const located = j.attempt === 2 ? [] : jobLocations(j, project);
|
|
4625
|
+
const where = j.attempt === 2 ? "" : [whereSection(j, project, located), factsSection(j, project, located.map((l) => l.at.file))].filter(Boolean).join("\n\n");
|
|
2994
4626
|
const texts = (await attachmentBlocks(j)).flatMap((b) => b.type === "text" ? [b.text] : []);
|
|
2995
4627
|
const skill = skillOf(j);
|
|
2996
|
-
return [...skill ? [cli.invokeSkill(skill)] : [], jobPrompt(j, where), ...texts].join("\n\n");
|
|
4628
|
+
return [...skill ? [cli.invokeSkill(skill)] : [], jobPrompt(j, where, options), ...texts].join("\n\n");
|
|
2997
4629
|
}
|
|
2998
4630
|
function sessionToResume(job, agent) {
|
|
2999
4631
|
const request = job.changeSet.request;
|
|
@@ -3015,16 +4647,27 @@ function replyOf(reply) {
|
|
|
3015
4647
|
}
|
|
3016
4648
|
}
|
|
3017
4649
|
notes = notes.trim();
|
|
3018
|
-
|
|
4650
|
+
const refused = refusedOf(data.refused);
|
|
4651
|
+
return { notes: notes || void 0, question: questionOf(data.question), props: propsOf(data.props), ...refused.length ? { refused } : {} };
|
|
3019
4652
|
}
|
|
3020
4653
|
function signInProblem(error) {
|
|
3021
4654
|
return !!error && /not (logged|signed) in|log ?in required|please (run )?\/?login|authenticat|unauthori[sz]ed|\b401\b|api key/i.test(error);
|
|
3022
4655
|
}
|
|
3023
|
-
function
|
|
4656
|
+
function outdatedNote(cli, missing) {
|
|
4657
|
+
return [`! ${cli.label} needs an update to work with Pilot. In a terminal, run:`, ` ${cli.update}`, ` (This version doesn't support ${missing.join(", ")}, which Pilot uses.)`].join("\n");
|
|
4658
|
+
}
|
|
4659
|
+
function errorFor(cli, error, missing) {
|
|
3024
4660
|
if (signInProblem(error)) return { title: `${cli.label} isn't signed in`, detail: `Run ${cli.signIn} in a terminal, then send again.` };
|
|
4661
|
+
if (missing?.length)
|
|
4662
|
+
return {
|
|
4663
|
+
title: `${cli.label} needs an update`,
|
|
4664
|
+
detail: `This version of ${cli.label} can't work with Pilot yet. In a terminal, run ${cli.update}, then send again.`
|
|
4665
|
+
};
|
|
4666
|
+
const lines = (error ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
|
|
4667
|
+
const telling = lines.find((l) => !l.startsWith(NOTHING_PRINTED)) ?? lines[0] ?? "It stopped without a reply.";
|
|
3025
4668
|
return {
|
|
3026
4669
|
title: `${cli.label} couldn't do this job`,
|
|
3027
|
-
detail: `${
|
|
4670
|
+
detail: `${telling.slice(0, 300)} The terminal running npx usepilot has the details. Send again to retry.`
|
|
3028
4671
|
};
|
|
3029
4672
|
}
|
|
3030
4673
|
function describeJob(job) {
|
|
@@ -3046,13 +4689,13 @@ function nameOf(target) {
|
|
|
3046
4689
|
return target.text ? `${target.tag} "${target.text.length > 30 ? `${target.text.slice(0, 30)}\u2026` : target.text}"` : target.tag;
|
|
3047
4690
|
}
|
|
3048
4691
|
function sleep(ms, signal) {
|
|
3049
|
-
return new Promise((
|
|
3050
|
-
const timer = setTimeout(
|
|
4692
|
+
return new Promise((resolve5) => {
|
|
4693
|
+
const timer = setTimeout(resolve5, ms);
|
|
3051
4694
|
signal?.addEventListener(
|
|
3052
4695
|
"abort",
|
|
3053
4696
|
() => {
|
|
3054
4697
|
clearTimeout(timer);
|
|
3055
|
-
|
|
4698
|
+
resolve5();
|
|
3056
4699
|
},
|
|
3057
4700
|
{ once: true }
|
|
3058
4701
|
);
|
|
@@ -3061,14 +4704,14 @@ function sleep(ms, signal) {
|
|
|
3061
4704
|
|
|
3062
4705
|
// src/update.ts
|
|
3063
4706
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
3064
|
-
import { existsSync as
|
|
4707
|
+
import { existsSync as existsSync10, readFileSync as readFileSync11 } from "fs";
|
|
3065
4708
|
import { homedir as homedir5 } from "os";
|
|
3066
|
-
import { dirname as
|
|
4709
|
+
import { dirname as dirname8, join as join13 } from "path";
|
|
3067
4710
|
async function update(options = {}) {
|
|
3068
4711
|
const cwd = options.cwd ?? process.cwd();
|
|
3069
4712
|
const run2 = options.run ?? runCommand2;
|
|
3070
4713
|
const home = options.home ?? homedir5();
|
|
3071
|
-
const pkg = readJson3(
|
|
4714
|
+
const pkg = readJson3(join13(cwd, "package.json"));
|
|
3072
4715
|
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
3073
4716
|
if (!pkg || !deps.usepilot) {
|
|
3074
4717
|
return `# Pilot isn't installed here
|
|
@@ -3119,18 +4762,18 @@ ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
|
|
|
3119
4762
|
` : "Nothing else to do.\n"}`;
|
|
3120
4763
|
}
|
|
3121
4764
|
function bridgeOf(cwd, root) {
|
|
3122
|
-
for (let dir = cwd; ; dir =
|
|
3123
|
-
const file =
|
|
3124
|
-
if (
|
|
3125
|
-
const match = /BRIDGE_VERSION = (\d+)/.exec(
|
|
4765
|
+
for (let dir = cwd; ; dir = dirname8(dir)) {
|
|
4766
|
+
const file = join13(dir, "node_modules", "usepilot", "cli", "index.js");
|
|
4767
|
+
if (existsSync10(file)) {
|
|
4768
|
+
const match = /BRIDGE_VERSION = (\d+)/.exec(readFileSync11(file, "utf8"));
|
|
3126
4769
|
return match ? Number(match[1]) : null;
|
|
3127
4770
|
}
|
|
3128
|
-
if (dir === root ||
|
|
4771
|
+
if (dir === root || dirname8(dir) === dir) return null;
|
|
3129
4772
|
}
|
|
3130
4773
|
}
|
|
3131
4774
|
function readJson3(file) {
|
|
3132
4775
|
try {
|
|
3133
|
-
return JSON.parse(
|
|
4776
|
+
return JSON.parse(readFileSync11(file, "utf8"));
|
|
3134
4777
|
} catch {
|
|
3135
4778
|
return null;
|
|
3136
4779
|
}
|