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