@skillstech/thunderlang 0.5.11 → 0.5.12
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/CHANGELOG.md +437 -0
- package/dist/core.cjs +30431 -7604
- package/dist/index.cjs +28577 -5331
- package/dist/learn.cjs +22676 -3870
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +48 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +59 -12
- package/src/model.mjs +462 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1015 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
// Docker Compose in Thunder (spec section 12): the services an app starts on one computer, and how they connect.
|
|
2
|
+
// Each service is a Resource that knows what it runs (an image, or the image built from a folder, linked to that
|
|
3
|
+
// folder's Dockerfile when it is in the repository), the ports it publishes and to whom, its settings (a secret-looking
|
|
4
|
+
// value is never shown; `${VAR}` is worked out when it starts), the files and volumes it keeps, what it waits for, and
|
|
5
|
+
// how its health is checked. Named volumes, networks, secrets, and configs are Resources too. The order things start,
|
|
6
|
+
// from depends_on, is one Steps card. Deterministic, browser-safe; reads the file, not what is running.
|
|
7
|
+
import { parseYamlDocs, get, entry, text, list, scalar } from './yaml.mjs';
|
|
8
|
+
import { listWords, orWords, cap } from './infra-words.mjs';
|
|
9
|
+
import { topoOrder } from './infra-cloud.mjs';
|
|
10
|
+
import { imageShort, imageWords, imageNotPinned, cpuWords, memWords, isSecretName, secretLiteral, servicesNamed, commandText, hasVar } from './infra-containers.mjs';
|
|
11
|
+
|
|
12
|
+
const STARTS = 'worked out when it starts';
|
|
13
|
+
const str = (n) => { const v = scalar(n); return v == null ? undefined : String(v); };
|
|
14
|
+
const lineOf = (n, key, fallback) => entry(n, key)?.line ?? fallback;
|
|
15
|
+
const short = (s, n = 80) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
16
|
+
const varsIn = (s) => { const out = []; const re = /\$\{([A-Za-z_][A-Za-z0-9_]*)|\$([A-Za-z_][A-Za-z0-9_]*)/g; let m; while ((m = re.exec(String(s)))) { const v = m[1] ?? m[2]; if (!out.includes(v)) out.push(v); } return out; };
|
|
17
|
+
const later = (s) => { const vs = varsIn(s); return `${STARTS}${vs.length && vs.length <= 2 ? `, from the variable${vs.length === 1 ? '' : 's'} ${listWords(vs)}` : ''}`; };
|
|
18
|
+
|
|
19
|
+
/** The last line a node covers. */
|
|
20
|
+
function lastLine(n) {
|
|
21
|
+
if (!n) return 0;
|
|
22
|
+
if (n.t === 'map') return Math.max(n.line, ...n.entries.map((e) => Math.max(e.line, lastLine(e.value))));
|
|
23
|
+
if (n.t === 'seq') return Math.max(n.line, ...n.items.map(lastLine));
|
|
24
|
+
if (n.block) return (n.valueLine ?? n.line) + Math.max(0, String(n.v).replace(/\n+$/, '').split('\n').length - 1);
|
|
25
|
+
return n.line;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** `a/b/../c` -> `a/c`; null when the path leaves the repository. */
|
|
29
|
+
function normPath(p) {
|
|
30
|
+
const out = [];
|
|
31
|
+
for (const seg of String(p).replace(/\\/g, '/').split('/')) {
|
|
32
|
+
if (!seg || seg === '.') continue;
|
|
33
|
+
if (seg === '..') { if (!out.length) return null; out.pop(); } else out.push(seg);
|
|
34
|
+
}
|
|
35
|
+
return out.join('/');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A published port, short or long syntax: { host, container, ip, proto, line }. */
|
|
39
|
+
function portOf(n) {
|
|
40
|
+
if (n.t === 'map') return { container: str(get(n, 'target')), host: str(get(n, 'published')), ip: str(get(n, 'host_ip')), proto: str(get(n, 'protocol')), line: n.line };
|
|
41
|
+
const s = String(scalar(n) ?? '');
|
|
42
|
+
let rest = s, proto;
|
|
43
|
+
const slash = rest.lastIndexOf('/');
|
|
44
|
+
if (slash > 0) { proto = rest.slice(slash + 1); rest = rest.slice(0, slash); }
|
|
45
|
+
let ip;
|
|
46
|
+
if (rest.startsWith('[')) { const end = rest.indexOf(']'); ip = rest.slice(1, end); rest = rest.slice(end + 2); }
|
|
47
|
+
const parts = rest.split(':');
|
|
48
|
+
if (parts.length === 3) ip = parts.shift();
|
|
49
|
+
const [a, b] = parts;
|
|
50
|
+
return b != null ? { host: a, container: b, ip, proto, line: n.line } : { container: a, ip, proto, line: n.line };
|
|
51
|
+
}
|
|
52
|
+
const LOCAL = /^(127\.\d+\.\d+\.\d+|::1|localhost)$/;
|
|
53
|
+
|
|
54
|
+
/** Environment entries, map or `KEY=value` list: [{ key, value (undefined: taken from the computer), line }]. */
|
|
55
|
+
function envEntries(n) {
|
|
56
|
+
if (n?.t === 'map') return n.entries.map((e) => ({ key: e.key, value: e.value?.t === 'str' ? (e.value.v == null ? undefined : String(scalar(e.value))) : undefined, line: e.line }));
|
|
57
|
+
return list(n).map((x) => { const s = String(scalar(x) ?? ''); const i = s.indexOf('='); return i < 0 ? { key: s, value: undefined, line: x.line } : { key: s.slice(0, i), value: s.slice(i + 1), line: x.line }; });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A health check test in words: ["CMD", "curl", "-f", "http://localhost"] -> 'curl -f http://localhost'. */
|
|
61
|
+
function testWords(n) {
|
|
62
|
+
if (n?.t === 'seq') {
|
|
63
|
+
const xs = list(n).map(str);
|
|
64
|
+
if (xs[0] === 'NONE') return null;
|
|
65
|
+
return commandText(xs[0] === 'CMD' || xs[0] === 'CMD-SHELL' ? xs.slice(1) : xs);
|
|
66
|
+
}
|
|
67
|
+
return str(n) ?? '';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const RESTART = { no: 'never (it stays stopped)', always: 'always', 'unless-stopped': 'always, unless someone stops it', 'on-failure': 'when it fails', none: 'never (it stays stopped)', any: 'always' };
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Read a Compose file: services, named volumes, networks, secrets, and configs as Resources, their settings, facts,
|
|
74
|
+
* and links, plus one Steps card with the order they start. `file` is the path, used to find a service's Dockerfile.
|
|
75
|
+
*/
|
|
76
|
+
export function readCompose(src, file = 'compose.yaml') {
|
|
77
|
+
const docs = parseYamlDocs(src);
|
|
78
|
+
const things = [], settings = [], facts = [], links = [], unknowns = [];
|
|
79
|
+
for (const d of docs) if (d.error) unknowns.push({ file, line: d.error.line ?? d.line, why: `This part could not be read as YAML: ${d.error.message}` });
|
|
80
|
+
const root = docs.find((d) => d.node?.t === 'map')?.node;
|
|
81
|
+
if (!root) return { items: [], things, settings, facts, links, permissions: [], unknowns };
|
|
82
|
+
const dir = file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : '';
|
|
83
|
+
const factIds = new Set();
|
|
84
|
+
const fact = (kind, says, line) => {
|
|
85
|
+
let id = `${file}#${kind}#${line}`;
|
|
86
|
+
for (let i = 2; factIds.has(id); i++) id = `${file}#${kind}#${line}#${i}`;
|
|
87
|
+
factIds.add(id);
|
|
88
|
+
facts.push({ id, kind, says, file, line });
|
|
89
|
+
};
|
|
90
|
+
const setting = (x) => { if (!settings.some((s) => s.name === x.name && s.source === x.source && s.line === x.line)) settings.push({ file, ...x }); };
|
|
91
|
+
const link = (from, to, kind, line) => {
|
|
92
|
+
if (from === to) return;
|
|
93
|
+
const same = links.find((l) => l.from === from && l.to === to);
|
|
94
|
+
if (!same) links.push({ from, to, kind, file, line });
|
|
95
|
+
else if (same.kind === 'uses' && kind !== 'uses') { same.kind = kind; same.line = line; }
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const services = get(root, 'services');
|
|
99
|
+
const serviceNames = new Set((services?.entries ?? []).map((e) => e.key));
|
|
100
|
+
const top = (key) => new Map((get(root, key)?.entries ?? []).map((e) => [e.key, e]));
|
|
101
|
+
const volumes = top('volumes'), networks = top('networks'), secrets = top('secrets'), configs = top('configs');
|
|
102
|
+
|
|
103
|
+
// ── Named volumes, networks, secrets, configs ──
|
|
104
|
+
const declared = [];
|
|
105
|
+
for (const [key, type, word] of [['networks', 'compose-network', 'network'], ['volumes', 'compose-volume', 'volume'], ['secrets', 'compose-secret', 'secret'], ['configs', 'compose-config', 'config']]) {
|
|
106
|
+
for (const [name, e] of top(key)) {
|
|
107
|
+
const v = e.value;
|
|
108
|
+
const knows = [];
|
|
109
|
+
const know = (label, kindText, line, extra = {}) => knows.push({ name: label, label, kind: kindText, start: null, line: line ?? e.line, ...extra });
|
|
110
|
+
const ext = get(v, 'external');
|
|
111
|
+
const external = str(ext) === 'true' || ext?.t === 'map';
|
|
112
|
+
const realName = str(get(v, 'name')) ?? str(get(ext, 'name'));
|
|
113
|
+
if (external) know('Made', `elsewhere: Compose uses the existing ${word}${realName ? ` ${realName}` : ''}`, lineOf(v, 'external'));
|
|
114
|
+
else if (realName) know('Named', realName, lineOf(v, 'name'));
|
|
115
|
+
const driver = str(get(v, 'driver'));
|
|
116
|
+
if (driver) know('Driver', driver, lineOf(v, 'driver'));
|
|
117
|
+
if (key === 'networks' && str(get(v, 'internal')) === 'true') know('Reaches', 'only the services on it (no way out to the internet)', lineOf(v, 'internal'));
|
|
118
|
+
if (key === 'secrets' || key === 'configs') {
|
|
119
|
+
const f = str(get(v, 'file')), env = str(get(v, 'environment')), content = get(v, 'content');
|
|
120
|
+
if (f) know('Read from', `the file ${f} on the computer it starts on`, lineOf(v, 'file'));
|
|
121
|
+
if (env) know('Taken from', `the variable ${env} on the computer it starts on`, lineOf(v, 'environment'));
|
|
122
|
+
if (content) know('Written here', key === 'secrets' ? 'yes (not shown)' : short(str(content) ?? ''), lineOf(v, 'content'));
|
|
123
|
+
if (key === 'secrets') {
|
|
124
|
+
setting({ name, source: 'secret', secret: true, line: e.line });
|
|
125
|
+
if (content && !hasVar(str(content))) fact('secret-in-plain-config', `The secret ${name} has its value written in the Compose file.`, lineOf(v, 'content'));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const address = `${key}.${name}`;
|
|
129
|
+
things.push({ kind: 'resource', name: address, label: `${cap(word)} ${name}`, resourceType: type, address, file, lines: [e.line, Math.max(e.line, lastLine(v))], knows, choices: [], ...(external ? { existing: true } : {}) });
|
|
130
|
+
declared.push({ address, kind: key, name, line: e.line, external });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ── Services ──
|
|
135
|
+
const starts = new Map();
|
|
136
|
+
for (const e of services?.entries ?? []) {
|
|
137
|
+
const name = e.key, s = e.value;
|
|
138
|
+
const address = `services.${name}`;
|
|
139
|
+
const where = `The service ${name}`;
|
|
140
|
+
const knows = [];
|
|
141
|
+
const know = (label, kindText, line, extra = {}) => knows.push({ name: extra.name ?? label, label, kind: kindText, start: null, line: line ?? e.line, ...extra });
|
|
142
|
+
const image = str(get(s, 'image'));
|
|
143
|
+
const build = get(s, 'build');
|
|
144
|
+
const info = { image, build: null, after: [], profiles: list(get(s, 'profiles')).map(str) };
|
|
145
|
+
if (build) {
|
|
146
|
+
const ctx = build.t === 'map' ? str(get(build, 'context')) ?? '.' : str(build) ?? '.';
|
|
147
|
+
const df = build.t === 'map' ? str(get(build, 'dockerfile')) : undefined;
|
|
148
|
+
const target = build.t === 'map' ? str(get(build, 'target')) : undefined;
|
|
149
|
+
const remote = /^(https?|git|ssh):\/\/|^git@|\.git(#|$)/.test(ctx);
|
|
150
|
+
info.build = ctx;
|
|
151
|
+
know('Built from', `${remote ? `the repository ${ctx}` : ctx === '.' ? 'this folder' : `the folder ${ctx}`}${df ? `, with ${df}` : ''}${target ? `, the ${target} stage` : ''}`, build.t === 'map' ? lineOf(build, 'context', lineOf(s, 'build')) : lineOf(s, 'build'), { name: 'build' });
|
|
152
|
+
if (!remote && !hasVar(ctx) && !(df && (hasVar(df) || df.startsWith('/')))) {
|
|
153
|
+
const path = normPath(`${dir ? `${dir}/` : ''}${ctx}/${df ?? 'Dockerfile'}`);
|
|
154
|
+
if (path) link(address, `image:${path}`, 'uses', lineOf(s, 'build'));
|
|
155
|
+
}
|
|
156
|
+
for (const a of envEntries(build.t === 'map' ? get(build, 'args') : null)) {
|
|
157
|
+
const secret = isSecretName(a.key);
|
|
158
|
+
if (secretLiteral(a.key, a.value)) fact('secret-in-plain-env', `${where} passes ${a.key} to its build with the value written in the file.`, a.line);
|
|
159
|
+
setting({ name: a.key, source: a.value == null || hasVar(a.value) ? 'computed' : 'parameter', secret, line: a.line, ...(a.value == null || hasVar(a.value) ? { computed: true } : {}), ...(!secret && a.value != null && !hasVar(a.value) ? { default: a.value } : {}) });
|
|
160
|
+
}
|
|
161
|
+
if (image) know('Names the image', image, lineOf(s, 'image'));
|
|
162
|
+
} else if (image) {
|
|
163
|
+
know('Runs', imageWords(image, later(image)), lineOf(s, 'image'), { name: 'image', ...(hasVar(image) ? { computed: true } : {}) });
|
|
164
|
+
const says = imageNotPinned(image, where);
|
|
165
|
+
if (says) fact('image-not-pinned', says, lineOf(s, 'image'));
|
|
166
|
+
} else if (get(s, 'extends')) {
|
|
167
|
+
const ex = get(s, 'extends');
|
|
168
|
+
know('Builds on', `the service ${str(get(ex, 'service')) ?? str(ex)}${str(get(ex, 'file')) ? ` in ${str(get(ex, 'file'))}` : ''}`, lineOf(s, 'extends'));
|
|
169
|
+
}
|
|
170
|
+
const ent = get(s, 'entrypoint'), cmd = get(s, 'command');
|
|
171
|
+
const cmdText = (n) => (n?.t === 'seq' ? commandText(list(n).map(str)) : str(n));
|
|
172
|
+
if (ent || cmd) know('Starts with', short([cmdText(ent), cmdText(cmd)].filter(Boolean).join(' '), 120), lineOf(s, ent ? 'entrypoint' : 'command'));
|
|
173
|
+
const deploy = get(s, 'deploy');
|
|
174
|
+
const replicas = str(get(deploy, 'replicas')) ?? str(get(s, 'scale'));
|
|
175
|
+
if (replicas) know('How many', `${replicas} cop${replicas === '1' ? 'y' : 'ies'}`, lineOf(deploy, 'replicas', lineOf(s, 'scale')));
|
|
176
|
+
|
|
177
|
+
// Ports: published on every network address unless a local address is named.
|
|
178
|
+
const ports = list(get(s, 'ports')).map(portOf);
|
|
179
|
+
for (const p of ports) {
|
|
180
|
+
const local = p.ip && LOCAL.test(p.ip);
|
|
181
|
+
const anyIp = !p.ip || p.ip === '0.0.0.0' || p.ip === '::' || p.ip === '[::]';
|
|
182
|
+
const hostPart = p.host ? `port ${p.host}` : 'a port Docker picks';
|
|
183
|
+
know('Publishes', `port ${p.container}${p.proto && p.proto !== 'tcp' ? ` (${p.proto.toUpperCase()})` : ''} as ${hostPart}, ${local ? 'on this computer only' : anyIp ? 'on every network the computer is on' : `on the address ${p.ip}`}`, p.line);
|
|
184
|
+
if (!local && anyIp) fact('public-ingress', `${where} publishes ${p.host ? `port ${p.host}` : `port ${p.container} on a port Docker picks`} on every network address of the computer it runs on, so anyone who can reach that computer can reach it.`, p.line);
|
|
185
|
+
}
|
|
186
|
+
const expose = list(get(s, 'expose')).map(str);
|
|
187
|
+
if (expose.length) know('Open to the other services on', `port${expose.length === 1 ? '' : 's'} ${listWords(expose)}`, lineOf(s, 'expose'));
|
|
188
|
+
const nm = str(get(s, 'network_mode'));
|
|
189
|
+
if (nm === 'host') know('Network', "the computer's own network: every port it opens is open on the computer", lineOf(s, 'network_mode'));
|
|
190
|
+
else if (nm?.startsWith('service:')) { const other = nm.slice(8); know('Network', `shares the network of the service ${other}`, lineOf(s, 'network_mode')); link(address, `services.${other}`, 'runs-in', lineOf(s, 'network_mode')); }
|
|
191
|
+
|
|
192
|
+
// Settings.
|
|
193
|
+
for (const x of envEntries(get(s, 'environment'))) {
|
|
194
|
+
const secret = isSecretName(x.key);
|
|
195
|
+
const fromHost = x.value === undefined;
|
|
196
|
+
const computed = !fromHost && hasVar(x.value);
|
|
197
|
+
if (secretLiteral(x.key, x.value)) fact('secret-in-plain-env', `${where} has ${x.key} written in the Compose file, where anyone who can read it sees the value.`, x.line);
|
|
198
|
+
const says = fromHost ? `taken from the computer it starts on (${STARTS})` : secret ? (computed ? `a secret, ${later(x.value)} (not shown)` : 'a secret-looking setting, written in the file (not shown)') : computed ? `${short(x.value)} (${later(x.value)})` : `a setting: ${x.value === '' ? '(empty)' : short(x.value)}`;
|
|
199
|
+
know(x.key, says, x.line, { setting: true, ...(secret ? { secret: true } : {}), ...(fromHost || computed ? { computed: true } : {}) });
|
|
200
|
+
setting({ name: x.key, source: fromHost ? 'variable' : computed ? 'computed' : 'literal', secret, line: x.line, ...(computed || fromHost ? { computed: true } : {}), ...(!secret && !computed && !fromHost ? { default: x.value === '' ? '(empty)' : short(x.value) } : {}) });
|
|
201
|
+
if (x.value) for (const other of servicesNamed(x.key, x.value, serviceNames)) link(address, `services.${other}`, 'sends-to', x.line);
|
|
202
|
+
}
|
|
203
|
+
const envFiles = get(s, 'env_file');
|
|
204
|
+
for (const f of list(envFiles)) {
|
|
205
|
+
const p = f.t === 'map' ? str(get(f, 'path')) : str(f);
|
|
206
|
+
const optional = f.t === 'map' && str(get(f, 'required')) === 'false';
|
|
207
|
+
know('Reads settings from', `the file ${p}${optional ? ' (if it exists)' : ''}`, f.line);
|
|
208
|
+
}
|
|
209
|
+
for (const sec of list(get(s, 'secrets'))) {
|
|
210
|
+
const sn = sec.t === 'map' ? str(get(sec, 'source')) : str(sec);
|
|
211
|
+
const target = sec.t === 'map' ? str(get(sec, 'target')) : undefined;
|
|
212
|
+
know('Reads the secret', `${sn} (at ${target?.startsWith('/') ? target : `/run/secrets/${target ?? sn}`}, only its name is shown)`, sec.line, { secret: true });
|
|
213
|
+
link(address, `secrets.${sn}`, 'reads-from', sec.line);
|
|
214
|
+
}
|
|
215
|
+
for (const c of list(get(s, 'configs'))) {
|
|
216
|
+
const cn = c.t === 'map' ? str(get(c, 'source')) : str(c);
|
|
217
|
+
const target = c.t === 'map' ? str(get(c, 'target')) : undefined;
|
|
218
|
+
know('Reads the config', `${cn}${target ? ` (at ${target})` : ''}`, c.line);
|
|
219
|
+
link(address, `configs.${cn}`, 'reads-from', c.line);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Files and volumes.
|
|
223
|
+
for (const v of list(get(s, 'volumes'))) {
|
|
224
|
+
let source, target, ro = false, type;
|
|
225
|
+
if (v.t === 'map') { source = str(get(v, 'source')); target = str(get(v, 'target')); ro = str(get(v, 'read_only')) === 'true'; type = str(get(v, 'type')); }
|
|
226
|
+
else {
|
|
227
|
+
const parts = String(scalar(v) ?? '').split(':');
|
|
228
|
+
if (parts.length === 1) target = parts[0];
|
|
229
|
+
else { source = parts[0]; target = parts[1]; ro = /(^|,)ro(,|$)/.test(parts[2] ?? ''); }
|
|
230
|
+
// A Windows drive letter (C:\x) is part of the source.
|
|
231
|
+
if (/^[A-Za-z]$/.test(parts[0]) && parts.length >= 3) { source = `${parts[0]}:${parts[1]}`; target = parts[2]; ro = /(^|,)ro(,|$)/.test(parts[3] ?? ''); }
|
|
232
|
+
}
|
|
233
|
+
const isNamed = source && !/^[./~$]|^[A-Za-z]:/.test(source) && type !== 'bind';
|
|
234
|
+
let says;
|
|
235
|
+
if (!source) says = type === 'tmpfs' ? 'a scratch folder in memory' : 'a volume of its own (no name: Docker makes one)';
|
|
236
|
+
else if (isNamed) { says = `the volume ${source}`; link(address, `volumes.${source}`, 'uses', v.line); }
|
|
237
|
+
else says = `the folder ${source} from the computer it runs on`;
|
|
238
|
+
know(`Keeps ${target}`, `in ${says}${ro ? ' (read-only)' : ''}`, v.line);
|
|
239
|
+
if (source && /docker\.sock$/.test(source)) fact('privileged-container', `${where} can reach the Docker socket (${source}), which lets it control every container on the computer.`, v.line);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// What it waits for.
|
|
243
|
+
const dep = get(s, 'depends_on');
|
|
244
|
+
const deps = dep?.t === 'map' ? dep.entries.map((x) => ({ name: x.key, cond: str(get(x.value, 'condition')), line: x.line })) : list(dep).map((x) => ({ name: str(x), cond: undefined, line: x.line }));
|
|
245
|
+
for (const x of deps) {
|
|
246
|
+
info.after.push(x);
|
|
247
|
+
link(address, `services.${x.name}`, 'uses', x.line);
|
|
248
|
+
}
|
|
249
|
+
if (deps.length) know('Starts after', listWords(deps.map((x) => `${x.name}${x.cond === 'service_healthy' ? ' (once it is healthy)' : x.cond === 'service_completed_successfully' ? ' (once it has finished successfully)' : ''}`)), lineOf(s, 'depends_on'));
|
|
250
|
+
for (const nx of list(get(s, 'networks')).length ? list(get(s, 'networks')) : get(s, 'networks')?.entries?.map((x) => ({ t: 'str', v: x.key, line: x.line })) ?? []) {
|
|
251
|
+
const nn = str(nx);
|
|
252
|
+
if (nn) { know('On the network', nn, nx.line); if (networks.has(nn)) link(address, `networks.${nn}`, 'runs-in', nx.line); }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Health, restarts, and who it runs as.
|
|
256
|
+
const hc = get(s, 'healthcheck');
|
|
257
|
+
if (hc) {
|
|
258
|
+
const t = testWords(get(hc, 'test'));
|
|
259
|
+
if (str(get(hc, 'disable')) === 'true' || t === null) know('Health check', 'turned off', lineOf(s, 'healthcheck'));
|
|
260
|
+
else know('Checks its health with', `${short(t ?? '', 100)}${str(get(hc, 'interval')) ? `, every ${str(get(hc, 'interval'))}` : ''}`, lineOf(s, 'healthcheck'));
|
|
261
|
+
}
|
|
262
|
+
const restart = str(get(s, 'restart')) ?? str(get(get(deploy, 'restart_policy'), 'condition'));
|
|
263
|
+
if (restart) know('Restarts', RESTART[restart.split(':')[0]] ?? restart, lineOf(s, 'restart', lineOf(deploy, 'restart_policy')));
|
|
264
|
+
const user = str(get(s, 'user'));
|
|
265
|
+
if (user) {
|
|
266
|
+
const root = /^(root|0)(:.*)?$/.test(user);
|
|
267
|
+
know('Runs as', root ? 'root, the user that can do anything' : `the user ${user}`, lineOf(s, 'user'));
|
|
268
|
+
if (root) fact('runs-as-root', `${where} runs as root (user: ${user}).`, lineOf(s, 'user'));
|
|
269
|
+
}
|
|
270
|
+
if (str(get(s, 'privileged')) === 'true') { know('Privileged', 'yes: it can do almost anything on the computer', lineOf(s, 'privileged')); fact('privileged-container', `${where} is privileged (privileged: true), so it can do almost anything on the computer it runs on.`, lineOf(s, 'privileged')); }
|
|
271
|
+
const caps = list(get(s, 'cap_add')).map(str);
|
|
272
|
+
if (caps.some((c) => /^(ALL|SYS_ADMIN|CAP_SYS_ADMIN)$/i.test(c))) fact('privileged-container', `${where} adds the ${caps.filter((c) => /ALL|SYS_ADMIN/i.test(c)).join(' and ')} capabilit${caps.length === 1 ? 'y' : 'ies'}, which gives it nearly the power of the computer itself.`, lineOf(s, 'cap_add'));
|
|
273
|
+
if (str(get(s, 'pid')) === 'host') fact('privileged-container', `${where} shares every process on the computer (pid: host).`, lineOf(s, 'pid'));
|
|
274
|
+
const lim = get(get(deploy, 'resources'), 'limits'), res = get(get(deploy, 'resources'), 'reservations');
|
|
275
|
+
const amount = (m) => listWords([str(get(m, 'cpus')) && cpuWords(str(get(m, 'cpus'))), str(get(m, 'memory')) && `${memWords(str(get(m, 'memory')))} of memory`].filter(Boolean));
|
|
276
|
+
if (res && amount(res)) know('Asks for', amount(res), lineOf(get(deploy, 'resources'), 'reservations'));
|
|
277
|
+
if (lim && amount(lim)) know('Can use at most', amount(lim), lineOf(get(deploy, 'resources'), 'limits'));
|
|
278
|
+
else if (str(get(s, 'mem_limit')) || str(get(s, 'cpus'))) know('Can use at most', listWords([str(get(s, 'cpus')) && cpuWords(str(get(s, 'cpus'))), str(get(s, 'mem_limit')) && `${memWords(str(get(s, 'mem_limit')))} of memory`].filter(Boolean)), lineOf(s, 'mem_limit', lineOf(s, 'cpus')));
|
|
279
|
+
if (info.profiles.length) know('Only starts with', `the profile${info.profiles.length === 1 ? '' : 's'} ${orWords(info.profiles)}`, lineOf(s, 'profiles'));
|
|
280
|
+
|
|
281
|
+
things.push({ kind: 'resource', name: address, label: `Service ${name}`, resourceType: 'compose-service', address, file, lines: [e.line, Math.max(e.line, lastLine(s))], knows, choices: [] });
|
|
282
|
+
starts.set(address, { name, line: e.line, info });
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ── The order things start: one Steps card ──
|
|
286
|
+
const steps = [];
|
|
287
|
+
for (const d of declared.filter((x) => x.kind === 'networks' || x.kind === 'volumes')) {
|
|
288
|
+
steps.push({ kind: 'call', says: d.external ? `Uses the existing ${d.kind.slice(0, -1)} ${d.name} (made elsewhere)` : `Creates the ${d.kind.slice(0, -1)} ${d.name}`, code: `${d.kind}:\n ${d.name}`, line: d.line });
|
|
289
|
+
}
|
|
290
|
+
const ids = [...starts.keys()];
|
|
291
|
+
// depends_on decides the order; network_mode: service:x also needs x running first.
|
|
292
|
+
const edges = [...starts].flatMap(([a, x]) => x.info.after.map((d) => [a, `services.${d.name}`]));
|
|
293
|
+
for (const l of links) if (l.kind === 'runs-in' && starts.has(l.from) && starts.has(l.to)) edges.push([l.from, l.to]);
|
|
294
|
+
for (const a of topoOrder(ids, edges)) {
|
|
295
|
+
const { name, line, info } = starts.get(a);
|
|
296
|
+
const what = info.build ? `Builds and starts ${name} (from ${info.build === '.' ? 'this folder' : info.build})` : `Starts ${name}${info.image ? ` (${imageShort(info.image)})` : ''}`;
|
|
297
|
+
const after = info.after.filter((x) => starts.has(`services.${x.name}`)).map((x) => `${x.name} ${x.cond === 'service_healthy' ? 'is healthy' : x.cond === 'service_completed_successfully' ? 'has finished successfully' : 'has started'}`);
|
|
298
|
+
let step = { kind: 'call', says: `${what}${after.length ? `, once ${listWords(after)}` : ''}`, code: `services:\n ${name}:`, line };
|
|
299
|
+
if (info.profiles.length) step = { kind: 'branch', says: `Is the profile ${orWords(info.profiles)} turned on?`, code: `profiles: [${info.profiles.join(', ')}]`, line, children: [step] };
|
|
300
|
+
steps.push(step);
|
|
301
|
+
}
|
|
302
|
+
const base = file.slice(file.lastIndexOf('/') + 1);
|
|
303
|
+
const items = [];
|
|
304
|
+
if (starts.size) {
|
|
305
|
+
const first = Math.min(...steps.map((x) => x.line)), last = Math.max(...things.map((t) => t.lines[1]));
|
|
306
|
+
items.push({
|
|
307
|
+
id: `up:${first}`, name: 'up', label: `Starting ${base}`, title: `What starting ${base} does, in order`, line: first, endLine: last,
|
|
308
|
+
inputs: [], returns: null, provenance: 'inferred-from-code', kind: 'function', status: 'signature-only', steps, stepsMore: 0, stepsReadable: 1,
|
|
309
|
+
says: `Starting ${base} runs ${starts.size} service${starts.size === 1 ? '' : 's'}, each after the ones it waits for.`,
|
|
310
|
+
headline: `Starting ${base}: ${starts.size} service${starts.size === 1 ? '' : 's'}.`, guards: [], unread: [],
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
const nameNode = get(root, 'name');
|
|
314
|
+
return { items, things, settings, facts, links, permissions: [], unknowns, purpose: text(nameNode) ?? null };
|
|
315
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Words for running containers, shared by the Kubernetes and Docker Compose readers (spec section 12): an image
|
|
2
|
+
// reference in words ("frontend (no tag, so whatever latest is)"), CPU and memory ("0.1 CPU", "128 MiB"), which
|
|
3
|
+
// settings hold secrets, and which other services a setting's value names ("redis:6379" -> the service redis).
|
|
4
|
+
// Deterministic and browser-safe; no regex here can backtrack.
|
|
5
|
+
import { SECRET_NAME } from './infra-words.mjs';
|
|
6
|
+
import { isSecretKey } from './infra-cloud.mjs';
|
|
7
|
+
|
|
8
|
+
/** `${VAR}` (Compose) or `$(VAR)` (Kubernetes): a value filled in when it starts. */
|
|
9
|
+
export const hasVar = (s) => /\$\{[A-Za-z_]|\$[A-Za-z_]|\$\([A-Za-z_]/.test(String(s ?? ''));
|
|
10
|
+
|
|
11
|
+
/** The parts of an image reference: 'gcr.io/proj/api:1.2@sha256:…' -> { name: 'api', repo, tag: '1.2', digest }. */
|
|
12
|
+
export function parseImage(ref) {
|
|
13
|
+
const s = String(ref ?? '').trim();
|
|
14
|
+
const at = s.indexOf('@');
|
|
15
|
+
const digest = at >= 0 ? s.slice(at + 1) : null;
|
|
16
|
+
const noDigest = at >= 0 ? s.slice(0, at) : s;
|
|
17
|
+
const slash = noDigest.lastIndexOf('/');
|
|
18
|
+
const colon = noDigest.lastIndexOf(':');
|
|
19
|
+
const tag = colon > slash ? noDigest.slice(colon + 1) : null;
|
|
20
|
+
const repo = colon > slash ? noDigest.slice(0, colon) : noDigest;
|
|
21
|
+
return { ref: s, repo, name: repo.slice(repo.lastIndexOf('/') + 1), tag, digest, computed: hasVar(s) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** An image reference short enough for a step: a digest becomes ", pinned". */
|
|
25
|
+
export function imageShort(ref) {
|
|
26
|
+
const im = parseImage(ref);
|
|
27
|
+
return im.digest ? `${im.repo}${im.tag ? `:${im.tag}` : ''}, pinned` : im.ref;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The image a container runs, in words. */
|
|
31
|
+
export function imageWords(ref, later = 'worked out when it starts') {
|
|
32
|
+
const im = parseImage(ref);
|
|
33
|
+
if (im.computed) return `${im.ref} (${later})`;
|
|
34
|
+
if (im.digest) return `${im.ref} (pinned to one exact image)`;
|
|
35
|
+
if (!im.tag) return `${im.ref} (no tag, so whatever "latest" is when it starts)`;
|
|
36
|
+
return im.ref;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What a fact says about an image that is not pinned to a digest, or null when it is pinned (or filled in later). */
|
|
40
|
+
export function imageNotPinned(ref, where) {
|
|
41
|
+
const im = parseImage(ref);
|
|
42
|
+
if (im.digest || im.computed || !im.repo) return null;
|
|
43
|
+
if (!im.tag || im.tag === 'latest') return `${where} runs ${im.ref}${im.tag ? '' : ' (no tag, so "latest")'}, which can point to a different image every time it starts.`;
|
|
44
|
+
return `${where} runs ${im.ref} without a pinned digest (@sha256:…), so the tag can be moved to a different image.`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Kubernetes CPU in words: '100m' -> '0.1 CPU', '2' -> '2 CPUs'. */
|
|
48
|
+
export function cpuWords(q) {
|
|
49
|
+
const s = String(q ?? '').trim();
|
|
50
|
+
let n = null;
|
|
51
|
+
if (/^\d+m$/.test(s)) n = Number(s.slice(0, -1)) / 1000;
|
|
52
|
+
else if (/^\d+(\.\d+)?$/.test(s)) n = Number(s);
|
|
53
|
+
if (n == null) return `${s} CPU`;
|
|
54
|
+
return `${n} CPU${n > 1 ? 's' : ''}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const MEM = { Ki: 'KiB', Mi: 'MiB', Gi: 'GiB', Ti: 'TiB', K: 'KB', k: 'KB', M: 'MB', G: 'GB', T: 'TB', m: 'MB', g: 'GB', b: 'bytes', kb: 'KB', mb: 'MB', gb: 'GB' };
|
|
58
|
+
/** Memory or storage in words: '64Mi' -> '64 MiB', '1G' -> '1 GB', '512m' (Compose) -> '512 MB'. */
|
|
59
|
+
export function memWords(q) {
|
|
60
|
+
const s = String(q ?? '').trim();
|
|
61
|
+
const m = /^(\d+(?:\.\d+)?)\s*([A-Za-z]{0,2})$/.exec(s);
|
|
62
|
+
if (!m) return s;
|
|
63
|
+
if (!m[2]) return `${m[1]} bytes`;
|
|
64
|
+
return MEM[m[2]] ? `${m[1]} ${MEM[m[2]]}` : s;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A setting's name that says it holds a secret (its value is never shown). */
|
|
68
|
+
export const isSecretName = (name) => isSecretKey(name) || SECRET_NAME.test(String(name ?? ''));
|
|
69
|
+
|
|
70
|
+
/** True when a literal value written for a secret-looking name is a real value, not a placeholder or a flag. */
|
|
71
|
+
export function secretLiteral(name, value) {
|
|
72
|
+
if (!isSecretKey(name) || value == null) return false;
|
|
73
|
+
const v = String(value).trim();
|
|
74
|
+
if (!v || hasVar(v)) return false;
|
|
75
|
+
return !/^(true|false|yes|no|on|off|\d+|enabled|disabled|none|null|changeme|<.*>)$/i.test(v);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const HOST_KEY = /(host|hostname|addr|address|url|uri|server|servers|endpoint|dsn|broker|brokers|connection|conn)$/i;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The names of services a setting's value points at, from exact names only: 'redis:6379', 'http://api:3000/x',
|
|
82
|
+
* 'postgres://user@db:5432/app', or a bare 'db' under a key like DB_HOST. `known` is the set of service names (null: any name, for matching across files later).
|
|
83
|
+
*/
|
|
84
|
+
export function servicesNamed(key, value, known) {
|
|
85
|
+
const out = [];
|
|
86
|
+
const v = String(value ?? '').trim();
|
|
87
|
+
const add = (h) => { const host = String(h).toLowerCase(); if ((!known || known.has(host)) && !out.includes(host) && !/^(localhost|0\.0\.0\.0|127\.0\.0\.1)$/.test(host)) out.push(host); };
|
|
88
|
+
for (const part of v.split(/[,\s]+/)) {
|
|
89
|
+
if (!part) continue;
|
|
90
|
+
const url = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/:?#]+)/i.exec(part);
|
|
91
|
+
if (url) { add(url[1]); continue; }
|
|
92
|
+
const hp = /^([A-Za-z0-9][\w.-]*):\d+$/.exec(part);
|
|
93
|
+
if (hp) { add(hp[1]); continue; }
|
|
94
|
+
if (HOST_KEY.test(String(key ?? '').replace(/[_-]/g, '')) && /^[A-Za-z0-9][\w.-]*$/.test(part)) add(part);
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A command (a list or a string) as one line: ['node', 'server.js'] -> 'node server.js'. */
|
|
100
|
+
export const commandText = (xs) => (Array.isArray(xs) ? xs.map((x) => (/\s/.test(String(x)) ? `"${x}"` : String(x))).join(' ') : String(xs ?? ''));
|