@egen-civitas/esm-embed-testing 0.0.0-stage → 0.2.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.
@@ -0,0 +1,104 @@
1
+ import type { ConnectOptions, EgenClient } from '@egen-civitas/esm-embed-client';
2
+ import { createTestHost } from './test-host.js';
3
+
4
+ export type ConnectFn = (options: ConnectOptions) => Promise<EgenClient>;
5
+
6
+ export interface ConformanceApi {
7
+ describe(name: string, fn: () => void): void;
8
+ it(name: string, fn: () => Promise<void> | void): void;
9
+ expect: (value: any) => any;
10
+ }
11
+
12
+ /**
13
+ * Suite de conformité du protocole v2 pour un client (le SDK, ou toute implémentation tierce qui expose la même forme).
14
+ * Utilisation (Vitest/Jest) : `defineConformance(connectToEgen, { describe, it, expect })`.
15
+ */
16
+ export function defineConformance(connect: ConnectFn, t: ConformanceApi): void {
17
+ const { describe, it, expect } = t;
18
+ const tick = (ms = 25) => new Promise((r) => setTimeout(r, ms));
19
+
20
+ describe('conformité protocole v2 (client)', () => {
21
+ it('poignée de main : connecté en protocole 2', async () => {
22
+ const sim = createTestHost();
23
+ const c = await connect({ ...sim.connectOptions, capabilities: ['session'] });
24
+ expect(c.connected).toBe(true);
25
+ expect(c.protocol).toBe(2);
26
+ c.close();
27
+ sim.destroy();
28
+ });
29
+
30
+ it('hôte muet : mode autonome, appels rejetés DENIED sans exception synchrone', async () => {
31
+ const sim = createTestHost();
32
+ const silent = { postMessage: () => undefined };
33
+ const c = await connect({ ...sim.connectOptions, host: silent as any, timeoutMs: 80 });
34
+ expect(c.connected).toBe(false);
35
+ await expect(c.session.get()).rejects.toMatchObject({ code: 'DENIED' });
36
+ sim.destroy();
37
+ });
38
+
39
+ it('origine d’hôte inattendue : jamais connecté', async () => {
40
+ const sim = createTestHost();
41
+ const c = await connect({ ...sim.connectOptions, hostOrigins: ['https://autre.exemple.org'], timeoutMs: 80 });
42
+ expect(c.connected).toBe(false);
43
+ sim.destroy();
44
+ });
45
+
46
+ it('hostOrigins : joker et liste vide refusés', async () => {
47
+ const sim = createTestHost();
48
+ await expect(Promise.resolve().then(() => connect({ ...sim.connectOptions, hostOrigins: ['*'] }))).rejects.toThrow();
49
+ await expect(Promise.resolve().then(() => connect({ ...sim.connectOptions, hostOrigins: [] }))).rejects.toThrow();
50
+ sim.destroy();
51
+ });
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' } });
59
+ c.close();
60
+ sim.destroy();
61
+ });
62
+
63
+ it('moindre privilège : capacité non approuvée refusée à la négociation et localement', async () => {
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);
70
+ c.close();
71
+ sim.destroy();
72
+ });
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' } });
80
+ await tick();
81
+ expect(themes).toEqual([{ mode: 'dark', tokens: { '--p': '#000' } }]);
82
+ c.close();
83
+ sim.destroy();
84
+ });
85
+
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' });
92
+ c.close();
93
+ sim.destroy();
94
+ });
95
+
96
+ it('fermeture : appels suivants rejetés', async () => {
97
+ const sim = createTestHost();
98
+ const c = await connect({ ...sim.connectOptions, capabilities: ['session'] });
99
+ c.close();
100
+ await expect(c.session.get()).rejects.toMatchObject({ code: 'DENIED' });
101
+ sim.destroy();
102
+ });
103
+ });
104
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './test-host.js';
2
+ export * from './conformance.js';
3
+ export * from './check.js';
package/src/server.ts ADDED
@@ -0,0 +1,134 @@
1
+ import { createServer, type Server } from 'node:http';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join, normalize, sep } from 'node:path';
5
+ import type { AddressInfo } from 'node:net';
6
+ import { validateManifest, CAPABILITY_IDS, CAPABILITIES, type ApprovedGrants, type EmbedManifest } from '@egen-civitas/esm-embed-protocol';
7
+
8
+ export interface SimulatorOptions {
9
+ /** URL de l'app embarquée (ex. `http://localhost:3000`). */
10
+ app: string;
11
+ port?: number;
12
+ host?: string;
13
+ /** Manifeste `egen-app.json` de l'app (objet déjà lu). Sans manifeste : l'opérateur simulé définit seul. */
14
+ manifest?: unknown;
15
+ /** Approuver toutes les capacités demandées (défaut) ou seulement celles « par défaut » (`strict`). */
16
+ strict?: boolean;
17
+ session?: Record<string, unknown>;
18
+ }
19
+
20
+ export interface Simulator {
21
+ url: string;
22
+ server: Server;
23
+ close(): Promise<void>;
24
+ }
25
+
26
+ const require_ = createRequire(import.meta.url);
27
+ const pkgDist = (name: string) => dirname(require_.resolve(name));
28
+
29
+ const MIME: Record<string, string> = { '.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8' };
30
+
31
+ function approvedFor(manifest: EmbedManifest | undefined, strict: boolean): ApprovedGrants {
32
+ if (strict || !manifest) return {};
33
+ // « tout approuver » : chaque capacité demandée est approuvée avec sa propre configuration (ceiling = demande)
34
+ const out: ApprovedGrants = {};
35
+ for (const id of CAPABILITY_IDS) {
36
+ const asked = manifest.capabilities[id];
37
+ if (asked !== undefined && !CAPABILITIES[id].defaultGrant) out[id] = asked;
38
+ }
39
+ return out;
40
+ }
41
+
42
+ export async function startSimulator(o: SimulatorOptions): Promise<Simulator> {
43
+ const appUrl = new URL(o.app);
44
+ let manifest: EmbedManifest | undefined;
45
+ if (o.manifest !== undefined) {
46
+ const r = validateManifest(o.manifest, { allowInsecureLocalhost: true });
47
+ if (!r.ok) throw new Error(`Manifeste invalide :\n- ${r.errors.join('\n- ')}`);
48
+ manifest = r.manifest;
49
+ }
50
+ const config = {
51
+ app: appUrl.href,
52
+ moduleName: manifest?.name ?? '@acme/esm-sim-app',
53
+ manifestCapabilities: manifest?.capabilities,
54
+ 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' },
56
+ };
57
+ const roots: Record<string, string> = { protocol: pkgDist('@egen-civitas/esm-embed-protocol'), host: pkgDist('@egen-civitas/esm-embed-host') };
58
+
59
+ const server = createServer(async (req, res) => {
60
+ const url = new URL(req.url ?? '/', 'http://x');
61
+ const send = (code: number, body: string | Buffer, type = 'text/plain; charset=utf-8') => {
62
+ res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
63
+ res.end(body);
64
+ };
65
+ try {
66
+ if (url.pathname === '/') return send(200, PAGE, 'text/html; charset=utf-8');
67
+ if (url.pathname === '/api/config') return send(200, JSON.stringify(config), MIME['.json']);
68
+ const m = /^\/vendor\/(protocol|host)\/(.+)$/.exec(url.pathname);
69
+ if (m) {
70
+ const root = roots[m[1]];
71
+ const file = normalize(join(root, m[2]));
72
+ if (!file.startsWith(root + sep) || !file.endsWith('.js')) return send(404, 'Introuvable');
73
+ return send(200, await readFile(file), MIME['.js']);
74
+ }
75
+ send(404, 'Introuvable');
76
+ } catch {
77
+ send(404, 'Introuvable');
78
+ }
79
+ });
80
+ await new Promise<void>((resolve) => server.listen(o.port ?? 4100, o.host ?? '127.0.0.1', resolve));
81
+ const addr = server.address() as AddressInfo;
82
+ return { url: `http://${o.host ?? '127.0.0.1'}:${addr.port}`, server, close: () => new Promise((r) => server.close(() => r())) };
83
+ }
84
+
85
+ const PAGE = `<!doctype html><html lang="fr"><head><meta charset="utf-8"><title>EGEN — simulateur de Shell</title>
86
+ <meta name="viewport" content="width=device-width,initial-scale=1">
87
+ <script type="importmap">{"imports":{"@egen-civitas/esm-embed-protocol":"/vendor/protocol/index.js"}}</script>
88
+ <style>
89
+ :root{color-scheme:light dark;--b:#d0d7de;font-family:system-ui,sans-serif}
90
+ body{margin:0;display:grid;grid-template-columns:1fr 360px;height:100vh}
91
+ #stage{min-width:0;display:flex}#stage iframe{flex:1;border:0}
92
+ aside{border-left:1px solid var(--b);padding:12px;overflow:auto;font-size:13px}
93
+ button{margin:2px 4px 2px 0;padding:4px 8px;cursor:pointer}
94
+ pre{white-space:pre-wrap;word-break:break-word;font-size:12px;max-height:50vh;overflow:auto;border:1px solid var(--b);padding:6px;border-radius:6px}
95
+ .toast{border:1px solid var(--b);border-radius:6px;padding:6px;margin:4px 0}
96
+ h1{font-size:14px;margin:0 0 8px}h2{font-size:12px;margin:12px 0 4px;text-transform:uppercase;opacity:.7}
97
+ </style></head><body>
98
+ <div id="stage"></div>
99
+ <aside><h1>Simulateur de Shell EGEN</h1>
100
+ <div id="info"></div>
101
+ <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>
103
+ <h2>Notifications</h2><div id="toasts"></div>
104
+ <h2>Journal des échanges</h2><pre id="log"></pre></aside>
105
+ <script type="module">
106
+ import { effectiveGrants } from '@egen-civitas/esm-embed-protocol';
107
+ import { createEmbedHost } from '/vendor/host/index.js';
108
+ const cfg = await (await fetch('/api/config')).json();
109
+ const $ = (id) => document.getElementById(id);
110
+ const log = (...a) => { $('log').textContent = new Date().toLocaleTimeString() + ' ' + a.map((x) => typeof x === 'string' ? x : JSON.stringify(x)).join(' ') + '\\n' + $('log').textContent; };
111
+ 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();
115
+ 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
+ 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 }),
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); } },
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
+ 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
+ };
126
+ const grants = effectiveGrants(cfg.manifestCapabilities, cfg.approved);
127
+ $('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
+ 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
+ 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
+ $('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
+ $('event').onclick = () => (topics.get('core.sim.ping') || []).forEach((f) => f({ at: Date.now() }));
134
+ </script></body></html>`;
@@ -0,0 +1,223 @@
1
+ import { effectiveGrants, type ApprovedGrants, type CapabilityId, type GrantConfig } from '@egen-civitas/esm-embed-protocol';
2
+ import type { ConnectOptions } from '@egen-civitas/esm-embed-client';
3
+ import { createBus, HostConnection, type ApiRequest, type ApiResponse, type HostProviders, type ThemeState } from '@egen-civitas/esm-embed-host';
4
+
5
+ export interface TestHostOptions {
6
+ moduleName?: string;
7
+ /** Origine simulée du Shell (à mettre dans `hostOrigins` de l'app). */
8
+ origin?: string;
9
+ /** Capacités demandées par le manifeste de l'app (défaut : aucune demande explicite = l'opérateur définit seul). */
10
+ manifestCapabilities?: Partial<Record<CapabilityId, GrantConfig>>;
11
+ /** Plafond fixé par l'opérateur (défaut : rien d'approuvé hors capacités « par défaut »). */
12
+ approved?: ApprovedGrants;
13
+ session?: Record<string, unknown>;
14
+ tenant?: { id: string | null };
15
+ locale?: string;
16
+ theme?: ThemeState;
17
+ config?: Record<string, unknown>;
18
+ flags?: Record<string, boolean>;
19
+ /** Permissions que l'utilisateur simulé possède. */
20
+ permissions?: string[];
21
+ api?: (req: ApiRequest) => ApiResponse | Promise<ApiResponse>;
22
+ confirm?: boolean | ((d: { title: string; message: string; danger?: boolean }) => boolean);
23
+ }
24
+
25
+ export interface CallRecord {
26
+ cap: string;
27
+ method: string;
28
+ args: unknown[];
29
+ }
30
+
31
+ export interface TestHost {
32
+ /** À passer à `connectToEgen({ ...host.connectOptions, capabilities: [...] })`. */
33
+ connectOptions: Pick<ConnectOptions, 'moduleName' | 'hostOrigins' | 'window' | 'host' | 'timeoutMs'>;
34
+ connection: HostConnection;
35
+ /** Journal des services du Core sollicités par l'app. */
36
+ calls: CallRecord[];
37
+ notifications: Array<{ kind: string; title: string; subtitle?: string }>;
38
+ published: Array<{ topic: string; payload: unknown; from: string }>;
39
+ tools: Map<string, { description: string }>;
40
+ /** Pousse un changement vers l'app (comme le ferait le Core). */
41
+ emit: {
42
+ session(v: Record<string, unknown>): void;
43
+ tenant(v: { id: string | null }): void;
44
+ locale(v: string): void;
45
+ theme(v: ThemeState): void;
46
+ config(v: Record<string, unknown>): void;
47
+ event(topic: string, payload?: unknown): void;
48
+ goto(path: string): void;
49
+ visibility(visible: boolean): void;
50
+ };
51
+ /** L'agent IA appelle un outil déclaré par l'app. */
52
+ invokeTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
53
+ destroy(): void;
54
+ }
55
+
56
+ function watchable<T>(initial: T) {
57
+ let value = initial;
58
+ const subs = new Set<(v: T) => void>();
59
+ return {
60
+ get: () => value,
61
+ subscribe: (cb: (v: T) => void) => (subs.add(cb), () => void subs.delete(cb)),
62
+ set: (v: T) => {
63
+ value = v;
64
+ subs.forEach((s) => s(v));
65
+ },
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Hôte EGEN de test, en mémoire : un vrai `HostConnection` (mêmes grants, mêmes refus, même dispatch fermé que le Core)
71
+ * relié à votre app par de fausses fenêtres et un vrai `MessageChannel`. Aucun navigateur, aucun Core.
72
+ *
73
+ * ```ts
74
+ * const sim = createTestHost({ session: { authenticated: true, user: { display: 'Sam' } } });
75
+ * const egen = await connectToEgen({ ...sim.connectOptions, capabilities: ['session'] });
76
+ * ```
77
+ */
78
+ export function createTestHost(o: TestHostOptions = {}): TestHost {
79
+ const moduleName = o.moduleName ?? '@acme/esm-test-app';
80
+ const origin = o.origin ?? 'https://shell.test';
81
+ const calls: CallRecord[] = [];
82
+ const notifications: TestHost['notifications'] = [];
83
+ const published: TestHost['published'] = [];
84
+ const tools = new Map<string, { description: string }>();
85
+ const toolInvokers = new Map<string, (name: string, args: Record<string, unknown>) => Promise<unknown>>();
86
+ const log = (cap: string, method: string, ...args: unknown[]) => void calls.push({ cap, method, args });
87
+
88
+ const session = watchable<Record<string, unknown> | undefined>(o.session ?? { authenticated: true });
89
+ const tenant = watchable(o.tenant ?? { id: null });
90
+ const locale = watchable(o.locale ?? 'fr');
91
+ const theme = watchable<ThemeState>(o.theme ?? { mode: 'light', tokens: {} });
92
+ const config = watchable(o.config ?? {});
93
+ const flagSubs = new Set<() => void>();
94
+ const eventSubs = new Map<string, Set<(p: unknown) => void>>();
95
+ const channel = createBus();
96
+
97
+ const wrapWatch = <T,>(cap: string, w: ReturnType<typeof watchable<T>>) => ({
98
+ get: () => {
99
+ log(cap, 'get');
100
+ return w.get();
101
+ },
102
+ subscribe: w.subscribe,
103
+ });
104
+
105
+ const providers: HostProviders = {
106
+ session: wrapWatch('session', session),
107
+ tenant: wrapWatch('tenant', tenant),
108
+ locale: wrapWatch('locale', locale),
109
+ theme: wrapWatch('theme', theme),
110
+ config: wrapWatch('config', config),
111
+ flags: {
112
+ isEnabled: (n) => {
113
+ log('flags', 'isEnabled', n);
114
+ return !!o.flags?.[n];
115
+ },
116
+ subscribe: (cb) => (flagSubs.add(cb), () => void flagSubs.delete(cb)),
117
+ },
118
+ permissions: {
119
+ can: (p) => {
120
+ log('permissions', 'can', p);
121
+ return !!o.permissions?.includes(p);
122
+ },
123
+ },
124
+ events: {
125
+ publish: (topic, payload, ctx) => {
126
+ log('events', 'publish', topic, payload);
127
+ published.push({ topic, payload, from: ctx.moduleName });
128
+ },
129
+ subscribe: (topic, cb) => {
130
+ let set = eventSubs.get(topic);
131
+ if (!set) eventSubs.set(topic, (set = new Set()));
132
+ set.add(cb);
133
+ return () => void set!.delete(cb);
134
+ },
135
+ },
136
+ notifications: {
137
+ show: (n) => {
138
+ log('notifications', 'show', n);
139
+ notifications.push(n);
140
+ },
141
+ },
142
+ dialogs: {
143
+ confirm: (d) => {
144
+ log('dialogs', 'confirm', d);
145
+ return typeof o.confirm === 'function' ? o.confirm(d) : (o.confirm ?? true);
146
+ },
147
+ },
148
+ api: {
149
+ fetch: async (req) => {
150
+ log('api', 'fetch', req);
151
+ return o.api ? o.api(req) : { status: 200, headers: { 'content-type': 'application/json' }, body: '{}' };
152
+ },
153
+ },
154
+ telemetry: { log: (l, m, c) => log('telemetry', 'log', l, m, c), metric: (n, v, t) => log('telemetry', 'metric', n, v, t) },
155
+ aiTools: {
156
+ register: (_m, list, invoke) => {
157
+ log('ai-tools', 'register', list.map((t) => t.name));
158
+ for (const t of list) {
159
+ tools.set(t.name, { description: t.description });
160
+ toolInvokers.set(t.name, invoke);
161
+ }
162
+ },
163
+ unregister: (_m, names) => {
164
+ for (const n of names) {
165
+ tools.delete(n);
166
+ toolInvokers.delete(n);
167
+ }
168
+ },
169
+ },
170
+ };
171
+
172
+ const appWindow = new EventTarget();
173
+ const hostWindow: { postMessage(message: unknown, targetOrigin: string): void } = {
174
+ postMessage: (message) => void queueMicrotask(() => connection.handle(message)),
175
+ };
176
+ const connection: HostConnection = new HostConnection({
177
+ moduleName,
178
+ grants: effectiveGrants(o.manifestCapabilities, o.approved ?? {}),
179
+ providers,
180
+ controls: {
181
+ channel,
182
+ report: (p) => log('navigation', 'report', p),
183
+ navigate: (t) => log('navigation', 'navigate', t),
184
+ setTitle: (t) => log('navigation', 'setTitle', t),
185
+ resize: (h) => log('navigation', 'resize', h),
186
+ onReady: () => log('lifecycle', 'ready'),
187
+ },
188
+ limits: { pingIntervalMs: 0 },
189
+ post: (message, transfer) => {
190
+ const ev: any = new Event('message');
191
+ ev.data = message;
192
+ ev.origin = origin;
193
+ ev.source = hostWindow;
194
+ ev.ports = transfer ?? [];
195
+ queueMicrotask(() => appWindow.dispatchEvent(ev));
196
+ },
197
+ });
198
+
199
+ return {
200
+ connectOptions: { moduleName, hostOrigins: [origin], window: appWindow as any, host: hostWindow as any, timeoutMs: 500 },
201
+ connection,
202
+ calls,
203
+ notifications,
204
+ published,
205
+ tools,
206
+ emit: {
207
+ session: (v) => session.set(v),
208
+ tenant: (v) => tenant.set(v),
209
+ locale: (v) => locale.set(v),
210
+ theme: (v) => theme.set(v),
211
+ config: (v) => config.set(v),
212
+ event: (topic, payload) => eventSubs.get(topic)?.forEach((cb) => cb(payload)),
213
+ goto: (path) => channel.emit('goto', { path, seq: Date.now() }),
214
+ visibility: (v) => channel.emit('visibility', v),
215
+ },
216
+ invokeTool: async (name, args = {}) => {
217
+ const inv = toolInvokers.get(name);
218
+ if (!inv) throw new Error(`Outil non enregistré : ${name}`);
219
+ return inv(name, args);
220
+ },
221
+ destroy: () => connection.destroy(),
222
+ };
223
+ }