@egen-civitas/esm-embed-host 0.9.0 → 0.10.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @egen-civitas/esm-embed-host
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 259cae8: Événements étendus (B6), additifs : `publish(topic, payload, { to, correlationId, v })`, abonnement enveloppe `events.on` (`EgenEvent` avec `meta.source` posé par le Shell, non falsifiable), `once`, `request`/`respond` (corrélation, délai 10 s, `TIMEOUT`), `define` (sujets typés validés localement). L'hôte applique le ciblage `to` et fournit le bus de référence `createEventBus`. Les fournisseurs et clients plus anciens restent compatibles (`source` vaut `unknown` sans `meta` du fournisseur ; `subscribe` historique inchangé).
8
+ - 186ccfa: Notifications et dialogues étendus (B7), additifs : `notifications.show` renvoie une poignée `{ id, displayed, closed, dismiss }` (`closed` : `user | timeout | api | deduplicated`, jamais pendante) ; `notifications.dismiss` ; action de toast `{ label, topic }` (le Shell publie `topic` sur le bus, aucun code exécuté) ; `dialogs.alert` (servie seulement si le Core la fournit, pas de `prompt`). Nouveau contrat fournisseur optionnel `NotificationShown` (`closed`, `dismiss`) et `dialogs.alert`.
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies [259cae8]
13
+ - Updated dependencies [186ccfa]
14
+ - @egen-civitas/esm-embed-protocol@0.10.0
15
+
3
16
  ## 0.9.0
4
17
 
5
18
  ### Minor Changes
@@ -0,0 +1,13 @@
1
+ import type { PublishOptions } from '@egen-civitas/esm-embed-protocol';
2
+ import type { HostProviders } from './providers.js';
3
+ export type ShellEventBus = NonNullable<HostProviders['events']> & {
4
+ /** Publication par le Shell lui-même : `meta.source` vaut `shell`. */
5
+ publishAsShell(topic: string, payload?: unknown, options?: PublishOptions): void;
6
+ };
7
+ /**
8
+ * « Shell Event Bus » de référence (spec §5) : en mémoire, éphémère, propre à l'onglet, sans garantie de livraison inter-onglets.
9
+ * Il pose lui-même `meta.source` (depuis le `ctx` de la connexion approuvée, jamais depuis le message) et transmet `to`,
10
+ * que l'hôte applique à la livraison. Un abonné reçoit aussi ses propres publications, comme le pont `egen:event` du Core.
11
+ */
12
+ export declare function createEventBus(now?: () => number): ShellEventBus;
13
+ //# sourceMappingURL=event-bus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../src/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,KAAK,EAA8B,aAAa,EAAS,MAAM,gBAAgB,CAAC;AAEvF,MAAM,MAAM,aAAa,GAAG,WAAW,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,GAAG;IACjE,sEAAsE;IACtE,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CAClF,CAAC;AAQF;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,GAAE,MAAM,MAAyB,GAAG,aAAa,CAiClF"}
@@ -0,0 +1,123 @@
1
+ function _array_like_to_array(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _array_without_holes(arr) {
7
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
8
+ }
9
+ function _define_property(obj, key, value) {
10
+ if (key in obj) {
11
+ Object.defineProperty(obj, key, {
12
+ value: value,
13
+ enumerable: true,
14
+ configurable: true,
15
+ writable: true
16
+ });
17
+ } else {
18
+ obj[key] = value;
19
+ }
20
+ return obj;
21
+ }
22
+ function _iterable_to_array(iter) {
23
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
24
+ }
25
+ function _non_iterable_spread() {
26
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
27
+ }
28
+ function _object_spread(target) {
29
+ for(var i = 1; i < arguments.length; i++){
30
+ var source = arguments[i] != null ? arguments[i] : {};
31
+ var ownKeys = Object.keys(source);
32
+ if (typeof Object.getOwnPropertySymbols === "function") {
33
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
34
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
35
+ }));
36
+ }
37
+ ownKeys.forEach(function(key) {
38
+ _define_property(target, key, source[key]);
39
+ });
40
+ }
41
+ return target;
42
+ }
43
+ function _to_consumable_array(arr) {
44
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
45
+ }
46
+ function _unsupported_iterable_to_array(o, minLen) {
47
+ if (!o) return;
48
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
49
+ var n = Object.prototype.toString.call(o).slice(8, -1);
50
+ if (n === "Object" && o.constructor) n = o.constructor.name;
51
+ if (n === "Map" || n === "Set") return Array.from(n);
52
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
53
+ }
54
+ var seq = 0;
55
+ var newId = function newId() {
56
+ var c = globalThis.crypto;
57
+ return (c === null || c === void 0 ? void 0 : c.randomUUID) ? c.randomUUID() : "evt-".concat(Date.now().toString(36), "-").concat((++seq).toString(36));
58
+ };
59
+ /**
60
+ * « Shell Event Bus » de référence (spec §5) : en mémoire, éphémère, propre à l'onglet, sans garantie de livraison inter-onglets.
61
+ * Il pose lui-même `meta.source` (depuis le `ctx` de la connexion approuvée, jamais depuis le message) et transmet `to`,
62
+ * que l'hôte applique à la livraison. Un abonné reçoit aussi ses propres publications, comme le pont `egen:event` du Core.
63
+ */ export function createEventBus() {
64
+ var now = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : function() {
65
+ return Date.now();
66
+ };
67
+ var subs = new Map();
68
+ var deliver = function deliver(topic, payload, meta) {
69
+ var _subs_get;
70
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
71
+ try {
72
+ for(var _iterator = _to_consumable_array((_subs_get = subs.get(topic)) !== null && _subs_get !== void 0 ? _subs_get : [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
73
+ var cb = _step.value;
74
+ try {
75
+ cb(payload, meta);
76
+ } catch (unused) {
77
+ /* un abonné fautif ne bloque pas les autres */ }
78
+ }
79
+ } catch (err) {
80
+ _didIteratorError = true;
81
+ _iteratorError = err;
82
+ } finally{
83
+ try {
84
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
85
+ _iterator.return();
86
+ }
87
+ } finally{
88
+ if (_didIteratorError) {
89
+ throw _iteratorError;
90
+ }
91
+ }
92
+ }
93
+ };
94
+ var metaOf = function metaOf(source, o) {
95
+ return _object_spread({
96
+ id: newId(),
97
+ source: source,
98
+ ts: now()
99
+ }, (o === null || o === void 0 ? void 0 : o.v) !== undefined ? {
100
+ v: o.v
101
+ } : {}, (o === null || o === void 0 ? void 0 : o.correlationId) !== undefined ? {
102
+ correlationId: o.correlationId
103
+ } : {}, (o === null || o === void 0 ? void 0 : o.to) !== undefined ? {
104
+ to: o.to
105
+ } : {});
106
+ };
107
+ return {
108
+ publish: function publish(topic, payload, ctx, options) {
109
+ deliver(topic, payload, metaOf(ctx.moduleName, options));
110
+ },
111
+ publishAsShell: function publishAsShell(topic, payload, options) {
112
+ deliver(topic, payload, metaOf('shell', options));
113
+ },
114
+ subscribe: function subscribe(topic, cb) {
115
+ var set = subs.get(topic);
116
+ if (!set) subs.set(topic, set = new Set());
117
+ set.add(cb);
118
+ return function() {
119
+ return void set.delete(cb);
120
+ };
121
+ }
122
+ };
123
+ }
package/dist/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export * from './table.js';
4
4
  export * from './connection.js';
5
5
  export * from './navigation.js';
6
6
  export * from './host.js';
7
+ export * from './event-bus.js';
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -4,3 +4,4 @@ export * from './table.js';
4
4
  export * from './connection.js';
5
5
  export * from './navigation.js';
6
6
  export * from './host.js';
7
+ export * from './event-bus.js';
@@ -1,13 +1,31 @@
1
+ import type { NotificationCloseReason, PublishOptions } from '@egen-civitas/esm-embed-protocol';
1
2
  export type Unsub = () => void;
2
3
  /** Valeur lisible et observable fournie par le Core. */
3
4
  export interface Watchable<T> {
4
5
  get(): T | Promise<T>;
5
6
  subscribe?(cb: (value: T) => void): Unsub;
6
7
  }
8
+ /** Métadonnées fournies par le bus avec chaque événement livré. */
9
+ export interface EventMetaIn {
10
+ id?: string;
11
+ source?: string;
12
+ ts?: number;
13
+ v?: number;
14
+ correlationId?: string;
15
+ to?: string;
16
+ }
7
17
  export interface CallerContext {
8
18
  /** Nom du module de l'app appelante (non falsifiable : porté par la connexion, pas par le message). */
9
19
  moduleName: string;
10
20
  }
21
+ /** Ce que le Core peut renvoyer de `show` pour suivre son toast (tout est optionnel : renvoyer `void`/`boolean` reste valide). */
22
+ export interface NotificationShown {
23
+ displayed?: boolean;
24
+ /** Résolue à la fermeture du toast, avec sa cause. Absente : l'hôte estime la fermeture à `timeoutMs` (6 s par défaut). */
25
+ closed?: Promise<NotificationCloseReason>;
26
+ /** Ferme le toast sur demande de l'app (`dismiss`). */
27
+ dismiss?: () => void;
28
+ }
11
29
  export interface NotificationInput {
12
30
  /** Clé de dédoublonnage facultative : un même `id` ne produit pas deux toasts rapprochés. */
13
31
  id?: string;
@@ -15,6 +33,11 @@ export interface NotificationInput {
15
33
  title: string;
16
34
  subtitle?: string;
17
35
  timeoutMs?: number;
36
+ /** Bouton du toast : le Shell publie `topic` sur le bus d'événements (aucun code n'est exécuté). */
37
+ action?: {
38
+ label: string;
39
+ topic: string;
40
+ };
18
41
  }
19
42
  export interface ExtensionInfo {
20
43
  name: string;
@@ -39,13 +62,18 @@ export interface HostProviders {
39
62
  isEnabled(name: string): boolean | Promise<boolean>;
40
63
  subscribe?(cb: () => void): Unsub;
41
64
  };
65
+ /**
66
+ * Bus d'événements du Shell. `publish`/`subscribe` historiques inchangés ; les paramètres ajoutés sont optionnels (un fournisseur
67
+ * plus ancien qui les ignore reste valide : `meta.source` vaut alors `unknown`, `to` n'est pas appliqué).
68
+ * Le fournisseur DOIT poser `source` lui-même (depuis `ctx.moduleName`, jamais depuis la charge utile).
69
+ */
42
70
  events?: {
43
- publish(topic: string, payload: unknown, ctx: CallerContext): void;
44
- subscribe(topic: string, cb: (payload: unknown) => void): Unsub;
71
+ publish(topic: string, payload: unknown, ctx: CallerContext, options?: PublishOptions): void;
72
+ subscribe(topic: string, cb: (payload: unknown, meta?: EventMetaIn) => void, ctx?: CallerContext): Unsub;
45
73
  };
46
74
  /** Affiche le toast dans l'interface du Core ; retourne `false` si non affiché (doublon, etc.). Le Core attribue le toast à son app d'origine. */
47
75
  notifications?: {
48
- show(n: NotificationInput, ctx: CallerContext): void | boolean | Promise<void | boolean>;
76
+ show(n: NotificationInput, ctx: CallerContext): void | boolean | NotificationShown | Promise<void | boolean | NotificationShown>;
49
77
  };
50
78
  dialogs?: {
51
79
  confirm(d: {
@@ -53,6 +81,11 @@ export interface HostProviders {
53
81
  message: string;
54
82
  danger?: boolean;
55
83
  }, ctx: CallerContext): boolean | Promise<boolean>;
84
+ /** Information à acquitter. Absente : `dialogs.alert` n'est pas servie (`UNKNOWN_METHOD`) — jamais simulée par un `confirm`. */
85
+ alert?(d: {
86
+ title: string;
87
+ message: string;
88
+ }, ctx: CallerContext): void | Promise<void>;
56
89
  };
57
90
  /** Extensions attachées à un slot du Core (apps internes, framework, autres apps) : métadonnées seulement, jamais le rendu. */
58
91
  extensions?: {
@@ -1 +1 @@
1
- {"version":3,"file":"providers.d.ts","sourceRoot":"","sources":["../src/providers.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC;AAE/B,wDAAwD;AACxD,MAAM,WAAW,SAAS,CAAC,CAAC;IAC1B,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACtB,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,GAAG,KAAK,CAAC;CAC3C;AAED,MAAM,WAAW,aAAa;IAC5B,uGAAuG;IACvG,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAChC,6FAA6F;IAC7F,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,OAAO,CAAC;IAC/C,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAA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AC,EAAE,eAAe,GAAG,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACjI,6FAA6F;IAC7F,QAAQ,CAAC,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,MAAM,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,OAAO,CAAC,IAAI,IAAI,CAAC;IACjB,6DAA6D;IAC7D,OAAO,EAAE,GAAG,CAAC;CACd;AAED,8HAA8H;AAC9H,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,aAAa,GAAG,GAAG,CAAC,YAAY,CAAC,CAczE;AAID,MAAM,WAAW,YAAY;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,iBAAiB,EAAE,CAAC;IAC7B,SAAS,EAAE,aAAa,CAAC;IACzB,QAAQ,EAAE,YAAY,CAAC;CACxB;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,YAAY,GAAG;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,gBAAgB,CAAA;CAAE,CAkJ3G"}
package/dist/table.js CHANGED
@@ -117,6 +117,10 @@ function _object_spread_props(target, source) {
117
117
  function _sliced_to_array(arr, i) {
118
118
  return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
119
119
  }
120
+ function _type_of(obj) {
121
+ "@swc/helpers - typeof";
122
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
123
+ }
120
124
  function _unsupported_iterable_to_array(o, minLen) {
121
125
  if (!o) return;
122
126
  if (typeof o === "string") return _array_like_to_array(o, minLen);
@@ -371,9 +375,10 @@ var list = function list(cfg, key) {
371
375
  if (cfgOf.has('events') && p.events) {
372
376
  var pub = list(cfgOf.get('events'), 'publish');
373
377
  table.events = {
374
- publish: function publish(topic, payload) {
378
+ publish: function publish(topic, payload, options) {
375
379
  if (!topicAllowed(pub, topic)) throw denied("Publication non autoris\xe9e sur : ".concat(topic));
376
- p.events.publish(topic, payload, ctx);
380
+ if (options === undefined) p.events.publish(topic, payload, ctx);
381
+ else p.events.publish(topic, payload, ctx, options);
377
382
  }
378
383
  };
379
384
  }
@@ -381,50 +386,118 @@ var list = function list(cfg, key) {
381
386
  // Anti-spam : une iframe ne doit pas pouvoir inonder l'interface du Core (ni imiter des messages système en rafale).
382
387
  var policy = notificationPolicy(cfgOf.get('notifications'));
383
388
  var allow = createSlidingLimiter(policy.rate.max, policy.rate.perSeconds);
389
+ var open = new Map(); // toasts encore ouverts de cette app, par id
384
390
  table.notifications = {
385
391
  show: function show(n) {
386
392
  return _async_to_generator(function() {
387
- var _tmp;
393
+ var _n_id, r, shown, id, settled, timer, finish, handle, _timer_unref;
388
394
  return _ts_generator(this, function(_state) {
389
395
  switch(_state.label){
390
396
  case 0:
391
397
  if (!allow()) throw new EmbedError('RATE_LIMITED', 'Trop de notifications');
392
- _tmp = {};
393
398
  return [
394
399
  4,
395
400
  p.notifications.show(n, ctx)
396
401
  ];
397
402
  case 1:
403
+ r = _state.sent();
404
+ shown = r !== null && (typeof r === "undefined" ? "undefined" : _type_of(r)) === 'object' ? r : {};
405
+ id = (_n_id = n.id) !== null && _n_id !== void 0 ? _n_id : "n-".concat(++toastSeq);
406
+ if (r === false || shown.displayed === false) return [
407
+ 2,
408
+ {
409
+ displayed: false,
410
+ id: id,
411
+ reason: 'deduplicated'
412
+ }
413
+ ];
414
+ settled = false;
415
+ finish = function finish(reason) {
416
+ if (settled) return;
417
+ settled = true;
418
+ if (timer) clearTimeout(timer);
419
+ if (open.get(id) === handle) open.delete(id);
420
+ c.channel.emit('notifications.closed', {
421
+ id: id,
422
+ reason: reason
423
+ });
424
+ };
425
+ handle = {
426
+ dismiss: function dismiss() {
427
+ var _shown_dismiss;
428
+ return (_shown_dismiss = shown.dismiss) === null || _shown_dismiss === void 0 ? void 0 : _shown_dismiss.call(shown), finish('api');
429
+ }
430
+ };
431
+ open.set(id, handle);
432
+ if (shown.closed) shown.closed.then(finish, function() {
433
+ return finish('api');
434
+ });
435
+ else {
436
+ ;
437
+ // Le Core ne dit pas quand le toast se ferme : fermeture estimée à `timeoutMs` (la promesse `closed` n'est jamais pendante).
438
+ timer = setTimeout(function() {
439
+ return finish('timeout');
440
+ }, n.timeoutMs || DEFAULT_TOAST_MS);
441
+ (_timer_unref = timer.unref) === null || _timer_unref === void 0 ? void 0 : _timer_unref.call(timer);
442
+ }
398
443
  return [
399
444
  2,
400
- (_tmp.displayed = _state.sent() !== false, _tmp)
445
+ {
446
+ displayed: true,
447
+ id: id
448
+ }
401
449
  ];
402
450
  }
403
451
  });
404
452
  })();
453
+ },
454
+ dismiss: function dismiss(id) {
455
+ var _open_get;
456
+ return (_open_get = open.get(id)) === null || _open_get === void 0 ? void 0 : _open_get.dismiss();
405
457
  }
406
458
  };
407
459
  }
408
- if (cfgOf.has('dialogs') && p.dialogs) table.dialogs = {
409
- confirm: function confirm(d) {
410
- return _async_to_generator(function() {
411
- return _ts_generator(this, function(_state) {
412
- switch(_state.label){
413
- case 0:
414
- return [
415
- 4,
416
- p.dialogs.confirm(d, ctx)
417
- ];
418
- case 1:
419
- return [
420
- 2,
421
- !!_state.sent()
422
- ];
423
- }
424
- });
425
- })();
426
- }
427
- };
460
+ if (cfgOf.has('dialogs') && p.dialogs) {
461
+ table.dialogs = _object_spread({
462
+ confirm: function confirm(d) {
463
+ return _async_to_generator(function() {
464
+ return _ts_generator(this, function(_state) {
465
+ switch(_state.label){
466
+ case 0:
467
+ return [
468
+ 4,
469
+ p.dialogs.confirm(d, ctx)
470
+ ];
471
+ case 1:
472
+ return [
473
+ 2,
474
+ !!_state.sent()
475
+ ];
476
+ }
477
+ });
478
+ })();
479
+ }
480
+ }, p.dialogs.alert ? {
481
+ alert: function alert(d) {
482
+ return _async_to_generator(function() {
483
+ return _ts_generator(this, function(_state) {
484
+ switch(_state.label){
485
+ case 0:
486
+ return [
487
+ 4,
488
+ p.dialogs.alert(d, ctx)
489
+ ];
490
+ case 1:
491
+ return [
492
+ 2,
493
+ void _state.sent()
494
+ ];
495
+ }
496
+ });
497
+ })();
498
+ }
499
+ } : {});
500
+ }
428
501
  if (cfgOf.has('extensions') && p.extensions) {
429
502
  var discover = list(cfgOf.get('extensions'), 'discover');
430
503
  table.extensions = {
@@ -526,7 +599,30 @@ var list = function list(cfg, key) {
526
599
  var cfg = cfgOf.get(cap);
527
600
  var desc = CAPABILITIES[cap];
528
601
  if (!cfg || !desc || !table[cap]) return undefined;
529
- if (cap === 'events') return topicAllowed(list(cfg, 'subscribe'), ev) ? p.events.subscribe(ev, emit) : undefined;
602
+ if (cap === 'events') {
603
+ // `@sujet` : abonnement « enveloppe » (EgenEvent avec meta) ; `sujet` : charge utile seule (clients historiques).
604
+ var envelope = ev.startsWith('@');
605
+ var topic = envelope ? ev.slice(1) : ev;
606
+ if (!topicAllowed(list(cfg, 'subscribe'), topic)) return undefined;
607
+ return p.events.subscribe(topic, function(payload, meta) {
608
+ var _ref, _ref1, _ref2;
609
+ if ((meta === null || meta === void 0 ? void 0 : meta.to) !== undefined && meta.to !== ctx.moduleName) return; // ciblage : les autres apps ne reçoivent rien
610
+ if (!envelope) return emit(payload);
611
+ emit({
612
+ topic: topic,
613
+ payload: payload,
614
+ meta: _object_spread({
615
+ id: (_ref = meta === null || meta === void 0 ? void 0 : meta.id) !== null && _ref !== void 0 ? _ref : randomId(),
616
+ source: (_ref1 = meta === null || meta === void 0 ? void 0 : meta.source) !== null && _ref1 !== void 0 ? _ref1 : 'unknown',
617
+ ts: (_ref2 = meta === null || meta === void 0 ? void 0 : meta.ts) !== null && _ref2 !== void 0 ? _ref2 : Date.now()
618
+ }, (meta === null || meta === void 0 ? void 0 : meta.v) !== undefined ? {
619
+ v: meta.v
620
+ } : {}, (meta === null || meta === void 0 ? void 0 : meta.correlationId) !== undefined ? {
621
+ correlationId: meta.correlationId
622
+ } : {})
623
+ });
624
+ }, ctx);
625
+ }
530
626
  if (cap === 'extensions') return slotAllowed(list(cfg, 'discover'), ev) && p.extensions.subscribe ? p.extensions.subscribe(ev, emit) : undefined;
531
627
  if (!desc.events.includes(ev)) return undefined;
532
628
  switch(cap){
@@ -547,6 +643,8 @@ var list = function list(cfg, key) {
547
643
  case 'navigation':
548
644
  case 'lifecycle':
549
645
  return c.channel.on(ev, emit);
646
+ case 'notifications':
647
+ return c.channel.on('notifications.closed', emit);
550
648
  default:
551
649
  return undefined;
552
650
  }
@@ -556,3 +654,10 @@ var list = function list(cfg, key) {
556
654
  subscribe: subscribe
557
655
  };
558
656
  }
657
+ var toastSeq = 0;
658
+ var DEFAULT_TOAST_MS = 6000;
659
+ var idSeq = 0;
660
+ /** Identifiant d'événement quand le bus n'en fournit pas : unique pour la session de l'hôte. */ function randomId() {
661
+ var c = globalThis.crypto;
662
+ return (c === null || c === void 0 ? void 0 : c.randomUUID) ? c.randomUUID() : "evt-".concat(Date.now().toString(36), "-").concat((++idSeq).toString(36));
663
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egen-civitas/esm-embed-host",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Hôte (côté Shell/Core) des applications embarquées : iframe sécurisée, poignée de main v2, grants, fournisseurs de capacités, navigation partagée, compatibilité du pont 1.1.",
6
6
  "type": "module",
@@ -57,7 +57,7 @@
57
57
  "access": "public"
58
58
  },
59
59
  "devDependencies": {
60
- "@egen-civitas/esm-embed-client": "^0.10.0",
60
+ "@egen-civitas/esm-embed-client": "^0.11.0",
61
61
  "@swc/cli": "0.8.1",
62
62
  "@swc/core": "1.15.21",
63
63
  "@types/node": "^20",
@@ -69,6 +69,6 @@
69
69
  "vitest": "^4.1.2"
70
70
  },
71
71
  "dependencies": {
72
- "@egen-civitas/esm-embed-protocol": "^0.9.0"
72
+ "@egen-civitas/esm-embed-protocol": "^0.10.0"
73
73
  }
74
74
  }
@@ -6,7 +6,8 @@ export const ORIGIN = 'https://shell.exemple.org';
6
6
  export const MODULE = '@acme/esm-demo-app';
7
7
 
8
8
  /** Banc d'essai : un vrai `HostConnection` face au vrai client SDK, reliés par des fenêtres simulées et un vrai MessageChannel. */
9
- export async function harness(opts: { providers?: HostProviders; approved?: ApprovedGrants; requested?: Parameters<typeof connectToEgen>[0]['capabilities']; controls?: Partial<HostControls>; grants?: EffectiveGrants; limits?: ConnectionOptions['limits'] } = {}) {
9
+ export async function harness(opts: { providers?: HostProviders; approved?: ApprovedGrants; requested?: Parameters<typeof connectToEgen>[0]['capabilities']; controls?: Partial<HostControls>; grants?: EffectiveGrants; limits?: ConnectionOptions['limits']; moduleName?: string } = {}) {
10
+ const moduleName = opts.moduleName ?? MODULE;
10
11
  const appWindow = new EventTarget();
11
12
  const hostWindow: any = {
12
13
  postMessage: (message: unknown, targetOrigin: string) => {
@@ -19,7 +20,7 @@ export async function harness(opts: { providers?: HostProviders; approved?: Appr
19
20
  const channel = createBus();
20
21
  const controls: HostControls = { channel, ...opts.controls };
21
22
  const conn: HostConnection = new HostConnection({
22
- moduleName: MODULE,
23
+ moduleName,
23
24
  grants: opts.grants ?? effectiveGrants(undefined, opts.approved ?? {}),
24
25
  providers: opts.providers ?? {},
25
26
  controls,
@@ -34,7 +35,7 @@ export async function harness(opts: { providers?: HostProviders; approved?: Appr
34
35
  },
35
36
  });
36
37
  const client: EgenClient = await new Promise<EgenClient>((resolve) => {
37
- connectToEgen({ moduleName: MODULE, hostOrigins: [ORIGIN], window: appWindow as any, host: hostWindow, capabilities: opts.requested, timeoutMs: 400 }).then(resolve);
38
+ connectToEgen({ moduleName, hostOrigins: [ORIGIN], window: appWindow as any, host: hostWindow, capabilities: opts.requested, timeoutMs: 400 }).then(resolve);
38
39
  });
39
40
  return { client, conn, channel, sentByApp, close: () => (client.close(), conn.destroy()) };
40
41
  }
@@ -0,0 +1,53 @@
1
+ import type { PublishOptions } from '@egen-civitas/esm-embed-protocol';
2
+ import type { CallerContext, EventMetaIn, HostProviders, Unsub } from './providers.js';
3
+
4
+ export type ShellEventBus = NonNullable<HostProviders['events']> & {
5
+ /** Publication par le Shell lui-même : `meta.source` vaut `shell`. */
6
+ publishAsShell(topic: string, payload?: unknown, options?: PublishOptions): void;
7
+ };
8
+
9
+ let seq = 0;
10
+ const newId = () => {
11
+ const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
12
+ return c?.randomUUID ? c.randomUUID() : `evt-${Date.now().toString(36)}-${(++seq).toString(36)}`;
13
+ };
14
+
15
+ /**
16
+ * « Shell Event Bus » de référence (spec §5) : en mémoire, éphémère, propre à l'onglet, sans garantie de livraison inter-onglets.
17
+ * Il pose lui-même `meta.source` (depuis le `ctx` de la connexion approuvée, jamais depuis le message) et transmet `to`,
18
+ * que l'hôte applique à la livraison. Un abonné reçoit aussi ses propres publications, comme le pont `egen:event` du Core.
19
+ */
20
+ export function createEventBus(now: () => number = () => Date.now()): ShellEventBus {
21
+ const subs = new Map<string, Set<(payload: unknown, meta?: EventMetaIn) => void>>();
22
+ const deliver = (topic: string, payload: unknown, meta: EventMetaIn) => {
23
+ for (const cb of [...(subs.get(topic) ?? [])]) {
24
+ try {
25
+ cb(payload, meta);
26
+ } catch {
27
+ /* un abonné fautif ne bloque pas les autres */
28
+ }
29
+ }
30
+ };
31
+ const metaOf = (source: string, o?: PublishOptions): EventMetaIn => ({
32
+ id: newId(),
33
+ source,
34
+ ts: now(),
35
+ ...(o?.v !== undefined ? { v: o.v } : {}),
36
+ ...(o?.correlationId !== undefined ? { correlationId: o.correlationId } : {}),
37
+ ...(o?.to !== undefined ? { to: o.to } : {}),
38
+ });
39
+ return {
40
+ publish(topic: string, payload: unknown, ctx: CallerContext, options?: PublishOptions) {
41
+ deliver(topic, payload, metaOf(ctx.moduleName, options));
42
+ },
43
+ publishAsShell(topic, payload, options) {
44
+ deliver(topic, payload, metaOf('shell', options));
45
+ },
46
+ subscribe(topic, cb): Unsub {
47
+ let set = subs.get(topic);
48
+ if (!set) subs.set(topic, (set = new Set()));
49
+ set.add(cb);
50
+ return () => void set!.delete(cb);
51
+ },
52
+ };
53
+ }
package/src/index.ts CHANGED
@@ -4,3 +4,4 @@ export * from './table.js';
4
4
  export * from './connection.js';
5
5
  export * from './navigation.js';
6
6
  export * from './host.js';
7
+ export * from './event-bus.js';
package/src/providers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { NotificationCloseReason, PublishOptions } from '@egen-civitas/esm-embed-protocol';
1
2
  export type Unsub = () => void;
2
3
 
3
4
  /** Valeur lisible et observable fournie par le Core. */
@@ -6,11 +7,30 @@ export interface Watchable<T> {
6
7
  subscribe?(cb: (value: T) => void): Unsub;
7
8
  }
8
9
 
10
+ /** Métadonnées fournies par le bus avec chaque événement livré. */
11
+ export interface EventMetaIn {
12
+ id?: string;
13
+ source?: string;
14
+ ts?: number;
15
+ v?: number;
16
+ correlationId?: string;
17
+ to?: string;
18
+ }
19
+
9
20
  export interface CallerContext {
10
21
  /** Nom du module de l'app appelante (non falsifiable : porté par la connexion, pas par le message). */
11
22
  moduleName: string;
12
23
  }
13
24
 
25
+ /** Ce que le Core peut renvoyer de `show` pour suivre son toast (tout est optionnel : renvoyer `void`/`boolean` reste valide). */
26
+ export interface NotificationShown {
27
+ displayed?: boolean;
28
+ /** Résolue à la fermeture du toast, avec sa cause. Absente : l'hôte estime la fermeture à `timeoutMs` (6 s par défaut). */
29
+ closed?: Promise<NotificationCloseReason>;
30
+ /** Ferme le toast sur demande de l'app (`dismiss`). */
31
+ dismiss?: () => void;
32
+ }
33
+
14
34
  export interface NotificationInput {
15
35
  /** Clé de dédoublonnage facultative : un même `id` ne produit pas deux toasts rapprochés. */
16
36
  id?: string;
@@ -18,6 +38,8 @@ export interface NotificationInput {
18
38
  title: string;
19
39
  subtitle?: string;
20
40
  timeoutMs?: number;
41
+ /** Bouton du toast : le Shell publie `topic` sur le bus d'événements (aucun code n'est exécuté). */
42
+ action?: { label: string; topic: string };
21
43
  }
22
44
 
23
45
  export interface ExtensionInfo {
@@ -39,10 +61,22 @@ export interface HostProviders {
39
61
  locale?: Watchable<string>;
40
62
  config?: Watchable<Record<string, unknown>>;
41
63
  flags?: { isEnabled(name: string): boolean | Promise<boolean>; subscribe?(cb: () => void): Unsub };
42
- events?: { publish(topic: string, payload: unknown, ctx: CallerContext): void; subscribe(topic: string, cb: (payload: unknown) => void): Unsub };
64
+ /**
65
+ * Bus d'événements du Shell. `publish`/`subscribe` historiques inchangés ; les paramètres ajoutés sont optionnels (un fournisseur
66
+ * plus ancien qui les ignore reste valide : `meta.source` vaut alors `unknown`, `to` n'est pas appliqué).
67
+ * Le fournisseur DOIT poser `source` lui-même (depuis `ctx.moduleName`, jamais depuis la charge utile).
68
+ */
69
+ events?: {
70
+ publish(topic: string, payload: unknown, ctx: CallerContext, options?: PublishOptions): void;
71
+ subscribe(topic: string, cb: (payload: unknown, meta?: EventMetaIn) => void, ctx?: CallerContext): Unsub;
72
+ };
43
73
  /** Affiche le toast dans l'interface du Core ; retourne `false` si non affiché (doublon, etc.). Le Core attribue le toast à son app d'origine. */
44
- notifications?: { show(n: NotificationInput, ctx: CallerContext): void | boolean | Promise<void | boolean> };
45
- dialogs?: { confirm(d: { title: string; message: string; danger?: boolean }, ctx: CallerContext): boolean | Promise<boolean> };
74
+ notifications?: { show(n: NotificationInput, ctx: CallerContext): void | boolean | NotificationShown | Promise<void | boolean | NotificationShown> };
75
+ dialogs?: {
76
+ confirm(d: { title: string; message: string; danger?: boolean }, ctx: CallerContext): boolean | Promise<boolean>;
77
+ /** Information à acquitter. Absente : `dialogs.alert` n'est pas servie (`UNKNOWN_METHOD`) — jamais simulée par un `confirm`. */
78
+ alert?(d: { title: string; message: string }, ctx: CallerContext): void | Promise<void>;
79
+ };
46
80
  /** Extensions attachées à un slot du Core (apps internes, framework, autres apps) : métadonnées seulement, jamais le rendu. */
47
81
  extensions?: { list(slot: string): ExtensionInfo[] | Promise<ExtensionInfo[]>; subscribe?(slot: string, cb: (list: ExtensionInfo[]) => void): Unsub };
48
82
  telemetry?: {
package/src/table.ts CHANGED
@@ -10,12 +10,14 @@ import {
10
10
  type GrantConfig,
11
11
  type HandlerTable,
12
12
  type NavigateOptions,
13
+ type NotificationCloseReason,
14
+ type PublishOptions,
13
15
  type NavigationResult,
14
16
  type RouteInfo,
15
17
  type SubscribeHandler,
16
18
  } from '@egen-civitas/esm-embed-protocol';
17
19
  import type { Bus } from './bus.js';
18
- import type { CallerContext, HostProviders } from './providers.js';
20
+ import type { CallerContext, HostProviders, NotificationShown } from './providers.js';
19
21
 
20
22
  /** Actions du Shell pilotées par les capacités `navigation` et `lifecycle`. */
21
23
  export interface HostControls {
@@ -91,9 +93,10 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
91
93
  if (cfgOf.has('events') && p.events) {
92
94
  const pub = list(cfgOf.get('events'), 'publish');
93
95
  table.events = {
94
- publish: (topic: string, payload?: unknown) => {
96
+ publish: (topic: string, payload?: unknown, options?: PublishOptions) => {
95
97
  if (!topicAllowed(pub, topic)) throw denied(`Publication non autorisée sur : ${topic}`);
96
- p.events!.publish(topic, payload, ctx);
98
+ if (options === undefined) p.events!.publish(topic, payload, ctx);
99
+ else p.events!.publish(topic, payload, ctx, options);
97
100
  },
98
101
  };
99
102
  }
@@ -101,14 +104,42 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
101
104
  // Anti-spam : une iframe ne doit pas pouvoir inonder l'interface du Core (ni imiter des messages système en rafale).
102
105
  const policy = notificationPolicy(cfgOf.get('notifications'));
103
106
  const allow = createSlidingLimiter(policy.rate.max, policy.rate.perSeconds);
107
+ const open = new Map<string, { dismiss(): void }>(); // toasts encore ouverts de cette app, par id
104
108
  table.notifications = {
105
109
  show: async (n: any) => {
106
110
  if (!allow()) throw new EmbedError('RATE_LIMITED', 'Trop de notifications');
107
- return { displayed: (await p.notifications!.show(n, ctx)) !== false };
111
+ const r = await p.notifications!.show(n, ctx);
112
+ const shown: NotificationShown = r !== null && typeof r === 'object' ? r : {};
113
+ const id: string = n.id ?? `n-${++toastSeq}`;
114
+ if (r === false || shown.displayed === false) return { displayed: false, id, reason: 'deduplicated' as const };
115
+ let settled = false;
116
+ let timer: ReturnType<typeof setTimeout> | undefined;
117
+ const finish = (reason: NotificationCloseReason) => {
118
+ if (settled) return;
119
+ settled = true;
120
+ if (timer) clearTimeout(timer);
121
+ if (open.get(id) === handle) open.delete(id);
122
+ c.channel.emit('notifications.closed', { id, reason });
123
+ };
124
+ const handle = { dismiss: () => (shown.dismiss?.(), finish('api')) };
125
+ open.set(id, handle);
126
+ if (shown.closed) shown.closed.then(finish, () => finish('api'));
127
+ else {
128
+ // Le Core ne dit pas quand le toast se ferme : fermeture estimée à `timeoutMs` (la promesse `closed` n'est jamais pendante).
129
+ timer = setTimeout(() => finish('timeout'), n.timeoutMs || DEFAULT_TOAST_MS);
130
+ (timer as { unref?: () => void }).unref?.();
131
+ }
132
+ return { displayed: true, id };
108
133
  },
134
+ dismiss: (id: string) => open.get(id)?.dismiss(),
135
+ };
136
+ }
137
+ if (cfgOf.has('dialogs') && p.dialogs) {
138
+ table.dialogs = {
139
+ confirm: async (d: any) => !!(await p.dialogs!.confirm(d, ctx)),
140
+ ...(p.dialogs.alert ? { alert: async (d: any) => void (await p.dialogs!.alert!(d, ctx)) } : {}),
109
141
  };
110
142
  }
111
- if (cfgOf.has('dialogs') && p.dialogs) table.dialogs = { confirm: async (d: any) => !!(await p.dialogs!.confirm(d, ctx)) };
112
143
  if (cfgOf.has('extensions') && p.extensions) {
113
144
  const discover = list(cfgOf.get('extensions'), 'discover');
114
145
  table.extensions = {
@@ -144,7 +175,21 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
144
175
  const cfg = cfgOf.get(cap as CapabilityId);
145
176
  const desc = CAPABILITIES[cap as CapabilityId];
146
177
  if (!cfg || !desc || !table[cap]) return undefined;
147
- if (cap === 'events') return topicAllowed(list(cfg, 'subscribe'), ev) ? p.events!.subscribe(ev, emit) : undefined;
178
+ if (cap === 'events') {
179
+ // `@sujet` : abonnement « enveloppe » (EgenEvent avec meta) ; `sujet` : charge utile seule (clients historiques).
180
+ const envelope = ev.startsWith('@');
181
+ const topic = envelope ? ev.slice(1) : ev;
182
+ if (!topicAllowed(list(cfg, 'subscribe'), topic)) return undefined;
183
+ return p.events!.subscribe(
184
+ topic,
185
+ (payload, meta) => {
186
+ if (meta?.to !== undefined && meta.to !== ctx.moduleName) return; // ciblage : les autres apps ne reçoivent rien
187
+ if (!envelope) return emit(payload);
188
+ emit({ topic, payload, meta: { id: meta?.id ?? randomId(), source: meta?.source ?? 'unknown', ts: meta?.ts ?? Date.now(), ...(meta?.v !== undefined ? { v: meta.v } : {}), ...(meta?.correlationId !== undefined ? { correlationId: meta.correlationId } : {}) } });
189
+ },
190
+ ctx,
191
+ );
192
+ }
148
193
  if (cap === 'extensions') return slotAllowed(list(cfg, 'discover'), ev) && p.extensions!.subscribe ? p.extensions!.subscribe(ev, emit as (l: any) => void) : undefined;
149
194
  if (!desc.events.includes(ev)) return undefined;
150
195
  switch (cap) {
@@ -159,6 +204,8 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
159
204
  case 'navigation':
160
205
  case 'lifecycle':
161
206
  return c.channel.on(ev, emit);
207
+ case 'notifications':
208
+ return c.channel.on('notifications.closed', emit);
162
209
  default:
163
210
  return undefined;
164
211
  }
@@ -169,3 +216,12 @@ export function createCapabilityTable(o: TableOptions): { table: HandlerTable; s
169
216
  subscribe,
170
217
  };
171
218
  }
219
+
220
+ let toastSeq = 0;
221
+ const DEFAULT_TOAST_MS = 6000;
222
+ let idSeq = 0;
223
+ /** Identifiant d'événement quand le bus n'en fournit pas : unique pour la session de l'hôte. */
224
+ function randomId(): string {
225
+ const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
226
+ return c?.randomUUID ? c.randomUUID() : `evt-${Date.now().toString(36)}-${(++idSeq).toString(36)}`;
227
+ }