@egen-civitas/esm-nextjs-utils 0.2.0 → 0.3.1

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,51 @@
1
+ /**
2
+ * Navigation partagée Shell ↔ application embarquée (protocole 1.1, additif).
3
+ *
4
+ * L'URL du Core reste la source de vérité, comme pour une app interne : `<base>/<route>/<chemin-de-l'app>?q#h`.
5
+ * Ce module ne contient que des fonctions pures (aucun accès au DOM), testées isolément.
6
+ */
7
+ import type { NavigationMode } from './protocol.js';
8
+ /** Paramètres jamais recopiés dans l'URL du Core (jetons, codes OAuth…). Comparaison insensible à la casse. */
9
+ export declare const DEFAULT_SENSITIVE_PARAMS: string[];
10
+ export declare const MAX_APP_PATH_LENGTH = 2000;
11
+ /** Mappage optionnel entre l'espace de chemins du Core et celui de l'application (flexibilité par app). */
12
+ export interface PathMap {
13
+ /** Chemin affiché dans le Core (`/dashboard/x`) → chemin interne de l'application. */
14
+ toApp?: (corePath: string) => string;
15
+ /** Chemin interne de l'application → chemin affiché dans le Core. */
16
+ toCore?: (appPath: string) => string;
17
+ }
18
+ export interface NavigationOptions {
19
+ /** Route de la page dans `routes.json` (`penpot`) : le Core est sur `<base>/<route>[/sous-chemin]`. */
20
+ route: string;
21
+ /** `history` (défaut), `hash`, ou `none` pour désactiver (comportement opaque d'origine). */
22
+ mode?: NavigationMode;
23
+ /** Paramètres supplémentaires à ne jamais recopier (s'ajoutent à `DEFAULT_SENSITIVE_PARAMS`). */
24
+ sensitiveParams?: string[];
25
+ pathMap?: PathMap;
26
+ /** Reçoit le titre annoncé par l'application (fil d'Ariane, titre de page). */
27
+ onTitle?: (title: string) => void;
28
+ }
29
+ /** Chemin interne sûr (`/x?y#z`), ou `null` : jamais d'URL absolue, de `//hôte`, d'espaces ni de caractères de contrôle. */
30
+ export declare function normalizeAppPath(input: unknown): string | null;
31
+ /** Retire les paramètres sensibles de la requête (et de la requête portée par le fragment `#/x?token=…`). */
32
+ export declare function stripSensitive(path: string, extra?: string[]): string;
33
+ /**
34
+ * Sous-chemin de l'application déduit de l'URL du Core, ou `null` si le Core n'est pas sur cette page.
35
+ * `pathname=/egen/spa/penpot/dashboard/x`, `spaBase=/egen/spa/`, `route=penpot` → `/dashboard/x` (`/` à la racine).
36
+ */
37
+ export declare function coreSubpath(pathname: string, spaBase: string, route: string): string | null;
38
+ /** URL du Core (chemin seul) pour un chemin d'application : `<base>/<route><chemin>`, sans `/` final superflu. */
39
+ export declare function buildCoreUrl(spaBase: string, route: string, appPath: string): string;
40
+ /**
41
+ * URL de chargement de l'iframe : l'adresse de base de l'application + le chemin interne.
42
+ * `history` : `<origine><chemin-de-base>/<chemin>?q#h` ; `hash` : `<base>#<chemin>`.
43
+ */
44
+ export declare function buildEmbedSrc(baseUrl: string, appPath: string, mode: NavigationMode): string;
45
+ /** Chemin d'application → chemin affiché par le Core (sans paramètres sensibles ; `pathMap.toCore` en dernier). */
46
+ export declare function toCorePath(appPath: unknown, opts: Pick<NavigationOptions, 'pathMap' | 'sensitiveParams'>): string | null;
47
+ /** Chemin lu dans l'URL du Core → chemin d'application (`pathMap.toApp` ; sans paramètres sensibles). */
48
+ export declare function toAppPath(corePath: string, opts: Pick<NavigationOptions, 'pathMap' | 'sensitiveParams'>): string | null;
49
+ /** Garde-fou de débit : au plus `max` messages par fenêtre `windowMs` (History API limitée par les navigateurs). */
50
+ export declare function createRateLimiter(max?: number, windowMs?: number, now?: () => number): () => boolean;
51
+ //# sourceMappingURL=navigation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"navigation.d.ts","sourceRoot":"","sources":["../src/navigation.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,+GAA+G;AAC/G,eAAO,MAAM,wBAAwB,UAgBpC,CAAC;AAEF,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAIxC,2GAA2G;AAC3G,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CAMxH;AAED,yGAAyG;AACzG,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,iBAAiB,EAAE,SAAS,GAAG,iBAAiB,CAAC,GAAG,MAAM,GAAG,IAAI,CAMvH;AAED,oHAAoH;AACpH,wBAAgB,iBAAiB,CAAC,GAAG,SAAK,EAAE,QAAQ,SAAO,EAAE,GAAG,GAAE,MAAM,MAAyB,SAEpF,OAAO,CAOnB"}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Navigation partagée Shell ↔ application embarquée (protocole 1.1, additif).
3
+ *
4
+ * L'URL du Core reste la source de vérité, comme pour une app interne : `<base>/<route>/<chemin-de-l'app>?q#h`.
5
+ * Ce module ne contient que des fonctions pures (aucun accès au DOM), testées isolément.
6
+ */ function _array_like_to_array(arr, len) {
7
+ if (len == null || len > arr.length) len = arr.length;
8
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
9
+ return arr2;
10
+ }
11
+ function _array_without_holes(arr) {
12
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
13
+ }
14
+ function _iterable_to_array(iter) {
15
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
16
+ }
17
+ function _non_iterable_spread() {
18
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
19
+ }
20
+ function _to_consumable_array(arr) {
21
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
22
+ }
23
+ function _unsupported_iterable_to_array(o, minLen) {
24
+ if (!o) return;
25
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
26
+ var n = Object.prototype.toString.call(o).slice(8, -1);
27
+ if (n === "Object" && o.constructor) n = o.constructor.name;
28
+ if (n === "Map" || n === "Set") return Array.from(n);
29
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
30
+ }
31
+ /** Paramètres jamais recopiés dans l'URL du Core (jetons, codes OAuth…). Comparaison insensible à la casse. */ export var DEFAULT_SENSITIVE_PARAMS = [
32
+ 'token',
33
+ 'access_token',
34
+ 'id_token',
35
+ 'refresh_token',
36
+ 'code',
37
+ 'state',
38
+ 'password',
39
+ 'secret',
40
+ 'otp',
41
+ 'session',
42
+ 'sessionid',
43
+ 'auth',
44
+ 'key',
45
+ 'api_key',
46
+ 'apikey'
47
+ ];
48
+ export var MAX_APP_PATH_LENGTH = 2000;
49
+ // eslint-disable-next-line no-control-regex
50
+ var SAFE_APP_PATH = /^\/(?!\/)[^\s\\\u0000-\u001f]*$/;
51
+ function trimSlashes(s) {
52
+ return s.replace(/^\/+|\/+$/g, '');
53
+ }
54
+ /** Chemin interne sûr (`/x?y#z`), ou `null` : jamais d'URL absolue, de `//hôte`, d'espaces ni de caractères de contrôle. */ export function normalizeAppPath(input) {
55
+ if (typeof input !== 'string' || input.length > MAX_APP_PATH_LENGTH) return null;
56
+ return SAFE_APP_PATH.test(input) ? input : null;
57
+ }
58
+ /** Retire les paramètres sensibles de la requête (et de la requête portée par le fragment `#/x?token=…`). */ export function stripSensitive(path) {
59
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
60
+ var blocked = new Set(_to_consumable_array(DEFAULT_SENSITIVE_PARAMS).concat(_to_consumable_array(extra)).map(function(p) {
61
+ return p.toLowerCase();
62
+ }));
63
+ var clean = function clean(query) {
64
+ var kept = query.split('&').filter(function(pair) {
65
+ return pair && !blocked.has(decodeSafe(pair.split('=')[0]).toLowerCase());
66
+ });
67
+ return kept.join('&');
68
+ };
69
+ var hashAt = path.indexOf('#');
70
+ var beforeHash = hashAt === -1 ? path : path.slice(0, hashAt);
71
+ var hash = hashAt === -1 ? '' : path.slice(hashAt);
72
+ var cleanHash = function() {
73
+ var q = hash.indexOf('?');
74
+ if (q === -1) return hash;
75
+ var kept = clean(hash.slice(q + 1));
76
+ return hash.slice(0, q) + (kept ? "?".concat(kept) : '');
77
+ }();
78
+ var qAt = beforeHash.indexOf('?');
79
+ if (qAt === -1) return beforeHash + cleanHash;
80
+ var kept = clean(beforeHash.slice(qAt + 1));
81
+ return beforeHash.slice(0, qAt) + (kept ? "?".concat(kept) : '') + cleanHash;
82
+ }
83
+ function decodeSafe(s) {
84
+ try {
85
+ return decodeURIComponent(s);
86
+ } catch (unused) {
87
+ return s;
88
+ }
89
+ }
90
+ /**
91
+ * Sous-chemin de l'application déduit de l'URL du Core, ou `null` si le Core n'est pas sur cette page.
92
+ * `pathname=/egen/spa/penpot/dashboard/x`, `spaBase=/egen/spa/`, `route=penpot` → `/dashboard/x` (`/` à la racine).
93
+ */ export function coreSubpath(pathname, spaBase, route) {
94
+ var base = '/' + trimSlashes(spaBase);
95
+ var prefix = (base === '/' ? '' : base) + '/' + trimSlashes(route);
96
+ if (pathname !== prefix && !pathname.startsWith(prefix + '/')) return null;
97
+ var rest = pathname.slice(prefix.length);
98
+ return rest === '' ? '/' : rest;
99
+ }
100
+ /** URL du Core (chemin seul) pour un chemin d'application : `<base>/<route><chemin>`, sans `/` final superflu. */ export function buildCoreUrl(spaBase, route, appPath) {
101
+ var base = '/' + trimSlashes(spaBase);
102
+ var prefix = (base === '/' ? '' : base) + '/' + trimSlashes(route);
103
+ if (appPath === '/' || appPath === '') return prefix;
104
+ return prefix + (appPath.startsWith('/') ? appPath : '/' + appPath);
105
+ }
106
+ /**
107
+ * URL de chargement de l'iframe : l'adresse de base de l'application + le chemin interne.
108
+ * `history` : `<origine><chemin-de-base>/<chemin>?q#h` ; `hash` : `<base>#<chemin>`.
109
+ */ export function buildEmbedSrc(baseUrl, appPath, mode) {
110
+ if (mode === 'none' || appPath === '/' || appPath === '') return baseUrl;
111
+ var base = new URL(baseUrl);
112
+ if (mode === 'hash') {
113
+ base.hash = appPath;
114
+ return base.href;
115
+ }
116
+ var hashAt = appPath.indexOf('#');
117
+ var noHash = hashAt === -1 ? appPath : appPath.slice(0, hashAt);
118
+ var hash = hashAt === -1 ? '' : appPath.slice(hashAt);
119
+ var qAt = noHash.indexOf('?');
120
+ var pathname = qAt === -1 ? noHash : noHash.slice(0, qAt);
121
+ var search = qAt === -1 ? '' : noHash.slice(qAt);
122
+ var basePath = base.pathname.replace(/\/+$/, '');
123
+ return "".concat(base.origin).concat(basePath).concat(pathname).concat(search).concat(hash);
124
+ }
125
+ /** Chemin d'application → chemin affiché par le Core (sans paramètres sensibles ; `pathMap.toCore` en dernier). */ export function toCorePath(appPath, opts) {
126
+ var _opts_pathMap;
127
+ var safe = normalizeAppPath(appPath);
128
+ if (!safe) return null;
129
+ var clean = stripSensitive(safe, opts.sensitiveParams);
130
+ var mapped = ((_opts_pathMap = opts.pathMap) === null || _opts_pathMap === void 0 ? void 0 : _opts_pathMap.toCore) ? opts.pathMap.toCore(clean) : clean;
131
+ return normalizeAppPath(mapped);
132
+ }
133
+ /** Chemin lu dans l'URL du Core → chemin d'application (`pathMap.toApp` ; sans paramètres sensibles). */ export function toAppPath(corePath, opts) {
134
+ var _opts_pathMap;
135
+ var safe = normalizeAppPath(corePath);
136
+ if (!safe) return null;
137
+ var clean = stripSensitive(safe, opts.sensitiveParams);
138
+ var mapped = ((_opts_pathMap = opts.pathMap) === null || _opts_pathMap === void 0 ? void 0 : _opts_pathMap.toApp) ? opts.pathMap.toApp(clean) : clean;
139
+ return normalizeAppPath(mapped);
140
+ }
141
+ /** Garde-fou de débit : au plus `max` messages par fenêtre `windowMs` (History API limitée par les navigateurs). */ export function createRateLimiter() {
142
+ var max = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 40, windowMs = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1000, now = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : function() {
143
+ return Date.now();
144
+ };
145
+ var stamps = [];
146
+ return function() {
147
+ var t = now();
148
+ while(stamps.length && t - stamps[0] > windowMs)stamps.shift();
149
+ if (stamps.length >= max) return false;
150
+ stamps.push(t);
151
+ return true;
152
+ };
153
+ }
@@ -0,0 +1,101 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { buildCoreUrl, buildEmbedSrc, coreSubpath, createRateLimiter, normalizeAppPath, stripSensitive, toAppPath, toCorePath } from './navigation.js';
3
+ describe('navigation partagée : fonctions pures', function() {
4
+ it('normalizeAppPath : chemins internes sûrs uniquement', function() {
5
+ for(var _i = 0, _iter = [
6
+ '/',
7
+ '/a/b?x=1#h',
8
+ '/dashboard/recent?team-id=1'
9
+ ]; _i < _iter.length; _i++){
10
+ var ok = _iter[_i];
11
+ expect(normalizeAppPath(ok)).toBe(ok);
12
+ }
13
+ for(var _i1 = 0, _iter1 = [
14
+ '//evil.com',
15
+ 'https://x.org',
16
+ 'javascript:1',
17
+ 'a',
18
+ '/a b',
19
+ '/a\\b',
20
+ '/a\u0000',
21
+ 7,
22
+ undefined,
23
+ '/' + 'x'.repeat(2001)
24
+ ]; _i1 < _iter1.length; _i1++){
25
+ var ko = _iter1[_i1];
26
+ expect(normalizeAppPath(ko)).toBeNull();
27
+ }
28
+ });
29
+ it('stripSensitive : requête et fragment, insensible à la casse, ajouts configurables', function() {
30
+ expect(stripSensitive('/a?x=1&token=S&Code=C&y=2')).toBe('/a?x=1&y=2');
31
+ expect(stripSensitive('/a?token=S')).toBe('/a');
32
+ expect(stripSensitive('/#/invite?TOKEN=S&team=1')).toBe('/#/invite?team=1');
33
+ expect(stripSensitive('/a?invite=Z&x=1', [
34
+ 'invite'
35
+ ])).toBe('/a?x=1');
36
+ expect(stripSensitive('/a?%74oken=S&x=1')).toBe('/a?x=1');
37
+ expect(stripSensitive('/a?tokenize=1')).toBe('/a?tokenize=1');
38
+ });
39
+ it('coreSubpath / buildCoreUrl : aller-retour sur la route de la page', function() {
40
+ expect(coreSubpath('/egen/spa/penpot', '/egen/spa/', 'penpot')).toBe('/');
41
+ expect(coreSubpath('/egen/spa/penpot/', '/egen/spa/', 'penpot')).toBe('/');
42
+ expect(coreSubpath('/egen/spa/penpot/dash/x', '/egen/spa/', 'penpot')).toBe('/dash/x');
43
+ expect(coreSubpath('/egen/spa/penpotx', '/egen/spa/', 'penpot')).toBeNull();
44
+ expect(coreSubpath('/egen/spa/home', '/egen/spa/', 'penpot')).toBeNull();
45
+ expect(coreSubpath('/penpot/a', '/', 'penpot')).toBe('/a');
46
+ expect(buildCoreUrl('/egen/spa/', 'penpot', '/dash/x?q=1')).toBe('/egen/spa/penpot/dash/x?q=1');
47
+ expect(buildCoreUrl('/egen/spa/', 'penpot', '/')).toBe('/egen/spa/penpot');
48
+ expect(buildCoreUrl('/', 'penpot', '/a')).toBe('/penpot/a');
49
+ });
50
+ it('buildEmbedSrc : history, hash, none, racine, préfixe de base', function() {
51
+ expect(buildEmbedSrc('https://a.org', '/', 'history')).toBe('https://a.org');
52
+ expect(buildEmbedSrc('https://a.org/', '/x/y?q=1#h', 'history')).toBe('https://a.org/x/y?q=1#h');
53
+ expect(buildEmbedSrc('https://a.org/studio/', '/x?q=1', 'history')).toBe('https://a.org/studio/x?q=1');
54
+ expect(buildEmbedSrc('https://a.org/', '/dash/recent?t=1', 'hash')).toBe('https://a.org/#/dash/recent?t=1');
55
+ expect(buildEmbedSrc('https://a.org/', '/x', 'none')).toBe('https://a.org/');
56
+ });
57
+ it('toCorePath / toAppPath : filtrage, pathMap, rejet des chemins dangereux', function() {
58
+ expect(toCorePath('/a?token=S&x=1', {})).toBe('/a?x=1');
59
+ expect(toCorePath('//evil', {})).toBeNull();
60
+ var pathMap = {
61
+ toCore: function toCore(p) {
62
+ return p.replace(/^\/w/, '/workspace');
63
+ },
64
+ toApp: function toApp(p) {
65
+ return p.replace(/^\/workspace/, '/w');
66
+ }
67
+ };
68
+ expect(toCorePath('/w/1', {
69
+ pathMap: pathMap
70
+ })).toBe('/workspace/1');
71
+ expect(toAppPath('/workspace/1', {
72
+ pathMap: pathMap
73
+ })).toBe('/w/1');
74
+ expect(toCorePath('/a', {
75
+ pathMap: {
76
+ toCore: function toCore() {
77
+ return 'https://evil.org';
78
+ }
79
+ }
80
+ })).toBeNull();
81
+ });
82
+ it('createRateLimiter : plafonne les rafales puis reprend', function() {
83
+ var t = 0;
84
+ var allow = createRateLimiter(3, 1000, function() {
85
+ return t;
86
+ });
87
+ expect([
88
+ allow(),
89
+ allow(),
90
+ allow(),
91
+ allow()
92
+ ]).toEqual([
93
+ true,
94
+ true,
95
+ true,
96
+ false
97
+ ]);
98
+ t = 1500;
99
+ expect(allow()).toBe(true);
100
+ });
101
+ });
@@ -784,7 +784,11 @@ describe('côté application : createEgenBridge', function() {
784
784
  case 0:
785
785
  b = make();
786
786
  expect(host.postMessage).toHaveBeenCalledWith(wrap('@acme/next-app', {
787
- kind: 'ready'
787
+ kind: 'ready',
788
+ caps: [
789
+ 'location',
790
+ 'goto'
791
+ ]
788
792
  }), HOST);
789
793
  states = [];
790
794
  b.subscribe(function(s) {
@@ -12,7 +12,14 @@ export interface EmbedInit {
12
12
  spaBase: string;
13
13
  /** Session filtrée par liste blanche (voir `sessionFields`) ; absente tant que non chargée. */
14
14
  session?: Record<string, unknown>;
15
+ /** Protocole 1.1 : navigation partagée active pour cette instance (absente = opaque). */
16
+ navigation?: {
17
+ mode: NavigationMode;
18
+ route: string;
19
+ };
15
20
  }
21
+ /** Mode de navigation partagée (voir `navigation.ts`) : `none` = opaque, `history` = chemins, `hash` = `#/chemin`. */
22
+ export type NavigationMode = 'none' | 'history' | 'hash';
16
23
  export type HostToEmbed = {
17
24
  kind: 'init';
18
25
  payload: EmbedInit;
@@ -22,9 +29,20 @@ export type HostToEmbed = {
22
29
  } | {
23
30
  kind: 'locale';
24
31
  locale: string;
32
+ }
33
+ /** Protocole 1.1 : poignée de main initiée par le Shell (à chaque chargement de l'iframe). */
34
+ | {
35
+ kind: 'hello';
36
+ }
37
+ /** Protocole 1.1 : le Shell demande à l'application d'aller à `path` (retour/avance, lien du Core). */
38
+ | {
39
+ kind: 'goto';
40
+ path: string;
41
+ seq: number;
25
42
  };
26
43
  export type EmbedToHost = {
27
44
  kind: 'ready';
45
+ caps?: string[];
28
46
  } | {
29
47
  kind: 'navigate';
30
48
  to: string;
@@ -34,6 +52,13 @@ export type EmbedToHost = {
34
52
  } | {
35
53
  kind: 'title';
36
54
  title: string;
55
+ }
56
+ /** Protocole 1.1 : l'application annonce sa page courante (chemin interne, requête et fragment compris). */
57
+ | {
58
+ kind: 'location';
59
+ path: string;
60
+ replace?: boolean;
61
+ title?: string;
37
62
  };
38
63
  export interface Envelope<T> {
39
64
  egen: typeof EGEN_EMBED_PROTOCOL;
@@ -1 +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,M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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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egen-civitas/esm-nextjs-utils",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "license": "MPL-2.0",
5
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
6
  "type": "module",
package/src/client.ts CHANGED
@@ -26,6 +26,10 @@ export interface EgenBridge {
26
26
  setHeight(height: number): void;
27
27
  /** Annonce un titre accessible pour l'iframe. */
28
28
  setTitle(title: string): void;
29
+ /** Protocole 1.1 : annonce la page courante de l'application (`/chemin?q#h`) ; `replace` n'ajoute pas d'entrée d'historique. */
30
+ reportLocation(path: string, options?: { replace?: boolean; title?: string }): void;
31
+ /** Protocole 1.1 : le Shell demande d'aller à `path` (retour/avance, lien du Core) ; renvoie le désabonnement. */
32
+ onGoto(listener: (path: string) => void): () => void;
29
33
  /** Annonce automatiquement la hauteur du document (ResizeObserver). */
30
34
  autoResize(): () => void;
31
35
  destroy(): void;
@@ -40,6 +44,7 @@ export function createEgenBridge(opts: EgenBridgeOptions): EgenBridge {
40
44
 
41
45
  let state: Partial<EmbedInit> = {};
42
46
  const listeners = new Set<(s: Partial<EmbedInit>) => void>();
47
+ const gotoListeners = new Set<(path: string) => void>();
43
48
  let resolveReady!: (i: EmbedInit) => void;
44
49
  const ready = new Promise<EmbedInit>((r) => (resolveReady = r));
45
50
  // L'origine du Shell n'est connue qu'à la première réponse : le message `ready` est donc envoyé à chaque origine autorisée.
@@ -58,6 +63,10 @@ export function createEgenBridge(opts: EgenBridgeOptions): EgenBridge {
58
63
  } else if (msg.kind === 'session') {
59
64
  state = { ...state, session: msg.session };
60
65
  emit();
66
+ } else if (msg.kind === 'hello') {
67
+ send({ kind: 'ready', caps: ['location', 'goto'] });
68
+ } else if (msg.kind === 'goto') {
69
+ gotoListeners.forEach((l) => l(msg.path));
61
70
  } else if (msg.kind === 'locale') {
62
71
  state = { ...state, locale: msg.locale };
63
72
  emit();
@@ -69,11 +78,16 @@ export function createEgenBridge(opts: EgenBridgeOptions): EgenBridge {
69
78
  const targets = hostOrigin ? [hostOrigin] : opts.allowedHostOrigins;
70
79
  targets.forEach((o) => host.postMessage(wrap(opts.moduleName, message), o));
71
80
  };
72
- send({ kind: 'ready' });
81
+ send({ kind: 'ready', caps: ['location', 'goto'] });
73
82
 
74
83
  return {
75
84
  ready,
76
85
  getState: () => state,
86
+ reportLocation: (path, o) => send({ kind: 'location', path, replace: o?.replace, title: o?.title }),
87
+ onGoto(l) {
88
+ gotoListeners.add(l);
89
+ return () => gotoListeners.delete(l);
90
+ },
77
91
  subscribe(l) {
78
92
  listeners.add(l);
79
93
  return () => listeners.delete(l);
package/src/host.ts CHANGED
@@ -9,6 +9,16 @@ import {
9
9
  type LifecycleOptions,
10
10
  type Unsubscribe,
11
11
  } from '@egen-civitas/esm-integration-utils';
12
+ import {
13
+ buildCoreUrl,
14
+ buildEmbedSrc,
15
+ coreSubpath,
16
+ createRateLimiter,
17
+ stripSensitive,
18
+ toAppPath,
19
+ toCorePath,
20
+ type NavigationOptions,
21
+ } from './navigation.js';
12
22
  import { DEFAULT_SESSION_FIELDS, isEnvelope, pickFields, wrap, type EmbedToHost, type HostToEmbed } from './protocol.js';
13
23
 
14
24
  export interface EmbedLifecycleOptions extends LifecycleOptions {
@@ -26,6 +36,11 @@ export interface EmbedLifecycleOptions extends LifecycleOptions {
26
36
  minHeight?: number;
27
37
  /** Navigation demandée par l'application (défaut : `singleSpaNavigate(spaBase + chemin)`). */
28
38
  onNavigate?: (to: string) => void;
39
+ /**
40
+ * Navigation partagée (protocole 1.1) : l'URL du Core reflète la page courante de l'application et inversement
41
+ * (actualisation, retour/avance, lien partageable). Absent ou `mode: 'none'` : comportement opaque d'origine.
42
+ */
43
+ navigation?: NavigationOptions;
29
44
  }
30
45
 
31
46
  const DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';
@@ -53,7 +68,20 @@ export function getEmbedLifecycle(userOpts: EmbedLifecycleOptions): LifeCycles {
53
68
  bootstrap: () => Promise.resolve(),
54
69
  mount: (props: any) => {
55
70
  const target = resolveMountTarget(props);
56
- const src = typeof opts.url === 'function' ? opts.url(props) : opts.url;
71
+ const baseUrl = typeof opts.url === 'function' ? opts.url(props) : opts.url;
72
+ const nav = opts.navigation && (opts.navigation.mode ?? 'history') !== 'none' ? { ...opts.navigation, mode: opts.navigation.mode ?? 'history' } : undefined;
73
+ const spaBase = (): string => (window as any).getEgenSpaBase?.() ?? '/';
74
+ /** Page courante du Core, en chemin (`/x?q#h`) relatif à la route de l'application ; `null` hors de cette page. */
75
+ const currentCorePath = (): string | null => {
76
+ if (!nav) return null;
77
+ const sub = coreSubpath(window.location.pathname, spaBase(), nav.route);
78
+ if (sub === null) return null;
79
+ const raw = sub + window.location.search + window.location.hash;
80
+ return stripSensitive(raw, nav.sensitiveParams);
81
+ };
82
+ let lastCorePath = currentCorePath() ?? '/';
83
+ const initialAppPath = nav ? toAppPath(lastCorePath, nav) ?? '/' : '/';
84
+ const src = nav ? buildEmbedSrc(baseUrl, initialAppPath, nav.mode) : baseUrl;
57
85
  const origin = opts.allowedOrigin ?? new URL(src, window.location.href).origin;
58
86
  if (origin === '*' || origin === 'null') throw new Error('allowedOrigin invalide : une origine explicite est requise.');
59
87
 
@@ -69,12 +97,18 @@ export function getEmbedLifecycle(userOpts: EmbedLifecycleOptions): LifeCycles {
69
97
  iframe.title = opts.title ?? opts.featureName;
70
98
  iframe.setAttribute('sandbox', sandbox);
71
99
  iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
100
+ // Demande au Shell de donner à ce conteneur la hauteur de
101
+ // #egen-scroll-region (règle :has(> [data-egen-fill]) du styleguide).
102
+ iframe.setAttribute('data-egen-fill', '');
72
103
  iframe.style.cssText = `width:100%;border:0;display:block;min-height:${opts.minHeight ?? 400}px`;
73
104
 
74
105
  const send = (message: HostToEmbed) => iframe.contentWindow?.postMessage(wrap(opts.moduleName, message), origin);
75
106
  const stop: Unsubscribe[] = [];
76
107
  let ready = false;
77
108
  let lastSession: Record<string, unknown> | undefined;
109
+ let bridgeSeen = false;
110
+ let seq = 0;
111
+ const allowLocation = createRateLimiter();
78
112
 
79
113
  const onMessage = (event: MessageEvent) => {
80
114
  if (event.source !== iframe.contentWindow || event.origin !== origin) return;
@@ -83,6 +117,7 @@ export function getEmbedLifecycle(userOpts: EmbedLifecycleOptions): LifeCycles {
83
117
  switch (msg.kind) {
84
118
  case 'ready':
85
119
  ready = true;
120
+ bridgeSeen = true;
86
121
  send({
87
122
  kind: 'init',
88
123
  payload: {
@@ -90,6 +125,7 @@ export function getEmbedLifecycle(userOpts: EmbedLifecycleOptions): LifeCycles {
90
125
  locale: (window as any).i18next?.language,
91
126
  spaBase: (window as any).getEgenSpaBase?.() ?? '/',
92
127
  session: lastSession,
128
+ navigation: nav ? { mode: nav.mode!, route: nav.route } : undefined,
93
129
  },
94
130
  });
95
131
  break;
@@ -104,11 +140,49 @@ export function getEmbedLifecycle(userOpts: EmbedLifecycleOptions): LifeCycles {
104
140
  case 'title':
105
141
  if (typeof msg.title === 'string') iframe.title = msg.title.slice(0, 200);
106
142
  break;
143
+ case 'location': {
144
+ if (!nav || !allowLocation()) break;
145
+ bridgeSeen = true;
146
+ if (typeof msg.title === 'string') {
147
+ iframe.title = msg.title.slice(0, 200);
148
+ nav.onTitle?.(iframe.title);
149
+ }
150
+ const corePath = toCorePath(msg.path, nav);
151
+ if (!corePath || corePath === lastCorePath) break;
152
+ lastCorePath = corePath;
153
+ const url = buildCoreUrl(spaBase(), nav.route, corePath);
154
+ // History API (surchargée par Single-SPA) : la page reste active (la route correspond toujours), sans remontage.
155
+ window.history[msg.replace ? 'replaceState' : 'pushState'](window.history.state, '', url);
156
+ break;
157
+ }
107
158
  }
108
159
  };
109
160
  window.addEventListener('message', onMessage);
110
161
  stop.push(() => window.removeEventListener('message', onMessage));
111
162
 
163
+ if (nav) {
164
+ // poignée de main à chaque chargement de l'iframe (le script injectable n'a pas besoin de connaître l'origine du Shell)
165
+ const onLoad = () => send({ kind: 'hello' });
166
+ iframe.addEventListener('load', onLoad);
167
+ stop.push(() => iframe.removeEventListener('load', onLoad));
168
+ // URL du Core modifiée hors de l'application (retour/avance, lien) → l'application suit
169
+ const onCoreLocation = () => {
170
+ const cur = currentCorePath();
171
+ if (cur === null || cur === lastCorePath) return;
172
+ lastCorePath = cur;
173
+ const appPath = toAppPath(cur, nav);
174
+ if (!appPath) return;
175
+ if (bridgeSeen) send({ kind: 'goto', path: appPath, seq: ++seq });
176
+ else iframe.src = buildEmbedSrc(baseUrl, appPath, nav.mode);
177
+ };
178
+ window.addEventListener('single-spa:routing-event', onCoreLocation);
179
+ window.addEventListener('popstate', onCoreLocation);
180
+ stop.push(() => {
181
+ window.removeEventListener('single-spa:routing-event', onCoreLocation);
182
+ window.removeEventListener('popstate', onCoreLocation);
183
+ });
184
+ }
185
+
112
186
  stop.push(
113
187
  watchSession((session) => {
114
188
  lastSession = pickFields(session, fields);
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './host.js';
2
+ export * from './navigation.js';
2
3
  export * from './protocol.js';