@zalosai/zalos-cli 0.2.34 → 0.2.36
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 +7 -1
- package/dist/client.js +9 -0
- package/dist/commands/close.js +15 -0
- package/dist/commands/codepack.js +115 -2
- package/dist/commands/execution.js +96 -0
- package/dist/commands/file.js +23 -10
- package/dist/commands/workflow.js +109 -5
- package/dist/main.js +4 -0
- package/dist/utils/codepack-cases.js +655 -0
- package/dist/utils/codepack-scaffold.js +23 -0
- package/dist/utils/codepack.js +6 -3
- package/package.json +1 -1
- package/skills/codepack-authoring/SKILL.md +55 -9
- package/skills/zl-ops/SKILL.md +11 -0
package/README.md
CHANGED
|
@@ -139,6 +139,9 @@ zl page create --input /tmp/month-end-close.md --apply
|
|
|
139
139
|
zl page update <page-id> --input /tmp/month-end-close.md --apply
|
|
140
140
|
zl workflow run <id> --dry-run
|
|
141
141
|
zl workflow run <id>
|
|
142
|
+
zl workflow run <id> --json '{"period":"2026-11"}' --file bankReport=./jpm.xlsx
|
|
143
|
+
zl execution respond <execution-id> --dry-run
|
|
144
|
+
zl execution respond <execution-id> --json '{"approved":true}' --file ./reviewed.xlsx
|
|
142
145
|
zl template list
|
|
143
146
|
zl credential list
|
|
144
147
|
zl file list
|
|
@@ -163,7 +166,10 @@ zl close registry import-baseline --team-id <team-ref> --expected-version <versi
|
|
|
163
166
|
```
|
|
164
167
|
|
|
165
168
|
Workflow import/update/publish require `--apply`; without it they validate and print a preview.
|
|
166
|
-
`workflow run
|
|
169
|
+
`workflow run --file <field>=<path>` uploads a local file to Team Files and passes it to that form
|
|
170
|
+
file field, exactly like choosing a Team File in the web form. `execution respond` completes the
|
|
171
|
+
form step a run is waiting on (review/wait nodes), with optional `--file` uploads; `--dry-run` shows
|
|
172
|
+
the fields it expects. `workflow run` executes unless `--dry-run` is supplied. Product authorization comes
|
|
167
173
|
from the signed-in human's team membership, role, and token scopes. Credential reads
|
|
168
174
|
return metadata only. No product command loads database credentials.
|
|
169
175
|
|
package/dist/client.js
CHANGED
|
@@ -61,6 +61,10 @@ async function request(options, tokenOverride) {
|
|
|
61
61
|
}
|
|
62
62
|
throw new AuthError('Unauthorized. Check your API token.');
|
|
63
63
|
}
|
|
64
|
+
if (options.textResponse && !response.ok) {
|
|
65
|
+
const message = (await response.text()).trim().slice(0, 500);
|
|
66
|
+
throw new ApiError(response.status, message || response.statusText);
|
|
67
|
+
}
|
|
64
68
|
if (response.status === 404) {
|
|
65
69
|
throw new NotFoundError('resource', path);
|
|
66
70
|
}
|
|
@@ -70,6 +74,8 @@ async function request(options, tokenOverride) {
|
|
|
70
74
|
}
|
|
71
75
|
if (response.status === 204)
|
|
72
76
|
return undefined;
|
|
77
|
+
if (options.textResponse)
|
|
78
|
+
return (await response.text());
|
|
73
79
|
if (options.binaryResponse) {
|
|
74
80
|
return {
|
|
75
81
|
body: Buffer.from(await response.arrayBuffer()),
|
|
@@ -82,7 +88,10 @@ export const client = {
|
|
|
82
88
|
get: (path, query) => request({ method: 'GET', path, query }),
|
|
83
89
|
post: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
84
90
|
postForm: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
91
|
+
postFormText: (path, body, options) => request({ method: 'POST', path, body, textResponse: true, ...options }),
|
|
85
92
|
postBinary: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
93
|
+
/** POST a binary body and return the raw response, e.g. a streamed NDJSON result. */
|
|
94
|
+
postBinaryRaw: (path, body, options) => request({ method: 'POST', path, body, binaryResponse: true, ...options }),
|
|
86
95
|
putBinary: (path, body, options) => request({ method: 'PUT', path, body, ...options }),
|
|
87
96
|
getBinary: (path, options) => request({ method: 'GET', path, binaryResponse: true, ...options }),
|
|
88
97
|
put: (path, body) => request({ method: 'PUT', path, body }),
|
package/dist/commands/close.js
CHANGED
|
@@ -185,6 +185,21 @@ export function registerCloseCommand(program) {
|
|
|
185
185
|
else
|
|
186
186
|
process.stdout.write(yaml);
|
|
187
187
|
}));
|
|
188
|
+
registry
|
|
189
|
+
.command('retire-dataset')
|
|
190
|
+
.description('Retire one Data Hub report and retain its history; previews unless --confirm')
|
|
191
|
+
.requiredOption('--team-id <ref>', 'Team public ID or UUID (select it before confirming)')
|
|
192
|
+
.requiredOption('--dataset-key <key>', 'Report dataset key, e.g. bank.transactions')
|
|
193
|
+
.requiredOption('--expected-version <number>', 'Active registry version')
|
|
194
|
+
.option('--confirm <digest>', 'Publish the previewed retirement with its confirmation digest')
|
|
195
|
+
.action(async (o) => action(async () => {
|
|
196
|
+
printJson(dataRow(await client.post('/developer/finance/registry/retire-dataset', {
|
|
197
|
+
teamId: resourceId(o.teamId),
|
|
198
|
+
datasetKey: o.datasetKey,
|
|
199
|
+
expectedVersion: positiveVersion(o.expectedVersion),
|
|
200
|
+
...(o.confirm !== undefined ? { confirm: confirmDigest(o.confirm) } : {}),
|
|
201
|
+
}, { timeoutMs: APPLY_TIMEOUT_MS })));
|
|
202
|
+
}));
|
|
188
203
|
registerOnboardInput(registry);
|
|
189
204
|
registerAddAgent(registry);
|
|
190
205
|
}
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import { client } from '../client.js';
|
|
2
2
|
import { packCodepack, packCodepackSource, unpackCodepack, } from '../utils/codepack.js';
|
|
3
3
|
import { scaffoldCodepack } from '../utils/codepack-scaffold.js';
|
|
4
|
+
import { CASES_ROOT, isCasePath, loadCodepackCases, runLocalCodepackTests, selectCases, } from '../utils/codepack-cases.js';
|
|
4
5
|
import { ApiError, ValidationError } from '../utils/errors.js';
|
|
5
6
|
import { printJson } from '../utils/output.js';
|
|
6
7
|
import { action, dataRow, isRow, resourceId } from '../utils/product-api.js';
|
|
7
8
|
import { parseWorkflowFile } from '../workflow-file.js';
|
|
8
9
|
import { publicationStatus, putWorkflowDraft } from './workflow.js';
|
|
9
10
|
const PUBLISH_TIMEOUT_MS = 120_000;
|
|
11
|
+
/** Time a remote run may take beyond its own limit: sandbox start, upload and download. */
|
|
12
|
+
const REMOTE_TEST_OVERHEAD_SECONDS = 600;
|
|
13
|
+
/** The server's default for a test run (MAX_CODEPACK_RUN_TIMEOUT_SECONDS). */
|
|
14
|
+
const DEFAULT_REMOTE_TEST_SECONDS = 900;
|
|
15
|
+
const MAX_REMOTE_TEST_SECONDS = 900;
|
|
16
|
+
const MAX_LOCAL_CASE_SECONDS = 1800;
|
|
10
17
|
const CODEPACK_REF_PATTERN = /^codepack:sha256:[0-9a-f]{64}$/;
|
|
11
18
|
const CODEPACK_NODE_TYPE = 'mesh-nodes-base.codepack';
|
|
12
19
|
const MAX_CHECKPOINT_NAME_LENGTH = 200;
|
|
@@ -159,6 +166,103 @@ async function uploadCodepack(packed, options) {
|
|
|
159
166
|
});
|
|
160
167
|
return published;
|
|
161
168
|
}
|
|
169
|
+
function parseTimeout(raw, maximum) {
|
|
170
|
+
if (raw === undefined)
|
|
171
|
+
return undefined;
|
|
172
|
+
const value = Number(raw);
|
|
173
|
+
if (!/^\d+$/.test(raw) || value < 10 || value > maximum) {
|
|
174
|
+
throw new ValidationError('timeout', `Expected whole seconds from 10 to ${maximum}`);
|
|
175
|
+
}
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
/** The streamed result of POST /codepacks/test: heartbeat lines, then one result or error. */
|
|
179
|
+
function remoteTestResult(body) {
|
|
180
|
+
const lines = body
|
|
181
|
+
.toString('utf8')
|
|
182
|
+
.split('\n')
|
|
183
|
+
.filter((line) => line.trim())
|
|
184
|
+
.map((line) => {
|
|
185
|
+
try {
|
|
186
|
+
return JSON.parse(line);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
})
|
|
192
|
+
.filter(isRow);
|
|
193
|
+
const last = lines.filter((line) => line.type !== 'heartbeat').at(-1);
|
|
194
|
+
if (last?.type === 'result' && isRow(last.data))
|
|
195
|
+
return last.data;
|
|
196
|
+
if (last?.type === 'error' && isRow(last.error)) {
|
|
197
|
+
throw new ApiError(last.error.code === 'INVALID_CODEPACK' ? 400 : 502, String(last.error.message ?? 'The codepack test run failed'));
|
|
198
|
+
}
|
|
199
|
+
throw new ApiError(502, 'The test run ended without a result; try again');
|
|
200
|
+
}
|
|
201
|
+
async function remoteTestReport(directory, options) {
|
|
202
|
+
const timeoutSeconds = parseTimeout(options.timeout, MAX_REMOTE_TEST_SECONDS);
|
|
203
|
+
// Same checks a publish makes, then the cases, before anything is sent.
|
|
204
|
+
const codepack = await packCodepack(directory);
|
|
205
|
+
const { cases } = await loadCodepackCases(directory);
|
|
206
|
+
const selected = new Set(selectCases(cases, options.case).map((testCase) => testCase.name));
|
|
207
|
+
const source = await packCodepackSource(directory, {
|
|
208
|
+
// With --case, send only those cases; unit tests are skipped as they are locally.
|
|
209
|
+
exclude: options.case
|
|
210
|
+
? (path) => isCasePath(path)
|
|
211
|
+
? !selected.has(path.slice(CASES_ROOT.length + 1).split('/')[0])
|
|
212
|
+
: path.startsWith('tests/')
|
|
213
|
+
: undefined,
|
|
214
|
+
});
|
|
215
|
+
const { body } = await client.postBinaryRaw('/codepacks/test', source.archive, {
|
|
216
|
+
contentType: 'application/gzip',
|
|
217
|
+
timeoutMs: ((timeoutSeconds ?? DEFAULT_REMOTE_TEST_SECONDS) + REMOTE_TEST_OVERHEAD_SECONDS) * 1000,
|
|
218
|
+
...(timeoutSeconds !== undefined ? { query: { timeoutSeconds: String(timeoutSeconds) } } : {}),
|
|
219
|
+
});
|
|
220
|
+
const result = remoteTestResult(body);
|
|
221
|
+
const reported = Array.isArray(result.cases) ? result.cases.length : 0;
|
|
222
|
+
return {
|
|
223
|
+
where: 'remote',
|
|
224
|
+
templateKey: codepack.templateKey,
|
|
225
|
+
agentRef: codepack.agentRef,
|
|
226
|
+
runtimeSnapshot: result.runtimeSnapshot,
|
|
227
|
+
status: result.status,
|
|
228
|
+
unitTests: result.unitTests,
|
|
229
|
+
cases: Array.isArray(result.cases) ? result.cases : [],
|
|
230
|
+
// Every case that was sent must report; a missing result is a failure.
|
|
231
|
+
casesMissing: reported < selected.size,
|
|
232
|
+
...(reported < selected.size
|
|
233
|
+
? { notice: `Only ${reported} of ${selected.size} cases reported a result; see log.` }
|
|
234
|
+
: {}),
|
|
235
|
+
log: result.log,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** Runs a codepack's unit tests and cases, locally or on the production runtime. */
|
|
239
|
+
export async function testCodepackAction(directory, options = {}) {
|
|
240
|
+
if (options.remote && options.python !== undefined) {
|
|
241
|
+
throw new ValidationError('python', '--python applies to local runs; --remote uses the runtime');
|
|
242
|
+
}
|
|
243
|
+
const report = options.remote
|
|
244
|
+
? await remoteTestReport(directory, options)
|
|
245
|
+
: {
|
|
246
|
+
where: 'local',
|
|
247
|
+
...(await runLocalCodepackTests(directory, {
|
|
248
|
+
...(options.python !== undefined ? { python: options.python } : {}),
|
|
249
|
+
...(options.case ? { cases: options.case } : {}),
|
|
250
|
+
...(options.timeout !== undefined
|
|
251
|
+
? { timeoutSeconds: parseTimeout(options.timeout, MAX_LOCAL_CASE_SECONDS) }
|
|
252
|
+
: {}),
|
|
253
|
+
})),
|
|
254
|
+
};
|
|
255
|
+
const cases = report.cases;
|
|
256
|
+
const failed = cases.filter((testCase) => testCase.status === 'failed').length;
|
|
257
|
+
const unitTests = isRow(report.unitTests) ? report.unitTests : {};
|
|
258
|
+
const ok = unitTests.status !== 'failed' &&
|
|
259
|
+
failed === 0 &&
|
|
260
|
+
!('casesMissing' in report && report.casesMissing) &&
|
|
261
|
+
(report.where === 'local' || report.status === 'succeeded');
|
|
262
|
+
printJson({ data: { ok, passed: cases.length - failed, failed, ...report } });
|
|
263
|
+
if (!ok)
|
|
264
|
+
process.exitCode = 1;
|
|
265
|
+
}
|
|
162
266
|
export async function validateCodepackAction(directory) {
|
|
163
267
|
printJson({ data: summary(await packCodepack(directory)) });
|
|
164
268
|
}
|
|
@@ -171,7 +275,8 @@ export async function initCodepackAction(name, options) {
|
|
|
171
275
|
next: [
|
|
172
276
|
`cd ${JSON.stringify(dir)}`,
|
|
173
277
|
'python process.py inputs/sample.csv --period_end 2026-10-31',
|
|
174
|
-
|
|
278
|
+
`zl codepack test ${JSON.stringify(dir)}`,
|
|
279
|
+
`zl --environment <env> codepack test ${JSON.stringify(dir)} --remote`,
|
|
175
280
|
`zl codepack validate ${JSON.stringify(dir)}`,
|
|
176
281
|
`zl codepack publish ${JSON.stringify(dir)}`,
|
|
177
282
|
],
|
|
@@ -273,7 +378,7 @@ export async function fetchCodepackSourceAction(agentRef, options) {
|
|
|
273
378
|
files,
|
|
274
379
|
next: [
|
|
275
380
|
`cd ${JSON.stringify(directory)}`,
|
|
276
|
-
'
|
|
381
|
+
'zl codepack test .',
|
|
277
382
|
`zl codepack publish ${JSON.stringify(directory)} --parent ${agentRef} --label "<what changed>"`,
|
|
278
383
|
],
|
|
279
384
|
},
|
|
@@ -292,6 +397,14 @@ export function registerCodepackCommand(program) {
|
|
|
292
397
|
.command('validate <directory>')
|
|
293
398
|
.description('Check a codepack folder and print the codepack ref it would publish as')
|
|
294
399
|
.action(async (directory) => action(() => validateCodepackAction(directory)));
|
|
400
|
+
cmd
|
|
401
|
+
.command('test <directory>')
|
|
402
|
+
.description('Run the unit tests (tests/test_*.py) and cases (tests/cases/<case>/) with local Python, or with --remote on the production codepack runtime')
|
|
403
|
+
.option('--remote', 'Run on the production codepack runtime in the selected region')
|
|
404
|
+
.option('--case <name...>', 'Run only these cases (skips unit tests)')
|
|
405
|
+
.option('--python <path>', 'Local Python (default: ./.venv/bin/python, else python3)')
|
|
406
|
+
.option('--timeout <seconds>', 'Local: limit per case. Remote: limit for the whole run (max 900)')
|
|
407
|
+
.action(async (directory, o) => action(() => testCodepackAction(directory, o)));
|
|
295
408
|
cmd
|
|
296
409
|
.command('publish <directory>')
|
|
297
410
|
.description('Publish a codepack folder to the selected team; with --workflow, repin its Codepack node and save a named checkpoint')
|
|
@@ -7,6 +7,8 @@ import { currentEnvironment } from '../environments.js';
|
|
|
7
7
|
import { downloadToNewFile } from '../utils/download-file.js';
|
|
8
8
|
import { ApiError, ValidationError } from '../utils/errors.js';
|
|
9
9
|
import { filterFields, filterSingle, printJson } from '../utils/output.js';
|
|
10
|
+
import { parseJson } from '../utils/validate.js';
|
|
11
|
+
import { readLocalUploadFile, UPLOAD_TIMEOUT_MS } from './file.js';
|
|
10
12
|
import { action, dataRow, fields, integer, isRow, resourceId, } from '../utils/product-api.js';
|
|
11
13
|
function isReplayBundleArtifact(value) {
|
|
12
14
|
if (!isRow(value))
|
|
@@ -198,6 +200,93 @@ export async function listExecutionsAction(options) {
|
|
|
198
200
|
export async function viewExecutionAction(id, options, summary = false) {
|
|
199
201
|
printJson(filterSingle(dataRow(await client.get(`/executions/${resourceId(id)}${summary ? '/summary' : ''}`)), options.fields));
|
|
200
202
|
}
|
|
203
|
+
// Mirrors the server's wait-form multer limits (routes.ts WAIT_FORM_UPLOAD_MAX_BYTES).
|
|
204
|
+
const WAIT_FORM_MAX_FILE_BYTES = 100 * 1024 * 1024;
|
|
205
|
+
const WAIT_FORM_MAX_FILES = 10;
|
|
206
|
+
function waitFormTarget(submitUrl) {
|
|
207
|
+
if (typeof submitUrl !== 'string')
|
|
208
|
+
throw new ApiError(502, 'Waiting form has no submit URL');
|
|
209
|
+
const url = new URL(submitUrl, 'http://zl.invalid');
|
|
210
|
+
const match = /^\/api\/executions\/([^/]+)\/wait-form$/.exec(url.pathname);
|
|
211
|
+
const token = url.searchParams.get('token');
|
|
212
|
+
if (!match || !token)
|
|
213
|
+
throw new ApiError(502, 'Unexpected waiting form submit URL');
|
|
214
|
+
return { executionId: decodeURIComponent(match[1]), token };
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Completes a paused form step (wait/review node), uploading local files the same
|
|
218
|
+
* way the web form does. The resume token stays in memory and is never printed.
|
|
219
|
+
*/
|
|
220
|
+
export async function respondToExecutionFormAction(id, options) {
|
|
221
|
+
const executionId = resourceId(id);
|
|
222
|
+
const values = parseJson(options.json ?? '{}');
|
|
223
|
+
if (!isRow(values))
|
|
224
|
+
throw new ValidationError('json', 'Form values must be an object');
|
|
225
|
+
const response = await client.get(`/executions/${executionId}/wait-form-config`);
|
|
226
|
+
const config = isRow(response) && isRow(response.data) ? response.data : response;
|
|
227
|
+
if (!isRow(config))
|
|
228
|
+
throw new ApiError(502, 'Invalid waiting form response');
|
|
229
|
+
const target = waitFormTarget(config.submitUrl);
|
|
230
|
+
const files = options.file ?? [];
|
|
231
|
+
const fileField = typeof config.fileUploadFieldName === 'string' && config.fileUploadFieldName
|
|
232
|
+
? config.fileUploadFieldName
|
|
233
|
+
: 'uploadedFiles';
|
|
234
|
+
const problems = [];
|
|
235
|
+
if (files.length > 0 && config.allowFileUpload !== true)
|
|
236
|
+
problems.push('This form step does not accept file uploads');
|
|
237
|
+
if (files.length === 0 && config.fileUploadRequired === true)
|
|
238
|
+
problems.push('This form step requires a file: pass --file <path>');
|
|
239
|
+
// A dry run is how users discover what the form needs, so report problems instead.
|
|
240
|
+
if (problems.length > 0 && !options.dryRun)
|
|
241
|
+
throw new ValidationError('file', problems[0]);
|
|
242
|
+
if (files.length > WAIT_FORM_MAX_FILES)
|
|
243
|
+
throw new ValidationError('file', `A form step accepts at most ${WAIT_FORM_MAX_FILES} files`);
|
|
244
|
+
const uploads = [];
|
|
245
|
+
for (const path of files)
|
|
246
|
+
uploads.push(await readLocalUploadFile(path, undefined, {
|
|
247
|
+
bytes: WAIT_FORM_MAX_FILE_BYTES,
|
|
248
|
+
label: 'the 100 MiB form upload limit',
|
|
249
|
+
}));
|
|
250
|
+
const summary = {
|
|
251
|
+
executionId: target.executionId,
|
|
252
|
+
waitNodeName: config.waitNodeName ?? null,
|
|
253
|
+
formTitle: config.formTitle ?? null,
|
|
254
|
+
formFields: config.formFields ?? [],
|
|
255
|
+
allowFileUpload: config.allowFileUpload === true,
|
|
256
|
+
fileUploadRequired: config.fileUploadRequired === true,
|
|
257
|
+
...(config.allowFileUpload === true ? { fileUploadFieldName: fileField } : {}),
|
|
258
|
+
};
|
|
259
|
+
if (options.dryRun) {
|
|
260
|
+
printJson({
|
|
261
|
+
dryRun: true,
|
|
262
|
+
form: summary,
|
|
263
|
+
values,
|
|
264
|
+
files: uploads.map((upload) => ({ name: upload.name, size: upload.size })),
|
|
265
|
+
...(problems.length > 0 ? { problems } : {}),
|
|
266
|
+
});
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
const form = new FormData();
|
|
270
|
+
for (const [key, value] of Object.entries(values)) {
|
|
271
|
+
if (key === fileField || value === null || value === undefined)
|
|
272
|
+
continue;
|
|
273
|
+
const items = Array.isArray(value) ? value : [value];
|
|
274
|
+
for (const item of items)
|
|
275
|
+
form.append(key, typeof item === 'object' ? JSON.stringify(item) : String(item));
|
|
276
|
+
}
|
|
277
|
+
for (const upload of uploads)
|
|
278
|
+
form.append(fileField, upload.file, upload.name);
|
|
279
|
+
await client.postFormText(`/executions/${encodeURIComponent(target.executionId)}/wait-form`, form, {
|
|
280
|
+
query: { token: target.token },
|
|
281
|
+
timeoutMs: UPLOAD_TIMEOUT_MS,
|
|
282
|
+
});
|
|
283
|
+
printJson({
|
|
284
|
+
executionId: target.executionId,
|
|
285
|
+
waitNodeName: summary.waitNodeName,
|
|
286
|
+
submitted: true,
|
|
287
|
+
files: uploads.length,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
201
290
|
export async function stopExecutionAction(id) {
|
|
202
291
|
const executionId = resourceId(id);
|
|
203
292
|
const result = await client.post(`/executions/${executionId}/stop`);
|
|
@@ -218,6 +307,13 @@ export function registerExecutionCommand(program) {
|
|
|
218
307
|
cmd
|
|
219
308
|
.command(`${verb} <id>`)
|
|
220
309
|
.action(async (id) => action(() => viewExecutionAction(id, fields(program), verb === 'summary')));
|
|
310
|
+
cmd
|
|
311
|
+
.command('respond <execution-id>')
|
|
312
|
+
.description('Complete the form step an execution is waiting on; --dry-run shows the fields it expects')
|
|
313
|
+
.option('--json <values>', 'Form values as JSON')
|
|
314
|
+
.option('--file <path>', 'Upload a local file with the response (repeatable)', (value, previous) => [...previous, value], [])
|
|
315
|
+
.option('--dry-run', 'Show the waiting form and planned response without submitting')
|
|
316
|
+
.action(async (id, options) => action(() => respondToExecutionFormAction(id, options)));
|
|
221
317
|
cmd
|
|
222
318
|
.command('stop <execution-id>')
|
|
223
319
|
.description('Stop a running execution and its downstream work')
|
package/dist/commands/file.js
CHANGED
|
@@ -12,7 +12,7 @@ const FOLDER_FIELDS = 'id,name,parentFolderId,createdAt,updatedAt';
|
|
|
12
12
|
// Team Files folders live in the `files` folder scope; workflow folders use `workflows`.
|
|
13
13
|
const FILES_FOLDER_SCOPE = 'files';
|
|
14
14
|
const MAX_FILE_SIZE_BYTES = 500 * 1024 * 1024;
|
|
15
|
-
const UPLOAD_TIMEOUT_MS = 15 * 60_000;
|
|
15
|
+
export const UPLOAD_TIMEOUT_MS = 15 * 60_000;
|
|
16
16
|
const MIME_TYPES = {
|
|
17
17
|
'.csv': 'text/csv',
|
|
18
18
|
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
@@ -94,9 +94,12 @@ export async function downloadFileAction(idOrPath, options) {
|
|
|
94
94
|
allowDataUrl: options.allowDataUrl,
|
|
95
95
|
}));
|
|
96
96
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
97
|
+
/** Validates a local file against the Team Files limits and opens it for multipart upload. */
|
|
98
|
+
export async function readLocalUploadFile(localPath, mimeTypeOverride, limit = {
|
|
99
|
+
bytes: MAX_FILE_SIZE_BYTES,
|
|
100
|
+
label: 'the 500 MiB Team Files limit',
|
|
101
|
+
}) {
|
|
102
|
+
const mimeType = mimeTypeOverride ?? MIME_TYPES[extname(localPath).toLowerCase()] ?? 'application/octet-stream';
|
|
100
103
|
if (!/^[\w.+-]+\/[\w.+-]+$/.test(mimeType)) {
|
|
101
104
|
throw new ValidationError('mimeType', 'Invalid MIME type');
|
|
102
105
|
}
|
|
@@ -109,21 +112,31 @@ export async function uploadFileAction(localPath, options) {
|
|
|
109
112
|
}
|
|
110
113
|
if (!fileStat.isFile())
|
|
111
114
|
throw new ValidationError('file', 'Local path must be a regular file');
|
|
112
|
-
if (fileStat.size >
|
|
113
|
-
throw new ValidationError('file',
|
|
115
|
+
if (fileStat.size > limit.bytes) {
|
|
116
|
+
throw new ValidationError('file', `${basename(localPath)} exceeds ${limit.label}`);
|
|
114
117
|
}
|
|
115
|
-
let file;
|
|
116
118
|
try {
|
|
117
|
-
|
|
119
|
+
return {
|
|
120
|
+
file: await openAsBlob(localPath, { type: mimeType }),
|
|
121
|
+
name: basename(localPath),
|
|
122
|
+
size: fileStat.size,
|
|
123
|
+
};
|
|
118
124
|
}
|
|
119
125
|
catch {
|
|
120
126
|
throw new ValidationError('file', `Unable to read local file: ${localPath}`);
|
|
121
127
|
}
|
|
128
|
+
}
|
|
129
|
+
export async function uploadLocalTeamFile(localPath, options) {
|
|
130
|
+
const folderId = options.folderId ? resourceId(options.folderId) : 'root';
|
|
131
|
+
const upload = await readLocalUploadFile(localPath, options.mimeType);
|
|
122
132
|
const form = new FormData();
|
|
123
133
|
form.append('folderId', folderId);
|
|
124
134
|
form.append('collisionStrategy', options.overwrite ? 'overwrite' : 'create_unique_name');
|
|
125
|
-
form.append('file', file,
|
|
126
|
-
|
|
135
|
+
form.append('file', upload.file, upload.name);
|
|
136
|
+
return dataRow(await client.postForm('/team-files/upload', form, { timeoutMs: UPLOAD_TIMEOUT_MS }));
|
|
137
|
+
}
|
|
138
|
+
export async function uploadFileAction(localPath, options) {
|
|
139
|
+
printJson(await uploadLocalTeamFile(localPath, options));
|
|
127
140
|
}
|
|
128
141
|
export async function listFoldersAction(options) {
|
|
129
142
|
const parentFolderId = options.parentFolderId ? resourceId(options.parentFolderId) : 'root';
|
|
@@ -2,10 +2,11 @@ import { writeFile, stat } from 'node:fs/promises';
|
|
|
2
2
|
import { resolve, join } from 'node:path';
|
|
3
3
|
import { client } from '../client.js';
|
|
4
4
|
import { parseWorkflowFile, readWorkflowFile, serializeWorkflow } from '../workflow-file.js';
|
|
5
|
-
import { ApiError, ValidationError } from '../utils/errors.js';
|
|
5
|
+
import { ApiError, NotFoundError, ValidationError } from '../utils/errors.js';
|
|
6
6
|
import { filterSingle, printJson } from '../utils/output.js';
|
|
7
7
|
import { action, dataRow, dataRows, fields, isRow, printPage, resourceId, } from '../utils/product-api.js';
|
|
8
8
|
import { parseJson } from '../utils/validate.js';
|
|
9
|
+
import { readLocalUploadFile, uploadLocalTeamFile } from './file.js';
|
|
9
10
|
import { registerWorkflowScheduleCommand } from './workflow-schedule.js';
|
|
10
11
|
import { registerWorkflowEvalCommand } from './workflow-eval.js';
|
|
11
12
|
async function readWorkflow(id, options) {
|
|
@@ -217,17 +218,119 @@ export async function deleteWorkflowAction(id, options) {
|
|
|
217
218
|
await client.delete(path);
|
|
218
219
|
printJson({ deleted: true, workflowId });
|
|
219
220
|
}
|
|
221
|
+
function parseFileInputs(entries) {
|
|
222
|
+
const seen = new Set();
|
|
223
|
+
return entries.map((entry) => {
|
|
224
|
+
const separator = entry.indexOf('=');
|
|
225
|
+
const field = entry.slice(0, separator).trim();
|
|
226
|
+
const path = entry.slice(separator + 1);
|
|
227
|
+
if (separator <= 0 || !field || !path)
|
|
228
|
+
throw new ValidationError('file', 'Use --file <field>=<local-path>');
|
|
229
|
+
if (seen.has(field))
|
|
230
|
+
throw new ValidationError('file', `Only one file per field is supported: ${field}`);
|
|
231
|
+
seen.add(field);
|
|
232
|
+
return { field, path };
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
/** Form file field keys as the server names them, or null when there is no form trigger. */
|
|
236
|
+
function formFileFields(workflow) {
|
|
237
|
+
const nodes = Array.isArray(workflow.nodes) ? workflow.nodes.filter(isRow) : [];
|
|
238
|
+
const trigger = nodes.find((node) => typeof node.type === 'string' && node.type.endsWith('.formTrigger'));
|
|
239
|
+
if (!trigger)
|
|
240
|
+
return null;
|
|
241
|
+
const raw = isRow(trigger.parameters) ? trigger.parameters.formFields : undefined;
|
|
242
|
+
let values = isRow(raw) ? raw.values : undefined;
|
|
243
|
+
// Older workflows store the field list as a JSON string.
|
|
244
|
+
if (typeof raw === 'string') {
|
|
245
|
+
try {
|
|
246
|
+
values = JSON.parse(raw);
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
values = [];
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (!Array.isArray(values))
|
|
253
|
+
return [];
|
|
254
|
+
// A missing or blank fieldName is keyed by position, as the server's form readers do.
|
|
255
|
+
return values.flatMap((field, index) => isRow(field) && field.fieldType === 'file'
|
|
256
|
+
? [
|
|
257
|
+
typeof field.fieldName === 'string' && field.fieldName.trim()
|
|
258
|
+
? field.fieldName
|
|
259
|
+
: `field_${index}`,
|
|
260
|
+
]
|
|
261
|
+
: []);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Internal workflows are hidden from a plain read but still runnable, so retry the read with
|
|
265
|
+
* includeInternal. A 404 there means no such workflow (the server checks existence before the
|
|
266
|
+
* internal permission), so fail before uploading; only a refused internal read skips the check.
|
|
267
|
+
*/
|
|
268
|
+
async function runnableFormFileFields(workflowId) {
|
|
269
|
+
try {
|
|
270
|
+
return formFileFields(dataRow(await client.get(`/workflows/${workflowId}`)));
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
if (!(error instanceof NotFoundError))
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
return formFileFields(dataRow(await client.get(`/workflows/${workflowId}`, { includeInternal: 'true' })));
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
if (error instanceof NotFoundError)
|
|
281
|
+
throw error;
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
220
285
|
export async function runWorkflowAction(id, options) {
|
|
221
|
-
const
|
|
286
|
+
const workflowId = resourceId(id);
|
|
287
|
+
const path = `/workflows/${workflowId}/run`;
|
|
222
288
|
const triggerData = parseJson(options.json ?? '{}');
|
|
223
289
|
if (!isRow(triggerData))
|
|
224
290
|
throw new ValidationError('json', 'Trigger inputs must be an object');
|
|
225
|
-
const
|
|
291
|
+
const files = parseFileInputs(options.file ?? []);
|
|
292
|
+
for (const { field } of files) {
|
|
293
|
+
if (Object.hasOwn(triggerData, field))
|
|
294
|
+
throw new ValidationError('file', `Field ${field} is set both in --json and --file`);
|
|
295
|
+
}
|
|
296
|
+
if (files.length > 0) {
|
|
297
|
+
const accepted = await runnableFormFileFields(workflowId);
|
|
298
|
+
for (const { field } of files) {
|
|
299
|
+
if (accepted && !accepted.includes(field)) {
|
|
300
|
+
throw new ValidationError('file', `The form has no file field ${field}. File fields: ${accepted.join(', ') || 'none'}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// Validate every local file before uploading any, so a typo uploads nothing.
|
|
304
|
+
for (const file of files)
|
|
305
|
+
await readLocalUploadFile(file.path);
|
|
306
|
+
}
|
|
226
307
|
if (options.dryRun) {
|
|
227
|
-
printJson({
|
|
308
|
+
printJson({
|
|
309
|
+
dryRun: true,
|
|
310
|
+
method: 'POST',
|
|
311
|
+
path,
|
|
312
|
+
payload: { triggerData },
|
|
313
|
+
uploads: files.map(({ field, path: localPath }) => ({
|
|
314
|
+
field,
|
|
315
|
+
localPath,
|
|
316
|
+
to: 'Team Files root, then passed as mesh://team-files/<id>',
|
|
317
|
+
})),
|
|
318
|
+
});
|
|
228
319
|
return;
|
|
229
320
|
}
|
|
230
|
-
|
|
321
|
+
const fileInputsMeta = {};
|
|
322
|
+
for (const { field, path: localPath } of files) {
|
|
323
|
+
const uploaded = await uploadLocalTeamFile(localPath, {});
|
|
324
|
+
if (typeof uploaded.id !== 'string')
|
|
325
|
+
throw new ApiError(502, 'Team Files upload response did not include a file ID');
|
|
326
|
+
triggerData[field] = `mesh://team-files/${uploaded.id}`;
|
|
327
|
+
fileInputsMeta[field] = {
|
|
328
|
+
fileId: uploaded.id,
|
|
329
|
+
name: typeof uploaded.name === 'string' ? uploaded.name : localPath,
|
|
330
|
+
size: typeof uploaded.fileSize === 'number' ? uploaded.fileSize : 0,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
printJson(dataRow(await client.post(path, files.length > 0 ? { triggerData, fileInputsMeta } : { triggerData })));
|
|
231
334
|
}
|
|
232
335
|
function propertyContainer(draft, pointer, target) {
|
|
233
336
|
if (!pointer.startsWith('/') || /~(?![01])/.test(pointer))
|
|
@@ -411,6 +514,7 @@ export function registerWorkflowCommand(program) {
|
|
|
411
514
|
cmd
|
|
412
515
|
.command('run <id>')
|
|
413
516
|
.option('--json <inputs>', 'Trigger inputs as JSON')
|
|
517
|
+
.option('--file <field=path>', 'Upload a local file for a form file field (repeatable)', (value, previous) => [...previous, value], [])
|
|
414
518
|
.option('--dry-run', 'Preview execution')
|
|
415
519
|
.action(async (id, o) => action(() => runWorkflowAction(id, o)));
|
|
416
520
|
}
|
package/dist/main.js
CHANGED
|
@@ -54,6 +54,10 @@ program
|
|
|
54
54
|
(actionCommand.name() === 'validate' && actionCommand.parent?.name() === 'data-table') ||
|
|
55
55
|
((actionCommand.name() === 'validate' || actionCommand.name() === 'init') &&
|
|
56
56
|
actionCommand.parent?.name() === 'codepack') ||
|
|
57
|
+
// A local test run needs no region; --remote does.
|
|
58
|
+
(actionCommand.name() === 'test' &&
|
|
59
|
+
actionCommand.parent?.name() === 'codepack' &&
|
|
60
|
+
!actionCommand.opts().remote) ||
|
|
57
61
|
((actionCommand.name() === 'validate' || actionCommand.name() === 'starter') &&
|
|
58
62
|
actionCommand.parent?.name() === 'custom-page') ||
|
|
59
63
|
actionCommand.parent?.name() === 'schema' ||
|