@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.
@@ -469,6 +469,645 @@
469
469
  }
470
470
  /* /end V24-01 */
471
471
 
472
+ /* ==================================================================
473
+ v2.4 / RFC V24-04: Snapshot versioning + optimistic concurrency
474
+ ==================================================================
475
+
476
+ Promotes NAC3 from a decoration-and-verb contract to a real
477
+ agentic concurrency protocol. See docs/RFC_V24-04.md for the
478
+ full design + Appendix C for agent best practices. Three
479
+ primitives, in order an agent should typically use them:
480
+
481
+ plugin_version primary; per-plugin monotonic; ignores noise
482
+ outside the targeted plugin.
483
+ element_state_hash content-aware; 128-bit SHA-256 truncated.
484
+ tree_version escape hatch; global monotonic.
485
+
486
+ All three are returned by describe(); all three are honored as
487
+ expected_* parameters on every mutating API; mismatches reject
488
+ with NacError('snapshot_stale', { reason, ... }) and the side
489
+ effect does not occur.
490
+ */
491
+
492
+ /* ---- Internal state ---- */
493
+
494
+ let _tree_version = 0;
495
+ const _plugin_versions = new Map(); /* key: `${slug}|${instance_id||''}` */
496
+ const _version_history = []; /* circular buffer, max 500 */
497
+ const _plugin_scope_cache = (typeof WeakMap !== 'undefined')
498
+ ? new WeakMap() /* Element -> { slug, instance_id } */
499
+ : null;
500
+ let _hydration_complete = false;
501
+ let _hydration_fallback_timer = null;
502
+ let _mutation_observer = null;
503
+
504
+ /* STRICT_VERSIONING + eager_hashing + HARD_DEDUP are exposed via
505
+ the NAC export (bottom of the module) so hosts can flip them
506
+ before / after install. Internal mirrors keep hot-path checks
507
+ property-access-free in the most common cases. */
508
+ function _strictVersioningOn() {
509
+ return (typeof window !== 'undefined' && window.NAC &&
510
+ window.NAC.STRICT_VERSIONING === true);
511
+ }
512
+ function _eagerHashingOn() {
513
+ return (typeof window !== 'undefined' && window.NAC &&
514
+ window.NAC.eager_hashing === true);
515
+ }
516
+
517
+ /* ---- Plugin scope resolver (RFC sec 5.1.1) ----
518
+
519
+ "Plugin scope is logical, not physical." An element belongs to
520
+ the plugin declared by its nearest [data-nac-plugin] ancestor.
521
+ Portals/teleports that carry the attribute on their portaled
522
+ root inherit the right scope regardless of DOM hierarchy.
523
+
524
+ Cached per element via WeakMap to avoid O(depth) walks on every
525
+ mutation in high-rate paths (drag-drop, autocomplete filtering).
526
+ Cache entries invalidate naturally when the element is GC'd; we
527
+ also clear them on attribute mutations of data-nac-plugin* in
528
+ the observer below. */
529
+ function _resolvePluginScope(el) {
530
+ if (!el || el.nodeType !== 1) return null;
531
+ if (_plugin_scope_cache && _plugin_scope_cache.has(el)) {
532
+ return _plugin_scope_cache.get(el);
533
+ }
534
+ let cur = el;
535
+ while (cur && cur.nodeType === 1) {
536
+ if (cur.hasAttribute && cur.hasAttribute('data-nac-plugin')) {
537
+ const scope = {
538
+ slug: cur.getAttribute('data-nac-plugin') || '',
539
+ instance_id: cur.getAttribute('data-nac-plugin-id') || null,
540
+ };
541
+ if (_plugin_scope_cache) _plugin_scope_cache.set(el, scope);
542
+ return scope;
543
+ }
544
+ cur = cur.parentElement;
545
+ }
546
+ if (_plugin_scope_cache) _plugin_scope_cache.set(el, null);
547
+ return null;
548
+ }
549
+
550
+ function _pluginKey(slug, instance_id) {
551
+ return slug + '|' + (instance_id || '');
552
+ }
553
+ function _pluginVersionFor(slug, instance_id) {
554
+ return 'v_' + (_plugin_versions.get(_pluginKey(slug, instance_id)) || 0);
555
+ }
556
+ function _treeVersionStr() { return 'v_' + _tree_version; }
557
+
558
+ /* ---- Bump functions (RFC sec 8.1) ---- */
559
+
560
+ function _bumpTreeVersion(trigger, affected_plugins) {
561
+ _tree_version += 1;
562
+ _version_history.push({
563
+ at: Date.now(),
564
+ tree_version: _treeVersionStr(),
565
+ trigger: trigger,
566
+ affected_plugins: affected_plugins || [],
567
+ });
568
+ while (_version_history.length > 500) _version_history.shift();
569
+ if (typeof document !== 'undefined') {
570
+ document.dispatchEvent(new CustomEvent('nac:tree:invalidated', {
571
+ detail: {
572
+ from_version: 'v_' + (_tree_version - 1),
573
+ to_version: _treeVersionStr(),
574
+ trigger: trigger,
575
+ affected_plugins: affected_plugins || [],
576
+ },
577
+ }));
578
+ }
579
+ }
580
+
581
+ function _bumpPluginVersion(slug, instance_id, trigger) {
582
+ if (!slug) return;
583
+ const key = _pluginKey(slug, instance_id);
584
+ const prev = _plugin_versions.get(key) || 0;
585
+ const next = prev + 1;
586
+ _plugin_versions.set(key, next);
587
+ /* Tree version bumps along with every plugin version bump. */
588
+ _bumpTreeVersion(trigger, [{ slug: slug, instance_id: instance_id || null }]);
589
+ if (typeof document !== 'undefined') {
590
+ document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
591
+ detail: {
592
+ plugin_slug: slug,
593
+ plugin_instance_id: instance_id || null,
594
+ from_version: 'v_' + prev,
595
+ to_version: 'v_' + next,
596
+ trigger: trigger,
597
+ },
598
+ }));
599
+ }
600
+ }
601
+
602
+ /* Helper invoked from data-table primitives + syncPlugin to bump
603
+ versions without needing a mutation observer round-trip. */
604
+ function _markStructuralChange(slug, instance_id, trigger) {
605
+ _bumpPluginVersion(slug, instance_id, trigger || 'syncPlugin');
606
+ }
607
+
608
+ /* ---- Mutation observer (RFC sec 8.2) ----
609
+
610
+ Single observer rooted at document.body, filters mutations to
611
+ elements inside any [data-nac-plugin] subtree, coalesces all
612
+ mutations in a single microtask into one bump per affected
613
+ plugin. Structural changes (add/remove [data-nac-*] elements,
614
+ attribute changes to data-nac-id/role/action/plugin*, visibility
615
+ transitions) bump; pure state changes (value/textContent/focus)
616
+ do not. */
617
+ const _NAC_ATTRS_STRUCTURAL = new Set([
618
+ 'data-nac-id', 'data-nac-role', 'data-nac-action',
619
+ 'data-nac-plugin', 'data-nac-plugin-id', 'data-nac-verb',
620
+ 'aria-hidden', 'hidden', 'style',
621
+ ]);
622
+
623
+ function _scopeOfMutation(mutation) {
624
+ /* attributes: target is the element itself.
625
+ childList: walk added/removed nodes; each contributes a scope. */
626
+ const scopes = [];
627
+ if (mutation.type === 'attributes' && mutation.target) {
628
+ const s = _resolvePluginScope(mutation.target);
629
+ if (s) scopes.push(s);
630
+ } else if (mutation.type === 'childList') {
631
+ const collect = function (nl) {
632
+ for (let i = 0; i < nl.length; i++) {
633
+ const n = nl[i];
634
+ if (n.nodeType !== 1) continue;
635
+ /* Only nodes that themselves carry a data-nac-* attribute,
636
+ or that contain one, are agent-relevant. */
637
+ let relevant = false;
638
+ if (n.hasAttribute && (n.hasAttribute('data-nac-id') ||
639
+ n.hasAttribute('data-nac-role') ||
640
+ n.hasAttribute('data-nac-plugin'))) {
641
+ relevant = true;
642
+ }
643
+ if (!relevant && n.querySelector) {
644
+ relevant = !!n.querySelector('[data-nac-id],[data-nac-role],[data-nac-plugin]');
645
+ }
646
+ if (relevant) {
647
+ /* Resolve scope from the mutation parent (where the node
648
+ was inserted/removed), since the removed node may no
649
+ longer be in the tree. */
650
+ const s = _resolvePluginScope(mutation.target);
651
+ if (s) scopes.push(s);
652
+ }
653
+ }
654
+ };
655
+ collect(mutation.addedNodes);
656
+ collect(mutation.removedNodes);
657
+ }
658
+ return scopes;
659
+ }
660
+
661
+ function _isStructuralAttrChange(mutation) {
662
+ if (mutation.type !== 'attributes') return false;
663
+ return _NAC_ATTRS_STRUCTURAL.has(mutation.attributeName || '');
664
+ }
665
+
666
+ function _handleMutationRecords(records) {
667
+ /* Coalesce: collect every affected (slug, instance_id) and emit
668
+ exactly one bump per pair per microtask flush. */
669
+ const affected = new Map();
670
+ for (let i = 0; i < records.length; i++) {
671
+ const r = records[i];
672
+ let structural = false;
673
+ if (r.type === 'childList') structural = true;
674
+ else if (r.type === 'attributes' && _isStructuralAttrChange(r)) structural = true;
675
+ else if (r.type === 'attributes' &&
676
+ (r.attributeName === 'data-nac-plugin' ||
677
+ r.attributeName === 'data-nac-plugin-id') &&
678
+ _plugin_scope_cache && r.target) {
679
+ /* Plugin scope changed -- invalidate cache for this element. */
680
+ try { _plugin_scope_cache.delete(r.target); } catch (_) {}
681
+ }
682
+ if (!structural) continue;
683
+ const scopes = _scopeOfMutation(r);
684
+ for (let j = 0; j < scopes.length; j++) {
685
+ const k = _pluginKey(scopes[j].slug, scopes[j].instance_id);
686
+ if (!affected.has(k)) {
687
+ affected.set(k, { slug: scopes[j].slug, instance_id: scopes[j].instance_id });
688
+ }
689
+ }
690
+ }
691
+ if (affected.size === 0) return;
692
+ affected.forEach(function (scope) {
693
+ _bumpPluginVersion(scope.slug, scope.instance_id, 'mutation');
694
+ });
695
+ }
696
+
697
+ function _installMutationObserver() {
698
+ if (_mutation_observer || typeof MutationObserver === 'undefined' ||
699
+ typeof document === 'undefined' || !document.body) return;
700
+ _mutation_observer = new MutationObserver(_handleMutationRecords);
701
+ _mutation_observer.observe(document.body, {
702
+ childList: true,
703
+ subtree: true,
704
+ attributes: true,
705
+ attributeFilter: ['data-nac-id', 'data-nac-role', 'data-nac-action',
706
+ 'data-nac-plugin', 'data-nac-plugin-id', 'data-nac-verb',
707
+ 'data-nac-state', 'aria-hidden', 'hidden', 'disabled',
708
+ 'style'],
709
+ });
710
+ }
711
+
712
+ /* ---- element_state_hash (RFC sec 5.2) ----
713
+
714
+ The hash covers exactly 5 keys (visible, disabled, value, text,
715
+ custom) per the canonical mini-spec. Truncation at 256 chars on
716
+ value+text is normative. Serializer emits keys alphabetically,
717
+ non-ASCII escaped as \uXXXX lowercase, no whitespace. SHA-256
718
+ over the canonical bytes, truncated to the leading 128 bits
719
+ (16 bytes), encoded as 32 lowercase hex chars. */
720
+
721
+ function _hashIsEffectivelyVisible(el) {
722
+ /* Cheap visibility check: offsetParent + style.display +
723
+ style.visibility + aria-hidden. */
724
+ if (!el || el.nodeType !== 1) return false;
725
+ if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false;
726
+ if (typeof el.offsetParent === 'object' && el.offsetParent === null) {
727
+ /* position:fixed escapes offsetParent=null. Use rect fallback. */
728
+ if (typeof el.getBoundingClientRect === 'function') {
729
+ const r = el.getBoundingClientRect();
730
+ if (r.width === 0 && r.height === 0) return false;
731
+ } else {
732
+ return false;
733
+ }
734
+ }
735
+ if (typeof window !== 'undefined' && window.getComputedStyle) {
736
+ const cs = window.getComputedStyle(el);
737
+ if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return false;
738
+ }
739
+ return true;
740
+ }
741
+
742
+ function _hashReadValue(el) {
743
+ if (!el || el.nodeType !== 1) return null;
744
+ const tag = (el.tagName || '').toLowerCase();
745
+ if (tag === 'input' || tag === 'textarea') {
746
+ const t = (el.type || '').toLowerCase();
747
+ if (t === 'checkbox' || t === 'radio') return el.checked ? 'true' : 'false';
748
+ return el.value == null ? null : String(el.value).slice(0, 256);
749
+ }
750
+ if (tag === 'select') {
751
+ return el.value == null ? null : String(el.value).slice(0, 256);
752
+ }
753
+ /* role=option fallback: aria-selected. */
754
+ if (el.getAttribute && el.getAttribute('aria-selected') === 'true') return 'selected';
755
+ return null;
756
+ }
757
+
758
+ function _jsonStringCanonical(s) {
759
+ /* RFC 8259 string encoding + the V24-04 normative rule: non-ASCII
760
+ escaped as \uXXXX lowercase. Eliminates engine divergence. */
761
+ let out = '"';
762
+ for (let i = 0; i < s.length; i++) {
763
+ const c = s.charCodeAt(i);
764
+ if (c === 0x22) out += '\\"';
765
+ else if (c === 0x5C) out += '\\\\';
766
+ else if (c === 0x08) out += '\\b';
767
+ else if (c === 0x0C) out += '\\f';
768
+ else if (c === 0x0A) out += '\\n';
769
+ else if (c === 0x0D) out += '\\r';
770
+ else if (c === 0x09) out += '\\t';
771
+ else if (c < 0x20 || c > 0x7E) {
772
+ let hex = c.toString(16);
773
+ while (hex.length < 4) hex = '0' + hex;
774
+ out += '\\u' + hex.toLowerCase();
775
+ } else {
776
+ out += s.charAt(i);
777
+ }
778
+ }
779
+ out += '"';
780
+ return out;
781
+ }
782
+
783
+ function _canonicalSerializeState(obj) {
784
+ /* Keys in alphabetical order: custom, disabled, text, value, visible. */
785
+ return '{'
786
+ + '"custom":' + (obj.custom === null ? 'null' : _jsonStringCanonical(obj.custom)) + ','
787
+ + '"disabled":' + (obj.disabled ? 'true' : 'false') + ','
788
+ + '"text":' + (obj.text === null ? 'null' : _jsonStringCanonical(obj.text)) + ','
789
+ + '"value":' + (obj.value === null ? 'null' : _jsonStringCanonical(obj.value)) + ','
790
+ + '"visible":' + (obj.visible ? 'true' : 'false')
791
+ + '}';
792
+ }
793
+
794
+ function _bytesToHexLower(bytes) {
795
+ let out = '';
796
+ for (let i = 0; i < bytes.length; i++) {
797
+ const v = bytes[i];
798
+ out += (v < 16 ? '0' : '') + v.toString(16);
799
+ }
800
+ return out;
801
+ }
802
+
803
+ /* Synchronous SHA-256 fallback. Used in non-secure contexts where
804
+ crypto.subtle is unavailable (HTTP iframes, legacy embeds).
805
+ Reference implementation (~80 LOC). Produces byte-identical
806
+ digests to crypto.subtle.digest('SHA-256', ...). */
807
+ function _sha256Sync(bytes) {
808
+ const K = [
809
+ 0x428a2f98|0,0x71374491|0,0xb5c0fbcf|0,0xe9b5dba5|0,0x3956c25b|0,0x59f111f1|0,0x923f82a4|0,0xab1c5ed5|0,
810
+ 0xd807aa98|0,0x12835b01|0,0x243185be|0,0x550c7dc3|0,0x72be5d74|0,0x80deb1fe|0,0x9bdc06a7|0,0xc19bf174|0,
811
+ 0xe49b69c1|0,0xefbe4786|0,0x0fc19dc6|0,0x240ca1cc|0,0x2de92c6f|0,0x4a7484aa|0,0x5cb0a9dc|0,0x76f988da|0,
812
+ 0x983e5152|0,0xa831c66d|0,0xb00327c8|0,0xbf597fc7|0,0xc6e00bf3|0,0xd5a79147|0,0x06ca6351|0,0x14292967|0,
813
+ 0x27b70a85|0,0x2e1b2138|0,0x4d2c6dfc|0,0x53380d13|0,0x650a7354|0,0x766a0abb|0,0x81c2c92e|0,0x92722c85|0,
814
+ 0xa2bfe8a1|0,0xa81a664b|0,0xc24b8b70|0,0xc76c51a3|0,0xd192e819|0,0xd6990624|0,0xf40e3585|0,0x106aa070|0,
815
+ 0x19a4c116|0,0x1e376c08|0,0x2748774c|0,0x34b0bcb5|0,0x391c0cb3|0,0x4ed8aa4a|0,0x5b9cca4f|0,0x682e6ff3|0,
816
+ 0x748f82ee|0,0x78a5636f|0,0x84c87814|0,0x8cc70208|0,0x90befffa|0,0xa4506ceb|0,0xbef9a3f7|0,0xc67178f2|0,
817
+ ];
818
+ let H = [0x6a09e667|0,0xbb67ae85|0,0x3c6ef372|0,0xa54ff53a|0,0x510e527f|0,0x9b05688c|0,0x1f83d9ab|0,0x5be0cd19|0];
819
+ /* Padding */
820
+ const ml = bytes.length;
821
+ const bits = ml * 8;
822
+ const padlen = (((ml + 9 + 63) >> 6) << 6) - ml;
823
+ const buf = new Uint8Array(ml + padlen);
824
+ buf.set(bytes, 0);
825
+ buf[ml] = 0x80;
826
+ /* big-endian 64-bit length, low 32 bits in the last 4 bytes */
827
+ buf[buf.length - 4] = (bits >>> 24) & 0xff;
828
+ buf[buf.length - 3] = (bits >>> 16) & 0xff;
829
+ buf[buf.length - 2] = (bits >>> 8) & 0xff;
830
+ buf[buf.length - 1] = bits & 0xff;
831
+ const W = new Int32Array(64);
832
+ function ROTR(x, n) { return (x >>> n) | (x << (32 - n)); }
833
+ for (let chunk = 0; chunk < buf.length; chunk += 64) {
834
+ for (let i = 0; i < 16; i++) {
835
+ W[i] = (buf[chunk + i*4 ] << 24) |
836
+ (buf[chunk + i*4 + 1] << 16) |
837
+ (buf[chunk + i*4 + 2] << 8) |
838
+ (buf[chunk + i*4 + 3]);
839
+ }
840
+ for (let i = 16; i < 64; i++) {
841
+ const s0 = ROTR(W[i-15], 7) ^ ROTR(W[i-15], 18) ^ (W[i-15] >>> 3);
842
+ const s1 = ROTR(W[i-2], 17) ^ ROTR(W[i-2], 19) ^ (W[i-2] >>> 10);
843
+ W[i] = (W[i-16] + s0 + W[i-7] + s1) | 0;
844
+ }
845
+ 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];
846
+ for (let i = 0; i < 64; i++) {
847
+ const S1 = ROTR(e,6) ^ ROTR(e,11) ^ ROTR(e,25);
848
+ const ch = (e & f) ^ ((~e) & g);
849
+ const t1 = (h + S1 + ch + K[i] + W[i]) | 0;
850
+ const S0 = ROTR(a,2) ^ ROTR(a,13) ^ ROTR(a,22);
851
+ const mj = (a & b) ^ (a & c) ^ (b & c);
852
+ const t2 = (S0 + mj) | 0;
853
+ h = g; g = f; f = e; e = (d + t1) | 0;
854
+ d = c; c = b; b = a; a = (t1 + t2) | 0;
855
+ }
856
+ H[0]=(H[0]+a)|0; H[1]=(H[1]+b)|0; H[2]=(H[2]+c)|0; H[3]=(H[3]+d)|0;
857
+ H[4]=(H[4]+e)|0; H[5]=(H[5]+f)|0; H[6]=(H[6]+g)|0; H[7]=(H[7]+h)|0;
858
+ }
859
+ const out = new Uint8Array(32);
860
+ for (let i = 0; i < 8; i++) {
861
+ out[i*4 ] = (H[i] >>> 24) & 0xff;
862
+ out[i*4 + 1] = (H[i] >>> 16) & 0xff;
863
+ out[i*4 + 2] = (H[i] >>> 8) & 0xff;
864
+ out[i*4 + 3] = H[i] & 0xff;
865
+ }
866
+ return out;
867
+ }
868
+
869
+ async function _sha256(bytes) {
870
+ if (typeof crypto !== 'undefined' && crypto.subtle && crypto.subtle.digest) {
871
+ const buf = await crypto.subtle.digest('SHA-256', bytes);
872
+ return new Uint8Array(buf);
873
+ }
874
+ return _sha256Sync(bytes);
875
+ }
876
+
877
+ function _buildHashState(el) {
878
+ if (!el || el.nodeType !== 1) return null;
879
+ const role = (el.getAttribute && (el.getAttribute('data-nac-role') || '')) || '';
880
+ let text = null;
881
+ if (role === 'action' || role === 'tab') {
882
+ const t = (el.textContent || '').trim();
883
+ text = t.slice(0, 256);
884
+ }
885
+ let value = null;
886
+ if (role === 'field' || role === 'option') {
887
+ value = _hashReadValue(el);
888
+ }
889
+ return {
890
+ custom: (el.getAttribute && el.getAttribute('data-nac-state')) || null,
891
+ disabled: el.disabled === true ||
892
+ (el.getAttribute && el.getAttribute('aria-disabled') === 'true'),
893
+ text: text,
894
+ value: value,
895
+ visible: _hashIsEffectivelyVisible(el),
896
+ };
897
+ }
898
+
899
+ function _encodeCanonical(canonical) {
900
+ if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(canonical);
901
+ const b = new Uint8Array(canonical.length);
902
+ for (let i = 0; i < canonical.length; i++) b[i] = canonical.charCodeAt(i) & 0xff;
903
+ return b;
904
+ }
905
+
906
+ /* Async variant -- uses WebCrypto when available (faster on long
907
+ strings); falls back to the sync implementation in non-secure
908
+ contexts. Awaited by _resolveVersionExpectations on the hash
909
+ check path. */
910
+ async function _stateHashOf(el) {
911
+ const state = _buildHashState(el);
912
+ if (!state) return null;
913
+ const enc = _encodeCanonical(_canonicalSerializeState(state));
914
+ const digest = await _sha256(enc);
915
+ return _bytesToHexLower(digest.slice(0, 16));
916
+ }
917
+
918
+ /* Sync variant -- always uses _sha256Sync. Used by describe() so
919
+ the public read API stays synchronous. ~0.5-1ms per element on
920
+ modern V8; acceptable up to a few hundred elements per describe.
921
+ Hosts with thousands of elements should pre-cache via the
922
+ eager_hashing flag (future optimization). */
923
+ function _stateHashOfSync(el) {
924
+ const state = _buildHashState(el);
925
+ if (!state) return null;
926
+ const enc = _encodeCanonical(_canonicalSerializeState(state));
927
+ const digest = _sha256Sync(enc);
928
+ return _bytesToHexLower(digest.slice(0, 16));
929
+ }
930
+
931
+ /* ---- markHydrationComplete + 100ms fallback (RFC sec 5.10) ---- */
932
+
933
+ function _completeHydration(triggered_by) {
934
+ if (_hydration_complete) return;
935
+ _hydration_complete = true;
936
+ if (_hydration_fallback_timer) {
937
+ clearTimeout(_hydration_fallback_timer);
938
+ _hydration_fallback_timer = null;
939
+ }
940
+ /* Enumerate every registered plugin instance and emit per-plugin
941
+ events with from_version=null, plus a global tree event. */
942
+ const affected = [];
943
+ _plugin_versions.forEach(function (_n, key) {
944
+ const i = key.indexOf('|');
945
+ const slug = key.slice(0, i);
946
+ const inst = key.slice(i + 1) || null;
947
+ affected.push({ slug: slug, instance_id: inst });
948
+ });
949
+ /* Tree bump tagged as hydration_complete. */
950
+ _bumpTreeVersion('hydration_complete', affected.slice());
951
+ if (typeof document !== 'undefined') {
952
+ for (let i = 0; i < affected.length; i++) {
953
+ const a = affected[i];
954
+ const key = _pluginKey(a.slug, a.instance_id);
955
+ const curN = _plugin_versions.get(key) || 0;
956
+ document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
957
+ detail: {
958
+ plugin_slug: a.slug,
959
+ plugin_instance_id: a.instance_id,
960
+ from_version: null,
961
+ to_version: 'v_' + curN,
962
+ trigger: 'hydration_complete',
963
+ },
964
+ }));
965
+ }
966
+ }
967
+ }
968
+
969
+ function markHydrationComplete() {
970
+ if (_hydration_complete) return;
971
+ _completeHydration('explicit');
972
+ }
973
+
974
+ function _armHydrationFallback() {
975
+ if (typeof document === 'undefined') return;
976
+ const start = function () {
977
+ _hydration_fallback_timer = setTimeout(function () {
978
+ if (!_hydration_complete) _completeHydration('fallback_100ms');
979
+ }, 100);
980
+ };
981
+ if (document.readyState === 'loading') {
982
+ document.addEventListener('DOMContentLoaded', start, { once: true });
983
+ } else {
984
+ start();
985
+ }
986
+ }
987
+
988
+ /* ---- versionHistory devtools surface (RFC sec 5.9) ---- */
989
+
990
+ function versionHistory(limit) {
991
+ const n = (typeof limit === 'number' && limit > 0)
992
+ ? Math.min(limit, _version_history.length)
993
+ : Math.min(50, _version_history.length);
994
+ return _version_history.slice(-n).reverse();
995
+ }
996
+
997
+ /* ---- Resolver helper for expected_* checks (RFC sec 5.4 + 8.3) ----
998
+
999
+ Returns Promise<void>. Throws NacError on mismatch / tier reject /
1000
+ STRICT-without-expectation. Cheap-to-expensive order:
1001
+ 1. STRICT gate
1002
+ 2. NAC-3 (non-versioned) tier rejects ANY expected_*
1003
+ 3. expected_plugin_version (integer compare)
1004
+ 4. expected_tree_version (integer compare)
1005
+ 5. expected_element_state_hash (SHA-256, awaited last)
1006
+ */
1007
+ async function _resolveVersionExpectations(opts, el) {
1008
+ const o = opts || {};
1009
+ const hasAny = ('expected_plugin_version' in o) ||
1010
+ ('expected_tree_version' in o) ||
1011
+ ('expected_element_state_hash' in o);
1012
+ if (_strictVersioningOn() && !hasAny) {
1013
+ throw NacError('version_required',
1014
+ 'STRICT_VERSIONING is on; at least one expected_* required.',
1015
+ { method: (o && o.method) || undefined });
1016
+ }
1017
+ /* Tier reject -- conformance_tier is exposed on the NAC export,
1018
+ and a runtime that declares NAC-3 must NOT silently honor any
1019
+ expected_*. */
1020
+ const tier = (typeof window !== 'undefined' && window.NAC &&
1021
+ window.NAC.conformance_tier) || 'NAC-3-versioned';
1022
+ if (tier === 'NAC-3' && hasAny) {
1023
+ throw NacError('feature_not_supported',
1024
+ 'Runtime tier is NAC-3 (non-versioned); expected_* parameters are not honored.',
1025
+ { tier: 'NAC-3', requested_feature: 'versioning' });
1026
+ }
1027
+ /* Plugin version */
1028
+ if ('expected_plugin_version' in o) {
1029
+ const scope = _resolvePluginScope(el);
1030
+ if (scope) {
1031
+ const cur = _pluginVersionFor(scope.slug, scope.instance_id);
1032
+ if (o.expected_plugin_version !== cur) {
1033
+ /* RFC V24-04 sec 5.5: extras nested under .detail.
1034
+ NacError() flattens by default; mirror under detail
1035
+ for the new versioning error class so agents reading
1036
+ the RFC can use err.detail.reason directly. */
1037
+ const detail = {
1038
+ reason: 'plugin_changed',
1039
+ plugin_slug: scope.slug,
1040
+ plugin_instance_id: scope.instance_id,
1041
+ expected_plugin_version: o.expected_plugin_version,
1042
+ current_plugin_version: cur,
1043
+ };
1044
+ throw NacError('snapshot_stale',
1045
+ 'expected_plugin_version=' + o.expected_plugin_version +
1046
+ ' current_plugin_version=' + cur,
1047
+ Object.assign({ detail: detail }, detail));
1048
+ }
1049
+ }
1050
+ }
1051
+ /* Tree version */
1052
+ if ('expected_tree_version' in o) {
1053
+ const cur = _treeVersionStr();
1054
+ if (o.expected_tree_version !== cur) {
1055
+ const detail = {
1056
+ reason: 'tree_changed',
1057
+ expected_tree_version: o.expected_tree_version,
1058
+ current_tree_version: cur,
1059
+ };
1060
+ throw NacError('snapshot_stale',
1061
+ 'expected_tree_version=' + o.expected_tree_version +
1062
+ ' current_tree_version=' + cur,
1063
+ Object.assign({ detail: detail }, detail));
1064
+ }
1065
+ }
1066
+ /* Element state hash (awaited last) */
1067
+ if ('expected_element_state_hash' in o) {
1068
+ const cur = await _stateHashOf(el);
1069
+ if (o.expected_element_state_hash !== cur) {
1070
+ const detail = {
1071
+ reason: 'element_changed',
1072
+ expected_element_state_hash: o.expected_element_state_hash,
1073
+ current_element_state_hash: cur,
1074
+ };
1075
+ throw NacError('snapshot_stale',
1076
+ 'expected_element_state_hash=' + o.expected_element_state_hash +
1077
+ ' current_element_state_hash=' + cur,
1078
+ Object.assign({ detail: detail }, detail));
1079
+ }
1080
+ }
1081
+ }
1082
+
1083
+ /* Read back the post-dispatch versions. Used by every mutating API
1084
+ after the side effect lands. Pair with _flushObserverQueue() to
1085
+ guarantee MutationObserver records have been integrated. */
1086
+ function _atVersionsFor(el) {
1087
+ const scope = _resolvePluginScope(el);
1088
+ return {
1089
+ at_plugin_version: scope ? _pluginVersionFor(scope.slug, scope.instance_id) : null,
1090
+ at_tree_version: _treeVersionStr(),
1091
+ };
1092
+ }
1093
+
1094
+ /* Flush pending MutationObserver records into version bumps before
1095
+ resolving the promise (RFC sec 5.8). queueMicrotask is enough --
1096
+ the observer fires once per microtask flush. */
1097
+ function _flushObserverQueue() {
1098
+ return new Promise(function (resolve) {
1099
+ if (typeof queueMicrotask === 'function') {
1100
+ queueMicrotask(resolve);
1101
+ } else {
1102
+ Promise.resolve().then(resolve);
1103
+ }
1104
+ });
1105
+ }
1106
+
1107
+ /* ==================================================================
1108
+ End of v2.4 / RFC V24-04 foundation block.
1109
+ ================================================================== */
1110
+
472
1111
  /* H1.v7 (2026-05-21): structured disambiguation contract.
473
1112
  When the runtime cannot resolve an id/verb/qualifier/label
474
1113
  unambiguously, it MUST emit `nac:disambiguation_requested` with
@@ -1775,14 +2414,10 @@
1775
2414
  and -- only on REPLACE, not first-add -- emits
1776
2415
  nac:plugin:invalidated so subscribers can refresh derived state. */
1777
2416
 
1778
- /* Monotonic + sortable plugin_version stamp. Format `v_<base36 ts>_<seq>`
1779
- so versions ordered lexicographically reflect register order. */
1780
- let _v25_versionSeq = 0;
1781
- function _v25_nextPluginVersion() {
1782
- _v25_versionSeq += 1;
1783
- return 'v_' + Date.now().toString(36) + '_' + _v25_versionSeq.toString(36);
1784
- }
1785
-
2417
+ /* syncPlugin uses the V24-04 versioning machinery: every replace
2418
+ calls _bumpPluginVersion(slug, null, 'syncPlugin') which bumps
2419
+ _plugin_versions + _tree_version + dispatches nac:plugin:invalidated
2420
+ in one atomic step. Single source of truth for OCC. */
1786
2421
  function syncPlugin(arg1, arg2) {
1787
2422
  let m;
1788
2423
  if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
@@ -1801,9 +2436,6 @@
1801
2436
  'syncPlugin: manifest.plugin_slug required (non-empty string)');
1802
2437
  }
1803
2438
  const wasPresent = !!_manifests[slug];
1804
- const prevVersion = wasPresent && _manifests[slug]._v25_plugin_version
1805
- ? _manifests[slug]._v25_plugin_version
1806
- : null;
1807
2439
  /* Replace path: drop the prior entry so register() does not
1808
2440
  append-by-side-effect when callers used the array-of-elements
1809
2441
  merge pattern. */
@@ -1815,31 +2447,18 @@
1815
2447
  exactly one place. If register throws (strict validation), the
1816
2448
  prior entry is GONE -- caller's responsibility to handle. */
1817
2449
  register(m);
1818
- const newVersion = _v25_nextPluginVersion();
1819
- if (_manifests[slug]) {
1820
- _manifests[slug]._v25_plugin_version = newVersion;
1821
- }
1822
- /* Emit invalidated ONLY on replace. First-add is a normal
1823
- register: subscribers do not need to refresh anything that
1824
- did not exist a moment ago. */
1825
- if (wasPresent && typeof document !== 'undefined') {
1826
- try {
1827
- document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
1828
- detail: {
1829
- plugin_slug: slug,
1830
- plugin_instance_id: null,
1831
- from_version: prevVersion || 'v_initial',
1832
- to_version: newVersion,
1833
- trigger: 'syncPlugin',
1834
- },
1835
- bubbles: true,
1836
- }));
1837
- } catch (_) { /* document.dispatchEvent absent in SSR */ }
2450
+ /* Bump V24-04 OCC version on REPLACE only. First-add is a normal
2451
+ register: the boot tree_version already reflects the new plugin
2452
+ and subscribers do not need to refresh anything that did not
2453
+ exist a moment ago. _bumpPluginVersion fires nac:plugin:invalidated
2454
+ as part of its work, so we don't dispatch again here. */
2455
+ if (wasPresent) {
2456
+ _bumpPluginVersion(slug, null, 'syncPlugin');
1838
2457
  }
1839
2458
  return {
1840
2459
  replaced: wasPresent,
1841
2460
  slug: slug,
1842
- version: newVersion,
2461
+ version: _pluginVersionFor(slug, null),
1843
2462
  };
1844
2463
  }
1845
2464
 
@@ -1882,6 +2501,7 @@
1882
2501
 
1883
2502
  const _V25_SCOPE_RANK = { low: 1, medium: 2, high: 3 };
1884
2503
  const _v25_authority_grants = new Map();
2504
+ let _v25_authReqSeq = 0;
1885
2505
  let _v25_confirm_handler = null;
1886
2506
 
1887
2507
  function _v25_emitAuth(kind, detail) {
@@ -1946,7 +2566,7 @@
1946
2566
  'request_authority: NAC.set_confirm_handler must be called first'));
1947
2567
  return;
1948
2568
  }
1949
- const reqId = _v25_nextPluginVersion(); /* reuse the monotonic stamp */
2569
+ const reqId = 'auth_' + Date.now().toString(36) + '_' + (++_v25_authReqSeq).toString(36);
1950
2570
  const req = {
1951
2571
  kind: 'request_authority',
1952
2572
  request_id: reqId,
@@ -2265,12 +2885,20 @@
2265
2885
  const plugins = Array.prototype.slice.call(
2266
2886
  document.querySelectorAll('[data-nac-plugin]')
2267
2887
  ).map(function (root) {
2888
+ const slug = root.getAttribute('data-nac-plugin');
2889
+ const instance_id = root.getAttribute('data-nac-plugin-id') || null;
2268
2890
  return {
2269
- plugin: root.getAttribute('data-nac-plugin'),
2270
- plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
2271
- elements: Array.prototype.slice.call(
2891
+ plugin: slug,
2892
+ plugin_instance_id: instance_id,
2893
+ plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
2894
+ /* v2.5 / RFC V24-04 (sec 5.1): per-plugin monotonic version
2895
+ token. Primary tool for agents -- ignore noise outside the
2896
+ targeted plugin by passing expected_plugin_version on
2897
+ dispatch. */
2898
+ plugin_version: _pluginVersionFor(slug, instance_id),
2899
+ elements: Array.prototype.slice.call(
2272
2900
  root.querySelectorAll('[data-nac-id]')
2273
- ).map(_serializeElement),
2901
+ ).map(_serializeElementWithHash),
2274
2902
  };
2275
2903
  });
2276
2904
  return {
@@ -2279,9 +2907,24 @@
2279
2907
  url: location.href,
2280
2908
  active: _activePlugin(),
2281
2909
  plugins: plugins,
2910
+ /* v2.5 / RFC V24-04 (sec 5.3): global monotonic version token.
2911
+ Escape hatch for cross-plugin orchestration; prefer
2912
+ plugin_version for single-plugin plans. */
2913
+ tree_version: _treeVersionStr(),
2282
2914
  };
2283
2915
  }
2284
2916
 
2917
+ /* v2.5 / RFC V24-04 (sec 5.2): serialize + attach element_state_hash.
2918
+ Sync compute; ~0.5-1ms per element. NULL when the element does
2919
+ not carry a role that contributes to the hash. */
2920
+ function _serializeElementWithHash(el) {
2921
+ const base = _serializeElement(el);
2922
+ if (!base) return base;
2923
+ try { base.element_state_hash = _stateHashOfSync(el); }
2924
+ catch (_) { base.element_state_hash = null; }
2925
+ return base;
2926
+ }
2927
+
2285
2928
  function list(role) {
2286
2929
  const all = _allElements().map(_serializeElement);
2287
2930
  if (!role) return all;
@@ -2586,6 +3229,19 @@
2586
3229
  });
2587
3230
  throw NacError(ariaPF.reason, ariaPF.message);
2588
3231
  }
3232
+ /* v2.5 / RFC V24-04 OCC gate. Only await when opts actually
3233
+ carries expected_* OR STRICT_VERSIONING demands it; otherwise
3234
+ skip to avoid introducing a microtask boundary that would
3235
+ reorder side-effect-then-immediate-check call patterns. */
3236
+ {
3237
+ const _o = opts || {};
3238
+ const _hasExp = ('expected_plugin_version' in _o)
3239
+ || ('expected_tree_version' in _o)
3240
+ || ('expected_element_state_hash' in _o);
3241
+ if (_hasExp || _strictVersioningOn()) {
3242
+ await _resolveVersionExpectations(opts, el);
3243
+ }
3244
+ }
2589
3245
  const role = el.getAttribute('data-nac-role') || 'action';
2590
3246
  const family = _CLICK_EVENT_FAMILY[role] || _CLICK_EVENT_FAMILY['action'];
2591
3247
  /* The first event in each family is the "success" signal; if a
@@ -2819,6 +3475,16 @@
2819
3475
  });
2820
3476
  throw NacError(fillPF.reason, fillPF.message);
2821
3477
  }
3478
+ /* v2.5 / RFC V24-04 OCC gate. Same conditional pattern as click. */
3479
+ {
3480
+ const _o = opts || {};
3481
+ const _hasExp = ('expected_plugin_version' in _o)
3482
+ || ('expected_tree_version' in _o)
3483
+ || ('expected_element_state_hash' in _o);
3484
+ if (_hasExp || _strictVersioningOn()) {
3485
+ await _resolveVersionExpectations(opts, el);
3486
+ }
3487
+ }
2822
3488
  _focusElement(el);
2823
3489
  const ft = el.getAttribute('data-nac-field-type');
2824
3490
 
@@ -2879,6 +3545,16 @@
2879
3545
  async function select(nac_id, option, opts) {
2880
3546
  const el = _findElement(nac_id, opts);
2881
3547
  if (!el) throw NacError('not_found', 'No select with nac_id=' + nac_id);
3548
+ /* v2.5 / RFC V24-04 OCC gate. */
3549
+ {
3550
+ const _o = opts || {};
3551
+ const _hasExp = ('expected_plugin_version' in _o)
3552
+ || ('expected_tree_version' in _o)
3553
+ || ('expected_element_state_hash' in _o);
3554
+ if (_hasExp || _strictVersioningOn()) {
3555
+ await _resolveVersionExpectations(opts, el);
3556
+ }
3557
+ }
2882
3558
  _focusElement(el);
2883
3559
  if (el.tagName === 'SELECT') {
2884
3560
  if (el.multiple && Array.isArray(option)) {
@@ -3193,6 +3869,16 @@
3193
3869
  an invoke based on UI state should do it in their
3194
3870
  nac:action:requested listener and emit nac:action:failed
3195
3871
  with a meaningful error code. */
3872
+ /* v2.5 / RFC V24-04 OCC gate. */
3873
+ {
3874
+ const _o = opts || {};
3875
+ const _hasExp = ('expected_plugin_version' in _o)
3876
+ || ('expected_tree_version' in _o)
3877
+ || ('expected_element_state_hash' in _o);
3878
+ if (_hasExp || _strictVersioningOn()) {
3879
+ await _resolveVersionExpectations(opts, el);
3880
+ }
3881
+ }
3196
3882
  const verb = (payload && payload.verb)
3197
3883
  || el.getAttribute('data-nac-action')
3198
3884
  || '';
@@ -6872,7 +7558,7 @@
6872
7558
 
6873
7559
  global.NAC = {
6874
7560
  __nac_v1_installed: true,
6875
- version: '2.5.0-alpha.1',
7561
+ version: '2.5.0-alpha.3',
6876
7562
  spec_version: '2.5',
6877
7563
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
6878
7564
  NAC.register throws on findings (manifest_role_unknown,
@@ -6907,6 +7593,19 @@
6907
7593
  request_authority: request_authority,
6908
7594
  has_authority: has_authority,
6909
7595
  revoke_authority: revoke_authority,
7596
+ /* v2.5 V24-04 -- Snapshot versioning + optimistic concurrency.
7597
+ plugin_version + element_state_hash + tree_version appear in
7598
+ describe() output (RFC sec 5.2/5.3). expected_plugin_version
7599
+ / expected_tree_version / expected_element_state_hash on every
7600
+ mutating API reject with NacError('snapshot_stale', ...) when
7601
+ the snapshot is stale. Default STRICT_VERSIONING=false in
7602
+ 2.5.0-alpha.2 so adopters opt in; flips to true in alpha.3
7603
+ once the dispatch hooks finish their soak window. */
7604
+ STRICT_VERSIONING: false,
7605
+ eager_hashing: false,
7606
+ conformance_tier: 'NAC-3-versioned',
7607
+ markHydrationComplete: markHydrationComplete,
7608
+ versionHistory: versionHistory,
6910
7609
  /* v2.3 preview (V23-02): introspection helper that returns the
6911
7610
  list of plugin slugs currently registered (regardless of DOM
6912
7611
  mount state). Used by the interop layer's export_tree to