@nac3/runtime 2.3.0-alpha.1 → 2.3.0

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.
@@ -653,6 +653,74 @@
653
653
  const _manifests = Object.create(null);
654
654
  const _instances = Object.create(null);
655
655
 
656
+ /* v2.3 (F7) -- auth-aware capabilities. Hosts call
657
+ NAC.setCapabilities([...]) when the user logs in / role changes.
658
+ Manifest entries opt in by declaring `requires_capability` on the
659
+ element or on a specific verb. Public verbs (NAC.click /
660
+ NAC.invoke) gate before dispatch and reject with
661
+ code='capability_required' if the cap is absent. */
662
+ let _userCapabilities = new Set();
663
+
664
+ function _resolveCapability(nac_id, verb) {
665
+ /* Walk every registered manifest, find a matching element id, and
666
+ return:
667
+ - the verb-specific requires_capability if verb is given and
668
+ the matching verb entry has one set,
669
+ - else the element-level requires_capability,
670
+ - else null. */
671
+ for (const slug in _manifests) {
672
+ const m = _manifests[slug];
673
+ if (!m) continue;
674
+ const all = (m.elements || []).concat(m.tabs || []);
675
+ for (let i = 0; i < all.length; i++) {
676
+ const e = all[i];
677
+ if (!e || e.id !== nac_id) continue;
678
+ /* verb-level. */
679
+ if (verb && Array.isArray(e.actions)) {
680
+ for (let j = 0; j < e.actions.length; j++) {
681
+ const a = e.actions[j];
682
+ if (a && a.verb === verb && a.requires_capability) {
683
+ return a.requires_capability;
684
+ }
685
+ }
686
+ }
687
+ /* element-level fallback. */
688
+ if (e.requires_capability) return e.requires_capability;
689
+ return null;
690
+ }
691
+ }
692
+ return null;
693
+ }
694
+
695
+ function _hasCapability(cap) {
696
+ if (!cap) return true;
697
+ if (Array.isArray(cap)) {
698
+ /* Array semantics: user must have AT LEAST ONE of the listed
699
+ capabilities (OR). Use repeated array entries OR a higher-
700
+ level guard for AND semantics. */
701
+ for (let i = 0; i < cap.length; i++) {
702
+ if (_userCapabilities.has(cap[i])) return true;
703
+ }
704
+ return false;
705
+ }
706
+ return _userCapabilities.has(cap);
707
+ }
708
+
709
+ function setCapabilities(arr) {
710
+ /* Accepts an array, a single string, or null (clears).
711
+ Replaces the entire set; for incremental updates use
712
+ grantCapability / revokeCapability. */
713
+ if (arr == null) { _userCapabilities = new Set(); return; }
714
+ if (typeof arr === 'string') arr = [arr];
715
+ if (!Array.isArray(arr)) {
716
+ throw NacError('invalid', 'setCapabilities: array of strings required');
717
+ }
718
+ _userCapabilities = new Set(arr.map(String));
719
+ }
720
+ function grantCapability(cap) { _userCapabilities.add(String(cap)); }
721
+ function revokeCapability(cap) { _userCapabilities.delete(String(cap)); }
722
+ function userCapabilities() { return Array.from(_userCapabilities); }
723
+
656
724
  /* register(manifest) -- canonical, plugin_slug inside manifest
657
725
  register(slug, manifest) -- v1.4.1: accepted for back-compat with
658
726
  integrators that match the typical
@@ -845,6 +913,73 @@
845
913
  };
846
914
  }
847
915
 
916
+ /* v2.3 (F2): bindTab -- the tab companion to bindAction. Bakes the
917
+ `nac:tab:activated` contract event into the runtime so tab handlers
918
+ don't have to remember to emit it. Same shape, different event
919
+ family. ctx must carry { plugin, tab_id }.
920
+
921
+ Activation event fires nac:tab:activated on document. On handler
922
+ throw or rejected promise, emits nac:tab:activation_failed with
923
+ the same detail shape plus the error message.
924
+
925
+ Like bindAction, listens on 'click' (the canonical user activation).
926
+ Hosts that activate tabs via keyboard or programmatic state must
927
+ dispatch their own click on the element, OR call bindTab with a
928
+ custom activate event (opts.activate_event). */
929
+ function bindTab(el, handler, ctx, opts) {
930
+ if (!el) throw NacError('invalid', 'bindTab: element required');
931
+ if (typeof handler !== 'function') throw NacError('invalid', 'bindTab: handler must be a function');
932
+ if (!ctx || !ctx.plugin || !ctx.tab_id) {
933
+ throw NacError('invalid', 'bindTab: ctx.plugin and ctx.tab_id required');
934
+ }
935
+ const plugin = String(ctx.plugin);
936
+ const tab_id = String(ctx.tab_id);
937
+ const activateEv = (opts && opts.activate_event) || 'click';
938
+
939
+ function emitActivated(ev) {
940
+ document.dispatchEvent(new CustomEvent('nac:tab:activated', {
941
+ detail: {
942
+ plugin: plugin,
943
+ tab_id: tab_id,
944
+ is_trusted: ev ? !!ev.isTrusted : false
945
+ }
946
+ }));
947
+ }
948
+ function emitFailure(ev, err) {
949
+ document.dispatchEvent(new CustomEvent('nac:tab:activation_failed', {
950
+ detail: {
951
+ plugin: plugin,
952
+ tab_id: tab_id,
953
+ is_trusted: ev ? !!ev.isTrusted : false,
954
+ error: (err && err.message) || String(err)
955
+ }
956
+ }));
957
+ }
958
+
959
+ function listener(ev) {
960
+ let result;
961
+ try {
962
+ result = handler.call(el, ev);
963
+ } catch (err) {
964
+ emitFailure(ev, err);
965
+ throw err;
966
+ }
967
+ if (result && typeof result.then === 'function') {
968
+ result.then(
969
+ function () { emitActivated(ev); },
970
+ function (err) { emitFailure(ev, err); }
971
+ );
972
+ } else {
973
+ emitActivated(ev);
974
+ }
975
+ }
976
+
977
+ el.addEventListener(activateEv, listener);
978
+ return function unbind() {
979
+ el.removeEventListener(activateEv, listener);
980
+ };
981
+ }
982
+
848
983
  /* ===================================================================
849
984
  v2.3 PREVIEW (V23-01) -- Field editor primitive.
850
985
 
@@ -956,8 +1091,8 @@
956
1091
  if (_manifests['nac_editor']) return;
957
1092
  register({
958
1093
  plugin_slug: 'nac_editor',
959
- version: '2.3.0-preview',
960
- nac_version: '2.2', /* runtime is 2.2; primitive is v2.3 preview */
1094
+ version: '2.3.0',
1095
+ nac_version: '2.3', /* primitive promoted from preview to GA in v2.3 stable (F4) */
961
1096
  elements: [
962
1097
  { id: 'nac_editor.modal', role: 'region',
963
1098
  label_i18n: { es:'Editor de campo',en:'Field editor',pt:'Editor',fr:'Editeur',
@@ -996,16 +1131,16 @@
996
1131
  actions: [{ verb: 'delete_selection',
997
1132
  label_i18n: { es:'Borrar seleccion',en:'Delete selection',pt:'Apagar selecao',
998
1133
  fr:'Supprimer selection',it:'Elimina selezione',de:'Auswahl loeschen',
999
- ja:'選択削除',zh:'删除选择',hi:'chuna hatao',ar:'حذف التحديد' } }],
1134
+ ja:'選択範囲を削除',zh:'删除所选',hi:'chuna hua hatao',ar:'حذف التحديد' } }],
1000
1135
  label_i18n: { es:'Borrar',en:'Delete',pt:'Apagar',fr:'Supprimer',it:'Elimina',
1001
1136
  de:'Loeschen',ja:'削除',zh:'删除',hi:'hatao',ar:'حذف' } },
1002
1137
  { id: 'nac_editor.ai_correct_syntax', role: 'action',
1003
1138
  actions: [{ verb: 'ai_correct_syntax',
1004
- label_i18n: { es:'Corregir con IA',en:'AI correct',pt:'Corrigir IA',
1005
- fr:'Corriger IA',it:'Correggi IA',de:'KI korrigieren',
1006
- ja:'AI修正',zh:'AI修正',hi:'AI sudhar',ar:'تصحيح AI' } }],
1007
- label_i18n: { es:'IA','en':'AI',pt:'IA',fr:'IA',it:'IA',
1008
- de:'KI',ja:'AI',zh:'AI',hi:'AI',ar:'AI' } },
1139
+ label_i18n: { es:'Corregir con IA',en:'AI correct',pt:'Corrigir com IA',
1140
+ fr:'Corriger avec IA',it:'Correggi con IA',de:'KI korrigieren',
1141
+ ja:'AI校正',zh:'AI校正',hi:'AI se sudhar',ar:'تصحيح بالذكاء الاصطناعي' } }],
1142
+ label_i18n: { es:'IA',en:'AI',pt:'IA',fr:'IA',it:'IA',
1143
+ de:'KI',ja:'AI',zh:'AI',hi:'AI',ar:'ذكاء' } },
1009
1144
  { id: 'nac_editor.save', role: 'action',
1010
1145
  actions: [{ verb: 'save',
1011
1146
  label_i18n: { es:'Guardar','en':'Save',pt:'Salvar',fr:'Sauver',it:'Salva',
@@ -1430,10 +1565,116 @@
1430
1565
 
1431
1566
  /* ---------- Element discovery ----------------------------------- */
1432
1567
 
1568
+ /* ---------- v2.3 shadow DOM resolution (F1 + F6) ----------
1569
+ Walks open shadow roots recursively (cap depth=10) and delegates
1570
+ to el.nac3.query/queryAll on closed shadow hosts that opted in.
1571
+ Errors are emitted as nac:shadow_blocked / nac:shadow_protocol_violation
1572
+ events, each at most once per host (tracked via WeakSet). Existing
1573
+ light-DOM callsites are unaffected; the helpers are strict supersets
1574
+ of the previous document.querySelectorAll('[data-nac-id]') call. */
1575
+ const _SHADOW_DEPTH_CAP = 10;
1576
+ const _shadowBlockedEmitted = new WeakSet();
1577
+ const _shadowProtocolViolated = new WeakSet();
1578
+
1579
+ function _emitShadowBlocked(host, reason) {
1580
+ if (!host || _shadowBlockedEmitted.has(host)) return;
1581
+ _shadowBlockedEmitted.add(host);
1582
+ try {
1583
+ const ev = new CustomEvent('nac:shadow_blocked', {
1584
+ bubbles: true,
1585
+ composed: true,
1586
+ detail: { host: host, reason: reason, ts: Date.now() }
1587
+ });
1588
+ (host.dispatchEvent ? host : document).dispatchEvent(ev);
1589
+ } catch (_) {}
1590
+ }
1591
+ function _emitShadowProtocolViolation(host, message, value) {
1592
+ if (!host || _shadowProtocolViolated.has(host)) return;
1593
+ _shadowProtocolViolated.add(host);
1594
+ try {
1595
+ const ev = new CustomEvent('nac:shadow_protocol_violation', {
1596
+ bubbles: true,
1597
+ composed: true,
1598
+ detail: { host: host, message: message,
1599
+ value_snapshot: (function () {
1600
+ try { return typeof value === 'object' ? '[object]' : String(value).slice(0, 80); }
1601
+ catch (_) { return '[unprintable]'; } })(), ts: Date.now() }
1602
+ });
1603
+ (host.dispatchEvent ? host : document).dispatchEvent(ev);
1604
+ } catch (_) {}
1605
+ }
1606
+
1607
+ function _deepQueryAll(selector, root, depth) {
1608
+ root = root || document;
1609
+ depth = depth || 0;
1610
+ let out = [];
1611
+ /* Direct match on this root. */
1612
+ try {
1613
+ if (root.querySelectorAll) {
1614
+ out = Array.prototype.slice.call(root.querySelectorAll(selector));
1615
+ }
1616
+ } catch (_) {}
1617
+ if (depth >= _SHADOW_DEPTH_CAP) return out;
1618
+ /* Walk every element under root looking for shadow boundaries. */
1619
+ let walk;
1620
+ try {
1621
+ walk = root.querySelectorAll ? root.querySelectorAll('*') : [];
1622
+ } catch (_) { walk = []; }
1623
+ for (let i = 0; i < walk.length; i++) {
1624
+ const el = walk[i];
1625
+ /* Open shadow root: recurse. */
1626
+ if (el.shadowRoot) {
1627
+ const inner = _deepQueryAll(selector, el.shadowRoot, depth + 1);
1628
+ if (inner.length) out = out.concat(inner);
1629
+ continue;
1630
+ }
1631
+ /* Closed shadow root with voluntary exposure API. */
1632
+ const nac3 = el.nac3;
1633
+ if (nac3 && typeof nac3 === 'object') {
1634
+ try {
1635
+ if (typeof nac3.queryAll === 'function') {
1636
+ const raw = nac3.queryAll(selector);
1637
+ if (Array.isArray(raw)) {
1638
+ const valid = [];
1639
+ for (let k = 0; k < raw.length; k++) {
1640
+ const n = raw[k];
1641
+ if (n && n.nodeType === 1) valid.push(n);
1642
+ else _emitShadowProtocolViolation(el,
1643
+ 'nac3.queryAll returned non-Element item', n);
1644
+ }
1645
+ if (valid.length) out = out.concat(valid);
1646
+ } else if (raw != null) {
1647
+ _emitShadowProtocolViolation(el,
1648
+ 'nac3.queryAll did not return an array', raw);
1649
+ }
1650
+ } else if (typeof nac3.query === 'function') {
1651
+ const one = nac3.query(selector);
1652
+ if (one && one.nodeType === 1) out.push(one);
1653
+ else if (one != null) {
1654
+ _emitShadowProtocolViolation(el,
1655
+ 'nac3.query returned non-Element value', one);
1656
+ }
1657
+ }
1658
+ } catch (e) {
1659
+ _emitShadowBlocked(el, 'exposure_threw');
1660
+ }
1661
+ } else if (el.hasAttribute && el.hasAttribute('data-nac-shadow')
1662
+ && el.getAttribute('data-nac-shadow') === 'closed') {
1663
+ /* Element explicitly declared as closed-shadow with no exposure
1664
+ API. Per spec sec 5.1.6, this is a deliberate opt-out;
1665
+ emit shadow_blocked once so debugging tooling sees it. */
1666
+ _emitShadowBlocked(el, 'not_exposed');
1667
+ }
1668
+ }
1669
+ return out;
1670
+ }
1671
+ function _deepQuery(selector, root) {
1672
+ const all = _deepQueryAll(selector, root, 0);
1673
+ return all.length ? all[0] : null;
1674
+ }
1675
+
1433
1676
  function _allElements() {
1434
- return Array.prototype.slice.call(
1435
- document.querySelectorAll('[data-nac-id]')
1436
- );
1677
+ return _deepQueryAll('[data-nac-id]', document, 0);
1437
1678
  }
1438
1679
 
1439
1680
  function _activePlugin() {
@@ -1828,6 +2069,25 @@
1828
2069
  });
1829
2070
  throw NacError('disabled', 'Element ' + nac_id + ' is disabled');
1830
2071
  }
2072
+ /* v2.3 (F7): capability gate. If the action declares
2073
+ requires_capability and the current user set does not satisfy
2074
+ it, reject before dispatch with code='capability_required'. */
2075
+ {
2076
+ const reqCap = _resolveCapability(nac_id, null);
2077
+ if (reqCap && !_hasCapability(reqCap)) {
2078
+ _emitCommandRejected({
2079
+ command_method: 'click',
2080
+ command_target: nac_id,
2081
+ reason: 'capability_required',
2082
+ message: 'Element ' + nac_id + ' requires capability ' +
2083
+ (Array.isArray(reqCap) ? '[' + reqCap.join(',') + ']' : reqCap),
2084
+ source: (opts && opts.source) || undefined,
2085
+ });
2086
+ throw NacError('capability_required',
2087
+ 'Element ' + nac_id + ' requires capability ' +
2088
+ (Array.isArray(reqCap) ? '[' + reqCap.join(',') + ']' : reqCap));
2089
+ }
2090
+ }
1831
2091
  /* v1.8.0: hidden-target rejection. A button inside display:none
1832
2092
  or aria-hidden="true" is not a click target a user could reach;
1833
2093
  sec 6.2.28 requires us to surface this rather than fire silently.
@@ -2252,24 +2512,38 @@
2252
2512
  });
2253
2513
  throw NacError('not_found', 'No element with nac_id=' + action_id);
2254
2514
  }
2255
- /* invoke deliberately does NOT enforce visibility -- the
2256
- canonical use case is a mic / search / upload widget that
2257
- may live outside the visible viewport but is still a valid
2258
- NAC target (the agent never had to "see" it to use it).
2259
- Disabled state is still respected. */
2260
- if (el.disabled || el.getAttribute('aria-disabled') === 'true') {
2261
- _emitCommandRejected({
2262
- command_method: 'invoke',
2263
- command_target: action_id,
2264
- reason: 'disabled',
2265
- message: 'Element ' + action_id + ' is disabled',
2266
- source: (opts && opts.source) || undefined,
2267
- });
2268
- throw NacError('disabled', 'Element ' + action_id + ' is disabled');
2269
- }
2515
+ /* invoke deliberately does NOT enforce visibility OR disabled --
2516
+ the canonical use case is a mic / search / upload widget
2517
+ that may live outside the visible viewport or be visually
2518
+ disabled while a previous request is processing, but is
2519
+ still a valid NAC target (the agent's request is a logical
2520
+ message, not a synthetic click). Hosts that need to refuse
2521
+ an invoke based on UI state should do it in their
2522
+ nac:action:requested listener and emit nac:action:failed
2523
+ with a meaningful error code. */
2270
2524
  const verb = (payload && payload.verb)
2271
2525
  || el.getAttribute('data-nac-action')
2272
2526
  || '';
2527
+ /* v2.3 (F7): capability gate. Unlike disabled, capabilities ARE
2528
+ enforced on invoke -- a missing permission is not a UI state
2529
+ issue, it is a logical authorization failure that should
2530
+ short-circuit BEFORE the host's listener even hears about it. */
2531
+ {
2532
+ const reqCap = _resolveCapability(action_id, verb);
2533
+ if (reqCap && !_hasCapability(reqCap)) {
2534
+ _emitCommandRejected({
2535
+ command_method: 'invoke',
2536
+ command_target: action_id,
2537
+ reason: 'capability_required',
2538
+ message: 'Action ' + action_id + ' (verb=' + verb + ') requires capability ' +
2539
+ (Array.isArray(reqCap) ? '[' + reqCap.join(',') + ']' : reqCap),
2540
+ source: (opts && opts.source) || undefined,
2541
+ });
2542
+ throw NacError('capability_required',
2543
+ 'Action ' + action_id + ' (verb=' + verb + ') requires capability ' +
2544
+ (Array.isArray(reqCap) ? '[' + reqCap.join(',') + ']' : reqCap));
2545
+ }
2546
+ }
2273
2547
  const pluginRoot = el.closest('[data-nac-plugin]');
2274
2548
  const plugin = pluginRoot
2275
2549
  ? pluginRoot.getAttribute('data-nac-plugin')
@@ -3592,6 +3866,12 @@
3592
3866
  }
3593
3867
  }
3594
3868
  function _byId(id) {
3869
+ /* v2.3: deep-aware. Walks open shadow roots + closed-shadow
3870
+ exposure API. Falls back to document.querySelector when
3871
+ the deep helper is unavailable (defensive). */
3872
+ if (typeof _deepQuery === 'function') {
3873
+ return _deepQuery('[data-nac-id="' + id + '"]', document);
3874
+ }
3595
3875
  return document.querySelector('[data-nac-id="' + id + '"]');
3596
3876
  }
3597
3877
 
@@ -5158,14 +5438,17 @@
5158
5438
 
5159
5439
  global.NAC = {
5160
5440
  __nac_v1_installed: true,
5161
- version: '2.3.0-alpha.1',
5441
+ version: '2.3.0',
5162
5442
  spec_version: '2.3',
5163
5443
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
5164
5444
  NAC.register throws on findings (manifest_role_unknown,
5165
5445
  tab_id_manifest_role_drift, manifest_dom_role_mismatch).
5166
5446
  Default false in v2.2 (warning-only) for the migration
5167
- window; v2.3 default flips to true; v3.0 removes the flag. */
5168
- STRICT_VALIDATION: false,
5447
+ window; v2.3 stable flips default to true (F3); v3.0 removes
5448
+ the flag. Opt-out: set NAC.STRICT_VALIDATION = false in your
5449
+ bootstrap before any register() call. See
5450
+ guides/MIGRATION_v2.2_to_v2.3.md. */
5451
+ STRICT_VALIDATION: true,
5169
5452
  /* registry */
5170
5453
  register: register,
5171
5454
  unregister: unregister,
@@ -5185,6 +5468,16 @@
5185
5468
  Removes the brownfield foot-gun where panels forget to emit
5186
5469
  the contract event and NAC.click() times out spuriously. */
5187
5470
  bindAction: bindAction,
5471
+ bindTab: bindTab,
5472
+ /* v2.3 (F7): auth-aware capabilities. setCapabilities replaces
5473
+ the user's full set; grant/revoke for incremental updates;
5474
+ userCapabilities returns a snapshot array. NAC.click and
5475
+ NAC.invoke gate against this set when the manifest entry
5476
+ declares requires_capability. */
5477
+ setCapabilities: setCapabilities,
5478
+ grantCapability: grantCapability,
5479
+ revokeCapability: revokeCapability,
5480
+ userCapabilities: userCapabilities,
5188
5481
  /* v2.3.0 PREVIEW (V23-01) -- field editor primitive. Opens a
5189
5482
  Word-style modal on any field, with select/replace/delete/
5190
5483
  AI-syntax-correct verbs all NAC-3 callable. The modal