@nac3/runtime 2.4.0 → 2.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -323,6 +323,152 @@
323
323
  return e;
324
324
  }
325
325
 
326
+ /* ================================================================
327
+ v2.5 / RFC V24-01: Plugin slug uniqueness gate (spec sec 7.4)
328
+ ================================================================
329
+
330
+ When a plugin slug appears on more than one DOM root
331
+ simultaneously, every root MUST carry a unique
332
+ data-nac-plugin-id attribute. The runtime enforces via three
333
+ mechanisms:
334
+
335
+ NAC.register -> synchronous throw on the registered slug
336
+ boot-time pass -> nac:fatal + visible red banner at first
337
+ cross-slug violation, then refuse further
338
+ dispatches
339
+ validate_global -> structured finding for CI (non-fatal)
340
+
341
+ Gated by NAC.HARD_DEDUP (default true; set false for migration). */
342
+
343
+ /* _scanPluginInstances() walks the live DOM and groups every
344
+ [data-nac-plugin] root by its slug. For each group of >1 root,
345
+ it requires every root to carry a non-empty data-nac-plugin-id
346
+ AND for those ids to be pairwise unique. Returns a structured
347
+ findings array; never throws. */
348
+ function _scanPluginInstances() {
349
+ if (typeof document === 'undefined') return [];
350
+ const findings = [];
351
+ const bySlug = {};
352
+ const all = document.querySelectorAll('[data-nac-plugin]');
353
+ for (let i = 0; i < all.length; i++) {
354
+ const el = all[i];
355
+ const slug = el.getAttribute('data-nac-plugin') || '';
356
+ if (!slug) continue;
357
+ (bySlug[slug] = bySlug[slug] || []).push(el);
358
+ }
359
+ for (const slug in bySlug) {
360
+ if (!Object.prototype.hasOwnProperty.call(bySlug, slug)) continue;
361
+ const roots = bySlug[slug];
362
+ if (roots.length < 2) continue;
363
+ const ids = [];
364
+ const missing = [];
365
+ for (let r = 0; r < roots.length; r++) {
366
+ const id = roots[r].getAttribute('data-nac-plugin-id') || '';
367
+ if (!id) missing.push(roots[r]); else ids.push(id);
368
+ }
369
+ const dupIds = [];
370
+ const seen = {};
371
+ for (let j = 0; j < ids.length; j++) {
372
+ if (seen[ids[j]]) dupIds.push(ids[j]);
373
+ else seen[ids[j]] = 1;
374
+ }
375
+ if (missing.length > 0 || dupIds.length > 0) {
376
+ findings.push({
377
+ code: 'duplicate_plugin_no_instance_id',
378
+ severity: 'error',
379
+ slug: slug,
380
+ instance_count: roots.length,
381
+ missing_instance_id_count: missing.length,
382
+ duplicate_instance_ids: dupIds,
383
+ message: roots.length + ' DOM roots carry data-nac-plugin="'
384
+ + slug + '" but '
385
+ + (missing.length
386
+ ? missing.length + ' lack data-nac-plugin-id'
387
+ : 'two share data-nac-plugin-id "' + dupIds[0] + '"')
388
+ + '. Per SPEC sec 7.4, every root sharing a slug MUST '
389
+ + 'carry a unique data-nac-plugin-id.',
390
+ });
391
+ }
392
+ }
393
+ return findings;
394
+ }
395
+
396
+ /* _checkPluginSlugUniqueOrThrow(slug) is the synchronous gate used
397
+ by NAC.register(). Throws the first finding for the registered
398
+ slug; other-slug findings are ignored here -- the DOM-ready pass
399
+ below catches them globally. */
400
+ function _checkPluginSlugUniqueOrThrow(slug) {
401
+ const all = _scanPluginInstances();
402
+ for (let i = 0; i < all.length; i++) {
403
+ if (all[i].slug !== slug) continue;
404
+ throw NacError('duplicate_plugin_no_instance_id', all[i].message, {
405
+ slug: slug,
406
+ instance_count: all[i].instance_count,
407
+ missing_instance_id_count: all[i].missing_instance_id_count,
408
+ duplicate_instance_ids: all[i].duplicate_instance_ids,
409
+ });
410
+ }
411
+ }
412
+
413
+ /* _installPluginDedupBootGate() runs once at DOMContentLoaded and
414
+ enforces the same contract across every slug. On first violation
415
+ it dispatches nac:fatal, paints a red banner, and re-throws
416
+ asynchronously so test harnesses + browsers catch the error
417
+ instead of silently swallowing. */
418
+ let _bootDedupFatal = null;
419
+ function _installPluginDedupBootGate() {
420
+ if (typeof document === 'undefined') return;
421
+ const run = function () {
422
+ if (typeof global !== 'undefined' && global.NAC &&
423
+ global.NAC.HARD_DEDUP === false) return;
424
+ if (typeof window !== 'undefined' && window.NAC &&
425
+ window.NAC.HARD_DEDUP === false) return;
426
+ const findings = _scanPluginInstances();
427
+ if (findings.length === 0) return;
428
+ const f = findings[0];
429
+ const err = NacError('duplicate_plugin_no_instance_id', f.message, {
430
+ slug: f.slug,
431
+ instance_count: f.instance_count,
432
+ missing_instance_id_count: f.missing_instance_id_count,
433
+ duplicate_instance_ids: f.duplicate_instance_ids,
434
+ all_findings: findings,
435
+ });
436
+ _bootDedupFatal = err;
437
+ try {
438
+ document.dispatchEvent(new CustomEvent('nac:fatal', {
439
+ detail: { code: 'duplicate_plugin_no_instance_id',
440
+ slug: f.slug, message: f.message,
441
+ findings: findings },
442
+ }));
443
+ } catch (_) {}
444
+ try { _paintFatalBanner(err); } catch (_) {}
445
+ setTimeout(function () { throw err; }, 0);
446
+ };
447
+ if (document.readyState === 'loading') {
448
+ document.addEventListener('DOMContentLoaded', run, { once: true });
449
+ } else {
450
+ run();
451
+ }
452
+ }
453
+
454
+ function _paintFatalBanner(err) {
455
+ if (typeof document === 'undefined' || !document.body) return;
456
+ if (document.getElementById('__nac_fatal_banner__')) return;
457
+ const div = document.createElement('div');
458
+ div.id = '__nac_fatal_banner__';
459
+ div.setAttribute('role', 'alert');
460
+ div.style = 'position:fixed;top:0;left:0;right:0;z-index:2147483647;'
461
+ + 'background:#DC2626;color:#fff;font:600 14px/1.4 system-ui,sans-serif;'
462
+ + 'padding:12px 16px;box-shadow:0 2px 8px rgba(0,0,0,.25);';
463
+ div.textContent = '[NAC3 FATAL] ' + err.code + ': ' + err.message;
464
+ if (document.body.firstChild) {
465
+ document.body.insertBefore(div, document.body.firstChild);
466
+ } else {
467
+ document.body.appendChild(div);
468
+ }
469
+ }
470
+ /* /end V24-01 */
471
+
326
472
  /* H1.v7 (2026-05-21): structured disambiguation contract.
327
473
  When the runtime cannot resolve an id/verb/qualifier/label
328
474
  unambiguously, it MUST emit `nac:disambiguation_requested` with
@@ -1432,6 +1578,20 @@
1432
1578
  if (!manifest.version) manifest.version = '1.0.0';
1433
1579
  if (!manifest.nac_version) manifest.nac_version = '1.0';
1434
1580
 
1581
+ /* v2.5 / RFC V24-01 -- synchronous slug uniqueness gate.
1582
+ Throws NacError('duplicate_plugin_no_instance_id', ...) when
1583
+ the DOM already contains multiple roots for this slug and any
1584
+ of them omit or duplicate data-nac-plugin-id. Gated by
1585
+ NAC.HARD_DEDUP (default true; settable false for migration). */
1586
+ const _hardDedup = (typeof global !== 'undefined' && global.NAC
1587
+ ? global.NAC.HARD_DEDUP !== false
1588
+ : (typeof window !== 'undefined' && window.NAC
1589
+ ? window.NAC.HARD_DEDUP !== false
1590
+ : true));
1591
+ if (_hardDedup) {
1592
+ _checkPluginSlugUniqueOrThrow(slug);
1593
+ }
1594
+
1435
1595
  /* v1.5.1 cross-plugin duplicate-id detection.
1436
1596
  Spec section P7 expects nac_ids to be plugin-namespaced
1437
1597
  ('plugin.element' convention). When two manifests register
@@ -1599,6 +1759,273 @@
1599
1759
  return _manifests[slug] || null;
1600
1760
  }
1601
1761
 
1762
+ /* ================================================================
1763
+ v2.5 V24-02 -- syncPlugin: idempotent registration
1764
+ ================================================================
1765
+
1766
+ SPA hosts that re-render a component call register() again on
1767
+ remount; the legacy register() appends a new manifest entry,
1768
+ accumulating stale state. syncPlugin REPLACES the manifest for a
1769
+ given slug instead of appending. Calling N times with the same
1770
+ manifest leaves the registry in the same state as calling once.
1771
+
1772
+ Validation is identical to register() (manifest_role_unknown,
1773
+ tab_id_manifest_role_drift, etc honour STRICT_VALIDATION).
1774
+ Versioning: each call mints a new plugin_version (V24-04 OCC)
1775
+ and -- only on REPLACE, not first-add -- emits
1776
+ nac:plugin:invalidated so subscribers can refresh derived state. */
1777
+
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
+
1786
+ function syncPlugin(arg1, arg2) {
1787
+ let m;
1788
+ if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
1789
+ /* (slug, manifest) form -- match register's calling convention. */
1790
+ m = Object.assign({}, arg2);
1791
+ if (!m.plugin_slug) m.plugin_slug = arg1;
1792
+ } else if (arg1 && typeof arg1 === 'object') {
1793
+ m = arg1;
1794
+ } else {
1795
+ throw NacError('invalid',
1796
+ 'syncPlugin: requires (manifest) or (slug, manifest)');
1797
+ }
1798
+ const slug = m.plugin_slug;
1799
+ if (!slug || typeof slug !== 'string') {
1800
+ throw NacError('invalid',
1801
+ 'syncPlugin: manifest.plugin_slug required (non-empty string)');
1802
+ }
1803
+ const wasPresent = !!_manifests[slug];
1804
+ const prevVersion = wasPresent && _manifests[slug]._v25_plugin_version
1805
+ ? _manifests[slug]._v25_plugin_version
1806
+ : null;
1807
+ /* Replace path: drop the prior entry so register() does not
1808
+ append-by-side-effect when callers used the array-of-elements
1809
+ merge pattern. */
1810
+ if (wasPresent) {
1811
+ delete _manifests[slug];
1812
+ if (typeof _instances !== 'undefined') delete _instances[slug];
1813
+ }
1814
+ /* Delegate to register() so validation + storage code-path stays
1815
+ exactly one place. If register throws (strict validation), the
1816
+ prior entry is GONE -- caller's responsibility to handle. */
1817
+ 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 */ }
1838
+ }
1839
+ return {
1840
+ replaced: wasPresent,
1841
+ slug: slug,
1842
+ version: newVersion,
1843
+ };
1844
+ }
1845
+
1846
+ /* ================================================================
1847
+ v2.5 V24-05 -- Agent authority + sudo elevation
1848
+ ================================================================
1849
+
1850
+ Three primitives for a host to interpose a confirmation UI
1851
+ between an agent dispatch and the action's side effect, with a
1852
+ SUDO-style elevation that bypasses confirmations for a granted
1853
+ scope until its TTL expires.
1854
+
1855
+ NAC.set_confirm_handler(fn)
1856
+ fn is async (req) => boolean. The host renders its UI
1857
+ (modal, voice, Discord button, etc) and resolves true on
1858
+ approve, false on reject. A handler that throws is treated
1859
+ as "reject" (never as a silent approval).
1860
+
1861
+ NAC.confirm_action(action_id, message, opts?)
1862
+ opts = { scope?: 'low'|'medium'|'high', metadata?: {...} }
1863
+ Returns Promise<boolean>. If currently elevated for an
1864
+ equal-or-stricter scope, resolves true synchronously
1865
+ WITHOUT invoking the handler.
1866
+
1867
+ NAC.request_authority(scope, ttl_ms, opts?)
1868
+ Asks the host for sudo elevation. On grant, subsequent
1869
+ confirm_action calls in that scope (or lower) resolve
1870
+ immediately for ttl_ms. After TTL the elevation
1871
+ auto-revokes; manual revoke is NAC.revoke_authority(scope).
1872
+
1873
+ NAC.has_authority(scope) -> boolean
1874
+ NAC.revoke_authority(scope) -> void (idempotent)
1875
+
1876
+ Scope rank: high > medium > low. Granted high authority
1877
+ satisfies medium + low; granted low does NOT satisfy higher.
1878
+
1879
+ Provenance on document:
1880
+ nac:authority:requested / :granted / :denied / :revoked / :expired
1881
+ nac:action:confirmed / :rejected */
1882
+
1883
+ const _V25_SCOPE_RANK = { low: 1, medium: 2, high: 3 };
1884
+ const _v25_authority_grants = new Map();
1885
+ let _v25_confirm_handler = null;
1886
+
1887
+ function _v25_emitAuth(kind, detail) {
1888
+ if (typeof document === 'undefined') return;
1889
+ try {
1890
+ document.dispatchEvent(new CustomEvent('nac:authority:' + kind,
1891
+ { detail: detail, bubbles: true }));
1892
+ } catch (_) { /* SSR or no document */ }
1893
+ }
1894
+ function _v25_emitAction(kind, detail) {
1895
+ if (typeof document === 'undefined') return;
1896
+ try {
1897
+ document.dispatchEvent(new CustomEvent('nac:action:' + kind,
1898
+ { detail: detail, bubbles: true }));
1899
+ } catch (_) { /* SSR or no document */ }
1900
+ }
1901
+
1902
+ function set_confirm_handler(fn) {
1903
+ if (typeof fn !== 'function') {
1904
+ throw NacError('invalid',
1905
+ 'NAC.set_confirm_handler: fn must be a function');
1906
+ }
1907
+ _v25_confirm_handler = fn;
1908
+ }
1909
+
1910
+ function has_authority(scope) {
1911
+ if (!_V25_SCOPE_RANK[scope]) return false;
1912
+ const want = _V25_SCOPE_RANK[scope];
1913
+ const now = Date.now();
1914
+ /* Iterate live grants. Higher rank satisfies lower-rank check.
1915
+ Auto-purge expired entries inline so the map stays clean. */
1916
+ let satisfied = false;
1917
+ _v25_authority_grants.forEach(function (info, grantedScope) {
1918
+ if (info.expires_at <= now) return; /* timer will purge */
1919
+ if (_V25_SCOPE_RANK[grantedScope] >= want) satisfied = true;
1920
+ });
1921
+ return satisfied;
1922
+ }
1923
+
1924
+ function revoke_authority(scope) {
1925
+ const info = _v25_authority_grants.get(scope);
1926
+ if (!info) return; /* idempotent */
1927
+ if (info.timer) { try { clearTimeout(info.timer); } catch (_) {} }
1928
+ _v25_authority_grants.delete(scope);
1929
+ _v25_emitAuth('revoked', { scope: scope, reason: 'manual' });
1930
+ }
1931
+
1932
+ function request_authority(scope, ttl_ms, opts) {
1933
+ return new Promise(function (resolve, reject) {
1934
+ if (!_V25_SCOPE_RANK[scope]) {
1935
+ reject(NacError('invalid',
1936
+ 'request_authority: scope must be one of low|medium|high'));
1937
+ return;
1938
+ }
1939
+ if (typeof ttl_ms !== 'number' || ttl_ms < 0 || !isFinite(ttl_ms)) {
1940
+ reject(NacError('invalid',
1941
+ 'request_authority: ttl_ms must be a non-negative finite number'));
1942
+ return;
1943
+ }
1944
+ if (!_v25_confirm_handler) {
1945
+ reject(NacError('no_confirm_handler',
1946
+ 'request_authority: NAC.set_confirm_handler must be called first'));
1947
+ return;
1948
+ }
1949
+ const reqId = _v25_nextPluginVersion(); /* reuse the monotonic stamp */
1950
+ const req = {
1951
+ kind: 'request_authority',
1952
+ request_id: reqId,
1953
+ scope: scope,
1954
+ ttl_ms: ttl_ms,
1955
+ metadata: (opts && opts.metadata) || {},
1956
+ };
1957
+ _v25_emitAuth('requested', req);
1958
+ let p;
1959
+ try { p = Promise.resolve(_v25_confirm_handler(req)); }
1960
+ catch (e) { p = Promise.resolve(false); }
1961
+ p.then(function (granted) { return !!granted; },
1962
+ function () { return false; })
1963
+ .then(function (granted) {
1964
+ if (!granted) {
1965
+ _v25_emitAuth('denied',
1966
+ { scope: scope, ttl_ms: ttl_ms, request_id: reqId });
1967
+ resolve({ granted: false, scope: scope, expires_at: null });
1968
+ return;
1969
+ }
1970
+ const now = Date.now();
1971
+ const expires_at = now + ttl_ms;
1972
+ /* Replace any prior grant for the same scope. */
1973
+ const prior = _v25_authority_grants.get(scope);
1974
+ if (prior && prior.timer) { try { clearTimeout(prior.timer); } catch (_) {} }
1975
+ const timer = setTimeout(function () {
1976
+ _v25_authority_grants.delete(scope);
1977
+ _v25_emitAuth('expired', { scope: scope, reason: 'ttl' });
1978
+ }, ttl_ms);
1979
+ _v25_authority_grants.set(scope, { expires_at: expires_at, timer: timer });
1980
+ _v25_emitAuth('granted',
1981
+ { scope: scope, expires_at: expires_at, request_id: reqId });
1982
+ resolve({ granted: true, scope: scope, expires_at: expires_at });
1983
+ });
1984
+ });
1985
+ }
1986
+
1987
+ function confirm_action(action_id, message, opts) {
1988
+ return new Promise(function (resolve, reject) {
1989
+ if (typeof action_id !== 'string' || !action_id) {
1990
+ reject(NacError('invalid',
1991
+ 'confirm_action: action_id must be a non-empty string'));
1992
+ return;
1993
+ }
1994
+ const scope = (opts && opts.scope) || 'medium';
1995
+ const metadata = (opts && opts.metadata) || {};
1996
+ /* Sudo bypass -- if we already have authority for this scope
1997
+ (or higher), short-circuit without calling the handler. */
1998
+ if (has_authority(scope)) {
1999
+ _v25_emitAction('confirmed',
2000
+ { action_id: action_id, scope: scope, sudo: true });
2001
+ resolve(true);
2002
+ return;
2003
+ }
2004
+ if (!_v25_confirm_handler) {
2005
+ reject(NacError('no_confirm_handler',
2006
+ 'confirm_action: NAC.set_confirm_handler must be called first'));
2007
+ return;
2008
+ }
2009
+ const req = {
2010
+ kind: 'confirm_action',
2011
+ action_id: action_id,
2012
+ message: message,
2013
+ scope: scope,
2014
+ metadata: metadata,
2015
+ };
2016
+ let p;
2017
+ try { p = Promise.resolve(_v25_confirm_handler(req)); }
2018
+ catch (e) { p = Promise.resolve(false); }
2019
+ p.then(function (approved) { return !!approved; },
2020
+ function () { return false; })
2021
+ .then(function (approved) {
2022
+ _v25_emitAction(approved ? 'confirmed' : 'rejected',
2023
+ { action_id: action_id, scope: scope, sudo: false });
2024
+ resolve(approved);
2025
+ });
2026
+ });
2027
+ }
2028
+
1602
2029
  /* ---------- Element discovery ----------------------------------- */
1603
2030
 
1604
2031
  /* ---------- v2.3 shadow DOM resolution (F1 + F6) ----------
@@ -3500,6 +3927,10 @@
3500
3927
  orphans: [],
3501
3928
  unmounted: [],
3502
3929
  convention_violations: [],
3930
+ /* v2.5 / RFC V24-01: plugin slug uniqueness findings live in
3931
+ their own bucket so CI integrations can gate on them
3932
+ independently of nac_id duplicates. */
3933
+ plugin_instance_violations: _scanPluginInstances(),
3503
3934
  plugin_count: 0,
3504
3935
  total_ids: 0,
3505
3936
  timestamp: Date.now(),
@@ -5540,114 +5971,6 @@
5540
5971
  };
5541
5972
  }
5542
5973
 
5543
- /* ---------- v1.9.0: action confirmation (sec 6.2.32) ---------- */
5544
-
5545
- /* The runtime maintains an in-memory map of in-flight confirm
5546
- requests keyed by confirm_id. confirm_action() emits the
5547
- requested event, awaits the host's handler decision (or the
5548
- default window.confirm), then emits granted/denied. */
5549
- let _confirmHandler = null;
5550
- function set_confirm_handler(fn) {
5551
- _confirmHandler = (typeof fn === 'function') ? fn : null;
5552
- }
5553
- function _newConfirmId() {
5554
- return 'cfm-' + Date.now().toString(36) + '-' +
5555
- Math.random().toString(36).slice(2, 8);
5556
- }
5557
- async function confirm_action(action_id, opts) {
5558
- opts = opts || {};
5559
- /* Resolve the element + its declared a11y_hint. */
5560
- const el = _findElement(action_id, {});
5561
- let hints = opts.hints;
5562
- if (!hints && el) {
5563
- const raw = el.getAttribute('data-nac-a11y-hint') || '';
5564
- hints = raw.split('|').map(function (s) { return s.trim(); })
5565
- .filter(function (s) { return s.length > 0; });
5566
- }
5567
- hints = hints || [];
5568
- const locale = (document.documentElement.lang || 'en').split('-')[0];
5569
- /* v1.9.0 sec 3.1: data-nac-confirmation-message override.
5570
- Host can declare per-element confirmation text (literal or
5571
- i18n key). Beats the auto-generated hint vocabulary text. */
5572
- let hint_text = opts.hint_text;
5573
- if (!hint_text && el) {
5574
- const cm = el.getAttribute('data-nac-confirmation-message');
5575
- if (cm && cm.length) {
5576
- if (cm.indexOf('i18n:') === 0 && _a11y_hint_localizer) {
5577
- /* Re-use the localizer hook with the i18n key as tag. */
5578
- try {
5579
- const v = _a11y_hint_localizer(cm.slice(5), locale);
5580
- if (typeof v === 'string' && v) hint_text = v;
5581
- } catch (e) { /* fall through */ }
5582
- }
5583
- if (!hint_text) hint_text = cm.indexOf('i18n:') === 0 ? cm.slice(5) : cm;
5584
- }
5585
- }
5586
- if (!hint_text) {
5587
- /* v1.9.0: walk hints in normative priority order so the
5588
- strongest tag leads the interposition text. */
5589
- const sorted = sort_hints_by_priority(hints);
5590
- hint_text = sorted.map(function (t) { return _localizeHintTag(t, locale); }).join(' ');
5591
- }
5592
- if (!hint_text) hint_text = 'Confirm this action?';
5593
- const verb = (el && el.getAttribute('data-nac-action')) || 'apply';
5594
- const confirm_id = _newConfirmId();
5595
- const pluginRoot = el && el.closest('[data-nac-plugin]');
5596
- const plugin = pluginRoot ? pluginRoot.getAttribute('data-nac-plugin') : null;
5597
- const reqDetail = {
5598
- plugin: plugin, plugin_instance_id: null,
5599
- action_id: action_id,
5600
- verb: verb,
5601
- hints: hints,
5602
- hint_text: hint_text,
5603
- confirm_id: confirm_id,
5604
- expires_at: Date.now() + (opts.timeout_ms || 60000),
5605
- };
5606
- /* opts.source defaults to {type:'script'} via _emit's normalisation. */
5607
- if (opts.source) reqDetail.source = opts.source;
5608
- _emit('nac:action:confirm:requested', reqDetail);
5609
- let resp;
5610
- try {
5611
- if (_confirmHandler) {
5612
- resp = await _confirmHandler(reqDetail);
5613
- } else if (typeof window.confirm === 'function') {
5614
- const ok = window.confirm(hint_text);
5615
- resp = { granted: !!ok, granted_via: 'window_confirm' };
5616
- } else {
5617
- resp = { granted: false, reason: 'no_handler' };
5618
- }
5619
- } catch (err) {
5620
- resp = { granted: false, reason: 'handler_error',
5621
- error: err && err.message };
5622
- }
5623
- if (resp.granted) {
5624
- _emit('nac:action:confirm:granted', {
5625
- plugin: plugin, plugin_instance_id: null,
5626
- action_id: action_id,
5627
- confirm_id: confirm_id,
5628
- granted_by: opts.source && opts.source.type === 'agent' ? 'agent' : 'user',
5629
- granted_via: resp.granted_via || 'modal_button',
5630
- source: opts.source || { type: 'user' },
5631
- });
5632
- } else {
5633
- _emit('nac:action:confirm:denied', {
5634
- plugin: plugin, plugin_instance_id: null,
5635
- action_id: action_id,
5636
- confirm_id: confirm_id,
5637
- reason: resp.reason || 'user_cancelled',
5638
- source: opts.source || { type: 'user' },
5639
- });
5640
- }
5641
- return {
5642
- confirm_id: confirm_id,
5643
- granted: !!resp.granted,
5644
- granted_by: resp.granted ?
5645
- (opts.source && opts.source.type === 'agent' ? 'agent' : 'user') : undefined,
5646
- granted_via: resp.granted ? (resp.granted_via || 'modal_button') : undefined,
5647
- reason: resp.granted ? undefined : (resp.reason || 'user_cancelled'),
5648
- };
5649
- }
5650
-
5651
5974
  /* ---------- v1.9.0: action undoable flag (sec 6.2.33) --------- */
5652
5975
 
5653
5976
  function _findActionInManifests(action_id) {
@@ -5780,12 +6103,777 @@
5780
6103
  return count;
5781
6104
  }
5782
6105
 
6106
+ /* ================================================================
6107
+ v2.5 Block A -- plugin extension contract (SPEC.md sec 15)
6108
+ ================================================================
6109
+
6110
+ Adds an agnostic routing layer so a plugin can declare verbs /
6111
+ state / events that flow through backends other than direct DOM:
6112
+ postMessage to iframes, plugin SDK calls, script bridges, DOM
6113
+ mirrors, same-origin window reads, synthetic events. The runtime
6114
+ stays ignorant of any specific app -- it only knows the fixed
6115
+ vocabulary of backend kinds and the extractor DSL.
6116
+
6117
+ IMPORTANT: NO fallback to v2.4 register() semantics. v2.5 plugins
6118
+ live in their own registry. NAC.call / read / subscribe ONLY
6119
+ consult this registry; they never silently degrade to NAC.click()
6120
+ against a same-named DOM element. */
6121
+
6122
+ const _v25_plugins = Object.create(null);
6123
+
6124
+ /* The 8 backend names from SPEC.md sec 15.4. Any other name in a
6125
+ manifest is a hard reject at register time. */
6126
+ const _V25_VALID_BACKENDS = {
6127
+ 'postmessage': true,
6128
+ 'postmessage-listen': true,
6129
+ 'sdk-call': true,
6130
+ 'script-bridge': true,
6131
+ 'dom-mirror': true,
6132
+ 'same-origin-window': true,
6133
+ 'synthetic-mutation': true,
6134
+ 'synthetic-poll': true,
6135
+ };
6136
+
6137
+ /* Counter for the request_id baked into every provenance event. */
6138
+ let _v25_req_counter = 0;
6139
+ function _v25_nextRequestId(prefix) {
6140
+ _v25_req_counter += 1;
6141
+ /* Hex-ish but non-cryptographic; the contract only requires
6142
+ uniqueness within a session for correlation. */
6143
+ return prefix + '_' + Date.now().toString(36) + '_' + _v25_req_counter.toString(36);
6144
+ }
6145
+
6146
+ /* ---------- 15.5 extractor DSL ---------- */
6147
+
6148
+ /* Apply an extractor DSL string to a raw value (or DOM element).
6149
+ Returns the extracted value. Throws if the DSL is malformed.
6150
+ The runtime swallows extractor errors at dispatch time (treats
6151
+ them as "this binding failed"); throwing here lets the test
6152
+ surface bad manifests during register / first call. */
6153
+ function _v25_extract(rawValue, dsl, isDom) {
6154
+ if (dsl == null || dsl === '') return rawValue;
6155
+ /* DOM-only forms first */
6156
+ if (dsl === 'text') {
6157
+ if (!isDom) throw new Error('extractor "text" requires a DOM element');
6158
+ return rawValue.textContent;
6159
+ }
6160
+ if (dsl === 'value') {
6161
+ if (!isDom) throw new Error('extractor "value" requires a DOM element');
6162
+ return rawValue.value;
6163
+ }
6164
+ if (dsl === 'present') {
6165
+ /* For DOM backends, rawValue is the element OR null. */
6166
+ return rawValue != null;
6167
+ }
6168
+ if (dsl.indexOf('attribute:') === 0) {
6169
+ if (!isDom) throw new Error('extractor "attribute:" requires a DOM element');
6170
+ const attr = dsl.slice('attribute:'.length);
6171
+ return rawValue.getAttribute(attr);
6172
+ }
6173
+ if (dsl.indexOf('classList.contains:') === 0) {
6174
+ if (!isDom) throw new Error('extractor "classList.contains:" requires a DOM element');
6175
+ const cls = dsl.slice('classList.contains:'.length);
6176
+ return rawValue.classList.contains(cls);
6177
+ }
6178
+ /* Otherwise treat as a dotted field path against rawValue. */
6179
+ if (/^[A-Za-z_][\w.]*$/.test(dsl)) {
6180
+ const parts = dsl.split('.');
6181
+ let cur = rawValue;
6182
+ for (let i = 0; i < parts.length; i++) {
6183
+ if (cur == null) return undefined;
6184
+ cur = cur[parts[i]];
6185
+ }
6186
+ return cur;
6187
+ }
6188
+ throw new Error('unknown extractor DSL: ' + dsl);
6189
+ }
6190
+
6191
+ /* ---------- 15.4 backend dispatchers ----------
6192
+ Each backend dispatcher returns a Promise.
6193
+ - For verbs: resolves with the backend's return value (often {ok}).
6194
+ - For state: resolves with the raw value (extractor applied by caller).
6195
+ - Rejects with a plain Error whose .message goes into provenance /
6196
+ err.attempts. */
6197
+
6198
+ function _v25_resolvePath(root, path) {
6199
+ /* Walk a dotted path. Returns { parent, key, value } where
6200
+ parent[key] === value. Used by sdk-call assign / read. */
6201
+ if (!path) return { parent: null, key: null, value: undefined };
6202
+ const parts = path.split('.');
6203
+ let parent = null;
6204
+ let cur = root;
6205
+ let key = null;
6206
+ for (let i = 0; i < parts.length; i++) {
6207
+ if (cur == null) return { parent: null, key: parts[i], value: undefined };
6208
+ parent = cur;
6209
+ key = parts[i];
6210
+ cur = cur[key];
6211
+ }
6212
+ return { parent: parent, key: key, value: cur };
6213
+ }
6214
+
6215
+ function _v25_backend_sdk_call(binding, args) {
6216
+ const mode = binding.mode || 'invoke';
6217
+ const path = binding.path;
6218
+ if (!path || typeof path !== 'string') {
6219
+ return Promise.reject(new Error('sdk-call requires `path` string'));
6220
+ }
6221
+ const resolved = _v25_resolvePath(global, path);
6222
+ if (mode === 'read') {
6223
+ if (resolved.parent == null) {
6224
+ return Promise.reject(new Error('sdk-call read: path not resolvable: ' + path));
6225
+ }
6226
+ if (resolved.value === undefined) {
6227
+ return Promise.reject(new Error('sdk-call read: path resolves to undefined: ' + path));
6228
+ }
6229
+ return Promise.resolve(resolved.value);
6230
+ }
6231
+ if (mode === 'assign') {
6232
+ if (resolved.parent == null) {
6233
+ return Promise.reject(new Error('sdk-call assign: path parent not resolvable: ' + path));
6234
+ }
6235
+ resolved.parent[resolved.key] = args;
6236
+ return Promise.resolve({ ok: true });
6237
+ }
6238
+ if (mode === 'invoke') {
6239
+ if (resolved.parent == null || typeof resolved.value !== 'function') {
6240
+ return Promise.reject(new Error('sdk-call invoke: path is not a function: ' + path));
6241
+ }
6242
+ try {
6243
+ const ret = resolved.value.call(resolved.parent, args);
6244
+ return Promise.resolve(ret);
6245
+ } catch (e) {
6246
+ return Promise.reject(e);
6247
+ }
6248
+ }
6249
+ return Promise.reject(new Error('sdk-call: unknown mode ' + mode));
6250
+ }
6251
+
6252
+ function _v25_backend_dom_mirror(binding /*, args*/) {
6253
+ const sel = binding.selector;
6254
+ if (!sel) return Promise.reject(new Error('dom-mirror requires `selector` string'));
6255
+ const el = document.querySelector(sel);
6256
+ if (binding.extract === 'present') {
6257
+ /* present extractor is well-defined even for null element. */
6258
+ return Promise.resolve(el != null);
6259
+ }
6260
+ if (el == null) {
6261
+ return Promise.reject(new Error('dom-mirror: selector matched no element: ' + sel));
6262
+ }
6263
+ try {
6264
+ const value = _v25_extract(el, binding.extract, true);
6265
+ if (value === undefined) {
6266
+ return Promise.reject(new Error('dom-mirror: extractor returned undefined for ' + sel));
6267
+ }
6268
+ return Promise.resolve(value);
6269
+ } catch (e) {
6270
+ return Promise.reject(e);
6271
+ }
6272
+ }
6273
+
6274
+ /* postmessage (verb): post a structured message to the iframe.contentWindow
6275
+ of the target. `values` literal + `values_from_args` forward keys. */
6276
+ function _v25_backend_postmessage(binding, args) {
6277
+ const sel = binding.target;
6278
+ if (!sel) return Promise.reject(new Error('postmessage requires `target` selector'));
6279
+ const iframe = document.querySelector(sel);
6280
+ if (!iframe) {
6281
+ const e = new Error('postmessage: target iframe not found: ' + sel);
6282
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6283
+ }
6284
+ if (!iframe.contentWindow || typeof iframe.contentWindow.postMessage !== 'function') {
6285
+ const e = new Error('postmessage: target has no contentWindow.postMessage');
6286
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6287
+ }
6288
+ const msg = {
6289
+ MessageId: binding.message,
6290
+ SendTime: Date.now(),
6291
+ Values: Object.assign({}, binding.values || {}),
6292
+ };
6293
+ if (Array.isArray(binding.values_from_args) && args && typeof args === 'object') {
6294
+ for (let i = 0; i < binding.values_from_args.length; i++) {
6295
+ const k = binding.values_from_args[i];
6296
+ if (Object.prototype.hasOwnProperty.call(args, k)) msg.Values[k] = args[k];
6297
+ }
6298
+ }
6299
+ try {
6300
+ iframe.contentWindow.postMessage(msg, binding.target_origin || '*');
6301
+ return Promise.resolve({ ok: true });
6302
+ } catch (e) {
6303
+ return Promise.reject(e);
6304
+ }
6305
+ }
6306
+
6307
+ /* same-origin-window (state): read iframe.contentWindow.<path>. Throws
6308
+ a cross-origin sentinel if accessing the contentWindow fails the
6309
+ same-origin check. In the reference shim we honor an `_sameOrigin`
6310
+ flag the test sets explicitly; in real browsers the property access
6311
+ throws a DOMException SecurityError which we map the same way. */
6312
+ function _v25_backend_same_origin_window(binding /*, args*/) {
6313
+ const sel = binding.target;
6314
+ if (!sel) return Promise.reject(new Error('same-origin-window requires `target`'));
6315
+ const iframe = document.querySelector(sel);
6316
+ if (!iframe) {
6317
+ const e = new Error('same-origin-window: iframe not found: ' + sel);
6318
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6319
+ }
6320
+ if (iframe._sameOrigin === false) {
6321
+ const e = new Error('cross_origin_blocked: iframe is cross-origin');
6322
+ e._code = 'cross_origin_blocked'; return Promise.reject(e);
6323
+ }
6324
+ let cw;
6325
+ try { cw = iframe.contentWindow; }
6326
+ catch (e) {
6327
+ const ex = new Error('cross_origin_blocked: contentWindow access threw');
6328
+ ex._code = 'cross_origin_blocked'; return Promise.reject(ex);
6329
+ }
6330
+ if (!cw) {
6331
+ const e = new Error('same-origin-window: contentWindow is null');
6332
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6333
+ }
6334
+ /* Walk the path. */
6335
+ if (!binding.path) return Promise.reject(new Error('same-origin-window requires `path`'));
6336
+ const parts = binding.path.split('.');
6337
+ let cur = cw;
6338
+ for (let i = 0; i < parts.length; i++) {
6339
+ if (cur == null) return Promise.reject(new Error('same-origin-window: path segment ' + parts[i] + ' is null'));
6340
+ try { cur = cur[parts[i]]; }
6341
+ catch (e) {
6342
+ const ex = new Error('cross_origin_blocked: read into contentWindow threw');
6343
+ ex._code = 'cross_origin_blocked'; return Promise.reject(ex);
6344
+ }
6345
+ }
6346
+ if (cur === undefined) {
6347
+ return Promise.reject(new Error('same-origin-window: path resolves to undefined'));
6348
+ }
6349
+ return Promise.resolve(cur);
6350
+ }
6351
+
6352
+ /* script-bridge (state/verb): postmessage with a request, await a
6353
+ correlated response, extract the value. Used by Collabora's
6354
+ CallPythonScript pattern; generalises to any app that exposes a
6355
+ RPC channel over postMessage. */
6356
+ function _v25_backend_script_bridge(binding, args) {
6357
+ const sel = binding.target;
6358
+ if (!sel) return Promise.reject(new Error('script-bridge requires `target`'));
6359
+ const iframe = document.querySelector(sel);
6360
+ if (!iframe) {
6361
+ const e = new Error('script-bridge: iframe not found: ' + sel);
6362
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6363
+ }
6364
+ if (!iframe.contentWindow || typeof iframe.contentWindow.postMessage !== 'function') {
6365
+ const e = new Error('script-bridge: target has no contentWindow.postMessage');
6366
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6367
+ }
6368
+ const responseMsgId = binding.response_match;
6369
+ if (!responseMsgId) return Promise.reject(new Error('script-bridge requires `response_match`'));
6370
+ const timeoutMs = binding.timeout_ms || 5000;
6371
+ const wantValues = Object.assign({}, binding.values || {});
6372
+ if (args && typeof args === 'object') {
6373
+ for (const k in args) wantValues[k] = args[k];
6374
+ }
6375
+ return new Promise(function (resolve, reject) {
6376
+ let settled = false;
6377
+ function onMessage(ev) {
6378
+ if (settled) return;
6379
+ if (!ev || !ev.data) return;
6380
+ if (ev.source !== iframe.contentWindow) return;
6381
+ if (ev.data.MessageId !== responseMsgId) return;
6382
+ settled = true;
6383
+ global.removeEventListener('message', onMessage);
6384
+ clearTimeout(t);
6385
+ /* Resolve with the raw response object. The caller (read or call)
6386
+ applies binding.extract once -- the dispatcher does not, so the
6387
+ extractor is never run twice. */
6388
+ resolve(ev.data);
6389
+ }
6390
+ const t = setTimeout(function () {
6391
+ if (settled) return;
6392
+ settled = true;
6393
+ global.removeEventListener('message', onMessage);
6394
+ reject(new Error('script-bridge: timeout after ' + timeoutMs + 'ms'));
6395
+ }, timeoutMs);
6396
+ global.addEventListener('message', onMessage);
6397
+ /* Fire the request. */
6398
+ iframe.contentWindow.postMessage({
6399
+ MessageId: binding.message,
6400
+ SendTime: Date.now(),
6401
+ Values: wantValues,
6402
+ }, binding.target_origin || '*');
6403
+ });
6404
+ }
6405
+
6406
+ /* synthetic-poll (event): observe declared state paths on a fixed
6407
+ setInterval cadence. On each tick, re-read every observed path,
6408
+ compare to the cached snapshot, and fire the cb with the new
6409
+ snapshot when ANY value differs. Requires only setInterval; no
6410
+ MutationObserver dependency. Teardown clears the interval. */
6411
+ function _v25_subscribe_synthetic_poll(plugin, event_path, binding, cb) {
6412
+ if (!Array.isArray(binding.observe) || binding.observe.length === 0) {
6413
+ throw new Error('synthetic-poll requires `observe: [state_path, ...]`');
6414
+ }
6415
+ const interval = binding.interval_ms || 250;
6416
+ const paths = binding.observe.slice();
6417
+ let cached = null; /* null until first successful snapshot */
6418
+ function snapshot() {
6419
+ const out = {};
6420
+ let allOk = true;
6421
+ const promises = paths.map(function (p) {
6422
+ return read(plugin, p).then(function (v) { out[p] = v; },
6423
+ function () { allOk = false; });
6424
+ });
6425
+ return Promise.all(promises).then(function () {
6426
+ return allOk ? out : null;
6427
+ });
6428
+ }
6429
+ function diffsFromCached(snap) {
6430
+ if (cached == null) return false;
6431
+ for (let i = 0; i < paths.length; i++) {
6432
+ const k = paths[i];
6433
+ /* Strict JSON-shape compare for primitives + objects. */
6434
+ const a = cached[k]; const b = snap[k];
6435
+ if (a !== b) {
6436
+ if (typeof a !== 'object' || typeof b !== 'object') return true;
6437
+ if (JSON.stringify(a) !== JSON.stringify(b)) return true;
6438
+ }
6439
+ }
6440
+ return false;
6441
+ }
6442
+ /* Prime the cache from the first snapshot so the first real change
6443
+ fires (and not the initial baseline). */
6444
+ snapshot().then(function (first) { if (first != null) cached = first; });
6445
+ const handle = setInterval(function () {
6446
+ snapshot().then(function (snap) {
6447
+ if (snap == null) return;
6448
+ if (cached == null) { cached = snap; return; }
6449
+ if (diffsFromCached(snap)) {
6450
+ cached = snap;
6451
+ try { cb(snap); }
6452
+ finally {
6453
+ _v25_emitProvenance('event', plugin, event_path, 'synthetic-poll',
6454
+ _v25_nextRequestId('pe'), true, null, 0);
6455
+ }
6456
+ }
6457
+ });
6458
+ }, interval);
6459
+ return function teardown() { clearInterval(handle); };
6460
+ }
6461
+
6462
+ /* synthetic-mutation (event): observe declared state paths via
6463
+ MutationObserver on the underlying dom-mirror elements. On
6464
+ mutation (with throttle), re-read every observed path and fire
6465
+ the user cb when ANY value changed vs the cached snapshot.
6466
+
6467
+ Requires that every observed path's FIRST state binding be
6468
+ dom-mirror -- only DOM-rooted state is observable via mutations.
6469
+ Mixed manifests (dom-mirror + sdk-call in the same observe list)
6470
+ reject at subscribe time with `invalid`. The manifest author can
6471
+ fall back to synthetic-poll for those cases (declared, not
6472
+ implicit). */
6473
+ function _v25_subscribe_synthetic_mutation(plugin, event_path, binding, cb) {
6474
+ if (typeof MutationObserver === 'undefined') {
6475
+ throw new Error('synthetic-mutation requires MutationObserver in scope');
6476
+ }
6477
+ if (!Array.isArray(binding.observe) || binding.observe.length === 0) {
6478
+ throw new Error('synthetic-mutation requires `observe: [state_path, ...]`');
6479
+ }
6480
+ const throttle = binding.throttle_ms != null ? binding.throttle_ms : 100;
6481
+ const paths = binding.observe.slice();
6482
+ /* Resolve each observed path to a dom-mirror element. Reject the
6483
+ whole subscription if any observed path's primary binding is
6484
+ not dom-mirror -- spec contract, no silent degradation. */
6485
+ const elements = [];
6486
+ const manifest = _v25_plugins[plugin];
6487
+ for (let i = 0; i < paths.length; i++) {
6488
+ const stateChain = manifest.state[paths[i]];
6489
+ if (!stateChain || !stateChain.length) {
6490
+ const e = new Error('synthetic-mutation: observed state "' + paths[i] + '" not declared');
6491
+ e._code = 'invalid'; throw e;
6492
+ }
6493
+ const first = stateChain[0];
6494
+ if (first.backend !== 'dom-mirror') {
6495
+ const e = new Error('synthetic-mutation: observed state "' + paths[i] +
6496
+ '" primary backend must be dom-mirror, got ' + first.backend);
6497
+ e._code = 'invalid'; throw e;
6498
+ }
6499
+ const el = document.querySelector(first.selector);
6500
+ if (el) elements.push(el);
6501
+ }
6502
+ let cached = null;
6503
+ let pending = null;
6504
+ function snapshot() {
6505
+ const out = {};
6506
+ let allOk = true;
6507
+ const promises = paths.map(function (p) {
6508
+ return read(plugin, p).then(function (v) { out[p] = v; },
6509
+ function () { allOk = false; });
6510
+ });
6511
+ return Promise.all(promises).then(function () {
6512
+ return allOk ? out : null;
6513
+ });
6514
+ }
6515
+ function diffsFromCached(snap) {
6516
+ if (cached == null) return false;
6517
+ for (let i = 0; i < paths.length; i++) {
6518
+ const k = paths[i];
6519
+ const a = cached[k]; const b = snap[k];
6520
+ if (a !== b) {
6521
+ if (typeof a !== 'object' || typeof b !== 'object') return true;
6522
+ if (JSON.stringify(a) !== JSON.stringify(b)) return true;
6523
+ }
6524
+ }
6525
+ return false;
6526
+ }
6527
+ function tick() {
6528
+ pending = null;
6529
+ snapshot().then(function (snap) {
6530
+ if (snap == null) return;
6531
+ if (cached == null) { cached = snap; return; }
6532
+ if (diffsFromCached(snap)) {
6533
+ cached = snap;
6534
+ try { cb(snap); }
6535
+ finally {
6536
+ _v25_emitProvenance('event', plugin, event_path, 'synthetic-mutation',
6537
+ _v25_nextRequestId('pe'), true, null, 0);
6538
+ }
6539
+ }
6540
+ });
6541
+ }
6542
+ /* Prime cache from first snapshot. */
6543
+ snapshot().then(function (first) { if (first != null) cached = first; });
6544
+ const observer = new MutationObserver(function () {
6545
+ if (pending != null) return; /* already throttled */
6546
+ pending = setTimeout(tick, throttle);
6547
+ });
6548
+ for (let i = 0; i < elements.length; i++) {
6549
+ observer.observe(elements[i], {
6550
+ attributes: true, childList: true, characterData: true, subtree: true,
6551
+ });
6552
+ }
6553
+ return function teardown() {
6554
+ observer.disconnect();
6555
+ if (pending != null) { clearTimeout(pending); pending = null; }
6556
+ };
6557
+ }
6558
+
6559
+ /* postmessage-listen (event): subscribe to incoming `message` events
6560
+ on the host window, filter by source iframe + MessageId, run the
6561
+ extractor, fire the user callback. Returns a teardown closure. */
6562
+ function _v25_subscribe_postmessage_listen(plugin, event_path, binding, cb) {
6563
+ const sel = binding.source;
6564
+ const wantMsgId = binding.message;
6565
+ if (!wantMsgId) throw new Error('postmessage-listen requires `message`');
6566
+ /* Source filtering: if a selector is given, resolve the iframe NOW.
6567
+ If the iframe is later replaced, the subscription stops matching;
6568
+ that is intentional -- callers can re-subscribe on remount. */
6569
+ const iframe = sel ? document.querySelector(sel) : null;
6570
+ function onMessage(ev) {
6571
+ if (!ev || !ev.data) return;
6572
+ if (ev.data.MessageId !== wantMsgId) return;
6573
+ if (iframe && ev.source !== iframe.contentWindow) return;
6574
+ let value;
6575
+ try {
6576
+ value = binding.extract ? _v25_extract(ev.data, binding.extract, false) : ev.data;
6577
+ } catch (e) {
6578
+ _v25_emitProvenance('event', plugin, event_path, 'postmessage-listen',
6579
+ _v25_nextRequestId('pe'), false, e.message, 0);
6580
+ return;
6581
+ }
6582
+ try { cb(value); }
6583
+ finally {
6584
+ _v25_emitProvenance('event', plugin, event_path, 'postmessage-listen',
6585
+ _v25_nextRequestId('pe'), true, null, 0);
6586
+ }
6587
+ }
6588
+ global.addEventListener('message', onMessage);
6589
+ return function teardown() { global.removeEventListener('message', onMessage); };
6590
+ }
6591
+
6592
+ /* Registry of dispatchers keyed by backend name. */
6593
+ const _V25_VERB_DISPATCHERS = {
6594
+ 'sdk-call': _v25_backend_sdk_call,
6595
+ 'postmessage': _v25_backend_postmessage,
6596
+ 'script-bridge': _v25_backend_script_bridge,
6597
+ /* same-origin-window and dom-mirror are state-only; the synthetic
6598
+ backends are event-only. */
6599
+ };
6600
+ const _V25_STATE_DISPATCHERS = {
6601
+ 'sdk-call': _v25_backend_sdk_call,
6602
+ 'dom-mirror': _v25_backend_dom_mirror,
6603
+ 'same-origin-window': _v25_backend_same_origin_window,
6604
+ 'script-bridge': _v25_backend_script_bridge,
6605
+ };
6606
+ const _V25_EVENT_SUBSCRIBERS = {
6607
+ 'postmessage-listen': _v25_subscribe_postmessage_listen,
6608
+ 'synthetic-poll': _v25_subscribe_synthetic_poll,
6609
+ 'synthetic-mutation': _v25_subscribe_synthetic_mutation,
6610
+ };
6611
+
6612
+ /* ---------- 15.2 / 15.3 public surface ---------- */
6613
+
6614
+ function _v25_validateManifest(slug, manifest) {
6615
+ if (typeof slug !== 'string' || !slug) {
6616
+ const e = new Error('registerPlugin: slug must be non-empty string');
6617
+ e.code = 'invalid'; throw e;
6618
+ }
6619
+ if (manifest == null || typeof manifest !== 'object') {
6620
+ const e = new Error('registerPlugin: manifest object required');
6621
+ e.code = 'invalid'; throw e;
6622
+ }
6623
+ const verbs = manifest.verbs || {};
6624
+ const states = manifest.state || {};
6625
+ const events = manifest.events || {};
6626
+ /* Verbs: single binding each, backend in vocabulary. */
6627
+ for (const vp in verbs) {
6628
+ const b = verbs[vp];
6629
+ if (!b || typeof b !== 'object' || !b.backend) {
6630
+ const e = new Error('verb "' + vp + '" missing backend');
6631
+ e.code = 'invalid'; throw e;
6632
+ }
6633
+ if (!_V25_VALID_BACKENDS[b.backend]) {
6634
+ const e = new Error('verb "' + vp + '" declares unknown backend: ' + b.backend);
6635
+ e.code = 'backend_unknown'; throw e;
6636
+ }
6637
+ }
6638
+ /* State: array of bindings each. */
6639
+ for (const sp in states) {
6640
+ const arr = states[sp];
6641
+ if (!Array.isArray(arr) || arr.length === 0) {
6642
+ const e = new Error('state "' + sp + '" must be a non-empty array of bindings');
6643
+ e.code = 'invalid'; throw e;
6644
+ }
6645
+ for (let i = 0; i < arr.length; i++) {
6646
+ const b = arr[i];
6647
+ if (!b || typeof b !== 'object' || !b.backend) {
6648
+ const e = new Error('state "' + sp + '" binding[' + i + '] missing backend');
6649
+ e.code = 'invalid'; throw e;
6650
+ }
6651
+ if (!_V25_VALID_BACKENDS[b.backend]) {
6652
+ const e = new Error('state "' + sp + '" binding[' + i + '] unknown backend: ' + b.backend);
6653
+ e.code = 'backend_unknown'; throw e;
6654
+ }
6655
+ }
6656
+ }
6657
+ /* Events: single binding each. */
6658
+ for (const ep in events) {
6659
+ const b = events[ep];
6660
+ if (!b || typeof b !== 'object' || !b.backend) {
6661
+ const e = new Error('event "' + ep + '" missing backend');
6662
+ e.code = 'invalid'; throw e;
6663
+ }
6664
+ if (!_V25_VALID_BACKENDS[b.backend]) {
6665
+ const e = new Error('event "' + ep + '" unknown backend: ' + b.backend);
6666
+ e.code = 'backend_unknown'; throw e;
6667
+ }
6668
+ }
6669
+ }
6670
+
6671
+ function registerPlugin(slug, manifest) {
6672
+ _v25_validateManifest(slug, manifest);
6673
+ /* Re-register replaces -- idempotent for live-reload scenarios. */
6674
+ _v25_plugins[slug] = {
6675
+ slug: slug,
6676
+ verbs: manifest.verbs || {},
6677
+ state: manifest.state || {},
6678
+ events: manifest.events || {},
6679
+ };
6680
+ }
6681
+
6682
+ /* Provenance emit helper -- the kind is one of 'invoked', 'read',
6683
+ 'event'. Detail shape per SPEC.md sec 15.7. */
6684
+ function _v25_emitProvenance(kind, plugin, path, backend, request_id, ok, error, duration_ms, extra) {
6685
+ const detail = {
6686
+ plugin: plugin,
6687
+ backend: backend || null,
6688
+ request_id: request_id,
6689
+ source: 'agent',
6690
+ trusted: false,
6691
+ duration_ms: duration_ms,
6692
+ ok: !!ok,
6693
+ error: error || null,
6694
+ };
6695
+ if (kind === 'invoked') detail.verb_path = path;
6696
+ else if (kind === 'read') detail.state_path = path;
6697
+ else if (kind === 'event') detail.event_path = path;
6698
+ if (extra) {
6699
+ for (const k in extra) detail[k] = extra[k];
6700
+ }
6701
+ try {
6702
+ document.dispatchEvent(new CustomEvent('nac:plugin:' + kind, { detail: detail, bubbles: true }));
6703
+ } catch (_) { /* if document lacks dispatch, swallow */ }
6704
+ }
6705
+
6706
+ function _v25_buildNacError(code, message, extra) {
6707
+ const e = new Error(message);
6708
+ e.code = code;
6709
+ if (extra) for (const k in extra) e[k] = extra[k];
6710
+ return e;
6711
+ }
6712
+
6713
+ function call(plugin, verb_path, args) {
6714
+ const request_id = _v25_nextRequestId('pi');
6715
+ const t0 = Date.now();
6716
+ /* Errors that surface BEFORE any backend dispatch still get a
6717
+ provenance row -- the agent's request happened, it just failed
6718
+ at routing. backend stays null in that case. */
6719
+ if (!_v25_plugins[plugin]) {
6720
+ const err = _v25_buildNacError('plugin_not_registered',
6721
+ 'NAC.call: plugin "' + plugin + '" not registered');
6722
+ _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
6723
+ return Promise.reject(err);
6724
+ }
6725
+ const binding = _v25_plugins[plugin].verbs[verb_path];
6726
+ if (!binding) {
6727
+ const err = _v25_buildNacError('verb_not_declared',
6728
+ 'NAC.call: plugin "' + plugin + '" has no verb "' + verb_path + '"');
6729
+ _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
6730
+ return Promise.reject(err);
6731
+ }
6732
+ const dispatcher = _V25_VERB_DISPATCHERS[binding.backend];
6733
+ if (!dispatcher) {
6734
+ const err = _v25_buildNacError('backend_unknown',
6735
+ 'NAC.call: backend "' + binding.backend + '" not implemented for verbs');
6736
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, false, err.message, Date.now() - t0);
6737
+ return Promise.reject(err);
6738
+ }
6739
+ return dispatcher(binding, args).then(function (value) {
6740
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, true, null, Date.now() - t0);
6741
+ return value;
6742
+ }, function (err) {
6743
+ /* If the dispatcher tagged the error with a NacError code via
6744
+ `_code`, lift it onto a proper NacError so callers see e.g.
6745
+ backend_target_missing or cross_origin_blocked instead of the
6746
+ raw Error. Provenance always records the human message. */
6747
+ const msg = (err && err.message) || String(err);
6748
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, false, msg, Date.now() - t0);
6749
+ if (err && err._code) {
6750
+ throw _v25_buildNacError(err._code, msg);
6751
+ }
6752
+ throw err;
6753
+ });
6754
+ }
6755
+
6756
+ function read(plugin, state_path) {
6757
+ const request_id = _v25_nextRequestId('pr');
6758
+ const t0 = Date.now();
6759
+ if (!_v25_plugins[plugin]) {
6760
+ const err = _v25_buildNacError('plugin_not_registered',
6761
+ 'NAC.read: plugin "' + plugin + '" not registered');
6762
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
6763
+ return Promise.reject(err);
6764
+ }
6765
+ const chain = _v25_plugins[plugin].state[state_path];
6766
+ if (!chain) {
6767
+ const err = _v25_buildNacError('state_not_declared',
6768
+ 'NAC.read: plugin "' + plugin + '" has no state "' + state_path + '"');
6769
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
6770
+ return Promise.reject(err);
6771
+ }
6772
+ /* Walk the chain in declared order. First binding to resolve with
6773
+ a non-undefined value wins. Every failure is recorded for the
6774
+ state_unreadable error if none succeed. */
6775
+ const attempts = [];
6776
+ function tryAt(i) {
6777
+ if (i >= chain.length) {
6778
+ const err = _v25_buildNacError('state_unreadable',
6779
+ 'NAC.read: every binding in chain for "' + state_path + '" failed',
6780
+ { attempts: attempts });
6781
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0, { attempts: attempts });
6782
+ return Promise.reject(err);
6783
+ }
6784
+ const binding = chain[i];
6785
+ const dispatcher = _V25_STATE_DISPATCHERS[binding.backend];
6786
+ if (!dispatcher) {
6787
+ attempts.push({ backend: binding.backend, reason: 'dispatcher not implemented for state' });
6788
+ return tryAt(i + 1);
6789
+ }
6790
+ return dispatcher(binding).then(function (raw) {
6791
+ /* For dom-mirror with extract, the dispatcher already applied
6792
+ the extractor and returned the extracted value. For sdk-call
6793
+ with mode:read, the raw value is the path's value -- no
6794
+ extractor needed unless the manifest declared one. */
6795
+ let value;
6796
+ if (binding.backend === 'dom-mirror') {
6797
+ value = raw; /* already extracted */
6798
+ } else if (binding.extract) {
6799
+ try { value = _v25_extract(raw, binding.extract, false); }
6800
+ catch (e) {
6801
+ attempts.push({ backend: binding.backend, reason: e.message });
6802
+ return tryAt(i + 1);
6803
+ }
6804
+ } else {
6805
+ value = raw;
6806
+ }
6807
+ if (value === undefined) {
6808
+ attempts.push({ backend: binding.backend, reason: 'resolved value was undefined' });
6809
+ return tryAt(i + 1);
6810
+ }
6811
+ _v25_emitProvenance('read', plugin, state_path, binding.backend, request_id, true, null, Date.now() - t0);
6812
+ return value;
6813
+ }, function (err) {
6814
+ attempts.push({ backend: binding.backend, reason: err.message || String(err) });
6815
+ return tryAt(i + 1);
6816
+ });
6817
+ }
6818
+ return tryAt(0);
6819
+ }
6820
+
6821
+ /* Active subscription handles -> teardown closures. Allows
6822
+ idempotent unsubscribe by handle reference. */
6823
+ const _v25_subscriptions = new WeakMap();
6824
+ let _v25_sub_counter = 0;
6825
+
6826
+ function subscribe(plugin, event_path, cb) {
6827
+ if (typeof cb !== 'function') {
6828
+ throw _v25_buildNacError('invalid', 'NAC.subscribe: cb must be a function');
6829
+ }
6830
+ if (!_v25_plugins[plugin]) {
6831
+ throw _v25_buildNacError('plugin_not_registered',
6832
+ 'NAC.subscribe: plugin "' + plugin + '" not registered');
6833
+ }
6834
+ const binding = _v25_plugins[plugin].events[event_path];
6835
+ if (!binding) {
6836
+ throw _v25_buildNacError('event_not_declared',
6837
+ 'NAC.subscribe: plugin "' + plugin + '" has no event "' + event_path + '"');
6838
+ }
6839
+ const subscriber = _V25_EVENT_SUBSCRIBERS[binding.backend];
6840
+ if (!subscriber) {
6841
+ throw _v25_buildNacError('backend_unknown',
6842
+ 'NAC.subscribe: backend "' + binding.backend + '" not implemented for events');
6843
+ }
6844
+ let teardown;
6845
+ try { teardown = subscriber(plugin, event_path, binding, cb); }
6846
+ catch (e) {
6847
+ if (e && e._code) throw _v25_buildNacError(e._code, e.message);
6848
+ throw e;
6849
+ }
6850
+ _v25_sub_counter += 1;
6851
+ const handle = {
6852
+ __v25_sub: true,
6853
+ id: _v25_sub_counter,
6854
+ plugin: plugin,
6855
+ event_path: event_path,
6856
+ backend: binding.backend,
6857
+ };
6858
+ _v25_subscriptions.set(handle, teardown);
6859
+ return handle;
6860
+ }
6861
+
6862
+ function unsubscribe(handle) {
6863
+ if (!handle || !handle.__v25_sub) return;
6864
+ const teardown = _v25_subscriptions.get(handle);
6865
+ if (teardown) {
6866
+ try { teardown(); } catch (_) { /* idempotent */ }
6867
+ _v25_subscriptions.delete(handle);
6868
+ }
6869
+ }
6870
+
5783
6871
  /* ---------- Install -------------------------------------------- */
5784
6872
 
5785
6873
  global.NAC = {
5786
6874
  __nac_v1_installed: true,
5787
- version: '2.4.0',
5788
- spec_version: '2.4',
6875
+ version: '2.5.0-alpha.1',
6876
+ spec_version: '2.5',
5789
6877
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
5790
6878
  NAC.register throws on findings (manifest_role_unknown,
5791
6879
  tab_id_manifest_role_drift, manifest_dom_role_mismatch).
@@ -5795,10 +6883,30 @@
5795
6883
  bootstrap before any register() call. See
5796
6884
  guides/MIGRATION_v2.2_to_v2.3.md. */
5797
6885
  STRICT_VALIDATION: true,
6886
+ /* v2.5 / RFC V24-01 -- when true (default), NAC.register throws
6887
+ on the first slug uniqueness violation; the boot-time pass
6888
+ paints a red banner + dispatches nac:fatal. Set false BEFORE
6889
+ any register() call to opt out for a single migration window.
6890
+ The flag is removed in v2.6 (enforcement becomes unconditional). */
6891
+ HARD_DEDUP: true,
5798
6892
  /* registry */
5799
6893
  register: register,
5800
6894
  unregister: unregister,
5801
6895
  manifest: manifest,
6896
+ /* v2.5 V24-02 -- idempotent registration. Use this in SPA hosts
6897
+ where a component remount may call into NAC twice; syncPlugin
6898
+ replaces the manifest instead of appending. */
6899
+ syncPlugin: syncPlugin,
6900
+ /* v2.5 V24-05 -- Agent authority + sudo elevation. The host
6901
+ interposes a confirmation UI between agent dispatch and the
6902
+ action's side effect; request_authority + has_authority let
6903
+ the user grant a time-bounded "sudo" elevation that bypasses
6904
+ confirmations for a scope until TTL expires. */
6905
+ set_confirm_handler: set_confirm_handler,
6906
+ confirm_action: confirm_action,
6907
+ request_authority: request_authority,
6908
+ has_authority: has_authority,
6909
+ revoke_authority: revoke_authority,
5802
6910
  /* v2.3 preview (V23-02): introspection helper that returns the
5803
6911
  list of plugin slugs currently registered (regardless of DOM
5804
6912
  mount state). Used by the interop layer's export_tree to
@@ -5966,9 +7074,10 @@
5966
7074
  assert_event_count: assert_event_count,
5967
7075
  perf_probe: perf_probe,
5968
7076
  replay_pending: replay_pending,
5969
- /* v1.9.0 -- action confirmation (sec 6.2.32) */
5970
- confirm_action: confirm_action,
5971
- set_confirm_handler: set_confirm_handler,
7077
+ /* v1.9.0 -- action confirmation -- superseded by v2.5 V24-05
7078
+ (set_confirm_handler / confirm_action / request_authority /
7079
+ has_authority / revoke_authority exposed earlier in this
7080
+ object). The v1.9 single-handler model is a strict subset. */
5972
7081
  /* v1.9.0 -- action undoable flag (sec 6.2.33) */
5973
7082
  action_undoable: action_undoable,
5974
7083
  action_undo_window_ms: action_undo_window_ms,
@@ -5990,6 +7099,15 @@
5990
7099
  },
5991
7100
  /* errors */
5992
7101
  NacError: NacError,
7102
+ /* v2.5 Block A -- plugin extension contract (SPEC.md sec 15).
7103
+ Agnostic routing for canvas + API surfaces (Collabora, Figma,
7104
+ Miro, Excalidraw, etc). Lives in its own registry; never falls
7105
+ back to v2.4 register() semantics. */
7106
+ registerPlugin: registerPlugin,
7107
+ call: call,
7108
+ read: read,
7109
+ subscribe: subscribe,
7110
+ unsubscribe: unsubscribe,
5993
7111
  };
5994
7112
 
5995
7113
  /* v2.2.1: guard browser-only init so this module is importable in