poad 2.61.2 → 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.
@@ -1,7 +1,7 @@
1
1
  // Archive de déploiement : le dossier poad/ en tar.gz, par liste blanche.
2
2
  //
3
3
  // Entrent (chemins relatifs à poad/, sans préfixe) :
4
- // dossiers migrations queries auth storage functions flows api reference variables types
4
+ // dossiers migrations queries auth storage functions flows api reference sources variables types
5
5
  // credentials/manifest.json noms, types et usages des credentials, sans valeur
6
6
  // (les valeurs restent dans le coffre de chaque engine)
7
7
  // fichiers seed.sql, config.toml (sans aucune clé secrète : stripSecrets)
@@ -19,7 +19,7 @@ const fs = require('fs');
19
19
  const path = require('path');
20
20
  const zlib = require('zlib');
21
21
 
22
- const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'variables', 'types'];
22
+ const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'variables', 'types'];
23
23
  const FILES = ['seed.sql', 'config.toml'];
24
24
  const NEVER = [/^secrets\.toml$/i, /^\.env$/i, /^\.env\..*/i, /^\.DS_Store$/, /^Thumbs\.db$/i, /^desktop\.ini$/i, /~$/, /\.swp$/];
25
25
  const SKIP_DIRS = new Set(['node_modules', '.git', 'data', 'backups', '.cache']);
@@ -194,7 +194,11 @@ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
194
194
  } catch {}
195
195
  }
196
196
  if (!rels.includes('config.toml')) throw new BundleError('poad/config.toml is missing');
197
- if (rels.length > limits.maxEntries) throw new BundleError(`more than ${limits.maxEntries} files to send`);
197
+ // Dépendances npm des fonctions : seuls les fichiers que leurs imports atteignent (utils/cloud/deps.js)
198
+ const deps = require('./deps').traceDependencies(path.join(poadDir, 'functions'));
199
+ const depFiles = deps.files.map((f) => ({ ...f, path: `functions/${f.rel}` }));
200
+ for (const s of skipped) if (s.path === 'functions/node_modules/') s.reason = depFiles.length ? `only the ${depFiles.length} file(s) the functions import are sent` : 'nothing imported by the functions';
201
+ if (rels.length + depFiles.length > limits.maxEntries) throw new BundleError(`more than ${limits.maxEntries} files to send`);
198
202
 
199
203
  const secrets = localSecrets(poadDir);
200
204
  const files = [];
@@ -232,9 +236,19 @@ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
232
236
  if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
233
237
  files.push({ path: rel, data, mode: st.mode & 0o111 ? 0o755 : 0o644 });
234
238
  }
239
+ for (const f of depFiles) {
240
+ const st = fs.statSync(f.abs);
241
+ if (st.size > limits.maxFile) throw new BundleError(`${f.path} is larger than ${Math.round(limits.maxFile / 1048576)} MB`);
242
+ const data = f.data || fs.readFileSync(f.abs);
243
+ for (const s of secrets) if (data.includes(s)) throw new BundleError(`${f.path} contains a secret of poad/secrets.toml: nothing was sent.`);
244
+ total += data.length;
245
+ if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
246
+ // Jamais exécutable : un paquet n'apporte que du code et des données lus par l'engine
247
+ files.push({ path: f.path, data, mode: 0o644 });
248
+ }
235
249
  files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
236
250
  const tgz = zlib.gzipSync(tar(files), { level: 9 });
237
- return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total };
251
+ return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total, deps: { packages: deps.packages, files: depFiles.length, missing: deps.missing, outside: deps.outside } };
238
252
  }
239
253
 
240
254
  module.exports = { build, tar, cleanConfig, cleanCredentialsManifest, localSecrets, BundleError, DIRS, FILES, LIMITS };
@@ -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 };
@@ -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: {
@@ -114,15 +116,33 @@ const sheets = {
114
116
  ['event=<event>', 'an event, e.g. ai_default_model_changed'],
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'],
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'],
117
122
  ['limit=100', 'number of lines, from 1 to 10000'],
118
123
  ['-f, --follow', 'follow live'],
119
124
  ['--json', 'one JSON line per entry (for jq)'],
120
125
  ],
121
126
  notes: [
122
127
  'Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f',
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"',
123
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.',
124
131
  ],
125
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
+ },
126
146
  'db diff': {
127
147
  usage: ['poad db diff', 'poad db diff <name>', 'poad db diff --discard', 'poad db diff --json'],
128
148
  text: [
@@ -136,8 +156,34 @@ const sheets = {
136
156
  ['--json', 'entries, groups, SQL and the summary (summary: change, kind, object, others, detail)'],
137
157
  ],
138
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
+ },
139
185
  storage: {
140
- usage: ['poad storage ls [bucket[/folder]] [-r]', 'poad storage cp <source> <destination> [-r]', 'poad storage mv <bucket/path> <bucket/path> [-r]', 'poad storage rm <bucket/path…> [-r] [--yes]'],
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>]'],
141
187
  text: [
142
188
  'Files of the project storage, local engine (poad start) or poad.io (--env), whatever its backend: engine disk, S3 or 1fichier. A storage path is bucket/path; folders exist through their files ("a/b/c.png"), as in the console. For cp, write a storage path poad:bucket/path so that it is not taken for a file of the disk.',
143
189
  ],
@@ -148,21 +194,58 @@ const sheets = {
148
194
  ['cp poad:images/a.png poad:backup/a.png', 'storage → storage'],
149
195
  ['mv', 'move or rename inside the storage: copy, then delete each source copied (a failed copy leaves its source in place)'],
150
196
  ['rm', 'delete files; a folder or a whole bucket needs -r and a confirmation (the bucket itself stays)'],
197
+ ['sync --env <name>', 'align the storage of a poad.io environment on the local one (see poad help storage sync)'],
151
198
  ['-r', 'folders, recursively'],
152
199
  ['--env <name>', 'the storage of a poad.io environment of the linked project (main: production) instead of the local engine'],
153
200
  ['--project <id>', 'another poad.io project (poad login); with --env for one of its environments'],
201
+ ['--concurrency <n>', 'cp, mv, sync: transfers at the same time, 1 to 32 (default 4); more helps with a distant storage, see the notes'],
154
202
  ['--yes', 'no question (required outside a terminal for rm -r)'],
155
- ['--json', 'the result as JSON'],
203
+ ['--json', 'the result as JSON; cp, mv and sync add failures: [{ path, reason }]'],
156
204
  ],
157
205
  notes: [
158
- 'Transfers stream through the CLI (4 at a time). Local engine: the service_role key of poad/config.toml, never shown. poad.io: a storage token of 15 minutes given to the owner (renewed during long transfers), never the service_role key. A file already there is replaced. Every request is logged by the storage service: poad logs storage.',
206
+ 'Transfers stream through the CLI, 4 at a time (--concurrency <n>, 1 to 32: more helps when each transfer waits on a distant storage; some providers limit the rate themselves, 1fichier for one allows 2 requests per second per account, and more transfers at once then gain little). Local engine: the service_role key of poad/config.toml, never shown. poad.io: a storage token of 15 minutes given to the owner (renewed during long transfers), never the service_role key. A file already at the destination with the same size and MD5 (and type) is left alone, so cp -r run again only sends what is missing or changed; a different one is replaced. A failed file does not stop the others: the final summary lists every failure (path and reason, such as the size limit of the storage) and the command exits with code 1. Every request is logged by the storage service: poad logs storage.',
159
207
  'Deleted content leaves the backend a minute later (storage sweeper).',
160
208
  ],
161
209
  },
162
210
  'storage ls': { usage: ['poad storage ls [bucket[/folder]] [-r] [--json]'], text: ['Buckets, or the folders then files of a folder (-r: every file under it, full path).'] },
163
- 'storage cp': { usage: ['poad storage cp <source> <destination> [-r] [--json]'], text: ['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/'] },
164
- 'storage mv': { usage: ['poad storage mv <bucket/path> <bucket/path> [-r] [--json]'], text: ['Move or rename inside the storage: copy, then delete each source copied.'] },
211
+ 'storage cp': {
212
+ usage: ['poad storage cp <source> <destination> [-r] [--concurrency <n>] [--json]'],
213
+ text: [
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/',
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.',
217
+ ],
218
+ },
219
+ 'storage mv': {
220
+ usage: ['poad storage mv <bucket/path> <bucket/path> [-r] [--concurrency <n>] [--json]'],
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.'],
222
+ },
165
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).'] },
224
+ 'storage sync': {
225
+ usage: ['poad storage sync --env <name> [--project <id>] [--pull] [--bucket <name>] [--prune] [--dry-run] [--copy-bytes] [--concurrency <n>] [--yes] [--json]'],
226
+ text: [
227
+ 'Align the storage of a poad.io environment on the storage of the local project (engine started), or the other way with --pull: same buckets (created when missing, never deleted), same files. Files are compared by name, size and MD5; an identical file is left alone, so a sync run again (after an interruption or a failure) only does what is missing.',
228
+ 'How depends on where each side keeps its files. Either side on its engine disk: the bytes are sent, and the command says so. Both on S3 or 1fichier at the same place (same S3 endpoint, bucket and prefix; same 1fichier folder), between environments of the same project only (your machine and its linked poad.io project, production and a staging environment…): only references are sent (name, size, type, key of the content) and no byte moves; the other storage checks that the request comes from the same project and that each content is really there before recording it. Two different places: the command stops and says so; add --copy-bytes to send the files themselves.',
229
+ 'Every project is independent: a storage location is never shared between projects. Two different projects pointing at the same place is a configuration error: the command says so and copies nothing, not even with --copy-bytes.',
230
+ 'The place is compared through a fingerprint published by each storage (endpoint, bucket, prefix or folder, never a key), the project through its poad.io identifier (linked with poad link; restart the local engine after linking). Credentials are never copied, read or shown: each side keeps the one set on it.',
231
+ ],
232
+ options: [
233
+ ['--env <name>', 'the poad.io environment (main: production) of the linked project'],
234
+ ['--project <id>', 'another poad.io project (poad login); with --env for one of its environments'],
235
+ ['--pull', 'poad.io → local instead of local → poad.io'],
236
+ ['--bucket <name>', 'this bucket only'],
237
+ ['--prune', 'also delete on the destination the files missing from the source; a file whose content the source still uses under another name (same place) is kept and reported. Buckets are never deleted, not even with --prune: delete a bucket yourself, in the console'],
238
+ ['--dry-run, -n', 'show what would be done, change nothing'],
239
+ ['--copy-bytes', 'send the bytes even when references would do, or when the two sides store files in different places'],
240
+ ['--concurrency <n>', 'byte transfers at the same time, 1 to 32 (default 4). Some providers limit the rate themselves (1fichier: 2 requests per second per account): more transfers at once then gain little'],
241
+ ['--yes', 'no question (replacing or deleting files asks first; required outside a terminal)'],
242
+ ['--json', 'the plan or the result as JSON (totals: added, updated, unchanged, removed, kept, failed, bytes; failures: [{ path, reason }])'],
243
+ ],
244
+ notes: [
245
+ 'Same place for two environments of a project: a file deleted on the side that wrote it is gone for the other side too. Each engine only ever removes the contents it wrote itself (orphans, replaced files, folders of deleted buckets), with nothing to turn on, so a sync never makes one environment clean up the other.',
246
+ 'A failed file does not stop the others: the final summary lists every failure (path and reason) and the command exits with code 1. References need storage 0.4.0 on both engines (the command says so otherwise); bytes work with any engine. Internal buckets (poad-*) are left out unless named with --bucket. Every request is logged by the storage service of each side: poad logs storage.',
247
+ ],
248
+ },
166
249
  functions: {
167
250
  usage: ['poad functions new <name>', 'poad functions list', 'poad functions types'],
168
251
  text: [
@@ -203,6 +286,30 @@ const sheets = {
203
286
  ],
204
287
  notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
205
288
  },
289
+ source: {
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>]'],
291
+ text: [
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).',
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.',
294
+ ],
295
+ options: [
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'],
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'],
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'],
302
+ ['--detach (or --no-wait)', 'print the run id only, without following it'],
303
+ ['--json', 'ls: the sources as JSON'],
304
+ ['--env <name>', 'an environment of the linked poad.io project (main: production)'],
305
+ ['--project <id>', 'a poad.io project other than the one linked to this folder (no project folder needed)'],
306
+ ],
307
+ notes: [
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.',
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.',
311
+ ],
312
+ },
206
313
  migrate: {
207
314
  usage: ['poad migrate', 'poad migrate --force-reference'],
208
315
  text: ['Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).'],
@@ -232,6 +339,7 @@ const alias = (of, name) => ({
232
339
  });
233
340
  sheets.function = alias('functions', 'function');
234
341
  sheets.flow = alias('flows', 'flow');
342
+ sheets.sources = alias('source', 'sources');
235
343
 
236
344
  // --- poad.io (projets hébergés) -------------------------------------------------
237
345
  const EXIT_NOTE = 'Exit codes: 0 done, 1 error (poad.io, network), 2 usage (option, folder, link), 3 session (poad login), 4 confirmation missing or refused, 5 deploy failed.';