1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312 | /**
* Source lints for the silent ClojureScript traps this suite has been bitten
* by, plus the two hygiene rules every repo here publishes under.
*
* The reader (test/helpers/cljs-reader.mjs) is chat's, via social-kit. The lint
* selection is this kit's: only the ones whose defect class can actually reach
* these files, each with an executable non-vacuity probe that feeds it the
* exact shape that motivated it.
*
* 1. THE 8-PAIR CLIFF — the one that matters most here. `#js {}` and the
* `js-obj` MACRO both route their pairs through `(into {})`: eight pairs is
* a PersistentArrayMap and insertion order survives, nine is a
* PersistentHashMap and the emitted literal comes out in HASH order, at
* every optimization level, with no warning. social-kit shipped a dist with
* exactly that. In social-kit it was inert; here it would not be. `wpo` is
* THIRTEEN keys and the transmitted bytes are JSON.stringify in insertion
* order, so a reordered literal is a changed wire format that no signature
* test would notice — canon() sorts, so the signatures would all still
* verify. Anything above eight pairs goes through macros/obj, which emits
* sequential unchecked-set calls and holds order at any width.
*
* 2. A local binding named after a core MACRO shadows it inside its own body,
* with no warning at any optimization level.
*
* 3. An interop call with a function literal in TARGET position — the
* consequence trace of a paren that closed one form early, which took chat
* v24 and board v12 down. Never valid at any indentation.
*
* 4. No local filesystem path in anything committed, dist/ and the fixtures
* included: the publish gate decompresses every object and aborts on one.
*
* 5. No control bytes in a source or fixture file. This kit rejects control
* characters on the wire, and its own tests have to be able to SAY so
* without carrying a NUL through git, an editor and a diff.
*/
import test from "node:test";
import assert from "node:assert/strict";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { readForms, strip, sym } from "./helpers/cljs-reader.mjs";
const ROOT = new URL("..", import.meta.url).pathname;
const SRC = join(ROOT, "src/ardegazu/wallet");
const MACROS = new Set([
"when", "when-not", "when-let", "when-some", "when-first",
"if", "if-let", "if-some", "if-not", "cond", "condp", "case",
"let", "loop", "recur", "for", "doseq", "dotimes", "do", "and", "or", "while",
"try", "binding", "lazy-seq", "doto", "this-as", "declare", "fn", "defn",
"->", "->>", "some->", "some->>", "as->", "set!", "new", "var",
"time", "assert", "comment",
]);
const walk = (dir, ext) =>
readdirSync(dir).flatMap((n) => {
const p = join(dir, n);
return statSync(p).isDirectory() ? walk(p, ext) : p.endsWith(ext) ? [p] : [];
});
const cljsFiles = () => walk(SRC, ".cljs");
const rel = (f) => f.slice(SRC.length + 1);
test("the lints actually reach this repo's sources", () => {
const found = cljsFiles().map(rel).sort();
assert.deepEqual(found, [
"consts.cljs", "index.cljs", "ledger.cljs", "paylink.cljs",
"selftest.cljs", "shapes.cljs",
], "a new namespace appeared and nothing told the lints about it");
});
// ---- 1. the 8-pair cliff ----------------------------------------------------
const MAX_LITERAL_PAIRS = 8;
function wideLiterals(file, src) {
const hits = [];
for (const nd of readForms(src)) {
let pairs = null;
let what = null;
if (sym(nd) === "js-obj") {
pairs = (nd.children.length - 1) / 2;
what = "(js-obj …)";
} else if (nd.type === "map" && src.slice(nd.start, nd.start + 3) === "#js") {
pairs = nd.children.length / 2;
what = "#js {…}";
}
if (pairs !== null && pairs > MAX_LITERAL_PAIRS) {
hits.push(`${file}:${nd.line} ${what} with ${pairs} pairs — key order is HASH order here`);
}
}
return hits;
}
test("no #js {} or js-obj literal wider than eight pairs — use macros/obj", () => {
const hits = cljsFiles().flatMap((f) => wideLiterals(rel(f), readFileSync(f, "utf8")));
assert.deepEqual(hits, [], `key order silently becomes hash order:\n${hits.join("\n")}`);
});
test("the 8-pair lint would have caught the shape this kit is full of", () => {
// wpo's twelve unsigned pairs, written the wrong way
const twelve =
'(js-obj "v" 1 "t" "wpo" "id" i "cur" c "amt" a "seq" s ' +
'"from" f "to" t "ctx" x "memo" m "ts" ts "exp" e)';
assert.equal(wideLiterals("sample", twelve).length, 1);
const eight = '(js-obj "a" 1 "b" 2 "c" 3 "d" 4 "e" 5 "f" 6 "g" 7 "h" 8)';
assert.equal(wideLiterals("sample", eight).length, 0, "eight is the last safe width");
const nine = '(js-obj "a" 1 "b" 2 "c" 3 "d" 4 "e" 5 "f" 6 "g" 7 "h" 8 "i" 9)';
assert.equal(wideLiterals("sample", nine).length, 1, "nine is not");
assert.equal(wideLiterals("sample", "#js {:a 1 :b 2 :c 3 :d 4 :e 5 :f 6 :g 7 :h 8 :i 9}").length, 1);
});
test("every artifact builder goes through the ordered macro", () => {
const shapes = readFileSync(join(SRC, "shapes.cljs"), "utf8");
// the four unsigned-* builders and the two settlement literals are the wire
for (const name of ["unsigned-pay-request", "unsigned-order", "unsigned-settlement"]) {
const at = shapes.indexOf(`(defn ${name}`);
assert.ok(at > 0, `${name} must exist`);
const body = strip(shapes.slice(at, shapes.indexOf("\n\n(", at + 1)));
assert.ok(/\(obj\s/.test(body), `${name} must build with the obj macro`);
assert.ok(!/#js\s*\{|\(js-obj\s/.test(body), `${name} must not use a hash-ordered literal`);
}
});
// ---- 2. macro shadowing -----------------------------------------------------
const TOKEN = /[^\s()[\]{}]+/g;
const BINDING_FORMS = ["let", "loop", "doseq", "dotimes", "if-let", "when-let",
"if-some", "when-some", "js-await", "awaits"];
/**
* Binding NAMES out of a binding form, read from the parse tree.
*
* social-kit's copy of this lint tokenises the bracket text and calls every
* even token a name, which is only true when no binding VALUE contains a nested
* form. `(let [raw (js/JSON.parse (or (getItem k) "{}"))] …)` breaks the
* alignment and the lint starts reporting `or` as a shadowed binding — a false
* positive that would train a reader to ignore it. Reading children of the
* binding vector costs nothing and cannot drift.
*/
function bindingNames(src, kind) {
const out = [];
for (const nd of readForms(src)) {
if (sym(nd) !== kind) continue;
const vec = nd.children[1];
if (!vec || vec.type !== "vector") continue;
for (let k = 0; k < vec.children.length; k += 2) {
const b = vec.children[k];
if (b?.type === "symbol") out.push({ nm: b.text, line: b.line });
}
}
return out;
}
test("no let/loop/awaits binding is named after a core macro", () => {
const hits = [];
for (const file of cljsFiles()) {
const src = readFileSync(file, "utf8");
for (const kind of BINDING_FORMS) {
for (const { nm, line } of bindingNames(src, kind)) {
if (MACROS.has(nm)) hits.push(`${rel(file)}:${line} ${kind} binding \`${nm}\``);
}
}
}
assert.deepEqual(hits, [], `a binding shadows a macro:\n${hits.join("\n")}`);
});
test("the binding lint reaches this repo's own `awaits` macro, and only real names", () => {
// the regression this guards is a lint that quietly stopped looking
const sample = "(defn- f [] (awaits [when (g)] (when true 1)))";
const seen = (kind) => bindingNames(sample, kind).map((b) => b.nm);
assert.deepEqual(seen("awaits"), ["when"], "the awaits pattern must see the binding");
assert.deepEqual(seen("let"), [], "the bare `let` pattern must NOT match `(awaits `");
assert.ok(BINDING_FORMS.includes("awaits"));
// and the false positive that motivated reading the tree instead of the text
const nested = '(let [raw (js/JSON.parse (or (getItem k) "{}"))] raw)';
assert.deepEqual(seen2(nested), ["raw"]);
function seen2(s) { return bindingNames(s, "let").map((b) => b.nm); }
});
/** Parameter names of every defn/fn in a file, read from the parse tree. */
function paramNames(src) {
const out = [];
for (const nd of readForms(src)) {
const h = sym(nd);
if (h !== "defn" && h !== "defn-" && h !== "fn") continue;
const vec = nd.children.find((c) => c.type === "vector");
if (!vec) continue;
for (const b of vec.children) if (b.type === "symbol") out.push({ nm: b.text, line: b.line });
}
return out;
}
test("no defn/fn parameter is named after a core macro", () => {
const hits = [];
for (const file of cljsFiles()) {
for (const { nm, line } of paramNames(readFileSync(file, "utf8"))) {
if (MACROS.has(nm)) hits.push(`${rel(file)}:${line} param \`${nm}\``);
}
}
assert.deepEqual(hits, [], `a parameter shadows a macro:\n${hits.join("\n")}`);
});
test("the parameter lint would have caught what it did catch", () => {
// social-kit's selftest writes `(defn- check [cond what] …)`, which shadows
// `cond` for that whole body. This kit's copy was written the same way and
// this lint is why it is not any more.
assert.deepEqual(paramNames("(defn- check [cond what] (cond a b))").map((p) => p.nm), ["cond", "what"]);
});
// ---- 3. interop on a function literal ---------------------------------------
const THREADS = { "->": 1, "->>": 1, "some->": 1, "some->>": 1, "cond->": 1,
"cond->>": 1, "doto": 1, "as->": 3, "..": 2 };
const FN_LITERAL = new Set(["fn", "fn*", "defn", "defn-"]);
function interopOnFn(file, src) {
const hits = [];
const lines = src.split("\n");
for (const nd of readForms(src)) {
const h = sym(nd);
if (!h || !h.startsWith(".") || h === "." || h === "..") continue;
const outer = nd.parent ? sym(nd.parent) : null;
const from = outer !== null && outer in THREADS ? THREADS[outer] : null;
if (from !== null && nd.parent.children.indexOf(nd) >= from) continue; // threaded in
const target = nd.children?.[1];
if (!target) continue;
if (target.type === "fn-literal" || FN_LITERAL.has(sym(target))) {
hits.push(`${file}:${nd.line} \`${h}\` on a function literal — ${(lines[nd.line - 1] ?? "").trim().slice(0, 72)}`);
}
}
return hits;
}
test("no interop call has a function literal in target position", () => {
const hits = cljsFiles().flatMap((f) => interopOnFn(rel(f), readFileSync(f, "utf8")));
assert.deepEqual(hits, [], `a method is called on a function, which throws:\n${hits.join("\n")}`);
});
test("the interop lint would have caught the bug that motivated it", () => {
const broken = [
"(-> ((fn page [n]",
" (if (>= n 200) nil (page (inc n)))",
" 0)",
" (.then (fn [_] nil))))",
].join("\n");
assert.equal(interopOnFn("sample", broken).length, 1);
const fixed = [
"(-> ((fn page [n]",
" (if (>= n 200) nil (page (inc n))))",
" 0)",
" (.then (fn [_] nil)))",
].join("\n");
assert.equal(interopOnFn("sample", fixed).length, 0);
});
// ---- 4/5. publish hygiene ---------------------------------------------------
const COMMITTED = () =>
[
...walk(join(ROOT, "src"), ".cljs"),
...walk(join(ROOT, "src"), ".clj"),
...walk(join(ROOT, "dist"), ".js"),
...walk(join(ROOT, "test"), ".mjs"),
...walk(join(ROOT, "test"), ".json"),
...walk(join(ROOT, "types"), ".d.ts"),
join(ROOT, "package.json"),
join(ROOT, "deps.edn"),
join(ROOT, "shadow-cljs.edn"),
join(ROOT, "README.md"),
join(ROOT, "deploy/check-dist.sh"),
...walk(join(ROOT, "scripts"), ".mjs"),
];
test("no local filesystem path in anything committed", () => {
// built from pieces: the bytes of this test must not themselves be the
// pattern the publish gate hunts for
const LEAK = ["/Use" + "rs/", "/ho" + "me/", "C:\\\\Users"];
const hits = [];
for (const f of COMMITTED()) {
const src = readFileSync(f, "utf8");
for (const pat of LEAK) if (src.includes(pat)) hits.push(`${f.slice(ROOT.length)} contains ${pat}`);
}
assert.deepEqual(hits, [], `a leaked path aborts the publish gate:\n${hits.join("\n")}`);
});
test("no control bytes in any committed source or fixture", () => {
const hits = [];
for (const f of COMMITTED()) {
const buf = readFileSync(f);
for (const b of buf) {
if (b < 9 || (b > 13 && b < 32) || b === 127) {
hits.push(`${f.slice(ROOT.length)} contains byte 0x${b.toString(16)}`);
break;
}
}
}
assert.deepEqual(hits, [], `control bytes in committed text:\n${hits.join("\n")}`);
});
test("no libp2p anywhere in this kit", () => {
// the artifact layer opens no sockets; the day it imports one, the whole
// "two peerDependencies" story stops being true
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
const deps = Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies, ...pkg.devDependencies });
assert.deepEqual(deps.filter((d) => /libp2p|multiformats|orbit/.test(d)), []);
assert.deepEqual(Object.keys(pkg.peerDependencies).sort(), ["ardegazu-id-kit", "ardegazu-social-kit"]);
for (const f of [...walk(SRC, ".cljs"), ...walk(join(ROOT, "dist"), ".js")]) {
assert.ok(!/libp2p/.test(readFileSync(f, "utf8")), `${f.slice(ROOT.length)} mentions libp2p`);
}
});
|