@nac3/runtime 2.4.0 → 2.5.0-alpha.2

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.
package/dist/nac.cjs CHANGED
@@ -324,6 +324,791 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
324
324
  return e;
325
325
  }
326
326
 
327
+ /* ================================================================
328
+ v2.5 / RFC V24-01: Plugin slug uniqueness gate (spec sec 7.4)
329
+ ================================================================
330
+
331
+ When a plugin slug appears on more than one DOM root
332
+ simultaneously, every root MUST carry a unique
333
+ data-nac-plugin-id attribute. The runtime enforces via three
334
+ mechanisms:
335
+
336
+ NAC.register -> synchronous throw on the registered slug
337
+ boot-time pass -> nac:fatal + visible red banner at first
338
+ cross-slug violation, then refuse further
339
+ dispatches
340
+ validate_global -> structured finding for CI (non-fatal)
341
+
342
+ Gated by NAC.HARD_DEDUP (default true; set false for migration). */
343
+
344
+ /* _scanPluginInstances() walks the live DOM and groups every
345
+ [data-nac-plugin] root by its slug. For each group of >1 root,
346
+ it requires every root to carry a non-empty data-nac-plugin-id
347
+ AND for those ids to be pairwise unique. Returns a structured
348
+ findings array; never throws. */
349
+ function _scanPluginInstances() {
350
+ if (typeof document === 'undefined') return [];
351
+ const findings = [];
352
+ const bySlug = {};
353
+ const all = document.querySelectorAll('[data-nac-plugin]');
354
+ for (let i = 0; i < all.length; i++) {
355
+ const el = all[i];
356
+ const slug = el.getAttribute('data-nac-plugin') || '';
357
+ if (!slug) continue;
358
+ (bySlug[slug] = bySlug[slug] || []).push(el);
359
+ }
360
+ for (const slug in bySlug) {
361
+ if (!Object.prototype.hasOwnProperty.call(bySlug, slug)) continue;
362
+ const roots = bySlug[slug];
363
+ if (roots.length < 2) continue;
364
+ const ids = [];
365
+ const missing = [];
366
+ for (let r = 0; r < roots.length; r++) {
367
+ const id = roots[r].getAttribute('data-nac-plugin-id') || '';
368
+ if (!id) missing.push(roots[r]); else ids.push(id);
369
+ }
370
+ const dupIds = [];
371
+ const seen = {};
372
+ for (let j = 0; j < ids.length; j++) {
373
+ if (seen[ids[j]]) dupIds.push(ids[j]);
374
+ else seen[ids[j]] = 1;
375
+ }
376
+ if (missing.length > 0 || dupIds.length > 0) {
377
+ findings.push({
378
+ code: 'duplicate_plugin_no_instance_id',
379
+ severity: 'error',
380
+ slug: slug,
381
+ instance_count: roots.length,
382
+ missing_instance_id_count: missing.length,
383
+ duplicate_instance_ids: dupIds,
384
+ message: roots.length + ' DOM roots carry data-nac-plugin="'
385
+ + slug + '" but '
386
+ + (missing.length
387
+ ? missing.length + ' lack data-nac-plugin-id'
388
+ : 'two share data-nac-plugin-id "' + dupIds[0] + '"')
389
+ + '. Per SPEC sec 7.4, every root sharing a slug MUST '
390
+ + 'carry a unique data-nac-plugin-id.',
391
+ });
392
+ }
393
+ }
394
+ return findings;
395
+ }
396
+
397
+ /* _checkPluginSlugUniqueOrThrow(slug) is the synchronous gate used
398
+ by NAC.register(). Throws the first finding for the registered
399
+ slug; other-slug findings are ignored here -- the DOM-ready pass
400
+ below catches them globally. */
401
+ function _checkPluginSlugUniqueOrThrow(slug) {
402
+ const all = _scanPluginInstances();
403
+ for (let i = 0; i < all.length; i++) {
404
+ if (all[i].slug !== slug) continue;
405
+ throw NacError('duplicate_plugin_no_instance_id', all[i].message, {
406
+ slug: slug,
407
+ instance_count: all[i].instance_count,
408
+ missing_instance_id_count: all[i].missing_instance_id_count,
409
+ duplicate_instance_ids: all[i].duplicate_instance_ids,
410
+ });
411
+ }
412
+ }
413
+
414
+ /* _installPluginDedupBootGate() runs once at DOMContentLoaded and
415
+ enforces the same contract across every slug. On first violation
416
+ it dispatches nac:fatal, paints a red banner, and re-throws
417
+ asynchronously so test harnesses + browsers catch the error
418
+ instead of silently swallowing. */
419
+ let _bootDedupFatal = null;
420
+ function _installPluginDedupBootGate() {
421
+ if (typeof document === 'undefined') return;
422
+ const run = function () {
423
+ if (typeof global !== 'undefined' && global.NAC &&
424
+ global.NAC.HARD_DEDUP === false) return;
425
+ if (typeof window !== 'undefined' && window.NAC &&
426
+ window.NAC.HARD_DEDUP === false) return;
427
+ const findings = _scanPluginInstances();
428
+ if (findings.length === 0) return;
429
+ const f = findings[0];
430
+ const err = NacError('duplicate_plugin_no_instance_id', f.message, {
431
+ slug: f.slug,
432
+ instance_count: f.instance_count,
433
+ missing_instance_id_count: f.missing_instance_id_count,
434
+ duplicate_instance_ids: f.duplicate_instance_ids,
435
+ all_findings: findings,
436
+ });
437
+ _bootDedupFatal = err;
438
+ try {
439
+ document.dispatchEvent(new CustomEvent('nac:fatal', {
440
+ detail: { code: 'duplicate_plugin_no_instance_id',
441
+ slug: f.slug, message: f.message,
442
+ findings: findings },
443
+ }));
444
+ } catch (_) {}
445
+ try { _paintFatalBanner(err); } catch (_) {}
446
+ setTimeout(function () { throw err; }, 0);
447
+ };
448
+ if (document.readyState === 'loading') {
449
+ document.addEventListener('DOMContentLoaded', run, { once: true });
450
+ } else {
451
+ run();
452
+ }
453
+ }
454
+
455
+ function _paintFatalBanner(err) {
456
+ if (typeof document === 'undefined' || !document.body) return;
457
+ if (document.getElementById('__nac_fatal_banner__')) return;
458
+ const div = document.createElement('div');
459
+ div.id = '__nac_fatal_banner__';
460
+ div.setAttribute('role', 'alert');
461
+ div.style = 'position:fixed;top:0;left:0;right:0;z-index:2147483647;'
462
+ + 'background:#DC2626;color:#fff;font:600 14px/1.4 system-ui,sans-serif;'
463
+ + 'padding:12px 16px;box-shadow:0 2px 8px rgba(0,0,0,.25);';
464
+ div.textContent = '[NAC3 FATAL] ' + err.code + ': ' + err.message;
465
+ if (document.body.firstChild) {
466
+ document.body.insertBefore(div, document.body.firstChild);
467
+ } else {
468
+ document.body.appendChild(div);
469
+ }
470
+ }
471
+ /* /end V24-01 */
472
+
473
+ /* ==================================================================
474
+ v2.4 / RFC V24-04: Snapshot versioning + optimistic concurrency
475
+ ==================================================================
476
+
477
+ Promotes NAC3 from a decoration-and-verb contract to a real
478
+ agentic concurrency protocol. See docs/RFC_V24-04.md for the
479
+ full design + Appendix C for agent best practices. Three
480
+ primitives, in order an agent should typically use them:
481
+
482
+ plugin_version primary; per-plugin monotonic; ignores noise
483
+ outside the targeted plugin.
484
+ element_state_hash content-aware; 128-bit SHA-256 truncated.
485
+ tree_version escape hatch; global monotonic.
486
+
487
+ All three are returned by describe(); all three are honored as
488
+ expected_* parameters on every mutating API; mismatches reject
489
+ with NacError('snapshot_stale', { reason, ... }) and the side
490
+ effect does not occur.
491
+ */
492
+
493
+ /* ---- Internal state ---- */
494
+
495
+ let _tree_version = 0;
496
+ const _plugin_versions = new Map(); /* key: `${slug}|${instance_id||''}` */
497
+ const _version_history = []; /* circular buffer, max 500 */
498
+ const _plugin_scope_cache = (typeof WeakMap !== 'undefined')
499
+ ? new WeakMap() /* Element -> { slug, instance_id } */
500
+ : null;
501
+ let _hydration_complete = false;
502
+ let _hydration_fallback_timer = null;
503
+ let _mutation_observer = null;
504
+
505
+ /* STRICT_VERSIONING + eager_hashing + HARD_DEDUP are exposed via
506
+ the NAC export (bottom of the module) so hosts can flip them
507
+ before / after install. Internal mirrors keep hot-path checks
508
+ property-access-free in the most common cases. */
509
+ function _strictVersioningOn() {
510
+ return (typeof window !== 'undefined' && window.NAC &&
511
+ window.NAC.STRICT_VERSIONING === true);
512
+ }
513
+ function _eagerHashingOn() {
514
+ return (typeof window !== 'undefined' && window.NAC &&
515
+ window.NAC.eager_hashing === true);
516
+ }
517
+
518
+ /* ---- Plugin scope resolver (RFC sec 5.1.1) ----
519
+
520
+ "Plugin scope is logical, not physical." An element belongs to
521
+ the plugin declared by its nearest [data-nac-plugin] ancestor.
522
+ Portals/teleports that carry the attribute on their portaled
523
+ root inherit the right scope regardless of DOM hierarchy.
524
+
525
+ Cached per element via WeakMap to avoid O(depth) walks on every
526
+ mutation in high-rate paths (drag-drop, autocomplete filtering).
527
+ Cache entries invalidate naturally when the element is GC'd; we
528
+ also clear them on attribute mutations of data-nac-plugin* in
529
+ the observer below. */
530
+ function _resolvePluginScope(el) {
531
+ if (!el || el.nodeType !== 1) return null;
532
+ if (_plugin_scope_cache && _plugin_scope_cache.has(el)) {
533
+ return _plugin_scope_cache.get(el);
534
+ }
535
+ let cur = el;
536
+ while (cur && cur.nodeType === 1) {
537
+ if (cur.hasAttribute && cur.hasAttribute('data-nac-plugin')) {
538
+ const scope = {
539
+ slug: cur.getAttribute('data-nac-plugin') || '',
540
+ instance_id: cur.getAttribute('data-nac-plugin-id') || null,
541
+ };
542
+ if (_plugin_scope_cache) _plugin_scope_cache.set(el, scope);
543
+ return scope;
544
+ }
545
+ cur = cur.parentElement;
546
+ }
547
+ if (_plugin_scope_cache) _plugin_scope_cache.set(el, null);
548
+ return null;
549
+ }
550
+
551
+ function _pluginKey(slug, instance_id) {
552
+ return slug + '|' + (instance_id || '');
553
+ }
554
+ function _pluginVersionFor(slug, instance_id) {
555
+ return 'v_' + (_plugin_versions.get(_pluginKey(slug, instance_id)) || 0);
556
+ }
557
+ function _treeVersionStr() { return 'v_' + _tree_version; }
558
+
559
+ /* ---- Bump functions (RFC sec 8.1) ---- */
560
+
561
+ function _bumpTreeVersion(trigger, affected_plugins) {
562
+ _tree_version += 1;
563
+ _version_history.push({
564
+ at: Date.now(),
565
+ tree_version: _treeVersionStr(),
566
+ trigger: trigger,
567
+ affected_plugins: affected_plugins || [],
568
+ });
569
+ while (_version_history.length > 500) _version_history.shift();
570
+ if (typeof document !== 'undefined') {
571
+ document.dispatchEvent(new CustomEvent('nac:tree:invalidated', {
572
+ detail: {
573
+ from_version: 'v_' + (_tree_version - 1),
574
+ to_version: _treeVersionStr(),
575
+ trigger: trigger,
576
+ affected_plugins: affected_plugins || [],
577
+ },
578
+ }));
579
+ }
580
+ }
581
+
582
+ function _bumpPluginVersion(slug, instance_id, trigger) {
583
+ if (!slug) return;
584
+ const key = _pluginKey(slug, instance_id);
585
+ const prev = _plugin_versions.get(key) || 0;
586
+ const next = prev + 1;
587
+ _plugin_versions.set(key, next);
588
+ /* Tree version bumps along with every plugin version bump. */
589
+ _bumpTreeVersion(trigger, [{ slug: slug, instance_id: instance_id || null }]);
590
+ if (typeof document !== 'undefined') {
591
+ document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
592
+ detail: {
593
+ plugin_slug: slug,
594
+ plugin_instance_id: instance_id || null,
595
+ from_version: 'v_' + prev,
596
+ to_version: 'v_' + next,
597
+ trigger: trigger,
598
+ },
599
+ }));
600
+ }
601
+ }
602
+
603
+ /* Helper invoked from data-table primitives + syncPlugin to bump
604
+ versions without needing a mutation observer round-trip. */
605
+ function _markStructuralChange(slug, instance_id, trigger) {
606
+ _bumpPluginVersion(slug, instance_id, trigger || 'syncPlugin');
607
+ }
608
+
609
+ /* ---- Mutation observer (RFC sec 8.2) ----
610
+
611
+ Single observer rooted at document.body, filters mutations to
612
+ elements inside any [data-nac-plugin] subtree, coalesces all
613
+ mutations in a single microtask into one bump per affected
614
+ plugin. Structural changes (add/remove [data-nac-*] elements,
615
+ attribute changes to data-nac-id/role/action/plugin*, visibility
616
+ transitions) bump; pure state changes (value/textContent/focus)
617
+ do not. */
618
+ const _NAC_ATTRS_STRUCTURAL = new Set([
619
+ 'data-nac-id', 'data-nac-role', 'data-nac-action',
620
+ 'data-nac-plugin', 'data-nac-plugin-id', 'data-nac-verb',
621
+ 'aria-hidden', 'hidden', 'style',
622
+ ]);
623
+
624
+ function _scopeOfMutation(mutation) {
625
+ /* attributes: target is the element itself.
626
+ childList: walk added/removed nodes; each contributes a scope. */
627
+ const scopes = [];
628
+ if (mutation.type === 'attributes' && mutation.target) {
629
+ const s = _resolvePluginScope(mutation.target);
630
+ if (s) scopes.push(s);
631
+ } else if (mutation.type === 'childList') {
632
+ const collect = function (nl) {
633
+ for (let i = 0; i < nl.length; i++) {
634
+ const n = nl[i];
635
+ if (n.nodeType !== 1) continue;
636
+ /* Only nodes that themselves carry a data-nac-* attribute,
637
+ or that contain one, are agent-relevant. */
638
+ let relevant = false;
639
+ if (n.hasAttribute && (n.hasAttribute('data-nac-id') ||
640
+ n.hasAttribute('data-nac-role') ||
641
+ n.hasAttribute('data-nac-plugin'))) {
642
+ relevant = true;
643
+ }
644
+ if (!relevant && n.querySelector) {
645
+ relevant = !!n.querySelector('[data-nac-id],[data-nac-role],[data-nac-plugin]');
646
+ }
647
+ if (relevant) {
648
+ /* Resolve scope from the mutation parent (where the node
649
+ was inserted/removed), since the removed node may no
650
+ longer be in the tree. */
651
+ const s = _resolvePluginScope(mutation.target);
652
+ if (s) scopes.push(s);
653
+ }
654
+ }
655
+ };
656
+ collect(mutation.addedNodes);
657
+ collect(mutation.removedNodes);
658
+ }
659
+ return scopes;
660
+ }
661
+
662
+ function _isStructuralAttrChange(mutation) {
663
+ if (mutation.type !== 'attributes') return false;
664
+ return _NAC_ATTRS_STRUCTURAL.has(mutation.attributeName || '');
665
+ }
666
+
667
+ function _handleMutationRecords(records) {
668
+ /* Coalesce: collect every affected (slug, instance_id) and emit
669
+ exactly one bump per pair per microtask flush. */
670
+ const affected = new Map();
671
+ for (let i = 0; i < records.length; i++) {
672
+ const r = records[i];
673
+ let structural = false;
674
+ if (r.type === 'childList') structural = true;
675
+ else if (r.type === 'attributes' && _isStructuralAttrChange(r)) structural = true;
676
+ else if (r.type === 'attributes' &&
677
+ (r.attributeName === 'data-nac-plugin' ||
678
+ r.attributeName === 'data-nac-plugin-id') &&
679
+ _plugin_scope_cache && r.target) {
680
+ /* Plugin scope changed -- invalidate cache for this element. */
681
+ try { _plugin_scope_cache.delete(r.target); } catch (_) {}
682
+ }
683
+ if (!structural) continue;
684
+ const scopes = _scopeOfMutation(r);
685
+ for (let j = 0; j < scopes.length; j++) {
686
+ const k = _pluginKey(scopes[j].slug, scopes[j].instance_id);
687
+ if (!affected.has(k)) {
688
+ affected.set(k, { slug: scopes[j].slug, instance_id: scopes[j].instance_id });
689
+ }
690
+ }
691
+ }
692
+ if (affected.size === 0) return;
693
+ affected.forEach(function (scope) {
694
+ _bumpPluginVersion(scope.slug, scope.instance_id, 'mutation');
695
+ });
696
+ }
697
+
698
+ function _installMutationObserver() {
699
+ if (_mutation_observer || typeof MutationObserver === 'undefined' ||
700
+ typeof document === 'undefined' || !document.body) return;
701
+ _mutation_observer = new MutationObserver(_handleMutationRecords);
702
+ _mutation_observer.observe(document.body, {
703
+ childList: true,
704
+ subtree: true,
705
+ attributes: true,
706
+ attributeFilter: ['data-nac-id', 'data-nac-role', 'data-nac-action',
707
+ 'data-nac-plugin', 'data-nac-plugin-id', 'data-nac-verb',
708
+ 'data-nac-state', 'aria-hidden', 'hidden', 'disabled',
709
+ 'style'],
710
+ });
711
+ }
712
+
713
+ /* ---- element_state_hash (RFC sec 5.2) ----
714
+
715
+ The hash covers exactly 5 keys (visible, disabled, value, text,
716
+ custom) per the canonical mini-spec. Truncation at 256 chars on
717
+ value+text is normative. Serializer emits keys alphabetically,
718
+ non-ASCII escaped as \uXXXX lowercase, no whitespace. SHA-256
719
+ over the canonical bytes, truncated to the leading 128 bits
720
+ (16 bytes), encoded as 32 lowercase hex chars. */
721
+
722
+ function _hashIsEffectivelyVisible(el) {
723
+ /* Cheap visibility check: offsetParent + style.display +
724
+ style.visibility + aria-hidden. */
725
+ if (!el || el.nodeType !== 1) return false;
726
+ if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false;
727
+ if (typeof el.offsetParent === 'object' && el.offsetParent === null) {
728
+ /* position:fixed escapes offsetParent=null. Use rect fallback. */
729
+ if (typeof el.getBoundingClientRect === 'function') {
730
+ const r = el.getBoundingClientRect();
731
+ if (r.width === 0 && r.height === 0) return false;
732
+ } else {
733
+ return false;
734
+ }
735
+ }
736
+ if (typeof window !== 'undefined' && window.getComputedStyle) {
737
+ const cs = window.getComputedStyle(el);
738
+ if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return false;
739
+ }
740
+ return true;
741
+ }
742
+
743
+ function _hashReadValue(el) {
744
+ if (!el || el.nodeType !== 1) return null;
745
+ const tag = (el.tagName || '').toLowerCase();
746
+ if (tag === 'input' || tag === 'textarea') {
747
+ const t = (el.type || '').toLowerCase();
748
+ if (t === 'checkbox' || t === 'radio') return el.checked ? 'true' : 'false';
749
+ return el.value == null ? null : String(el.value).slice(0, 256);
750
+ }
751
+ if (tag === 'select') {
752
+ return el.value == null ? null : String(el.value).slice(0, 256);
753
+ }
754
+ /* role=option fallback: aria-selected. */
755
+ if (el.getAttribute && el.getAttribute('aria-selected') === 'true') return 'selected';
756
+ return null;
757
+ }
758
+
759
+ function _jsonStringCanonical(s) {
760
+ /* RFC 8259 string encoding + the V24-04 normative rule: non-ASCII
761
+ escaped as \uXXXX lowercase. Eliminates engine divergence. */
762
+ let out = '"';
763
+ for (let i = 0; i < s.length; i++) {
764
+ const c = s.charCodeAt(i);
765
+ if (c === 0x22) out += '\\"';
766
+ else if (c === 0x5C) out += '\\\\';
767
+ else if (c === 0x08) out += '\\b';
768
+ else if (c === 0x0C) out += '\\f';
769
+ else if (c === 0x0A) out += '\\n';
770
+ else if (c === 0x0D) out += '\\r';
771
+ else if (c === 0x09) out += '\\t';
772
+ else if (c < 0x20 || c > 0x7E) {
773
+ let hex = c.toString(16);
774
+ while (hex.length < 4) hex = '0' + hex;
775
+ out += '\\u' + hex.toLowerCase();
776
+ } else {
777
+ out += s.charAt(i);
778
+ }
779
+ }
780
+ out += '"';
781
+ return out;
782
+ }
783
+
784
+ function _canonicalSerializeState(obj) {
785
+ /* Keys in alphabetical order: custom, disabled, text, value, visible. */
786
+ return '{'
787
+ + '"custom":' + (obj.custom === null ? 'null' : _jsonStringCanonical(obj.custom)) + ','
788
+ + '"disabled":' + (obj.disabled ? 'true' : 'false') + ','
789
+ + '"text":' + (obj.text === null ? 'null' : _jsonStringCanonical(obj.text)) + ','
790
+ + '"value":' + (obj.value === null ? 'null' : _jsonStringCanonical(obj.value)) + ','
791
+ + '"visible":' + (obj.visible ? 'true' : 'false')
792
+ + '}';
793
+ }
794
+
795
+ function _bytesToHexLower(bytes) {
796
+ let out = '';
797
+ for (let i = 0; i < bytes.length; i++) {
798
+ const v = bytes[i];
799
+ out += (v < 16 ? '0' : '') + v.toString(16);
800
+ }
801
+ return out;
802
+ }
803
+
804
+ /* Synchronous SHA-256 fallback. Used in non-secure contexts where
805
+ crypto.subtle is unavailable (HTTP iframes, legacy embeds).
806
+ Reference implementation (~80 LOC). Produces byte-identical
807
+ digests to crypto.subtle.digest('SHA-256', ...). */
808
+ function _sha256Sync(bytes) {
809
+ const K = [
810
+ 0x428a2f98|0,0x71374491|0,0xb5c0fbcf|0,0xe9b5dba5|0,0x3956c25b|0,0x59f111f1|0,0x923f82a4|0,0xab1c5ed5|0,
811
+ 0xd807aa98|0,0x12835b01|0,0x243185be|0,0x550c7dc3|0,0x72be5d74|0,0x80deb1fe|0,0x9bdc06a7|0,0xc19bf174|0,
812
+ 0xe49b69c1|0,0xefbe4786|0,0x0fc19dc6|0,0x240ca1cc|0,0x2de92c6f|0,0x4a7484aa|0,0x5cb0a9dc|0,0x76f988da|0,
813
+ 0x983e5152|0,0xa831c66d|0,0xb00327c8|0,0xbf597fc7|0,0xc6e00bf3|0,0xd5a79147|0,0x06ca6351|0,0x14292967|0,
814
+ 0x27b70a85|0,0x2e1b2138|0,0x4d2c6dfc|0,0x53380d13|0,0x650a7354|0,0x766a0abb|0,0x81c2c92e|0,0x92722c85|0,
815
+ 0xa2bfe8a1|0,0xa81a664b|0,0xc24b8b70|0,0xc76c51a3|0,0xd192e819|0,0xd6990624|0,0xf40e3585|0,0x106aa070|0,
816
+ 0x19a4c116|0,0x1e376c08|0,0x2748774c|0,0x34b0bcb5|0,0x391c0cb3|0,0x4ed8aa4a|0,0x5b9cca4f|0,0x682e6ff3|0,
817
+ 0x748f82ee|0,0x78a5636f|0,0x84c87814|0,0x8cc70208|0,0x90befffa|0,0xa4506ceb|0,0xbef9a3f7|0,0xc67178f2|0,
818
+ ];
819
+ let H = [0x6a09e667|0,0xbb67ae85|0,0x3c6ef372|0,0xa54ff53a|0,0x510e527f|0,0x9b05688c|0,0x1f83d9ab|0,0x5be0cd19|0];
820
+ /* Padding */
821
+ const ml = bytes.length;
822
+ const bits = ml * 8;
823
+ const padlen = (((ml + 9 + 63) >> 6) << 6) - ml;
824
+ const buf = new Uint8Array(ml + padlen);
825
+ buf.set(bytes, 0);
826
+ buf[ml] = 0x80;
827
+ /* big-endian 64-bit length, low 32 bits in the last 4 bytes */
828
+ buf[buf.length - 4] = (bits >>> 24) & 0xff;
829
+ buf[buf.length - 3] = (bits >>> 16) & 0xff;
830
+ buf[buf.length - 2] = (bits >>> 8) & 0xff;
831
+ buf[buf.length - 1] = bits & 0xff;
832
+ const W = new Int32Array(64);
833
+ function ROTR(x, n) { return (x >>> n) | (x << (32 - n)); }
834
+ for (let chunk = 0; chunk < buf.length; chunk += 64) {
835
+ for (let i = 0; i < 16; i++) {
836
+ W[i] = (buf[chunk + i*4 ] << 24) |
837
+ (buf[chunk + i*4 + 1] << 16) |
838
+ (buf[chunk + i*4 + 2] << 8) |
839
+ (buf[chunk + i*4 + 3]);
840
+ }
841
+ for (let i = 16; i < 64; i++) {
842
+ const s0 = ROTR(W[i-15], 7) ^ ROTR(W[i-15], 18) ^ (W[i-15] >>> 3);
843
+ const s1 = ROTR(W[i-2], 17) ^ ROTR(W[i-2], 19) ^ (W[i-2] >>> 10);
844
+ W[i] = (W[i-16] + s0 + W[i-7] + s1) | 0;
845
+ }
846
+ let a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7];
847
+ for (let i = 0; i < 64; i++) {
848
+ const S1 = ROTR(e,6) ^ ROTR(e,11) ^ ROTR(e,25);
849
+ const ch = (e & f) ^ ((~e) & g);
850
+ const t1 = (h + S1 + ch + K[i] + W[i]) | 0;
851
+ const S0 = ROTR(a,2) ^ ROTR(a,13) ^ ROTR(a,22);
852
+ const mj = (a & b) ^ (a & c) ^ (b & c);
853
+ const t2 = (S0 + mj) | 0;
854
+ h = g; g = f; f = e; e = (d + t1) | 0;
855
+ d = c; c = b; b = a; a = (t1 + t2) | 0;
856
+ }
857
+ H[0]=(H[0]+a)|0; H[1]=(H[1]+b)|0; H[2]=(H[2]+c)|0; H[3]=(H[3]+d)|0;
858
+ H[4]=(H[4]+e)|0; H[5]=(H[5]+f)|0; H[6]=(H[6]+g)|0; H[7]=(H[7]+h)|0;
859
+ }
860
+ const out = new Uint8Array(32);
861
+ for (let i = 0; i < 8; i++) {
862
+ out[i*4 ] = (H[i] >>> 24) & 0xff;
863
+ out[i*4 + 1] = (H[i] >>> 16) & 0xff;
864
+ out[i*4 + 2] = (H[i] >>> 8) & 0xff;
865
+ out[i*4 + 3] = H[i] & 0xff;
866
+ }
867
+ return out;
868
+ }
869
+
870
+ async function _sha256(bytes) {
871
+ if (typeof crypto !== 'undefined' && crypto.subtle && crypto.subtle.digest) {
872
+ const buf = await crypto.subtle.digest('SHA-256', bytes);
873
+ return new Uint8Array(buf);
874
+ }
875
+ return _sha256Sync(bytes);
876
+ }
877
+
878
+ function _buildHashState(el) {
879
+ if (!el || el.nodeType !== 1) return null;
880
+ const role = (el.getAttribute && (el.getAttribute('data-nac-role') || '')) || '';
881
+ let text = null;
882
+ if (role === 'action' || role === 'tab') {
883
+ const t = (el.textContent || '').trim();
884
+ text = t.slice(0, 256);
885
+ }
886
+ let value = null;
887
+ if (role === 'field' || role === 'option') {
888
+ value = _hashReadValue(el);
889
+ }
890
+ return {
891
+ custom: (el.getAttribute && el.getAttribute('data-nac-state')) || null,
892
+ disabled: el.disabled === true ||
893
+ (el.getAttribute && el.getAttribute('aria-disabled') === 'true'),
894
+ text: text,
895
+ value: value,
896
+ visible: _hashIsEffectivelyVisible(el),
897
+ };
898
+ }
899
+
900
+ function _encodeCanonical(canonical) {
901
+ if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(canonical);
902
+ const b = new Uint8Array(canonical.length);
903
+ for (let i = 0; i < canonical.length; i++) b[i] = canonical.charCodeAt(i) & 0xff;
904
+ return b;
905
+ }
906
+
907
+ /* Async variant -- uses WebCrypto when available (faster on long
908
+ strings); falls back to the sync implementation in non-secure
909
+ contexts. Awaited by _resolveVersionExpectations on the hash
910
+ check path. */
911
+ async function _stateHashOf(el) {
912
+ const state = _buildHashState(el);
913
+ if (!state) return null;
914
+ const enc = _encodeCanonical(_canonicalSerializeState(state));
915
+ const digest = await _sha256(enc);
916
+ return _bytesToHexLower(digest.slice(0, 16));
917
+ }
918
+
919
+ /* Sync variant -- always uses _sha256Sync. Used by describe() so
920
+ the public read API stays synchronous. ~0.5-1ms per element on
921
+ modern V8; acceptable up to a few hundred elements per describe.
922
+ Hosts with thousands of elements should pre-cache via the
923
+ eager_hashing flag (future optimization). */
924
+ function _stateHashOfSync(el) {
925
+ const state = _buildHashState(el);
926
+ if (!state) return null;
927
+ const enc = _encodeCanonical(_canonicalSerializeState(state));
928
+ const digest = _sha256Sync(enc);
929
+ return _bytesToHexLower(digest.slice(0, 16));
930
+ }
931
+
932
+ /* ---- markHydrationComplete + 100ms fallback (RFC sec 5.10) ---- */
933
+
934
+ function _completeHydration(triggered_by) {
935
+ if (_hydration_complete) return;
936
+ _hydration_complete = true;
937
+ if (_hydration_fallback_timer) {
938
+ clearTimeout(_hydration_fallback_timer);
939
+ _hydration_fallback_timer = null;
940
+ }
941
+ /* Enumerate every registered plugin instance and emit per-plugin
942
+ events with from_version=null, plus a global tree event. */
943
+ const affected = [];
944
+ _plugin_versions.forEach(function (_n, key) {
945
+ const i = key.indexOf('|');
946
+ const slug = key.slice(0, i);
947
+ const inst = key.slice(i + 1) || null;
948
+ affected.push({ slug: slug, instance_id: inst });
949
+ });
950
+ /* Tree bump tagged as hydration_complete. */
951
+ _bumpTreeVersion('hydration_complete', affected.slice());
952
+ if (typeof document !== 'undefined') {
953
+ for (let i = 0; i < affected.length; i++) {
954
+ const a = affected[i];
955
+ const key = _pluginKey(a.slug, a.instance_id);
956
+ const curN = _plugin_versions.get(key) || 0;
957
+ document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
958
+ detail: {
959
+ plugin_slug: a.slug,
960
+ plugin_instance_id: a.instance_id,
961
+ from_version: null,
962
+ to_version: 'v_' + curN,
963
+ trigger: 'hydration_complete',
964
+ },
965
+ }));
966
+ }
967
+ }
968
+ }
969
+
970
+ function markHydrationComplete() {
971
+ if (_hydration_complete) return;
972
+ _completeHydration('explicit');
973
+ }
974
+
975
+ function _armHydrationFallback() {
976
+ if (typeof document === 'undefined') return;
977
+ const start = function () {
978
+ _hydration_fallback_timer = setTimeout(function () {
979
+ if (!_hydration_complete) _completeHydration('fallback_100ms');
980
+ }, 100);
981
+ };
982
+ if (document.readyState === 'loading') {
983
+ document.addEventListener('DOMContentLoaded', start, { once: true });
984
+ } else {
985
+ start();
986
+ }
987
+ }
988
+
989
+ /* ---- versionHistory devtools surface (RFC sec 5.9) ---- */
990
+
991
+ function versionHistory(limit) {
992
+ const n = (typeof limit === 'number' && limit > 0)
993
+ ? Math.min(limit, _version_history.length)
994
+ : Math.min(50, _version_history.length);
995
+ return _version_history.slice(-n).reverse();
996
+ }
997
+
998
+ /* ---- Resolver helper for expected_* checks (RFC sec 5.4 + 8.3) ----
999
+
1000
+ Returns Promise<void>. Throws NacError on mismatch / tier reject /
1001
+ STRICT-without-expectation. Cheap-to-expensive order:
1002
+ 1. STRICT gate
1003
+ 2. NAC-3 (non-versioned) tier rejects ANY expected_*
1004
+ 3. expected_plugin_version (integer compare)
1005
+ 4. expected_tree_version (integer compare)
1006
+ 5. expected_element_state_hash (SHA-256, awaited last)
1007
+ */
1008
+ async function _resolveVersionExpectations(opts, el) {
1009
+ const o = opts || {};
1010
+ const hasAny = ('expected_plugin_version' in o) ||
1011
+ ('expected_tree_version' in o) ||
1012
+ ('expected_element_state_hash' in o);
1013
+ if (_strictVersioningOn() && !hasAny) {
1014
+ throw NacError('version_required',
1015
+ 'STRICT_VERSIONING is on; at least one expected_* required.',
1016
+ { method: (o && o.method) || undefined });
1017
+ }
1018
+ /* Tier reject -- conformance_tier is exposed on the NAC export,
1019
+ and a runtime that declares NAC-3 must NOT silently honor any
1020
+ expected_*. */
1021
+ const tier = (typeof window !== 'undefined' && window.NAC &&
1022
+ window.NAC.conformance_tier) || 'NAC-3-versioned';
1023
+ if (tier === 'NAC-3' && hasAny) {
1024
+ throw NacError('feature_not_supported',
1025
+ 'Runtime tier is NAC-3 (non-versioned); expected_* parameters are not honored.',
1026
+ { tier: 'NAC-3', requested_feature: 'versioning' });
1027
+ }
1028
+ /* Plugin version */
1029
+ if ('expected_plugin_version' in o) {
1030
+ const scope = _resolvePluginScope(el);
1031
+ if (scope) {
1032
+ const cur = _pluginVersionFor(scope.slug, scope.instance_id);
1033
+ if (o.expected_plugin_version !== cur) {
1034
+ /* RFC V24-04 sec 5.5: extras nested under .detail.
1035
+ NacError() flattens by default; mirror under detail
1036
+ for the new versioning error class so agents reading
1037
+ the RFC can use err.detail.reason directly. */
1038
+ const detail = {
1039
+ reason: 'plugin_changed',
1040
+ plugin_slug: scope.slug,
1041
+ plugin_instance_id: scope.instance_id,
1042
+ expected_plugin_version: o.expected_plugin_version,
1043
+ current_plugin_version: cur,
1044
+ };
1045
+ throw NacError('snapshot_stale',
1046
+ 'expected_plugin_version=' + o.expected_plugin_version +
1047
+ ' current_plugin_version=' + cur,
1048
+ Object.assign({ detail: detail }, detail));
1049
+ }
1050
+ }
1051
+ }
1052
+ /* Tree version */
1053
+ if ('expected_tree_version' in o) {
1054
+ const cur = _treeVersionStr();
1055
+ if (o.expected_tree_version !== cur) {
1056
+ const detail = {
1057
+ reason: 'tree_changed',
1058
+ expected_tree_version: o.expected_tree_version,
1059
+ current_tree_version: cur,
1060
+ };
1061
+ throw NacError('snapshot_stale',
1062
+ 'expected_tree_version=' + o.expected_tree_version +
1063
+ ' current_tree_version=' + cur,
1064
+ Object.assign({ detail: detail }, detail));
1065
+ }
1066
+ }
1067
+ /* Element state hash (awaited last) */
1068
+ if ('expected_element_state_hash' in o) {
1069
+ const cur = await _stateHashOf(el);
1070
+ if (o.expected_element_state_hash !== cur) {
1071
+ const detail = {
1072
+ reason: 'element_changed',
1073
+ expected_element_state_hash: o.expected_element_state_hash,
1074
+ current_element_state_hash: cur,
1075
+ };
1076
+ throw NacError('snapshot_stale',
1077
+ 'expected_element_state_hash=' + o.expected_element_state_hash +
1078
+ ' current_element_state_hash=' + cur,
1079
+ Object.assign({ detail: detail }, detail));
1080
+ }
1081
+ }
1082
+ }
1083
+
1084
+ /* Read back the post-dispatch versions. Used by every mutating API
1085
+ after the side effect lands. Pair with _flushObserverQueue() to
1086
+ guarantee MutationObserver records have been integrated. */
1087
+ function _atVersionsFor(el) {
1088
+ const scope = _resolvePluginScope(el);
1089
+ return {
1090
+ at_plugin_version: scope ? _pluginVersionFor(scope.slug, scope.instance_id) : null,
1091
+ at_tree_version: _treeVersionStr(),
1092
+ };
1093
+ }
1094
+
1095
+ /* Flush pending MutationObserver records into version bumps before
1096
+ resolving the promise (RFC sec 5.8). queueMicrotask is enough --
1097
+ the observer fires once per microtask flush. */
1098
+ function _flushObserverQueue() {
1099
+ return new Promise(function (resolve) {
1100
+ if (typeof queueMicrotask === 'function') {
1101
+ queueMicrotask(resolve);
1102
+ } else {
1103
+ Promise.resolve().then(resolve);
1104
+ }
1105
+ });
1106
+ }
1107
+
1108
+ /* ==================================================================
1109
+ End of v2.4 / RFC V24-04 foundation block.
1110
+ ================================================================== */
1111
+
327
1112
  /* H1.v7 (2026-05-21): structured disambiguation contract.
328
1113
  When the runtime cannot resolve an id/verb/qualifier/label
329
1114
  unambiguously, it MUST emit `nac:disambiguation_requested` with
@@ -1433,6 +2218,20 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1433
2218
  if (!manifest.version) manifest.version = '1.0.0';
1434
2219
  if (!manifest.nac_version) manifest.nac_version = '1.0';
1435
2220
 
2221
+ /* v2.5 / RFC V24-01 -- synchronous slug uniqueness gate.
2222
+ Throws NacError('duplicate_plugin_no_instance_id', ...) when
2223
+ the DOM already contains multiple roots for this slug and any
2224
+ of them omit or duplicate data-nac-plugin-id. Gated by
2225
+ NAC.HARD_DEDUP (default true; settable false for migration). */
2226
+ const _hardDedup = (typeof global !== 'undefined' && global.NAC
2227
+ ? global.NAC.HARD_DEDUP !== false
2228
+ : (typeof window !== 'undefined' && window.NAC
2229
+ ? window.NAC.HARD_DEDUP !== false
2230
+ : true));
2231
+ if (_hardDedup) {
2232
+ _checkPluginSlugUniqueOrThrow(slug);
2233
+ }
2234
+
1436
2235
  /* v1.5.1 cross-plugin duplicate-id detection.
1437
2236
  Spec section P7 expects nac_ids to be plugin-namespaced
1438
2237
  ('plugin.element' convention). When two manifests register
@@ -1600,6 +2399,254 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1600
2399
  return _manifests[slug] || null;
1601
2400
  }
1602
2401
 
2402
+ /* ================================================================
2403
+ v2.5 V24-02 -- syncPlugin: idempotent registration
2404
+ ================================================================
2405
+
2406
+ SPA hosts that re-render a component call register() again on
2407
+ remount; the legacy register() appends a new manifest entry,
2408
+ accumulating stale state. syncPlugin REPLACES the manifest for a
2409
+ given slug instead of appending. Calling N times with the same
2410
+ manifest leaves the registry in the same state as calling once.
2411
+
2412
+ Validation is identical to register() (manifest_role_unknown,
2413
+ tab_id_manifest_role_drift, etc honour STRICT_VALIDATION).
2414
+ Versioning: each call mints a new plugin_version (V24-04 OCC)
2415
+ and -- only on REPLACE, not first-add -- emits
2416
+ nac:plugin:invalidated so subscribers can refresh derived state. */
2417
+
2418
+ /* syncPlugin uses the V24-04 versioning machinery: every replace
2419
+ calls _bumpPluginVersion(slug, null, 'syncPlugin') which bumps
2420
+ _plugin_versions + _tree_version + dispatches nac:plugin:invalidated
2421
+ in one atomic step. Single source of truth for OCC. */
2422
+ function syncPlugin(arg1, arg2) {
2423
+ let m;
2424
+ if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
2425
+ /* (slug, manifest) form -- match register's calling convention. */
2426
+ m = Object.assign({}, arg2);
2427
+ if (!m.plugin_slug) m.plugin_slug = arg1;
2428
+ } else if (arg1 && typeof arg1 === 'object') {
2429
+ m = arg1;
2430
+ } else {
2431
+ throw NacError('invalid',
2432
+ 'syncPlugin: requires (manifest) or (slug, manifest)');
2433
+ }
2434
+ const slug = m.plugin_slug;
2435
+ if (!slug || typeof slug !== 'string') {
2436
+ throw NacError('invalid',
2437
+ 'syncPlugin: manifest.plugin_slug required (non-empty string)');
2438
+ }
2439
+ const wasPresent = !!_manifests[slug];
2440
+ /* Replace path: drop the prior entry so register() does not
2441
+ append-by-side-effect when callers used the array-of-elements
2442
+ merge pattern. */
2443
+ if (wasPresent) {
2444
+ delete _manifests[slug];
2445
+ if (typeof _instances !== 'undefined') delete _instances[slug];
2446
+ }
2447
+ /* Delegate to register() so validation + storage code-path stays
2448
+ exactly one place. If register throws (strict validation), the
2449
+ prior entry is GONE -- caller's responsibility to handle. */
2450
+ register(m);
2451
+ /* Bump V24-04 OCC version on REPLACE only. First-add is a normal
2452
+ register: the boot tree_version already reflects the new plugin
2453
+ and subscribers do not need to refresh anything that did not
2454
+ exist a moment ago. _bumpPluginVersion fires nac:plugin:invalidated
2455
+ as part of its work, so we don't dispatch again here. */
2456
+ if (wasPresent) {
2457
+ _bumpPluginVersion(slug, null, 'syncPlugin');
2458
+ }
2459
+ return {
2460
+ replaced: wasPresent,
2461
+ slug: slug,
2462
+ version: _pluginVersionFor(slug, null),
2463
+ };
2464
+ }
2465
+
2466
+ /* ================================================================
2467
+ v2.5 V24-05 -- Agent authority + sudo elevation
2468
+ ================================================================
2469
+
2470
+ Three primitives for a host to interpose a confirmation UI
2471
+ between an agent dispatch and the action's side effect, with a
2472
+ SUDO-style elevation that bypasses confirmations for a granted
2473
+ scope until its TTL expires.
2474
+
2475
+ NAC.set_confirm_handler(fn)
2476
+ fn is async (req) => boolean. The host renders its UI
2477
+ (modal, voice, Discord button, etc) and resolves true on
2478
+ approve, false on reject. A handler that throws is treated
2479
+ as "reject" (never as a silent approval).
2480
+
2481
+ NAC.confirm_action(action_id, message, opts?)
2482
+ opts = { scope?: 'low'|'medium'|'high', metadata?: {...} }
2483
+ Returns Promise<boolean>. If currently elevated for an
2484
+ equal-or-stricter scope, resolves true synchronously
2485
+ WITHOUT invoking the handler.
2486
+
2487
+ NAC.request_authority(scope, ttl_ms, opts?)
2488
+ Asks the host for sudo elevation. On grant, subsequent
2489
+ confirm_action calls in that scope (or lower) resolve
2490
+ immediately for ttl_ms. After TTL the elevation
2491
+ auto-revokes; manual revoke is NAC.revoke_authority(scope).
2492
+
2493
+ NAC.has_authority(scope) -> boolean
2494
+ NAC.revoke_authority(scope) -> void (idempotent)
2495
+
2496
+ Scope rank: high > medium > low. Granted high authority
2497
+ satisfies medium + low; granted low does NOT satisfy higher.
2498
+
2499
+ Provenance on document:
2500
+ nac:authority:requested / :granted / :denied / :revoked / :expired
2501
+ nac:action:confirmed / :rejected */
2502
+
2503
+ const _V25_SCOPE_RANK = { low: 1, medium: 2, high: 3 };
2504
+ const _v25_authority_grants = new Map();
2505
+ let _v25_authReqSeq = 0;
2506
+ let _v25_confirm_handler = null;
2507
+
2508
+ function _v25_emitAuth(kind, detail) {
2509
+ if (typeof document === 'undefined') return;
2510
+ try {
2511
+ document.dispatchEvent(new CustomEvent('nac:authority:' + kind,
2512
+ { detail: detail, bubbles: true }));
2513
+ } catch (_) { /* SSR or no document */ }
2514
+ }
2515
+ function _v25_emitAction(kind, detail) {
2516
+ if (typeof document === 'undefined') return;
2517
+ try {
2518
+ document.dispatchEvent(new CustomEvent('nac:action:' + kind,
2519
+ { detail: detail, bubbles: true }));
2520
+ } catch (_) { /* SSR or no document */ }
2521
+ }
2522
+
2523
+ function set_confirm_handler(fn) {
2524
+ if (typeof fn !== 'function') {
2525
+ throw NacError('invalid',
2526
+ 'NAC.set_confirm_handler: fn must be a function');
2527
+ }
2528
+ _v25_confirm_handler = fn;
2529
+ }
2530
+
2531
+ function has_authority(scope) {
2532
+ if (!_V25_SCOPE_RANK[scope]) return false;
2533
+ const want = _V25_SCOPE_RANK[scope];
2534
+ const now = Date.now();
2535
+ /* Iterate live grants. Higher rank satisfies lower-rank check.
2536
+ Auto-purge expired entries inline so the map stays clean. */
2537
+ let satisfied = false;
2538
+ _v25_authority_grants.forEach(function (info, grantedScope) {
2539
+ if (info.expires_at <= now) return; /* timer will purge */
2540
+ if (_V25_SCOPE_RANK[grantedScope] >= want) satisfied = true;
2541
+ });
2542
+ return satisfied;
2543
+ }
2544
+
2545
+ function revoke_authority(scope) {
2546
+ const info = _v25_authority_grants.get(scope);
2547
+ if (!info) return; /* idempotent */
2548
+ if (info.timer) { try { clearTimeout(info.timer); } catch (_) {} }
2549
+ _v25_authority_grants.delete(scope);
2550
+ _v25_emitAuth('revoked', { scope: scope, reason: 'manual' });
2551
+ }
2552
+
2553
+ function request_authority(scope, ttl_ms, opts) {
2554
+ return new Promise(function (resolve, reject) {
2555
+ if (!_V25_SCOPE_RANK[scope]) {
2556
+ reject(NacError('invalid',
2557
+ 'request_authority: scope must be one of low|medium|high'));
2558
+ return;
2559
+ }
2560
+ if (typeof ttl_ms !== 'number' || ttl_ms < 0 || !isFinite(ttl_ms)) {
2561
+ reject(NacError('invalid',
2562
+ 'request_authority: ttl_ms must be a non-negative finite number'));
2563
+ return;
2564
+ }
2565
+ if (!_v25_confirm_handler) {
2566
+ reject(NacError('no_confirm_handler',
2567
+ 'request_authority: NAC.set_confirm_handler must be called first'));
2568
+ return;
2569
+ }
2570
+ const reqId = 'auth_' + Date.now().toString(36) + '_' + (++_v25_authReqSeq).toString(36);
2571
+ const req = {
2572
+ kind: 'request_authority',
2573
+ request_id: reqId,
2574
+ scope: scope,
2575
+ ttl_ms: ttl_ms,
2576
+ metadata: (opts && opts.metadata) || {},
2577
+ };
2578
+ _v25_emitAuth('requested', req);
2579
+ let p;
2580
+ try { p = Promise.resolve(_v25_confirm_handler(req)); }
2581
+ catch (e) { p = Promise.resolve(false); }
2582
+ p.then(function (granted) { return !!granted; },
2583
+ function () { return false; })
2584
+ .then(function (granted) {
2585
+ if (!granted) {
2586
+ _v25_emitAuth('denied',
2587
+ { scope: scope, ttl_ms: ttl_ms, request_id: reqId });
2588
+ resolve({ granted: false, scope: scope, expires_at: null });
2589
+ return;
2590
+ }
2591
+ const now = Date.now();
2592
+ const expires_at = now + ttl_ms;
2593
+ /* Replace any prior grant for the same scope. */
2594
+ const prior = _v25_authority_grants.get(scope);
2595
+ if (prior && prior.timer) { try { clearTimeout(prior.timer); } catch (_) {} }
2596
+ const timer = setTimeout(function () {
2597
+ _v25_authority_grants.delete(scope);
2598
+ _v25_emitAuth('expired', { scope: scope, reason: 'ttl' });
2599
+ }, ttl_ms);
2600
+ _v25_authority_grants.set(scope, { expires_at: expires_at, timer: timer });
2601
+ _v25_emitAuth('granted',
2602
+ { scope: scope, expires_at: expires_at, request_id: reqId });
2603
+ resolve({ granted: true, scope: scope, expires_at: expires_at });
2604
+ });
2605
+ });
2606
+ }
2607
+
2608
+ function confirm_action(action_id, message, opts) {
2609
+ return new Promise(function (resolve, reject) {
2610
+ if (typeof action_id !== 'string' || !action_id) {
2611
+ reject(NacError('invalid',
2612
+ 'confirm_action: action_id must be a non-empty string'));
2613
+ return;
2614
+ }
2615
+ const scope = (opts && opts.scope) || 'medium';
2616
+ const metadata = (opts && opts.metadata) || {};
2617
+ /* Sudo bypass -- if we already have authority for this scope
2618
+ (or higher), short-circuit without calling the handler. */
2619
+ if (has_authority(scope)) {
2620
+ _v25_emitAction('confirmed',
2621
+ { action_id: action_id, scope: scope, sudo: true });
2622
+ resolve(true);
2623
+ return;
2624
+ }
2625
+ if (!_v25_confirm_handler) {
2626
+ reject(NacError('no_confirm_handler',
2627
+ 'confirm_action: NAC.set_confirm_handler must be called first'));
2628
+ return;
2629
+ }
2630
+ const req = {
2631
+ kind: 'confirm_action',
2632
+ action_id: action_id,
2633
+ message: message,
2634
+ scope: scope,
2635
+ metadata: metadata,
2636
+ };
2637
+ let p;
2638
+ try { p = Promise.resolve(_v25_confirm_handler(req)); }
2639
+ catch (e) { p = Promise.resolve(false); }
2640
+ p.then(function (approved) { return !!approved; },
2641
+ function () { return false; })
2642
+ .then(function (approved) {
2643
+ _v25_emitAction(approved ? 'confirmed' : 'rejected',
2644
+ { action_id: action_id, scope: scope, sudo: false });
2645
+ resolve(approved);
2646
+ });
2647
+ });
2648
+ }
2649
+
1603
2650
  /* ---------- Element discovery ----------------------------------- */
1604
2651
 
1605
2652
  /* ---------- v2.3 shadow DOM resolution (F1 + F6) ----------
@@ -1839,12 +2886,20 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1839
2886
  const plugins = Array.prototype.slice.call(
1840
2887
  document.querySelectorAll('[data-nac-plugin]')
1841
2888
  ).map(function (root) {
2889
+ const slug = root.getAttribute('data-nac-plugin');
2890
+ const instance_id = root.getAttribute('data-nac-plugin-id') || null;
1842
2891
  return {
1843
- plugin: root.getAttribute('data-nac-plugin'),
1844
- plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
1845
- elements: Array.prototype.slice.call(
2892
+ plugin: slug,
2893
+ plugin_instance_id: instance_id,
2894
+ plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
2895
+ /* v2.5 / RFC V24-04 (sec 5.1): per-plugin monotonic version
2896
+ token. Primary tool for agents -- ignore noise outside the
2897
+ targeted plugin by passing expected_plugin_version on
2898
+ dispatch. */
2899
+ plugin_version: _pluginVersionFor(slug, instance_id),
2900
+ elements: Array.prototype.slice.call(
1846
2901
  root.querySelectorAll('[data-nac-id]')
1847
- ).map(_serializeElement),
2902
+ ).map(_serializeElementWithHash),
1848
2903
  };
1849
2904
  });
1850
2905
  return {
@@ -1853,9 +2908,24 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1853
2908
  url: location.href,
1854
2909
  active: _activePlugin(),
1855
2910
  plugins: plugins,
2911
+ /* v2.5 / RFC V24-04 (sec 5.3): global monotonic version token.
2912
+ Escape hatch for cross-plugin orchestration; prefer
2913
+ plugin_version for single-plugin plans. */
2914
+ tree_version: _treeVersionStr(),
1856
2915
  };
1857
2916
  }
1858
2917
 
2918
+ /* v2.5 / RFC V24-04 (sec 5.2): serialize + attach element_state_hash.
2919
+ Sync compute; ~0.5-1ms per element. NULL when the element does
2920
+ not carry a role that contributes to the hash. */
2921
+ function _serializeElementWithHash(el) {
2922
+ const base = _serializeElement(el);
2923
+ if (!base) return base;
2924
+ try { base.element_state_hash = _stateHashOfSync(el); }
2925
+ catch (_) { base.element_state_hash = null; }
2926
+ return base;
2927
+ }
2928
+
1859
2929
  function list(role) {
1860
2930
  const all = _allElements().map(_serializeElement);
1861
2931
  if (!role) return all;
@@ -3501,6 +4571,10 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
3501
4571
  orphans: [],
3502
4572
  unmounted: [],
3503
4573
  convention_violations: [],
4574
+ /* v2.5 / RFC V24-01: plugin slug uniqueness findings live in
4575
+ their own bucket so CI integrations can gate on them
4576
+ independently of nac_id duplicates. */
4577
+ plugin_instance_violations: _scanPluginInstances(),
3504
4578
  plugin_count: 0,
3505
4579
  total_ids: 0,
3506
4580
  timestamp: Date.now(),
@@ -5541,114 +6615,6 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
5541
6615
  };
5542
6616
  }
5543
6617
 
5544
- /* ---------- v1.9.0: action confirmation (sec 6.2.32) ---------- */
5545
-
5546
- /* The runtime maintains an in-memory map of in-flight confirm
5547
- requests keyed by confirm_id. confirm_action() emits the
5548
- requested event, awaits the host's handler decision (or the
5549
- default window.confirm), then emits granted/denied. */
5550
- let _confirmHandler = null;
5551
- function set_confirm_handler(fn) {
5552
- _confirmHandler = (typeof fn === 'function') ? fn : null;
5553
- }
5554
- function _newConfirmId() {
5555
- return 'cfm-' + Date.now().toString(36) + '-' +
5556
- Math.random().toString(36).slice(2, 8);
5557
- }
5558
- async function confirm_action(action_id, opts) {
5559
- opts = opts || {};
5560
- /* Resolve the element + its declared a11y_hint. */
5561
- const el = _findElement(action_id, {});
5562
- let hints = opts.hints;
5563
- if (!hints && el) {
5564
- const raw = el.getAttribute('data-nac-a11y-hint') || '';
5565
- hints = raw.split('|').map(function (s) { return s.trim(); })
5566
- .filter(function (s) { return s.length > 0; });
5567
- }
5568
- hints = hints || [];
5569
- const locale = (document.documentElement.lang || 'en').split('-')[0];
5570
- /* v1.9.0 sec 3.1: data-nac-confirmation-message override.
5571
- Host can declare per-element confirmation text (literal or
5572
- i18n key). Beats the auto-generated hint vocabulary text. */
5573
- let hint_text = opts.hint_text;
5574
- if (!hint_text && el) {
5575
- const cm = el.getAttribute('data-nac-confirmation-message');
5576
- if (cm && cm.length) {
5577
- if (cm.indexOf('i18n:') === 0 && _a11y_hint_localizer) {
5578
- /* Re-use the localizer hook with the i18n key as tag. */
5579
- try {
5580
- const v = _a11y_hint_localizer(cm.slice(5), locale);
5581
- if (typeof v === 'string' && v) hint_text = v;
5582
- } catch (e) { /* fall through */ }
5583
- }
5584
- if (!hint_text) hint_text = cm.indexOf('i18n:') === 0 ? cm.slice(5) : cm;
5585
- }
5586
- }
5587
- if (!hint_text) {
5588
- /* v1.9.0: walk hints in normative priority order so the
5589
- strongest tag leads the interposition text. */
5590
- const sorted = sort_hints_by_priority(hints);
5591
- hint_text = sorted.map(function (t) { return _localizeHintTag(t, locale); }).join(' ');
5592
- }
5593
- if (!hint_text) hint_text = 'Confirm this action?';
5594
- const verb = (el && el.getAttribute('data-nac-action')) || 'apply';
5595
- const confirm_id = _newConfirmId();
5596
- const pluginRoot = el && el.closest('[data-nac-plugin]');
5597
- const plugin = pluginRoot ? pluginRoot.getAttribute('data-nac-plugin') : null;
5598
- const reqDetail = {
5599
- plugin: plugin, plugin_instance_id: null,
5600
- action_id: action_id,
5601
- verb: verb,
5602
- hints: hints,
5603
- hint_text: hint_text,
5604
- confirm_id: confirm_id,
5605
- expires_at: Date.now() + (opts.timeout_ms || 60000),
5606
- };
5607
- /* opts.source defaults to {type:'script'} via _emit's normalisation. */
5608
- if (opts.source) reqDetail.source = opts.source;
5609
- _emit('nac:action:confirm:requested', reqDetail);
5610
- let resp;
5611
- try {
5612
- if (_confirmHandler) {
5613
- resp = await _confirmHandler(reqDetail);
5614
- } else if (typeof window.confirm === 'function') {
5615
- const ok = window.confirm(hint_text);
5616
- resp = { granted: !!ok, granted_via: 'window_confirm' };
5617
- } else {
5618
- resp = { granted: false, reason: 'no_handler' };
5619
- }
5620
- } catch (err) {
5621
- resp = { granted: false, reason: 'handler_error',
5622
- error: err && err.message };
5623
- }
5624
- if (resp.granted) {
5625
- _emit('nac:action:confirm:granted', {
5626
- plugin: plugin, plugin_instance_id: null,
5627
- action_id: action_id,
5628
- confirm_id: confirm_id,
5629
- granted_by: opts.source && opts.source.type === 'agent' ? 'agent' : 'user',
5630
- granted_via: resp.granted_via || 'modal_button',
5631
- source: opts.source || { type: 'user' },
5632
- });
5633
- } else {
5634
- _emit('nac:action:confirm:denied', {
5635
- plugin: plugin, plugin_instance_id: null,
5636
- action_id: action_id,
5637
- confirm_id: confirm_id,
5638
- reason: resp.reason || 'user_cancelled',
5639
- source: opts.source || { type: 'user' },
5640
- });
5641
- }
5642
- return {
5643
- confirm_id: confirm_id,
5644
- granted: !!resp.granted,
5645
- granted_by: resp.granted ?
5646
- (opts.source && opts.source.type === 'agent' ? 'agent' : 'user') : undefined,
5647
- granted_via: resp.granted ? (resp.granted_via || 'modal_button') : undefined,
5648
- reason: resp.granted ? undefined : (resp.reason || 'user_cancelled'),
5649
- };
5650
- }
5651
-
5652
6618
  /* ---------- v1.9.0: action undoable flag (sec 6.2.33) --------- */
5653
6619
 
5654
6620
  function _findActionInManifests(action_id) {
@@ -5781,12 +6747,777 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
5781
6747
  return count;
5782
6748
  }
5783
6749
 
6750
+ /* ================================================================
6751
+ v2.5 Block A -- plugin extension contract (SPEC.md sec 15)
6752
+ ================================================================
6753
+
6754
+ Adds an agnostic routing layer so a plugin can declare verbs /
6755
+ state / events that flow through backends other than direct DOM:
6756
+ postMessage to iframes, plugin SDK calls, script bridges, DOM
6757
+ mirrors, same-origin window reads, synthetic events. The runtime
6758
+ stays ignorant of any specific app -- it only knows the fixed
6759
+ vocabulary of backend kinds and the extractor DSL.
6760
+
6761
+ IMPORTANT: NO fallback to v2.4 register() semantics. v2.5 plugins
6762
+ live in their own registry. NAC.call / read / subscribe ONLY
6763
+ consult this registry; they never silently degrade to NAC.click()
6764
+ against a same-named DOM element. */
6765
+
6766
+ const _v25_plugins = Object.create(null);
6767
+
6768
+ /* The 8 backend names from SPEC.md sec 15.4. Any other name in a
6769
+ manifest is a hard reject at register time. */
6770
+ const _V25_VALID_BACKENDS = {
6771
+ 'postmessage': true,
6772
+ 'postmessage-listen': true,
6773
+ 'sdk-call': true,
6774
+ 'script-bridge': true,
6775
+ 'dom-mirror': true,
6776
+ 'same-origin-window': true,
6777
+ 'synthetic-mutation': true,
6778
+ 'synthetic-poll': true,
6779
+ };
6780
+
6781
+ /* Counter for the request_id baked into every provenance event. */
6782
+ let _v25_req_counter = 0;
6783
+ function _v25_nextRequestId(prefix) {
6784
+ _v25_req_counter += 1;
6785
+ /* Hex-ish but non-cryptographic; the contract only requires
6786
+ uniqueness within a session for correlation. */
6787
+ return prefix + '_' + Date.now().toString(36) + '_' + _v25_req_counter.toString(36);
6788
+ }
6789
+
6790
+ /* ---------- 15.5 extractor DSL ---------- */
6791
+
6792
+ /* Apply an extractor DSL string to a raw value (or DOM element).
6793
+ Returns the extracted value. Throws if the DSL is malformed.
6794
+ The runtime swallows extractor errors at dispatch time (treats
6795
+ them as "this binding failed"); throwing here lets the test
6796
+ surface bad manifests during register / first call. */
6797
+ function _v25_extract(rawValue, dsl, isDom) {
6798
+ if (dsl == null || dsl === '') return rawValue;
6799
+ /* DOM-only forms first */
6800
+ if (dsl === 'text') {
6801
+ if (!isDom) throw new Error('extractor "text" requires a DOM element');
6802
+ return rawValue.textContent;
6803
+ }
6804
+ if (dsl === 'value') {
6805
+ if (!isDom) throw new Error('extractor "value" requires a DOM element');
6806
+ return rawValue.value;
6807
+ }
6808
+ if (dsl === 'present') {
6809
+ /* For DOM backends, rawValue is the element OR null. */
6810
+ return rawValue != null;
6811
+ }
6812
+ if (dsl.indexOf('attribute:') === 0) {
6813
+ if (!isDom) throw new Error('extractor "attribute:" requires a DOM element');
6814
+ const attr = dsl.slice('attribute:'.length);
6815
+ return rawValue.getAttribute(attr);
6816
+ }
6817
+ if (dsl.indexOf('classList.contains:') === 0) {
6818
+ if (!isDom) throw new Error('extractor "classList.contains:" requires a DOM element');
6819
+ const cls = dsl.slice('classList.contains:'.length);
6820
+ return rawValue.classList.contains(cls);
6821
+ }
6822
+ /* Otherwise treat as a dotted field path against rawValue. */
6823
+ if (/^[A-Za-z_][\w.]*$/.test(dsl)) {
6824
+ const parts = dsl.split('.');
6825
+ let cur = rawValue;
6826
+ for (let i = 0; i < parts.length; i++) {
6827
+ if (cur == null) return undefined;
6828
+ cur = cur[parts[i]];
6829
+ }
6830
+ return cur;
6831
+ }
6832
+ throw new Error('unknown extractor DSL: ' + dsl);
6833
+ }
6834
+
6835
+ /* ---------- 15.4 backend dispatchers ----------
6836
+ Each backend dispatcher returns a Promise.
6837
+ - For verbs: resolves with the backend's return value (often {ok}).
6838
+ - For state: resolves with the raw value (extractor applied by caller).
6839
+ - Rejects with a plain Error whose .message goes into provenance /
6840
+ err.attempts. */
6841
+
6842
+ function _v25_resolvePath(root, path) {
6843
+ /* Walk a dotted path. Returns { parent, key, value } where
6844
+ parent[key] === value. Used by sdk-call assign / read. */
6845
+ if (!path) return { parent: null, key: null, value: undefined };
6846
+ const parts = path.split('.');
6847
+ let parent = null;
6848
+ let cur = root;
6849
+ let key = null;
6850
+ for (let i = 0; i < parts.length; i++) {
6851
+ if (cur == null) return { parent: null, key: parts[i], value: undefined };
6852
+ parent = cur;
6853
+ key = parts[i];
6854
+ cur = cur[key];
6855
+ }
6856
+ return { parent: parent, key: key, value: cur };
6857
+ }
6858
+
6859
+ function _v25_backend_sdk_call(binding, args) {
6860
+ const mode = binding.mode || 'invoke';
6861
+ const path = binding.path;
6862
+ if (!path || typeof path !== 'string') {
6863
+ return Promise.reject(new Error('sdk-call requires `path` string'));
6864
+ }
6865
+ const resolved = _v25_resolvePath(global, path);
6866
+ if (mode === 'read') {
6867
+ if (resolved.parent == null) {
6868
+ return Promise.reject(new Error('sdk-call read: path not resolvable: ' + path));
6869
+ }
6870
+ if (resolved.value === undefined) {
6871
+ return Promise.reject(new Error('sdk-call read: path resolves to undefined: ' + path));
6872
+ }
6873
+ return Promise.resolve(resolved.value);
6874
+ }
6875
+ if (mode === 'assign') {
6876
+ if (resolved.parent == null) {
6877
+ return Promise.reject(new Error('sdk-call assign: path parent not resolvable: ' + path));
6878
+ }
6879
+ resolved.parent[resolved.key] = args;
6880
+ return Promise.resolve({ ok: true });
6881
+ }
6882
+ if (mode === 'invoke') {
6883
+ if (resolved.parent == null || typeof resolved.value !== 'function') {
6884
+ return Promise.reject(new Error('sdk-call invoke: path is not a function: ' + path));
6885
+ }
6886
+ try {
6887
+ const ret = resolved.value.call(resolved.parent, args);
6888
+ return Promise.resolve(ret);
6889
+ } catch (e) {
6890
+ return Promise.reject(e);
6891
+ }
6892
+ }
6893
+ return Promise.reject(new Error('sdk-call: unknown mode ' + mode));
6894
+ }
6895
+
6896
+ function _v25_backend_dom_mirror(binding /*, args*/) {
6897
+ const sel = binding.selector;
6898
+ if (!sel) return Promise.reject(new Error('dom-mirror requires `selector` string'));
6899
+ const el = document.querySelector(sel);
6900
+ if (binding.extract === 'present') {
6901
+ /* present extractor is well-defined even for null element. */
6902
+ return Promise.resolve(el != null);
6903
+ }
6904
+ if (el == null) {
6905
+ return Promise.reject(new Error('dom-mirror: selector matched no element: ' + sel));
6906
+ }
6907
+ try {
6908
+ const value = _v25_extract(el, binding.extract, true);
6909
+ if (value === undefined) {
6910
+ return Promise.reject(new Error('dom-mirror: extractor returned undefined for ' + sel));
6911
+ }
6912
+ return Promise.resolve(value);
6913
+ } catch (e) {
6914
+ return Promise.reject(e);
6915
+ }
6916
+ }
6917
+
6918
+ /* postmessage (verb): post a structured message to the iframe.contentWindow
6919
+ of the target. `values` literal + `values_from_args` forward keys. */
6920
+ function _v25_backend_postmessage(binding, args) {
6921
+ const sel = binding.target;
6922
+ if (!sel) return Promise.reject(new Error('postmessage requires `target` selector'));
6923
+ const iframe = document.querySelector(sel);
6924
+ if (!iframe) {
6925
+ const e = new Error('postmessage: target iframe not found: ' + sel);
6926
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6927
+ }
6928
+ if (!iframe.contentWindow || typeof iframe.contentWindow.postMessage !== 'function') {
6929
+ const e = new Error('postmessage: target has no contentWindow.postMessage');
6930
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6931
+ }
6932
+ const msg = {
6933
+ MessageId: binding.message,
6934
+ SendTime: Date.now(),
6935
+ Values: Object.assign({}, binding.values || {}),
6936
+ };
6937
+ if (Array.isArray(binding.values_from_args) && args && typeof args === 'object') {
6938
+ for (let i = 0; i < binding.values_from_args.length; i++) {
6939
+ const k = binding.values_from_args[i];
6940
+ if (Object.prototype.hasOwnProperty.call(args, k)) msg.Values[k] = args[k];
6941
+ }
6942
+ }
6943
+ try {
6944
+ iframe.contentWindow.postMessage(msg, binding.target_origin || '*');
6945
+ return Promise.resolve({ ok: true });
6946
+ } catch (e) {
6947
+ return Promise.reject(e);
6948
+ }
6949
+ }
6950
+
6951
+ /* same-origin-window (state): read iframe.contentWindow.<path>. Throws
6952
+ a cross-origin sentinel if accessing the contentWindow fails the
6953
+ same-origin check. In the reference shim we honor an `_sameOrigin`
6954
+ flag the test sets explicitly; in real browsers the property access
6955
+ throws a DOMException SecurityError which we map the same way. */
6956
+ function _v25_backend_same_origin_window(binding /*, args*/) {
6957
+ const sel = binding.target;
6958
+ if (!sel) return Promise.reject(new Error('same-origin-window requires `target`'));
6959
+ const iframe = document.querySelector(sel);
6960
+ if (!iframe) {
6961
+ const e = new Error('same-origin-window: iframe not found: ' + sel);
6962
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6963
+ }
6964
+ if (iframe._sameOrigin === false) {
6965
+ const e = new Error('cross_origin_blocked: iframe is cross-origin');
6966
+ e._code = 'cross_origin_blocked'; return Promise.reject(e);
6967
+ }
6968
+ let cw;
6969
+ try { cw = iframe.contentWindow; }
6970
+ catch (e) {
6971
+ const ex = new Error('cross_origin_blocked: contentWindow access threw');
6972
+ ex._code = 'cross_origin_blocked'; return Promise.reject(ex);
6973
+ }
6974
+ if (!cw) {
6975
+ const e = new Error('same-origin-window: contentWindow is null');
6976
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6977
+ }
6978
+ /* Walk the path. */
6979
+ if (!binding.path) return Promise.reject(new Error('same-origin-window requires `path`'));
6980
+ const parts = binding.path.split('.');
6981
+ let cur = cw;
6982
+ for (let i = 0; i < parts.length; i++) {
6983
+ if (cur == null) return Promise.reject(new Error('same-origin-window: path segment ' + parts[i] + ' is null'));
6984
+ try { cur = cur[parts[i]]; }
6985
+ catch (e) {
6986
+ const ex = new Error('cross_origin_blocked: read into contentWindow threw');
6987
+ ex._code = 'cross_origin_blocked'; return Promise.reject(ex);
6988
+ }
6989
+ }
6990
+ if (cur === undefined) {
6991
+ return Promise.reject(new Error('same-origin-window: path resolves to undefined'));
6992
+ }
6993
+ return Promise.resolve(cur);
6994
+ }
6995
+
6996
+ /* script-bridge (state/verb): postmessage with a request, await a
6997
+ correlated response, extract the value. Used by Collabora's
6998
+ CallPythonScript pattern; generalises to any app that exposes a
6999
+ RPC channel over postMessage. */
7000
+ function _v25_backend_script_bridge(binding, args) {
7001
+ const sel = binding.target;
7002
+ if (!sel) return Promise.reject(new Error('script-bridge requires `target`'));
7003
+ const iframe = document.querySelector(sel);
7004
+ if (!iframe) {
7005
+ const e = new Error('script-bridge: iframe not found: ' + sel);
7006
+ e._code = 'backend_target_missing'; return Promise.reject(e);
7007
+ }
7008
+ if (!iframe.contentWindow || typeof iframe.contentWindow.postMessage !== 'function') {
7009
+ const e = new Error('script-bridge: target has no contentWindow.postMessage');
7010
+ e._code = 'backend_target_missing'; return Promise.reject(e);
7011
+ }
7012
+ const responseMsgId = binding.response_match;
7013
+ if (!responseMsgId) return Promise.reject(new Error('script-bridge requires `response_match`'));
7014
+ const timeoutMs = binding.timeout_ms || 5000;
7015
+ const wantValues = Object.assign({}, binding.values || {});
7016
+ if (args && typeof args === 'object') {
7017
+ for (const k in args) wantValues[k] = args[k];
7018
+ }
7019
+ return new Promise(function (resolve, reject) {
7020
+ let settled = false;
7021
+ function onMessage(ev) {
7022
+ if (settled) return;
7023
+ if (!ev || !ev.data) return;
7024
+ if (ev.source !== iframe.contentWindow) return;
7025
+ if (ev.data.MessageId !== responseMsgId) return;
7026
+ settled = true;
7027
+ global.removeEventListener('message', onMessage);
7028
+ clearTimeout(t);
7029
+ /* Resolve with the raw response object. The caller (read or call)
7030
+ applies binding.extract once -- the dispatcher does not, so the
7031
+ extractor is never run twice. */
7032
+ resolve(ev.data);
7033
+ }
7034
+ const t = setTimeout(function () {
7035
+ if (settled) return;
7036
+ settled = true;
7037
+ global.removeEventListener('message', onMessage);
7038
+ reject(new Error('script-bridge: timeout after ' + timeoutMs + 'ms'));
7039
+ }, timeoutMs);
7040
+ global.addEventListener('message', onMessage);
7041
+ /* Fire the request. */
7042
+ iframe.contentWindow.postMessage({
7043
+ MessageId: binding.message,
7044
+ SendTime: Date.now(),
7045
+ Values: wantValues,
7046
+ }, binding.target_origin || '*');
7047
+ });
7048
+ }
7049
+
7050
+ /* synthetic-poll (event): observe declared state paths on a fixed
7051
+ setInterval cadence. On each tick, re-read every observed path,
7052
+ compare to the cached snapshot, and fire the cb with the new
7053
+ snapshot when ANY value differs. Requires only setInterval; no
7054
+ MutationObserver dependency. Teardown clears the interval. */
7055
+ function _v25_subscribe_synthetic_poll(plugin, event_path, binding, cb) {
7056
+ if (!Array.isArray(binding.observe) || binding.observe.length === 0) {
7057
+ throw new Error('synthetic-poll requires `observe: [state_path, ...]`');
7058
+ }
7059
+ const interval = binding.interval_ms || 250;
7060
+ const paths = binding.observe.slice();
7061
+ let cached = null; /* null until first successful snapshot */
7062
+ function snapshot() {
7063
+ const out = {};
7064
+ let allOk = true;
7065
+ const promises = paths.map(function (p) {
7066
+ return read(plugin, p).then(function (v) { out[p] = v; },
7067
+ function () { allOk = false; });
7068
+ });
7069
+ return Promise.all(promises).then(function () {
7070
+ return allOk ? out : null;
7071
+ });
7072
+ }
7073
+ function diffsFromCached(snap) {
7074
+ if (cached == null) return false;
7075
+ for (let i = 0; i < paths.length; i++) {
7076
+ const k = paths[i];
7077
+ /* Strict JSON-shape compare for primitives + objects. */
7078
+ const a = cached[k]; const b = snap[k];
7079
+ if (a !== b) {
7080
+ if (typeof a !== 'object' || typeof b !== 'object') return true;
7081
+ if (JSON.stringify(a) !== JSON.stringify(b)) return true;
7082
+ }
7083
+ }
7084
+ return false;
7085
+ }
7086
+ /* Prime the cache from the first snapshot so the first real change
7087
+ fires (and not the initial baseline). */
7088
+ snapshot().then(function (first) { if (first != null) cached = first; });
7089
+ const handle = setInterval(function () {
7090
+ snapshot().then(function (snap) {
7091
+ if (snap == null) return;
7092
+ if (cached == null) { cached = snap; return; }
7093
+ if (diffsFromCached(snap)) {
7094
+ cached = snap;
7095
+ try { cb(snap); }
7096
+ finally {
7097
+ _v25_emitProvenance('event', plugin, event_path, 'synthetic-poll',
7098
+ _v25_nextRequestId('pe'), true, null, 0);
7099
+ }
7100
+ }
7101
+ });
7102
+ }, interval);
7103
+ return function teardown() { clearInterval(handle); };
7104
+ }
7105
+
7106
+ /* synthetic-mutation (event): observe declared state paths via
7107
+ MutationObserver on the underlying dom-mirror elements. On
7108
+ mutation (with throttle), re-read every observed path and fire
7109
+ the user cb when ANY value changed vs the cached snapshot.
7110
+
7111
+ Requires that every observed path's FIRST state binding be
7112
+ dom-mirror -- only DOM-rooted state is observable via mutations.
7113
+ Mixed manifests (dom-mirror + sdk-call in the same observe list)
7114
+ reject at subscribe time with `invalid`. The manifest author can
7115
+ fall back to synthetic-poll for those cases (declared, not
7116
+ implicit). */
7117
+ function _v25_subscribe_synthetic_mutation(plugin, event_path, binding, cb) {
7118
+ if (typeof MutationObserver === 'undefined') {
7119
+ throw new Error('synthetic-mutation requires MutationObserver in scope');
7120
+ }
7121
+ if (!Array.isArray(binding.observe) || binding.observe.length === 0) {
7122
+ throw new Error('synthetic-mutation requires `observe: [state_path, ...]`');
7123
+ }
7124
+ const throttle = binding.throttle_ms != null ? binding.throttle_ms : 100;
7125
+ const paths = binding.observe.slice();
7126
+ /* Resolve each observed path to a dom-mirror element. Reject the
7127
+ whole subscription if any observed path's primary binding is
7128
+ not dom-mirror -- spec contract, no silent degradation. */
7129
+ const elements = [];
7130
+ const manifest = _v25_plugins[plugin];
7131
+ for (let i = 0; i < paths.length; i++) {
7132
+ const stateChain = manifest.state[paths[i]];
7133
+ if (!stateChain || !stateChain.length) {
7134
+ const e = new Error('synthetic-mutation: observed state "' + paths[i] + '" not declared');
7135
+ e._code = 'invalid'; throw e;
7136
+ }
7137
+ const first = stateChain[0];
7138
+ if (first.backend !== 'dom-mirror') {
7139
+ const e = new Error('synthetic-mutation: observed state "' + paths[i] +
7140
+ '" primary backend must be dom-mirror, got ' + first.backend);
7141
+ e._code = 'invalid'; throw e;
7142
+ }
7143
+ const el = document.querySelector(first.selector);
7144
+ if (el) elements.push(el);
7145
+ }
7146
+ let cached = null;
7147
+ let pending = null;
7148
+ function snapshot() {
7149
+ const out = {};
7150
+ let allOk = true;
7151
+ const promises = paths.map(function (p) {
7152
+ return read(plugin, p).then(function (v) { out[p] = v; },
7153
+ function () { allOk = false; });
7154
+ });
7155
+ return Promise.all(promises).then(function () {
7156
+ return allOk ? out : null;
7157
+ });
7158
+ }
7159
+ function diffsFromCached(snap) {
7160
+ if (cached == null) return false;
7161
+ for (let i = 0; i < paths.length; i++) {
7162
+ const k = paths[i];
7163
+ const a = cached[k]; const b = snap[k];
7164
+ if (a !== b) {
7165
+ if (typeof a !== 'object' || typeof b !== 'object') return true;
7166
+ if (JSON.stringify(a) !== JSON.stringify(b)) return true;
7167
+ }
7168
+ }
7169
+ return false;
7170
+ }
7171
+ function tick() {
7172
+ pending = null;
7173
+ snapshot().then(function (snap) {
7174
+ if (snap == null) return;
7175
+ if (cached == null) { cached = snap; return; }
7176
+ if (diffsFromCached(snap)) {
7177
+ cached = snap;
7178
+ try { cb(snap); }
7179
+ finally {
7180
+ _v25_emitProvenance('event', plugin, event_path, 'synthetic-mutation',
7181
+ _v25_nextRequestId('pe'), true, null, 0);
7182
+ }
7183
+ }
7184
+ });
7185
+ }
7186
+ /* Prime cache from first snapshot. */
7187
+ snapshot().then(function (first) { if (first != null) cached = first; });
7188
+ const observer = new MutationObserver(function () {
7189
+ if (pending != null) return; /* already throttled */
7190
+ pending = setTimeout(tick, throttle);
7191
+ });
7192
+ for (let i = 0; i < elements.length; i++) {
7193
+ observer.observe(elements[i], {
7194
+ attributes: true, childList: true, characterData: true, subtree: true,
7195
+ });
7196
+ }
7197
+ return function teardown() {
7198
+ observer.disconnect();
7199
+ if (pending != null) { clearTimeout(pending); pending = null; }
7200
+ };
7201
+ }
7202
+
7203
+ /* postmessage-listen (event): subscribe to incoming `message` events
7204
+ on the host window, filter by source iframe + MessageId, run the
7205
+ extractor, fire the user callback. Returns a teardown closure. */
7206
+ function _v25_subscribe_postmessage_listen(plugin, event_path, binding, cb) {
7207
+ const sel = binding.source;
7208
+ const wantMsgId = binding.message;
7209
+ if (!wantMsgId) throw new Error('postmessage-listen requires `message`');
7210
+ /* Source filtering: if a selector is given, resolve the iframe NOW.
7211
+ If the iframe is later replaced, the subscription stops matching;
7212
+ that is intentional -- callers can re-subscribe on remount. */
7213
+ const iframe = sel ? document.querySelector(sel) : null;
7214
+ function onMessage(ev) {
7215
+ if (!ev || !ev.data) return;
7216
+ if (ev.data.MessageId !== wantMsgId) return;
7217
+ if (iframe && ev.source !== iframe.contentWindow) return;
7218
+ let value;
7219
+ try {
7220
+ value = binding.extract ? _v25_extract(ev.data, binding.extract, false) : ev.data;
7221
+ } catch (e) {
7222
+ _v25_emitProvenance('event', plugin, event_path, 'postmessage-listen',
7223
+ _v25_nextRequestId('pe'), false, e.message, 0);
7224
+ return;
7225
+ }
7226
+ try { cb(value); }
7227
+ finally {
7228
+ _v25_emitProvenance('event', plugin, event_path, 'postmessage-listen',
7229
+ _v25_nextRequestId('pe'), true, null, 0);
7230
+ }
7231
+ }
7232
+ global.addEventListener('message', onMessage);
7233
+ return function teardown() { global.removeEventListener('message', onMessage); };
7234
+ }
7235
+
7236
+ /* Registry of dispatchers keyed by backend name. */
7237
+ const _V25_VERB_DISPATCHERS = {
7238
+ 'sdk-call': _v25_backend_sdk_call,
7239
+ 'postmessage': _v25_backend_postmessage,
7240
+ 'script-bridge': _v25_backend_script_bridge,
7241
+ /* same-origin-window and dom-mirror are state-only; the synthetic
7242
+ backends are event-only. */
7243
+ };
7244
+ const _V25_STATE_DISPATCHERS = {
7245
+ 'sdk-call': _v25_backend_sdk_call,
7246
+ 'dom-mirror': _v25_backend_dom_mirror,
7247
+ 'same-origin-window': _v25_backend_same_origin_window,
7248
+ 'script-bridge': _v25_backend_script_bridge,
7249
+ };
7250
+ const _V25_EVENT_SUBSCRIBERS = {
7251
+ 'postmessage-listen': _v25_subscribe_postmessage_listen,
7252
+ 'synthetic-poll': _v25_subscribe_synthetic_poll,
7253
+ 'synthetic-mutation': _v25_subscribe_synthetic_mutation,
7254
+ };
7255
+
7256
+ /* ---------- 15.2 / 15.3 public surface ---------- */
7257
+
7258
+ function _v25_validateManifest(slug, manifest) {
7259
+ if (typeof slug !== 'string' || !slug) {
7260
+ const e = new Error('registerPlugin: slug must be non-empty string');
7261
+ e.code = 'invalid'; throw e;
7262
+ }
7263
+ if (manifest == null || typeof manifest !== 'object') {
7264
+ const e = new Error('registerPlugin: manifest object required');
7265
+ e.code = 'invalid'; throw e;
7266
+ }
7267
+ const verbs = manifest.verbs || {};
7268
+ const states = manifest.state || {};
7269
+ const events = manifest.events || {};
7270
+ /* Verbs: single binding each, backend in vocabulary. */
7271
+ for (const vp in verbs) {
7272
+ const b = verbs[vp];
7273
+ if (!b || typeof b !== 'object' || !b.backend) {
7274
+ const e = new Error('verb "' + vp + '" missing backend');
7275
+ e.code = 'invalid'; throw e;
7276
+ }
7277
+ if (!_V25_VALID_BACKENDS[b.backend]) {
7278
+ const e = new Error('verb "' + vp + '" declares unknown backend: ' + b.backend);
7279
+ e.code = 'backend_unknown'; throw e;
7280
+ }
7281
+ }
7282
+ /* State: array of bindings each. */
7283
+ for (const sp in states) {
7284
+ const arr = states[sp];
7285
+ if (!Array.isArray(arr) || arr.length === 0) {
7286
+ const e = new Error('state "' + sp + '" must be a non-empty array of bindings');
7287
+ e.code = 'invalid'; throw e;
7288
+ }
7289
+ for (let i = 0; i < arr.length; i++) {
7290
+ const b = arr[i];
7291
+ if (!b || typeof b !== 'object' || !b.backend) {
7292
+ const e = new Error('state "' + sp + '" binding[' + i + '] missing backend');
7293
+ e.code = 'invalid'; throw e;
7294
+ }
7295
+ if (!_V25_VALID_BACKENDS[b.backend]) {
7296
+ const e = new Error('state "' + sp + '" binding[' + i + '] unknown backend: ' + b.backend);
7297
+ e.code = 'backend_unknown'; throw e;
7298
+ }
7299
+ }
7300
+ }
7301
+ /* Events: single binding each. */
7302
+ for (const ep in events) {
7303
+ const b = events[ep];
7304
+ if (!b || typeof b !== 'object' || !b.backend) {
7305
+ const e = new Error('event "' + ep + '" missing backend');
7306
+ e.code = 'invalid'; throw e;
7307
+ }
7308
+ if (!_V25_VALID_BACKENDS[b.backend]) {
7309
+ const e = new Error('event "' + ep + '" unknown backend: ' + b.backend);
7310
+ e.code = 'backend_unknown'; throw e;
7311
+ }
7312
+ }
7313
+ }
7314
+
7315
+ function registerPlugin(slug, manifest) {
7316
+ _v25_validateManifest(slug, manifest);
7317
+ /* Re-register replaces -- idempotent for live-reload scenarios. */
7318
+ _v25_plugins[slug] = {
7319
+ slug: slug,
7320
+ verbs: manifest.verbs || {},
7321
+ state: manifest.state || {},
7322
+ events: manifest.events || {},
7323
+ };
7324
+ }
7325
+
7326
+ /* Provenance emit helper -- the kind is one of 'invoked', 'read',
7327
+ 'event'. Detail shape per SPEC.md sec 15.7. */
7328
+ function _v25_emitProvenance(kind, plugin, path, backend, request_id, ok, error, duration_ms, extra) {
7329
+ const detail = {
7330
+ plugin: plugin,
7331
+ backend: backend || null,
7332
+ request_id: request_id,
7333
+ source: 'agent',
7334
+ trusted: false,
7335
+ duration_ms: duration_ms,
7336
+ ok: !!ok,
7337
+ error: error || null,
7338
+ };
7339
+ if (kind === 'invoked') detail.verb_path = path;
7340
+ else if (kind === 'read') detail.state_path = path;
7341
+ else if (kind === 'event') detail.event_path = path;
7342
+ if (extra) {
7343
+ for (const k in extra) detail[k] = extra[k];
7344
+ }
7345
+ try {
7346
+ document.dispatchEvent(new CustomEvent('nac:plugin:' + kind, { detail: detail, bubbles: true }));
7347
+ } catch (_) { /* if document lacks dispatch, swallow */ }
7348
+ }
7349
+
7350
+ function _v25_buildNacError(code, message, extra) {
7351
+ const e = new Error(message);
7352
+ e.code = code;
7353
+ if (extra) for (const k in extra) e[k] = extra[k];
7354
+ return e;
7355
+ }
7356
+
7357
+ function call(plugin, verb_path, args) {
7358
+ const request_id = _v25_nextRequestId('pi');
7359
+ const t0 = Date.now();
7360
+ /* Errors that surface BEFORE any backend dispatch still get a
7361
+ provenance row -- the agent's request happened, it just failed
7362
+ at routing. backend stays null in that case. */
7363
+ if (!_v25_plugins[plugin]) {
7364
+ const err = _v25_buildNacError('plugin_not_registered',
7365
+ 'NAC.call: plugin "' + plugin + '" not registered');
7366
+ _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
7367
+ return Promise.reject(err);
7368
+ }
7369
+ const binding = _v25_plugins[plugin].verbs[verb_path];
7370
+ if (!binding) {
7371
+ const err = _v25_buildNacError('verb_not_declared',
7372
+ 'NAC.call: plugin "' + plugin + '" has no verb "' + verb_path + '"');
7373
+ _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
7374
+ return Promise.reject(err);
7375
+ }
7376
+ const dispatcher = _V25_VERB_DISPATCHERS[binding.backend];
7377
+ if (!dispatcher) {
7378
+ const err = _v25_buildNacError('backend_unknown',
7379
+ 'NAC.call: backend "' + binding.backend + '" not implemented for verbs');
7380
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, false, err.message, Date.now() - t0);
7381
+ return Promise.reject(err);
7382
+ }
7383
+ return dispatcher(binding, args).then(function (value) {
7384
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, true, null, Date.now() - t0);
7385
+ return value;
7386
+ }, function (err) {
7387
+ /* If the dispatcher tagged the error with a NacError code via
7388
+ `_code`, lift it onto a proper NacError so callers see e.g.
7389
+ backend_target_missing or cross_origin_blocked instead of the
7390
+ raw Error. Provenance always records the human message. */
7391
+ const msg = (err && err.message) || String(err);
7392
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, false, msg, Date.now() - t0);
7393
+ if (err && err._code) {
7394
+ throw _v25_buildNacError(err._code, msg);
7395
+ }
7396
+ throw err;
7397
+ });
7398
+ }
7399
+
7400
+ function read(plugin, state_path) {
7401
+ const request_id = _v25_nextRequestId('pr');
7402
+ const t0 = Date.now();
7403
+ if (!_v25_plugins[plugin]) {
7404
+ const err = _v25_buildNacError('plugin_not_registered',
7405
+ 'NAC.read: plugin "' + plugin + '" not registered');
7406
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
7407
+ return Promise.reject(err);
7408
+ }
7409
+ const chain = _v25_plugins[plugin].state[state_path];
7410
+ if (!chain) {
7411
+ const err = _v25_buildNacError('state_not_declared',
7412
+ 'NAC.read: plugin "' + plugin + '" has no state "' + state_path + '"');
7413
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
7414
+ return Promise.reject(err);
7415
+ }
7416
+ /* Walk the chain in declared order. First binding to resolve with
7417
+ a non-undefined value wins. Every failure is recorded for the
7418
+ state_unreadable error if none succeed. */
7419
+ const attempts = [];
7420
+ function tryAt(i) {
7421
+ if (i >= chain.length) {
7422
+ const err = _v25_buildNacError('state_unreadable',
7423
+ 'NAC.read: every binding in chain for "' + state_path + '" failed',
7424
+ { attempts: attempts });
7425
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0, { attempts: attempts });
7426
+ return Promise.reject(err);
7427
+ }
7428
+ const binding = chain[i];
7429
+ const dispatcher = _V25_STATE_DISPATCHERS[binding.backend];
7430
+ if (!dispatcher) {
7431
+ attempts.push({ backend: binding.backend, reason: 'dispatcher not implemented for state' });
7432
+ return tryAt(i + 1);
7433
+ }
7434
+ return dispatcher(binding).then(function (raw) {
7435
+ /* For dom-mirror with extract, the dispatcher already applied
7436
+ the extractor and returned the extracted value. For sdk-call
7437
+ with mode:read, the raw value is the path's value -- no
7438
+ extractor needed unless the manifest declared one. */
7439
+ let value;
7440
+ if (binding.backend === 'dom-mirror') {
7441
+ value = raw; /* already extracted */
7442
+ } else if (binding.extract) {
7443
+ try { value = _v25_extract(raw, binding.extract, false); }
7444
+ catch (e) {
7445
+ attempts.push({ backend: binding.backend, reason: e.message });
7446
+ return tryAt(i + 1);
7447
+ }
7448
+ } else {
7449
+ value = raw;
7450
+ }
7451
+ if (value === undefined) {
7452
+ attempts.push({ backend: binding.backend, reason: 'resolved value was undefined' });
7453
+ return tryAt(i + 1);
7454
+ }
7455
+ _v25_emitProvenance('read', plugin, state_path, binding.backend, request_id, true, null, Date.now() - t0);
7456
+ return value;
7457
+ }, function (err) {
7458
+ attempts.push({ backend: binding.backend, reason: err.message || String(err) });
7459
+ return tryAt(i + 1);
7460
+ });
7461
+ }
7462
+ return tryAt(0);
7463
+ }
7464
+
7465
+ /* Active subscription handles -> teardown closures. Allows
7466
+ idempotent unsubscribe by handle reference. */
7467
+ const _v25_subscriptions = new WeakMap();
7468
+ let _v25_sub_counter = 0;
7469
+
7470
+ function subscribe(plugin, event_path, cb) {
7471
+ if (typeof cb !== 'function') {
7472
+ throw _v25_buildNacError('invalid', 'NAC.subscribe: cb must be a function');
7473
+ }
7474
+ if (!_v25_plugins[plugin]) {
7475
+ throw _v25_buildNacError('plugin_not_registered',
7476
+ 'NAC.subscribe: plugin "' + plugin + '" not registered');
7477
+ }
7478
+ const binding = _v25_plugins[plugin].events[event_path];
7479
+ if (!binding) {
7480
+ throw _v25_buildNacError('event_not_declared',
7481
+ 'NAC.subscribe: plugin "' + plugin + '" has no event "' + event_path + '"');
7482
+ }
7483
+ const subscriber = _V25_EVENT_SUBSCRIBERS[binding.backend];
7484
+ if (!subscriber) {
7485
+ throw _v25_buildNacError('backend_unknown',
7486
+ 'NAC.subscribe: backend "' + binding.backend + '" not implemented for events');
7487
+ }
7488
+ let teardown;
7489
+ try { teardown = subscriber(plugin, event_path, binding, cb); }
7490
+ catch (e) {
7491
+ if (e && e._code) throw _v25_buildNacError(e._code, e.message);
7492
+ throw e;
7493
+ }
7494
+ _v25_sub_counter += 1;
7495
+ const handle = {
7496
+ __v25_sub: true,
7497
+ id: _v25_sub_counter,
7498
+ plugin: plugin,
7499
+ event_path: event_path,
7500
+ backend: binding.backend,
7501
+ };
7502
+ _v25_subscriptions.set(handle, teardown);
7503
+ return handle;
7504
+ }
7505
+
7506
+ function unsubscribe(handle) {
7507
+ if (!handle || !handle.__v25_sub) return;
7508
+ const teardown = _v25_subscriptions.get(handle);
7509
+ if (teardown) {
7510
+ try { teardown(); } catch (_) { /* idempotent */ }
7511
+ _v25_subscriptions.delete(handle);
7512
+ }
7513
+ }
7514
+
5784
7515
  /* ---------- Install -------------------------------------------- */
5785
7516
 
5786
7517
  global.NAC = {
5787
7518
  __nac_v1_installed: true,
5788
- version: '2.4.0',
5789
- spec_version: '2.4',
7519
+ version: '2.5.0-alpha.2',
7520
+ spec_version: '2.5',
5790
7521
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
5791
7522
  NAC.register throws on findings (manifest_role_unknown,
5792
7523
  tab_id_manifest_role_drift, manifest_dom_role_mismatch).
@@ -5796,10 +7527,43 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
5796
7527
  bootstrap before any register() call. See
5797
7528
  guides/MIGRATION_v2.2_to_v2.3.md. */
5798
7529
  STRICT_VALIDATION: true,
7530
+ /* v2.5 / RFC V24-01 -- when true (default), NAC.register throws
7531
+ on the first slug uniqueness violation; the boot-time pass
7532
+ paints a red banner + dispatches nac:fatal. Set false BEFORE
7533
+ any register() call to opt out for a single migration window.
7534
+ The flag is removed in v2.6 (enforcement becomes unconditional). */
7535
+ HARD_DEDUP: true,
5799
7536
  /* registry */
5800
7537
  register: register,
5801
7538
  unregister: unregister,
5802
7539
  manifest: manifest,
7540
+ /* v2.5 V24-02 -- idempotent registration. Use this in SPA hosts
7541
+ where a component remount may call into NAC twice; syncPlugin
7542
+ replaces the manifest instead of appending. */
7543
+ syncPlugin: syncPlugin,
7544
+ /* v2.5 V24-05 -- Agent authority + sudo elevation. The host
7545
+ interposes a confirmation UI between agent dispatch and the
7546
+ action's side effect; request_authority + has_authority let
7547
+ the user grant a time-bounded "sudo" elevation that bypasses
7548
+ confirmations for a scope until TTL expires. */
7549
+ set_confirm_handler: set_confirm_handler,
7550
+ confirm_action: confirm_action,
7551
+ request_authority: request_authority,
7552
+ has_authority: has_authority,
7553
+ revoke_authority: revoke_authority,
7554
+ /* v2.5 V24-04 -- Snapshot versioning + optimistic concurrency.
7555
+ plugin_version + element_state_hash + tree_version appear in
7556
+ describe() output (RFC sec 5.2/5.3). expected_plugin_version
7557
+ / expected_tree_version / expected_element_state_hash on every
7558
+ mutating API reject with NacError('snapshot_stale', ...) when
7559
+ the snapshot is stale. Default STRICT_VERSIONING=false in
7560
+ 2.5.0-alpha.2 so adopters opt in; flips to true in alpha.3
7561
+ once the dispatch hooks finish their soak window. */
7562
+ STRICT_VERSIONING: false,
7563
+ eager_hashing: false,
7564
+ conformance_tier: 'NAC-3-versioned',
7565
+ markHydrationComplete: markHydrationComplete,
7566
+ versionHistory: versionHistory,
5803
7567
  /* v2.3 preview (V23-02): introspection helper that returns the
5804
7568
  list of plugin slugs currently registered (regardless of DOM
5805
7569
  mount state). Used by the interop layer's export_tree to
@@ -5967,9 +7731,10 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
5967
7731
  assert_event_count: assert_event_count,
5968
7732
  perf_probe: perf_probe,
5969
7733
  replay_pending: replay_pending,
5970
- /* v1.9.0 -- action confirmation (sec 6.2.32) */
5971
- confirm_action: confirm_action,
5972
- set_confirm_handler: set_confirm_handler,
7734
+ /* v1.9.0 -- action confirmation -- superseded by v2.5 V24-05
7735
+ (set_confirm_handler / confirm_action / request_authority /
7736
+ has_authority / revoke_authority exposed earlier in this
7737
+ object). The v1.9 single-handler model is a strict subset. */
5973
7738
  /* v1.9.0 -- action undoable flag (sec 6.2.33) */
5974
7739
  action_undoable: action_undoable,
5975
7740
  action_undo_window_ms: action_undo_window_ms,
@@ -5991,6 +7756,15 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
5991
7756
  },
5992
7757
  /* errors */
5993
7758
  NacError: NacError,
7759
+ /* v2.5 Block A -- plugin extension contract (SPEC.md sec 15).
7760
+ Agnostic routing for canvas + API surfaces (Collabora, Figma,
7761
+ Miro, Excalidraw, etc). Lives in its own registry; never falls
7762
+ back to v2.4 register() semantics. */
7763
+ registerPlugin: registerPlugin,
7764
+ call: call,
7765
+ read: read,
7766
+ subscribe: subscribe,
7767
+ unsubscribe: unsubscribe,
5994
7768
  };
5995
7769
 
5996
7770
  /* v2.2.1: guard browser-only init so this module is importable in