@nodefony/frontend 10.0.0-alpha.9 → 10.0.0-beta.2

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/README.md CHANGED
@@ -21,16 +21,17 @@ Vite a besoin d'un event-loop et d'un tas V8 pour compiler/HMR. L'exécuter **in
21
21
 
22
22
  ### 1. Activer `@nodefony/frontend` dans l'app
23
23
 
24
- Dans `index.ts` racine :
24
+ Dans `nodefony.config.ts` :
25
25
 
26
26
  ```ts
27
- @modules([
28
- "@nodefony/http",
29
- "@nodefony/framework",
30
- "@nodefony/frontend", // ← avant ton module consumer
31
- "@nodefony/mon-module",
32
- ])
33
- class App extends Module { ... }
27
+ export default defineConfig(() => ({
28
+ modules: [
29
+ "@nodefony/http",
30
+ "@nodefony/framework",
31
+ "@nodefony/frontend", // ← avant ton module consumer
32
+ "@nodefony/mon-module",
33
+ ],
34
+ }));
34
35
  ```
35
36
 
36
37
  > **Ordre important** : `@nodefony/frontend` doit être déclaré AVANT les modules qui appellent `registerEntry()` — sinon le service `frontend` n'existe pas dans le DI Container au moment du `onKernelBoot()` du consumer.
@@ -163,7 +164,7 @@ Le superviseur Vite démarre automatiquement sur l'event `onServersReady` du ker
163
164
 
164
165
  ```
165
166
  INFO frontend : registered entry: my-module (react19) from "my-module"
166
- INFO frontend : vite dev server ready on 127.0.0.1:5173
167
+ INFO frontend : vite [default] ready on 127.0.0.1:5173
167
168
  ```
168
169
 
169
170
  Va sur `http://127.0.0.1:5151/my-route/` — Nodefony rend l'HTML, le browser tape Vite (5173) pour les assets, HMR fonctionne en édition de `App.tsx`.
@@ -239,12 +240,13 @@ svc.on("frontend:ready", (status) => {
239
240
 
240
241
  ```ts
241
242
  interface IFrontendService {
242
- registerEntry(module, declaration): IResolvedFrontendEntry;
243
243
  listEntries(): ReadonlyArray<IResolvedFrontendEntry>;
244
244
  status(): IViteSupervisorStatus;
245
+ statusAll(): ReadonlyArray<{ family: string; status: IViteSupervisorStatus }>;
245
246
  startDev(): Promise<void>; // appelé auto par onServersReady
246
247
  stopDev(): Promise<void>;
247
- build(): Promise<void>; // vite.build() in-proc
248
+ // vite.build() par entrée ; bilan construits / ignorés / en échec
249
+ build(opts?: { force?: boolean }): Promise<IFrontendBuildResult>;
248
250
  // `nonce` = `Context.cspNonce` ; `requestHost` = `Context.domain` (sans port),
249
251
  // dont l'origine des assets est dérivée en développement.
250
252
  renderTags(entryName, nonce?, requestHost?): string;
@@ -253,20 +255,18 @@ interface IFrontendService {
253
255
  }
254
256
  ```
255
257
 
258
+ `registerEntry(module, declaration)` est porté par la classe `FrontendService`, pas par l'interface.
259
+
256
260
  ---
257
261
 
258
262
  ## Troubleshooting
259
263
 
260
264
  ### Page blanche, scripts bloqués par CSP
261
265
 
262
- Le helmet de `@nodefony/security` pose `script-src 'self'` par défaut. Override dans le controller :
263
-
264
- ```ts
265
- this.context.response.setHeader(
266
- "Content-Security-Policy",
267
- svc.getCspDirectives(),
268
- );
269
- ```
266
+ En développement, le service déclare les origines Vite au pare-feu (`@nodefony/security`) une fois
267
+ Vite prêt, et ce dernier émet UN seul en-tête CSP avec le nonce de la requête. Vérifie que tu passes
268
+ `this.context?.cspNonce` à `svc.renderTags(…)` / `renderDocument(…)`, et ne réécris jamais l'en-tête
269
+ dans le contrôleur : tu écraserais le nonce.
270
270
 
271
271
  ### `Unexpected token '<'` sur `fetch("/api/...")`
272
272
 
@@ -319,7 +319,7 @@ FrontendService.startDev()
319
319
  ↓
320
320
  ViteProcessSupervisor.start()
321
321
  ├─ écrit vite.config.generated.mjs (proxy, https, base, env)
322
- ├─ spawn("npx", ["vite", "--config", ...])
322
+ ├─ spawn(node, [vite.js, "--config", ...]) (repli npx si le binaire n'est pas résolu)
323
323
  ├─ parse stdout "Local: https://host:port" → state = "ready"
324
324
  ├─ attach exit handler (auto-restart si crash inattendu)
325
325
  └─ start health check loop (ping HTTP périodique)
@@ -1,4 +1,4 @@
1
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/decorate.js
1
+ //#region \0@oxc-project+runtime@0.152.0/helpers/esm/decorate.js
2
2
  function __decorate(decorators, target, key, desc) {
3
3
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
4
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -1,4 +1,4 @@
1
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/decorateMetadata.js
1
+ //#region \0@oxc-project+runtime@0.152.0/helpers/esm/decorateMetadata.js
2
2
  function __decorateMetadata(k, v) {
3
3
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
4
4
  }
package/dist/index.js CHANGED
@@ -10,8 +10,8 @@ import { ViteBuilder } from "./nodefony/src/builders/ViteBuilder.js";
10
10
  import { ViteConfigGenerator } from "./nodefony/service/ViteConfigGenerator.js";
11
11
  import { ViteProcessSupervisor } from "./nodefony/service/ViteProcessSupervisor.js";
12
12
  import { TemplateHelper } from "./nodefony/src/template/TemplateHelper.js";
13
- import __decorateMetadata from "./_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/decorateMetadata.js";
14
- import __decorate from "./_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/decorate.js";
13
+ import __decorateMetadata from "./_virtual/_@oxc-project_runtime@0.152.0/helpers/esm/decorateMetadata.js";
14
+ import __decorate from "./_virtual/_@oxc-project_runtime@0.152.0/helpers/esm/decorate.js";
15
15
  import FrontendService_default from "./nodefony/service/FrontendService.js";
16
16
  import { buildFrontendStatus, createFrontendAdminApi } from "./nodefony/src/FrontendAdminApi.js";
17
17
  import FrontendBuild from "./nodefony/command/frontend-build.js";
@@ -5,8 +5,8 @@ import { allowedHostPatternForTemplate, detectRemoteDev, isLoopbackHostname, isV
5
5
  import { ViteProcessSupervisor } from "./ViteProcessSupervisor.js";
6
6
  import { TemplateHelper } from "../src/template/TemplateHelper.js";
7
7
  import { familyPortBlocks, familyPortPlan, isolationGroup } from "../src/isolationGroups.js";
8
- import __decorateMetadata from "../../_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/decorateMetadata.js";
9
- import __decorate from "../../_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/decorate.js";
8
+ import __decorateMetadata from "../../_virtual/_@oxc-project_runtime@0.152.0/helpers/esm/decorateMetadata.js";
9
+ import __decorate from "../../_virtual/_@oxc-project_runtime@0.152.0/helpers/esm/decorate.js";
10
10
  import { FRONTEND_CHOICES, Module, Service, extend, injectable, stripTrailingSlashes } from "nodefony";
11
11
  import path from "node:path";
12
12
  import fs from "node:fs";
@@ -74,14 +74,15 @@ let FrontendService = class FrontendService extends Service {
74
74
  */
75
75
  plannedPortBlocks = null;
76
76
  constructor(module) {
77
- const merged = extend(true, {}, config, module.options ?? {});
77
+ const options = module.options;
78
+ const merged = extend(true, {}, config, options ?? {});
78
79
  super("frontend", module.container, module.notificationsCenter, merged);
79
80
  this.module = module;
80
81
  this.cfg = merged;
81
82
  }
82
83
  /** Base CDN normalisée (sans slash final). `""` = origine Nodefony. */
83
84
  get assetBase() {
84
- return stripTrailingSlashes(this.cfg.assetBaseUrl ?? "");
85
+ return stripTrailingSlashes(this.cfg.assetBaseUrl);
85
86
  }
86
87
  /**
87
88
  * Résout l'URL publique d'un asset. Préfixe `p` par `assetBaseUrl` (CDN) si
@@ -172,14 +173,14 @@ let FrontendService = class FrontendService extends Service {
172
173
  return this.entries;
173
174
  }
174
175
  status() {
175
- const primary = this.supervisors.get("default") ?? [...this.supervisors.values()][0];
176
+ const primary = this.supervisors.get("default") ?? [...this.supervisors.values()].at(0);
176
177
  if (!primary) return {
177
178
  state: "idle",
178
179
  host: this.cfg.devHost,
179
180
  origin: null,
180
181
  port: null,
181
182
  pid: null,
182
- https: !!this.cfg.https,
183
+ https: this.cfg.https,
183
184
  restartCount: 0,
184
185
  healthFailures: 0,
185
186
  portRetries: 0,
@@ -214,12 +215,12 @@ let FrontendService = class FrontendService extends Service {
214
215
  this.originPinnedBy = pinned?.source ?? null;
215
216
  const allowedHosts = this.viteAllowedHosts(publicOriginTemplate);
216
217
  const nodeEnv = this.kernel?.environment;
217
- const extraEnv = this.cfg.viteEnv ?? {};
218
+ const extraEnv = this.cfg.viteEnv;
218
219
  const groups = this.groupEntriesByFamily();
219
- const portPlan = familyPortPlan(this.cfg.devPort, [...groups.keys()], this.cfg.resilience?.portRetryAttempts ?? 3);
220
+ const portPlan = familyPortPlan(this.cfg.devPort, [...groups.keys()], this.cfg.resilience.portRetryAttempts);
220
221
  const families = [...portPlan.keys()];
221
222
  if (publicOriginTemplate && !publicOriginTemplate.includes("{port}") && families.length > 1) this.log(`publicOrigin figée (« ${publicOriginTemplate} ») avec ${families.length} familles Vite (${families.join(", ")}) — une origine ne peut en servir qu'UNE : utiliser {port} (ex. https://host:{port}) pour suivre chaque famille`, "WARNING");
222
- this.plannedPortBlocks = familyPortBlocks(portPlan, this.cfg.resilience?.portRetryAttempts ?? 3);
223
+ this.plannedPortBlocks = familyPortBlocks(portPlan, this.cfg.resilience.portRetryAttempts);
223
224
  this.#registerCsp();
224
225
  this.fire("frontend:starting", {
225
226
  backendOrigin,
@@ -227,9 +228,10 @@ let FrontendService = class FrontendService extends Service {
227
228
  });
228
229
  const total = this.entries.length;
229
230
  let done = 0;
230
- (await Promise.allSettled(families.map((family) => {
231
- const famSize = groups.get(family).length;
232
- return this.startFamily(family, groups.get(family), portPlan.get(family), {
231
+ (await Promise.allSettled([...portPlan].map(([family, port]) => {
232
+ const familyEntries = groups.get(family) ?? [];
233
+ const famSize = familyEntries.length;
234
+ return this.startFamily(family, familyEntries, port, {
233
235
  backendOrigin,
234
236
  https,
235
237
  nodeEnv,
@@ -246,7 +248,8 @@ let FrontendService = class FrontendService extends Service {
246
248
  }))).forEach((res, i) => {
247
249
  if (res.status === "rejected") {
248
250
  const reason = res.reason;
249
- this.log(`frontend family "${families[i]}" failed to start (isolated): ${reason?.message ?? reason}`, "ERROR");
251
+ const detail = reason instanceof Error ? reason.message : String(reason);
252
+ this.log(`frontend family "${families[i]}" failed to start (isolated): ${detail}`, "ERROR");
250
253
  }
251
254
  });
252
255
  if ([...this.supervisors.values()].filter((s) => s.status().state === "ready").length === 0) {
@@ -271,7 +274,7 @@ let FrontendService = class FrontendService extends Service {
271
274
  * ne dépend pas de `@nodefony/http` (cycle via la config d'app).
272
275
  */
273
276
  resolveBackendPort() {
274
- const server = this.container?.get?.("server-http");
277
+ const server = this.container?.get("server-http");
275
278
  const real = server?.active && server.port ? server.port : 0;
276
279
  if (real > 0 && real !== this.cfg.backendPort) this.log(`backend à l'écoute sur ${real} (et non ${this.cfg.backendPort}) — le proxy Vite suit le port réel`, "INFO");
277
280
  return real > 0 ? real : this.cfg.backendPort;
@@ -283,8 +286,8 @@ let FrontendService = class FrontendService extends Service {
283
286
  */
284
287
  resolveHttps() {
285
288
  if (!this.cfg.https) return void 0;
286
- const certs = this.container?.get?.("certificates");
287
- if (!certs?.privateKeyPath || !certs?.certPath) {
289
+ const certs = this.container?.get("certificates");
290
+ if (!certs?.privateKeyPath || !certs.certPath) {
288
291
  this.log("https: true requested but `certificates` service unavailable — falling back to HTTP", "WARNING");
289
292
  return;
290
293
  }
@@ -342,7 +345,7 @@ let FrontendService = class FrontendService extends Service {
342
345
  * `true` (même délégation). Un pattern non exprimable chez Vite est ANNONCÉ.
343
346
  */
344
347
  viteAllowedHosts(publicOriginTemplate) {
345
- const th = (this.container?.get?.("HttpKernel"))?.trustedHosts;
348
+ const th = (this.container?.get("HttpKernel"))?.trustedHosts;
346
349
  if (th === true) return true;
347
350
  const hosts = /* @__PURE__ */ new Set();
348
351
  if (this.kernel?.domain) {
@@ -381,7 +384,9 @@ let FrontendService = class FrontendService extends Service {
381
384
  * observable même si le démarrage échoue → rendu propre, pas d'exception).
382
385
  */
383
386
  async startFamily(family, entries, port, ctx) {
384
- const r = this.cfg.resilience ?? {};
387
+ const [first] = entries;
388
+ if (first === void 0) throw new FrontendNoEntriesError();
389
+ const r = this.cfg.resilience;
385
390
  const supervisor = new ViteProcessSupervisor({
386
391
  devHost: this.cfg.devHost,
387
392
  devPort: port,
@@ -389,7 +394,7 @@ let FrontendService = class FrontendService extends Service {
389
394
  allowedHosts: ctx.allowedHosts,
390
395
  startupTimeoutMs: this.cfg.startupTimeoutMs,
391
396
  pipeLogs: this.cfg.pipeViteLogs,
392
- cwd: entries[0].root,
397
+ cwd: first.root,
393
398
  backendOrigin: ctx.backendOrigin,
394
399
  https: ctx.https,
395
400
  nodeEnv: ctx.nodeEnv,
@@ -447,7 +452,7 @@ let FrontendService = class FrontendService extends Service {
447
452
  this.log(`entrée(s) frontend sans build (${names}) et vite indisponible ici — les pages seront servies SANS interface (blanches). Builde AVANT de lancer : npm run build (ou nodefony frontend:build), puis redémarre. Si vite manque aussi en développement, il n'est pas une dépendance de ce module : installe-le côté application (npm i -D vite, plus le plugin de ton framework). Détail : ${e instanceof Error ? e.message : String(e)}`, "ERROR");
448
453
  }
449
454
  }
450
- const stat = this.container?.get?.("server-static");
455
+ const stat = this.container?.get("server-static");
451
456
  if (stat?.addMount) for (const e of this.entries) {
452
457
  stat.addMount(e.publicPath, e.outDir);
453
458
  this.log(`prod static mount ${e.publicPath} → ${e.outDir}`, "INFO");
@@ -463,7 +468,7 @@ let FrontendService = class FrontendService extends Service {
463
468
  this.templateHelpers.clear();
464
469
  this.entryFamily.clear();
465
470
  this.plannedPortBlocks = null;
466
- (this.container?.get?.("firewall"))?.unregisterCspOrigins?.("frontend");
471
+ (this.container?.get("firewall"))?.unregisterCspOrigins?.("frontend");
467
472
  this.fire("frontend:stopped");
468
473
  }
469
474
  /**
@@ -614,7 +619,7 @@ let FrontendService = class FrontendService extends Service {
614
619
  if (!requestHost) return void 0;
615
620
  if (this.originPinnedBy === "config") return void 0;
616
621
  if (this.originPinnedBy === "platform" && !isLoopbackHostname(requestHost)) return;
617
- const httpKernel = this.container?.get?.("HttpKernel");
622
+ const httpKernel = this.container?.get("HttpKernel");
618
623
  if (!httpKernel || httpKernel.trustedHosts === true) return void 0;
619
624
  return httpKernel.isTrustedHostname?.(requestHost) === true ? requestHost : void 0;
620
625
  }
@@ -625,7 +630,7 @@ let FrontendService = class FrontendService extends Service {
625
630
  * No-op si security absent (app sans firewall).
626
631
  */
627
632
  #registerCsp() {
628
- (this.container?.get?.("firewall"))?.registerCspOrigins?.("frontend", this.#viteCspFragment());
633
+ (this.container?.get("firewall"))?.registerCspOrigins?.("frontend", this.#viteCspFragment());
629
634
  }
630
635
  /**
631
636
  * Fragment CSP des besoins Vite DEV. Deux exigences :
@@ -646,7 +651,7 @@ let FrontendService = class FrontendService extends Service {
646
651
  const ports = this.cspPorts();
647
652
  const hosts = /* @__PURE__ */ new Set(["127.0.0.1", "localhost"]);
648
653
  if (this.kernel?.domain) hosts.add(this.kernel.domain);
649
- const th = (this.container?.get?.("HttpKernel"))?.trustedHosts;
654
+ const th = (this.container?.get("HttpKernel"))?.trustedHosts;
650
655
  if (typeof th === "string") hosts.add(th);
651
656
  else if (Array.isArray(th)) for (const h of th) hosts.add(h);
652
657
  const httpSrc = [];
@@ -722,7 +727,7 @@ let FrontendService = class FrontendService extends Service {
722
727
  const ports = /* @__PURE__ */ new Set();
723
728
  for (const [family, block] of this.plannedPortBlocks ?? []) {
724
729
  const st = this.supervisors.get(family)?.status();
725
- if ((st?.state === "ready" || st?.state === "compiling") && st?.port) ports.add(String(st.port));
730
+ if ((st?.state === "ready" || st?.state === "compiling") && st.port) ports.add(String(st.port));
726
731
  else for (const p of block) ports.add(String(p));
727
732
  }
728
733
  for (const [family, sup] of this.supervisors) {
@@ -23,7 +23,8 @@ var ViteConfigGenerator = class {
23
23
  * un SPA-fallback HTML (cause classique de `Unexpected token '<'`).
24
24
  */
25
25
  toMjs(entries, mode, opts = {}) {
26
- if (entries.length === 0) throw new Error("ViteConfigGenerator: empty entries");
26
+ const [first] = entries;
27
+ if (first === void 0) throw new Error("ViteConfigGenerator: empty entries");
27
28
  const usedTypes = /* @__PURE__ */ new Set();
28
29
  for (const e of entries) usedTypes.add(e.type);
29
30
  const angularEntry = entries.find((e) => e.type === "angular");
@@ -43,6 +44,7 @@ var ViteConfigGenerator = class {
43
44
  break;
44
45
  case "angular": {
45
46
  imports.push(`import angular from "@analogjs/vite-plugin-angular";`);
47
+ if (!angularEntry) throw new Error("vite config: aucune entrée angular pour le type « angular »");
46
48
  const tsconfigPath = toGeneratedPath(path.resolve(angularEntry.root, "tsconfig.app.json"));
47
49
  pluginsExprs.push(`angular({ disableTypeChecking: false, tsconfig: ${JSON.stringify(tsconfigPath)} })`);
48
50
  optimizeInclude.push("@angular/core", "@angular/common", "@angular/platform-browser");
@@ -58,8 +60,8 @@ var ViteConfigGenerator = class {
58
60
  }
59
61
  const input = {};
60
62
  for (const e of entries) input[e.entryName] = toGeneratedPath(path.resolve(e.root, e.entryFile));
61
- const root = toGeneratedPath(entries[0].root);
62
- const outDir = toGeneratedPath(entries[0].outDir);
63
+ const root = toGeneratedPath(first.root);
64
+ const outDir = toGeneratedPath(first.outDir);
63
65
  const fsAllowSet = /* @__PURE__ */ new Set([toGeneratedPath(process.cwd())]);
64
66
  for (const e of entries) fsAllowSet.add(toGeneratedPath(e.root));
65
67
  try {
@@ -2,7 +2,7 @@ import { FrontendSupervisorStartError } from "../src/errors/FrontendError.js";
2
2
  import { ViteConfigGenerator } from "./ViteConfigGenerator.js";
3
3
  import { browserReachableHost, resolveOriginTemplate } from "../src/remoteDev.js";
4
4
  import { createRequire } from "node:module";
5
- import { signalProcessGroup } from "nodefony";
5
+ import { GENERATED_VITE_CONFIG_FILE, signalProcessGroup } from "nodefony";
6
6
  import path from "node:path";
7
7
  import { spawn } from "node:child_process";
8
8
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
@@ -249,13 +249,15 @@ var ViteProcessSupervisor = class {
249
249
  async attemptSpawn(port) {
250
250
  this.state = "starting";
251
251
  this.cleanupChildListeners();
252
- const moduleRoot = this.entries[0].root;
253
- this.configFilePath = path.resolve(moduleRoot, "vite.config.generated.mjs");
252
+ const [first] = this.entries;
253
+ if (first === void 0) throw new FrontendSupervisorStartError("no entries");
254
+ const moduleRoot = first.root;
255
+ this.configFilePath = path.resolve(moduleRoot, GENERATED_VITE_CONFIG_FILE);
254
256
  const scheme = this.opts.https ? "https" : "http";
255
257
  const tpl = this.opts.publicOriginTemplate;
256
258
  const resolved = tpl ? resolveOriginTemplate(tpl, port) : null;
257
259
  if (tpl && !resolved) this.opts.logger.error(`publicOrigin invalide (« ${tpl} ») — attendu scheme://host[:port|:{port}] ; origine locale dérivée utilisée à la place`);
258
- if (resolved && !tpl.includes("{port}") && port !== this.opts.devPort) this.opts.logger.error(`publicOrigin figée (« ${tpl} ») mais Vite écoute sur ${port} (≠ ${this.opts.devPort}) — ajouter {port} au template ou libérer le port d'origine`);
260
+ if (resolved && tpl && !tpl.includes("{port}") && port !== this.opts.devPort) this.opts.logger.error(`publicOrigin figée (« ${tpl} ») mais Vite écoute sur ${port} (≠ ${this.opts.devPort}) — ajouter {port} au template ou libérer le port d'origine`);
259
261
  const viteOrigin = resolved?.origin ?? `${scheme}://${browserReachableHost(this.opts.devHost)}:${port}`;
260
262
  this.resolvedOrigin = viteOrigin;
261
263
  const content = this.generator.toMjs(this.entries, "development", {
@@ -347,9 +349,9 @@ var ViteProcessSupervisor = class {
347
349
  pipeClean(txt, "info");
348
350
  if (resolved) return;
349
351
  buffer += txt.replace(ansiRe, "");
350
- const m = buffer.match(localRe);
351
- if (m) {
352
- this.resolvedPort = parseInt(m[2], 10);
352
+ const [, , port] = buffer.match(localRe) ?? [];
353
+ if (port !== void 0) {
354
+ this.resolvedPort = parseInt(port, 10);
353
355
  this.state = "ready";
354
356
  this.healthFailures = 0;
355
357
  resolved = true;
@@ -363,9 +365,9 @@ var ViteProcessSupervisor = class {
363
365
  pipeClean(txt, "error");
364
366
  if (resolved) return;
365
367
  buffer += txt.replace(ansiRe, "");
366
- const m = buffer.match(localRe);
367
- if (m) {
368
- this.resolvedPort = parseInt(m[2], 10);
368
+ const [, , port] = buffer.match(localRe) ?? [];
369
+ if (port !== void 0) {
370
+ this.resolvedPort = parseInt(port, 10);
369
371
  this.state = "ready";
370
372
  this.healthFailures = 0;
371
373
  resolved = true;
@@ -399,8 +401,8 @@ var ViteProcessSupervisor = class {
399
401
  this.lastError = err.message;
400
402
  reject(new FrontendSupervisorStartError(err.message, err));
401
403
  };
402
- this.trackListener(child.stdout, "data", onStdout);
403
- this.trackListener(child.stderr, "data", onStderr);
404
+ if (child.stdout) this.trackListener(child.stdout, "data", onStdout);
405
+ if (child.stderr) this.trackListener(child.stderr, "data", onStderr);
404
406
  this.trackListener(child, "exit", onExit);
405
407
  this.trackListener(child, "error", onError);
406
408
  });
@@ -456,7 +458,7 @@ var ViteProcessSupervisor = class {
456
458
  this.opts.logger.info(`vite restart #${this.restartCount} succeeded`);
457
459
  this.startHealthCheck();
458
460
  }).catch((e) => {
459
- this.opts.logger.error(`vite restart #${this.restartCount} failed: ${e?.message ?? e}`);
461
+ this.opts.logger.error(`vite restart #${this.restartCount} failed: ${e instanceof Error ? e.message : String(e)}`);
460
462
  this.state = "crashed";
461
463
  this.scheduleRestart();
462
464
  });
@@ -476,7 +478,7 @@ var ViteProcessSupervisor = class {
476
478
  }
477
479
  }).catch((e) => {
478
480
  this.healthFailures++;
479
- this.opts.logger.error(`vite healthcheck failed (${this.healthFailures}/${this.cfg.healthCheckFailureThreshold}): ${e?.message ?? e}`);
481
+ this.opts.logger.error(`vite healthcheck failed (${this.healthFailures}/${this.cfg.healthCheckFailureThreshold}): ${e instanceof Error ? e.message : String(e)}`);
480
482
  if (this.healthFailures >= this.cfg.healthCheckFailureThreshold && this.state === "ready") {
481
483
  this.opts.logger.error(`vite unhealthy — killing child to trigger restart`);
482
484
  this.expectRestartKill = true;
@@ -557,7 +559,7 @@ var ViteProcessSupervisor = class {
557
559
  }
558
560
  sigKillTimer = setTimeout(() => {
559
561
  const c = this.child;
560
- if (c && c.exitCode === null && c.signalCode === null) this.signalTree(c, "SIGKILL");
562
+ if (c?.exitCode === null && c.signalCode === null) this.signalTree(c, "SIGKILL");
561
563
  }, 3e3);
562
564
  });
563
565
  }
@@ -75,7 +75,8 @@ var ViteBuilder = class {
75
75
  this.presets.set(preset.type, preset);
76
76
  }
77
77
  async buildViteConfig(entries, mode, assetBaseUrl = "") {
78
- if (entries.length === 0) return { mode };
78
+ const [first] = entries;
79
+ if (first === void 0) return { mode };
79
80
  const usedPresets = /* @__PURE__ */ new Set();
80
81
  for (const e of entries) usedPresets.add(e.type);
81
82
  const plugins = [];
@@ -88,9 +89,9 @@ var ViteBuilder = class {
88
89
  }
89
90
  const input = {};
90
91
  for (const e of entries) input[e.entryName] = path.resolve(e.root, e.entryFile);
91
- const root = entries[0].root;
92
- const outDir = entries[0].outDir;
93
- const base = mode === "production" ? assetBaseUrl + entries[0].publicPath : void 0;
92
+ const root = first.root;
93
+ const outDir = first.outDir;
94
+ const base = mode === "production" ? assetBaseUrl + first.publicPath : void 0;
94
95
  const dedupe = resolveDedupe(usedPresets);
95
96
  return {
96
97
  mode,
@@ -108,7 +108,8 @@ function originWithHostname(origin, hostname) {
108
108
  const m = RESOLVED_ORIGIN_RE.exec(origin);
109
109
  if (!m) return null;
110
110
  if (!/^(\[[^\]/]+\]|[A-Za-z0-9._-]+)$/.test(hostname)) return null;
111
- return `${m[1]}${hostname}${m[3] ?? ""}`;
111
+ const port = m[3];
112
+ return `${m[1]}${hostname}${port ?? ""}`;
112
113
  }
113
114
  /**
114
115
  * Résout un template d'origine contre le port RÉEL du spawn. Pure.
@@ -135,9 +136,8 @@ function resolveOriginTemplate(template, port) {
135
136
  * (un `{port}` dans le DERNIER label n'a pas de suffixe à wildcarder).
136
137
  */
137
138
  function allowedHostPatternForTemplate(template) {
138
- const m = ORIGIN_TEMPLATE_RE.exec(template);
139
- if (!m) return null;
140
- const hostTemplate = m[2];
139
+ const [, , hostTemplate] = ORIGIN_TEMPLATE_RE.exec(template) ?? [];
140
+ if (hostTemplate === void 0) return null;
141
141
  if (!hostTemplate.includes("{port}")) return hostTemplate;
142
142
  const dot = hostTemplate.indexOf(".");
143
143
  if (dot === -1 || hostTemplate.slice(dot + 1).includes("{port}")) return null;
@@ -73,7 +73,7 @@ var TemplateHelper = class {
73
73
  const tags = this.renderTags(entryName, nonce, requestHost);
74
74
  const entry = this.entries.find((e) => e.entryName === entryName) ?? this.supervisor?.status().entries.find((e) => e.entryName === entryName);
75
75
  const html = entry ? this.loadIndexHtml(entry.root) : null;
76
- if (!html) return `<!DOCTYPE html>
76
+ if (!entry || !html) return `<!DOCTYPE html>
77
77
  <html lang="en">
78
78
  <head>
79
79
  <meta charset="utf-8" />
@@ -201,7 +201,7 @@ mountDebugBar(${opts});
201
201
  const manifest = this.loadManifest(entry.outDir);
202
202
  if (!manifest) return `<!-- @nodefony/frontend: prod manifest missing for "${entryName}" (run \`nodefony frontend:build\`) -->`;
203
203
  const key = entry.entryFile.replace(/\\/g, "/");
204
- const chunk = manifest[key] ?? Object.values(manifest).find((c) => c.isEntry);
204
+ const chunk = manifest[key] ?? Object.values(manifest).find((c) => c?.isEntry);
205
205
  if (!chunk) return `<!-- @nodefony/frontend: entry chunk "${key}" not in manifest -->`;
206
206
  const base = this.assetBaseUrl + entry.publicPath;
207
207
  const tags = [];
@@ -185,7 +185,7 @@ declare class FrontendService extends Service implements IFrontendService {
185
185
  * @param opts.force ignore le cache de fraîcheur (rebuild systématique).
186
186
  */
187
187
  build(opts?: {
188
- force?: boolean;
188
+ force?: boolean | undefined;
189
189
  }): Promise<IFrontendBuildResult>;
190
190
  /**
191
191
  * Une entrée est « fraîche » si son `manifest.json` existe ET qu'aucun fichier
@@ -13,7 +13,7 @@ export interface ViteConfigGeneratorOptions {
13
13
  * Origine du serveur Nodefony pour le proxy Vite (`server.proxy`).
14
14
  * Exemple : `"http://127.0.0.1:5151"`. En dev uniquement — ignoré en prod.
15
15
  */
16
- readonly backendOrigin?: string;
16
+ readonly backendOrigin?: string | undefined;
17
17
  /**
18
18
  * Origine publique du dev server Vite — ex `"http://127.0.0.1:5173"`.
19
19
  * Définie comme `base` dans Vite, ce qui force les imports internes du
@@ -22,7 +22,7 @@ export interface ViteConfigGeneratorOptions {
22
22
  * Nodefony (5151) qui charge `/src/main.tsx` voit ses imports résolus
23
23
  * contre 5151 → 404. Active aussi `strictPort` pour garantir l'origine.
24
24
  */
25
- readonly viteOrigin?: string;
25
+ readonly viteOrigin?: string | undefined;
26
26
  /**
27
27
  * Certificats HTTPS — paths absolus vers les fichiers PEM. Quand fourni,
28
28
  * la config Vite générée inclut `server.https: { key, cert }` (lus via
@@ -31,14 +31,14 @@ export interface ViteConfigGeneratorOptions {
31
31
  readonly https?: {
32
32
  readonly keyPath: string;
33
33
  readonly certPath: string;
34
- };
34
+ } | undefined;
35
35
  /**
36
36
  * Hôtes acceptés dans le header `Host` (`server.allowedHosts`, Vite ≥6).
37
37
  * `true` = tous. Un motif `.suffixe` couvre le domaine et ses sous-domaines.
38
38
  * Les IP et `localhost` sont toujours acceptés par Vite — cette liste ne
39
39
  * sert que les NOMS (vhosts, `host.docker.internal`, forwarders).
40
40
  */
41
- readonly allowedHosts?: true | ReadonlyArray<string>;
41
+ readonly allowedHosts?: true | ReadonlyArray<string> | undefined;
42
42
  }
43
43
  export declare class ViteConfigGenerator {
44
44
  /**
@@ -18,13 +18,13 @@ export interface ViteSupervisorOptions {
18
18
  * de `devHost:port`. Dissocie ce que Vite ÉCOUTE de ce que le navigateur
19
19
  * APPELLE (forwarder Codespaces/Gitpod, `host.docker.internal`, remap).
20
20
  */
21
- readonly publicOriginTemplate?: string;
21
+ readonly publicOriginTemplate?: string | undefined;
22
22
  /**
23
23
  * Hôtes que Vite doit accepter dans le header `Host` (`server.allowedHosts`).
24
24
  * `true` = tous. Dérivé par FrontendService de la liste `trustedHosts` http —
25
25
  * jamais maintenu ici (1 règle = 1 implémentation).
26
26
  */
27
- readonly allowedHosts?: true | ReadonlyArray<string>;
27
+ readonly allowedHosts?: true | ReadonlyArray<string> | undefined;
28
28
  readonly startupTimeoutMs: number;
29
29
  readonly pipeLogs: boolean;
30
30
  readonly cwd: string;
@@ -41,9 +41,9 @@ export interface ViteSupervisorOptions {
41
41
  readonly https?: {
42
42
  readonly keyPath: string;
43
43
  readonly certPath: string;
44
- };
44
+ } | undefined;
45
45
  /** Valeur de `NODE_ENV` à propager au child Vite — généralement `kernel.environment`. */
46
- readonly nodeEnv?: string;
46
+ readonly nodeEnv?: string | undefined;
47
47
  /**
48
48
  * Variables d'env additionnelles passées au child Vite. Les clés `VITE_*`
49
49
  * sont automatiquement exposées au browser via `import.meta.env`.
@@ -33,7 +33,7 @@ export interface IViteInstanceView {
33
33
  entries: {
34
34
  entryName: string;
35
35
  type: string;
36
- version?: string;
36
+ version?: string | undefined;
37
37
  }[];
38
38
  }
39
39
  /** Snapshot frontend servi par l'endpoint `vite`. */
@@ -41,7 +41,7 @@ export interface IFrontendStatusView {
41
41
  /** Au moins une instance Vite `ready` (HMR actif). */
42
42
  available: boolean;
43
43
  /** Version de Vite (le builder), si résolue. */
44
- vite?: string;
44
+ vite?: string | undefined;
45
45
  /** Instance principale (famille `default` ou la première). */
46
46
  primary: IViteInstanceView;
47
47
  /** Toutes les instances (multi-bundle). */
package/docs/index.md CHANGED
@@ -84,7 +84,7 @@ qui remplace Vite une fois en production.
84
84
  ### La vision Nodefony — ce que ce module fait différemment
85
85
 
86
86
  **Vite est un processus système, pas une bibliothèque.** Le superviseur lance le binaire Vite avec
87
- `child_process.spawn` (`ViteProcessSupervisor.attemptSpawn()`, `ViteProcessSupervisor.ts:414`). La
87
+ `child_process.spawn` (`ViteProcessSupervisor.attemptSpawn()`, `ViteProcessSupervisor.ts:418`). La
88
88
  conséquence est concrète : compiler dix mille modules ne coûte **rien** à la latence de tes requêtes,
89
89
  et un plantage de Vite ne tue pas ton serveur — le superviseur le relance tout seul.
90
90
 
@@ -570,8 +570,8 @@ les processus meurent.
570
570
 
571
571
  | Situation | Réponse |
572
572
  | -------------------------- | ----------------------------------------------------------------------------------------------------- |
573
- | Port occupé au lancement | essai sur le port suivant, jusqu'à `portRetryAttempts` (`ViteProcessSupervisor.ts:297`) |
574
- | Vite plante | relance avec délai exponentiel plafonné (`scheduleRestart()`, `ViteProcessSupervisor.ts:715`) |
573
+ | Port occupé au lancement | essai sur le port suivant, jusqu'à `portRetryAttempts` (`ViteProcessSupervisor.ts:301`) |
574
+ | Vite plante | relance avec délai exponentiel plafonné (`scheduleRestart()`, `ViteProcessSupervisor.ts:729`) |
575
575
  | Vite ne répond plus (gelé) | sonde périodique ; après N échecs, Vite est tué pour être relancé (`ViteProcessSupervisor.ts:787`) |
576
576
  | Deux `start()` concurrents | la promesse en cours est partagée — jamais deux processus |
577
577
  | Ctrl+C au terminal | le signal marque un arrêt **voulu** : pas de relance (`markShutdown`, `ViteProcessSupervisor.ts:266`) |
@@ -593,7 +593,7 @@ incompréhensibles :
593
593
  repayant l'attente de démarrage à chaque essai.
594
594
 
595
595
  Les écouteurs attachés au processus enfant sont suivis puis retirés à chaque mort
596
- (`cleanupChildListeners()`, `ViteProcessSupervisor.ts:971`) : sans cela, les relances successives les
596
+ (`cleanupChildListeners()`, `ViteProcessSupervisor.ts:984`) : sans cela, les relances successives les
597
597
  accumuleraient jusqu'à l'avertissement de fuite.
598
598
 
599
599
  ## 🧰 API publique
@@ -667,7 +667,7 @@ l'état. Une page dégradée reste une page.
667
667
  ### Les helpers de vue
668
668
 
669
669
  Si tu rends une vue Eta plutôt qu'une chaîne, trois helpers sont déjà dans tes variables locales
670
- (`Controller.withFrontendLocals()`, `Controller.ts:448`) — inspirés des helpers d'assets de Symfony :
670
+ (`Controller.withFrontendLocals()`, `Controller.ts:562`) — inspirés des helpers d'assets de Symfony :
671
671
 
672
672
  ```html
673
673
  <%~ frontendDocument("shop") %>
@@ -699,7 +699,7 @@ et son manifeste — c'est ce qui rend le multi-modules possible et ce qui isole
699
699
  Quatre comportements à connaître :
700
700
 
701
701
  - **Idempotent.** Une entrée dont le manifeste est plus récent que ses sources est ignorée
702
- (`isBuildFresh()`, `FrontendService.ts:879`) — le scan est borné au dossier front et saute
702
+ (`isBuildFresh()`, `FrontendService.ts:886`) — le scan est borné au dossier front et saute
703
703
  `node_modules`. Relancer un déploiement ne recompile pas tout.
704
704
  - **Les échecs sont collectés, pas propagés.** Un bundle en échec n'arrête pas les autres ; la
705
705
  commande passe le code de sortie à `1` s'il en reste un — de quoi casser un pipeline sans masquer
@@ -829,7 +829,7 @@ Sur le chemin chaud du rendu, trois précautions :
829
829
  - le **manifeste** est lu une fois par dossier de sortie, jamais par requête ;
830
830
  - l'**`index.html`** est mis en cache en production (relu en développement, où la fraîcheur prime) ;
831
831
  - les **écouteurs** du processus enfant sont suivis et retirés à chaque mort
832
- (`trackListener()`, `ViteProcessSupervisor.ts:961`) — sans quoi les relances les accumuleraient.
832
+ (`trackListener()`, `ViteProcessSupervisor.ts:974`) — sans quoi les relances les accumuleraient.
833
833
 
834
834
  La sonde de vie coûte une requête HTTP toutes les trente secondes par famille. Elle est désactivable
835
835
  (`healthCheckIntervalMs: 0`) si ce budget te gêne, au prix de la détection d'un Vite gelé.
@@ -928,6 +928,3 @@ Vite en ligne de commande, jamais par un navigateur sans affichage.
928
928
  [build et empaquetage](../../../../../docs/architecture/build-bundling.md) ·
929
929
  [vue d'ensemble du framework](../../../../../docs/architecture/vue-ensemble.md)
930
930
  - 📖 [Lexique général](../../../../../docs/lexique.md) du framework.
931
- </content>
932
-
933
- </invoke>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodefony/frontend",
3
- "version": "10.0.0-alpha.9",
3
+ "version": "10.0.0-beta.2",
4
4
  "description": "Construction et rechargement à chaud des frontends de chaque module Nodefony — Vite intégré, multi-framework (React, Vue, Angular, Svelte)",
5
5
  "author": "Christophe CAMENSULI <ccamensuli@gmail.com>",
6
6
  "type": "module",
@@ -36,21 +36,20 @@
36
36
  "esm"
37
37
  ],
38
38
  "peerDependencies": {
39
- "@nodefony/framework": "^10.0.0-alpha.9",
40
- "@nodefony/http": "^10.0.0-alpha.9",
41
- "nodefony": "^10.0.0-alpha.9",
39
+ "@nodefony/framework": "^10.0.0-beta.2",
40
+ "@nodefony/http": "^10.0.0-beta.2",
41
+ "nodefony": "^10.0.0-beta.2",
42
42
  "zod": "^4.6.5"
43
43
  },
44
44
  "devDependencies": {
45
- "@nodefony/framework": "^10.0.0-alpha.9",
46
- "@nodefony/http": "^10.0.0-alpha.9",
45
+ "@nodefony/framework": "^10.0.0-beta.2",
46
+ "@nodefony/http": "^10.0.0-beta.2",
47
47
  "@types/chai": "5.2.3",
48
- "@types/node": "26.6.2",
49
- "@vitest/coverage-v8": "5.0.1",
50
- "chai": "6.2.2",
51
- "nodefony": "^10.0.0-alpha.9",
52
- "vite": "8.3.1",
53
- "vitest": "5.0.1"
48
+ "@types/node": "26.6.3",
49
+ "@vitest/coverage-v8": "5.0.3",
50
+ "nodefony": "^10.0.0-beta.2",
51
+ "vite": "8.3.2",
52
+ "vitest": "5.0.3"
54
53
  },
55
54
  "private": false,
56
55
  "engines": {