@firstdraft.com/cli 0.8.2 → 0.10.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.
@@ -0,0 +1,513 @@
1
+ import {
2
+ FirstDraftNetworkError,
3
+ FirstDraftProtocolError,
4
+ isProblemBody,
5
+ problemProjection,
6
+ readResponseBytes,
7
+ } from "./api-response.js";
8
+ import { VERSION } from "./version.js";
9
+
10
+ /** The public page with the update steps for each setup. */
11
+ export const UPDATE_URL = "https://firstdraft.com/update";
12
+
13
+ /**
14
+ * The Service API contracts this CLI accepts. release/compatibility.json
15
+ * declares the same range for the release check, and
16
+ * test/release-compatibility.test.js keeps the two equal.
17
+ */
18
+ export const API_CONTRACT_RANGE = Object.freeze([">= 0.9.0", "< 0.10.0"]);
19
+
20
+ /** Set by the plugin's launcher; docs/commands.md names them for wrappers. */
21
+ export const PLUGIN_VERSION_VARIABLE = "FIRSTDRAFT_PLUGIN_VERSION";
22
+ export const AGENT_VARIABLE = "FIRSTDRAFT_AGENT";
23
+
24
+ // SemVer 2.0.0, as test/release-compatibility.test.js validates it. Build
25
+ // metadata after `+` is kept in the text but has no precedence.
26
+ const SEMVER =
27
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
28
+ const AGENT_NAME = /^[a-z0-9][a-z0-9._-]{0,39}$/;
29
+ const PLATFORM = /^[a-z0-9]{1,32}$/;
30
+ const MAX_LIMIT_PROBLEM_BYTES = 64 * 1024;
31
+ // The Service ignores the whole header, or keeps no client facts with a
32
+ // report, when one value is longer.
33
+ const MAX_FACT_LENGTH = 40;
34
+
35
+ /**
36
+ * A response told the CLI to stop. The CLI finishes handling that response
37
+ * and sends nothing after it. When the stop cut the command short, this
38
+ * replaces the command's result, and `replaced` holds the error it replaced.
39
+ */
40
+ export class ServiceStopError extends Error {
41
+ /** @type {unknown} */
42
+ replaced = undefined;
43
+ }
44
+
45
+ export class UpdateRequiredError extends ServiceStopError {
46
+ /** @param {{component: "plugin" | "cli", installed: string, minimum: string}} options */
47
+ constructor({ component, installed, minimum }) {
48
+ super("First Draft requires a newer plugin or CLI.");
49
+ this.component = component;
50
+ this.installed = installed;
51
+ this.minimum = minimum;
52
+ }
53
+ }
54
+
55
+ export class ApiContractUnsupportedError extends ServiceStopError {
56
+ /** @param {{origin: string, contract: string, kind: "newer" | "older" | "prerelease"}} options */
57
+ constructor({ origin, contract, kind }) {
58
+ super("First Draft serves an API contract this CLI does not accept.");
59
+ this.origin = origin;
60
+ this.contract = contract;
61
+ this.kind = kind;
62
+ }
63
+ }
64
+
65
+ export class RateLimitedError extends ServiceStopError {
66
+ /** @param {{retryAt: string | undefined, response: Record<string, unknown> | null}} options */
67
+ constructor({ retryAt, response }) {
68
+ super("First Draft refused a request because of an account limit.");
69
+ this.status = 429;
70
+ this.retryAt = retryAt;
71
+ this.response = response;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * @typedef {object} ServiceSession
77
+ * @property {string} clientHeader the FirstDraft-Client value sent on every request
78
+ * @property {string | null} pluginVersion the plugin's version from
79
+ * FIRSTDRAFT_PLUGIN_VERSION, or null when that is unset or not a version
80
+ * @property {(request?: typeof globalThis.fetch) => typeof globalThis.fetch} fetch
81
+ * Wraps a fetch function so every request carries FirstDraft-Client and
82
+ * every response is checked.
83
+ * @property {<T>(work: Promise<T>) => Promise<T>} settle
84
+ * Awaits a command's work. When a response told the CLI to stop and the
85
+ * stop cut the work short (a later request was not sent) or was a 429,
86
+ * rejects with that ServiceStopError. Otherwise the work finished on its
87
+ * own terms: settle writes one line that names the stop and resolves or
88
+ * rejects as the work did, so its result or recovery data is kept. Either
89
+ * way it then writes the command's one version line, if any.
90
+ * @property {() => void} throwIfStopped
91
+ * Throws the recorded stop as the next request would, so a command that
92
+ * prints what it is about to send can stop before printing it.
93
+ * @property {() => void} flush
94
+ * Writes the version line for a command that does not settle its work.
95
+ */
96
+
97
+ /**
98
+ * One session per command invocation, so the update line is printed at most
99
+ * once however many requests the command makes.
100
+ *
101
+ * @param {object} options
102
+ * @param {Readonly<Record<string, string | undefined>>} options.env
103
+ * @param {(line: string) => void} options.notify writes one line to stderr
104
+ * @param {string} [options.platform]
105
+ * @param {() => number} [options.now]
106
+ * @returns {ServiceSession}
107
+ */
108
+ export function createServiceSession({
109
+ env,
110
+ notify,
111
+ platform = process.platform,
112
+ now = Date.now,
113
+ }) {
114
+ const plugin = semver(env[PLUGIN_VERSION_VARIABLE]);
115
+ const agent = env[AGENT_VARIABLE]?.toLowerCase();
116
+ // The Service parses this grammar and ignores a header that breaks it, so
117
+ // build metadata, which has no precedence, is not sent.
118
+ const clientHeader = [
119
+ `cli/${VERSION}`,
120
+ ...(plugin === null || plugin.release.length > MAX_FACT_LENGTH
121
+ ? []
122
+ : [`plugin/${plugin.release}`]),
123
+ ...(agent !== undefined && AGENT_NAME.test(agent)
124
+ ? [`agent/${agent}`]
125
+ : []),
126
+ ...(PLATFORM.test(platform) ? [`os/${platform}`] : []),
127
+ ].join("; ");
128
+ // A plugin is compared with the plugin versions First Draft names; a CLI
129
+ // run without one, such as a direct npm installation, with the CLI
130
+ // versions. The two packages are numbered separately.
131
+ // A plugin version that is set, even blank, but unreadable says a plugin is
132
+ // present without saying which, so neither pair is compared, and the
133
+ // command's one version line says why.
134
+ const pluginSet = env[PLUGIN_VERSION_VARIABLE] !== undefined;
135
+ /** @type {{component: "plugin" | "cli", label: string, version: Version, latestHeader: string, minimumHeader: string} | null} */
136
+ const installed =
137
+ pluginSet && plugin === null
138
+ ? null
139
+ : plugin === null
140
+ ? {
141
+ component: "cli",
142
+ label: "CLI",
143
+ version: /** @type {Version} */ (semver(VERSION)),
144
+ latestHeader: "firstdraft-latest-cli",
145
+ minimumHeader: "firstdraft-minimum-cli",
146
+ }
147
+ : {
148
+ component: "plugin",
149
+ label: "plugin",
150
+ version: plugin,
151
+ latestHeader: "firstdraft-latest-plugin",
152
+ minimumHeader: "firstdraft-minimum-plugin",
153
+ };
154
+ /** @type {ServiceStopError | null} */
155
+ let stop = null;
156
+ let blocked = false;
157
+ /** @type {string | null} */
158
+ let updateLine = null;
159
+ let flushed = false;
160
+
161
+ /**
162
+ * @param {string} origin
163
+ * @param {Response} response
164
+ * @returns {Promise<Response>} the response, rebuilt when its body was read
165
+ */
166
+ async function observe(origin, response) {
167
+ // A pair is compared only when both of its versions are readable.
168
+ const pair =
169
+ installed === null
170
+ ? null
171
+ : versionPair(
172
+ response,
173
+ installed.latestHeader,
174
+ installed.minimumHeader,
175
+ );
176
+ if (
177
+ installed !== null &&
178
+ updateLine === null &&
179
+ pair !== null &&
180
+ compareVersions(installed.version, pair.latest) < 0
181
+ ) {
182
+ updateLine =
183
+ `First Draft: an update is available (${installed.label} ${pair.latest.text}; this setup has ` +
184
+ `${installed.label} ${installed.version.text}). ` +
185
+ `Tell the person the update steps are at ${UPDATE_URL}\n`;
186
+ }
187
+ if (
188
+ installed === null &&
189
+ updateLine === null &&
190
+ versionPair(
191
+ response,
192
+ "firstdraft-latest-plugin",
193
+ "firstdraft-minimum-plugin",
194
+ ) !== null
195
+ ) {
196
+ updateLine =
197
+ `First Draft: ${PLUGIN_VERSION_VARIABLE} is set but is not a plugin version, so the CLI could not ` +
198
+ `tell whether this setup is current. The update steps are at ${UPDATE_URL}\n`;
199
+ }
200
+
201
+ // A 429 refused the request, whatever else the response says.
202
+ if (response.status === 429) {
203
+ // The body is read here rather than through a clone: a tee holds a
204
+ // cancelled branch until the other branch is read, so an oversized
205
+ // body would stall. The command gets the same bytes back.
206
+ const { body, problem } = await readLimitProblem(response);
207
+ stop = new RateLimitedError({
208
+ retryAt: retryTime(response.headers.get("retry-after"), now),
209
+ response: problem,
210
+ });
211
+ return new Response(body, {
212
+ status: response.status,
213
+ statusText: response.statusText,
214
+ headers: response.headers,
215
+ });
216
+ }
217
+
218
+ const contract = semver(response.headers.get("firstdraft-api-contract"));
219
+ if (contract !== null && !acceptsContract(contract)) {
220
+ stop = new ApiContractUnsupportedError({
221
+ origin,
222
+ contract: contract.text,
223
+ kind: contractKind(contract),
224
+ });
225
+ return response;
226
+ }
227
+
228
+ if (
229
+ installed !== null &&
230
+ pair !== null &&
231
+ compareVersions(installed.version, pair.minimum) < 0
232
+ ) {
233
+ stop = new UpdateRequiredError({
234
+ component: installed.component,
235
+ installed: installed.version.text,
236
+ minimum: pair.minimum.text,
237
+ });
238
+ return response;
239
+ }
240
+
241
+ return response;
242
+ }
243
+
244
+ /**
245
+ * Writes the one version line for this command: the stop when a response
246
+ * required an update the command survived, else the update notice.
247
+ *
248
+ * @param {{versionStopReported: boolean}} options
249
+ */
250
+ function flush({ versionStopReported }) {
251
+ if (flushed) return;
252
+ flushed = true;
253
+ if (stop !== null && !(stop instanceof RateLimitedError)) {
254
+ if (!versionStopReported) {
255
+ notify(
256
+ `First Draft: ${stopSentence(stop)} This command finished; ${stopAction(stop)} before the next one.\n`,
257
+ );
258
+ }
259
+ return;
260
+ }
261
+ if (updateLine !== null) notify(updateLine);
262
+ }
263
+
264
+ function throwIfStopped() {
265
+ if (stop !== null) {
266
+ blocked = true;
267
+ throw stop;
268
+ }
269
+ }
270
+
271
+ return {
272
+ clientHeader,
273
+ pluginVersion: plugin === null ? null : plugin.text,
274
+ fetch(request = globalThis.fetch) {
275
+ /** @type {typeof globalThis.fetch} */
276
+ const serviceFetch = async (input, init) => {
277
+ throwIfStopped();
278
+
279
+ const response = await request(input, {
280
+ ...init,
281
+ headers: { ...init?.headers, "FirstDraft-Client": clientHeader },
282
+ });
283
+ const url = new URL(input instanceof Request ? input.url : input);
284
+ return observe(url.origin, response);
285
+ };
286
+ return serviceFetch;
287
+ },
288
+ async settle(work) {
289
+ let value;
290
+ try {
291
+ value = await work;
292
+ } catch (error) {
293
+ if (stop !== null && (blocked || stop instanceof RateLimitedError)) {
294
+ stop.replaced = error;
295
+ flush({ versionStopReported: true });
296
+ throw stop;
297
+ }
298
+ flush({ versionStopReported: false });
299
+ throw error;
300
+ }
301
+ // A 429 refused the request, so a result built from it is a refusal.
302
+ if (stop instanceof RateLimitedError) {
303
+ flush({ versionStopReported: true });
304
+ throw stop;
305
+ }
306
+ flush({ versionStopReported: false });
307
+ return value;
308
+ },
309
+ throwIfStopped,
310
+ flush() {
311
+ flush({ versionStopReported: false });
312
+ },
313
+ };
314
+ }
315
+
316
+ /**
317
+ * Both versions of a latest-and-minimum pair, or null unless both are
318
+ * readable.
319
+ *
320
+ * @param {Response} response
321
+ * @param {string} latestHeader
322
+ * @param {string} minimumHeader
323
+ */
324
+ function versionPair(response, latestHeader, minimumHeader) {
325
+ const latest = semver(response.headers.get(latestHeader));
326
+ const minimum = semver(response.headers.get(minimumHeader));
327
+ return latest === null || minimum === null ? null : { latest, minimum };
328
+ }
329
+
330
+ /**
331
+ * @param {Version} contract
332
+ * @returns {"newer" | "older" | "prerelease"}
333
+ */
334
+ function contractKind(contract) {
335
+ if (compareVersions(contract, API_CONTRACT_FLOOR) < 0) return "older";
336
+ return acceptsContract({ ...contract, prerelease: [] })
337
+ ? "prerelease"
338
+ : "newer";
339
+ }
340
+
341
+ /** @param {ServiceStopError} stop */
342
+ export function stopAction(stop) {
343
+ return stop instanceof ApiContractUnsupportedError && stop.kind !== "newer"
344
+ ? "use the CLI version that this First Draft origin supports"
345
+ : `tell the person to update with the steps at ${UPDATE_URL}`;
346
+ }
347
+
348
+ /** @typedef {{major: number, minor: number, patch: number, prerelease: string[], text: string, release: string}} Version */
349
+
350
+ /**
351
+ * @param {string | null | undefined} value
352
+ * @returns {Version | null}
353
+ */
354
+ function semver(value) {
355
+ const match = typeof value === "string" ? SEMVER.exec(value.trim()) : null;
356
+ if (match === null) return null;
357
+
358
+ return {
359
+ major: Number(match[1]),
360
+ minor: Number(match[2]),
361
+ patch: Number(match[3]),
362
+ prerelease: match[4] === undefined ? [] : match[4].split("."),
363
+ text: match[0],
364
+ release: match[0].replace(/\+.*$/, ""),
365
+ };
366
+ }
367
+
368
+ /**
369
+ * SemVer 2.0.0 precedence: a prerelease sorts before its release, numeric
370
+ * identifiers compare numerically and before alphanumeric ones.
371
+ *
372
+ * @param {Version} left
373
+ * @param {Version} right
374
+ */
375
+ export function compareVersions(left, right) {
376
+ const core =
377
+ left.major - right.major ||
378
+ left.minor - right.minor ||
379
+ left.patch - right.patch;
380
+ if (core !== 0) return Math.sign(core);
381
+ if (left.prerelease.length === 0 || right.prerelease.length === 0) {
382
+ return Math.sign(right.prerelease.length - left.prerelease.length);
383
+ }
384
+
385
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
386
+ for (let index = 0; index < length; index += 1) {
387
+ const a = left.prerelease[index];
388
+ const b = right.prerelease[index];
389
+ if (a === undefined) return -1;
390
+ if (b === undefined) return 1;
391
+ if (a === b) continue;
392
+
393
+ const aNumeric = /^\d+$/.test(a);
394
+ const bNumeric = /^\d+$/.test(b);
395
+ if (aNumeric && bNumeric) return Math.sign(Number(a) - Number(b));
396
+ if (aNumeric) return -1;
397
+ if (bNumeric) return 1;
398
+ return a < b ? -1 : 1;
399
+ }
400
+ return 0;
401
+ }
402
+
403
+ const COMPARATOR_SIGNS = new Map([
404
+ ["=", [0]],
405
+ ["<", [-1]],
406
+ ["<=", [-1, 0]],
407
+ [">", [1]],
408
+ [">=", [0, 1]],
409
+ ]);
410
+
411
+ const API_CONTRACT_COMPARATORS = API_CONTRACT_RANGE.map((requirement) => {
412
+ const [operator, bound] = requirement.split(/\s+/);
413
+ const signs = COMPARATOR_SIGNS.get(operator ?? "");
414
+ const version = semver(bound);
415
+ if (signs === undefined || version === null) {
416
+ throw new TypeError(`Invalid API contract requirement: ${requirement}`);
417
+ }
418
+ return { signs, version };
419
+ });
420
+
421
+ const API_CONTRACT_FLOOR = /** @type {Version} */ (
422
+ API_CONTRACT_COMPARATORS.find(({ signs }) => signs.includes(1))?.version
423
+ );
424
+
425
+ /**
426
+ * As in npm ranges, a prerelease contract is outside a range whose bounds
427
+ * name none, so `0.10.0-rc.1` is refused like `0.10.0`.
428
+ *
429
+ * @param {Version} contract
430
+ */
431
+ function acceptsContract(contract) {
432
+ return (
433
+ contract.prerelease.length === 0 &&
434
+ API_CONTRACT_COMPARATORS.every(({ signs, version }) =>
435
+ signs.includes(compareVersions(contract, version)),
436
+ )
437
+ );
438
+ }
439
+
440
+ /**
441
+ * The sentence that names a stop, shared by the stop line and the handled
442
+ * errors in src/cli.js.
443
+ *
444
+ * @param {ServiceStopError} stop
445
+ */
446
+ export function stopSentence(stop) {
447
+ if (stop instanceof UpdateRequiredError) {
448
+ const label = stop.component === "plugin" ? "plugin" : "CLI";
449
+ return `First Draft requires ${label} ${stop.minimum} or later, and this setup has ${label} ${stop.installed}.`;
450
+ }
451
+ if (stop instanceof ApiContractUnsupportedError) {
452
+ return stop.kind === "prerelease"
453
+ ? `First Draft at ${stop.origin} serves prerelease API contract ${stop.contract}, which CLI ${VERSION} does not accept.`
454
+ : `First Draft at ${stop.origin} serves API contract ${stop.contract}, which is ${stop.kind} than CLI ${VERSION} accepts.`;
455
+ }
456
+ return "First Draft refused a request because a limit was reached.";
457
+ }
458
+
459
+ /**
460
+ * RFC 9110 Retry-After: delay-seconds or an HTTP-date. Returns a UTC time to
461
+ * the second, or undefined when the header is absent or unreadable.
462
+ *
463
+ * @param {string | null} value
464
+ * @param {() => number} now
465
+ */
466
+ function retryTime(value, now) {
467
+ if (value === null) return undefined;
468
+
469
+ const trimmed = value.trim();
470
+ const milliseconds = /^\d{1,10}$/.test(trimmed)
471
+ ? now() + Number(trimmed) * 1000
472
+ : /[A-Za-z]/.test(trimmed)
473
+ ? Date.parse(trimmed)
474
+ : Number.NaN;
475
+ if (!Number.isFinite(milliseconds)) return undefined;
476
+
477
+ return new Date(Math.ceil(milliseconds / 1000) * 1000)
478
+ .toISOString()
479
+ .replace(/\.\d{3}Z$/, "Z");
480
+ }
481
+
482
+ /** @param {Response} response */
483
+ async function readLimitProblem(response) {
484
+ let bytes;
485
+ try {
486
+ bytes = await readResponseBytes(response, MAX_LIMIT_PROBLEM_BYTES);
487
+ } catch (error) {
488
+ // The limit still applies when its explanation cannot be read.
489
+ if (
490
+ error instanceof FirstDraftNetworkError ||
491
+ error instanceof FirstDraftProtocolError
492
+ ) {
493
+ return { body: null, problem: null };
494
+ }
495
+ throw error;
496
+ }
497
+
498
+ const body = parseJson(bytes);
499
+ return {
500
+ body: bytes,
501
+ problem: isProblemBody(response, body) ? problemProjection(body) : null,
502
+ };
503
+ }
504
+
505
+ /** @param {Buffer} bytes */
506
+ function parseJson(bytes) {
507
+ try {
508
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
509
+ } catch (error) {
510
+ if (error instanceof SyntaxError || error instanceof TypeError) return null;
511
+ throw error;
512
+ }
513
+ }