@egen-civitas/esm-nextjs-utils 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 +14 -0
- package/README.md +70 -2
- package/dist/client.d.ts +31 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +158 -0
- package/dist/host.d.ts +31 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +125 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/nextjs-utils.test.js +952 -0
- package/dist/protocol.d.ts +54 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +83 -0
- package/package.json +84 -3
- package/src/client.ts +94 -0
- package/src/host.ts +144 -0
- package/src/index.ts +2 -0
- package/src/protocol.ts +71 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Protocole du pont Shell ↔ application embarquée (iframe). Version 1.
|
|
3
|
+
* Toutes les messages sont enveloppés : `{ egen: 1, moduleName, message }`.
|
|
4
|
+
*/
|
|
5
|
+
export declare const EGEN_EMBED_PROTOCOL = 1;
|
|
6
|
+
/** Données initiales transmises à l'application embarquée. */
|
|
7
|
+
export interface EmbedInit {
|
|
8
|
+
moduleName: string;
|
|
9
|
+
/** Langue courante (i18next du Shell). */
|
|
10
|
+
locale?: string;
|
|
11
|
+
/** Base d'URL du Shell (`getEgenSpaBase()`), pour construire des liens. */
|
|
12
|
+
spaBase: string;
|
|
13
|
+
/** Session filtrée par liste blanche (voir `sessionFields`) ; absente tant que non chargée. */
|
|
14
|
+
session?: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
export type HostToEmbed = {
|
|
17
|
+
kind: 'init';
|
|
18
|
+
payload: EmbedInit;
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'session';
|
|
21
|
+
session: Record<string, unknown>;
|
|
22
|
+
} | {
|
|
23
|
+
kind: 'locale';
|
|
24
|
+
locale: string;
|
|
25
|
+
};
|
|
26
|
+
export type EmbedToHost = {
|
|
27
|
+
kind: 'ready';
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'navigate';
|
|
30
|
+
to: string;
|
|
31
|
+
} | {
|
|
32
|
+
kind: 'resize';
|
|
33
|
+
height: number;
|
|
34
|
+
} | {
|
|
35
|
+
kind: 'title';
|
|
36
|
+
title: string;
|
|
37
|
+
};
|
|
38
|
+
export interface Envelope<T> {
|
|
39
|
+
egen: typeof EGEN_EMBED_PROTOCOL;
|
|
40
|
+
moduleName: string;
|
|
41
|
+
message: T;
|
|
42
|
+
}
|
|
43
|
+
export declare function wrap<T>(moduleName: string, message: T): Envelope<T>;
|
|
44
|
+
export declare function isEnvelope(data: unknown, moduleName: string): data is Envelope<{
|
|
45
|
+
kind: string;
|
|
46
|
+
}>;
|
|
47
|
+
/**
|
|
48
|
+
* Champs de session transmis par défaut. `sessionId` n'est JAMAIS dans cette liste : un identifiant
|
|
49
|
+
* de session ne doit pas être confié à une application tierce embarquée.
|
|
50
|
+
*/
|
|
51
|
+
export declare const DEFAULT_SESSION_FIELDS: string[];
|
|
52
|
+
/** Copie uniquement les chemins listés (notation pointée). */
|
|
53
|
+
export declare function pickFields(source: unknown, fields: string[]): Record<string, unknown>;
|
|
54
|
+
//# sourceMappingURL=protocol.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC,8DAA8D;AAC9D,MAAM,WAAW,SAAS;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,0CAA0C;IAC1C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2EAA2E;IAC3E,OAAO,EAAE,MAAM,CAAC;IAChB,+FAA+F;IAC/F,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED,MAAM,MAAM,WAAW,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,SAAS,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GACrD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvC,MAAM,MAAM,WAAW,GACnB;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAErC,MAAM,WAAW,QAAQ,CAAC,CAAC;IACzB,IAAI,EAAE,OAAO,mBAAmB,CAAC;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,CAAC,CAAC;CACZ;AAED,wBAAgB,IAAI,CAAC,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAEnE;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,IAAI,QAAQ,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAWhG;AAED;;;GAGG;AACH,eAAO,MAAM,sBAAsB,UAA8F,CAAC;AAElI,8DAA8D;AAC9D,wBAAgB,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYrF"}
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
function _type_of(obj) {
|
|
2
|
+
"@swc/helpers - typeof";
|
|
3
|
+
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Protocole du pont Shell ↔ application embarquée (iframe). Version 1.
|
|
7
|
+
* Toutes les messages sont enveloppés : `{ egen: 1, moduleName, message }`.
|
|
8
|
+
*/ export var EGEN_EMBED_PROTOCOL = 1;
|
|
9
|
+
export function wrap(moduleName, message) {
|
|
10
|
+
return {
|
|
11
|
+
egen: EGEN_EMBED_PROTOCOL,
|
|
12
|
+
moduleName: moduleName,
|
|
13
|
+
message: message
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function isEnvelope(data, moduleName) {
|
|
17
|
+
var d = data;
|
|
18
|
+
return !!d && (typeof d === "undefined" ? "undefined" : _type_of(d)) === 'object' && d.egen === EGEN_EMBED_PROTOCOL && d.moduleName === moduleName && !!d.message && _type_of(d.message) === 'object' && typeof d.message.kind === 'string';
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Champs de session transmis par défaut. `sessionId` n'est JAMAIS dans cette liste : un identifiant
|
|
22
|
+
* de session ne doit pas être confié à une application tierce embarquée.
|
|
23
|
+
*/ export var DEFAULT_SESSION_FIELDS = [
|
|
24
|
+
'authenticated',
|
|
25
|
+
'locale',
|
|
26
|
+
'allowedLocales',
|
|
27
|
+
'user.uuid',
|
|
28
|
+
'user.display',
|
|
29
|
+
'user.username'
|
|
30
|
+
];
|
|
31
|
+
/** Copie uniquement les chemins listés (notation pointée). */ export function pickFields(source, fields) {
|
|
32
|
+
var out = {};
|
|
33
|
+
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
34
|
+
try {
|
|
35
|
+
var _loop = function() {
|
|
36
|
+
var path = _step.value;
|
|
37
|
+
var keys = path.split('.');
|
|
38
|
+
var from = source;
|
|
39
|
+
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
40
|
+
try {
|
|
41
|
+
for(var _iterator = keys[Symbol.iterator](), _step1; !(_iteratorNormalCompletion = (_step1 = _iterator.next()).done); _iteratorNormalCompletion = true){
|
|
42
|
+
var k = _step1.value;
|
|
43
|
+
from = from != null && (typeof from === "undefined" ? "undefined" : _type_of(from)) === 'object' ? from[k] : undefined;
|
|
44
|
+
}
|
|
45
|
+
} catch (err) {
|
|
46
|
+
_didIteratorError = true;
|
|
47
|
+
_iteratorError = err;
|
|
48
|
+
} finally{
|
|
49
|
+
try {
|
|
50
|
+
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
51
|
+
_iterator.return();
|
|
52
|
+
}
|
|
53
|
+
} finally{
|
|
54
|
+
if (_didIteratorError) {
|
|
55
|
+
throw _iteratorError;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (from === undefined) return "continue";
|
|
60
|
+
var to = out;
|
|
61
|
+
keys.slice(0, -1).forEach(function(k) {
|
|
62
|
+
var _to, _k, _;
|
|
63
|
+
return to = (_ = (_to = to)[_k = k]) !== null && _ !== void 0 ? _ : _to[_k] = {};
|
|
64
|
+
});
|
|
65
|
+
to[keys[keys.length - 1]] = from;
|
|
66
|
+
};
|
|
67
|
+
for(var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
|
|
68
|
+
} catch (err) {
|
|
69
|
+
_didIteratorError = true;
|
|
70
|
+
_iteratorError = err;
|
|
71
|
+
} finally{
|
|
72
|
+
try {
|
|
73
|
+
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
74
|
+
_iterator.return();
|
|
75
|
+
}
|
|
76
|
+
} finally{
|
|
77
|
+
if (_didIteratorError) {
|
|
78
|
+
throw _iteratorError;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@egen-civitas/esm-nextjs-utils",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"license": "MPL-2.0",
|
|
5
|
+
"description": "Intégration d'applications autonomes (Next.js, SSR, routeur propre) à EGEN par iframe et pont postMessage sécurisé : lifecycle côté Shell et client côté application",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"src",
|
|
11
|
+
"!src/**/*.test.*"
|
|
12
|
+
],
|
|
13
|
+
"module": "dist/index.js",
|
|
14
|
+
"types": "dist/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./client": {
|
|
21
|
+
"types": "./dist/client.d.ts",
|
|
22
|
+
"default": "./dist/client.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": {
|
|
25
|
+
"default": "./package.json"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"source": true,
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "cross-env TZ=UTC vitest run --passWithNoTests",
|
|
31
|
+
"test:watch": "cross-env TZ=UTC vitest watch --passWithNoTests",
|
|
32
|
+
"build": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist\" \"tsc --project tsconfig.build.json\"",
|
|
33
|
+
"build:development": "rimraf dist && concurrently \"swc --strip-leading-paths src -d dist\" \"tsc --project tsconfig.build.json\"",
|
|
34
|
+
"typescript": "tsc --project tsconfig.build.json",
|
|
35
|
+
"lint": "eslint src --ext ts,tsx"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"egen",
|
|
39
|
+
"microfrontends",
|
|
40
|
+
"nextjs",
|
|
41
|
+
"iframe"
|
|
42
|
+
],
|
|
43
|
+
"directories": {
|
|
44
|
+
"lib": "dist",
|
|
45
|
+
"src": "src"
|
|
46
|
+
},
|
|
47
|
+
"browserslist": [
|
|
48
|
+
"extends browserslist-config-egen"
|
|
49
|
+
],
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/amourgit/Frontend-esm-framework.git",
|
|
53
|
+
"directory": "packages/framework/esm-nextjs-utils"
|
|
54
|
+
},
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/amourgit/Frontend-esm-framework/issues"
|
|
57
|
+
},
|
|
58
|
+
"homepage": "https://github.com/amourgit/Frontend-esm-framework#readme",
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
},
|
|
62
|
+
"dependencies": {
|
|
63
|
+
"@egen-civitas/esm-integration-utils": "^0.2.0"
|
|
64
|
+
},
|
|
65
|
+
"peerDependencies": {
|
|
66
|
+
"@egen-civitas/esm-api": ">=3.0.0",
|
|
67
|
+
"@egen-civitas/esm-config": ">=2.0.0",
|
|
68
|
+
"@egen-civitas/esm-extensions": ">=2.0.0",
|
|
69
|
+
"@egen-civitas/esm-feature-flags": ">=1.0.0",
|
|
70
|
+
"@egen-civitas/esm-globals": ">=2.5.0",
|
|
71
|
+
"@egen-civitas/esm-integration-utils": ">=0.2.0",
|
|
72
|
+
"single-spa": "6.x"
|
|
73
|
+
},
|
|
74
|
+
"devDependencies": {
|
|
75
|
+
"@swc/cli": "0.8.1",
|
|
76
|
+
"@swc/core": "1.15.21",
|
|
77
|
+
"@types/node": "^20",
|
|
78
|
+
"concurrently": "^9.2.1",
|
|
79
|
+
"cross-env": "^10.1.0",
|
|
80
|
+
"happy-dom": "^20.6.0",
|
|
81
|
+
"rimraf": "^6.1.3",
|
|
82
|
+
"single-spa": "^6.0.0",
|
|
83
|
+
"typescript": "^5.8.3",
|
|
84
|
+
"vitest": "^4.1.2",
|
|
85
|
+
"zustand": "^4.5.5"
|
|
86
|
+
}
|
|
6
87
|
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Côté application embarquée (Next.js ou autre) : s'exécute DANS l'iframe, sans dépendance au Framework.
|
|
3
|
+
* Ne l'utiliser que côté navigateur (dans un `useEffect` pour Next.js : pas pendant le rendu serveur).
|
|
4
|
+
*/
|
|
5
|
+
import { isEnvelope, wrap, type EmbedInit, type EmbedToHost, type HostToEmbed } from './protocol.js';
|
|
6
|
+
|
|
7
|
+
export type { EmbedInit } from './protocol.js';
|
|
8
|
+
|
|
9
|
+
export interface EgenBridgeOptions {
|
|
10
|
+
/** Nom du module (identique à `moduleName` du lifecycle côté Shell). */
|
|
11
|
+
moduleName: string;
|
|
12
|
+
/** Origines du Shell autorisées. Obligatoire, jamais « * ». */
|
|
13
|
+
allowedHostOrigins: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface EgenBridge {
|
|
17
|
+
/** Résolue à la réception des données initiales du Shell. */
|
|
18
|
+
ready: Promise<EmbedInit>;
|
|
19
|
+
/** Dernières données connues (session, langue). */
|
|
20
|
+
getState(): Partial<EmbedInit>;
|
|
21
|
+
/** S'abonne aux changements (session, langue) ; renvoie le désabonnement. */
|
|
22
|
+
subscribe(listener: (state: Partial<EmbedInit>) => void): () => void;
|
|
23
|
+
/** Demande une navigation du Shell vers un chemin interne (`/accueil`). */
|
|
24
|
+
navigate(to: string): void;
|
|
25
|
+
/** Annonce la hauteur du contenu (le Shell redimensionne l'iframe). */
|
|
26
|
+
setHeight(height: number): void;
|
|
27
|
+
/** Annonce un titre accessible pour l'iframe. */
|
|
28
|
+
setTitle(title: string): void;
|
|
29
|
+
/** Annonce automatiquement la hauteur du document (ResizeObserver). */
|
|
30
|
+
autoResize(): () => void;
|
|
31
|
+
destroy(): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createEgenBridge(opts: EgenBridgeOptions): EgenBridge {
|
|
35
|
+
if (!opts.allowedHostOrigins?.length || opts.allowedHostOrigins.some((o) => o === '*' || o === 'null')) {
|
|
36
|
+
throw new Error('allowedHostOrigins : au moins une origine explicite est requise (jamais « * »).');
|
|
37
|
+
}
|
|
38
|
+
const host = window.parent;
|
|
39
|
+
if (host === window) throw new Error("createEgenBridge doit s'exécuter dans une iframe affichée par le Shell EGEN.");
|
|
40
|
+
|
|
41
|
+
let state: Partial<EmbedInit> = {};
|
|
42
|
+
const listeners = new Set<(s: Partial<EmbedInit>) => void>();
|
|
43
|
+
let resolveReady!: (i: EmbedInit) => void;
|
|
44
|
+
const ready = new Promise<EmbedInit>((r) => (resolveReady = r));
|
|
45
|
+
// L'origine du Shell n'est connue qu'à la première réponse : le message `ready` est donc envoyé à chaque origine autorisée.
|
|
46
|
+
let hostOrigin: string | undefined;
|
|
47
|
+
|
|
48
|
+
const emit = () => listeners.forEach((l) => l(state));
|
|
49
|
+
const onMessage = (event: MessageEvent) => {
|
|
50
|
+
if (event.source !== host || !opts.allowedHostOrigins.includes(event.origin)) return;
|
|
51
|
+
if (!isEnvelope(event.data, opts.moduleName)) return;
|
|
52
|
+
hostOrigin = event.origin;
|
|
53
|
+
const msg = event.data.message as HostToEmbed;
|
|
54
|
+
if (msg.kind === 'init') {
|
|
55
|
+
state = { ...msg.payload };
|
|
56
|
+
resolveReady(msg.payload);
|
|
57
|
+
emit();
|
|
58
|
+
} else if (msg.kind === 'session') {
|
|
59
|
+
state = { ...state, session: msg.session };
|
|
60
|
+
emit();
|
|
61
|
+
} else if (msg.kind === 'locale') {
|
|
62
|
+
state = { ...state, locale: msg.locale };
|
|
63
|
+
emit();
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
window.addEventListener('message', onMessage);
|
|
67
|
+
|
|
68
|
+
const send = (message: EmbedToHost) => {
|
|
69
|
+
const targets = hostOrigin ? [hostOrigin] : opts.allowedHostOrigins;
|
|
70
|
+
targets.forEach((o) => host.postMessage(wrap(opts.moduleName, message), o));
|
|
71
|
+
};
|
|
72
|
+
send({ kind: 'ready' });
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
ready,
|
|
76
|
+
getState: () => state,
|
|
77
|
+
subscribe(l) {
|
|
78
|
+
listeners.add(l);
|
|
79
|
+
return () => listeners.delete(l);
|
|
80
|
+
},
|
|
81
|
+
navigate: (to) => send({ kind: 'navigate', to }),
|
|
82
|
+
setHeight: (height) => send({ kind: 'resize', height }),
|
|
83
|
+
setTitle: (title) => send({ kind: 'title', title }),
|
|
84
|
+
autoResize() {
|
|
85
|
+
const ro = new ResizeObserver(() => send({ kind: 'resize', height: document.documentElement.scrollHeight }));
|
|
86
|
+
ro.observe(document.documentElement);
|
|
87
|
+
return () => ro.disconnect();
|
|
88
|
+
},
|
|
89
|
+
destroy() {
|
|
90
|
+
window.removeEventListener('message', onMessage);
|
|
91
|
+
listeners.clear();
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { LifeCycles } from 'single-spa';
|
|
2
|
+
import {
|
|
3
|
+
assertLifecycleOptions,
|
|
4
|
+
resolveMountTarget,
|
|
5
|
+
toLifecycleExport,
|
|
6
|
+
watchSession,
|
|
7
|
+
watchTranslations,
|
|
8
|
+
type LifecycleExport,
|
|
9
|
+
type LifecycleOptions,
|
|
10
|
+
type Unsubscribe,
|
|
11
|
+
} from '@egen-civitas/esm-integration-utils';
|
|
12
|
+
import { DEFAULT_SESSION_FIELDS, isEnvelope, pickFields, wrap, type EmbedToHost, type HostToEmbed } from './protocol.js';
|
|
13
|
+
|
|
14
|
+
export interface EmbedLifecycleOptions extends LifecycleOptions {
|
|
15
|
+
/** URL de l'application embarquée (ou fonction des props Single-SPA). */
|
|
16
|
+
url: string | ((props: Record<string, any>) => string);
|
|
17
|
+
/** Origine autorisée pour les messages (défaut : origine de `url`). Jamais de « * ». */
|
|
18
|
+
allowedOrigin?: string;
|
|
19
|
+
/** Champs de session transmis (notation pointée). Défaut : `DEFAULT_SESSION_FIELDS` (sans `sessionId`). */
|
|
20
|
+
sessionFields?: string[];
|
|
21
|
+
/** Attribut `sandbox` de l'iframe (défaut : scripts + même origine + formulaires + popups). */
|
|
22
|
+
sandbox?: string;
|
|
23
|
+
/** Titre accessible de l'iframe. */
|
|
24
|
+
title?: string;
|
|
25
|
+
/** Hauteur minimale en px tant que l'application n'a pas annoncé la sienne (défaut 400). */
|
|
26
|
+
minHeight?: number;
|
|
27
|
+
/** Navigation demandée par l'application (défaut : `singleSpaNavigate(spaBase + chemin)`). */
|
|
28
|
+
onNavigate?: (to: string) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';
|
|
32
|
+
const SAFE_PATH = /^\/(?!\/)[^\s\\]*$/;
|
|
33
|
+
|
|
34
|
+
/** Chemin relatif interne uniquement (`/x`), jamais d'URL absolue ni `//hôte`. */
|
|
35
|
+
export function isSafeInternalPath(to: unknown): to is string {
|
|
36
|
+
return typeof to === 'string' && SAFE_PATH.test(to);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Lifecycles Single-SPA qui affichent une application autonome (ex. Next.js avec SSR) dans une iframe
|
|
41
|
+
* et la relient au Shell par un pont `postMessage` :
|
|
42
|
+
* Shell → app : langue, session filtrée ; app → Shell : prêt, navigation, hauteur, titre.
|
|
43
|
+
* Sécurité : messages acceptés seulement de l'iframe elle-même ET de l'origine autorisée ; envoi toujours
|
|
44
|
+
* avec une origine cible explicite ; navigation limitée aux chemins internes.
|
|
45
|
+
*/
|
|
46
|
+
export function getEmbedLifecycle(userOpts: EmbedLifecycleOptions): LifeCycles {
|
|
47
|
+
assertLifecycleOptions(userOpts);
|
|
48
|
+
const opts = userOpts;
|
|
49
|
+
const fields = opts.sessionFields ?? DEFAULT_SESSION_FIELDS;
|
|
50
|
+
const mounted = new Map<string, { iframe: HTMLIFrameElement; stop: Unsubscribe[] }>();
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
bootstrap: () => Promise.resolve(),
|
|
54
|
+
mount: (props: any) => {
|
|
55
|
+
const target = resolveMountTarget(props);
|
|
56
|
+
const src = typeof opts.url === 'function' ? opts.url(props) : opts.url;
|
|
57
|
+
const origin = opts.allowedOrigin ?? new URL(src, window.location.href).origin;
|
|
58
|
+
if (origin === '*' || origin === 'null') throw new Error('allowedOrigin invalide : une origine explicite est requise.');
|
|
59
|
+
|
|
60
|
+
const sandbox = opts.sandbox ?? DEFAULT_SANDBOX;
|
|
61
|
+
if (origin === window.location.origin && /allow-scripts/.test(sandbox) && /allow-same-origin/.test(sandbox)) {
|
|
62
|
+
console.warn(
|
|
63
|
+
`[egen] ${opts.moduleName} : application embarquée de même origine que le Shell avec « allow-scripts allow-same-origin » : ` +
|
|
64
|
+
"le bac à sable est sans effet. Héberger l'application sur une autre origine (sous-domaine).",
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const iframe = document.createElement('iframe');
|
|
68
|
+
iframe.src = src;
|
|
69
|
+
iframe.title = opts.title ?? opts.featureName;
|
|
70
|
+
iframe.setAttribute('sandbox', sandbox);
|
|
71
|
+
iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
|
|
72
|
+
iframe.style.cssText = `width:100%;border:0;display:block;min-height:${opts.minHeight ?? 400}px`;
|
|
73
|
+
|
|
74
|
+
const send = (message: HostToEmbed) => iframe.contentWindow?.postMessage(wrap(opts.moduleName, message), origin);
|
|
75
|
+
const stop: Unsubscribe[] = [];
|
|
76
|
+
let ready = false;
|
|
77
|
+
let lastSession: Record<string, unknown> | undefined;
|
|
78
|
+
|
|
79
|
+
const onMessage = (event: MessageEvent) => {
|
|
80
|
+
if (event.source !== iframe.contentWindow || event.origin !== origin) return;
|
|
81
|
+
if (!isEnvelope(event.data, opts.moduleName)) return;
|
|
82
|
+
const msg = event.data.message as EmbedToHost;
|
|
83
|
+
switch (msg.kind) {
|
|
84
|
+
case 'ready':
|
|
85
|
+
ready = true;
|
|
86
|
+
send({
|
|
87
|
+
kind: 'init',
|
|
88
|
+
payload: {
|
|
89
|
+
moduleName: opts.moduleName,
|
|
90
|
+
locale: (window as any).i18next?.language,
|
|
91
|
+
spaBase: (window as any).getEgenSpaBase?.() ?? '/',
|
|
92
|
+
session: lastSession,
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
break;
|
|
96
|
+
case 'navigate':
|
|
97
|
+
if (isSafeInternalPath(msg.to)) {
|
|
98
|
+
(opts.onNavigate ?? ((to) => (window as any).singleSpaNavigate?.(((window as any).getEgenSpaBase?.() ?? '/') + to.replace(/^\//, ''))))(msg.to);
|
|
99
|
+
}
|
|
100
|
+
break;
|
|
101
|
+
case 'resize':
|
|
102
|
+
if (Number.isFinite(msg.height) && msg.height >= 0) iframe.style.height = `${Math.min(Math.ceil(msg.height), 100_000)}px`;
|
|
103
|
+
break;
|
|
104
|
+
case 'title':
|
|
105
|
+
if (typeof msg.title === 'string') iframe.title = msg.title.slice(0, 200);
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
window.addEventListener('message', onMessage);
|
|
110
|
+
stop.push(() => window.removeEventListener('message', onMessage));
|
|
111
|
+
|
|
112
|
+
stop.push(
|
|
113
|
+
watchSession((session) => {
|
|
114
|
+
lastSession = pickFields(session, fields);
|
|
115
|
+
if (ready) send({ kind: 'session', session: lastSession });
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
stop.push(
|
|
119
|
+
watchTranslations(() => {
|
|
120
|
+
const locale = (window as any).i18next?.language;
|
|
121
|
+
if (ready && locale) send({ kind: 'locale', locale });
|
|
122
|
+
}),
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
target.appendChild(iframe);
|
|
126
|
+
mounted.set(props.name, { iframe, stop });
|
|
127
|
+
return Promise.resolve();
|
|
128
|
+
},
|
|
129
|
+
unmount: (props: any) => {
|
|
130
|
+
const m = mounted.get(props.name);
|
|
131
|
+
if (m) {
|
|
132
|
+
m.stop.forEach((s) => s());
|
|
133
|
+
m.iframe.remove();
|
|
134
|
+
mounted.delete(props.name);
|
|
135
|
+
}
|
|
136
|
+
return Promise.resolve();
|
|
137
|
+
},
|
|
138
|
+
} as LifeCycles;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Export prêt pour `routes.json` : fonction → promesse de lifecycles. */
|
|
142
|
+
export function getSyncLifecycle(options: EmbedLifecycleOptions): LifecycleExport {
|
|
143
|
+
return toLifecycleExport(getEmbedLifecycle(options));
|
|
144
|
+
}
|
package/src/index.ts
ADDED
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Protocole du pont Shell ↔ application embarquée (iframe). Version 1.
|
|
3
|
+
* Toutes les messages sont enveloppés : `{ egen: 1, moduleName, message }`.
|
|
4
|
+
*/
|
|
5
|
+
export const EGEN_EMBED_PROTOCOL = 1;
|
|
6
|
+
|
|
7
|
+
/** Données initiales transmises à l'application embarquée. */
|
|
8
|
+
export interface EmbedInit {
|
|
9
|
+
moduleName: string;
|
|
10
|
+
/** Langue courante (i18next du Shell). */
|
|
11
|
+
locale?: string;
|
|
12
|
+
/** Base d'URL du Shell (`getEgenSpaBase()`), pour construire des liens. */
|
|
13
|
+
spaBase: string;
|
|
14
|
+
/** Session filtrée par liste blanche (voir `sessionFields`) ; absente tant que non chargée. */
|
|
15
|
+
session?: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type HostToEmbed =
|
|
19
|
+
| { kind: 'init'; payload: EmbedInit }
|
|
20
|
+
| { kind: 'session'; session: Record<string, unknown> }
|
|
21
|
+
| { kind: 'locale'; locale: string };
|
|
22
|
+
|
|
23
|
+
export type EmbedToHost =
|
|
24
|
+
| { kind: 'ready' }
|
|
25
|
+
| { kind: 'navigate'; to: string }
|
|
26
|
+
| { kind: 'resize'; height: number }
|
|
27
|
+
| { kind: 'title'; title: string };
|
|
28
|
+
|
|
29
|
+
export interface Envelope<T> {
|
|
30
|
+
egen: typeof EGEN_EMBED_PROTOCOL;
|
|
31
|
+
moduleName: string;
|
|
32
|
+
message: T;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function wrap<T>(moduleName: string, message: T): Envelope<T> {
|
|
36
|
+
return { egen: EGEN_EMBED_PROTOCOL, moduleName, message };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isEnvelope(data: unknown, moduleName: string): data is Envelope<{ kind: string }> {
|
|
40
|
+
const d = data as Envelope<{ kind?: unknown }> | null;
|
|
41
|
+
return (
|
|
42
|
+
!!d &&
|
|
43
|
+
typeof d === 'object' &&
|
|
44
|
+
d.egen === EGEN_EMBED_PROTOCOL &&
|
|
45
|
+
d.moduleName === moduleName &&
|
|
46
|
+
!!d.message &&
|
|
47
|
+
typeof d.message === 'object' &&
|
|
48
|
+
typeof d.message.kind === 'string'
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Champs de session transmis par défaut. `sessionId` n'est JAMAIS dans cette liste : un identifiant
|
|
54
|
+
* de session ne doit pas être confié à une application tierce embarquée.
|
|
55
|
+
*/
|
|
56
|
+
export const DEFAULT_SESSION_FIELDS = ['authenticated', 'locale', 'allowedLocales', 'user.uuid', 'user.display', 'user.username'];
|
|
57
|
+
|
|
58
|
+
/** Copie uniquement les chemins listés (notation pointée). */
|
|
59
|
+
export function pickFields(source: unknown, fields: string[]): Record<string, unknown> {
|
|
60
|
+
const out: Record<string, any> = {};
|
|
61
|
+
for (const path of fields) {
|
|
62
|
+
const keys = path.split('.');
|
|
63
|
+
let from: any = source;
|
|
64
|
+
for (const k of keys) from = from != null && typeof from === 'object' ? from[k] : undefined;
|
|
65
|
+
if (from === undefined) continue;
|
|
66
|
+
let to = out;
|
|
67
|
+
keys.slice(0, -1).forEach((k) => (to = to[k] ??= {}));
|
|
68
|
+
to[keys[keys.length - 1]] = from;
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|