@egen-civitas/esm-embed-testing 0.2.0 → 0.4.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/dist/test-host.js CHANGED
@@ -1,131 +1,3 @@
1
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
- try {
3
- var info = gen[key](arg);
4
- var value = info.value;
5
- } catch (error) {
6
- reject(error);
7
- return;
8
- }
9
- if (info.done) {
10
- resolve(value);
11
- } else {
12
- Promise.resolve(value).then(_next, _throw);
13
- }
14
- }
15
- function _async_to_generator(fn) {
16
- return function() {
17
- var self = this, args = arguments;
18
- return new Promise(function(resolve, reject) {
19
- var gen = fn.apply(self, args);
20
- function _next(value) {
21
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
- }
23
- function _throw(err) {
24
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
- }
26
- _next(undefined);
27
- });
28
- };
29
- }
30
- function _ts_generator(thisArg, body) {
31
- var f, y, t, _ = {
32
- label: 0,
33
- sent: function() {
34
- if (t[0] & 1) throw t[1];
35
- return t[1];
36
- },
37
- trys: [],
38
- ops: []
39
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
40
- return d(g, "next", {
41
- value: verb(0)
42
- }), d(g, "throw", {
43
- value: verb(1)
44
- }), d(g, "return", {
45
- value: verb(2)
46
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
47
- value: function() {
48
- return this;
49
- }
50
- }), g;
51
- function verb(n) {
52
- return function(v) {
53
- return step([
54
- n,
55
- v
56
- ]);
57
- };
58
- }
59
- function step(op) {
60
- if (f) throw new TypeError("Generator is already executing.");
61
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
62
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
63
- if (y = 0, t) op = [
64
- op[0] & 2,
65
- t.value
66
- ];
67
- switch(op[0]){
68
- case 0:
69
- case 1:
70
- t = op;
71
- break;
72
- case 4:
73
- _.label++;
74
- return {
75
- value: op[1],
76
- done: false
77
- };
78
- case 5:
79
- _.label++;
80
- y = op[1];
81
- op = [
82
- 0
83
- ];
84
- continue;
85
- case 7:
86
- op = _.ops.pop();
87
- _.trys.pop();
88
- continue;
89
- default:
90
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
91
- _ = 0;
92
- continue;
93
- }
94
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
95
- _.label = op[1];
96
- break;
97
- }
98
- if (op[0] === 6 && _.label < t[1]) {
99
- _.label = t[1];
100
- t = op;
101
- break;
102
- }
103
- if (t && _.label < t[2]) {
104
- _.label = t[2];
105
- _.ops.push(op);
106
- break;
107
- }
108
- if (t[2]) _.ops.pop();
109
- _.trys.pop();
110
- continue;
111
- }
112
- op = body.call(thisArg, _);
113
- } catch (e) {
114
- op = [
115
- 6,
116
- e
117
- ];
118
- y = 0;
119
- } finally{
120
- f = t = 0;
121
- }
122
- if (op[0] & 5) throw op[1];
123
- return {
124
- value: op[0] ? op[1] : void 0,
125
- done: true
126
- };
127
- }
128
- }
129
1
  import { effectiveGrants } from '@egen-civitas/esm-embed-protocol';
130
2
  import { createBus, HostConnection } from '@egen-civitas/esm-embed-host';
131
3
  function watchable(initial) {
@@ -153,19 +25,17 @@ function watchable(initial) {
153
25
  * relié à votre app par de fausses fenêtres et un vrai `MessageChannel`. Aucun navigateur, aucun Core.
154
26
  *
155
27
  * ```ts
156
- * const sim = createTestHost({ session: { authenticated: true, user: { display: 'Sam' } } });
157
- * const egen = await connectToEgen({ ...sim.connectOptions, capabilities: ['session'] });
28
+ * const sim = createTestHost({ locale: 'fr', tenant: { id: 'acme' } });
29
+ * const egen = await connectToEgen({ ...sim.connectOptions, capabilities: ['locale', 'tenant'] });
158
30
  * ```
159
31
  */ export function createTestHost() {
160
32
  var o = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
161
- var _o_moduleName, _o_origin, _o_session, _o_tenant, _o_locale, _o_theme, _o_config, _o_approved;
33
+ var _o_moduleName, _o_origin, _o_tenant, _o_locale, _o_extensions, _o_config, _o_approved;
162
34
  var moduleName = (_o_moduleName = o.moduleName) !== null && _o_moduleName !== void 0 ? _o_moduleName : '@acme/esm-test-app';
163
35
  var origin = (_o_origin = o.origin) !== null && _o_origin !== void 0 ? _o_origin : 'https://shell.test';
164
36
  var calls = [];
165
37
  var notifications = [];
166
38
  var published = [];
167
- var tools = new Map();
168
- var toolInvokers = new Map();
169
39
  var log = function log(cap, method) {
170
40
  for(var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++){
171
41
  args[_key - 2] = arguments[_key];
@@ -176,17 +46,12 @@ function watchable(initial) {
176
46
  args: args
177
47
  });
178
48
  };
179
- var session = watchable((_o_session = o.session) !== null && _o_session !== void 0 ? _o_session : {
180
- authenticated: true
181
- });
182
49
  var tenant = watchable((_o_tenant = o.tenant) !== null && _o_tenant !== void 0 ? _o_tenant : {
183
50
  id: null
184
51
  });
185
52
  var locale = watchable((_o_locale = o.locale) !== null && _o_locale !== void 0 ? _o_locale : 'fr');
186
- var theme = watchable((_o_theme = o.theme) !== null && _o_theme !== void 0 ? _o_theme : {
187
- mode: 'light',
188
- tokens: {}
189
- });
53
+ var extList = new Map(Object.entries((_o_extensions = o.extensions) !== null && _o_extensions !== void 0 ? _o_extensions : {}));
54
+ var extSubs = new Map();
190
55
  var config = watchable((_o_config = o.config) !== null && _o_config !== void 0 ? _o_config : {});
191
56
  var flagSubs = new Set();
192
57
  var eventSubs = new Map();
@@ -201,10 +66,8 @@ function watchable(initial) {
201
66
  };
202
67
  };
203
68
  var providers = {
204
- session: wrapWatch('session', session),
205
69
  tenant: wrapWatch('tenant', tenant),
206
70
  locale: wrapWatch('locale', locale),
207
- theme: wrapWatch('theme', theme),
208
71
  config: wrapWatch('config', config),
209
72
  flags: {
210
73
  isEnabled: function isEnabled(n) {
@@ -218,11 +81,19 @@ function watchable(initial) {
218
81
  };
219
82
  }
220
83
  },
221
- permissions: {
222
- can: function can(p) {
223
- var _o_permissions;
224
- log('permissions', 'can', p);
225
- return !!((_o_permissions = o.permissions) === null || _o_permissions === void 0 ? void 0 : _o_permissions.includes(p));
84
+ extensions: {
85
+ list: function list(slot) {
86
+ var _extList_get;
87
+ log('extensions', 'list', slot);
88
+ return (_extList_get = extList.get(slot)) !== null && _extList_get !== void 0 ? _extList_get : [];
89
+ },
90
+ subscribe: function subscribe(slot, cb) {
91
+ var set = extSubs.get(slot);
92
+ if (!set) extSubs.set(slot, set = new Set());
93
+ set.add(cb);
94
+ return function() {
95
+ return void set.delete(cb);
96
+ };
226
97
  }
227
98
  },
228
99
  events: {
@@ -246,7 +117,12 @@ function watchable(initial) {
246
117
  notifications: {
247
118
  show: function show(n) {
248
119
  log('notifications', 'show', n);
120
+ // même dédoublonnage que le Core : un `id` déjà affiché n'est pas réaffiché
121
+ if (n.id && notifications.some(function(x) {
122
+ return x.id === n.id;
123
+ })) return false;
249
124
  notifications.push(n);
125
+ return true;
250
126
  }
251
127
  },
252
128
  dialogs: {
@@ -256,25 +132,6 @@ function watchable(initial) {
256
132
  return typeof o.confirm === 'function' ? o.confirm(d) : (_o_confirm = o.confirm) !== null && _o_confirm !== void 0 ? _o_confirm : true;
257
133
  }
258
134
  },
259
- api: {
260
- fetch: function fetch(req) {
261
- return _async_to_generator(function() {
262
- return _ts_generator(this, function(_state) {
263
- log('api', 'fetch', req);
264
- return [
265
- 2,
266
- o.api ? o.api(req) : {
267
- status: 200,
268
- headers: {
269
- 'content-type': 'application/json'
270
- },
271
- body: '{}'
272
- }
273
- ];
274
- });
275
- })();
276
- }
277
- },
278
135
  telemetry: {
279
136
  log: function log1(l, m, c) {
280
137
  return log('telemetry', 'log', l, m, c);
@@ -282,59 +139,6 @@ function watchable(initial) {
282
139
  metric: function metric(n, v, t) {
283
140
  return log('telemetry', 'metric', n, v, t);
284
141
  }
285
- },
286
- aiTools: {
287
- register: function register(_m, list, invoke) {
288
- log('ai-tools', 'register', list.map(function(t) {
289
- return t.name;
290
- }));
291
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
292
- try {
293
- for(var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
294
- var t = _step.value;
295
- tools.set(t.name, {
296
- description: t.description
297
- });
298
- toolInvokers.set(t.name, invoke);
299
- }
300
- } catch (err) {
301
- _didIteratorError = true;
302
- _iteratorError = err;
303
- } finally{
304
- try {
305
- if (!_iteratorNormalCompletion && _iterator.return != null) {
306
- _iterator.return();
307
- }
308
- } finally{
309
- if (_didIteratorError) {
310
- throw _iteratorError;
311
- }
312
- }
313
- }
314
- },
315
- unregister: function unregister(_m, names) {
316
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
317
- try {
318
- for(var _iterator = names[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
319
- var n = _step.value;
320
- tools.delete(n);
321
- toolInvokers.delete(n);
322
- }
323
- } catch (err) {
324
- _didIteratorError = true;
325
- _iteratorError = err;
326
- } finally{
327
- try {
328
- if (!_iteratorNormalCompletion && _iterator.return != null) {
329
- _iterator.return();
330
- }
331
- } finally{
332
- if (_didIteratorError) {
333
- throw _iteratorError;
334
- }
335
- }
336
- }
337
- }
338
142
  }
339
143
  };
340
144
  var appWindow = new EventTarget();
@@ -395,19 +199,19 @@ function watchable(initial) {
395
199
  calls: calls,
396
200
  notifications: notifications,
397
201
  published: published,
398
- tools: tools,
399
202
  emit: {
400
- session: function session1(v) {
401
- return session.set(v);
402
- },
403
203
  tenant: function tenant1(v) {
404
204
  return tenant.set(v);
405
205
  },
406
206
  locale: function locale1(v) {
407
207
  return locale.set(v);
408
208
  },
409
- theme: function theme1(v) {
410
- return theme.set(v);
209
+ extensions: function extensions(slot, list) {
210
+ var _extSubs_get;
211
+ extList.set(slot, list);
212
+ (_extSubs_get = extSubs.get(slot)) === null || _extSubs_get === void 0 ? void 0 : _extSubs_get.forEach(function(cb) {
213
+ return cb(list);
214
+ });
411
215
  },
412
216
  config: function config1(v) {
413
217
  return config.set(v);
@@ -428,20 +232,6 @@ function watchable(initial) {
428
232
  return channel.emit('visibility', v);
429
233
  }
430
234
  },
431
- invokeTool: function invokeTool(name) {
432
- var args = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
433
- return _async_to_generator(function() {
434
- var inv;
435
- return _ts_generator(this, function(_state) {
436
- inv = toolInvokers.get(name);
437
- if (!inv) throw new Error("Outil non enregistr\xe9 : ".concat(name));
438
- return [
439
- 2,
440
- inv(name, args)
441
- ];
442
- });
443
- })();
444
- },
445
235
  destroy: function destroy() {
446
236
  return connection.destroy();
447
237
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egen-civitas/esm-embed-testing",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Développer et tester une app embarquée sans le Core : hôte de test en mémoire, suite de conformité du protocole v2, simulateur de Shell (egen-embed-sim).",
6
6
  "type": "module",
@@ -76,9 +76,9 @@
76
76
  "vitest": "^4.1.2"
77
77
  },
78
78
  "dependencies": {
79
- "@egen-civitas/esm-embed-client": "^0.1.1",
80
- "@egen-civitas/esm-embed-host": "^0.2.0",
81
- "@egen-civitas/esm-embed-protocol": "^0.2.0"
79
+ "@egen-civitas/esm-embed-client": "^0.3.0",
80
+ "@egen-civitas/esm-embed-host": "^0.4.0",
81
+ "@egen-civitas/esm-embed-protocol": "^0.4.0"
82
82
  },
83
83
  "bin": {
84
84
  "egen-embed-check": "bin/egen-embed-check.mjs",
package/src/check.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CAPABILITIES, FORBIDDEN_SESSION_FIELDS, patternCovers, validateManifest, type EmbedManifest } from '@egen-civitas/esm-embed-protocol';
1
+ import { CAPABILITIES, patternCovers, validateManifest, type EmbedManifest } from '@egen-civitas/esm-embed-protocol';
2
2
 
3
3
  export interface CheckIssue {
4
4
  level: 'error' | 'warn' | 'info';
@@ -32,9 +32,6 @@ export async function checkEmbedApp(o: CheckOptions): Promise<CheckIssue[]> {
32
32
  const needApproval = Object.keys(caps).filter((id) => !CAPABILITIES[id as keyof typeof CAPABILITIES].defaultGrant);
33
33
  if (needApproval.length) add('info', `Capacités à faire approuver par l'opérateur (grants) : ${needApproval.join(', ')}`);
34
34
 
35
- const fields = caps.session?.fields;
36
- if (Array.isArray(fields)) for (const f of fields) if (FORBIDDEN_SESSION_FIELDS.includes(String(f).split('.')[0])) add('error', `session.fields : « ${f} » ne sera jamais transmis (identifiant de session ou jeton)`);
37
-
38
35
  const pub = caps.events?.publish;
39
36
  if (Array.isArray(pub)) {
40
37
  const own = `app.${m.route}.*`;
@@ -43,17 +40,15 @@ export async function checkEmbedApp(o: CheckOptions): Promise<CheckIssue[]> {
43
40
  else if (!patternCovers(own, String(p).replace(/\.\*$/, '.x'))) add('warn', `events.publish : « ${p} » sort de l'espace conseillé ${own}`);
44
41
  }
45
42
  }
46
- const tools = caps['ai-tools']?.tools;
47
- if (Array.isArray(tools) && tools.some((t) => !String(t).includes('.'))) add('warn', 'ai-tools.tools : préférer des noms d’outils préfixés (ex. studio.apply) pour éviter les collisions');
48
43
 
49
- if (caps.api && !(Array.isArray(caps.api.paths) && caps.api.paths.length) && !(Array.isArray(caps.api.hosts) && caps.api.hosts.length)) add('warn', 'api : ni paths ni hosts demandés : aucun appel ne sera possible (deny-by-default)');
50
- const apiPaths = caps.api?.paths;
51
- if (Array.isArray(apiPaths)) for (const p of apiPaths) if (p === '/*' || p === '*') add('warn', `api.paths : « ${p} » ouvre toute l'API du Core avec la session de l'utilisateur ; nommer les chemins nécessaires`);
52
- const hosts = caps.api?.hosts;
53
- if (Array.isArray(hosts)) for (const h of hosts) if (!/^https:\/\//i.test(String(h))) add('error', `api.hosts : « ${h} » doit être une origine https`);
44
+ if (caps.notifications) add('info', "Notifications : le Core affiche les toasts (par défaut seul). N'affichez pas les vôtres : appelez egen.notify(toast, local) et ne rendez votre composant de toasts que si !egen.coreDisplaysNotifications");
45
+ const slots = [...new Set((m.extensions ?? []).map((e) => e.slot))];
46
+ if (slots.length) add('info', `Contributions d'extension : l'opérateur doit approuver les slots (extensions.contribute) : ${slots.join(', ')}`);
47
+ for (const e of m.extensions ?? []) if (e.view) add('info', `Extension « ${e.name} » : la vue ${e.view} sera affichée dans une iframe du Core (frame-ancestors à autoriser pour le Shell, hauteur via navigation.resize)`);
48
+ const discover = caps.extensions?.discover;
49
+ if (Array.isArray(discover) && discover.some((s) => s === '*')) add('error', "extensions.discover : le motif « * » n'est pas supporté (nommer les slots)");
54
50
 
55
51
  if (m.technology === 'nextjs' && m.navigation.mode === 'none') add('info', 'Next.js avec navigation « none » : l’URL du Core ne reflétera pas la page courante (partage de lien, F5)');
56
- if (!caps.lifecycle && !caps.navigation) add('info', 'Aucune capacité navigation/lifecycle demandée : l’app ne pourra ni redimensionner l’iframe ni signaler qu’elle est prête (valeurs par défaut accordées si utilisées)');
57
52
 
58
53
  if (o.probe) {
59
54
  const f = o.fetchImpl ?? fetch;
@@ -20,7 +20,7 @@ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
20
20
  describe('conformité protocole v2 (client)', () => {
21
21
  it('poignée de main : connecté en protocole 2', async () => {
22
22
  const sim = createTestHost();
23
- const c = await connect({ ...sim.connectOptions, capabilities: ['session'] });
23
+ const c = await connect({ ...sim.connectOptions, capabilities: ['tenant'] });
24
24
  expect(c.connected).toBe(true);
25
25
  expect(c.protocol).toBe(2);
26
26
  c.close();
@@ -32,7 +32,7 @@ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
32
32
  const silent = { postMessage: () => undefined };
33
33
  const c = await connect({ ...sim.connectOptions, host: silent as any, timeoutMs: 80 });
34
34
  expect(c.connected).toBe(false);
35
- await expect(c.session.get()).rejects.toMatchObject({ code: 'DENIED' });
35
+ await expect(c.tenant.get()).rejects.toMatchObject({ code: 'DENIED' });
36
36
  sim.destroy();
37
37
  });
38
38
 
@@ -50,54 +50,90 @@ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
50
50
  sim.destroy();
51
51
  });
52
52
 
53
- it('session : champs listés seulement, jamais de sessionId', async () => {
54
- const sim = createTestHost({ session: { authenticated: true, sessionId: 'SECRET', user: { uuid: 'u', display: 'Sam', email: 'e@x.y' } } });
55
- const c = await connect({ ...sim.connectOptions, capabilities: ['session'] });
56
- const s = await c.session.get();
57
- expect(JSON.stringify(s)).not.toMatch(/SECRET|e@x\.y/);
58
- expect(s).toMatchObject({ authenticated: true, user: { uuid: 'u', display: 'Sam' } });
53
+ it('règle d’or : identité, droits, thème et api ne sont pas des capacités du SDK', async () => {
54
+ const sim = createTestHost();
55
+ const c = await connect({ ...sim.connectOptions, capabilities: ['tenant', 'session', 'theme', 'permissions', 'api'] as any });
56
+ expect(c.has('tenant')).toBe(true);
57
+ expect(c.denied.map((d) => d.id).sort()).toEqual(['api', 'permissions', 'session', 'theme']);
58
+ expect(c.denied.every((d) => d.reason === 'UNKNOWN')).toBe(true);
59
59
  c.close();
60
60
  sim.destroy();
61
61
  });
62
62
 
63
63
  it('moindre privilège : capacité non approuvée refusée à la négociation et localement', async () => {
64
64
  const sim = createTestHost();
65
- const c = await connect({ ...sim.connectOptions, capabilities: ['session', 'api', 'notifications'] });
66
- expect(c.has('api')).toBe(false);
67
- expect(c.denied.map((d) => d.id).sort()).toEqual(['api', 'notifications']);
68
- await expect(c.api.fetch({ path: '/x' })).rejects.toMatchObject({ code: 'DENIED' });
69
- expect(sim.calls.some((x) => x.cap === 'api')).toBe(false);
65
+ const c = await connect({ ...sim.connectOptions, capabilities: ['tenant', 'events', 'notifications'] });
66
+ expect(c.has('events')).toBe(false);
67
+ expect(c.denied.map((d) => d.id).sort()).toEqual(['events', 'notifications']);
68
+ await expect(c.notifications.show({ kind: 'info', title: 'x' })).rejects.toMatchObject({ code: 'DENIED' });
69
+ expect(sim.calls.some((x) => x.cap === 'notifications')).toBe(false);
70
70
  c.close();
71
71
  sim.destroy();
72
72
  });
73
73
 
74
- it('changements poussés par l’hôte (thème)', async () => {
75
- const sim = createTestHost({ theme: { mode: 'light', tokens: { '--p': '#fff' } } });
76
- const c = await connect({ ...sim.connectOptions, capabilities: ['session', 'theme'] });
77
- const themes: unknown[] = [];
78
- await c.theme.onChange((x) => themes.push(x));
79
- sim.emit.theme({ mode: 'dark', tokens: { '--p': '#000' } });
74
+ it('changements poussés par l’hôte (langue)', async () => {
75
+ const sim = createTestHost({ locale: 'fr' });
76
+ const c = await connect({ ...sim.connectOptions, capabilities: ['locale'] });
77
+ const seen: unknown[] = [];
78
+ await c.locale.onChange((x) => seen.push(x));
79
+ sim.emit.locale('en');
80
80
  await tick();
81
- expect(themes).toEqual([{ mode: 'dark', tokens: { '--p': '#000' } }]);
81
+ expect(seen).toEqual(['en']);
82
+ c.close();
83
+ sim.destroy();
84
+ });
85
+
86
+ it('extensions : découverte limitée aux slots approuvés', async () => {
87
+ const list = [{ name: 'nav-x', moduleName: '@egen/esm-x-app', meta: { label: 'X' } }];
88
+ const sim = createTestHost({ extensions: { 'topbar-nav-slot': list }, manifestCapabilities: { extensions: { discover: ['topbar-nav-slot'] } }, approved: { extensions: { discover: ['topbar-nav-slot'] } } });
89
+ const c = await connect({ ...sim.connectOptions, capabilities: ['extensions'] });
90
+ await expect(c.extensions.list('topbar-nav-slot')).resolves.toEqual(list);
91
+ await expect(c.extensions.list('shell-rail-left-slot')).rejects.toMatchObject({ code: 'DENIED' });
92
+ c.close();
93
+ sim.destroy();
94
+ });
95
+
96
+ it('toasts : le Core affiche seul, l’app n’affiche pas les siens (notify sans doublon)', async () => {
97
+ const sim = createTestHost({ manifestCapabilities: { notifications: {} }, approved: { notifications: {} } });
98
+ const c = await connect({ ...sim.connectOptions, capabilities: ['notifications'] });
99
+ const local: unknown[] = [];
100
+ expect(c.coreDisplaysNotifications).toBe(true);
101
+ await c.notify({ kind: 'success', title: 'Enregistré', id: 't1' }, (t) => local.push(t));
102
+ await c.notify({ kind: 'success', title: 'Enregistré', id: 't1' }, (t) => local.push(t));
103
+ expect(local).toEqual([]);
104
+ expect(sim.notifications).toHaveLength(1); // le doublon (même id) n'est pas réaffiché par le Core
105
+ c.close();
106
+ sim.destroy();
107
+ });
108
+
109
+ it('toasts : sans approbation, l’app affiche elle-même (jamais de perte, jamais de doublon)', async () => {
110
+ const sim = createTestHost();
111
+ const c = await connect({ ...sim.connectOptions, capabilities: ['notifications'] });
112
+ const local: unknown[] = [];
113
+ expect(c.coreDisplaysNotifications).toBe(false);
114
+ await c.notify({ kind: 'info', title: 'x' }, (t) => local.push(t));
115
+ expect(local).toHaveLength(1);
116
+ expect(sim.notifications).toHaveLength(0);
82
117
  c.close();
83
118
  sim.destroy();
84
119
  });
85
120
 
86
- it('thème : variables CSS invalides ignorées (pas d’injection)', async () => {
87
- const set: Record<string, string> = {};
88
- const sim = createTestHost({ theme: { mode: 'dark', tokens: { '--ok': '#111', color: 'red', '--bad': 'x;}body{display:none' } } });
89
- const c = await connect({ ...sim.connectOptions, capabilities: ['theme'] });
90
- await c.theme.sync({ style: { setProperty: (k: string, v: string) => (set[k] = v) } });
91
- expect(set).toEqual({ '--ok': '#111' });
121
+ it('toasts : anti-spam (rate) — au-delà, abandonné, ni Core ni local', async () => {
122
+ const sim = createTestHost({ manifestCapabilities: { notifications: {} }, approved: { notifications: { rate: { max: 2, perSeconds: 60 } } } });
123
+ const c = await connect({ ...sim.connectOptions, capabilities: ['notifications'] });
124
+ const local: unknown[] = [];
125
+ for (let i = 0; i < 5; i++) await c.notify({ kind: 'info', title: `t${i}` }, (t) => local.push(t));
126
+ expect(sim.notifications).toHaveLength(2);
127
+ expect(local).toEqual([]);
92
128
  c.close();
93
129
  sim.destroy();
94
130
  });
95
131
 
96
132
  it('fermeture : appels suivants rejetés', async () => {
97
133
  const sim = createTestHost();
98
- const c = await connect({ ...sim.connectOptions, capabilities: ['session'] });
134
+ const c = await connect({ ...sim.connectOptions, capabilities: ['tenant'] });
99
135
  c.close();
100
- await expect(c.session.get()).rejects.toMatchObject({ code: 'DENIED' });
136
+ await expect(c.tenant.get()).rejects.toMatchObject({ code: 'DENIED' });
101
137
  sim.destroy();
102
138
  });
103
139
  });
package/src/server.ts CHANGED
@@ -14,7 +14,6 @@ export interface SimulatorOptions {
14
14
  manifest?: unknown;
15
15
  /** Approuver toutes les capacités demandées (défaut) ou seulement celles « par défaut » (`strict`). */
16
16
  strict?: boolean;
17
- session?: Record<string, unknown>;
18
17
  }
19
18
 
20
19
  export interface Simulator {
@@ -52,7 +51,7 @@ export async function startSimulator(o: SimulatorOptions): Promise<Simulator> {
52
51
  moduleName: manifest?.name ?? '@acme/esm-sim-app',
53
52
  manifestCapabilities: manifest?.capabilities,
54
53
  approved: approvedFor(manifest, !!o.strict),
55
- session: o.session ?? { authenticated: true, locale: 'fr', user: { uuid: 'sim-user', display: 'Utilisateur simulé', username: 'sim' }, sessionId: 'NE-DOIT-JAMAIS-ETRE-VISIBLE' },
54
+ extensions: { 'topbar-nav-slot': [{ name: 'nav-demo', moduleName: '@egen/esm-demo-app', order: 1, meta: { label: 'Démo', route: 'demo' } }] },
56
55
  };
57
56
  const roots: Record<string, string> = { protocol: pkgDist('@egen-civitas/esm-embed-protocol'), host: pkgDist('@egen-civitas/esm-embed-host') };
58
57
 
@@ -99,7 +98,7 @@ h1{font-size:14px;margin:0 0 8px}h2{font-size:12px;margin:12px 0 4px;text-transf
99
98
  <aside><h1>Simulateur de Shell EGEN</h1>
100
99
  <div id="info"></div>
101
100
  <h2>Pousser vers l'app</h2>
102
- <button id="theme">Thème clair/sombre</button><button id="locale">Langue fr/en</button><button id="session">Session (autre nom)</button><button id="event">Événement core.sim.ping</button>
101
+ <button id="locale">Langue fr/en</button><button id="event">Événement core.sim.ping</button><button id="ext">Changer les extensions de topbar-nav-slot</button>
103
102
  <h2>Notifications</h2><div id="toasts"></div>
104
103
  <h2>Journal des échanges</h2><pre id="log"></pre></aside>
105
104
  <script type="module">
@@ -109,26 +108,24 @@ const cfg = await (await fetch('/api/config')).json();
109
108
  const $ = (id) => document.getElementById(id);
110
109
  const log = (...a) => { $('log').textContent = new Date().toLocaleTimeString() + ' ' + a.map((x) => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\\n' + $('log').textContent; };
111
110
  const watch = (v) => { const s = new Set(); return { get: () => v, subscribe: (cb) => (s.add(cb), () => s.delete(cb)), set: (n) => { v = n; s.forEach((f) => f(n)); } }; };
112
- const session = watch(cfg.session), theme = watch({ mode: 'light', tokens: { '--primary': '#2563eb', '--background': '#ffffff', '--foreground': '#111111' } }), locale = watch('fr');
113
- const tenant = watch({ id: 'sim-tenant' }), conf = watch({});
114
- const topics = new Map();
111
+ const locale = watch('fr'), tenant = watch({ id: 'sim-tenant' }), conf = watch({});
112
+ const topics = new Map(), seenToasts = new Set();
113
+ const extState = new Map(Object.entries(cfg.extensions)), extSubs = new Map();
115
114
  const wrap = (cap, p) => Object.fromEntries(Object.entries(p).map(([k, f]) => [k, typeof f === 'function' ? (...a) => { log('←', cap + '.' + k, a); return f(...a); } : f]));
116
115
  const providers = {
117
- session: wrap('session', session), theme: wrap('theme', theme), locale: wrap('locale', locale), tenant: wrap('tenant', tenant), config: wrap('config', conf),
118
- flags: wrap('flags', { isEnabled: () => true }), permissions: wrap('permissions', { can: () => true }),
116
+ locale: wrap('locale', locale), tenant: wrap('tenant', tenant), config: wrap('config', conf),
117
+ flags: wrap('flags', { isEnabled: () => true }),
118
+ extensions: { list: (slot) => { log('← extensions.list', slot); return extState.get(slot) || []; }, subscribe: (slot, cb) => { const s = extSubs.get(slot) || new Set(); s.add(cb); extSubs.set(slot, s); return () => s.delete(cb); } },
119
119
  events: { publish: (t, p, c) => { log('← events.publish', t, p, 'de', c.moduleName); (topics.get(t) || []).forEach((f) => f(p)); }, subscribe: (t, cb) => { log('← events.subscribe', t); const l = topics.get(t) || []; l.push(cb); topics.set(t, l); return () => topics.set(t, (topics.get(t) || []).filter((f) => f !== cb)); } },
120
- notifications: { show: (n) => { log('← notifications.show', n); const d = document.createElement('div'); d.className = 'toast'; d.textContent = '[' + n.kind + '] ' + n.title + (n.subtitle ? ' — ' + n.subtitle : ''); $('toasts').prepend(d); } },
120
+ notifications: { show: (n, c) => { log('← notifications.show', n, 'de', c.moduleName); if (n.id && seenToasts.has(n.id)) return false; if (n.id) seenToasts.add(n.id); const d = document.createElement('div'); d.className = 'toast'; d.textContent = '[' + n.kind + '] ' + cfg.moduleName + ' · ' + n.title + (n.subtitle ? ' — ' + n.subtitle : ''); $('toasts').prepend(d); return true; } },
121
121
  dialogs: { confirm: (d) => { log('← dialogs.confirm', d); return confirm(d.title + '\\n\\n' + d.message); } },
122
- api: { fetch: async (r) => { log('← api.fetch', r); return { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ simulated: true, request: r }) }; } },
123
122
  telemetry: { log: (...a) => log('← telemetry.log', a.slice(0, 3)), metric: (...a) => log('← telemetry.metric', a.slice(0, 3)) },
124
- aiTools: { register: (m, t) => log('← ai-tools.register', t.map((x) => x.name)), unregister: (m, n) => log('← ai-tools.unregister', n) },
125
123
  };
126
124
  const grants = effectiveGrants(cfg.manifestCapabilities, cfg.approved);
127
125
  $('info').innerHTML = '<b>App</b> ' + cfg.app + '<br><b>Module</b> ' + cfg.moduleName + '<br><b>hostOrigins à déclarer dans l’app</b> <code>' + location.origin + '</code><br><b>Capacités accordées</b> ' + Object.keys(grants).join(', ');
128
126
  const host = createEmbedHost({ moduleName: cfg.moduleName, src: cfg.app, grants, providers, onConnect: (g, d) => log('✔ connecté', { accordées: g.map((x) => x.id), refusées: d }), onClose: (r) => log('✖ fermé', r) });
129
127
  host.mount($('stage'));
130
- $('theme').onclick = () => { const t = theme.get(); const dark = t.mode !== 'dark'; theme.set({ mode: dark ? 'dark' : 'light', tokens: { ...t.tokens, '--background': dark ? '#0b0b0f' : '#ffffff', '--foreground': dark ? '#f5f5f5' : '#111111' } }); };
131
128
  $('locale').onclick = () => locale.set(locale.get() === 'fr' ? 'en' : 'fr');
132
- $('session').onclick = () => { const s = session.get(); session.set({ ...s, user: { ...s.user, display: 'Autre ' + Math.floor(Math.random() * 100) } }); };
133
129
  $('event').onclick = () => (topics.get('core.sim.ping') || []).forEach((f) => f({ at: Date.now() }));
130
+ $('ext').onclick = () => { const n = [{ name: 'nav-' + Math.floor(Math.random() * 100), moduleName: '@egen/esm-demo-app', meta: { label: 'Nouvelle extension' } }]; extState.set('topbar-nav-slot', n); (extSubs.get('topbar-nav-slot') || []).forEach((f) => f(n)); };
134
131
  </script></body></html>`;