@firstdraft.com/cli 0.1.0-alpha.2

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,302 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstatSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import {
6
+ FirstDraftProtocolError,
7
+ isDiagnostic,
8
+ isProblemBody,
9
+ readResponseBody,
10
+ responseMediaType,
11
+ sendRequest,
12
+ } from "../api-response.js";
13
+ import { isFileSystemError } from "../file-system.js";
14
+ import {
15
+ MAX_STATE_BYTES,
16
+ PlanStateConfigurationError,
17
+ isStrongEtag,
18
+ normalizeApiUrl,
19
+ readLocalFile,
20
+ readPlanState,
21
+ } from "../plan-state.js";
22
+
23
+ export {
24
+ PlanStateConfigurationError as PlanPushConfigurationError,
25
+ PlanStateLocalError as PlanPushLocalError,
26
+ normalizeApiUrl,
27
+ } from "../plan-state.js";
28
+ export {
29
+ FirstDraftNetworkError as PlanPushNetworkError,
30
+ FirstDraftProtocolError as PlanPushProtocolError,
31
+ } from "../api-response.js";
32
+
33
+ export const DEFAULT_API_URL = "https://firstdraft.com";
34
+
35
+ const FOUNDATION_PLAN_MEDIA_TYPE =
36
+ "application/vnd.firstdraft.foundation-plan+json";
37
+ const MAX_PLAN_BYTES = 1024 * 1024;
38
+ const REQUEST_TIMEOUT_MS = 30_000;
39
+
40
+ /**
41
+ * @typedef {object} PlanPushFileSystem
42
+ * @property {typeof lstatSync} lstatSync
43
+ * @property {typeof readFileSync} readFileSync
44
+ * @property {typeof renameSync} renameSync
45
+ * @property {typeof writeFileSync} writeFileSync
46
+ */
47
+
48
+ /** @type {PlanPushFileSystem} */
49
+ const DEFAULT_FILE_SYSTEM = {
50
+ lstatSync,
51
+ readFileSync,
52
+ renameSync,
53
+ writeFileSync,
54
+ };
55
+
56
+ export class PlanPushStateWriteError extends Error {
57
+ /**
58
+ * @param {{format: string, project_id: string, api_url: string, foundation_plan_etag: string}} recoveryState
59
+ * @param {{cause: Error}} options
60
+ */
61
+ constructor(recoveryState, options) {
62
+ super("The Foundation Plan was accepted, but local state was not saved.", {
63
+ cause: options.cause,
64
+ });
65
+ this.recoveryState = recoveryState;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @typedef {object} PushPlanOptions
71
+ * @property {string} cwd
72
+ * @property {string} [apiUrl]
73
+ * @property {typeof globalThis.fetch} [fetchFunction]
74
+ * @property {PlanPushFileSystem} [fileSystem]
75
+ * @property {() => string} [createTemporaryId]
76
+ * @property {() => AbortSignal} [createRequestSignal]
77
+ */
78
+
79
+ /**
80
+ * @typedef {object} PushPlanResult
81
+ * @property {number} status
82
+ * @property {string} etag
83
+ * @property {"created" | "updated"} outcome
84
+ * @property {Record<string, unknown>} body
85
+ */
86
+
87
+ /**
88
+ * @typedef {object} RejectedPushResult
89
+ * @property {number} status
90
+ * @property {"diagnostics" | "problem" | null} responseKind
91
+ * @property {Record<string, unknown> | null} body
92
+ */
93
+
94
+ /**
95
+ * @param {PushPlanOptions} options
96
+ * @returns {Promise<PushPlanResult | RejectedPushResult>}
97
+ */
98
+ export async function pushPlan({
99
+ cwd,
100
+ apiUrl,
101
+ fetchFunction = globalThis.fetch,
102
+ fileSystem = DEFAULT_FILE_SYSTEM,
103
+ createTemporaryId = randomUUID,
104
+ createRequestSignal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
105
+ }) {
106
+ const state = readPlanState({ cwd, fileSystem });
107
+ const directory = path.join(cwd, ".firstdraft");
108
+ const planPath = path.join(directory, "foundation-plan.json");
109
+ const statePath = path.join(directory, "state.json");
110
+ const planSource = readLocalFile(planPath, MAX_PLAN_BYTES, fileSystem);
111
+ const origin = resolveApiUrl(apiUrl, state.api_url);
112
+ const endpoint = new URL(
113
+ `/v1/projects/${state.project_id}/foundation-plan`,
114
+ origin,
115
+ );
116
+ const headers = {
117
+ Accept: "application/json, application/problem+json",
118
+ "Content-Type": FOUNDATION_PLAN_MEDIA_TYPE,
119
+ ...(state.foundation_plan_etag
120
+ ? { "If-Match": state.foundation_plan_etag }
121
+ : { "If-None-Match": "*" }),
122
+ };
123
+
124
+ const response = await sendRequest(fetchFunction, endpoint, {
125
+ method: "PUT",
126
+ headers,
127
+ body: planSource,
128
+ redirect: "error",
129
+ signal: createRequestSignal(),
130
+ });
131
+ const body = await readResponseBody(response);
132
+ const sourceSha256 = createHash("sha256").update(planSource).digest("hex");
133
+
134
+ if (
135
+ response.status === 422 &&
136
+ (responseMediaType(response) !== "application/json" ||
137
+ !isDiagnosticBody(body, sourceSha256))
138
+ ) {
139
+ throw new FirstDraftProtocolError(
140
+ "First Draft returned invalid diagnostics.",
141
+ { status: response.status },
142
+ );
143
+ }
144
+
145
+ if (response.status !== 200 && response.status !== 201) {
146
+ if (response.ok) {
147
+ throw new FirstDraftProtocolError(
148
+ "First Draft returned an unexpected success status.",
149
+ { status: response.status },
150
+ );
151
+ }
152
+ if (response.status === 422) {
153
+ return { status: response.status, responseKind: "diagnostics", body };
154
+ }
155
+
156
+ if (isProblemBody(response, body)) {
157
+ return { status: response.status, responseKind: "problem", body };
158
+ }
159
+
160
+ return { status: response.status, responseKind: null, body: null };
161
+ }
162
+
163
+ const etag = response.headers.get("etag");
164
+ const expectedStatus = state.foundation_plan_etag ? 200 : 201;
165
+ if (
166
+ response.status !== expectedStatus ||
167
+ responseMediaType(response) !== "application/json" ||
168
+ !isStrongEtag(etag) ||
169
+ !isAcceptedBody(body, state.project_id, sourceSha256)
170
+ ) {
171
+ throw new FirstDraftProtocolError(
172
+ "First Draft returned an invalid success response.",
173
+ { status: response.status },
174
+ );
175
+ }
176
+
177
+ saveState({
178
+ statePath,
179
+ state,
180
+ apiUrl: origin,
181
+ etag,
182
+ fileSystem,
183
+ temporaryId: createTemporaryId(),
184
+ });
185
+
186
+ return {
187
+ status: response.status,
188
+ etag,
189
+ outcome: response.status === 201 ? "created" : "updated",
190
+ body,
191
+ };
192
+ }
193
+
194
+ /** @param {string | undefined} configured @param {string | undefined} stored */
195
+ function resolveApiUrl(configured, stored) {
196
+ const configuredOrigin =
197
+ configured === undefined ? undefined : normalizeApiUrl(configured);
198
+ if (
199
+ stored !== undefined &&
200
+ configuredOrigin !== undefined &&
201
+ stored !== configuredOrigin
202
+ ) {
203
+ throw new PlanStateConfigurationError(
204
+ "The configured API URL does not match local state.",
205
+ );
206
+ }
207
+
208
+ return stored ?? configuredOrigin ?? DEFAULT_API_URL;
209
+ }
210
+
211
+ /**
212
+ * @param {object} options
213
+ * @param {string} options.statePath
214
+ * @param {{format: string, project_id: string, api_url?: string, foundation_plan_etag?: string}} options.state
215
+ * @param {string} options.apiUrl
216
+ * @param {string} options.etag
217
+ * @param {PlanPushFileSystem} options.fileSystem
218
+ * @param {string} options.temporaryId
219
+ */
220
+ function saveState({
221
+ statePath,
222
+ state,
223
+ apiUrl,
224
+ etag,
225
+ fileSystem,
226
+ temporaryId,
227
+ }) {
228
+ const recoveryState = {
229
+ format: state.format,
230
+ project_id: state.project_id,
231
+ api_url: apiUrl,
232
+ foundation_plan_etag: etag,
233
+ };
234
+ const source = `${JSON.stringify(recoveryState, null, 2)}\n`;
235
+ const temporaryPath = `${statePath}.${temporaryId}.tmp`;
236
+
237
+ if (Buffer.byteLength(source) > MAX_STATE_BYTES) {
238
+ throw new PlanPushStateWriteError(recoveryState, {
239
+ cause: new RangeError("Local First Draft state exceeds its size limit."),
240
+ });
241
+ }
242
+
243
+ try {
244
+ fileSystem.writeFileSync(temporaryPath, source, {
245
+ flag: "wx",
246
+ mode: 0o600,
247
+ flush: true,
248
+ });
249
+ fileSystem.renameSync(temporaryPath, statePath);
250
+ } catch (error) {
251
+ if (!isFileSystemError(error)) throw error;
252
+
253
+ throw new PlanPushStateWriteError(recoveryState, { cause: error });
254
+ }
255
+ }
256
+
257
+ /**
258
+ * @param {unknown} body
259
+ * @param {string} projectId
260
+ * @param {string} sourceSha256
261
+ */
262
+ function isAcceptedBody(body, projectId, sourceSha256) {
263
+ if (!isRecord(body)) return false;
264
+
265
+ const project = body.project;
266
+ const foundationPlan = body.foundation_plan;
267
+ return (
268
+ isRecord(project) &&
269
+ project.id === projectId &&
270
+ Number.isSafeInteger(project.graph_version) &&
271
+ Number(project.graph_version) >= 1 &&
272
+ isRecord(foundationPlan) &&
273
+ typeof foundationPlan.format === "string" &&
274
+ foundationPlan.source_sha256 === sourceSha256 &&
275
+ Array.isArray(body.diagnostics) &&
276
+ body.diagnostics.every(isWarningDiagnostic)
277
+ );
278
+ }
279
+
280
+ /** @param {unknown} body @param {string} sourceSha256 */
281
+ function isDiagnosticBody(body, sourceSha256) {
282
+ return (
283
+ isRecord(body) &&
284
+ body.source_sha256 === sourceSha256 &&
285
+ Array.isArray(body.diagnostics) &&
286
+ body.diagnostics.some(
287
+ (diagnostic) =>
288
+ isDiagnostic(diagnostic) && diagnostic.severity === "error",
289
+ ) &&
290
+ body.diagnostics.every(isDiagnostic)
291
+ );
292
+ }
293
+
294
+ /** @param {unknown} value */
295
+ function isWarningDiagnostic(value) {
296
+ return isDiagnostic(value) && value.severity === "warning";
297
+ }
298
+
299
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
300
+ function isRecord(value) {
301
+ return typeof value === "object" && value !== null && !Array.isArray(value);
302
+ }