@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,12 @@
1
+ /**
2
+ * @param {unknown} error
3
+ * @returns {error is Error & {code: string}}
4
+ */
5
+ export function isFileSystemError(error) {
6
+ return (
7
+ error instanceof Error &&
8
+ "code" in error &&
9
+ typeof error.code === "string" &&
10
+ (error.code === "ERR_ACCESS_DENIED" || !error.code.startsWith("ERR_"))
11
+ );
12
+ }
@@ -0,0 +1,214 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { isFileSystemError } from "./file-system.js";
5
+
6
+ const STATE_FORMAT = "firstdraft.cli-state/1";
7
+ export const MAX_STATE_BYTES = 4096;
8
+ const MAX_ETAG_BYTES = 1024;
9
+ const PROJECT_ID_PATTERN =
10
+ /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11
+ const STRONG_ETAG_PATTERN = /^"(?:[\x21\x23-\x7e\x80-\xff])*"$/;
12
+
13
+ /**
14
+ * @typedef {object} PlanStateFileSystem
15
+ * @property {typeof lstatSync} lstatSync
16
+ * @property {typeof readFileSync} readFileSync
17
+ */
18
+
19
+ /** @type {PlanStateFileSystem} */
20
+ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
21
+
22
+ export class PlanStateConfigurationError extends Error {}
23
+ export class PlanStateLocalError extends Error {}
24
+
25
+ /**
26
+ * @param {object} options
27
+ * @param {string} options.cwd
28
+ * @param {PlanStateFileSystem} [options.fileSystem]
29
+ */
30
+ export function readPlanState({ cwd, fileSystem = DEFAULT_FILE_SYSTEM }) {
31
+ const directory = path.join(cwd, ".firstdraft");
32
+ assertLocalDirectory(directory, fileSystem);
33
+ const source = readLocalFile(
34
+ path.join(directory, "state.json"),
35
+ MAX_STATE_BYTES,
36
+ fileSystem,
37
+ );
38
+
39
+ return parsePlanState(source);
40
+ }
41
+
42
+ /** @param {string} value */
43
+ export function normalizeApiUrl(value) {
44
+ let url;
45
+
46
+ try {
47
+ url = new URL(value);
48
+ } catch (error) {
49
+ if (!(error instanceof TypeError)) throw error;
50
+
51
+ throw new PlanStateConfigurationError("The API URL is invalid.", {
52
+ cause: error,
53
+ });
54
+ }
55
+
56
+ const loopbackHttp =
57
+ url.protocol === "http:" &&
58
+ (url.hostname === "127.0.0.1" ||
59
+ url.hostname === "localhost" ||
60
+ url.hostname === "[::1]");
61
+ if (
62
+ (url.protocol !== "https:" && !loopbackHttp) ||
63
+ url.username !== "" ||
64
+ url.password !== "" ||
65
+ url.pathname !== "/" ||
66
+ url.search !== "" ||
67
+ url.hash !== ""
68
+ ) {
69
+ throw new PlanStateConfigurationError("The API URL is invalid.");
70
+ }
71
+
72
+ return url.origin;
73
+ }
74
+
75
+ /** @param {unknown} value @returns {value is string} */
76
+ export function isUuidV7(value) {
77
+ return typeof value === "string" && PROJECT_ID_PATTERN.test(value);
78
+ }
79
+
80
+ /**
81
+ * @param {string} filePath
82
+ * @param {number} maximumBytes
83
+ * @param {PlanStateFileSystem} fileSystem
84
+ */
85
+ export function readLocalFile(filePath, maximumBytes, fileSystem) {
86
+ try {
87
+ const stat = fileSystem.lstatSync(filePath);
88
+ if (!stat.isFile() || stat.size > maximumBytes) {
89
+ throw new PlanStateLocalError("A local First Draft file is invalid.");
90
+ }
91
+
92
+ const source = fileSystem.readFileSync(filePath);
93
+ if (!Buffer.isBuffer(source) || source.byteLength > maximumBytes) {
94
+ throw new PlanStateLocalError("A local First Draft file is invalid.");
95
+ }
96
+
97
+ return source;
98
+ } catch (error) {
99
+ if (error instanceof PlanStateLocalError) throw error;
100
+ if (!isFileSystemError(error)) throw error;
101
+
102
+ throw new PlanStateLocalError(
103
+ "A local First Draft file could not be read.",
104
+ { cause: error },
105
+ );
106
+ }
107
+ }
108
+
109
+ /**
110
+ * @param {string} directory
111
+ * @param {PlanStateFileSystem} fileSystem
112
+ */
113
+ function assertLocalDirectory(directory, fileSystem) {
114
+ try {
115
+ if (!fileSystem.lstatSync(directory).isDirectory()) {
116
+ throw new PlanStateLocalError(
117
+ "The local First Draft directory is invalid.",
118
+ );
119
+ }
120
+ } catch (error) {
121
+ if (error instanceof PlanStateLocalError) throw error;
122
+ if (!isFileSystemError(error)) throw error;
123
+
124
+ throw new PlanStateLocalError(
125
+ "The local First Draft directory could not be read.",
126
+ { cause: error },
127
+ );
128
+ }
129
+ }
130
+
131
+ /** @param {Buffer} source */
132
+ function parsePlanState(source) {
133
+ let state;
134
+
135
+ try {
136
+ state = JSON.parse(
137
+ new TextDecoder("utf-8", { fatal: true }).decode(source),
138
+ );
139
+ } catch (error) {
140
+ if (!(error instanceof SyntaxError || error instanceof TypeError)) {
141
+ throw error;
142
+ }
143
+
144
+ throw new PlanStateLocalError("Local First Draft state is invalid.", {
145
+ cause: error,
146
+ });
147
+ }
148
+
149
+ if (!isRecord(state)) {
150
+ throw new PlanStateLocalError("Local First Draft state is invalid.");
151
+ }
152
+
153
+ const keys = Object.keys(state).sort();
154
+ const hasRemoteState =
155
+ state.api_url !== undefined || state.foundation_plan_etag !== undefined;
156
+ const expectedKeys = hasRemoteState
157
+ ? ["api_url", "format", "foundation_plan_etag", "project_id"]
158
+ : ["format", "project_id"];
159
+ let storedApiUrl;
160
+
161
+ if (typeof state.api_url === "string") {
162
+ try {
163
+ storedApiUrl = normalizeApiUrl(state.api_url);
164
+ } catch (error) {
165
+ if (!(error instanceof PlanStateConfigurationError)) throw error;
166
+
167
+ throw new PlanStateLocalError("Local First Draft state is invalid.", {
168
+ cause: error,
169
+ });
170
+ }
171
+ }
172
+
173
+ if (
174
+ !arraysEqual(keys, expectedKeys) ||
175
+ state.format !== STATE_FORMAT ||
176
+ !isUuidV7(state.project_id) ||
177
+ (hasRemoteState && storedApiUrl !== state.api_url) ||
178
+ (state.foundation_plan_etag !== undefined &&
179
+ !isStrongEtag(state.foundation_plan_etag))
180
+ ) {
181
+ throw new PlanStateLocalError("Local First Draft state is invalid.");
182
+ }
183
+
184
+ return {
185
+ format: state.format,
186
+ project_id: state.project_id,
187
+ ...(storedApiUrl ? { api_url: storedApiUrl } : {}),
188
+ ...(typeof state.foundation_plan_etag === "string"
189
+ ? { foundation_plan_etag: state.foundation_plan_etag }
190
+ : {}),
191
+ };
192
+ }
193
+
194
+ /** @param {unknown} value @returns {value is string} */
195
+ export function isStrongEtag(value) {
196
+ return (
197
+ typeof value === "string" &&
198
+ Buffer.byteLength(value) <= MAX_ETAG_BYTES &&
199
+ STRONG_ETAG_PATTERN.test(value)
200
+ );
201
+ }
202
+
203
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
204
+ function isRecord(value) {
205
+ return typeof value === "object" && value !== null && !Array.isArray(value);
206
+ }
207
+
208
+ /** @param {string[]} left @param {string[]} right */
209
+ function arraysEqual(left, right) {
210
+ return (
211
+ left.length === right.length &&
212
+ left.every((value, index) => value === right[index])
213
+ );
214
+ }
package/src/uuid-v7.js ADDED
@@ -0,0 +1,55 @@
1
+ import { randomBytes as secureRandomBytes } from "node:crypto";
2
+
3
+ const MAX_TIMESTAMP = 2 ** 48 - 1;
4
+ const RANDOM_BYTE_LENGTH = 16;
5
+
6
+ /**
7
+ * @typedef {object} UuidV7Options
8
+ * @property {() => number} [now]
9
+ * @property {(size: number) => Uint8Array} [randomBytes]
10
+ */
11
+
12
+ /** @param {UuidV7Options} [options] */
13
+ export function generateUuidV7({
14
+ now = Date.now,
15
+ randomBytes = secureRandomBytes,
16
+ } = {}) {
17
+ const timestamp = now();
18
+
19
+ if (
20
+ !Number.isInteger(timestamp) ||
21
+ timestamp < 0 ||
22
+ timestamp > MAX_TIMESTAMP
23
+ ) {
24
+ throw new RangeError(
25
+ `UUIDv7 timestamp must be an integer between 0 and ${MAX_TIMESTAMP}`,
26
+ );
27
+ }
28
+
29
+ const suppliedRandomness = randomBytes(RANDOM_BYTE_LENGTH);
30
+
31
+ if (
32
+ !(suppliedRandomness instanceof Uint8Array) ||
33
+ suppliedRandomness.byteLength !== RANDOM_BYTE_LENGTH
34
+ ) {
35
+ throw new TypeError("UUIDv7 randomBytes must return exactly 16 bytes");
36
+ }
37
+
38
+ const bytes = Uint8Array.from(suppliedRandomness);
39
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
40
+ let remainingTimestamp = timestamp;
41
+
42
+ for (let index = 5; index >= 0; index -= 1) {
43
+ bytes[index] = remainingTimestamp % 256;
44
+ remainingTimestamp = Math.floor(remainingTimestamp / 256);
45
+ }
46
+
47
+ view.setUint8(6, (view.getUint8(6) & 0x0f) | 0x70);
48
+ view.setUint8(8, (view.getUint8(8) & 0x3f) | 0x80);
49
+
50
+ const hex = Array.from(bytes, (byte) =>
51
+ byte.toString(16).padStart(2, "0"),
52
+ ).join("");
53
+
54
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
55
+ }
package/src/version.js ADDED
@@ -0,0 +1,11 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ const packageMetadata = JSON.parse(
4
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
5
+ );
6
+
7
+ if (typeof packageMetadata.version !== "string") {
8
+ throw new TypeError("package.json must declare a string version");
9
+ }
10
+
11
+ export const VERSION = packageMetadata.version;