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