@trops/dash-check 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +355 -2
  3. package/cli/bin.js +12 -0
  4. package/cli/index.d.ts +7 -0
  5. package/cli/index.js +566 -0
  6. package/examples/changes-match-plan.bad.json +4 -0
  7. package/examples/changes-match-plan.check.js +18 -0
  8. package/examples/changes-match-plan.sample.json +4 -0
  9. package/examples/commits-scoped.bad.json +5 -0
  10. package/examples/commits-scoped.check.json +6 -0
  11. package/examples/commits-scoped.sample.json +5 -0
  12. package/examples/every-acceptance-has-a-test.bad.json +3 -0
  13. package/examples/every-acceptance-has-a-test.check.js +19 -0
  14. package/examples/every-acceptance-has-a-test.sample.json +3 -0
  15. package/examples/helpers/changelog.js +23 -0
  16. package/examples/jira-comment-from-job.bad.json +5 -0
  17. package/examples/jira-comment-from-job.check.js +10 -0
  18. package/examples/jira-comment-from-job.sample.json +5 -0
  19. package/examples/lockfile-explained.bad.json +11 -0
  20. package/examples/lockfile-explained.check.json +6 -0
  21. package/examples/lockfile-explained.sample.json +11 -0
  22. package/examples/max-growth.bad.json +8 -0
  23. package/examples/max-growth.check.json +6 -0
  24. package/examples/max-growth.sample.json +8 -0
  25. package/examples/merge-outcome.bad.json +4 -0
  26. package/examples/merge-outcome.check.js +9 -0
  27. package/examples/merge-outcome.sample.json +4 -0
  28. package/examples/new-tests-are-run.bad.json +4 -0
  29. package/examples/new-tests-are-run.check.json +7 -0
  30. package/examples/new-tests-are-run.sample.json +4 -0
  31. package/examples/no-new-debt.bad.json +8 -0
  32. package/examples/no-new-debt.check.json +14 -0
  33. package/examples/no-new-debt.sample.json +8 -0
  34. package/examples/on-branch.bad.json +6 -0
  35. package/examples/on-branch.check.js +12 -0
  36. package/examples/on-branch.sample.json +6 -0
  37. package/examples/plan-complete.bad.json +5 -0
  38. package/examples/plan-complete.check.js +14 -0
  39. package/examples/plan-complete.sample.json +5 -0
  40. package/examples/plan-scope.bad.json +4 -0
  41. package/examples/plan-scope.check.json +6 -0
  42. package/examples/plan-scope.sample.json +4 -0
  43. package/examples/pr-ci.bad.json +4 -0
  44. package/examples/pr-ci.check.js +12 -0
  45. package/examples/pr-ci.sample.json +4 -0
  46. package/examples/ready-for-review.bad.json +6 -0
  47. package/examples/ready-for-review.check.json +12 -0
  48. package/examples/ready-for-review.sample.json +6 -0
  49. package/examples/setup.bad.json +6 -0
  50. package/examples/setup.check.js +8 -0
  51. package/examples/setup.sample.json +6 -0
  52. package/examples/source-has-tests.bad.json +4 -0
  53. package/examples/source-has-tests.check.json +6 -0
  54. package/examples/source-has-tests.sample.json +4 -0
  55. package/examples/test-script-is-real.bad.json +6 -0
  56. package/examples/test-script-is-real.check.json +6 -0
  57. package/examples/test-script-is-real.sample.json +6 -0
  58. package/examples/ticket-has-acceptance.bad.json +4 -0
  59. package/examples/ticket-has-acceptance.check.js +10 -0
  60. package/examples/ticket-has-acceptance.sample.json +4 -0
  61. package/examples/validate-leaves-tree-clean.bad.json +6 -0
  62. package/examples/validate-leaves-tree-clean.check.json +7 -0
  63. package/examples/validate-leaves-tree-clean.sample.json +6 -0
  64. package/examples/validate.bad.json +6 -0
  65. package/examples/validate.check.js +14 -0
  66. package/examples/validate.sample.json +6 -0
  67. package/examples/work-committed.bad.json +13 -0
  68. package/examples/work-committed.check.js +13 -0
  69. package/examples/work-committed.sample.json +5 -0
  70. package/examples/workspace-cleaned.bad.json +4 -0
  71. package/examples/workspace-cleaned.check.js +7 -0
  72. package/examples/workspace-cleaned.sample.json +4 -0
  73. package/helpers/commands.js +62 -0
  74. package/helpers/files.js +124 -0
  75. package/helpers/git.js +379 -0
  76. package/helpers/github.js +77 -0
  77. package/helpers/handoff.js +80 -0
  78. package/helpers/index.d.ts +103 -0
  79. package/helpers/index.js +36 -0
  80. package/helpers/node.js +296 -0
  81. package/helpers/plan.js +55 -0
  82. package/helpers/tracker.js +60 -0
  83. package/index.d.ts +347 -0
  84. package/index.js +86 -0
  85. package/lib/adapters/fs.js +85 -0
  86. package/lib/adapters/git.js +163 -0
  87. package/lib/adapters/github.js +151 -0
  88. package/lib/adapters/run.js +76 -0
  89. package/lib/adapters/tool.js +64 -0
  90. package/lib/context.js +102 -0
  91. package/lib/discover.js +102 -0
  92. package/lib/expect.js +238 -0
  93. package/lib/glob.js +89 -0
  94. package/lib/handoff.js +68 -0
  95. package/lib/helper.js +236 -0
  96. package/lib/register.js +35 -0
  97. package/lib/runner.js +214 -0
  98. package/lib/scope.js +107 -0
  99. package/lib/util.js +122 -0
  100. package/lib/values.js +138 -0
  101. package/package.json +59 -4
  102. package/recipe/index.d.ts +70 -0
  103. package/recipe/index.js +381 -0
  104. package/recipe/schema.json +55 -0
package/lib/runner.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * runner.js: check(), describe() and running them.
3
+ *
4
+ * A run gives
5
+ * { pass, reason, checks: [{ name, pass, skipped?, reason, failures: [{ message, at?, expected, received }], ms }] }
6
+ * and, run as a file, prints a report and then one last line,
7
+ * {"reason", "details"}: Dash's check contract, so Dash needs no new parsing.
8
+ *
9
+ * A `.check.js` file runs itself when node runs it directly
10
+ * (`node validate.check.js`), the way Dash runs a repo check today.
11
+ */
12
+ "use strict";
13
+
14
+ const fs = require("fs");
15
+ const path = require("path");
16
+ const { collect, display } = require("./scope");
17
+ const { createContext } = require("./context");
18
+
19
+ const PKG_ROOT = path.resolve(__dirname, "..");
20
+
21
+ let suite = [];
22
+ let prefix = [];
23
+ let collecting = 0;
24
+ let autorunScheduled = false;
25
+ let ranByHand = false;
26
+
27
+ function add(name, fn, mode) {
28
+ if (typeof name !== "string" || !name.trim()) throw new TypeError("check(name, fn): give the check a name");
29
+ if (typeof fn !== "function" && mode !== "skip") throw new TypeError(`check("${name}"): give it a function, (ctx) => { … }`);
30
+ suite.push({ name: [...prefix, name.trim()].join(" › "), fn, mode });
31
+ maybeAutorun();
32
+ }
33
+
34
+ /**
35
+ * Define a check. `fn` gets the context and may be async.
36
+ * @param {string} name what it proves, said so a failure reads well
37
+ * @param {(ctx: object) => any} fn
38
+ */
39
+ function check(name, fn) {
40
+ add(name, fn, null);
41
+ }
42
+ check.skip = (name, fn) => add(name, fn, "skip");
43
+ check.only = (name, fn) => add(name, fn, "only");
44
+
45
+ /** Group checks; their names are prefixed with the group's ("group › check"). */
46
+ function describe(name, fn) {
47
+ prefix.push(String(name));
48
+ try {
49
+ const r = fn();
50
+ if (r && typeof r.then === "function") throw new TypeError(`describe("${name}") can't be async: put the awaits inside check()`);
51
+ } finally {
52
+ prefix.pop();
53
+ }
54
+ }
55
+
56
+ /** The checks defined so far (and forget them). */
57
+ function takeChecks() {
58
+ const out = suite;
59
+ suite = [];
60
+ prefix = [];
61
+ return out;
62
+ }
63
+
64
+ const cut = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
65
+
66
+ /**
67
+ * Run a list of checks against a context.
68
+ * @param {Array<{ name, fn, mode }>} checks
69
+ * @param {object} ctx from createContext
70
+ * @param {{ filter?: (name: string) => boolean }} [opts]
71
+ */
72
+ async function runChecks(checks, ctx, opts = {}) {
73
+ const hasOnly = checks.some((c) => c.mode === "only");
74
+ const results = [];
75
+ for (const c of checks) {
76
+ const skip = c.mode === "skip" || (hasOnly && c.mode !== "only") || (opts.filter && !opts.filter(c.name));
77
+ if (skip) {
78
+ results.push({ name: c.name, pass: true, skipped: true, reason: "Skipped", failures: [], ms: 0 });
79
+ continue;
80
+ }
81
+ const t0 = Date.now();
82
+ const s = await collect(() => c.fn(ctx));
83
+ const pass = s.failures.length === 0;
84
+ results.push({
85
+ name: c.name,
86
+ pass,
87
+ reason: pass ? s.notes.join("; ") || "Passed" : cut(s.failures.map(display).join("; "), 2000),
88
+ failures: s.failures,
89
+ ms: Date.now() - t0,
90
+ });
91
+ }
92
+ return summarize(results);
93
+ }
94
+
95
+ /** The run's pass and reason, from its checks. */
96
+ function summarize(checks) {
97
+ const ran = checks.filter((c) => !c.skipped);
98
+ if (!checks.length) {
99
+ return { pass: false, reason: "There are no checks here: add one with check(name, fn)", checks };
100
+ }
101
+ const failed = ran.filter((c) => !c.pass);
102
+ if (!failed.length) {
103
+ if (!ran.length) return { pass: true, reason: `Skipped all ${checks.length}`, checks };
104
+ if (ran.length === 1) {
105
+ const c = ran[0];
106
+ return { pass: true, reason: c.reason && c.reason !== "Passed" ? `${c.name}: ${c.reason}` : `Passed: ${c.name}`, checks };
107
+ }
108
+ return { pass: true, reason: cut(`${ran.length} checks passed: ${ran.map((c) => c.name).join("; ")}`, 500), checks };
109
+ }
110
+ const all = failed.flatMap((c) => c.failures.map(display));
111
+ const shown = all.slice(0, 3).join("; ");
112
+ const more = all.length > 3 ? ` (and ${all.length - 3} more)` : "";
113
+ return { pass: false, reason: cut(`${shown}${more}`, 1500), checks };
114
+ }
115
+
116
+ /** A result's last line: {"reason", "details"} (Dash's contract). */
117
+ function lastLine(result) {
118
+ const details = {
119
+ checks: (result.checks || []).map((c) => ({
120
+ name: c.name,
121
+ pass: c.pass,
122
+ ...(c.skipped ? { skipped: true } : {}),
123
+ reason: c.reason,
124
+ ...(c.failures && c.failures.length
125
+ ? { failures: c.failures.slice(0, 10).map((f) => ({ message: f.message, ...(f.at ? { at: f.at } : {}), ...("expected" in f ? { expected: f.expected } : {}), ...("received" in f ? { received: f.received } : {}) })) }
126
+ : {}),
127
+ })),
128
+ ...(result.steps ? { steps: result.steps.map((s) => ({ index: s.index, label: s.label, pass: s.pass, ...(s.skipped ? { skipped: true } : {}), reason: s.reason })) } : {}),
129
+ };
130
+ let line = JSON.stringify({ reason: result.reason, details });
131
+ if (line.length > 60000) line = JSON.stringify({ reason: result.reason, details: { cut: true } });
132
+ return line;
133
+ }
134
+
135
+ /** A Jest-like report of a result. */
136
+ function report(result, { title, color = false } = {}) {
137
+ const c = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
138
+ const lines = [];
139
+ if (title) lines.push(`${result.pass ? c("42;30", " PASS ") : c("41;37", " FAIL ")} ${title}`);
140
+ const items = result.steps || result.checks || [];
141
+ for (const it of items) {
142
+ const name = it.label || it.name;
143
+ if (it.skipped) lines.push(` ${c(33, "○")} ${name} ${c(2, "(skipped)")}`);
144
+ else if (it.pass) lines.push(` ${c(32, "✓")} ${name}${it.reason && it.reason !== "Passed" ? c(2, ` (${it.reason})`) : ""}${it.ms ? c(2, ` ${it.ms} ms`) : ""}`);
145
+ else {
146
+ lines.push(` ${c(31, "✗")} ${name}`);
147
+ for (const f of it.failures || []) lines.push(` ${c(31, "●")} ${display(f)}`);
148
+ }
149
+ }
150
+ return lines.join("\n");
151
+ }
152
+
153
+ /** Read a check input file (Dash's $DASH_INPUT). `{}` when there's none. */
154
+ function readInput(file) {
155
+ if (!file) return {};
156
+ try {
157
+ return JSON.parse(fs.readFileSync(file, "utf8"));
158
+ } catch (_e) {
159
+ return {};
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Run the checks defined so far (in this file).
165
+ * @param {object} [input] the check input; default: $DASH_INPUT
166
+ * @param {object} [opts] createContext options, plus { ctx } to give your own
167
+ */
168
+ async function run(input, opts = {}) {
169
+ ranByHand = true;
170
+ const ctx = opts.ctx || createContext(input === undefined ? readInput(process.env.DASH_INPUT) : input, opts);
171
+ return runChecks(takeChecks(), ctx, opts);
172
+ }
173
+
174
+ /** Load a .check.js file's checks without running them. */
175
+ function loadChecks(file) {
176
+ const full = path.resolve(file);
177
+ const before = takeChecks();
178
+ collecting++;
179
+ try {
180
+ delete require.cache[full];
181
+ require(full);
182
+ return takeChecks();
183
+ } finally {
184
+ collecting--;
185
+ suite = before;
186
+ }
187
+ }
188
+
189
+ function isInside(file, dir) {
190
+ const rel = path.relative(dir, file);
191
+ return !!rel && !rel.startsWith("..") && !path.isAbsolute(rel);
192
+ }
193
+
194
+ function shouldAutorun() {
195
+ if (collecting || autorunScheduled || process.env.DASH_CHECK_NO_AUTORUN) return false;
196
+ const main = require.main && require.main.filename;
197
+ if (!main) return false;
198
+ return /\.check\.c?js$/.test(main) || !isInside(main, PKG_ROOT);
199
+ }
200
+
201
+ function maybeAutorun() {
202
+ if (!shouldAutorun()) return;
203
+ autorunScheduled = true;
204
+ setImmediate(async () => {
205
+ if (ranByHand) return;
206
+ const result = await runChecks(takeChecks(), createContext(readInput(process.env.DASH_INPUT)));
207
+ const text = process.env.DASH_CHECK_QUIET ? "" : report(result);
208
+ if (text) process.stdout.write(`${text}\n`);
209
+ process.stdout.write(`${lastLine(result)}\n`);
210
+ process.exitCode = result.pass ? 0 : 1;
211
+ });
212
+ }
213
+
214
+ module.exports = { check, describe, run, runChecks, summarize, takeChecks, loadChecks, lastLine, report, readInput };
package/lib/scope.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * scope.js: where a failing `expect` goes.
3
+ *
4
+ * Inside a running check, failures are collected (like a Jest report, every
5
+ * one is listed) and the check goes on. Outside one, a failure throws a
6
+ * CheckFailure straight away.
7
+ */
8
+ "use strict";
9
+
10
+ const { AsyncLocalStorage } = require("async_hooks");
11
+ const { safe } = require("./util");
12
+
13
+ const store = new AsyncLocalStorage();
14
+
15
+ /** Thrown by `expect` outside a running check, and by `collect` on failure. */
16
+ class CheckFailure extends Error {
17
+ constructor(failures) {
18
+ const list = Array.isArray(failures) ? failures : [failures];
19
+ super(list.map(display).join("; ") || "Failed");
20
+ this.name = "CheckFailure";
21
+ this.failures = list;
22
+ }
23
+ }
24
+
25
+ /** How a failure reads: its message, and where when it says. */
26
+ function display(f) {
27
+ if (!f) return "";
28
+ return f.at ? `${f.message}: ${f.at}` : f.message;
29
+ }
30
+
31
+ function makeFailure(message, extra = {}) {
32
+ const f = { message: String(message || "Failed") };
33
+ if (f.message.length > 2000) f.message = `${f.message.slice(0, 1999)}…`;
34
+ if (extra.at) f.at = String(extra.at).slice(0, 1000);
35
+ if ("expected" in extra && extra.expected !== undefined) f.expected = safe(extra.expected);
36
+ if ("received" in extra) f.received = safe(extra.received);
37
+ if (extra.matcher) f.matcher = extra.matcher;
38
+ if (extra.label) f.label = extra.label;
39
+ if (extra.error) f.error = true;
40
+ return f;
41
+ }
42
+
43
+ /** Record a failure in the running check, or throw one outside a check. */
44
+ function record(failure) {
45
+ const s = store.getStore();
46
+ if (!s) throw new CheckFailure([failure]);
47
+ s.failures.push(failure);
48
+ return failure;
49
+ }
50
+
51
+ /**
52
+ * Fail the running check with a message (the fix), going on with the rest.
53
+ * @param {string} message what to fix
54
+ * @param {{ at?: string, expected?: any, received?: any }} [extra]
55
+ */
56
+ function fail(message, extra) {
57
+ record(makeFailure(message, extra));
58
+ return false;
59
+ }
60
+
61
+ /** Say how the running check passed (its reason, when nothing failed). */
62
+ function note(text) {
63
+ const s = store.getStore();
64
+ if (s && text) s.notes.push(String(text));
65
+ }
66
+
67
+ /**
68
+ * Run `fn` with its own failure list. Resolves with { failures, notes,
69
+ * error }; never throws.
70
+ */
71
+ async function collect(fn) {
72
+ const s = { failures: [], notes: [] };
73
+ await store.run(s, async () => {
74
+ try {
75
+ await fn();
76
+ } catch (e) {
77
+ addError(s, e);
78
+ }
79
+ });
80
+ return s;
81
+ }
82
+
83
+ /** An error thrown inside a check, as a failure. */
84
+ function addError(s, e) {
85
+ if (e instanceof CheckFailure) {
86
+ s.failures.push(...e.failures);
87
+ return;
88
+ }
89
+ const msg = e && e.message ? e.message : String(e);
90
+ const named = e && e.name && e.name !== "Error" && e.name !== "DashCheckError" ? `${e.name}: ` : "";
91
+ s.failures.push(makeFailure(`${named}${msg}`, { error: true }));
92
+ }
93
+
94
+ const current = () => store.getStore() || null;
95
+
96
+ module.exports = {
97
+ store,
98
+ CheckFailure,
99
+ makeFailure,
100
+ record,
101
+ fail,
102
+ note,
103
+ collect,
104
+ addError,
105
+ current,
106
+ display,
107
+ };
package/lib/util.js ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * util.js: small pure helpers shared by the core (no I/O).
3
+ */
4
+ "use strict";
5
+
6
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
7
+
8
+ /** An error a check's author can act on. `fix` says what to do about it. */
9
+ class DashCheckError extends Error {
10
+ constructor(message, { fix, code } = {}) {
11
+ super(fix ? `${message}: ${fix}` : message);
12
+ this.name = "DashCheckError";
13
+ if (fix) this.fix = fix;
14
+ if (code !== undefined) this.code = code;
15
+ }
16
+ }
17
+
18
+ /** Empty: undefined, null, "", " ", [], {}. */
19
+ function isEmpty(v) {
20
+ if (v === undefined || v === null) return true;
21
+ if (typeof v === "string") return !v.trim();
22
+ if (Array.isArray(v)) return v.length === 0;
23
+ if (v instanceof Map || v instanceof Set) return v.size === 0;
24
+ if (isObj(v)) return Object.keys(v).length === 0;
25
+ return false;
26
+ }
27
+
28
+ function deepEqual(a, b) {
29
+ if (Object.is(a, b)) return true;
30
+ if (typeof a !== typeof b || a === null || b === null) return false;
31
+ if (typeof a !== "object") return false;
32
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
33
+ if (a instanceof RegExp || b instanceof RegExp) return String(a) === String(b);
34
+ if (a instanceof Date || b instanceof Date) {
35
+ return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
36
+ }
37
+ const ka = Object.keys(a).filter((k) => a[k] !== undefined);
38
+ const kb = Object.keys(b).filter((k) => b[k] !== undefined);
39
+ if (ka.length !== kb.length) return false;
40
+ return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
41
+ }
42
+
43
+ /** A value as short text for a failure message. */
44
+ function fmt(v, max = 200) {
45
+ let s;
46
+ if (v === undefined) return "missing";
47
+ if (typeof v === "string") s = JSON.stringify(v);
48
+ else if (v instanceof RegExp) s = String(v);
49
+ else if (typeof v === "function") s = `[function ${v.name || "anonymous"}]`;
50
+ else if (v instanceof Error) s = `${v.name}: ${v.message}`;
51
+ else {
52
+ try {
53
+ s = JSON.stringify(v);
54
+ } catch (_e) {
55
+ s = String(v);
56
+ }
57
+ if (s === undefined) s = String(v);
58
+ }
59
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
60
+ }
61
+
62
+ /** A JSON-safe, size-capped copy of a value (for a result's failures). */
63
+ function safe(v, depth = 0) {
64
+ if (v === undefined) return undefined;
65
+ if (v === null || typeof v === "number" || typeof v === "boolean") return v;
66
+ if (typeof v === "string") return v.length > 500 ? `${v.slice(0, 499)}…` : v;
67
+ if (typeof v === "bigint") return String(v);
68
+ if (v instanceof RegExp) return String(v);
69
+ if (v instanceof Error) return `${v.name}: ${v.message}`;
70
+ if (typeof v === "function") return `[function ${v.name || "anonymous"}]`;
71
+ if (depth >= 4) return Array.isArray(v) ? `[${v.length} items]` : "{…}";
72
+ if (Array.isArray(v)) {
73
+ const out = v.slice(0, 20).map((x) => safe(x, depth + 1));
74
+ if (v.length > 20) out.push(`… and ${v.length - 20} more`);
75
+ return out;
76
+ }
77
+ if (typeof v === "object") {
78
+ const out = {};
79
+ const keys = Object.keys(v);
80
+ for (const k of keys.slice(0, 30)) out[k] = safe(v[k], depth + 1);
81
+ if (keys.length > 30) out["…"] = `${keys.length - 30} more keys`;
82
+ return out;
83
+ }
84
+ return String(v);
85
+ }
86
+
87
+ /** Split "a.b.0.c" into ["a", "b", "0", "c"]. */
88
+ const splitPath = (p) => String(p).split(".").filter((s) => s !== "");
89
+
90
+ /** The value at a dotted path, or undefined. */
91
+ function getPath(obj, p) {
92
+ let cur = obj;
93
+ for (const k of Array.isArray(p) ? p : splitPath(p)) {
94
+ if (cur === null || cur === undefined) return undefined;
95
+ cur = cur[k];
96
+ }
97
+ return cur;
98
+ }
99
+
100
+ const plural = (n, word, many = `${word}s`) => `${n} ${n === 1 ? word : many}`;
101
+
102
+ /** The last `n` characters of some output, on a line boundary when it can. */
103
+ function tail(text, n = 1500) {
104
+ const s = String(text || "").trimEnd();
105
+ if (s.length <= n) return s;
106
+ const cut = s.slice(-n);
107
+ const nl = cut.indexOf("\n");
108
+ return `…${nl >= 0 && nl < 200 ? cut.slice(nl) : cut}`;
109
+ }
110
+
111
+ module.exports = {
112
+ isObj,
113
+ isEmpty,
114
+ deepEqual,
115
+ fmt,
116
+ safe,
117
+ splitPath,
118
+ getPath,
119
+ plural,
120
+ tail,
121
+ DashCheckError,
122
+ };
package/lib/values.js ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * values.js: reading a value by path, and filling "{placeholders}".
3
+ *
4
+ * A path starts at one of the context's data roots:
5
+ * input, answer, handoff, item, workspace, picks, row, settings, step, job, env
6
+ * Any other first word is looked up in the picked table rows, then in the
7
+ * team settings, so "{repo.baseBranch}" is row.repo.baseBranch and
8
+ * "{workRoot}" is settings.workRoot.
9
+ */
10
+ "use strict";
11
+
12
+ const { getPath, splitPath, isObj, isEmpty, DashCheckError } = require("./util");
13
+
14
+ const ROOTS = ["input", "answer", "handoff", "item", "workspace", "picks", "row", "settings", "step", "job", "env"];
15
+ const TOKEN = /\{\{|\}\}|\{([A-Za-z_$][\w$-]*(?:\.[\w$-]+)*)\}/g;
16
+
17
+ /** { found, value } for a path in a context. */
18
+ function lookup(ctx, p) {
19
+ const parts = splitPath(p);
20
+ if (!parts.length) return { found: false };
21
+ const [first, ...rest] = parts;
22
+ if (ROOTS.includes(first)) {
23
+ const v = getPath(ctx[first], rest);
24
+ return { found: v !== undefined, value: v };
25
+ }
26
+ for (const root of ["row", "settings"]) {
27
+ const base = ctx[root];
28
+ if (isObj(base) && base[first] !== undefined) {
29
+ const v = getPath(base, parts);
30
+ return { found: v !== undefined, value: v };
31
+ }
32
+ }
33
+ return { found: false };
34
+ }
35
+
36
+ /** The value at a path ("handoff.files", "repo.baseBranch"), or undefined. */
37
+ function get(ctx, p) {
38
+ return lookup(ctx, p).value;
39
+ }
40
+
41
+ /** Is there a placeholder in this text? */
42
+ const hasPlaceholder = (s) => typeof s === "string" && /\{[A-Za-z_$][\w$-]*(?:\.[\w$-]+)*\}/.test(s);
43
+
44
+ /**
45
+ * Fill "{placeholders}" in a string (deep in arrays and objects).
46
+ * A string that is only one placeholder keeps the value's type.
47
+ * "{{" and "}}" are literal braces.
48
+ * @param {object} ctx
49
+ * @param {any} value
50
+ * @param {{ missing?: "throw" | "empty" | "keep" }} [opts]
51
+ */
52
+ function fill(ctx, value, opts = {}) {
53
+ const missing = opts.missing || "throw";
54
+ if (Array.isArray(value)) return value.map((v) => fill(ctx, v, opts));
55
+ if (isObj(value)) {
56
+ const out = {};
57
+ for (const [k, v] of Object.entries(value)) out[k] = fill(ctx, v, opts);
58
+ return out;
59
+ }
60
+ if (typeof value !== "string") return value;
61
+ const whole = value.match(/^\{([A-Za-z_$][\w$-]*(?:\.[\w$-]+)*)\}$/);
62
+ if (whole) {
63
+ const r = lookup(ctx, whole[1]);
64
+ if (r.found) return r.value;
65
+ return onMissing(whole[1], value, missing);
66
+ }
67
+ return value.replace(TOKEN, (m, p) => {
68
+ if (m === "{{") return "{";
69
+ if (m === "}}") return "}";
70
+ const r = lookup(ctx, p);
71
+ if (r.found) return typeof r.value === "object" ? JSON.stringify(r.value) : String(r.value);
72
+ const out = onMissing(p, m, missing);
73
+ return out === undefined ? "" : out;
74
+ });
75
+ }
76
+
77
+ function onMissing(p, raw, missing) {
78
+ if (missing === "keep") return raw;
79
+ if (missing === "empty") return undefined;
80
+ const first = splitPath(p)[0];
81
+ const where = ROOTS.includes(first)
82
+ ? `the job has no ${p}`
83
+ : `there's no table row or team setting named "${first}"${p.includes(".") ? ` with ${p.slice(first.length + 1)}` : ""}`;
84
+ throw new DashCheckError(`{${p}} has no value here (${where})`, {
85
+ fix: "pick the row or set the setting on the team, or give the value directly",
86
+ });
87
+ }
88
+
89
+ /**
90
+ * Is a `when` true? A path ("handoff.prUrl") or a placeholder
91
+ * ("{mergeWhenGreen}"); "!" in front turns it around. Empty, false,
92
+ * "false", "no", "off" and "0" are false.
93
+ */
94
+ function when(ctx, expr) {
95
+ if (typeof expr === "boolean") return expr;
96
+ if (expr === undefined || expr === null) return true;
97
+ let s = String(expr).trim();
98
+ let not = false;
99
+ while (s.startsWith("!")) {
100
+ not = !not;
101
+ s = s.slice(1).trim();
102
+ }
103
+ const v = hasPlaceholder(s) ? fill(ctx, s, { missing: "empty" }) : get(ctx, s);
104
+ return not ? !truthy(v) : truthy(v);
105
+ }
106
+
107
+ function truthy(v) {
108
+ if (typeof v === "string") return !["", "false", "no", "off", "0"].includes(v.trim().toLowerCase());
109
+ if (typeof v === "number") return v !== 0 && !Number.isNaN(v);
110
+ if (typeof v === "boolean") return v;
111
+ return !isEmpty(v);
112
+ }
113
+
114
+ /**
115
+ * Every value path in a sample input's context, for a value picker:
116
+ * [{ path, type, sample }].
117
+ */
118
+ function valuePaths(ctx, { maxDepth = 4, max = 300 } = {}) {
119
+ const out = [];
120
+ const walk = (v, p, d) => {
121
+ if (out.length >= max) return;
122
+ const type = Array.isArray(v) ? "list" : v === null ? "null" : typeof v;
123
+ if (p) out.push({ path: p, type, ...(type === "object" || type === "list" ? {} : { sample: v }) });
124
+ if (d >= maxDepth) return;
125
+ if (isObj(v)) for (const k of Object.keys(v)) walk(v[k], p ? `${p}.${k}` : k, d + 1);
126
+ };
127
+ for (const root of ["handoff", "item", "workspace", "picks", "row", "settings", "step", "job"]) {
128
+ const v = ctx[root];
129
+ if (isObj(v)) {
130
+ const plain = {};
131
+ for (const [k, x] of Object.entries(v)) if (typeof x !== "function") plain[k] = x;
132
+ walk(plain, root, 0);
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+
138
+ module.exports = { ROOTS, lookup, get, fill, when, truthy, hasPlaceholder, valuePaths };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@trops/dash-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Compose deterministic checks from small, described building blocks: Jest-style files, JSON recipes and helpers. Runs in Dash, in CI and on a laptop.",
5
+ "license": "MIT",
6
+ "author": "trops",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/trops/dash-check.git"
10
+ },
11
+ "homepage": "https://github.com/trops/dash-check#readme",
12
+ "bugs": "https://github.com/trops/dash-check/issues",
13
+ "keywords": ["dash", "checks", "ci", "testing", "bots", "deterministic"],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "type": "commonjs",
18
+ "main": "./index.js",
19
+ "types": "./index.d.ts",
20
+ "bin": {
21
+ "dash-check": "cli/bin.js"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./index.d.ts",
26
+ "default": "./index.js"
27
+ },
28
+ "./helpers": {
29
+ "types": "./helpers/index.d.ts",
30
+ "default": "./helpers/index.js"
31
+ },
32
+ "./recipe": {
33
+ "types": "./recipe/index.d.ts",
34
+ "default": "./recipe/index.js"
35
+ },
36
+ "./recipe/schema.json": "./recipe/schema.json",
37
+ "./cli": {
38
+ "types": "./cli/index.d.ts",
39
+ "default": "./cli/index.js"
40
+ },
41
+ "./lib/register.js": "./lib/register.js",
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "index.js",
46
+ "index.d.ts",
47
+ "lib/",
48
+ "helpers/",
49
+ "recipe/",
50
+ "cli/",
51
+ "examples/",
52
+ "README.md",
53
+ "LICENSE"
54
+ ],
55
+ "scripts": {
56
+ "test": "node --test test/*.test.js"
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }