poad 2.63.0 → 2.64.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/global/start.js +7 -0
- package/package.json +2 -2
- package/poad.js +2 -2
- package/project/auth/import.js +68 -0
- package/project/auth/index.js +7 -0
- package/project/cli.js +6 -1
- package/project/db/import.js +138 -0
- package/project/db/index.js +1 -0
- package/project/deploy.js +4 -0
- package/project/logs.js +2 -0
- package/project/source.js +199 -41
- package/project/storage/cp.js +4 -2
- package/test/auth-import.test.js +113 -0
- package/test/cloud.test.js +1 -0
- package/test/data.test.js +24 -0
- package/test/deps.test.js +108 -0
- package/test/import.test.js +210 -0
- package/test/logs.test.js +12 -0
- package/test/naming.test.js +18 -0
- package/test/source.test.js +37 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +7 -0
- package/utils/auth-import.js +204 -0
- package/utils/cloud/bundle.js +16 -2
- package/utils/cloud/deps.js +297 -0
- package/utils/data.js +41 -0
- package/utils/help-details.js +53 -4
- package/utils/import-upload.js +112 -0
- package/utils/logline.js +2 -2
- package/utils/logs.js +8 -1
- package/utils/naming.js +41 -0
- package/utils/runner.js +1 -1
- package/utils/storage-copy.js +31 -3
- package/utils/storage-tus.js +201 -0
- package/utils/storage.js +37 -1
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// Dépendances npm des fonctions, pour poad deploy : seuls les fichiers de
|
|
2
|
+
// poad/functions/node_modules que les fonctions atteignent réellement par leurs
|
|
3
|
+
// imports, plus le package.json de chaque paquet atteint (réduit aux champs de la
|
|
4
|
+
// résolution) et les fichiers des règles de modules (.wasm, .bin, .txt, .html, .sql).
|
|
5
|
+
//
|
|
6
|
+
// Même résolution que le service functions de l'engine (services/functions/src/resolve.ts),
|
|
7
|
+
// elle-même alignée sur wrangler pour un Worker de Cloudflare : conditions d'export
|
|
8
|
+
// workerd, worker, browser, puis import / require / default ; champs browser, module,
|
|
9
|
+
// main ; sous-chemins et motifs ; imports « # » du paquet. Les imports sont relevés dans le
|
|
10
|
+
// texte (import, export … from, import(), require()) : un import trouvé dans un commentaire
|
|
11
|
+
// ajoute au pire un fichier de trop, jamais un de moins. Un paquet installé plus haut que
|
|
12
|
+
// poad/functions/node_modules n'est pas envoyé (signalé).
|
|
13
|
+
//
|
|
14
|
+
// traceDependencies('<projet>/poad/functions')
|
|
15
|
+
// → { files: [{ rel, abs, data? }], packages: ['jpeg-js', …], missing: [{ spec, from }], outside: [...] }
|
|
16
|
+
// rel : chemin relatif à poad/functions (« node_modules/jpeg-js/index.js »)
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const path = require('path');
|
|
19
|
+
const { builtinModules } = require('module');
|
|
20
|
+
|
|
21
|
+
const SOURCE_EXT = ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.jsx'];
|
|
22
|
+
const PROBE_EXT = ['.js', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts', '.jsx', '.json'];
|
|
23
|
+
// Règles de modules de Cloudflare (WebAssembly, données, texte) : envoyés, pas lus
|
|
24
|
+
const MODULE_RULE = /\.(wasm|bin|txt|html|sql)(\?module)?$/;
|
|
25
|
+
// Ce qu'un paquet peut contenir d'utile ici (jamais d'exécutable ni de binaire natif)
|
|
26
|
+
const SENT_EXT = /\.(js|mjs|cjs|jsx|ts|tsx|mts|cts|json|wasm|bin|txt|html|sql)$/;
|
|
27
|
+
const NODE = new Set(builtinModules.filter((m) => !m.startsWith('_')));
|
|
28
|
+
const PKG_FIELDS = ['name', 'version', 'type', 'main', 'module', 'browser', 'exports', 'imports', 'sideEffects'];
|
|
29
|
+
const IMPORT_CONDITIONS = ['workerd', 'worker', 'browser', 'import', 'module', 'default'];
|
|
30
|
+
const REQUIRE_CONDITIONS = ['workerd', 'worker', 'browser', 'require', 'default'];
|
|
31
|
+
// Jeux de conditions essayés : celui de l'engine (import ou require), et sans « module » au cas
|
|
32
|
+
// où l'assembleur ne le connaît pas ; un fichier de trop plutôt qu'un de moins
|
|
33
|
+
const CONDITION_SETS = [IMPORT_CONDITIONS, REQUIRE_CONDITIONS, IMPORT_CONDITIONS.filter((c) => c !== 'module')];
|
|
34
|
+
const targetsAll = (map, sub) => new Set(CONDITION_SETS.flatMap((c) => targetsOf(map, sub, c)));
|
|
35
|
+
|
|
36
|
+
/** Imports d'un texte source : [{ spec, kind: 'import' | 'require' }] */
|
|
37
|
+
function importsOf(text) {
|
|
38
|
+
const out = [];
|
|
39
|
+
const add = (spec, kind) => spec && out.push({ spec, kind });
|
|
40
|
+
const res = [
|
|
41
|
+
[/\b(?:import|export)\s+(?:type\s+)?(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g, 'import'],
|
|
42
|
+
[/\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g, 'import'],
|
|
43
|
+
[/\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g, 'require'],
|
|
44
|
+
];
|
|
45
|
+
for (const [re, kind] of res) for (const m of text.matchAll(re)) add(m[1], kind);
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const isFile = (p) => {
|
|
50
|
+
try {
|
|
51
|
+
return fs.statSync(p).isFile();
|
|
52
|
+
} catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const isDir = (p) => {
|
|
57
|
+
try {
|
|
58
|
+
return fs.statSync(p).isDirectory();
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const readJson = (p) => {
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Nom du paquet d'un import nu ; null pour un chemin ou un protocole */
|
|
72
|
+
function packageName(spec) {
|
|
73
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('#') || /^[a-z][a-z0-9+.-]*:/i.test(spec)) return null;
|
|
74
|
+
const parts = spec.split('/');
|
|
75
|
+
if (spec.startsWith('@')) return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null;
|
|
76
|
+
return parts[0];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Cible d'un champ exports / imports pour un sous-chemin et des conditions ; toutes les cibles possibles */
|
|
80
|
+
function targetsOf(map, sub, conditions) {
|
|
81
|
+
const pick = (t, star) => {
|
|
82
|
+
if (typeof t === 'string') return [star === undefined ? t : t.split('*').join(star)];
|
|
83
|
+
if (Array.isArray(t)) {
|
|
84
|
+
for (const x of t) {
|
|
85
|
+
const r = pick(x, star);
|
|
86
|
+
if (r.length) return r;
|
|
87
|
+
}
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
if (t && typeof t === 'object') {
|
|
91
|
+
for (const [k, v] of Object.entries(t)) if (conditions.includes(k)) {
|
|
92
|
+
const r = pick(v, star);
|
|
93
|
+
if (r.length) return r;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return [];
|
|
97
|
+
};
|
|
98
|
+
// exports : une chaîne, un tableau, ou un objet de conditions, valent pour « . »
|
|
99
|
+
if (typeof map === 'string' || Array.isArray(map)) return sub === '.' ? pick(map) : [];
|
|
100
|
+
if (!map || typeof map !== 'object') return [];
|
|
101
|
+
const keys = Object.keys(map);
|
|
102
|
+
if (keys.length && !keys.some((k) => k.startsWith('.') || k.startsWith('#'))) return sub === '.' ? pick(map) : [];
|
|
103
|
+
if (Object.prototype.hasOwnProperty.call(map, sub)) return pick(map[sub]);
|
|
104
|
+
// Motifs « ./x/* » : le préfixe le plus long l'emporte
|
|
105
|
+
let best = null;
|
|
106
|
+
for (const k of keys) {
|
|
107
|
+
const i = k.indexOf('*');
|
|
108
|
+
if (i < 0) continue;
|
|
109
|
+
const pre = k.slice(0, i);
|
|
110
|
+
const post = k.slice(i + 1);
|
|
111
|
+
if (sub.startsWith(pre) && sub.endsWith(post) && sub.length >= pre.length + post.length && (!best || pre.length > best.pre.length)) best = { k, pre, star: sub.slice(pre.length, sub.length - post.length) };
|
|
112
|
+
}
|
|
113
|
+
if (best) return pick(map[best.k], best.star);
|
|
114
|
+
// Ancienne forme « ./dossier/ »
|
|
115
|
+
for (const k of keys) if (k.endsWith('/') && sub.startsWith(k) && typeof map[k] === 'string') return [map[k] + sub.slice(k.length)];
|
|
116
|
+
return [];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Trace les dépendances des fonctions de functionsDir. N'envoie que ce qui est sous
|
|
121
|
+
* functionsDir/node_modules.
|
|
122
|
+
*/
|
|
123
|
+
function traceDependencies(functionsDir) {
|
|
124
|
+
const root = path.resolve(functionsDir);
|
|
125
|
+
const nm = path.join(root, 'node_modules');
|
|
126
|
+
const result = { files: [], packages: [], missing: [], outside: [] };
|
|
127
|
+
if (!isDir(root)) return result;
|
|
128
|
+
const inNm = (p) => p === nm || p.startsWith(nm + path.sep);
|
|
129
|
+
const sent = new Map();
|
|
130
|
+
const pkgs = new Map();
|
|
131
|
+
const seen = new Set();
|
|
132
|
+
const queue = [];
|
|
133
|
+
|
|
134
|
+
const send = (abs) => {
|
|
135
|
+
if (!inNm(abs) || sent.has(abs)) return;
|
|
136
|
+
const rel = path.relative(root, abs).split(path.sep).join('/');
|
|
137
|
+
if (!SENT_EXT.test(rel) || rel.split('/').some((s) => s.startsWith('.'))) return;
|
|
138
|
+
sent.set(abs, { rel, abs });
|
|
139
|
+
};
|
|
140
|
+
// package.json d'un paquet atteint, réduit aux champs de la résolution
|
|
141
|
+
const sendPkg = (dir) => {
|
|
142
|
+
const file = path.join(dir, 'package.json');
|
|
143
|
+
if (!inNm(dir) || sent.has(file)) return;
|
|
144
|
+
const pkg = readJson(file);
|
|
145
|
+
if (!pkg) return;
|
|
146
|
+
const slim = {};
|
|
147
|
+
for (const k of PKG_FIELDS) if (pkg[k] !== undefined) slim[k] = pkg[k];
|
|
148
|
+
sent.set(file, { rel: path.relative(root, file).split(path.sep).join('/'), abs: file, data: Buffer.from(JSON.stringify(slim, null, 2) + '\n') });
|
|
149
|
+
if (pkg.name && !pkgs.has(pkg.name)) pkgs.set(pkg.name, dir);
|
|
150
|
+
// Champ browser en objet : ses remplacements peuvent être atteints
|
|
151
|
+
if (pkg.browser && typeof pkg.browser === 'object') {
|
|
152
|
+
for (const v of Object.values(pkg.browser)) {
|
|
153
|
+
if (typeof v !== 'string') continue;
|
|
154
|
+
if (v.startsWith('.')) visitPath(path.join(dir, v), 'import');
|
|
155
|
+
else visitBare(v, dir, 'import', dir);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
const visit = (abs, kind) => {
|
|
160
|
+
if (seen.has(abs)) return;
|
|
161
|
+
seen.add(abs);
|
|
162
|
+
send(abs);
|
|
163
|
+
if (MODULE_RULE.test(abs) || abs.endsWith('.json')) return;
|
|
164
|
+
if (SOURCE_EXT.includes(path.extname(abs))) queue.push({ abs, kind });
|
|
165
|
+
};
|
|
166
|
+
/** Fichier (ou dossier) désigné par un chemin : mêmes essais qu'un assembleur */
|
|
167
|
+
const fileOf = (p) => {
|
|
168
|
+
if (isFile(p)) return p;
|
|
169
|
+
for (const e of PROBE_EXT) if (isFile(p + e)) return p + e;
|
|
170
|
+
// Source TypeScript importée en « .js »
|
|
171
|
+
if (/\.[mc]?js$/.test(p)) for (const e of ['.ts', '.tsx', '.mts', '.cts']) if (isFile(p.replace(/\.[mc]?js$/, e))) return p.replace(/\.[mc]?js$/, e);
|
|
172
|
+
if (isDir(p)) {
|
|
173
|
+
const pkg = readJson(path.join(p, 'package.json'));
|
|
174
|
+
if (pkg) {
|
|
175
|
+
sendPkg(p);
|
|
176
|
+
for (const f of [typeof pkg.browser === 'string' ? pkg.browser : null, pkg.module, pkg.main].filter((x) => typeof x === 'string')) {
|
|
177
|
+
const hit = fileOf(path.join(p, f));
|
|
178
|
+
if (hit) return hit;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
for (const e of PROBE_EXT) if (isFile(path.join(p, 'index' + e))) return path.join(p, 'index' + e);
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
};
|
|
185
|
+
const visitPath = (p, kind) => {
|
|
186
|
+
const f = fileOf(p.replace(/\?module$/, ''));
|
|
187
|
+
if (f) visit(f, kind);
|
|
188
|
+
return f;
|
|
189
|
+
};
|
|
190
|
+
/** Dossier du paquet name, vu depuis from (node_modules de from et de ses parents, jusqu'à poad/functions) */
|
|
191
|
+
const packageDir = (name, from) => {
|
|
192
|
+
for (let d = from; ; d = path.dirname(d)) {
|
|
193
|
+
const cand = path.join(d, 'node_modules', name);
|
|
194
|
+
if (isDir(cand)) return cand;
|
|
195
|
+
if (d === root || path.dirname(d) === d || !d.startsWith(root)) break;
|
|
196
|
+
}
|
|
197
|
+
// Plus haut que poad/functions : trouvé mais pas envoyé
|
|
198
|
+
for (let d = path.dirname(root); path.dirname(d) !== d; d = path.dirname(d)) if (isDir(path.join(d, 'node_modules', name))) return { outside: path.join(d, 'node_modules', name) };
|
|
199
|
+
return null;
|
|
200
|
+
};
|
|
201
|
+
const entriesOf = (dir, sub, kind) => {
|
|
202
|
+
const pkg = readJson(path.join(dir, 'package.json')) || {};
|
|
203
|
+
sendPkg(dir);
|
|
204
|
+
const hits = [];
|
|
205
|
+
if (pkg.exports !== undefined) {
|
|
206
|
+
// Les deux jeux de conditions : un paquet importé puis requis ailleurs garde ses deux formes
|
|
207
|
+
const targets = targetsAll(pkg.exports, sub);
|
|
208
|
+
for (const t of targets) if (typeof t === 'string' && t.startsWith('./')) hits.push(path.join(dir, t));
|
|
209
|
+
if (hits.length) return hits;
|
|
210
|
+
}
|
|
211
|
+
if (sub !== '.') return [path.join(dir, sub)];
|
|
212
|
+
// Sans exports : tous les champs d'entrée présents (un de trop vaut mieux qu'un de moins)
|
|
213
|
+
for (const f of [typeof pkg.browser === 'string' ? pkg.browser : null, pkg.module, pkg.main]) if (typeof f === 'string') hits.push(path.join(dir, f));
|
|
214
|
+
if (!hits.length) hits.push(path.join(dir, 'index'));
|
|
215
|
+
return hits;
|
|
216
|
+
};
|
|
217
|
+
const visitBare = (spec, fromDir, kind, importer) => {
|
|
218
|
+
const name = packageName(spec);
|
|
219
|
+
if (!name) return true;
|
|
220
|
+
const dir = packageDir(name, fromDir);
|
|
221
|
+
if (!dir) return false;
|
|
222
|
+
if (dir.outside) {
|
|
223
|
+
if (!result.outside.includes(name)) result.outside.push(name);
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
const sub = spec === name ? '.' : `./${spec.slice(name.length + 1)}`;
|
|
227
|
+
for (const t of entriesOf(dir, sub, kind)) visitPath(t, kind);
|
|
228
|
+
return true;
|
|
229
|
+
};
|
|
230
|
+
/** Import « #x » : champ imports du package.json le plus proche */
|
|
231
|
+
const visitHash = (spec, fromDir, kind) => {
|
|
232
|
+
for (let d = fromDir; d.startsWith(root); d = path.dirname(d)) {
|
|
233
|
+
const pkg = readJson(path.join(d, 'package.json'));
|
|
234
|
+
if (!pkg) continue;
|
|
235
|
+
sendPkg(d);
|
|
236
|
+
for (const t of targetsAll(pkg.imports, spec)) {
|
|
237
|
+
if (typeof t !== 'string') continue;
|
|
238
|
+
if (t.startsWith('./')) visitPath(path.join(d, t), kind);
|
|
239
|
+
else visitBare(t, d, kind, d);
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// Les sources des fonctions (hors node_modules et dossiers cachés)
|
|
246
|
+
const walk = (d) => {
|
|
247
|
+
let entries = [];
|
|
248
|
+
try {
|
|
249
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
250
|
+
} catch {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
254
|
+
if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
|
|
255
|
+
const p = path.join(d, e.name);
|
|
256
|
+
if (e.isDirectory()) walk(p);
|
|
257
|
+
else if (e.isFile() && SOURCE_EXT.includes(path.extname(e.name))) queue.push({ abs: p, kind: 'import', own: true });
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
walk(root);
|
|
261
|
+
|
|
262
|
+
while (queue.length) {
|
|
263
|
+
const { abs, own } = queue.shift();
|
|
264
|
+
let text;
|
|
265
|
+
try {
|
|
266
|
+
text = fs.readFileSync(abs, 'utf8');
|
|
267
|
+
} catch {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const from = path.dirname(abs);
|
|
271
|
+
for (const { spec, kind } of importsOf(text)) {
|
|
272
|
+
const clean = spec.replace(/\?module$/, '');
|
|
273
|
+
if (clean === '@poadio/functions' || /^(node|cloudflare|data|https?):/.test(clean)) continue;
|
|
274
|
+
if (clean.startsWith('./') || clean.startsWith('../') || clean === '.' || clean === '..') {
|
|
275
|
+
visitPath(path.resolve(from, clean), kind);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (clean.startsWith('#')) {
|
|
279
|
+
visitHash(clean, from, kind);
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const name = packageName(clean);
|
|
283
|
+
if (!name) continue;
|
|
284
|
+
const ok = visitBare(clean, from, kind, abs);
|
|
285
|
+
// Module de Node.js sans paquet de ce nom : fourni par le moteur (nodejs_compat)
|
|
286
|
+
if (!ok && !NODE.has(clean) && !NODE.has(name) && own) {
|
|
287
|
+
const rel = path.relative(root, abs).split(path.sep).join('/');
|
|
288
|
+
if (!result.missing.some((m) => m.spec === name)) result.missing.push({ spec: name, from: rel });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
result.files = [...sent.values()].sort((a, b) => (a.rel < b.rel ? -1 : 1));
|
|
293
|
+
result.packages = [...pkgs.keys()].sort();
|
|
294
|
+
return result;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
module.exports = { traceDependencies, importsOf, targetsOf, packageName };
|
package/utils/data.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Service data de l'engine (/rest/v1) : réglages de poad/config.toml passés en
|
|
2
|
+
// variables d'environnement par `poad start`.
|
|
3
|
+
//
|
|
4
|
+
// [data]
|
|
5
|
+
// service_role_statement_timeout = 120 délai d'une requête de service_role (fonction
|
|
6
|
+
// avec poadAdmin, flow, script) : secondes, ou
|
|
7
|
+
// "500ms", "30s", "2min", "1h" ; 0 = sans limite
|
|
8
|
+
//
|
|
9
|
+
// anon (3 s) et authenticated (8 s) ne se règlent pas ici. La passerelle de l'engine attend la
|
|
10
|
+
// réponse de data et functions aussi longtemps pour une requête portant la clé service_role
|
|
11
|
+
// (POAD_GATEWAY_SERVICE_ROLE_TIMEOUT : 15 min au plus, 0 = ce plafond), 60 s pour les autres. Engine avec data 0.11.0 et
|
|
12
|
+
// plus (POAD_DATA_STATEMENT_TIMEOUT_SERVICE_ROLE) ; un engine plus ancien ignore la
|
|
13
|
+
// variable et coupe toutes les requêtes à 8 s.
|
|
14
|
+
|
|
15
|
+
const DURATION = /^(\d+)(ms|s|min|h)?$/;
|
|
16
|
+
const UNIT_MS = { ms: 1, s: 1000, min: 60000, h: 3600000 };
|
|
17
|
+
const MAX_MS = 24 * 3600000;
|
|
18
|
+
|
|
19
|
+
/** Délai normalisé (« 120s », « 500ms », « 0 ») ; { value: null } sans réglage ; warning si refusé */
|
|
20
|
+
const serviceRoleTimeout = (config) => {
|
|
21
|
+
const raw = config && config.data ? config.data.service_role_statement_timeout : undefined;
|
|
22
|
+
if (raw === undefined || raw === null || raw === '') return { value: null };
|
|
23
|
+
const text = String(raw).trim().toLowerCase();
|
|
24
|
+
const m = DURATION.exec(text);
|
|
25
|
+
const ms = m ? Number(m[1]) * UNIT_MS[m[2] || 's'] : NaN;
|
|
26
|
+
if (m && Number.isSafeInteger(ms) && ms <= MAX_MS) return { value: `${m[1]}${m[2] || 's'}` };
|
|
27
|
+
return {
|
|
28
|
+
value: null,
|
|
29
|
+
warning: `[data] service_role_statement_timeout = "${String(raw).slice(0, 32)}" in poad/config.toml is not a duration (examples: 120, "30s", "2min"; 0 = no limit; 24 h at most): the engine default (120 s) is used.`,
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Variables de l'engine */
|
|
34
|
+
const engineEnv = (config) => {
|
|
35
|
+
const t = serviceRoleTimeout(config);
|
|
36
|
+
// La passerelle attend la réponse aussi longtemps pour une requête portant la clé service_role
|
|
37
|
+
// (vers data et functions ; 15 min au plus, 0 = ce plafond ; jamais moins de 60 s)
|
|
38
|
+
return t.value === null ? [] : [`POAD_DATA_STATEMENT_TIMEOUT_SERVICE_ROLE=${t.value}`, `POAD_GATEWAY_SERVICE_ROLE_TIMEOUT=${t.value}`];
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
module.exports = { serviceRoleTimeout, engineEnv };
|
package/utils/help-details.js
CHANGED
|
@@ -36,6 +36,8 @@ const sheets = {
|
|
|
36
36
|
'Secrets are hidden in the state shown at the end: poad info --secrets shows them.',
|
|
37
37
|
'A port of poad/config.toml already used on this machine is replaced by a free one.',
|
|
38
38
|
'Request bodies are limited by the gateway to [gateway] max_body of poad/config.toml (default "10m", storage uploads excepted).',
|
|
39
|
+
'Storage files are limited to [storage] file_size_limit of poad/config.toml (default 50 MiB; "200MB", "1GB"…, storage 0.6+), the ceiling of every bucket limit.',
|
|
40
|
+
'Requests of service_role (poadAdmin in a function, flows, scripts) stop after [data] service_role_statement_timeout of poad/config.toml (seconds, or "30s", "2min"; default 120 s, 0 = no limit, the gateway then waits 15 min at most); anon after 3 s, authenticated after 8 s.',
|
|
39
41
|
],
|
|
40
42
|
},
|
|
41
43
|
stop: {
|
|
@@ -115,6 +117,8 @@ const sheets = {
|
|
|
115
117
|
['table=<table>', 'lines about a table: realtime subscriptions and changes delivered (engine 0.32+), data errors'],
|
|
116
118
|
['channel=<name>', 'a realtime channel (engine 0.32+): joins, leaves, subscriptions, deliveries'],
|
|
117
119
|
['source=<name>', 'a source of poad/sources (engine 0.64+): each synchronisation (received, added, updated, removed) and its failures'],
|
|
120
|
+
['upload=<id>', 'a chunked storage upload (storage 0.6+): started, interrupted, resumed, finished, cancelled or abandoned'],
|
|
121
|
+
['bucket=<id>', 'the lines about a storage bucket: uploads, upload rules'],
|
|
118
122
|
['limit=100', 'number of lines, from 1 to 10000'],
|
|
119
123
|
['-f, --follow', 'follow live'],
|
|
120
124
|
['--json', 'one JSON line per entry (for jq)'],
|
|
@@ -122,9 +126,23 @@ const sheets = {
|
|
|
122
126
|
notes: [
|
|
123
127
|
'Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f',
|
|
124
128
|
'A source and its synchronisations: poad logs source=communes level=warn',
|
|
129
|
+
'Chunked uploads of a bucket: poad logs storage bucket=documents grep="envoi en morceaux"',
|
|
125
130
|
'A filter without a value (level=, request) or out of range (limit=0) is refused before anything is read, exit code 1. A log store that does not answer (engine starting or stopping, Docker stopped) is said in one sentence; POAD_DEBUG=1 shows the details of an unexpected error.',
|
|
126
131
|
],
|
|
127
132
|
},
|
|
133
|
+
'db import': {
|
|
134
|
+
usage: ['poad db import <file.sql> [--yes] [--json]', 'poad db import <file.sql> --env <name> [--project <id>]'],
|
|
135
|
+
text: [
|
|
136
|
+
'Run an SQL file (plain pg_dump accepted, COPY … FROM stdin included; .sql.gz too) in the database of the project, in ONE transaction: all or nothing. The file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads it streamed (any size) and gives a preview first: statements, tables touched, rows by COPY, structure.',
|
|
137
|
+
'Refused before anything runs, with the line: roles (CREATE/ALTER/DROP ROLE, SET ROLE, GRANT of a role, OWNER TO another role than postgres), system schemas (auth, storage, _poad, extensions…), DROP/CREATE DATABASE, COPY … PROGRAM and server files, ALTER SYSTEM, LOAD, unsafe languages, extensions outside the allowed list, psql commands (\\connect, \\!…). BEGIN/COMMIT of the file are ignored.',
|
|
138
|
+
],
|
|
139
|
+
options: [
|
|
140
|
+
['--yes', 'no question (required outside a terminal)'],
|
|
141
|
+
['--json', 'the preview and the result as JSON'],
|
|
142
|
+
['--env <name>', 'an environment of the linked poad.io project'],
|
|
143
|
+
],
|
|
144
|
+
notes: ['Structure created by the file lands in the change journal: "poad db diff <name>" writes it as a migration. Logs: poad logs meta event=sql_import (never a value of the file).'],
|
|
145
|
+
},
|
|
128
146
|
'db diff': {
|
|
129
147
|
usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
|
|
130
148
|
text: [
|
|
@@ -138,6 +156,32 @@ const sheets = {
|
|
|
138
156
|
['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
|
|
139
157
|
],
|
|
140
158
|
},
|
|
159
|
+
auth: {
|
|
160
|
+
usage: ['poad auth import <file> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>]'],
|
|
161
|
+
text: ['Accounts of the project auth service. auth import: accounts of another system (email, bcrypt password_hash, metadata, original date), skipped when the address already exists; see poad auth import --help.'],
|
|
162
|
+
},
|
|
163
|
+
'auth import': {
|
|
164
|
+
usage: ['poad auth import <file> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>] [--project <id>] [--yes] [--json]'],
|
|
165
|
+
text: [
|
|
166
|
+
'Accounts of another system into the auth service of the project, local engine (poad start) or poad.io (--env). One account per line: email (required), password_hash (bcrypt $2a$/$2b$/$2y$, cost 4 to 15; people then sign in with their old password), user_metadata and app_metadata (JSON objects), created_at (original date, ISO 8601), email_verified, id (optional: keep the original UUID).',
|
|
167
|
+
'File: .json (a list, or { "users": [...] }), .jsonl, or .csv with a header line (comma or semicolon; metadata columns hold JSON text).',
|
|
168
|
+
],
|
|
169
|
+
options: [
|
|
170
|
+
['--dry-run', 'what would be created, what already exists, the invalid lines; nothing is written'],
|
|
171
|
+
['--trust-verified', 'keep the email_verified column of the file (true: verified, false or missing: unverified); without it every address is unverified; only if the former system really proved them'],
|
|
172
|
+
['--send-confirmation', 'send a confirmation e-mail to each account created without a verified address (it keeps its imported password)'],
|
|
173
|
+
['--env <name>', 'a poad.io environment of the linked project (main: production) instead of the local engine; asks first (--yes)'],
|
|
174
|
+
['--project <id>', 'another poad.io project (poad login); with --env for one of its environments'],
|
|
175
|
+
['--yes', 'no question (required outside a terminal for poad.io)'],
|
|
176
|
+
['--json', 'the summary and one result per line as JSON'],
|
|
177
|
+
],
|
|
178
|
+
notes: [
|
|
179
|
+
'An account whose address already exists is skipped and reported, never overwritten: running the same import again resumes it without duplicates. Lines are sent in batches of 500.',
|
|
180
|
+
'Addresses are unverified, whatever the file says: with --trust-verified only, a line with email_verified: true is imported verified, marked "verified by import" (email_verified_by in the identity, user_imported in the audit); without it such lines are reported. An external provider (Keycloak…) is linked automatically to an account of the same address only when both sides verified it. An imported password is marked as set by the administration: it stays when the person confirms their address.',
|
|
181
|
+
'Exit code 5 when a line is invalid or failed (each listed with its reason), or a confirmation e-mail could not be sent. No password or hash is ever shown or logged; the auth service logs counts only: poad logs auth.',
|
|
182
|
+
'poad.io: the same 15-minute token as poad storage --env, given to the owner; never the service_role key.',
|
|
183
|
+
],
|
|
184
|
+
},
|
|
141
185
|
storage: {
|
|
142
186
|
usage: ['poad storage ls [bucket[/folder]] [-r]', 'poad storage cp <source> <destination> [-r] [--concurrency <n>]', 'poad storage mv <bucket/path> <bucket/path> [-r] [--concurrency <n>]', 'poad storage rm <bucket/path…> [-r] [--yes]', 'poad storage sync --env <name> [--pull] [--bucket <name>] [--prune] [--dry-run] [--copy-bytes] [--concurrency <n>]'],
|
|
143
187
|
text: [
|
|
@@ -169,11 +213,12 @@ const sheets = {
|
|
|
169
213
|
text: [
|
|
170
214
|
'Copy between the disk and the storage, or inside the storage. A storage path is written poad:bucket/path. Example: poad storage cp -r ./site poad:web/',
|
|
171
215
|
'A file already identical at the destination (same size and MD5) is not copied again: run the same command again after an interruption and only what is missing is sent. Failures are listed again at the end (path and reason); any failure: exit code 1. --concurrency <n>: transfers at the same time, 1 to 32 (default 4); some providers limit the rate themselves (1fichier: 2 requests per second per account), more then gains little.',
|
|
216
|
+
'Files above 6 MiB go in resumable chunks of 6 MiB (TUS, storage 0.6+): a cut connection is resumed where the storage is, and an interrupted command run again resumes the upload instead of starting over (upload addresses kept 24 h in ~/.poad/uploads.json, never a key). An engine without chunked uploads gets the file in one request, as before.',
|
|
172
217
|
],
|
|
173
218
|
},
|
|
174
219
|
'storage mv': {
|
|
175
220
|
usage: ['poad storage mv <bucket/path> <bucket/path> [-r] [--concurrency <n>] [--json]'],
|
|
176
|
-
text: ['Move or rename inside the storage: copy, then delete each source copied (or already identical at the destination). Failures are listed at the end and left in place; any failure: exit code 1. --concurrency <n>: as for cp.'],
|
|
221
|
+
text: ['Move or rename inside the storage: copy, then delete each source copied (or already identical at the destination). Failures are listed at the end and left in place; any failure: exit code 1. --concurrency <n>: as for cp.', 'A folder moved to the folder that already holds it (poad storage mv -r poad:b/folder poad:b) has its content moved up one level: poad:b/folder/a.txt becomes poad:b/a.txt.'],
|
|
177
222
|
},
|
|
178
223
|
'storage rm': { usage: ['poad storage rm <bucket/path…> [-r] [--yes] [--json]'], text: ['Delete files; -r for a folder or every file of a bucket, after a confirmation (--yes outside a terminal).'] },
|
|
179
224
|
'storage sync': {
|
|
@@ -242,15 +287,18 @@ const sheets = {
|
|
|
242
287
|
notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
|
|
243
288
|
},
|
|
244
289
|
source: {
|
|
245
|
-
usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source ls | refresh … --env <name> [--project <id>]'],
|
|
290
|
+
usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…>] [--existing] [--format …] [--root <path>] [--detach]', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | pull … --env <name> [--project <id>]'],
|
|
246
291
|
text: [
|
|
247
|
-
'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV or JSONL), declared in poad/sources/<name>.yaml (engine 0.64.0
|
|
292
|
+
'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV or JSONL), declared in poad/sources/<name>.yaml (engine 0.64.0+; from engine 0.65.0 a source created by poad is named after its table). The engine creates the table with a migration of poad/migrations (read-only for the application, readable through the API with api: true) and a generated flow source-<name> that fills it: download, read, deposit, apply (upsert by key, removals under a guard).',
|
|
248
293
|
'With --env or --project, the commands act on the project hosted on poad.io (session of poad login, owner only) instead of the local engine: poad.io gives an access of 15 minutes, never shown. Locally, the service_role key of the project, never shown.',
|
|
249
294
|
],
|
|
250
295
|
options: [
|
|
251
296
|
['ls', 'each source: mode, table, rows, last synchronisation, next one, problems (declaration, table that differs from it, last failure); exit code 1 if a declaration is invalid'],
|
|
252
297
|
['refresh <name>', 'apply the declaration (table, flow), synchronise now and follow the run step by step, then print what changed; exit code 1 if it fails'],
|
|
253
|
-
['
|
|
298
|
+
['import <file>', 'load a CSV, JSON, GeoJSON or JSONL file (.gz accepted, no size limit) into a table: the file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads a sample, proposes the columns and a key, declares an imported source (origin kind: upload) and loads it, streamed; a source is named after its table (poad/sources/<table>.yaml); the source already exists: a new version, same path, then the load. --table <name> (default: the file name; cleaned: lowercase, accents removed, spaces → _, leading digit → t_), --name <source> (kept for compatibility: an existing source of that name gets a new version, otherwise ignored), --key <col,…>, --existing (load into an existing table), --format and --root when the guess is wrong'],
|
|
299
|
+
['pull <name>', 'write the declaration of a source into poad/sources/<name>.yaml: with --env, a source created in the console of poad.io (kept in the project database); commit it, then poad deploy'],
|
|
300
|
+
['--force', 'refresh: lift the deletion guard (safety.maxDeletePercent) for this run: the source is right even though many rows go away; pull: replace an existing poad/sources/<name>.yaml'],
|
|
301
|
+
['--stdout', 'pull: print the declaration instead of writing the file'],
|
|
254
302
|
['--detach (or --no-wait)', 'print the run id only, without following it'],
|
|
255
303
|
['--json', 'ls: the sources as JSON'],
|
|
256
304
|
['--env <name>', 'an environment of the linked poad.io project (main: production)'],
|
|
@@ -259,6 +307,7 @@ const sheets = {
|
|
|
259
307
|
notes: [
|
|
260
308
|
'A run that would remove more rows than safety.maxDeletePercent allows (or empty a table) is refused and changes nothing: check the source, then poad source refresh <name> --force.',
|
|
261
309
|
'Their logs: poad logs source=<name>; the run: poad flows show <run_id>. poad deploy sends poad/sources to poad.io.',
|
|
310
|
+
'Sources can also be created in the console (Sources, New source): locally it writes poad/sources/<name>.yaml; on poad.io it keeps the declaration in the project ("created in the console") until poad source pull <name> --env <name> brings it into the repository.',
|
|
262
311
|
],
|
|
263
312
|
},
|
|
264
313
|
migrate: {
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Envoi d'un fichier d'import (poad source import, poad db import) dans le bucket système poad-sources du
|
|
2
|
+
// projet, local ou poad.io : envoi reprenable (TUS 1.0.0, POST /storage/v1/upload/resumable, morceaux de 6 Mo,
|
|
3
|
+
// reprise à l'octet après une coupure, même client que poad storage cp) si le stockage le propose, sinon envoi simple en flux (PUT de l'objet).
|
|
4
|
+
// Le fichier n'est jamais lu en entier en mémoire. La clé (service_role locale, jeton poad.io) n'est jamais affichée.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
|
|
7
|
+
const tus = require('./storage-tus');
|
|
8
|
+
|
|
9
|
+
const TUS_CHUNK = tus.CHUNK;
|
|
10
|
+
|
|
11
|
+
/** Type d'après l'extension (gzip : application/gzip). Pure. */
|
|
12
|
+
const typeOf = (file) => {
|
|
13
|
+
const f = String(file).toLowerCase();
|
|
14
|
+
if (f.endsWith('.gz')) return 'application/gzip';
|
|
15
|
+
if (f.endsWith('.csv') || f.endsWith('.tsv')) return 'text/csv';
|
|
16
|
+
if (f.endsWith('.geojson')) return 'application/geo+json';
|
|
17
|
+
if (f.endsWith('.jsonl') || f.endsWith('.ndjson')) return 'application/x-ndjson';
|
|
18
|
+
if (f.endsWith('.json')) return 'application/json';
|
|
19
|
+
if (f.endsWith('.sql')) return 'application/sql';
|
|
20
|
+
return 'application/octet-stream';
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Envoie `file` vers target ({ bucket, object }) du stockage `base`.
|
|
25
|
+
* auth() rend les en-têtes d'accès à jour (le jeton poad.io se renouvelle pendant un long envoi).
|
|
26
|
+
* Rend { method: 'tus' | 'simple' } ou lève une erreur lisible.
|
|
27
|
+
*/
|
|
28
|
+
const uploadImportFile = async ({ base, auth, file, target, onProgress = () => {}, fetch: doFetch = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) => {
|
|
29
|
+
const size = fs.statSync(file).size;
|
|
30
|
+
const type = typeOf(file);
|
|
31
|
+
// 1. Envoi reprenable : le client de poad storage cp (utils/storage-tus.js), reprise d'une commande à l'autre
|
|
32
|
+
// (~/.poad/uploads.json, jamais de clé) ; un stockage sans TUS (engine d'avant storage 0.6.0) → envoi simple
|
|
33
|
+
let created = false;
|
|
34
|
+
const api = {
|
|
35
|
+
raw: async (method, route, { headers = {}, body } = {}) => {
|
|
36
|
+
const res = await doFetch(`${base}/storage/v1${route}`, { method, headers: { ...(await auth()), ...headers }, ...(body ? { body } : {}) });
|
|
37
|
+
if (method === 'POST' && res.status === 201) created = true;
|
|
38
|
+
return res;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
try {
|
|
42
|
+
onProgress({ sent: 0, total: size, method: 'tus' });
|
|
43
|
+
await tus.tusUpload(api, tus.fileSource(file, size), {
|
|
44
|
+
bucket: target.bucket,
|
|
45
|
+
key: target.object,
|
|
46
|
+
type,
|
|
47
|
+
cacheControl: 'no-cache',
|
|
48
|
+
upsert: true,
|
|
49
|
+
base,
|
|
50
|
+
mtimeMs: fs.statSync(file).mtimeMs,
|
|
51
|
+
sleep,
|
|
52
|
+
onProgress: (sent, total) => onProgress({ sent, total, method: 'tus' }),
|
|
53
|
+
});
|
|
54
|
+
return { method: 'tus', bytes: size };
|
|
55
|
+
} catch (e) {
|
|
56
|
+
const status = e && e.status;
|
|
57
|
+
const unsupported = !created && ((e && e.code === 'tus_unsupported') || status === 404 || status === 405 || status === 501);
|
|
58
|
+
if (!unsupported) throw new Error(status ? `the storage refused the upload (HTTP ${status}): ${e.message}` : `upload interrupted: ${(e && e.message) || e}`);
|
|
59
|
+
}
|
|
60
|
+
// 2. Envoi simple, en flux
|
|
61
|
+
onProgress({ sent: 0, total: size, method: 'simple' });
|
|
62
|
+
// http(s).request et pipe : la contre-pression du réseau règle la lecture du disque (fetch, lui, lit tout d'avance)
|
|
63
|
+
const target_ = new URL(`${base}/storage/v1/object/${encodeURIComponent(target.bucket)}/${target.object.split('/').map(encodeURIComponent).join('/')}`);
|
|
64
|
+
const headers = { ...(await auth()), 'content-type': type, 'content-length': String(size), 'x-upsert': 'true' };
|
|
65
|
+
const { status, text } = await new Promise((resolve, reject) => {
|
|
66
|
+
const lib = target_.protocol === 'https:' ? require('https') : require('http');
|
|
67
|
+
const req = lib.request(target_, { method: 'PUT', headers }, (res) => {
|
|
68
|
+
const chunks = [];
|
|
69
|
+
res.on('data', (c) => chunks.push(c));
|
|
70
|
+
res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8') }));
|
|
71
|
+
res.on('error', reject);
|
|
72
|
+
});
|
|
73
|
+
req.on('error', reject);
|
|
74
|
+
let sent = 0;
|
|
75
|
+
const stream = fs.createReadStream(file, { highWaterMark: 1 << 20 });
|
|
76
|
+
stream.on('data', (c) => {
|
|
77
|
+
sent += c.length;
|
|
78
|
+
onProgress({ sent, total: size, method: 'simple' });
|
|
79
|
+
});
|
|
80
|
+
stream.on('error', reject);
|
|
81
|
+
stream.pipe(req);
|
|
82
|
+
});
|
|
83
|
+
if (status < 200 || status >= 300) {
|
|
84
|
+
let why = text.slice(0, 300) || `HTTP ${status}`;
|
|
85
|
+
try {
|
|
86
|
+
const j = JSON.parse(text);
|
|
87
|
+
why = String((j && ((j.error && j.error.message) || j.message || j.error)) || why);
|
|
88
|
+
} catch {
|
|
89
|
+
/* texte brut */
|
|
90
|
+
}
|
|
91
|
+
throw new Error(status === 413 ? `the file is too large for a simple upload (${why}): the resumable upload of the storage (engine with TUS) lifts this limit` : `the storage refused the upload (HTTP ${status}): ${why}`);
|
|
92
|
+
}
|
|
93
|
+
return { method: 'simple', bytes: size };
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** Avancement sur stderr (terminal seulement) ; done() efface la ligne */
|
|
97
|
+
const progressLine = (label) => {
|
|
98
|
+
const tty = process.stderr.isTTY;
|
|
99
|
+
let last = 0;
|
|
100
|
+
const mb = (n) => (n / 1048576).toFixed(1);
|
|
101
|
+
return {
|
|
102
|
+
update: (p) => {
|
|
103
|
+
if (!tty || Date.now() - last < 200) return;
|
|
104
|
+
last = Date.now();
|
|
105
|
+
const pct = p.total ? Math.floor((100 * p.sent) / p.total) : 0;
|
|
106
|
+
process.stderr.write(`\r ${label}: ${mb(p.sent)} / ${mb(p.total)} MB (${pct} %, ${p.method === 'tus' ? 'resumable' : 'simple'} upload) `);
|
|
107
|
+
},
|
|
108
|
+
done: () => tty && process.stderr.write('\r\x1b[2K'),
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
module.exports = { uploadImportFile, typeOf, progressLine, TUS_CHUNK };
|
package/utils/logline.js
CHANGED
|
@@ -5,8 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
|
|
|
5
5
|
|
|
6
6
|
// Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
|
|
7
7
|
// que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
|
|
8
|
-
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name' };
|
|
9
|
-
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes' };
|
|
8
|
+
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket' };
|
|
9
|
+
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents' };
|
|
10
10
|
// Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
|
|
11
11
|
const RUN_RE = /^[0-9a-f-]{8,36}$/;
|
|
12
12
|
|
package/utils/logs.js
CHANGED
|
@@ -9,8 +9,15 @@ const { setKeys } = require('./tomlfile');
|
|
|
9
9
|
|
|
10
10
|
const GELF_CONTAINER_PORT = '12201/udp';
|
|
11
11
|
|
|
12
|
+
// Puits de logs : engine 0.8.1 et plus. Une version qui n'est pas un numéro
|
|
13
|
+
// (image de développement construite localement, « auth-import-dev ») est
|
|
14
|
+
// tenue pour récente : elle vient des sources actuelles, qui ont le puits.
|
|
12
15
|
const supportsLogs = (config) => {
|
|
13
|
-
const
|
|
16
|
+
const engine = String((config && config.engine) || '').trim();
|
|
17
|
+
if (!engine) return false;
|
|
18
|
+
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(engine);
|
|
19
|
+
if (!m) return true;
|
|
20
|
+
const [major, minor, patch] = m.slice(1).map(Number);
|
|
14
21
|
return major > 0 || minor > 8 || (minor === 8 && patch >= 1);
|
|
15
22
|
};
|
|
16
23
|
|
package/utils/naming.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Noms de tables et de colonnes nettoyés : même règle que meta (services/meta/src/naming.ts) et la console.
|
|
2
|
+
// minuscules ; accents retirés (é → e, ç → c ; œ, æ, ß : oe, ae, ss) ; camelCase coupé ; espaces, tirets, points,
|
|
3
|
+
// barres → « _ » ; autres caractères hors [a-z0-9_] retirés ; « _ » fusionnés et ôtés aux bouts ; chiffre en tête :
|
|
4
|
+
// t_ (table) ou c_ (colonne) ; 63 octets au plus ; mot réservé de SQL : suffixe _t ou _c ; vide : donnees / colonne.
|
|
5
|
+
// Le nom d'une source créée par poad est celui de sa table (poad/sources/<table>.yaml).
|
|
6
|
+
const RESERVED = new Set(
|
|
7
|
+
(
|
|
8
|
+
'all analyse analyze and any array as asc asymmetric authorization binary both case cast check collate collation column concurrently ' +
|
|
9
|
+
'constraint create cross current_catalog current_date current_role current_schema current_time current_timestamp current_user default ' +
|
|
10
|
+
'deferrable desc distinct do else end except false fetch for foreign freeze from full grant group having ilike in initially inner intersect ' +
|
|
11
|
+
'into is isnull join lateral leading left like limit localtime localtimestamp natural not notnull null offset on only or order outer overlaps ' +
|
|
12
|
+
'placing primary references returning right select session_user similar some symmetric system_user table tablesample then to trailing true ' +
|
|
13
|
+
'union unique user using variadic verbose when where window with'
|
|
14
|
+
).split(' '),
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
/** Nom nettoyé ; kind : 'table' ou 'column'. Pure. */
|
|
18
|
+
function cleanIdent(raw, kind = 'table') {
|
|
19
|
+
let s = String(raw == null ? '' : raw)
|
|
20
|
+
.replace(/œ/g, 'oe')
|
|
21
|
+
.replace(/Œ/g, 'OE')
|
|
22
|
+
.replace(/æ/g, 'ae')
|
|
23
|
+
.replace(/Æ/g, 'AE')
|
|
24
|
+
.replace(/ß/g, 'ss')
|
|
25
|
+
.normalize('NFD')
|
|
26
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
27
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
28
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
|
|
29
|
+
.toLowerCase()
|
|
30
|
+
.replace(/[\s\-./\\:,;|+]+/g, '_')
|
|
31
|
+
.replace(/[^a-z0-9_]/g, '')
|
|
32
|
+
.replace(/_+/g, '_')
|
|
33
|
+
.replace(/^_+|_+$/g, '');
|
|
34
|
+
if (!s) s = kind === 'table' ? 'donnees' : 'colonne';
|
|
35
|
+
if (/^[0-9]/.test(s)) s = `${kind === 'table' ? 't' : 'c'}_${s}`;
|
|
36
|
+
s = s.slice(0, 63).replace(/_+$/, '');
|
|
37
|
+
if (RESERVED.has(s)) s = `${s}_${kind === 'table' ? 't' : 'c'}`;
|
|
38
|
+
return s;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { cleanIdent, RESERVED };
|