@egen-civitas/sdk 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.
- package/CHANGELOG.md +15 -0
- package/README.md +33 -2
- package/dist/app.d.ts +53 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +169 -0
- package/dist/connect.d.ts +23 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +316 -0
- package/dist/errors.d.ts +11 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +18 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/standalone.d.ts +35 -0
- package/dist/standalone.d.ts.map +1 -0
- package/dist/standalone.js +412 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +1 -0
- package/package.json +62 -3
- package/src/app.ts +98 -0
- package/src/connect.ts +73 -0
- package/src/errors.ts +14 -0
- package/src/index.ts +8 -0
- package/src/standalone.ts +104 -0
- package/src/version.ts +2 -0
package/src/connect.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { EgenClient, connectToEgen, type ConnectOptions as EmbeddedOptions } from '@egen-civitas/esm-embed-client';
|
|
2
|
+
import { EmbedError, CAPABILITIES, CAPABILITY_IDS, type CapabilityId } from '@egen-civitas/esm-embed-protocol';
|
|
3
|
+
import { EgenApp, type EgenMode } from './app.js';
|
|
4
|
+
import { STANDALONE_CAPABILITIES, createStandaloneRuntime, type StandaloneOptions } from './standalone.js';
|
|
5
|
+
|
|
6
|
+
export interface ConnectOptions extends Omit<EmbeddedOptions, 'hostOrigins'> {
|
|
7
|
+
/** Origines EXACTES du Shell. Obligatoire pour le mode embarqué ; sans elles, `auto` reste en mode autonome. */
|
|
8
|
+
hostOrigins?: string[];
|
|
9
|
+
/**
|
|
10
|
+
* `auto` (défaut) : embarqué si la page est dans une iframe, autonome sinon ou si le Shell ne répond pas ;
|
|
11
|
+
* `embedded` : exige le Shell (échec explicite sinon) ; `standalone` : n'essaie jamais de se connecter.
|
|
12
|
+
*/
|
|
13
|
+
mode?: 'auto' | EgenMode;
|
|
14
|
+
/** Capacités sans lesquelles l'app ne peut pas fonctionner : `connect()` échoue si l'une manque. */
|
|
15
|
+
required?: CapabilityId[];
|
|
16
|
+
/** Comportement hors Shell. */
|
|
17
|
+
standalone?: StandaloneOptions;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const inIframe = (w?: unknown): boolean => {
|
|
21
|
+
if (w !== undefined) return true; // fenêtre injectée (tests) : on suppose un hôte
|
|
22
|
+
try {
|
|
23
|
+
return typeof window !== 'undefined' && window.parent !== window;
|
|
24
|
+
} catch {
|
|
25
|
+
return true; // accès à window.parent refusé : on est bien dans un cadre d'une autre origine
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function localClient(options: ConnectOptions): EgenClient {
|
|
30
|
+
const requested = (options.capabilities ?? CAPABILITY_IDS.filter((id) => CAPABILITIES[id].defaultGrant)).map((c) => (typeof c === 'string' ? c : (c.id as CapabilityId)));
|
|
31
|
+
const ids = new Set<CapabilityId>([...requested, ...(options.required ?? [])]);
|
|
32
|
+
const granted = [...ids]
|
|
33
|
+
.filter((id) => STANDALONE_CAPABILITIES.includes(id))
|
|
34
|
+
.map((id) => ({ id, version: CAPABILITIES[id].version, config: id === 'notifications' ? { exclusive: false } : {} }));
|
|
35
|
+
const denied = [...ids].filter((id) => !STANDALONE_CAPABILITIES.includes(id)).map((id) => ({ id, reason: 'UNAVAILABLE' as const }));
|
|
36
|
+
return new EgenClient({ connected: false, moduleName: options.moduleName, granted: granted as never, denied, rpc: createStandaloneRuntime(options.standalone) });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function enforceRequired(app: EgenApp, required: CapabilityId[] | undefined): EgenApp {
|
|
40
|
+
const missing = (required ?? []).filter((id) => !app.has(id));
|
|
41
|
+
if (missing.length) {
|
|
42
|
+
app.close();
|
|
43
|
+
throw new EmbedError('DENIED', `Capacités requises non accordées (${app.mode}) : ${missing.join(', ')}`);
|
|
44
|
+
}
|
|
45
|
+
return app;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Point d'entrée unique du SDK. Retourne toujours une `EgenApp` utilisable, sauf si `required` n'est pas satisfait
|
|
50
|
+
* ou si `mode: 'embedded'` est exigé sans Shell (erreurs typées `EgenError`).
|
|
51
|
+
*/
|
|
52
|
+
export async function connect(options: ConnectOptions): Promise<EgenApp> {
|
|
53
|
+
if (!options || typeof options.moduleName !== 'string' || !options.moduleName) throw new EmbedError('INVALID_ARGS', 'connect : moduleName est obligatoire');
|
|
54
|
+
const mode = options.mode ?? 'auto';
|
|
55
|
+
const standalone = (note: string) => enforceRequired(new EgenApp(localClient(options), 'standalone', note), options.required);
|
|
56
|
+
|
|
57
|
+
if (mode === 'standalone') return standalone('Mode autonome demandé explicitement.');
|
|
58
|
+
|
|
59
|
+
const origins = options.hostOrigins;
|
|
60
|
+
if (!origins || origins.length === 0) {
|
|
61
|
+
if (mode === 'embedded') throw new EmbedError('INVALID_ARGS', 'connect : hostOrigins est obligatoire en mode embedded');
|
|
62
|
+
return standalone('Aucune origine de Shell fournie (hostOrigins) : mode autonome.');
|
|
63
|
+
}
|
|
64
|
+
if (!inIframe(options.window)) {
|
|
65
|
+
if (mode === 'embedded') throw new EmbedError('UNSUPPORTED_IN_MODE', "connect : mode embedded exigé mais la page n'est pas dans une iframe du Shell");
|
|
66
|
+
return standalone("Page ouverte hors d'une iframe : mode autonome.");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const client = await connectToEgen({ ...options, hostOrigins: origins });
|
|
70
|
+
if (client.connected) return enforceRequired(new EgenApp(client, 'embedded'), options.required);
|
|
71
|
+
if (mode === 'embedded') throw new EmbedError('TIMEOUT', `Aucune réponse du Shell pour « ${options.moduleName} » (voir les pistes de diagnostic dans la console)`);
|
|
72
|
+
return standalone("Le Shell n'a pas répondu à la poignée de main : mode autonome.");
|
|
73
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { EmbedError, type ErrorCode } from '@egen-civitas/esm-embed-protocol';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Erreur typée du SDK. C'est la MÊME classe que celle du protocole : toute erreur levée par le client
|
|
5
|
+
* embarqué est donc reconnue par `instanceof EgenError` / `isEgenError`.
|
|
6
|
+
* Codes : DENIED, UNKNOWN_CAPABILITY, UNKNOWN_METHOD, INVALID_ARGS, TIMEOUT, RATE_LIMITED, TOO_LARGE, CLOSED, INTERNAL,
|
|
7
|
+
* NOT_FOUND, CANCELLED, QUOTA_EXCEEDED, UNSUPPORTED_IN_MODE.
|
|
8
|
+
*/
|
|
9
|
+
export { EmbedError as EgenError };
|
|
10
|
+
export type EgenErrorCode = ErrorCode;
|
|
11
|
+
|
|
12
|
+
export function isEgenError(e: unknown, code?: EgenErrorCode): e is EmbedError {
|
|
13
|
+
return e instanceof EmbedError && (code === undefined || e.code === code);
|
|
14
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { connect, type ConnectOptions } from './connect.js';
|
|
2
|
+
export { EgenApp, type Diagnosis, type EgenMode } from './app.js';
|
|
3
|
+
export { EgenError, isEgenError, type EgenErrorCode } from './errors.js';
|
|
4
|
+
export { createStandaloneRuntime, STANDALONE_CAPABILITIES, type StandaloneOptions } from './standalone.js';
|
|
5
|
+
export { SDK_VERSION } from './version.js';
|
|
6
|
+
// Compatibilité : les apps existantes gardent `connectToEgen` / `EgenClient` (dépréciation : voir roadmap §4).
|
|
7
|
+
export { connectToEgen, EgenClient } from '@egen-civitas/esm-embed-client';
|
|
8
|
+
export type { CapabilityId, CapabilityDenied, CapabilityGranted } from '@egen-civitas/esm-embed-protocol';
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { EmbedError, validateCall, type CapabilityId } from '@egen-civitas/esm-embed-protocol';
|
|
2
|
+
import type { RpcLike } from '@egen-civitas/esm-embed-client';
|
|
3
|
+
|
|
4
|
+
type Json = Record<string, unknown>;
|
|
5
|
+
|
|
6
|
+
/** Comportement de l'app HORS Shell (mode `standalone`) : la même application fonctionne sans EGEN (cahier §1). */
|
|
7
|
+
export interface StandaloneOptions {
|
|
8
|
+
tenantId?: string | null;
|
|
9
|
+
locale?: string;
|
|
10
|
+
/** Configuration publique servie par `config.get()`. */
|
|
11
|
+
config?: Json;
|
|
12
|
+
/** Drapeaux de fonctionnalité locaux. */
|
|
13
|
+
flags?: Record<string, boolean>;
|
|
14
|
+
/** Remplace `window.confirm` pour `dialogs.confirm`. */
|
|
15
|
+
confirm?: (d: { title: string; message: string; danger?: boolean }) => boolean | Promise<boolean>;
|
|
16
|
+
/** Reçoit `telemetry.log` / `telemetry.metric` (défaut : ignorés). */
|
|
17
|
+
onTelemetry?: (kind: 'log' | 'metric', data: unknown[]) => void;
|
|
18
|
+
/** Injectables pour les tests / hors navigateur. */
|
|
19
|
+
window?: Pick<Window, 'history' | 'document'> & { navigator?: { language?: string } };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type Handler = (args: unknown[]) => unknown | Promise<unknown>;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Runtime local qui sert les capacités du catalogue sans Shell. Il respecte la validation d'arguments du protocole
|
|
26
|
+
* (mêmes `INVALID_ARGS` qu'avec un hôte) ; ce qui n'a pas de sens hors Shell est refusé avec `UNSUPPORTED_IN_MODE`.
|
|
27
|
+
*/
|
|
28
|
+
export function createStandaloneRuntime(opts: StandaloneOptions = {}): RpcLike {
|
|
29
|
+
const win = opts.window ?? (typeof window !== 'undefined' ? (window as unknown as NonNullable<StandaloneOptions['window']>) : undefined);
|
|
30
|
+
const listeners = new Map<string, Set<(v: unknown) => void>>();
|
|
31
|
+
let closed = false;
|
|
32
|
+
let seq = 0;
|
|
33
|
+
const emit = (cap: string, ev: string, v: unknown) => listeners.get(`${cap}:${ev}`)?.forEach((cb) => cb(v));
|
|
34
|
+
const unsupported = (what: string) => new EmbedError('UNSUPPORTED_IN_MODE', `${what} : indisponible hors du Shell EGEN (mode autonome)`);
|
|
35
|
+
|
|
36
|
+
const handlers: Record<string, Record<string, Handler>> = {
|
|
37
|
+
tenant: { get: () => ({ id: opts.tenantId ?? null }) },
|
|
38
|
+
locale: { get: () => opts.locale ?? win?.navigator?.language ?? 'fr' },
|
|
39
|
+
config: { get: () => ({ ...(opts.config ?? {}) }) },
|
|
40
|
+
flags: { isEnabled: ([name]) => !!opts.flags?.[name as string] },
|
|
41
|
+
telemetry: {
|
|
42
|
+
log: (a) => void opts.onTelemetry?.('log', a),
|
|
43
|
+
metric: (a) => void opts.onTelemetry?.('metric', a),
|
|
44
|
+
},
|
|
45
|
+
lifecycle: { ready: () => undefined },
|
|
46
|
+
extensions: { list: () => [] },
|
|
47
|
+
events: { publish: ([topic, payload]) => void emit('events', topic as string, payload) },
|
|
48
|
+
notifications: { show: () => ({ displayed: false }) },
|
|
49
|
+
dialogs: {
|
|
50
|
+
confirm: async ([d]) => {
|
|
51
|
+
if (opts.confirm) return !!(await opts.confirm(d as never));
|
|
52
|
+
const g = globalThis as { confirm?: (m: string) => boolean };
|
|
53
|
+
if (typeof g.confirm === 'function') return g.confirm(String((d as Json).message));
|
|
54
|
+
throw unsupported('dialogs.confirm');
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
navigation: {
|
|
58
|
+
report: ([path, o]) => {
|
|
59
|
+
const replace = !!(o as Json | undefined)?.replace;
|
|
60
|
+
const title = (o as Json | undefined)?.title as string | undefined;
|
|
61
|
+
if (win) (replace ? win.history.replaceState : win.history.pushState).call(win.history, null, '', path as string);
|
|
62
|
+
if (title && win) win.document.title = title;
|
|
63
|
+
},
|
|
64
|
+
navigate: ([to]) => {
|
|
65
|
+
win?.history.pushState(null, '', to as string);
|
|
66
|
+
emit('navigation', 'goto', { path: to, seq: ++seq });
|
|
67
|
+
},
|
|
68
|
+
notFound: () => undefined,
|
|
69
|
+
setTitle: ([t]) => {
|
|
70
|
+
if (win) win.document.title = t as string;
|
|
71
|
+
},
|
|
72
|
+
resize: () => undefined,
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
get closed() {
|
|
78
|
+
return closed;
|
|
79
|
+
},
|
|
80
|
+
async call<T>(cap: string, method: string, args: unknown[] = []): Promise<T> {
|
|
81
|
+
if (closed) throw new EmbedError('CLOSED', 'Connexion fermée');
|
|
82
|
+
const invalid = validateCall(cap, method, args);
|
|
83
|
+
if (invalid) throw new EmbedError('INVALID_ARGS', invalid);
|
|
84
|
+
const h = handlers[cap]?.[method];
|
|
85
|
+
if (!h) throw unsupported(`${cap}.${method}`);
|
|
86
|
+
return (await h(args)) as T;
|
|
87
|
+
},
|
|
88
|
+
async subscribe(cap: string, ev: string, cb: (v: unknown) => void) {
|
|
89
|
+
if (closed) throw new EmbedError('CLOSED', 'Connexion fermée');
|
|
90
|
+
const key = `${cap}:${ev}`;
|
|
91
|
+
let set = listeners.get(key);
|
|
92
|
+
if (!set) listeners.set(key, (set = new Set()));
|
|
93
|
+
set.add(cb);
|
|
94
|
+
return () => void set!.delete(cb);
|
|
95
|
+
},
|
|
96
|
+
close() {
|
|
97
|
+
closed = true;
|
|
98
|
+
listeners.clear();
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Capacités servies localement en mode autonome. */
|
|
104
|
+
export const STANDALONE_CAPABILITIES: readonly CapabilityId[] = ['tenant', 'locale', 'config', 'flags', 'telemetry', 'lifecycle', 'extensions', 'events', 'notifications', 'dialogs', 'navigation'];
|
package/src/version.ts
ADDED