@diagonal-hq/cli 0.38.1 → 0.38.3

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.
@@ -0,0 +1,52 @@
1
+ import { createRequire as __diagonalCreateRequire } from 'node:module';
2
+ const require = __diagonalCreateRequire(import.meta.url);
3
+
4
+ // scripts/lib/workflow-script/constants.mjs
5
+ var PROFILES = {
6
+ workflow: {
7
+ label: "A workflow script",
8
+ imports: ["@diagonal/workflow", "@diagonal/workflow/workspace"],
9
+ specifier: null,
10
+ entry: null,
11
+ defaultExports: ["defineWorkflow"]
12
+ },
13
+ test: {
14
+ label: "A test script",
15
+ imports: ["@diagonal/workflow", "@diagonal-hq/workflows/test", "@diagonal/workflow/workspace"],
16
+ specifier: "@diagonal-hq/workflows/test",
17
+ entry: "/sdk/profiles/test.ts",
18
+ defaultExports: ["defineWorkflow"]
19
+ }
20
+ };
21
+ var PROFILE_SPECIFIERS = new Set(
22
+ Object.values(PROFILES).flatMap(({ specifier }) => specifier === null ? [] : [specifier])
23
+ );
24
+
25
+ // scripts/lib/runtime-build/string-facts.mjs
26
+ var URL_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
27
+ function isUrl(value) {
28
+ return URL_PATTERN.test(value) && URL.canParse(value);
29
+ }
30
+ function isTimezone(value) {
31
+ try {
32
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
33
+ } catch (error) {
34
+ if (error instanceof RangeError) {
35
+ return false;
36
+ }
37
+ throw error;
38
+ }
39
+ return value.includes("/") || value === "UTC";
40
+ }
41
+ function stringFacts(strings) {
42
+ const facts = /* @__PURE__ */ Object.create(null);
43
+ for (const text of strings) {
44
+ facts[text] = [isTimezone(text), isUrl(text), !Number.isNaN(Date.parse(text))];
45
+ }
46
+ return facts;
47
+ }
48
+
49
+ export {
50
+ stringFacts,
51
+ PROFILES
52
+ };
@@ -0,0 +1,359 @@
1
+ import { createRequire as __diagonalCreateRequire } from 'node:module';
2
+ const require = __diagonalCreateRequire(import.meta.url);
3
+
4
+ // scripts/lib/runtime-build/api-cli.mjs
5
+ var WORKFLOWS_USAGE = "Usage: diagonal workflows [--json]";
6
+ var RUN_USAGE = "Usage: diagonal run <path> [--input '<json object>'] [--json]";
7
+ var LOGS_USAGE = "Usage: diagonal logs [path | execution id] [--status <success|error|exception|started|pending>] [--limit <1-100>] [--json]";
8
+ var SUCCESS = "execution.success";
9
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ var STATUSES = ["success", "error", "exception", "started", "pending"];
11
+ function credentials(env, stderr) {
12
+ const url = env.DIAGONAL_URL?.trim().replace(/\/+$/, "") ?? "";
13
+ const apiKey = env.DIAGONAL_API_KEY?.trim() ?? "";
14
+ if (url === "" || apiKey === "") {
15
+ stderr.write(
16
+ "Set DIAGONAL_URL to the workspace URL and DIAGONAL_API_KEY to an API key of a System Administrator.\n"
17
+ );
18
+ return null;
19
+ }
20
+ return { url, apiKey };
21
+ }
22
+ function errorText(status, body) {
23
+ const lines = [`Request failed with HTTP ${status}${body?.message ? `: ${body.message}` : ""}`];
24
+ for (const messages of Object.values(body?.errors ?? {})) {
25
+ for (const message of messages) {
26
+ if (message !== body.message) {
27
+ lines.push(` ${message}`);
28
+ }
29
+ }
30
+ }
31
+ return `${lines.join("\n")}
32
+ `;
33
+ }
34
+ async function request({ url, apiKey }, method, path, body, stderr, { responseDetails = false } = {}) {
35
+ const headers = { Accept: "application/json", Authorization: `Bearer ${apiKey}` };
36
+ const init = body === void 0 || body instanceof FormData ? { method, headers, body } : {
37
+ method,
38
+ headers: { ...headers, "Content-Type": "application/json" },
39
+ body: JSON.stringify(body)
40
+ };
41
+ let response;
42
+ let text;
43
+ try {
44
+ response = await fetch(`${url}${path}`, init);
45
+ text = await response.text();
46
+ } catch (error) {
47
+ if (!(error instanceof TypeError)) {
48
+ throw error;
49
+ }
50
+ stderr.write(`Could not reach ${url}: ${error.cause?.message ?? error.message}
51
+ `);
52
+ return null;
53
+ }
54
+ let json;
55
+ try {
56
+ json = JSON.parse(text);
57
+ } catch (error) {
58
+ if (!(error instanceof SyntaxError)) {
59
+ throw error;
60
+ }
61
+ stderr.write(`HTTP ${response.status} from ${url}${path} is not JSON.
62
+ `);
63
+ return null;
64
+ }
65
+ if (responseDetails) {
66
+ return { ok: response.ok, status: response.status, body: json };
67
+ }
68
+ if (!response.ok) {
69
+ stderr.write(errorText(response.status, json));
70
+ return null;
71
+ }
72
+ return json;
73
+ }
74
+ function parseFlags(args, valueFlags, booleanFlags) {
75
+ const positional = [];
76
+ const values = {};
77
+ const booleans = /* @__PURE__ */ new Set();
78
+ for (let index = 0; index < args.length; index++) {
79
+ const arg = args[index];
80
+ if (!arg.startsWith("--")) {
81
+ positional.push(arg);
82
+ continue;
83
+ }
84
+ if (booleanFlags.includes(arg)) {
85
+ booleans.add(arg);
86
+ continue;
87
+ }
88
+ if (!valueFlags.includes(arg)) {
89
+ return { error: `Unknown option ${arg}` };
90
+ }
91
+ if (index + 1 >= args.length || args[index + 1].startsWith("--")) {
92
+ return { error: `${arg} needs a value` };
93
+ }
94
+ values[arg] = args[++index];
95
+ }
96
+ return { positional, values, booleans };
97
+ }
98
+ async function listWorkflows(args, { env, stdout, stderr }) {
99
+ const parsed = parseFlags(args, [], ["--json"]);
100
+ if (parsed.error !== void 0 || parsed.positional.length > 0) {
101
+ stderr.write(
102
+ `${parsed.error ?? "diagonal workflows takes no arguments"}
103
+ ${WORKFLOWS_USAGE}
104
+ `
105
+ );
106
+ return 2;
107
+ }
108
+ const target = credentials(env, stderr);
109
+ if (target === null) {
110
+ return 2;
111
+ }
112
+ const body = await request(target, "GET", "/api/runtime/workflows", void 0, stderr);
113
+ if (body === null) {
114
+ return 1;
115
+ }
116
+ if (parsed.booleans.has("--json")) {
117
+ stdout.write(`${JSON.stringify(body, null, 2)}
118
+ `);
119
+ return 0;
120
+ }
121
+ if (body.active_sha === null) {
122
+ stdout.write("The workspace has no active deployment.\n");
123
+ return 0;
124
+ }
125
+ const rows = body.data.map((workflow) => [workflow.path, workflow.type, workflow.title]);
126
+ const widths = [0, 1].map((column) => Math.max(...rows.map((row) => row[column].length)));
127
+ for (const row of rows) {
128
+ stdout.write(`${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}
129
+ `);
130
+ }
131
+ stdout.write(
132
+ `${rows.length} workflow${rows.length === 1 ? "" : "s"} at ${body.active_sha.slice(0, 7)}
133
+ `
134
+ );
135
+ return 0;
136
+ }
137
+ function parseRunArguments(args) {
138
+ const parsed = parseFlags(args, ["--input"], ["--json"]);
139
+ if (parsed.error !== void 0) {
140
+ return parsed;
141
+ }
142
+ if (parsed.positional.length !== 1) {
143
+ return {
144
+ error: "Give one workflow path, for example workflows/seed-catalog.ts"
145
+ };
146
+ }
147
+ const json = parsed.booleans.has("--json");
148
+ const path = parsed.positional[0].replace(/^\.\//, "");
149
+ const rawInput = parsed.values["--input"];
150
+ if (rawInput === void 0) {
151
+ return { path, input: {}, json };
152
+ }
153
+ let input;
154
+ try {
155
+ input = JSON.parse(rawInput);
156
+ } catch (error) {
157
+ if (!(error instanceof SyntaxError)) {
158
+ throw error;
159
+ }
160
+ return { error: `--input is not valid JSON: ${error.message}` };
161
+ }
162
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
163
+ return { error: "--input must be a JSON object" };
164
+ }
165
+ return { path, input, json };
166
+ }
167
+ async function runWorkflow(args, { env, stdout, stderr }) {
168
+ const parsed = parseRunArguments(args);
169
+ if (parsed.error !== void 0) {
170
+ stderr.write(`${parsed.error}
171
+ ${RUN_USAGE}
172
+ `);
173
+ return 2;
174
+ }
175
+ const target = credentials(env, stderr);
176
+ if (target === null) {
177
+ return 2;
178
+ }
179
+ const body = await request(
180
+ target,
181
+ "POST",
182
+ `/api/runtime/workflows/run?path=${encodeURIComponent(parsed.path)}`,
183
+ { input: parsed.input },
184
+ stderr
185
+ );
186
+ if (body === null) {
187
+ return 1;
188
+ }
189
+ const succeeded = body.status === SUCCESS;
190
+ if (parsed.json) {
191
+ stdout.write(`${JSON.stringify(body, null, 2)}
192
+ `);
193
+ return succeeded ? 0 : 1;
194
+ }
195
+ stdout.write(`${body.path} ${body.status} (execution ${body.execution_id})
196
+ `);
197
+ if (body.output !== null && body.output !== void 0) {
198
+ stdout.write(`${JSON.stringify(body.output, null, 2)}
199
+ `);
200
+ }
201
+ return succeeded ? 0 : 1;
202
+ }
203
+ function parseLogsArguments(args) {
204
+ const parsed = parseFlags(args, ["--status", "--limit"], ["--json"]);
205
+ if (parsed.error !== void 0) {
206
+ return parsed;
207
+ }
208
+ if (parsed.positional.length > 1) {
209
+ return { error: "Give at most one workflow path or execution id" };
210
+ }
211
+ const target = parsed.positional[0]?.replace(/^\.\//, "") ?? null;
212
+ const status = parsed.values["--status"] ?? null;
213
+ const rawLimit = parsed.values["--limit"];
214
+ const limit = rawLimit === void 0 ? null : Number(rawLimit);
215
+ if (status !== null && !STATUSES.includes(status)) {
216
+ return { error: `--status must be one of ${STATUSES.join(", ")}` };
217
+ }
218
+ if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {
219
+ return { error: "--limit must be a whole number from 1 to 100" };
220
+ }
221
+ const execution = target !== null && UUID.test(target) ? target : null;
222
+ if (execution !== null && (status !== null || limit !== null)) {
223
+ return {
224
+ error: "--status and --limit apply to a list of runs, not to one execution"
225
+ };
226
+ }
227
+ return {
228
+ execution,
229
+ path: execution === null ? target : null,
230
+ status,
231
+ limit,
232
+ json: parsed.booleans.has("--json")
233
+ };
234
+ }
235
+ function runDuration(run) {
236
+ if (run.duration_ms === null || run.duration_ms === void 0) {
237
+ return "";
238
+ }
239
+ return run.duration_ms < 1e3 ? `${run.duration_ms}ms` : `${(run.duration_ms / 1e3).toFixed(1)}s`;
240
+ }
241
+ function errorLines(error, indent) {
242
+ if (error === null || error === void 0) {
243
+ return [];
244
+ }
245
+ const lines = [`${indent}${error.type ?? "Error"}: ${error.message ?? "(no message)"}`];
246
+ const fieldErrors = Array.isArray(error.errors) ? error.errors : Object.entries(error.errors ?? {});
247
+ for (const [field, messages] of fieldErrors) {
248
+ for (const message of Array.isArray(messages) ? messages : [messages]) {
249
+ lines.push(`${indent} ${field}: ${message}`);
250
+ }
251
+ }
252
+ return lines;
253
+ }
254
+ function runLine(run) {
255
+ const trigger = run.trigger?.request_path ?? run.trigger?.type ?? "";
256
+ const status = run.response_status_code === null ? run.status : `${run.status} ${run.response_status_code}`;
257
+ return [run.started_at, status, run.path, trigger, runDuration(run), run.execution_id].filter((part) => part !== "").join(" ");
258
+ }
259
+ async function showLogs(args, { env, stdout, stderr }) {
260
+ const parsed = parseLogsArguments(args);
261
+ if (parsed.error !== void 0) {
262
+ stderr.write(`${parsed.error}
263
+ ${LOGS_USAGE}
264
+ `);
265
+ return 2;
266
+ }
267
+ const target = credentials(env, stderr);
268
+ if (target === null) {
269
+ return 2;
270
+ }
271
+ if (parsed.execution !== null) {
272
+ const run = await request(
273
+ target,
274
+ "GET",
275
+ `/api/runtime/executions/${parsed.execution}`,
276
+ void 0,
277
+ stderr
278
+ );
279
+ if (run === null) {
280
+ return 1;
281
+ }
282
+ if (parsed.json) {
283
+ stdout.write(`${JSON.stringify(run, null, 2)}
284
+ `);
285
+ return 0;
286
+ }
287
+ stdout.write(`${runLine(run)}
288
+ `);
289
+ if (run.error !== null) {
290
+ stdout.write(`${JSON.stringify(run.error, null, 2)}
291
+ `);
292
+ } else if (run.output !== null) {
293
+ stdout.write(`${JSON.stringify(run.output, null, 2)}
294
+ `);
295
+ }
296
+ return 0;
297
+ }
298
+ const query = new URLSearchParams();
299
+ if (parsed.path !== null) {
300
+ query.set("workflow", parsed.path);
301
+ }
302
+ if (parsed.status !== null) {
303
+ query.set("status", parsed.status);
304
+ }
305
+ if (parsed.limit !== null) {
306
+ query.set("limit", String(parsed.limit));
307
+ }
308
+ const suffix = query.size === 0 ? "" : `?${query}`;
309
+ const body = await request(target, "GET", `/api/runtime/executions${suffix}`, void 0, stderr);
310
+ if (body === null) {
311
+ return 1;
312
+ }
313
+ if (parsed.json) {
314
+ stdout.write(`${JSON.stringify(body, null, 2)}
315
+ `);
316
+ return 0;
317
+ }
318
+ if (body.data.length === 0) {
319
+ stdout.write("No runs.\n");
320
+ return 0;
321
+ }
322
+ for (const run of [...body.data].reverse()) {
323
+ stdout.write(`${[runLine(run), ...errorLines(run.error, " ")].join("\n")}
324
+ `);
325
+ }
326
+ return 0;
327
+ }
328
+
329
+ // scripts/lib/runtime-build/assets-cli-usage.mjs
330
+ var ASSETS_UPLOAD_USAGE = "Usage: diagonal assets upload <file> [--key <key>] [--no-write] [--json]";
331
+ var ASSETS_LIST_USAGE = "Usage: diagonal assets list [--search <text>] [--versions] [--json]";
332
+
333
+ // scripts/lib/runtime-build/format-diagnostic.mjs
334
+ function formatDiagnostic(diagnostic) {
335
+ const [headline, ...details] = diagnostic.message.split("\n");
336
+ const lines = [
337
+ `${diagnostic.path}:${diagnostic.line}:${diagnostic.column} ${diagnostic.severity} ${headline}`
338
+ ];
339
+ for (const detail of details) {
340
+ lines.push(` ${detail}`);
341
+ }
342
+ return lines.join("\n");
343
+ }
344
+
345
+ export {
346
+ WORKFLOWS_USAGE,
347
+ RUN_USAGE,
348
+ LOGS_USAGE,
349
+ credentials,
350
+ errorText,
351
+ request,
352
+ parseFlags,
353
+ listWorkflows,
354
+ runWorkflow,
355
+ showLogs,
356
+ ASSETS_UPLOAD_USAGE,
357
+ ASSETS_LIST_USAGE,
358
+ formatDiagnostic
359
+ };
@@ -0,0 +1,63 @@
1
+ import { createRequire as __diagonalCreateRequire } from 'node:module';
2
+ const require = __diagonalCreateRequire(import.meta.url);
3
+ import {
4
+ AssetVersionValue,
5
+ SourceError,
6
+ defaultExportOf,
7
+ expectDefineCall,
8
+ staticObject
9
+ } from "./cli-chunk-F2J44UIS.mjs";
10
+
11
+ // scripts/lib/runtime-build/assets.mjs
12
+ var ASSET_KEY = /^[a-z][A-Za-z0-9]*$/;
13
+ var MAX_ASSET_VERSIONS = 500;
14
+ var VERSION_REFERENCE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
15
+ function isAssetKey(key) {
16
+ return key.length <= 64 && ASSET_KEY.test(key);
17
+ }
18
+ function assetKeyMessage(key) {
19
+ return `Asset key "${key}" must be a camelCase name of at most 64 letters and digits that starts with a lowercase letter, such as 'hero'`;
20
+ }
21
+ function assetLibraryMessage(reference) {
22
+ return `Asset version "${reference}" is not in this application's asset library`;
23
+ }
24
+ function buildAssets(ast, catalog) {
25
+ const { declaration } = defaultExportOf(ast);
26
+ const [definition] = expectDefineCall(declaration, "defineAssets", 1);
27
+ const { value, nodes } = staticObject(definition, { assetVersions: true });
28
+ if (Object.keys(value).length > MAX_ASSET_VERSIONS) {
29
+ throw new SourceError("assets.ts can have at most 500 entries.", declaration);
30
+ }
31
+ return Object.entries(value).map(([key, version]) => {
32
+ if (!isAssetKey(key)) {
33
+ throw new SourceError(assetKeyMessage(key), nodes[key].key);
34
+ }
35
+ if (!(version instanceof AssetVersionValue)) {
36
+ throw new SourceError(
37
+ "An asset value must be asset.version('<reference>')",
38
+ nodes[key].value
39
+ );
40
+ }
41
+ if (!VERSION_REFERENCE.test(version.reference)) {
42
+ throw new SourceError("An asset version reference must be a lower-case UUID", version.node);
43
+ }
44
+ if (catalog !== null && !Object.hasOwn(catalog, version.reference)) {
45
+ throw new SourceError(assetLibraryMessage(version.reference), version.node);
46
+ }
47
+ return {
48
+ key,
49
+ reference: version.reference,
50
+ line: version.node.loc.start.line,
51
+ column: version.node.loc.start.column + 1
52
+ };
53
+ });
54
+ }
55
+ var GENERATED_ASSETS_PATH = "generated/assets.ts";
56
+
57
+ export {
58
+ isAssetKey,
59
+ assetKeyMessage,
60
+ assetLibraryMessage,
61
+ buildAssets,
62
+ GENERATED_ASSETS_PATH
63
+ };