@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.
- package/README.md +8 -6
- package/docs/README.md +1 -1
- package/docs/commands.md +591 -119
- package/docs/errors.md +171 -70
- package/package.json +4 -1
- package/src/agent-sentences.js +210 -0
- package/src/api-authentication.js +25 -6
- package/src/api-response.js +50 -5
- package/src/cli.js +3113 -1076
- package/src/commands/account.js +97 -0
- package/src/commands/login.js +246 -42
- package/src/commands/maintain.js +662 -0
- package/src/commands/note.js +204 -0
- package/src/commands/plan-compile.js +2 -56
- package/src/commands/report.js +469 -0
- package/src/commands/start.js +52 -0
- package/src/compilation-artifact.js +4 -1
- package/src/credentials.js +145 -7
- package/src/oauth.js +33 -25
- package/src/plan-compile-progress.js +8 -81
- package/src/plan-state.js +250 -1
- package/src/service-client.js +513 -0
- package/src/commands/plan-publish.js +0 -1146
package/src/credentials.js
CHANGED
|
@@ -13,7 +13,10 @@ import path from "node:path";
|
|
|
13
13
|
import { isFileSystemError } from "./file-system.js";
|
|
14
14
|
|
|
15
15
|
export const CREDENTIALS_FORMAT = "firstdraft.cli-credentials/1";
|
|
16
|
+
export const DEVICE_LOGIN_FORMAT = "firstdraft.cli-device-login/1";
|
|
16
17
|
const MAX_CREDENTIALS_BYTES = 256 * 1024;
|
|
18
|
+
const MAX_DEVICE_LOGIN_BYTES = 16 * 1024;
|
|
19
|
+
const USER_CODE = /^[\x21-\x7e]{1,64}$/;
|
|
17
20
|
const LOCK_TIMEOUT_MS = 10_000;
|
|
18
21
|
const LOCK_RETRY_MS = 25;
|
|
19
22
|
|
|
@@ -93,6 +96,113 @@ export function credentialsPath(store = {}) {
|
|
|
93
96
|
return path.join(base, "firstdraft", "credentials.json");
|
|
94
97
|
}
|
|
95
98
|
|
|
99
|
+
/**
|
|
100
|
+
* `device-login.json` beside the credentials file. It holds the one device
|
|
101
|
+
* login that `login --no-wait` started and `login --finish` has not ended,
|
|
102
|
+
* including its device code, which is a credential.
|
|
103
|
+
*
|
|
104
|
+
* @param {CredentialStore} [store]
|
|
105
|
+
*/
|
|
106
|
+
export function deviceLoginPath(store = {}) {
|
|
107
|
+
return path.join(path.dirname(credentialsPath(store)), "device-login.json");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @typedef {object} DeviceLogin
|
|
112
|
+
* @property {string} origin
|
|
113
|
+
* @property {string} deviceCode
|
|
114
|
+
* @property {string} userCode
|
|
115
|
+
* @property {string} verificationUri
|
|
116
|
+
* @property {string | undefined} verificationUriComplete
|
|
117
|
+
* @property {number} interval seconds between polls
|
|
118
|
+
* @property {number} expiresAt epoch milliseconds
|
|
119
|
+
* @property {number} nextPollAt epoch milliseconds
|
|
120
|
+
*/
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Reads the waiting device login, or null when there is none. A malformed
|
|
124
|
+
* file throws CredentialsInvalidError.
|
|
125
|
+
*
|
|
126
|
+
* @param {CredentialStore} [store]
|
|
127
|
+
* @returns {DeviceLogin | null}
|
|
128
|
+
*/
|
|
129
|
+
export function readDeviceLogin(store = {}) {
|
|
130
|
+
const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
|
|
131
|
+
let source;
|
|
132
|
+
try {
|
|
133
|
+
source = fileSystem.readFileSync(deviceLoginPath(store));
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (isMissingFileError(error)) return null;
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const parsed =
|
|
140
|
+
source.byteLength > MAX_DEVICE_LOGIN_BYTES ? null : parseJson(source);
|
|
141
|
+
if (
|
|
142
|
+
!isRecord(parsed) ||
|
|
143
|
+
parsed.format !== DEVICE_LOGIN_FORMAT ||
|
|
144
|
+
typeof parsed.origin !== "string" ||
|
|
145
|
+
typeof parsed.device_code !== "string" ||
|
|
146
|
+
parsed.device_code.length === 0 ||
|
|
147
|
+
typeof parsed.user_code !== "string" ||
|
|
148
|
+
!USER_CODE.test(parsed.user_code) ||
|
|
149
|
+
!isHttpUrl(parsed.verification_uri) ||
|
|
150
|
+
(parsed.verification_uri_complete !== undefined &&
|
|
151
|
+
!isHttpUrl(parsed.verification_uri_complete)) ||
|
|
152
|
+
!Number.isSafeInteger(parsed.interval) ||
|
|
153
|
+
Number(parsed.interval) <= 0 ||
|
|
154
|
+
typeof parsed.expires_at !== "string" ||
|
|
155
|
+
!Number.isFinite(Date.parse(parsed.expires_at)) ||
|
|
156
|
+
typeof parsed.next_poll_at !== "string" ||
|
|
157
|
+
!Number.isFinite(Date.parse(parsed.next_poll_at))
|
|
158
|
+
) {
|
|
159
|
+
throw new CredentialsInvalidError("The device login file is invalid.");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
origin: parsed.origin,
|
|
164
|
+
deviceCode: parsed.device_code,
|
|
165
|
+
userCode: parsed.user_code,
|
|
166
|
+
verificationUri: parsed.verification_uri,
|
|
167
|
+
verificationUriComplete: parsed.verification_uri_complete,
|
|
168
|
+
interval: Number(parsed.interval),
|
|
169
|
+
expiresAt: Date.parse(parsed.expires_at),
|
|
170
|
+
nextPollAt: Date.parse(parsed.next_poll_at),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Saves the waiting device login with mode 0600, replacing any other.
|
|
176
|
+
*
|
|
177
|
+
* @param {CredentialStore} store
|
|
178
|
+
* @param {DeviceLogin} login
|
|
179
|
+
*/
|
|
180
|
+
export function writeDeviceLogin(store, login) {
|
|
181
|
+
const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
|
|
182
|
+
const target = deviceLoginPath(store);
|
|
183
|
+
fileSystem.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
184
|
+
writePrivateFile(store, target, {
|
|
185
|
+
format: DEVICE_LOGIN_FORMAT,
|
|
186
|
+
origin: login.origin,
|
|
187
|
+
device_code: login.deviceCode,
|
|
188
|
+
user_code: login.userCode,
|
|
189
|
+
verification_uri: login.verificationUri,
|
|
190
|
+
...(login.verificationUriComplete === undefined
|
|
191
|
+
? {}
|
|
192
|
+
: { verification_uri_complete: login.verificationUriComplete }),
|
|
193
|
+
interval: login.interval,
|
|
194
|
+
expires_at: new Date(login.expiresAt).toISOString(),
|
|
195
|
+
next_poll_at: new Date(login.nextPollAt).toISOString(),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** @param {CredentialStore} store */
|
|
200
|
+
export function deleteDeviceLogin(store) {
|
|
201
|
+
(store.fileSystem ?? DEFAULT_FILE_SYSTEM).rmSync(deviceLoginPath(store), {
|
|
202
|
+
force: true,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
96
206
|
/**
|
|
97
207
|
* Reads the credentials file. A missing file is an empty store; an unreadable
|
|
98
208
|
* or malformed file throws.
|
|
@@ -274,22 +384,33 @@ function sleep(milliseconds) {
|
|
|
274
384
|
|
|
275
385
|
/** @param {CredentialStore} store @param {Credentials} credentials */
|
|
276
386
|
function saveCredentials(store, credentials) {
|
|
387
|
+
writePrivateFile(store, credentialsPath(store), credentials);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Writes JSON with mode 0600 through a temporary file and an atomic rename,
|
|
392
|
+
* so a reader sees the old file or the new one, never a partial write.
|
|
393
|
+
*
|
|
394
|
+
* @param {CredentialStore} store
|
|
395
|
+
* @param {string} target
|
|
396
|
+
* @param {unknown} value
|
|
397
|
+
*/
|
|
398
|
+
function writePrivateFile(store, target, value) {
|
|
277
399
|
const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
|
|
278
|
-
const target = credentialsPath(store);
|
|
279
400
|
const directory = path.dirname(target);
|
|
280
401
|
const temporaryId =
|
|
281
402
|
store.createTemporaryId?.() ?? randomBytes(8).toString("hex");
|
|
282
403
|
const temporary = path.join(
|
|
283
404
|
directory,
|
|
284
|
-
|
|
405
|
+
`.${path.basename(target)}.${temporaryId}.tmp`,
|
|
285
406
|
);
|
|
286
407
|
|
|
287
408
|
try {
|
|
288
|
-
fileSystem.writeFileSync(
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
);
|
|
409
|
+
fileSystem.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, {
|
|
410
|
+
flag: "wx",
|
|
411
|
+
mode: 0o600,
|
|
412
|
+
flush: true,
|
|
413
|
+
});
|
|
293
414
|
fileSystem.renameSync(temporary, target);
|
|
294
415
|
} catch (error) {
|
|
295
416
|
try {
|
|
@@ -337,6 +458,23 @@ function isMissingFileError(error) {
|
|
|
337
458
|
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
338
459
|
}
|
|
339
460
|
|
|
461
|
+
/** @param {Buffer} source */
|
|
462
|
+
function parseJson(source) {
|
|
463
|
+
try {
|
|
464
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(source));
|
|
465
|
+
} catch (error) {
|
|
466
|
+
if (error instanceof SyntaxError || error instanceof TypeError) return null;
|
|
467
|
+
throw error;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** @param {unknown} value @returns {value is string} */
|
|
472
|
+
function isHttpUrl(value) {
|
|
473
|
+
if (typeof value !== "string" || !URL.canParse(value)) return false;
|
|
474
|
+
const { protocol } = new URL(value);
|
|
475
|
+
return protocol === "https:" || protocol === "http:";
|
|
476
|
+
}
|
|
477
|
+
|
|
340
478
|
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
341
479
|
function isRecord(value) {
|
|
342
480
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
package/src/oauth.js
CHANGED
|
@@ -88,12 +88,9 @@ export function createState(random = randomBytes) {
|
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
90
|
* @param {string} origin
|
|
91
|
-
* @param {{redirectUri: string, state: string, challenge: string
|
|
91
|
+
* @param {{redirectUri: string, state: string, challenge: string}} options
|
|
92
92
|
*/
|
|
93
|
-
export function authorizationUrl(
|
|
94
|
-
origin,
|
|
95
|
-
{ redirectUri, state, challenge, deviceName },
|
|
96
|
-
) {
|
|
93
|
+
export function authorizationUrl(origin, { redirectUri, state, challenge }) {
|
|
97
94
|
const url = new URL("/oauth/authorize", origin);
|
|
98
95
|
url.search = new URLSearchParams({
|
|
99
96
|
response_type: "code",
|
|
@@ -102,7 +99,6 @@ export function authorizationUrl(
|
|
|
102
99
|
state,
|
|
103
100
|
code_challenge: challenge,
|
|
104
101
|
code_challenge_method: "S256",
|
|
105
|
-
...(deviceName ? { device_name: deviceName } : {}),
|
|
106
102
|
}).toString();
|
|
107
103
|
return url.href;
|
|
108
104
|
}
|
|
@@ -290,17 +286,14 @@ export async function exchangeAuthorizationCode({
|
|
|
290
286
|
*/
|
|
291
287
|
|
|
292
288
|
/**
|
|
293
|
-
* @param {RequestOptions
|
|
289
|
+
* @param {RequestOptions} request
|
|
294
290
|
* @returns {Promise<DeviceAuthorization>}
|
|
295
291
|
*/
|
|
296
|
-
export async function requestDeviceAuthorization(
|
|
292
|
+
export async function requestDeviceAuthorization(request) {
|
|
297
293
|
const { status, body } = await postForm(
|
|
298
294
|
request,
|
|
299
295
|
SERVICE_ROUTES.requestDeviceAuthorization,
|
|
300
|
-
{
|
|
301
|
-
client_id: CLIENT_ID,
|
|
302
|
-
...(deviceName ? { device_name: deviceName } : {}),
|
|
303
|
-
},
|
|
296
|
+
{ client_id: CLIENT_ID },
|
|
304
297
|
);
|
|
305
298
|
if (status !== 200) throw oauthFailure(status, body);
|
|
306
299
|
|
|
@@ -372,21 +365,36 @@ export async function pollDeviceToken({
|
|
|
372
365
|
});
|
|
373
366
|
}
|
|
374
367
|
|
|
375
|
-
const
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
if (response.status === 200) return accessTokenFrom(response);
|
|
368
|
+
const result = await requestDeviceToken({ ...request, deviceCode });
|
|
369
|
+
if (!("pending" in result)) return result;
|
|
370
|
+
if (result.pending === "slow_down") intervalMs += SLOW_DOWN_INCREMENT_MS;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
381
373
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
374
|
+
/**
|
|
375
|
+
* One poll of the token endpoint for a device grant. Resolves the token, or
|
|
376
|
+
* which of the two answers that mean "ask again later" First Draft gave;
|
|
377
|
+
* rejects with an OAuthError for every other answer.
|
|
378
|
+
*
|
|
379
|
+
* @param {RequestOptions & {deviceCode: string}} options
|
|
380
|
+
* @returns {Promise<AccessToken | {pending: "authorization_pending" | "slow_down"}>}
|
|
381
|
+
*/
|
|
382
|
+
export async function requestDeviceToken({ deviceCode, ...request }) {
|
|
383
|
+
const response = await postForm(request, SERVICE_ROUTES.requestOAuthToken, {
|
|
384
|
+
grant_type: DEVICE_CODE_GRANT_TYPE,
|
|
385
|
+
device_code: deviceCode,
|
|
386
|
+
client_id: CLIENT_ID,
|
|
387
|
+
});
|
|
388
|
+
if (response.status === 200) return accessTokenFrom(response);
|
|
389
|
+
|
|
390
|
+
const failure = oauthFailure(response.status, response.body);
|
|
391
|
+
if (
|
|
392
|
+
failure.code === "authorization_pending" ||
|
|
393
|
+
failure.code === "slow_down"
|
|
394
|
+
) {
|
|
395
|
+
return { pending: failure.code };
|
|
389
396
|
}
|
|
397
|
+
throw failure;
|
|
390
398
|
}
|
|
391
399
|
|
|
392
400
|
/**
|
|
@@ -1,23 +1,5 @@
|
|
|
1
1
|
const PREFIX = "First Draft: ";
|
|
2
2
|
|
|
3
|
-
const PUBLICATION_MESSAGES = new Map([
|
|
4
|
-
["preparing_repository", "Preparing private GitHub repository..."],
|
|
5
|
-
["creating_repository", "Creating private GitHub repository..."],
|
|
6
|
-
[
|
|
7
|
-
"preparing_repository_reconciliation",
|
|
8
|
-
"Preparing to verify GitHub repository creation...",
|
|
9
|
-
],
|
|
10
|
-
["reconciling_repository", "Verifying GitHub repository creation..."],
|
|
11
|
-
["preparing_artifact", "Preparing compiled application..."],
|
|
12
|
-
["publishing_artifact", "Publishing compiled application to GitHub..."],
|
|
13
|
-
[
|
|
14
|
-
"preparing_publication_reconciliation",
|
|
15
|
-
"Preparing to verify GitHub publication...",
|
|
16
|
-
],
|
|
17
|
-
["reconciling_publication", "Verifying GitHub publication..."],
|
|
18
|
-
["completed", "GitHub publication complete."],
|
|
19
|
-
]);
|
|
20
|
-
|
|
21
3
|
/**
|
|
22
4
|
* @typedef {object} AnalysisProgress
|
|
23
5
|
* @property {"analysis"} phase
|
|
@@ -31,29 +13,18 @@ const PUBLICATION_MESSAGES = new Map([
|
|
|
31
13
|
*/
|
|
32
14
|
|
|
33
15
|
/**
|
|
34
|
-
* @typedef {
|
|
35
|
-
* @property {"publication"} phase
|
|
36
|
-
* @property {"queued" | "running" | "succeeded" | "failed" | "cancelled"} compilationStatus
|
|
37
|
-
* @property {string} publicationPhase
|
|
38
|
-
* @property {string | null} retryAt
|
|
39
|
-
* @property {number} retryCount
|
|
40
|
-
* @property {string | null} reasonCode
|
|
41
|
-
*/
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* @typedef {AnalysisProgress | CompilationProgress | PublicationProgress} PlanCompileProgress
|
|
16
|
+
* @typedef {AnalysisProgress | CompilationProgress} PlanCompileProgress
|
|
45
17
|
*/
|
|
46
18
|
|
|
47
19
|
/**
|
|
48
20
|
* Convert deliberately narrow lifecycle observations into stable progress.
|
|
49
|
-
* This boundary never receives response projections, identifiers, hashes,
|
|
50
|
-
*
|
|
21
|
+
* This boundary never receives response projections, identifiers, hashes, URLs,
|
|
22
|
+
* or local state.
|
|
51
23
|
*
|
|
52
24
|
* @param {{write: (text: string) => unknown}} writer
|
|
53
25
|
* @returns {(progress: PlanCompileProgress) => void}
|
|
54
26
|
*/
|
|
55
27
|
export function createPlanCompileProgressReporter(writer) {
|
|
56
|
-
let compilationSucceeded = false;
|
|
57
28
|
/** @type {string | null} */
|
|
58
29
|
let previousProgress = null;
|
|
59
30
|
|
|
@@ -76,54 +47,10 @@ export function createPlanCompileProgressReporter(writer) {
|
|
|
76
47
|
return;
|
|
77
48
|
}
|
|
78
49
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
);
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
if (progress.compilationStatus === "succeeded" && !compilationSucceeded) {
|
|
89
|
-
write("Application compiled.");
|
|
90
|
-
compilationSucceeded = true;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
if (progress.publicationPhase === "compiling") return;
|
|
94
|
-
if (progress.publicationPhase === "failed") {
|
|
95
|
-
write(
|
|
96
|
-
progress.compilationStatus === "failed"
|
|
97
|
-
? "Application compilation failed."
|
|
98
|
-
: "GitHub publication failed.",
|
|
99
|
-
);
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
if (progress.publicationPhase === "cancelled") {
|
|
103
|
-
write(
|
|
104
|
-
progress.compilationStatus === "cancelled"
|
|
105
|
-
? "Application compilation cancelled."
|
|
106
|
-
: "GitHub publication cancelled.",
|
|
107
|
-
);
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
if (progress.publicationPhase === "github_preflight") {
|
|
111
|
-
write(githubPreflightMessage(progress));
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
const message = PUBLICATION_MESSAGES.get(progress.publicationPhase);
|
|
116
|
-
if (message !== undefined) write(message);
|
|
50
|
+
write(
|
|
51
|
+
progress.status === "waiting"
|
|
52
|
+
? "Compiling application..."
|
|
53
|
+
: "Application compiled.",
|
|
54
|
+
);
|
|
117
55
|
};
|
|
118
56
|
}
|
|
119
|
-
|
|
120
|
-
/** @param {PublicationProgress} progress */
|
|
121
|
-
function githubPreflightMessage(progress) {
|
|
122
|
-
if (progress.retryCount === 0) return "Checking GitHub access...";
|
|
123
|
-
|
|
124
|
-
const retry =
|
|
125
|
-
progress.retryAt === null
|
|
126
|
-
? "automatic retries paused; operator recovery required"
|
|
127
|
-
: `next retry: ${progress.retryAt}`;
|
|
128
|
-
return `Checking GitHub access (reason: ${progress.reasonCode}; retry count: ${progress.retryCount}; ${retry}).`;
|
|
129
|
-
}
|
package/src/plan-state.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
|
|
4
5
|
import { isFileSystemError } from "./file-system.js";
|
|
@@ -21,6 +22,7 @@ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
|
|
|
21
22
|
|
|
22
23
|
export class PlanStateConfigurationError extends Error {}
|
|
23
24
|
export class PlanStateLocalError extends Error {}
|
|
25
|
+
export class PlanStateNotPushedError extends Error {}
|
|
24
26
|
|
|
25
27
|
/**
|
|
26
28
|
* @param {object} options
|
|
@@ -39,6 +41,224 @@ export function readPlanState({ cwd, fileSystem = DEFAULT_FILE_SYSTEM }) {
|
|
|
39
41
|
return parsePlanState(source);
|
|
40
42
|
}
|
|
41
43
|
|
|
44
|
+
/**
|
|
45
|
+
* The Project and API origin that a successful plan push pinned, read from
|
|
46
|
+
* the Project's directory or, in an application that adopted the current
|
|
47
|
+
* directory, from the planning state archived at .firstdraft/design.
|
|
48
|
+
*
|
|
49
|
+
* @param {object} options
|
|
50
|
+
* @param {string} options.cwd
|
|
51
|
+
* @param {PlanStateFileSystem} [options.fileSystem]
|
|
52
|
+
*/
|
|
53
|
+
export function readPinnedProject({ cwd, fileSystem }) {
|
|
54
|
+
const projectDirectory = pinnedProjectDirectory(cwd, fileSystem);
|
|
55
|
+
const state = readPlanState({ cwd: projectDirectory, fileSystem });
|
|
56
|
+
if (state.api_url === undefined) {
|
|
57
|
+
throw new PlanStateNotPushedError(
|
|
58
|
+
"The local Foundation Plan has not been pushed.",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
apiUrl: state.api_url,
|
|
64
|
+
projectId: state.project_id,
|
|
65
|
+
stateDirectory: path.join(projectDirectory, ".firstdraft"),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Every Compilation writes its GapSet into the application as
|
|
70
|
+
// .firstdraft/gaps.json, and the GapSet's project.id is the Project's ID,
|
|
71
|
+
// which no recompile changes. The service caps a GapSet at 32 MiB.
|
|
72
|
+
const APPLICATION_GAP_SET = path.join(".firstdraft", "gaps.json");
|
|
73
|
+
const MAX_GAP_SET_BYTES = 32 * 1024 * 1024;
|
|
74
|
+
const GAP_SET_FORMAT_PREFIX = "firstdraft.foundation-gaps/";
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The Project as readPinnedProject reads it, or, where there is no Project
|
|
78
|
+
* state but the application's own .firstdraft/gaps.json names a Project, as
|
|
79
|
+
* in a fresh clone of the application, that Project at `selectOrigin()`. The
|
|
80
|
+
* application's files hold no origin and no Compilation record, so such a
|
|
81
|
+
* Project has neither a pinned origin nor a state directory.
|
|
82
|
+
*
|
|
83
|
+
* @param {object} options
|
|
84
|
+
* @param {string} options.cwd
|
|
85
|
+
* @param {PlanStateFileSystem} [options.fileSystem]
|
|
86
|
+
* @param {() => string} options.selectOrigin the origin `login` would use
|
|
87
|
+
* @returns {{apiUrl: string, projectId: string, stateDirectory: string | null, fromApplication: boolean}}
|
|
88
|
+
*/
|
|
89
|
+
export function readPinnedOrApplicationProject({
|
|
90
|
+
cwd,
|
|
91
|
+
fileSystem = DEFAULT_FILE_SYSTEM,
|
|
92
|
+
selectOrigin,
|
|
93
|
+
}) {
|
|
94
|
+
const stateFile = path.join(
|
|
95
|
+
pinnedProjectDirectory(cwd, fileSystem),
|
|
96
|
+
".firstdraft",
|
|
97
|
+
"state.json",
|
|
98
|
+
);
|
|
99
|
+
const gapSetFile = path.join(cwd, APPLICATION_GAP_SET);
|
|
100
|
+
if (isAbsent(stateFile, fileSystem) && !isAbsent(gapSetFile, fileSystem)) {
|
|
101
|
+
assertLocalDirectory(path.join(cwd, ".firstdraft"), fileSystem);
|
|
102
|
+
return {
|
|
103
|
+
apiUrl: selectOrigin(),
|
|
104
|
+
projectId: readGapSetProjectId(gapSetFile, fileSystem),
|
|
105
|
+
stateDirectory: null,
|
|
106
|
+
fromApplication: true,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return { ...readPinnedProject({ cwd, fileSystem }), fromApplication: false };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* @param {string} filePath
|
|
115
|
+
* @param {PlanStateFileSystem} fileSystem
|
|
116
|
+
*/
|
|
117
|
+
function readGapSetProjectId(filePath, fileSystem) {
|
|
118
|
+
const source = readLocalFile(filePath, MAX_GAP_SET_BYTES, fileSystem);
|
|
119
|
+
/** @type {unknown} */
|
|
120
|
+
let document;
|
|
121
|
+
try {
|
|
122
|
+
document = JSON.parse(
|
|
123
|
+
new TextDecoder("utf-8", { fatal: true }).decode(source),
|
|
124
|
+
);
|
|
125
|
+
} catch {
|
|
126
|
+
throw new PlanStateLocalError(
|
|
127
|
+
"The application's GapSet is not UTF-8 JSON.",
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
const projectId =
|
|
131
|
+
isRecord(document) &&
|
|
132
|
+
typeof document.format === "string" &&
|
|
133
|
+
document.format.startsWith(GAP_SET_FORMAT_PREFIX) &&
|
|
134
|
+
isRecord(document.project)
|
|
135
|
+
? document.project.id
|
|
136
|
+
: undefined;
|
|
137
|
+
if (typeof projectId !== "string" || !PROJECT_ID_PATTERN.test(projectId)) {
|
|
138
|
+
throw new PlanStateLocalError(
|
|
139
|
+
"The application's GapSet names no First Draft Project.",
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return projectId;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The directory whose .firstdraft holds the Project's state: `cwd`, or the
|
|
148
|
+
* archive at .firstdraft/design when `cwd` is an adopted application root.
|
|
149
|
+
*
|
|
150
|
+
* @param {string} cwd
|
|
151
|
+
* @param {PlanStateFileSystem} [fileSystem]
|
|
152
|
+
*/
|
|
153
|
+
function pinnedProjectDirectory(cwd, fileSystem) {
|
|
154
|
+
// Only an adopted root, whose real .firstdraft holds no state.json, falls
|
|
155
|
+
// back; any other local problem is reported for this directory.
|
|
156
|
+
const adoptedRoot =
|
|
157
|
+
isDirectory(path.join(cwd, ".firstdraft"), fileSystem) &&
|
|
158
|
+
isAbsent(path.join(cwd, ".firstdraft", "state.json"), fileSystem) &&
|
|
159
|
+
isDirectory(path.join(cwd, ".firstdraft", "design"), fileSystem);
|
|
160
|
+
return adoptedRoot ? path.join(cwd, ".firstdraft", "design") : cwd;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// The Compilation whose code the CLI last recorded writing for the Project,
|
|
164
|
+
// kept in its own file beside state.json so the state format stays as it
|
|
165
|
+
// is. It moves with the planning state into an adopted root's archive.
|
|
166
|
+
const COMPILATION_RECORD_NAME = "compilation.json";
|
|
167
|
+
const COMPILATION_RECORD_FORMAT = "firstdraft.cli-compilation/1";
|
|
168
|
+
|
|
169
|
+
export class CompilationRecordWriteError extends Error {}
|
|
170
|
+
export class CompilationNotRecordedError extends Error {}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Records `compilationId` as the Compilation whose code the CLI just wrote,
|
|
174
|
+
* beside the state of the Project found from `cwd` as readPinnedProject
|
|
175
|
+
* finds it, replacing any earlier record.
|
|
176
|
+
*
|
|
177
|
+
* @param {object} options
|
|
178
|
+
* @param {string} options.cwd
|
|
179
|
+
* @param {string} options.compilationId
|
|
180
|
+
* @param {() => string} [options.createTemporaryId]
|
|
181
|
+
* @returns {string} the record's path
|
|
182
|
+
*/
|
|
183
|
+
export function recordCompilation({
|
|
184
|
+
cwd,
|
|
185
|
+
compilationId,
|
|
186
|
+
createTemporaryId = randomUUID,
|
|
187
|
+
}) {
|
|
188
|
+
const recordPath = path.join(
|
|
189
|
+
pinnedProjectDirectory(cwd),
|
|
190
|
+
".firstdraft",
|
|
191
|
+
COMPILATION_RECORD_NAME,
|
|
192
|
+
);
|
|
193
|
+
const temporaryPath = `${recordPath}.${createTemporaryId()}.tmp`;
|
|
194
|
+
const source = `${JSON.stringify(
|
|
195
|
+
{ format: COMPILATION_RECORD_FORMAT, compilation_id: compilationId },
|
|
196
|
+
null,
|
|
197
|
+
2,
|
|
198
|
+
)}\n`;
|
|
199
|
+
try {
|
|
200
|
+
writeFileSync(temporaryPath, source, {
|
|
201
|
+
flag: "wx",
|
|
202
|
+
mode: 0o600,
|
|
203
|
+
flush: true,
|
|
204
|
+
});
|
|
205
|
+
renameSync(temporaryPath, recordPath);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (!isFileSystemError(error)) throw error;
|
|
208
|
+
|
|
209
|
+
throw new CompilationRecordWriteError(
|
|
210
|
+
"The Compilation record could not be written.",
|
|
211
|
+
{ cause: error },
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
return recordPath;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The Compilation that recordCompilation recorded in `stateDirectory`.
|
|
219
|
+
*
|
|
220
|
+
* @param {object} options
|
|
221
|
+
* @param {string} options.stateDirectory from readPinnedProject
|
|
222
|
+
* @param {PlanStateFileSystem} [options.fileSystem]
|
|
223
|
+
* @returns {string}
|
|
224
|
+
*/
|
|
225
|
+
export function readRecordedCompilation({
|
|
226
|
+
stateDirectory,
|
|
227
|
+
fileSystem = DEFAULT_FILE_SYSTEM,
|
|
228
|
+
}) {
|
|
229
|
+
const recordPath = path.join(stateDirectory, COMPILATION_RECORD_NAME);
|
|
230
|
+
if (isAbsent(recordPath, fileSystem)) {
|
|
231
|
+
throw new CompilationNotRecordedError(
|
|
232
|
+
"No Compilation is recorded for this Project.",
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const source = readLocalFile(recordPath, MAX_STATE_BYTES, fileSystem);
|
|
237
|
+
let record;
|
|
238
|
+
try {
|
|
239
|
+
record = JSON.parse(
|
|
240
|
+
new TextDecoder("utf-8", { fatal: true }).decode(source),
|
|
241
|
+
);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (!(error instanceof SyntaxError || error instanceof TypeError)) {
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
throw new PlanStateLocalError("The Compilation record is invalid.", {
|
|
248
|
+
cause: error,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
if (
|
|
252
|
+
!isRecord(record) ||
|
|
253
|
+
!arraysEqual(Object.keys(record).sort(), ["compilation_id", "format"]) ||
|
|
254
|
+
record.format !== COMPILATION_RECORD_FORMAT ||
|
|
255
|
+
!isUuidV7(record.compilation_id)
|
|
256
|
+
) {
|
|
257
|
+
throw new PlanStateLocalError("The Compilation record is invalid.");
|
|
258
|
+
}
|
|
259
|
+
return record.compilation_id;
|
|
260
|
+
}
|
|
261
|
+
|
|
42
262
|
/** @param {string} value */
|
|
43
263
|
export function normalizeApiUrl(value) {
|
|
44
264
|
let url;
|
|
@@ -72,6 +292,35 @@ export function normalizeApiUrl(value) {
|
|
|
72
292
|
return url.origin;
|
|
73
293
|
}
|
|
74
294
|
|
|
295
|
+
/**
|
|
296
|
+
* @param {string} directory
|
|
297
|
+
* @param {PlanStateFileSystem} [fileSystem]
|
|
298
|
+
*/
|
|
299
|
+
function isDirectory(directory, fileSystem = DEFAULT_FILE_SYSTEM) {
|
|
300
|
+
try {
|
|
301
|
+
return fileSystem.lstatSync(directory).isDirectory();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (!isFileSystemError(error)) throw error;
|
|
304
|
+
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* @param {string} filePath
|
|
311
|
+
* @param {PlanStateFileSystem} [fileSystem]
|
|
312
|
+
*/
|
|
313
|
+
function isAbsent(filePath, fileSystem = DEFAULT_FILE_SYSTEM) {
|
|
314
|
+
try {
|
|
315
|
+
fileSystem.lstatSync(filePath);
|
|
316
|
+
return false;
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (!isFileSystemError(error)) throw error;
|
|
319
|
+
|
|
320
|
+
return error.code === "ENOENT";
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
75
324
|
/** @param {unknown} value @returns {value is string} */
|
|
76
325
|
export function isUuidV7(value) {
|
|
77
326
|
return typeof value === "string" && PROJECT_ID_PATTERN.test(value);
|