@nac3/runtime 2.5.2 → 2.8.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.
@@ -0,0 +1,578 @@
1
+ /**
2
+ * dom-harness.mjs -- one DOM harness, with the three things the
3
+ * eighteen hand-rolled ones did not have.
4
+ *
5
+ * WHY THIS EXISTS (TF-D11). Measured 2026-11-24: eighteen test
6
+ * harnesses in this repository stub the DOM, each one written for the
7
+ * suite it lives in, and NONE of them has `activeElement` or
8
+ * `nextSibling`; the ones that implement `insertBefore` do it
9
+ * differently from each other. That is not an aesthetic complaint, it
10
+ * is why three verbs had zero coverage and could not get any:
11
+ *
12
+ * context() reads document.activeElement. With no harness that
13
+ * has one, the verb cannot be called at all.
14
+ * reorder() moves a node among its siblings with insertBefore and
15
+ * reads nextSibling to know where it landed.
16
+ * drag_drop() moves a node between parents and -- the defect of
17
+ * TF-A01 -- removes an element from the host document.
18
+ * Proving it no longer does that needs a document that
19
+ * really holds nodes.
20
+ *
21
+ * So the gap was structural, not an oversight: those verbs were
22
+ * untestable with the harnesses that existed.
23
+ *
24
+ * WHAT THIS IS NOT. It is not a migration. The eighteen existing
25
+ * harnesses are untouched and their suites keep using them -- rewriting
26
+ * working suites is exactly what the working agreement forbids. This is
27
+ * additive: the NEW suites use it, and anything written later can.
28
+ *
29
+ * It is also deliberately NOT jsdom. The battery runs with no browser
30
+ * and no dependency beyond node core, which is a property worth
31
+ * keeping; this stubs the surface js/nac.js actually touches and
32
+ * nothing else.
33
+ *
34
+ * ASCII-only.
35
+ */
36
+
37
+ import vm from 'node:vm';
38
+ import fs from 'node:fs';
39
+ import path from 'node:path';
40
+ import url from 'node:url';
41
+
42
+ const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
43
+ /* The repository root. From runtime/src/ and from runtime/dist/ alike
44
+ it is two levels up, which is why this file can be published by a
45
+ copy with nothing substituted into it. It lived in runtime/test/lib/
46
+ until 2026-11-27 and moved here when the third CLI mode made it a
47
+ PUBLISHED source: runtime/test/lib/dom-harness.mjs is now a
48
+ re-export, so every suite keeps the import it had. */
49
+ const ROOT = path.resolve(__dirname, '..', '..');
50
+
51
+ /* ------------------------------------------------------------------ */
52
+ /* selectors */
53
+ /* ------------------------------------------------------------------ */
54
+
55
+ /* The selector shapes js/nac.js uses: an attribute presence or value,
56
+ a tag, a class, an id, and a comma-separated list of those. A
57
+ selector this does NOT understand throws, rather than quietly
58
+ matching nothing -- a harness that answers "no elements" to a
59
+ selector it failed to parse makes a verb look broken when the test
60
+ is. */
61
+ function parseSimple(sel) {
62
+ const s = sel.trim();
63
+ let m = /^\[([\w-]+)\]$/.exec(s);
64
+ if (m) return (el) => el.getAttribute(m[1]) !== null;
65
+ m = /^\[([\w-]+)=["']?([^"'\]]*)["']?\]$/.exec(s);
66
+ if (m) return (el) => el.getAttribute(m[1]) === m[2];
67
+ m = /^\[([\w-]+)\^=["']?([^"'\]]*)["']?\]$/.exec(s);
68
+ if (m) return (el) => String(el.getAttribute(m[1]) || '').indexOf(m[2]) === 0;
69
+ m = /^#([\w.-]+)$/.exec(s);
70
+ if (m) return (el) => el.getAttribute('id') === m[1];
71
+ m = /^\.([\w-]+)$/.exec(s);
72
+ if (m) return (el) => el.classList.contains(m[1]);
73
+ m = /^([a-zA-Z][\w-]*)$/.exec(s);
74
+ if (m) return (el) => el.tagName === m[1].toUpperCase();
75
+ m = /^\*$/.exec(s);
76
+ if (m) return () => true;
77
+ throw new Error('dom-harness: selector not supported: ' + JSON.stringify(sel)
78
+ + ' -- add it here rather than letting it silently match nothing');
79
+ }
80
+
81
+ /* One compound term: tag plus any number of attribute / class / id
82
+ qualifiers, e.g. button[data-nac-role="tab"].active */
83
+ function parseCompound(sel) {
84
+ const parts = sel.trim().match(/(^[a-zA-Z][\w-]*|\*)|(\[[^\]]*\])|(\.[\w-]+)|(#[\w.-]+)/g);
85
+ if (!parts || parts.length === 0) {
86
+ throw new Error('dom-harness: cannot parse selector ' + JSON.stringify(sel));
87
+ }
88
+ const tests = parts.map(parseSimple);
89
+ return (el) => tests.every((t) => t(el));
90
+ }
91
+
92
+ /* A comma list of compound terms. Descendant combinators are not
93
+ supported and say so. */
94
+ function parseSelector(sel) {
95
+ const groups = String(sel).split(',').map((g) => g.trim()).filter(Boolean);
96
+ if (groups.length === 0) throw new Error('dom-harness: empty selector');
97
+ for (const g of groups) {
98
+ if (/\s/.test(g)) {
99
+ throw new Error('dom-harness: descendant selectors are not supported: '
100
+ + JSON.stringify(g) + ' -- the runtime does not use them on the paths'
101
+ + ' these suites drive; if that changes, implement it here');
102
+ }
103
+ }
104
+ const tests = groups.map(parseCompound);
105
+ return (el) => tests.some((t) => t(el));
106
+ }
107
+
108
+ /* ------------------------------------------------------------------ */
109
+ /* nodes */
110
+ /* ------------------------------------------------------------------ */
111
+
112
+ class HEvent {
113
+ constructor(type, init) {
114
+ this.type = type;
115
+ this.detail = (init || {}).detail;
116
+ this.bubbles = !!(init || {}).bubbles;
117
+ this.isTrusted = false;
118
+ this.defaultPrevented = false;
119
+ this.target = null;
120
+ this.currentTarget = null;
121
+ }
122
+ preventDefault() { this.defaultPrevented = true; }
123
+ stopPropagation() { this._stopped = true; }
124
+ }
125
+
126
+ /* A TEXT node. narrate()'s second precedence tier walks
127
+ el.firstChild / n.nextSibling looking for nodeType === 3, so a
128
+ harness whose nodes are all elements cannot exercise it -- the tier
129
+ silently never matches and the verb looks like it skips to the
130
+ third. Another instance of the structural gap TF-D11 describes: the
131
+ test was impossible, not missing. */
132
+ class HText {
133
+ constructor(doc, text) {
134
+ Object.defineProperty(this, '_doc', { value: doc, enumerable: false, writable: true });
135
+ this.nodeType = 3;
136
+ this.nodeValue = String(text);
137
+ this.parentNode = null;
138
+ this.children = [];
139
+ }
140
+ get textContent() { return this.nodeValue; }
141
+ set textContent(v) { this.nodeValue = String(v); }
142
+ get nextSibling() {
143
+ if (!this.parentNode) return null;
144
+ const sibs = this.parentNode.children;
145
+ const i = sibs.indexOf(this);
146
+ return i >= 0 && i + 1 < sibs.length ? sibs[i + 1] : null;
147
+ }
148
+ getAttribute() { return null; }
149
+ contains(c) { return c === this; }
150
+ }
151
+
152
+ class HNode {
153
+ constructor(doc, tag) {
154
+ /* NON-ENUMERABLE on purpose. A real DOM element has no own
155
+ enumerable properties, so JSON.stringify(element) is '{}'. With
156
+ _doc enumerable, a harness node is a CYCLE -- and code that
157
+ stringifies a state value threw here while it would not have in
158
+ a browser. A harness must not be harder to serialise than the
159
+ thing it stands in for. (It did find a real defect on the way:
160
+ expect() stringified the value in its timeout path with no
161
+ guard. That is fixed in js/nac.js, and this is still the right
162
+ shape for the harness.) */
163
+ Object.defineProperty(this, '_doc', { value: doc, enumerable: false, writable: true });
164
+ this.tagName = String(tag || 'DIV').toUpperCase();
165
+ this._attrs = Object.create(null);
166
+ this._listeners = Object.create(null);
167
+ this.children = [];
168
+ this.parentNode = null;
169
+ this.value = '';
170
+ this.checked = false;
171
+ this.disabled = false;
172
+ this.type = '';
173
+ this.style = {
174
+ _p: Object.create(null),
175
+ setProperty(k, v) { this._p[k] = v; },
176
+ removeProperty(k) { delete this._p[k]; },
177
+ getPropertyValue(k) { return this._p[k] || ''; },
178
+ };
179
+ this.classList = {
180
+ _s: new Set(),
181
+ add(...v) { v.forEach((x) => this._s.add(x)); },
182
+ remove(...v) { v.forEach((x) => this._s.delete(x)); },
183
+ contains(v) { return this._s.has(v); },
184
+ toggle(v) { if (this._s.has(v)) { this._s.delete(v); return false; } this._s.add(v); return true; },
185
+ };
186
+ /* The runtime reads offsetParent to decide whether an element is
187
+ laid out. A detached node has none; an attached one reports its
188
+ parent, which is what a browser does for anything not fixed or
189
+ hidden. */
190
+ this._hidden = false;
191
+ /* nodeType, because the visibility predicate checks it and a node
192
+ without one is not an element as far as the runtime is
193
+ concerned. The first version of this harness omitted it, and
194
+ every element came back visible: false -- which made a correct
195
+ runtime look broken. A harness that is missing a property the
196
+ runtime reads does not produce a smaller test, it produces a
197
+ wrong one. */
198
+ this.nodeType = 1;
199
+ }
200
+
201
+ /* A layout box. 10x10 when laid out, 0x0 when hidden -- the runtime
202
+ reads width and height to tell a position:fixed element (no
203
+ offsetParent, real box) from a collapsed one. */
204
+ getBoundingClientRect() {
205
+ const size = this._hidden ? 0 : 10;
206
+ return { x: 0, y: 0, top: 0, left: 0, right: size, bottom: size, width: size, height: size };
207
+ }
208
+
209
+ /* textContent reads THROUGH the children, and writing it replaces
210
+ them with a single text node -- which is what a browser does, and
211
+ what makes el.firstChild.nodeType === 3 true for a node built with
212
+ { text: 'x' }. Holding it as a plain string instead would make the
213
+ two views of the same content disagree, which is the class of
214
+ harness bug this file has already produced twice. */
215
+ get textContent() {
216
+ let out = '';
217
+ for (const c of this.children) out += (c.nodeType === 3 ? c.nodeValue : c.textContent);
218
+ return out;
219
+ }
220
+ set textContent(v) {
221
+ this.children = [];
222
+ if (String(v).length) this.appendChild(new HText(this._doc, v));
223
+ }
224
+
225
+ get ownerDocument() { return this._doc; }
226
+ get parentElement() { return this.parentNode; }
227
+ get childNodes() { return this.children; }
228
+ get firstChild() { return this.children[0] || null; }
229
+ get lastChild() { return this.children[this.children.length - 1] || null; }
230
+
231
+ /* THE TWO THE OTHER HARNESSES DID NOT HAVE. */
232
+ get nextSibling() {
233
+ if (!this.parentNode) return null;
234
+ const sibs = this.parentNode.children;
235
+ const i = sibs.indexOf(this);
236
+ return i >= 0 && i + 1 < sibs.length ? sibs[i + 1] : null;
237
+ }
238
+ get previousSibling() {
239
+ if (!this.parentNode) return null;
240
+ const sibs = this.parentNode.children;
241
+ const i = sibs.indexOf(this);
242
+ return i > 0 ? sibs[i - 1] : null;
243
+ }
244
+ get nextElementSibling() { return this.nextSibling; }
245
+ get previousElementSibling() { return this.previousSibling; }
246
+
247
+ get offsetParent() {
248
+ if (this._hidden) return null;
249
+ return this.parentNode || null;
250
+ }
251
+
252
+ getAttribute(n) {
253
+ /* class and classList are ONE thing. They were two here at first,
254
+ so a node built with { class: 'x' } did not match '.x' and a
255
+ selector silently found nothing -- which made a runtime fix look
256
+ broken when the harness was. */
257
+ if (n === 'class') return [...this.classList._s].join(' ') || null;
258
+ return n in this._attrs ? this._attrs[n] : null;
259
+ }
260
+ setAttribute(n, v) {
261
+ if (n === 'class') {
262
+ this.classList._s = new Set(String(v).split(/\s+/).filter(Boolean));
263
+ return;
264
+ }
265
+ this._attrs[n] = String(v);
266
+ }
267
+ hasAttribute(n) {
268
+ if (n === 'class') return this.classList._s.size > 0;
269
+ return n in this._attrs;
270
+ }
271
+ removeAttribute(n) {
272
+ if (n === 'class') { this.classList._s = new Set(); return; }
273
+ delete this._attrs[n];
274
+ }
275
+ get attributes() {
276
+ const out = Object.keys(this._attrs).map((name) => ({ name, value: this._attrs[name] }));
277
+ if (this.classList._s.size) out.push({ name: 'class', value: [...this.classList._s].join(' ') });
278
+ return out;
279
+ }
280
+
281
+ appendChild(c) {
282
+ if (c.parentNode) c.parentNode.removeChild(c);
283
+ c.parentNode = this;
284
+ this.children.push(c);
285
+ return c;
286
+ }
287
+ removeChild(c) {
288
+ const i = this.children.indexOf(c);
289
+ if (i < 0) throw new Error('dom-harness: removeChild of a node that is not a child');
290
+ this.children.splice(i, 1);
291
+ c.parentNode = null;
292
+ return c;
293
+ }
294
+ /* ONE implementation, with the null case a browser has: a null
295
+ reference appends. The harnesses that had this at all disagreed
296
+ about exactly that. */
297
+ insertBefore(node, ref) {
298
+ if (node.parentNode) node.parentNode.removeChild(node);
299
+ node.parentNode = this;
300
+ if (ref == null) { this.children.push(node); return node; }
301
+ const i = this.children.indexOf(ref);
302
+ if (i < 0) throw new Error('dom-harness: insertBefore reference is not a child');
303
+ this.children.splice(i, 0, node);
304
+ return node;
305
+ }
306
+ remove() { if (this.parentNode) this.parentNode.removeChild(this); }
307
+
308
+ contains(c) {
309
+ if (c === this) return true;
310
+ return this.children.some((x) => x.contains(c));
311
+ }
312
+ matches(sel) { return parseSelector(sel)(this); }
313
+ closest(sel) {
314
+ const test = parseSelector(sel);
315
+ let n = this;
316
+ while (n) { if (test(n)) return n; n = n.parentNode; }
317
+ return null;
318
+ }
319
+ querySelectorAll(sel) {
320
+ const test = parseSelector(sel);
321
+ const out = [];
322
+ const walk = (n) => {
323
+ for (const c of n.children) {
324
+ if (c.nodeType === 3) continue; /* text is not an element */
325
+ if (test(c)) out.push(c);
326
+ walk(c);
327
+ }
328
+ };
329
+ walk(this);
330
+ return out;
331
+ }
332
+ querySelector(sel) { return this.querySelectorAll(sel)[0] || null; }
333
+
334
+ addEventListener(t, fn) { (this._listeners[t] = this._listeners[t] || []).push(fn); }
335
+ removeEventListener(t, fn) {
336
+ if (!this._listeners[t]) return;
337
+ this._listeners[t] = this._listeners[t].filter((f) => f !== fn);
338
+ }
339
+ dispatchEvent(ev) {
340
+ ev.target = ev.target || this;
341
+ let n = this;
342
+ while (n) {
343
+ ev.currentTarget = n;
344
+ for (const fn of (n._listeners[ev.type] || []).slice()) {
345
+ fn.call(n, ev);
346
+ if (ev._stopped) return !ev.defaultPrevented;
347
+ }
348
+ if (!ev.bubbles) break;
349
+ n = n.parentNode;
350
+ }
351
+ /* A bubbling event reaches the document, which is where the
352
+ protocol's contract events are listened for. */
353
+ if (ev.bubbles && this._doc) this._doc._fire(ev, false);
354
+ return !ev.defaultPrevented;
355
+ }
356
+
357
+ focus() { if (this._doc) this._doc.activeElement = this; }
358
+ blur() { if (this._doc && this._doc.activeElement === this) this._doc.activeElement = this._doc.body; }
359
+ click() {
360
+ const ev = new HEvent('click', { bubbles: true });
361
+ ev.isTrusted = false;
362
+ this.dispatchEvent(ev);
363
+ }
364
+ }
365
+
366
+ class HDocument {
367
+ constructor() {
368
+ this.readyState = 'complete';
369
+ this._listeners = Object.create(null);
370
+ this.documentElement = new HNode(this, 'html');
371
+ this.body = new HNode(this, 'body');
372
+ this.head = new HNode(this, 'head');
373
+ this.documentElement.appendChild(this.head);
374
+ this.documentElement.appendChild(this.body);
375
+ /* THE ONE NO OTHER HARNESS HAD. A browser points it at the body
376
+ when nothing is focused, which is what context() has to be able
377
+ to read without special-casing null. */
378
+ this.activeElement = this.body;
379
+ }
380
+ createElement(tag) { return new HNode(this, tag); }
381
+ createTextNode(text) { return new HText(this, text); }
382
+ querySelectorAll(sel) { return this.documentElement.querySelectorAll(sel); }
383
+ querySelector(sel) { return this.documentElement.querySelector(sel); }
384
+ getElementById(id) { return this.querySelector('[id="' + id + '"]'); }
385
+ addEventListener(t, fn) { (this._listeners[t] = this._listeners[t] || []).push(fn); }
386
+ removeEventListener(t, fn) {
387
+ if (!this._listeners[t]) return;
388
+ this._listeners[t] = this._listeners[t].filter((f) => f !== fn);
389
+ }
390
+ _fire(ev, setTarget) {
391
+ if (setTarget) ev.target = ev.target || this;
392
+ ev.currentTarget = this;
393
+ for (const fn of (this._listeners[ev.type] || []).slice()) fn.call(this, ev);
394
+ return !ev.defaultPrevented;
395
+ }
396
+ dispatchEvent(ev) { return this._fire(ev, true); }
397
+ }
398
+
399
+ /* ------------------------------------------------------------------ */
400
+ /* building a tree, and loading the runtime over it */
401
+ /* ------------------------------------------------------------------ */
402
+
403
+ /* A tiny declarative tree builder, so a suite describes the page it
404
+ needs instead of assembling nodes by hand:
405
+ el('ul', { 'data-nac-id': 'x', 'data-nac-role': 'drop-target' }, [ ... ])
406
+ Returns a factory because each test wants its own fresh tree. */
407
+ export function el(tag, attrs, kids) {
408
+ return (doc) => {
409
+ const n = doc.createElement(tag);
410
+ for (const [k, v] of Object.entries(attrs || {})) {
411
+ if (k === 'text') n.textContent = String(v);
412
+ else if (k === 'value') n.value = String(v);
413
+ else if (k === 'hidden') n._hidden = !!v;
414
+ else if (k === 'type') { n.type = String(v); n.setAttribute('type', String(v)); }
415
+ else n.setAttribute(k, String(v));
416
+ }
417
+ for (const kid of (kids || [])) n.appendChild(kid(doc));
418
+ return n;
419
+ };
420
+ }
421
+
422
+ /* Load the runtime source in a sandbox over a document built from the
423
+ given factories, and hand back everything a suite needs to drive it.
424
+ `mutate` plants a defect in the bytes IN MEMORY -- never on disk --
425
+ which is how a suite proves its lock goes red on the real
426
+ regression instead of asserting a green it was handed. Same idea as
427
+ scripts/fixture-dom.mjs, which does it for validate_global. */
428
+ export function loadRuntime(opts) {
429
+ const o = opts || {};
430
+ /* `runtimeSource`, 2026-11-27 (PLAN_LUNES): WHERE to read the runtime
431
+ from. The battery reads js/nac.js, which is the authoritative
432
+ source and the only thing worth testing in a checkout. The CLI
433
+ harness mode has to work from an INSTALLED package, where js/ is
434
+ not published and the runtime is dist/nac.cjs -- so it passes the
435
+ path instead of this module guessing. Additive: every existing
436
+ caller gets the same file it got before. */
437
+ const srcPath = o.runtimeSource || path.join(ROOT, 'js', 'nac.js');
438
+ let src = fs.readFileSync(srcPath, 'utf8');
439
+ if (o.mutate) {
440
+ const before = src;
441
+ src = o.mutate(src);
442
+ if (src === before) {
443
+ throw new Error('the mutation matched nothing in js/nac.js: the lock would pass for the wrong reason');
444
+ }
445
+ }
446
+
447
+ const document = new HDocument();
448
+ for (const factory of (o.tree || [])) document.body.appendChild(factory(document));
449
+
450
+ const events = [];
451
+ const warnings = [];
452
+
453
+ /* Every contract event the runtime emits, recorded in order. A suite
454
+ asserting on a payload should not have to add its own listener. */
455
+ const origFire = document._fire.bind(document);
456
+ document._fire = (ev, setTarget) => { events.push({ type: ev.type, detail: ev.detail }); return origFire(ev, setTarget); };
457
+ const origDispatch = document.dispatchEvent.bind(document);
458
+ document.dispatchEvent = (ev) => { return origDispatch(ev); };
459
+
460
+ const win = {
461
+ document,
462
+ CustomEvent: HEvent,
463
+ Event: HEvent,
464
+ setTimeout, clearTimeout, setInterval, clearInterval,
465
+ queueMicrotask,
466
+ Promise, Map, Set, WeakMap, JSON, Math, Date, Array, Object, String, Number, Boolean,
467
+ RegExp, Error, TypeError, Symbol, Proxy, Reflect, isNaN, parseInt, parseFloat,
468
+ performance: { now: () => Date.now() },
469
+ /* WebCrypto, because sign_provenance / verify_provenance go
470
+ through SubtleCrypto. Node has it; a harness without it makes
471
+ those two verbs untestable rather than failing loudly, which is
472
+ the shape of gap TF-D11 is about. */
473
+ crypto: globalThis.crypto,
474
+ TextEncoder, TextDecoder, Uint8Array, ArrayBuffer, atob, btoa,
475
+ navigator: { language: o.language || 'en-US', userAgent: 'nac3-dom-harness' },
476
+ location: { href: o.href || 'http://localhost/nac3-harness', origin: 'http://localhost' },
477
+ /* getComputedStyle, present on purpose: two definitions of
478
+ "visible" in the runtime read it, one of them through
479
+ ownerDocument.defaultView, and a harness without it cannot tell
480
+ the two apart. */
481
+ getComputedStyle(node) {
482
+ return {
483
+ opacity: node && node._hidden ? '0' : '1',
484
+ display: node && node._hidden ? 'none' : 'block',
485
+ visibility: node && node._hidden ? 'hidden' : 'visible',
486
+ getPropertyValue(k) { return this[k] || ''; },
487
+ };
488
+ },
489
+ requestAnimationFrame(fn) { return setTimeout(() => fn(Date.now()), 0); },
490
+ cancelAnimationFrame(id) { clearTimeout(id); },
491
+ matchMedia() { return { matches: false, addEventListener() {}, removeEventListener() {} }; },
492
+ localStorage: {
493
+ _m: new Map(),
494
+ getItem(k) { return this._m.has(k) ? this._m.get(k) : null; },
495
+ setItem(k, v) { this._m.set(k, String(v)); },
496
+ removeItem(k) { this._m.delete(k); },
497
+ },
498
+ MutationObserver: class { observe() {} disconnect() {} takeRecords() { return []; } },
499
+ addEventListener() {}, removeEventListener() {}, dispatchEvent() { return true; },
500
+ };
501
+ win.window = win;
502
+ win.globalThis = win;
503
+ win.self = win;
504
+ /* defaultView is what the second "visible" implementation reaches
505
+ through. Present here so the suite can also REMOVE it and prove
506
+ what happens in an environment that has none. */
507
+ document.defaultView = win;
508
+
509
+ const console_ = {
510
+ log() {},
511
+ info() {},
512
+ warn(...a) { warnings.push(a.map(String).join(' ')); },
513
+ error(...a) { warnings.push('ERROR ' + a.map(String).join(' ')); },
514
+ };
515
+ win.console = console_;
516
+
517
+ /* 2.7.0 (SPEC sec 19) -- a sandbox with NO document at all. The
518
+ headless profile cannot be tested honestly against a stub that
519
+ answers "no elements": a stub IS a document, and the thing being
520
+ exercised is the absence of one. Opt-in and additive -- every
521
+ existing suite keeps the document it already has. A real screenless
522
+ host has no MutationObserver either, so that goes too. */
523
+ if (o.headless) {
524
+ delete win.document;
525
+ delete win.MutationObserver;
526
+ }
527
+
528
+ const ctx = vm.createContext(win);
529
+ vm.runInContext(src, ctx, { filename: srcPath });
530
+
531
+ /* The v2 extensions, on request. They install onto the same NAC
532
+ export and carry the locale machinery (locale, registerCatalog,
533
+ t, setAutoRTL) -- which TF-D06 measured at zero coverage, and
534
+ which is where three of the list's defects live. `mutateExt`
535
+ plants a defect in THEIR bytes, in memory, for the same reason
536
+ `mutate` does for the runtime. */
537
+ if (o.extensions) {
538
+ /* Same reasoning as runtimeSource above: from a checkout the
539
+ extensions are js/nac-v2-extensions.js, from an installed
540
+ package they are a dist artefact, and the caller knows which. */
541
+ let ext = fs.readFileSync(
542
+ o.extensionsSource || path.join(ROOT, 'js', 'nac-v2-extensions.js'), 'utf8');
543
+ if (o.mutateExt) {
544
+ const before = ext;
545
+ ext = o.mutateExt(ext);
546
+ if (ext === before) {
547
+ throw new Error('the extension mutation matched nothing: the lock would pass for the wrong reason');
548
+ }
549
+ }
550
+ vm.runInContext(ext, ctx, { filename: 'js/nac-v2-extensions.js' });
551
+ }
552
+
553
+ const NAC = ctx.NAC || win.NAC;
554
+ if (!NAC || typeof NAC.click !== 'function') {
555
+ throw new Error('js/nac.js did not install a NAC export with click() in the harness sandbox');
556
+ }
557
+
558
+ return {
559
+ NAC,
560
+ document,
561
+ window: win,
562
+ events,
563
+ warnings,
564
+ /* Helpers suites keep needing. */
565
+ byId: (id) => document.querySelector('[data-nac-id="' + id + '"]'),
566
+ emit: (type, detail) => document._fire(new HEvent(type, { detail }), true),
567
+ /* The order of children, by nac id: the only readable way to
568
+ assert what reorder() and drag_drop() did. */
569
+ orderOf: (containerId) => {
570
+ const c = document.querySelector('[data-nac-id="' + containerId + '"]');
571
+ if (!c) throw new Error('no container with data-nac-id=' + containerId);
572
+ return c.children.map((n) => n.getAttribute('data-nac-id'));
573
+ },
574
+ eventsOfType: (type) => events.filter((e) => e.type === type),
575
+ };
576
+ }
577
+
578
+ export { HNode, HText, HDocument, HEvent };
@@ -33,13 +33,50 @@
33
33
  NacChat.setLang(code)
34
34
  NacChat.snapshotTree() // returns the tree posted to backend
35
35
  NacChat.onAction(kind, fn) // override or extend a kind handler
36
+ NacChat.debug = true // turn the diagnostic log on (OFF by default)
37
+
38
+ THE DIAGNOSTIC LOG IS OFF BY DEFAULT, and that is a deliberate
39
+ change of behaviour made on 2026-11-24. This file carried five
40
+ unconditional console.log calls in published code, and three of them
41
+ printed CONTENT rather than control flow: the language model's reply
42
+ to the user, and -- twice, in the speech path -- the text the
43
+ microphone had just transcribed. An adopter embedding this on a page
44
+ where someone dictates a name, an address or a diagnosis was putting
45
+ that text in the browser console on every utterance, with no switch
46
+ to stop it and nothing in the documentation saying so.
47
+
48
+ What did NOT change: console.warn and console.error still speak
49
+ unconditionally. An adopter has to be able to see that something
50
+ broke; a silent failure is the thing this project argues against.
51
+ Only the diagnostics are behind the switch.
52
+
53
+ To turn them back on, either set NacChat.debug = true at runtime or
54
+ define window.NAC_CHAT_DEBUG = true before this file loads (the
55
+ second form exists because the most useful diagnostics happen during
56
+ init, before anyone has a handle to the object).
36
57
 
37
58
  ASCII-only.
38
59
  =============================================================== */
39
60
  (function (global) {
40
61
  'use strict';
41
62
 
63
+ /* The diagnostic log, off unless asked for. See the header: three of
64
+ these printed user content, so the default has to be quiet. */
65
+ function _dbgEnabled() {
66
+ if (NacChat && NacChat.debug === true) return true;
67
+ return global.NAC_CHAT_DEBUG === true;
68
+ }
69
+ function _dbg() {
70
+ if (!_dbgEnabled()) return;
71
+ if (!global.console || typeof global.console.log !== 'function') return;
72
+ global.console.log.apply(global.console, arguments);
73
+ }
74
+
42
75
  var NacChat = {
76
+ /* Public, additive, and documented in the header. Not a private
77
+ underscore field: an adopter debugging a page needs to be able
78
+ to reach for it without reading the source. */
79
+ debug: false,
43
80
  _endpoint: '/crm/api/v1/yujin/nac-demo',
44
81
  _sessionId: 'sess_' + Math.random().toString(36).slice(2, 10),
45
82
  _lang: 'es',
@@ -289,10 +326,10 @@
289
326
  }
290
327
  }
291
328
  } catch (_) {}
292
- console.log('[nac-chat] snapshot plugins (' + plugins.length + '):',
329
+ _dbg('[nac-chat] snapshot plugins (' + plugins.length + '):',
293
330
  plugins.map(function (p) { return p.plugin; }).join(', '));
294
331
  if (out.data_tables && out.data_tables.length) {
295
- console.log('[nac-chat] data_tables:',
332
+ _dbg('[nac-chat] data_tables:',
296
333
  out.data_tables.map(function (t) {
297
334
  return t.table_id + ' (' + t.subkind + ')';
298
335
  }).join(', '));
@@ -518,8 +555,12 @@
518
555
  returned so 'chat says X but nothing happens' is
519
556
  distinguishable from 'chat dispatched X but it failed
520
557
  silently'. If the LLM only emits a {message} with no
521
- actions, this log makes it obvious. */
522
- console.log('[nac-chat] backend response: message="' + message
558
+ actions, this log makes it obvious.
559
+
560
+ Behind NacChat.debug since 2026-11-24: `message` is the model's
561
+ reply to the user, so this line published user-facing content to
562
+ the console of every page that embedded the client. */
563
+ _dbg('[nac-chat] backend response: message="' + message
523
564
  + '" actions=' + JSON.stringify(actions));
524
565
  if (message) {
525
566
  _bubble('bot', message);
@@ -558,11 +599,11 @@
558
599
  if (NacChat._sttFlushTimer) { clearTimeout(NacChat._sttFlushTimer); NacChat._sttFlushTimer = null; }
559
600
  if (!text) return;
560
601
  if (_isBotEcho(text)) {
561
- console.log('[nac-chat-stt] dropping bot-echo:', text);
602
+ _dbg('[nac-chat-stt] dropping bot-echo:', text);
562
603
  return;
563
604
  }
564
605
  if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
565
- console.log('[nac-chat-stt] dropping during TTS:', text);
606
+ _dbg('[nac-chat-stt] dropping during TTS:', text);
566
607
  return;
567
608
  }
568
609
  NacChat.send(text);