@clipwright/cli 0.85.0 → 0.87.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -6
- package/dist/guided.js +122 -0
- package/dist/index.js +222 -128
- package/dist/native.js +276 -0
- package/dist/output.js +162 -0
- package/dist/payload.js +120 -0
- package/dist/retry.js +34 -0
- package/dist/wait.js +120 -0
- package/dist/workflows.js +2 -1
- package/package.json +3 -3
package/dist/native.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
3
|
+
import { adGuideQuery, analyzeCreatorRequest, analyzeReferenceRequest, ASSET_BYTES_ROUTE_VIDEO_MAX_BYTES, ASSET_ROLES, assetListQuery, checkFilmInput, createAssetRequest, createCutInput, createFilmDraftInput, filmCutInput, filmCutPreviewInput, filmCutRunInput, filmEditInput, filmGuideQuery, filmKitQuery, filmRenderInput, filmVoiceInput, findTrendsInput, generateImageRequest, generateVideoRequest, makeUgcInput, putFilmFilesInput, takeCheckInput, takeFramesInput, updateCutInput, uploadIntentRequest, } from "@clipwright/core";
|
|
4
|
+
import { ClipwrightResponseError } from "@clipwright/sdk";
|
|
5
|
+
import { Option } from "commander";
|
|
6
|
+
import { commandLine, fail, outputMode, unverifiedFailure } from "./output.js";
|
|
7
|
+
import { buildPayload, templateOf, withPayloadOptions } from "./payload.js";
|
|
8
|
+
import { startWithResend } from "./retry.js";
|
|
9
|
+
import { failIfFailed, READ_COMMAND, saveFile, waitUntilDone, withWaitOptions } from "./wait.js";
|
|
10
|
+
const print = (value) => console.log(JSON.stringify(value, null, 2));
|
|
11
|
+
export const sameCommand = () => commandLine(process.argv.slice(2));
|
|
12
|
+
export function withAttemptOption(command, parse) {
|
|
13
|
+
return command
|
|
14
|
+
.addOption(new Option("--attempt <n>", "attempt number, 1 by default: another number starts a NEW paid run; " +
|
|
15
|
+
"the same command and number return the run already started").argParser(parse("--attempt")).conflicts("retry"))
|
|
16
|
+
.addOption(new Option("--retry <n>", "the same as --attempt").argParser(parse("--retry")).hideHelp());
|
|
17
|
+
}
|
|
18
|
+
export const attemptOf = (opts) => opts.attempt ?? opts.retry;
|
|
19
|
+
export async function confirmDestructive(opts, summary, words) {
|
|
20
|
+
if (opts.yes === true)
|
|
21
|
+
return;
|
|
22
|
+
const command = commandLine(words);
|
|
23
|
+
if (process.stdin.isTTY === true && process.stderr.isTTY === true && outputMode() === "text") {
|
|
24
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
25
|
+
const answer = await prompt.question(`${summary} This cannot be undone. Continue? [y/N] `).catch(() => "");
|
|
26
|
+
prompt.close();
|
|
27
|
+
if (/^y(es)?$/i.test(answer.trim()))
|
|
28
|
+
return;
|
|
29
|
+
fail({ code: "cancelled", message: "Nothing was deleted.", fix: [`Run ${command} --yes once the user agrees.`] });
|
|
30
|
+
}
|
|
31
|
+
fail({ code: "confirmation_required", message: `${summary} This cannot be undone, so it needs --yes. Nothing was deleted.`,
|
|
32
|
+
resume: `${command} --yes`, fix: ["Show the user what will be deleted and get a clear yes.", `Then run ${command} --yes.`] });
|
|
33
|
+
}
|
|
34
|
+
const hasMaxCredits = (schema) => {
|
|
35
|
+
const json = schema.toJSONSchema({ io: "input", unrepresentable: "any" });
|
|
36
|
+
return json.properties !== undefined && "max_credits" in json.properties;
|
|
37
|
+
};
|
|
38
|
+
function startCommand(program, registry, spec) {
|
|
39
|
+
registry.templates.set(spec.name, spec.schema);
|
|
40
|
+
const command = withPayloadOptions(program.command(spec.name).description(spec.description))
|
|
41
|
+
.option("--dry-run", "print the quote of this exact request instead of starting it; spends nothing");
|
|
42
|
+
if (hasMaxCredits(spec.schema)) {
|
|
43
|
+
command.addOption(new Option("--max-credits <n>", "the most this call may cost; a call that reserves more is refused and nothing is charged")
|
|
44
|
+
.argParser(registry.parseCredits));
|
|
45
|
+
}
|
|
46
|
+
if (spec.keyed)
|
|
47
|
+
withAttemptOption(command, registry.parse);
|
|
48
|
+
withWaitOptions(command, spec.fileOf !== undefined);
|
|
49
|
+
command.action(async (opts) => {
|
|
50
|
+
const body = buildPayload(opts);
|
|
51
|
+
if (opts.maxCredits !== undefined)
|
|
52
|
+
body.max_credits = opts.maxCredits;
|
|
53
|
+
const sdk = registry.client();
|
|
54
|
+
if (opts.dryRun === true) {
|
|
55
|
+
print(await spec.quote(sdk, body));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const attempt = attemptOf(opts);
|
|
59
|
+
let started;
|
|
60
|
+
try {
|
|
61
|
+
started = spec.keyed ? await startWithResend(() => spec.start(sdk, body, attempt)) : await spec.start(sdk, body, attempt);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (!(error instanceof ClipwrightResponseError))
|
|
65
|
+
throw error;
|
|
66
|
+
fail(unverifiedFailure(error, sameCommand(), spec.keyed), [`error: ${error.message}`]);
|
|
67
|
+
}
|
|
68
|
+
const id = spec.idOf(started);
|
|
69
|
+
if (opts.wait !== true && opts.output === undefined) {
|
|
70
|
+
print(started);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const done = await waitUntilDone(sdk, spec.wait, id, started, opts.timeout);
|
|
74
|
+
print(done);
|
|
75
|
+
failIfFailed(id, done, spec.keyed
|
|
76
|
+
? `To try again, ask the user, then run the same command with --attempt ${(attempt ?? 1) + 1}: that is a new paid run.`
|
|
77
|
+
: "To try again, run its quote first and ask the user: a new start may be charged again.");
|
|
78
|
+
if (opts.output !== undefined)
|
|
79
|
+
await saveDelivered(spec.wait, id, spec.fileOf?.(done), opts.output);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
async function saveDelivered(kind, id, url, path) {
|
|
83
|
+
const resume = commandLine([READ_COMMAND[kind], id, "--output", path]);
|
|
84
|
+
if (url === undefined) {
|
|
85
|
+
fail({ code: "no_file", message: `${id} succeeded without a file to save`, details: { id },
|
|
86
|
+
fix: [`Read it with ${commandLine([READ_COMMAND[kind], id])}; what it delivered is in that answer.`] });
|
|
87
|
+
}
|
|
88
|
+
await saveFile(url, path, resume);
|
|
89
|
+
}
|
|
90
|
+
function quoteCommand(program, registry, name, description, schema, quote) {
|
|
91
|
+
registry.templates.set(name, schema);
|
|
92
|
+
withPayloadOptions(program.command(name).description(description)).action(async (opts) => {
|
|
93
|
+
print(await quote(registry.client(), buildPayload(opts)));
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
function readCommand(program, registry, name, description, read, wait) {
|
|
97
|
+
const command = program.command(`${name} <id>`).description(description);
|
|
98
|
+
if (wait !== undefined)
|
|
99
|
+
withWaitOptions(command, wait.fileOf !== undefined);
|
|
100
|
+
command.action(async (id, opts) => {
|
|
101
|
+
const sdk = registry.client();
|
|
102
|
+
const first = await read(sdk, id);
|
|
103
|
+
if (wait === undefined || (opts.wait !== true && opts.output === undefined)) {
|
|
104
|
+
print(first);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const done = await waitUntilDone(sdk, wait.kind, id, first, opts.timeout);
|
|
108
|
+
print(done);
|
|
109
|
+
failIfFailed(id, done, "Read what went wrong in error; to try again, start it anew after the user agrees.");
|
|
110
|
+
if (opts.output !== undefined)
|
|
111
|
+
await saveDelivered(wait.kind, id, wait.fileOf?.(done), opts.output);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function bodyCommand(program, registry, name, description, schema, call, withId = false) {
|
|
115
|
+
registry.templates.set(name, schema);
|
|
116
|
+
withPayloadOptions(program.command(withId ? `${name} <id>` : name).description(description))
|
|
117
|
+
.action(async (...args) => {
|
|
118
|
+
const id = withId ? args[0] : undefined;
|
|
119
|
+
const opts = (withId ? args[1] : args[0]);
|
|
120
|
+
print(await call(registry.client(), buildPayload(opts), id));
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function deleteCommand(program, registry, name, what, call) {
|
|
124
|
+
program.command(`${name} <id>`).description(`delete ${what}; asks first at a terminal, needs --yes anywhere else`)
|
|
125
|
+
.option("--yes", "confirm the deletion; it cannot be undone")
|
|
126
|
+
.action(async (id, opts) => {
|
|
127
|
+
await confirmDestructive(opts, `Delete ${what} ${id}?`, [name, id]);
|
|
128
|
+
await call(registry.client(), id);
|
|
129
|
+
print({ deleted: id });
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
const as = (body) => body;
|
|
133
|
+
const idField = (field) => (read) => String(read[field]);
|
|
134
|
+
const runId = idField("run_id");
|
|
135
|
+
const runFile = (read) => {
|
|
136
|
+
const run = read;
|
|
137
|
+
return run.final_output?.video_url ?? run.generation?.url;
|
|
138
|
+
};
|
|
139
|
+
const filmFile = (read) => {
|
|
140
|
+
const run = read;
|
|
141
|
+
return run.film?.video_url ?? run.voice?.audio_url;
|
|
142
|
+
};
|
|
143
|
+
function sniffAsset(bytes) {
|
|
144
|
+
const at = (offset, ...values) => values.every((value, index) => bytes[offset + index] === value);
|
|
145
|
+
if (at(0, 0x89, 0x50, 0x4e, 0x47))
|
|
146
|
+
return "image/png";
|
|
147
|
+
if (at(0, 0xff, 0xd8, 0xff))
|
|
148
|
+
return "image/jpeg";
|
|
149
|
+
if (at(0, 0x1a, 0x45, 0xdf, 0xa3))
|
|
150
|
+
return "video/webm";
|
|
151
|
+
if (at(4, 0x66, 0x74, 0x79, 0x70))
|
|
152
|
+
return at(8, 0x71, 0x74, 0x20, 0x20) ? "video/quicktime" : "video/mp4";
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
export function registerNativeCommands(program, registry) {
|
|
156
|
+
const templates = registry.templates;
|
|
157
|
+
readCommand(program, registry, "get-run", "read a run as JSON; --wait waits until it succeeds or fails (free)", (sdk, id) => sdk.getRun(id), { kind: "run", fileOf: runFile });
|
|
158
|
+
quoteCommand(program, registry, "quote-ugc", "price a presenter video request without spending credits", makeUgcInput, (sdk, body) => sdk.quoteUgc(as(body)));
|
|
159
|
+
startCommand(program, registry, { name: "make-ugc", description: "start a presenter video (paid) and print the run at once; --wait waits for it",
|
|
160
|
+
schema: makeUgcInput, quote: (sdk, body) => sdk.quoteUgc(as(body)), start: (sdk, body, attempt) => sdk.startUgc(as(body), { attempt }),
|
|
161
|
+
keyed: true, wait: "run", idOf: runId, fileOf: runFile });
|
|
162
|
+
quoteCommand(program, registry, "quote-trends", "price a trend search: 0 when a search of the same query from the last 24 hours answers it", findTrendsInput, (sdk, body) => sdk.quoteTrends(as(body)));
|
|
163
|
+
startCommand(program, registry, { name: "find-trends", description: "search for reels that took off on a topic (paid after the free ones); " +
|
|
164
|
+
"prints the search at once, --wait waits for its ranking", schema: findTrendsInput, quote: (sdk, body) => sdk.quoteTrends(as(body)),
|
|
165
|
+
start: (sdk, body) => sdk.findTrends(as(body)), keyed: false, wait: "trend", idOf: idField("search_id") });
|
|
166
|
+
readCommand(program, registry, "get-trend-search", "read a trend search and its ranking (free)", (sdk, id) => sdk.getTrendSearch(id), { kind: "trend" });
|
|
167
|
+
program.command("trend-niches").description("list the account's saved niches, the primary first (free)")
|
|
168
|
+
.action(async () => print(await registry.client().getTrendNiches()));
|
|
169
|
+
quoteCommand(program, registry, "quote-analysis", "price a reference analysis without spending credits", analyzeReferenceRequest, (sdk, body) => sdk.quoteAnalysis(as(body)));
|
|
170
|
+
startCommand(program, registry, { name: "analyze-reference", description: "break down a reel by link or asset (paid); prints the analysis at once, " +
|
|
171
|
+
"--wait waits until it is done", schema: analyzeReferenceRequest, quote: (sdk, body) => sdk.quoteAnalysis(as(body)),
|
|
172
|
+
start: (sdk, body) => sdk.analyzeReference(as(body)), keyed: false, wait: "analysis",
|
|
173
|
+
idOf: idField("analysis_id") });
|
|
174
|
+
readCommand(program, registry, "get-reference-analysis", "read a reference analysis (free)", (sdk, id) => sdk.getReferenceAnalysis(id), { kind: "analysis" });
|
|
175
|
+
quoteCommand(program, registry, "quote-creator-profile", "price a creator profile without spending credits", analyzeCreatorRequest, (sdk, body) => sdk.quoteCreatorProfile(as(body)));
|
|
176
|
+
startCommand(program, registry, { name: "analyze-creator", description: "profile a creator from a profile or video link (paid); --wait waits for it",
|
|
177
|
+
schema: analyzeCreatorRequest, quote: (sdk, body) => sdk.quoteCreatorProfile(as(body)), start: (sdk, body) => sdk.analyzeCreator(as(body)),
|
|
178
|
+
keyed: false, wait: "creator", idOf: idField("profile_id") });
|
|
179
|
+
readCommand(program, registry, "get-creator-profile", "read a creator profile (free)", (sdk, id) => sdk.getCreatorProfile(id), { kind: "creator" });
|
|
180
|
+
deleteCommand(program, registry, "delete-creator-profile", "the creator profile", (sdk, id) => sdk.deleteCreatorProfile(id));
|
|
181
|
+
program.command("list-generation-models").description("list the image and clip models with their sizes and prices (free)")
|
|
182
|
+
.action(async () => print(await registry.client().listGenerationModels()));
|
|
183
|
+
quoteCommand(program, registry, "quote-image", "price one image without spending credits", generateImageRequest, (sdk, body) => sdk.quoteImage(as(body)));
|
|
184
|
+
startCommand(program, registry, { name: "generate-image", description: "generate one image (paid); --wait waits for it, --output saves it",
|
|
185
|
+
schema: generateImageRequest, quote: (sdk, body) => sdk.quoteImage(as(body)),
|
|
186
|
+
start: (sdk, body, attempt) => sdk.generateImage(as(body), { attempt }), keyed: true, wait: "run", idOf: runId, fileOf: runFile });
|
|
187
|
+
quoteCommand(program, registry, "quote-video", "price one clip without spending credits", generateVideoRequest, (sdk, body) => sdk.quoteVideo(as(body)));
|
|
188
|
+
startCommand(program, registry, { name: "generate-video", description: "generate one clip (paid); --wait waits for it, --output saves it",
|
|
189
|
+
schema: generateVideoRequest, quote: (sdk, body) => sdk.quoteVideo(as(body)),
|
|
190
|
+
start: (sdk, body, attempt) => sdk.generateVideo(as(body), { attempt }), keyed: true, wait: "run", idOf: runId, fileOf: runFile });
|
|
191
|
+
const film = (name, description, schema, quote, start, fileOf) => startCommand(program, registry, { name, description, schema, quote, start, keyed: true, wait: "film", idOf: runId,
|
|
192
|
+
...(fileOf !== undefined && { fileOf }) });
|
|
193
|
+
quoteCommand(program, registry, "quote-voice", "price a voice take without spending credits", filmVoiceInput, (sdk, body) => sdk.quoteVoice(as(body)));
|
|
194
|
+
film("make-voice", "record a voice take with word timings (paid); --output saves the audio", filmVoiceInput, (sdk, body) => sdk.quoteVoice(as(body)), (sdk, body, attempt) => sdk.makeVoice(as(body), { attempt }), filmFile);
|
|
195
|
+
quoteCommand(program, registry, "quote-edit", "price an edit of your clips without spending credits", filmEditInput, (sdk, body) => sdk.quoteEdit(as(body)));
|
|
196
|
+
film("render-edit", "cut your clips, voice and captions into one vertical video (paid); --output saves it", filmEditInput, (sdk, body) => sdk.quoteEdit(as(body)), (sdk, body, attempt) => sdk.renderEdit(as(body), { attempt }), filmFile);
|
|
197
|
+
bodyCommand(program, registry, "create-cut", "create a cut record: the brief and the slots of the shot plan (free)", createCutInput, (sdk, body) => sdk.createCut(as(body)));
|
|
198
|
+
readCommand(program, registry, "get-cut", "read a cut record with its voice, takes, previews, renders and next call (free)", (sdk, id) => sdk.getCut(id));
|
|
199
|
+
bodyCommand(program, registry, "update-cut", "replace a cut record's brief, slots or both (free)", updateCutInput, (sdk, body, id) => sdk.updateCut(id, as(body)), true);
|
|
200
|
+
bodyCommand(program, registry, "check-cut", "check a cut sheet against your voice, pictures and takes; starts nothing (free)", filmCutInput, (sdk, body) => sdk.checkCut(as(body)));
|
|
201
|
+
quoteCommand(program, registry, "quote-cut", "price rendering a checked cut sheet, line by line", filmCutRunInput, (sdk, body) => sdk.quoteCut(as(body)));
|
|
202
|
+
film("render-cut", "render a checked cut sheet to one vertical video with its sound (paid); --output saves it", filmCutRunInput, (sdk, body) => sdk.quoteCut(as(body)), (sdk, body, attempt) => sdk.renderCut(as(body), { attempt }), filmFile);
|
|
203
|
+
quoteCommand(program, registry, "quote-cut-preview", "price stills of a cut sheet and how many are free", filmCutPreviewInput, (sdk, body) => sdk.quotePreviewCut(as(body)));
|
|
204
|
+
film("preview-cut", "draw stills of a cut sheet as the video shows them (free up to the daily allowance of stills, then paid)", filmCutPreviewInput, (sdk, body) => sdk.quotePreviewCut(as(body)), (sdk, body, attempt) => sdk.previewCut(as(body), { attempt }));
|
|
205
|
+
quoteCommand(program, registry, "quote-take-check", "price checking a clip against its prompt", takeCheckInput, (sdk, body) => sdk.quoteTakeCheck(as(body)));
|
|
206
|
+
film("check-take", "check a clip against its prompt and list defects with their seconds (paid)", takeCheckInput, (sdk, body) => sdk.quoteTakeCheck(as(body)), (sdk, body, attempt) => sdk.checkTake(as(body), { attempt }));
|
|
207
|
+
film("take-frames", "draw a clip's frames on contact sheets, each labelled with its second (free)", takeFramesInput, (sdk, body) => sdk.quoteTakeFrames(as(body)), (sdk, body, attempt) => sdk.takeFrames(as(body), { attempt }));
|
|
208
|
+
bodyCommand(program, registry, "create-film-draft", "create a film draft for your own scene code (free)", createFilmDraftInput, (sdk, body) => sdk.createFilmDraft(as(body)));
|
|
209
|
+
readCommand(program, registry, "get-film-draft", "read a film draft (free)", (sdk, id) => sdk.getFilmDraft(id));
|
|
210
|
+
bodyCommand(program, registry, "put-film-files", "change a draft's files, anchors, sounds or captions on the revision you read (free)", putFilmFilesInput, (sdk, body, id) => sdk.putFilmFiles(id, as(body)), true);
|
|
211
|
+
bodyCommand(program, registry, "check-film", "check a draft revision on a delivered voice before stills or a render (free)", checkFilmInput, (sdk, body, id) => sdk.checkFilm(id, as(body)), true);
|
|
212
|
+
quoteCommand(program, registry, "quote-render", "price rendering a film draft", filmRenderInput, (sdk, body) => sdk.quoteRender(as(body)));
|
|
213
|
+
film("render-film", "render a film draft on its voice (paid); --output saves it", filmRenderInput, (sdk, body) => sdk.quoteRender(as(body)), (sdk, body, attempt) => sdk.renderFilm(as(body), { attempt }), filmFile);
|
|
214
|
+
readCommand(program, registry, "get-film-run", "read a voice, edit, cut, film, check or frames run and what it delivered (free)", (sdk, id) => sdk.getFilmRun(id), { kind: "film", fileOf: filmFile });
|
|
215
|
+
bodyCommand(program, registry, "get-film-kit", "list the scene kit's files, or read one with --set path=<file> (free)", filmKitQuery, (sdk, body) => sdk.getFilmKit(as(body)));
|
|
216
|
+
bodyCommand(program, registry, "get-film-guide", "read the film guide, or one format or section of it (free)", filmGuideQuery, (sdk, body) => sdk.getFilmGuide(as(body)));
|
|
217
|
+
bodyCommand(program, registry, "get-ad-guide", "read the ad guide's index, or one section with --set section=<name> (free)", adGuideQuery, (sdk, body) => sdk.getAdGuide(as(body)));
|
|
218
|
+
withPayloadOptions(program.command("create-asset").description("save an asset from a generation, an upload or a url, or from a local file " +
|
|
219
|
+
"with --from-file (free)"))
|
|
220
|
+
.option("--from-file <path>", "a local PNG, JPEG, MP4, MOV or WebM file instead of --file/--set")
|
|
221
|
+
.addOption(new Option("--role <role>", "with --from-file: what the asset is").choices(ASSET_ROLES))
|
|
222
|
+
.option("--name <text>", "with --from-file: the asset's name")
|
|
223
|
+
.addOption(new Option("--rights-confirmed", "with --from-file: you may use the people and works in it").conflicts("analysisOnly"))
|
|
224
|
+
.option("--analysis-only", "with --from-file: keep it for reference analysis only")
|
|
225
|
+
.action(async (opts) => {
|
|
226
|
+
if (opts.fromFile === undefined) {
|
|
227
|
+
print(await registry.client().createAsset(as(buildPayload(opts))));
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (opts.role === undefined || opts.name === undefined || (opts.rightsConfirmed !== true && opts.analysisOnly !== true)) {
|
|
231
|
+
fail({ code: "missing_input", message: "--from-file needs --role, --name and one of --rights-confirmed or --analysis-only. Nothing was sent.",
|
|
232
|
+
fix: ["Add --role, --name and --rights-confirmed (or --analysis-only for a reel kept only for analysis)."] });
|
|
233
|
+
}
|
|
234
|
+
let bytes;
|
|
235
|
+
try {
|
|
236
|
+
bytes = new Uint8Array(readFileSync(opts.fromFile));
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
fail({ code: "file_unreadable", message: `${opts.fromFile} cannot be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
240
|
+
fix: ["Pass --from-file a readable PNG, JPEG, MP4, MOV or WebM file."] });
|
|
241
|
+
}
|
|
242
|
+
const mediaType = sniffAsset(bytes);
|
|
243
|
+
if (mediaType === undefined) {
|
|
244
|
+
fail({ code: "invalid_value", message: `${opts.fromFile} is not a PNG, JPEG, MP4, MOV or WebM file (checked by its first bytes)`,
|
|
245
|
+
fix: ["Pass a PNG, JPEG, MP4, MOV or WebM file."] });
|
|
246
|
+
}
|
|
247
|
+
if (bytes.byteLength > ASSET_BYTES_ROUTE_VIDEO_MAX_BYTES) {
|
|
248
|
+
fail({ code: "invalid_value", message: `${opts.fromFile} is ${bytes.byteLength} bytes; --from-file sends at most ` +
|
|
249
|
+
`${ASSET_BYTES_ROUTE_VIDEO_MAX_BYTES}. Nothing was sent.`,
|
|
250
|
+
fix: ["For a larger clip, run clipwright create-asset with source.put set to its media_type, bytes and sha256 " +
|
|
251
|
+
"(clipwright template create-asset shows the fields), PUT the file to the link it returns, then read it with clipwright get-asset."] });
|
|
252
|
+
}
|
|
253
|
+
const meta = opts.analysisOnly === true ? { role: opts.role, name: opts.name, analysis_only: true }
|
|
254
|
+
: { role: opts.role, name: opts.name, rights_confirmed: true };
|
|
255
|
+
print(await registry.client().createAssetFromBytes(bytes, mediaType, meta));
|
|
256
|
+
});
|
|
257
|
+
templates.set("create-asset", createAssetRequest);
|
|
258
|
+
bodyCommand(program, registry, "list-assets", "list the account's assets, newest first, with its usage of the caps (free)", assetListQuery, (sdk, body) => sdk.listAssets(as(body)));
|
|
259
|
+
readCommand(program, registry, "get-asset", "read one asset with a fresh link, or its pending state (free)", (sdk, id) => sdk.getAsset(id));
|
|
260
|
+
deleteCommand(program, registry, "delete-asset", "the asset", (sdk, id) => sdk.deleteAsset(id));
|
|
261
|
+
bodyCommand(program, registry, "create-upload", "get a signed PUT for a local file of the declared type, size and sha256 (free)", uploadIntentRequest, (sdk, body) => sdk.createUpload(as(body)));
|
|
262
|
+
readCommand(program, registry, "get-upload", "read one upload with a fresh link; after a PUT it also confirms it (free)", (sdk, id) => sdk.getUpload(id));
|
|
263
|
+
deleteCommand(program, registry, "delete-upload", "the upload", (sdk, id) => sdk.deleteUpload(id));
|
|
264
|
+
deleteCommand(program, registry, "delete-run-media", "the files of the finished run", (sdk, id) => sdk.deleteRunMedia(id));
|
|
265
|
+
program.command("template <command>")
|
|
266
|
+
.description("print the request a command takes: its JSON Schema and a request to fill in, with the fields still to fill (free, offline)")
|
|
267
|
+
.action((name) => {
|
|
268
|
+
const schema = templates.get(name);
|
|
269
|
+
if (schema === undefined) {
|
|
270
|
+
fail({ code: "unknown_command", message: `${name} takes no request file`,
|
|
271
|
+
choices: { flag: "<command>", values: [...templates.keys()].sort() },
|
|
272
|
+
fix: [`Pass one of the commands that take --file: ${[...templates.keys()].sort().join(", ")}.`] });
|
|
273
|
+
}
|
|
274
|
+
print(templateOf(name, schema));
|
|
275
|
+
});
|
|
276
|
+
}
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { PUBLIC_APP_BASE_URL, rateLimitedError } from "@clipwright/core";
|
|
2
|
+
import { ClipwrightApiError, ClipwrightResponseError } from "@clipwright/sdk";
|
|
3
|
+
import { formatApiError, formatSchemaError } from "./format.js";
|
|
4
|
+
export function outputMode() {
|
|
5
|
+
const forced = process.env.CLIPWRIGHT_OUTPUT?.trim().toLowerCase();
|
|
6
|
+
if (forced === "json" || forced === "text")
|
|
7
|
+
return forced;
|
|
8
|
+
return process.stdout.isTTY === true && process.stderr.isTTY === true ? "text" : "json";
|
|
9
|
+
}
|
|
10
|
+
export const shellWord = (word) => (/^[\w@%+=:,./-]+$/.test(word) || /^<[\w .-]+>$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`);
|
|
11
|
+
export const commandLine = (words) => ["clipwright", ...words].map(shellWord).join(" ");
|
|
12
|
+
const KEY_TOKEN = /cw_[A-Za-z0-9_-]{8,}/g;
|
|
13
|
+
export function scrubKeys(text) {
|
|
14
|
+
const key = process.env.CLIPWRIGHT_API_KEY;
|
|
15
|
+
const withoutKey = key !== undefined && key.length >= 8 ? text.replaceAll(key, "cw_…") : text;
|
|
16
|
+
return withoutKey.replace(KEY_TOKEN, "cw_…");
|
|
17
|
+
}
|
|
18
|
+
const scrubDeep = (value) => typeof value === "string" ? scrubKeys(value)
|
|
19
|
+
: Array.isArray(value) ? value.map(scrubDeep)
|
|
20
|
+
: value !== null && typeof value === "object"
|
|
21
|
+
? Object.fromEntries(Object.entries(value).map(([field, inner]) => [field, scrubDeep(inner)])) : value;
|
|
22
|
+
export function note(line) {
|
|
23
|
+
console.error(outputMode() === "json" ? JSON.stringify({ note: scrubKeys(line) }) : scrubKeys(line));
|
|
24
|
+
}
|
|
25
|
+
export function warn(text) {
|
|
26
|
+
console.error(outputMode() === "json" ? JSON.stringify({ warning: scrubKeys(text) }) : `warning: ${scrubKeys(text)}`);
|
|
27
|
+
}
|
|
28
|
+
export function emitFailure(failure, prose = [failure.message]) {
|
|
29
|
+
if (outputMode() === "json") {
|
|
30
|
+
console.error(JSON.stringify({ ok: false, error: scrubDeep(failure) }));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
for (const line of prose)
|
|
34
|
+
console.error(scrubKeys(line));
|
|
35
|
+
}
|
|
36
|
+
export function fail(failure, prose) {
|
|
37
|
+
const full = { retryable: false, fix: [failure.message], ...failure };
|
|
38
|
+
if (full.fix.length === 0)
|
|
39
|
+
full.fix = [full.message];
|
|
40
|
+
emitFailure(full, prose ?? [full.message]);
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
43
|
+
export function commanderFailure(error) {
|
|
44
|
+
const message = error.message.replace(/^error: /, "");
|
|
45
|
+
const flag = /option '(--?[A-Za-z][\w-]*)/.exec(message)?.[1] ?? /'(--?[A-Za-z][\w-]*)'/.exec(message)?.[1];
|
|
46
|
+
const allowed = /Allowed choices are (.+)\.$/.exec(message)?.[1];
|
|
47
|
+
const codes = {
|
|
48
|
+
"commander.unknownOption": "unknown_option",
|
|
49
|
+
"commander.unknownCommand": "unknown_command",
|
|
50
|
+
"commander.missingArgument": "missing_argument",
|
|
51
|
+
"commander.optionMissingArgument": "missing_argument",
|
|
52
|
+
"commander.missingMandatoryOptionValue": "missing_option",
|
|
53
|
+
"commander.conflictingOption": "conflicting_options",
|
|
54
|
+
"commander.excessArguments": "unexpected_argument",
|
|
55
|
+
"commander.invalidArgument": allowed === undefined ? "invalid_value" : "invalid_choice",
|
|
56
|
+
};
|
|
57
|
+
if (error.code === "commander.help") {
|
|
58
|
+
return { code: "missing_command", message: "no command given", retryable: false,
|
|
59
|
+
fix: ["Run clipwright --help for the commands, or clipwright guided --goal <text> to pick one from a goal."] };
|
|
60
|
+
}
|
|
61
|
+
const code = codes[error.code] ?? "invalid_usage";
|
|
62
|
+
const quoted = /'([^']+)'/.exec(message)?.[1];
|
|
63
|
+
const fix = allowed !== undefined && flag !== undefined
|
|
64
|
+
? [`Pass ${flag} one of: ${allowed}.`]
|
|
65
|
+
: code === "unknown_option" || code === "unknown_command" || code === "unexpected_argument"
|
|
66
|
+
? ["Run the command with --help for what it takes; this CLI refuses anything it does not know."]
|
|
67
|
+
: error.code === "commander.missingArgument" && quoted !== undefined
|
|
68
|
+
? [`Pass <${quoted}> after the command.`, "Run the command with --help for its arguments."]
|
|
69
|
+
: (code === "missing_option" || code === "missing_argument") && quoted !== undefined
|
|
70
|
+
? [`Pass ${quoted}.`, "Run the command with --help for its flags."]
|
|
71
|
+
: [`${message.charAt(0).toUpperCase()}${message.slice(1)}`, "Run the command with --help for its flags."];
|
|
72
|
+
return {
|
|
73
|
+
code, message, retryable: false, fix,
|
|
74
|
+
...(allowed !== undefined && flag !== undefined && { choices: { flag, values: allowed.split(", ") } }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export const commandOf = (tool) => tool.replaceAll("_", "-");
|
|
78
|
+
function apiFix(report, next) {
|
|
79
|
+
if (report.code === "unauthorized") {
|
|
80
|
+
return [`Create a key at ${PUBLIC_APP_BASE_URL}/api-keys and export it: export CLIPWRIGHT_API_KEY=cw_...`,
|
|
81
|
+
"Then run clipwright account, which is free, to confirm the key works."];
|
|
82
|
+
}
|
|
83
|
+
if (report.code === rateLimitedError.shape.error.shape.code.value) {
|
|
84
|
+
const wait = report.retry_after_seconds === undefined ? "a few seconds" : `${report.retry_after_seconds} seconds`;
|
|
85
|
+
return [`Wait ${wait}, then run the same command again unchanged.`];
|
|
86
|
+
}
|
|
87
|
+
if (report.code === "max_credits_exceeded" && report.hold_credits !== undefined) {
|
|
88
|
+
return [`This call reserves ${report.hold_credits} credits, above --max-credits ${report.max_credits ?? 0}.`,
|
|
89
|
+
`Show the user the quote; with their go-ahead, run the same command with --max-credits ${report.hold_credits}.`];
|
|
90
|
+
}
|
|
91
|
+
if (next !== undefined) {
|
|
92
|
+
const where = "command" in next ? `run ${next.command} --file <that file>` : `send ${next.method} ${next.path} with it`;
|
|
93
|
+
return [report.next_action,
|
|
94
|
+
`Write error.next.body to a file${next.add.length > 0 ? `, set ${next.add.join(", ")} in it` : ""}, then ${where}.`];
|
|
95
|
+
}
|
|
96
|
+
return [report.next_action];
|
|
97
|
+
}
|
|
98
|
+
export function apiFailure(error, commands) {
|
|
99
|
+
const report = error.report();
|
|
100
|
+
const { status: _status, code, message, retryable, next_action, retry_after_seconds, issues, warnings, next: serverNext, ...details } = report;
|
|
101
|
+
const next = serverNext === undefined ? undefined
|
|
102
|
+
: commands.has(commandOf(serverNext.action))
|
|
103
|
+
? { command: `clipwright ${commandOf(serverNext.action)}`, body: serverNext.body, add: serverNext.add }
|
|
104
|
+
: { method: serverNext.method, path: serverNext.path, body: serverNext.body, add: serverNext.add };
|
|
105
|
+
return {
|
|
106
|
+
code, message: clip(message), retryable, fix: apiFix(report, next), http_status: error.status, next_action,
|
|
107
|
+
...(retry_after_seconds !== undefined && { retry_after_seconds }),
|
|
108
|
+
...(next !== undefined && { next }),
|
|
109
|
+
...(issues !== undefined && { issues }),
|
|
110
|
+
...(warnings !== undefined && { warnings }),
|
|
111
|
+
...(Object.keys(details).length > 0 && { details }),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
const MESSAGE_MAX = 500;
|
|
115
|
+
const clip = (text) => (text.length > MESSAGE_MAX ? `${text.slice(0, MESSAGE_MAX - 1)}…` : text);
|
|
116
|
+
export function unverifiedFailure(error, resume, keyed) {
|
|
117
|
+
if (!error.mayHaveTakenEffect) {
|
|
118
|
+
return { code: error.deliveryConfirmed ? "response_unverified" : "network_error", message: error.message, retryable: true,
|
|
119
|
+
fix: ["Nothing was charged and no run was created: run the same command again."] };
|
|
120
|
+
}
|
|
121
|
+
const fromStdin = process.argv.some((word, at) => word === "--file=-" || (word === "--file" && process.argv[at + 1] === "-"));
|
|
122
|
+
const fix = keyed
|
|
123
|
+
? [`Run ${resume ?? "the same command"} again unchanged: it sends the same idempotency key and returns the run it may have started instead of starting another.`,
|
|
124
|
+
...(fromStdin ? ["Pipe the same request in again, or save it to a file and pass --file <path>: a different request is a new key and a new paid run."] : []),
|
|
125
|
+
"Do not pass another --attempt: a new attempt is a new paid run."]
|
|
126
|
+
: ["The call may have gone through. For a paid one, run its quote command with the same input first: 0 means repeating it " +
|
|
127
|
+
"costs nothing (a trend search of the same query within 24 hours returns the earlier one); any other price means ask the user before repeating.",
|
|
128
|
+
"For a free one, read what it made before repeating it."];
|
|
129
|
+
return { code: "response_unverified", message: error.message, retryable: keyed, fix, ...(keyed && resume !== undefined && { resume }) };
|
|
130
|
+
}
|
|
131
|
+
export function failureOf(error, commands) {
|
|
132
|
+
if (error instanceof ClipwrightApiError)
|
|
133
|
+
return { failure: apiFailure(error, commands), prose: [formatApiError(error)] };
|
|
134
|
+
if (error instanceof ClipwrightResponseError) {
|
|
135
|
+
return { failure: unverifiedFailure(error, undefined, false), prose: [`error: ${error.message}`] };
|
|
136
|
+
}
|
|
137
|
+
const schema = formatSchemaError(error);
|
|
138
|
+
if (schema !== undefined) {
|
|
139
|
+
const issues = error.issues
|
|
140
|
+
.map((issue) => ({ path: Array.isArray(issue.path) ? issue.path.join(".") : "", message: issue.message ?? "invalid" }));
|
|
141
|
+
return {
|
|
142
|
+
failure: { code: "schema_rejected", message: "the request was rejected before it was sent", retryable: false, issues,
|
|
143
|
+
fix: issues.map((issue) => `Fix ${issue.path || "the input"}: ${issue.message}`) },
|
|
144
|
+
prose: [schema],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
if (outputMode() === "text") {
|
|
148
|
+
if (error instanceof Error) {
|
|
149
|
+
error.message = scrubKeys(error.message);
|
|
150
|
+
if (error.stack !== undefined)
|
|
151
|
+
error.stack = scrubKeys(error.stack);
|
|
152
|
+
}
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const cause = error instanceof Error && error.cause instanceof Error ? `: ${error.cause.message}` : "";
|
|
156
|
+
const message = scrubKeys(`${error instanceof Error ? error.message : String(error)}${cause}`);
|
|
157
|
+
const network = error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError" ||
|
|
158
|
+
(error.name === "TypeError" && /fetch failed/i.test(message)));
|
|
159
|
+
return network
|
|
160
|
+
? { failure: { code: "network_error", message, retryable: true, fix: ["Check the network and the API address, then run the same command again."] }, prose: [] }
|
|
161
|
+
: { failure: { code: "internal_error", message, retryable: false, fix: ["Run clipwright feedback --kind wrong with the command and this message."] }, prose: [] };
|
|
162
|
+
}
|
package/dist/payload.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { fail } from "./output.js";
|
|
3
|
+
const collect = (value, previous = []) => [...previous, value];
|
|
4
|
+
export function withPayloadOptions(command) {
|
|
5
|
+
return command
|
|
6
|
+
.option("--file <path>", "the request as a JSON file, as clipwright template <command> prints it; - reads it from stdin")
|
|
7
|
+
.option("--set <field=value>", "set one field over --file: a.b=text is a string, a.b:=<json> is JSON (a number, true, a list); " +
|
|
8
|
+
"a number segment is a list index; repeat it for more fields", collect);
|
|
9
|
+
}
|
|
10
|
+
const FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
|
|
11
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12
|
+
function readJson(path) {
|
|
13
|
+
let text;
|
|
14
|
+
try {
|
|
15
|
+
text = readFileSync(path === "-" ? 0 : path, "utf8");
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
fail({ code: "file_unreadable", message: `${path} cannot be read: ${error instanceof Error ? error.message : String(error)}. Nothing was sent.`,
|
|
19
|
+
fix: ["Pass --file a readable JSON file, or - to read the request from stdin."] });
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(text);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
fail({ code: "file_unreadable", message: `${path} is not JSON. Nothing was sent.`,
|
|
26
|
+
fix: ["Fix the JSON in the file; clipwright template <command> prints a request to start from."] });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function parseSet(raw) {
|
|
30
|
+
const at = raw.indexOf("=");
|
|
31
|
+
const json = at > 0 && raw[at - 1] === ":";
|
|
32
|
+
const key = at < 0 ? "" : raw.slice(0, json ? at - 1 : at);
|
|
33
|
+
const usage = { code: "invalid_value", fix: ["Write --set field=text for a string or --set field:=<json> for any other value, e.g. --set duration_s:=5."] };
|
|
34
|
+
if (key === "" || key.split(".").some((segment) => segment === "")) {
|
|
35
|
+
fail({ ...usage, message: `--set expects field=value, got ${JSON.stringify(raw)}` });
|
|
36
|
+
}
|
|
37
|
+
const segments = key.split(".");
|
|
38
|
+
const forbidden = segments.find((segment) => FORBIDDEN_SEGMENTS.has(segment));
|
|
39
|
+
if (forbidden !== undefined)
|
|
40
|
+
fail({ ...usage, message: `--set cannot name the field ${forbidden}` });
|
|
41
|
+
const text = raw.slice(at + 1);
|
|
42
|
+
let value = text;
|
|
43
|
+
if (json) {
|
|
44
|
+
try {
|
|
45
|
+
value = JSON.parse(text);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
fail({ ...usage, message: `--set ${key}:= expects JSON after :=, got ${JSON.stringify(text)}` });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { path: segments.map((segment) => (/^(0|[1-9]\d*)$/.test(segment) ? Number(segment) : segment)), value };
|
|
52
|
+
}
|
|
53
|
+
function setAt(target, path, value, shown) {
|
|
54
|
+
let node = target;
|
|
55
|
+
for (const [index, segment] of path.entries()) {
|
|
56
|
+
const last = index === path.length - 1;
|
|
57
|
+
if (typeof segment === "number" && !Array.isArray(node)) {
|
|
58
|
+
fail({ code: "invalid_value", message: `--set ${shown}: ${path.slice(0, index).join(".") || "the request"} is not a list`,
|
|
59
|
+
fix: ["Use a number segment only inside a list."] });
|
|
60
|
+
}
|
|
61
|
+
const container = node;
|
|
62
|
+
if (last) {
|
|
63
|
+
container[segment] = value;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const nextIsIndex = typeof path[index + 1] === "number";
|
|
67
|
+
const existing = container[segment];
|
|
68
|
+
if (existing === undefined) {
|
|
69
|
+
container[segment] = nextIsIndex ? [] : {};
|
|
70
|
+
}
|
|
71
|
+
else if (!(Array.isArray(existing) || isRecord(existing))) {
|
|
72
|
+
fail({ code: "invalid_value", message: `--set ${shown}: ${path.slice(0, index + 1).join(".")} already holds a value that is not an object`,
|
|
73
|
+
fix: ["Set the field itself, or remove it from --file first."] });
|
|
74
|
+
}
|
|
75
|
+
node = container[segment];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export function buildPayload(opts) {
|
|
79
|
+
const loaded = opts.file === undefined ? {} : readJson(opts.file);
|
|
80
|
+
if (!isRecord(loaded)) {
|
|
81
|
+
fail({ code: "file_unreadable", message: `${opts.file ?? "--file"} must hold a JSON object. Nothing was sent.`,
|
|
82
|
+
fix: ["Put the request in a JSON object; clipwright template <command> prints one."] });
|
|
83
|
+
}
|
|
84
|
+
for (const raw of opts.set ?? []) {
|
|
85
|
+
const { path, value } = parseSet(raw);
|
|
86
|
+
setAt(loaded, path, value, raw);
|
|
87
|
+
}
|
|
88
|
+
return loaded;
|
|
89
|
+
}
|
|
90
|
+
function starter(schema) {
|
|
91
|
+
if ("const" in schema)
|
|
92
|
+
return schema.const;
|
|
93
|
+
if ("default" in schema)
|
|
94
|
+
return schema.default;
|
|
95
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0)
|
|
96
|
+
return schema.enum[0];
|
|
97
|
+
const branches = (schema.anyOf ?? schema.oneOf ?? schema.allOf);
|
|
98
|
+
if (Array.isArray(branches))
|
|
99
|
+
return starter(branches.find((branch) => branch.type !== "null") ?? branches[0]);
|
|
100
|
+
switch (schema.type) {
|
|
101
|
+
case "object": return objectStarter(schema);
|
|
102
|
+
case "array": return [];
|
|
103
|
+
case "string": return "";
|
|
104
|
+
case "number":
|
|
105
|
+
case "integer": return typeof schema.minimum === "number" ? schema.minimum : 0;
|
|
106
|
+
case "boolean": return false;
|
|
107
|
+
default: return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function objectStarter(schema) {
|
|
111
|
+
const properties = (schema.properties ?? {});
|
|
112
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
113
|
+
return Object.fromEntries(required.filter((key) => key in properties).map((key) => [key, starter(properties[key])]));
|
|
114
|
+
}
|
|
115
|
+
export function templateOf(command, schema, example = {}) {
|
|
116
|
+
const json = schema.toJSONSchema({ io: "input", unrepresentable: "any" });
|
|
117
|
+
const payload = { ...objectStarter(json), ...example };
|
|
118
|
+
const fill = schema.safeParse(payload).error?.issues.map((issue) => issue.path.map(String).join(".") || "(request)") ?? [];
|
|
119
|
+
return { command, schema: json, payload, fill: [...new Set(fill)] };
|
|
120
|
+
}
|
package/dist/retry.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ClipwrightApiError, ClipwrightResponseError } from "@clipwright/sdk";
|
|
2
|
+
import { note } from "./output.js";
|
|
3
|
+
export const START_RESENDS = 2;
|
|
4
|
+
export const START_RESEND_MAX_PAUSE_S = 30;
|
|
5
|
+
const RESEND_PAUSES_MS = [2_000, 5_000];
|
|
6
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
+
function resendPauseMs(error, resend) {
|
|
8
|
+
const base = RESEND_PAUSES_MS[Math.min(resend, RESEND_PAUSES_MS.length - 1)];
|
|
9
|
+
if (error instanceof ClipwrightResponseError)
|
|
10
|
+
return error.mayHaveTakenEffect && !error.deliveryConfirmed ? base : undefined;
|
|
11
|
+
if (!(error instanceof ClipwrightApiError) || !error.retryable)
|
|
12
|
+
return undefined;
|
|
13
|
+
const seconds = error.retryAfterSeconds;
|
|
14
|
+
if (seconds !== undefined && seconds > START_RESEND_MAX_PAUSE_S)
|
|
15
|
+
return undefined;
|
|
16
|
+
return Math.max(base, (seconds ?? 0) * 1000);
|
|
17
|
+
}
|
|
18
|
+
export async function startWithResend(start, wait = pause) {
|
|
19
|
+
for (let resend = 0;; resend += 1) {
|
|
20
|
+
try {
|
|
21
|
+
return await start();
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
const ms = resend < START_RESENDS ? resendPauseMs(error, resend) : undefined;
|
|
25
|
+
if (ms === undefined)
|
|
26
|
+
throw error;
|
|
27
|
+
const seconds = Math.round(ms / 1000);
|
|
28
|
+
note(error instanceof ClipwrightResponseError
|
|
29
|
+
? `no answer to the start yet; sending it again with the same idempotency key in ${seconds} s`
|
|
30
|
+
: `the server asked to try again; sending the start again with the same idempotency key in ${seconds} s`);
|
|
31
|
+
await wait(ms);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|