@nac3/runtime 2.3.0 → 2.3.1

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.
@@ -1,2107 +1,2296 @@
1
1
  // Generated by build.mjs -- do not edit. Source: yujin.app/nac-spec/js/nac-v2-extensions.js
2
2
  const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
3
- /* ===============================================================
4
- nac-v2-extensions.js -- NAC v2.0 additive extensions to v1.9
5
- ---------------------------------------------------------------
6
- Strict superset: this file LOADS AFTER nac.js v1.9.0 and ATTACHES
7
- the v2.0 primitives onto window.NAC without modifying the v1.9
8
- surface. Every v1.9 client keeps working unchanged.
9
-
10
- Provides:
11
- - NAC.scope(spec) hierarchical constructor
12
- - NAC.autoRegister(el, opts) DOM-driven registration
13
- - NAC.adopt(rule) third-party non-compliant
14
- - NAC.bridgeShadowRoot(host) Shadow DOM bridge
15
- - NAC.bridgeIframe(iframeEl, opts) same-vendor iframe bridge
16
- - NAC.declareVirtual(spec) virtualized lists
17
- - NAC.captureEphemeral(opts) transient UI capture
18
- - NAC.setTenantPrefix(slug) multi-tenant naming
19
- - NAC.declareSitemap(spec) optional sitemap (sec 17)
20
- - NAC.attestUserGesture(opts) isTrusted attestation
21
- - NAC.t(key, opts?) i18n resolver
22
- - NAC.registerCatalog(catalog) i18n catalog registration
23
- - NAC.locale(code?) locale getter/setter
24
- - NAC.setSupportedLocales(arr) extend supported list
25
- - NAC.setRTLLocales(arr) extend RTL list
26
- - NAC.set_provenance_secret(secret) HMAC secret registration
27
-
28
- And tightens (only at NAC-3):
29
- - check_canonical_shape: agent must sign + user_gesture_attested
30
- - validate_global: i18n_strict mode
31
-
32
- Spec: spec/NAC-v2.0.md + RFC_v2.0.0.md
33
- ASCII-only.
34
- =============================================================== */
35
- (function (global) {
36
- 'use strict';
37
- if (!global.NAC) {
38
- console.error('[NAC v2] requires nac.js v1.9.0+ to be loaded first');
39
- return;
40
- }
41
- if (global.NAC.__nac_v2_installed) return;
42
- global.NAC.__nac_v2_installed = true;
43
-
44
- var NAC = global.NAC;
45
- var SEPARATOR = '.';
46
- var MAX_DEPTH = 6;
47
- var WARN_DEPTH = 4;
48
-
49
- /* ------------------------------------------------------------- locales */
50
-
51
- var SUPPORTED_LOCALES_DEFAULT = ['es','en','pt','fr','it','de','ja','zh','hi','ar'];
52
- var RTL_LOCALES_DEFAULT = ['ar','he','fa','ur'];
53
- var _supported = SUPPORTED_LOCALES_DEFAULT.slice();
54
- var _rtl = RTL_LOCALES_DEFAULT.slice();
55
- var _currentLocale = (function () {
56
- try {
57
- var l = (document.documentElement.getAttribute('lang')
58
- || navigator.language
59
- || 'es').slice(0, 2).toLowerCase();
60
- return _supported.indexOf(l) >= 0 ? l : 'es';
61
- } catch (_) { return 'es'; }
62
- })();
63
- var _catalog = Object.create(null);
64
-
65
- function setSupportedLocales(arr) {
66
- if (!Array.isArray(arr) || !arr.length) {
67
- throw new Error('[NAC v2] setSupportedLocales requires non-empty array');
68
- }
69
- _supported = arr.slice();
70
- }
71
- function setRTLLocales(arr) {
72
- if (!Array.isArray(arr)) throw new Error('[NAC v2] setRTLLocales requires array');
73
- _rtl = arr.slice();
74
- }
75
- /* v2.0-rc3 (Claude T5-F4): some hosts ship multi-locale
76
- content in one DOM (e.g. user in 'ar' viewing untranslated
77
- English log lines); auto-flipping dir=rtl on documentElement
78
- globally breaks the LTR content's BIDI. Hosts opt out via
79
- setAutoRTL(false), then manage dir on a sub-tree element. */
80
- var _autoRTL = true;
81
- function setAutoRTL(enabled) { _autoRTL = !!enabled; }
82
-
83
- function locale(code) {
84
- if (code === undefined) return _currentLocale;
85
- if (_supported.indexOf(code) < 0) {
86
- console.warn('[NAC v2] locale', code, 'not in supported list');
87
- }
88
- _currentLocale = code;
89
- /* Auto-apply dir=rtl unless host opted out via setAutoRTL(false). */
90
- if (_autoRTL) {
91
- try {
92
- if (_rtl.indexOf(code) >= 0) {
93
- document.documentElement.setAttribute('dir', 'rtl');
94
- } else {
95
- document.documentElement.removeAttribute('dir');
96
- }
97
- } catch (_) {}
98
- }
99
- document.dispatchEvent(new CustomEvent('nac:locale_changed', {
100
- detail: { locale: code, autoRTL: _autoRTL }, bubbles: true
101
- }));
102
- }
103
- function registerCatalog(obj) {
104
- if (!obj || typeof obj !== 'object') {
105
- throw new Error('[NAC v2] registerCatalog requires object');
106
- }
107
- Object.keys(obj).forEach(function (k) { _catalog[k] = obj[k]; });
108
- }
109
- function t(key, opts) {
110
- opts = opts || {};
111
- var loc = opts.locale || _currentLocale;
112
- var entry = _catalog[key];
113
- if (!entry) return opts.fallback || key;
114
- if (entry[loc]) return entry[loc];
115
- /* Fallback chain: requested -> es -> en -> first available */
116
- if (entry.es) return entry.es;
117
- if (entry.en) return entry.en;
118
- var firstKey = Object.keys(entry)[0];
119
- return firstKey ? entry[firstKey] : (opts.fallback || key);
120
- }
121
-
122
- /* ------------------------------------------------------------- HMAC */
123
-
124
- var _provenanceSecrets = [];
125
- function set_provenance_secret(s) {
126
- if (typeof s === 'string') _provenanceSecrets = [s];
127
- else if (Array.isArray(s)) _provenanceSecrets = s.slice();
128
- else if (s == null) _provenanceSecrets = [];
129
- else throw new Error('[NAC v2] set_provenance_secret expects string|string[]');
130
- /* v2.0-rc3 (Claude T6-F2): warm the crypto path now that we
131
- have a secret registered; first agent sign won't pay the
132
- cold-start cost. */
133
- if (_provenanceSecrets[0] && typeof NAC.sign_provenance === 'function') {
134
- try {
135
- NAC.sign_provenance({ _warmup: true, ts: Date.now() }, _provenanceSecrets[0])
136
- .catch(function () {});
137
- } catch (_) {}
138
- }
139
- }
140
- /* sign / verify provenance helpers exist in v1.9 already; reuse them */
141
- function _hasSecrets() { return _provenanceSecrets.length > 0; }
142
-
143
- async function _verify_with_registered(detail) {
144
- if (!_hasSecrets()) return false;
145
- if (typeof NAC.verify_provenance !== 'function') return false;
146
- for (var i = 0; i < _provenanceSecrets.length; i++) {
147
- try {
148
- var ok = await NAC.verify_provenance(detail, _provenanceSecrets[i]);
149
- if (ok) return true;
150
- } catch (_) {}
151
- }
152
- return false;
153
- }
154
-
155
- /* ------------------------------------------------------------- isTrusted */
156
-
157
- /* v2.0-rc3 (Claude T4-F1 BLOCKER fix): the gesture buffer is now
158
- bound to the originating event's composedPath, NOT a global
159
- flag. _readGestureAttested(forElement) verifies that the
160
- element being invoked is in the captured path before honoring
161
- attested. Without this, any user click anywhere on the page
162
- leaked attested=true to ANY subsequent _invoke within the
163
- freshness window -- the FOURTH impersonation path Claude
164
- surfaced.
165
-
166
- Additionally: GESTURE_FRESH_MS reduced 100ms -> 16ms (one
167
- animation frame). Genuine click handlers run synchronously
168
- (or via microtask), well within 16ms. Promise-resolved-later
169
- handlers no longer count as user-attested -- which is the
170
- security-correct behaviour. */
171
- var _lastGestureTrusted = null;
172
- var _lastGestureTime = 0;
173
- var _lastGesturePath = null; /* Array<EventTarget> from e.composedPath() */
174
- var GESTURE_FRESH_MS = 16; /* was 100 in rc2 */
175
-
176
- /* v2.0-rc2 (Mistral T4-F1): mobile WebView contexts (Cordova,
177
- Capacitor, React Native WebView) have inconsistent isTrusted
178
- semantics. Hosts running in those environments register a
179
- custom derivation function via setMobileWebViewAttestation so
180
- the platform-specific signal substitutes for browser
181
- event.isTrusted. */
182
- var _mobileWebViewAttestor = null;
183
-
184
- function setMobileWebViewAttestation(fn) {
185
- if (fn != null && typeof fn !== 'function') {
186
- throw new Error('[NAC v2] setMobileWebViewAttestation expects function|null');
187
- }
188
- _mobileWebViewAttestor = fn;
189
- }
190
-
191
- function _captureGestureFromDom() {
192
- var handler = function (e) {
193
- /* When a custom WebView attestor is registered, its return
194
- value (or function call given the event) substitutes the
195
- raw isTrusted reading. */
196
- if (_mobileWebViewAttestor) {
197
- try {
198
- var attested = !!_mobileWebViewAttestor(e);
199
- _lastGestureTrusted = attested;
200
- } catch (err) {
201
- _lastGestureTrusted = !!e.isTrusted;
202
- }
203
- } else {
204
- _lastGestureTrusted = !!e.isTrusted;
205
- }
206
- _lastGestureTime = Date.now();
207
- /* v2.0-rc3: capture the composed path so _invoke can verify
208
- identity. Polyfill for ancient browsers via target ancestor
209
- walk (composedPath() ships in all browsers >= 2018). */
210
- try {
211
- if (typeof e.composedPath === 'function') {
212
- _lastGesturePath = e.composedPath();
213
- } else {
214
- _lastGesturePath = [];
215
- var n = e.target;
216
- while (n) { _lastGesturePath.push(n); n = n.parentNode; }
217
- }
218
- } catch (_) {
219
- _lastGesturePath = e.target ? [e.target] : [];
220
- }
221
- };
222
- ['click','keydown','keyup','touchstart','pointerdown'].forEach(function (n) {
223
- document.addEventListener(n, handler, { capture: true, passive: true });
224
- });
225
- }
226
- /* v2.2.1: guard browser-only DOM hookup so this bundle is
227
- importable in Node / SSR / test contexts. */
228
- if (typeof document !== 'undefined') {
229
- if (document.readyState === 'loading') {
230
- document.addEventListener('DOMContentLoaded', _captureGestureFromDom);
231
- } else {
232
- _captureGestureFromDom();
233
- }
234
- }
235
-
236
- /* v2.0-rc3: _readGestureAttested now requires the element being
237
- invoked. Returns the captured attested flag ONLY if:
238
- (a) the gesture is within GESTURE_FRESH_MS (16ms) AND
239
- (b) `forElement` is in the captured composedPath (or no
240
- element was captured -- legacy callers).
241
- Returns null in all other cases (matrix treats null as
242
- not-attested -> 'user' source rejected at NAC-3). */
243
- function _readGestureAttested(forElement) {
244
- if (Date.now() - _lastGestureTime > GESTURE_FRESH_MS) return null;
245
- if (!forElement) return _lastGestureTrusted; /* legacy fallback */
246
- if (!_lastGesturePath || !_lastGesturePath.length) return _lastGestureTrusted;
247
- /* Identity check: only honor attested when the target element
248
- is in the originating event's path. Closes Claude T4-F1. */
249
- if (_lastGesturePath.indexOf(forElement) >= 0) {
250
- return _lastGestureTrusted;
251
- }
252
- return null;
253
- }
254
-
255
- /* Buffer for validate_global_v2 to surface findings emitted
256
- by runtime guards (added rc6). Declared BEFORE
257
- attestUserGesture so the override-blocking branch can
258
- push into it without a temporal-dead-zone error. */
259
- var _validatorFindings = [];
260
-
261
- var _scriptOverride = null;
262
- function attestUserGesture(opts) {
263
- opts = opts || {};
264
- /* 2026-05-09 (Claude R6 MEDIUM): the API was previously a
265
- complete bypass for the identity-binding check. A page-
266
- level script could call
267
- attestUserGesture({trusted:true, type:'user'}) and the
268
- next invoke would inherit attested=true with NO identity
269
- binding to a real isTrusted gesture path. The override
270
- was specified as testing-only (sec 15.10) but the runtime
271
- accepted arbitrary opts.type values.
272
-
273
- Fix: opts.type may ONLY be 'script' or 'agent'. Attempts
274
- to claim 'user' (the only type that maps to source.type=
275
- 'user' downstream) are blocked at runtime AND emit a
276
- finding code script_override_claims_user that
277
- validate_global_v2() reports. The override remains
278
- useful for headless test fixtures (testing-only as the
279
- spec always said) but cannot launder a script-origin
280
- action as a user-origin one. */
281
- var requestedType = (typeof opts.type === 'string' && opts.type) ? opts.type : 'script';
282
- if (requestedType === 'user') {
283
- _validatorFindings.push({
284
- code: 'script_override_claims_user',
285
- severity: 'error',
286
- timestamp: Date.now(),
287
- note: 'attestUserGesture rejected opts.type="user" -- only script/agent permitted'
288
- });
289
- console.warn('[NAC v2] attestUserGesture: opts.type="user" rejected; '
290
- + 'forcing type="script". Identity-binding bypass blocked.');
291
- requestedType = 'script';
292
- }
293
- if (requestedType !== 'script' && requestedType !== 'agent') {
294
- throw new Error('[NAC v2] attestUserGesture: opts.type must be '
295
- + '"script" or "agent" (got "' + requestedType + '")');
296
- }
297
- _scriptOverride = {
298
- trusted: !!opts.trusted,
299
- type: requestedType,
300
- ts: Date.now()
301
- };
302
- }
303
-
304
- /* ------------------------------------------------------------- perf tolerance */
305
-
306
- /* v2.0-rc2 (Grok+Mistral T6-F1): default throttle bumped 50ms ->
307
- 100ms after concurrent reviewer feedback that 50ms drops
308
- events on bursty UIs. set_perf_tolerance({mutation_throttle_ms,
309
- describe_target_ms, etc}) lets hosts tune for their workload. */
310
- var _perfTolerance = {
311
- mutation_throttle_ms: 100, /* was 50 in rc1 */
312
- describe_target_ms: 50, /* was 30 in rc1 (Mistral T6-F2) */
313
- describe_hard_fail_ms: 150, /* was 100 in rc1 */
314
- adopt_hard_fail_ms: 20, /* was 15 in rc1 */
315
- autoregister_hard_fail_ms: 5,
316
- /* v2.0-rc4 (Claude T8.1 middle ground): hard-fail RATE
317
- tightened from 5%/5s (rc2/rc3) to 2%/5s (rc4). Same
318
- window width, tighter rate. Rationale: 5% over 5s = ~1
319
- hitched describe() per 20s on Snapdragon 6 Gen 1 = breaks
320
- SR reading flow; 1%/10s window too long for bursty
321
- stalls. 2%/5s captures sustained AND bursty correctly.
322
- Tunable for hosts that need looser thresholds. */
323
- perf_budget_fail_rate_pct: 2, /* was implicit 5% in rc3 */
324
- perf_budget_window_ms: 5000 /* unchanged */
325
- };
326
-
327
- function set_perf_tolerance(opts) {
328
- if (!opts || typeof opts !== 'object') {
329
- throw new Error('[NAC v2] set_perf_tolerance expects object');
330
- }
331
- Object.keys(opts).forEach(function (k) {
332
- if (k in _perfTolerance && typeof opts[k] === 'number' && opts[k] > 0) {
333
- _perfTolerance[k] = opts[k];
334
- }
335
- });
336
- }
337
- function get_perf_tolerance() { return Object.assign({}, _perfTolerance); }
338
-
339
- /* ------------------------------------------------------------- validation tolerance */
340
-
341
- /* v2.0-rc2 (Grok T5-F1 + Mistral T5-F2): NAC-3 default i18n
342
- severity bumped from 'error' to 'warn' after concurrent
343
- reviewer feedback that mandatory at NAC-3 blocks incremental
344
- SaaS rollouts. Hosts that want strict 'error' behaviour opt
345
- in via set_validation_tolerance({i18n_strict: 'error'}). */
346
- var _validationTolerance = {
347
- i18n_strict: 'warn', /* 'warn' (default) | 'error' | 'silent' */
348
- /* v2.0-rc4 (Mistral T7-F1): iframe_strict opt-in turns on
349
- NAC-3 fail-closed for bridgeIframe. Default 'warn' = rc3
350
- fail-open behaviour preserved for NAC-1/NAC-2. */
351
- iframe_strict: 'warn', /* 'warn' (default) | 'error' */
352
- /* v2.0-rc4 (Claude T8.2): autoderived_action signals when
353
- autoRegister inferred the action without an explicit
354
- data-nac-action attribute. Default 'warn'; opt-in 'error'
355
- for regulated-environment audit pipelines. */
356
- autoderived_action: 'warn' /* 'warn' (default) | 'error' | 'silent' */
357
- };
358
-
359
- function set_validation_tolerance(opts) {
360
- if (!opts || typeof opts !== 'object') {
361
- throw new Error('[NAC v2] set_validation_tolerance expects object');
362
- }
363
- if (opts.i18n_strict && ['warn', 'error', 'silent'].indexOf(opts.i18n_strict) >= 0) {
364
- _validationTolerance.i18n_strict = opts.i18n_strict;
365
- }
366
- if (opts.iframe_strict && ['warn', 'error'].indexOf(opts.iframe_strict) >= 0) {
367
- _validationTolerance.iframe_strict = opts.iframe_strict;
368
- }
369
- if (opts.autoderived_action && ['warn', 'error', 'silent'].indexOf(opts.autoderived_action) >= 0) {
370
- _validationTolerance.autoderived_action = opts.autoderived_action;
371
- }
372
- }
373
- function get_validation_tolerance() { return Object.assign({}, _validationTolerance); }
374
-
375
- /* ------------------------------------------------------------- scope */
376
-
377
- var _scopes = Object.create(null);
378
-
379
- function _validateLeaf(slug) {
380
- if (!slug || typeof slug !== 'string') {
381
- throw new Error('[NAC v2] slug required');
382
- }
383
- /* v2.0-rc3 (DeepSeek T3.1): empty string passes the typeof
384
- check + indexOf check, then produces malformed slugs. Reject
385
- it explicitly. */
386
- if (slug.length === 0) {
387
- throw new Error('[NAC v2] slug_invalid: empty string');
388
- }
389
- if (slug.indexOf(SEPARATOR) >= 0) {
390
- throw new Error('[NAC v2] slug_invalid: contains "' + SEPARATOR + '"');
391
- }
392
- }
393
-
394
- function scope(spec) {
395
- spec = spec || {};
396
- _validateLeaf(spec.slug);
397
- return _makeSubScope(spec.slug, [spec.slug], spec);
398
- }
399
-
400
- function _makeSubScope(currentSlug, chain, spec) {
401
- var depth = chain.length;
402
- if (depth > MAX_DEPTH) {
403
- throw new Error('[NAC v2] depth_exceeded: ' + chain.join(SEPARATOR));
404
- }
405
- if (depth === WARN_DEPTH + 1) {
406
- document.dispatchEvent(new CustomEvent('nac:depth_warn', {
407
- detail: { path: chain.join(SEPARATOR), depth: depth }, bubbles: true
408
- }));
409
- }
410
-
411
- var node = {
412
- id: chain.join(SEPARATOR),
413
- depth: depth,
414
- label_i18n: spec ? spec.label_i18n || null : null,
415
- };
416
- /* v2.0-rc3 (Claude T3.1): track intermediate nodes that carry
417
- a label_i18n so describe_v2 can expose them. Leaf nodes go
418
- through register() and end up in _scopes; intermediate
419
- (non-leaf) nodes need a separate index. */
420
- if (node.label_i18n) {
421
- _intermediateScopes[node.id] = {
422
- depth: depth,
423
- label_i18n: node.label_i18n
424
- };
425
- }
426
- Object.assign(node, {
427
-
428
- scope: function (childSpec) {
429
- _validateLeaf(childSpec.slug);
430
- var childChain = chain.concat([childSpec.slug]);
431
- return _makeSubScope(childSpec.slug, childChain, childSpec);
432
- },
433
-
434
- register: function (regSpec) {
435
- _validateLeaf(regSpec.slug);
436
- var fullSlug = chain.concat([regSpec.slug]).join(SEPARATOR);
437
-
438
- var entry = {
439
- slug: fullSlug,
440
- intent: regSpec.intent || 'navigate',
441
- source: regSpec.source || 'human',
442
- label_i18n: regSpec.label_i18n || null,
443
- desc_i18n: regSpec.desc_i18n || null,
444
- a11y_hint: regSpec.a11y_hint || null,
445
- irreversible:!!regSpec.irreversible,
446
- role: regSpec.role || null,
447
- element: regSpec.element || null,
448
- handler: typeof regSpec.handler === 'function' ? regSpec.handler : null,
449
- autoderived: false,
450
- parent_chain: chain.slice(),
451
- registered_at: Date.now()
452
- };
453
-
454
- /* Idempotent: re-register with same slug + same element silently
455
- updates; re-register with same slug + different element warns. */
456
- var prior = _scopes[fullSlug];
457
- if (prior) {
458
- if (prior.element === entry.element) {
459
- _scopes[fullSlug] = entry;
460
- } else {
461
- document.dispatchEvent(new CustomEvent('nac:duplicate_warn', {
462
- detail: { slug: fullSlug, prior: prior, next: entry }, bubbles: true
463
- }));
464
- _scopes[fullSlug] = entry; /* last-wins */
465
- }
466
- } else {
467
- _scopes[fullSlug] = entry;
468
- }
469
-
470
- if (entry.element) {
471
- entry.element.setAttribute('data-nac-id', fullSlug);
472
- entry.element.setAttribute('data-nac-parent', chain.join(' '));
473
- if (entry.role) entry.element.setAttribute('role', entry.role);
474
- if (entry.label_i18n) {
475
- var lbl = t.bind(null);
476
- var labelText = (function () {
477
- if (entry.label_i18n[_currentLocale]) return entry.label_i18n[_currentLocale];
478
- if (entry.label_i18n.es) return entry.label_i18n.es;
479
- if (entry.label_i18n.en) return entry.label_i18n.en;
480
- return fullSlug;
481
- })();
482
- if (!entry.element.getAttribute('aria-label')) {
483
- entry.element.setAttribute('aria-label', labelText);
484
- }
485
- }
486
- if (entry.irreversible) {
487
- entry.element.setAttribute('data-nac-irreversible', '1');
488
- }
489
- }
490
-
491
- return {
492
- id: fullSlug,
493
- invoke: function (params) { return _invoke(fullSlug, params); }
494
- };
495
- }
496
- });
497
- return node;
498
- }
499
-
500
- function _invoke(slug, params) {
501
- var entry = _scopes[slug];
502
- if (!entry) return Promise.reject(new Error('unknown_slug:' + slug));
503
- var src = (params && params.source) || entry.source || 'human';
504
-
505
- var attested;
506
- if (_scriptOverride && Date.now() - _scriptOverride.ts < GESTURE_FRESH_MS) {
507
- attested = _scriptOverride.trusted;
508
- _scriptOverride = null;
509
- } else {
510
- /* v2.0-rc3 (Claude T4-F1 BLOCKER fix): pass entry.element so
511
- _readGestureAttested can verify identity, not just freshness.
512
- Closes the gesture-buffer leak. */
513
- attested = _readGestureAttested(entry.element);
514
- }
515
-
516
- /* v2.0-rc3 (Claude T4-F3): os_level pass-through. When source is
517
- 'agent' AND host opts in (e.g. for Computer Use telemetry),
518
- params.os_level is propagated into provenance for audit. */
519
- var osLevel = (params && params.os_level === true) ? true : null;
520
-
521
- var prov = {
522
- slug: slug,
523
- intent: entry.intent,
524
- source: src,
525
- type: src,
526
- user_gesture_attested: attested,
527
- ts: Date.now(),
528
- params: params || null
529
- };
530
- if (osLevel === true) prov.os_level = true;
531
-
532
- /* Agent + irreversible -> decline path */
533
- if (src === 'agent' && entry.irreversible) {
534
- var hint = entry.a11y_hint
535
- ? (entry.a11y_hint[_currentLocale] || entry.a11y_hint.es)
536
- : null;
537
- document.dispatchEvent(new CustomEvent('nac:command_rejected', {
538
- detail: { slug: slug, reason: 'agent_declined_irreversible', hint: hint, ts: Date.now() },
539
- bubbles: true
540
- }));
541
- return Promise.reject(new Error('agent_declined_irreversible'));
542
- }
543
-
544
- /* Sign if we can (agent must) */
545
- var signPromise;
546
- if (typeof NAC.sign_provenance === 'function' && _provenanceSecrets[0]) {
547
- signPromise = NAC.sign_provenance(prov, _provenanceSecrets[0]);
548
- } else {
549
- signPromise = Promise.resolve(null);
550
- }
551
-
552
- return signPromise.then(function (sig) {
553
- if (sig) prov.signature = sig;
554
- var detail = { provenance: prov, signature: sig, version: 'v2.0' };
555
- document.dispatchEvent(new CustomEvent('nac:command_pending', {
556
- detail: detail, bubbles: true
557
- }));
558
- var run = entry.handler
559
- ? Promise.resolve().then(function () { return entry.handler(params || {}, detail); })
560
- : Promise.resolve(null);
561
- return run.then(function (result) {
562
- document.dispatchEvent(new CustomEvent('nac:command_done', {
563
- detail: Object.assign({}, detail, { result: result }), bubbles: true
564
- }));
565
- return result;
566
- }, function (err) {
567
- document.dispatchEvent(new CustomEvent('nac:command_failed', {
568
- detail: Object.assign({}, detail, { error: String(err) }), bubbles: true
569
- }));
570
- throw err;
571
- });
572
- });
573
- }
574
-
575
- /* ------------------------------------------------------------- autoRegister */
576
-
577
- function _findScopeAncestor(el) {
578
- var anc = el.parentElement;
579
- while (anc) {
580
- if (anc.hasAttribute && anc.hasAttribute('data-nac-scope')) {
581
- return anc.getAttribute('data-nac-scope');
582
- }
583
- anc = anc.parentElement;
584
- }
585
- return null;
586
- }
587
-
588
- function _deriveLeafSlug(el) {
589
- if (el.id) return el.id;
590
- if (el.dataset && el.dataset.nacAction) return el.dataset.nacAction;
591
- /* v2.0-rc3 (Claude T3.2): the rc1 fallback hashed only
592
- el.outerHTML.slice(0,100) which produces identical hashes for
593
- 400 cards rendered from the same template (template prefixes
594
- are byte-identical). The fix mixes in: tag name + textContent
595
- (more discriminating) + position-in-parent (guaranteed
596
- unique). Collisions still possible when two truly identical
597
- elements exist; idempotent register handles those by
598
- last-wins-same-element. */
599
- var src = '';
600
- src += el.tagName || '';
601
- src += '|';
602
- src += (el.textContent || '').trim().slice(0, 60);
603
- src += '|';
604
- if (el.parentNode) {
605
- try {
606
- var siblings = el.parentNode.children;
607
- for (var s = 0; s < siblings.length; s++) {
608
- if (siblings[s] === el) { src += '@' + s; break; }
609
- }
610
- } catch (_) {}
611
- }
612
- src += '|';
613
- src += (el.outerHTML || '').slice(0, 80);
614
- var h = 0;
615
- for (var i = 0; i < src.length; i++) {
616
- h = ((h << 5) - h) + src.charCodeAt(i);
617
- h |= 0;
618
- }
619
- return 'auto_' + (Math.abs(h)).toString(36);
620
- }
621
-
622
- function _deriveRole(el) {
623
- var tag = el.tagName.toLowerCase();
624
- var attrRole = el.getAttribute('role');
625
- if (attrRole) return attrRole;
626
- if (tag === 'button') return 'button';
627
- if (tag === 'a' && el.hasAttribute('href')) return 'link';
628
- if (tag === 'input') {
629
- var t = el.getAttribute('type') || 'text';
630
- if (t === 'checkbox' || t === 'radio') return 'toggle';
631
- return 'field';
632
- }
633
- if (tag === 'textarea') return 'field';
634
- if (tag === 'select') return 'select';
635
- return 'interactive';
636
- }
637
-
638
- function _deriveLabel(el) {
639
- var aria = el.getAttribute('aria-label');
640
- if (aria) return aria;
641
- return (el.textContent || '').trim().slice(0, 200);
642
- }
643
-
644
- function autoRegister(el, opts) {
645
- opts = opts || {};
646
- if (!el) throw new Error('[NAC v2] autoRegister requires element');
647
- var leaf = _deriveLeafSlug(el);
648
- var parentSlug = opts.inheritScope !== false ? _findScopeAncestor(el) : null;
649
- /* v2.0-rc3 (DeepSeek T3.2): warn on orphan slugs (no parent
650
- scope ancestor found). Easy to happen on pages with multiple
651
- dynamic regions; without a warn the slug ends up huerfano
652
- silently. */
653
- if (opts.inheritScope !== false && !parentSlug) {
654
- try {
655
- document.dispatchEvent(new CustomEvent('nac:autoregister_orphan_warn', {
656
- detail: { leaf: leaf, element: el }, bubbles: true
657
- }));
658
- } catch (_) {}
659
- }
660
- var fullSlug = parentSlug ? (parentSlug + SEPARATOR + leaf) : leaf;
661
-
662
- /* i18n strict check */
663
- var i18nKey = el.getAttribute('data-i18n-key');
664
- var labelI18n = null;
665
- var autoderived = false;
666
- if (i18nKey && _catalog[i18nKey]) {
667
- labelI18n = _catalog[i18nKey];
668
- } else if (i18nKey) {
669
- /* Key declared but catalog missing the entry */
670
- if (opts.i18n_strict !== false) {
671
- document.dispatchEvent(new CustomEvent('nac:i18n_skipped', {
672
- detail: { slug: fullSlug, key: i18nKey, reason: 'catalog_missing' },
673
- bubbles: true
674
- }));
675
- return null;
676
- }
677
- } else {
678
- /* No data-i18n-key. In strict (default) we skip; in permissive
679
- we mono-locale fallback */
680
- if (opts.i18n_strict !== false && opts.i18n_strict !== 'permissive') {
681
- document.dispatchEvent(new CustomEvent('nac:i18n_skipped', {
682
- detail: { slug: fullSlug, reason: 'no_data_i18n_key' },
683
- bubbles: true
684
- }));
685
- return null;
686
- }
687
- var derivedLabel = _deriveLabel(el);
688
- labelI18n = {};
689
- labelI18n[_currentLocale] = derivedLabel;
690
- autoderived = true;
691
- }
692
-
693
- var role = (opts.derive && opts.derive.role === 'auto')
694
- ? _deriveRole(el)
695
- : (opts.derive && opts.derive.role) || _deriveRole(el);
696
-
697
- var entry = {
698
- slug: fullSlug,
699
- intent: 'navigate',
700
- source: 'human',
701
- label_i18n: labelI18n,
702
- role: role,
703
- element: el,
704
- autoderived: autoderived,
705
- registered_at: Date.now()
706
- };
707
- _scopes[fullSlug] = entry;
708
- el.setAttribute('data-nac-id', fullSlug);
709
- if (parentSlug) {
710
- el.setAttribute('data-nac-parent', parentSlug.split(SEPARATOR).join(' '));
711
- }
712
- if (role && !el.getAttribute('role')) el.setAttribute('role', role);
713
- if (labelI18n && !el.getAttribute('aria-label')) {
714
- var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
715
- el.setAttribute('aria-label', lab);
716
- }
717
- return entry;
718
- }
719
-
720
- /* MutationObserver-based watch */
721
- var _watchObservers = [];
722
- autoRegister.watch = function (containerEl, opts) {
723
- opts = opts || {};
724
- /* v2.0-rc2: default throttle pulled from _perfTolerance (100ms),
725
- caller may still override per-watch via opts.throttleMs. */
726
- var throttleMs = opts.throttleMs || _perfTolerance.mutation_throttle_ms;
727
- var pending = false;
728
- var queue = [];
729
-
730
- /* v2.0-rc3 (Claude T6-F1): chunk batches > 50 elements via
731
- requestIdleCallback (or setTimeout fallback) to stay under
732
- the cumulative-batch perf budget. Per-element cost stays the
733
- same; main thread is yielded between sub-batches so the
734
- page stays responsive. */
735
- var CHUNK_SIZE = 50;
736
- function _yieldThen(fn) {
737
- if (typeof window.requestIdleCallback === 'function') {
738
- window.requestIdleCallback(fn, { timeout: 100 });
739
- } else {
740
- setTimeout(fn, 0);
741
- }
742
- }
743
- function processOne(entry) {
744
- if (entry.added) {
745
- if (entry.el.hasAttribute && entry.el.hasAttribute('data-nac-action')) {
746
- try { autoRegister(entry.el, opts); } catch (_) {}
747
- }
748
- /* Descend into added subtree */
749
- if (entry.el.querySelectorAll) {
750
- entry.el.querySelectorAll('[data-nac-action]').forEach(function (x) {
751
- try { autoRegister(x, opts); } catch (_) {}
752
- });
753
- }
754
- } else {
755
- /* Removed: clean manifest */
756
- if (entry.el.getAttribute) {
757
- var slug = entry.el.getAttribute('data-nac-id');
758
- if (slug && _scopes[slug]) delete _scopes[slug];
759
- }
760
- }
761
- }
762
- function flush() {
763
- var batch = queue.splice(0);
764
- pending = false;
765
- if (batch.length <= CHUNK_SIZE) {
766
- batch.forEach(processOne);
767
- return;
768
- }
769
- /* Chunked path: yield between sub-batches. */
770
- var idx = 0;
771
- function step() {
772
- var end = Math.min(idx + CHUNK_SIZE, batch.length);
773
- for (; idx < end; idx++) processOne(batch[idx]);
774
- if (idx < batch.length) _yieldThen(step);
775
- }
776
- step();
777
- }
778
-
779
- var obs = new MutationObserver(function (muts) {
780
- muts.forEach(function (m) {
781
- m.addedNodes.forEach(function (n) {
782
- if (n.nodeType === 1) queue.push({ added: true, el: n });
783
- });
784
- m.removedNodes.forEach(function (n) {
785
- if (n.nodeType === 1) queue.push({ added: false, el: n });
786
- });
787
- });
788
- if (!pending) {
789
- pending = true;
790
- setTimeout(flush, throttleMs);
791
- }
792
- });
793
- obs.observe(containerEl, { childList: true, subtree: true });
794
- _watchObservers.push(obs);
795
- /* Also process existing descendants */
796
- containerEl.querySelectorAll('[data-nac-action]').forEach(function (el) {
797
- try { autoRegister(el, opts); } catch (_) {}
798
- });
799
- return obs;
800
- };
801
-
802
- /* ------------------------------------------------------------- adopt */
803
-
804
- function adopt(rule) {
805
- if (!rule || !rule.selector) throw new Error('[NAC v2] adopt requires selector');
806
- rule.parent = rule.parent || null;
807
- rule.observe = rule.observe !== false;
808
-
809
- function process(el) {
810
- try {
811
- var leaf = (rule.derive && rule.derive.slug)
812
- ? rule.derive.slug(el)
813
- : _deriveLeafSlug(el);
814
- var fullSlug = rule.parent
815
- ? (rule.parent + SEPARATOR + leaf)
816
- : leaf;
817
- var role = (rule.derive && rule.derive.role)
818
- ? rule.derive.role(el)
819
- : _deriveRole(el);
820
- var labelI18n = (rule.derive && rule.derive.label_i18n)
821
- ? rule.derive.label_i18n(el)
822
- : (function () { var o={}; o[_currentLocale]=_deriveLabel(el); return o; })();
823
- var irreversible = (rule.derive && rule.derive.irreversible)
824
- ? rule.derive.irreversible(el)
825
- : false;
826
- var entry = {
827
- slug: fullSlug,
828
- intent: (rule.derive && rule.derive.intent && rule.derive.intent(el)) || 'navigate',
829
- source: 'human',
830
- label_i18n: labelI18n,
831
- role: role,
832
- element: el,
833
- irreversible: irreversible,
834
- adopted: true,
835
- registered_at: Date.now()
836
- };
837
- _scopes[fullSlug] = entry;
838
- el.setAttribute('data-nac-id', fullSlug);
839
- if (role && !el.getAttribute('role')) el.setAttribute('role', role);
840
- if (labelI18n && !el.getAttribute('aria-label')) {
841
- var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
842
- el.setAttribute('aria-label', lab);
843
- }
844
- if (irreversible) el.setAttribute('data-nac-irreversible', '1');
845
- } catch (e) {
846
- document.dispatchEvent(new CustomEvent('nac:adopt_failed', {
847
- detail: { rule: rule.selector, error: String(e) }, bubbles: true
848
- }));
849
- }
850
- }
851
-
852
- /* v2.0-rc3 (Claude T3.3): scope the observer to a host-supplied
853
- containerEl (smaller subtree) when provided, instead of always
854
- attaching to document.body. Reduces mutation-observer cost
855
- on DOM-heavy pages with N rules. */
856
- var scopedRoot = (rule.containerEl && rule.containerEl.nodeType === 1)
857
- ? rule.containerEl
858
- : document.body;
859
-
860
- /* Initial pass: query within the scoped root, not always document. */
861
- scopedRoot.querySelectorAll(rule.selector).forEach(process);
862
-
863
- /* Observer */
864
- if (rule.observe) {
865
- var obs = new MutationObserver(function (muts) {
866
- muts.forEach(function (m) {
867
- m.addedNodes.forEach(function (n) {
868
- if (n.nodeType !== 1) return;
869
- if (n.matches && n.matches(rule.selector)) process(n);
870
- if (n.querySelectorAll) {
871
- n.querySelectorAll(rule.selector).forEach(process);
872
- }
873
- });
874
- });
875
- });
876
- obs.observe(scopedRoot, { childList: true, subtree: true });
877
- }
878
- return rule;
879
- }
880
-
881
- /* ------------------------------------------------------------- bridges */
882
-
883
- /* v2.0-rc3 (DeepSeek T3.4): dedup bridged hosts via WeakSet so
884
- repeat calls on the same host do not produce duplicate
885
- registrations. */
886
- var _bridgedShadowHosts = new WeakSet();
887
-
888
- function bridgeShadowRoot(host, depth) {
889
- depth = depth || 0;
890
- if (depth > 6) {
891
- document.dispatchEvent(new CustomEvent('nac:shadow_depth_exceeded', {
892
- detail: { host: host }, bubbles: true
893
- }));
894
- return;
895
- }
896
- if (!host || !host.shadowRoot) {
897
- document.dispatchEvent(new CustomEvent('nac:shadow_blocked', {
898
- detail: { host: host, reason: 'closed_or_missing' }, bubbles: true
899
- }));
900
- return;
901
- }
902
- /* v2.0-rc3: skip if already bridged. */
903
- if (_bridgedShadowHosts.has(host)) return;
904
- _bridgedShadowHosts.add(host);
905
- /* Walk shadow root: any [data-nac-id] becomes operable; any
906
- [data-nac-action] auto-registers */
907
- var sr = host.shadowRoot;
908
- sr.querySelectorAll('[data-nac-action]').forEach(function (el) {
909
- try { autoRegister(el, { i18n_strict: 'permissive' }); } catch (_) {}
910
- });
911
- /* Recurse */
912
- sr.querySelectorAll('*').forEach(function (el) {
913
- if (el.shadowRoot) bridgeShadowRoot(el, depth + 1);
914
- });
915
- }
916
-
917
- function bridgeIframe(iframeEl, opts) {
918
- opts = opts || {};
919
- var ns = opts.postMessageNamespace || 'nac.iframe.v1';
920
- var trusted = opts.trusted_origins || [];
921
- var timeout = opts.timeout_ms || 5000;
922
- var iframeId = iframeEl.id || 'iframe_' + Math.random().toString(36).slice(2,8);
923
- /* v2.0-rc4 (Mistral T7-F1 + Claude T4-F2.1): NAC-3 enforcement
924
- opt-in. When opts.nac_level === 3 (or auto-detected from
925
- _validationTolerance.iframe_strict === 'error'), runtime
926
- enforces fail-closed on missing secret and verifies
927
- signatures on BOTH handshake_ack AND describe_result. */
928
- var nacLevel = opts.nac_level
929
- || (_validationTolerance.iframe_strict === 'error' ? 3 : 1);
930
-
931
- /* v2.0-rc3 (Claude T4-F2): the spec mandates HMAC chain on
932
- cross-origin agent-source events. We additionally require
933
- that handshake_ack and describe_result messages carry
934
- signature fields verifiable against our registered HMAC
935
- secret. Without this, a compromised trusted-origin (XSS in
936
- a vendor's CDN) can ride on the allowlist trust to inject
937
- manifest entries unchecked.
938
- v2.0-rc4: extended to describe_result + NAC-3 fail-closed. */
939
- return new Promise(function (resolve, reject) {
940
- var done = false;
941
- function listener(ev) {
942
- if (trusted.length && trusted.indexOf(ev.origin) < 0) {
943
- document.dispatchEvent(new CustomEvent('nac:iframe_untrusted', {
944
- detail: { origin: ev.origin }, bubbles: true
945
- }));
946
- return;
947
- }
948
- var d = ev.data;
949
- if (!d || d.ns !== ns) return;
950
- if (d.cmd === 'handshake_ack') {
951
- if (done) return;
952
- /* v2.0-rc4 (Mistral T7-F1): NAC-3 fail-closed. If no
953
- secret registered AND we are at NAC-3, reject the
954
- handshake. NAC-1/NAC-2 path keeps fail-open with
955
- warn (rc3 behaviour). */
956
- if (nacLevel >= 3 && !_hasSecrets()) {
957
- done = true;
958
- window.removeEventListener('message', listener);
959
- document.dispatchEvent(new CustomEvent('nac:iframe_no_secret_at_nac3', {
960
- detail: { iframeId: iframeId }, bubbles: true
961
- }));
962
- reject(new Error('iframe_no_secret_at_nac3'));
963
- return;
964
- }
965
- /* v2.0-rc3: verify signature on handshake_ack if HMAC
966
- secret registered. */
967
- if (_hasSecrets() && d.signature) {
968
- _verify_with_registered({ ns: d.ns, cmd: d.cmd, version: d.version, signature: d.signature })
969
- .then(function (ok) {
970
- if (!ok) {
971
- done = true;
972
- window.removeEventListener('message', listener);
973
- document.dispatchEvent(new CustomEvent('nac:iframe_signature_invalid', {
974
- detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
975
- }));
976
- reject(new Error('iframe_signature_invalid'));
977
- return;
978
- }
979
- _continueHandshakeAck();
980
- });
981
- return;
982
- }
983
- if (_hasSecrets() && !d.signature) {
984
- /* Secret registered but iframe did not sign -> at
985
- NAC-3 fail-closed; at lower levels emit warn and
986
- continue. */
987
- if (nacLevel >= 3) {
988
- done = true;
989
- window.removeEventListener('message', listener);
990
- document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
991
- detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
992
- }));
993
- reject(new Error('iframe_signature_missing'));
994
- return;
995
- }
996
- document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
997
- detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
998
- }));
999
- }
1000
- _continueHandshakeAck();
1001
-
1002
- function _continueHandshakeAck() {
1003
- done = true;
1004
- if (d.version && d.version.split('.')[0] !== '2') {
1005
- document.dispatchEvent(new CustomEvent('nac:iframe_version_mismatch', {
1006
- detail: { theirs: d.version, ours: '2.0' }, bubbles: true
1007
- }));
1008
- reject(new Error('iframe_version_mismatch'));
1009
- return;
1010
- }
1011
- window.removeEventListener('message', listener);
1012
- resolve({ iframeId: iframeId, version: d.version,
1013
- signed: !!d.signature, nac_level: nacLevel });
1014
- }
1015
- }
1016
- /* v2.0-rc4 (Mistral T4-F2.1): describe_result messages
1017
- ALSO must be HMAC-verified at NAC-3. The handshake
1018
- promise has already resolved by this point; this
1019
- listener stays installed for follow-up describe()
1020
- pulls. We emit events but cannot reject the promise
1021
- (already settled). */
1022
- if (d.cmd === 'describe_result') {
1023
- if (nacLevel >= 3 && !_hasSecrets()) {
1024
- document.dispatchEvent(new CustomEvent('nac:iframe_no_secret_at_nac3', {
1025
- detail: { iframeId: iframeId, message: 'describe_result' },
1026
- bubbles: true
1027
- }));
1028
- return;
1029
- }
1030
- if (_hasSecrets() && d.signature) {
1031
- _verify_with_registered({
1032
- ns: d.ns, cmd: d.cmd, manifest: d.manifest, signature: d.signature
1033
- }).then(function (ok) {
1034
- if (!ok) {
1035
- document.dispatchEvent(new CustomEvent('nac:iframe_signature_invalid', {
1036
- detail: { iframeId: iframeId, message: 'describe_result' },
1037
- bubbles: true
1038
- }));
1039
- return;
1040
- }
1041
- /* Verified: forward manifest to whoever subscribes. */
1042
- document.dispatchEvent(new CustomEvent('nac:iframe_describe_received', {
1043
- detail: { iframeId: iframeId, manifest: d.manifest }, bubbles: true
1044
- }));
1045
- });
1046
- return;
1047
- }
1048
- if (_hasSecrets() && !d.signature) {
1049
- document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
1050
- detail: { iframeId: iframeId, message: 'describe_result' }, bubbles: true
1051
- }));
1052
- if (nacLevel >= 3) return; /* drop unsigned at NAC-3 */
1053
- }
1054
- /* NAC-1/NAC-2 + no secret: forward manifest as-is. */
1055
- document.dispatchEvent(new CustomEvent('nac:iframe_describe_received', {
1056
- detail: { iframeId: iframeId, manifest: d.manifest }, bubbles: true
1057
- }));
1058
- }
1059
- }
1060
- window.addEventListener('message', listener);
1061
- iframeEl.contentWindow.postMessage(
1062
- { ns: ns, cmd: 'handshake', version: '2.0' },
1063
- trusted.length ? trusted[0] : '*'
1064
- );
1065
- setTimeout(function () {
1066
- if (!done) {
1067
- done = true;
1068
- window.removeEventListener('message', listener);
1069
- document.dispatchEvent(new CustomEvent('nac:iframe_handshake_timeout', {
1070
- detail: { iframeId: iframeId }, bubbles: true
1071
- }));
1072
- reject(new Error('iframe_handshake_timeout'));
1073
- }
1074
- }, timeout);
1075
- });
1076
- }
1077
-
1078
- /* ------------------------------------------------------------- virtual */
1079
-
1080
- var _virtuals = [];
1081
- function declareVirtual(spec) {
1082
- if (!spec || !spec.slug_pattern || typeof spec.resolver !== 'function') {
1083
- throw new Error('[NAC v2] declareVirtual requires {slug_pattern, count, resolver}');
1084
- }
1085
- _virtuals.push(spec);
1086
- return spec;
1087
- }
1088
- /* v2.0-rc3 (Claude T3.6 / DeepSeek T3.6): escape regex
1089
- metacharacters in the static parts of the pattern before
1090
- substituting {i}. Without this, `pipeline.runs.row.{i}` would
1091
- match `pipelineXrunsXrowX7` (because `.` is a regex wildcard);
1092
- a malicious URL or DOM-injected slug could hit arbitrary
1093
- pattern. */
1094
- function _escapeRegex(s) {
1095
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1096
- }
1097
- function _resolveVirtual(slug) {
1098
- for (var i = 0; i < _virtuals.length; i++) {
1099
- var v = _virtuals[i];
1100
- /* Split on {i} so we can escape the static parts. */
1101
- var parts = v.slug_pattern.split('{i}');
1102
- var pat = parts.map(_escapeRegex).join('(\\d+)');
1103
- var m = slug.match(new RegExp('^' + pat + '$'));
1104
- if (m) {
1105
- var idx = parseInt(m[1], 10);
1106
- var count = typeof v.count === 'function' ? v.count() : v.count;
1107
- if (idx >= 0 && idx < count) {
1108
- var t0 = performance.now();
1109
- var entry = v.resolver(idx);
1110
- var elapsed = performance.now() - t0;
1111
- if (elapsed > 50) {
1112
- document.dispatchEvent(new CustomEvent('nac:virtual_resolver_slow', {
1113
- detail: { slug: slug, elapsed_ms: elapsed }, bubbles: true
1114
- }));
1115
- }
1116
- return entry;
1117
- }
1118
- }
1119
- }
1120
- return null;
1121
- }
1122
-
1123
- /* ------------------------------------------------------------- ephemeral */
1124
-
1125
- var _ephemeralRing = [];
1126
- var _ephemeralOpts = null;
1127
- function captureEphemeral(opts) {
1128
- opts = opts || {};
1129
- _ephemeralOpts = {
1130
- duration_ms: opts.duration_ms || 3000,
1131
- ring_size: opts.ring_size || 100,
1132
- on_capture: opts.on_capture || null
1133
- };
1134
- var liveTimers = new Map();
1135
- var obs = new MutationObserver(function (muts) {
1136
- muts.forEach(function (m) {
1137
- m.addedNodes.forEach(function (n) {
1138
- if (n.nodeType === 1 && n.getAttribute && n.getAttribute('data-nac-id')) {
1139
- var slug = n.getAttribute('data-nac-id');
1140
- liveTimers.set(slug, { added_at: Date.now(), node: n });
1141
- }
1142
- });
1143
- m.removedNodes.forEach(function (n) {
1144
- if (n.nodeType === 1 && n.getAttribute && n.getAttribute('data-nac-id')) {
1145
- var slug = n.getAttribute('data-nac-id');
1146
- var live = liveTimers.get(slug);
1147
- if (live && (Date.now() - live.added_at) <= _ephemeralOpts.duration_ms) {
1148
- var capture = {
1149
- slug: slug,
1150
- role: n.getAttribute('role'),
1151
- label: n.textContent.trim().slice(0, 200),
1152
- added_at: live.added_at,
1153
- removed_at: Date.now(),
1154
- duration_ms: Date.now() - live.added_at
1155
- };
1156
- _ephemeralRing.push(capture);
1157
- if (_ephemeralRing.length > _ephemeralOpts.ring_size) {
1158
- _ephemeralRing.shift();
1159
- }
1160
- if (_ephemeralOpts.on_capture) _ephemeralOpts.on_capture(capture);
1161
- }
1162
- liveTimers.delete(slug);
1163
- }
1164
- });
1165
- });
1166
- });
1167
- obs.observe(document.body, { childList: true, subtree: true });
1168
- return obs;
1169
- }
1170
-
1171
- /* ------------------------------------------------------------- tenant */
1172
-
1173
- var _tenantPrefix = null;
1174
- function setTenantPrefix(slug) {
1175
- if (_tenantPrefix !== null) {
1176
- throw new Error('[NAC v2] tenant_prefix_locked: already set to ' + _tenantPrefix);
1177
- }
1178
- _validateLeaf(slug);
1179
- _tenantPrefix = slug;
1180
- }
1181
- function getTenantPrefix() { return _tenantPrefix; }
1182
-
1183
- /* ------------------------------------------------------------- describe v2 */
1184
-
1185
- /* Augment v1.9's describe() with v2 additions when called.
1186
- We don't replace the v1.9 function; we expose a new
1187
- `describe_v2()` and decorate the v1 result. */
1188
- /* v2.0-rc3 (Claude T3.1): track intermediate scope nodes so
1189
- describe_v2 can expose their label_i18n. Without this,
1190
- a catalog declares `shell.topbar` label but no consumer
1191
- reads it because the intermediate node has no element.
1192
-
1193
- v2.0-rc4 (Mistral T7-F2): the index grows monotonically with
1194
- unique scope paths created. Realistic SPA case is bounded
1195
- (~6 levels x ~few sections = O(N small)) but an SPA that
1196
- dynamically creates and discards scopes can leak. WeakMap
1197
- was rejected because keys are strings (paths), not objects.
1198
- Solution: NAC.gcIntermediateScopes(activePathSet) lets the
1199
- host prune entries no longer in use. Default behaviour:
1200
- no automatic GC; documented growth pattern. */
1201
- var _intermediateScopes = Object.create(null);
1202
-
1203
- /* v2.0-rc5 (spec sec 17): optional sitemap primitive. Hosts with
1204
- 50+ logical screens declare the full path catalog so the
1205
- intermediary can plan navigation to slugs not currently in
1206
- the visible tree. Authority separation is CRITICAL: the
1207
- sitemap is navigational metadata only, never a source of
1208
- can-operate truth. The visible tree (_scopes / v1 manifest)
1209
- remains the only authority for dispatch. */
1210
- var _sitemap = null; /* { paths: [...] } or null */
1211
-
1212
- function declareSitemap(spec) {
1213
- if (spec === null || typeof spec === 'undefined') {
1214
- _sitemap = null;
1215
- return;
1216
- }
1217
- if (typeof spec !== 'object' || !Array.isArray(spec.paths)) {
1218
- throw new Error('[NAC v2] declareSitemap: spec must be { paths: [...] }');
1219
- }
1220
- var seenSlugs = Object.create(null);
1221
- var clean = [];
1222
- for (var i = 0; i < spec.paths.length; i++) {
1223
- var p = spec.paths[i];
1224
- if (!p || typeof p.slug !== 'string' || p.slug === '') {
1225
- throw new Error('[NAC v2] declareSitemap: paths[' + i + '].slug required');
1226
- }
1227
- if (seenSlugs[p.slug]) {
1228
- throw new Error('[NAC v2] declareSitemap: duplicate slug "' + p.slug + '"');
1229
- }
1230
- seenSlugs[p.slug] = true;
1231
- var entry = { slug: p.slug };
1232
- if (p.label_i18n && typeof p.label_i18n === 'object') {
1233
- entry.label_i18n = p.label_i18n;
1234
- }
1235
- if (Array.isArray(p.affordance_to_navigate)) {
1236
- entry.affordance_to_navigate = p.affordance_to_navigate.slice();
1237
- }
1238
- if (Array.isArray(p.requires_permission)) {
1239
- entry.requires_permission = p.requires_permission.slice();
1240
- }
1241
- if (Array.isArray(p.tags)) {
1242
- entry.tags = p.tags.slice();
1243
- }
1244
- clean.push(entry);
1245
- }
1246
- _sitemap = { paths: clean };
1247
- }
1248
-
1249
- function getSitemap() {
1250
- if (!_sitemap) return null;
1251
- /* return a defensive shallow copy so callers cannot mutate
1252
- internal state */
1253
- return { paths: _sitemap.paths.slice() };
1254
- }
1255
-
1256
- /* Public GC API (rc4): the host passes a Set or array of path
1257
- strings that are still considered "active". Any entry in the
1258
- index whose path is NOT in that set gets removed. */
1259
- function gcIntermediateScopes(activePaths) {
1260
- if (!activePaths) {
1261
- /* No-arg form: clear ALL intermediate scopes. Use only when
1262
- tearing down the SPA / navigating to a totally new shell. */
1263
- _intermediateScopes = Object.create(null);
1264
- return 0;
1265
- }
1266
- var active = (typeof activePaths.has === 'function')
1267
- ? activePaths
1268
- : new Set(activePaths);
1269
- var removed = 0;
1270
- Object.keys(_intermediateScopes).forEach(function (k) {
1271
- if (!active.has(k)) {
1272
- delete _intermediateScopes[k];
1273
- removed++;
1274
- }
1275
- });
1276
- return removed;
1277
- }
1278
-
1279
- function describe_v2() {
1280
- var v1 = (typeof NAC.describe === 'function') ? NAC.describe() : { plugins: [] };
1281
- var scopeEntries = Object.keys(_scopes).map(function (k) {
1282
- var e = _scopes[k];
1283
- return {
1284
- slug: e.slug,
1285
- role: e.role,
1286
- intent: e.intent,
1287
- autoderived: e.autoderived || false,
1288
- adopted: e.adopted || false,
1289
- irreversible: e.irreversible || false,
1290
- parent_chain: e.parent_chain || null,
1291
- has_element: !!e.element
1292
- };
1293
- });
1294
- var intermediateScopes = Object.keys(_intermediateScopes).map(function (k) {
1295
- return {
1296
- slug: k,
1297
- depth: _intermediateScopes[k].depth,
1298
- label_i18n: _intermediateScopes[k].label_i18n,
1299
- is_intermediate: true
1300
- };
1301
- });
1302
- var virtual_summary = _virtuals.map(function (v) {
1303
- var count = typeof v.count === 'function' ? v.count() : v.count;
1304
- return { slug_pattern: v.slug_pattern, count: count };
1305
- });
1306
- /* v2.1 sec 18: surface every registered data-table so the
1307
- chatbot intermediary, RPA bot and test runner all see the
1308
- same snapshot. data_tables is [] when no host has called
1309
- registerDataTable(). */
1310
- var dataTables = (typeof NAC.__v2_dtSummariseAll === 'function')
1311
- ? NAC.__v2_dtSummariseAll()
1312
- : [];
1313
- return {
1314
- nac_version: '2.1.0-rc1',
1315
- timestamp: Date.now(),
1316
- tenant_prefix: _tenantPrefix,
1317
- v1_plugins: v1.plugins || [],
1318
- v2_scope_entries: scopeEntries,
1319
- v2_intermediate_scopes: intermediateScopes,
1320
- virtual: virtual_summary,
1321
- ephemeral_log: _ephemeralRing.slice(),
1322
- locale: _currentLocale,
1323
- supported_locales: _supported.slice(),
1324
- /* v2.0-rc5 (spec sec 17): null when host has not declared a
1325
- sitemap (small SPAs / demos); otherwise the path catalog.
1326
- Intermediaries treat this as PLANNING data, not authority. */
1327
- sitemap: _sitemap ? { paths: _sitemap.paths.slice() } : null,
1328
- /* v2.1 (spec sec 18): registered data-tables with their full
1329
- state. [] when no host has registered any. */
1330
- data_tables: dataTables
1331
- };
1332
- }
1333
-
1334
- /* ------------------------------------------------------------- validate v2 */
1335
-
1336
- function validate_global_v2(opts) {
1337
- opts = opts || {};
1338
- var findings = { errors: [], warnings: [] };
1339
- /* 2026-05-09 (Claude R6): drain runtime guard findings
1340
- FIRST, before any early-return, so security-relevant
1341
- events (script_override_claims_user, etc.) ALWAYS reach
1342
- the validator output regardless of i18n severity. */
1343
- for (var fi = 0; fi < _validatorFindings.length; fi++) {
1344
- var rf = _validatorFindings[fi];
1345
- var bkt = rf.severity === 'error' ? findings.errors : findings.warnings;
1346
- bkt.push({
1347
- code: rf.code,
1348
- severity: rf.severity,
1349
- timestamp: rf.timestamp,
1350
- note: rf.note
1351
- });
1352
- }
1353
- /* v2.0-rc2 (Grok T5-F1 + Mistral T5-F2): severity for missing-
1354
- locale findings now honours the tolerance setting. Default
1355
- at NAC-3 is 'warn'; hosts that need NAC-4-equivalent strict
1356
- mode opt in via set_validation_tolerance({i18n_strict:'error'})
1357
- OR pass opts.i18n_strict_severity explicitly. */
1358
- var severity = opts.i18n_strict_severity || _validationTolerance.i18n_strict;
1359
- if (severity === 'silent') return findings;
1360
- var bucket = severity === 'error' ? findings.errors : findings.warnings;
1361
-
1362
- if (opts.i18n_strict) {
1363
- Object.keys(_catalog).forEach(function (key) {
1364
- var entry = _catalog[key];
1365
- var missing = _supported.filter(function (loc) { return !entry[loc]; });
1366
- if (missing.length) {
1367
- bucket.push({
1368
- code: 'i18n_missing_locale',
1369
- key: key,
1370
- missing: missing,
1371
- severity: severity
1372
- });
1373
- }
1374
- Object.keys(entry).forEach(function (loc) {
1375
- if (_supported.indexOf(loc) < 0) {
1376
- /* invalid_locale always error: catalog has nonsense key */
1377
- findings.errors.push({
1378
- code: 'i18n_invalid_locale',
1379
- key: key,
1380
- locale: loc
1381
- });
1382
- }
1383
- /* empty_string honours severity tolerance too */
1384
- if (typeof entry[loc] === 'string' && entry[loc].length === 0) {
1385
- bucket.push({ code: 'i18n_string_empty', key: key, locale: loc, severity: severity });
1386
- }
1387
- if (typeof entry[loc] === 'string' && entry[loc].length > 1000) {
1388
- findings.warnings.push({ code: 'i18n_string_too_long', key: key, locale: loc });
1389
- }
1390
- });
1391
- });
1392
- /* Mono-locale autoderived warn (always warn -- this is a
1393
- drift signal, not a correctness signal). */
1394
- Object.keys(_scopes).forEach(function (slug) {
1395
- if (_scopes[slug].autoderived) {
1396
- findings.warnings.push({ code: 'i18n_mono_locale_autoderived', slug: slug });
1397
- }
1398
- });
1399
- }
1400
-
1401
- /* v2.0-rc4 (Claude T8.2 codification): at NAC-3, autoderived
1402
- data-nac-action is SHOULD with REQUIRED fallback. Emit
1403
- data_nac_action_autoderived per scope where the action was
1404
- inferred rather than declared. Severity follows
1405
- _validationTolerance.autoderived_action (default warn). */
1406
- var autodSev = opts.autoderived_action_severity
1407
- || _validationTolerance.autoderived_action;
1408
- if (autodSev !== 'silent') {
1409
- var autodBucket = autodSev === 'error' ? findings.errors : findings.warnings;
1410
- Object.keys(_scopes).forEach(function (slug) {
1411
- var entry = _scopes[slug];
1412
- if (entry.element && !entry.element.hasAttribute('data-nac-action')) {
1413
- /* Only emit for elements that DO have a registered
1414
- intent but lack the explicit data-nac-action attr.
1415
- autoRegister-only path: the slug exists in _scopes
1416
- but the host did not declare data-nac-action. */
1417
- if (entry.autoderived || entry.adopted) {
1418
- autodBucket.push({
1419
- code: 'data_nac_action_autoderived',
1420
- slug: slug,
1421
- severity: autodSev
1422
- });
1423
- }
1424
- }
1425
- });
1426
- }
1427
- return findings;
1428
- }
1429
-
1430
- /* ------------------------------------------------------------- exports */
1431
-
1432
- /* Attach v2 surface to NAC namespace without overwriting v1.9 */
1433
- NAC.scope = scope;
1434
- NAC.autoRegister = autoRegister;
1435
- NAC.adopt = adopt;
1436
- NAC.bridgeShadowRoot = bridgeShadowRoot;
1437
- NAC.bridgeIframe = bridgeIframe;
1438
- NAC.declareVirtual = declareVirtual;
1439
- NAC.captureEphemeral = captureEphemeral;
1440
- NAC.setTenantPrefix = setTenantPrefix;
1441
- NAC.getTenantPrefix = getTenantPrefix;
1442
- NAC.attestUserGesture = attestUserGesture;
1443
- NAC.setMobileWebViewAttestation = setMobileWebViewAttestation;
1444
- NAC.t = t;
1445
- NAC.registerCatalog = registerCatalog;
1446
- NAC.locale = locale;
1447
- NAC.setSupportedLocales = setSupportedLocales;
1448
- NAC.setRTLLocales = setRTLLocales;
1449
- NAC.setAutoRTL = setAutoRTL;
1450
- NAC.set_provenance_secret = set_provenance_secret;
1451
- NAC.set_perf_tolerance = set_perf_tolerance;
1452
- NAC.get_perf_tolerance = get_perf_tolerance;
1453
- NAC.set_validation_tolerance = set_validation_tolerance;
1454
- NAC.get_validation_tolerance = get_validation_tolerance;
1455
- NAC.describe_v2 = describe_v2;
1456
- NAC.validate_global_v2 = validate_global_v2;
1457
- NAC.gcIntermediateScopes = gcIntermediateScopes;
1458
- NAC.declareSitemap = declareSitemap;
1459
- NAC.getSitemap = getSitemap;
1460
-
1461
- /* Convenience: expose internals for tests */
1462
- NAC.__v2 = {
1463
- SUPPORTED_LOCALES_DEFAULT: SUPPORTED_LOCALES_DEFAULT,
1464
- SEPARATOR: SEPARATOR,
1465
- MAX_DEPTH: MAX_DEPTH,
1466
- _scopes: _scopes,
1467
- _catalog: _catalog,
1468
- _virtuals: _virtuals,
1469
- _ephemeralRing: _ephemeralRing
1470
- };
1471
-
1472
- /* v2.0-rc3 (Claude T6-F2): warm SubtleCrypto's HMAC sign path
1473
- at boot so the cold-start cost is paid once, not at first
1474
- agent action. Best-effort: fails silently when no secret is
1475
- registered yet (which is fine -- adopters that wire HMAC
1476
- register the secret at boot). */
1477
- function _warmCrypto() {
1478
- if (typeof NAC.sign_provenance !== 'function') return;
1479
- if (!_provenanceSecrets[0]) return;
1480
- try {
1481
- NAC.sign_provenance({ _warmup: true, ts: Date.now() }, _provenanceSecrets[0])
1482
- .catch(function () {}); /* silently swallow warmup errors */
1483
- } catch (_) {}
1484
- }
1485
- /* Defer warm to next tick so the secret-registration call has a
1486
- chance to land first. Hosts that register the secret AFTER
1487
- boot can manually call NAC.set_provenance_secret() which
1488
- re-warms. */
1489
- setTimeout(_warmCrypto, 0);
1490
-
1491
- /* ------------------------------------------------------------- v2.1 data-table primitive (spec sec 18) */
1492
- /* See docs/V2_1_DATA_TABLE_GUIDE.md for the adopter walk-through.
1493
- Authority separation: the runtime owns the in-memory state,
1494
- the host owns persistence (commit handler does the HTTP/DB
1495
- write). All operator classes (user, agent, bot) use the same
1496
- dt_* API; the `by` discriminator on every emitted event lets
1497
- audit pipelines attribute changes per source.type contract. */
1498
-
1499
- var _dataTables = Object.create(null);
1500
- /* { table_id -> {
1501
- schema: {...}, // immutable post-register
1502
- current_rows: [...], // collection: array of objects
1503
- current_cells: [...], // matrix: array of {row, col, value}
1504
- initial_state: deep_copy, // for discard()
1505
- selected: Set<row_id>, // collection only
1506
- modified: bool,
1507
- computed_fns: { col_key -> fn(row, allRows) } } } */
1508
-
1509
- function _dtDeepCopy(o) {
1510
- /* JSON-roundtrip: cheap, preserves the primitive shapes our
1511
- cells carry (string/number/boolean/null/array/plain object).
1512
- If a host puts Date/Map in a cell we reject at register time. */
1513
- return o === undefined ? undefined : JSON.parse(JSON.stringify(o));
1514
- }
1515
-
1516
- function _dtEmit(name, detail) {
1517
- document.dispatchEvent(new CustomEvent(name, { detail: detail, bubbles: true }));
1518
- }
1519
-
1520
- function _dtBy() {
1521
- /* Detect operator class. If the call originated from a recent
1522
- attested user gesture, by='user'; otherwise by='agent'. The
1523
- gesture buffer (rc3 T4-F1) is the source of truth. */
1524
- try {
1525
- if (typeof NAC.attestUserGesture === 'function') {
1526
- var gesture = NAC._readGestureAttested
1527
- ? NAC._readGestureAttested()
1528
- : null;
1529
- if (gesture && gesture.attested) return 'user';
1530
- }
1531
- } catch (_) {}
1532
- return 'agent';
1533
- }
1534
-
1535
- function _dtCheckColumnValue(col, value) {
1536
- if (value === null || value === undefined) {
1537
- if (col.required) return { ok: false, error: 'required_missing' };
1538
- return { ok: true };
1539
- }
1540
- var t = col.type;
1541
- if (t === 'number' || t === 'currency') {
1542
- if (typeof value !== 'number' || !isFinite(value)) {
1543
- return { ok: false, error: 'invalid_type:expected_number' };
1544
- }
1545
- if (typeof col.min === 'number' && value < col.min) {
1546
- return { ok: false, error: 'below_min:' + col.min };
1547
- }
1548
- if (typeof col.max === 'number' && value > col.max) {
1549
- return { ok: false, error: 'above_max:' + col.max };
1550
- }
1551
- } else if (t === 'boolean') {
1552
- if (typeof value !== 'boolean') {
1553
- return { ok: false, error: 'invalid_type:expected_boolean' };
1554
- }
1555
- } else if (t === 'select') {
1556
- var opts = col.options || [];
1557
- var ok = opts.some(function (o) { return (o.value !== undefined ? o.value : o) === value; });
1558
- if (!ok) return { ok: false, error: 'invalid_option' };
1559
- } else if (t === 'date') {
1560
- if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}/.test(value)) {
1561
- return { ok: false, error: 'invalid_type:expected_date_iso' };
1562
- }
1563
- } else {
1564
- /* text and others: just require string-like */
1565
- if (typeof value !== 'string' && typeof value !== 'number') {
1566
- return { ok: false, error: 'invalid_type:expected_text' };
1567
- }
1568
- }
1569
- return { ok: true };
1570
- }
1571
-
1572
- function _dtRecomputeRow(table, row) {
1573
- /* Recompute every column whose `computed:true` and a fn is
1574
- registered. */
1575
- var changed = false;
1576
- table.schema.columns.forEach(function (col) {
1577
- if (!col.computed) return;
1578
- var fn = table.computed_fns[col.key];
1579
- if (!fn) return;
1580
- try {
1581
- var newVal = fn(row, table.current_rows);
1582
- if (row[col.key] !== newVal) {
1583
- row[col.key] = newVal;
1584
- changed = true;
1585
- }
1586
- } catch (_) { /* swallow; computed err leaves stale value */ }
1587
- });
1588
- return changed;
1589
- }
1590
-
1591
- function _dtRecomputeAggregates(table, prevAggs) {
1592
- var aggs = {};
1593
- var defs = table.schema.aggregates || {};
1594
- Object.keys(defs).forEach(function (aggKey) {
1595
- var cols = defs[aggKey] || [];
1596
- aggs[aggKey] = {};
1597
- cols.forEach(function (colKey) {
1598
- if (colKey === '*') {
1599
- aggs[aggKey]['*'] = aggKey === 'count' ? table.current_rows.length : 0;
1600
- return;
1601
- }
1602
- var values = table.current_rows
1603
- .map(function (r) { return r[colKey]; })
1604
- .filter(function (v) { return typeof v === 'number' && isFinite(v); });
1605
- if (aggKey === 'sum') {
1606
- aggs[aggKey][colKey] = values.reduce(function (s, v) { return s + v; }, 0);
1607
- } else if (aggKey === 'avg') {
1608
- aggs[aggKey][colKey] = values.length
1609
- ? values.reduce(function (s, v) { return s + v; }, 0) / values.length
1610
- : 0;
1611
- } else if (aggKey === 'count') {
1612
- aggs[aggKey][colKey] = values.length;
1613
- } else if (aggKey === 'min') {
1614
- aggs[aggKey][colKey] = values.length ? Math.min.apply(null, values) : null;
1615
- } else if (aggKey === 'max') {
1616
- aggs[aggKey][colKey] = values.length ? Math.max.apply(null, values) : null;
1617
- }
1618
- });
1619
- });
1620
- /* Emit per (agg, column) pair when changed. */
1621
- if (prevAggs) {
1622
- Object.keys(aggs).forEach(function (aggKey) {
1623
- Object.keys(aggs[aggKey]).forEach(function (colKey) {
1624
- var oldV = (prevAggs[aggKey] || {})[colKey];
1625
- var newV = aggs[aggKey][colKey];
1626
- if (oldV !== newV) {
1627
- _dtEmit('nac:dt:aggregate_changed', {
1628
- table_id: table.schema.table_id,
1629
- agg_key: aggKey, column: colKey, old: oldV, new: newV
1630
- });
1631
- }
1632
- });
1633
- });
1634
- }
1635
- return aggs;
1636
- }
1637
-
1638
- function _dtGenRowId(table) {
1639
- var prefix = (table.schema.row_id_field || 'r').slice(0, 1).toUpperCase();
1640
- var n = table.current_rows.length + 1;
1641
- var candidate;
1642
- do {
1643
- candidate = prefix + n;
1644
- n++;
1645
- } while (table.current_rows.some(function (r) { return r[table.schema.row_id_field] === candidate; }));
1646
- return candidate;
1647
- }
1648
-
1649
- function registerDataTable(spec) {
1650
- if (!spec || typeof spec !== 'object') {
1651
- throw new Error('[NAC v2.1] registerDataTable: spec must be an object');
1652
- }
1653
- if (typeof spec.table_id !== 'string' || !spec.table_id) {
1654
- throw new Error('[NAC v2.1] registerDataTable: table_id required');
1655
- }
1656
- if (_dataTables[spec.table_id]) {
1657
- throw new Error('[NAC v2.1] registerDataTable: table_id "'
1658
- + spec.table_id + '" already registered');
1659
- }
1660
- var subkind = spec.subkind || 'collection';
1661
- if (['collection', 'matrix', 'readonly'].indexOf(subkind) < 0) {
1662
- throw new Error('[NAC v2.1] registerDataTable: invalid subkind "' + subkind + '"');
1663
- }
1664
- /* Subkind-specific validation. */
1665
- if (subkind === 'matrix') {
1666
- if (!spec.row_axis || !spec.column_axis) {
1667
- throw new Error('[NAC v2.1] registerDataTable: matrix requires row_axis + column_axis');
1668
- }
1669
- } else {
1670
- if (!Array.isArray(spec.columns) || !spec.columns.length) {
1671
- throw new Error('[NAC v2.1] registerDataTable: collection/readonly requires columns[]');
1672
- }
1673
- if (!spec.row_id_field) {
1674
- throw new Error('[NAC v2.1] registerDataTable: row_id_field required for collection');
1675
- }
1676
- }
1677
- var schema = {
1678
- table_id: spec.table_id,
1679
- scope_owner: spec.scope_owner || null,
1680
- subkind: subkind,
1681
- transactional: spec.transactional !== false,
1682
- row_id_field: spec.row_id_field || null,
1683
- columns: spec.columns || [],
1684
- row_axis: spec.row_axis || null,
1685
- column_axis: spec.column_axis || null,
1686
- cell_type: spec.cell_type || 'boolean',
1687
- supports: spec.supports || [],
1688
- selection_mode: spec.selection_mode || 'none',
1689
- aggregates: spec.aggregates || {},
1690
- validators: spec.validators || []
1691
- };
1692
- var table = {
1693
- schema: schema,
1694
- current_rows: subkind === 'matrix' ? [] : (_dtDeepCopy(spec.initial_rows) || []),
1695
- current_cells: subkind === 'matrix' ? (_dtDeepCopy(spec.initial_cells) || []) : [],
1696
- initial_state: subkind === 'matrix'
1697
- ? { cells: _dtDeepCopy(spec.initial_cells) || [] }
1698
- : { rows: _dtDeepCopy(spec.initial_rows) || [] },
1699
- selected: new Set(),
1700
- modified: false,
1701
- computed_fns: Object.create(null),
1702
- _aggregates_cache: null
1703
- };
1704
- _dataTables[spec.table_id] = table;
1705
- table._aggregates_cache = _dtRecomputeAggregates(table, null);
1706
- _dtEmit('nac:dt:registered', { table_id: spec.table_id, schema: schema });
1707
- return spec.table_id;
1708
- }
1709
-
1710
- function unregisterDataTable(table_id) {
1711
- if (_dataTables[table_id]) {
1712
- delete _dataTables[table_id];
1713
- _dtEmit('nac:dt:unregistered', { table_id: table_id });
1714
- }
1715
- }
1716
-
1717
- function registerDataTableComputed(table_id, column_key, fn) {
1718
- var t = _dataTables[table_id];
1719
- if (!t) throw new Error('[NAC v2.1] data-table not registered: ' + table_id);
1720
- if (typeof fn !== 'function') {
1721
- throw new Error('[NAC v2.1] computed fn must be a function');
1722
- }
1723
- t.computed_fns[column_key] = fn;
1724
- /* Recompute now so newly-attached fns reflect on existing rows. */
1725
- t.current_rows.forEach(function (row) { _dtRecomputeRow(t, row); });
1726
- var prev = t._aggregates_cache;
1727
- t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1728
- }
1729
-
1730
- function dt_state(table_id) {
1731
- var t = _dataTables[table_id];
1732
- if (!t) return null;
1733
- if (t.schema.subkind === 'matrix') {
1734
- return {
1735
- cells: _dtDeepCopy(t.current_cells),
1736
- modified: t.modified,
1737
- valid: dt_validate(table_id).valid
1738
- };
1739
- }
1740
- return {
1741
- rows: _dtDeepCopy(t.current_rows),
1742
- aggregates: _dtDeepCopy(t._aggregates_cache),
1743
- modified: t.modified,
1744
- valid: dt_validate(table_id).valid,
1745
- selected_count: t.selected.size,
1746
- selected_ids: Array.from(t.selected)
1747
- };
1748
- }
1749
-
1750
- function dt_add_row(table_id, valuesByColumn) {
1751
- var t = _dataTables[table_id];
1752
- if (!t) throw new Error('[NAC v2.1] data-table not registered: ' + table_id);
1753
- if (t.schema.subkind === 'matrix') {
1754
- throw new Error('[NAC v2.1] add_row not applicable to matrix');
1755
- }
1756
- if (t.schema.subkind === 'readonly') {
1757
- throw new Error('[NAC v2.1] add_row not allowed on readonly');
1758
- }
1759
- var values = valuesByColumn || {};
1760
- var row = {};
1761
- t.schema.columns.forEach(function (col) {
1762
- if (col.key === t.schema.row_id_field) return;
1763
- if (Object.prototype.hasOwnProperty.call(values, col.key)) {
1764
- row[col.key] = values[col.key];
1765
- } else if (col.required && !col.computed) {
1766
- /* required but missing -- caller must provide */
1767
- }
1768
- });
1769
- /* Row id: caller-provided OR auto-generated. */
1770
- var rowId = values[t.schema.row_id_field];
1771
- if (!rowId) rowId = _dtGenRowId(t);
1772
- row[t.schema.row_id_field] = rowId;
1773
- /* Validate every provided column. */
1774
- var fail = null;
1775
- t.schema.columns.forEach(function (col) {
1776
- if (fail) return;
1777
- if (col.computed) return;
1778
- var v = row[col.key];
1779
- var check = _dtCheckColumnValue(col, v);
1780
- if (!check.ok) fail = { column: col.key, error: check.error };
1781
- });
1782
- if (fail) {
1783
- _dtEmit('nac:dt:validation_failed', {
1784
- table_id: t.schema.table_id,
1785
- errors: [{ code: 'add_row_invalid', column: fail.column, message_i18n: { en: fail.error } }]
1786
- });
1787
- return { row_id: null, ok: false, error: fail.error, column: fail.column };
1788
- }
1789
- t.current_rows.push(row);
1790
- _dtRecomputeRow(t, row);
1791
- var prev = t._aggregates_cache;
1792
- t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1793
- t.modified = true;
1794
- _dtEmit('nac:dt:row_added', {
1795
- table_id: t.schema.table_id, row: _dtDeepCopy(row), by: _dtBy()
1796
- });
1797
- return { row_id: rowId, ok: true };
1798
- }
1799
-
1800
- function dt_remove_row(table_id, row_id) {
1801
- var t = _dataTables[table_id];
1802
- if (!t || t.schema.subkind === 'matrix' || t.schema.subkind === 'readonly') return;
1803
- var idx = -1;
1804
- for (var i = 0; i < t.current_rows.length; i++) {
1805
- if (t.current_rows[i][t.schema.row_id_field] === row_id) { idx = i; break; }
1806
- }
1807
- if (idx < 0) return;
1808
- t.current_rows.splice(idx, 1);
1809
- t.selected.delete(row_id);
1810
- var prev = t._aggregates_cache;
1811
- t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1812
- t.modified = true;
1813
- _dtEmit('nac:dt:row_removed', {
1814
- table_id: t.schema.table_id, row_id: row_id, by: _dtBy()
1815
- });
1816
- }
1817
-
1818
- function dt_edit_cell(table_id, row_id, column_key, value) {
1819
- var t = _dataTables[table_id];
1820
- if (!t) return { ok: false, error: 'table_not_registered' };
1821
- if (t.schema.subkind === 'matrix') {
1822
- return { ok: false, error: 'use_dt_set_cell_for_matrix' };
1823
- }
1824
- if (t.schema.subkind === 'readonly') return { ok: false, error: 'readonly' };
1825
- var col = t.schema.columns.filter(function (c) { return c.key === column_key; })[0];
1826
- if (!col) return { ok: false, error: 'column_not_found' };
1827
- /* computed wins over editable -- a column declared
1828
- `computed:true` is implicitly non-editable even if the
1829
- host forgets to set editable:false. Spec sec 18.4 ordering. */
1830
- if (col.computed) return { ok: false, error: 'computed_column' };
1831
- if (!col.editable) return { ok: false, error: 'column_not_editable' };
1832
- var check = _dtCheckColumnValue(col, value);
1833
- if (!check.ok) {
1834
- _dtEmit('nac:dt:validation_failed', {
1835
- table_id: t.schema.table_id,
1836
- errors: [{ code: 'edit_cell_invalid', row_id: row_id, column: column_key,
1837
- message_i18n: { en: check.error } }]
1838
- });
1839
- return { ok: false, error: check.error };
1840
- }
1841
- var row = t.current_rows.filter(function (r) {
1842
- return r[t.schema.row_id_field] === row_id;
1843
- })[0];
1844
- if (!row) return { ok: false, error: 'row_not_found' };
1845
- var oldVal = row[column_key];
1846
- if (oldVal === value) return { ok: true, unchanged: true };
1847
- row[column_key] = value;
1848
- _dtRecomputeRow(t, row);
1849
- var prev = t._aggregates_cache;
1850
- t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1851
- t.modified = true;
1852
- _dtEmit('nac:dt:cell_edited', {
1853
- table_id: t.schema.table_id,
1854
- row_id: row_id, column: column_key,
1855
- old: oldVal, new: value, by: _dtBy()
1856
- });
1857
- return { ok: true };
1858
- }
1859
-
1860
- function dt_read_aggregate(table_id, agg_key, column_key) {
1861
- var t = _dataTables[table_id];
1862
- if (!t) return null;
1863
- if (!t._aggregates_cache || !t._aggregates_cache[agg_key]) return null;
1864
- var v = t._aggregates_cache[agg_key][column_key];
1865
- return v === undefined ? null : v;
1866
- }
1867
-
1868
- function dt_validate(table_id) {
1869
- var t = _dataTables[table_id];
1870
- if (!t) return { valid: false, errors: [{ code: 'table_not_registered' }] };
1871
- var errors = [];
1872
- /* Per-row validators. */
1873
- (t.schema.validators || []).forEach(function (v) {
1874
- if (v.kind !== 'row') return;
1875
- t.current_rows.forEach(function (row) {
1876
- var cellVal = row[v.column];
1877
- var ok = _dtCheckOp(cellVal, v.op, v.value);
1878
- if (!ok) errors.push({
1879
- code: v.code, row_id: row[t.schema.row_id_field],
1880
- column: v.column, message_i18n: v.message_i18n || null
1881
- });
1882
- });
1883
- });
1884
- /* Table-level validators. */
1885
- (t.schema.validators || []).forEach(function (v) {
1886
- if (v.kind !== 'table') return;
1887
- if (v.unique_columns) {
1888
- var seen = Object.create(null);
1889
- t.current_rows.forEach(function (row) {
1890
- var key = v.unique_columns.map(function (c) { return row[c]; }).join('|');
1891
- if (seen[key]) {
1892
- errors.push({
1893
- code: v.code, row_id: row[t.schema.row_id_field],
1894
- message_i18n: v.message_i18n || null
1895
- });
1896
- }
1897
- seen[key] = true;
1898
- });
1899
- }
1900
- if (typeof v.min_rows === 'number' && t.current_rows.length < v.min_rows) {
1901
- errors.push({ code: v.code, message_i18n: v.message_i18n || null });
1902
- }
1903
- if (typeof v.max_rows === 'number' && t.current_rows.length > v.max_rows) {
1904
- errors.push({ code: v.code, message_i18n: v.message_i18n || null });
1905
- }
1906
- });
1907
- /* Required-column validator (implicit). */
1908
- t.schema.columns.forEach(function (col) {
1909
- if (!col.required || col.computed) return;
1910
- t.current_rows.forEach(function (row) {
1911
- var v = row[col.key];
1912
- if (v === null || v === undefined || v === '') {
1913
- errors.push({
1914
- code: 'required_missing', row_id: row[t.schema.row_id_field],
1915
- column: col.key, message_i18n: { en: 'Required column missing' }
1916
- });
1917
- }
1918
- });
1919
- });
1920
- return { valid: errors.length === 0, errors: errors };
1921
- }
1922
-
1923
- function _dtCheckOp(cellVal, op, value) {
1924
- switch (op) {
1925
- case 'gt': return typeof cellVal === 'number' && cellVal > value;
1926
- case 'gte': return typeof cellVal === 'number' && cellVal >= value;
1927
- case 'lt': return typeof cellVal === 'number' && cellVal < value;
1928
- case 'lte': return typeof cellVal === 'number' && cellVal <= value;
1929
- case 'eq': return cellVal === value;
1930
- case 'neq': return cellVal !== value;
1931
- case 'in': return Array.isArray(value) && value.indexOf(cellVal) >= 0;
1932
- case 'matches': return typeof cellVal === 'string' && new RegExp(value).test(cellVal);
1933
- default: return true;
1934
- }
1935
- }
1936
-
1937
- function dt_select(table_id, target) {
1938
- var t = _dataTables[table_id];
1939
- if (!t || t.schema.subkind === 'matrix') return { selected_count: 0 };
1940
- var ids = [];
1941
- if (target === null || target === 'none') {
1942
- ids = [];
1943
- } else if (target === 'all' || target === 'visible') {
1944
- ids = t.current_rows.map(function (r) { return r[t.schema.row_id_field]; });
1945
- } else if (Array.isArray(target)) {
1946
- ids = target.slice();
1947
- } else if (target && target.column && target.op) {
1948
- ids = t.current_rows
1949
- .filter(function (r) { return _dtCheckOp(r[target.column], target.op, target.value); })
1950
- .map(function (r) { return r[t.schema.row_id_field]; });
1951
- } else if (typeof target === 'string') {
1952
- ids = [target];
1953
- }
1954
- t.selected = new Set(ids);
1955
- _dtEmit('nac:dt:selection_changed', {
1956
- table_id: t.schema.table_id,
1957
- selected_count: t.selected.size,
1958
- selected_ids: Array.from(t.selected)
1959
- });
1960
- return { selected_count: t.selected.size };
1961
- }
1962
-
1963
- function dt_set_cell(table_id, row_slug, col_slug, value) {
1964
- var t = _dataTables[table_id];
1965
- if (!t) return { ok: false, error: 'table_not_registered' };
1966
- if (t.schema.subkind !== 'matrix') {
1967
- return { ok: false, error: 'use_dt_edit_cell_for_collection' };
1968
- }
1969
- /* Validate row/col exist on the axes. */
1970
- var rowKnown = (t.schema.row_axis.values || [])
1971
- .some(function (r) { return r.slug === row_slug; });
1972
- var colKnown = (t.schema.column_axis.values || [])
1973
- .some(function (c) { return c.slug === col_slug; });
1974
- if (!rowKnown) return { ok: false, error: 'row_not_in_axis' };
1975
- if (!colKnown) return { ok: false, error: 'col_not_in_axis' };
1976
- var existing = null;
1977
- for (var i = 0; i < t.current_cells.length; i++) {
1978
- if (t.current_cells[i].row === row_slug && t.current_cells[i].col === col_slug) {
1979
- existing = t.current_cells[i]; break;
1980
- }
1981
- }
1982
- var oldVal = existing ? existing.value : undefined;
1983
- if (oldVal === value) return { ok: true, unchanged: true };
1984
- if (existing) {
1985
- existing.value = value;
1986
- } else {
1987
- t.current_cells.push({ row: row_slug, col: col_slug, value: value });
1988
- }
1989
- t.modified = true;
1990
- _dtEmit('nac:dt:matrix_cell_set', {
1991
- table_id: t.schema.table_id,
1992
- row: row_slug, col: col_slug, old: oldVal, new: value, by: _dtBy()
1993
- });
1994
- return { ok: true };
1995
- }
1996
-
1997
- function dt_get_cell(table_id, row_slug, col_slug) {
1998
- var t = _dataTables[table_id];
1999
- if (!t || t.schema.subkind !== 'matrix') return undefined;
2000
- for (var i = 0; i < t.current_cells.length; i++) {
2001
- if (t.current_cells[i].row === row_slug && t.current_cells[i].col === col_slug) {
2002
- return t.current_cells[i].value;
2003
- }
2004
- }
2005
- return undefined;
2006
- }
2007
-
2008
- function dt_commit(table_id) {
2009
- var t = _dataTables[table_id];
2010
- if (!t) return { ok: false, error: 'table_not_registered' };
2011
- var v = dt_validate(table_id);
2012
- if (!v.valid) {
2013
- _dtEmit('nac:dt:validation_failed', {
2014
- table_id: t.schema.table_id, errors: v.errors
2015
- });
2016
- return { ok: false, errors: v.errors };
2017
- }
2018
- /* Build audit diff vs initial_state. */
2019
- var initial = t.initial_state;
2020
- var finalState = t.schema.subkind === 'matrix'
2021
- ? { cells: _dtDeepCopy(t.current_cells) }
2022
- : { rows: _dtDeepCopy(t.current_rows) };
2023
- /* Reset modified + replace initial_state so a subsequent
2024
- discard would revert to THIS state, not the original. */
2025
- t.initial_state = _dtDeepCopy(finalState);
2026
- t.modified = false;
2027
- _dtEmit('nac:dt:committed', {
2028
- table_id: t.schema.table_id,
2029
- final_state: finalState,
2030
- audit_diff: { initial: initial, final: finalState }
2031
- });
2032
- return { ok: true, final_state: finalState };
2033
- }
2034
-
2035
- function dt_discard(table_id) {
2036
- var t = _dataTables[table_id];
2037
- if (!t) return;
2038
- if (t.schema.subkind === 'matrix') {
2039
- t.current_cells = _dtDeepCopy(t.initial_state.cells) || [];
2040
- } else {
2041
- t.current_rows = _dtDeepCopy(t.initial_state.rows) || [];
2042
- }
2043
- t.selected.clear();
2044
- var prev = t._aggregates_cache;
2045
- t._aggregates_cache = _dtRecomputeAggregates(t, prev);
2046
- t.modified = false;
2047
- _dtEmit('nac:dt:discarded', { table_id: t.schema.table_id });
2048
- }
2049
-
2050
- /* describe_v2() extension: surface every registered data-table. */
2051
- function _dtSummariseAll() {
2052
- var out = [];
2053
- Object.keys(_dataTables).forEach(function (id) {
2054
- var t = _dataTables[id];
2055
- out.push({
2056
- table_id: id,
2057
- scope_owner: t.schema.scope_owner,
2058
- subkind: t.schema.subkind,
2059
- schema: {
2060
- columns: t.schema.columns,
2061
- row_axis: t.schema.row_axis,
2062
- column_axis: t.schema.column_axis,
2063
- supports: t.schema.supports,
2064
- aggregates: t.schema.aggregates,
2065
- selection_mode: t.schema.selection_mode,
2066
- row_id_field: t.schema.row_id_field
2067
- },
2068
- current_state: dt_state(id)
2069
- });
2070
- });
2071
- return out;
2072
- }
2073
-
2074
- /* Exports for v2.1 data-table primitive. */
2075
- NAC.registerDataTable = registerDataTable;
2076
- NAC.unregisterDataTable = unregisterDataTable;
2077
- NAC.registerDataTableComputed = registerDataTableComputed;
2078
- NAC.dt_state = dt_state;
2079
- NAC.dt_add_row = dt_add_row;
2080
- NAC.dt_remove_row = dt_remove_row;
2081
- NAC.dt_edit_cell = dt_edit_cell;
2082
- NAC.dt_read_aggregate = dt_read_aggregate;
2083
- NAC.dt_validate = dt_validate;
2084
- NAC.dt_select = dt_select;
2085
- NAC.dt_set_cell = dt_set_cell;
2086
- NAC.dt_get_cell = dt_get_cell;
2087
- NAC.dt_commit = dt_commit;
2088
- NAC.dt_discard = dt_discard;
2089
- /* Exposed for tests + describe_v2 extension. */
2090
- NAC.__v2_dataTables = _dataTables;
2091
- NAC.__v2_dtSummariseAll = _dtSummariseAll;
2092
-
2093
- /* Bump version constants */
2094
- NAC.version_v2 = '2.1.0-rc1';
2095
- NAC.spec_version_v2 = '2.1';
2096
-
2097
- /* v2.2.1: guard browser-only dispatch so this bundle is importable
2098
- in Node / SSR / test contexts. */
2099
- if (typeof document !== 'undefined') {
2100
- document.dispatchEvent(new CustomEvent('nac:v2_installed', {
2101
- detail: { version: '2.0.0' }, bubbles: true
2102
- }));
2103
- }
2104
- })(typeof window !== 'undefined' ? window : globalThis);
3
+ /* ===============================================================
4
+ nac-v2-extensions.js -- NAC v2.0 additive extensions to v1.9
5
+ ---------------------------------------------------------------
6
+ Strict superset: this file LOADS AFTER nac.js v1.9.0 and ATTACHES
7
+ the v2.0 primitives onto window.NAC without modifying the v1.9
8
+ surface. Every v1.9 client keeps working unchanged.
9
+
10
+ Provides:
11
+ - NAC.scope(spec) hierarchical constructor
12
+ - NAC.autoRegister(el, opts) DOM-driven registration
13
+ - NAC.adopt(rule) third-party non-compliant
14
+ - NAC.bridgeShadowRoot(host) Shadow DOM bridge
15
+ - NAC.bridgeIframe(iframeEl, opts) same-vendor iframe bridge
16
+ - NAC.declareVirtual(spec) virtualized lists
17
+ - NAC.captureEphemeral(opts) transient UI capture
18
+ - NAC.setTenantPrefix(slug) multi-tenant naming
19
+ - NAC.declareSitemap(spec) optional sitemap (sec 17)
20
+ - NAC.attestUserGesture(opts) isTrusted attestation
21
+ - NAC.t(key, opts?) i18n resolver
22
+ - NAC.registerCatalog(catalog) i18n catalog registration
23
+ - NAC.locale(code?) locale getter/setter
24
+ - NAC.setSupportedLocales(arr) extend supported list
25
+ - NAC.setRTLLocales(arr) extend RTL list
26
+ - NAC.set_provenance_secret(secret) HMAC secret registration
27
+
28
+ And tightens (only at NAC-3):
29
+ - check_canonical_shape: agent must sign + user_gesture_attested
30
+ - validate_global: i18n_strict mode
31
+
32
+ Spec: spec/NAC-v2.0.md + RFC_v2.0.0.md
33
+ ASCII-only.
34
+ =============================================================== */
35
+ (function (global) {
36
+ 'use strict';
37
+ if (!global.NAC) {
38
+ console.error('[NAC v2] requires nac.js v1.9.0+ to be loaded first');
39
+ return;
40
+ }
41
+ if (global.NAC.__nac_v2_installed) return;
42
+ global.NAC.__nac_v2_installed = true;
43
+
44
+ var NAC = global.NAC;
45
+ var SEPARATOR = '.';
46
+ var MAX_DEPTH = 6;
47
+ var WARN_DEPTH = 4;
48
+
49
+ /* ------------------------------------------------------------- locales */
50
+
51
+ var SUPPORTED_LOCALES_DEFAULT = ['es','en','pt','fr','it','de','ja','zh','hi','ar'];
52
+ var RTL_LOCALES_DEFAULT = ['ar','he','fa','ur'];
53
+ var _supported = SUPPORTED_LOCALES_DEFAULT.slice();
54
+ var _rtl = RTL_LOCALES_DEFAULT.slice();
55
+ var _currentLocale = (function () {
56
+ try {
57
+ var l = (document.documentElement.getAttribute('lang')
58
+ || navigator.language
59
+ || 'es').slice(0, 2).toLowerCase();
60
+ return _supported.indexOf(l) >= 0 ? l : 'es';
61
+ } catch (_) { return 'es'; }
62
+ })();
63
+ var _catalog = Object.create(null);
64
+
65
+ function setSupportedLocales(arr) {
66
+ if (!Array.isArray(arr) || !arr.length) {
67
+ throw new Error('[NAC v2] setSupportedLocales requires non-empty array');
68
+ }
69
+ _supported = arr.slice();
70
+ }
71
+ function setRTLLocales(arr) {
72
+ if (!Array.isArray(arr)) throw new Error('[NAC v2] setRTLLocales requires array');
73
+ _rtl = arr.slice();
74
+ }
75
+ /* v2.0-rc3 (Claude T5-F4): some hosts ship multi-locale
76
+ content in one DOM (e.g. user in 'ar' viewing untranslated
77
+ English log lines); auto-flipping dir=rtl on documentElement
78
+ globally breaks the LTR content's BIDI. Hosts opt out via
79
+ setAutoRTL(false), then manage dir on a sub-tree element. */
80
+ var _autoRTL = true;
81
+ function setAutoRTL(enabled) { _autoRTL = !!enabled; }
82
+
83
+ function locale(code) {
84
+ if (code === undefined) return _currentLocale;
85
+ if (_supported.indexOf(code) < 0) {
86
+ console.warn('[NAC v2] locale', code, 'not in supported list');
87
+ }
88
+ _currentLocale = code;
89
+ /* Auto-apply dir=rtl unless host opted out via setAutoRTL(false). */
90
+ if (_autoRTL) {
91
+ try {
92
+ if (_rtl.indexOf(code) >= 0) {
93
+ document.documentElement.setAttribute('dir', 'rtl');
94
+ } else {
95
+ document.documentElement.removeAttribute('dir');
96
+ }
97
+ } catch (_) {}
98
+ }
99
+ document.dispatchEvent(new CustomEvent('nac:locale_changed', {
100
+ detail: { locale: code, autoRTL: _autoRTL }, bubbles: true
101
+ }));
102
+ }
103
+ function registerCatalog(obj) {
104
+ if (!obj || typeof obj !== 'object') {
105
+ throw new Error('[NAC v2] registerCatalog requires object');
106
+ }
107
+ Object.keys(obj).forEach(function (k) { _catalog[k] = obj[k]; });
108
+ }
109
+ function t(key, opts) {
110
+ opts = opts || {};
111
+ var loc = opts.locale || _currentLocale;
112
+ var entry = _catalog[key];
113
+ if (!entry) return opts.fallback || key;
114
+ if (entry[loc]) return entry[loc];
115
+ /* Fallback chain: requested -> es -> en -> first available */
116
+ if (entry.es) return entry.es;
117
+ if (entry.en) return entry.en;
118
+ var firstKey = Object.keys(entry)[0];
119
+ return firstKey ? entry[firstKey] : (opts.fallback || key);
120
+ }
121
+
122
+ /* ------------------------------------------------------------- HMAC */
123
+
124
+ var _provenanceSecrets = [];
125
+ function set_provenance_secret(s) {
126
+ if (typeof s === 'string') _provenanceSecrets = [s];
127
+ else if (Array.isArray(s)) _provenanceSecrets = s.slice();
128
+ else if (s == null) _provenanceSecrets = [];
129
+ else throw new Error('[NAC v2] set_provenance_secret expects string|string[]');
130
+ /* v2.0-rc3 (Claude T6-F2): warm the crypto path now that we
131
+ have a secret registered; first agent sign won't pay the
132
+ cold-start cost. */
133
+ if (_provenanceSecrets[0] && typeof NAC.sign_provenance === 'function') {
134
+ try {
135
+ NAC.sign_provenance({ _warmup: true, ts: Date.now() }, _provenanceSecrets[0])
136
+ .catch(function () {});
137
+ } catch (_) {}
138
+ }
139
+ }
140
+ /* sign / verify provenance helpers exist in v1.9 already; reuse them */
141
+ function _hasSecrets() { return _provenanceSecrets.length > 0; }
142
+
143
+ async function _verify_with_registered(detail) {
144
+ if (!_hasSecrets()) return false;
145
+ if (typeof NAC.verify_provenance !== 'function') return false;
146
+ for (var i = 0; i < _provenanceSecrets.length; i++) {
147
+ try {
148
+ var ok = await NAC.verify_provenance(detail, _provenanceSecrets[i]);
149
+ if (ok) return true;
150
+ } catch (_) {}
151
+ }
152
+ return false;
153
+ }
154
+
155
+ /* ------------------------------------------------------------- isTrusted */
156
+
157
+ /* v2.0-rc3 (Claude T4-F1 BLOCKER fix): the gesture buffer is now
158
+ bound to the originating event's composedPath, NOT a global
159
+ flag. _readGestureAttested(forElement) verifies that the
160
+ element being invoked is in the captured path before honoring
161
+ attested. Without this, any user click anywhere on the page
162
+ leaked attested=true to ANY subsequent _invoke within the
163
+ freshness window -- the FOURTH impersonation path Claude
164
+ surfaced.
165
+
166
+ Additionally: GESTURE_FRESH_MS reduced 100ms -> 16ms (one
167
+ animation frame). Genuine click handlers run synchronously
168
+ (or via microtask), well within 16ms. Promise-resolved-later
169
+ handlers no longer count as user-attested -- which is the
170
+ security-correct behaviour. */
171
+ var _lastGestureTrusted = null;
172
+ var _lastGestureTime = 0;
173
+ var _lastGesturePath = null; /* Array<EventTarget> from e.composedPath() */
174
+ var GESTURE_FRESH_MS = 16; /* was 100 in rc2 */
175
+
176
+ /* v2.0-rc2 (Mistral T4-F1): mobile WebView contexts (Cordova,
177
+ Capacitor, React Native WebView) have inconsistent isTrusted
178
+ semantics. Hosts running in those environments register a
179
+ custom derivation function via setMobileWebViewAttestation so
180
+ the platform-specific signal substitutes for browser
181
+ event.isTrusted. */
182
+ var _mobileWebViewAttestor = null;
183
+
184
+ function setMobileWebViewAttestation(fn) {
185
+ if (fn != null && typeof fn !== 'function') {
186
+ throw new Error('[NAC v2] setMobileWebViewAttestation expects function|null');
187
+ }
188
+ _mobileWebViewAttestor = fn;
189
+ }
190
+
191
+ function _captureGestureFromDom() {
192
+ var handler = function (e) {
193
+ /* When a custom WebView attestor is registered, its return
194
+ value (or function call given the event) substitutes the
195
+ raw isTrusted reading. */
196
+ if (_mobileWebViewAttestor) {
197
+ try {
198
+ var attested = !!_mobileWebViewAttestor(e);
199
+ _lastGestureTrusted = attested;
200
+ } catch (err) {
201
+ _lastGestureTrusted = !!e.isTrusted;
202
+ }
203
+ } else {
204
+ _lastGestureTrusted = !!e.isTrusted;
205
+ }
206
+ _lastGestureTime = Date.now();
207
+ /* v2.0-rc3: capture the composed path so _invoke can verify
208
+ identity. Polyfill for ancient browsers via target ancestor
209
+ walk (composedPath() ships in all browsers >= 2018). */
210
+ try {
211
+ if (typeof e.composedPath === 'function') {
212
+ _lastGesturePath = e.composedPath();
213
+ } else {
214
+ _lastGesturePath = [];
215
+ var n = e.target;
216
+ while (n) { _lastGesturePath.push(n); n = n.parentNode; }
217
+ }
218
+ } catch (_) {
219
+ _lastGesturePath = e.target ? [e.target] : [];
220
+ }
221
+ };
222
+ ['click','keydown','keyup','touchstart','pointerdown'].forEach(function (n) {
223
+ document.addEventListener(n, handler, { capture: true, passive: true });
224
+ });
225
+ }
226
+ /* v2.2.1: guard browser-only DOM hookup so this bundle is
227
+ importable in Node / SSR / test contexts. */
228
+ if (typeof document !== 'undefined') {
229
+ if (document.readyState === 'loading') {
230
+ document.addEventListener('DOMContentLoaded', _captureGestureFromDom);
231
+ } else {
232
+ _captureGestureFromDom();
233
+ }
234
+ }
235
+
236
+ /* v2.0-rc3: _readGestureAttested now requires the element being
237
+ invoked. Returns the captured attested flag ONLY if:
238
+ (a) the gesture is within GESTURE_FRESH_MS (16ms) AND
239
+ (b) `forElement` is in the captured composedPath (or no
240
+ element was captured -- legacy callers).
241
+ Returns null in all other cases (matrix treats null as
242
+ not-attested -> 'user' source rejected at NAC-3). */
243
+ function _readGestureAttested(forElement) {
244
+ if (Date.now() - _lastGestureTime > GESTURE_FRESH_MS) return null;
245
+ if (!forElement) return _lastGestureTrusted; /* legacy fallback */
246
+ if (!_lastGesturePath || !_lastGesturePath.length) return _lastGestureTrusted;
247
+ /* Identity check: only honor attested when the target element
248
+ is in the originating event's path. Closes Claude T4-F1. */
249
+ if (_lastGesturePath.indexOf(forElement) >= 0) {
250
+ return _lastGestureTrusted;
251
+ }
252
+ return null;
253
+ }
254
+
255
+ /* Buffer for validate_global_v2 to surface findings emitted
256
+ by runtime guards (added rc6). Declared BEFORE
257
+ attestUserGesture so the override-blocking branch can
258
+ push into it without a temporal-dead-zone error. */
259
+ var _validatorFindings = [];
260
+
261
+ var _scriptOverride = null;
262
+ function attestUserGesture(opts) {
263
+ opts = opts || {};
264
+ /* 2026-05-09 (Claude R6 MEDIUM): the API was previously a
265
+ complete bypass for the identity-binding check. A page-
266
+ level script could call
267
+ attestUserGesture({trusted:true, type:'user'}) and the
268
+ next invoke would inherit attested=true with NO identity
269
+ binding to a real isTrusted gesture path. The override
270
+ was specified as testing-only (sec 15.10) but the runtime
271
+ accepted arbitrary opts.type values.
272
+
273
+ Fix: opts.type may ONLY be 'script' or 'agent'. Attempts
274
+ to claim 'user' (the only type that maps to source.type=
275
+ 'user' downstream) are blocked at runtime AND emit a
276
+ finding code script_override_claims_user that
277
+ validate_global_v2() reports. The override remains
278
+ useful for headless test fixtures (testing-only as the
279
+ spec always said) but cannot launder a script-origin
280
+ action as a user-origin one. */
281
+ var requestedType = (typeof opts.type === 'string' && opts.type) ? opts.type : 'script';
282
+ if (requestedType === 'user') {
283
+ _validatorFindings.push({
284
+ code: 'script_override_claims_user',
285
+ severity: 'error',
286
+ timestamp: Date.now(),
287
+ note: 'attestUserGesture rejected opts.type="user" -- only script/agent permitted'
288
+ });
289
+ console.warn('[NAC v2] attestUserGesture: opts.type="user" rejected; '
290
+ + 'forcing type="script". Identity-binding bypass blocked.');
291
+ requestedType = 'script';
292
+ }
293
+ if (requestedType !== 'script' && requestedType !== 'agent') {
294
+ throw new Error('[NAC v2] attestUserGesture: opts.type must be '
295
+ + '"script" or "agent" (got "' + requestedType + '")');
296
+ }
297
+ _scriptOverride = {
298
+ trusted: !!opts.trusted,
299
+ type: requestedType,
300
+ ts: Date.now()
301
+ };
302
+ }
303
+
304
+ /* ------------------------------------------------------------- perf tolerance */
305
+
306
+ /* v2.0-rc2 (Grok+Mistral T6-F1): default throttle bumped 50ms ->
307
+ 100ms after concurrent reviewer feedback that 50ms drops
308
+ events on bursty UIs. set_perf_tolerance({mutation_throttle_ms,
309
+ describe_target_ms, etc}) lets hosts tune for their workload. */
310
+ var _perfTolerance = {
311
+ mutation_throttle_ms: 100, /* was 50 in rc1 */
312
+ describe_target_ms: 50, /* was 30 in rc1 (Mistral T6-F2) */
313
+ describe_hard_fail_ms: 150, /* was 100 in rc1 */
314
+ adopt_hard_fail_ms: 20, /* was 15 in rc1 */
315
+ autoregister_hard_fail_ms: 5,
316
+ /* v2.0-rc4 (Claude T8.1 middle ground): hard-fail RATE
317
+ tightened from 5%/5s (rc2/rc3) to 2%/5s (rc4). Same
318
+ window width, tighter rate. Rationale: 5% over 5s = ~1
319
+ hitched describe() per 20s on Snapdragon 6 Gen 1 = breaks
320
+ SR reading flow; 1%/10s window too long for bursty
321
+ stalls. 2%/5s captures sustained AND bursty correctly.
322
+ Tunable for hosts that need looser thresholds. */
323
+ perf_budget_fail_rate_pct: 2, /* was implicit 5% in rc3 */
324
+ perf_budget_window_ms: 5000 /* unchanged */
325
+ };
326
+
327
+ function set_perf_tolerance(opts) {
328
+ if (!opts || typeof opts !== 'object') {
329
+ throw new Error('[NAC v2] set_perf_tolerance expects object');
330
+ }
331
+ Object.keys(opts).forEach(function (k) {
332
+ if (k in _perfTolerance && typeof opts[k] === 'number' && opts[k] > 0) {
333
+ _perfTolerance[k] = opts[k];
334
+ }
335
+ });
336
+ }
337
+ function get_perf_tolerance() { return Object.assign({}, _perfTolerance); }
338
+
339
+ /* ------------------------------------------------------------- validation tolerance */
340
+
341
+ /* v2.0-rc2 (Grok T5-F1 + Mistral T5-F2): NAC-3 default i18n
342
+ severity bumped from 'error' to 'warn' after concurrent
343
+ reviewer feedback that mandatory at NAC-3 blocks incremental
344
+ SaaS rollouts. Hosts that want strict 'error' behaviour opt
345
+ in via set_validation_tolerance({i18n_strict: 'error'}). */
346
+ var _validationTolerance = {
347
+ i18n_strict: 'warn', /* 'warn' (default) | 'error' | 'silent' */
348
+ /* v2.0-rc4 (Mistral T7-F1): iframe_strict opt-in turns on
349
+ NAC-3 fail-closed for bridgeIframe. Default 'warn' = rc3
350
+ fail-open behaviour preserved for NAC-1/NAC-2. */
351
+ iframe_strict: 'warn', /* 'warn' (default) | 'error' */
352
+ /* v2.0-rc4 (Claude T8.2): autoderived_action signals when
353
+ autoRegister inferred the action without an explicit
354
+ data-nac-action attribute. Default 'warn'; opt-in 'error'
355
+ for regulated-environment audit pipelines. */
356
+ autoderived_action: 'warn' /* 'warn' (default) | 'error' | 'silent' */
357
+ };
358
+
359
+ function set_validation_tolerance(opts) {
360
+ if (!opts || typeof opts !== 'object') {
361
+ throw new Error('[NAC v2] set_validation_tolerance expects object');
362
+ }
363
+ if (opts.i18n_strict && ['warn', 'error', 'silent'].indexOf(opts.i18n_strict) >= 0) {
364
+ _validationTolerance.i18n_strict = opts.i18n_strict;
365
+ }
366
+ if (opts.iframe_strict && ['warn', 'error'].indexOf(opts.iframe_strict) >= 0) {
367
+ _validationTolerance.iframe_strict = opts.iframe_strict;
368
+ }
369
+ if (opts.autoderived_action && ['warn', 'error', 'silent'].indexOf(opts.autoderived_action) >= 0) {
370
+ _validationTolerance.autoderived_action = opts.autoderived_action;
371
+ }
372
+ }
373
+ function get_validation_tolerance() { return Object.assign({}, _validationTolerance); }
374
+
375
+ /* ------------------------------------------------------------- scope */
376
+
377
+ var _scopes = Object.create(null);
378
+
379
+ function _validateLeaf(slug) {
380
+ if (!slug || typeof slug !== 'string') {
381
+ throw new Error('[NAC v2] slug required');
382
+ }
383
+ /* v2.0-rc3 (DeepSeek T3.1): empty string passes the typeof
384
+ check + indexOf check, then produces malformed slugs. Reject
385
+ it explicitly. */
386
+ if (slug.length === 0) {
387
+ throw new Error('[NAC v2] slug_invalid: empty string');
388
+ }
389
+ if (slug.indexOf(SEPARATOR) >= 0) {
390
+ throw new Error('[NAC v2] slug_invalid: contains "' + SEPARATOR + '"');
391
+ }
392
+ }
393
+
394
+ function scope(spec) {
395
+ spec = spec || {};
396
+ _validateLeaf(spec.slug);
397
+ return _makeSubScope(spec.slug, [spec.slug], spec);
398
+ }
399
+
400
+ function _makeSubScope(currentSlug, chain, spec) {
401
+ var depth = chain.length;
402
+ if (depth > MAX_DEPTH) {
403
+ throw new Error('[NAC v2] depth_exceeded: ' + chain.join(SEPARATOR));
404
+ }
405
+ if (depth === WARN_DEPTH + 1) {
406
+ document.dispatchEvent(new CustomEvent('nac:depth_warn', {
407
+ detail: { path: chain.join(SEPARATOR), depth: depth }, bubbles: true
408
+ }));
409
+ }
410
+
411
+ var node = {
412
+ id: chain.join(SEPARATOR),
413
+ depth: depth,
414
+ label_i18n: spec ? spec.label_i18n || null : null,
415
+ };
416
+ /* v2.0-rc3 (Claude T3.1): track intermediate nodes that carry
417
+ a label_i18n so describe_v2 can expose them. Leaf nodes go
418
+ through register() and end up in _scopes; intermediate
419
+ (non-leaf) nodes need a separate index. */
420
+ if (node.label_i18n) {
421
+ _intermediateScopes[node.id] = {
422
+ depth: depth,
423
+ label_i18n: node.label_i18n
424
+ };
425
+ }
426
+ Object.assign(node, {
427
+
428
+ scope: function (childSpec) {
429
+ _validateLeaf(childSpec.slug);
430
+ var childChain = chain.concat([childSpec.slug]);
431
+ return _makeSubScope(childSpec.slug, childChain, childSpec);
432
+ },
433
+
434
+ register: function (regSpec) {
435
+ _validateLeaf(regSpec.slug);
436
+ var fullSlug = chain.concat([regSpec.slug]).join(SEPARATOR);
437
+
438
+ var entry = {
439
+ slug: fullSlug,
440
+ intent: regSpec.intent || 'navigate',
441
+ source: regSpec.source || 'human',
442
+ label_i18n: regSpec.label_i18n || null,
443
+ desc_i18n: regSpec.desc_i18n || null,
444
+ a11y_hint: regSpec.a11y_hint || null,
445
+ irreversible:!!regSpec.irreversible,
446
+ role: regSpec.role || null,
447
+ element: regSpec.element || null,
448
+ handler: typeof regSpec.handler === 'function' ? regSpec.handler : null,
449
+ autoderived: false,
450
+ parent_chain: chain.slice(),
451
+ registered_at: Date.now()
452
+ };
453
+
454
+ /* Idempotent: re-register with same slug + same element silently
455
+ updates; re-register with same slug + different element warns. */
456
+ var prior = _scopes[fullSlug];
457
+ if (prior) {
458
+ if (prior.element === entry.element) {
459
+ _scopes[fullSlug] = entry;
460
+ } else {
461
+ document.dispatchEvent(new CustomEvent('nac:duplicate_warn', {
462
+ detail: { slug: fullSlug, prior: prior, next: entry }, bubbles: true
463
+ }));
464
+ _scopes[fullSlug] = entry; /* last-wins */
465
+ }
466
+ } else {
467
+ _scopes[fullSlug] = entry;
468
+ }
469
+
470
+ if (entry.element) {
471
+ entry.element.setAttribute('data-nac-id', fullSlug);
472
+ entry.element.setAttribute('data-nac-parent', chain.join(' '));
473
+ if (entry.role) entry.element.setAttribute('role', entry.role);
474
+ if (entry.label_i18n) {
475
+ var lbl = t.bind(null);
476
+ var labelText = (function () {
477
+ if (entry.label_i18n[_currentLocale]) return entry.label_i18n[_currentLocale];
478
+ if (entry.label_i18n.es) return entry.label_i18n.es;
479
+ if (entry.label_i18n.en) return entry.label_i18n.en;
480
+ return fullSlug;
481
+ })();
482
+ if (!entry.element.getAttribute('aria-label')) {
483
+ entry.element.setAttribute('aria-label', labelText);
484
+ }
485
+ }
486
+ if (entry.irreversible) {
487
+ entry.element.setAttribute('data-nac-irreversible', '1');
488
+ }
489
+ }
490
+
491
+ return {
492
+ id: fullSlug,
493
+ invoke: function (params) { return _invoke(fullSlug, params); }
494
+ };
495
+ }
496
+ });
497
+ return node;
498
+ }
499
+
500
+ function _invoke(slug, params) {
501
+ var entry = _scopes[slug];
502
+ if (!entry) return Promise.reject(new Error('unknown_slug:' + slug));
503
+ var src = (params && params.source) || entry.source || 'human';
504
+
505
+ var attested;
506
+ if (_scriptOverride && Date.now() - _scriptOverride.ts < GESTURE_FRESH_MS) {
507
+ attested = _scriptOverride.trusted;
508
+ _scriptOverride = null;
509
+ } else {
510
+ /* v2.0-rc3 (Claude T4-F1 BLOCKER fix): pass entry.element so
511
+ _readGestureAttested can verify identity, not just freshness.
512
+ Closes the gesture-buffer leak. */
513
+ attested = _readGestureAttested(entry.element);
514
+ }
515
+
516
+ /* v2.0-rc3 (Claude T4-F3): os_level pass-through. When source is
517
+ 'agent' AND host opts in (e.g. for Computer Use telemetry),
518
+ params.os_level is propagated into provenance for audit. */
519
+ var osLevel = (params && params.os_level === true) ? true : null;
520
+
521
+ var prov = {
522
+ slug: slug,
523
+ intent: entry.intent,
524
+ source: src,
525
+ type: src,
526
+ user_gesture_attested: attested,
527
+ ts: Date.now(),
528
+ params: params || null
529
+ };
530
+ if (osLevel === true) prov.os_level = true;
531
+
532
+ /* Agent + irreversible -> decline path */
533
+ if (src === 'agent' && entry.irreversible) {
534
+ var hint = entry.a11y_hint
535
+ ? (entry.a11y_hint[_currentLocale] || entry.a11y_hint.es)
536
+ : null;
537
+ document.dispatchEvent(new CustomEvent('nac:command_rejected', {
538
+ detail: { slug: slug, reason: 'agent_declined_irreversible', hint: hint, ts: Date.now() },
539
+ bubbles: true
540
+ }));
541
+ return Promise.reject(new Error('agent_declined_irreversible'));
542
+ }
543
+
544
+ /* Sign if we can (agent must) */
545
+ var signPromise;
546
+ if (typeof NAC.sign_provenance === 'function' && _provenanceSecrets[0]) {
547
+ signPromise = NAC.sign_provenance(prov, _provenanceSecrets[0]);
548
+ } else {
549
+ signPromise = Promise.resolve(null);
550
+ }
551
+
552
+ return signPromise.then(function (sig) {
553
+ if (sig) prov.signature = sig;
554
+ var detail = { provenance: prov, signature: sig, version: 'v2.0' };
555
+ document.dispatchEvent(new CustomEvent('nac:command_pending', {
556
+ detail: detail, bubbles: true
557
+ }));
558
+ var run = entry.handler
559
+ ? Promise.resolve().then(function () { return entry.handler(params || {}, detail); })
560
+ : Promise.resolve(null);
561
+ return run.then(function (result) {
562
+ document.dispatchEvent(new CustomEvent('nac:command_done', {
563
+ detail: Object.assign({}, detail, { result: result }), bubbles: true
564
+ }));
565
+ return result;
566
+ }, function (err) {
567
+ document.dispatchEvent(new CustomEvent('nac:command_failed', {
568
+ detail: Object.assign({}, detail, { error: String(err) }), bubbles: true
569
+ }));
570
+ throw err;
571
+ });
572
+ });
573
+ }
574
+
575
+ /* ------------------------------------------------------------- autoRegister */
576
+
577
+ function _findScopeAncestor(el) {
578
+ var anc = el.parentElement;
579
+ while (anc) {
580
+ if (anc.hasAttribute && anc.hasAttribute('data-nac-scope')) {
581
+ return anc.getAttribute('data-nac-scope');
582
+ }
583
+ anc = anc.parentElement;
584
+ }
585
+ return null;
586
+ }
587
+
588
+ function _deriveLeafSlug(el) {
589
+ if (el.id) return el.id;
590
+ if (el.dataset && el.dataset.nacAction) return el.dataset.nacAction;
591
+ /* v2.0-rc3 (Claude T3.2): the rc1 fallback hashed only
592
+ el.outerHTML.slice(0,100) which produces identical hashes for
593
+ 400 cards rendered from the same template (template prefixes
594
+ are byte-identical). The fix mixes in: tag name + textContent
595
+ (more discriminating) + position-in-parent (guaranteed
596
+ unique). Collisions still possible when two truly identical
597
+ elements exist; idempotent register handles those by
598
+ last-wins-same-element. */
599
+ var src = '';
600
+ src += el.tagName || '';
601
+ src += '|';
602
+ src += (el.textContent || '').trim().slice(0, 60);
603
+ src += '|';
604
+ if (el.parentNode) {
605
+ try {
606
+ var siblings = el.parentNode.children;
607
+ for (var s = 0; s < siblings.length; s++) {
608
+ if (siblings[s] === el) { src += '@' + s; break; }
609
+ }
610
+ } catch (_) {}
611
+ }
612
+ src += '|';
613
+ src += (el.outerHTML || '').slice(0, 80);
614
+ var h = 0;
615
+ for (var i = 0; i < src.length; i++) {
616
+ h = ((h << 5) - h) + src.charCodeAt(i);
617
+ h |= 0;
618
+ }
619
+ return 'auto_' + (Math.abs(h)).toString(36);
620
+ }
621
+
622
+ function _deriveRole(el) {
623
+ var tag = el.tagName.toLowerCase();
624
+ var attrRole = el.getAttribute('role');
625
+ if (attrRole) return attrRole;
626
+ if (tag === 'button') return 'button';
627
+ if (tag === 'a' && el.hasAttribute('href')) return 'link';
628
+ if (tag === 'input') {
629
+ var t = el.getAttribute('type') || 'text';
630
+ if (t === 'checkbox' || t === 'radio') return 'toggle';
631
+ return 'field';
632
+ }
633
+ if (tag === 'textarea') return 'field';
634
+ if (tag === 'select') return 'select';
635
+ return 'interactive';
636
+ }
637
+
638
+ function _deriveLabel(el) {
639
+ var aria = el.getAttribute('aria-label');
640
+ if (aria) return aria;
641
+ return (el.textContent || '').trim().slice(0, 200);
642
+ }
643
+
644
+ function autoRegister(el, opts) {
645
+ opts = opts || {};
646
+ if (!el) throw new Error('[NAC v2] autoRegister requires element');
647
+ var leaf = _deriveLeafSlug(el);
648
+ var parentSlug = opts.inheritScope !== false ? _findScopeAncestor(el) : null;
649
+ /* v2.0-rc3 (DeepSeek T3.2): warn on orphan slugs (no parent
650
+ scope ancestor found). Easy to happen on pages with multiple
651
+ dynamic regions; without a warn the slug ends up huerfano
652
+ silently. */
653
+ if (opts.inheritScope !== false && !parentSlug) {
654
+ try {
655
+ document.dispatchEvent(new CustomEvent('nac:autoregister_orphan_warn', {
656
+ detail: { leaf: leaf, element: el }, bubbles: true
657
+ }));
658
+ } catch (_) {}
659
+ }
660
+ var fullSlug = parentSlug ? (parentSlug + SEPARATOR + leaf) : leaf;
661
+
662
+ /* i18n strict check */
663
+ var i18nKey = el.getAttribute('data-i18n-key');
664
+ var labelI18n = null;
665
+ var autoderived = false;
666
+ if (i18nKey && _catalog[i18nKey]) {
667
+ labelI18n = _catalog[i18nKey];
668
+ } else if (i18nKey) {
669
+ /* Key declared but catalog missing the entry */
670
+ if (opts.i18n_strict !== false) {
671
+ document.dispatchEvent(new CustomEvent('nac:i18n_skipped', {
672
+ detail: { slug: fullSlug, key: i18nKey, reason: 'catalog_missing' },
673
+ bubbles: true
674
+ }));
675
+ return null;
676
+ }
677
+ } else {
678
+ /* No data-i18n-key. In strict (default) we skip; in permissive
679
+ we mono-locale fallback */
680
+ if (opts.i18n_strict !== false && opts.i18n_strict !== 'permissive') {
681
+ document.dispatchEvent(new CustomEvent('nac:i18n_skipped', {
682
+ detail: { slug: fullSlug, reason: 'no_data_i18n_key' },
683
+ bubbles: true
684
+ }));
685
+ return null;
686
+ }
687
+ var derivedLabel = _deriveLabel(el);
688
+ labelI18n = {};
689
+ labelI18n[_currentLocale] = derivedLabel;
690
+ autoderived = true;
691
+ }
692
+
693
+ var role = (opts.derive && opts.derive.role === 'auto')
694
+ ? _deriveRole(el)
695
+ : (opts.derive && opts.derive.role) || _deriveRole(el);
696
+
697
+ var entry = {
698
+ slug: fullSlug,
699
+ intent: 'navigate',
700
+ source: 'human',
701
+ label_i18n: labelI18n,
702
+ role: role,
703
+ element: el,
704
+ autoderived: autoderived,
705
+ registered_at: Date.now()
706
+ };
707
+ _scopes[fullSlug] = entry;
708
+ el.setAttribute('data-nac-id', fullSlug);
709
+ if (parentSlug) {
710
+ el.setAttribute('data-nac-parent', parentSlug.split(SEPARATOR).join(' '));
711
+ }
712
+ if (role && !el.getAttribute('role')) el.setAttribute('role', role);
713
+ if (labelI18n && !el.getAttribute('aria-label')) {
714
+ var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
715
+ el.setAttribute('aria-label', lab);
716
+ }
717
+ return entry;
718
+ }
719
+
720
+ /* MutationObserver-based watch */
721
+ var _watchObservers = [];
722
+ autoRegister.watch = function (containerEl, opts) {
723
+ opts = opts || {};
724
+ /* v2.0-rc2: default throttle pulled from _perfTolerance (100ms),
725
+ caller may still override per-watch via opts.throttleMs. */
726
+ var throttleMs = opts.throttleMs || _perfTolerance.mutation_throttle_ms;
727
+ var pending = false;
728
+ var queue = [];
729
+
730
+ /* v2.0-rc3 (Claude T6-F1): chunk batches > 50 elements via
731
+ requestIdleCallback (or setTimeout fallback) to stay under
732
+ the cumulative-batch perf budget. Per-element cost stays the
733
+ same; main thread is yielded between sub-batches so the
734
+ page stays responsive. */
735
+ var CHUNK_SIZE = 50;
736
+ function _yieldThen(fn) {
737
+ if (typeof window.requestIdleCallback === 'function') {
738
+ window.requestIdleCallback(fn, { timeout: 100 });
739
+ } else {
740
+ setTimeout(fn, 0);
741
+ }
742
+ }
743
+ function processOne(entry) {
744
+ if (entry.added) {
745
+ if (entry.el.hasAttribute && entry.el.hasAttribute('data-nac-action')) {
746
+ try { autoRegister(entry.el, opts); } catch (_) {}
747
+ }
748
+ /* Descend into added subtree */
749
+ if (entry.el.querySelectorAll) {
750
+ entry.el.querySelectorAll('[data-nac-action]').forEach(function (x) {
751
+ try { autoRegister(x, opts); } catch (_) {}
752
+ });
753
+ }
754
+ } else {
755
+ /* Removed: clean manifest */
756
+ if (entry.el.getAttribute) {
757
+ var slug = entry.el.getAttribute('data-nac-id');
758
+ if (slug && _scopes[slug]) delete _scopes[slug];
759
+ }
760
+ }
761
+ }
762
+ function flush() {
763
+ var batch = queue.splice(0);
764
+ pending = false;
765
+ if (batch.length <= CHUNK_SIZE) {
766
+ batch.forEach(processOne);
767
+ return;
768
+ }
769
+ /* Chunked path: yield between sub-batches. */
770
+ var idx = 0;
771
+ function step() {
772
+ var end = Math.min(idx + CHUNK_SIZE, batch.length);
773
+ for (; idx < end; idx++) processOne(batch[idx]);
774
+ if (idx < batch.length) _yieldThen(step);
775
+ }
776
+ step();
777
+ }
778
+
779
+ var obs = new MutationObserver(function (muts) {
780
+ muts.forEach(function (m) {
781
+ m.addedNodes.forEach(function (n) {
782
+ if (n.nodeType === 1) queue.push({ added: true, el: n });
783
+ });
784
+ m.removedNodes.forEach(function (n) {
785
+ if (n.nodeType === 1) queue.push({ added: false, el: n });
786
+ });
787
+ });
788
+ if (!pending) {
789
+ pending = true;
790
+ setTimeout(flush, throttleMs);
791
+ }
792
+ });
793
+ obs.observe(containerEl, { childList: true, subtree: true });
794
+ _watchObservers.push(obs);
795
+ /* Also process existing descendants */
796
+ containerEl.querySelectorAll('[data-nac-action]').forEach(function (el) {
797
+ try { autoRegister(el, opts); } catch (_) {}
798
+ });
799
+ return obs;
800
+ };
801
+
802
+ /* ------------------------------------------------------------- adopt */
803
+
804
+ function adopt(rule) {
805
+ if (!rule || !rule.selector) throw new Error('[NAC v2] adopt requires selector');
806
+ rule.parent = rule.parent || null;
807
+ rule.observe = rule.observe !== false;
808
+
809
+ function process(el) {
810
+ try {
811
+ var leaf = (rule.derive && rule.derive.slug)
812
+ ? rule.derive.slug(el)
813
+ : _deriveLeafSlug(el);
814
+ var fullSlug = rule.parent
815
+ ? (rule.parent + SEPARATOR + leaf)
816
+ : leaf;
817
+ var role = (rule.derive && rule.derive.role)
818
+ ? rule.derive.role(el)
819
+ : _deriveRole(el);
820
+ var labelI18n = (rule.derive && rule.derive.label_i18n)
821
+ ? rule.derive.label_i18n(el)
822
+ : (function () { var o={}; o[_currentLocale]=_deriveLabel(el); return o; })();
823
+ var irreversible = (rule.derive && rule.derive.irreversible)
824
+ ? rule.derive.irreversible(el)
825
+ : false;
826
+ var entry = {
827
+ slug: fullSlug,
828
+ intent: (rule.derive && rule.derive.intent && rule.derive.intent(el)) || 'navigate',
829
+ source: 'human',
830
+ label_i18n: labelI18n,
831
+ role: role,
832
+ element: el,
833
+ irreversible: irreversible,
834
+ adopted: true,
835
+ registered_at: Date.now()
836
+ };
837
+ _scopes[fullSlug] = entry;
838
+ el.setAttribute('data-nac-id', fullSlug);
839
+ if (role && !el.getAttribute('role')) el.setAttribute('role', role);
840
+ if (labelI18n && !el.getAttribute('aria-label')) {
841
+ var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
842
+ el.setAttribute('aria-label', lab);
843
+ }
844
+ if (irreversible) el.setAttribute('data-nac-irreversible', '1');
845
+ } catch (e) {
846
+ document.dispatchEvent(new CustomEvent('nac:adopt_failed', {
847
+ detail: { rule: rule.selector, error: String(e) }, bubbles: true
848
+ }));
849
+ }
850
+ }
851
+
852
+ /* v2.0-rc3 (Claude T3.3): scope the observer to a host-supplied
853
+ containerEl (smaller subtree) when provided, instead of always
854
+ attaching to document.body. Reduces mutation-observer cost
855
+ on DOM-heavy pages with N rules. */
856
+ var scopedRoot = (rule.containerEl && rule.containerEl.nodeType === 1)
857
+ ? rule.containerEl
858
+ : document.body;
859
+
860
+ /* Initial pass: query within the scoped root, not always document. */
861
+ scopedRoot.querySelectorAll(rule.selector).forEach(process);
862
+
863
+ /* Observer */
864
+ if (rule.observe) {
865
+ var obs = new MutationObserver(function (muts) {
866
+ muts.forEach(function (m) {
867
+ m.addedNodes.forEach(function (n) {
868
+ if (n.nodeType !== 1) return;
869
+ if (n.matches && n.matches(rule.selector)) process(n);
870
+ if (n.querySelectorAll) {
871
+ n.querySelectorAll(rule.selector).forEach(process);
872
+ }
873
+ });
874
+ });
875
+ });
876
+ obs.observe(scopedRoot, { childList: true, subtree: true });
877
+ }
878
+ return rule;
879
+ }
880
+
881
+ /* ------------------------------------------------------------- bridges */
882
+
883
+ /* v2.0-rc3 (DeepSeek T3.4): dedup bridged hosts via WeakSet so
884
+ repeat calls on the same host do not produce duplicate
885
+ registrations. */
886
+ var _bridgedShadowHosts = new WeakSet();
887
+
888
+ function bridgeShadowRoot(host, depth) {
889
+ depth = depth || 0;
890
+ if (depth > 6) {
891
+ document.dispatchEvent(new CustomEvent('nac:shadow_depth_exceeded', {
892
+ detail: { host: host }, bubbles: true
893
+ }));
894
+ return;
895
+ }
896
+ if (!host || !host.shadowRoot) {
897
+ document.dispatchEvent(new CustomEvent('nac:shadow_blocked', {
898
+ detail: { host: host, reason: 'closed_or_missing' }, bubbles: true
899
+ }));
900
+ return;
901
+ }
902
+ /* v2.0-rc3: skip if already bridged. */
903
+ if (_bridgedShadowHosts.has(host)) return;
904
+ _bridgedShadowHosts.add(host);
905
+ /* Walk shadow root: any [data-nac-id] becomes operable; any
906
+ [data-nac-action] auto-registers */
907
+ var sr = host.shadowRoot;
908
+ sr.querySelectorAll('[data-nac-action]').forEach(function (el) {
909
+ try { autoRegister(el, { i18n_strict: 'permissive' }); } catch (_) {}
910
+ });
911
+ /* Recurse */
912
+ sr.querySelectorAll('*').forEach(function (el) {
913
+ if (el.shadowRoot) bridgeShadowRoot(el, depth + 1);
914
+ });
915
+ }
916
+
917
+ function bridgeIframe(iframeEl, opts) {
918
+ opts = opts || {};
919
+ var ns = opts.postMessageNamespace || 'nac.iframe.v1';
920
+ var trusted = opts.trusted_origins || [];
921
+ var timeout = opts.timeout_ms || 5000;
922
+ var iframeId = iframeEl.id || 'iframe_' + Math.random().toString(36).slice(2,8);
923
+ /* v2.0-rc4 (Mistral T7-F1 + Claude T4-F2.1): NAC-3 enforcement
924
+ opt-in. When opts.nac_level === 3 (or auto-detected from
925
+ _validationTolerance.iframe_strict === 'error'), runtime
926
+ enforces fail-closed on missing secret and verifies
927
+ signatures on BOTH handshake_ack AND describe_result. */
928
+ var nacLevel = opts.nac_level
929
+ || (_validationTolerance.iframe_strict === 'error' ? 3 : 1);
930
+
931
+ /* v2.0-rc3 (Claude T4-F2): the spec mandates HMAC chain on
932
+ cross-origin agent-source events. We additionally require
933
+ that handshake_ack and describe_result messages carry
934
+ signature fields verifiable against our registered HMAC
935
+ secret. Without this, a compromised trusted-origin (XSS in
936
+ a vendor's CDN) can ride on the allowlist trust to inject
937
+ manifest entries unchecked.
938
+ v2.0-rc4: extended to describe_result + NAC-3 fail-closed. */
939
+ return new Promise(function (resolve, reject) {
940
+ var done = false;
941
+ function listener(ev) {
942
+ if (trusted.length && trusted.indexOf(ev.origin) < 0) {
943
+ document.dispatchEvent(new CustomEvent('nac:iframe_untrusted', {
944
+ detail: { origin: ev.origin }, bubbles: true
945
+ }));
946
+ return;
947
+ }
948
+ var d = ev.data;
949
+ if (!d || d.ns !== ns) return;
950
+ if (d.cmd === 'handshake_ack') {
951
+ if (done) return;
952
+ /* v2.0-rc4 (Mistral T7-F1): NAC-3 fail-closed. If no
953
+ secret registered AND we are at NAC-3, reject the
954
+ handshake. NAC-1/NAC-2 path keeps fail-open with
955
+ warn (rc3 behaviour). */
956
+ if (nacLevel >= 3 && !_hasSecrets()) {
957
+ done = true;
958
+ window.removeEventListener('message', listener);
959
+ document.dispatchEvent(new CustomEvent('nac:iframe_no_secret_at_nac3', {
960
+ detail: { iframeId: iframeId }, bubbles: true
961
+ }));
962
+ reject(new Error('iframe_no_secret_at_nac3'));
963
+ return;
964
+ }
965
+ /* v2.0-rc3: verify signature on handshake_ack if HMAC
966
+ secret registered. */
967
+ if (_hasSecrets() && d.signature) {
968
+ _verify_with_registered({ ns: d.ns, cmd: d.cmd, version: d.version, signature: d.signature })
969
+ .then(function (ok) {
970
+ if (!ok) {
971
+ done = true;
972
+ window.removeEventListener('message', listener);
973
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_invalid', {
974
+ detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
975
+ }));
976
+ reject(new Error('iframe_signature_invalid'));
977
+ return;
978
+ }
979
+ _continueHandshakeAck();
980
+ });
981
+ return;
982
+ }
983
+ if (_hasSecrets() && !d.signature) {
984
+ /* Secret registered but iframe did not sign -> at
985
+ NAC-3 fail-closed; at lower levels emit warn and
986
+ continue. */
987
+ if (nacLevel >= 3) {
988
+ done = true;
989
+ window.removeEventListener('message', listener);
990
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
991
+ detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
992
+ }));
993
+ reject(new Error('iframe_signature_missing'));
994
+ return;
995
+ }
996
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
997
+ detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
998
+ }));
999
+ }
1000
+ _continueHandshakeAck();
1001
+
1002
+ function _continueHandshakeAck() {
1003
+ done = true;
1004
+ if (d.version && d.version.split('.')[0] !== '2') {
1005
+ document.dispatchEvent(new CustomEvent('nac:iframe_version_mismatch', {
1006
+ detail: { theirs: d.version, ours: '2.0' }, bubbles: true
1007
+ }));
1008
+ reject(new Error('iframe_version_mismatch'));
1009
+ return;
1010
+ }
1011
+ window.removeEventListener('message', listener);
1012
+ resolve({ iframeId: iframeId, version: d.version,
1013
+ signed: !!d.signature, nac_level: nacLevel });
1014
+ }
1015
+ }
1016
+ /* v2.0-rc4 (Mistral T4-F2.1): describe_result messages
1017
+ ALSO must be HMAC-verified at NAC-3. The handshake
1018
+ promise has already resolved by this point; this
1019
+ listener stays installed for follow-up describe()
1020
+ pulls. We emit events but cannot reject the promise
1021
+ (already settled). */
1022
+ if (d.cmd === 'describe_result') {
1023
+ if (nacLevel >= 3 && !_hasSecrets()) {
1024
+ document.dispatchEvent(new CustomEvent('nac:iframe_no_secret_at_nac3', {
1025
+ detail: { iframeId: iframeId, message: 'describe_result' },
1026
+ bubbles: true
1027
+ }));
1028
+ return;
1029
+ }
1030
+ if (_hasSecrets() && d.signature) {
1031
+ _verify_with_registered({
1032
+ ns: d.ns, cmd: d.cmd, manifest: d.manifest, signature: d.signature
1033
+ }).then(function (ok) {
1034
+ if (!ok) {
1035
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_invalid', {
1036
+ detail: { iframeId: iframeId, message: 'describe_result' },
1037
+ bubbles: true
1038
+ }));
1039
+ return;
1040
+ }
1041
+ /* Verified: forward manifest to whoever subscribes. */
1042
+ document.dispatchEvent(new CustomEvent('nac:iframe_describe_received', {
1043
+ detail: { iframeId: iframeId, manifest: d.manifest }, bubbles: true
1044
+ }));
1045
+ });
1046
+ return;
1047
+ }
1048
+ if (_hasSecrets() && !d.signature) {
1049
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
1050
+ detail: { iframeId: iframeId, message: 'describe_result' }, bubbles: true
1051
+ }));
1052
+ if (nacLevel >= 3) return; /* drop unsigned at NAC-3 */
1053
+ }
1054
+ /* NAC-1/NAC-2 + no secret: forward manifest as-is. */
1055
+ document.dispatchEvent(new CustomEvent('nac:iframe_describe_received', {
1056
+ detail: { iframeId: iframeId, manifest: d.manifest }, bubbles: true
1057
+ }));
1058
+ }
1059
+ }
1060
+ window.addEventListener('message', listener);
1061
+ iframeEl.contentWindow.postMessage(
1062
+ { ns: ns, cmd: 'handshake', version: '2.0' },
1063
+ trusted.length ? trusted[0] : '*'
1064
+ );
1065
+ setTimeout(function () {
1066
+ if (!done) {
1067
+ done = true;
1068
+ window.removeEventListener('message', listener);
1069
+ document.dispatchEvent(new CustomEvent('nac:iframe_handshake_timeout', {
1070
+ detail: { iframeId: iframeId }, bubbles: true
1071
+ }));
1072
+ reject(new Error('iframe_handshake_timeout'));
1073
+ }
1074
+ }, timeout);
1075
+ });
1076
+ }
1077
+
1078
+ /* ------------------------------------------------------------- virtual */
1079
+
1080
+ var _virtuals = [];
1081
+ function declareVirtual(spec) {
1082
+ if (!spec || !spec.slug_pattern || typeof spec.resolver !== 'function') {
1083
+ throw new Error('[NAC v2] declareVirtual requires {slug_pattern, count, resolver}');
1084
+ }
1085
+ _virtuals.push(spec);
1086
+ return spec;
1087
+ }
1088
+ /* v2.0-rc3 (Claude T3.6 / DeepSeek T3.6): escape regex
1089
+ metacharacters in the static parts of the pattern before
1090
+ substituting {i}. Without this, `pipeline.runs.row.{i}` would
1091
+ match `pipelineXrunsXrowX7` (because `.` is a regex wildcard);
1092
+ a malicious URL or DOM-injected slug could hit arbitrary
1093
+ pattern. */
1094
+ function _escapeRegex(s) {
1095
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1096
+ }
1097
+ function _resolveVirtual(slug) {
1098
+ for (var i = 0; i < _virtuals.length; i++) {
1099
+ var v = _virtuals[i];
1100
+ /* Split on {i} so we can escape the static parts. */
1101
+ var parts = v.slug_pattern.split('{i}');
1102
+ var pat = parts.map(_escapeRegex).join('(\\d+)');
1103
+ var m = slug.match(new RegExp('^' + pat + '$'));
1104
+ if (m) {
1105
+ var idx = parseInt(m[1], 10);
1106
+ var count = typeof v.count === 'function' ? v.count() : v.count;
1107
+ if (idx >= 0 && idx < count) {
1108
+ var t0 = performance.now();
1109
+ var entry = v.resolver(idx);
1110
+ var elapsed = performance.now() - t0;
1111
+ if (elapsed > 50) {
1112
+ document.dispatchEvent(new CustomEvent('nac:virtual_resolver_slow', {
1113
+ detail: { slug: slug, elapsed_ms: elapsed }, bubbles: true
1114
+ }));
1115
+ }
1116
+ return entry;
1117
+ }
1118
+ }
1119
+ }
1120
+ return null;
1121
+ }
1122
+
1123
+ /* ------------------------------------------------------------- ephemeral */
1124
+
1125
+ var _ephemeralRing = [];
1126
+ var _ephemeralOpts = null;
1127
+ function captureEphemeral(opts) {
1128
+ opts = opts || {};
1129
+ _ephemeralOpts = {
1130
+ duration_ms: opts.duration_ms || 3000,
1131
+ ring_size: opts.ring_size || 100,
1132
+ on_capture: opts.on_capture || null
1133
+ };
1134
+ var liveTimers = new Map();
1135
+ var obs = new MutationObserver(function (muts) {
1136
+ muts.forEach(function (m) {
1137
+ m.addedNodes.forEach(function (n) {
1138
+ if (n.nodeType === 1 && n.getAttribute && n.getAttribute('data-nac-id')) {
1139
+ var slug = n.getAttribute('data-nac-id');
1140
+ liveTimers.set(slug, { added_at: Date.now(), node: n });
1141
+ }
1142
+ });
1143
+ m.removedNodes.forEach(function (n) {
1144
+ if (n.nodeType === 1 && n.getAttribute && n.getAttribute('data-nac-id')) {
1145
+ var slug = n.getAttribute('data-nac-id');
1146
+ var live = liveTimers.get(slug);
1147
+ if (live && (Date.now() - live.added_at) <= _ephemeralOpts.duration_ms) {
1148
+ var capture = {
1149
+ slug: slug,
1150
+ role: n.getAttribute('role'),
1151
+ label: n.textContent.trim().slice(0, 200),
1152
+ added_at: live.added_at,
1153
+ removed_at: Date.now(),
1154
+ duration_ms: Date.now() - live.added_at
1155
+ };
1156
+ _ephemeralRing.push(capture);
1157
+ if (_ephemeralRing.length > _ephemeralOpts.ring_size) {
1158
+ _ephemeralRing.shift();
1159
+ }
1160
+ if (_ephemeralOpts.on_capture) _ephemeralOpts.on_capture(capture);
1161
+ }
1162
+ liveTimers.delete(slug);
1163
+ }
1164
+ });
1165
+ });
1166
+ });
1167
+ obs.observe(document.body, { childList: true, subtree: true });
1168
+ return obs;
1169
+ }
1170
+
1171
+ /* ------------------------------------------------------------- tenant */
1172
+
1173
+ var _tenantPrefix = null;
1174
+ function setTenantPrefix(slug) {
1175
+ if (_tenantPrefix !== null) {
1176
+ throw new Error('[NAC v2] tenant_prefix_locked: already set to ' + _tenantPrefix);
1177
+ }
1178
+ _validateLeaf(slug);
1179
+ _tenantPrefix = slug;
1180
+ }
1181
+ function getTenantPrefix() { return _tenantPrefix; }
1182
+
1183
+ /* ------------------------------------------------------------- describe v2 */
1184
+
1185
+ /* Augment v1.9's describe() with v2 additions when called.
1186
+ We don't replace the v1.9 function; we expose a new
1187
+ `describe_v2()` and decorate the v1 result. */
1188
+ /* v2.0-rc3 (Claude T3.1): track intermediate scope nodes so
1189
+ describe_v2 can expose their label_i18n. Without this,
1190
+ a catalog declares `shell.topbar` label but no consumer
1191
+ reads it because the intermediate node has no element.
1192
+
1193
+ v2.0-rc4 (Mistral T7-F2): the index grows monotonically with
1194
+ unique scope paths created. Realistic SPA case is bounded
1195
+ (~6 levels x ~few sections = O(N small)) but an SPA that
1196
+ dynamically creates and discards scopes can leak. WeakMap
1197
+ was rejected because keys are strings (paths), not objects.
1198
+ Solution: NAC.gcIntermediateScopes(activePathSet) lets the
1199
+ host prune entries no longer in use. Default behaviour:
1200
+ no automatic GC; documented growth pattern. */
1201
+ var _intermediateScopes = Object.create(null);
1202
+
1203
+ /* v2.0-rc5 (spec sec 17): optional sitemap primitive. Hosts with
1204
+ 50+ logical screens declare the full path catalog so the
1205
+ intermediary can plan navigation to slugs not currently in
1206
+ the visible tree. Authority separation is CRITICAL: the
1207
+ sitemap is navigational metadata only, never a source of
1208
+ can-operate truth. The visible tree (_scopes / v1 manifest)
1209
+ remains the only authority for dispatch. */
1210
+ var _sitemap = null; /* { paths: [...] } or null */
1211
+
1212
+ function declareSitemap(spec) {
1213
+ if (spec === null || typeof spec === 'undefined') {
1214
+ _sitemap = null;
1215
+ return;
1216
+ }
1217
+ if (typeof spec !== 'object' || !Array.isArray(spec.paths)) {
1218
+ throw new Error('[NAC v2] declareSitemap: spec must be { paths: [...] }');
1219
+ }
1220
+ var seenSlugs = Object.create(null);
1221
+ var clean = [];
1222
+ for (var i = 0; i < spec.paths.length; i++) {
1223
+ var p = spec.paths[i];
1224
+ if (!p || typeof p.slug !== 'string' || p.slug === '') {
1225
+ throw new Error('[NAC v2] declareSitemap: paths[' + i + '].slug required');
1226
+ }
1227
+ if (seenSlugs[p.slug]) {
1228
+ throw new Error('[NAC v2] declareSitemap: duplicate slug "' + p.slug + '"');
1229
+ }
1230
+ seenSlugs[p.slug] = true;
1231
+ var entry = { slug: p.slug };
1232
+ if (p.label_i18n && typeof p.label_i18n === 'object') {
1233
+ entry.label_i18n = p.label_i18n;
1234
+ }
1235
+ if (Array.isArray(p.affordance_to_navigate)) {
1236
+ entry.affordance_to_navigate = p.affordance_to_navigate.slice();
1237
+ }
1238
+ if (Array.isArray(p.requires_permission)) {
1239
+ entry.requires_permission = p.requires_permission.slice();
1240
+ }
1241
+ if (Array.isArray(p.tags)) {
1242
+ entry.tags = p.tags.slice();
1243
+ }
1244
+ clean.push(entry);
1245
+ }
1246
+ _sitemap = { paths: clean };
1247
+ }
1248
+
1249
+ function getSitemap() {
1250
+ if (!_sitemap) return null;
1251
+ /* return a defensive shallow copy so callers cannot mutate
1252
+ internal state */
1253
+ return { paths: _sitemap.paths.slice() };
1254
+ }
1255
+
1256
+ /* Public GC API (rc4): the host passes a Set or array of path
1257
+ strings that are still considered "active". Any entry in the
1258
+ index whose path is NOT in that set gets removed. */
1259
+ function gcIntermediateScopes(activePaths) {
1260
+ if (!activePaths) {
1261
+ /* No-arg form: clear ALL intermediate scopes. Use only when
1262
+ tearing down the SPA / navigating to a totally new shell. */
1263
+ _intermediateScopes = Object.create(null);
1264
+ return 0;
1265
+ }
1266
+ var active = (typeof activePaths.has === 'function')
1267
+ ? activePaths
1268
+ : new Set(activePaths);
1269
+ var removed = 0;
1270
+ Object.keys(_intermediateScopes).forEach(function (k) {
1271
+ if (!active.has(k)) {
1272
+ delete _intermediateScopes[k];
1273
+ removed++;
1274
+ }
1275
+ });
1276
+ return removed;
1277
+ }
1278
+
1279
+ function describe_v2() {
1280
+ var v1 = (typeof NAC.describe === 'function') ? NAC.describe() : { plugins: [] };
1281
+ var scopeEntries = Object.keys(_scopes).map(function (k) {
1282
+ var e = _scopes[k];
1283
+ return {
1284
+ slug: e.slug,
1285
+ role: e.role,
1286
+ intent: e.intent,
1287
+ autoderived: e.autoderived || false,
1288
+ adopted: e.adopted || false,
1289
+ irreversible: e.irreversible || false,
1290
+ parent_chain: e.parent_chain || null,
1291
+ has_element: !!e.element
1292
+ };
1293
+ });
1294
+ var intermediateScopes = Object.keys(_intermediateScopes).map(function (k) {
1295
+ return {
1296
+ slug: k,
1297
+ depth: _intermediateScopes[k].depth,
1298
+ label_i18n: _intermediateScopes[k].label_i18n,
1299
+ is_intermediate: true
1300
+ };
1301
+ });
1302
+ var virtual_summary = _virtuals.map(function (v) {
1303
+ var count = typeof v.count === 'function' ? v.count() : v.count;
1304
+ return { slug_pattern: v.slug_pattern, count: count };
1305
+ });
1306
+ /* v2.1 sec 18: surface every registered data-table so the
1307
+ chatbot intermediary, RPA bot and test runner all see the
1308
+ same snapshot. data_tables is [] when no host has called
1309
+ registerDataTable(). */
1310
+ var dataTables = (typeof NAC.__v2_dtSummariseAll === 'function')
1311
+ ? NAC.__v2_dtSummariseAll()
1312
+ : [];
1313
+ return {
1314
+ nac_version: '2.1.0-rc1',
1315
+ timestamp: Date.now(),
1316
+ tenant_prefix: _tenantPrefix,
1317
+ v1_plugins: v1.plugins || [],
1318
+ v2_scope_entries: scopeEntries,
1319
+ v2_intermediate_scopes: intermediateScopes,
1320
+ virtual: virtual_summary,
1321
+ ephemeral_log: _ephemeralRing.slice(),
1322
+ locale: _currentLocale,
1323
+ supported_locales: _supported.slice(),
1324
+ /* v2.0-rc5 (spec sec 17): null when host has not declared a
1325
+ sitemap (small SPAs / demos); otherwise the path catalog.
1326
+ Intermediaries treat this as PLANNING data, not authority. */
1327
+ sitemap: _sitemap ? { paths: _sitemap.paths.slice() } : null,
1328
+ /* v2.1 (spec sec 18): registered data-tables with their full
1329
+ state. [] when no host has registered any. */
1330
+ data_tables: dataTables
1331
+ };
1332
+ }
1333
+
1334
+ /* ------------------------------------------------------------- validate v2 */
1335
+
1336
+ function validate_global_v2(opts) {
1337
+ opts = opts || {};
1338
+ var findings = { errors: [], warnings: [] };
1339
+ /* 2026-05-09 (Claude R6): drain runtime guard findings
1340
+ FIRST, before any early-return, so security-relevant
1341
+ events (script_override_claims_user, etc.) ALWAYS reach
1342
+ the validator output regardless of i18n severity. */
1343
+ for (var fi = 0; fi < _validatorFindings.length; fi++) {
1344
+ var rf = _validatorFindings[fi];
1345
+ var bkt = rf.severity === 'error' ? findings.errors : findings.warnings;
1346
+ bkt.push({
1347
+ code: rf.code,
1348
+ severity: rf.severity,
1349
+ timestamp: rf.timestamp,
1350
+ note: rf.note
1351
+ });
1352
+ }
1353
+ /* v2.0-rc2 (Grok T5-F1 + Mistral T5-F2): severity for missing-
1354
+ locale findings now honours the tolerance setting. Default
1355
+ at NAC-3 is 'warn'; hosts that need NAC-4-equivalent strict
1356
+ mode opt in via set_validation_tolerance({i18n_strict:'error'})
1357
+ OR pass opts.i18n_strict_severity explicitly. */
1358
+ var severity = opts.i18n_strict_severity || _validationTolerance.i18n_strict;
1359
+ if (severity === 'silent') return findings;
1360
+ var bucket = severity === 'error' ? findings.errors : findings.warnings;
1361
+
1362
+ if (opts.i18n_strict) {
1363
+ Object.keys(_catalog).forEach(function (key) {
1364
+ var entry = _catalog[key];
1365
+ var missing = _supported.filter(function (loc) { return !entry[loc]; });
1366
+ if (missing.length) {
1367
+ bucket.push({
1368
+ code: 'i18n_missing_locale',
1369
+ key: key,
1370
+ missing: missing,
1371
+ severity: severity
1372
+ });
1373
+ }
1374
+ Object.keys(entry).forEach(function (loc) {
1375
+ if (_supported.indexOf(loc) < 0) {
1376
+ /* invalid_locale always error: catalog has nonsense key */
1377
+ findings.errors.push({
1378
+ code: 'i18n_invalid_locale',
1379
+ key: key,
1380
+ locale: loc
1381
+ });
1382
+ }
1383
+ /* empty_string honours severity tolerance too */
1384
+ if (typeof entry[loc] === 'string' && entry[loc].length === 0) {
1385
+ bucket.push({ code: 'i18n_string_empty', key: key, locale: loc, severity: severity });
1386
+ }
1387
+ if (typeof entry[loc] === 'string' && entry[loc].length > 1000) {
1388
+ findings.warnings.push({ code: 'i18n_string_too_long', key: key, locale: loc });
1389
+ }
1390
+ });
1391
+ });
1392
+ /* Mono-locale autoderived warn (always warn -- this is a
1393
+ drift signal, not a correctness signal). */
1394
+ Object.keys(_scopes).forEach(function (slug) {
1395
+ if (_scopes[slug].autoderived) {
1396
+ findings.warnings.push({ code: 'i18n_mono_locale_autoderived', slug: slug });
1397
+ }
1398
+ });
1399
+ }
1400
+
1401
+ /* v2.0-rc4 (Claude T8.2 codification): at NAC-3, autoderived
1402
+ data-nac-action is SHOULD with REQUIRED fallback. Emit
1403
+ data_nac_action_autoderived per scope where the action was
1404
+ inferred rather than declared. Severity follows
1405
+ _validationTolerance.autoderived_action (default warn). */
1406
+ var autodSev = opts.autoderived_action_severity
1407
+ || _validationTolerance.autoderived_action;
1408
+ if (autodSev !== 'silent') {
1409
+ var autodBucket = autodSev === 'error' ? findings.errors : findings.warnings;
1410
+ Object.keys(_scopes).forEach(function (slug) {
1411
+ var entry = _scopes[slug];
1412
+ if (entry.element && !entry.element.hasAttribute('data-nac-action')) {
1413
+ /* Only emit for elements that DO have a registered
1414
+ intent but lack the explicit data-nac-action attr.
1415
+ autoRegister-only path: the slug exists in _scopes
1416
+ but the host did not declare data-nac-action. */
1417
+ if (entry.autoderived || entry.adopted) {
1418
+ autodBucket.push({
1419
+ code: 'data_nac_action_autoderived',
1420
+ slug: slug,
1421
+ severity: autodSev
1422
+ });
1423
+ }
1424
+ }
1425
+ });
1426
+ }
1427
+ return findings;
1428
+ }
1429
+
1430
+ /* ------------------------------------------------------------- exports */
1431
+
1432
+ /* Attach v2 surface to NAC namespace without overwriting v1.9 */
1433
+ NAC.scope = scope;
1434
+ NAC.autoRegister = autoRegister;
1435
+ NAC.adopt = adopt;
1436
+ NAC.bridgeShadowRoot = bridgeShadowRoot;
1437
+ NAC.bridgeIframe = bridgeIframe;
1438
+ NAC.declareVirtual = declareVirtual;
1439
+ NAC.captureEphemeral = captureEphemeral;
1440
+ NAC.setTenantPrefix = setTenantPrefix;
1441
+ NAC.getTenantPrefix = getTenantPrefix;
1442
+ NAC.attestUserGesture = attestUserGesture;
1443
+ NAC.setMobileWebViewAttestation = setMobileWebViewAttestation;
1444
+ NAC.t = t;
1445
+ NAC.registerCatalog = registerCatalog;
1446
+ NAC.locale = locale;
1447
+ NAC.setSupportedLocales = setSupportedLocales;
1448
+ NAC.setRTLLocales = setRTLLocales;
1449
+ NAC.setAutoRTL = setAutoRTL;
1450
+ NAC.set_provenance_secret = set_provenance_secret;
1451
+ NAC.set_perf_tolerance = set_perf_tolerance;
1452
+ NAC.get_perf_tolerance = get_perf_tolerance;
1453
+ NAC.set_validation_tolerance = set_validation_tolerance;
1454
+ NAC.get_validation_tolerance = get_validation_tolerance;
1455
+ NAC.describe_v2 = describe_v2;
1456
+ NAC.validate_global_v2 = validate_global_v2;
1457
+ NAC.gcIntermediateScopes = gcIntermediateScopes;
1458
+ NAC.declareSitemap = declareSitemap;
1459
+ NAC.getSitemap = getSitemap;
1460
+
1461
+ /* Convenience: expose internals for tests */
1462
+ NAC.__v2 = {
1463
+ SUPPORTED_LOCALES_DEFAULT: SUPPORTED_LOCALES_DEFAULT,
1464
+ SEPARATOR: SEPARATOR,
1465
+ MAX_DEPTH: MAX_DEPTH,
1466
+ _scopes: _scopes,
1467
+ _catalog: _catalog,
1468
+ _virtuals: _virtuals,
1469
+ _ephemeralRing: _ephemeralRing
1470
+ };
1471
+
1472
+ /* v2.0-rc3 (Claude T6-F2): warm SubtleCrypto's HMAC sign path
1473
+ at boot so the cold-start cost is paid once, not at first
1474
+ agent action. Best-effort: fails silently when no secret is
1475
+ registered yet (which is fine -- adopters that wire HMAC
1476
+ register the secret at boot). */
1477
+ function _warmCrypto() {
1478
+ if (typeof NAC.sign_provenance !== 'function') return;
1479
+ if (!_provenanceSecrets[0]) return;
1480
+ try {
1481
+ NAC.sign_provenance({ _warmup: true, ts: Date.now() }, _provenanceSecrets[0])
1482
+ .catch(function () {}); /* silently swallow warmup errors */
1483
+ } catch (_) {}
1484
+ }
1485
+ /* Defer warm to next tick so the secret-registration call has a
1486
+ chance to land first. Hosts that register the secret AFTER
1487
+ boot can manually call NAC.set_provenance_secret() which
1488
+ re-warms. */
1489
+ setTimeout(_warmCrypto, 0);
1490
+
1491
+ /* ------------------------------------------------------------- v2.1 data-table primitive (spec sec 18) */
1492
+ /* See docs/V2_1_DATA_TABLE_GUIDE.md for the adopter walk-through.
1493
+ Authority separation: the runtime owns the in-memory state,
1494
+ the host owns persistence (commit handler does the HTTP/DB
1495
+ write). All operator classes (user, agent, bot) use the same
1496
+ dt_* API; the `by` discriminator on every emitted event lets
1497
+ audit pipelines attribute changes per source.type contract. */
1498
+
1499
+ var _dataTables = Object.create(null);
1500
+ /* { table_id -> {
1501
+ schema: {...}, // immutable post-register
1502
+ current_rows: [...], // collection: array of objects
1503
+ current_cells: [...], // matrix: array of {row, col, value}
1504
+ initial_state: deep_copy, // for discard()
1505
+ selected: Set<row_id>, // collection only
1506
+ modified: bool,
1507
+ computed_fns: { col_key -> fn(row, allRows) } } } */
1508
+
1509
+ function _dtDeepCopy(o) {
1510
+ /* JSON-roundtrip: cheap, preserves the primitive shapes our
1511
+ cells carry (string/number/boolean/null/array/plain object).
1512
+ If a host puts Date/Map in a cell we reject at register time. */
1513
+ return o === undefined ? undefined : JSON.parse(JSON.stringify(o));
1514
+ }
1515
+
1516
+ function _dtEmit(name, detail) {
1517
+ document.dispatchEvent(new CustomEvent(name, { detail: detail, bubbles: true }));
1518
+ }
1519
+
1520
+ function _dtBy() {
1521
+ /* Detect operator class. If the call originated from a recent
1522
+ attested user gesture, by='user'; otherwise by='agent'. The
1523
+ gesture buffer (rc3 T4-F1) is the source of truth. */
1524
+ try {
1525
+ if (typeof NAC.attestUserGesture === 'function') {
1526
+ var gesture = NAC._readGestureAttested
1527
+ ? NAC._readGestureAttested()
1528
+ : null;
1529
+ if (gesture && gesture.attested) return 'user';
1530
+ }
1531
+ } catch (_) {}
1532
+ return 'agent';
1533
+ }
1534
+
1535
+ /* v2.3: drainable data-table registration.
1536
+
1537
+ Hosts that register a data-table from an async chain
1538
+ (fetch().then(refresh) -> render -> registerDataTable) expose a
1539
+ race window where an agent action plan can dispatch dt_* against a
1540
+ table_id whose owner panel has rendered visually but whose
1541
+ `_dataTables[table_id]` entry has not been seeded yet. The dt_*
1542
+ primitives stay synchronous (`throw` on missing); v2.3 adds
1543
+ `awaitDataTable(table_id, timeoutMs)` so dispatchers can await
1544
+ registration before invoking the sync primitive.
1545
+
1546
+ Returns Promise<boolean>: true once the table is registered,
1547
+ false on timeout. timeoutMs defaults to NAC.DT_AWAIT_MS (600). */
1548
+ function awaitDataTable(table_id, timeoutMs) {
1549
+ var ms = (typeof timeoutMs === 'number')
1550
+ ? timeoutMs
1551
+ : (typeof NAC.DT_AWAIT_MS === 'number' ? NAC.DT_AWAIT_MS : 600);
1552
+ return new Promise(function (resolve) {
1553
+ if (_dataTables[table_id]) return resolve(true);
1554
+ if (!(ms > 0)) return resolve(false);
1555
+ var elapsed = 0;
1556
+ var step = 25;
1557
+ (function poll() {
1558
+ if (_dataTables[table_id]) return resolve(true);
1559
+ elapsed += step;
1560
+ if (elapsed >= ms) return resolve(false);
1561
+ setTimeout(poll, step);
1562
+ })();
1563
+ });
1564
+ }
1565
+
1566
+ function _dtCheckColumnValue(col, value) {
1567
+ if (value === null || value === undefined) {
1568
+ if (col.required) return { ok: false, error: 'required_missing' };
1569
+ return { ok: true };
1570
+ }
1571
+ var t = col.type;
1572
+ if (t === 'number' || t === 'currency') {
1573
+ if (typeof value !== 'number' || !isFinite(value)) {
1574
+ return { ok: false, error: 'invalid_type:expected_number' };
1575
+ }
1576
+ if (typeof col.min === 'number' && value < col.min) {
1577
+ return { ok: false, error: 'below_min:' + col.min };
1578
+ }
1579
+ if (typeof col.max === 'number' && value > col.max) {
1580
+ return { ok: false, error: 'above_max:' + col.max };
1581
+ }
1582
+ } else if (t === 'boolean') {
1583
+ if (typeof value !== 'boolean') {
1584
+ return { ok: false, error: 'invalid_type:expected_boolean' };
1585
+ }
1586
+ } else if (t === 'select') {
1587
+ var opts = col.options || [];
1588
+ var ok = opts.some(function (o) { return (o.value !== undefined ? o.value : o) === value; });
1589
+ if (!ok) return { ok: false, error: 'invalid_option' };
1590
+ } else if (t === 'date') {
1591
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}/.test(value)) {
1592
+ return { ok: false, error: 'invalid_type:expected_date_iso' };
1593
+ }
1594
+ } else {
1595
+ /* text and others: just require string-like */
1596
+ if (typeof value !== 'string' && typeof value !== 'number') {
1597
+ return { ok: false, error: 'invalid_type:expected_text' };
1598
+ }
1599
+ }
1600
+ return { ok: true };
1601
+ }
1602
+
1603
+ function _dtRecomputeRow(table, row) {
1604
+ /* Recompute every column whose `computed:true` and a fn is
1605
+ registered. */
1606
+ var changed = false;
1607
+ table.schema.columns.forEach(function (col) {
1608
+ if (!col.computed) return;
1609
+ var fn = table.computed_fns[col.key];
1610
+ if (!fn) return;
1611
+ try {
1612
+ var newVal = fn(row, table.current_rows);
1613
+ if (row[col.key] !== newVal) {
1614
+ row[col.key] = newVal;
1615
+ changed = true;
1616
+ }
1617
+ } catch (_) { /* swallow; computed err leaves stale value */ }
1618
+ });
1619
+ return changed;
1620
+ }
1621
+
1622
+ function _dtRecomputeAggregates(table, prevAggs) {
1623
+ var aggs = {};
1624
+ var defs = table.schema.aggregates || {};
1625
+ Object.keys(defs).forEach(function (aggKey) {
1626
+ var cols = defs[aggKey] || [];
1627
+ aggs[aggKey] = {};
1628
+ cols.forEach(function (colKey) {
1629
+ if (colKey === '*') {
1630
+ aggs[aggKey]['*'] = aggKey === 'count' ? table.current_rows.length : 0;
1631
+ return;
1632
+ }
1633
+ var values = table.current_rows
1634
+ .map(function (r) { return r[colKey]; })
1635
+ .filter(function (v) { return typeof v === 'number' && isFinite(v); });
1636
+ if (aggKey === 'sum') {
1637
+ aggs[aggKey][colKey] = values.reduce(function (s, v) { return s + v; }, 0);
1638
+ } else if (aggKey === 'avg') {
1639
+ aggs[aggKey][colKey] = values.length
1640
+ ? values.reduce(function (s, v) { return s + v; }, 0) / values.length
1641
+ : 0;
1642
+ } else if (aggKey === 'count') {
1643
+ aggs[aggKey][colKey] = values.length;
1644
+ } else if (aggKey === 'min') {
1645
+ aggs[aggKey][colKey] = values.length ? Math.min.apply(null, values) : null;
1646
+ } else if (aggKey === 'max') {
1647
+ aggs[aggKey][colKey] = values.length ? Math.max.apply(null, values) : null;
1648
+ }
1649
+ });
1650
+ });
1651
+ /* Emit per (agg, column) pair when changed. */
1652
+ if (prevAggs) {
1653
+ Object.keys(aggs).forEach(function (aggKey) {
1654
+ Object.keys(aggs[aggKey]).forEach(function (colKey) {
1655
+ var oldV = (prevAggs[aggKey] || {})[colKey];
1656
+ var newV = aggs[aggKey][colKey];
1657
+ if (oldV !== newV) {
1658
+ _dtEmit('nac:dt:aggregate_changed', {
1659
+ table_id: table.schema.table_id,
1660
+ agg_key: aggKey, column: colKey, old: oldV, new: newV
1661
+ });
1662
+ }
1663
+ });
1664
+ });
1665
+ }
1666
+ return aggs;
1667
+ }
1668
+
1669
+ function _dtGenRowId(table) {
1670
+ var prefix = (table.schema.row_id_field || 'r').slice(0, 1).toUpperCase();
1671
+ var n = table.current_rows.length + 1;
1672
+ var candidate;
1673
+ do {
1674
+ candidate = prefix + n;
1675
+ n++;
1676
+ } while (table.current_rows.some(function (r) { return r[table.schema.row_id_field] === candidate; }));
1677
+ return candidate;
1678
+ }
1679
+
1680
+ function registerDataTable(spec) {
1681
+ if (!spec || typeof spec !== 'object') {
1682
+ throw new Error('[NAC v2.1] registerDataTable: spec must be an object');
1683
+ }
1684
+ if (typeof spec.table_id !== 'string' || !spec.table_id) {
1685
+ throw new Error('[NAC v2.1] registerDataTable: table_id required');
1686
+ }
1687
+ if (_dataTables[spec.table_id]) {
1688
+ throw new Error('[NAC v2.1] registerDataTable: table_id "'
1689
+ + spec.table_id + '" already registered');
1690
+ }
1691
+ var subkind = spec.subkind || 'collection';
1692
+ if (['collection', 'matrix', 'readonly'].indexOf(subkind) < 0) {
1693
+ throw new Error('[NAC v2.1] registerDataTable: invalid subkind "' + subkind + '"');
1694
+ }
1695
+ /* Subkind-specific validation. */
1696
+ if (subkind === 'matrix') {
1697
+ if (!spec.row_axis || !spec.column_axis) {
1698
+ throw new Error('[NAC v2.1] registerDataTable: matrix requires row_axis + column_axis');
1699
+ }
1700
+ } else {
1701
+ if (!Array.isArray(spec.columns) || !spec.columns.length) {
1702
+ throw new Error('[NAC v2.1] registerDataTable: collection/readonly requires columns[]');
1703
+ }
1704
+ if (!spec.row_id_field) {
1705
+ throw new Error('[NAC v2.1] registerDataTable: row_id_field required for collection');
1706
+ }
1707
+ }
1708
+ var schema = {
1709
+ table_id: spec.table_id,
1710
+ scope_owner: spec.scope_owner || null,
1711
+ subkind: subkind,
1712
+ transactional: spec.transactional !== false,
1713
+ row_id_field: spec.row_id_field || null,
1714
+ columns: spec.columns || [],
1715
+ row_axis: spec.row_axis || null,
1716
+ column_axis: spec.column_axis || null,
1717
+ cell_type: spec.cell_type || 'boolean',
1718
+ supports: spec.supports || [],
1719
+ selection_mode: spec.selection_mode || 'none',
1720
+ aggregates: spec.aggregates || {},
1721
+ validators: spec.validators || []
1722
+ };
1723
+ var table = {
1724
+ schema: schema,
1725
+ current_rows: subkind === 'matrix' ? [] : (_dtDeepCopy(spec.initial_rows) || []),
1726
+ current_cells: subkind === 'matrix' ? (_dtDeepCopy(spec.initial_cells) || []) : [],
1727
+ initial_state: subkind === 'matrix'
1728
+ ? { cells: _dtDeepCopy(spec.initial_cells) || [] }
1729
+ : { rows: _dtDeepCopy(spec.initial_rows) || [] },
1730
+ selected: new Set(),
1731
+ modified: false,
1732
+ computed_fns: Object.create(null),
1733
+ _aggregates_cache: null
1734
+ };
1735
+ _dataTables[spec.table_id] = table;
1736
+ table._aggregates_cache = _dtRecomputeAggregates(table, null);
1737
+ _dtEmit('nac:dt:registered', { table_id: spec.table_id, schema: schema });
1738
+ return spec.table_id;
1739
+ }
1740
+
1741
+ function unregisterDataTable(table_id) {
1742
+ if (_dataTables[table_id]) {
1743
+ delete _dataTables[table_id];
1744
+ _dtEmit('nac:dt:unregistered', { table_id: table_id });
1745
+ }
1746
+ }
1747
+
1748
+ /* v2.3: upsert variant of registerDataTable.
1749
+
1750
+ Real hosts re-run their NAC sync logic on every state render
1751
+ (the documented __nacSync pattern in LLM_WIRING sec 5). Calling
1752
+ registerDataTable twice for the same table_id throws
1753
+ "already registered", which forces every host author to either
1754
+ (a) hand-roll a registered-set + skip re-register guard
1755
+ (state drift risk -- rows fed from server stop refreshing),
1756
+ or (b) wrap each call in try/catch (silent failure if the call
1757
+ was inside a multi-statement sync function -- exactly the bug
1758
+ that hid invoice_edit_modal.lines under the v2.1 contract).
1759
+
1760
+ syncDataTable(spec) is the documented idempotent path: it
1761
+ unregisters the prior entry (if any) and registers the new spec
1762
+ atomically. Any in-progress dt_commit / dt_discard transactional
1763
+ state on the prior entry is discarded -- callers that care about
1764
+ drafts must commit first. Emits nac:dt:resynced after the
1765
+ register so audit pipelines can distinguish a fresh register
1766
+ from a host-driven refresh.
1767
+
1768
+ Compatible with the legacy register/unregister pair: if a host
1769
+ prefers explicit lifecycle, those exports still work unchanged. */
1770
+ function syncDataTable(spec) {
1771
+ if (!spec || typeof spec !== 'object') {
1772
+ throw new Error('[NAC v2.3] syncDataTable: spec must be an object');
1773
+ }
1774
+ if (typeof spec.table_id !== 'string' || !spec.table_id) {
1775
+ throw new Error('[NAC v2.3] syncDataTable: table_id required');
1776
+ }
1777
+ var was_registered = !!_dataTables[spec.table_id];
1778
+ if (was_registered) {
1779
+ delete _dataTables[spec.table_id];
1780
+ }
1781
+ var ret = registerDataTable(spec);
1782
+ if (was_registered) {
1783
+ _dtEmit('nac:dt:resynced', { table_id: spec.table_id });
1784
+ }
1785
+ return ret;
1786
+ }
1787
+
1788
+ function registerDataTableComputed(table_id, column_key, fn) {
1789
+ var t = _dataTables[table_id];
1790
+ if (!t) throw new Error('[NAC v2.1] data-table not registered: ' + table_id);
1791
+ if (typeof fn !== 'function') {
1792
+ throw new Error('[NAC v2.1] computed fn must be a function');
1793
+ }
1794
+ t.computed_fns[column_key] = fn;
1795
+ /* Recompute now so newly-attached fns reflect on existing rows. */
1796
+ t.current_rows.forEach(function (row) { _dtRecomputeRow(t, row); });
1797
+ var prev = t._aggregates_cache;
1798
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1799
+ }
1800
+
1801
+ function dt_state(table_id) {
1802
+ var t = _dataTables[table_id];
1803
+ if (!t) return null;
1804
+ if (t.schema.subkind === 'matrix') {
1805
+ return {
1806
+ cells: _dtDeepCopy(t.current_cells),
1807
+ modified: t.modified,
1808
+ valid: dt_validate(table_id).valid
1809
+ };
1810
+ }
1811
+ return {
1812
+ rows: _dtDeepCopy(t.current_rows),
1813
+ aggregates: _dtDeepCopy(t._aggregates_cache),
1814
+ modified: t.modified,
1815
+ valid: dt_validate(table_id).valid,
1816
+ selected_count: t.selected.size,
1817
+ selected_ids: Array.from(t.selected)
1818
+ };
1819
+ }
1820
+
1821
+ function dt_add_row(table_id, valuesByColumn) {
1822
+ var t = _dataTables[table_id];
1823
+ if (!t) throw new Error('[NAC v2.1] data-table not registered: ' + table_id);
1824
+ if (t.schema.subkind === 'matrix') {
1825
+ throw new Error('[NAC v2.1] add_row not applicable to matrix');
1826
+ }
1827
+ if (t.schema.subkind === 'readonly') {
1828
+ throw new Error('[NAC v2.1] add_row not allowed on readonly');
1829
+ }
1830
+ var values = valuesByColumn || {};
1831
+ var row = {};
1832
+ t.schema.columns.forEach(function (col) {
1833
+ if (col.key === t.schema.row_id_field) return;
1834
+ if (Object.prototype.hasOwnProperty.call(values, col.key)) {
1835
+ row[col.key] = values[col.key];
1836
+ } else if (col.required && !col.computed) {
1837
+ /* required but missing -- caller must provide */
1838
+ }
1839
+ });
1840
+ /* Row id: caller-provided OR auto-generated. */
1841
+ var rowId = values[t.schema.row_id_field];
1842
+ if (!rowId) rowId = _dtGenRowId(t);
1843
+ row[t.schema.row_id_field] = rowId;
1844
+ /* Validate every provided column. */
1845
+ var fail = null;
1846
+ t.schema.columns.forEach(function (col) {
1847
+ if (fail) return;
1848
+ if (col.computed) return;
1849
+ var v = row[col.key];
1850
+ var check = _dtCheckColumnValue(col, v);
1851
+ if (!check.ok) fail = { column: col.key, error: check.error };
1852
+ });
1853
+ if (fail) {
1854
+ _dtEmit('nac:dt:validation_failed', {
1855
+ table_id: t.schema.table_id,
1856
+ errors: [{ code: 'add_row_invalid', column: fail.column, message_i18n: { en: fail.error } }]
1857
+ });
1858
+ return { row_id: null, ok: false, error: fail.error, column: fail.column };
1859
+ }
1860
+ t.current_rows.push(row);
1861
+ _dtRecomputeRow(t, row);
1862
+ var prev = t._aggregates_cache;
1863
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1864
+ t.modified = true;
1865
+ _dtEmit('nac:dt:row_added', {
1866
+ table_id: t.schema.table_id, row: _dtDeepCopy(row), by: _dtBy()
1867
+ });
1868
+ return { row_id: rowId, ok: true };
1869
+ }
1870
+
1871
+ function dt_remove_row(table_id, row_id) {
1872
+ var t = _dataTables[table_id];
1873
+ if (!t || t.schema.subkind === 'matrix' || t.schema.subkind === 'readonly') return;
1874
+ var idx = -1;
1875
+ for (var i = 0; i < t.current_rows.length; i++) {
1876
+ if (t.current_rows[i][t.schema.row_id_field] === row_id) { idx = i; break; }
1877
+ }
1878
+ if (idx < 0) return;
1879
+ t.current_rows.splice(idx, 1);
1880
+ t.selected.delete(row_id);
1881
+ var prev = t._aggregates_cache;
1882
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1883
+ t.modified = true;
1884
+ _dtEmit('nac:dt:row_removed', {
1885
+ table_id: t.schema.table_id, row_id: row_id, by: _dtBy()
1886
+ });
1887
+ }
1888
+
1889
+ function dt_edit_cell(table_id, row_id, column_key, value) {
1890
+ var t = _dataTables[table_id];
1891
+ if (!t) return { ok: false, error: 'table_not_registered' };
1892
+ if (t.schema.subkind === 'matrix') {
1893
+ return { ok: false, error: 'use_dt_set_cell_for_matrix' };
1894
+ }
1895
+ if (t.schema.subkind === 'readonly') return { ok: false, error: 'readonly' };
1896
+ var col = t.schema.columns.filter(function (c) { return c.key === column_key; })[0];
1897
+ if (!col) return { ok: false, error: 'column_not_found' };
1898
+ /* computed wins over editable -- a column declared
1899
+ `computed:true` is implicitly non-editable even if the
1900
+ host forgets to set editable:false. Spec sec 18.4 ordering. */
1901
+ if (col.computed) return { ok: false, error: 'computed_column' };
1902
+ if (!col.editable) return { ok: false, error: 'column_not_editable' };
1903
+ var check = _dtCheckColumnValue(col, value);
1904
+ if (!check.ok) {
1905
+ _dtEmit('nac:dt:validation_failed', {
1906
+ table_id: t.schema.table_id,
1907
+ errors: [{ code: 'edit_cell_invalid', row_id: row_id, column: column_key,
1908
+ message_i18n: { en: check.error } }]
1909
+ });
1910
+ return { ok: false, error: check.error };
1911
+ }
1912
+ var row = t.current_rows.filter(function (r) {
1913
+ return r[t.schema.row_id_field] === row_id;
1914
+ })[0];
1915
+ if (!row) return { ok: false, error: 'row_not_found' };
1916
+ var oldVal = row[column_key];
1917
+ if (oldVal === value) return { ok: true, unchanged: true };
1918
+ row[column_key] = value;
1919
+ _dtRecomputeRow(t, row);
1920
+ var prev = t._aggregates_cache;
1921
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1922
+ t.modified = true;
1923
+ _dtEmit('nac:dt:cell_edited', {
1924
+ table_id: t.schema.table_id,
1925
+ row_id: row_id, column: column_key,
1926
+ old: oldVal, new: value, by: _dtBy()
1927
+ });
1928
+ return { ok: true };
1929
+ }
1930
+
1931
+ function dt_read_aggregate(table_id, agg_key, column_key) {
1932
+ var t = _dataTables[table_id];
1933
+ if (!t) return null;
1934
+ if (!t._aggregates_cache || !t._aggregates_cache[agg_key]) return null;
1935
+ var v = t._aggregates_cache[agg_key][column_key];
1936
+ return v === undefined ? null : v;
1937
+ }
1938
+
1939
+ function dt_validate(table_id) {
1940
+ var t = _dataTables[table_id];
1941
+ if (!t) return { valid: false, errors: [{ code: 'table_not_registered' }] };
1942
+ var errors = [];
1943
+ /* Per-row validators. */
1944
+ (t.schema.validators || []).forEach(function (v) {
1945
+ if (v.kind !== 'row') return;
1946
+ t.current_rows.forEach(function (row) {
1947
+ var cellVal = row[v.column];
1948
+ var ok = _dtCheckOp(cellVal, v.op, v.value);
1949
+ if (!ok) errors.push({
1950
+ code: v.code, row_id: row[t.schema.row_id_field],
1951
+ column: v.column, message_i18n: v.message_i18n || null
1952
+ });
1953
+ });
1954
+ });
1955
+ /* Table-level validators. */
1956
+ (t.schema.validators || []).forEach(function (v) {
1957
+ if (v.kind !== 'table') return;
1958
+ if (v.unique_columns) {
1959
+ var seen = Object.create(null);
1960
+ t.current_rows.forEach(function (row) {
1961
+ var key = v.unique_columns.map(function (c) { return row[c]; }).join('|');
1962
+ if (seen[key]) {
1963
+ errors.push({
1964
+ code: v.code, row_id: row[t.schema.row_id_field],
1965
+ message_i18n: v.message_i18n || null
1966
+ });
1967
+ }
1968
+ seen[key] = true;
1969
+ });
1970
+ }
1971
+ if (typeof v.min_rows === 'number' && t.current_rows.length < v.min_rows) {
1972
+ errors.push({ code: v.code, message_i18n: v.message_i18n || null });
1973
+ }
1974
+ if (typeof v.max_rows === 'number' && t.current_rows.length > v.max_rows) {
1975
+ errors.push({ code: v.code, message_i18n: v.message_i18n || null });
1976
+ }
1977
+ });
1978
+ /* Required-column validator (implicit). */
1979
+ t.schema.columns.forEach(function (col) {
1980
+ if (!col.required || col.computed) return;
1981
+ t.current_rows.forEach(function (row) {
1982
+ var v = row[col.key];
1983
+ if (v === null || v === undefined || v === '') {
1984
+ errors.push({
1985
+ code: 'required_missing', row_id: row[t.schema.row_id_field],
1986
+ column: col.key, message_i18n: { en: 'Required column missing' }
1987
+ });
1988
+ }
1989
+ });
1990
+ });
1991
+ return { valid: errors.length === 0, errors: errors };
1992
+ }
1993
+
1994
+ function _dtCheckOp(cellVal, op, value) {
1995
+ switch (op) {
1996
+ case 'gt': return typeof cellVal === 'number' && cellVal > value;
1997
+ case 'gte': return typeof cellVal === 'number' && cellVal >= value;
1998
+ case 'lt': return typeof cellVal === 'number' && cellVal < value;
1999
+ case 'lte': return typeof cellVal === 'number' && cellVal <= value;
2000
+ case 'eq': return cellVal === value;
2001
+ case 'neq': return cellVal !== value;
2002
+ case 'in': return Array.isArray(value) && value.indexOf(cellVal) >= 0;
2003
+ case 'matches': return typeof cellVal === 'string' && new RegExp(value).test(cellVal);
2004
+ default: return true;
2005
+ }
2006
+ }
2007
+
2008
+ function dt_select(table_id, target) {
2009
+ var t = _dataTables[table_id];
2010
+ if (!t || t.schema.subkind === 'matrix') return { selected_count: 0 };
2011
+ var ids = [];
2012
+ if (target === null || target === 'none') {
2013
+ ids = [];
2014
+ } else if (target === 'all' || target === 'visible') {
2015
+ ids = t.current_rows.map(function (r) { return r[t.schema.row_id_field]; });
2016
+ } else if (Array.isArray(target)) {
2017
+ ids = target.slice();
2018
+ } else if (target && target.column && target.op) {
2019
+ ids = t.current_rows
2020
+ .filter(function (r) { return _dtCheckOp(r[target.column], target.op, target.value); })
2021
+ .map(function (r) { return r[t.schema.row_id_field]; });
2022
+ } else if (typeof target === 'string') {
2023
+ ids = [target];
2024
+ }
2025
+ t.selected = new Set(ids);
2026
+ _dtEmit('nac:dt:selection_changed', {
2027
+ table_id: t.schema.table_id,
2028
+ selected_count: t.selected.size,
2029
+ selected_ids: Array.from(t.selected)
2030
+ });
2031
+ return { selected_count: t.selected.size };
2032
+ }
2033
+
2034
+ function dt_set_cell(table_id, row_slug, col_slug, value) {
2035
+ var t = _dataTables[table_id];
2036
+ if (!t) return { ok: false, error: 'table_not_registered' };
2037
+ if (t.schema.subkind !== 'matrix') {
2038
+ return { ok: false, error: 'use_dt_edit_cell_for_collection' };
2039
+ }
2040
+ /* Validate row/col exist on the axes. */
2041
+ var rowKnown = (t.schema.row_axis.values || [])
2042
+ .some(function (r) { return r.slug === row_slug; });
2043
+ var colKnown = (t.schema.column_axis.values || [])
2044
+ .some(function (c) { return c.slug === col_slug; });
2045
+ if (!rowKnown) return { ok: false, error: 'row_not_in_axis' };
2046
+ if (!colKnown) return { ok: false, error: 'col_not_in_axis' };
2047
+ var existing = null;
2048
+ for (var i = 0; i < t.current_cells.length; i++) {
2049
+ if (t.current_cells[i].row === row_slug && t.current_cells[i].col === col_slug) {
2050
+ existing = t.current_cells[i]; break;
2051
+ }
2052
+ }
2053
+ var oldVal = existing ? existing.value : undefined;
2054
+ if (oldVal === value) return { ok: true, unchanged: true };
2055
+ if (existing) {
2056
+ existing.value = value;
2057
+ } else {
2058
+ t.current_cells.push({ row: row_slug, col: col_slug, value: value });
2059
+ }
2060
+ t.modified = true;
2061
+ _dtEmit('nac:dt:matrix_cell_set', {
2062
+ table_id: t.schema.table_id,
2063
+ row: row_slug, col: col_slug, old: oldVal, new: value, by: _dtBy()
2064
+ });
2065
+ return { ok: true };
2066
+ }
2067
+
2068
+ function dt_get_cell(table_id, row_slug, col_slug) {
2069
+ var t = _dataTables[table_id];
2070
+ if (!t || t.schema.subkind !== 'matrix') return undefined;
2071
+ for (var i = 0; i < t.current_cells.length; i++) {
2072
+ if (t.current_cells[i].row === row_slug && t.current_cells[i].col === col_slug) {
2073
+ return t.current_cells[i].value;
2074
+ }
2075
+ }
2076
+ return undefined;
2077
+ }
2078
+
2079
+ function dt_commit(table_id) {
2080
+ var t = _dataTables[table_id];
2081
+ if (!t) return { ok: false, error: 'table_not_registered' };
2082
+ var v = dt_validate(table_id);
2083
+ if (!v.valid) {
2084
+ _dtEmit('nac:dt:validation_failed', {
2085
+ table_id: t.schema.table_id, errors: v.errors
2086
+ });
2087
+ return { ok: false, errors: v.errors };
2088
+ }
2089
+ /* Build audit diff vs initial_state. */
2090
+ var initial = t.initial_state;
2091
+ var finalState = t.schema.subkind === 'matrix'
2092
+ ? { cells: _dtDeepCopy(t.current_cells) }
2093
+ : { rows: _dtDeepCopy(t.current_rows) };
2094
+ /* Reset modified + replace initial_state so a subsequent
2095
+ discard would revert to THIS state, not the original. */
2096
+ t.initial_state = _dtDeepCopy(finalState);
2097
+ t.modified = false;
2098
+ _dtEmit('nac:dt:committed', {
2099
+ table_id: t.schema.table_id,
2100
+ final_state: finalState,
2101
+ audit_diff: { initial: initial, final: finalState }
2102
+ });
2103
+ return { ok: true, final_state: finalState };
2104
+ }
2105
+
2106
+ function dt_discard(table_id) {
2107
+ var t = _dataTables[table_id];
2108
+ if (!t) return;
2109
+ if (t.schema.subkind === 'matrix') {
2110
+ t.current_cells = _dtDeepCopy(t.initial_state.cells) || [];
2111
+ } else {
2112
+ t.current_rows = _dtDeepCopy(t.initial_state.rows) || [];
2113
+ }
2114
+ t.selected.clear();
2115
+ var prev = t._aggregates_cache;
2116
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
2117
+ t.modified = false;
2118
+ _dtEmit('nac:dt:discarded', { table_id: t.schema.table_id });
2119
+ }
2120
+
2121
+ /* describe_v2() extension: surface every registered data-table. */
2122
+ function _dtSummariseAll() {
2123
+ var out = [];
2124
+ Object.keys(_dataTables).forEach(function (id) {
2125
+ var t = _dataTables[id];
2126
+ out.push({
2127
+ table_id: id,
2128
+ scope_owner: t.schema.scope_owner,
2129
+ subkind: t.schema.subkind,
2130
+ schema: {
2131
+ columns: t.schema.columns,
2132
+ row_axis: t.schema.row_axis,
2133
+ column_axis: t.schema.column_axis,
2134
+ supports: t.schema.supports,
2135
+ aggregates: t.schema.aggregates,
2136
+ selection_mode: t.schema.selection_mode,
2137
+ row_id_field: t.schema.row_id_field
2138
+ },
2139
+ current_state: dt_state(id)
2140
+ });
2141
+ });
2142
+ return out;
2143
+ }
2144
+
2145
+ /* v2.4 (V24-02): NAC.describe() snapshot consolidation.
2146
+
2147
+ Multi-instance plugins (the same slug carried by multiple DOM
2148
+ roots disambiguated via data-nac-plugin-id, per SPEC sec 7.4)
2149
+ are a legitimate construct -- a single plugin can split its UI
2150
+ across a topbar root + a main root + a footer root.
2151
+
2152
+ v2.1 describe() returned one plugins[] entry per DOM root.
2153
+ Snapshot consumers (LLM agents, in particular) then saw the
2154
+ same nac_id appearing multiple times in plugins[*].elements[*]
2155
+ -- once per root, sometimes with contradictory visibility
2156
+ flags after the v2.3 wrapper synth's manifest-declared but
2157
+ DOM-absent elements into every entry that shares the slug.
2158
+
2159
+ Empirical evidence (pilot 2026-05-19, see V24-02 in
2160
+ CHANGELOG): Sonnet T_MCP1 NAC3 7/15 (47%); MCP + Raw both
2161
+ 4/4 on the same model + task. Trace shows Sonnet's CoT
2162
+ explicitly verbalising "the confirm dialog is already
2163
+ active" because it integrated the contradiction between two
2164
+ visibility states for the same nac_id.
2165
+
2166
+ v2.4 contract: NAC.describe() output guarantees every nac_id
2167
+ appears at most once across plugins[*].elements[*]. Multi-
2168
+ instance plugins consolidate into one entry per slug; the
2169
+ element list is deduped by nac_id with visible:true winning
2170
+ over visible:false. Per-instance state is exposed via
2171
+ plugins[].instances[] for hosts that care.
2172
+
2173
+ validate_global() ('duplicate_nac_id_in_snapshot') enforces
2174
+ this at lint time; the runtime guarantee makes it always
2175
+ pass on a fresh snapshot. */
2176
+ function _consolidatePluginEntries(rawPlugins) {
2177
+ if (!Array.isArray(rawPlugins) || rawPlugins.length === 0) return rawPlugins || [];
2178
+ var bySlug = Object.create(null);
2179
+ var order = [];
2180
+ for (var i = 0; i < rawPlugins.length; i++) {
2181
+ var p = rawPlugins[i];
2182
+ if (!p) continue;
2183
+ var slug = p.plugin || p.plugin_slug || p.slug;
2184
+ if (!slug) continue;
2185
+ var b = bySlug[slug];
2186
+ if (!b) {
2187
+ b = { plugin: slug, elements: [], indexById: Object.create(null), instances: [] };
2188
+ bySlug[slug] = b;
2189
+ order.push(slug);
2190
+ }
2191
+ var inst = { plugin_state: p.plugin_state || p.state || 'idle' };
2192
+ /* Surface the instance discriminator when the host followed
2193
+ SPEC sec 7.4 and tagged each root with data-nac-plugin-id.
2194
+ describe() does not expose the attribute today, but if a
2195
+ downstream wrapper attaches it (e.g. installVisibilityHints)
2196
+ we forward it. */
2197
+ if (p.instance_id) inst.instance_id = p.instance_id;
2198
+ b.instances.push(inst);
2199
+ var els = p.elements || [];
2200
+ for (var j = 0; j < els.length; j++) {
2201
+ var e = els[j];
2202
+ if (!e) continue;
2203
+ var id = e.nac_id || e.id;
2204
+ if (!id) {
2205
+ /* No nac_id -> not agent-addressable. Keep as-is; dedup
2206
+ does not apply. */
2207
+ b.elements.push(e);
2208
+ continue;
2209
+ }
2210
+ var prev = b.indexById[id];
2211
+ if (prev == null) {
2212
+ b.indexById[id] = b.elements.length;
2213
+ b.elements.push(e);
2214
+ continue;
2215
+ }
2216
+ /* Same nac_id seen in a different root for the same slug.
2217
+ Prefer the entry that reports visible:true -- the element
2218
+ IS reachable somewhere, so the snapshot should advertise
2219
+ that. Otherwise keep the first occurrence. */
2220
+ var prevEl = b.elements[prev];
2221
+ var prevVisible = prevEl.visible !== false;
2222
+ var thisVisible = e.visible !== false;
2223
+ if (thisVisible && !prevVisible) {
2224
+ b.elements[prev] = e;
2225
+ }
2226
+ }
2227
+ }
2228
+ var out = [];
2229
+ for (var k = 0; k < order.length; k++) {
2230
+ var slug2 = order[k];
2231
+ var bucket = bySlug[slug2];
2232
+ var entry = { plugin: bucket.plugin, elements: bucket.elements };
2233
+ if (bucket.instances.length === 1) {
2234
+ if (bucket.instances[0].plugin_state) entry.plugin_state = bucket.instances[0].plugin_state;
2235
+ } else {
2236
+ entry.plugin_state = bucket.instances[0].plugin_state;
2237
+ entry.instances = bucket.instances;
2238
+ }
2239
+ out.push(entry);
2240
+ }
2241
+ return out;
2242
+ }
2243
+
2244
+ function installSnapshotConsolidation() {
2245
+ if (typeof NAC === 'undefined' || NAC === null) return;
2246
+ if (NAC.__snapshot_consolidation_v24) return;
2247
+ var origDescribe = NAC.describe;
2248
+ if (typeof origDescribe !== 'function') return;
2249
+ NAC.describe = function () {
2250
+ var base = origDescribe.apply(this, arguments) || {};
2251
+ var consolidated = _consolidatePluginEntries(base.plugins || []);
2252
+ var out = {};
2253
+ for (var bk in base) if (Object.prototype.hasOwnProperty.call(base, bk)) out[bk] = base[bk];
2254
+ out.plugins = consolidated;
2255
+ return out;
2256
+ };
2257
+ NAC.__snapshot_consolidation_v24 = true;
2258
+ }
2259
+
2260
+ /* Exports for v2.1 data-table primitive. */
2261
+ NAC.registerDataTable = registerDataTable;
2262
+ NAC.unregisterDataTable = unregisterDataTable;
2263
+ NAC.syncDataTable = syncDataTable;
2264
+ NAC.registerDataTableComputed = registerDataTableComputed;
2265
+ NAC.dt_state = dt_state;
2266
+ NAC.dt_add_row = dt_add_row;
2267
+ NAC.dt_remove_row = dt_remove_row;
2268
+ NAC.dt_edit_cell = dt_edit_cell;
2269
+ NAC.dt_read_aggregate = dt_read_aggregate;
2270
+ NAC.dt_validate = dt_validate;
2271
+ NAC.dt_select = dt_select;
2272
+ NAC.dt_set_cell = dt_set_cell;
2273
+ NAC.dt_get_cell = dt_get_cell;
2274
+ NAC.dt_commit = dt_commit;
2275
+ NAC.dt_discard = dt_discard;
2276
+ NAC.awaitDataTable = awaitDataTable;
2277
+ if (typeof NAC.DT_AWAIT_MS !== 'number') NAC.DT_AWAIT_MS = 600;
2278
+ /* Exposed for tests + describe_v2 extension. */
2279
+ NAC.__v2_dataTables = _dataTables;
2280
+ NAC.__v2_dtSummariseAll = _dtSummariseAll;
2281
+
2282
+ /* Bump version constants */
2283
+ NAC.version_v2 = '2.3.0-rc1';
2284
+ NAC.spec_version_v2 = '2.3';
2285
+
2286
+ /* v2.2.1: guard browser-only dispatch so this bundle is importable
2287
+ in Node / SSR / test contexts. */
2288
+ if (typeof document !== 'undefined') {
2289
+ document.dispatchEvent(new CustomEvent('nac:v2_installed', {
2290
+ detail: { version: '2.0.0' }, bubbles: true
2291
+ }));
2292
+ }
2293
+ })(typeof window !== 'undefined' ? window : globalThis);
2105
2294
 
2106
2295
  module.exports = _g.NAC || _g.NACv2 || _g.NacChat;
2107
2296
  module.exports.NAC = _g.NAC;