farseer-cli 1.15.0 → 1.17.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.
Files changed (55) hide show
  1. package/README.md +328 -0
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/commands/model.js +14 -4
  5. package/dist/commands/model.js.map +2 -2
  6. package/dist/index.js +16 -0
  7. package/dist/index.js.map +2 -2
  8. package/dist/pipeline/generated-reference.json +30 -30
  9. package/dist/pipeline/service.js +2 -2
  10. package/dist/pipeline/service.js.map +2 -2
  11. package/dist/services/codefirst/api.js +269 -0
  12. package/dist/services/codefirst/api.js.map +7 -0
  13. package/dist/services/codefirst/binaryDisk.js +67 -0
  14. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  15. package/dist/services/codefirst/byteHashes.js +129 -0
  16. package/dist/services/codefirst/byteHashes.js.map +7 -0
  17. package/dist/services/codefirst/documents.js +563 -0
  18. package/dist/services/codefirst/documents.js.map +7 -0
  19. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  20. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  21. package/dist/services/codefirst/layoutCompose.js +593 -0
  22. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  23. package/dist/services/codefirst/layoutCore.js +260 -0
  24. package/dist/services/codefirst/layoutCore.js.map +7 -0
  25. package/dist/services/codefirst/layoutPaths.js +492 -0
  26. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  27. package/dist/services/codefirst/layoutProjection.js +995 -0
  28. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  29. package/dist/services/codefirst/layoutReadback.js +2552 -0
  30. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  31. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  32. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  33. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  34. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  35. package/dist/services/codefirst/layoutScan.js +882 -0
  36. package/dist/services/codefirst/layoutScan.js.map +7 -0
  37. package/dist/services/codefirst/output.js +179 -0
  38. package/dist/services/codefirst/output.js.map +7 -0
  39. package/dist/services/codefirst/types.js +17 -0
  40. package/dist/services/codefirst/types.js.map +7 -0
  41. package/dist/services/codefirst/workflow.js +581 -0
  42. package/dist/services/codefirst/workflow.js.map +7 -0
  43. package/dist/services/codefirst/workspace.js +310 -0
  44. package/dist/services/codefirst/workspace.js.map +7 -0
  45. package/dist/services/codefirst/workspaceLock.js +148 -0
  46. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  47. package/dist/services/codefirst/workspaceRoot.js +147 -0
  48. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  49. package/dist/utils/logger.js +9 -3
  50. package/dist/utils/logger.js.map +2 -2
  51. package/docs/pipeline-client-guide.md +2 -2
  52. package/docs/pipeline-reference.md +156 -99
  53. package/package.json +3 -2
  54. package/skills/pipeline-authoring/SKILL.md +10 -8
  55. package/skills/pipeline-authoring/practices.md +39 -25
@@ -0,0 +1,269 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var api_exports = {};
30
+ __export(api_exports, {
31
+ CodeFirstApi: () => CodeFirstApi,
32
+ TransportError: () => TransportError,
33
+ requestSettled: () => requestSettled
34
+ });
35
+ module.exports = __toCommonJS(api_exports);
36
+ var import_stream = require("stream");
37
+ var farseer = __toESM(require("farseer-client"));
38
+ var import_httpError = require("../httpError");
39
+ const REQUEST_TIMEOUT_MS = 12e4;
40
+ const APPLY_TIMEOUT_MS = 18e4;
41
+ const NEVER_SENT = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"]);
42
+ const GATEWAY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
43
+ function failureCodes(error, depth = 0) {
44
+ if (!(error instanceof Error) || depth > 4) return [];
45
+ const code = error.code;
46
+ const nested = [error.cause, ...error instanceof AggregateError ? error.errors : []];
47
+ return [...typeof code === "string" ? [code] : [], ...nested.flatMap((item) => failureCodes(item, depth + 1))];
48
+ }
49
+ class TransportError extends Error {
50
+ constructor(cause) {
51
+ const codes = failureCodes(cause);
52
+ const message = cause instanceof Error ? cause.message : String(cause);
53
+ super(codes.length ? `${message} (${codes[0]})` : message, { cause });
54
+ this.name = "TransportError";
55
+ this.unanswered = !(codes.length && codes.every((code) => NEVER_SENT.has(code)));
56
+ }
57
+ }
58
+ function requestSettled(error) {
59
+ if (error instanceof import_httpError.HttpError) return !GATEWAY_STATUSES.has(error.status);
60
+ return !(error instanceof TransportError && error.unanswered);
61
+ }
62
+ function requestDeadline(ms) {
63
+ const controller = new AbortController();
64
+ const timer = setTimeout(
65
+ () => controller.abort(new DOMException(`timeout of ${ms}ms exceeded`, "TimeoutError")),
66
+ ms
67
+ );
68
+ return { signal: controller.signal, progress: () => timer.refresh(), settle: () => clearTimeout(timer) };
69
+ }
70
+ async function readBody(response) {
71
+ let text;
72
+ try {
73
+ text = await response.text();
74
+ } catch (error) {
75
+ throw new TransportError(error);
76
+ }
77
+ if (!text) return void 0;
78
+ try {
79
+ return JSON.parse(text);
80
+ } catch {
81
+ return text;
82
+ }
83
+ }
84
+ const PLAN_MODELS = {
85
+ 200: farseer.PlanFromJSON,
86
+ 400: (json) => "operations" in json ? farseer.PlanFromJSON(json) : json
87
+ };
88
+ const RECEIPT_MODELS = { 200: farseer.ReceiptFromJSON };
89
+ function wireBody(status, body, models) {
90
+ if (!body || typeof body !== "object") return body;
91
+ const model = models[status];
92
+ if (model) return model(body);
93
+ if (status === 202) return farseer.PendingFromJSON(body);
94
+ if (status !== 409) return body;
95
+ switch (body.code) {
96
+ case "apply-in-progress":
97
+ return farseer.ApplyingHeadFromJSON(body);
98
+ case "plan-expired":
99
+ return farseer.ExpiredPlanFromJSON(body);
100
+ case "admission-conflict":
101
+ return farseer.AdmissionConflictFromJSON(body);
102
+ }
103
+ return body;
104
+ }
105
+ const readable = (status) => status >= 200 && status < 300 || status === 400 || status === 409;
106
+ class CodeFirstApi {
107
+ constructor(target) {
108
+ this.configuration = target.native._configuration;
109
+ const send = this.configuration.fetchApi ?? fetch;
110
+ this.routes = new farseer.CodefirstApi(
111
+ new farseer.Configuration({
112
+ basePath: this.configuration.basePath,
113
+ headers: this.configuration.headers,
114
+ middleware: this.configuration.middleware,
115
+ fetchApi: async (input, init) => {
116
+ try {
117
+ return await send(input, init);
118
+ } catch (error) {
119
+ throw new TransportError(error);
120
+ }
121
+ }
122
+ })
123
+ );
124
+ }
125
+ /**
126
+ * The server every request of this session goes to: the session's base path, so the stored API
127
+ * key's base path for an API key and the organisation's host for a browser login, with
128
+ * `FARSEER_API_URL` over both. A workspace records it at checkout and refuses any other.
129
+ */
130
+ baseUrl() {
131
+ return this.configuration.basePath.replace(/\/+$/, "");
132
+ }
133
+ /**
134
+ * The server's answer: a status `returned` accepts (by default a 2xx, a 400 or a 409) is returned
135
+ * for the commands to read; any other status throws an `HttpError`. The generated runtime throws a
136
+ * non-2xx `Response`, so both ways end here.
137
+ */
138
+ async answer(route, init, returned = readable) {
139
+ let response;
140
+ try {
141
+ response = (await route(init)).raw;
142
+ } catch (thrown) {
143
+ if (!(thrown instanceof Response)) throw thrown;
144
+ response = thrown;
145
+ }
146
+ if (returned(response.status)) return response;
147
+ const detail = await response.text().catch(() => "");
148
+ throw new import_httpError.HttpError(response.status, `HTTP ${response.status}: ${detail}`);
149
+ }
150
+ /**
151
+ * `name` (method and path) only labels an unreadable answer: a body missing a field its model
152
+ * reads, which the generated `FromJSON` fails on with a `TypeError`.
153
+ */
154
+ async json(name, route, {
155
+ timeoutMs = REQUEST_TIMEOUT_MS,
156
+ returned = readable,
157
+ models = {}
158
+ } = {}) {
159
+ const deadline = requestDeadline(timeoutMs);
160
+ try {
161
+ const response = await this.answer(route, { signal: deadline.signal }, returned);
162
+ const body = await readBody(response);
163
+ let data;
164
+ try {
165
+ data = wireBody(response.status, body, models);
166
+ } catch (cause) {
167
+ const message = cause instanceof Error ? cause.message : String(cause);
168
+ throw new Error(`Unreadable code-first answer to ${name} (HTTP ${response.status}): ${message}`, {
169
+ cause
170
+ });
171
+ }
172
+ return { status: response.status, data, body };
173
+ } finally {
174
+ deadline.settle();
175
+ }
176
+ }
177
+ head() {
178
+ return this.json("GET /codefirst/head", (init) => this.routes.headRaw(init), {
179
+ models: { 200: farseer.HeadFromJSON }
180
+ });
181
+ }
182
+ /** Streams the bytes; the caller checked their hash and the 64 MiB limit just before. */
183
+ async uploadBlob(sha256, bytes) {
184
+ const deadline = requestDeadline(REQUEST_TIMEOUT_MS);
185
+ const body = import_stream.Readable.toWeb(bytes).pipeThrough(
186
+ new TransformStream({
187
+ transform(chunk, output) {
188
+ deadline.progress();
189
+ output.enqueue(chunk);
190
+ }
191
+ })
192
+ );
193
+ try {
194
+ const response = await this.answer(
195
+ // The empty Blob only satisfies the generated signature; the stream in `init` is sent.
196
+ (init) => this.routes.uploadBlobRaw({ sha256, body: new Blob([]) }, init),
197
+ // Node's fetch sends a stream body only as a half-duplex request.
198
+ { signal: deadline.signal, body, duplex: "half" }
199
+ );
200
+ const answered = await readBody(response);
201
+ if (![200, 201].includes(response.status)) throw new Error(`Blob upload failed (HTTP ${response.status})`);
202
+ return farseer.BlobContentFromJSON(answered);
203
+ } finally {
204
+ deadline.settle();
205
+ }
206
+ }
207
+ /** The answer must start within the timeout; the bytes then stream to disk for as long as they take. */
208
+ async downloadBlob(sha256) {
209
+ const deadline = requestDeadline(REQUEST_TIMEOUT_MS);
210
+ let response;
211
+ try {
212
+ response = await this.answer((init) => this.routes.downloadBlobRaw({ sha256 }, init), {
213
+ signal: deadline.signal
214
+ });
215
+ } finally {
216
+ deadline.settle();
217
+ }
218
+ if (response.status !== 200 || !response.body) {
219
+ await response.body?.cancel();
220
+ throw new Error(`Blob download failed (HTTP ${response.status})`);
221
+ }
222
+ return import_stream.Readable.fromWeb(response.body);
223
+ }
224
+ /** A 400 is a plan with a top-level `code`, or a plain `{code, message}` error the commands tell apart. */
225
+ plan(documents, baseline) {
226
+ const planRequest = { documents, baseline };
227
+ return this.json(
228
+ "POST /codefirst/plans",
229
+ (init) => this.routes.planRaw({ planRequest }, init),
230
+ { models: PLAN_MODELS }
231
+ );
232
+ }
233
+ /** Only a 200 carries the stored plan; any other answer throws an `HttpError`. */
234
+ async getPlan(planId) {
235
+ return this.json(
236
+ `GET /codefirst/plans/${planId}`,
237
+ (init) => this.routes.storedPlanRaw({ planId }, init),
238
+ {
239
+ returned: (status) => status === 200,
240
+ models: { 200: farseer.PlanFromJSON }
241
+ }
242
+ );
243
+ }
244
+ apply(planId) {
245
+ return this.json(
246
+ `POST /codefirst/plans/${planId}/apply`,
247
+ (init) => this.routes.applyRaw({ planId }, init),
248
+ { timeoutMs: APPLY_TIMEOUT_MS, models: RECEIPT_MODELS }
249
+ );
250
+ }
251
+ async attempt(planId) {
252
+ const response = await this.json(
253
+ `GET /codefirst/plans/${planId}/attempt`,
254
+ (init) => this.routes.attemptRaw({ planId }, init),
255
+ {
256
+ returned: (status) => readable(status) || status === 404,
257
+ models: RECEIPT_MODELS
258
+ }
259
+ );
260
+ return response.status === 404 ? { status: 404, data: void 0, body: response.body } : response;
261
+ }
262
+ }
263
+ // Annotate the CommonJS export names for ESM import in node:
264
+ 0 && (module.exports = {
265
+ CodeFirstApi,
266
+ TransportError,
267
+ requestSettled
268
+ });
269
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/api.ts"],
4
+ "sourcesContent": ["import { Readable } from 'stream';\nimport type { ReadableStream as WebReadableStream } from 'stream/web';\nimport * as farseer from 'farseer-client';\nimport { HttpError } from '../httpError';\nimport type { TenantSession } from '../preflight';\nimport type {\n AdmissionConflict,\n ApplyingHead,\n BlobContent,\n Document,\n ExpiredPlan,\n Head,\n Pending,\n Plan,\n Receipt,\n} from './types';\n\n/** Every request's timeout, except the apply's. */\nconst REQUEST_TIMEOUT_MS = 120_000;\n/**\n * The apply's own timeout. The server waits for the engine for at most 60 s and then still\n * finalizes, reads the head back and stamps, so a large tenant needs more than the usual window.\n */\nconst APPLY_TIMEOUT_MS = 180_000;\n/** Connection failures that happen before a request leaves this machine, so nothing reached a server. */\nconst NEVER_SENT = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH']);\n/** A gateway's answers: the request behind them can still be running on the server. */\nconst GATEWAY_STATUSES = new Set([502, 503, 504]);\n\nexport interface ApiResponse<T> {\n status: number;\n /** The body through its generated model (`wireBody`). */\n data: T;\n /** The body as the server sent it, parsed from JSON only. */\n body: unknown;\n}\n\n/** The `code` of a failure and of everything under it: fetch wraps the socket error in `cause`. */\nfunction failureCodes(error: unknown, depth = 0): string[] {\n if (!(error instanceof Error) || depth > 4) return [];\n const code = (error as { code?: unknown }).code;\n const nested = [error.cause, ...(error instanceof AggregateError ? error.errors : [])];\n return [...(typeof code === 'string' ? [code] : []), ...nested.flatMap((item) => failureCodes(item, depth + 1))];\n}\n\n/**\n * A code-first request that failed after it was handed to fetch: a connection that failed, a\n * connection lost before the whole answer arrived, or a timeout. `unanswered` says whether the\n * request may have reached the server and still be running there, which is every such failure except\n * a connection that never left this machine (offline, no such host, connection refused).\n */\nexport class TransportError extends Error {\n readonly unanswered: boolean;\n constructor(cause: unknown) {\n const codes = failureCodes(cause);\n const message = cause instanceof Error ? cause.message : String(cause);\n super(codes.length ? `${message} (${codes[0]})` : message, { cause });\n this.name = 'TransportError';\n this.unanswered = !(codes.length && codes.every((code) => NEVER_SENT.has(code)));\n }\n}\n\n/**\n * Whether a failed request is over on the server side. Only a request that was sent and got no\n * answer can still be running there: a timeout or a lost connection (an `unanswered`\n * `TransportError`), and a gateway's 502, 503 or 504, behind which the request can still be running.\n * Everything else is settled: an answer, a connection that never left this machine, and a failure\n * before the request reached fetch (an expired login, an invalid request).\n */\nexport function requestSettled(error: unknown): boolean {\n if (error instanceof HttpError) return !GATEWAY_STATUSES.has(error.status);\n return !(error instanceof TransportError && error.unanswered);\n}\n\n/**\n * One request's timeout. Like a socket timeout it counts silence: `progress` restarts it when an\n * upload chunk goes out, and `settle` ends it once the answer is in hand, so a JSON request gets a\n * plain deadline and a blob transfer that keeps moving bytes never times out.\n */\nfunction requestDeadline(ms: number) {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(new DOMException(`timeout of ${ms}ms exceeded`, 'TimeoutError')),\n ms,\n );\n return { signal: controller.signal, progress: () => timer.refresh(), settle: () => clearTimeout(timer) };\n}\n\n/** The JSON an answer carries; a body that is not JSON stays text. A body cut off is unanswered. */\nasync function readBody(response: Response): Promise<unknown> {\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n throw new TransportError(error);\n }\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** A route's own bodies by status, each read through its generated model. */\ntype Models = Partial<Record<number, (json: object) => unknown>>;\n/** A POST plans 400 is a plan with a top-level `code`, or a plain `{code, message}` error. */\nconst PLAN_MODELS: Models = {\n 200: farseer.PlanFromJSON,\n 400: (json) => ('operations' in json ? farseer.PlanFromJSON(json) : json),\n};\nconst RECEIPT_MODELS: Models = { 200: farseer.ReceiptFromJSON };\n\n/**\n * The body a command reads: a status the route names in `models` through that model, a 202 and a\n * 409 through the generated model (a 409's chosen by its `code`), any other body as parsed.\n * `expiresAt` becomes a `Date`.\n */\nfunction wireBody(status: number, body: unknown, models: Models): unknown {\n if (!body || typeof body !== 'object') return body;\n const model = models[status];\n if (model) return model(body);\n if (status === 202) return farseer.PendingFromJSON(body);\n if (status !== 409) return body;\n switch ((body as { code?: unknown }).code) {\n case 'apply-in-progress':\n return farseer.ApplyingHeadFromJSON(body);\n case 'plan-expired':\n return farseer.ExpiredPlanFromJSON(body);\n case 'admission-conflict':\n return farseer.AdmissionConflictFromJSON(body);\n }\n return body;\n}\n\n/** One generated `*Raw` call; the commands read its `raw` answer, never its `value()`. */\ntype Route = (init: RequestInit) => Promise<farseer.ApiResponse<unknown>>;\n/** The statuses most routes return for the commands to read: every 2xx, a 400 and a 409. */\nconst readable = (status: number) => (status >= 200 && status < 300) || status === 400 || status === 409;\n\n/**\n * The code-first routes over the session's own SDK client: the base path, the credential's headers\n * and the browser login's token refresh (the organisation's realm) are the ones every other command\n * uses, decided once in `credentials.ts`. Every request goes through a generated `CodefirstApi`\n * `*Raw` method; fetch is wrapped only to tell a transport failure (`TransportError`) from a failure\n * before sending. Headers never go in a request's `initOverrides`: the runtime spreads those last,\n * so they would replace the session's headers and the route's `Content-Type`.\n */\nexport class CodeFirstApi {\n private readonly configuration: farseer.Configuration;\n private readonly routes: farseer.CodefirstApi;\n\n constructor(target: Pick<TenantSession, 'native'>) {\n this.configuration = target.native._configuration;\n const send = this.configuration.fetchApi ?? fetch;\n this.routes = new farseer.CodefirstApi(\n new farseer.Configuration({\n basePath: this.configuration.basePath,\n headers: this.configuration.headers,\n middleware: this.configuration.middleware,\n fetchApi: async (input, init) => {\n try {\n return await send(input, init);\n } catch (error) {\n throw new TransportError(error);\n }\n },\n }),\n );\n }\n /**\n * The server every request of this session goes to: the session's base path, so the stored API\n * key's base path for an API key and the organisation's host for a browser login, with\n * `FARSEER_API_URL` over both. A workspace records it at checkout and refuses any other.\n */\n baseUrl(): string {\n return this.configuration.basePath.replace(/\\/+$/, '');\n }\n /**\n * The server's answer: a status `returned` accepts (by default a 2xx, a 400 or a 409) is returned\n * for the commands to read; any other status throws an `HttpError`. The generated runtime throws a\n * non-2xx `Response`, so both ways end here.\n */\n private async answer(route: Route, init: RequestInit, returned = readable): Promise<Response> {\n let response: Response;\n try {\n response = (await route(init)).raw;\n } catch (thrown) {\n if (!(thrown instanceof Response)) throw thrown;\n response = thrown;\n }\n if (returned(response.status)) return response;\n const detail = await response.text().catch(() => '');\n throw new HttpError(response.status, `HTTP ${response.status}: ${detail}`);\n }\n /**\n * `name` (method and path) only labels an unreadable answer: a body missing a field its model\n * reads, which the generated `FromJSON` fails on with a `TypeError`.\n */\n private async json<T>(\n name: string,\n route: Route,\n {\n timeoutMs = REQUEST_TIMEOUT_MS,\n returned = readable,\n models = {},\n }: { timeoutMs?: number; returned?: (status: number) => boolean; models?: Models } = {},\n ): Promise<ApiResponse<T>> {\n const deadline = requestDeadline(timeoutMs);\n try {\n const response = await this.answer(route, { signal: deadline.signal }, returned);\n const body = await readBody(response);\n let data: T;\n try {\n data = wireBody(response.status, body, models) as T;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new Error(`Unreadable code-first answer to ${name} (HTTP ${response.status}): ${message}`, {\n cause,\n });\n }\n return { status: response.status, data, body };\n } finally {\n deadline.settle();\n }\n }\n head() {\n return this.json<Head | ApplyingHead>('GET /codefirst/head', (init) => this.routes.headRaw(init), {\n models: { 200: farseer.HeadFromJSON },\n });\n }\n /** Streams the bytes; the caller checked their hash and the 64 MiB limit just before. */\n async uploadBlob(sha256: string, bytes: Readable): Promise<BlobContent> {\n const deadline = requestDeadline(REQUEST_TIMEOUT_MS);\n const body = (Readable.toWeb(bytes) as ReadableStream<Uint8Array>).pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, output) {\n deadline.progress();\n output.enqueue(chunk);\n },\n }),\n );\n try {\n const response = await this.answer(\n // The empty Blob only satisfies the generated signature; the stream in `init` is sent.\n (init) => this.routes.uploadBlobRaw({ sha256, body: new Blob([]) }, init),\n // Node's fetch sends a stream body only as a half-duplex request.\n { signal: deadline.signal, body, duplex: 'half' } as RequestInit,\n );\n const answered = await readBody(response);\n if (![200, 201].includes(response.status)) throw new Error(`Blob upload failed (HTTP ${response.status})`);\n return farseer.BlobContentFromJSON(answered);\n } finally {\n deadline.settle();\n }\n }\n /** The answer must start within the timeout; the bytes then stream to disk for as long as they take. */\n async downloadBlob(sha256: string): Promise<Readable> {\n const deadline = requestDeadline(REQUEST_TIMEOUT_MS);\n let response: Response;\n try {\n response = await this.answer((init) => this.routes.downloadBlobRaw({ sha256 }, init), {\n signal: deadline.signal,\n });\n } finally {\n deadline.settle();\n }\n if (response.status !== 200 || !response.body) {\n await response.body?.cancel();\n throw new Error(`Blob download failed (HTTP ${response.status})`);\n }\n return Readable.fromWeb(response.body as WebReadableStream<Uint8Array>);\n }\n /** A 400 is a plan with a top-level `code`, or a plain `{code, message}` error the commands tell apart. */\n plan(documents: Document[], baseline: Record<string, string>) {\n // The workspace's documents carry `kind` as the enum's string value, the generated model as the enum.\n const planRequest = { documents: documents as farseer.Document[], baseline };\n return this.json<Plan | farseer.ErrorResponse | ApplyingHead>(\n 'POST /codefirst/plans',\n (init) => this.routes.planRaw({ planRequest }, init),\n { models: PLAN_MODELS },\n );\n }\n /** Only a 200 carries the stored plan; any other answer throws an `HttpError`. */\n async getPlan(planId: string): Promise<ApiResponse<Plan>> {\n return this.json<Plan>(\n `GET /codefirst/plans/${planId}`,\n (init) => this.routes.storedPlanRaw({ planId }, init),\n {\n returned: (status) => status === 200,\n models: { 200: farseer.PlanFromJSON },\n },\n );\n }\n apply(planId: string) {\n return this.json<Receipt | Pending | ApplyingHead | ExpiredPlan | AdmissionConflict>(\n `POST /codefirst/plans/${planId}/apply`,\n (init) => this.routes.applyRaw({ planId }, init),\n { timeoutMs: APPLY_TIMEOUT_MS, models: RECEIPT_MODELS },\n );\n }\n async attempt(planId: string): Promise<ApiResponse<Receipt | Pending | undefined>> {\n const response = await this.json<Receipt | Pending>(\n `GET /codefirst/plans/${planId}/attempt`,\n (init) => this.routes.attemptRaw({ planId }, init),\n {\n returned: (status) => readable(status) || status === 404,\n models: RECEIPT_MODELS,\n },\n );\n return response.status === 404 ? { status: 404, data: undefined, body: response.body } : response;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAyB;AAEzB,cAAyB;AACzB,uBAA0B;AAe1B,MAAM,qBAAqB;AAK3B,MAAM,mBAAmB;AAEzB,MAAM,aAAa,oBAAI,IAAI,CAAC,aAAa,aAAa,gBAAgB,eAAe,cAAc,CAAC;AAEpG,MAAM,mBAAmB,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAWhD,SAAS,aAAa,OAAgB,QAAQ,GAAa;AACvD,MAAI,EAAE,iBAAiB,UAAU,QAAQ,EAAG,QAAO,CAAC;AACpD,QAAM,OAAQ,MAA6B;AAC3C,QAAM,SAAS,CAAC,MAAM,OAAO,GAAI,iBAAiB,iBAAiB,MAAM,SAAS,CAAC,CAAE;AACrF,SAAO,CAAC,GAAI,OAAO,SAAS,WAAW,CAAC,IAAI,IAAI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AM,cAAc,EAAE,WAA4C,SAAS;AAC3E,WAAO,KAAK;AAAA,MACR;AAAA,MACA,CAAC,SAAS,KAAK,OAAO,QAAQ,EAAE,YAAY,GAAG,IAAI;AAAA,MACnD,EAAE,QAAQ,YAAY;AAAA,IAC1B;AAAA,EACJ;AAAA;AAAA,EAEA,MAAM,QAAQ,QAA4C;AACtD,WAAO,KAAK;AAAA,MACR,wBAAwB,MAAM;AAAA,MAC9B,CAAC,SAAS,KAAK,OAAO,cAAc,EAAE,OAAO,GAAG,IAAI;AAAA,MACpD;AAAA,QACI,UAAU,CAAC,WAAW,WAAW;AAAA,QACjC,QAAQ,EAAE,KAAK,QAAQ,aAAa;AAAA,MACxC;AAAA,IACJ;AAAA,EACJ;AAAA,EACA,MAAM,QAAgB;AAClB,WAAO,KAAK;AAAA,MACR,yBAAyB,MAAM;AAAA,MAC/B,CAAC,SAAS,KAAK,OAAO,SAAS,EAAE,OAAO,GAAG,IAAI;AAAA,MAC/C,EAAE,WAAW,kBAAkB,QAAQ,eAAe;AAAA,IAC1D;AAAA,EACJ;AAAA,EACA,MAAM,QAAQ,QAAqE;AAC/E,UAAM,WAAW,MAAM,KAAK;AAAA,MACxB,wBAAwB,MAAM;AAAA,MAC9B,CAAC,SAAS,KAAK,OAAO,WAAW,EAAE,OAAO,GAAG,IAAI;AAAA,MACjD;AAAA,QACI,UAAU,CAAC,WAAW,SAAS,MAAM,KAAK,WAAW;AAAA,QACrD,QAAQ;AAAA,MACZ;AAAA,IACJ;AACA,WAAO,SAAS,WAAW,MAAM,EAAE,QAAQ,KAAK,MAAM,QAAW,MAAM,SAAS,KAAK,IAAI;AAAA,EAC7F;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var binaryDisk_exports = {};
30
+ __export(binaryDisk_exports, {
31
+ BLOB_UPLOAD_LIMIT: () => BLOB_UPLOAD_LIMIT,
32
+ hashFile: () => hashFile,
33
+ sameBytes: () => sameBytes
34
+ });
35
+ module.exports = __toCommonJS(binaryDisk_exports);
36
+ var fs = __toESM(require("fs"));
37
+ var import_crypto = require("crypto");
38
+ const BLOB_UPLOAD_LIMIT = 64 * 1024 * 1024;
39
+ const sameBytes = (a, b) => a === void 0 || b === void 0 ? a === b : a.sha256 === b.sha256 && a.size === b.size;
40
+ function hashFile(file) {
41
+ let fd;
42
+ try {
43
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
44
+ } catch (error) {
45
+ if (error.code === "ENOENT") return void 0;
46
+ throw error;
47
+ }
48
+ try {
49
+ if (!fs.fstatSync(fd).isFile()) throw new Error(`Expected regular file: ${file}`);
50
+ const buffer = Buffer.allocUnsafe(1024 * 1024), hash = (0, import_crypto.createHash)("sha256");
51
+ let size = 0, length;
52
+ while ((length = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) {
53
+ hash.update(buffer.subarray(0, length));
54
+ size += length;
55
+ }
56
+ return { sha256: hash.digest("hex"), size };
57
+ } finally {
58
+ fs.closeSync(fd);
59
+ }
60
+ }
61
+ // Annotate the CommonJS export names for ESM import in node:
62
+ 0 && (module.exports = {
63
+ BLOB_UPLOAD_LIMIT,
64
+ hashFile,
65
+ sameBytes
66
+ });
67
+ //# sourceMappingURL=binaryDisk.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/binaryDisk.ts"],
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport { createHash } from 'crypto';\nimport { Readable } from 'stream';\nimport { BlobContent } from './types';\n\nexport interface BlobApi {\n uploadBlob(sha256: string, bytes: Readable): Promise<BlobContent>;\n downloadBlob(sha256: string): Promise<Readable>;\n}\n\nexport const BLOB_UPLOAD_LIMIT = 64 * 1024 * 1024;\nexport const sameBytes = (a: BlobContent | undefined, b: BlobContent | undefined): boolean =>\n a === undefined || b === undefined ? a === b : a.sha256 === b.sha256 && a.size === b.size;\n\n/** Bounded local hashing; even existing files larger than the upload limit stay stream-sized. */\nexport function hashFile(file: string): BlobContent | undefined {\n let fd: number;\n try {\n fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n try {\n if (!fs.fstatSync(fd).isFile()) throw new Error(`Expected regular file: ${file}`);\n const buffer = Buffer.allocUnsafe(1024 * 1024),\n hash = createHash('sha256');\n let size = 0,\n length: number;\n while ((length = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) {\n hash.update(buffer.subarray(0, length));\n size += length;\n }\n return { sha256: hash.digest('hex'), size };\n } finally {\n fs.closeSync(fd);\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,oBAA2B;AASpB,MAAM,oBAAoB,KAAK,OAAO;AACtC,MAAM,YAAY,CAAC,GAA4B,MAClD,MAAM,UAAa,MAAM,SAAY,MAAM,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE;AAGlF,SAAS,SAAS,MAAuC;AAC5D,MAAI;AACJ,MAAI;AACA,SAAK,GAAG,SAAS,MAAM,GAAG,UAAU,WAAW,GAAG,UAAU,UAAU;AAAA,EAC1E,SAAS,OAAO;AACZ,QAAK,MAAgC,SAAS,SAAU,QAAO;AAC/D,UAAM;AAAA,EACV;AACA,MAAI;AACA,QAAI,CAAC,GAAG,UAAU,EAAE,EAAE,OAAO,EAAG,OAAM,IAAI,MAAM,0BAA0B,IAAI,EAAE;AAChF,UAAM,SAAS,OAAO,YAAY,OAAO,IAAI,GACzC,WAAO,0BAAW,QAAQ;AAC9B,QAAI,OAAO,GACP;AACJ,YAAQ,SAAS,GAAG,SAAS,IAAI,QAAQ,GAAG,OAAO,QAAQ,IAAI,KAAK,GAAG;AACnE,WAAK,OAAO,OAAO,SAAS,GAAG,MAAM,CAAC;AACtC,cAAQ;AAAA,IACZ;AACA,WAAO,EAAE,QAAQ,KAAK,OAAO,KAAK,GAAG,KAAK;AAAA,EAC9C,UAAE;AACE,OAAG,UAAU,EAAE;AAAA,EACnB;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var byteHashes_exports = {};
30
+ __export(byteHashes_exports, {
31
+ RACY_WINDOW_NS: () => RACY_WINDOW_NS,
32
+ byteHashesChanged: () => byteHashesChanged,
33
+ hashWorkspaceFile: () => hashWorkspaceFile,
34
+ persistableByteHashes: () => persistableByteHashes,
35
+ resetByteHashSessions: () => resetByteHashSessions,
36
+ useByteHashClock: () => useByteHashClock
37
+ });
38
+ module.exports = __toCommonJS(byteHashes_exports);
39
+ var fs = __toESM(require("fs"));
40
+ var path = __toESM(require("path"));
41
+ var import_binaryDisk = require("./binaryDisk");
42
+ var import_documents = require("./documents");
43
+ const RACY_WINDOW_NS = 2000000000n;
44
+ const STATE_FILE = path.join(".fscode", "state.json");
45
+ const sessions = /* @__PURE__ */ new Map();
46
+ const systemClockNs = () => BigInt(Date.now()) * 1000000n;
47
+ let nowNs = systemClockNs;
48
+ function useByteHashClock(clock) {
49
+ nowNs = clock ?? systemClockNs;
50
+ }
51
+ function loadSession(root) {
52
+ const entries = /* @__PURE__ */ new Map();
53
+ let cutoff = nowNs() - RACY_WINDOW_NS;
54
+ try {
55
+ const file = path.join(root, STATE_FILE);
56
+ cutoff = fs.statSync(file, { bigint: true }).mtimeNs - RACY_WINDOW_NS;
57
+ const parsed = (0, import_documents.peekState)(fs.readFileSync(file, "utf8"));
58
+ for (const [relative, entry] of Object.entries(parsed.layout?.byteHashes ?? {}))
59
+ if (BigInt(entry.mtimeNs) < cutoff) entries.set(relative, entry);
60
+ } catch {
61
+ }
62
+ return { entries, changed: false };
63
+ }
64
+ function sessionFor(root) {
65
+ const key = path.resolve(root);
66
+ let session = sessions.get(key);
67
+ if (!session) {
68
+ session = loadSession(key);
69
+ sessions.set(key, session);
70
+ }
71
+ return session;
72
+ }
73
+ function matches(entry, stat) {
74
+ return entry !== void 0 && BigInt(entry.size) === stat.size && entry.mtimeNs === String(stat.mtimeNs) && entry.ctimeNs === String(stat.ctimeNs) && entry.ino === String(stat.ino);
75
+ }
76
+ function lstat(file) {
77
+ try {
78
+ return fs.lstatSync(file, { bigint: true });
79
+ } catch (error) {
80
+ if (error.code === "ENOENT") return void 0;
81
+ throw error;
82
+ }
83
+ }
84
+ function hashWorkspaceFile(root, relative, absolute) {
85
+ const session = sessionFor(root);
86
+ const before = lstat(absolute);
87
+ const entry = session.entries.get(relative);
88
+ if (before?.isFile() && matches(entry, before)) return { sha256: entry.sha256, size: entry.size };
89
+ const started = nowNs();
90
+ const content = (0, import_binaryDisk.hashFile)(absolute);
91
+ const after = content ? lstat(absolute) : void 0;
92
+ const recorded = content && before?.isFile() ? {
93
+ sha256: content.sha256,
94
+ size: content.size,
95
+ mtimeNs: String(before.mtimeNs),
96
+ ctimeNs: String(before.ctimeNs),
97
+ ino: String(before.ino)
98
+ } : void 0;
99
+ if (recorded && after && matches(recorded, after) && before.mtimeNs < started - RACY_WINDOW_NS) {
100
+ session.entries.set(relative, recorded);
101
+ session.changed = true;
102
+ } else if (session.entries.delete(relative)) session.changed = true;
103
+ return content;
104
+ }
105
+ function persistableByteHashes(root, persisted) {
106
+ const session = sessions.get(path.resolve(root));
107
+ const candidates = session ? Object.fromEntries(session.entries) : { ...persisted ?? {} };
108
+ const kept = Object.entries(candidates).filter(([relative, entry]) => {
109
+ const stat = lstat(path.join(root, ...relative.split("/")));
110
+ return stat?.isFile() === true && matches(entry, stat);
111
+ }).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
112
+ return kept.length ? Object.fromEntries(kept) : void 0;
113
+ }
114
+ function byteHashesChanged(root) {
115
+ return sessions.get(path.resolve(root))?.changed === true;
116
+ }
117
+ function resetByteHashSessions() {
118
+ sessions.clear();
119
+ }
120
+ // Annotate the CommonJS export names for ESM import in node:
121
+ 0 && (module.exports = {
122
+ RACY_WINDOW_NS,
123
+ byteHashesChanged,
124
+ hashWorkspaceFile,
125
+ persistableByteHashes,
126
+ resetByteHashSessions,
127
+ useByteHashClock
128
+ });
129
+ //# sourceMappingURL=byteHashes.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/byteHashes.ts"],
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { hashFile } from './binaryDisk';\nimport { peekState } from './documents';\nimport { BlobContent, ByteHashEntry } from './types';\n\n/**\n * Files modified within this window of a reference time are never trusted from the cache, because a\n * write in the same timestamp tick can change content without changing size or mtime. The rule is\n * git's \"racy git\" rule (https://git-scm.com/docs/racy-git): a persisted entry is trusted only when\n * its mtime is more than this window older than the state file's mtime when the cache is loaded (or\n * than \"now\" when no state exists), and an entry is recorded only when the file's mtime is more than\n * this window older than the moment it was hashed. So an entry recorded shortly before a save is\n * never trusted by the next command.\n */\nexport const RACY_WINDOW_NS = 2_000_000_000n;\n\nconst STATE_FILE = path.join('.fscode', 'state.json');\n\ninterface ByteHashSession {\n entries: Map<string, ByteHashEntry>;\n changed: boolean;\n}\n\n/** One cache per workspace root and process: every capture, adoption and save of a command shares it. */\nconst sessions = new Map<string, ByteHashSession>();\n\nconst systemClockNs = () => BigInt(Date.now()) * 1_000_000n;\nlet nowNs = systemClockNs;\n\n/** Replace the clock the racy rule reads, or restore the system clock. For tests. */\nexport function useByteHashClock(clock?: () => bigint): void {\n nowNs = clock ?? systemClockNs;\n}\n\n/** The persisted entries the racy rule trusts, measured against the state file's own mtime. */\nfunction loadSession(root: string): ByteHashSession {\n const entries = new Map<string, ByteHashEntry>();\n let cutoff = nowNs() - RACY_WINDOW_NS;\n try {\n const file = path.join(root, STATE_FILE);\n cutoff = fs.statSync(file, { bigint: true }).mtimeNs - RACY_WINDOW_NS;\n const parsed = peekState(fs.readFileSync(file, 'utf8'));\n for (const [relative, entry] of Object.entries(parsed.layout?.byteHashes ?? {}))\n if (BigInt(entry.mtimeNs) < cutoff) entries.set(relative, entry);\n } catch {\n // No readable state: nothing is trusted, and every file is hashed.\n }\n return { entries, changed: false };\n}\n\nfunction sessionFor(root: string): ByteHashSession {\n const key = path.resolve(root);\n let session = sessions.get(key);\n if (!session) {\n session = loadSession(key);\n sessions.set(key, session);\n }\n return session;\n}\n\nfunction matches(entry: ByteHashEntry | undefined, stat: fs.BigIntStats): entry is ByteHashEntry {\n return (\n entry !== undefined &&\n BigInt(entry.size) === stat.size &&\n entry.mtimeNs === String(stat.mtimeNs) &&\n entry.ctimeNs === String(stat.ctimeNs) &&\n entry.ino === String(stat.ino)\n );\n}\n\nfunction lstat(file: string): fs.BigIntStats | undefined {\n try {\n return fs.lstatSync(file, { bigint: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\n/**\n * `hashFile` through the workspace's byte-hash cache: a regular file whose size, mtime, ctime and\n * inode equal a trusted entry returns the stored hash without reading its bytes.\n */\nexport function hashWorkspaceFile(root: string, relative: string, absolute: string): BlobContent | undefined {\n const session = sessionFor(root);\n const before = lstat(absolute);\n const entry = session.entries.get(relative);\n if (before?.isFile() && matches(entry, before)) return { sha256: entry.sha256, size: entry.size };\n // The racy rule measures the file against the moment hashing began, never the moment it ended.\n const started = nowNs();\n const content = hashFile(absolute);\n const after = content ? lstat(absolute) : undefined;\n const recorded =\n content && before?.isFile()\n ? {\n sha256: content.sha256,\n size: content.size,\n mtimeNs: String(before.mtimeNs),\n ctimeNs: String(before.ctimeNs),\n ino: String(before.ino),\n }\n : undefined;\n if (recorded && after && matches(recorded, after) && before!.mtimeNs < started - RACY_WINDOW_NS) {\n session.entries.set(relative, recorded);\n session.changed = true;\n } else if (session.entries.delete(relative)) session.changed = true;\n return content;\n}\n\n/**\n * The cache to save with the state: this command's entries over the persisted ones, keeping only\n * paths whose file still has the recorded size, mtime, ctime and inode.\n */\nexport function persistableByteHashes(\n root: string,\n persisted: Readonly<Record<string, ByteHashEntry>> | undefined,\n): Record<string, ByteHashEntry> | undefined {\n const session = sessions.get(path.resolve(root));\n const candidates = session ? Object.fromEntries(session.entries) : { ...(persisted ?? {}) };\n const kept = Object.entries(candidates)\n .filter(([relative, entry]) => {\n const stat = lstat(path.join(root, ...relative.split('/')));\n return stat?.isFile() === true && matches(entry, stat);\n })\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return kept.length ? Object.fromEntries(kept) : undefined;\n}\n\n/** Whether this command learned or dropped a cache entry that the saved state does not hold yet. */\nexport function byteHashesChanged(root: string): boolean {\n return sessions.get(path.resolve(root))?.changed === true;\n}\n\n/** Forget every in-process cache, as a new process would. For tests. */\nexport function resetByteHashSessions(): void {\n sessions.clear();\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,wBAAyB;AACzB,uBAA0B;AAYnB,MAAM,iBAAiB;AAE9B,MAAM,aAAa,KAAK,KAAK,WAAW,YAAY;AAQpD,MAAM,WAAW,oBAAI,IAA6B;AAElD,MAAM,gBAAgB,MAAM,OAAO,KAAK,IAAI,CAAC,IAAI;AACjD,IAAI,QAAQ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