@supersdk/supercli 0.3.10-staging.72 → 0.3.10-staging.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,677 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.defaultSchedulerDeps = void 0;
37
+ exports.isCommandOutcome = isCommandOutcome;
38
+ exports.resolveSchedulerAuth = resolveSchedulerAuth;
39
+ exports.schedulerFailure = schedulerFailure;
40
+ exports.resolveSchedulerHeaders = resolveSchedulerHeaders;
41
+ exports.resolveSchedulerBody = resolveSchedulerBody;
42
+ exports.buildCreateRequest = buildCreateRequest;
43
+ exports.runSchedulerList = runSchedulerList;
44
+ exports.runSchedulerCreate = runSchedulerCreate;
45
+ exports.runSchedulerShow = runSchedulerShow;
46
+ exports.runSchedulerPause = runSchedulerPause;
47
+ exports.runSchedulerResume = runSchedulerResume;
48
+ exports.runSchedulerDelete = runSchedulerDelete;
49
+ exports.runSchedulerRunNow = runSchedulerRunNow;
50
+ exports.runSchedulerExecutions = runSchedulerExecutions;
51
+ exports.registerSchedulerCommand = registerSchedulerCommand;
52
+ const fs = __importStar(require("node:fs"));
53
+ const schedulerClient_1 = require("../api/schedulerClient");
54
+ const tokenAuth_1 = require("../auth/tokenAuth");
55
+ const environments_1 = require("../config/environments");
56
+ const resultPrinter_1 = require("../output/resultPrinter");
57
+ const accountStore_1 = require("../store/accountStore");
58
+ const credentialStore_1 = require("../store/credentialStore");
59
+ const log_1 = require("../util/log");
60
+ const prompt_1 = require("../util/prompt");
61
+ const projectContext_1 = require("../workspace/projectContext");
62
+ const ENV_NAME_PATTERN = /^[a-z0-9]{1,10}$/;
63
+ const FORBIDDEN_HEADER_NAMES = new Set([
64
+ 'host',
65
+ 'content-length',
66
+ 'transfer-encoding',
67
+ 'connection',
68
+ 'upgrade',
69
+ 'te',
70
+ 'keep-alive',
71
+ ]);
72
+ const SCHEDULER_USER_DATA_PATHS = [
73
+ '$.jobs[*].name',
74
+ '$.jobs[*].description',
75
+ '$.jobs[*].url',
76
+ '$.jobs[*].schedule',
77
+ '$.jobs[*].timezone',
78
+ '$.jobs[*].hmac_suffix',
79
+ '$.job.name',
80
+ '$.job.description',
81
+ '$.job.url',
82
+ '$.job.schedule',
83
+ '$.job.timezone',
84
+ '$.job.hmac_secret',
85
+ '$.job.hmac_suffix',
86
+ '$.executions[*].id',
87
+ '$.executions[*].note',
88
+ '$.execution.id',
89
+ '$.execution.note',
90
+ ];
91
+ const SCHEDULER_MESSAGES = {
92
+ SCHEDULER_URL_INVALID: 'scheduler URL is invalid; it must be http(s) without userinfo or fragment',
93
+ SCHEDULER_CRON_INVALID: 'cron expression is not a valid five-field unix cron',
94
+ SCHEDULER_CRON_TOO_FREQUENT: 'cron interval must be at least one minute',
95
+ SCHEDULER_METHOD_INVALID: 'method must be GET, POST, PUT, PATCH, HEAD, or DELETE; only POST, PUT and PATCH may send a body',
96
+ SCHEDULER_BODY_TOO_LARGE: 'request body exceeds 64 KiB',
97
+ SCHEDULER_HEADER_INVALID: 'one or more headers are invalid, forbidden, duplicated, or too large',
98
+ SCHEDULER_NAME_INVALID: 'job name must be 1-40 lowercase letters, digits or hyphens, and may not start or end with a hyphen',
99
+ SCHEDULER_NAME_DUPLICATE: 'a scheduler job with this name already exists in the environment',
100
+ SCHEDULER_QUOTA_EXCEEDED: 'this environment already has 20 scheduler jobs, including paused jobs',
101
+ SCHEDULER_NOT_FOUND: 'scheduler job was not found in this project environment',
102
+ SCHEDULER_TIMEZONE_INVALID: 'timezone must be a valid IANA name such as UTC or Asia/Shanghai',
103
+ SCHEDULER_DESCRIPTION_INVALID: 'description must be at most 256 characters',
104
+ SCHEDULER_RETRIES_INVALID: 'retries must be an integer from 0 to 5',
105
+ SCHEDULER_TIMEOUT_INVALID: 'timeout-secs must be an integer from 5 to 30',
106
+ TARGET_UNREACHABLE: 'the scheduler target is unreachable or not a public HTTP(S) address',
107
+ NOT_FOUND: 'project, environment or scheduler job was not found',
108
+ };
109
+ function storedToken(account) {
110
+ return (0, credentialStore_1.backendForAccount)(account.backend, {
111
+ passphraseProvider: account.backend === 'encrypted-file'
112
+ ? () => (0, prompt_1.promptHiddenSync)(`Encryption passphrase for ${account.email ?? account.accountKey}: `)
113
+ : undefined,
114
+ }).get(account.accountKey)?.token ?? null;
115
+ }
116
+ exports.defaultSchedulerDeps = {
117
+ getCurrentAccount: accountStore_1.getCurrentAccount,
118
+ getStoredToken: storedToken,
119
+ markNeedsLogin: accountStore_1.markAccountNeedsLogin,
120
+ createClient: (apiOrigin) => new schedulerClient_1.SchedulerClient(apiOrigin),
121
+ readFile: (file) => fs.readFileSync(file),
122
+ readEnvVar: (name) => process.env[name],
123
+ };
124
+ function trimmed(input) {
125
+ const value = input?.trim();
126
+ return value && value.length > 0 ? value : null;
127
+ }
128
+ function isCommandOutcome(value) {
129
+ return value !== null && typeof value === 'object' && 'ok' in value;
130
+ }
131
+ function asRecord(value) {
132
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
133
+ ? value
134
+ : undefined;
135
+ }
136
+ function optionalString(value) {
137
+ return value === undefined || value === null || typeof value === 'string';
138
+ }
139
+ function optionalNumber(value) {
140
+ return value === undefined || value === null || typeof value === 'number';
141
+ }
142
+ function isJob(value) {
143
+ const item = asRecord(value);
144
+ return item !== undefined
145
+ && typeof item.name === 'string'
146
+ && typeof item.schedule === 'string'
147
+ && typeof item.timezone === 'string'
148
+ && typeof item.method === 'string'
149
+ && typeof item.url === 'string'
150
+ && typeof item.hmac === 'boolean'
151
+ && typeof item.retries === 'number'
152
+ && typeof item.timeout_secs === 'number'
153
+ && typeof item.state === 'string'
154
+ && typeof item.created_at === 'string'
155
+ && optionalString(item.description)
156
+ && optionalString(item.hmac_secret)
157
+ && optionalString(item.hmac_suffix)
158
+ && optionalString(item.last_status)
159
+ && optionalNumber(item.last_http_code)
160
+ && optionalString(item.last_at)
161
+ && optionalString(item.next_run_at);
162
+ }
163
+ function isExecution(value) {
164
+ const item = asRecord(value);
165
+ return item !== undefined
166
+ && typeof item.id === 'string'
167
+ && typeof item.at === 'string'
168
+ && typeof item.trigger === 'string'
169
+ && typeof item.status === 'string'
170
+ && typeof item.attempt === 'number'
171
+ && optionalNumber(item.http_code)
172
+ && optionalNumber(item.duration_ms)
173
+ && optionalString(item.note);
174
+ }
175
+ function isJobList(value) {
176
+ const item = asRecord(value);
177
+ return item !== undefined
178
+ && Array.isArray(item.jobs)
179
+ && item.jobs.every(isJob)
180
+ && typeof item.used === 'number'
181
+ && typeof item.limit === 'number';
182
+ }
183
+ function resolveSchedulerAuth(deps) {
184
+ const envToken = (0, tokenAuth_1.resolveEnvToken)();
185
+ if (envToken)
186
+ return { token: envToken, apiOrigin: (0, environments_1.resolveApiOrigin)().apiOrigin, source: 'env' };
187
+ const account = deps.getCurrentAccount();
188
+ if (!account) {
189
+ return { ok: false, kind: 'needs_login', message: 'no account is logged in — run `supercli login` first or set SUPERCLI_TOKEN' };
190
+ }
191
+ let token;
192
+ try {
193
+ token = deps.getStoredToken(account);
194
+ }
195
+ catch {
196
+ return { ok: false, kind: 'needs_login', message: 'cannot access the local credential — run `supercli login` again or set SUPERCLI_TOKEN' };
197
+ }
198
+ if (!token) {
199
+ deps.markNeedsLogin(account.accountKey);
200
+ return { ok: false, kind: 'needs_login', message: 'no valid credential found locally — run `supercli login` again or set SUPERCLI_TOKEN' };
201
+ }
202
+ return { token, apiOrigin: account.apiOrigin, source: 'stored', accountKey: account.accountKey };
203
+ }
204
+ function validEnv(raw) {
205
+ const value = trimmed(raw);
206
+ if (!value || !ENV_NAME_PATTERN.test(value)) {
207
+ return { ok: false, kind: 'usage_error', message: '--env is required and must be 1-10 lowercase letters or digits' };
208
+ }
209
+ return value;
210
+ }
211
+ function validJobName(raw) {
212
+ const value = trimmed(raw);
213
+ if (!value)
214
+ return { ok: false, kind: 'usage_error', message: 'job name is required' };
215
+ if (!schedulerClient_1.SCHEDULER_JOB_NAME_PATTERN.test(value)) {
216
+ return {
217
+ ok: false,
218
+ kind: 'usage_error',
219
+ message: 'job name must be 1-40 lowercase letters, digits or hyphens, and may not start or end with a hyphen',
220
+ };
221
+ }
222
+ return value;
223
+ }
224
+ function validScope(opts) {
225
+ const context = (0, projectContext_1.resolveWorkspaceContext)(process.cwd(), opts.config);
226
+ if (isCommandOutcome(context))
227
+ return context;
228
+ const env = validEnv(opts.env);
229
+ if (isCommandOutcome(env))
230
+ return env;
231
+ if (!context.spid)
232
+ return { ok: false, kind: 'usage_error', message: 'SPID is read from super.json' };
233
+ return { configPath: context.configPath, spid: context.spid, env };
234
+ }
235
+ function schedulerFailure(outcome, action) {
236
+ switch (outcome.kind) {
237
+ case 'business_error':
238
+ return {
239
+ ok: false,
240
+ kind: 'business_error',
241
+ publicCode: outcome.code,
242
+ message: SCHEDULER_MESSAGES[outcome.code] ?? `scheduler ${action} was rejected (${outcome.code})`,
243
+ };
244
+ case 'auth_invalid':
245
+ return { ok: false, kind: 'auth_invalid', message: 'scheduler authentication failed — run `supercli login` again or replace SUPERCLI_TOKEN' };
246
+ case 'forbidden':
247
+ return {
248
+ ok: false,
249
+ kind: 'forbidden',
250
+ message: `scheduler ${action} is forbidden for this project — writes require an admin credential in the owning organization`,
251
+ };
252
+ case 'rate_limited':
253
+ return { ok: false, kind: 'rate_limited', message: 'scheduler request was rate limited — retry later' };
254
+ case 'infra_error':
255
+ return { ok: false, kind: 'infra_error', message: 'scheduler service is unavailable or returned an invalid response — retry later' };
256
+ case 'success':
257
+ return { ok: false, kind: 'infra_error', message: 'unexpected scheduler client outcome' };
258
+ }
259
+ }
260
+ function handleFailure(outcome, auth, deps, action) {
261
+ if (outcome.kind === 'auth_invalid' && auth.source === 'stored' && auth.accountKey) {
262
+ deps.markNeedsLogin(auth.accountKey);
263
+ }
264
+ return schedulerFailure(outcome, action);
265
+ }
266
+ function success(scope, payload, humanMessage) {
267
+ const result = (0, projectContext_1.withConfigIdentity)(scope, { ...payload, env: scope.env });
268
+ return {
269
+ ok: true,
270
+ result,
271
+ humanMessage: humanMessage ?? JSON.stringify(result, null, 2),
272
+ allowTokenShapedPaths: SCHEDULER_USER_DATA_PATHS,
273
+ };
274
+ }
275
+ function requiredText(raw, flag) {
276
+ const value = trimmed(raw);
277
+ if (!value)
278
+ return { ok: false, kind: 'usage_error', message: `${flag} is required and must not be empty` };
279
+ return value;
280
+ }
281
+ function optionalBoundedInt(raw, flag, min, max) {
282
+ if (raw === undefined)
283
+ return undefined;
284
+ const value = trimmed(raw);
285
+ if (!value || !/^\d+$/.test(value)) {
286
+ return { ok: false, kind: 'usage_error', message: `${flag} must be an integer from ${min} to ${max}` };
287
+ }
288
+ const parsed = Number(value);
289
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
290
+ return { ok: false, kind: 'usage_error', message: `${flag} must be an integer from ${min} to ${max}` };
291
+ }
292
+ return parsed;
293
+ }
294
+ function parseHeaderPair(raw, separatorHint) {
295
+ const trimmedRaw = raw.trim();
296
+ const colon = trimmedRaw.indexOf(':');
297
+ const equals = trimmedRaw.indexOf('=');
298
+ let splitAt = -1;
299
+ if (separatorHint === ':')
300
+ splitAt = colon;
301
+ else if (separatorHint === '=')
302
+ splitAt = equals;
303
+ else if (colon >= 0 && (equals < 0 || colon < equals))
304
+ splitAt = colon;
305
+ else
306
+ splitAt = equals;
307
+ if (splitAt <= 0) {
308
+ return {
309
+ ok: false,
310
+ kind: 'usage_error',
311
+ message: separatorHint === '='
312
+ ? '--header-env must be Name=VAR'
313
+ : '--header must be Name:Value or Name=Value',
314
+ };
315
+ }
316
+ const name = trimmedRaw.slice(0, splitAt).trim();
317
+ const value = trimmedRaw.slice(splitAt + 1);
318
+ if (!name) {
319
+ return { ok: false, kind: 'usage_error', message: 'header name must not be empty' };
320
+ }
321
+ return { name, value };
322
+ }
323
+ function validateHeaderName(name) {
324
+ if (name.length < 1 || name.length > schedulerClient_1.SCHEDULER_HEADER_KEY_MAX) {
325
+ return { ok: false, kind: 'usage_error', message: 'header names must be 1-64 characters' };
326
+ }
327
+ const lower = name.toLowerCase();
328
+ if (FORBIDDEN_HEADER_NAMES.has(lower) || lower.startsWith('x-supersdk-')) {
329
+ return { ok: false, kind: 'usage_error', message: `header ${name} is reserved by SuperScheduler and cannot be set` };
330
+ }
331
+ return name;
332
+ }
333
+ function resolveSchedulerHeaders(opts, deps) {
334
+ const headers = {};
335
+ const seen = new Set();
336
+ const add = (name, value) => {
337
+ const validated = validateHeaderName(name);
338
+ if (isCommandOutcome(validated))
339
+ return validated;
340
+ if (value.length > schedulerClient_1.SCHEDULER_HEADER_VALUE_MAX) {
341
+ return { ok: false, kind: 'usage_error', message: 'header values must be at most 1 KiB' };
342
+ }
343
+ const key = validated.toLowerCase();
344
+ if (seen.has(key)) {
345
+ return { ok: false, kind: 'usage_error', message: `duplicate header ${validated}` };
346
+ }
347
+ seen.add(key);
348
+ headers[validated] = value;
349
+ return undefined;
350
+ };
351
+ for (const raw of opts.header ?? []) {
352
+ const pair = parseHeaderPair(raw, 'either');
353
+ if (isCommandOutcome(pair))
354
+ return pair;
355
+ const added = add(pair.name, pair.value);
356
+ if (added)
357
+ return added;
358
+ }
359
+ for (const raw of opts.headerEnv ?? []) {
360
+ const pair = parseHeaderPair(raw, '=');
361
+ if (isCommandOutcome(pair))
362
+ return pair;
363
+ const varName = pair.value.trim();
364
+ if (!varName)
365
+ return { ok: false, kind: 'usage_error', message: '--header-env must be Name=VAR' };
366
+ const value = deps.readEnvVar(varName);
367
+ if (value === undefined || value.length === 0) {
368
+ return { ok: false, kind: 'usage_error', message: `environment variable ${varName} is unset or empty` };
369
+ }
370
+ const added = add(pair.name, value);
371
+ if (added)
372
+ return added;
373
+ }
374
+ return headers;
375
+ }
376
+ function resolveSchedulerBody(opts, deps) {
377
+ const hasBody = opts.body !== undefined;
378
+ const hasFile = opts.bodyFile !== undefined;
379
+ if (hasBody && hasFile) {
380
+ return { ok: false, kind: 'usage_error', message: 'choose at most one body source: --body or --body-file' };
381
+ }
382
+ if (!hasBody && !hasFile)
383
+ return undefined;
384
+ if (hasBody)
385
+ return opts.body ?? '';
386
+ try {
387
+ return new TextDecoder('utf-8', { fatal: true }).decode(deps.readFile(opts.bodyFile ?? ''));
388
+ }
389
+ catch {
390
+ return { ok: false, kind: 'usage_error', message: 'could not read a valid UTF-8 body file; verify --body-file points to a readable UTF-8 file' };
391
+ }
392
+ }
393
+ function validateUrl(raw) {
394
+ let parsed;
395
+ try {
396
+ parsed = new URL(raw);
397
+ }
398
+ catch {
399
+ return { ok: false, kind: 'usage_error', message: '--url must be a valid http or https URL' };
400
+ }
401
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
402
+ return { ok: false, kind: 'usage_error', message: '--url must use http or https' };
403
+ }
404
+ if (parsed.username || parsed.password || parsed.hash) {
405
+ return { ok: false, kind: 'usage_error', message: '--url must not contain userinfo or fragment' };
406
+ }
407
+ return raw;
408
+ }
409
+ function buildCreateRequest(name, opts, deps) {
410
+ const schedule = requiredText(opts.schedule, '--schedule');
411
+ if (isCommandOutcome(schedule))
412
+ return schedule;
413
+ const timezone = requiredText(opts.timezone, '--timezone');
414
+ if (isCommandOutcome(timezone))
415
+ return timezone;
416
+ const urlRaw = requiredText(opts.url, '--url');
417
+ if (isCommandOutcome(urlRaw))
418
+ return urlRaw;
419
+ const url = validateUrl(urlRaw);
420
+ if (isCommandOutcome(url))
421
+ return url;
422
+ const methodRaw = trimmed(opts.method)?.toUpperCase() ?? 'POST';
423
+ if (!schedulerClient_1.SCHEDULER_METHODS.includes(methodRaw)) {
424
+ return { ok: false, kind: 'usage_error', message: '--method must be GET, POST, PUT, PATCH, HEAD, or DELETE' };
425
+ }
426
+ const method = methodRaw;
427
+ const descriptionRaw = opts.description === undefined ? undefined : opts.description.trim();
428
+ if (descriptionRaw !== undefined && [...descriptionRaw].length > schedulerClient_1.SCHEDULER_DESCRIPTION_MAX) {
429
+ return { ok: false, kind: 'usage_error', message: '--description must be at most 256 characters' };
430
+ }
431
+ const retries = optionalBoundedInt(opts.retries, '--retries', schedulerClient_1.SCHEDULER_MIN_RETRIES, schedulerClient_1.SCHEDULER_MAX_RETRIES);
432
+ if (isCommandOutcome(retries))
433
+ return retries;
434
+ const timeoutSecs = optionalBoundedInt(opts.timeoutSecs, '--timeout-secs', schedulerClient_1.SCHEDULER_MIN_TIMEOUT_SECS, schedulerClient_1.SCHEDULER_MAX_TIMEOUT_SECS);
435
+ if (isCommandOutcome(timeoutSecs))
436
+ return timeoutSecs;
437
+ const headers = resolveSchedulerHeaders(opts, deps);
438
+ if (isCommandOutcome(headers))
439
+ return headers;
440
+ const body = resolveSchedulerBody(opts, deps);
441
+ if (isCommandOutcome(body))
442
+ return body;
443
+ if (body !== undefined && !schedulerClient_1.SCHEDULER_BODY_METHODS.includes(method)) {
444
+ return { ok: false, kind: 'usage_error', message: `${method} cannot include a body; omit --body/--body-file or use POST, PUT or PATCH` };
445
+ }
446
+ if (body !== undefined && Buffer.byteLength(body, 'utf8') > schedulerClient_1.SCHEDULER_BODY_MAX_BYTES) {
447
+ return { ok: false, kind: 'usage_error', message: 'request body exceeds 64 KiB' };
448
+ }
449
+ return {
450
+ name,
451
+ schedule,
452
+ timezone,
453
+ method,
454
+ url,
455
+ ...(descriptionRaw ? { description: descriptionRaw } : {}),
456
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
457
+ ...(body !== undefined ? { body } : {}),
458
+ hmac: opts.hmac !== false,
459
+ ...(retries === undefined ? {} : { retries }),
460
+ ...(timeoutSecs === undefined ? {} : { timeout_secs: timeoutSecs }),
461
+ };
462
+ }
463
+ async function runSchedulerList(opts, deps = exports.defaultSchedulerDeps) {
464
+ const scope = validScope(opts);
465
+ if (isCommandOutcome(scope))
466
+ return scope;
467
+ const auth = resolveSchedulerAuth(deps);
468
+ if (isCommandOutcome(auth))
469
+ return auth;
470
+ const outcome = await deps.createClient(auth.apiOrigin).list({ token: auth.token }, scope);
471
+ if (outcome.kind !== 'success')
472
+ return handleFailure(outcome, auth, deps, 'list');
473
+ if (!isJobList(outcome.data)) {
474
+ return { ok: false, kind: 'infra_error', message: 'scheduler job list returned an invalid response' };
475
+ }
476
+ return success(scope, { jobs: outcome.data.jobs, used: outcome.data.used, limit: outcome.data.limit });
477
+ }
478
+ async function runSchedulerCreate(nameRaw, opts, requestId, deps = exports.defaultSchedulerDeps) {
479
+ const name = validJobName(nameRaw);
480
+ if (isCommandOutcome(name))
481
+ return name;
482
+ const body = buildCreateRequest(name, opts, deps);
483
+ if (isCommandOutcome(body))
484
+ return body;
485
+ const scope = validScope(opts);
486
+ if (isCommandOutcome(scope))
487
+ return scope;
488
+ const auth = resolveSchedulerAuth(deps);
489
+ if (isCommandOutcome(auth))
490
+ return auth;
491
+ const outcome = await deps.createClient(auth.apiOrigin).create({ token: auth.token, requestId }, scope, body);
492
+ if (outcome.kind !== 'success')
493
+ return handleFailure(outcome, auth, deps, 'create');
494
+ if (!isJob(outcome.data)) {
495
+ return { ok: false, kind: 'infra_error', message: 'scheduler create returned an invalid response' };
496
+ }
497
+ const humanLines = [JSON.stringify((0, projectContext_1.withConfigIdentity)(scope, { job: outcome.data, env: scope.env }), null, 2)];
498
+ if (outcome.data.hmac_secret) {
499
+ humanLines.unshift('hmac_secret is shown once; copy it now. list/show never return it.');
500
+ }
501
+ if (body.url.startsWith('http://')) {
502
+ humanLines.unshift('http URLs send headers, body and HMAC in plaintext.');
503
+ }
504
+ return success(scope, { job: outcome.data }, humanLines.join('\n'));
505
+ }
506
+ async function namedJobAction(action, nameRaw, opts, requestId, deps) {
507
+ const name = validJobName(nameRaw);
508
+ if (isCommandOutcome(name))
509
+ return name;
510
+ const scope = validScope(opts);
511
+ if (isCommandOutcome(scope))
512
+ return scope;
513
+ const auth = resolveSchedulerAuth(deps);
514
+ if (isCommandOutcome(auth))
515
+ return auth;
516
+ const client = deps.createClient(auth.apiOrigin);
517
+ const outcome = action === 'show'
518
+ ? await client.show({ token: auth.token }, scope, name)
519
+ : action === 'pause'
520
+ ? await client.pause({ token: auth.token, requestId }, scope, name)
521
+ : action === 'resume'
522
+ ? await client.resume({ token: auth.token, requestId }, scope, name)
523
+ : await client.remove({ token: auth.token, requestId }, scope, name);
524
+ if (outcome.kind !== 'success')
525
+ return handleFailure(outcome, auth, deps, action);
526
+ if (action === 'remove')
527
+ return success(scope, { deleted: true, name });
528
+ if (!isJob(outcome.data)) {
529
+ return { ok: false, kind: 'infra_error', message: `scheduler ${action} returned an invalid response` };
530
+ }
531
+ return success(scope, { job: outcome.data });
532
+ }
533
+ async function runSchedulerShow(name, opts, deps = exports.defaultSchedulerDeps) {
534
+ return namedJobAction('show', name, opts, '', deps);
535
+ }
536
+ async function runSchedulerPause(name, opts, requestId, deps = exports.defaultSchedulerDeps) {
537
+ return namedJobAction('pause', name, opts, requestId, deps);
538
+ }
539
+ async function runSchedulerResume(name, opts, requestId, deps = exports.defaultSchedulerDeps) {
540
+ return namedJobAction('resume', name, opts, requestId, deps);
541
+ }
542
+ async function runSchedulerDelete(name, opts, requestId, deps = exports.defaultSchedulerDeps) {
543
+ return namedJobAction('remove', name, opts, requestId, deps);
544
+ }
545
+ async function runSchedulerRunNow(nameRaw, opts, requestId, deps = exports.defaultSchedulerDeps) {
546
+ const name = validJobName(nameRaw);
547
+ if (isCommandOutcome(name))
548
+ return name;
549
+ const scope = validScope(opts);
550
+ if (isCommandOutcome(scope))
551
+ return scope;
552
+ const auth = resolveSchedulerAuth(deps);
553
+ if (isCommandOutcome(auth))
554
+ return auth;
555
+ const outcome = await deps.createClient(auth.apiOrigin).runNow({ token: auth.token, requestId }, scope, name);
556
+ if (outcome.kind !== 'success')
557
+ return handleFailure(outcome, auth, deps, 'run-now');
558
+ if (!isExecution(outcome.data)) {
559
+ return { ok: false, kind: 'infra_error', message: 'scheduler run-now returned an invalid response' };
560
+ }
561
+ return success(scope, { execution: outcome.data });
562
+ }
563
+ async function runSchedulerExecutions(nameRaw, opts, deps = exports.defaultSchedulerDeps) {
564
+ const name = validJobName(nameRaw);
565
+ if (isCommandOutcome(name))
566
+ return name;
567
+ const scope = validScope(opts);
568
+ if (isCommandOutcome(scope))
569
+ return scope;
570
+ const auth = resolveSchedulerAuth(deps);
571
+ if (isCommandOutcome(auth))
572
+ return auth;
573
+ const outcome = await deps.createClient(auth.apiOrigin).executions({ token: auth.token }, scope, name);
574
+ if (outcome.kind !== 'success')
575
+ return handleFailure(outcome, auth, deps, 'executions');
576
+ if (!Array.isArray(outcome.data) || !outcome.data.every(isExecution)) {
577
+ return { ok: false, kind: 'infra_error', message: 'scheduler executions returned an invalid response' };
578
+ }
579
+ return success(scope, { name, executions: outcome.data });
580
+ }
581
+ function outputModeOf(cmd) {
582
+ return cmd.optsWithGlobals?.()?.output === 'json' ? 'json' : 'human';
583
+ }
584
+ function addLeafOutputOptions(command) {
585
+ return command
586
+ .option('--output <mode>', 'output mode: "json" emits a single machine-readable envelope on stdout')
587
+ .option('--no-input', 'never prompt for interactive input; fail fast (implied by --output json)');
588
+ }
589
+ function collect(value, previous) {
590
+ return previous.concat(value);
591
+ }
592
+ function emit(printer, outcome) {
593
+ printer.emit(outcome);
594
+ }
595
+ function registerSchedulerCommand(program, deps = exports.defaultSchedulerDeps) {
596
+ const scheduler = program
597
+ .command('scheduler')
598
+ .description('Manage SuperScheduler timed HTTP(S) jobs in one project environment.');
599
+ addLeafOutputOptions(scheduler.command('list')
600
+ .description('List SuperScheduler jobs and the per-environment quota.')
601
+ .option('--config <path>', 'explicit super.json path')
602
+ .requiredOption('--env <env>', 'project environment')
603
+ .action(async (opts, cmd) => {
604
+ emit(new resultPrinter_1.ResultPrinter(outputModeOf(cmd)), await runSchedulerList(opts, deps));
605
+ }));
606
+ addLeafOutputOptions(scheduler.command('create <name>')
607
+ .description('Create one SuperScheduler job. HMAC secret is returned once.')
608
+ .option('--config <path>', 'explicit super.json path')
609
+ .requiredOption('--env <env>', 'project environment')
610
+ .requiredOption('--schedule <cron>', 'five-field unix cron; shortest interval is one minute (`* * * * *`)')
611
+ .requiredOption('--timezone <iana>', 'IANA timezone such as UTC or Asia/Shanghai')
612
+ .requiredOption('--url <url>', 'public http(s) URL the platform will call')
613
+ .option('--method <method>', 'HTTP method (default POST)')
614
+ .option('--description <text>', 'optional job description')
615
+ .option('--header <name:value>', 'add one outbound header (repeatable; prefer --header-env for secrets)', collect, [])
616
+ .option('--header-env <name=VAR>', 'add one outbound header from an environment variable (repeatable)', collect, [])
617
+ .option('--body <text>', 'request body (may be recorded in shell history)')
618
+ .option('--body-file <path>', 'read the request body from a UTF-8 file')
619
+ .option('--no-hmac', 'do not sign outbound requests with HMAC')
620
+ .option('--retries <n>', 'retry count 0-5 (default 2)')
621
+ .option('--timeout-secs <n>', 'per-attempt timeout 5-30 seconds (default 30)')
622
+ .action(async (name, opts, cmd) => {
623
+ const mode = outputModeOf(cmd);
624
+ const printer = new resultPrinter_1.ResultPrinter(mode);
625
+ if (mode === 'human' && opts.body !== undefined) {
626
+ log_1.log.warn('--body may be recorded in local shell history; prefer --body-file for sensitive payloads');
627
+ }
628
+ emit(printer, await runSchedulerCreate(name, opts, printer.requestId, deps));
629
+ }));
630
+ addLeafOutputOptions(scheduler.command('show <name>')
631
+ .description('Show one SuperScheduler job. Headers and HMAC secret are never returned.')
632
+ .option('--config <path>', 'explicit super.json path')
633
+ .requiredOption('--env <env>', 'project environment')
634
+ .action(async (name, opts, cmd) => {
635
+ emit(new resultPrinter_1.ResultPrinter(outputModeOf(cmd)), await runSchedulerShow(name, opts, deps));
636
+ }));
637
+ addLeafOutputOptions(scheduler.command('pause <name>')
638
+ .description('Pause one SuperScheduler job so cron no longer fires (admin).')
639
+ .option('--config <path>', 'explicit super.json path')
640
+ .requiredOption('--env <env>', 'project environment')
641
+ .action(async (name, opts, cmd) => {
642
+ const printer = new resultPrinter_1.ResultPrinter(outputModeOf(cmd));
643
+ emit(printer, await runSchedulerPause(name, opts, printer.requestId, deps));
644
+ }));
645
+ addLeafOutputOptions(scheduler.command('resume <name>')
646
+ .description('Resume one paused SuperScheduler job (admin).')
647
+ .option('--config <path>', 'explicit super.json path')
648
+ .requiredOption('--env <env>', 'project environment')
649
+ .action(async (name, opts, cmd) => {
650
+ const printer = new resultPrinter_1.ResultPrinter(outputModeOf(cmd));
651
+ emit(printer, await runSchedulerResume(name, opts, printer.requestId, deps));
652
+ }));
653
+ addLeafOutputOptions(scheduler.command('run-now <name>')
654
+ .description('Trigger one SuperScheduler job immediately without changing its schedule (admin).')
655
+ .option('--config <path>', 'explicit super.json path')
656
+ .requiredOption('--env <env>', 'project environment')
657
+ .action(async (name, opts, cmd) => {
658
+ const printer = new resultPrinter_1.ResultPrinter(outputModeOf(cmd));
659
+ emit(printer, await runSchedulerRunNow(name, opts, printer.requestId, deps));
660
+ }));
661
+ addLeafOutputOptions(scheduler.command('delete <name>')
662
+ .description('Soft-delete one SuperScheduler job (admin). The name can be reused afterwards.')
663
+ .option('--config <path>', 'explicit super.json path')
664
+ .requiredOption('--env <env>', 'project environment')
665
+ .action(async (name, opts, cmd) => {
666
+ const printer = new resultPrinter_1.ResultPrinter(outputModeOf(cmd));
667
+ emit(printer, await runSchedulerDelete(name, opts, printer.requestId, deps));
668
+ }));
669
+ addLeafOutputOptions(scheduler.command('executions <name>')
670
+ .description('List recent SuperScheduler executions for one job.')
671
+ .option('--config <path>', 'explicit super.json path')
672
+ .requiredOption('--env <env>', 'project environment')
673
+ .action(async (name, opts, cmd) => {
674
+ emit(new resultPrinter_1.ResultPrinter(outputModeOf(cmd)), await runSchedulerExecutions(name, opts, deps));
675
+ }));
676
+ }
677
+ //# sourceMappingURL=scheduler.js.map