poad 2.37.0 → 2.39.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/utils/latest.js CHANGED
@@ -1,67 +1,115 @@
1
- // Dernière version publiée de l'engine, lue sur Docker Hub (poadio/engine) :
2
- // le CLI n'a pas à être republié à chaque engine. Hors ligne ou réponse
3
- // illisible : null, l'appelant garde la version inscrite dans le CLI.
4
- const TAGS_URL = 'https://hub.docker.com/v2/repositories/poadio/engine/tags?page_size=100';
1
+ // Version d'engine à utiliser par défaut (init, install, proposition au
2
+ // démarrage, upgrade, clean) : le CLI n'a pas à être republié à chaque engine.
3
+ //
4
+ // 1. poadio/permalink (poad.json, public) : { "engine": { "stable": "x.y.z", "beta": "x.y.z-beta.N" } }.
5
+ // C'est la version recommandée par canal ; elle permet de retenir un engine
6
+ // publié, de revenir en arrière, ou d'en proposer un en avance (beta).
7
+ // 2. Sans permalink (illisible, sans clé engine) : le dernier tag x.y.z de
8
+ // poadio/engine sur Docker Hub, jamais plus ancien que celui du CLI.
9
+ // 3. Hors ligne : le dernier résultat connu (cache), sinon la version du CLI.
10
+ //
11
+ // Canal : stable par défaut ; beta par POAD_CHANNEL=beta, channel = "beta"
12
+ // dans poad/config.toml, ou channel=beta sur la ligne de commande. Le canal
13
+ // beta prend la beta de permalink si elle est plus récente que la stable.
14
+ const { isVersion, isRelease, compareVersions } = require('./version');
5
15
 
6
- const compare = (a, b) => {
7
- const x = a.split('.').map(Number);
8
- const y = b.split('.').map(Number);
9
- return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
10
- };
16
+ const TAGS_URL = 'https://hub.docker.com/v2/repositories/poadio/engine/tags?page_size=100';
17
+ const PERMALINK_URL = 'https://raw.githubusercontent.com/poadio/permalink/main/poad.json';
18
+ const CHANNELS = ['stable', 'beta'];
19
+ const CACHE_TTL = 6 * 3600 * 1000;
11
20
 
12
21
  // Seules les versions x.y.z comptent : ni latest, ni préversion
13
22
  const pickLatest = (tags) => {
14
- const versions = (tags || []).filter((t) => typeof t === 'string' && /^\d+\.\d+\.\d+$/.test(t));
15
- return versions.length ? versions.sort(compare).pop() : null;
23
+ const versions = (tags || []).filter(isRelease);
24
+ return versions.length ? versions.sort(compareVersions).pop() : null;
16
25
  };
17
26
 
18
- const latestEngine = async (timeout = 4000) => {
27
+ const fetchJson = async (url, timeout) => {
19
28
  try {
20
- const res = await fetch(TAGS_URL, { signal: AbortSignal.timeout(timeout) });
21
- if (!res.ok) return null;
22
- return pickLatest(((await res.json()).results || []).map((t) => t.name));
29
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeout), headers: { 'cache-control': 'no-cache' } });
30
+ return res.ok ? await res.json() : null;
23
31
  } catch {
24
32
  return null;
25
33
  }
26
34
  };
27
35
 
28
- // Version d'engine à utiliser par défaut (init, install, proposition au
29
- // démarrage, clean) : la dernière publiée, mise en cache quelques heures dans
30
- // ~/.poad pour ne pas interroger Docker Hub à chaque commande ; hors ligne, le
31
- // dernier résultat connu ; sans rien, la version inscrite dans le CLI. Jamais
32
- // plus ancienne que celle du CLI.
33
- const CACHE_TTL = 6 * 3600 * 1000;
36
+ const latestEngine = async (timeout = 4000) => {
37
+ const body = await fetchJson(TAGS_URL, timeout);
38
+ return body ? pickLatest((body.results || []).map((t) => t.name)) : null;
39
+ };
40
+
41
+ /** Versions d'engine par canal lues dans permalink : { stable?, beta? }, ou null */
42
+ const permalinkEngines = async (timeout = 4000) => {
43
+ const body = await fetchJson(PERMALINK_URL, timeout);
44
+ const engine = body && typeof body === 'object' ? body.engine : null;
45
+ if (!engine || typeof engine !== 'object') return null;
46
+ const out = {};
47
+ if (isRelease(engine.stable)) out.stable = engine.stable;
48
+ if (isVersion(engine.beta)) out.beta = engine.beta;
49
+ return Object.keys(out).length ? out : null;
50
+ };
51
+
52
+ const engineChannel = (config = {}, args = {}) => {
53
+ const c = String(args.channel || process.env.POAD_CHANNEL || (config && config.channel) || 'stable').toLowerCase();
54
+ return CHANNELS.includes(c) ? c : 'stable';
55
+ };
56
+
34
57
  const cacheFile = () => require('path').join(require('os').homedir(), '.poad', 'engine-latest.json');
35
58
 
36
59
  const readCache = () => {
37
60
  try {
38
61
  const c = JSON.parse(require('fs').readFileSync(cacheFile(), 'utf8'));
39
- return c && typeof c.version === 'string' && /^\d+\.\d+\.\d+$/.test(c.version) ? c : null;
62
+ return c && typeof c.at === 'number' ? c : null;
40
63
  } catch {
41
64
  return null;
42
65
  }
43
66
  };
44
67
 
45
- const writeCache = (version) => {
68
+ const writeCache = (data) => {
46
69
  try {
47
70
  const fs = require('fs');
48
71
  fs.mkdirSync(require('path').dirname(cacheFile()), { recursive: true });
49
- fs.writeFileSync(cacheFile(), JSON.stringify({ version, at: Date.now() }));
72
+ fs.writeFileSync(cacheFile(), JSON.stringify({ ...data, at: Date.now() }));
50
73
  } catch {
51
74
  // cache facultatif
52
75
  }
53
76
  };
54
77
 
55
- const engineRelease = async ({ fresh = false, timeout = 2500 } = {}) => {
78
+ /**
79
+ * { version, channel, source } : source = permalink, docker-hub, cache ou cli
80
+ * (hors ligne, sans rien de connu). fresh : ignorer le cache récent.
81
+ */
82
+ const engineReleaseInfo = async ({ fresh = false, channel = 'stable', timeout = 2500 } = {}) => {
56
83
  const pinned = (global.package && global.package.engine) || null;
57
84
  const cached = readCache();
58
- let latest = !fresh && cached && Date.now() - cached.at < CACHE_TTL ? cached.version : null;
59
- if (!latest) {
60
- latest = await latestEngine(timeout);
61
- if (latest) writeCache(latest);
62
- else latest = cached ? cached.version : null;
85
+ let data = !fresh && cached && Date.now() - cached.at < CACHE_TTL ? cached : null;
86
+ let source = data ? 'cache' : null;
87
+ if (!data) {
88
+ const permalink = await permalinkEngines(timeout);
89
+ const hub = permalink && permalink.stable ? null : await latestEngine(timeout);
90
+ if (permalink || hub) {
91
+ data = { permalink, hub };
92
+ writeCache(data);
93
+ source = permalink && permalink.stable ? 'permalink' : 'docker-hub';
94
+ } else if (cached) {
95
+ data = cached;
96
+ source = 'cache';
97
+ }
98
+ }
99
+ const permalink = (data && data.permalink) || null;
100
+ let stable = permalink && permalink.stable ? permalink.stable : null;
101
+ if (!stable) {
102
+ const hub = data && data.hub;
103
+ stable = pickLatest([hub, pinned].filter(Boolean)) || pinned;
63
104
  }
64
- return pickLatest([latest, pinned].filter(Boolean));
105
+ if (!data) source = 'cli';
106
+ let version = stable;
107
+ if (channel === 'beta' && permalink && permalink.beta && (!stable || compareVersions(permalink.beta, stable) > 0)) {
108
+ version = permalink.beta;
109
+ }
110
+ return { version: version || null, channel, source };
65
111
  };
66
112
 
67
- module.exports = { latestEngine, pickLatest, engineRelease };
113
+ const engineRelease = async (options = {}) => (await engineReleaseInfo(options)).version;
114
+
115
+ module.exports = { latestEngine, pickLatest, permalinkEngines, engineChannel, engineRelease, engineReleaseInfo };
@@ -0,0 +1,145 @@
1
+ // Registre npm, sans npm ni dépendance : métadonnées d'un paquet, archive de
2
+ // sa dernière version, vérification de son intégrité (sha512 publié par le
3
+ // registre) avant tout usage.
4
+ //
5
+ // Cache : ~/.poad/starters/ garde la dernière archive vérifiée de chaque
6
+ // paquet et son empreinte ; hors ligne, c'est elle qui sert (vérifiée à
7
+ // nouveau à la lecture).
8
+ const crypto = require('crypto');
9
+ const fs = require('fs');
10
+ const os = require('os');
11
+ const path = require('path');
12
+
13
+ const REGISTRY = 'https://registry.npmjs.org';
14
+ // Archive d'un modèle d'application : quelques centaines de Ko ; au-delà de
15
+ // 50 Mo, ce n'est plus un modèle
16
+ const MAX_TARBALL = 50 * 1024 * 1024;
17
+
18
+ class RegistryError extends Error {}
19
+
20
+ const cacheDir = () => path.join(os.homedir(), '.poad', 'starters');
21
+ const cacheBase = (name) => path.join(cacheDir(), name.replace(/^@/, '').replace(/[^a-zA-Z0-9._-]+/g, '__'));
22
+
23
+ /** URL des métadonnées : le « / » d'un nom à portée (@scope/nom) est encodé */
24
+ const metadataUrl = (name, registry = REGISTRY) => `${registry.replace(/\/+$/, '')}/${name.replace('/', '%2f')}`;
25
+
26
+ /**
27
+ * Métadonnées abrégées d'un paquet (dist-tags, versions avec dist) :
28
+ * { status: 'ok', data } | { status: 'missing' } (404) | { status: 'offline', error }
29
+ */
30
+ async function packageMetadata(name, { registry = REGISTRY, timeout = 3000 } = {}) {
31
+ try {
32
+ const res = await fetch(metadataUrl(name, registry), {
33
+ signal: AbortSignal.timeout(timeout),
34
+ headers: { accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8' },
35
+ });
36
+ if (res.status === 404) return { status: 'missing' };
37
+ if (!res.ok) return { status: 'offline', error: `HTTP ${res.status}` };
38
+ return { status: 'ok', data: await res.json() };
39
+ } catch (err) {
40
+ return { status: 'offline', error: err.name === 'TimeoutError' ? 'timeout' : err.message };
41
+ }
42
+ }
43
+
44
+ /** { version, tarball, integrity } de la version « latest », ou une erreur */
45
+ function latestDist(name, data) {
46
+ const version = data && data['dist-tags'] && data['dist-tags'].latest;
47
+ const meta = version && data.versions && data.versions[version];
48
+ if (!meta || !meta.dist) throw new RegistryError(`${name}: no "latest" version in the registry`);
49
+ const { tarball, integrity } = meta.dist;
50
+ if (typeof tarball !== 'string' || !tarball.startsWith('https://')) throw new RegistryError(`${name}@${version}: the tarball URL is not HTTPS`);
51
+ if (!parseIntegrity(integrity)) throw new RegistryError(`${name}@${version}: no sha512 integrity in the registry metadata`);
52
+ return { version, tarball, integrity };
53
+ }
54
+
55
+ /** Empreinte(s) sha512 d'une chaîne SRI (« sha512-<base64> », éventuellement plusieurs) */
56
+ function parseIntegrity(integrity) {
57
+ if (typeof integrity !== 'string') return null;
58
+ const hashes = integrity
59
+ .trim()
60
+ .split(/\s+/)
61
+ .map((h) => /^sha512-([A-Za-z0-9+/]+={0,2})(\?.*)?$/.exec(h))
62
+ .filter(Boolean)
63
+ .map((m) => Buffer.from(m[1], 'base64'))
64
+ .filter((b) => b.length === 64);
65
+ return hashes.length ? hashes : null;
66
+ }
67
+
68
+ /** Lève une erreur si le contenu ne correspond pas à l'empreinte sha512 publiée */
69
+ function verifyIntegrity(buf, integrity, label = 'archive') {
70
+ const expected = parseIntegrity(integrity);
71
+ if (!expected) throw new RegistryError(`${label}: no sha512 integrity to check against`);
72
+ const actual = crypto.createHash('sha512').update(buf).digest();
73
+ if (!expected.some((e) => crypto.timingSafeEqual(e, actual))) {
74
+ throw new RegistryError(`${label}: integrity check failed (sha512 mismatch): the download was altered or corrupted, nothing was extracted`);
75
+ }
76
+ }
77
+
78
+ async function download(url, { timeout = 60000, maxBytes = MAX_TARBALL } = {}) {
79
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeout), redirect: 'follow' });
80
+ if (!res.ok) throw new RegistryError(`download failed: HTTP ${res.status}`);
81
+ if (!res.url.startsWith('https://')) throw new RegistryError('download redirected outside HTTPS');
82
+ const declared = Number(res.headers.get('content-length'));
83
+ if (declared > maxBytes) throw new RegistryError(`tarball larger than ${maxBytes} bytes`);
84
+ const chunks = [];
85
+ let total = 0;
86
+ for await (const chunk of res.body) {
87
+ total += chunk.length;
88
+ if (total > maxBytes) throw new RegistryError(`tarball larger than ${maxBytes} bytes`);
89
+ chunks.push(chunk);
90
+ }
91
+ return Buffer.concat(chunks);
92
+ }
93
+
94
+ function readCached(name) {
95
+ try {
96
+ const meta = JSON.parse(fs.readFileSync(`${cacheBase(name)}.json`, 'utf8'));
97
+ const buf = fs.readFileSync(`${cacheBase(name)}.tgz`);
98
+ verifyIntegrity(buf, meta.integrity, `${name}@${meta.version} (cache)`);
99
+ return { ...meta, buf };
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ function writeCached(name, { version, integrity, buf }) {
106
+ try {
107
+ fs.mkdirSync(cacheDir(), { recursive: true });
108
+ fs.writeFileSync(`${cacheBase(name)}.tgz`, buf);
109
+ fs.writeFileSync(`${cacheBase(name)}.json`, JSON.stringify({ name, version, integrity, at: new Date().toISOString() }));
110
+ } catch {
111
+ // cache facultatif
112
+ }
113
+ }
114
+
115
+ /** Version connue en cache (sans lire l'archive), ou null */
116
+ function cachedVersion(name) {
117
+ try {
118
+ return JSON.parse(fs.readFileSync(`${cacheBase(name)}.json`, 'utf8')).version || null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Archive vérifiée de la dernière version d'un paquet : { version, buf, source: 'registry'|'cache' }.
126
+ * metadata : résultat de packageMetadata déjà obtenu (évite une seconde requête).
127
+ */
128
+ async function fetchLatestTarball(name, { registry = REGISTRY, metadata, timeout } = {}) {
129
+ const meta = metadata || (await packageMetadata(name, { registry, timeout }));
130
+ if (meta.status === 'missing') throw new RegistryError(`${name} is not published on npm`);
131
+ if (meta.status === 'offline') {
132
+ const cached = readCached(name);
133
+ if (cached) return { version: cached.version, buf: cached.buf, source: 'cache' };
134
+ throw new RegistryError(`the npm registry cannot be reached (${meta.error}) and ${name} is not in the cache`);
135
+ }
136
+ const dist = latestDist(name, meta.data);
137
+ const cached = readCached(name);
138
+ if (cached && cached.version === dist.version && cached.integrity === dist.integrity) return { version: dist.version, buf: cached.buf, source: 'cache' };
139
+ const buf = await download(dist.tarball);
140
+ verifyIntegrity(buf, dist.integrity, `${name}@${dist.version}`);
141
+ writeCached(name, { version: dist.version, integrity: dist.integrity, buf });
142
+ return { version: dist.version, buf, source: 'registry' };
143
+ }
144
+
145
+ module.exports = { REGISTRY, RegistryError, packageMetadata, latestDist, parseIntegrity, verifyIntegrity, fetchLatestTarball, cachedVersion, metadataUrl };
package/utils/report.js CHANGED
@@ -1,8 +1,19 @@
1
1
  // Affichage de l'état du projet, commun à poad info et poad start : le projet
2
2
  // (URL, base, clés, migrations), puis le panneau des services (Mailpit,
3
3
  // Keycloak, Valkey, exécuteur des flows) avec leur état et leurs accès.
4
+ //
5
+ // Secrets : jamais affichés par défaut (un terminal se partage, se filme, se
6
+ // colle dans un ticket). Le secret JWT, la clé service_role, la clé secrète S3
7
+ // et le mot de passe admin de Keycloak sont remplacés par « hidden » ; seul
8
+ // `poad info --secrets` les montre. La clé anon reste : elle est faite pour le
9
+ // navigateur.
4
10
  const path = require('path');
5
11
 
12
+ const SECRETS_HINT = 'hidden · poad info --secrets';
13
+
14
+ /** Valeur secrète affichée seulement si demandée (opts.secrets) */
15
+ const secretValue = (value, opts = {}) => (opts.secrets ? String(value) : require('chalk-v2').grey(SECRETS_HINT));
16
+
6
17
  async function migrationsLine(root, config) {
7
18
  const migrations = require('./migrations');
8
19
  const count = migrations.files(root).list.length;
@@ -27,7 +38,7 @@ async function migrationsLine(root, config) {
27
38
  }
28
39
  }
29
40
 
30
- async function printProject(root, config) {
41
+ async function printProject(root, config, opts = {}) {
31
42
  const chalk = require('chalk-v2');
32
43
  const prettyoutput = require('prettyoutput');
33
44
  const { storageInfo, dataInfo, supportsConsole, consoleUrl } = require('./engine');
@@ -49,12 +60,12 @@ async function printProject(root, config) {
49
60
  : 'this machine only (127.0.0.1)',
50
61
  'API URL': `http://localhost:${config.web.port}`,
51
62
  'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
52
- ...storageInfo(config),
53
- ...dataInfo(config),
63
+ ...storageInfo(config, opts),
64
+ ...dataInfo(config, opts),
54
65
  ...(mail.usesMailpit(config) ? {} : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
55
- 'JWT secret': `${config.auth.secret}`,
66
+ 'JWT secret': secretValue(config.auth.secret, opts),
56
67
  'anon key': config.auth.anon,
57
- 'service_role key': config.auth.service,
68
+ 'service_role key': secretValue(config.auth.service, opts),
58
69
  Config: `${path.relative(process.cwd(), root)} (secrets: ${path.relative(process.cwd(), require('./config').secretsFile(root))})`,
59
70
  };
60
71
  const line = await migrationsLine(root, config);
@@ -62,7 +73,7 @@ async function printProject(root, config) {
62
73
  console.log(prettyoutput(info));
63
74
  }
64
75
 
65
- async function printServices(root, config) {
76
+ async function printServices(root, config, opts = {}) {
66
77
  const chalk = require('chalk-v2');
67
78
  const Docker = require('dockerode');
68
79
  const docker = new Docker();
@@ -91,7 +102,7 @@ async function printServices(root, config) {
91
102
  const tag = auto ? chalk.cyan(' auto') : '';
92
103
  if (running) {
93
104
  console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}${tag}`);
94
- for (const [k, v] of Object.entries(s.info(config, root))) {
105
+ for (const [k, v] of Object.entries(s.info(config, root, opts))) {
95
106
  // Une liste (comptes de test) : une ligne par entrée, alignées
96
107
  const lines = Array.isArray(v) ? v : [v];
97
108
  lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
@@ -109,10 +120,10 @@ async function printServices(root, config) {
109
120
  console.log(' ');
110
121
  }
111
122
 
112
- /** Projet puis services */
113
- async function printReport(root, config) {
114
- await printProject(root, config);
115
- await printServices(root, config);
123
+ /** Projet puis services ; opts.secrets : montrer les secrets (poad info --secrets) */
124
+ async function printReport(root, config, opts = {}) {
125
+ await printProject(root, config, opts);
126
+ await printServices(root, config, opts);
116
127
  }
117
128
 
118
- module.exports = { printReport, printProject, printServices, migrationsLine };
129
+ module.exports = { printReport, printProject, printServices, migrationsLine, secretValue, SECRETS_HINT };
package/utils/services.js CHANGED
@@ -38,7 +38,7 @@ const SERVICES = [
38
38
  configured: (config) => Boolean(config.keycloak && (config.keycloak.port || config.keycloak.shared === true)),
39
39
  autostart: (config) => Boolean(config.keycloak && config.keycloak.autostart === true),
40
40
  savePort: (root, port) => kc.savePort(root, port),
41
- info: (config, root) => {
41
+ info: (config, root, opts = {}) => {
42
42
  const shared = require('./keycloak-shared');
43
43
  const state = shared.isShared(config) ? shared.readState() : null;
44
44
  const base = `http://localhost:${state ? state.port : config.keycloak.port}`;
@@ -48,7 +48,7 @@ const SERVICES = [
48
48
  const out = { URL: base + (state ? ' (shared by the local projects)' : ''), Issuer: `${base}/realms/${realm}`, Provider: `"${kc.PROVIDER}"` };
49
49
  if (project) {
50
50
  // Deux realms, deux usages : ne pas essayer alice sur la console d'admin
51
- out['Admin console'] = [`${base}/admin`, `admin ${state ? state.admin_password : project.secrets.admin_password}`];
51
+ out['Admin console'] = [`${base}/admin`, `admin ${require('./report').secretValue(state ? state.admin_password : project.secrets.admin_password, opts)}`];
52
52
  out['Test users'] = [
53
53
  `realm "${realm}" : "Continuer avec Keycloak" in the app, or ${base}/realms/${realm}/account`,
54
54
  ...project.users.map(
@@ -0,0 +1,214 @@
1
+ // Modèles d'application (« starters ») publiés sur npm sous @poadio/starter-<nom>,
2
+ // et ce qu'il faut faire d'un modèle extrait pour en faire une application :
3
+ // fichiers de publication retirés, .gitignore rétabli, package.json réécrit.
4
+ // Partagé par poad create et poad client init.
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+
8
+ const TEMPLATES = [
9
+ { value: 'angular', label: 'Angular', package: '@poadio/starter-angular' },
10
+ { value: 'next', label: 'Next.js', package: '@poadio/starter-next' },
11
+ { value: 'nuxt', label: 'Nuxt', package: '@poadio/starter-nuxt' },
12
+ { value: 'vanilla', label: 'Vanilla (HTML, CSS, JS)', package: '@poadio/starter-vanilla' },
13
+ ];
14
+
15
+ const templateByValue = (value) => TEMPLATES.find((t) => t.value === String(value || '').toLowerCase()) || null;
16
+
17
+ // Fichiers d'un modèle publié qui n'ont rien à faire dans une application
18
+ // neuve. poad/ : jamais repris (config.toml et secrets sont ceux de poad init).
19
+ const STRIP = ['.npmignore', 'poad/config.toml', 'poad/secrets.toml', 'poad/data', 'poad/backups', 'public/env.json', '.env.local', 'node_modules'];
20
+
21
+ // npm ne publie jamais .gitignore : un modèle le livre sous le nom « gitignore »
22
+ // (convention des create-*), ou, ancien comportement de npm, en .npmignore.
23
+ const GITIGNORE_SOURCES = ['gitignore', '_gitignore', '.npmignore'];
24
+
25
+ // package.json de l'application, règle par règle :
26
+ // fonction -> nouvelle valeur (undefined : clé retirée)
27
+ // null -> clé retirée (champs de publication du modèle)
28
+ const DROP = null;
29
+ const PACKAGE_RULES = {
30
+ name: (pkg, ctx) => ctx.name,
31
+ version: () => '0.1.0',
32
+ private: () => true,
33
+ title: (pkg, ctx) => ctx.title || pkg.title,
34
+ // La description du paquet parle du modèle : l'application prend la sienne
35
+ description: (pkg) => (pkg.poad && pkg.poad.template && pkg.poad.template.description) || undefined,
36
+ files: DROP,
37
+ publishConfig: DROP,
38
+ repository: DROP,
39
+ bugs: DROP,
40
+ homepage: DROP,
41
+ author: DROP,
42
+ contributors: DROP,
43
+ funding: DROP,
44
+ keywords: DROP,
45
+ license: DROP,
46
+ // Origine gardée pour mémoire ; les métadonnées de modèle ne servent plus
47
+ poad: (pkg, ctx) => {
48
+ const poad = { ...(pkg.poad || {}), from: ctx.from };
49
+ delete poad.template;
50
+ return poad;
51
+ },
52
+ };
53
+
54
+ /** package.json d'application à partir de celui du modèle (ctx : { name, title, from }) */
55
+ function rewritePackageJson(pkg, ctx) {
56
+ const out = { ...pkg };
57
+ for (const [key, rule] of Object.entries(PACKAGE_RULES)) {
58
+ const value = rule === DROP ? undefined : rule(pkg, ctx);
59
+ if (value === undefined) delete out[key];
60
+ else out[key] = value;
61
+ }
62
+ // Ordre lisible : name, version, private d'abord
63
+ const head = ['name', 'title', 'description', 'version', 'private'].filter((k) => k in out);
64
+ return Object.fromEntries([...head.map((k) => [k, out[k]]), ...Object.entries(out).filter(([k]) => !head.includes(k))]);
65
+ }
66
+
67
+ /** Nom de paquet npm valide tiré d'un nom de dossier */
68
+ function packageName(dir) {
69
+ const name = String(dir || '')
70
+ .toLowerCase()
71
+ .replace(/[^a-z0-9._-]+/g, '-')
72
+ .replace(/^[-._]+|[-._]+$/g, '')
73
+ .slice(0, 214);
74
+ return name || 'app';
75
+ }
76
+
77
+ /**
78
+ * Prépare un modèle extrait dans dir : .gitignore rétabli puis complété des
79
+ * lignes de poad.template.gitignore, fichiers de publication retirés.
80
+ * Renvoie { gitignore: 'restored'|'template'|null, stripped: [...] }.
81
+ */
82
+ function prepareStarter(dir) {
83
+ const result = { gitignore: null, stripped: [] };
84
+ const gi = path.join(dir, '.gitignore');
85
+ if (!fs.existsSync(gi)) {
86
+ const src = GITIGNORE_SOURCES.map((n) => path.join(dir, n)).find((f) => fs.existsSync(f) && fs.statSync(f).isFile());
87
+ if (src) {
88
+ fs.renameSync(src, gi);
89
+ result.gitignore = 'restored';
90
+ }
91
+ }
92
+ for (const rel of STRIP) {
93
+ const abs = path.join(dir, ...rel.split('/'));
94
+ if (fs.existsSync(abs)) {
95
+ fs.rmSync(abs, { recursive: true, force: true });
96
+ result.stripped.push(rel);
97
+ }
98
+ }
99
+ // Lignes propres au modèle, déclarées dans package.json (poad.template.gitignore)
100
+ const pkg = readPackage(dir);
101
+ const lines = pkg && pkg.poad && pkg.poad.template && Array.isArray(pkg.poad.template.gitignore) ? pkg.poad.template.gitignore.filter((l) => typeof l === 'string' && l.trim()) : [];
102
+ if (lines.length) {
103
+ const label = (pkg.poad.template.framework || 'template').toString();
104
+ require('./git').ensureLines(dir, `Front-end (${label})`, lines);
105
+ result.gitignore = result.gitignore || 'template';
106
+ }
107
+ return result;
108
+ }
109
+
110
+ function readPackage(dir) {
111
+ try {
112
+ return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ const LOCKFILES = { bun: ['bun.lock', 'bun.lockb'], npm: ['package-lock.json', 'npm-shrinkwrap.json'], pnpm: ['pnpm-lock.yaml'], yarn: ['yarn.lock'] };
119
+
120
+ /**
121
+ * Gestionnaire de paquets choisi : les fichiers de verrouillage des autres
122
+ * gestionnaires sont retirés, et le champ packageManager s'il en désigne un
123
+ * autre (pnpm et corepack refusent d'installer sinon).
124
+ */
125
+ function adaptToPackageManager(dir, pm) {
126
+ const removed = [];
127
+ for (const [other, files] of Object.entries(LOCKFILES)) {
128
+ if (other === pm) continue;
129
+ for (const f of files) {
130
+ if (fs.existsSync(path.join(dir, f))) {
131
+ fs.rmSync(path.join(dir, f));
132
+ removed.push(f);
133
+ }
134
+ }
135
+ }
136
+ const pkg = readPackage(dir);
137
+ if (pkg && typeof pkg.packageManager === 'string' && !pkg.packageManager.startsWith(`${pm}@`)) {
138
+ delete pkg.packageManager;
139
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
140
+ removed.push('packageManager (package.json)');
141
+ }
142
+ return removed;
143
+ }
144
+
145
+ /** Premier port libre sur 127.0.0.1 à partir de start (4200 est souvent pris) */
146
+ async function freePort(start, max = start + 100) {
147
+ const net = require('net');
148
+ const free = (port) =>
149
+ new Promise((ok) => {
150
+ const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
151
+ s.listen(port, '127.0.0.1');
152
+ });
153
+ let port = start;
154
+ while (!(await free(port)) && port < max) port++;
155
+ return port;
156
+ }
157
+
158
+ // Frameworks reconnus : étiquette affichée, dépendance qui les trahit, port de
159
+ // développement par défaut quand le modèle n'en déclare pas (celui de l'outil).
160
+ const FRAMEWORKS = {
161
+ angular: { label: 'Angular', dependency: '@angular/core', port: 4300 },
162
+ next: { label: 'Next.js', dependency: 'next', port: 3000 },
163
+ nuxt: { label: 'Nuxt', dependency: 'nuxt', port: 3000 },
164
+ vanilla: { label: 'Vanilla', dependency: null, port: null },
165
+ };
166
+
167
+ /** Framework d'un package.json : poad.template.framework, sinon ses dépendances ; null si inconnu */
168
+ function frameworkOf(pkg = {}) {
169
+ const declared = pkg && pkg.poad && pkg.poad.template && pkg.poad.template.framework;
170
+ if (declared && FRAMEWORKS[String(declared).toLowerCase()]) return String(declared).toLowerCase();
171
+ const deps = { ...((pkg && pkg.devDependencies) || {}), ...((pkg && pkg.dependencies) || {}) };
172
+ for (const [name, fw] of Object.entries(FRAMEWORKS)) if (fw.dependency && deps[fw.dependency]) return name;
173
+ return null;
174
+ }
175
+
176
+ /** Port déclaré par le modèle : poad.port (gardé dans l'application), sinon poad.template.port */
177
+ function declaredPort(pkg = {}) {
178
+ const poad = (pkg && pkg.poad) || {};
179
+ return Number(poad.port) || Number(poad.template && poad.template.port) || null;
180
+ }
181
+
182
+ /**
183
+ * Serveur de développement du front, d'après le package.json du modèle (avant
184
+ * réécriture : poad.template y est encore) :
185
+ * - Angular : premier port libre à partir du port déclaré (4300 par défaut),
186
+ * écrit dans angular.json (ng serve) ;
187
+ * - les autres (Next.js…) lisent leur port eux-mêmes (poad.port, gardé dans
188
+ * l'application) et prennent le premier libre au démarrage : rien à écrire.
189
+ * Renvoie { framework, label, port, url } (port et url null si inconnus).
190
+ */
191
+ async function devServer(dir, pkg = {}) {
192
+ const framework = frameworkOf(pkg);
193
+ const fw = framework ? FRAMEWORKS[framework] : null;
194
+ let port = declaredPort(pkg) || (fw && fw.port) || null;
195
+ const ngFile = path.join(dir, 'angular.json');
196
+ if (fs.existsSync(ngFile)) {
197
+ port = await freePort(port || FRAMEWORKS.angular.port);
198
+ const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
199
+ for (const p of Object.values(ng.projects || {})) {
200
+ const serve = p.architect && p.architect.serve;
201
+ if (serve) serve.options = { ...(serve.options || {}), port };
202
+ }
203
+ fs.writeFileSync(ngFile, JSON.stringify(ng, null, 2) + '\n');
204
+ }
205
+ return { framework, label: fw ? fw.label : null, port, url: port ? `http://localhost:${port}` : null };
206
+ }
207
+
208
+ /** Ancienne forme (port seul, Angular seulement) : gardée pour les appels existants */
209
+ async function applyDevPort(dir, template = {}) {
210
+ if (!fs.existsSync(path.join(dir, 'angular.json'))) return null;
211
+ return (await devServer(dir, { poad: { template } })).port;
212
+ }
213
+
214
+ module.exports = { freePort, applyDevPort, devServer, frameworkOf, declaredPort, FRAMEWORKS, TEMPLATES, templateByValue, STRIP, PACKAGE_RULES, rewritePackageJson, packageName, prepareStarter, readPackage, adaptToPackageManager };