@mediaruntime/cli 0.2.1 → 1.1.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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0 — 2026-08-18
4
+
5
+ - Add unauthenticated `capabilities` and `presets list` discovery commands backed by the
6
+ live gateway contract.
7
+ - Add repeated `--preset <public-preset>` execution while preserving `-o` and `--output`
8
+ for the six frozen aliases.
9
+ - Resolve preset output types from the gateway's ordered public catalog instead of
10
+ copying engine preset metadata into the CLI.
11
+ - Upgrade to `@mediaruntime/node` 1.1.1 capability contracts.
12
+
13
+ ## 1.0.0 — 2026-08-16
14
+
15
+ - Declare the documented CLI surface stable under semantic versioning, including command
16
+ names, flags, JSON envelopes, exit codes, and credential precedence.
17
+ - Require supported Node.js 22 or newer runtimes and depend on `@mediaruntime/node` 1.x.
18
+ - Point legacy package tooling at the shipped executable instead of a nonexistent entry.
19
+ - Freeze local upload, browser authentication, job inspection, atomic ZIP download,
20
+ interactive progress, and loopback webhook-trigger behavior as the v1 contract.
21
+
3
22
  ## 0.2.1 — 2026-08-16
4
23
 
5
24
  - Show an elapsed-time activity spinner during interactive local upload, job waiting,
package/README.md CHANGED
@@ -4,6 +4,10 @@ Official command-line client for MediaRuntime. It submits media, waits for jobs,
4
4
  the canonical ZIP output bundle, inspects account jobs, and sends correctly signed
5
5
  synthetic webhooks to a local receiver.
6
6
 
7
+ Status: stable `1.1.0`. The documented `1.x` command names, flags, JSON envelopes, exit
8
+ codes, and credential precedence follow semantic versioning. Breaking changes require a
9
+ new major version; additive commands and fields may ship in minor releases.
10
+
7
11
  ## Install
8
12
 
9
13
  ```bash
@@ -11,7 +15,7 @@ npm install --global @mediaruntime/cli
11
15
  mediaruntime --version
12
16
  ```
13
17
 
14
- Node.js 20 or newer is required. For interactive use, authorize through the browser once:
18
+ Node.js 22 or newer is required. For interactive use, authorize through the browser once:
15
19
 
16
20
  ```bash
17
21
  mediaruntime login
@@ -65,6 +69,24 @@ Supported frozen output aliases:
65
69
  - `audio.transcription`
66
70
  - `image.web`
67
71
 
72
+ Discover the live public catalog without signing in, then select an explicit preset when
73
+ an alias is not specific enough:
74
+
75
+ ```bash
76
+ mediaruntime capabilities
77
+ mediaruntime presets list
78
+ mediaruntime presets list --json
79
+
80
+ mediaruntime run ./launch.mp4 \
81
+ --preset dash_ladder_v1 \
82
+ --preset webm_vp9_1080p \
83
+ --download ./adaptive-and-vp9.zip
84
+ ```
85
+
86
+ `--preset` accepts only IDs in the gateway's current `publicPresets` catalog. The CLI
87
+ retrieves the catalog and supplies the preset's required output type automatically. Alias
88
+ and preset selections may be mixed and repeated in one command.
89
+
68
90
  Use `--json` for one compact, URL-redacted machine-readable result. A caller-provided
69
91
  `--idempotency-key` remains the durable deduplication mechanism across process restarts;
70
92
  the SDK-generated invocation key only protects retries inside one live command.
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ListJobsParams, JobPage, JobDetails, CreateJobParams, JobReceiptData, WaitForJobOptions } from '@mediaruntime/node';
1
+ import { Capabilities, ListJobsParams, JobPage, JobDetails, CreateJobParams, JobReceiptData, WaitForJobOptions } from '@mediaruntime/node';
2
2
 
3
3
  interface StoredCredential {
4
4
  apiKey: string;
@@ -13,6 +13,10 @@ interface CredentialStore {
13
13
  delete(baseUrl: string): Promise<void>;
14
14
  }
15
15
 
16
+ interface CapabilitiesReadClient {
17
+ retrieve(): Promise<Capabilities>;
18
+ }
19
+
16
20
  interface JobsReadClient {
17
21
  list(params?: ListJobsParams): Promise<JobPage>;
18
22
  get(jobId: string): Promise<JobDetails>;
@@ -87,6 +91,7 @@ declare function runAuthCommand(args: string[], baseUrl: string, dependencies?:
87
91
  type CliJobsClient = RunJobsClient & JobsReadClient;
88
92
  interface CliClient {
89
93
  jobs: CliJobsClient;
94
+ capabilities: CapabilitiesReadClient;
90
95
  }
91
96
  interface CliDependencies {
92
97
  createClient?(options: {
package/dist/cli.js CHANGED
@@ -358,6 +358,93 @@ async function runAuthCommand(args, baseUrl, dependencies = {}) {
358
358
  return runAuthStatusCommand(args.slice(1), baseUrl, dependencies);
359
359
  }
360
360
 
361
+ // src/commands/capabilities.ts
362
+ function cell(value) {
363
+ return value || "-";
364
+ }
365
+ function table(headings, rows) {
366
+ const widths = headings.map(
367
+ (heading, index) => Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0))
368
+ );
369
+ const render = (row) => row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(" ").trimEnd();
370
+ return `${[
371
+ render(headings),
372
+ render(widths.map((width) => "-".repeat(width))),
373
+ ...rows.map(render)
374
+ ].join("\n")}
375
+ `;
376
+ }
377
+ function publicPresetRows(capabilities) {
378
+ return capabilities.publicPresets.map((name) => {
379
+ const preset = capabilities.presets[name];
380
+ if (!preset) {
381
+ throw new Error(`Gateway capability contract is missing public preset metadata for ${name}`);
382
+ }
383
+ return {
384
+ name,
385
+ outputType: preset.outputType,
386
+ tier: preset.baseTier,
387
+ sourceKinds: preset.sourceKinds,
388
+ artifacts: preset.artifacts,
389
+ description: preset.description,
390
+ codec: preset.codec ?? null,
391
+ container: preset.container ?? null
392
+ };
393
+ });
394
+ }
395
+ function parseJsonOnly(args, command) {
396
+ let json = false;
397
+ for (const argument of args) {
398
+ if (argument === "--json") json = true;
399
+ else throw new UsageError(`Unknown ${command} option: ${argument}`);
400
+ }
401
+ return json;
402
+ }
403
+ async function runCapabilitiesCommand(args, dependencies) {
404
+ const json = parseJsonOnly(args, "capabilities");
405
+ const capabilities = await dependencies.capabilities.retrieve();
406
+ if (json) {
407
+ dependencies.writeStdout(`${JSON.stringify(capabilities)}
408
+ `);
409
+ return 0;
410
+ }
411
+ const aliases = Object.entries(capabilities.outputAliases).map(([name, value]) => [
412
+ name,
413
+ value.type,
414
+ value.preset,
415
+ value.tier
416
+ ]);
417
+ dependencies.writeStdout(
418
+ `Public presets: ${capabilities.publicPresets.length}
419
+ Optional features: ${Object.keys(capabilities.features).sort().join(", ") || "none"}
420
+
421
+ ` + table(["ALIAS", "TYPE", "PRESET", "TIER"], aliases) + "\nRun `mediaruntime presets list` for the complete public preset catalog.\n"
422
+ );
423
+ return 0;
424
+ }
425
+ async function runPresetsCommand(args, dependencies) {
426
+ const subcommand = args[0];
427
+ if (subcommand !== "list") throw new UsageError("Usage: mediaruntime presets list [--json]");
428
+ const json = parseJsonOnly(args.slice(1), "presets list");
429
+ const capabilities = await dependencies.capabilities.retrieve();
430
+ const presets = publicPresetRows(capabilities);
431
+ if (json) dependencies.writeStdout(`${JSON.stringify({ presets })}
432
+ `);
433
+ else {
434
+ dependencies.writeStdout(table(
435
+ ["PRESET", "TYPE", "TIER", "INPUTS", "ARTIFACTS"],
436
+ presets.map((preset) => [
437
+ preset.name,
438
+ cell(preset.outputType),
439
+ cell(preset.tier),
440
+ preset.sourceKinds.join(","),
441
+ preset.artifacts.join(", ")
442
+ ])
443
+ ));
444
+ }
445
+ return 0;
446
+ }
447
+
361
448
  // src/commands/jobs.ts
362
449
  var UNSUCCESSFUL_TERMINAL_STATUSES = /* @__PURE__ */ new Set(["FAILED", "REJECTED", "PARTIAL"]);
363
450
  function optionValue(args, index, option) {
@@ -400,7 +487,7 @@ function humanDetails(job) {
400
487
  return `${lines.join("\n")}
401
488
  `;
402
489
  }
403
- function cell(value) {
490
+ function cell2(value) {
404
491
  if (value === null || value === void 0 || value === "") return "-";
405
492
  return String(value);
406
493
  }
@@ -408,10 +495,10 @@ function humanList(page) {
408
495
  const rows = page.jobs.map((job) => [
409
496
  job.id,
410
497
  job.status,
411
- cell(job.tierBilled),
412
- cell(job.unitsTotal),
498
+ cell2(job.tierBilled),
499
+ cell2(job.unitsTotal),
413
500
  job.bundleAvailable ? "yes" : "no",
414
- cell(job.updatedAt)
501
+ cell2(job.updatedAt)
415
502
  ]);
416
503
  const headings = ["ID", "STATUS", "TIER", "UNITS", "BUNDLE", "UPDATED"];
417
504
  const widths = headings.map(
@@ -558,7 +645,10 @@ function parseRunOptions(args) {
558
645
  for (let index = 0; index < args.length; index += 1) {
559
646
  const argument = args[index];
560
647
  if (argument === "--output" || argument === "-o") {
561
- outputs.push(optionValue2(args, index, argument));
648
+ outputs.push({ kind: "alias", value: optionValue2(args, index, argument) });
649
+ index += 1;
650
+ } else if (argument === "--preset") {
651
+ outputs.push({ kind: "preset", value: optionValue2(args, index, argument) });
562
652
  index += 1;
563
653
  } else if (argument === "--metadata") {
564
654
  metadata = parseMetadata(optionValue2(args, index, argument));
@@ -591,10 +681,14 @@ function parseRunOptions(args) {
591
681
  throw new UsageError("run accepts exactly one source");
592
682
  }
593
683
  }
594
- if (!source) throw new UsageError("Usage: mediaruntime run <source> --output <alias> [--wait]");
595
- if (outputs.length === 0) throw new UsageError("run requires at least one --output");
596
- const unsupported = outputs.find((output) => !OUTPUT_ALIASES.has(output));
597
- if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported}`);
684
+ if (!source) {
685
+ throw new UsageError("Usage: mediaruntime run <source> (--output <alias> | --preset <name>) [--wait]");
686
+ }
687
+ if (outputs.length === 0) throw new UsageError("run requires at least one --output or --preset");
688
+ const unsupported = outputs.find(
689
+ (output) => output.kind === "alias" && !OUTPUT_ALIASES.has(output.value)
690
+ );
691
+ if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported.value}`);
598
692
  if (force && !download) throw new UsageError("--force requires --download");
599
693
  if (timeoutMs !== void 0 && !wait) throw new UsageError("--timeout-ms requires --wait or --download");
600
694
  return {
@@ -609,6 +703,21 @@ function parseRunOptions(args) {
609
703
  json
610
704
  };
611
705
  }
706
+ async function resolveOutputs(selections, capabilitiesClient) {
707
+ if (!selections.some((selection) => selection.kind === "preset")) {
708
+ return selections.map((selection) => selection.value);
709
+ }
710
+ const capabilities = await capabilitiesClient.retrieve();
711
+ const publicPresets = new Set(capabilities.publicPresets);
712
+ return selections.map((selection) => {
713
+ if (selection.kind === "alias") return selection.value;
714
+ const preset = capabilities.presets[selection.value];
715
+ if (!publicPresets.has(selection.value) || !preset) {
716
+ throw new UsageError(`Unknown or non-public preset: ${selection.value}`);
717
+ }
718
+ return { type: preset.outputType, preset: selection.value };
719
+ });
720
+ }
612
721
  function receiptProjection(job) {
613
722
  return {
614
723
  id: job.id,
@@ -660,9 +769,10 @@ Bundle: ${job.bundle.available ? "available" : "unavailable"}${error}
660
769
  }
661
770
  async function runCommand(args, dependencies) {
662
771
  const options = parseRunOptions(args);
772
+ const outputs = await resolveOutputs(options.outputs, dependencies.capabilities);
663
773
  const params = {
664
774
  source: options.source,
665
- outputs: options.outputs,
775
+ outputs,
666
776
  ...options.metadata === void 0 ? {} : { metadata: options.metadata },
667
777
  ...options.idempotencyKey === void 0 ? {} : { idempotencyKey: options.idempotencyKey }
668
778
  };
@@ -1040,11 +1150,13 @@ function createActivityIndicator(write, enabled) {
1040
1150
  }
1041
1151
 
1042
1152
  // src/cli.ts
1043
- var VERSION = "0.2.1";
1153
+ var VERSION = "1.1.0";
1044
1154
  var HELP = `MediaRuntime CLI
1045
1155
 
1046
1156
  Usage:
1047
- mediaruntime run <source> --output <alias> [--output <alias>] [--wait]
1157
+ mediaruntime run <source> (--output <alias> | --preset <name>) [...] [--wait]
1158
+ mediaruntime capabilities [--json]
1159
+ mediaruntime presets list [--json]
1048
1160
  mediaruntime jobs list [--status <status>] [--limit <n>] [--cursor <cursor>]
1049
1161
  mediaruntime jobs get <job_id> [--download <bundle.zip>] [--force]
1050
1162
  mediaruntime trigger <job.completed|job.failed|job.rejected> --to <local-url>
@@ -1228,6 +1340,18 @@ async function executeCli(argv, dependencies = {}) {
1228
1340
  if (command === "login") return await runLoginCommand(global.args.slice(1), authBaseUrl, authDependencies);
1229
1341
  if (command === "auth") return await runAuthCommand(global.args.slice(1), authBaseUrl, authDependencies);
1230
1342
  if (command === "logout") return await runLogoutCommand(global.args.slice(1), authBaseUrl, authDependencies);
1343
+ if (command === "capabilities" || command === "presets") {
1344
+ const publicClient = dependencies.createClient?.({
1345
+ ...baseUrl === void 0 ? {} : { baseUrl }
1346
+ }) ?? new MediaRuntime({
1347
+ ...baseUrl === void 0 ? {} : { baseUrl }
1348
+ });
1349
+ const publicDependencies = { capabilities: publicClient.capabilities, writeStdout };
1350
+ if (command === "capabilities") {
1351
+ return await runCapabilitiesCommand(global.args.slice(1), publicDependencies);
1352
+ }
1353
+ return await runPresetsCommand(global.args.slice(1), publicDependencies);
1354
+ }
1231
1355
  let apiKey = process.env.MEDIARUNTIME_API_KEY?.trim();
1232
1356
  if (!apiKey && (!dependencies.createClient || dependencies.credentialStore)) {
1233
1357
  apiKey = (await resolveCredential(authBaseUrl, authDependencies))?.apiKey;
@@ -1245,6 +1369,7 @@ async function executeCli(argv, dependencies = {}) {
1245
1369
  const downloadBundle = dependencies.downloadBundle ?? downloadBundleAtomically;
1246
1370
  const commandDependencies = {
1247
1371
  jobs: client.jobs,
1372
+ capabilities: client.capabilities,
1248
1373
  writeStdout,
1249
1374
  downloadBundle,
1250
1375
  activity: createActivityIndicator(writeStderr, isStderrTTY && !json)
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/errors.ts","../src/auth/api.ts","../src/commands/auth.ts","../src/auth/browser.ts","../src/auth/credential-store.ts","../src/commands/jobs.ts","../src/commands/run.ts","../src/commands/trigger.ts","../src/trigger/destination.ts","../src/trigger/event.ts","../src/trigger/signature.ts","../src/ui/activity.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { constants, realpathSync } from \"node:fs\";\nimport {\n access,\n link,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { createWriteStream } from \"node:fs\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n JobWaitTimeoutError,\n MediaRuntime,\n MediaRuntimeApiError,\n MediaRuntimeConnectionError,\n} from \"@mediaruntime/node\";\nimport { PRODUCTION_ORIGIN } from \"./auth/api.js\";\nimport type { CredentialStore } from \"./auth/credential-store.js\";\nimport {\n resolveCredential,\n runAuthCommand,\n runLoginCommand,\n runLogoutCommand,\n type AuthCommandDependencies,\n} from \"./commands/auth.js\";\nimport {\n runJobsCommand,\n type JobsReadClient,\n} from \"./commands/jobs.js\";\nimport {\n runCommand,\n type RunJobsClient,\n} from \"./commands/run.js\";\nimport { runTriggerCommand } from \"./commands/trigger.js\";\nimport { BundleDownloadError, CliError, UsageError } from \"./errors.js\";\nimport { isLoopbackDestination } from \"./trigger/destination.js\";\nimport { createActivityIndicator } from \"./ui/activity.js\";\n\nexport { parseTriggerArguments, runTriggerCommand } from \"./commands/trigger.js\";\nexport { createSyntheticTerminalEvent } from \"./trigger/event.js\";\nexport { signSyntheticWebhook } from \"./trigger/signature.js\";\nexport {\n resolveCredential,\n runAuthCommand,\n runAuthStatusCommand,\n runLoginCommand,\n runLogoutCommand,\n} from \"./commands/auth.js\";\n\nconst VERSION = \"0.2.1\";\nconst HELP = `MediaRuntime CLI\n\nUsage:\n mediaruntime run <source> --output <alias> [--output <alias>] [--wait]\n mediaruntime jobs list [--status <status>] [--limit <n>] [--cursor <cursor>]\n mediaruntime jobs get <job_id> [--download <bundle.zip>] [--force]\n mediaruntime trigger <job.completed|job.failed|job.rejected> --to <local-url>\n mediaruntime login [--no-browser]\n mediaruntime auth status\n mediaruntime logout [--local-only]\n\nGlobal options:\n --base-url <url> Developer override; normally leave unset\n --help Show help\n --version Show version\n\nRun/jobs options:\n --json Machine-readable, URL-redacted output\n\nAuthentication uses a secure login or MEDIARUNTIME_API_KEY.\n`;\n\ntype CliJobsClient = RunJobsClient & JobsReadClient;\n\nexport interface CliClient {\n jobs: CliJobsClient;\n}\n\nexport interface CliDependencies {\n createClient?(options: { baseUrl?: string; apiKey?: string }): CliClient;\n downloadBundle?(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n ): Promise<void>;\n writeStdout?(text: string): void;\n writeStderr?(text: string): void;\n isStderrTTY?: boolean;\n credentialStore?: CredentialStore;\n openBrowser?(url: string): Promise<void>;\n sleep?(milliseconds: number): Promise<void>;\n now?(): number;\n randomVerifier?(): string;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n return error instanceof Error && \"code\" in error && error.code === \"EEXIST\";\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function downloadBundleAtomically(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n): Promise<void> {\n const target = resolve(destination);\n if (!options.force && await exists(target)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n const temporary = resolve(\n dirname(target),\n `.${basename(target)}.${randomUUID()}.part`,\n );\n\n try {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new BundleDownloadError(\"Bundle download failed before receiving a response\", { cause: error });\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new BundleDownloadError(`Bundle download failed with HTTP ${response.status}`);\n }\n if (!response.body) throw new BundleDownloadError(\"Bundle download returned an empty response body\");\n const hash = createHash(\"sha256\");\n let sizeBytes = 0;\n const integrity = new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n sizeBytes += chunk.length;\n hash.update(chunk);\n callback(null, chunk);\n },\n });\n await pipeline(\n Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>),\n integrity,\n createWriteStream(temporary, { flags: \"wx\", mode: 0o600 }),\n );\n const sha256 = hash.digest(\"hex\");\n if (options.expectedSizeBytes !== undefined && options.expectedSizeBytes !== null &&\n sizeBytes !== options.expectedSizeBytes) {\n throw new BundleDownloadError(\n `Bundle size mismatch: expected ${options.expectedSizeBytes} bytes, received ${sizeBytes}`,\n );\n }\n if (options.expectedSha256 && sha256 !== options.expectedSha256.toLowerCase()) {\n throw new BundleDownloadError(\"Bundle SHA-256 mismatch\");\n }\n\n if (options.force) {\n await rename(temporary, target);\n } else {\n try {\n // A hard link publishes the completed same-filesystem temporary file atomically\n // and fails rather than replacing a destination created during the download.\n await link(temporary, target);\n } catch (error) {\n if (isFileExistsError(error)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n throw error;\n }\n await rm(temporary);\n }\n } catch (error) {\n await rm(temporary, { force: true });\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not write bundle to ${destination}`, { cause: error });\n }\n}\n\nfunction normalizeBaseUrl(raw: string): string {\n let value: URL;\n try {\n value = new URL(raw);\n } catch {\n throw new UsageError(\"--base-url must be an absolute HTTP(S) origin\");\n }\n if (value.username || value.password || value.search || value.hash || value.pathname !== \"/\") {\n throw new UsageError(\"--base-url must be an origin without credentials, path, query, or fragment\");\n }\n if (value.protocol !== \"https:\" && !(value.protocol === \"http:\" && isLoopbackDestination(value))) {\n throw new UsageError(\"--base-url must use HTTPS unless it points to loopback\");\n }\n return value.origin;\n}\n\nfunction extractGlobalOptions(argv: string[]): { baseUrl?: string; args: string[] } {\n const args = [...argv];\n let baseUrl: string | undefined;\n while (args[0] === \"--base-url\") {\n const value = args[1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(\"--base-url requires a value\");\n baseUrl = normalizeBaseUrl(value);\n args.splice(0, 2);\n }\n return { ...(baseUrl === undefined ? {} : { baseUrl }), args };\n}\n\nfunction safeApiError(error: MediaRuntimeApiError): Record<string, unknown> {\n return {\n name: error.name,\n message: error.message,\n code: error.code,\n status: error.status,\n retryable: error.retryable,\n requestId: error.requestId ?? null,\n field: error.field ?? null,\n };\n}\n\nfunction exitCodeFor(error: unknown): number {\n if (error instanceof CliError) return error.exitCode;\n if (error instanceof JobWaitTimeoutError) return 7;\n if (error instanceof MediaRuntimeConnectionError) return 5;\n if (error instanceof MediaRuntimeApiError) {\n if ([401, 402, 403].includes(error.status)) return 3;\n if (error.status >= 500) return 5;\n return 4;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") return 130;\n if (error instanceof TypeError && /fetch|network|socket|connect/i.test(error.message)) return 5;\n return 1;\n}\n\nfunction safeError(error: unknown, exitCode: number): Record<string, unknown> {\n if (error instanceof MediaRuntimeApiError) return { ...safeApiError(error), exitCode };\n return {\n code: error instanceof CliError ? error.code : \"cli_error\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n exitCode,\n };\n}\n\nexport async function executeCli(\n argv: string[],\n dependencies: CliDependencies = {},\n): Promise<number> {\n const writeStdout = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const writeStderr = dependencies.writeStderr ?? ((text: string) => process.stderr.write(text));\n const json = argv.includes(\"--json\");\n const isStderrTTY = dependencies.isStderrTTY ??\n (dependencies.writeStderr === undefined && process.stderr.isTTY === true);\n try {\n const global = extractGlobalOptions(argv);\n const command = global.args[0];\n if (!command || command === \"--help\" || command === \"-h\") {\n writeStdout(HELP);\n return 0;\n }\n if (command === \"--version\" || command === \"-v\") {\n writeStdout(`${VERSION}\\n`);\n return 0;\n }\n if (command === \"trigger\") {\n return await runTriggerCommand(global.args.slice(1), { writeStdout });\n }\n\n const configuredBaseUrl = global.baseUrl ?? process.env.MEDIARUNTIME_API_URL;\n const baseUrl = configuredBaseUrl ? normalizeBaseUrl(configuredBaseUrl) : undefined;\n const authBaseUrl = baseUrl ?? PRODUCTION_ORIGIN;\n const authDependencies: AuthCommandDependencies = {\n ...(dependencies.credentialStore ? { credentialStore: dependencies.credentialStore } : {}),\n ...(dependencies.openBrowser ? { openBrowser: dependencies.openBrowser } : {}),\n ...(dependencies.sleep ? { sleep: dependencies.sleep } : {}),\n ...(dependencies.now ? { now: dependencies.now } : {}),\n ...(dependencies.randomVerifier ? { randomVerifier: dependencies.randomVerifier } : {}),\n writeStdout,\n };\n if (command === \"login\") return await runLoginCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"auth\") return await runAuthCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"logout\") return await runLogoutCommand(global.args.slice(1), authBaseUrl, authDependencies);\n\n let apiKey = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (!apiKey && (!dependencies.createClient || dependencies.credentialStore)) {\n apiKey = (await resolveCredential(authBaseUrl, authDependencies))?.apiKey;\n }\n if (!dependencies.createClient && !apiKey) {\n throw new UsageError(\"Run mediaruntime login or set MEDIARUNTIME_API_KEY before using run or jobs\");\n }\n const client = dependencies.createClient?.({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n }) ?? new MediaRuntime({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n });\n const downloadBundle = dependencies.downloadBundle ?? downloadBundleAtomically;\n const commandDependencies = {\n jobs: client.jobs,\n writeStdout,\n downloadBundle,\n activity: createActivityIndicator(writeStderr, isStderrTTY && !json),\n };\n if (command === \"run\") return await runCommand(global.args.slice(1), commandDependencies);\n if (command === \"jobs\") {\n return await runJobsCommand(global.args.slice(1), commandDependencies);\n }\n throw new UsageError(`Unknown command: ${command}`);\n } catch (error) {\n const exitCode = exitCodeFor(error);\n if (json) {\n writeStderr(`${JSON.stringify({ error: safeError(error, exitCode) })}\\n`);\n } else {\n const requestId = error instanceof MediaRuntimeApiError && error.requestId\n ? ` (request ${error.requestId})`\n : \"\";\n writeStderr(`Error: ${error instanceof Error ? error.message : \"Unknown error\"}${requestId}\\n`);\n }\n return exitCode;\n }\n}\n\nlet isEntrypoint = false;\nif (process.argv[1] !== undefined) {\n try {\n // npm exposes binaries through a symlink. Resolve both sides so the installed command\n // executes while importing dist/cli.js in tests remains side-effect free.\n isEntrypoint = realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));\n } catch {\n isEntrypoint = false;\n }\n}\nif (isEntrypoint) process.exitCode = await executeCli(process.argv.slice(2));\n","export class CliError extends Error {\n readonly code: string;\n readonly exitCode: number;\n\n constructor(code: string, message: string, exitCode: number, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"CliError\";\n this.code = code;\n this.exitCode = exitCode;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class UsageError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"usage_error\", message, 2, options);\n this.name = \"UsageError\";\n }\n}\n\nexport class TriggerDeliveryError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"trigger_delivery_error\", message, 8, options);\n this.name = \"TriggerDeliveryError\";\n }\n}\n\nexport class BundleDownloadError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"bundle_download_error\", message, 9, options);\n this.name = \"BundleDownloadError\";\n }\n}\n","import { CliError } from \"../errors.js\";\n\nexport const PRODUCTION_ORIGIN = \"https://mediaruntime.com\";\n\ninterface ErrorPayload {\n error?: unknown;\n detail?: unknown;\n}\n\nexport interface DeviceAuthorization {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n interval: number;\n}\n\nexport interface IssuedCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n credentialType: \"cli\";\n}\n\nexport interface CredentialStatus {\n status: \"authenticated\";\n accountId: string;\n keyId: string;\n credentialType: \"cli\" | \"api_key\";\n}\n\nexport class AuthApiError extends CliError {\n readonly status: number;\n\n constructor(code: string, message: string, status: number) {\n super(code, message, status >= 500 ? 5 : 3);\n this.name = \"AuthApiError\";\n this.status = status;\n }\n}\n\nfunction endpoint(baseUrl: string, path: string): string {\n return `${baseUrl.replace(/\\/+$/, \"\")}/api/cli/auth/${path}`;\n}\n\nasync function responsePayload(response: Response): Promise<Record<string, unknown>> {\n try {\n const value: unknown = await response.json();\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n } catch {\n return {};\n }\n}\n\nasync function post(\n baseUrl: string,\n path: string,\n body: Record<string, unknown>,\n apiKey?: string,\n): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(endpoint(baseUrl, path), {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(apiKey ? { \"X-API-Key\": apiKey } : {}),\n },\n body: JSON.stringify(body),\n });\n } catch (error) {\n throw new CliError(\"auth_connection_error\", \"Could not reach MediaRuntime authentication\", 5, { cause: error });\n }\n const payload = await responsePayload(response);\n if (!response.ok) {\n const errorPayload = payload as ErrorPayload;\n throw new AuthApiError(\n typeof errorPayload.error === \"string\" ? errorPayload.error : \"authorization_failed\",\n typeof errorPayload.detail === \"string\" ? errorPayload.detail : `Authentication failed with HTTP ${response.status}`,\n response.status,\n );\n }\n return payload;\n}\n\nfunction requireString(payload: Record<string, unknown>, key: string): string {\n const value = payload[key];\n if (typeof value !== \"string\" || !value) throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned an invalid authentication response\", 5);\n return value;\n}\n\nexport async function startAuthorization(baseUrl: string, codeChallenge: string): Promise<DeviceAuthorization> {\n const payload = await post(baseUrl, \"start\", { codeChallenge, clientName: \"MediaRuntime CLI\" });\n return {\n deviceCode: requireString(payload, \"deviceCode\"),\n userCode: requireString(payload, \"userCode\"),\n verificationUri: requireString(payload, \"verificationUri\"),\n verificationUriComplete: requireString(payload, \"verificationUriComplete\"),\n expiresIn: Number(payload.expiresIn),\n interval: Number(payload.interval),\n };\n}\n\nexport async function exchangeAuthorization(baseUrl: string, deviceCode: string, codeVerifier: string): Promise<IssuedCredential> {\n const payload = await post(baseUrl, \"token\", { deviceCode, codeVerifier });\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\") throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n return {\n apiKey: requireString(payload, \"apiKey\"),\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function inspectCredential(baseUrl: string, apiKey: string): Promise<CredentialStatus> {\n const payload = await post(baseUrl, \"status\", {}, apiKey);\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\" && credentialType !== \"api_key\") {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n }\n return {\n status: \"authenticated\",\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function revokeCredential(baseUrl: string, apiKey: string): Promise<void> {\n await post(baseUrl, \"revoke\", {}, apiKey);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport {\n AuthApiError,\n exchangeAuthorization,\n inspectCredential,\n revokeCredential,\n startAuthorization,\n} from \"../auth/api.js\";\nimport { openBrowser } from \"../auth/browser.js\";\nimport {\n OsCredentialStore,\n type CredentialStore,\n type StoredCredential,\n} from \"../auth/credential-store.js\";\nimport { CliError, UsageError } from \"../errors.js\";\n\nexport interface AuthCommandDependencies {\n credentialStore?: CredentialStore;\n openBrowser?: (url: string) => Promise<void>;\n sleep?: (milliseconds: number) => Promise<void>;\n now?: () => number;\n randomVerifier?: () => string;\n writeStdout?: (text: string) => void;\n}\n\nconst defaultSleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));\n\nfunction verifierChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nfunction defaultVerifier(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nfunction store(dependencies: AuthCommandDependencies): CredentialStore {\n return dependencies.credentialStore ?? new OsCredentialStore();\n}\n\nfunction assertOnly(args: string[], allowed: string[]): void {\n const unexpected = args.find((arg) => !allowed.includes(arg));\n if (unexpected) throw new UsageError(`Unknown authentication option: ${unexpected}`);\n}\n\nexport async function resolveCredential(\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<{ apiKey: string; source: \"environment\" | \"keychain\"; stored?: StoredCredential } | null> {\n const environment = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (environment) return { apiKey: environment, source: \"environment\" };\n const stored = await store(dependencies).get(baseUrl);\n return stored ? { apiKey: stored.apiKey, source: \"keychain\", stored } : null;\n}\n\nexport async function runLoginCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--no-browser\"]);\n const noBrowser = args.includes(\"--no-browser\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const existing = await store(dependencies).get(baseUrl);\n if (existing) {\n try {\n await inspectCredential(baseUrl, existing.apiKey);\n write(`Already logged in to ${baseUrl} (account ${existing.accountId}).\\n`);\n return 0;\n } catch (error) {\n if (!(error instanceof AuthApiError) || error.status >= 500) throw error;\n }\n }\n\n const verifier = dependencies.randomVerifier?.() ?? defaultVerifier();\n if (verifier.length < 43 || verifier.length > 128) {\n throw new CliError(\"invalid_verifier\", \"Generated PKCE verifier is invalid\", 1);\n }\n const authorization = await startAuthorization(baseUrl, verifierChallenge(verifier));\n if (!Number.isFinite(authorization.expiresIn) || authorization.expiresIn <= 0 ||\n !Number.isFinite(authorization.interval) || authorization.interval < 1) {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned invalid authorization timing\", 5);\n }\n\n write(`Open this URL to authorize MediaRuntime CLI:\\n${authorization.verificationUriComplete}\\n\\n`);\n write(`Confirm code: ${authorization.userCode}\\n`);\n if (!noBrowser) await (dependencies.openBrowser ?? openBrowser)(authorization.verificationUriComplete);\n write(\"Waiting for browser approval…\\n\");\n\n const now = dependencies.now ?? Date.now;\n const sleep = dependencies.sleep ?? defaultSleep;\n const deadline = now() + authorization.expiresIn * 1000;\n let credential;\n while (now() < deadline) {\n try {\n credential = await exchangeAuthorization(baseUrl, authorization.deviceCode, verifier);\n break;\n } catch (error) {\n if (error instanceof AuthApiError && error.code === \"authorization_pending\") {\n await sleep(authorization.interval * 1000);\n continue;\n }\n throw error;\n }\n }\n if (!credential) throw new CliError(\"authorization_timeout\", \"Browser authorization expired; run mediaruntime login again\", 7);\n\n try {\n await inspectCredential(baseUrl, credential.apiKey);\n await store(dependencies).set({\n apiKey: credential.apiKey,\n accountId: credential.accountId,\n keyId: credential.keyId,\n baseUrl,\n createdAt: new Date(now()).toISOString(),\n });\n } catch (error) {\n await revokeCredential(baseUrl, credential.apiKey).catch(() => undefined);\n throw error;\n }\n\n write(`Logged in to ${baseUrl} (account ${credential.accountId}).\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) {\n write(\"MEDIARUNTIME_API_KEY is set and will take precedence over this login.\\n\");\n }\n return 0;\n}\n\nexport async function runAuthStatusCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--json\"]);\n const json = args.includes(\"--json\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const resolved = await resolveCredential(baseUrl, dependencies);\n if (!resolved) throw new CliError(\"authentication_required\", \"Run mediaruntime login or set MEDIARUNTIME_API_KEY\", 3);\n const status = await inspectCredential(baseUrl, resolved.apiKey);\n if (json) {\n write(`${JSON.stringify({ authenticated: true, source: resolved.source, ...status })}\\n`);\n } else {\n write(`Authenticated via ${resolved.source} (account ${status.accountId}, key ${status.keyId}).\\n`);\n }\n return 0;\n}\n\nexport async function runLogoutCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--local-only\"]);\n const localOnly = args.includes(\"--local-only\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const credentialStore = store(dependencies);\n const credential = await credentialStore.get(baseUrl);\n if (!credential) {\n write(`No stored login for ${baseUrl}.\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n }\n if (!localOnly) await revokeCredential(baseUrl, credential.apiKey);\n await credentialStore.delete(baseUrl);\n write(localOnly ? \"Removed the local CLI login without server revocation.\\n\" : \"Logged out and revoked the CLI credential.\\n\");\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n}\n\nexport async function runAuthCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand !== \"status\") throw new UsageError(\"Usage: mediaruntime auth status [--json]\");\n return runAuthStatusCommand(args.slice(1), baseUrl, dependencies);\n}\n","import { spawn } from \"node:child_process\";\nimport { CliError } from \"../errors.js\";\n\nexport async function openBrowser(url: string): Promise<void> {\n const command = process.platform === \"darwin\"\n ? { executable: \"open\", args: [url] }\n : process.platform === \"win32\"\n ? { executable: \"rundll32\", args: [\"url.dll,FileProtocolHandler\", url] }\n : { executable: \"xdg-open\", args: [url] };\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.once(\"error\", (error) => reject(new CliError(\n \"browser_open_failed\",\n \"Could not open a browser; rerun with --no-browser and open the printed URL\",\n 2,\n { cause: error },\n )));\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n","import { CliError } from \"../errors.js\";\n\nconst SERVICE = \"mediaruntime-cli\";\n\nexport interface StoredCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n baseUrl: string;\n createdAt: string;\n}\n\nexport interface CredentialStore {\n get(baseUrl: string): Promise<StoredCredential | null>;\n set(credential: StoredCredential): Promise<void>;\n delete(baseUrl: string): Promise<void>;\n}\n\nfunction vaultAccount(baseUrl: string): string {\n return new URL(baseUrl).host.toLowerCase();\n}\n\nfunction validCredential(value: unknown): value is StoredCredential {\n if (!value || typeof value !== \"object\") return false;\n const item = value as Record<string, unknown>;\n return typeof item.apiKey === \"string\" && item.apiKey.startsWith(\"sk_\") &&\n typeof item.accountId === \"string\" && item.accountId.length > 0 &&\n typeof item.keyId === \"string\" && item.keyId.length > 0 &&\n typeof item.baseUrl === \"string\" && item.baseUrl.length > 0 &&\n typeof item.createdAt === \"string\" && item.createdAt.length > 0;\n}\n\nasync function entry(baseUrl: string) {\n try {\n const { Entry } = await import(\"@napi-rs/keyring\");\n return new Entry(SERVICE, vaultAccount(baseUrl));\n } catch (error) {\n throw new CliError(\n \"credential_store_unavailable\",\n \"The operating-system credential vault is unavailable; use MEDIARUNTIME_API_KEY on this machine\",\n 2,\n { cause: error },\n );\n }\n}\n\nexport class OsCredentialStore implements CredentialStore {\n async get(baseUrl: string): Promise<StoredCredential | null> {\n try {\n const raw = (await entry(baseUrl)).getPassword();\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n if (!validCredential(parsed) || parsed.baseUrl !== baseUrl) {\n throw new Error(\"Stored credential has an invalid shape\");\n }\n return parsed;\n } catch (error) {\n if (error instanceof SyntaxError || (error instanceof Error && error.message.includes(\"invalid shape\"))) {\n throw new CliError(\"credential_store_invalid\", \"The stored MediaRuntime credential is invalid; run mediaruntime logout --local-only\", 3);\n }\n if (error instanceof CliError) throw error;\n // Keyring implementations return a not-found error rather than null on some platforms.\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return null;\n throw new CliError(\"credential_store_error\", \"Could not read the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async set(credential: StoredCredential): Promise<void> {\n try {\n (await entry(credential.baseUrl)).setPassword(JSON.stringify(credential));\n } catch (error) {\n if (error instanceof CliError) throw error;\n throw new CliError(\"credential_store_error\", \"Could not save the login in the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async delete(baseUrl: string): Promise<void> {\n try {\n (await entry(baseUrl)).deletePassword();\n } catch (error) {\n if (error instanceof CliError) throw error;\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return;\n throw new CliError(\"credential_store_error\", \"Could not remove the login from the operating-system credential vault\", 2, { cause: error });\n }\n }\n}\n","import type { JobDetails, JobPage, JobStatus, ListJobsParams } from \"@mediaruntime/node\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\n\nexport interface JobsReadClient {\n list(params?: ListJobsParams): Promise<JobPage>;\n get(jobId: string): Promise<JobDetails>;\n}\n\nexport interface JobsCommandDependencies {\n jobs: JobsReadClient;\n writeStdout(text: string): void;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction humanDetails(job: JobDetails): string {\n const lines = [\n `Job: ${job.id}`,\n `Status: ${job.status}`,\n `Tier: ${job.tier.billed ?? job.tier.effective ?? job.tier.requested ?? \"-\"}`,\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}`,\n ];\n if (job.bundle.sizeBytes !== null) lines.push(`Bundle size: ${job.bundle.sizeBytes} bytes`);\n if (job.error) lines.push(`Error: ${job.error}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cell(value: unknown): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return String(value);\n}\n\nfunction humanList(page: JobPage): string {\n const rows = page.jobs.map((job) => [\n job.id,\n job.status,\n cell(job.tierBilled),\n cell(job.unitsTotal),\n job.bundleAvailable ? \"yes\" : \"no\",\n cell(job.updatedAt),\n ]);\n const headings = [\"ID\", \"STATUS\", \"TIER\", \"UNITS\", \"BUNDLE\", \"UPDATED\"];\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n const lines = [render(headings), render(widths.map((width) => \"-\".repeat(width))), ...rows.map(render)];\n if (page.nextCursor) lines.push(`Next cursor: ${page.nextCursor}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function listCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let status: string | undefined;\n let limit: number | undefined;\n let cursor: string | undefined;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--status\") {\n status = optionValue(args, index, argument).toUpperCase();\n index += 1;\n } else if (argument === \"--limit\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value < 1 || value > 100) {\n throw new UsageError(\"--limit must be an integer between 1 and 100\");\n }\n limit = value;\n index += 1;\n } else if (argument === \"--cursor\") {\n cursor = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--json\") {\n json = true;\n } else {\n throw new UsageError(`Unknown jobs list option: ${argument}`);\n }\n }\n const params: ListJobsParams = {\n ...(status === undefined ? {} : { status: status as JobStatus }),\n ...(limit === undefined ? {} : { limit }),\n ...(cursor === undefined ? {} : { cursor }),\n };\n const page = await dependencies.jobs.list(params);\n dependencies.writeStdout(json ? `${JSON.stringify(page)}\\n` : humanList(page));\n return 0;\n}\n\nasync function getCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let jobId: string | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown jobs get option: ${argument}`);\n } else if (!jobId) {\n jobId = argument;\n } else {\n throw new UsageError(\"jobs get accepts exactly one job ID\");\n }\n }\n if (!jobId) throw new UsageError(\"Usage: mediaruntime jobs get <job_id>\");\n if (force && !download) throw new UsageError(\"--force requires --download\");\n const job = await dependencies.jobs.get(jobId);\n if (!json) dependencies.writeStdout(humanDetails(job));\n\n if (UNSUCCESSFUL_TERMINAL_STATUSES.has(String(job.status).toUpperCase())) {\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 6;\n }\n if (download) {\n if (String(job.status).toUpperCase() !== \"COMPLETED\" ||\n !job.bundle.available || !job.bundle.downloadUrl) {\n throw new BundleDownloadError(\"Bundle download requires a COMPLETED job with an available canonical bundle\");\n }\n try {\n await dependencies.downloadBundle(job.bundle.downloadUrl, download, {\n force,\n expectedSizeBytes: job.bundle.sizeBytes,\n expectedSha256: job.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${download}`, { cause: error });\n }\n if (!json) dependencies.writeStdout(`Downloaded bundle to ${download}\\n`);\n }\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 0;\n}\n\nexport async function runJobsCommand(\n args: string[],\n dependencies: JobsCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand === \"list\") return listCommand(args.slice(1), dependencies);\n if (subcommand === \"get\") return getCommand(args.slice(1), dependencies);\n throw new UsageError(\"Usage: mediaruntime jobs <list|get>\");\n}\n","import type {\n CreateJobParams,\n JobDetails,\n JobOutput,\n JobReceiptData,\n Metadata,\n OutputAlias,\n WaitForJobOptions,\n} from \"@mediaruntime/node\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\nimport type { ActivityIndicator } from \"../ui/activity.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\nconst OUTPUT_ALIASES = new Set([\n \"video.web\",\n \"video.streaming\",\n \"video.social\",\n \"audio.web\",\n \"audio.transcription\",\n \"image.web\",\n]);\n\ninterface SubmittedJob extends JobReceiptData {\n wait(options?: WaitForJobOptions): Promise<JobDetails>;\n}\n\nexport interface RunJobsClient {\n create(params: CreateJobParams): Promise<SubmittedJob>;\n}\n\nexport interface RunCommandDependencies {\n jobs: RunJobsClient;\n writeStdout(text: string): void;\n activity: ActivityIndicator;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\ninterface RunOptions {\n source: string;\n outputs: string[];\n metadata?: Metadata;\n idempotencyKey?: string;\n wait: boolean;\n timeoutMs?: number;\n download?: string;\n force: boolean;\n json: boolean;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction parseMetadata(value: string): Metadata {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value) as unknown;\n } catch {\n throw new UsageError(\"--metadata must be a valid JSON object\");\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new UsageError(\"--metadata must be a JSON object\");\n }\n return parsed as Metadata;\n}\n\nfunction parseRunOptions(args: string[]): RunOptions {\n let source: string | undefined;\n const outputs: string[] = [];\n let metadata: Metadata | undefined;\n let idempotencyKey: string | undefined;\n let wait = false;\n let timeoutMs: number | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--output\" || argument === \"-o\") {\n outputs.push(optionValue(args, index, argument));\n index += 1;\n } else if (argument === \"--metadata\") {\n metadata = parseMetadata(optionValue(args, index, argument));\n index += 1;\n } else if (argument === \"--idempotency-key\") {\n idempotencyKey = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--wait\") {\n wait = true;\n } else if (argument === \"--timeout-ms\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new UsageError(\"--timeout-ms must be a positive integer\");\n }\n timeoutMs = value;\n index += 1;\n } else if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n wait = true;\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown run option: ${argument}`);\n } else if (source === undefined) {\n source = argument;\n } else {\n throw new UsageError(\"run accepts exactly one source\");\n }\n }\n\n if (!source) throw new UsageError(\"Usage: mediaruntime run <source> --output <alias> [--wait]\");\n if (outputs.length === 0) throw new UsageError(\"run requires at least one --output\");\n const unsupported = outputs.find((output) => !OUTPUT_ALIASES.has(output));\n if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported}`);\n if (force && !download) throw new UsageError(\"--force requires --download\");\n if (timeoutMs !== undefined && !wait) throw new UsageError(\"--timeout-ms requires --wait or --download\");\n return {\n source,\n outputs,\n ...(metadata === undefined ? {} : { metadata }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n wait,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n ...(download === undefined ? {} : { download }),\n force,\n json,\n };\n}\n\nfunction receiptProjection(job: SubmittedJob): JobReceiptData {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n requiredTier: job.requiredTier,\n outputs: job.outputs,\n message: job.message,\n };\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction writeHumanReceipt(job: SubmittedJob, write: (text: string) => void): void {\n write(`Job: ${job.id}\\nStatus: ${job.status}\\nTier: ${job.tier || \"-\"}\\n`);\n}\n\nfunction writeHumanDetails(job: JobDetails, write: (text: string) => void): void {\n const error = job.error ? `\\nError: ${job.error}` : \"\";\n write(\n `Job: ${job.id}\\nStatus: ${job.status}\\n` +\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}${error}\\n`,\n );\n}\n\nexport async function runCommand(\n args: string[],\n dependencies: RunCommandDependencies,\n): Promise<number> {\n const options = parseRunOptions(args);\n const params: CreateJobParams = {\n source: options.source,\n outputs: options.outputs as Array<OutputAlias | JobOutput>,\n ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n };\n const isLocalSource = !/^(?:https?|gs):\\/\\//i.test(options.source);\n dependencies.activity.start(\n isLocalSource ? \"Uploading local source and creating job…\" : \"Creating job…\",\n );\n\n try {\n const submitted = await dependencies.jobs.create(params);\n\n if (!options.wait) {\n dependencies.activity.stop();\n if (options.json) dependencies.writeStdout(`${JSON.stringify(receiptProjection(submitted))}\\n`);\n else writeHumanReceipt(submitted, dependencies.writeStdout);\n return UNSUCCESSFUL_TERMINAL_STATUSES.has(String(submitted.status).toUpperCase()) ? 6 : 0;\n }\n\n dependencies.activity.update(`Waiting for job ${submitted.id} to complete…`);\n const details = await submitted.wait(\n options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },\n );\n if (String(details.status).toUpperCase() !== \"COMPLETED\") {\n dependencies.activity.stop();\n if (!options.json) writeHumanDetails(details, dependencies.writeStdout);\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 6;\n }\n if (options.download) {\n const url = details.bundle.downloadUrl;\n if (!details.bundle.available || !url) {\n throw new BundleDownloadError(\"Completed job does not have an available canonical bundle\");\n }\n dependencies.activity.update(\"Downloading and verifying ZIP bundle…\");\n try {\n await dependencies.downloadBundle(url, options.download, {\n force: options.force,\n expectedSizeBytes: details.bundle.sizeBytes,\n expectedSha256: details.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${options.download}`, { cause: error });\n }\n }\n dependencies.activity.stop();\n if (!options.json) {\n writeHumanDetails(details, dependencies.writeStdout);\n if (options.download) dependencies.writeStdout(`Downloaded bundle to ${options.download}\\n`);\n }\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 0;\n } finally {\n dependencies.activity.stop();\n }\n}\n","import { randomBytes, randomUUID } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\n\nimport { parseLocalDestination } from \"../trigger/destination.js\";\nimport {\n SUPPORTED_TRIGGER_EVENTS,\n createSyntheticTerminalEvent,\n isTriggerEventType,\n type TriggerEventType,\n} from \"../trigger/event.js\";\nimport { signSyntheticWebhook } from \"../trigger/signature.js\";\nimport { TriggerDeliveryError, UsageError } from \"../errors.js\";\n\nexport interface TriggerCommandDependencies {\n env?: Readonly<Record<string, string | undefined>>;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n randomUUID?: () => string;\n randomBytes?: (size: number) => Uint8Array;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n writeStdout?: (text: string) => void;\n}\n\ninterface TriggerArguments {\n type: TriggerEventType;\n destination: URL;\n secretFile?: string;\n generateSecret: boolean;\n jobId?: string;\n accountId?: string;\n json: boolean;\n}\n\nfunction requireOptionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nexport function parseTriggerArguments(args: string[]): TriggerArguments {\n const typeValue = args[0];\n if (!typeValue || typeValue.startsWith(\"--\")) {\n throw new UsageError(\n `trigger requires an event type: ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n if (!isTriggerEventType(typeValue)) {\n throw new UsageError(\n `Unsupported trigger event ${JSON.stringify(typeValue)}; expected ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n\n let to: string | undefined;\n let secretFile: string | undefined;\n let generateSecret = false;\n let jobId: string | undefined;\n let accountId: string | undefined;\n let json = false;\n for (let index = 1; index < args.length; index += 1) {\n const option = args[index];\n if (!option) continue;\n if (option === \"--generate-secret\") {\n generateSecret = true;\n continue;\n }\n if (option === \"--json\") {\n json = true;\n continue;\n }\n if ([\"--to\", \"--secret-file\", \"--job-id\", \"--account-id\"].includes(option)) {\n const value = requireOptionValue(args, index, option);\n index += 1;\n if (option === \"--to\") to = value;\n else if (option === \"--secret-file\") secretFile = value;\n else if (option === \"--job-id\") jobId = value;\n else accountId = value;\n continue;\n }\n throw new UsageError(`Unknown trigger option: ${option}`);\n }\n\n if (!to) throw new UsageError(\"trigger requires an explicit --to local URL\");\n if (generateSecret && secretFile) {\n throw new UsageError(\"--generate-secret and --secret-file are mutually exclusive\");\n }\n if (generateSecret && json) {\n throw new UsageError(\"--generate-secret and --json are mutually exclusive\");\n }\n if (jobId !== undefined && !jobId.trim()) throw new UsageError(\"--job-id must not be empty\");\n if (accountId !== undefined && !accountId.trim()) {\n throw new UsageError(\"--account-id must not be empty\");\n }\n return {\n type: typeValue,\n destination: parseLocalDestination(to),\n ...(secretFile === undefined ? {} : { secretFile }),\n generateSecret,\n ...(jobId === undefined ? {} : { jobId: jobId.trim() }),\n ...(accountId === undefined ? {} : { accountId: accountId.trim() }),\n json,\n };\n}\n\nasync function resolveSecret(\n args: TriggerArguments,\n dependencies: Required<\n Pick<TriggerCommandDependencies, \"env\" | \"randomBytes\" | \"readFile\" | \"writeStdout\">\n >,\n): Promise<string> {\n if (args.generateSecret) {\n const generated = Buffer.from(dependencies.randomBytes(32)).toString(\"base64url\");\n dependencies.writeStdout(\n `Generated webhook secret (configure the local receiver with this value): ${generated}\\n`,\n );\n return generated;\n }\n let secret: string | undefined;\n if (args.secretFile) {\n try {\n secret = await dependencies.readFile(args.secretFile, \"utf8\");\n } catch (error) {\n throw new UsageError(`Could not read webhook secret file: ${args.secretFile}`, { cause: error });\n }\n } else {\n secret = dependencies.env.MEDIARUNTIME_WEBHOOK_SECRET;\n }\n const normalized = secret?.trim();\n if (!normalized) {\n throw new UsageError(\n \"Set MEDIARUNTIME_WEBHOOK_SECRET, pass --secret-file, or explicitly use --generate-secret\",\n );\n }\n return normalized;\n}\n\nexport async function runTriggerCommand(\n args: string[],\n dependencies: TriggerCommandDependencies = {},\n): Promise<number> {\n const parsed = parseTriggerArguments(args);\n const deps = {\n env: dependencies.env ?? process.env,\n fetch: dependencies.fetch ?? globalThis.fetch,\n now: dependencies.now ?? Date.now,\n randomUUID: dependencies.randomUUID ?? randomUUID,\n randomBytes: dependencies.randomBytes ?? randomBytes,\n readFile: dependencies.readFile ?? readFile,\n writeStdout: dependencies.writeStdout ?? ((text: string) => process.stdout.write(text)),\n };\n const secret = await resolveSecret(parsed, deps);\n const timestamp = Math.floor(deps.now() / 1000);\n const unique = deps.randomUUID();\n const eventId = `evt_cli_${unique}`;\n const jobId = parsed.jobId ?? `job_cli_${unique}`;\n const accountId = parsed.accountId ?? \"acc_cli_local\";\n const payload = createSyntheticTerminalEvent(parsed.type, {\n eventId,\n jobId,\n accountId,\n timestamp,\n });\n const signed = signSyntheticWebhook(payload, { eventId, timestamp, secret });\n\n const response = await deps.fetch(parsed.destination, {\n method: \"POST\",\n headers: signed.headers,\n body: signed.body,\n redirect: \"manual\",\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) {\n throw new TriggerDeliveryError(\n `Local webhook endpoint returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}`,\n );\n }\n if (parsed.json) {\n deps.writeStdout(`${JSON.stringify({\n eventId,\n type: parsed.type,\n jobId,\n status: payload.status,\n destination: parsed.destination.href,\n httpStatus: response.status,\n })}\\n`);\n } else {\n deps.writeStdout(\n `Sent synthetic ${parsed.type} event ${eventId} to ${parsed.destination.href} (HTTP ${response.status})\\n`,\n );\n }\n return 0;\n}\n","import { UsageError } from \"../errors.js\";\n\nexport function isLoopbackDestination(value: URL): boolean {\n let hostname = value.hostname.toLowerCase();\n if (hostname.endsWith(\".\")) hostname = hostname.slice(0, -1);\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n hostname = hostname.slice(1, -1);\n }\n if (hostname === \"localhost\" || hostname === \"::1\" || hostname === \"0:0:0:0:0:0:0:1\") {\n return true;\n }\n\n const octets = hostname.split(\".\");\n if (octets.length !== 4 || octets.some((part) => !/^\\d{1,3}$/.test(part))) return false;\n const numbers = octets.map(Number);\n return numbers[0] === 127 && numbers.every((part) => part >= 0 && part <= 255);\n}\n\nexport function parseLocalDestination(raw: string): URL {\n let destination: URL;\n try {\n destination = new URL(raw);\n } catch {\n throw new UsageError(\"--to must be an absolute local HTTP(S) URL\");\n }\n if (destination.protocol !== \"http:\" && destination.protocol !== \"https:\") {\n throw new UsageError(\"--to must use http:// or https://\");\n }\n if (destination.username || destination.password) {\n throw new UsageError(\"--to must not contain URL credentials\");\n }\n if (!isLoopbackDestination(destination)) {\n throw new UsageError(\n \"trigger only sends to loopback destinations (localhost, 127.0.0.0/8, or ::1)\",\n );\n }\n return destination;\n}\n","export const SUPPORTED_TRIGGER_EVENTS = [\n \"job.completed\",\n \"job.failed\",\n \"job.rejected\",\n] as const;\n\nexport type TriggerEventType = (typeof SUPPORTED_TRIGGER_EVENTS)[number];\n\nexport function isTriggerEventType(value: string): value is TriggerEventType {\n return (SUPPORTED_TRIGGER_EVENTS as readonly string[]).includes(value);\n}\n\nexport interface SyntheticEventOptions {\n eventId: string;\n jobId: string;\n accountId: string;\n timestamp: number;\n}\n\nexport function createSyntheticTerminalEvent(\n type: TriggerEventType,\n options: SyntheticEventOptions,\n): Record<string, unknown> {\n const status = type.slice(\"job.\".length).toUpperCase();\n const occurredAt = new Date(options.timestamp * 1000).toISOString();\n const base = {\n event_id: options.eventId,\n job_id: options.jobId,\n account_id: options.accountId,\n status,\n };\n\n if (type === \"job.completed\") {\n const expiresAt = new Date((options.timestamp + 7 * 24 * 60 * 60) * 1000).toISOString();\n return {\n ...base,\n completedAt: occurredAt,\n delivery: {\n mode: \"PULL\",\n retentionDays: 7,\n expiresAt,\n bundle: {\n type: \"zip\",\n filename: `${options.jobId}_outputs.zip`,\n size_bytes: 0,\n sha256: \"0\".repeat(64),\n download: {\n url: `http://127.0.0.1/__mediaruntime_synthetic__/${encodeURIComponent(options.jobId)}.zip`,\n expiresAt,\n },\n },\n layout: \"bundle_relative_v1\",\n deliverables: [],\n manifests: {},\n },\n billing: { status: \"PAID\" },\n usage: { units_total: 0 },\n meta: { synthetic: true, request_metadata: {} },\n };\n }\n\n const failed = type === \"job.failed\";\n return {\n ...base,\n [failed ? \"failedAt\" : \"rejectedAt\"]: occurredAt,\n delivery: { mode: \"NONE\" },\n billing: { status: \"RELEASED\" },\n error: {\n code: failed ? \"SYNTHETIC_ENGINE_FAILED\" : \"SYNTHETIC_REJECTED\",\n message: `Synthetic ${type} event from the MediaRuntime CLI`,\n },\n meta: { synthetic: true, request_metadata: {} },\n };\n}\n","import { createHmac } from \"node:crypto\";\n\nexport const WEBHOOK_HEADERS = {\n id: \"X-Transcoder-Id\",\n timestamp: \"X-Transcoder-Timestamp\",\n signature: \"X-Transcoder-Signature\",\n} as const;\n\nexport interface SignedWebhook {\n body: string;\n headers: Record<string, string>;\n}\n\nexport function signSyntheticWebhook(\n payload: Readonly<Record<string, unknown>>,\n options: { eventId: string; timestamp: number; secret: string },\n): SignedWebhook {\n if (!options.eventId.trim()) throw new Error(\"Webhook event ID must not be empty\");\n if (!Number.isInteger(options.timestamp) || options.timestamp < 0) {\n throw new Error(\"Webhook timestamp must be a non-negative integer\");\n }\n if (!options.secret) throw new Error(\"Webhook secret must not be empty\");\n\n // JSON is serialized once. These exact bytes are both signed and sent.\n const body = JSON.stringify(payload);\n const bodyBytes = Buffer.from(body, \"utf8\");\n const prefix = Buffer.from(`${options.timestamp}.${options.eventId}.`, \"utf8\");\n const digest = createHmac(\"sha256\", options.secret)\n .update(prefix)\n .update(bodyBytes)\n .digest(\"hex\");\n\n return {\n body,\n headers: {\n \"Content-Type\": \"application/json\",\n [WEBHOOK_HEADERS.id]: options.eventId,\n [WEBHOOK_HEADERS.timestamp]: String(options.timestamp),\n [WEBHOOK_HEADERS.signature]: `t=${options.timestamp},v1=${digest}`,\n },\n };\n}\n","const FRAMES = [\"⣋\", \"⣙\", \"⣹\", \"⣸\", \"⣼\", \"⣴\", \"⣦\", \"⣧\", \"⣇\", \"⣏\"];\nconst CLEAR_LINE = \"\\r\\u001b[2K\";\n\nexport interface ActivityIndicator {\n start(message: string): void;\n update(message: string): void;\n stop(): void;\n}\n\nexport function createActivityIndicator(\n write: (text: string) => void,\n enabled: boolean,\n): ActivityIndicator {\n let timer: ReturnType<typeof setInterval> | undefined;\n let frameIndex = 0;\n let message = \"\";\n let startedAt = 0;\n\n const render = (): void => {\n if (!timer && startedAt === 0) return;\n const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));\n const elapsed = elapsedSeconds > 0 ? ` (${elapsedSeconds}s)` : \"\";\n write(`${CLEAR_LINE}${FRAMES[frameIndex % FRAMES.length]} ${message}${elapsed}`);\n frameIndex += 1;\n };\n\n return {\n start(nextMessage) {\n if (!enabled) return;\n if (timer) clearInterval(timer);\n message = nextMessage;\n startedAt = Date.now();\n frameIndex = 0;\n render();\n timer = setInterval(render, 80);\n timer.unref?.();\n },\n update(nextMessage) {\n if (!enabled || startedAt === 0) return;\n message = nextMessage;\n render();\n },\n stop() {\n if (!enabled || startedAt === 0) return;\n if (timer) clearInterval(timer);\n timer = undefined;\n startedAt = 0;\n write(CLEAR_LINE);\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,cAAAA,aAAY,cAAAC,mBAAkB;AACvC,SAAS,WAAW,oBAAoB;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AAA,EACT;AACF;AAEA,IAAI,eAAe;AACnB,IAAI,QAAQ,KAAK,CAAC,MAAM,QAAW;AACjC,MAAI;AAGF,mBAAe,aAAa,QAAQ,KAAK,CAAC,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EAC9F,QAAQ;AACN,mBAAe;AAAA,EACjB;AACF;AACA,IAAI,aAAc,SAAQ,WAAW,MAAM,WAAW,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":["createHash","randomUUID","resolve","resolve","UNSUCCESSFUL_TERMINAL_STATUSES","optionValue","detailsProjection","randomBytes","randomBytes","randomUUID","createHash"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/errors.ts","../src/auth/api.ts","../src/commands/auth.ts","../src/auth/browser.ts","../src/auth/credential-store.ts","../src/commands/capabilities.ts","../src/commands/jobs.ts","../src/commands/run.ts","../src/commands/trigger.ts","../src/trigger/destination.ts","../src/trigger/event.ts","../src/trigger/signature.ts","../src/ui/activity.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { constants, realpathSync } from \"node:fs\";\nimport {\n access,\n link,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { createWriteStream } from \"node:fs\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n JobWaitTimeoutError,\n MediaRuntime,\n MediaRuntimeApiError,\n MediaRuntimeConnectionError,\n} from \"@mediaruntime/node\";\nimport { PRODUCTION_ORIGIN } from \"./auth/api.js\";\nimport type { CredentialStore } from \"./auth/credential-store.js\";\nimport {\n resolveCredential,\n runAuthCommand,\n runLoginCommand,\n runLogoutCommand,\n type AuthCommandDependencies,\n} from \"./commands/auth.js\";\nimport {\n runCapabilitiesCommand,\n runPresetsCommand,\n type CapabilitiesReadClient,\n} from \"./commands/capabilities.js\";\nimport {\n runJobsCommand,\n type JobsReadClient,\n} from \"./commands/jobs.js\";\nimport {\n runCommand,\n type RunJobsClient,\n} from \"./commands/run.js\";\nimport { runTriggerCommand } from \"./commands/trigger.js\";\nimport { BundleDownloadError, CliError, UsageError } from \"./errors.js\";\nimport { isLoopbackDestination } from \"./trigger/destination.js\";\nimport { createActivityIndicator } from \"./ui/activity.js\";\n\nexport { parseTriggerArguments, runTriggerCommand } from \"./commands/trigger.js\";\nexport { createSyntheticTerminalEvent } from \"./trigger/event.js\";\nexport { signSyntheticWebhook } from \"./trigger/signature.js\";\nexport {\n resolveCredential,\n runAuthCommand,\n runAuthStatusCommand,\n runLoginCommand,\n runLogoutCommand,\n} from \"./commands/auth.js\";\n\nconst VERSION = \"1.1.0\";\nconst HELP = `MediaRuntime CLI\n\nUsage:\n mediaruntime run <source> (--output <alias> | --preset <name>) [...] [--wait]\n mediaruntime capabilities [--json]\n mediaruntime presets list [--json]\n mediaruntime jobs list [--status <status>] [--limit <n>] [--cursor <cursor>]\n mediaruntime jobs get <job_id> [--download <bundle.zip>] [--force]\n mediaruntime trigger <job.completed|job.failed|job.rejected> --to <local-url>\n mediaruntime login [--no-browser]\n mediaruntime auth status\n mediaruntime logout [--local-only]\n\nGlobal options:\n --base-url <url> Developer override; normally leave unset\n --help Show help\n --version Show version\n\nRun/jobs options:\n --json Machine-readable, URL-redacted output\n\nAuthentication uses a secure login or MEDIARUNTIME_API_KEY.\n`;\n\ntype CliJobsClient = RunJobsClient & JobsReadClient;\n\nexport interface CliClient {\n jobs: CliJobsClient;\n capabilities: CapabilitiesReadClient;\n}\n\nexport interface CliDependencies {\n createClient?(options: { baseUrl?: string; apiKey?: string }): CliClient;\n downloadBundle?(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n ): Promise<void>;\n writeStdout?(text: string): void;\n writeStderr?(text: string): void;\n isStderrTTY?: boolean;\n credentialStore?: CredentialStore;\n openBrowser?(url: string): Promise<void>;\n sleep?(milliseconds: number): Promise<void>;\n now?(): number;\n randomVerifier?(): string;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n return error instanceof Error && \"code\" in error && error.code === \"EEXIST\";\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function downloadBundleAtomically(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n): Promise<void> {\n const target = resolve(destination);\n if (!options.force && await exists(target)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n const temporary = resolve(\n dirname(target),\n `.${basename(target)}.${randomUUID()}.part`,\n );\n\n try {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new BundleDownloadError(\"Bundle download failed before receiving a response\", { cause: error });\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new BundleDownloadError(`Bundle download failed with HTTP ${response.status}`);\n }\n if (!response.body) throw new BundleDownloadError(\"Bundle download returned an empty response body\");\n const hash = createHash(\"sha256\");\n let sizeBytes = 0;\n const integrity = new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n sizeBytes += chunk.length;\n hash.update(chunk);\n callback(null, chunk);\n },\n });\n await pipeline(\n Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>),\n integrity,\n createWriteStream(temporary, { flags: \"wx\", mode: 0o600 }),\n );\n const sha256 = hash.digest(\"hex\");\n if (options.expectedSizeBytes !== undefined && options.expectedSizeBytes !== null &&\n sizeBytes !== options.expectedSizeBytes) {\n throw new BundleDownloadError(\n `Bundle size mismatch: expected ${options.expectedSizeBytes} bytes, received ${sizeBytes}`,\n );\n }\n if (options.expectedSha256 && sha256 !== options.expectedSha256.toLowerCase()) {\n throw new BundleDownloadError(\"Bundle SHA-256 mismatch\");\n }\n\n if (options.force) {\n await rename(temporary, target);\n } else {\n try {\n // A hard link publishes the completed same-filesystem temporary file atomically\n // and fails rather than replacing a destination created during the download.\n await link(temporary, target);\n } catch (error) {\n if (isFileExistsError(error)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n throw error;\n }\n await rm(temporary);\n }\n } catch (error) {\n await rm(temporary, { force: true });\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not write bundle to ${destination}`, { cause: error });\n }\n}\n\nfunction normalizeBaseUrl(raw: string): string {\n let value: URL;\n try {\n value = new URL(raw);\n } catch {\n throw new UsageError(\"--base-url must be an absolute HTTP(S) origin\");\n }\n if (value.username || value.password || value.search || value.hash || value.pathname !== \"/\") {\n throw new UsageError(\"--base-url must be an origin without credentials, path, query, or fragment\");\n }\n if (value.protocol !== \"https:\" && !(value.protocol === \"http:\" && isLoopbackDestination(value))) {\n throw new UsageError(\"--base-url must use HTTPS unless it points to loopback\");\n }\n return value.origin;\n}\n\nfunction extractGlobalOptions(argv: string[]): { baseUrl?: string; args: string[] } {\n const args = [...argv];\n let baseUrl: string | undefined;\n while (args[0] === \"--base-url\") {\n const value = args[1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(\"--base-url requires a value\");\n baseUrl = normalizeBaseUrl(value);\n args.splice(0, 2);\n }\n return { ...(baseUrl === undefined ? {} : { baseUrl }), args };\n}\n\nfunction safeApiError(error: MediaRuntimeApiError): Record<string, unknown> {\n return {\n name: error.name,\n message: error.message,\n code: error.code,\n status: error.status,\n retryable: error.retryable,\n requestId: error.requestId ?? null,\n field: error.field ?? null,\n };\n}\n\nfunction exitCodeFor(error: unknown): number {\n if (error instanceof CliError) return error.exitCode;\n if (error instanceof JobWaitTimeoutError) return 7;\n if (error instanceof MediaRuntimeConnectionError) return 5;\n if (error instanceof MediaRuntimeApiError) {\n if ([401, 402, 403].includes(error.status)) return 3;\n if (error.status >= 500) return 5;\n return 4;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") return 130;\n if (error instanceof TypeError && /fetch|network|socket|connect/i.test(error.message)) return 5;\n return 1;\n}\n\nfunction safeError(error: unknown, exitCode: number): Record<string, unknown> {\n if (error instanceof MediaRuntimeApiError) return { ...safeApiError(error), exitCode };\n return {\n code: error instanceof CliError ? error.code : \"cli_error\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n exitCode,\n };\n}\n\nexport async function executeCli(\n argv: string[],\n dependencies: CliDependencies = {},\n): Promise<number> {\n const writeStdout = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const writeStderr = dependencies.writeStderr ?? ((text: string) => process.stderr.write(text));\n const json = argv.includes(\"--json\");\n const isStderrTTY = dependencies.isStderrTTY ??\n (dependencies.writeStderr === undefined && process.stderr.isTTY === true);\n try {\n const global = extractGlobalOptions(argv);\n const command = global.args[0];\n if (!command || command === \"--help\" || command === \"-h\") {\n writeStdout(HELP);\n return 0;\n }\n if (command === \"--version\" || command === \"-v\") {\n writeStdout(`${VERSION}\\n`);\n return 0;\n }\n if (command === \"trigger\") {\n return await runTriggerCommand(global.args.slice(1), { writeStdout });\n }\n\n const configuredBaseUrl = global.baseUrl ?? process.env.MEDIARUNTIME_API_URL;\n const baseUrl = configuredBaseUrl ? normalizeBaseUrl(configuredBaseUrl) : undefined;\n const authBaseUrl = baseUrl ?? PRODUCTION_ORIGIN;\n const authDependencies: AuthCommandDependencies = {\n ...(dependencies.credentialStore ? { credentialStore: dependencies.credentialStore } : {}),\n ...(dependencies.openBrowser ? { openBrowser: dependencies.openBrowser } : {}),\n ...(dependencies.sleep ? { sleep: dependencies.sleep } : {}),\n ...(dependencies.now ? { now: dependencies.now } : {}),\n ...(dependencies.randomVerifier ? { randomVerifier: dependencies.randomVerifier } : {}),\n writeStdout,\n };\n if (command === \"login\") return await runLoginCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"auth\") return await runAuthCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"logout\") return await runLogoutCommand(global.args.slice(1), authBaseUrl, authDependencies);\n\n if (command === \"capabilities\" || command === \"presets\") {\n const publicClient = dependencies.createClient?.({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n }) ?? new MediaRuntime({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n });\n const publicDependencies = { capabilities: publicClient.capabilities, writeStdout };\n if (command === \"capabilities\") {\n return await runCapabilitiesCommand(global.args.slice(1), publicDependencies);\n }\n return await runPresetsCommand(global.args.slice(1), publicDependencies);\n }\n\n let apiKey = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (!apiKey && (!dependencies.createClient || dependencies.credentialStore)) {\n apiKey = (await resolveCredential(authBaseUrl, authDependencies))?.apiKey;\n }\n if (!dependencies.createClient && !apiKey) {\n throw new UsageError(\"Run mediaruntime login or set MEDIARUNTIME_API_KEY before using run or jobs\");\n }\n const client = dependencies.createClient?.({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n }) ?? new MediaRuntime({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n });\n const downloadBundle = dependencies.downloadBundle ?? downloadBundleAtomically;\n const commandDependencies = {\n jobs: client.jobs,\n capabilities: client.capabilities,\n writeStdout,\n downloadBundle,\n activity: createActivityIndicator(writeStderr, isStderrTTY && !json),\n };\n if (command === \"run\") return await runCommand(global.args.slice(1), commandDependencies);\n if (command === \"jobs\") {\n return await runJobsCommand(global.args.slice(1), commandDependencies);\n }\n throw new UsageError(`Unknown command: ${command}`);\n } catch (error) {\n const exitCode = exitCodeFor(error);\n if (json) {\n writeStderr(`${JSON.stringify({ error: safeError(error, exitCode) })}\\n`);\n } else {\n const requestId = error instanceof MediaRuntimeApiError && error.requestId\n ? ` (request ${error.requestId})`\n : \"\";\n writeStderr(`Error: ${error instanceof Error ? error.message : \"Unknown error\"}${requestId}\\n`);\n }\n return exitCode;\n }\n}\n\nlet isEntrypoint = false;\nif (process.argv[1] !== undefined) {\n try {\n // npm exposes binaries through a symlink. Resolve both sides so the installed command\n // executes while importing dist/cli.js in tests remains side-effect free.\n isEntrypoint = realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));\n } catch {\n isEntrypoint = false;\n }\n}\nif (isEntrypoint) process.exitCode = await executeCli(process.argv.slice(2));\n","export class CliError extends Error {\n readonly code: string;\n readonly exitCode: number;\n\n constructor(code: string, message: string, exitCode: number, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"CliError\";\n this.code = code;\n this.exitCode = exitCode;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class UsageError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"usage_error\", message, 2, options);\n this.name = \"UsageError\";\n }\n}\n\nexport class TriggerDeliveryError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"trigger_delivery_error\", message, 8, options);\n this.name = \"TriggerDeliveryError\";\n }\n}\n\nexport class BundleDownloadError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"bundle_download_error\", message, 9, options);\n this.name = \"BundleDownloadError\";\n }\n}\n","import { CliError } from \"../errors.js\";\n\nexport const PRODUCTION_ORIGIN = \"https://mediaruntime.com\";\n\ninterface ErrorPayload {\n error?: unknown;\n detail?: unknown;\n}\n\nexport interface DeviceAuthorization {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n interval: number;\n}\n\nexport interface IssuedCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n credentialType: \"cli\";\n}\n\nexport interface CredentialStatus {\n status: \"authenticated\";\n accountId: string;\n keyId: string;\n credentialType: \"cli\" | \"api_key\";\n}\n\nexport class AuthApiError extends CliError {\n readonly status: number;\n\n constructor(code: string, message: string, status: number) {\n super(code, message, status >= 500 ? 5 : 3);\n this.name = \"AuthApiError\";\n this.status = status;\n }\n}\n\nfunction endpoint(baseUrl: string, path: string): string {\n return `${baseUrl.replace(/\\/+$/, \"\")}/api/cli/auth/${path}`;\n}\n\nasync function responsePayload(response: Response): Promise<Record<string, unknown>> {\n try {\n const value: unknown = await response.json();\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n } catch {\n return {};\n }\n}\n\nasync function post(\n baseUrl: string,\n path: string,\n body: Record<string, unknown>,\n apiKey?: string,\n): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(endpoint(baseUrl, path), {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(apiKey ? { \"X-API-Key\": apiKey } : {}),\n },\n body: JSON.stringify(body),\n });\n } catch (error) {\n throw new CliError(\"auth_connection_error\", \"Could not reach MediaRuntime authentication\", 5, { cause: error });\n }\n const payload = await responsePayload(response);\n if (!response.ok) {\n const errorPayload = payload as ErrorPayload;\n throw new AuthApiError(\n typeof errorPayload.error === \"string\" ? errorPayload.error : \"authorization_failed\",\n typeof errorPayload.detail === \"string\" ? errorPayload.detail : `Authentication failed with HTTP ${response.status}`,\n response.status,\n );\n }\n return payload;\n}\n\nfunction requireString(payload: Record<string, unknown>, key: string): string {\n const value = payload[key];\n if (typeof value !== \"string\" || !value) throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned an invalid authentication response\", 5);\n return value;\n}\n\nexport async function startAuthorization(baseUrl: string, codeChallenge: string): Promise<DeviceAuthorization> {\n const payload = await post(baseUrl, \"start\", { codeChallenge, clientName: \"MediaRuntime CLI\" });\n return {\n deviceCode: requireString(payload, \"deviceCode\"),\n userCode: requireString(payload, \"userCode\"),\n verificationUri: requireString(payload, \"verificationUri\"),\n verificationUriComplete: requireString(payload, \"verificationUriComplete\"),\n expiresIn: Number(payload.expiresIn),\n interval: Number(payload.interval),\n };\n}\n\nexport async function exchangeAuthorization(baseUrl: string, deviceCode: string, codeVerifier: string): Promise<IssuedCredential> {\n const payload = await post(baseUrl, \"token\", { deviceCode, codeVerifier });\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\") throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n return {\n apiKey: requireString(payload, \"apiKey\"),\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function inspectCredential(baseUrl: string, apiKey: string): Promise<CredentialStatus> {\n const payload = await post(baseUrl, \"status\", {}, apiKey);\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\" && credentialType !== \"api_key\") {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n }\n return {\n status: \"authenticated\",\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function revokeCredential(baseUrl: string, apiKey: string): Promise<void> {\n await post(baseUrl, \"revoke\", {}, apiKey);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport {\n AuthApiError,\n exchangeAuthorization,\n inspectCredential,\n revokeCredential,\n startAuthorization,\n} from \"../auth/api.js\";\nimport { openBrowser } from \"../auth/browser.js\";\nimport {\n OsCredentialStore,\n type CredentialStore,\n type StoredCredential,\n} from \"../auth/credential-store.js\";\nimport { CliError, UsageError } from \"../errors.js\";\n\nexport interface AuthCommandDependencies {\n credentialStore?: CredentialStore;\n openBrowser?: (url: string) => Promise<void>;\n sleep?: (milliseconds: number) => Promise<void>;\n now?: () => number;\n randomVerifier?: () => string;\n writeStdout?: (text: string) => void;\n}\n\nconst defaultSleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));\n\nfunction verifierChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nfunction defaultVerifier(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nfunction store(dependencies: AuthCommandDependencies): CredentialStore {\n return dependencies.credentialStore ?? new OsCredentialStore();\n}\n\nfunction assertOnly(args: string[], allowed: string[]): void {\n const unexpected = args.find((arg) => !allowed.includes(arg));\n if (unexpected) throw new UsageError(`Unknown authentication option: ${unexpected}`);\n}\n\nexport async function resolveCredential(\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<{ apiKey: string; source: \"environment\" | \"keychain\"; stored?: StoredCredential } | null> {\n const environment = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (environment) return { apiKey: environment, source: \"environment\" };\n const stored = await store(dependencies).get(baseUrl);\n return stored ? { apiKey: stored.apiKey, source: \"keychain\", stored } : null;\n}\n\nexport async function runLoginCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--no-browser\"]);\n const noBrowser = args.includes(\"--no-browser\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const existing = await store(dependencies).get(baseUrl);\n if (existing) {\n try {\n await inspectCredential(baseUrl, existing.apiKey);\n write(`Already logged in to ${baseUrl} (account ${existing.accountId}).\\n`);\n return 0;\n } catch (error) {\n if (!(error instanceof AuthApiError) || error.status >= 500) throw error;\n }\n }\n\n const verifier = dependencies.randomVerifier?.() ?? defaultVerifier();\n if (verifier.length < 43 || verifier.length > 128) {\n throw new CliError(\"invalid_verifier\", \"Generated PKCE verifier is invalid\", 1);\n }\n const authorization = await startAuthorization(baseUrl, verifierChallenge(verifier));\n if (!Number.isFinite(authorization.expiresIn) || authorization.expiresIn <= 0 ||\n !Number.isFinite(authorization.interval) || authorization.interval < 1) {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned invalid authorization timing\", 5);\n }\n\n write(`Open this URL to authorize MediaRuntime CLI:\\n${authorization.verificationUriComplete}\\n\\n`);\n write(`Confirm code: ${authorization.userCode}\\n`);\n if (!noBrowser) await (dependencies.openBrowser ?? openBrowser)(authorization.verificationUriComplete);\n write(\"Waiting for browser approval…\\n\");\n\n const now = dependencies.now ?? Date.now;\n const sleep = dependencies.sleep ?? defaultSleep;\n const deadline = now() + authorization.expiresIn * 1000;\n let credential;\n while (now() < deadline) {\n try {\n credential = await exchangeAuthorization(baseUrl, authorization.deviceCode, verifier);\n break;\n } catch (error) {\n if (error instanceof AuthApiError && error.code === \"authorization_pending\") {\n await sleep(authorization.interval * 1000);\n continue;\n }\n throw error;\n }\n }\n if (!credential) throw new CliError(\"authorization_timeout\", \"Browser authorization expired; run mediaruntime login again\", 7);\n\n try {\n await inspectCredential(baseUrl, credential.apiKey);\n await store(dependencies).set({\n apiKey: credential.apiKey,\n accountId: credential.accountId,\n keyId: credential.keyId,\n baseUrl,\n createdAt: new Date(now()).toISOString(),\n });\n } catch (error) {\n await revokeCredential(baseUrl, credential.apiKey).catch(() => undefined);\n throw error;\n }\n\n write(`Logged in to ${baseUrl} (account ${credential.accountId}).\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) {\n write(\"MEDIARUNTIME_API_KEY is set and will take precedence over this login.\\n\");\n }\n return 0;\n}\n\nexport async function runAuthStatusCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--json\"]);\n const json = args.includes(\"--json\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const resolved = await resolveCredential(baseUrl, dependencies);\n if (!resolved) throw new CliError(\"authentication_required\", \"Run mediaruntime login or set MEDIARUNTIME_API_KEY\", 3);\n const status = await inspectCredential(baseUrl, resolved.apiKey);\n if (json) {\n write(`${JSON.stringify({ authenticated: true, source: resolved.source, ...status })}\\n`);\n } else {\n write(`Authenticated via ${resolved.source} (account ${status.accountId}, key ${status.keyId}).\\n`);\n }\n return 0;\n}\n\nexport async function runLogoutCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--local-only\"]);\n const localOnly = args.includes(\"--local-only\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const credentialStore = store(dependencies);\n const credential = await credentialStore.get(baseUrl);\n if (!credential) {\n write(`No stored login for ${baseUrl}.\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n }\n if (!localOnly) await revokeCredential(baseUrl, credential.apiKey);\n await credentialStore.delete(baseUrl);\n write(localOnly ? \"Removed the local CLI login without server revocation.\\n\" : \"Logged out and revoked the CLI credential.\\n\");\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n}\n\nexport async function runAuthCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand !== \"status\") throw new UsageError(\"Usage: mediaruntime auth status [--json]\");\n return runAuthStatusCommand(args.slice(1), baseUrl, dependencies);\n}\n","import { spawn } from \"node:child_process\";\nimport { CliError } from \"../errors.js\";\n\nexport async function openBrowser(url: string): Promise<void> {\n const command = process.platform === \"darwin\"\n ? { executable: \"open\", args: [url] }\n : process.platform === \"win32\"\n ? { executable: \"rundll32\", args: [\"url.dll,FileProtocolHandler\", url] }\n : { executable: \"xdg-open\", args: [url] };\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.once(\"error\", (error) => reject(new CliError(\n \"browser_open_failed\",\n \"Could not open a browser; rerun with --no-browser and open the printed URL\",\n 2,\n { cause: error },\n )));\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n","import { CliError } from \"../errors.js\";\n\nconst SERVICE = \"mediaruntime-cli\";\n\nexport interface StoredCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n baseUrl: string;\n createdAt: string;\n}\n\nexport interface CredentialStore {\n get(baseUrl: string): Promise<StoredCredential | null>;\n set(credential: StoredCredential): Promise<void>;\n delete(baseUrl: string): Promise<void>;\n}\n\nfunction vaultAccount(baseUrl: string): string {\n return new URL(baseUrl).host.toLowerCase();\n}\n\nfunction validCredential(value: unknown): value is StoredCredential {\n if (!value || typeof value !== \"object\") return false;\n const item = value as Record<string, unknown>;\n return typeof item.apiKey === \"string\" && item.apiKey.startsWith(\"sk_\") &&\n typeof item.accountId === \"string\" && item.accountId.length > 0 &&\n typeof item.keyId === \"string\" && item.keyId.length > 0 &&\n typeof item.baseUrl === \"string\" && item.baseUrl.length > 0 &&\n typeof item.createdAt === \"string\" && item.createdAt.length > 0;\n}\n\nasync function entry(baseUrl: string) {\n try {\n const { Entry } = await import(\"@napi-rs/keyring\");\n return new Entry(SERVICE, vaultAccount(baseUrl));\n } catch (error) {\n throw new CliError(\n \"credential_store_unavailable\",\n \"The operating-system credential vault is unavailable; use MEDIARUNTIME_API_KEY on this machine\",\n 2,\n { cause: error },\n );\n }\n}\n\nexport class OsCredentialStore implements CredentialStore {\n async get(baseUrl: string): Promise<StoredCredential | null> {\n try {\n const raw = (await entry(baseUrl)).getPassword();\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n if (!validCredential(parsed) || parsed.baseUrl !== baseUrl) {\n throw new Error(\"Stored credential has an invalid shape\");\n }\n return parsed;\n } catch (error) {\n if (error instanceof SyntaxError || (error instanceof Error && error.message.includes(\"invalid shape\"))) {\n throw new CliError(\"credential_store_invalid\", \"The stored MediaRuntime credential is invalid; run mediaruntime logout --local-only\", 3);\n }\n if (error instanceof CliError) throw error;\n // Keyring implementations return a not-found error rather than null on some platforms.\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return null;\n throw new CliError(\"credential_store_error\", \"Could not read the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async set(credential: StoredCredential): Promise<void> {\n try {\n (await entry(credential.baseUrl)).setPassword(JSON.stringify(credential));\n } catch (error) {\n if (error instanceof CliError) throw error;\n throw new CliError(\"credential_store_error\", \"Could not save the login in the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async delete(baseUrl: string): Promise<void> {\n try {\n (await entry(baseUrl)).deletePassword();\n } catch (error) {\n if (error instanceof CliError) throw error;\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return;\n throw new CliError(\"credential_store_error\", \"Could not remove the login from the operating-system credential vault\", 2, { cause: error });\n }\n }\n}\n","import type { Capabilities } from \"@mediaruntime/node\";\nimport { UsageError } from \"../errors.js\";\n\nexport interface CapabilitiesReadClient {\n retrieve(): Promise<Capabilities>;\n}\n\nexport interface CapabilitiesCommandDependencies {\n capabilities: CapabilitiesReadClient;\n writeStdout(text: string): void;\n}\n\nexport interface PublicPresetRow {\n name: string;\n outputType: string;\n tier: string;\n sourceKinds: string[];\n artifacts: string[];\n description: string;\n codec: string | null;\n container: string | null;\n}\n\nfunction cell(value: string): string {\n return value || \"-\";\n}\n\nfunction table(headings: string[], rows: string[][]): string {\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n return `${[\n render(headings),\n render(widths.map((width) => \"-\".repeat(width))),\n ...rows.map(render),\n ].join(\"\\n\")}\\n`;\n}\n\nexport function publicPresetRows(capabilities: Capabilities): PublicPresetRow[] {\n return capabilities.publicPresets.map((name) => {\n const preset = capabilities.presets[name];\n if (!preset) {\n throw new Error(`Gateway capability contract is missing public preset metadata for ${name}`);\n }\n return {\n name,\n outputType: preset.outputType,\n tier: preset.baseTier,\n sourceKinds: preset.sourceKinds,\n artifacts: preset.artifacts,\n description: preset.description,\n codec: preset.codec ?? null,\n container: preset.container ?? null,\n };\n });\n}\n\nfunction parseJsonOnly(args: string[], command: string): boolean {\n let json = false;\n for (const argument of args) {\n if (argument === \"--json\") json = true;\n else throw new UsageError(`Unknown ${command} option: ${argument}`);\n }\n return json;\n}\n\nexport async function runCapabilitiesCommand(\n args: string[],\n dependencies: CapabilitiesCommandDependencies,\n): Promise<number> {\n const json = parseJsonOnly(args, \"capabilities\");\n const capabilities = await dependencies.capabilities.retrieve();\n if (json) {\n dependencies.writeStdout(`${JSON.stringify(capabilities)}\\n`);\n return 0;\n }\n\n const aliases = Object.entries(capabilities.outputAliases).map(([name, value]) => [\n name,\n value.type,\n value.preset,\n value.tier,\n ]);\n dependencies.writeStdout(\n `Public presets: ${capabilities.publicPresets.length}\\n` +\n `Optional features: ${Object.keys(capabilities.features).sort().join(\", \") || \"none\"}\\n\\n` +\n table([\"ALIAS\", \"TYPE\", \"PRESET\", \"TIER\"], aliases) +\n \"\\nRun `mediaruntime presets list` for the complete public preset catalog.\\n\",\n );\n return 0;\n}\n\nexport async function runPresetsCommand(\n args: string[],\n dependencies: CapabilitiesCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand !== \"list\") throw new UsageError(\"Usage: mediaruntime presets list [--json]\");\n const json = parseJsonOnly(args.slice(1), \"presets list\");\n const capabilities = await dependencies.capabilities.retrieve();\n const presets = publicPresetRows(capabilities);\n if (json) dependencies.writeStdout(`${JSON.stringify({ presets })}\\n`);\n else {\n dependencies.writeStdout(table(\n [\"PRESET\", \"TYPE\", \"TIER\", \"INPUTS\", \"ARTIFACTS\"],\n presets.map((preset) => [\n preset.name,\n cell(preset.outputType),\n cell(preset.tier),\n preset.sourceKinds.join(\",\"),\n preset.artifacts.join(\", \"),\n ]),\n ));\n }\n return 0;\n}\n","import type { JobDetails, JobPage, JobStatus, ListJobsParams } from \"@mediaruntime/node\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\n\nexport interface JobsReadClient {\n list(params?: ListJobsParams): Promise<JobPage>;\n get(jobId: string): Promise<JobDetails>;\n}\n\nexport interface JobsCommandDependencies {\n jobs: JobsReadClient;\n writeStdout(text: string): void;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction humanDetails(job: JobDetails): string {\n const lines = [\n `Job: ${job.id}`,\n `Status: ${job.status}`,\n `Tier: ${job.tier.billed ?? job.tier.effective ?? job.tier.requested ?? \"-\"}`,\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}`,\n ];\n if (job.bundle.sizeBytes !== null) lines.push(`Bundle size: ${job.bundle.sizeBytes} bytes`);\n if (job.error) lines.push(`Error: ${job.error}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cell(value: unknown): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return String(value);\n}\n\nfunction humanList(page: JobPage): string {\n const rows = page.jobs.map((job) => [\n job.id,\n job.status,\n cell(job.tierBilled),\n cell(job.unitsTotal),\n job.bundleAvailable ? \"yes\" : \"no\",\n cell(job.updatedAt),\n ]);\n const headings = [\"ID\", \"STATUS\", \"TIER\", \"UNITS\", \"BUNDLE\", \"UPDATED\"];\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n const lines = [render(headings), render(widths.map((width) => \"-\".repeat(width))), ...rows.map(render)];\n if (page.nextCursor) lines.push(`Next cursor: ${page.nextCursor}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function listCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let status: string | undefined;\n let limit: number | undefined;\n let cursor: string | undefined;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--status\") {\n status = optionValue(args, index, argument).toUpperCase();\n index += 1;\n } else if (argument === \"--limit\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value < 1 || value > 100) {\n throw new UsageError(\"--limit must be an integer between 1 and 100\");\n }\n limit = value;\n index += 1;\n } else if (argument === \"--cursor\") {\n cursor = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--json\") {\n json = true;\n } else {\n throw new UsageError(`Unknown jobs list option: ${argument}`);\n }\n }\n const params: ListJobsParams = {\n ...(status === undefined ? {} : { status: status as JobStatus }),\n ...(limit === undefined ? {} : { limit }),\n ...(cursor === undefined ? {} : { cursor }),\n };\n const page = await dependencies.jobs.list(params);\n dependencies.writeStdout(json ? `${JSON.stringify(page)}\\n` : humanList(page));\n return 0;\n}\n\nasync function getCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let jobId: string | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown jobs get option: ${argument}`);\n } else if (!jobId) {\n jobId = argument;\n } else {\n throw new UsageError(\"jobs get accepts exactly one job ID\");\n }\n }\n if (!jobId) throw new UsageError(\"Usage: mediaruntime jobs get <job_id>\");\n if (force && !download) throw new UsageError(\"--force requires --download\");\n const job = await dependencies.jobs.get(jobId);\n if (!json) dependencies.writeStdout(humanDetails(job));\n\n if (UNSUCCESSFUL_TERMINAL_STATUSES.has(String(job.status).toUpperCase())) {\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 6;\n }\n if (download) {\n if (String(job.status).toUpperCase() !== \"COMPLETED\" ||\n !job.bundle.available || !job.bundle.downloadUrl) {\n throw new BundleDownloadError(\"Bundle download requires a COMPLETED job with an available canonical bundle\");\n }\n try {\n await dependencies.downloadBundle(job.bundle.downloadUrl, download, {\n force,\n expectedSizeBytes: job.bundle.sizeBytes,\n expectedSha256: job.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${download}`, { cause: error });\n }\n if (!json) dependencies.writeStdout(`Downloaded bundle to ${download}\\n`);\n }\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 0;\n}\n\nexport async function runJobsCommand(\n args: string[],\n dependencies: JobsCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand === \"list\") return listCommand(args.slice(1), dependencies);\n if (subcommand === \"get\") return getCommand(args.slice(1), dependencies);\n throw new UsageError(\"Usage: mediaruntime jobs <list|get>\");\n}\n","import type {\n Capabilities,\n CreateJobParams,\n JobDetails,\n JobOutput,\n JobReceiptData,\n Metadata,\n OutputAlias,\n WaitForJobOptions,\n} from \"@mediaruntime/node\";\nimport type { CapabilitiesReadClient } from \"./capabilities.js\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\nimport type { ActivityIndicator } from \"../ui/activity.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\nconst OUTPUT_ALIASES = new Set([\n \"video.web\",\n \"video.streaming\",\n \"video.social\",\n \"audio.web\",\n \"audio.transcription\",\n \"image.web\",\n]);\n\ninterface SubmittedJob extends JobReceiptData {\n wait(options?: WaitForJobOptions): Promise<JobDetails>;\n}\n\nexport interface RunJobsClient {\n create(params: CreateJobParams): Promise<SubmittedJob>;\n}\n\nexport interface RunCommandDependencies {\n jobs: RunJobsClient;\n capabilities: CapabilitiesReadClient;\n writeStdout(text: string): void;\n activity: ActivityIndicator;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\ninterface RunOptions {\n source: string;\n outputs: Array<{ kind: \"alias\" | \"preset\"; value: string }>;\n metadata?: Metadata;\n idempotencyKey?: string;\n wait: boolean;\n timeoutMs?: number;\n download?: string;\n force: boolean;\n json: boolean;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction parseMetadata(value: string): Metadata {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value) as unknown;\n } catch {\n throw new UsageError(\"--metadata must be a valid JSON object\");\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new UsageError(\"--metadata must be a JSON object\");\n }\n return parsed as Metadata;\n}\n\nfunction parseRunOptions(args: string[]): RunOptions {\n let source: string | undefined;\n const outputs: RunOptions[\"outputs\"] = [];\n let metadata: Metadata | undefined;\n let idempotencyKey: string | undefined;\n let wait = false;\n let timeoutMs: number | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--output\" || argument === \"-o\") {\n outputs.push({ kind: \"alias\", value: optionValue(args, index, argument) });\n index += 1;\n } else if (argument === \"--preset\") {\n outputs.push({ kind: \"preset\", value: optionValue(args, index, argument) });\n index += 1;\n } else if (argument === \"--metadata\") {\n metadata = parseMetadata(optionValue(args, index, argument));\n index += 1;\n } else if (argument === \"--idempotency-key\") {\n idempotencyKey = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--wait\") {\n wait = true;\n } else if (argument === \"--timeout-ms\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new UsageError(\"--timeout-ms must be a positive integer\");\n }\n timeoutMs = value;\n index += 1;\n } else if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n wait = true;\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown run option: ${argument}`);\n } else if (source === undefined) {\n source = argument;\n } else {\n throw new UsageError(\"run accepts exactly one source\");\n }\n }\n\n if (!source) {\n throw new UsageError(\"Usage: mediaruntime run <source> (--output <alias> | --preset <name>) [--wait]\");\n }\n if (outputs.length === 0) throw new UsageError(\"run requires at least one --output or --preset\");\n const unsupported = outputs.find(\n (output) => output.kind === \"alias\" && !OUTPUT_ALIASES.has(output.value),\n );\n if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported.value}`);\n if (force && !download) throw new UsageError(\"--force requires --download\");\n if (timeoutMs !== undefined && !wait) throw new UsageError(\"--timeout-ms requires --wait or --download\");\n return {\n source,\n outputs,\n ...(metadata === undefined ? {} : { metadata }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n wait,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n ...(download === undefined ? {} : { download }),\n force,\n json,\n };\n}\n\nasync function resolveOutputs(\n selections: RunOptions[\"outputs\"],\n capabilitiesClient: CapabilitiesReadClient,\n): Promise<Array<OutputAlias | JobOutput>> {\n if (!selections.some((selection) => selection.kind === \"preset\")) {\n return selections.map((selection) => selection.value as OutputAlias);\n }\n const capabilities: Capabilities = await capabilitiesClient.retrieve();\n const publicPresets = new Set(capabilities.publicPresets);\n return selections.map((selection) => {\n if (selection.kind === \"alias\") return selection.value as OutputAlias;\n const preset = capabilities.presets[selection.value];\n if (!publicPresets.has(selection.value) || !preset) {\n throw new UsageError(`Unknown or non-public preset: ${selection.value}`);\n }\n return { type: preset.outputType, preset: selection.value };\n });\n}\n\nfunction receiptProjection(job: SubmittedJob): JobReceiptData {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n requiredTier: job.requiredTier,\n outputs: job.outputs,\n message: job.message,\n };\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction writeHumanReceipt(job: SubmittedJob, write: (text: string) => void): void {\n write(`Job: ${job.id}\\nStatus: ${job.status}\\nTier: ${job.tier || \"-\"}\\n`);\n}\n\nfunction writeHumanDetails(job: JobDetails, write: (text: string) => void): void {\n const error = job.error ? `\\nError: ${job.error}` : \"\";\n write(\n `Job: ${job.id}\\nStatus: ${job.status}\\n` +\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}${error}\\n`,\n );\n}\n\nexport async function runCommand(\n args: string[],\n dependencies: RunCommandDependencies,\n): Promise<number> {\n const options = parseRunOptions(args);\n const outputs = await resolveOutputs(options.outputs, dependencies.capabilities);\n const params: CreateJobParams = {\n source: options.source,\n outputs,\n ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n };\n const isLocalSource = !/^(?:https?|gs):\\/\\//i.test(options.source);\n dependencies.activity.start(\n isLocalSource ? \"Uploading local source and creating job…\" : \"Creating job…\",\n );\n\n try {\n const submitted = await dependencies.jobs.create(params);\n\n if (!options.wait) {\n dependencies.activity.stop();\n if (options.json) dependencies.writeStdout(`${JSON.stringify(receiptProjection(submitted))}\\n`);\n else writeHumanReceipt(submitted, dependencies.writeStdout);\n return UNSUCCESSFUL_TERMINAL_STATUSES.has(String(submitted.status).toUpperCase()) ? 6 : 0;\n }\n\n dependencies.activity.update(`Waiting for job ${submitted.id} to complete…`);\n const details = await submitted.wait(\n options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },\n );\n if (String(details.status).toUpperCase() !== \"COMPLETED\") {\n dependencies.activity.stop();\n if (!options.json) writeHumanDetails(details, dependencies.writeStdout);\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 6;\n }\n if (options.download) {\n const url = details.bundle.downloadUrl;\n if (!details.bundle.available || !url) {\n throw new BundleDownloadError(\"Completed job does not have an available canonical bundle\");\n }\n dependencies.activity.update(\"Downloading and verifying ZIP bundle…\");\n try {\n await dependencies.downloadBundle(url, options.download, {\n force: options.force,\n expectedSizeBytes: details.bundle.sizeBytes,\n expectedSha256: details.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${options.download}`, { cause: error });\n }\n }\n dependencies.activity.stop();\n if (!options.json) {\n writeHumanDetails(details, dependencies.writeStdout);\n if (options.download) dependencies.writeStdout(`Downloaded bundle to ${options.download}\\n`);\n }\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 0;\n } finally {\n dependencies.activity.stop();\n }\n}\n","import { randomBytes, randomUUID } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\n\nimport { parseLocalDestination } from \"../trigger/destination.js\";\nimport {\n SUPPORTED_TRIGGER_EVENTS,\n createSyntheticTerminalEvent,\n isTriggerEventType,\n type TriggerEventType,\n} from \"../trigger/event.js\";\nimport { signSyntheticWebhook } from \"../trigger/signature.js\";\nimport { TriggerDeliveryError, UsageError } from \"../errors.js\";\n\nexport interface TriggerCommandDependencies {\n env?: Readonly<Record<string, string | undefined>>;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n randomUUID?: () => string;\n randomBytes?: (size: number) => Uint8Array;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n writeStdout?: (text: string) => void;\n}\n\ninterface TriggerArguments {\n type: TriggerEventType;\n destination: URL;\n secretFile?: string;\n generateSecret: boolean;\n jobId?: string;\n accountId?: string;\n json: boolean;\n}\n\nfunction requireOptionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nexport function parseTriggerArguments(args: string[]): TriggerArguments {\n const typeValue = args[0];\n if (!typeValue || typeValue.startsWith(\"--\")) {\n throw new UsageError(\n `trigger requires an event type: ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n if (!isTriggerEventType(typeValue)) {\n throw new UsageError(\n `Unsupported trigger event ${JSON.stringify(typeValue)}; expected ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n\n let to: string | undefined;\n let secretFile: string | undefined;\n let generateSecret = false;\n let jobId: string | undefined;\n let accountId: string | undefined;\n let json = false;\n for (let index = 1; index < args.length; index += 1) {\n const option = args[index];\n if (!option) continue;\n if (option === \"--generate-secret\") {\n generateSecret = true;\n continue;\n }\n if (option === \"--json\") {\n json = true;\n continue;\n }\n if ([\"--to\", \"--secret-file\", \"--job-id\", \"--account-id\"].includes(option)) {\n const value = requireOptionValue(args, index, option);\n index += 1;\n if (option === \"--to\") to = value;\n else if (option === \"--secret-file\") secretFile = value;\n else if (option === \"--job-id\") jobId = value;\n else accountId = value;\n continue;\n }\n throw new UsageError(`Unknown trigger option: ${option}`);\n }\n\n if (!to) throw new UsageError(\"trigger requires an explicit --to local URL\");\n if (generateSecret && secretFile) {\n throw new UsageError(\"--generate-secret and --secret-file are mutually exclusive\");\n }\n if (generateSecret && json) {\n throw new UsageError(\"--generate-secret and --json are mutually exclusive\");\n }\n if (jobId !== undefined && !jobId.trim()) throw new UsageError(\"--job-id must not be empty\");\n if (accountId !== undefined && !accountId.trim()) {\n throw new UsageError(\"--account-id must not be empty\");\n }\n return {\n type: typeValue,\n destination: parseLocalDestination(to),\n ...(secretFile === undefined ? {} : { secretFile }),\n generateSecret,\n ...(jobId === undefined ? {} : { jobId: jobId.trim() }),\n ...(accountId === undefined ? {} : { accountId: accountId.trim() }),\n json,\n };\n}\n\nasync function resolveSecret(\n args: TriggerArguments,\n dependencies: Required<\n Pick<TriggerCommandDependencies, \"env\" | \"randomBytes\" | \"readFile\" | \"writeStdout\">\n >,\n): Promise<string> {\n if (args.generateSecret) {\n const generated = Buffer.from(dependencies.randomBytes(32)).toString(\"base64url\");\n dependencies.writeStdout(\n `Generated webhook secret (configure the local receiver with this value): ${generated}\\n`,\n );\n return generated;\n }\n let secret: string | undefined;\n if (args.secretFile) {\n try {\n secret = await dependencies.readFile(args.secretFile, \"utf8\");\n } catch (error) {\n throw new UsageError(`Could not read webhook secret file: ${args.secretFile}`, { cause: error });\n }\n } else {\n secret = dependencies.env.MEDIARUNTIME_WEBHOOK_SECRET;\n }\n const normalized = secret?.trim();\n if (!normalized) {\n throw new UsageError(\n \"Set MEDIARUNTIME_WEBHOOK_SECRET, pass --secret-file, or explicitly use --generate-secret\",\n );\n }\n return normalized;\n}\n\nexport async function runTriggerCommand(\n args: string[],\n dependencies: TriggerCommandDependencies = {},\n): Promise<number> {\n const parsed = parseTriggerArguments(args);\n const deps = {\n env: dependencies.env ?? process.env,\n fetch: dependencies.fetch ?? globalThis.fetch,\n now: dependencies.now ?? Date.now,\n randomUUID: dependencies.randomUUID ?? randomUUID,\n randomBytes: dependencies.randomBytes ?? randomBytes,\n readFile: dependencies.readFile ?? readFile,\n writeStdout: dependencies.writeStdout ?? ((text: string) => process.stdout.write(text)),\n };\n const secret = await resolveSecret(parsed, deps);\n const timestamp = Math.floor(deps.now() / 1000);\n const unique = deps.randomUUID();\n const eventId = `evt_cli_${unique}`;\n const jobId = parsed.jobId ?? `job_cli_${unique}`;\n const accountId = parsed.accountId ?? \"acc_cli_local\";\n const payload = createSyntheticTerminalEvent(parsed.type, {\n eventId,\n jobId,\n accountId,\n timestamp,\n });\n const signed = signSyntheticWebhook(payload, { eventId, timestamp, secret });\n\n const response = await deps.fetch(parsed.destination, {\n method: \"POST\",\n headers: signed.headers,\n body: signed.body,\n redirect: \"manual\",\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) {\n throw new TriggerDeliveryError(\n `Local webhook endpoint returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}`,\n );\n }\n if (parsed.json) {\n deps.writeStdout(`${JSON.stringify({\n eventId,\n type: parsed.type,\n jobId,\n status: payload.status,\n destination: parsed.destination.href,\n httpStatus: response.status,\n })}\\n`);\n } else {\n deps.writeStdout(\n `Sent synthetic ${parsed.type} event ${eventId} to ${parsed.destination.href} (HTTP ${response.status})\\n`,\n );\n }\n return 0;\n}\n","import { UsageError } from \"../errors.js\";\n\nexport function isLoopbackDestination(value: URL): boolean {\n let hostname = value.hostname.toLowerCase();\n if (hostname.endsWith(\".\")) hostname = hostname.slice(0, -1);\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n hostname = hostname.slice(1, -1);\n }\n if (hostname === \"localhost\" || hostname === \"::1\" || hostname === \"0:0:0:0:0:0:0:1\") {\n return true;\n }\n\n const octets = hostname.split(\".\");\n if (octets.length !== 4 || octets.some((part) => !/^\\d{1,3}$/.test(part))) return false;\n const numbers = octets.map(Number);\n return numbers[0] === 127 && numbers.every((part) => part >= 0 && part <= 255);\n}\n\nexport function parseLocalDestination(raw: string): URL {\n let destination: URL;\n try {\n destination = new URL(raw);\n } catch {\n throw new UsageError(\"--to must be an absolute local HTTP(S) URL\");\n }\n if (destination.protocol !== \"http:\" && destination.protocol !== \"https:\") {\n throw new UsageError(\"--to must use http:// or https://\");\n }\n if (destination.username || destination.password) {\n throw new UsageError(\"--to must not contain URL credentials\");\n }\n if (!isLoopbackDestination(destination)) {\n throw new UsageError(\n \"trigger only sends to loopback destinations (localhost, 127.0.0.0/8, or ::1)\",\n );\n }\n return destination;\n}\n","export const SUPPORTED_TRIGGER_EVENTS = [\n \"job.completed\",\n \"job.failed\",\n \"job.rejected\",\n] as const;\n\nexport type TriggerEventType = (typeof SUPPORTED_TRIGGER_EVENTS)[number];\n\nexport function isTriggerEventType(value: string): value is TriggerEventType {\n return (SUPPORTED_TRIGGER_EVENTS as readonly string[]).includes(value);\n}\n\nexport interface SyntheticEventOptions {\n eventId: string;\n jobId: string;\n accountId: string;\n timestamp: number;\n}\n\nexport function createSyntheticTerminalEvent(\n type: TriggerEventType,\n options: SyntheticEventOptions,\n): Record<string, unknown> {\n const status = type.slice(\"job.\".length).toUpperCase();\n const occurredAt = new Date(options.timestamp * 1000).toISOString();\n const base = {\n event_id: options.eventId,\n job_id: options.jobId,\n account_id: options.accountId,\n status,\n };\n\n if (type === \"job.completed\") {\n const expiresAt = new Date((options.timestamp + 7 * 24 * 60 * 60) * 1000).toISOString();\n return {\n ...base,\n completedAt: occurredAt,\n delivery: {\n mode: \"PULL\",\n retentionDays: 7,\n expiresAt,\n bundle: {\n type: \"zip\",\n filename: `${options.jobId}_outputs.zip`,\n size_bytes: 0,\n sha256: \"0\".repeat(64),\n download: {\n url: `http://127.0.0.1/__mediaruntime_synthetic__/${encodeURIComponent(options.jobId)}.zip`,\n expiresAt,\n },\n },\n layout: \"bundle_relative_v1\",\n deliverables: [],\n manifests: {},\n },\n billing: { status: \"PAID\" },\n usage: { units_total: 0 },\n meta: { synthetic: true, request_metadata: {} },\n };\n }\n\n const failed = type === \"job.failed\";\n return {\n ...base,\n [failed ? \"failedAt\" : \"rejectedAt\"]: occurredAt,\n delivery: { mode: \"NONE\" },\n billing: { status: \"RELEASED\" },\n error: {\n code: failed ? \"SYNTHETIC_ENGINE_FAILED\" : \"SYNTHETIC_REJECTED\",\n message: `Synthetic ${type} event from the MediaRuntime CLI`,\n },\n meta: { synthetic: true, request_metadata: {} },\n };\n}\n","import { createHmac } from \"node:crypto\";\n\nexport const WEBHOOK_HEADERS = {\n id: \"X-Transcoder-Id\",\n timestamp: \"X-Transcoder-Timestamp\",\n signature: \"X-Transcoder-Signature\",\n} as const;\n\nexport interface SignedWebhook {\n body: string;\n headers: Record<string, string>;\n}\n\nexport function signSyntheticWebhook(\n payload: Readonly<Record<string, unknown>>,\n options: { eventId: string; timestamp: number; secret: string },\n): SignedWebhook {\n if (!options.eventId.trim()) throw new Error(\"Webhook event ID must not be empty\");\n if (!Number.isInteger(options.timestamp) || options.timestamp < 0) {\n throw new Error(\"Webhook timestamp must be a non-negative integer\");\n }\n if (!options.secret) throw new Error(\"Webhook secret must not be empty\");\n\n // JSON is serialized once. These exact bytes are both signed and sent.\n const body = JSON.stringify(payload);\n const bodyBytes = Buffer.from(body, \"utf8\");\n const prefix = Buffer.from(`${options.timestamp}.${options.eventId}.`, \"utf8\");\n const digest = createHmac(\"sha256\", options.secret)\n .update(prefix)\n .update(bodyBytes)\n .digest(\"hex\");\n\n return {\n body,\n headers: {\n \"Content-Type\": \"application/json\",\n [WEBHOOK_HEADERS.id]: options.eventId,\n [WEBHOOK_HEADERS.timestamp]: String(options.timestamp),\n [WEBHOOK_HEADERS.signature]: `t=${options.timestamp},v1=${digest}`,\n },\n };\n}\n","const FRAMES = [\"⣋\", \"⣙\", \"⣹\", \"⣸\", \"⣼\", \"⣴\", \"⣦\", \"⣧\", \"⣇\", \"⣏\"];\nconst CLEAR_LINE = \"\\r\\u001b[2K\";\n\nexport interface ActivityIndicator {\n start(message: string): void;\n update(message: string): void;\n stop(): void;\n}\n\nexport function createActivityIndicator(\n write: (text: string) => void,\n enabled: boolean,\n): ActivityIndicator {\n let timer: ReturnType<typeof setInterval> | undefined;\n let frameIndex = 0;\n let message = \"\";\n let startedAt = 0;\n\n const render = (): void => {\n if (!timer && startedAt === 0) return;\n const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));\n const elapsed = elapsedSeconds > 0 ? ` (${elapsedSeconds}s)` : \"\";\n write(`${CLEAR_LINE}${FRAMES[frameIndex % FRAMES.length]} ${message}${elapsed}`);\n frameIndex += 1;\n };\n\n return {\n start(nextMessage) {\n if (!enabled) return;\n if (timer) clearInterval(timer);\n message = nextMessage;\n startedAt = Date.now();\n frameIndex = 0;\n render();\n timer = setInterval(render, 80);\n timer.unref?.();\n },\n update(nextMessage) {\n if (!enabled || startedAt === 0) return;\n message = nextMessage;\n render();\n },\n stop() {\n if (!enabled || startedAt === 0) return;\n if (timer) clearInterval(timer);\n timer = undefined;\n startedAt = 0;\n write(CLEAR_LINE);\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,cAAAA,aAAY,cAAAC,mBAAkB;AACvC,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,UAAU,SAAS,eAAe;AAC3C,SAAS,UAAU,iBAAiB;AACpC,SAAS,gBAAgB;AAEzB,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACnBA,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EAET,YAAY,MAAc,SAAiB,UAAkB,SAA+B;AAC1F,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAEO,IAAM,aAAN,cAAyB,SAAS;AAAA,EACvC,YAAY,SAAiB,SAA+B;AAC1D,UAAM,eAAe,SAAS,GAAG,OAAO;AACxC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,uBAAN,cAAmC,SAAS;AAAA,EACjD,YAAY,SAAiB,SAA+B;AAC1D,UAAM,0BAA0B,SAAS,GAAG,OAAO;AACnD,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,SAAS;AAAA,EAChD,YAAY,SAAiB,SAA+B;AAC1D,UAAM,yBAAyB,SAAS,GAAG,OAAO;AAClD,SAAK,OAAO;AAAA,EACd;AACF;;;AC9BO,IAAM,oBAAoB;AA8B1B,IAAM,eAAN,cAA2B,SAAS;AAAA,EAChC;AAAA,EAET,Y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O,EAAE;AAAA,EACpD,SAAS,OAAO;AACd,UAAM,WAAW,YAAY,KAAK;AAClC,QAAI,MAAM;AACR,kBAAY,GAAG,KAAK,UAAU,EAAE,OAAO,UAAU,OAAO,QAAQ,EAAE,CAAC,CAAC;AAAA,CAAI;AAAA,IAC1E,OAAO;AACL,YAAM,YAAY,iBAAiB,wBAAwB,MAAM,YAC7D,aAAa,MAAM,SAAS,MAC5B;AACJ,kBAAY,UAAU,iBAAiB,QAAQ,MAAM,UAAU,eAAe,GAAG,SAAS;AAAA,CAAI;AAAA,IAChG;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAI,eAAe;AACnB,IAAI,QAAQ,KAAK,CAAC,MAAM,QAAW;AACjC,MAAI;AAGF,mBAAe,aAAa,QAAQ,KAAK,CAAC,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EAC9F,QAAQ;AACN,mBAAe;AAAA,EACjB;AACF;AACA,IAAI,aAAc,SAAQ,WAAW,MAAM,WAAW,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":["createHash","randomUUID","resolve","resolve","cell","UNSUCCESSFUL_TERMINAL_STATUSES","optionValue","detailsProjection","randomBytes","randomBytes","randomUUID","createHash"]}
package/docs/CLI_SDD.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # MediaRuntime CLI software design
2
2
 
3
- Status: implementation contract through browser-auth release 0.2
3
+ Status: stable public contract released as `1.1.0`
4
4
 
5
5
  Package: `@mediaruntime/cli`
6
6
 
7
7
  Executable: `mediaruntime`
8
8
 
9
- Runtime: Node.js 20 or newer
9
+ Runtime: Node.js 22 or newer
10
10
 
11
11
  ## 1. Decision summary
12
12
 
@@ -15,6 +15,9 @@ ships the media commands plus an interactive authentication surface:
15
15
 
16
16
  ```text
17
17
  mediaruntime run <source> --output <alias>
18
+ mediaruntime run <source> --preset <public-preset>
19
+ mediaruntime capabilities
20
+ mediaruntime presets list
18
21
  mediaruntime jobs list
19
22
  mediaruntime jobs get <job_id>
20
23
  mediaruntime trigger job.completed --to http://127.0.0.1:3000/webhooks/mediaruntime
@@ -53,9 +56,10 @@ engine directory layout.
53
56
  authenticated connections, event ownership, expiry, rate limits, and an abuse model.
54
57
  - Named multi-account profiles are deferred. Browser login stores one credential per API
55
58
  origin; an explicit environment key remains the account override.
56
- - Batch submission, explicit output recipe editing, moderation, watermark management,
59
+ - Batch submission, custom output recipe editing, moderation, watermark management,
57
60
  webhook registration, media-report retrieval, and moderation-result retrieval remain
58
- available through the SDK/API but are not CLI v1 commands.
61
+ available through the SDK/API but are not CLI v1 commands. Named public presets are
62
+ supported through `--preset`; arbitrary output objects remain deferred.
59
63
  - The CLI does not accept a per-job webhook URL. Terminal events go to the account-level
60
64
  destination configured in the MediaRuntime profile.
61
65
  - ZIP extraction, artifact selectors, HLS serving, and indefinite bundle retention are
@@ -67,6 +71,7 @@ The implementation depends on the released Node SDK and must not copy its HTTP c
67
71
  The following published contracts govern the CLI:
68
72
 
69
73
  - Node SDK `MediaRuntime`, `jobs.create`, `jobs.list`, `jobs.get`, and `Job.wait`.
74
+ - Node SDK `capabilities.retrieve()` and its ordered `publicPresets` catalog.
70
75
  - Gateway `contracts/v1/openapi.json` and `contracts/v1/conformance.json`.
71
76
  - Frozen output aliases: `video.web`, `video.streaming`, `video.social`, `audio.web`,
72
77
  `audio.transcription`, and `image.web`.
@@ -85,7 +90,7 @@ Authenticated commands resolve configuration once before doing file or network w
85
90
 
86
91
  | Setting | Highest precedence | Environment | Default |
87
92
  |---|---|---|---|
88
- | API key | `MEDIARUNTIME_API_KEY` | OS-vault browser login | required for `run` and `jobs` |
93
+ | API key | `MEDIARUNTIME_API_KEY` | OS-vault browser login | required for `run` and `jobs`; not required for capability discovery |
89
94
  | API base URL | `--base-url <url>` | `MEDIARUNTIME_API_URL` | `https://mediaruntime.com` |
90
95
  | Webhook signing secret | `--secret-file <path>` | `MEDIARUNTIME_WEBHOOK_SECRET` | required by `trigger`, unless explicitly generated |
91
96
 
@@ -110,7 +115,8 @@ mediaruntime --base-url http://127.0.0.1:8001 jobs list
110
115
  ### 5.1 `run`
111
116
 
112
117
  ```text
113
- mediaruntime run <source> --output <alias> [--output <alias> ...]
118
+ mediaruntime run <source>
119
+ (--output <alias> | --preset <public-preset>) [...]
114
120
  [--metadata <json-object>]
115
121
  [--idempotency-key <key>]
116
122
  [--wait]
@@ -119,12 +125,14 @@ mediaruntime run <source> --output <alias> [--output <alias> ...]
119
125
  [--json]
120
126
  ```
121
127
 
122
- `-o` is the short spelling of `--output`. Exactly one source and at least one output are
128
+ `-o` is the short spelling of `--output`. Exactly one source and at least one output or preset are
123
129
  required. `<source>` may be an HTTP(S) URL, `gs://` URI, local path, or `file://` URL. The
124
130
  CLI passes it to the SDK so local inputs use the SDK's signed-upload flow.
125
131
 
126
- Each `--output` must be one of the six frozen aliases. Repeating the option preserves the
127
- caller order. Explicit output objects and batch inputs are intentionally deferred from
132
+ Each `--output` must be one of the six frozen aliases. Each `--preset` must appear in the
133
+ gateway's ordered `publicPresets` catalog; the CLI retrieves its output type and submits
134
+ the corresponding explicit output object. Repeating and mixing both options preserves
135
+ caller order. Custom output objects and batch inputs remain intentionally deferred from
128
136
  the quick CLI; use an SDK when that control is required.
129
137
 
130
138
  `--metadata` is one JSON object, for example:
@@ -152,9 +160,26 @@ mediaruntime run ./launch.mp4 \
152
160
  --metadata '{"asset_id":"launch-01"}' \
153
161
  --idempotency-key 'asset:launch-01:v1' \
154
162
  --download ./launch-01.zip
163
+
164
+ mediaruntime run ./launch.mp4 \
165
+ --preset dash_ladder_v1 --preset webm_vp9_1080p \
166
+ --download ./adaptive-and-vp9.zip
155
167
  ```
156
168
 
157
- ### 5.2 `jobs list`
169
+ ### 5.2 Capability and preset discovery
170
+
171
+ ```text
172
+ mediaruntime capabilities [--json]
173
+ mediaruntime presets list [--json]
174
+ ```
175
+
176
+ Both commands call the unauthenticated capability endpoint and therefore do not require
177
+ a browser login or `MEDIARUNTIME_API_KEY`. Human output summarizes aliases, optional
178
+ features, and the ordered public preset table. JSON uses the Node SDK's camelCase contract;
179
+ `presets list --json` returns `{presets: [...]}` in gateway order. Neither command infers
180
+ public availability from the broader internal preset map.
181
+
182
+ ### 5.3 `jobs list`
158
183
 
159
184
  ```text
160
185
  mediaruntime jobs list
@@ -173,7 +198,7 @@ The human table columns are `ID`, `STATUS`, `TIER`, `UNITS`, `BUNDLE`, and `UPDA
173
198
  List rows intentionally have no bundle download URL; `jobs get` is the download-aware
174
199
  surface.
175
200
 
176
- ### 5.3 `jobs get`
201
+ ### 5.4 `jobs get`
177
202
 
178
203
  ```text
179
204
  mediaruntime jobs get <job_id>
@@ -320,6 +345,8 @@ surface.
320
345
  - `run --wait` and `jobs get`: curated job details, with bundle availability,
321
346
  `expiresAt`, `sizeBytes`, `sha256`, and `retentionDays`, but no `downloadUrl`.
322
347
  - `jobs list`: `{jobs, nextCursor}` from the SDK.
348
+ - `capabilities`: the complete SDK capability projection.
349
+ - `presets list`: `{presets: [...]}` containing only ordered public preset rows.
323
350
  - `trigger`: `{eventId, type, jobId, status, destination, httpStatus}`.
324
351
 
325
352
  If `--download` is used, a successful atomic download is required before exit `0`. The
@@ -482,9 +509,9 @@ production credentials, billable jobs, real storage, or listening ports.
482
509
 
483
510
  ## 13. Release gates
484
511
 
485
- The v1 package is ready only when:
512
+ The v1 release gates are:
486
513
 
487
- 1. Type checking, unit tests, package smoke tests, and Node 20/22 CI pass.
514
+ 1. Type checking, unit tests, package smoke tests, and Node 22/24 CI pass.
488
515
  2. A packed tarball installs and exposes the `mediaruntime` executable with a valid
489
516
  shebang and no development fixtures.
490
517
  3. Contract tests use the released Node SDK's gateway fixtures for aliases and statuses.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mediaruntime/cli",
3
- "version": "0.2.1",
3
+ "version": "1.1.0",
4
4
  "description": "Official command-line client for MediaRuntime",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,7 +21,7 @@
21
21
  "LICENSE"
22
22
  ],
23
23
  "engines": {
24
- "node": ">=20.0.0"
24
+ "node": ">=22.0.0"
25
25
  },
26
26
  "scripts": {
27
27
  "build": "tsup",
@@ -32,7 +32,7 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@napi-rs/keyring": "^1.3.0",
35
- "@mediaruntime/node": "^0.2.5"
35
+ "@mediaruntime/node": "^1.1.1"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "^24.3.0",
@@ -60,10 +60,5 @@
60
60
  "audio",
61
61
  "cli"
62
62
  ],
63
- "main": "index.js",
64
- "directories": {
65
- "doc": "docs",
66
- "test": "test"
67
- },
68
- "author": ""
63
+ "main": "./dist/cli.js"
69
64
  }