@nac3/runtime 2.5.0-alpha.1 → 2.5.0-alpha.3

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
@@ -470,6 +470,645 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
470
470
  }
471
471
  /* /end V24-01 */
472
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
+
473
1112
  /* H1.v7 (2026-05-21): structured disambiguation contract.
474
1113
  When the runtime cannot resolve an id/verb/qualifier/label
475
1114
  unambiguously, it MUST emit `nac:disambiguation_requested` with
@@ -1776,14 +2415,10 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1776
2415
  and -- only on REPLACE, not first-add -- emits
1777
2416
  nac:plugin:invalidated so subscribers can refresh derived state. */
1778
2417
 
1779
- /* Monotonic + sortable plugin_version stamp. Format `v_<base36 ts>_<seq>`
1780
- so versions ordered lexicographically reflect register order. */
1781
- let _v25_versionSeq = 0;
1782
- function _v25_nextPluginVersion() {
1783
- _v25_versionSeq += 1;
1784
- return 'v_' + Date.now().toString(36) + '_' + _v25_versionSeq.toString(36);
1785
- }
1786
-
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. */
1787
2422
  function syncPlugin(arg1, arg2) {
1788
2423
  let m;
1789
2424
  if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
@@ -1802,9 +2437,6 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1802
2437
  'syncPlugin: manifest.plugin_slug required (non-empty string)');
1803
2438
  }
1804
2439
  const wasPresent = !!_manifests[slug];
1805
- const prevVersion = wasPresent && _manifests[slug]._v25_plugin_version
1806
- ? _manifests[slug]._v25_plugin_version
1807
- : null;
1808
2440
  /* Replace path: drop the prior entry so register() does not
1809
2441
  append-by-side-effect when callers used the array-of-elements
1810
2442
  merge pattern. */
@@ -1816,31 +2448,18 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1816
2448
  exactly one place. If register throws (strict validation), the
1817
2449
  prior entry is GONE -- caller's responsibility to handle. */
1818
2450
  register(m);
1819
- const newVersion = _v25_nextPluginVersion();
1820
- if (_manifests[slug]) {
1821
- _manifests[slug]._v25_plugin_version = newVersion;
1822
- }
1823
- /* Emit invalidated ONLY on replace. First-add is a normal
1824
- register: subscribers do not need to refresh anything that
1825
- did not exist a moment ago. */
1826
- if (wasPresent && typeof document !== 'undefined') {
1827
- try {
1828
- document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
1829
- detail: {
1830
- plugin_slug: slug,
1831
- plugin_instance_id: null,
1832
- from_version: prevVersion || 'v_initial',
1833
- to_version: newVersion,
1834
- trigger: 'syncPlugin',
1835
- },
1836
- bubbles: true,
1837
- }));
1838
- } catch (_) { /* document.dispatchEvent absent in SSR */ }
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');
1839
2458
  }
1840
2459
  return {
1841
2460
  replaced: wasPresent,
1842
2461
  slug: slug,
1843
- version: newVersion,
2462
+ version: _pluginVersionFor(slug, null),
1844
2463
  };
1845
2464
  }
1846
2465
 
@@ -1883,6 +2502,7 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1883
2502
 
1884
2503
  const _V25_SCOPE_RANK = { low: 1, medium: 2, high: 3 };
1885
2504
  const _v25_authority_grants = new Map();
2505
+ let _v25_authReqSeq = 0;
1886
2506
  let _v25_confirm_handler = null;
1887
2507
 
1888
2508
  function _v25_emitAuth(kind, detail) {
@@ -1947,7 +2567,7 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
1947
2567
  'request_authority: NAC.set_confirm_handler must be called first'));
1948
2568
  return;
1949
2569
  }
1950
- const reqId = _v25_nextPluginVersion(); /* reuse the monotonic stamp */
2570
+ const reqId = 'auth_' + Date.now().toString(36) + '_' + (++_v25_authReqSeq).toString(36);
1951
2571
  const req = {
1952
2572
  kind: 'request_authority',
1953
2573
  request_id: reqId,
@@ -2266,12 +2886,20 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
2266
2886
  const plugins = Array.prototype.slice.call(
2267
2887
  document.querySelectorAll('[data-nac-plugin]')
2268
2888
  ).map(function (root) {
2889
+ const slug = root.getAttribute('data-nac-plugin');
2890
+ const instance_id = root.getAttribute('data-nac-plugin-id') || null;
2269
2891
  return {
2270
- plugin: root.getAttribute('data-nac-plugin'),
2271
- plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
2272
- 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(
2273
2901
  root.querySelectorAll('[data-nac-id]')
2274
- ).map(_serializeElement),
2902
+ ).map(_serializeElementWithHash),
2275
2903
  };
2276
2904
  });
2277
2905
  return {
@@ -2280,9 +2908,24 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
2280
2908
  url: location.href,
2281
2909
  active: _activePlugin(),
2282
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(),
2283
2915
  };
2284
2916
  }
2285
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
+
2286
2929
  function list(role) {
2287
2930
  const all = _allElements().map(_serializeElement);
2288
2931
  if (!role) return all;
@@ -2587,6 +3230,19 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
2587
3230
  });
2588
3231
  throw NacError(ariaPF.reason, ariaPF.message);
2589
3232
  }
3233
+ /* v2.5 / RFC V24-04 OCC gate. Only await when opts actually
3234
+ carries expected_* OR STRICT_VERSIONING demands it; otherwise
3235
+ skip to avoid introducing a microtask boundary that would
3236
+ reorder side-effect-then-immediate-check call patterns. */
3237
+ {
3238
+ const _o = opts || {};
3239
+ const _hasExp = ('expected_plugin_version' in _o)
3240
+ || ('expected_tree_version' in _o)
3241
+ || ('expected_element_state_hash' in _o);
3242
+ if (_hasExp || _strictVersioningOn()) {
3243
+ await _resolveVersionExpectations(opts, el);
3244
+ }
3245
+ }
2590
3246
  const role = el.getAttribute('data-nac-role') || 'action';
2591
3247
  const family = _CLICK_EVENT_FAMILY[role] || _CLICK_EVENT_FAMILY['action'];
2592
3248
  /* The first event in each family is the "success" signal; if a
@@ -2820,6 +3476,16 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
2820
3476
  });
2821
3477
  throw NacError(fillPF.reason, fillPF.message);
2822
3478
  }
3479
+ /* v2.5 / RFC V24-04 OCC gate. Same conditional pattern as click. */
3480
+ {
3481
+ const _o = opts || {};
3482
+ const _hasExp = ('expected_plugin_version' in _o)
3483
+ || ('expected_tree_version' in _o)
3484
+ || ('expected_element_state_hash' in _o);
3485
+ if (_hasExp || _strictVersioningOn()) {
3486
+ await _resolveVersionExpectations(opts, el);
3487
+ }
3488
+ }
2823
3489
  _focusElement(el);
2824
3490
  const ft = el.getAttribute('data-nac-field-type');
2825
3491
 
@@ -2880,6 +3546,16 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
2880
3546
  async function select(nac_id, option, opts) {
2881
3547
  const el = _findElement(nac_id, opts);
2882
3548
  if (!el) throw NacError('not_found', 'No select with nac_id=' + nac_id);
3549
+ /* v2.5 / RFC V24-04 OCC gate. */
3550
+ {
3551
+ const _o = opts || {};
3552
+ const _hasExp = ('expected_plugin_version' in _o)
3553
+ || ('expected_tree_version' in _o)
3554
+ || ('expected_element_state_hash' in _o);
3555
+ if (_hasExp || _strictVersioningOn()) {
3556
+ await _resolveVersionExpectations(opts, el);
3557
+ }
3558
+ }
2883
3559
  _focusElement(el);
2884
3560
  if (el.tagName === 'SELECT') {
2885
3561
  if (el.multiple && Array.isArray(option)) {
@@ -3194,6 +3870,16 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
3194
3870
  an invoke based on UI state should do it in their
3195
3871
  nac:action:requested listener and emit nac:action:failed
3196
3872
  with a meaningful error code. */
3873
+ /* v2.5 / RFC V24-04 OCC gate. */
3874
+ {
3875
+ const _o = opts || {};
3876
+ const _hasExp = ('expected_plugin_version' in _o)
3877
+ || ('expected_tree_version' in _o)
3878
+ || ('expected_element_state_hash' in _o);
3879
+ if (_hasExp || _strictVersioningOn()) {
3880
+ await _resolveVersionExpectations(opts, el);
3881
+ }
3882
+ }
3197
3883
  const verb = (payload && payload.verb)
3198
3884
  || el.getAttribute('data-nac-action')
3199
3885
  || '';
@@ -6873,7 +7559,7 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
6873
7559
 
6874
7560
  global.NAC = {
6875
7561
  __nac_v1_installed: true,
6876
- version: '2.5.0-alpha.1',
7562
+ version: '2.5.0-alpha.3',
6877
7563
  spec_version: '2.5',
6878
7564
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
6879
7565
  NAC.register throws on findings (manifest_role_unknown,
@@ -6908,6 +7594,19 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
6908
7594
  request_authority: request_authority,
6909
7595
  has_authority: has_authority,
6910
7596
  revoke_authority: revoke_authority,
7597
+ /* v2.5 V24-04 -- Snapshot versioning + optimistic concurrency.
7598
+ plugin_version + element_state_hash + tree_version appear in
7599
+ describe() output (RFC sec 5.2/5.3). expected_plugin_version
7600
+ / expected_tree_version / expected_element_state_hash on every
7601
+ mutating API reject with NacError('snapshot_stale', ...) when
7602
+ the snapshot is stale. Default STRICT_VERSIONING=false in
7603
+ 2.5.0-alpha.2 so adopters opt in; flips to true in alpha.3
7604
+ once the dispatch hooks finish their soak window. */
7605
+ STRICT_VERSIONING: false,
7606
+ eager_hashing: false,
7607
+ conformance_tier: 'NAC-3-versioned',
7608
+ markHydrationComplete: markHydrationComplete,
7609
+ versionHistory: versionHistory,
6911
7610
  /* v2.3 preview (V23-02): introspection helper that returns the
6912
7611
  list of plugin slugs currently registered (regardless of DOM
6913
7612
  mount state). Used by the interop layer's export_tree to