@firstdraft.com/cli 0.9.0 → 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,662 @@
1
+ import {
2
+ FirstDraftNetworkError,
3
+ FirstDraftProtocolError,
4
+ SERVICE_ROUTES,
5
+ isProblemBody,
6
+ readResponseBody,
7
+ responseMediaType,
8
+ sendRequest,
9
+ serviceEndpoint,
10
+ } from "../api-response.js";
11
+ import { readPinnedOrApplicationProject } from "../plan-state.js";
12
+
13
+ const REQUEST_TIMEOUT_MS = 30_000;
14
+ export const DEFAULT_ENVIRONMENT = "production";
15
+ export const RESOLUTION_REASONS = Object.freeze([
16
+ "pull_request",
17
+ "host_change",
18
+ "not_a_bug",
19
+ "duplicate",
20
+ "stopped_occurring",
21
+ ]);
22
+ // What caused the error: code First Draft generated, code written since,
23
+ // configuration or the host, data, a dependency, nothing wrong, or unknown
24
+ // when the agent looked and could not tell.
25
+ export const RESOLUTION_CAUSES = Object.freeze([
26
+ "generated_code",
27
+ "later_code",
28
+ "configuration_or_host",
29
+ "data",
30
+ "dependency",
31
+ "not_a_bug",
32
+ "unknown",
33
+ ]);
34
+ // The Service's Project::Environment::NAME_PATTERN. Checking it locally also
35
+ // keeps a name from adding path segments to the request URL.
36
+ const ENVIRONMENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,62}$/;
37
+ // Item IDs are UUIDs of any version, unlike the UUIDv7 Project IDs.
38
+ const ITEM_ID_PATTERN =
39
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40
+ // The Service's Project::Environment::Item::GITHUB_ISSUE_URL.
41
+ const GITHUB_ISSUE_URL_PATTERN =
42
+ /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}\/issues\/[1-9][0-9]{0,9}$/;
43
+ const KINDS = new Set(["agent_fixable"]);
44
+ const SEVERITIES = new Set(["fatal", "error", "warning", "info", "debug"]);
45
+ const ENVIRONMENT_KEYS = ["project_id", "name"];
46
+ const INDEX_KEYS = ["environment", "items", "next_page"];
47
+ const ITEM_RESPONSE_KEYS = ["environment", "item"];
48
+ const SUMMARY_KEYS = [
49
+ "id",
50
+ "kind",
51
+ "severity",
52
+ "title",
53
+ "occurrences",
54
+ "first_seen_at",
55
+ "last_seen_at",
56
+ "last_release",
57
+ "status",
58
+ "resolution_reason",
59
+ "resolution_cause",
60
+ "issue_url",
61
+ ];
62
+ const DETAIL_KEYS = [...SUMMARY_KEYS, "evidence", "done_when"];
63
+ const DEFERRAL_KEYS = ["id", "deferred_until"];
64
+ const OWNER_QUESTION_KEYS = ["id", "owner_asked_at"];
65
+ const EVIDENCE_KEYS = [
66
+ "occurred_at",
67
+ "release",
68
+ "exceptions",
69
+ "request",
70
+ "untrusted",
71
+ "note",
72
+ ];
73
+ const EXCEPTION_KEYS = ["type", "message", "frames"];
74
+ const FRAME_KEYS = ["file", "line", "function"];
75
+ const REQUEST_KEYS = ["method", "host", "path"];
76
+ const TIMESTAMP_PATTERN =
77
+ /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
78
+
79
+ export class MaintainRejectedError extends Error {
80
+ /**
81
+ * @param {number} status
82
+ * @param {Record<string, unknown>} response
83
+ */
84
+ constructor(status, response) {
85
+ super("First Draft rejected the maintenance request.");
86
+ this.status = status;
87
+ this.response = response;
88
+ }
89
+ }
90
+
91
+ export class MaintainUnavailableError extends Error {
92
+ /**
93
+ * @param {number | undefined} status
94
+ * @param {Record<string, unknown> | null} [response]
95
+ */
96
+ constructor(status, response = null) {
97
+ super("The maintenance request could not be completed.");
98
+ this.status = status;
99
+ this.response = response;
100
+ }
101
+ }
102
+
103
+ export class MaintainResponseInvalidError extends Error {
104
+ /** @param {number} status */
105
+ constructor(status) {
106
+ super("The maintenance response is invalid.");
107
+ this.status = status;
108
+ }
109
+ }
110
+
111
+ /** @param {unknown} value @returns {value is string} */
112
+ export function isEnvironmentName(value) {
113
+ return typeof value === "string" && ENVIRONMENT_NAME_PATTERN.test(value);
114
+ }
115
+
116
+ /** @param {unknown} value @returns {value is string} */
117
+ export function isItemId(value) {
118
+ return typeof value === "string" && ITEM_ID_PATTERN.test(value);
119
+ }
120
+
121
+ /** @param {unknown} value @returns {value is string} */
122
+ export function isResolutionReason(value) {
123
+ return (
124
+ typeof value === "string" &&
125
+ /** @type {readonly string[]} */ (RESOLUTION_REASONS).includes(value)
126
+ );
127
+ }
128
+
129
+ /** @param {unknown} value @returns {value is string} */
130
+ export function isResolutionCause(value) {
131
+ return (
132
+ typeof value === "string" &&
133
+ /** @type {readonly string[]} */ (RESOLUTION_CAUSES).includes(value)
134
+ );
135
+ }
136
+
137
+ /**
138
+ * The Project and origin every maintain request uses, read once per command:
139
+ * the Project's state, in `cwd` or in an adopted application's archive at
140
+ * .firstdraft/design, or else the Project the application's own
141
+ * .firstdraft/gaps.json names, at the origin `login` would select.
142
+ *
143
+ * @param {{cwd: string, fileSystem?: import("../plan-state.js").PlanStateFileSystem, selectOrigin: () => string}} options
144
+ * @returns {MaintainContext}
145
+ */
146
+ export function readMaintainContext({ cwd, fileSystem, selectOrigin }) {
147
+ const { apiUrl, projectId, fromApplication } = readPinnedOrApplicationProject(
148
+ { cwd, fileSystem, selectOrigin },
149
+ );
150
+ return { apiUrl, projectId, fromApplication };
151
+ }
152
+
153
+ /**
154
+ * @typedef {object} MaintainContext
155
+ * @property {string} apiUrl
156
+ * @property {string} projectId
157
+ * @property {boolean} fromApplication true when the Project came from the
158
+ * application's files, so the origin is not pinned
159
+ */
160
+
161
+ /**
162
+ * @typedef {object} MaintainRequestOptions
163
+ * @property {MaintainContext} context
164
+ * @property {string} environment
165
+ * @property {typeof globalThis.fetch} [fetchFunction]
166
+ * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
167
+ */
168
+
169
+ /**
170
+ * Read one page of an Environment's open items, most severe first.
171
+ *
172
+ * @param {MaintainRequestOptions & {page: number}} options
173
+ */
174
+ export async function listMaintenanceItems({
175
+ context,
176
+ environment,
177
+ page,
178
+ fetchFunction = globalThis.fetch,
179
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
180
+ }) {
181
+ const { apiUrl, projectId } = context;
182
+ const endpoint = serviceEndpoint(
183
+ SERVICE_ROUTES.listMaintenanceItems,
184
+ apiUrl,
185
+ {
186
+ project_id: projectId,
187
+ environment_name: environment,
188
+ },
189
+ );
190
+ endpoint.url.searchParams.set("page", String(page));
191
+ const { status, body } = await request(fetchFunction, endpoint, {
192
+ createRequestSignal,
193
+ });
194
+
195
+ if (
196
+ !hasExactKeys(body, INDEX_KEYS) ||
197
+ !isEnvironment(body.environment, projectId, environment) ||
198
+ !Array.isArray(body.items) ||
199
+ !body.items.every((item) => isSummary(item) && item.status === "open") ||
200
+ !(
201
+ body.next_page === null ||
202
+ (Number.isSafeInteger(body.next_page) && Number(body.next_page) > page)
203
+ )
204
+ ) {
205
+ throw new MaintainResponseInvalidError(status);
206
+ }
207
+
208
+ return {
209
+ environment: copyEnvironment(body.environment),
210
+ items: body.items.map(copySummary),
211
+ next_page: body.next_page,
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Read one item with its latest evidence and what done means.
217
+ *
218
+ * @param {MaintainRequestOptions & {itemId: string}} options
219
+ */
220
+ export async function showMaintenanceItem({
221
+ context,
222
+ environment,
223
+ itemId,
224
+ fetchFunction = globalThis.fetch,
225
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
226
+ }) {
227
+ const { apiUrl, projectId } = context;
228
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.readMaintenanceItem, apiUrl, {
229
+ project_id: projectId,
230
+ environment_name: environment,
231
+ item_id: itemId,
232
+ });
233
+ const { status, body } = await request(fetchFunction, endpoint, {
234
+ createRequestSignal,
235
+ });
236
+ const item = isRecord(body) ? body.item : null;
237
+
238
+ if (
239
+ !hasExactKeys(body, ITEM_RESPONSE_KEYS) ||
240
+ !isEnvironment(body.environment, projectId, environment) ||
241
+ !hasExactKeys(item, DETAIL_KEYS) ||
242
+ !isSummary(pick(item, SUMMARY_KEYS)) ||
243
+ item.id !== itemId ||
244
+ !(item.evidence === null || isEvidence(item.evidence)) ||
245
+ typeof item.done_when !== "string"
246
+ ) {
247
+ throw new MaintainResponseInvalidError(status);
248
+ }
249
+
250
+ return {
251
+ environment: copyEnvironment(body.environment),
252
+ item: {
253
+ ...copySummary(item),
254
+ evidence: item.evidence === null ? null : copyEvidence(item.evidence),
255
+ done_when: item.done_when,
256
+ },
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Resolve one open item. The Service refuses to resolve an item that is still
262
+ * resolved, but a recurrence reopens it, so an unconfirmed outcome must be
263
+ * checked with `maintain show` before resolving again.
264
+ *
265
+ * @param {MaintainRequestOptions & {itemId: string, reason: string, cause: string, detail?: string}} options
266
+ */
267
+ export async function resolveMaintenanceItem({
268
+ context,
269
+ environment,
270
+ itemId,
271
+ reason,
272
+ cause,
273
+ detail,
274
+ fetchFunction = globalThis.fetch,
275
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
276
+ }) {
277
+ const { apiUrl, projectId } = context;
278
+ const endpoint = serviceEndpoint(
279
+ SERVICE_ROUTES.resolveMaintenanceItem,
280
+ apiUrl,
281
+ {
282
+ project_id: projectId,
283
+ environment_name: environment,
284
+ item_id: itemId,
285
+ },
286
+ );
287
+ const { status, body } = await request(fetchFunction, endpoint, {
288
+ createRequestSignal,
289
+ json: { reason, cause, ...(detail === undefined ? {} : { detail }) },
290
+ });
291
+ const item = isRecord(body) ? body.item : null;
292
+
293
+ if (
294
+ !hasExactKeys(body, ITEM_RESPONSE_KEYS) ||
295
+ !isEnvironment(body.environment, projectId, environment) ||
296
+ !isSummary(item) ||
297
+ item.id !== itemId ||
298
+ item.status !== "resolved" ||
299
+ item.resolution_reason !== reason ||
300
+ item.resolution_cause !== cause
301
+ ) {
302
+ throw new MaintainResponseInvalidError(status);
303
+ }
304
+
305
+ return {
306
+ environment: copyEnvironment(body.environment),
307
+ item: copySummary(item),
308
+ };
309
+ }
310
+
311
+ /**
312
+ * Set one open item aside until a time, which First Draft accepts only within
313
+ * the next 90 days. Until then the index leaves the item out and escalation
314
+ * passes it over.
315
+ *
316
+ * @param {MaintainRequestOptions & {itemId: string, until: string}} options
317
+ */
318
+ export async function deferMaintenanceItem({
319
+ context,
320
+ environment,
321
+ itemId,
322
+ until,
323
+ fetchFunction = globalThis.fetch,
324
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
325
+ }) {
326
+ const { apiUrl, projectId } = context;
327
+ const endpoint = serviceEndpoint(
328
+ SERVICE_ROUTES.deferMaintenanceItem,
329
+ apiUrl,
330
+ {
331
+ project_id: projectId,
332
+ environment_name: environment,
333
+ item_id: itemId,
334
+ },
335
+ );
336
+ const { status, body } = await request(fetchFunction, endpoint, {
337
+ createRequestSignal,
338
+ json: { until },
339
+ });
340
+ const item = isRecord(body) ? body.item : null;
341
+
342
+ // First Draft writes the time back without fractional seconds.
343
+ if (
344
+ !hasExactKeys(body, ITEM_RESPONSE_KEYS) ||
345
+ !isEnvironment(body.environment, projectId, environment) ||
346
+ !hasExactKeys(item, DEFERRAL_KEYS) ||
347
+ item.id !== itemId ||
348
+ !isTimestamp(item.deferred_until) ||
349
+ wholeSeconds(item.deferred_until) !== wholeSeconds(until)
350
+ ) {
351
+ throw new MaintainResponseInvalidError(status);
352
+ }
353
+
354
+ return {
355
+ environment: copyEnvironment(body.environment),
356
+ item: pick(item, DEFERRAL_KEYS),
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Record a question for the owner on one open item; a later question replaces
362
+ * it. Whether the index shows the item does not change.
363
+ *
364
+ * @param {MaintainRequestOptions & {itemId: string, question: string}} options
365
+ */
366
+ export async function askMaintenanceOwner({
367
+ context,
368
+ environment,
369
+ itemId,
370
+ question,
371
+ fetchFunction = globalThis.fetch,
372
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
373
+ }) {
374
+ const { apiUrl, projectId } = context;
375
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.askMaintenanceOwner, apiUrl, {
376
+ project_id: projectId,
377
+ environment_name: environment,
378
+ item_id: itemId,
379
+ });
380
+ const { status, body } = await request(fetchFunction, endpoint, {
381
+ createRequestSignal,
382
+ json: { question },
383
+ });
384
+ const item = isRecord(body) ? body.item : null;
385
+
386
+ if (
387
+ !hasExactKeys(body, ITEM_RESPONSE_KEYS) ||
388
+ !isEnvironment(body.environment, projectId, environment) ||
389
+ !hasExactKeys(item, OWNER_QUESTION_KEYS) ||
390
+ item.id !== itemId ||
391
+ !isTimestamp(item.owner_asked_at)
392
+ ) {
393
+ throw new MaintainResponseInvalidError(status);
394
+ }
395
+
396
+ return {
397
+ environment: copyEnvironment(body.environment),
398
+ item: pick(item, OWNER_QUESTION_KEYS),
399
+ };
400
+ }
401
+
402
+ /**
403
+ * @param {typeof globalThis.fetch} fetchFunction
404
+ * @param {import("../api-response.js").ServiceEndpoint} endpoint
405
+ * @param {{createRequestSignal: (timeoutMs: number) => AbortSignal, json?: Record<string, string>}} options
406
+ */
407
+ async function request(fetchFunction, endpoint, { createRequestSignal, json }) {
408
+ let response;
409
+ let body;
410
+ try {
411
+ response = await sendRequest(fetchFunction, endpoint, {
412
+ headers: {
413
+ Accept: "application/json, application/problem+json",
414
+ ...(json === undefined ? {} : { "Content-Type": "application/json" }),
415
+ },
416
+ ...(json === undefined ? {} : { body: JSON.stringify(json) }),
417
+ redirect: "error",
418
+ signal: createRequestSignal(REQUEST_TIMEOUT_MS),
419
+ });
420
+ body = await readResponseBody(response);
421
+ } catch (error) {
422
+ if (error instanceof FirstDraftNetworkError) {
423
+ throw new MaintainUnavailableError(error.status);
424
+ }
425
+ // Only an oversized success breaks the contract; an oversized error body
426
+ // is as unconfirmed as any other failed response.
427
+ if (error instanceof FirstDraftProtocolError) {
428
+ throw error.status >= 200 && error.status < 300
429
+ ? new MaintainResponseInvalidError(error.status)
430
+ : new MaintainUnavailableError(error.status);
431
+ }
432
+
433
+ throw error;
434
+ }
435
+
436
+ if (response.status !== 200) {
437
+ if (response.ok) throw new MaintainResponseInvalidError(response.status);
438
+
439
+ const problem = safeProblem(response, body);
440
+ if (problem !== null && response.status !== 408 && response.status < 500) {
441
+ throw new MaintainRejectedError(response.status, problem);
442
+ }
443
+ throw new MaintainUnavailableError(response.status, problem);
444
+ }
445
+
446
+ if (responseMediaType(response) !== "application/json") {
447
+ throw new MaintainResponseInvalidError(response.status);
448
+ }
449
+
450
+ return { status: response.status, body };
451
+ }
452
+
453
+ /**
454
+ * @param {unknown} value
455
+ * @param {string} projectId
456
+ * @param {string} name
457
+ * @returns {value is Record<string, unknown>}
458
+ */
459
+ function isEnvironment(value, projectId, name) {
460
+ return (
461
+ hasExactKeys(value, ENVIRONMENT_KEYS) &&
462
+ value.project_id === projectId &&
463
+ value.name === name
464
+ );
465
+ }
466
+
467
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
468
+ function isSummary(value) {
469
+ if (!hasExactKeys(value, SUMMARY_KEYS)) return false;
470
+
471
+ return (
472
+ isItemId(value.id) &&
473
+ typeof value.kind === "string" &&
474
+ KINDS.has(value.kind) &&
475
+ typeof value.severity === "string" &&
476
+ SEVERITIES.has(value.severity) &&
477
+ typeof value.title === "string" &&
478
+ Number.isSafeInteger(value.occurrences) &&
479
+ Number(value.occurrences) >= 0 &&
480
+ isTimestamp(value.first_seen_at) &&
481
+ isTimestamp(value.last_seen_at) &&
482
+ isNullableString(value.last_release) &&
483
+ (value.issue_url === null ||
484
+ (typeof value.issue_url === "string" &&
485
+ GITHUB_ISSUE_URL_PATTERN.test(value.issue_url))) &&
486
+ ((value.status === "open" &&
487
+ value.resolution_reason === null &&
488
+ value.resolution_cause === null) ||
489
+ (value.status === "resolved" &&
490
+ isResolutionReason(value.resolution_reason) &&
491
+ isResolutionCause(value.resolution_cause)))
492
+ );
493
+ }
494
+
495
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
496
+ function isEvidence(value) {
497
+ return (
498
+ hasExactKeys(value, EVIDENCE_KEYS) &&
499
+ (value.occurred_at === null || isTimestamp(value.occurred_at)) &&
500
+ isNullableString(value.release) &&
501
+ Array.isArray(value.exceptions) &&
502
+ value.exceptions.every(isException) &&
503
+ (value.request === null || isRequest(value.request)) &&
504
+ Array.isArray(value.untrusted) &&
505
+ value.untrusted.every((field) => typeof field === "string") &&
506
+ typeof value.note === "string"
507
+ );
508
+ }
509
+
510
+ /** @param {unknown} value */
511
+ function isException(value) {
512
+ return (
513
+ hasExactKeys(value, EXCEPTION_KEYS) &&
514
+ isNullableString(value.type) &&
515
+ typeof value.message === "string" &&
516
+ Array.isArray(value.frames) &&
517
+ value.frames.every(isFrame)
518
+ );
519
+ }
520
+
521
+ /** @param {unknown} value */
522
+ function isFrame(value) {
523
+ return (
524
+ hasExactKeys(value, FRAME_KEYS) &&
525
+ isNullableString(value.file) &&
526
+ (value.line === null || Number.isSafeInteger(value.line)) &&
527
+ isNullableString(value.function)
528
+ );
529
+ }
530
+
531
+ /** @param {unknown} value */
532
+ function isRequest(value) {
533
+ return (
534
+ hasExactKeys(value, REQUEST_KEYS) &&
535
+ isNullableString(value.method) &&
536
+ isNullableString(value.host) &&
537
+ isNullableString(value.path)
538
+ );
539
+ }
540
+
541
+ /** @param {Record<string, unknown>} environment */
542
+ function copyEnvironment(environment) {
543
+ return { project_id: environment.project_id, name: environment.name };
544
+ }
545
+
546
+ /** @param {Record<string, unknown>} item */
547
+ function copySummary(item) {
548
+ return pick(item, SUMMARY_KEYS);
549
+ }
550
+
551
+ /** @param {Record<string, unknown>} evidence */
552
+ function copyEvidence(evidence) {
553
+ const exceptions = /** @type {Record<string, unknown>[]} */ (
554
+ evidence.exceptions
555
+ );
556
+ const request = /** @type {Record<string, unknown> | null} */ (
557
+ evidence.request
558
+ );
559
+ return {
560
+ occurred_at: evidence.occurred_at,
561
+ release: evidence.release,
562
+ exceptions: exceptions.map((exception) => ({
563
+ type: exception.type,
564
+ message: exception.message,
565
+ frames: /** @type {Record<string, unknown>[]} */ (exception.frames).map(
566
+ (frame) => pick(frame, FRAME_KEYS),
567
+ ),
568
+ })),
569
+ request: request === null ? null : pick(request, REQUEST_KEYS),
570
+ untrusted: [.../** @type {string[]} */ (evidence.untrusted)],
571
+ note: evidence.note,
572
+ };
573
+ }
574
+
575
+ /** @param {Response} response @param {unknown} body */
576
+ function safeProblem(response, body) {
577
+ if (!isRecord(body) || !isProblemBody(response, body)) return null;
578
+
579
+ return {
580
+ ...(body.type === "about:blank" ? { type: body.type } : {}),
581
+ title: body.title,
582
+ status: body.status,
583
+ code: body.code,
584
+ detail: body.detail,
585
+ };
586
+ }
587
+
588
+ /**
589
+ * An ISO 8601 date and time with its offset, the form of every time in a
590
+ * maintenance response and of a deferral's `--until`.
591
+ *
592
+ * @param {unknown} value
593
+ * @returns {value is string}
594
+ */
595
+ export function isTimestamp(value) {
596
+ if (typeof value !== "string") return false;
597
+
598
+ const match = TIMESTAMP_PATTERN.exec(value);
599
+ if (!match) return false;
600
+
601
+ const [year, month, day, hour, minute, second] = match
602
+ .slice(1, 7)
603
+ .map(Number);
604
+ const offsetHour = match[7] === undefined ? 0 : Number(match[7]);
605
+ const offsetMinute = match[8] === undefined ? 0 : Number(match[8]);
606
+ return (
607
+ year !== undefined &&
608
+ month !== undefined &&
609
+ day !== undefined &&
610
+ month >= 1 &&
611
+ month <= 12 &&
612
+ day >= 1 &&
613
+ day <= daysInMonth(year, month) &&
614
+ Number(hour) <= 23 &&
615
+ Number(minute) <= 59 &&
616
+ Number(second) <= 59 &&
617
+ offsetHour <= 23 &&
618
+ offsetMinute <= 59
619
+ );
620
+ }
621
+
622
+ /** @param {string} timestamp a value isTimestamp accepts */
623
+ function wholeSeconds(timestamp) {
624
+ return Math.floor(Date.parse(timestamp) / 1000);
625
+ }
626
+
627
+ /** @param {number} year @param {number} month */
628
+ function daysInMonth(year, month) {
629
+ if (month === 2) {
630
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
631
+ }
632
+
633
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
634
+ }
635
+
636
+ /** @param {unknown} value */
637
+ function isNullableString(value) {
638
+ return value === null || typeof value === "string";
639
+ }
640
+
641
+ /** @param {Record<string, unknown>} value @param {string[]} keys */
642
+ function pick(value, keys) {
643
+ return Object.fromEntries(keys.map((key) => [key, value[key]]));
644
+ }
645
+
646
+ /**
647
+ * @param {unknown} value
648
+ * @param {string[]} keys
649
+ * @returns {value is Record<string, unknown>}
650
+ */
651
+ function hasExactKeys(value, keys) {
652
+ return (
653
+ isRecord(value) &&
654
+ Object.keys(value).length === keys.length &&
655
+ keys.every((key) => Object.prototype.hasOwnProperty.call(value, key))
656
+ );
657
+ }
658
+
659
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
660
+ function isRecord(value) {
661
+ return typeof value === "object" && value !== null && !Array.isArray(value);
662
+ }