@trops/dash-check 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +309 -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 +10 -0
  8. package/examples/changes-match-plan.sample.json +4 -0
  9. package/examples/every-acceptance-has-a-test.bad.json +3 -0
  10. package/examples/every-acceptance-has-a-test.check.js +19 -0
  11. package/examples/every-acceptance-has-a-test.sample.json +3 -0
  12. package/examples/helpers/changelog.js +23 -0
  13. package/examples/jira-comment-from-job.bad.json +5 -0
  14. package/examples/jira-comment-from-job.check.js +10 -0
  15. package/examples/jira-comment-from-job.sample.json +5 -0
  16. package/examples/merge-outcome.bad.json +4 -0
  17. package/examples/merge-outcome.check.js +9 -0
  18. package/examples/merge-outcome.sample.json +4 -0
  19. package/examples/on-branch.bad.json +6 -0
  20. package/examples/on-branch.check.js +12 -0
  21. package/examples/on-branch.sample.json +6 -0
  22. package/examples/plan-complete.bad.json +5 -0
  23. package/examples/plan-complete.check.js +14 -0
  24. package/examples/plan-complete.sample.json +5 -0
  25. package/examples/pr-ci.bad.json +4 -0
  26. package/examples/pr-ci.check.js +12 -0
  27. package/examples/pr-ci.sample.json +4 -0
  28. package/examples/ready-for-review.bad.json +6 -0
  29. package/examples/ready-for-review.check.json +12 -0
  30. package/examples/ready-for-review.sample.json +6 -0
  31. package/examples/setup.bad.json +6 -0
  32. package/examples/setup.check.js +8 -0
  33. package/examples/setup.sample.json +6 -0
  34. package/examples/ticket-has-acceptance.bad.json +4 -0
  35. package/examples/ticket-has-acceptance.check.js +10 -0
  36. package/examples/ticket-has-acceptance.sample.json +4 -0
  37. package/examples/validate.bad.json +6 -0
  38. package/examples/validate.check.js +14 -0
  39. package/examples/validate.sample.json +6 -0
  40. package/examples/work-committed.bad.json +13 -0
  41. package/examples/work-committed.check.js +13 -0
  42. package/examples/work-committed.sample.json +5 -0
  43. package/examples/workspace-cleaned.bad.json +4 -0
  44. package/examples/workspace-cleaned.check.js +7 -0
  45. package/examples/workspace-cleaned.sample.json +4 -0
  46. package/helpers/commands.js +62 -0
  47. package/helpers/files.js +74 -0
  48. package/helpers/git.js +116 -0
  49. package/helpers/github.js +77 -0
  50. package/helpers/handoff.js +80 -0
  51. package/helpers/index.d.ts +15 -0
  52. package/helpers/index.js +36 -0
  53. package/helpers/node.js +106 -0
  54. package/helpers/plan.js +55 -0
  55. package/helpers/tracker.js +60 -0
  56. package/index.d.ts +325 -0
  57. package/index.js +86 -0
  58. package/lib/adapters/fs.js +85 -0
  59. package/lib/adapters/git.js +87 -0
  60. package/lib/adapters/github.js +151 -0
  61. package/lib/adapters/run.js +76 -0
  62. package/lib/adapters/tool.js +64 -0
  63. package/lib/context.js +102 -0
  64. package/lib/discover.js +102 -0
  65. package/lib/expect.js +238 -0
  66. package/lib/glob.js +89 -0
  67. package/lib/handoff.js +68 -0
  68. package/lib/helper.js +219 -0
  69. package/lib/register.js +35 -0
  70. package/lib/runner.js +214 -0
  71. package/lib/scope.js +107 -0
  72. package/lib/util.js +122 -0
  73. package/lib/values.js +138 -0
  74. package/package.json +59 -4
  75. package/recipe/index.d.ts +70 -0
  76. package/recipe/index.js +381 -0
  77. package/recipe/schema.json +55 -0
@@ -0,0 +1,102 @@
1
+ /**
2
+ * discover.js: finding a team's own helpers.
3
+ *
4
+ * - every .js file in the repo's .dash/checks/helpers/;
5
+ * - every installed package (dependencies and devDependencies) whose
6
+ * package.json says "dashCheck": { "helpers": ["./a.js", …] }.
7
+ *
8
+ * A file exports one helper, a list of them, or an object of them. A file
9
+ * that won't load is reported with its error; the others still load.
10
+ */
11
+ "use strict";
12
+
13
+ const fs = require("fs");
14
+ const path = require("path");
15
+ const { register, unregister } = require("./helper");
16
+
17
+ const HELPERS_DIR = ".dash/checks/helpers";
18
+
19
+ function helpersIn(exported) {
20
+ if (!exported) return [];
21
+ if (exported.isDashCheckHelper) return [exported];
22
+ if (Array.isArray(exported)) return exported.filter((h) => h && h.isDashCheckHelper);
23
+ if (typeof exported === "object") return Object.values(exported).filter((h) => h && h.isDashCheckHelper);
24
+ return [];
25
+ }
26
+
27
+ function loadFile(file, source, out, loaded) {
28
+ const shown = source;
29
+ try {
30
+ const full = path.resolve(file);
31
+ // A helper file asks for the same copy of dash-check as this one, so
32
+ // its defineHelper and expect are ours.
33
+ require("./register");
34
+ const prev = loaded.get(full);
35
+ if (prev) prev.forEach((id) => unregister(id));
36
+ delete require.cache[full];
37
+ const list = helpersIn(require(full));
38
+ if (!list.length) throw new Error("it exports no helper: module.exports = defineHelper({ … })");
39
+ register(list, { source: shown, replace: !!prev });
40
+ loaded.set(full, list.map((h) => h.meta.id));
41
+ for (const h of list) out.helpers.push({ id: h.meta.id, source: shown });
42
+ } catch (e) {
43
+ out.errors.push({ source: shown, error: e && e.message ? e.message.split("\n")[0] : String(e) });
44
+ }
45
+ }
46
+
47
+ const LOADED = new Map();
48
+
49
+ /**
50
+ * Load a repo's helpers into the registry.
51
+ * @param {{ cwd?: string }} [opts]
52
+ * @returns {{ helpers: Array<{ id, source }>, errors: Array<{ source, error }> }}
53
+ */
54
+ function loadHelpers({ cwd = process.cwd() } = {}) {
55
+ const out = { helpers: [], errors: [] };
56
+ const dir = path.join(cwd, HELPERS_DIR);
57
+ let files = [];
58
+ try {
59
+ files = fs.readdirSync(dir).filter((f) => /\.c?js$/.test(f)).sort();
60
+ } catch (_e) {
61
+ files = [];
62
+ }
63
+ for (const f of files) loadFile(path.join(dir, f), `${HELPERS_DIR}/${f}`, out, LOADED);
64
+
65
+ let pkg = null;
66
+ try {
67
+ pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
68
+ } catch (_e) {
69
+ pkg = null;
70
+ }
71
+ const deps = pkg ? Object.keys({ ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }).sort() : [];
72
+ const self = pkg && pkg.dashCheck ? [[".", pkg]] : [];
73
+ const found = [...self];
74
+ for (const name of deps) {
75
+ const at = path.join(cwd, "node_modules", name);
76
+ try {
77
+ const dp = JSON.parse(fs.readFileSync(path.join(at, "package.json"), "utf8"));
78
+ if (dp.dashCheck) found.push([name, dp]);
79
+ } catch (_e) {
80
+ // Not installed, or no package.json: nothing to load.
81
+ }
82
+ }
83
+ for (const [name, dp] of found) {
84
+ const root = name === "." ? cwd : path.join(cwd, "node_modules", name);
85
+ const list = dp.dashCheck && Array.isArray(dp.dashCheck.helpers) ? dp.dashCheck.helpers : null;
86
+ if (!list) {
87
+ out.errors.push({ source: `${name}/package.json`, error: 'its "dashCheck" needs "helpers": ["./file.js", …]' });
88
+ continue;
89
+ }
90
+ for (const rel of list) {
91
+ const full = path.resolve(root, String(rel));
92
+ if (path.relative(root, full).startsWith("..")) {
93
+ out.errors.push({ source: `${name}: ${rel}`, error: "a helper must be inside its package" });
94
+ continue;
95
+ }
96
+ loadFile(full, name === "." ? String(rel) : `${name}/${String(rel).replace(/^\.\//, "")}`, out, LOADED);
97
+ }
98
+ }
99
+ return out;
100
+ }
101
+
102
+ module.exports = { loadHelpers, HELPERS_DIR };
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 };