@uselazuli/cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -0
  3. package/README.md +202 -2
  4. package/agents/lazuli-design-reviewer.md +30 -0
  5. package/agents/lazuli-first-look.md +22 -0
  6. package/agents/lazuli-task-tester.md +25 -0
  7. package/bin/lazuli.mjs +699 -0
  8. package/package.json +11 -4
  9. package/rules/accessibility/HYPOTHESES.md +8 -0
  10. package/rules/accessibility/_area.yaml +7 -0
  11. package/rules/accessibility/operable.yaml +100 -0
  12. package/rules/accessibility/perceivable.yaml +153 -0
  13. package/rules/accessibility/robust.yaml +24 -0
  14. package/rules/accessibility/understandable.yaml +72 -0
  15. package/rules/color/HYPOTHESES.md +27 -0
  16. package/rules/color/_area.yaml +10 -0
  17. package/rules/color/adapt.yaml +183 -0
  18. package/rules/color/create.yaml +259 -0
  19. package/rules/color/review.yaml +215 -0
  20. package/rules/color/signal.yaml +196 -0
  21. package/rules/content/HYPOTHESES.md +18 -0
  22. package/rules/content/_area.yaml +8 -0
  23. package/rules/content/review.yaml +347 -0
  24. package/rules/content/voice.yaml +144 -0
  25. package/rules/content/writing.yaml +202 -0
  26. package/rules/data/HYPOTHESES.md +11 -0
  27. package/rules/data/_area.yaml +7 -0
  28. package/rules/data/charts.yaml +189 -0
  29. package/rules/data/dashboards.yaml +141 -0
  30. package/rules/data/review.yaml +159 -0
  31. package/rules/graphic/HYPOTHESES.md +17 -0
  32. package/rules/graphic/_area.yaml +8 -0
  33. package/rules/graphic/identity.yaml +141 -0
  34. package/rules/graphic/pieces.yaml +164 -0
  35. package/rules/graphic/review.yaml +242 -0
  36. package/rules/graphic/symbol.yaml +141 -0
  37. package/rules/motion/HYPOTHESES.md +19 -0
  38. package/rules/motion/_area.yaml +7 -0
  39. package/rules/motion/micro.yaml +143 -0
  40. package/rules/motion/review.yaml +347 -0
  41. package/rules/motion/transitions.yaml +169 -0
  42. package/rules/typography/HYPOTHESES.md +12 -0
  43. package/rules/typography/_area.yaml +8 -0
  44. package/rules/typography/adapt.yaml +45 -0
  45. package/rules/typography/create.yaml +126 -0
  46. package/rules/typography/review.yaml +127 -0
  47. package/rules/ui/HYPOTHESES.md +23 -0
  48. package/rules/ui/_area.yaml +9 -0
  49. package/rules/ui/compose.yaml +219 -0
  50. package/rules/ui/grid.yaml +75 -0
  51. package/rules/ui/review.yaml +399 -0
  52. package/rules/ui/states.yaml +257 -0
  53. package/rules/ux/HYPOTHESES.md +13 -0
  54. package/rules/ux/_area.yaml +8 -0
  55. package/rules/ux/flows.yaml +164 -0
  56. package/rules/ux/forms.yaml +142 -0
  57. package/rules/ux/review.yaml +186 -0
  58. package/skills/lazuli/SKILL.md +180 -0
  59. package/skills/lazuli/procedures/create.md +29 -0
  60. package/skills/lazuli/procedures/explain-decisions.md +22 -0
  61. package/skills/lazuli/procedures/improve.md +30 -0
  62. package/skills/lazuli/procedures/remember-this.md +41 -0
  63. package/skills/lazuli/procedures/review-design.md +35 -0
  64. package/skills/lazuli/procedures/show-options.md +32 -0
  65. package/skills/lazuli-accessibility-check/SKILL.md +68 -0
  66. package/skills/lazuli-color-context-and-culture/SKILL.md +53 -0
  67. package/skills/lazuli-color-context-and-culture/references/sectors.md +26 -0
  68. package/skills/lazuli-color-palette-by-intent/SKILL.md +54 -0
  69. package/skills/lazuli-color-palette-by-intent/references/intent-chords.md +51 -0
  70. package/skills/lazuli-color-screen-review/SKILL.md +51 -0
  71. package/skills/lazuli-color-states-and-signals/SKILL.md +53 -0
  72. package/skills/lazuli-content-interface-writing/SKILL.md +53 -0
  73. package/skills/lazuli-content-voice/SKILL.md +39 -0
  74. package/skills/lazuli-data-charts-and-dashboards/SKILL.md +59 -0
  75. package/skills/lazuli-graphic-derived-pieces/SKILL.md +40 -0
  76. package/skills/lazuli-graphic-derived-pieces/references/piece-template.html +24 -0
  77. package/skills/lazuli-graphic-identity/SKILL.md +43 -0
  78. package/skills/lazuli-motion-micro-and-transitions/SKILL.md +49 -0
  79. package/skills/lazuli-typography-choose-and-pair/SKILL.md +50 -0
  80. package/skills/lazuli-typography-screen-review/SKILL.md +51 -0
  81. package/skills/lazuli-ui-composition/SKILL.md +42 -0
  82. package/skills/lazuli-ui-composition/references/option-template.html +34 -0
  83. package/skills/lazuli-ui-layout-review/SKILL.md +47 -0
  84. package/skills/lazuli-ui-states-and-system/SKILL.md +54 -0
  85. package/skills/lazuli-ux-flows-and-forms/SKILL.md +51 -0
  86. package/skills/lazuli-ux-task-test/SKILL.md +44 -0
  87. package/src/browser.mjs +161 -0
  88. package/src/commands/capture.mjs +313 -0
  89. package/src/commands/catalog.mjs +37 -0
  90. package/src/commands/check-design.mjs +428 -0
  91. package/src/commands/check-goals.mjs +57 -0
  92. package/src/commands/compare-designs.mjs +97 -0
  93. package/src/commands/draft-memo.mjs +161 -0
  94. package/src/commands/hooks.mjs +343 -0
  95. package/src/commands/install-hooks.mjs +120 -0
  96. package/src/commands/install.mjs +132 -0
  97. package/src/commands/list-rules.mjs +49 -0
  98. package/src/commands/map-page.mjs +594 -0
  99. package/src/commands/record-answers.mjs +79 -0
  100. package/src/commands/record-log.mjs +296 -0
  101. package/src/commands/record-task.mjs +250 -0
  102. package/src/commands/render-options.mjs +164 -0
  103. package/src/commands/start-project.mjs +32 -0
  104. package/src/measure/a11y.mjs +383 -0
  105. package/src/measure/asset.mjs +206 -0
  106. package/src/measure/at-rest.mjs +49 -0
  107. package/src/measure/cases.mjs +549 -0
  108. package/src/measure/chart-read.mjs +401 -0
  109. package/src/measure/chart.mjs +264 -0
  110. package/src/measure/coherence.mjs +145 -0
  111. package/src/measure/color.mjs +79 -0
  112. package/src/measure/content.mjs +82 -0
  113. package/src/measure/cvd.mjs +24 -0
  114. package/src/measure/extreme.mjs +241 -0
  115. package/src/measure/forms.mjs +150 -0
  116. package/src/measure/in-page/a11y.js +489 -0
  117. package/src/measure/in-page/color.js +346 -0
  118. package/src/measure/in-page/composition.js +1496 -0
  119. package/src/measure/in-page/contrast.js +15 -0
  120. package/src/measure/in-page/cvd.js +173 -0
  121. package/src/measure/in-page/extreme.js +355 -0
  122. package/src/measure/in-page/frames.js +781 -0
  123. package/src/measure/in-page/look.js +28 -0
  124. package/src/measure/in-page/motion-probe.js +169 -0
  125. package/src/measure/in-page/style.js +107 -0
  126. package/src/measure/in-page/svg-strokes.js +112 -0
  127. package/src/measure/in-page/svg-uses.js +50 -0
  128. package/src/measure/in-page/symbol.js +123 -0
  129. package/src/measure/in-page/type.js +266 -0
  130. package/src/measure/in-page/weight.js +207 -0
  131. package/src/measure/layout.mjs +91 -0
  132. package/src/measure/motion.mjs +508 -0
  133. package/src/measure/piece.mjs +195 -0
  134. package/src/measure/registry.mjs +252 -0
  135. package/src/measure/rhythm.mjs +81 -0
  136. package/src/measure/signature.mjs +65 -0
  137. package/src/measure/states.mjs +240 -0
  138. package/src/measure/style.mjs +13 -0
  139. package/src/measure/symbol.mjs +268 -0
  140. package/src/measure/terms.mjs +153 -0
  141. package/src/measure/tiles.mjs +20 -0
  142. package/src/measure/timeline.mjs +621 -0
  143. package/src/measure/type.mjs +167 -0
  144. package/src/measure/weight.mjs +18 -0
  145. package/src/private-strings.mjs +81 -0
  146. package/src/project/blind.mjs +70 -0
  147. package/src/project/edits.mjs +154 -0
  148. package/src/project/gate.mjs +159 -0
  149. package/src/project/lazuli-md.mjs +497 -0
  150. package/src/project/log.mjs +329 -0
  151. package/src/project/match.mjs +112 -0
  152. package/src/project/records.mjs +380 -0
  153. package/src/project/tasks.mjs +153 -0
  154. package/src/report/evaluate.mjs +27 -0
  155. package/src/report/evaluators/a11y.mjs +206 -0
  156. package/src/report/evaluators/chart.mjs +151 -0
  157. package/src/report/evaluators/coherence.mjs +103 -0
  158. package/src/report/evaluators/color.mjs +86 -0
  159. package/src/report/evaluators/content.mjs +112 -0
  160. package/src/report/evaluators/extreme.mjs +53 -0
  161. package/src/report/evaluators/forms.mjs +116 -0
  162. package/src/report/evaluators/layout.mjs +94 -0
  163. package/src/report/evaluators/motion.mjs +273 -0
  164. package/src/report/evaluators/piece.mjs +69 -0
  165. package/src/report/evaluators/rhythm.mjs +99 -0
  166. package/src/report/evaluators/states.mjs +39 -0
  167. package/src/report/evaluators/style.mjs +35 -0
  168. package/src/report/evaluators/symbol.mjs +110 -0
  169. package/src/report/evaluators/terms.mjs +49 -0
  170. package/src/report/evaluators/type.mjs +163 -0
  171. package/src/report/evaluators/weight.mjs +51 -0
  172. package/src/report/evidence.mjs +4 -0
  173. package/src/report/finding.mjs +11 -0
  174. package/src/report/format.mjs +215 -0
  175. package/src/rules/hypotheses.mjs +28 -0
  176. package/src/rules/load.mjs +256 -0
  177. package/src/rules/public-text.mjs +56 -0
  178. package/src/rules/schema.mjs +212 -0
  179. package/templates/LAZULI.md +86 -0
@@ -0,0 +1,380 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { readLazuliMd } from "./lazuli-md.mjs";
4
+ import { matchGoals, targetKey } from "./match.mjs";
5
+ import { findTask, noTaskMessage } from "./tasks.mjs";
6
+
7
+ export class RecordError extends Error {
8
+ constructor(problems) {
9
+ super(problems.join("\n"));
10
+ this.name = "RecordError";
11
+ this.code = "RECORD_INVALID";
12
+ this.problems = problems;
13
+ }
14
+ }
15
+
16
+ const norm = (s) => String(s ?? "").trim().toLowerCase();
17
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
18
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
19
+ // Implementation tolerances, not rules: the longest text a record stores, and how long a write waits for another.
20
+ export const MAX_TEXT_CHARS = 2000;
21
+ const LOCK_TRIES = 100;
22
+ const LOCK_WAIT_MS = 50;
23
+ const LOCK_STALE_MS = 30000;
24
+ const CAPTURE_ID = /^[0-9A-Za-z_-]+$/;
25
+
26
+ const VERDICTS = ["redo", "fix", "approve"];
27
+ const IDEAS = ["shown", "missing", "none"];
28
+ const DIMENSIONS = ["understand", "feel", "do"];
29
+ const LEVELS = ["met", "partly", "missed"];
30
+
31
+ function validateFirstLook(data, { manifest, records }) {
32
+ const problems = [];
33
+ // A pending review holds no first look, so it does not lock the capture: the real review replaces it.
34
+ if (records.some((r) => r.kind === "review" && r.captureId === manifest.captureId && r.data?.verdict !== "pending")) {
35
+ problems.push(`A review is already recorded for ${manifest.captureId}; its first look cannot be replaced.`);
36
+ }
37
+ if (!isText(data.reader)) {
38
+ problems.push("reader is required.");
39
+ }
40
+ if (!Array.isArray(data.answers)) {
41
+ problems.push("answers must be a list with one answer per captured width.");
42
+ return problems;
43
+ }
44
+ const answers = data.answers.filter(isObject);
45
+ for (const a of answers) {
46
+ if (!Number.isInteger(a.width)) {
47
+ problems.push(`Width ${JSON.stringify(a.width)} must be a whole number of pixels.`);
48
+ }
49
+ }
50
+ if (answers.length !== data.answers.length) {
51
+ problems.push("Each answer must be an object.");
52
+ }
53
+ for (const w of manifest.widths) {
54
+ const n = answers.filter((a) => a.width === w).length;
55
+ if (n === 0) {
56
+ problems.push(`No answer for width ${w}.`);
57
+ } else if (n > 1) {
58
+ problems.push(`More than one answer for width ${w}.`);
59
+ }
60
+ }
61
+ for (const a of answers) {
62
+ if (!Number.isInteger(a.width)) {
63
+ continue;
64
+ }
65
+ if (!manifest.widths.includes(a.width)) {
66
+ problems.push(`Width ${a.width} was not captured.`);
67
+ continue;
68
+ }
69
+ for (const field of ["about", "mainAction", "feeling"]) {
70
+ if (!isText(a[field])) {
71
+ problems.push(`Answer for width ${a.width}: ${field} is required.`);
72
+ }
73
+ }
74
+ }
75
+ return problems;
76
+ }
77
+
78
+ // A review nobody could run: it records why, needs no first look, goals or fixes, and never opens the gate.
79
+ function validatePendingReview(data) {
80
+ const problems = [];
81
+ if (!isText(data.reason)) {
82
+ problems.push("A pending review needs a reason: say who or what was missing.");
83
+ }
84
+ const given = (v) => v !== undefined && !(Array.isArray(v) && v.length === 0);
85
+ if (given(data.goals)) {
86
+ problems.push("A pending review judges no goals; leave goals out.");
87
+ }
88
+ if (given(data.fixes)) {
89
+ problems.push("A pending review lists no fixes; leave fixes out.");
90
+ }
91
+ return problems;
92
+ }
93
+
94
+ function validateReview(data, { manifest, goals, records, idea }) {
95
+ if (data.verdict === "pending") {
96
+ return validatePendingReview(data);
97
+ }
98
+ const problems = [];
99
+ if (!records.some((r) => r.kind === "first-look" && r.captureId === manifest.captureId)) {
100
+ problems.push(`Record the first look for ${manifest.captureId} before the review.`);
101
+ }
102
+ if (!isText(data.reviewer)) {
103
+ problems.push("reviewer is required.");
104
+ }
105
+ if (!VERDICTS.includes(data.verdict)) {
106
+ problems.push(`verdict must be one of ${VERDICTS.join(", ")}, or pending with a reason when no reviewer is available.`);
107
+ }
108
+ if (!IDEAS.includes(data.idea)) {
109
+ problems.push(`idea must be one of ${IDEAS.join(", ")}.`);
110
+ } else if (data.idea === "none" && idea) {
111
+ problems.push("idea is none, but LAZULI.md has an idea; use shown or missing.");
112
+ }
113
+
114
+ const judged = Array.isArray(data.goals) ? data.goals.filter(isObject) : [];
115
+ if (!Array.isArray(data.goals)) {
116
+ problems.push("goals must be a list with one item per goal of the page.");
117
+ }
118
+ const named = new Map();
119
+ for (const g of judged) {
120
+ const piece = norm(g.piece);
121
+ named.set(piece, (named.get(piece) ?? 0) + 1);
122
+ }
123
+ for (const g of goals) {
124
+ const n = named.get(norm(g.piece)) ?? 0;
125
+ if (n === 0 && Array.isArray(data.goals)) {
126
+ problems.push(`Goal "${g.piece}" is not judged.`);
127
+ } else if (n > 1) {
128
+ problems.push(`Goal "${g.piece}" is judged more than once.`);
129
+ }
130
+ }
131
+ const known = new Set(goals.map((g) => norm(g.piece)));
132
+ for (const g of judged) {
133
+ if (!known.has(norm(g.piece))) {
134
+ problems.push(`"${g.piece}" is not a goal of this page.`);
135
+ }
136
+ }
137
+ for (const g of judged) {
138
+ const label = g.piece;
139
+ for (const d of DIMENSIONS) {
140
+ if (!LEVELS.includes(g[d])) {
141
+ problems.push(`Goal "${label}": ${d} must be one of ${LEVELS.join(", ")}.`);
142
+ } else if (g[d] === "missed" && data.verdict === "approve") {
143
+ problems.push(`approve with a missed goal: "${label}" ${d}.`);
144
+ }
145
+ }
146
+ if (!isText(g.evidence)) {
147
+ problems.push(`Goal "${label}": evidence is required.`);
148
+ }
149
+ }
150
+
151
+ const fixesOk = Array.isArray(data.fixes) && data.fixes.every(isText);
152
+ if (!fixesOk) {
153
+ problems.push("fixes must be a list of text, one change per item.");
154
+ } else if ((data.verdict === "fix" || data.verdict === "redo") && data.fixes.length === 0) {
155
+ problems.push(`${data.verdict} needs at least one fix.`);
156
+ }
157
+ return problems;
158
+ }
159
+
160
+ // One entry per kind. Later sub-plans add kinds (F adds "task") by adding an entry here.
161
+ // normalize keeps only the known fields of a valid record, so nothing else is stored.
162
+ function normalizeFirstLook(d) {
163
+ return { captureId: d.captureId, reader: d.reader, answers: d.answers.map((a) => ({ width: a.width, about: a.about, mainAction: a.mainAction, feeling: a.feeling })) };
164
+ }
165
+
166
+ // ctx carries the goals of the page and the idea as LAZULI.md has them now; the review keeps that text so the gate can tell when it changed.
167
+ function normalizeReview(d, ctx) {
168
+ if (d.verdict === "pending") {
169
+ return { captureId: d.captureId, verdict: "pending", reason: d.reason };
170
+ }
171
+ const textOf = (piece) => {
172
+ const g = ctx.goals.find((x) => norm(x.piece) === norm(piece));
173
+ return { understand: g?.understand ?? "", feel: g?.feel ?? "", do: g?.do ?? "" };
174
+ };
175
+ return {
176
+ captureId: d.captureId,
177
+ reviewer: d.reviewer,
178
+ verdict: d.verdict,
179
+ idea: d.idea,
180
+ ideaText: ctx.idea ?? "",
181
+ goals: d.goals.map((g) => ({ piece: g.piece, understand: g.understand, feel: g.feel, do: g.do, evidence: g.evidence, goalText: textOf(g.piece) })),
182
+ fixes: [...d.fixes],
183
+ };
184
+ }
185
+
186
+ // A closed simulated task. record-task builds the data from the step maps and the answers, so only the
187
+ // one-record-per-task rule is checked here. It never counts as a review: the gate reads reviews only.
188
+ const TASK_OUTCOMES = ["done", "stuck", "stopped", "left"];
189
+
190
+ function validateTask(data, { manifest, records }) {
191
+ const problems = [];
192
+ if (records.some((r) => r.kind === "task" && r.taskId === manifest.taskId)) {
193
+ problems.push(`A task record for ${manifest.taskId} is already stored.`);
194
+ }
195
+ if (!TASK_OUTCOMES.includes(data.outcome)) {
196
+ problems.push(`outcome must be one of ${TASK_OUTCOMES.join(", ")}.`);
197
+ }
198
+ return problems;
199
+ }
200
+
201
+ function normalizeTask(d) {
202
+ return { taskId: d.taskId, piece: d.piece, task: d.task, tester: d.tester, outcome: d.outcome, reason: d.reason ?? null, remembered: d.remembered ?? "", steps: Array.isArray(d.steps) ? d.steps : [], counts: d.counts };
203
+ }
204
+
205
+ // locate: the field of the data that names the folder the record belongs to, how to find it, and what to
206
+ // say when it is missing. Kinds without one belong to a capture.
207
+ const CAPTURE_LOCATOR = {
208
+ id: "captureId",
209
+ find: findCapture,
210
+ missing: (id) => (isText(id) ? `No capture "${id}" under .lazuli/captures. Run capture first.` : "captureId is required."),
211
+ };
212
+
213
+ export const RECORD_KINDS = {
214
+ "first-look": { validate: validateFirstLook, normalize: normalizeFirstLook },
215
+ review: { validate: validateReview, normalize: normalizeReview },
216
+ task: { validate: validateTask, normalize: normalizeTask, locate: { id: "taskId", find: findTask, missing: (id) => (isText(id) ? noTaskMessage(id) : "taskId is required.") } },
217
+ };
218
+
219
+ function longTexts(value, found = []) {
220
+ if (typeof value === "string") {
221
+ if (value.length > MAX_TEXT_CHARS) {
222
+ found.push(value);
223
+ }
224
+ } else if (Array.isArray(value)) {
225
+ value.forEach((v) => longTexts(v, found));
226
+ } else if (isObject(value)) {
227
+ Object.values(value).forEach((v) => longTexts(v, found));
228
+ }
229
+ return found;
230
+ }
231
+
232
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
233
+
234
+ // Writes next to the file and renames over it, so a failed write never leaves a half file.
235
+ export async function writeFileAtomic(file, text) {
236
+ const tmp = `${file}.tmp-${process.pid}`;
237
+ try {
238
+ await fs.writeFile(tmp, text);
239
+ } catch (err) {
240
+ await fs.rm(tmp, { force: true });
241
+ throw err;
242
+ }
243
+ try {
244
+ await fs.rename(tmp, file);
245
+ } catch (err) {
246
+ await fs.rm(tmp, { force: true });
247
+ if (err?.code !== "EPERM" && err?.code !== "EBUSY") {
248
+ throw err;
249
+ }
250
+ await fs.writeFile(file, text);
251
+ }
252
+ }
253
+
254
+ // One writer at a time per records file: a lock file made with the wx flag, removed in finally.
255
+ export async function withLock(file, fn) {
256
+ const lock = `${file}.lock`;
257
+ let held = false;
258
+ for (let i = 0; i < LOCK_TRIES && !held; i++) {
259
+ try {
260
+ await (await fs.open(lock, "wx")).close();
261
+ held = true;
262
+ } catch (err) {
263
+ if (err?.code !== "EEXIST" && err?.code !== "EPERM" && err?.code !== "EBUSY") {
264
+ throw err;
265
+ }
266
+ try {
267
+ if (Date.now() - (await fs.stat(lock)).mtimeMs > LOCK_STALE_MS) {
268
+ await fs.rm(lock, { force: true });
269
+ continue;
270
+ }
271
+ } catch {
272
+ continue;
273
+ }
274
+ await sleep(LOCK_WAIT_MS);
275
+ }
276
+ }
277
+ if (!held) {
278
+ throw new RecordError([`Another run holds ${lock}; try again.`]);
279
+ }
280
+ try {
281
+ return await fn();
282
+ } finally {
283
+ await fs.rm(lock, { force: true });
284
+ }
285
+ }
286
+
287
+ export function recordFilePath(cwd, key) {
288
+ return path.join(path.resolve(cwd), ".lazuli", "records", `${key}.json`);
289
+ }
290
+
291
+ // Finds .lazuli/captures/*/<captureId>/capture.json. The manifest comes back with absolute dir and targetFile, and folderKey, the folder it was found in.
292
+ export async function findCapture(cwd, captureId) {
293
+ if (typeof captureId !== "string" || !CAPTURE_ID.test(captureId)) {
294
+ return null;
295
+ }
296
+ const root = path.resolve(cwd);
297
+ const base = path.join(root, ".lazuli", "captures");
298
+ let keys;
299
+ try {
300
+ keys = await fs.readdir(base);
301
+ } catch {
302
+ return null;
303
+ }
304
+ for (const key of keys) {
305
+ try {
306
+ const manifest = JSON.parse(await fs.readFile(path.join(base, key, captureId, "capture.json"), "utf8"));
307
+ const abs = (p) => (typeof p === "string" && !path.isAbsolute(p) ? path.resolve(root, p) : p);
308
+ return { ...manifest, folderKey: key, dir: abs(manifest.dir) ?? path.join(base, key, captureId), targetFile: abs(manifest.targetFile) };
309
+ } catch {
310
+ // not in this folder, or unreadable: keep looking
311
+ }
312
+ }
313
+ return null;
314
+ }
315
+
316
+ async function readFileRecords(file) {
317
+ let text;
318
+ try {
319
+ text = await fs.readFile(file, "utf8");
320
+ } catch (err) {
321
+ if (err?.code === "ENOENT") {
322
+ return null;
323
+ }
324
+ throw err;
325
+ }
326
+ let parsed;
327
+ try {
328
+ parsed = JSON.parse(text);
329
+ } catch {
330
+ parsed = null;
331
+ }
332
+ if (!isObject(parsed) || !Array.isArray(parsed.records)) {
333
+ throw new RecordError([`${file} is not a records file; it was left as it was.`]);
334
+ }
335
+ return parsed;
336
+ }
337
+
338
+ // Records of a page, oldest first, [] when there are none. Every written form of the target gives the same file.
339
+ export async function readRecords(cwd, target) {
340
+ const found = await readFileRecords(recordFilePath(cwd, targetKey(target, path.resolve(cwd))));
341
+ return found ? found.records : [];
342
+ }
343
+
344
+ export async function appendRecord({ cwd = process.cwd(), kind, data, beforeWrite }) {
345
+ const root = path.resolve(cwd);
346
+ const entry = Object.hasOwn(RECORD_KINDS, kind) ? RECORD_KINDS[kind] : null;
347
+ if (!entry) {
348
+ throw new RecordError([`Unknown record kind "${kind}".`]);
349
+ }
350
+ if (!isObject(data)) {
351
+ throw new RecordError(["The record must be a JSON object."]);
352
+ }
353
+ const locate = entry.locate ?? CAPTURE_LOCATOR;
354
+ const manifest = await locate.find(root, data[locate.id]);
355
+ if (!manifest) {
356
+ throw new RecordError([locate.missing(data[locate.id])]);
357
+ }
358
+ const file = recordFilePath(root, manifest.folderKey);
359
+ await fs.mkdir(path.dirname(file), { recursive: true });
360
+ return withLock(file, async () => {
361
+ const existing = await readFileRecords(file);
362
+ const records = existing?.records ?? [];
363
+ const md = await readLazuliMd(root);
364
+ const goals = matchGoals(md, manifest.target, root);
365
+ const problems = entry.validate(data, { manifest, goals, records, idea: md?.idea ?? null });
366
+ if (problems.length > 0) {
367
+ throw new RecordError(problems);
368
+ }
369
+ const clean = entry.normalize(data, { goals, idea: md?.idea ?? null });
370
+ if (longTexts(clean).length > 0) {
371
+ throw new RecordError([`A text is longer than ${MAX_TEXT_CHARS} characters.`]);
372
+ }
373
+ const record = { kind, at: new Date().toISOString(), [locate.id]: manifest[locate.id], data: clean };
374
+ if (beforeWrite) {
375
+ await beforeWrite(record, manifest);
376
+ }
377
+ await writeFileAtomic(file, JSON.stringify({ target: existing?.target ?? manifest.target, records: [...records, record] }, null, 2));
378
+ return record;
379
+ });
380
+ }
@@ -0,0 +1,153 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ // The simulated task: what counts as local, which links name a checkout or payment flow, and what the
5
+ // walk may do with each action of a step. The CLI itself never clicks, types or submits anything.
6
+
7
+ export class TaskInputError extends Error {
8
+ constructor(problems) {
9
+ super(problems.join("\n"));
10
+ this.name = "TaskInputError";
11
+ this.code = "TASK_INPUT";
12
+ this.problems = problems;
13
+ }
14
+ }
15
+
16
+ // Definition, not a cutoff: fixed before any
17
+ // site was read, and never edited after a site reading. Words match whole tokens of a URL's path and
18
+ // query, lowercased and split on every character that is not a letter or a digit. Plurals, commerce
19
+ // words and links that change state with a plain GET (add, remove, delete, logout) stop the walk too;
20
+ // signup, register and cadastro stay out (opening a sign-up page only reads it).
21
+ export const FLOW_STOP_WORDS = [
22
+ "checkout", "checkouts", "cart", "carrinho", "carrinhos", "payment", "payments", "pay", "pagamento", "pagamentos", "pagar",
23
+ "billing", "cobranca", "cobrança", "buy", "order", "orders", "basket", "bag", "comprar", "compra", "pedido", "finalizar",
24
+ "add", "remove", "delete", "logout", "signout", "unsubscribe", "cancelar",
25
+ // Added later, still before any tuning to a site.
26
+ "pedidos", "sair", "remover", "excluir", "deletar",
27
+ ];
28
+ // Definition, not a cutoff: matched as lowercase substrings of the
29
+ // same text, so compounds and camelCase stop too (/onestepcheckout/, /AddToCart, ?checkoutMode=).
30
+ // Over-blocking is the safe direction. "cart" alone is not here: it is inside ordinary words.
31
+ export const FLOW_STOP_SUBSTRINGS = ["checkout", "payment", "pagamento", "carrinho", "sacola", "addtocart", "add-to-cart", "logout", "logoff", "signout", "unsubscribe", "descadastr"];
32
+
33
+ export const STOP_CHECKOUT = "a checkout or payment link on a site that is not local";
34
+ export const STOP_CONTROL = "a control on a site that is not local: the task does not click, type or submit here";
35
+ export const STOP_FORM = "the form posts to a site that is not local";
36
+ export const STOP_PAGE = "the page is a checkout or payment page of a site that is not local";
37
+ export const LEAVES = "leaves the site";
38
+
39
+ const WEB = new Set(["http:", "https:", "file:"]);
40
+
41
+ const parse = (url) => {
42
+ try {
43
+ return new URL(url);
44
+ } catch {
45
+ return null;
46
+ }
47
+ };
48
+ const tokensOf = (text) => text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
49
+ // Each run of escapes on its own, so one malformed escape never leaves the rest undecoded.
50
+ const decode = (text) =>
51
+ text.replace(/(?:%[0-9a-f]{2})+/gi, (run) => {
52
+ try {
53
+ return decodeURIComponent(run);
54
+ } catch {
55
+ return run;
56
+ }
57
+ });
58
+ const withoutHash = (url) => String(url).split("#")[0];
59
+
60
+ // The hosts of this machine. The hooks use it as it is; isLocalTarget adds file: and .test.
61
+ export function isLoopbackHost(hostname) {
62
+ return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]";
63
+ }
64
+
65
+ // Local: a file, or a host of this machine or under .test. Everything else, a staging host included, is not.
66
+ export function isLocalTarget(url) {
67
+ const u = parse(url);
68
+ if (!u) return false;
69
+ // A file on another machine (a network share) is not local.
70
+ if (u.protocol === "file:") return u.hostname === "" || u.hostname === "localhost";
71
+ return isLoopbackHost(u.hostname) || u.hostname.endsWith(".test");
72
+ }
73
+
74
+ // A URL whose path or query names a checkout or payment flow, or a link that changes state. A fragment
75
+ // that is a route (#/checkout, #!/checkout) is read too; a plain anchor (#checkout) is not.
76
+ export function flowStopUrl(url) {
77
+ const u = parse(url);
78
+ const route = u && /^#!?\//.test(u.hash) ? u.hash : "";
79
+ const text = u ? `${decode(u.pathname)} ${decode(u.search)} ${decode(route)}` : decode(String(url));
80
+ return hasStopWord(text);
81
+ }
82
+
83
+ // The stop-word test of flowStopUrl on any text (a URL's decoded path and query, or a control's name):
84
+ // a whole token in FLOW_STOP_WORDS or a lowercase substring in FLOW_STOP_SUBSTRINGS.
85
+ export function hasStopWord(text) {
86
+ const tokens = new Set(tokensOf(String(text)));
87
+ const lower = String(text).toLowerCase();
88
+ return FLOW_STOP_WORDS.some((w) => tokens.has(w)) || FLOW_STOP_SUBSTRINGS.some((s) => lower.includes(s));
89
+ }
90
+
91
+ // Files have no origin of their own ("null"): a local file links to another local file on the same machine.
92
+ const sameOrigin = (u, origin) => (u.protocol === "file:" ? origin === "null" && isLocalTarget(u.href) : u.origin === origin);
93
+
94
+ // What the walk may do with one action: follow a link, act on a local control, leave the site, or stop.
95
+ // local, origin and pageUrl are those of this step's final URL. A link is a link only with an http, https
96
+ // or file address that is not this page; a javascript: link, a bare # and a same-page anchor are controls.
97
+ export function actOf(action, { local, origin, pageUrl }) {
98
+ const href = action.kind === "link" && typeof action.href === "string" ? action.href : null;
99
+ if (href !== null) {
100
+ const u = parse(href);
101
+ const scheme = u ? u.protocol : null;
102
+ if (scheme !== "javascript:" && !WEB.has(scheme)) {
103
+ return { act: "leave", reason: LEAVES };
104
+ }
105
+ if (scheme !== "javascript:" && withoutHash(href) !== withoutHash(pageUrl)) {
106
+ if (!isLocalTarget(href) && flowStopUrl(href)) {
107
+ return { act: "stop", reason: STOP_CHECKOUT };
108
+ }
109
+ // Only a link that stays on this step's origin is followed, local or not: another origin may be a
110
+ // hosted checkout with no stop word in its address (pay.hotmart.com, pay.kiwify.com.br).
111
+ return sameOrigin(u, origin) ? { act: "follow", reason: null } : { act: "leave", reason: LEAVES };
112
+ }
113
+ }
114
+ if (!local) {
115
+ return { act: "stop", reason: STOP_CONTROL };
116
+ }
117
+ if (typeof action.formAction === "string" && !isLocalTarget(action.formAction)) {
118
+ return { act: "stop", reason: STOP_FORM };
119
+ }
120
+ return { act: "act", reason: null };
121
+ }
122
+
123
+ export const TASK_ID = /^[0-9A-Za-z_-]+$/;
124
+ export const noTaskMessage = (taskId) => `No task "${taskId}" under .lazuli/tasks. Run map-page first.`;
125
+
126
+ export function tasksRoot(cwd) {
127
+ return path.join(path.resolve(cwd), ".lazuli", "tasks");
128
+ }
129
+
130
+ // Finds .lazuli/tasks/*/<taskId>/task.json. The manifest comes back with the absolute dir it was found in
131
+ // (never a path stored in the file), folderKey, and target, the first step's target.
132
+ export async function findTask(cwd, taskId) {
133
+ if (typeof taskId !== "string" || !TASK_ID.test(taskId)) {
134
+ return null;
135
+ }
136
+ const base = tasksRoot(cwd);
137
+ let keys;
138
+ try {
139
+ keys = await fs.readdir(base);
140
+ } catch {
141
+ return null;
142
+ }
143
+ for (const key of keys.sort()) {
144
+ const dir = path.join(base, key, taskId);
145
+ try {
146
+ const manifest = JSON.parse(await fs.readFile(path.join(dir, "task.json"), "utf8"));
147
+ return { ...manifest, dir, folderKey: key, target: manifest.steps?.[0]?.target ?? null };
148
+ } catch {
149
+ // not in this folder, or unreadable: keep looking
150
+ }
151
+ }
152
+ return null;
153
+ }
@@ -0,0 +1,27 @@
1
+ import { MEASURERS } from "../measure/registry.mjs";
2
+
3
+ // A measurer with no result at a width (it failed or did not run) skips its evaluators there.
4
+ // An evaluator that throws becomes a note on its measurer's result for that width.
5
+ export function evaluate(rules, measures, measurers = MEASURERS) {
6
+ const findings = [];
7
+ for (const m of measures) {
8
+ for (const rule of rules) {
9
+ if (!rule.measure) continue;
10
+ const measurer = measurers.find((x) => x.ids.includes(rule.measure));
11
+ const fn = measurer?.evaluators[rule.measure];
12
+ if (!fn || m[measurer.name] == null) continue;
13
+ let f;
14
+ try {
15
+ f = fn(rule, m);
16
+ } catch (err) {
17
+ const value = m[measurer.name];
18
+ if (!Array.isArray(value.notes)) value.notes = [];
19
+ const note = `${rule.measure} evaluator failed: ${err?.message ?? String(err)}`;
20
+ if (!value.notes.includes(note)) value.notes.push(note);
21
+ continue;
22
+ }
23
+ if (f) findings.push(f);
24
+ }
25
+ }
26
+ return findings;
27
+ }