@ductape/cli 0.5.8 → 0.6.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/README.md CHANGED
@@ -128,3 +128,28 @@ npm test
128
128
  ## Changelog
129
129
 
130
130
  See [CHANGELOG.md](./CHANGELOG.md).
131
+
132
+ ### Functions inside deployed APIs
133
+
134
+ `ductape deploy deployments get <deploymentId>` and deployment list responses include
135
+ `servedFunctions` for service deployments. Ductape automatically queries the signed
136
+ SDK runtime inventory after the service's health checks pass. Each inventory names
137
+ its cloud revision, release hash, traffic allocation, function namespaces, independent
138
+ function versions, operation names and contract hashes. Workbench shows the same
139
+ inventory in the deployment detail and MCP returns it through `ductape_deploy_status`.
140
+
141
+ A discovered handler is **deployed**, with function verification **unverified**.
142
+ Discovery never runs a business operation, changes invocation routing, or creates a
143
+ standalone deployment. Health checks do not prove individual function correctness.
144
+ Replacing a revision removes its functions from the serving view; canaries show both
145
+ revisions and rollback restores the previous revision's recorded inventory.
146
+
147
+ Use an SDK with signed runtime inventory support and expose its portable HTTP handler.
148
+ NestJS does this through its module's portable function controller (with
149
+ `NestFactory.create(..., { rawBody: true })`). Service `DUCTAPE_ACCESS_KEY` must reference
150
+ an accessible workspace secret. Discovery reuses provider authorization and private
151
+ verification transports, across supported service providers. Missing support or failed
152
+ discovery is reported as `unavailable`, not as zero functions, and does not fail an
153
+ otherwise healthy generic HTTP service. Existing deployments need a redeploy to collect
154
+ an inventory. Function contracts retain their own versions independently of the API
155
+ version.
@@ -0,0 +1,58 @@
1
+ export declare function runUiCreate(name: string, opts: {
2
+ framework?: string;
3
+ description?: string;
4
+ json?: boolean;
5
+ }): Promise<void>;
6
+ export declare function runUiValidate(name: string | undefined, opts: {
7
+ typecheck?: boolean;
8
+ json?: boolean;
9
+ }): Promise<void>;
10
+ export declare function runUiPack(name: string, opts: {
11
+ out?: string;
12
+ json?: boolean;
13
+ }): Promise<void>;
14
+ export declare function runUiPublish(name: string, opts: {
15
+ typecheck?: boolean;
16
+ dryRun?: boolean;
17
+ json?: boolean;
18
+ }): Promise<void>;
19
+ export declare function runUiList(opts: {
20
+ search?: string;
21
+ json?: boolean;
22
+ }): Promise<void>;
23
+ export declare function runUiInspect(ref: string, opts: {
24
+ json?: boolean;
25
+ }): Promise<void>;
26
+ export declare function runUiDeprecate(ref: string, opts: {
27
+ reason: string;
28
+ replacement?: string;
29
+ json?: boolean;
30
+ }): Promise<void>;
31
+ export declare function runUiUndeprecate(ref: string, opts: {
32
+ json?: boolean;
33
+ }): Promise<void>;
34
+ export declare function runUiAdd(ref: string, opts: {
35
+ ignorePeers?: boolean;
36
+ json?: boolean;
37
+ }): Promise<void>;
38
+ export declare function runUiInstall(opts: {
39
+ offline?: boolean;
40
+ json?: boolean;
41
+ }): Promise<void>;
42
+ export declare function runUiUpdate(name: string, opts: {
43
+ to?: string;
44
+ ignorePeers?: boolean;
45
+ json?: boolean;
46
+ }): Promise<void>;
47
+ export declare function runUiRemove(name: string, opts: {
48
+ json?: boolean;
49
+ }): Promise<void>;
50
+ export declare function runUiVerify(opts: {
51
+ skipPeers?: boolean;
52
+ json?: boolean;
53
+ }): Promise<void>;
54
+ export declare function runUiCheck(name: string | undefined, opts: {
55
+ product?: string;
56
+ env?: string;
57
+ json?: boolean;
58
+ }): Promise<void>;
@@ -0,0 +1,359 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { findProjectConfig } from '../lib/config.js';
4
+ import { UI_FRAMEWORKS } from '../lib/ui/manifest.js';
5
+ import { listAuthoredUi, scaffoldUi, uiProjectRoot, UI_DIR } from '../lib/ui/scaffold.js';
6
+ import { packUiDirectory, typecheckUiDirectory, validateUiDirectory } from '../lib/ui/validate.js';
7
+ import { parseRef, UiRegistry } from '../lib/ui/registry.js';
8
+ import { requireWorkspaceContext } from '../lib/workspace-context.js';
9
+ import { applyPlan, checkPeers, installedRoot, LOCKFILE, planAdd, planInstall, planRemove, planUpdate, readLockfile, syncImports, verifyInstalled, writeLockfile } from '../lib/ui/consume.js';
10
+ import { checkRequirements, platformLookup } from '../lib/ui/check.js';
11
+ const root = () => uiProjectRoot(findProjectConfig()?.dir);
12
+ function formatDiagnostics(name, diagnostics) {
13
+ if (diagnostics.length === 0)
14
+ return `${name}: ok`;
15
+ const lines = diagnostics.map((d) => ` ${d.severity === 'error' ? 'error' : 'warn '} ${d.code}${d.file ? ` ${d.file}${d.line ? `:${d.line}` : ''}` : ''} ${d.message}`);
16
+ const errors = diagnostics.filter((d) => d.severity === 'error').length;
17
+ return `${name}: ${errors > 0 ? `${errors} ${errors === 1 ? 'error' : 'errors'}` : 'ok'}\n${lines.join('\n')}`;
18
+ }
19
+ export async function runUiCreate(name, opts) {
20
+ const framework = (opts.framework ?? 'react');
21
+ if (!UI_FRAMEWORKS.includes(framework)) {
22
+ throw new Error(`Framework "${framework}" is not supported yet. Supported: ${UI_FRAMEWORKS.join(', ')}`);
23
+ }
24
+ const projectRoot = root();
25
+ const created = scaffoldUi(projectRoot, name, framework, opts.description);
26
+ const relative = path.relative(projectRoot, created.dir) || '.';
27
+ if (opts.json) {
28
+ console.log(JSON.stringify({ name, framework, dir: relative, files: created.files }, null, 2));
29
+ return;
30
+ }
31
+ console.log(`Created ${relative}\n${created.files.map((file) => ` ${file}`).join('\n')}\n\nNext: list the actions it needs in ui.json, then run \`ductape ui validate ${name}\`.`);
32
+ }
33
+ export async function runUiValidate(name, opts) {
34
+ const projectRoot = root();
35
+ const names = name ? [name] : listAuthoredUi(projectRoot);
36
+ if (names.length === 0)
37
+ throw new Error(`No UI pieces found under ${UI_DIR}. Create one with \`ductape ui create <name>\`.`);
38
+ const results = names.map((piece) => {
39
+ const dir = path.join(projectRoot, UI_DIR, piece);
40
+ if (!fs.existsSync(dir))
41
+ return { ok: false, dir, files: [], diagnostics: [{ severity: 'error', code: 'UI_NOT_FOUND', message: `${path.join(UI_DIR, piece)} does not exist` }] };
42
+ const result = validateUiDirectory(dir);
43
+ if (opts.typecheck && result.ok) {
44
+ const typeErrors = typecheckUiDirectory(dir, projectRoot);
45
+ result.diagnostics.push(...typeErrors);
46
+ result.ok = typeErrors.length === 0;
47
+ }
48
+ return result;
49
+ });
50
+ if (opts.json)
51
+ console.log(JSON.stringify({ ok: results.every((r) => r.ok), results: results.map((r) => ({ ...r, dir: path.relative(projectRoot, r.dir) })) }, null, 2));
52
+ else
53
+ console.log(results.map((r, i) => formatDiagnostics(names[i], r.diagnostics)).join('\n\n'));
54
+ if (!results.every((r) => r.ok))
55
+ process.exitCode = 1;
56
+ }
57
+ export async function runUiPack(name, opts) {
58
+ const projectRoot = root();
59
+ const dir = path.join(projectRoot, UI_DIR, name);
60
+ if (!fs.existsSync(dir))
61
+ throw new Error(`${path.join(UI_DIR, name)} does not exist`);
62
+ const { validation, pack } = packUiDirectory(dir);
63
+ if (!pack) {
64
+ if (opts.json)
65
+ console.log(JSON.stringify({ ok: false, diagnostics: validation.diagnostics }, null, 2));
66
+ else
67
+ console.log(formatDiagnostics(name, validation.diagnostics));
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ const out = path.resolve(opts.out ?? path.join(projectRoot, 'ductape', '.ui-packs', `${pack.manifest.name}@${pack.manifest.version}.json`));
72
+ fs.mkdirSync(path.dirname(out), { recursive: true });
73
+ fs.writeFileSync(out, `${JSON.stringify(pack, null, 2)}\n`);
74
+ const summary = { name: pack.manifest.name, version: pack.manifest.version, framework: pack.manifest.framework, files: pack.files.length, integrity: pack.integrity, out: path.relative(projectRoot, out) };
75
+ if (opts.json)
76
+ console.log(JSON.stringify(summary, null, 2));
77
+ else
78
+ console.log(`Packed ${summary.name}@${summary.version} (${summary.files} files)\n ${summary.integrity}\n ${summary.out}`);
79
+ }
80
+ // ---- Registry: the workspace's published UI pieces ---------------------------------------------------------------
81
+ const registry = () => new UiRegistry(requireWorkspaceContext());
82
+ const deprecationNote = (v) => v.deprecation ? `deprecated: ${v.deprecation.reason ?? 'no reason given'}${v.deprecation.replacement ? ` (use ${v.deprecation.replacement})` : ''}` : '';
83
+ export async function runUiPublish(name, opts) {
84
+ const projectRoot = root();
85
+ const dir = path.join(projectRoot, UI_DIR, name);
86
+ if (!fs.existsSync(dir))
87
+ throw new Error(`${path.join(UI_DIR, name)} does not exist`);
88
+ const { validation, pack } = packUiDirectory(dir);
89
+ const typeErrors = pack && opts.typecheck ? typecheckUiDirectory(dir, projectRoot) : [];
90
+ if (!pack || typeErrors.length > 0) {
91
+ const diagnostics = [...validation.diagnostics, ...typeErrors];
92
+ if (opts.json)
93
+ console.log(JSON.stringify({ ok: false, diagnostics }, null, 2));
94
+ else
95
+ console.log(`${formatDiagnostics(name, diagnostics)}\n\nNothing was published.`);
96
+ process.exitCode = 1;
97
+ return;
98
+ }
99
+ const label = `${pack.manifest.name}@${pack.manifest.version}`;
100
+ if (opts.dryRun) {
101
+ const summary = { dryRun: true, name: pack.manifest.name, version: pack.manifest.version, files: pack.files.length, integrity: pack.integrity };
102
+ if (opts.json)
103
+ console.log(JSON.stringify(summary, null, 2));
104
+ else
105
+ console.log(`Would publish ${label} (${pack.files.length} files)\n ${pack.integrity}`);
106
+ return;
107
+ }
108
+ const result = await registry().publish(pack);
109
+ if (opts.json) {
110
+ console.log(JSON.stringify(result, null, 2));
111
+ return;
112
+ }
113
+ const lines = [result.created ? `Published ${label} (${result.version.files} files)` : `${label} is already published with this exact content; nothing changed`, ` ${result.version.integrity}`];
114
+ for (const warning of result.warnings)
115
+ lines.push(` warning: ${warning}`);
116
+ console.log(lines.join('\n'));
117
+ }
118
+ export async function runUiList(opts) {
119
+ const pieces = await registry().list(opts.search);
120
+ if (opts.json) {
121
+ console.log(JSON.stringify(pieces, null, 2));
122
+ return;
123
+ }
124
+ if (pieces.length === 0) {
125
+ console.log(opts.search ? `No UI pieces match "${opts.search}".` : 'This workspace has not published any UI pieces yet. Publish one with `ductape ui publish <name>`.');
126
+ return;
127
+ }
128
+ const width = Math.max(...pieces.map((p) => p.name.length));
129
+ console.log(pieces.map((p) => `${p.name.padEnd(width)} ${(p.latest ?? 'no release').padEnd(12)} ${p.framework.padEnd(6)} ${p.versions} ${p.versions === 1 ? 'version' : 'versions'}${p.description ? ` ${p.description}` : ''}`).join('\n'));
130
+ }
131
+ export async function runUiInspect(ref, opts) {
132
+ const { name, version } = parseRef(ref);
133
+ const reg = registry();
134
+ if (version) {
135
+ const detail = await reg.getVersion(name, version);
136
+ if (opts.json) {
137
+ console.log(JSON.stringify(detail, null, 2));
138
+ return;
139
+ }
140
+ const manifest = detail.manifest;
141
+ const lines = [
142
+ `${detail.name}@${detail.version} ${detail.framework}${detail.deprecated ? ` ${deprecationNote(detail)}` : ''}`,
143
+ ...(detail.description ? [` ${detail.description}`] : []),
144
+ ` integrity ${detail.integrity}`,
145
+ ` published ${detail.publishedAt} by ${detail.publishedBy}`,
146
+ ` entry ${manifest.entry}`,
147
+ ` peers ${Object.entries(manifest.peerDependencies ?? {}).map(([k, v]) => `${k} ${v}`).join(', ') || 'none'}`,
148
+ ` uses ${Object.entries(manifest.uses ?? {}).map(([k, v]) => `${k}@${v}`).join(', ') || 'none'}`,
149
+ ` requires ${[
150
+ ...(manifest.requires?.actions ?? []).map((a) => `action ${a.app}/${a.action}`),
151
+ ...(manifest.requires?.features ?? []).map((f) => `feature ${f}`),
152
+ ...(manifest.requires?.sessions ?? []).map((s) => `session ${s}`),
153
+ ].join(', ') || 'nothing'}`,
154
+ ` files`,
155
+ ...detail.fileList.map((f) => ` ${f.path} ${f.bytes} B`),
156
+ ];
157
+ console.log(lines.join('\n'));
158
+ return;
159
+ }
160
+ const detail = await reg.get(name);
161
+ if (opts.json) {
162
+ console.log(JSON.stringify(detail, null, 2));
163
+ return;
164
+ }
165
+ console.log([
166
+ `${detail.name} ${detail.framework} latest ${detail.latest ?? 'none (every release is deprecated or a pre-release)'}`,
167
+ ...detail.versions.map((v) => ` ${v.version.padEnd(14)} ${v.publishedAt} ${v.integrity.slice(0, 19)}...${v.deprecated ? ` ${deprecationNote(v)}` : ''}`),
168
+ ].join('\n'));
169
+ }
170
+ export async function runUiDeprecate(ref, opts) {
171
+ const { name, version } = parseRef(ref, true);
172
+ if (opts.replacement)
173
+ parseRef(`${name}@${opts.replacement}`, true);
174
+ const result = await registry().deprecate(name, version, opts.reason, opts.replacement);
175
+ if (opts.json)
176
+ console.log(JSON.stringify(result, null, 2));
177
+ else
178
+ console.log(`${name}@${version} is deprecated. Applications that already pinned it keep building; \`latest\` no longer picks it.`);
179
+ }
180
+ export async function runUiUndeprecate(ref, opts) {
181
+ const { name, version } = parseRef(ref, true);
182
+ const result = await registry().undeprecate(name, version);
183
+ if (opts.json)
184
+ console.log(JSON.stringify(result, null, 2));
185
+ else
186
+ console.log(`${name}@${version} is no longer deprecated.`);
187
+ }
188
+ // ---- Using UI pieces in an application ----------------------------------------------------------------------------
189
+ function applicationRoot() {
190
+ const projectRoot = root();
191
+ if (!fs.existsSync(path.join(projectRoot, 'package.json')))
192
+ throw new Error('Run this inside an application: no package.json was found');
193
+ return projectRoot;
194
+ }
195
+ /** #ui/<name> needs a module resolution that reads package.json "imports". Says so when tsconfig.json clearly uses one that does not. */
196
+ function moduleResolutionWarning(projectRoot) {
197
+ const file = path.join(projectRoot, 'tsconfig.json');
198
+ if (!fs.existsSync(file))
199
+ return undefined;
200
+ const found = /"moduleResolution"\s*:\s*"([^"]+)"/i.exec(fs.readFileSync(file, 'utf8'))?.[1]?.toLowerCase();
201
+ return found && ['node', 'node10', 'classic'].includes(found)
202
+ ? `tsconfig.json uses "moduleResolution": "${found}", which does not read package.json "imports"; set it to "bundler" (or "node16"/"nodenext") so TypeScript resolves #ui/ imports`
203
+ : undefined;
204
+ }
205
+ function printPeerProblems(problems) {
206
+ for (const p of problems)
207
+ console.log(` ${p.severity === 'error' ? 'error' : 'warn '} ${p.code} ${p.message}`);
208
+ }
209
+ export async function runUiAdd(ref, opts) {
210
+ const { name, version } = parseRef(ref);
211
+ const projectRoot = applicationRoot();
212
+ const plan = await planAdd(registry(), readLockfile(projectRoot), name, version ?? 'latest');
213
+ const added = [...plan.write.values()];
214
+ const peerProblems = checkPeers(projectRoot, added.map((p) => p.manifest));
215
+ const blocking = peerProblems.filter((p) => p.severity === 'error');
216
+ if (blocking.length > 0 && !opts.ignorePeers) {
217
+ if (opts.json)
218
+ console.log(JSON.stringify({ ok: false, peers: peerProblems }, null, 2));
219
+ else {
220
+ console.log(`${name} needs packages this application does not have. Nothing was added.`);
221
+ printPeerProblems(peerProblems);
222
+ }
223
+ process.exitCode = 1;
224
+ return;
225
+ }
226
+ if (added.length > 0)
227
+ applyPlan(projectRoot, plan);
228
+ else
229
+ syncImports(projectRoot, plan.lock);
230
+ if (added.length === 0 && plan.lock.pieces[name])
231
+ writeLockfile(projectRoot, plan.lock);
232
+ const tsWarning = moduleResolutionWarning(projectRoot);
233
+ const summary = {
234
+ ok: true,
235
+ added: added.map((p) => ({ name: p.manifest.name, version: p.manifest.version, integrity: p.integrity, direct: plan.lock.pieces[p.manifest.name].direct })),
236
+ warnings: [...plan.warnings, ...peerProblems.map((p) => p.message), ...(tsWarning ? [tsWarning] : [])],
237
+ import: `#ui/${name}`,
238
+ };
239
+ if (opts.json) {
240
+ console.log(JSON.stringify(summary, null, 2));
241
+ return;
242
+ }
243
+ if (added.length === 0)
244
+ console.log(`${name}@${plan.lock.pieces[name].version} is already added.`);
245
+ for (const a of summary.added)
246
+ console.log(`Added ${a.name}@${a.version}${a.direct ? '' : ' (used by another piece)'}`);
247
+ for (const w of summary.warnings)
248
+ console.log(` warning: ${w}`);
249
+ console.log(`\nImport it from '#ui/${name}'. The source is in ${path.join(UI_DIR, 'installed', name)}, pinned in ductape/ui.lock.json: commit both.`);
250
+ }
251
+ export async function runUiInstall(opts) {
252
+ const projectRoot = applicationRoot();
253
+ const { plan, restored } = await planInstall(projectRoot, opts.offline ? undefined : registry);
254
+ const changed = plan.write.size > 0 || plan.removed.length > 0;
255
+ if (changed)
256
+ applyPlan(projectRoot, plan);
257
+ const importsChanged = changed ? false : syncImports(projectRoot, plan.lock);
258
+ const result = { restored, removed: plan.removed, importsUpdated: importsChanged };
259
+ if (opts.json)
260
+ console.log(JSON.stringify(result, null, 2));
261
+ else if (!changed && !importsChanged)
262
+ console.log(`Everything matches ${LOCKFILE} (${Object.keys(plan.lock.pieces).length} pieces).`);
263
+ else {
264
+ for (const name of restored)
265
+ console.log(`Restored ${name}@${plan.lock.pieces[name].version}`);
266
+ for (const name of plan.removed)
267
+ console.log(`Removed ${name}: it is not in ${LOCKFILE}`);
268
+ if (importsChanged)
269
+ console.log('Updated package.json "imports".');
270
+ }
271
+ }
272
+ export async function runUiUpdate(name, opts) {
273
+ if (opts.to)
274
+ parseRef(`${name}@${opts.to}`);
275
+ const projectRoot = applicationRoot();
276
+ const plan = await planUpdate(registry(), readLockfile(projectRoot), name, opts.to ?? 'latest');
277
+ if (plan.from === plan.to) {
278
+ if (opts.json)
279
+ console.log(JSON.stringify({ updated: false, version: plan.to }, null, 2));
280
+ else
281
+ console.log(`${name} is already at ${plan.to}.`);
282
+ return;
283
+ }
284
+ const peerProblems = checkPeers(projectRoot, [...plan.write.values()].map((p) => p.manifest));
285
+ if (peerProblems.some((p) => p.severity === 'error') && !opts.ignorePeers) {
286
+ if (opts.json)
287
+ console.log(JSON.stringify({ ok: false, peers: peerProblems }, null, 2));
288
+ else {
289
+ console.log(`${name}@${plan.to} needs packages this application does not have. Nothing was changed.`);
290
+ printPeerProblems(peerProblems);
291
+ }
292
+ process.exitCode = 1;
293
+ return;
294
+ }
295
+ applyPlan(projectRoot, plan);
296
+ const result = { updated: true, from: plan.from, to: plan.to, written: [...plan.write.keys()], removed: plan.removed, warnings: plan.warnings };
297
+ if (opts.json)
298
+ console.log(JSON.stringify(result, null, 2));
299
+ else {
300
+ console.log(`Updated ${name} ${plan.from} -> ${plan.to}`);
301
+ for (const other of result.written.filter((n) => n !== name))
302
+ console.log(` added ${other}@${plan.lock.pieces[other].version}`);
303
+ for (const other of plan.removed)
304
+ console.log(` removed ${other} (no longer used)`);
305
+ for (const w of plan.warnings)
306
+ console.log(` warning: ${w}`);
307
+ }
308
+ }
309
+ export async function runUiRemove(name, opts) {
310
+ const projectRoot = applicationRoot();
311
+ const plan = planRemove(readLockfile(projectRoot), name);
312
+ applyPlan(projectRoot, plan);
313
+ if (opts.json)
314
+ console.log(JSON.stringify({ removed: plan.removed }, null, 2));
315
+ else
316
+ console.log(`Removed ${plan.removed.join(', ')}. Imports of #ui/${name} will no longer resolve.`);
317
+ }
318
+ export async function runUiVerify(opts) {
319
+ const projectRoot = applicationRoot();
320
+ const result = verifyInstalled(projectRoot, { peers: !opts.skipPeers });
321
+ if (opts.json)
322
+ console.log(JSON.stringify(result, null, 2));
323
+ else if (result.diagnostics.length === 0)
324
+ console.log(`ok: ${result.checked.length} ${result.checked.length === 1 ? 'piece matches' : 'pieces match'} ${LOCKFILE}`);
325
+ else
326
+ console.log(formatDiagnostics('installed UI pieces', result.diagnostics));
327
+ if (!result.ok)
328
+ process.exitCode = 1;
329
+ }
330
+ export async function runUiCheck(name, opts) {
331
+ const projectRoot = applicationRoot();
332
+ const linked = findProjectConfig()?.config;
333
+ const product = opts.product ?? linked?.product_tag;
334
+ const env = opts.env ?? linked?.env_slug;
335
+ if (!product || !env)
336
+ throw new Error('Name the product and environment with --product and --env, or run `ductape link` in this application');
337
+ const lock = readLockfile(projectRoot);
338
+ const names = name ? [name] : Object.keys(lock.pieces).sort();
339
+ if (name && !lock.pieces[name])
340
+ throw new Error(`${name} is not added to this application`);
341
+ if (names.length === 0)
342
+ throw new Error('No UI pieces are added to this application');
343
+ const pieces = names.map((piece) => {
344
+ const manifest = JSON.parse(fs.readFileSync(path.join(installedRoot(projectRoot), piece, 'ui.json'), 'utf8'));
345
+ return { name: piece, requires: manifest.requires };
346
+ });
347
+ const result = await checkRequirements(platformLookup(requireWorkspaceContext(), product, env), env, pieces);
348
+ if (opts.json)
349
+ console.log(JSON.stringify({ product, env, ...result }, null, 2));
350
+ else {
351
+ console.log(`${product} (${env})${result.envKnown ? '' : `: the product has no environment "${env}"`}`);
352
+ if (result.results.length === 0)
353
+ console.log(' The pieces declare no requirements.');
354
+ for (const r of result.results)
355
+ console.log(` ${r.status === 'ok' ? 'ok ' : r.status === 'missing' ? 'missing' : 'unknown'} ${r.piece}: ${r.kind} ${r.ref}${r.detail ? ` (${r.detail})` : ''}`);
356
+ }
357
+ if (!result.ok)
358
+ process.exitCode = 1;
359
+ }
package/dist/index.js CHANGED
@@ -20,6 +20,7 @@ import { runDb, runDbActions, runDbContext } from './commands/db.js';
20
20
  import { runComponentActions } from './commands/component-actions.js';
21
21
  import { runDbMigrate, runDbMigrateStatus, runDbMigrateRollback, runDbMigrateBaseline } from './commands/db-migrate.js';
22
22
  import { runFeaturesSync, runFeaturesValidate } from './commands/features-sync.js';
23
+ import { runUiAdd, runUiCheck, runUiCreate, runUiDeprecate, runUiInspect, runUiInstall, runUiList, runUiPack, runUiPublish, runUiRemove, runUiUndeprecate, runUiUpdate, runUiValidate, runUiVerify } from './commands/ui.js';
23
24
  import { runSessionsValidate } from './commands/sessions-validate.js';
24
25
  import { runRateLimits } from './commands/rate-limits.js';
25
26
  import { runDeploy } from './commands/deploy.js';
@@ -128,13 +129,13 @@ const codeTarget = (c) => c
128
129
  .option('--product <tag>').option('--function <name>').option('--fn-version <version>').option('--env <slug>');
129
130
  remote('step-up', 'start', 'Email yourself a six-digit code for one change (a person only)', codeTarget).action(op('stepup.start'));
130
131
  remote('step-up', 'verify', 'Check the code and print a grant, good for ten minutes and for that one change; put it in an environment variable and pass its name with --grant-env', (c) => codeTarget(c).requiredOption('--code <code>', 'the six-digit code from your email')).action(op('stepup.verify'));
131
- remote('plans', 'create', 'Create a plan from a JSON file; nothing is changed', (c) => c.requiredOption('--file <file>', 'Plan request JSON (static egress uses runtime.vpcEgress on Cloud Run with optional provision: true or runtime.awsVpcEgress on Lambda or ECS Fargate)')).action(op('plans.create'));
132
+ remote('plans', 'create', 'Create a plan from a JSON file; nothing is changed', (c) => c.requiredOption('--file <file>', 'Plan request JSON (Cloud Run, Azure Container Apps, and AWS Lambda services accept runtime.publicAccess: true or false with human approval; static egress uses runtime.vpcEgress on Cloud Run with optional provision: true or runtime.awsVpcEgress on Lambda or ECS Fargate)')).action(op('plans.create'));
132
133
  remote('plans', 'approve <planId>', 'Approve a plan (a person only; refused for agents)', grantOption).action(op('plans.approve'));
133
134
  remote('plans', 'list', 'List plans with where each stands: blocked, pending_approval, approved, ready, applied or expired', (c) => c.option('--product <tag>').option('--env <env>').option('--stage <stage>')).action(op('plans.list'));
134
135
  remote('plans', 'get <planId>', 'Show one plan: what it would change, its warnings and the state of the cloud it was made from').action(op('plans.get'));
135
136
  remote('plans', 'apply <planId>', 'Apply an approved or permitted plan').action(op('plans.apply'));
136
137
  remote('deployments', 'list', 'List deployments (functions and services)', (c) => c.option('--product <tag>').option('--env <env>').option('--fn-version <version>').option('--kind <kind>', 'function or service').option('--connection <tag>', 'only what was applied through this cloud connection')).action(op('deployments.list'));
137
- remote('deployments', 'get <deploymentId>', 'Show one deployment').action(op('deployments.get'));
138
+ remote('deployments', 'get <deploymentId>', 'Show one deployment, including functions served by each active service revision').action(op('deployments.get'));
138
139
  remote('deployments', 'journal <deploymentId>', 'Show a deployment\'s journal').action(op('deployments.journal'));
139
140
  const planFromDeployment = (c) => c
140
141
  .option('--runtime-file <file>', 'Runtime settings JSON that replace the deployment\'s own (cpu, memory, minInstances, maxInstances, or Cloud Run vpcEgress with network and subnet names)')
@@ -1100,6 +1101,95 @@ db
1100
1101
  throw new Error('Specify a verb: connect | query');
1101
1102
  return runDb(verb, { file: opts.file, json: opts.json });
1102
1103
  }));
1104
+ const ui = program
1105
+ .command('ui')
1106
+ .description('Frontend UI pieces written once in ductape/ui/ and added to any application of the workspace, which compiles them with its own bundler');
1107
+ ui
1108
+ .command('create <name>')
1109
+ .description('Write a new UI piece under ductape/ui/<name>: manifest, component, styles and README')
1110
+ .option('--framework <framework>', 'react, vue or javascript (plain DOM code any application can use)', 'react')
1111
+ .option('--description <text>', 'One line saying what it is for')
1112
+ .option('--json', 'JSON output')
1113
+ .action(wrap((name, opts) => runUiCreate(name, opts)));
1114
+ ui
1115
+ .command('validate [name]')
1116
+ .description('Check a UI piece (or all of them): manifest, published files, imports, secrets. Offline; changes nothing')
1117
+ .option('--typecheck', 'Also type-check it with this project\'s TypeScript, React and Ductape SDK types')
1118
+ .option('--json', 'JSON output')
1119
+ .action(wrap((name, opts) => runUiValidate(name, { typecheck: Boolean(opts.typecheck), json: Boolean(opts.json) })));
1120
+ ui
1121
+ .command('pack <name>')
1122
+ .description('Validate, then write the publishable artifact with its integrity hash. Offline')
1123
+ .option('--out <file>', 'Where to write it (default ductape/.ui-packs/<name>@<version>.json)')
1124
+ .option('--json', 'JSON output')
1125
+ .action(wrap((name, opts) => runUiPack(name, { out: opts.out, json: Boolean(opts.json) })));
1126
+ ui
1127
+ .command('publish <name>')
1128
+ .description('Validate and pack ductape/ui/<name>, then publish it to this workspace. Published versions never change')
1129
+ .option('--typecheck', 'Type-check before publishing')
1130
+ .option('--dry-run', 'Validate and pack, and say what would be published, without publishing')
1131
+ .option('--json', 'JSON output')
1132
+ .action(wrap((name, opts) => runUiPublish(name, { typecheck: Boolean(opts.typecheck), dryRun: Boolean(opts.dryRun), json: Boolean(opts.json) })));
1133
+ ui
1134
+ .command('list')
1135
+ .description('The UI pieces published in this workspace, with their latest release')
1136
+ .option('--search <text>', 'Only pieces whose name or description contains this')
1137
+ .option('--json', 'JSON output')
1138
+ .action(wrap((opts) => runUiList({ search: opts.search, json: Boolean(opts.json) })));
1139
+ ui
1140
+ .command('inspect <ref>')
1141
+ .description('A piece\'s versions (name), or one version\'s manifest, requirements and files (name@version or name@latest)')
1142
+ .option('--json', 'JSON output')
1143
+ .action(wrap((ref, opts) => runUiInspect(ref, { json: Boolean(opts.json) })));
1144
+ ui
1145
+ .command('deprecate <ref>')
1146
+ .description('Mark name@version deprecated. It stays installable by exact version; latest stops choosing it')
1147
+ .requiredOption('--reason <text>', 'Why, shown to anyone who installs it')
1148
+ .option('--replacement <version>', 'The version to use instead')
1149
+ .option('--json', 'JSON output')
1150
+ .action(wrap((ref, opts) => runUiDeprecate(ref, { reason: opts.reason, replacement: opts.replacement, json: Boolean(opts.json) })));
1151
+ ui
1152
+ .command('undeprecate <ref>')
1153
+ .description('Clear the deprecation of name@version')
1154
+ .option('--json', 'JSON output')
1155
+ .action(wrap((ref, opts) => runUiUndeprecate(ref, { json: Boolean(opts.json) })));
1156
+ ui
1157
+ .command('add <ref>')
1158
+ .description('Add a published piece (name, name@version or name@latest) to this application: its verified source goes in ductape/ui/installed/, pinned in ductape/ui.lock.json, importable as #ui/<name>')
1159
+ .option('--ignore-peers', 'Add it even when the packages it needs are missing or the wrong version')
1160
+ .option('--json', 'JSON output')
1161
+ .action(wrap((ref, opts) => runUiAdd(ref, { ignorePeers: Boolean(opts.ignorePeers), json: Boolean(opts.json) })));
1162
+ ui
1163
+ .command('install')
1164
+ .description('Make ductape/ui/installed/ and package.json match ductape/ui.lock.json, fetching exactly the pinned artifacts where files are missing or changed')
1165
+ .option('--offline', 'Fetch nothing; fail if anything would need fetching')
1166
+ .option('--json', 'JSON output')
1167
+ .action(wrap((opts) => runUiInstall({ offline: Boolean(opts.offline), json: Boolean(opts.json) })));
1168
+ ui
1169
+ .command('update <name>')
1170
+ .description('Move an added piece to its latest release, or to --to <version>')
1171
+ .option('--to <version>', 'Exact version to move to')
1172
+ .option('--ignore-peers', 'Update even when the packages it needs are missing or the wrong version')
1173
+ .option('--json', 'JSON output')
1174
+ .action(wrap((name, opts) => runUiUpdate(name, { to: opts.to, ignorePeers: Boolean(opts.ignorePeers), json: Boolean(opts.json) })));
1175
+ ui
1176
+ .command('remove <name>')
1177
+ .description('Remove an added piece, and any piece it used that nothing else uses')
1178
+ .option('--json', 'JSON output')
1179
+ .action(wrap((name, opts) => runUiRemove(name, { json: Boolean(opts.json) })));
1180
+ ui
1181
+ .command('verify')
1182
+ .description('Offline check for CI: installed pieces are exactly the pinned artifacts, package.json imports them, and the packages they need are installed')
1183
+ .option('--skip-peers', 'Do not check the packages the pieces need')
1184
+ .option('--json', 'JSON output')
1185
+ .action(wrap((opts) => runUiVerify({ skipPeers: Boolean(opts.skipPeers), json: Boolean(opts.json) })));
1186
+ ui
1187
+ .command('check [name]')
1188
+ .description('Online: does the product have the actions, features and sessions the added pieces need? Uses the linked product and environment unless given')
1189
+ .option('--product <tag>', 'Product tag')
1190
+ .option('--env <slug>', 'Environment slug')
1191
+ .option('--json', 'JSON output')
1192
+ .action(wrap((name, opts) => runUiCheck(name, { product: opts.product, env: opts.env, json: Boolean(opts.json) })));
1103
1193
  const features = program.command('features').description('Code-first Ductape Features (ductape/features/)');
1104
1194
  const sessions = program.command('sessions').description('Session lifecycle and propagation checks');
1105
1195
  sessions
@@ -459,6 +459,7 @@ export const AZURE_DEPLOY_TROUBLESHOOTING = [
459
459
  export const CLOUDFLARE_DEPLOY_ROLE_LIST = [
460
460
  { role: 'Account / Workers Scripts / Edit', for: 'create Worker versions and deployments, and the placeholder that stands in until a release is checked' },
461
461
  { role: 'Account / Workers KV Storage / Edit', for: 'keep release bundles in a namespace named ductape-releases until they are deployed' },
462
+ { role: 'Account / Workers Containers / Edit', for: 'only to deploy container images (cloudflare_containers): copy them into the account\'s Cloudflare registry, prepare them and create the Container application; needs the Workers Paid plan' },
462
463
  ];
463
464
  export const CLOUDFLARE_DEPLOY_CREATES = [
464
465
  'A Workers KV namespace named ductape-releases, where each release bundle waits until it is deployed (the bundle stays in your account; Ductape keeps only its digest)',
@@ -466,15 +467,18 @@ export const CLOUDFLARE_DEPLOY_CREATES = [
466
467
  'One Worker version per release, tagged with the release hash, carrying the deployment\'s signing key as a secret binding',
467
468
  'One deployment per traffic change: Cloudflare\'s own gradual rollout, with the percentages you plan',
468
469
  'A workers.dev address for each Worker and a preview address for each version, so a release is called and checked before it takes any traffic',
470
+ 'For container images (cloudflare_containers): the image copied into registry.cloudflare.com under the account, one router Worker per deployment with a Durable Object class, one Container application, and each release\'s environment encrypted in Workers KV (only the key is a Worker secret)',
469
471
  ];
470
472
  export const CLOUDFLARE_DEPLOY_SAFETY = 'Ductape only adds resources it tags as its own (ductape_managed), never changes or reuses one it did not create, and never deletes anything, including what it created. Removing deployed Workers is always your own action. A Worker has no cloud-level access check in front of it: the function\'s own signature check, which every call must pass, is the access control. Only functions can run on Workers, not services, and only TypeScript functions.';
471
473
  export const CLOUDFLARE_DEPLOY_TROUBLESHOOTING = [
472
474
  { problem: 'Validation says the token lacks permissions', fix: 'Edit the API token and add Account / Workers Scripts / Edit and Account / Workers KV Storage / Edit, limited to this account, then validate again.' },
475
+ { problem: 'A container deploy is refused while copying the image into the Cloudflare registry ("Authentication error", 10000)', fix: 'Edit the API token and add Account / Workers Containers / Edit (under Developer Platform). The account must be on the Workers Paid plan.' },
476
+ { problem: 'The image is built for linux/arm64', fix: 'Cloudflare Containers run linux/amd64 only. Build with --platform linux/amd64, or publish a multi-platform image that includes it.' },
473
477
  { problem: '"has no workers.dev subdomain"', fix: 'Set one under Workers & Pages in the dashboard. Deployed functions are reached on it.' },
474
478
  { problem: '"not in this Cloudflare account (namespace ductape-releases)"', fix: 'Publish the bundle again with ductape deploy releases publish-worker. Releases are published through one connection and deployed through the same one.' },
475
479
  { problem: 'A plan says this release is a container image, or a Worker bundle', fix: 'A release is made of one kind of artifact. Bundles run only on cloudflare_workers targets and images only on the others.' },
476
480
  { problem: 'A plan is blocked on timeout', fix: 'A Worker is stopped after 30 seconds of CPU time. Lower the contract\'s timeout_ms, or deploy that function to Cloud Run, Lambda or Container Apps.' },
477
- { problem: 'The cloud refuses cpu, memory or instance settings', fix: 'Cloudflare manages size and scaling. Remove the runtime block from the plan.' },
481
+ { problem: 'The cloud refuses cpu, memory or instance settings', fix: 'On Workers, Cloudflare manages size and scaling: remove the runtime block. On Containers only cpu, memory and maxInstances apply; they pick the instance type and how many containers share a release.' },
478
482
  { problem: 'Cloudflare only keeps the last 100 versions', fix: 'Rolling back to a release that is older than that fails with a clear message. Publish and deploy it again.' },
479
483
  ];
480
484
  export const GCP_DEPLOY_APIS = [
@@ -562,12 +566,12 @@ export function connectionGuide(providerInput, purposeInput = 'resources') {
562
566
  if (provider === 'cloudflare' && purpose === 'deploy') {
563
567
  return {
564
568
  ...base, supported: true,
565
- summary: 'Lets Ductape deploy your TypeScript functions to Cloudflare Workers in your own account, through an API token you create and can read. Workers have no container: you publish a JavaScript bundle.',
569
+ summary: 'Lets Ductape deploy your TypeScript functions to Cloudflare Workers, and container images (services included) to Cloudflare Containers, in your own account, through an API token you create and can read. Workers have no container: you publish a JavaScript bundle. Containers take a linux/amd64 image, which Ductape copies into the account\'s Cloudflare registry.',
566
570
  steps: [
567
571
  { step: 1, who: 'you', title: 'Find your account id', notes: ['In the Cloudflare dashboard, open Workers & Pages. The account id is on the right and is 32 characters. Make sure the account has a workers.dev subdomain.'] },
568
572
  {
569
- step: 2, who: 'you', title: 'Create an API token with two permissions',
570
- notes: ['Manage Account, Account API Tokens, Create Token, Create Custom Token. Add Account / Workers Scripts / Edit and Account / Workers KV Storage / Edit, limit it to this account and create it. Cloudflare shows the token once.'],
573
+ step: 2, who: 'you', title: 'Create an API token',
574
+ notes: ['Manage Account, Account API Tokens, Create Token, Create Custom Token. Add Account / Workers Scripts / Edit and Account / Workers KV Storage / Edit. To deploy container images also add Account / Workers Containers / Edit (listed under Developer Platform); the account then needs the Workers Paid plan. Limit it to this account and create it. Cloudflare shows the token once.'],
571
575
  },
572
576
  { step: 3, who: 'you', title: 'Put the token in an environment variable', commands: ['read -s CLOUDFLARE_API_TOKEN && export CLOUDFLARE_API_TOKEN'], notes: ['This keeps the token out of the command line and shell history.'] },
573
577
  { step: 4, who: 'ductape', title: 'Create the connection', commands: ['ductape cloud connections create --provider cloudflare --name "<NAME>" --tag <TAG> --deploy'] },
@@ -580,6 +584,7 @@ export function connectionGuide(providerInput, purposeInput = 'resources') {
580
584
  next: [
581
585
  'Publish a release: ductape deploy releases publish-worker --file release.json --connection <TAG> --entry src/index.ts (or --bundle dist/index.js). The file holds product, function, version, contract, config and verification, and no image.',
582
586
  'Plan and apply as usual with a target of kind cloudflare_workers on that connection. Release, plan, approval, canary and rollback work the same as on the other clouds.',
587
+ 'For a container image: register it with ductape deploy releases register (a public image on Docker Hub or GHCR, or one already in registry.cloudflare.com under the account), then plan with a target of kind cloudflare_containers. runtime.cpu and runtime.memory pick the instance type and runtime.maxInstances how many containers share a release.',
583
588
  CLOUDFLARE_DEPLOY_SAFETY,
584
589
  ],
585
590
  };