poad 2.20.0 → 2.22.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/package.json +2 -2
- package/project/cli.js +4 -0
- package/project/client/index.js +9 -0
- package/project/client/init.js +179 -0
- package/project/db/diff.js +13 -4
- package/utils/compact.js +118 -0
- package/utils/git.js +12 -1
- package/utils/migrations.js +9 -4
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
*/
|
|
9
9
|
module.exports = {
|
|
10
10
|
info: `Information about your project`,
|
|
11
|
+
client: {
|
|
12
|
+
description: 'Front-end of the project: client init creates it from a template (Angular; Vue and React soon), wired to poad with sign-in',
|
|
13
|
+
init: 'Create the front-end (angular | vue | react, dir=<folder>, from=<local template>, --yes)',
|
|
14
|
+
},
|
|
11
15
|
console: 'Open the administration console of the running project in the browser (engine 0.11.0+, no password, this machine only)',
|
|
12
16
|
kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
|
|
13
17
|
setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, kc=shared|own, --all, --none, --list)',
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// poad client : aide des commandes du front
|
|
2
|
+
module.exports = async () => {
|
|
3
|
+
const chalk = require('chalk-v2');
|
|
4
|
+
console.log(`${chalk.bold(' Usage :')}`);
|
|
5
|
+
console.log(' ');
|
|
6
|
+
console.log(` ${chalk.cyanBright('poad client init')} Create the front-end of the project (Angular; Vue and React soon), wired to poad with sign-in`);
|
|
7
|
+
console.log(` ${chalk.grey(' options: angular | vue | react, dir=<folder>, from=<local template>, --yes')}`);
|
|
8
|
+
console.log(' ');
|
|
9
|
+
};
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// poad client init [angular|vue|react] [dir=web] [from=<dossier ou .tgz>] [--yes]
|
|
2
|
+
//
|
|
3
|
+
// Crée le front du projet à partir d'un modèle (@poadio/starter-<framework>
|
|
4
|
+
// sur npm) : connexion, compte, cadre d'application, branché sur le projet
|
|
5
|
+
// poad (URL et clé lues dans poad/config.toml au démarrage, rien à écrire).
|
|
6
|
+
// - à la racine du projet, ou dans dir= (proposé si la racine a déjà un
|
|
7
|
+
// package.json) ;
|
|
8
|
+
// - port de développement libre à partir de 4300 ;
|
|
9
|
+
// - .gitignore complété, dépendances installées (bun, sinon npm).
|
|
10
|
+
// from= : un modèle local (dossier ou archive), pour le développer.
|
|
11
|
+
const FRAMEWORKS = [
|
|
12
|
+
{ value: 'angular', name: 'Angular (@cadriciel/ui)', package: '@poadio/starter-angular' },
|
|
13
|
+
{ value: 'vue', name: 'Vue.js (bientôt)', disabled: 'bientôt' },
|
|
14
|
+
{ value: 'react', name: 'React (bientôt)', disabled: 'bientôt' },
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
// Jamais copiés depuis un dossier modèle local
|
|
18
|
+
const SKIP = new Set(['node_modules', 'dist', '.angular', '.git', '.github', '.env.local', 'env.json', '.DS_Store', 'poad']);
|
|
19
|
+
|
|
20
|
+
module.exports = async (args = {}) => {
|
|
21
|
+
const chalk = require('chalk-v2');
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const os = require('os');
|
|
24
|
+
const path = require('path');
|
|
25
|
+
const { spawnSync } = require('child_process');
|
|
26
|
+
const { findPoadDir } = require('../../utils/findpoad');
|
|
27
|
+
const { readConfig } = require('../../utils/config');
|
|
28
|
+
|
|
29
|
+
const root = findPoadDir(process.cwd());
|
|
30
|
+
if (!root) {
|
|
31
|
+
process.exitCode = 1;
|
|
32
|
+
return console.log(chalk.redBright('No poad project here: "poad init" first (the backend), then "poad client init".'));
|
|
33
|
+
}
|
|
34
|
+
const config = readConfig(root);
|
|
35
|
+
const projectDir = path.dirname(path.dirname(root)); // dossier qui contient poad/
|
|
36
|
+
const flag = (f) => Boolean(args[f] || args[`--${f}`]);
|
|
37
|
+
const tty = process.stdin.isTTY && process.stdout.isTTY && !flag('yes');
|
|
38
|
+
const prompts = tty ? require('@inquirer/prompts') : null;
|
|
39
|
+
|
|
40
|
+
// 1. Framework
|
|
41
|
+
let fw = FRAMEWORKS.find((f) => args[f.value]);
|
|
42
|
+
if (!fw && prompts) {
|
|
43
|
+
const v = await prompts.select({ message: 'Front-end framework', choices: FRAMEWORKS }).catch(() => null);
|
|
44
|
+
fw = FRAMEWORKS.find((f) => f.value === v);
|
|
45
|
+
}
|
|
46
|
+
if (!fw) fw = FRAMEWORKS[0];
|
|
47
|
+
if (fw.disabled) {
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
return console.log(chalk.yellowBright(`${fw.value}: coming soon. Angular is available now.`));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 2. Dossier : la racine si elle est libre, sinon un sous-dossier
|
|
53
|
+
let dir = typeof args.dir === 'string' ? args.dir : null;
|
|
54
|
+
if (!dir) {
|
|
55
|
+
const rootTaken = fs.existsSync(path.join(projectDir, 'package.json'));
|
|
56
|
+
if (!rootTaken) dir = '.';
|
|
57
|
+
else if (prompts) dir = await prompts.input({ message: 'The project root already has a package.json. Folder for the front-end', default: 'web' }).catch(() => null);
|
|
58
|
+
else dir = 'web';
|
|
59
|
+
}
|
|
60
|
+
if (!dir) return;
|
|
61
|
+
const target = path.resolve(projectDir, dir);
|
|
62
|
+
if (fs.existsSync(path.join(target, 'package.json'))) {
|
|
63
|
+
process.exitCode = 1;
|
|
64
|
+
return console.log(chalk.redBright(`${path.relative(process.cwd(), path.join(target, 'package.json')) || 'package.json'} already exists: choose another folder (dir=<folder>).`));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 3. Modèle : dossier local, archive, ou npm
|
|
68
|
+
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-client-'));
|
|
69
|
+
const ora = require('ora');
|
|
70
|
+
let progress = ora(`Fetching the ${fw.value} template`).start();
|
|
71
|
+
let source;
|
|
72
|
+
try {
|
|
73
|
+
const from = typeof args.from === 'string' ? path.resolve(process.cwd(), args.from.replace(/^~(?=\/)/, os.homedir())) : null;
|
|
74
|
+
let tgz = null;
|
|
75
|
+
if (from && fs.statSync(from).isDirectory()) source = from;
|
|
76
|
+
else if (from) tgz = from;
|
|
77
|
+
else {
|
|
78
|
+
const r = spawnSync('npm', ['pack', `${fw.package}@latest`, '--pack-destination', work, '--json', '--silent'], { encoding: 'utf8', shell: process.platform === 'win32' });
|
|
79
|
+
if (r.status !== 0) throw new Error((r.stderr || r.stdout || 'npm pack failed').trim().split('\n').slice(-3).join(' '));
|
|
80
|
+
tgz = path.join(work, JSON.parse(r.stdout)[0].filename);
|
|
81
|
+
}
|
|
82
|
+
if (tgz) {
|
|
83
|
+
const x = spawnSync('tar', ['-xzf', tgz, '-C', work], { encoding: 'utf8' });
|
|
84
|
+
if (x.status !== 0) throw new Error(`tar: ${x.stderr.trim()}`);
|
|
85
|
+
source = path.join(work, 'package');
|
|
86
|
+
}
|
|
87
|
+
progress.succeed(`Template: ${chalk.bold(require(path.join(source, 'package.json')).name)} ${chalk.grey(require(path.join(source, 'package.json')).version)}`);
|
|
88
|
+
} catch (err) {
|
|
89
|
+
progress.fail(chalk.redBright(`Template unavailable: ${err.message}`));
|
|
90
|
+
process.exitCode = 1;
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 4. Copie (sans écraser un fichier existant)
|
|
95
|
+
const copy = (from, to) => {
|
|
96
|
+
for (const name of fs.readdirSync(from)) {
|
|
97
|
+
if (SKIP.has(name)) continue;
|
|
98
|
+
const a = path.join(from, name);
|
|
99
|
+
const b = path.join(to, name);
|
|
100
|
+
if (fs.statSync(a).isDirectory()) {
|
|
101
|
+
fs.mkdirSync(b, { recursive: true });
|
|
102
|
+
copy(a, b);
|
|
103
|
+
} else if (!fs.existsSync(b)) fs.copyFileSync(a, b);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
fs.mkdirSync(target, { recursive: true });
|
|
107
|
+
copy(source, target);
|
|
108
|
+
|
|
109
|
+
// 5. package.json de l'application : nom du projet, rien de la publication
|
|
110
|
+
const pkgFile = path.join(target, 'package.json');
|
|
111
|
+
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
|
|
112
|
+
const tpl = (pkg.poad && pkg.poad.template) || {};
|
|
113
|
+
const name = String(config.project_id || path.basename(projectDir))
|
|
114
|
+
.toLowerCase()
|
|
115
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
116
|
+
.replace(/^[-._]+|[-._]+$/g, '') || 'app';
|
|
117
|
+
pkg.name = dir === '.' ? name : `${name}-${path.basename(target)}`;
|
|
118
|
+
pkg.title = config.project_id || pkg.title;
|
|
119
|
+
// La description du paquet npm parle du modèle : l'application reprend la sienne
|
|
120
|
+
if (tpl.description) pkg.description = tpl.description;
|
|
121
|
+
pkg.version = '0.1.0';
|
|
122
|
+
pkg.private = true;
|
|
123
|
+
for (const k of ['files', 'repository', 'publishConfig', 'license']) delete pkg[k];
|
|
124
|
+
const origin = require(path.join(source, 'package.json'));
|
|
125
|
+
pkg.poad = { ...(pkg.poad || {}), from: `${origin.name}@${origin.version}` };
|
|
126
|
+
delete pkg.poad.template;
|
|
127
|
+
fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
|
|
128
|
+
|
|
129
|
+
// 6. Port de développement libre (4200 est souvent pris)
|
|
130
|
+
const net = require('net');
|
|
131
|
+
const free = (port) =>
|
|
132
|
+
new Promise((ok) => {
|
|
133
|
+
const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
|
|
134
|
+
s.listen(port, '127.0.0.1');
|
|
135
|
+
});
|
|
136
|
+
let port = Number(tpl.port) || 4300;
|
|
137
|
+
while (!(await free(port)) && port < 4400) port++;
|
|
138
|
+
const ngFile = path.join(target, 'angular.json');
|
|
139
|
+
if (fw.value === 'angular' && fs.existsSync(ngFile)) {
|
|
140
|
+
const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
|
|
141
|
+
for (const p of Object.values(ng.projects || {})) {
|
|
142
|
+
const serve = p.architect && p.architect.serve;
|
|
143
|
+
if (serve) serve.options = { ...(serve.options || {}), port };
|
|
144
|
+
}
|
|
145
|
+
fs.writeFileSync(ngFile, JSON.stringify(ng, null, 2) + '\n');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Titre de la page : le nom du projet
|
|
149
|
+
const html = path.join(target, 'src', 'index.html');
|
|
150
|
+
if (fs.existsSync(html)) fs.writeFileSync(html, fs.readFileSync(html, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${String(pkg.title).replace(/[<&]/g, '')}</title>`));
|
|
151
|
+
|
|
152
|
+
// 7. .gitignore : celui de poad init (racine), complété des fichiers du front
|
|
153
|
+
const git = require('../../utils/git');
|
|
154
|
+
git.ensureRootGitignore(projectDir);
|
|
155
|
+
if (Array.isArray(tpl.gitignore) && tpl.gitignore.length) {
|
|
156
|
+
const prefix = dir === '.' ? '' : `/${path.relative(projectDir, target).split(path.sep).join('/')}`;
|
|
157
|
+
const lines = tpl.gitignore.map((l) => (l.startsWith('/') ? `${prefix}${l}` : l));
|
|
158
|
+
git.ensureLines(projectDir, `Front-end (${fw.value})`, lines);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 8. Dépendances
|
|
162
|
+
const hasBun = spawnSync('bun', ['--version'], { encoding: 'utf8' }).status === 0;
|
|
163
|
+
const pm = hasBun ? 'bun' : 'npm';
|
|
164
|
+
progress = ora(`Installing the dependencies (${pm} install)`).start();
|
|
165
|
+
const inst = spawnSync(pm, ['install'], { cwd: target, encoding: 'utf8', shell: process.platform === 'win32' });
|
|
166
|
+
if (inst.status !== 0) progress.fail(chalk.yellowBright(`${pm} install failed: run it in ${path.relative(process.cwd(), target) || '.'}`));
|
|
167
|
+
else progress.succeed('Dependencies installed');
|
|
168
|
+
fs.rmSync(work, { recursive: true, force: true });
|
|
169
|
+
|
|
170
|
+
const rel = path.relative(process.cwd(), target) || '.';
|
|
171
|
+
const run = hasBun ? 'bun start' : 'npm start';
|
|
172
|
+
console.log(' ');
|
|
173
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(`${fw.value} front-end created`)} in ${chalk.cyanBright(rel)}`);
|
|
174
|
+
console.log(chalk.grey(' Sign-in (e-mail, magic link, providers), account and app layout, wired to this poad project.'));
|
|
175
|
+
console.log(' ');
|
|
176
|
+
console.log(` ${chalk.bold('poad start')}${chalk.grey(' the backend (if not running)')}`);
|
|
177
|
+
console.log(` ${chalk.bold(`${rel === '.' ? '' : `cd ${rel} && `}${run}`)}${chalk.grey(` http://localhost:${port}`)}`);
|
|
178
|
+
console.log(' ');
|
|
179
|
+
};
|
package/project/db/diff.js
CHANGED
|
@@ -44,16 +44,25 @@ module.exports = async (args = {}) => {
|
|
|
44
44
|
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) forgotten ${chalk.grey('(still in the database)')}.`);
|
|
45
45
|
}
|
|
46
46
|
if (!name) {
|
|
47
|
-
|
|
47
|
+
const byId = new Map(c.entries.map((e) => [e.id, e]));
|
|
48
|
+
console.log(chalk.bold(`${c.units.length} structure change(s) not in a migration`));
|
|
48
49
|
console.log(' ');
|
|
49
|
-
for (const
|
|
50
|
+
for (const u of c.units) {
|
|
51
|
+
const e = byId.get(u.keep.length ? u.keep[u.keep.length - 1] : u.ids[u.ids.length - 1]);
|
|
50
52
|
const when = new Date(e.at).toLocaleString();
|
|
51
|
-
|
|
52
|
-
console.log(
|
|
53
|
+
const group = u.effect === 'merged' ? chalk.cyanBright(` · ${u.ids.length} changes → ${u.result}`) : u.effect === 'none' ? chalk.yellowBright(` · ${u.ids.length} changes, no effect`) : '';
|
|
54
|
+
console.log(chalk.grey(`-- ${when} · ${e.role_name}${e.application ? ' · ' + e.application : ''} · ${(e.commands || []).join(', ')}`) + group);
|
|
55
|
+
if (u.effect === 'none') console.log(chalk.grey(`-- ${u.target}: nothing to write`));
|
|
56
|
+
for (const id of u.keep) console.log(String(byId.get(id).statement).trim().replace(/;?\s*$/, ';'));
|
|
53
57
|
console.log(' ');
|
|
54
58
|
}
|
|
55
59
|
return console.log(chalk.grey(' "poad db diff <name>" writes them to poad/migrations (not replayed); "poad db diff --discard" forgets them.'));
|
|
56
60
|
}
|
|
61
|
+
if (!c.sql.trim()) {
|
|
62
|
+
// Que des changements qui s'annulent : rien à écrire
|
|
63
|
+
await migrations.discardChanges(client, c.upTo);
|
|
64
|
+
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no net effect: nothing to write, journal cleared.`);
|
|
65
|
+
}
|
|
57
66
|
const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo);
|
|
58
67
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} ${chalk.grey(`(${c.entries.length} change(s), already applied here)`)}`);
|
|
59
68
|
console.log(chalk.grey(' Review it, then commit it with your branch.'));
|
package/utils/compact.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Copie de infra/services/meta/src/compact.ts (compilée en CommonJS) : garder
|
|
2
|
+
// les deux identiques, la console et poad db diff regroupent pareil.
|
|
3
|
+
"use strict";
|
|
4
|
+
// Regroupement des changements du journal avant d'en faire une migration.
|
|
5
|
+
//
|
|
6
|
+
// Pour les objets qui n'ont qu'un état (présent / absent, activé / désactivé),
|
|
7
|
+
// une suite de changements se résume à son effet net :
|
|
8
|
+
// extension activer, désactiver, activer -> le dernier create
|
|
9
|
+
// activer, désactiver -> sans effet
|
|
10
|
+
// RLS d'une table enable, disable, enable -> le dernier enable
|
|
11
|
+
// enable, disable -> sans effet
|
|
12
|
+
// politique, index create, alter, drop -> sans effet
|
|
13
|
+
// drop, create -> drop puis create (remplacement)
|
|
14
|
+
// create, alter -> gardés tels quels
|
|
15
|
+
// Tout le reste (tables, colonnes, fonctions, renommages…) est gardé tel quel,
|
|
16
|
+
// dans l'ordre : deviner y ferait perdre une intention ou des données.
|
|
17
|
+
//
|
|
18
|
+
// Un changement n'est regroupé que s'il ne touche qu'un objet, et un groupe
|
|
19
|
+
// n'est résumé que si rien ne s'intercale entre ses entrées (sauf des
|
|
20
|
+
// politiques ou du RLS, dont rien ne dépend) : activer vector, créer une table
|
|
21
|
+
// qui l'utilise, la supprimer, désactiver vector garde tout, sinon la table
|
|
22
|
+
// serait créée sans son extension. Les entrées
|
|
23
|
+
// écartées (superseded) restent dans le journal jusqu'à ce que la migration
|
|
24
|
+
// les emporte (ids) ; seules celles de keep écrivent du SQL.
|
|
25
|
+
//
|
|
26
|
+
// Même code dans le CLI (utils/compact.js) : poad db diff regroupe pareil.
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.compact = exports.classify = void 0;
|
|
29
|
+
const RLS_RE = /^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(.+?)\s+(enable|disable)\s+row\s+level\s+security\s*;?\s*$/is;
|
|
30
|
+
/** Objet unique et opération d'une entrée, ou null si elle n'est pas regroupable */
|
|
31
|
+
const classify = (e) => {
|
|
32
|
+
const objs = e.objects.filter((o) => Boolean(o));
|
|
33
|
+
if (e.commands.length !== 1 || objs.length !== 1)
|
|
34
|
+
return null;
|
|
35
|
+
const [cmd] = e.commands;
|
|
36
|
+
const target = objs[0];
|
|
37
|
+
const by = {
|
|
38
|
+
'CREATE EXTENSION': ['extension', 'on'],
|
|
39
|
+
'DROP EXTENSION': ['extension', 'off'],
|
|
40
|
+
'CREATE POLICY': ['policy', 'on'],
|
|
41
|
+
'ALTER POLICY': ['policy', 'alter'],
|
|
42
|
+
'DROP POLICY': ['policy', 'off'],
|
|
43
|
+
'CREATE INDEX': ['index', 'on'],
|
|
44
|
+
'DROP INDEX': ['index', 'off'],
|
|
45
|
+
};
|
|
46
|
+
if (by[cmd])
|
|
47
|
+
return { kind: by[cmd][0], target, op: by[cmd][1] };
|
|
48
|
+
if (cmd === 'ALTER TABLE') {
|
|
49
|
+
const m = RLS_RE.exec(e.statement);
|
|
50
|
+
if (m)
|
|
51
|
+
return { kind: 'rls', target, op: m[2].toLowerCase() === 'enable' ? 'on' : 'off' };
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
};
|
|
55
|
+
exports.classify = classify;
|
|
56
|
+
const RESULT = {
|
|
57
|
+
extension: ['activée', 'désactivée'],
|
|
58
|
+
rls: ['RLS activé', 'RLS désactivé'],
|
|
59
|
+
policy: ['créée', 'supprimée'],
|
|
60
|
+
index: ['créé', 'supprimé'],
|
|
61
|
+
};
|
|
62
|
+
/** Effet net d'une suite d'opérations sur un même objet */
|
|
63
|
+
const net = (kind, items) => {
|
|
64
|
+
const ops = items.map((i) => i.op);
|
|
65
|
+
const before = ops[0] === 'on' ? 'off' : 'on'; // create : l'objet n'existait pas
|
|
66
|
+
const after = ops.at(-1) === 'off' ? 'off' : 'on';
|
|
67
|
+
const lastOff = ops.lastIndexOf('off');
|
|
68
|
+
const lastOn = ops.lastIndexOf('on');
|
|
69
|
+
const stateOnly = kind === 'extension' || kind === 'rls';
|
|
70
|
+
let keep;
|
|
71
|
+
if (before === 'off' && after === 'off')
|
|
72
|
+
keep = [];
|
|
73
|
+
else if (before === 'off')
|
|
74
|
+
keep = items.slice(lastOn).map((i) => i.id); // le dernier create et ce qui le suit
|
|
75
|
+
else if (after === 'off')
|
|
76
|
+
keep = [items[lastOff].id]; // un seul drop
|
|
77
|
+
else if (lastOff < 0)
|
|
78
|
+
keep = items.map((i) => i.id); // que des alter
|
|
79
|
+
else if (stateOnly)
|
|
80
|
+
keep = []; // désactivé puis réactivé : comme avant
|
|
81
|
+
else
|
|
82
|
+
keep = items.slice(lastOff).map((i) => i.id); // remplacement : drop puis create
|
|
83
|
+
const effect = items.length === 1 ? 'one' : keep.length ? 'merged' : 'none';
|
|
84
|
+
return { keep, effect, result: effect === 'merged' ? RESULT[kind][after === 'on' ? 0 : 1] : null };
|
|
85
|
+
};
|
|
86
|
+
/** Unités à présenter, dans l'ordre du journal (position de leur dernière entrée gardée) */
|
|
87
|
+
const compact = (entries) => {
|
|
88
|
+
const groups = new Map();
|
|
89
|
+
const units = [];
|
|
90
|
+
for (const e of entries) {
|
|
91
|
+
const c = (0, exports.classify)(e);
|
|
92
|
+
if (!c) {
|
|
93
|
+
units.push({ ids: [e.id], keep: [e.id], kind: null, target: null, effect: 'one', result: null, at: e.id });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const key = `${c.kind}:${c.target}`;
|
|
97
|
+
const g = groups.get(key) ?? { kind: c.kind, target: c.target, items: [] };
|
|
98
|
+
g.items.push({ id: e.id, op: c.op });
|
|
99
|
+
groups.set(key, g);
|
|
100
|
+
}
|
|
101
|
+
const kindOf = new Map(entries.map((e) => [e.id, (0, exports.classify)(e)?.kind ?? null]));
|
|
102
|
+
for (const g of groups.values()) {
|
|
103
|
+
const ids = g.items.map((i) => i.id);
|
|
104
|
+
const mine = new Set(ids);
|
|
105
|
+
const between = entries.filter((e) => e.id > ids[0] && e.id < ids.at(-1) && !mine.has(e.id));
|
|
106
|
+
const free = between.every((e) => kindOf.get(e.id) === 'policy' || kindOf.get(e.id) === 'rls');
|
|
107
|
+
if (!free) {
|
|
108
|
+
// Des changements dépendent peut-être des états intermédiaires : tout est gardé
|
|
109
|
+
for (const id of ids)
|
|
110
|
+
units.push({ ids: [id], keep: [id], kind: g.kind, target: g.target, effect: 'one', result: null, at: id });
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const n = net(g.kind, g.items);
|
|
114
|
+
units.push({ ids, keep: n.keep, kind: g.kind, target: g.target, effect: n.effect, result: n.result, at: n.keep.at(-1) ?? ids.at(-1) });
|
|
115
|
+
}
|
|
116
|
+
return units.sort((a, b) => a.at - b.at).map(({ at: _at, ...u }) => u);
|
|
117
|
+
};
|
|
118
|
+
exports.compact = compact;
|
package/utils/git.js
CHANGED
|
@@ -70,4 +70,15 @@ function setupRepo(dir) {
|
|
|
70
70
|
return { gitignore, repo: 'created', root: dir };
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
/** Ajoute au .gitignore du dossier les lignes qui lui manquent, sous un titre */
|
|
74
|
+
function ensureLines(dir, title, lines) {
|
|
75
|
+
const file = path.join(dir, '.gitignore');
|
|
76
|
+
const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
77
|
+
const have = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
|
|
78
|
+
const missing = lines.filter((l) => !have.has(l));
|
|
79
|
+
if (!missing.length) return 0;
|
|
80
|
+
fs.writeFileSync(file, (existing ? existing.replace(/\s*$/, '\n') : '') + `\n# ${title}\n${missing.join('\n')}\n`);
|
|
81
|
+
return missing.length;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { version, repoRoot, ensureRootGitignore, ensureLines, setupRepo, BLOCKS };
|
package/utils/migrations.js
CHANGED
|
@@ -233,17 +233,22 @@ async function snapshot(client) {
|
|
|
233
233
|
if (await hasJournal(client)) await client.query('select poad_migrations.snapshot()');
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
/** Changements non enregistrés : { supported, entries, upTo, drift, sql } */
|
|
236
|
+
/** Changements non enregistrés : { supported, entries, units, upTo, drift, sql } (sql : regroupé) */
|
|
237
237
|
async function changes(client) {
|
|
238
238
|
if (!(await hasJournal(client))) return { supported: false, entries: [], upTo: null, drift: false, sql: '' };
|
|
239
239
|
const { rows } = await client.query('select id, at, statement, commands, objects, role_name, application from poad_migrations.journal order by id');
|
|
240
240
|
const st = (await client.query('select poad_migrations.status() as s')).rows[0].s || {};
|
|
241
|
+
// Effet net par objet (extension activée puis désactivée…) : utils/compact.js
|
|
242
|
+
const entries = rows.map((r) => ({ ...r, id: Number(r.id) }));
|
|
243
|
+
const units = require('./compact').compact(entries);
|
|
244
|
+
const kept = new Set(units.flatMap((u) => u.keep));
|
|
241
245
|
return {
|
|
242
246
|
supported: true,
|
|
243
|
-
entries
|
|
244
|
-
|
|
247
|
+
entries,
|
|
248
|
+
units,
|
|
249
|
+
upTo: entries.length ? entries[entries.length - 1].id : null,
|
|
245
250
|
drift: Boolean(st.drift) && rows.length === 0,
|
|
246
|
-
sql:
|
|
251
|
+
sql: entries.filter((r) => kept.has(r.id)).map((r) => String(r.statement).trim().replace(/;?\s*$/, ';')).join('\n\n'),
|
|
247
252
|
};
|
|
248
253
|
}
|
|
249
254
|
|