@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/expect.js ADDED
@@ -0,0 +1,238 @@
1
+ /**
2
+ * expect.js: `expect(value, label?)` and its matchers.
3
+ *
4
+ * Every matcher is registered with its metadata, so a UI can list it and
5
+ * read a step back as a sentence:
6
+ *
7
+ * { id, label, sentence, notSentence, params: [{ name, type, label }] }
8
+ *
9
+ * Every matcher takes an optional last argument, `message`: the fix shown
10
+ * when it fails. A matcher returns whether it passed, so code can guard:
11
+ *
12
+ * if (expect(h.tests, "handoff.tests").toBeArray()) for (const t of h.tests) …
13
+ */
14
+ "use strict";
15
+
16
+ const { isObj, isEmpty, deepEqual, fmt, getPath } = require("./util");
17
+ const { record, makeFailure } = require("./scope");
18
+
19
+ const MATCHERS = new Map();
20
+
21
+ const sizeOf = (v) => {
22
+ if (typeof v === "string" || Array.isArray(v)) return v.length;
23
+ if (v instanceof Map || v instanceof Set) return v.size;
24
+ if (isObj(v)) return Object.keys(v).length;
25
+ return undefined;
26
+ };
27
+ const sizeText = (v) => {
28
+ const n = sizeOf(v);
29
+ if (n === undefined) return "";
30
+ return typeof v === "string" ? ` (${n} characters)` : ` (${n} item${n === 1 ? "" : "s"})`;
31
+ };
32
+ const isNum = (v) => typeof v === "number" && !Number.isNaN(v);
33
+ const toRegex = (p) => (p instanceof RegExp ? p : new RegExp(String(p)));
34
+
35
+ /**
36
+ * Register a matcher.
37
+ * @param {{ id: string, label: string, sentence: string, notSentence?: string,
38
+ * params?: Array<{ name: string, type: string, label?: string }>,
39
+ * test: (received: any, ...args: any[]) => boolean | { pass: boolean, got?: string },
40
+ * description?: string }} def
41
+ */
42
+ function defineMatcher(def) {
43
+ if (!def || typeof def.id !== "string" || !/^[a-zA-Z][a-zA-Z0-9]*$/.test(def.id)) {
44
+ throw new TypeError("A matcher needs an id made of letters and digits, e.g. toBeEven");
45
+ }
46
+ if (typeof def.test !== "function") throw new TypeError(`Matcher ${def.id} needs a test function`);
47
+ if (typeof def.sentence !== "string") throw new TypeError(`Matcher ${def.id} needs a sentence, e.g. "{value} is even"`);
48
+ const meta = {
49
+ id: def.id,
50
+ label: def.label || def.id,
51
+ sentence: def.sentence,
52
+ notSentence: def.notSentence || def.sentence.replace("{value}", "not: {value}"),
53
+ params: (def.params || []).map((p) => ({ name: p.name, type: p.type || "text", label: p.label || p.name })),
54
+ description: def.description || "",
55
+ };
56
+ MATCHERS.set(def.id, { meta, test: def.test });
57
+ return meta;
58
+ }
59
+
60
+ /** Fill a matcher's sentence: "{value} has at least {n} item(s)". */
61
+ function sentenceFor(meta, label, args, not) {
62
+ const tpl = not ? meta.notSentence : meta.sentence;
63
+ return tpl.replace(/\{(\w+)\}/g, (m, k) => {
64
+ if (k === "value") return label;
65
+ const i = meta.params.findIndex((p) => p.name === k);
66
+ if (i < 0) return m;
67
+ const v = args[i];
68
+ return Array.isArray(v) ? v.map((x) => fmt(x)).join(", ") : fmt(v);
69
+ });
70
+ }
71
+
72
+ /** Apply one matcher; records a failure when it doesn't hold. */
73
+ function apply(id, received, label, rawArgs, not) {
74
+ const m = MATCHERS.get(id);
75
+ const n = m.meta.params.length;
76
+ const args = rawArgs.slice(0, n);
77
+ const message = rawArgs.length > n && typeof rawArgs[n] === "string" ? rawArgs[n] : null;
78
+ let out;
79
+ try {
80
+ out = m.test(received, ...args);
81
+ } catch (e) {
82
+ out = { pass: false, got: `it couldn't be checked (${e.message})` };
83
+ not = false; // a matcher that can't run fails both ways
84
+ }
85
+ const ok = typeof out === "object" && out ? !!out.pass : !!out;
86
+ const pass = not ? !ok : ok;
87
+ if (pass) return true;
88
+ const label2 = label || "the value";
89
+ const want = sentenceFor(m.meta, label2, args, not);
90
+ const got = (out && typeof out === "object" && out.got) || `${label2} is ${fmt(received)}${typeof received !== "string" || /Length|Empty/.test(id) ? sizeText(received) : ""}`;
91
+ record(
92
+ makeFailure(message || `Expected ${want}, but ${got}`, {
93
+ matcher: `${not ? "not." : ""}${id}`,
94
+ expected: args.length === 1 ? args[0] : args.length ? args : undefined,
95
+ received,
96
+ label: label || undefined,
97
+ }),
98
+ );
99
+ return false;
100
+ }
101
+
102
+ function matchersFor(get, label, not, mode) {
103
+ const api = {};
104
+ for (const id of MATCHERS.keys()) {
105
+ api[id] = (...args) => {
106
+ if (mode) {
107
+ return Promise.resolve()
108
+ .then(get)
109
+ .then((v) => apply(id, v, label, args, not));
110
+ }
111
+ return apply(id, get(), label, args, not);
112
+ };
113
+ }
114
+ return api;
115
+ }
116
+
117
+ /**
118
+ * expect(value, label?) → matchers, plus .not, .resolves and .rejects.
119
+ * @param {any} value
120
+ * @param {string} [label] how the value is named in a failure ("handoff.files")
121
+ */
122
+ function expect(value, label) {
123
+ const plain = () => value;
124
+ const api = matchersFor(plain, label, false);
125
+ api.not = matchersFor(plain, label, true);
126
+ const settle = (wantReject) => async () => {
127
+ const p = typeof value === "function" ? value() : value;
128
+ try {
129
+ const v = await p;
130
+ if (wantReject) {
131
+ record(makeFailure(`Expected ${label || "the promise"} to reject, but it resolved with ${fmt(v)}`, { received: v }));
132
+ throw SETTLED;
133
+ }
134
+ return v;
135
+ } catch (e) {
136
+ if (e === SETTLED) throw e;
137
+ if (!wantReject) {
138
+ record(makeFailure(`Expected ${label || "the promise"} to resolve, but it rejected: ${e && e.message ? e.message : fmt(e)}`, { received: e }));
139
+ throw SETTLED;
140
+ }
141
+ return e;
142
+ }
143
+ };
144
+ const asyncApi = (wantReject) => {
145
+ const get = settle(wantReject);
146
+ const wrap = (not) => {
147
+ const inner = matchersFor(get, label, not, "async");
148
+ const out = {};
149
+ for (const id of Object.keys(inner)) {
150
+ out[id] = (...args) => inner[id](...args).catch((e) => (e === SETTLED ? false : Promise.reject(e)));
151
+ }
152
+ return out;
153
+ };
154
+ const a = wrap(false);
155
+ a.not = wrap(true);
156
+ return a;
157
+ };
158
+ Object.defineProperty(api, "resolves", { get: () => asyncApi(false) });
159
+ Object.defineProperty(api, "rejects", { get: () => asyncApi(true) });
160
+ return api;
161
+ }
162
+ const SETTLED = Symbol("settled");
163
+
164
+ /** Every matcher's metadata, for a palette. */
165
+ expect.matchers = () => [...MATCHERS.values()].map((m) => ({ ...m.meta, params: m.meta.params.map((p) => ({ ...p })) }));
166
+ expect.extend = (defs) => (Array.isArray(defs) ? defs : [defs]).map(defineMatcher);
167
+ expect.has = (id) => MATCHERS.has(id);
168
+ expect.meta = (id) => (MATCHERS.has(id) ? MATCHERS.get(id).meta : null);
169
+ expect.sentence = (id, label, args = [], not = false) => {
170
+ const m = MATCHERS.get(id);
171
+ return m ? sentenceFor(m.meta, label, args, not) : null;
172
+ };
173
+
174
+ // ---- the built-in matchers ------------------------------------------------
175
+
176
+ const B = [
177
+ // equality and type
178
+ { id: "toBe", label: "is", sentence: "{value} is {expected}", notSentence: "{value} is not {expected}",
179
+ params: [{ name: "expected", type: "any", label: "Value" }], test: (r, e) => Object.is(r, e) },
180
+ { id: "toEqual", label: "equals", sentence: "{value} equals {expected}", notSentence: "{value} does not equal {expected}",
181
+ params: [{ name: "expected", type: "any", label: "Value" }], test: (r, e) => deepEqual(r, e) },
182
+ { id: "toBeDefined", label: "is set", sentence: "{value} is set", notSentence: "{value} is not set",
183
+ test: (r) => r !== undefined },
184
+ { id: "toBeTruthy", label: "is true / set", sentence: "{value} is truthy", notSentence: "{value} is falsy",
185
+ test: (r) => !!r },
186
+ { id: "toBeArray", label: "is a list", sentence: "{value} is a list", notSentence: "{value} is not a list",
187
+ test: (r) => Array.isArray(r) },
188
+ { id: "toBeString", label: "is text", sentence: "{value} is text", notSentence: "{value} is not text",
189
+ test: (r) => typeof r === "string" },
190
+ { id: "toBeNonEmptyString", label: "is non-empty text", sentence: "{value} is non-empty text",
191
+ notSentence: "{value} is not non-empty text", test: (r) => typeof r === "string" && r.trim() !== "" },
192
+ { id: "toBeNumber", label: "is a number", sentence: "{value} is a number", notSentence: "{value} is not a number",
193
+ test: (r) => isNum(r) },
194
+ // size
195
+ { id: "toBeEmpty", label: "is empty", sentence: "{value} is empty", notSentence: "{value} is not empty",
196
+ test: (r) => isEmpty(r) },
197
+ { id: "toHaveLength", label: "has exactly", sentence: "{value} has length {n}", notSentence: "{value} does not have length {n}",
198
+ params: [{ name: "n", type: "number", label: "Length" }], test: (r, n) => sizeOf(r) === n },
199
+ { id: "toHaveLengthAtLeast", label: "has at least", sentence: "{value} has at least {n} item(s)",
200
+ notSentence: "{value} has fewer than {n} item(s)",
201
+ params: [{ name: "n", type: "number", label: "At least" }],
202
+ test: (r, n) => sizeOf(r) !== undefined && sizeOf(r) >= n },
203
+ // membership
204
+ { id: "toContain", label: "contains", sentence: "{value} contains {item}", notSentence: "{value} does not contain {item}",
205
+ params: [{ name: "item", type: "any", label: "Item or text" }],
206
+ test: (r, item) => {
207
+ if (typeof r === "string") return r.includes(String(item));
208
+ if (Array.isArray(r)) return r.some((x) => deepEqual(x, item));
209
+ if (r instanceof Set) return r.has(item);
210
+ return { pass: false, got: `it's ${fmt(r)}, neither text nor a list` };
211
+ } },
212
+ { id: "toBeOneOf", label: "is one of", sentence: "{value} is one of {options}", notSentence: "{value} is none of {options}",
213
+ params: [{ name: "options", type: "list", label: "Options" }],
214
+ test: (r, options) => Array.isArray(options) && options.some((o) => deepEqual(o, r)) },
215
+ { id: "toHaveKeys", label: "has keys", sentence: "{value} has {keys}", notSentence: "{value} has none of {keys}",
216
+ params: [{ name: "keys", type: "list", label: "Keys" }],
217
+ test: (r, keys) => {
218
+ const list = Array.isArray(keys) ? keys : [keys];
219
+ if (!r || typeof r !== "object") return { pass: false, got: `it's ${fmt(r)}, not an object` };
220
+ const missing = list.filter((k) => getPath(r, k) === undefined);
221
+ return { pass: missing.length === 0, got: missing.length ? `it has no ${missing.join(", ")}` : "it has all of them" };
222
+ } },
223
+ // text and numbers
224
+ { id: "toMatch", label: "matches", sentence: "{value} matches {pattern}", notSentence: "{value} does not match {pattern}",
225
+ params: [{ name: "pattern", type: "regex", label: "Pattern" }],
226
+ test: (r, p) => {
227
+ const s = r instanceof Error ? r.message : r;
228
+ if (typeof s !== "string") return { pass: false, got: `it's ${fmt(r)}, not text` };
229
+ return toRegex(p).test(s);
230
+ } },
231
+ { id: "toBeGreaterThan", label: "is more than", sentence: "{value} is more than {n}", notSentence: "{value} is at most {n}",
232
+ params: [{ name: "n", type: "number", label: "Number" }], test: (r, n) => isNum(r) && r > n },
233
+ { id: "toBeLessThan", label: "is less than", sentence: "{value} is less than {n}", notSentence: "{value} is at least {n}",
234
+ params: [{ name: "n", type: "number", label: "Number" }], test: (r, n) => isNum(r) && r < n },
235
+ ];
236
+ B.forEach(defineMatcher);
237
+
238
+ module.exports = { expect, defineMatcher };
package/lib/glob.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * glob.js: a small glob matcher (no dependencies).
3
+ *
4
+ * * anything but "/"
5
+ * ** any number of folders ("src/**\/*.js" matches src/a.js and src/a/b.js)
6
+ * ? one character but "/"
7
+ * {a,b} either
8
+ * [abc] one of
9
+ * !glob (in a list) not this
10
+ *
11
+ * Paths are matched with "/" separators, relative, without a leading "./".
12
+ */
13
+ "use strict";
14
+
15
+ const cache = new Map();
16
+
17
+ function globToRegExp(glob) {
18
+ const g = String(glob).replace(/^\.\//, "");
19
+ if (cache.has(g)) return cache.get(g);
20
+ let re = "";
21
+ let depth = 0;
22
+ for (let i = 0; i < g.length; i++) {
23
+ const c = g[i];
24
+ if (c === "*") {
25
+ if (g[i + 1] === "*") {
26
+ const before = i === 0 || g[i - 1] === "/";
27
+ const after = g[i + 2] === "/" || i + 2 === g.length;
28
+ if (before && after) {
29
+ i += 1;
30
+ if (g[i + 1] === "/") {
31
+ i += 1;
32
+ re += "(?:.*/)?";
33
+ } else re += ".*";
34
+ continue;
35
+ }
36
+ }
37
+ re += "[^/]*";
38
+ } else if (c === "?") re += "[^/]";
39
+ else if (c === "{") {
40
+ depth++;
41
+ re += "(?:";
42
+ } else if (c === "}" && depth > 0) {
43
+ depth--;
44
+ re += ")";
45
+ } else if (c === "," && depth > 0) re += "|";
46
+ else if (c === "[") {
47
+ const end = g.indexOf("]", i + 1);
48
+ if (end < 0) re += "\\[";
49
+ else {
50
+ let body = g.slice(i + 1, end).replace(/\\/g, "\\\\");
51
+ if (body[0] === "!") body = `^${body.slice(1)}`;
52
+ re += `[${body}]`;
53
+ i = end;
54
+ }
55
+ } else if ("\\^$.|+()".includes(c)) re += `\\${c}`;
56
+ else re += c;
57
+ }
58
+ const out = new RegExp(`^${re}$`);
59
+ cache.set(g, out);
60
+ return out;
61
+ }
62
+
63
+ const norm = (p) => String(p).replace(/\\/g, "/").replace(/^\.\//, "");
64
+
65
+ /** Does a path match a glob, or a list of globs (with "!glob" to leave out)? */
66
+ function matchGlob(globs, p) {
67
+ const list = (Array.isArray(globs) ? globs : [globs]).map(String).filter(Boolean);
68
+ const file = norm(p);
69
+ let hit = false;
70
+ for (const g of list) {
71
+ if (g.startsWith("!")) {
72
+ if (globToRegExp(g.slice(1)).test(file)) return false;
73
+ } else if (globToRegExp(g).test(file)) hit = true;
74
+ }
75
+ return hit;
76
+ }
77
+
78
+ /** The fixed folder a glob starts in ("src/**\/*.js" → "src"), to walk less. */
79
+ function globBase(glob) {
80
+ const parts = norm(glob).split("/");
81
+ const fixed = [];
82
+ for (const part of parts.slice(0, -1)) {
83
+ if (/[*?{[]/.test(part)) break;
84
+ fixed.push(part);
85
+ }
86
+ return fixed.join("/");
87
+ }
88
+
89
+ module.exports = { globToRegExp, matchGlob, globBase };
package/lib/handoff.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * handoff.js: the bot's handoff, read the way Dash reads it (dash-core
3
+ * electron/bots/answerJson.js): the whole answer when it's JSON, else its
4
+ * last ```json (or bare ```) block. Blocks in other languages are skipped.
5
+ */
6
+ "use strict";
7
+
8
+ const { isObj } = require("./util");
9
+
10
+ /**
11
+ * The JSON an answer ends with.
12
+ * @returns {{ found: boolean, value?: any, fenced?: boolean, broken?: boolean, error?: string }}
13
+ */
14
+ function lastJsonBlock(text) {
15
+ const s = String(text == null ? "" : text).trim();
16
+ if (!s) return { found: false };
17
+ const parse = (t) => {
18
+ try {
19
+ const v = JSON.parse(t);
20
+ return isObj(v) || Array.isArray(v) ? { ok: true, v } : { ok: false, error: "it isn't a JSON object" };
21
+ } catch (e) {
22
+ return { ok: false, error: (e && e.message) || "it isn't JSON" };
23
+ }
24
+ };
25
+ const whole = parse(s);
26
+ if (whole.ok) return { found: true, value: whole.v, fenced: false };
27
+ let last = null;
28
+ for (const m of s.matchAll(/```([A-Za-z0-9_+-]*)([\s\S]*?)```/g)) {
29
+ const lang = m[1].toLowerCase();
30
+ if (lang === "json" || lang === "jsonc" || lang === "") last = m[2];
31
+ }
32
+ if (last === null) return { found: false };
33
+ const inBlock = parse(last.trim());
34
+ if (inBlock.ok) return { found: true, value: inBlock.v, fenced: true };
35
+ return { found: false, broken: true, error: inBlock.error };
36
+ }
37
+
38
+ /** The bot's whole answer in a check input ({ input: { answer } } or { input: "…" }). */
39
+ function answerOf(input) {
40
+ const work = input && input.input;
41
+ if (work && typeof work === "object" && typeof work.answer === "string") return work.answer;
42
+ if (typeof work === "string") return work;
43
+ return "";
44
+ }
45
+
46
+ /**
47
+ * The handoff in a check input: `input.handoff` when Dash parsed it already,
48
+ * else the answer's last json block. `{}` when there's none.
49
+ * @returns {{ handoff: object, info: { found: boolean, broken?: boolean, error?: string, list?: boolean } }}
50
+ */
51
+ function readHandoff(input) {
52
+ if (input && isObj(input.handoff)) {
53
+ const h = { ...input.handoff };
54
+ if (h.status === undefined) h.status = "ok";
55
+ return { handoff: h, info: { found: true, given: true } };
56
+ }
57
+ const j = lastJsonBlock(answerOf(input));
58
+ if (!j.found) {
59
+ return { handoff: {}, info: j.broken ? { found: false, broken: true, error: j.error } : { found: false } };
60
+ }
61
+ if (!isObj(j.value)) return { handoff: {}, info: { found: false, list: true } };
62
+ const h = { ...j.value };
63
+ if (h.status === undefined) h.status = "ok";
64
+ else if (typeof h.status === "string") h.status = h.status.trim().toLowerCase();
65
+ return { handoff: h, info: { found: true } };
66
+ }
67
+
68
+ module.exports = { lastJsonBlock, answerOf, readHandoff };
package/lib/helper.js ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * helper.js: defineHelper, a building block made only from Layer 0 and
3
+ * described well enough for a UI to list it, render its form and read it
4
+ * back as a sentence.
5
+ *
6
+ * defineHelper({ id, group, label, description, sentence, params, reads, run })
7
+ *
8
+ * The result is a function, `await helper(ctx, params)`, with its metadata
9
+ * on `.meta`. Calling it:
10
+ * - fills each param's default, then "{placeholders}" from the context
11
+ * (a default whose placeholder has no value counts as empty);
12
+ * - checks and converts each param to its type;
13
+ * - runs it; anything it throws becomes a failure, so the check goes on;
14
+ * - with `message`, its failures say that instead (where they were stays).
15
+ */
16
+ "use strict";
17
+
18
+ const { isObj, fmt, DashCheckError } = require("./util");
19
+ const { collect, record, CheckFailure, current, note } = require("./scope");
20
+ const values = require("./values");
21
+
22
+ const TYPES = ["text", "number", "boolean", "select", "path", "glob", "regex", "list"];
23
+ const ID_RE = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
24
+ const REGISTRY = new Map();
25
+
26
+ function normParams(id, params) {
27
+ if (params === undefined) return {};
28
+ if (!isObj(params)) throw new TypeError(`${id}: params must be an object of { name: { type, label, default } }`);
29
+ const out = {};
30
+ for (const [name, p] of Object.entries(params)) {
31
+ if (name === "message") throw new TypeError(`${id}: "message" is every helper's own param; don't declare it`);
32
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name)) throw new TypeError(`${id}: "${name}" can't be a param's name`);
33
+ const def = isObj(p) ? p : { type: p };
34
+ const type = def.type || "text";
35
+ if (!TYPES.includes(type)) throw new TypeError(`${id}: param ${name} has type "${type}"; use one of ${TYPES.join(", ")}`);
36
+ if (type === "select" && (!Array.isArray(def.options) || !def.options.length)) {
37
+ throw new TypeError(`${id}: select param ${name} needs options`);
38
+ }
39
+ out[name] = {
40
+ type,
41
+ label: def.label || name,
42
+ ...(def.description ? { description: def.description } : {}),
43
+ ...(def.default !== undefined ? { default: def.default } : {}),
44
+ ...(def.required ? { required: true } : {}),
45
+ ...(def.options ? { options: def.options.slice() } : {}),
46
+ ...(def.placeholder ? { placeholder: def.placeholder } : {}),
47
+ };
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** "a, b" → ["a", "b"], leaving commas in a glob's {a,b} alone. */
53
+ function splitList(s) {
54
+ const out = [];
55
+ let depth = 0;
56
+ let cur = "";
57
+ for (const c of s) {
58
+ if (c === "{") depth++;
59
+ else if (c === "}" && depth > 0) depth--;
60
+ if (c === "," && depth === 0) {
61
+ out.push(cur);
62
+ cur = "";
63
+ } else cur += c;
64
+ }
65
+ out.push(cur);
66
+ return out;
67
+ }
68
+
69
+ /** A param's value, converted to its type, or throws saying what's wrong. */
70
+ function coerce(id, name, p, v) {
71
+ const bad = (what) => new DashCheckError(`${id}: ${p.label} (${name}) ${what}`, { fix: `got ${fmt(v)}` });
72
+ if (v === undefined || v === null || (typeof v === "string" && v.trim() === "")) {
73
+ if (p.required) throw new DashCheckError(`${id}: set ${p.label} (${name})`, { fix: "it has no value" });
74
+ return p.type === "list" ? [] : undefined;
75
+ }
76
+ switch (p.type) {
77
+ case "number": {
78
+ const n = typeof v === "number" ? v : Number(String(v).trim());
79
+ if (!Number.isFinite(n)) throw bad("must be a number");
80
+ return n;
81
+ }
82
+ case "boolean":
83
+ if (typeof v === "boolean") return v;
84
+ if (["true", "yes", "on", "1"].includes(String(v).toLowerCase())) return true;
85
+ if (["false", "no", "off", "0"].includes(String(v).toLowerCase())) return false;
86
+ throw bad("must be true or false");
87
+ case "select":
88
+ if (!p.options.map(String).includes(String(v))) throw bad(`must be one of ${p.options.join(", ")}`);
89
+ return p.options.find((o) => String(o) === String(v));
90
+ case "list": {
91
+ const list = Array.isArray(v) ? v : splitList(String(v));
92
+ return list.map((x) => (typeof x === "string" ? x.trim() : x)).filter((x) => x !== "" && x !== undefined && x !== null);
93
+ }
94
+ case "regex":
95
+ if (v instanceof RegExp) return v;
96
+ try {
97
+ return new RegExp(String(v));
98
+ } catch (e) {
99
+ throw bad(`isn't a valid pattern (${e.message})`);
100
+ }
101
+ default:
102
+ if (typeof v === "object") throw bad("must be text");
103
+ return String(v);
104
+ }
105
+ }
106
+
107
+ /** Fill and convert a call's params (exported for recipes and tests). */
108
+ function resolveParams(meta, ctx, given = {}) {
109
+ const out = {};
110
+ const g = isObj(given) ? given : {};
111
+ for (const k of Object.keys(g)) {
112
+ if (k !== "message" && !meta.params[k]) {
113
+ throw new DashCheckError(`${meta.id} has no param "${k}"`, { fix: `use ${Object.keys(meta.params).join(", ") || "no params"}` });
114
+ }
115
+ }
116
+ for (const [name, p] of Object.entries(meta.params)) {
117
+ let v;
118
+ if (g[name] !== undefined) v = ctx ? values.fill(ctx, g[name]) : g[name];
119
+ else if (p.default !== undefined) v = ctx ? values.fill(ctx, p.default, { missing: "empty" }) : p.default;
120
+ out[name] = coerce(meta.id, name, p, v);
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * Define a helper.
127
+ * @param {{ id: string, group?: string, label: string, description?: string,
128
+ * sentence?: string, params?: object, reads?: string[],
129
+ * run: (ctx: object, params: object) => any }} def
130
+ */
131
+ function defineHelper(def) {
132
+ if (!def || typeof def !== "object") throw new TypeError("defineHelper({ id, label, run }) needs a definition");
133
+ if (typeof def.id !== "string" || !ID_RE.test(def.id)) {
134
+ throw new TypeError(`A helper's id is "group.name" in camelCase, e.g. "team.changelogUpdated" (got ${fmt(def.id)})`);
135
+ }
136
+ if (typeof def.run !== "function") throw new TypeError(`${def.id}: give it run(ctx, params)`);
137
+ if (typeof def.label !== "string" || !def.label.trim()) throw new TypeError(`${def.id}: give it a label, e.g. "Changelog updated"`);
138
+ const meta = Object.freeze({
139
+ id: def.id,
140
+ group: def.group || def.id.split(".")[0],
141
+ label: def.label,
142
+ description: def.description || "",
143
+ sentence: def.sentence || "",
144
+ params: normParams(def.id, def.params),
145
+ reads: Array.isArray(def.reads) ? def.reads.slice() : [],
146
+ });
147
+ const runIt = def.run;
148
+
149
+ async function helper(ctx, given = {}) {
150
+ if (!ctx || typeof ctx !== "object" || !ctx.input) {
151
+ throw new TypeError(`${meta.id}(ctx, params): pass the check's ctx first`);
152
+ }
153
+ const s = await collect(async () => {
154
+ const params = resolveParams(meta, ctx, given);
155
+ await runIt(ctx, params);
156
+ });
157
+ const message = isObj(given) && typeof given.message === "string" && given.message.trim()
158
+ ? values.fill(ctx, given.message, { missing: "keep" })
159
+ : null;
160
+ const failures = s.failures.map((f) => (message ? { ...f, message, original: f.message } : f));
161
+ if (!current()) {
162
+ if (failures.length) throw new CheckFailure(failures);
163
+ return true;
164
+ }
165
+ failures.forEach(record);
166
+ s.notes.forEach(note);
167
+ return failures.length === 0;
168
+ }
169
+ Object.defineProperty(helper, "name", { value: meta.id });
170
+ helper.meta = meta;
171
+ helper.isDashCheckHelper = true;
172
+ return helper;
173
+ }
174
+
175
+ /** Fill a helper's sentence with values: "at least 1 commit(s) past main". */
176
+ function sentenceOf(meta, given = {}) {
177
+ return String(meta.sentence || "").replace(/\{(\w+)\}/g, (m, k) => {
178
+ const p = meta.params[k];
179
+ if (!p) return m;
180
+ const v = isObj(given) && given[k] !== undefined ? given[k] : p.default;
181
+ if (v === undefined || v === "") return `(${p.label})`;
182
+ if (Array.isArray(v)) return v.join(", ");
183
+ if (v instanceof RegExp) return v.source;
184
+ return String(v);
185
+ });
186
+ }
187
+
188
+ /** Add helpers to the registry (built-ins and discovered ones). */
189
+ function register(helpers, { source, replace = false } = {}) {
190
+ const added = [];
191
+ for (const h of [].concat(helpers)) {
192
+ if (!h || !h.isDashCheckHelper) throw new TypeError("register() takes helpers made with defineHelper");
193
+ const had = REGISTRY.get(h.meta.id);
194
+ if (had && had.helper !== h && !replace) {
195
+ throw new Error(`Another helper already has the id ${h.meta.id}${had.source ? ` (${had.source})` : ""}: give this one a different id`);
196
+ }
197
+ REGISTRY.set(h.meta.id, { helper: h, source: source || (had && had.source) || null });
198
+ added.push(h);
199
+ }
200
+ return added;
201
+ }
202
+
203
+ /** A registered helper by id, or null. */
204
+ function getHelper(id) {
205
+ require("../helpers");
206
+ const r = REGISTRY.get(id);
207
+ return r ? r.helper : null;
208
+ }
209
+
210
+ /** Every registered helper's metadata, with where it came from. */
211
+ function listHelpers() {
212
+ require("../helpers");
213
+ return [...REGISTRY.values()].map(({ helper, source }) => ({ ...helper.meta, params: { ...helper.meta.params }, ...(source ? { source } : {}) }));
214
+ }
215
+
216
+ function unregister(id) {
217
+ return REGISTRY.delete(id);
218
+ }
219
+
220
+ /**
221
+ * helper(id) → the helper, to call from code: await helper("team.changelog")(ctx, {…}).
222
+ * Built-ins are always there; a repo's own are found from ctx.cwd on first use.
223
+ */
224
+ function helper(id) {
225
+ return async (ctx, given) => {
226
+ let h = getHelper(id);
227
+ if (!h && ctx && ctx.cwd) {
228
+ require("./discover").loadHelpers({ cwd: ctx.cwd });
229
+ h = getHelper(id);
230
+ }
231
+ if (!h) throw new DashCheckError(`There's no helper ${id}`, { fix: "check its id, or add it to .dash/checks/helpers/" });
232
+ return h(ctx, given);
233
+ };
234
+ }
235
+
236
+ module.exports = { defineHelper, resolveParams, coerce, sentenceOf, register, getHelper, listHelpers, unregister, helper, TYPES };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * register.js: make `require("@trops/dash-check")` (and its subpaths) give
3
+ * this copy, so a check or helper file run by this CLI works even where the
4
+ * package isn't installed (npx), and shares one registry and one runner.
5
+ *
6
+ * node -r @trops/dash-check/lib/register.js my.check.js
7
+ */
8
+ "use strict";
9
+
10
+ const Module = require("module");
11
+ const path = require("path");
12
+
13
+ const ROOT = path.resolve(__dirname, "..");
14
+ const NAME = "@trops/dash-check";
15
+ const MAP = {
16
+ "": "index.js",
17
+ "/helpers": "helpers/index.js",
18
+ "/recipe": "recipe/index.js",
19
+ "/cli": "cli/index.js",
20
+ "/package.json": "package.json",
21
+ };
22
+
23
+ if (!Module.__dashCheckRegistered) {
24
+ Module.__dashCheckRegistered = true;
25
+ const orig = Module._resolveFilename;
26
+ Module._resolveFilename = function resolve(request, ...rest) {
27
+ if (typeof request === "string" && (request === NAME || request.startsWith(`${NAME}/`))) {
28
+ const sub = request.slice(NAME.length);
29
+ if (MAP[sub] !== undefined) return path.join(ROOT, MAP[sub]);
30
+ }
31
+ return orig.call(this, request, ...rest);
32
+ };
33
+ }
34
+
35
+ module.exports = { ROOT };