@habitat-ai/cli 0.5.15 → 0.6.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 +62 -4
- package/dist/application-gZ8XAszE.js +80 -0
- package/dist/application.js +2 -18
- package/dist/cli-hhbbymEz.js +4738 -0
- package/dist/cli.js +2 -0
- package/dist/command-DkmTpQvc.js +74 -0
- package/dist/command.d.ts +36 -35
- package/dist/command.js +2 -45
- package/dist/generators/cli-command.js +263 -0
- package/dist/generators/cli-extension.js +192 -0
- package/dist/generators/init.js +20 -20
- package/dist/generators/preset.js +8 -7
- package/dist/generators/remove-hook.js +7 -4
- package/dist/generators/service.js +130 -139
- package/dist/habitat.app-Cl-58zQB.js +16615 -0
- package/dist/habitat.app.js +2 -0
- package/dist/host-BcptPYDL.js +293 -0
- package/dist/host.d.ts +57 -0
- package/dist/host.js +3 -0
- package/dist/index.js +8 -5
- package/dist/initialization-BWDg3bks.js +249 -0
- package/dist/migrations/0-5-7-repository-foundation.js +42 -38
- package/dist/nx-generators-DQDXOkMX.js +44 -0
- package/dist/nx-generators.js +2 -51
- package/dist/nx-plugin.d.ts +4 -1
- package/dist/nx-plugin.js +241 -15
- package/dist/oclif-CJS8CHjO.js +11 -0
- package/dist/oclif.js +3 -0
- package/dist/product-version-Bqc0L8lq.js +18 -0
- package/dist/publish-generator-tree-CgFdcykY.js +14 -0
- package/dist/repository-preset-DYxxe7p3.js +543 -0
- package/dist/verified-writes-Cne-zTxS.js +60 -0
- package/generators/cli-command/schema.json +20 -0
- package/generators/cli-extension/schema.json +20 -0
- package/generators/service/files/AGENTS.md.template +2 -2
- package/generators/service/files/habitat.toml.template +1 -1
- package/generators.json +10 -0
- package/oclif.manifest.json +1094 -27
- package/package.json +72 -8
- package/dist/application.d.ts +0 -14
- package/dist/commands/check.d.ts +0 -15
- package/dist/commands/check.js +0 -32
- package/dist/commands/hook.d.ts +0 -12
- package/dist/commands/hook.js +0 -25
- package/dist/commands/resolve.d.ts +0 -9
- package/dist/commands/resolve.js +0 -15
- package/dist/generators/init.d.ts +0 -3
- package/dist/generators/preset.d.ts +0 -4
- package/dist/generators/remove-hook.d.ts +0 -3
- package/dist/generators/service.d.ts +0 -16
- package/dist/index.d.ts +0 -1
- package/dist/lib/binding.d.ts +0 -10
- package/dist/lib/binding.js +0 -16
- package/dist/lib/output.d.ts +0 -9
- package/dist/lib/output.js +0 -22
- package/dist/migrations/0-5-7-repository-foundation.d.ts +0 -3
- package/dist/nx/initialization.d.ts +0 -62
- package/dist/nx/initialization.js +0 -265
- package/dist/nx/projection.d.ts +0 -29
- package/dist/nx/projection.js +0 -308
- package/dist/nx/repository-preset.d.ts +0 -22
- package/dist/nx/repository-preset.js +0 -596
- package/dist/nx-generators.d.ts +0 -42
- package/dist/product-version.d.ts +0 -2
- package/dist/product-version.js +0 -15
|
@@ -0,0 +1,4738 @@
|
|
|
1
|
+
import { A as FilesystemRuntimeResource, C as SourceInventoryPathSchema, D as RuleEvaluationRequestSchema, E as MAX_RULE_EVALUATION_FAILURE_DETAIL, O as SourceInventoryRuntimeResource, S as ObserveSourceInventoryInputSchema, _ as CodexNativeAgentProviderRuntimeResource, a as MaterializeRemoteInputSchema, b as MAX_SOURCE_INVENTORY_FAILURE_DETAIL, c as CanonicalGitRepositoryUrlSchema, d as NativeProviderMarketplaceIdentityInputSchema, f as NativeProviderPluginFilesReadInputSchema, g as ClaudeNativeAgentProviderRuntimeResource, h as VersionedContentRuntimeResource, i as MAX_VERSIONED_CONTENT_FAILURE_DETAIL, k as RuleEvaluationRuntimeResource, l as NativeMarketplaceSourceSchema, m as NativeProviderSessionInputSchema, n as ChildProcessRuntimeResource, o as ObserveRemoteInputSchema, p as NativeProviderPluginSelectorInputSchema, r as AncestryInputSchema, s as VersionedContentTreeEntrySchema, t as habitatApp, u as NativeProviderInventorySchema, v as ContentWorkspaceRuntimeResource, w as SourceInventoryResultSchema, x as MAX_SOURCE_INVENTORY_ROOT_LENGTH, y as AgentPluginPackageOutputRuntimeResource } from "./habitat.app-Cl-58zQB.js";
|
|
2
|
+
import { t as createOclifHost } from "./host-BcptPYDL.js";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { requireResource } from "@habitat-ai/sdk/runtime/resources";
|
|
5
|
+
import { RuntimeSchema } from "@habitat-ai/sdk/runtime/schema";
|
|
6
|
+
import { Cause, Context, Effect, Equal, Exit, FileSystem, Layer, Option, Path, Random, Semaphore, Stream } from "effect";
|
|
7
|
+
import { ReadonlyObject, Refine, Type } from "typebox";
|
|
8
|
+
import Schema, { Validator } from "typebox/schema";
|
|
9
|
+
import { Value } from "typebox/value";
|
|
10
|
+
import { defineEntrypoint, defineProcessCatalog, startApp } from "@habitat-ai/sdk/app";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
|
13
|
+
import { TelemetryRuntimeResource, defineOpenTelemetryNodeRuntimeProvider } from "@habitat-ai/sdk/telemetry";
|
|
14
|
+
import { defineRuntimeProvider } from "@habitat-ai/sdk/runtime/providers";
|
|
15
|
+
import { providerFx } from "@habitat-ai/sdk/runtime/providers/effect";
|
|
16
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
17
|
+
import { NodeChildProcessSpawner, NodeServices } from "@effect/platform-node";
|
|
18
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
19
|
+
import { defineRuntimeProfile, providerSelection } from "@habitat-ai/sdk/runtime/profiles";
|
|
20
|
+
//#region \0rolldown/runtime.js
|
|
21
|
+
var __create = Object.create;
|
|
22
|
+
var __defProp = Object.defineProperty;
|
|
23
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
24
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
25
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
26
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
27
|
+
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
28
|
+
var __copyProps = (to, from, except, desc) => {
|
|
29
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
30
|
+
key = keys[i];
|
|
31
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
32
|
+
get: ((k) => from[k]).bind(null, key),
|
|
33
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return to;
|
|
37
|
+
};
|
|
38
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
39
|
+
value: mod,
|
|
40
|
+
enumerable: true
|
|
41
|
+
}) : target, mod));
|
|
42
|
+
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region runtime/processes.ts
|
|
45
|
+
const processes = defineProcessCatalog({ cli: {
|
|
46
|
+
id: "cli",
|
|
47
|
+
roles: ["cli"],
|
|
48
|
+
harness: "habitat.oclif",
|
|
49
|
+
resourceRequirements: [requireResource({
|
|
50
|
+
resource: TelemetryRuntimeResource,
|
|
51
|
+
reason: "Native CLI instrumentation"
|
|
52
|
+
})]
|
|
53
|
+
} });
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region ../../node_modules/.bun/buffer-crc32@1.0.0/node_modules/buffer-crc32/dist/index.cjs
|
|
56
|
+
var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
57
|
+
function getDefaultExportFromCjs(x) {
|
|
58
|
+
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
|
|
59
|
+
}
|
|
60
|
+
const CRC_TABLE = new Int32Array([
|
|
61
|
+
0,
|
|
62
|
+
1996959894,
|
|
63
|
+
3993919788,
|
|
64
|
+
2567524794,
|
|
65
|
+
124634137,
|
|
66
|
+
1886057615,
|
|
67
|
+
3915621685,
|
|
68
|
+
2657392035,
|
|
69
|
+
249268274,
|
|
70
|
+
2044508324,
|
|
71
|
+
3772115230,
|
|
72
|
+
2547177864,
|
|
73
|
+
162941995,
|
|
74
|
+
2125561021,
|
|
75
|
+
3887607047,
|
|
76
|
+
2428444049,
|
|
77
|
+
498536548,
|
|
78
|
+
1789927666,
|
|
79
|
+
4089016648,
|
|
80
|
+
2227061214,
|
|
81
|
+
450548861,
|
|
82
|
+
1843258603,
|
|
83
|
+
4107580753,
|
|
84
|
+
2211677639,
|
|
85
|
+
325883990,
|
|
86
|
+
1684777152,
|
|
87
|
+
4251122042,
|
|
88
|
+
2321926636,
|
|
89
|
+
335633487,
|
|
90
|
+
1661365465,
|
|
91
|
+
4195302755,
|
|
92
|
+
2366115317,
|
|
93
|
+
997073096,
|
|
94
|
+
1281953886,
|
|
95
|
+
3579855332,
|
|
96
|
+
2724688242,
|
|
97
|
+
1006888145,
|
|
98
|
+
1258607687,
|
|
99
|
+
3524101629,
|
|
100
|
+
2768942443,
|
|
101
|
+
901097722,
|
|
102
|
+
1119000684,
|
|
103
|
+
3686517206,
|
|
104
|
+
2898065728,
|
|
105
|
+
853044451,
|
|
106
|
+
1172266101,
|
|
107
|
+
3705015759,
|
|
108
|
+
2882616665,
|
|
109
|
+
651767980,
|
|
110
|
+
1373503546,
|
|
111
|
+
3369554304,
|
|
112
|
+
3218104598,
|
|
113
|
+
565507253,
|
|
114
|
+
1454621731,
|
|
115
|
+
3485111705,
|
|
116
|
+
3099436303,
|
|
117
|
+
671266974,
|
|
118
|
+
1594198024,
|
|
119
|
+
3322730930,
|
|
120
|
+
2970347812,
|
|
121
|
+
795835527,
|
|
122
|
+
1483230225,
|
|
123
|
+
3244367275,
|
|
124
|
+
3060149565,
|
|
125
|
+
1994146192,
|
|
126
|
+
31158534,
|
|
127
|
+
2563907772,
|
|
128
|
+
4023717930,
|
|
129
|
+
1907459465,
|
|
130
|
+
112637215,
|
|
131
|
+
2680153253,
|
|
132
|
+
3904427059,
|
|
133
|
+
2013776290,
|
|
134
|
+
251722036,
|
|
135
|
+
2517215374,
|
|
136
|
+
3775830040,
|
|
137
|
+
2137656763,
|
|
138
|
+
141376813,
|
|
139
|
+
2439277719,
|
|
140
|
+
3865271297,
|
|
141
|
+
1802195444,
|
|
142
|
+
476864866,
|
|
143
|
+
2238001368,
|
|
144
|
+
4066508878,
|
|
145
|
+
1812370925,
|
|
146
|
+
453092731,
|
|
147
|
+
2181625025,
|
|
148
|
+
4111451223,
|
|
149
|
+
1706088902,
|
|
150
|
+
314042704,
|
|
151
|
+
2344532202,
|
|
152
|
+
4240017532,
|
|
153
|
+
1658658271,
|
|
154
|
+
366619977,
|
|
155
|
+
2362670323,
|
|
156
|
+
4224994405,
|
|
157
|
+
1303535960,
|
|
158
|
+
984961486,
|
|
159
|
+
2747007092,
|
|
160
|
+
3569037538,
|
|
161
|
+
1256170817,
|
|
162
|
+
1037604311,
|
|
163
|
+
2765210733,
|
|
164
|
+
3554079995,
|
|
165
|
+
1131014506,
|
|
166
|
+
879679996,
|
|
167
|
+
2909243462,
|
|
168
|
+
3663771856,
|
|
169
|
+
1141124467,
|
|
170
|
+
855842277,
|
|
171
|
+
2852801631,
|
|
172
|
+
3708648649,
|
|
173
|
+
1342533948,
|
|
174
|
+
654459306,
|
|
175
|
+
3188396048,
|
|
176
|
+
3373015174,
|
|
177
|
+
1466479909,
|
|
178
|
+
544179635,
|
|
179
|
+
3110523913,
|
|
180
|
+
3462522015,
|
|
181
|
+
1591671054,
|
|
182
|
+
702138776,
|
|
183
|
+
2966460450,
|
|
184
|
+
3352799412,
|
|
185
|
+
1504918807,
|
|
186
|
+
783551873,
|
|
187
|
+
3082640443,
|
|
188
|
+
3233442989,
|
|
189
|
+
3988292384,
|
|
190
|
+
2596254646,
|
|
191
|
+
62317068,
|
|
192
|
+
1957810842,
|
|
193
|
+
3939845945,
|
|
194
|
+
2647816111,
|
|
195
|
+
81470997,
|
|
196
|
+
1943803523,
|
|
197
|
+
3814918930,
|
|
198
|
+
2489596804,
|
|
199
|
+
225274430,
|
|
200
|
+
2053790376,
|
|
201
|
+
3826175755,
|
|
202
|
+
2466906013,
|
|
203
|
+
167816743,
|
|
204
|
+
2097651377,
|
|
205
|
+
4027552580,
|
|
206
|
+
2265490386,
|
|
207
|
+
503444072,
|
|
208
|
+
1762050814,
|
|
209
|
+
4150417245,
|
|
210
|
+
2154129355,
|
|
211
|
+
426522225,
|
|
212
|
+
1852507879,
|
|
213
|
+
4275313526,
|
|
214
|
+
2312317920,
|
|
215
|
+
282753626,
|
|
216
|
+
1742555852,
|
|
217
|
+
4189708143,
|
|
218
|
+
2394877945,
|
|
219
|
+
397917763,
|
|
220
|
+
1622183637,
|
|
221
|
+
3604390888,
|
|
222
|
+
2714866558,
|
|
223
|
+
953729732,
|
|
224
|
+
1340076626,
|
|
225
|
+
3518719985,
|
|
226
|
+
2797360999,
|
|
227
|
+
1068828381,
|
|
228
|
+
1219638859,
|
|
229
|
+
3624741850,
|
|
230
|
+
2936675148,
|
|
231
|
+
906185462,
|
|
232
|
+
1090812512,
|
|
233
|
+
3747672003,
|
|
234
|
+
2825379669,
|
|
235
|
+
829329135,
|
|
236
|
+
1181335161,
|
|
237
|
+
3412177804,
|
|
238
|
+
3160834842,
|
|
239
|
+
628085408,
|
|
240
|
+
1382605366,
|
|
241
|
+
3423369109,
|
|
242
|
+
3138078467,
|
|
243
|
+
570562233,
|
|
244
|
+
1426400815,
|
|
245
|
+
3317316542,
|
|
246
|
+
2998733608,
|
|
247
|
+
733239954,
|
|
248
|
+
1555261956,
|
|
249
|
+
3268935591,
|
|
250
|
+
3050360625,
|
|
251
|
+
752459403,
|
|
252
|
+
1541320221,
|
|
253
|
+
2607071920,
|
|
254
|
+
3965973030,
|
|
255
|
+
1969922972,
|
|
256
|
+
40735498,
|
|
257
|
+
2617837225,
|
|
258
|
+
3943577151,
|
|
259
|
+
1913087877,
|
|
260
|
+
83908371,
|
|
261
|
+
2512341634,
|
|
262
|
+
3803740692,
|
|
263
|
+
2075208622,
|
|
264
|
+
213261112,
|
|
265
|
+
2463272603,
|
|
266
|
+
3855990285,
|
|
267
|
+
2094854071,
|
|
268
|
+
198958881,
|
|
269
|
+
2262029012,
|
|
270
|
+
4057260610,
|
|
271
|
+
1759359992,
|
|
272
|
+
534414190,
|
|
273
|
+
2176718541,
|
|
274
|
+
4139329115,
|
|
275
|
+
1873836001,
|
|
276
|
+
414664567,
|
|
277
|
+
2282248934,
|
|
278
|
+
4279200368,
|
|
279
|
+
1711684554,
|
|
280
|
+
285281116,
|
|
281
|
+
2405801727,
|
|
282
|
+
4167216745,
|
|
283
|
+
1634467795,
|
|
284
|
+
376229701,
|
|
285
|
+
2685067896,
|
|
286
|
+
3608007406,
|
|
287
|
+
1308918612,
|
|
288
|
+
956543938,
|
|
289
|
+
2808555105,
|
|
290
|
+
3495958263,
|
|
291
|
+
1231636301,
|
|
292
|
+
1047427035,
|
|
293
|
+
2932959818,
|
|
294
|
+
3654703836,
|
|
295
|
+
1088359270,
|
|
296
|
+
936918e3,
|
|
297
|
+
2847714899,
|
|
298
|
+
3736837829,
|
|
299
|
+
1202900863,
|
|
300
|
+
817233897,
|
|
301
|
+
3183342108,
|
|
302
|
+
3401237130,
|
|
303
|
+
1404277552,
|
|
304
|
+
615818150,
|
|
305
|
+
3134207493,
|
|
306
|
+
3453421203,
|
|
307
|
+
1423857449,
|
|
308
|
+
601450431,
|
|
309
|
+
3009837614,
|
|
310
|
+
3294710456,
|
|
311
|
+
1567103746,
|
|
312
|
+
711928724,
|
|
313
|
+
3020668471,
|
|
314
|
+
3272380065,
|
|
315
|
+
1510334235,
|
|
316
|
+
755167117
|
|
317
|
+
]);
|
|
318
|
+
function ensureBuffer(input) {
|
|
319
|
+
if (Buffer.isBuffer(input)) return input;
|
|
320
|
+
if (typeof input === "number") return Buffer.alloc(input);
|
|
321
|
+
else if (typeof input === "string") return Buffer.from(input);
|
|
322
|
+
else throw new Error("input must be buffer, number, or string, received " + typeof input);
|
|
323
|
+
}
|
|
324
|
+
function bufferizeInt(num) {
|
|
325
|
+
const tmp = ensureBuffer(4);
|
|
326
|
+
tmp.writeInt32BE(num, 0);
|
|
327
|
+
return tmp;
|
|
328
|
+
}
|
|
329
|
+
function _crc32(buf, previous) {
|
|
330
|
+
buf = ensureBuffer(buf);
|
|
331
|
+
if (Buffer.isBuffer(previous)) previous = previous.readUInt32BE(0);
|
|
332
|
+
let crc = ~~previous ^ -1;
|
|
333
|
+
for (var n = 0; n < buf.length; n++) crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8;
|
|
334
|
+
return crc ^ -1;
|
|
335
|
+
}
|
|
336
|
+
function crc32() {
|
|
337
|
+
return bufferizeInt(_crc32.apply(null, arguments));
|
|
338
|
+
}
|
|
339
|
+
crc32.signed = function() {
|
|
340
|
+
return _crc32.apply(null, arguments);
|
|
341
|
+
};
|
|
342
|
+
crc32.unsigned = function() {
|
|
343
|
+
return _crc32.apply(null, arguments) >>> 0;
|
|
344
|
+
};
|
|
345
|
+
module.exports = /* @__PURE__ */ getDefaultExportFromCjs(crc32);
|
|
346
|
+
}));
|
|
347
|
+
//#endregion
|
|
348
|
+
//#region ../../resources/agent-plugin-package-output/dist/providers/cowork-v1-effect-platform-node/index.js
|
|
349
|
+
var import_yazl = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
|
|
350
|
+
var fs = __require("fs");
|
|
351
|
+
var Transform = __require("stream").Transform;
|
|
352
|
+
var PassThrough = __require("stream").PassThrough;
|
|
353
|
+
var zlib = __require("zlib");
|
|
354
|
+
var util = __require("util");
|
|
355
|
+
var EventEmitter = __require("events").EventEmitter;
|
|
356
|
+
var errorMonitor = __require("events").errorMonitor;
|
|
357
|
+
var crc32 = require_dist();
|
|
358
|
+
exports.ZipFile = ZipFile;
|
|
359
|
+
util.inherits(ZipFile, EventEmitter);
|
|
360
|
+
function ZipFile() {
|
|
361
|
+
this.outputStream = new PassThrough();
|
|
362
|
+
this.entries = [];
|
|
363
|
+
this.outputStreamCursor = 0;
|
|
364
|
+
this.ended = false;
|
|
365
|
+
this.allDone = false;
|
|
366
|
+
this.forceZip64Eocd = false;
|
|
367
|
+
this.errored = false;
|
|
368
|
+
this.on(errorMonitor, function() {
|
|
369
|
+
this.errored = true;
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
ZipFile.prototype.addFile = function(realPath, metadataPath, options) {
|
|
373
|
+
var self = this;
|
|
374
|
+
metadataPath = validateMetadataPath(metadataPath, false);
|
|
375
|
+
if (options == null) options = {};
|
|
376
|
+
if (shouldIgnoreAdding(self)) return;
|
|
377
|
+
var entry = new Entry(metadataPath, false, options);
|
|
378
|
+
self.entries.push(entry);
|
|
379
|
+
fs.stat(realPath, function(err, stats) {
|
|
380
|
+
if (err) return self.emit("error", err);
|
|
381
|
+
if (!stats.isFile()) return self.emit("error", /* @__PURE__ */ new Error("not a file: " + realPath));
|
|
382
|
+
entry.uncompressedSize = stats.size;
|
|
383
|
+
if (options.mtime == null) entry.setLastModDate(stats.mtime);
|
|
384
|
+
if (options.mode == null) entry.setFileAttributesMode(stats.mode);
|
|
385
|
+
entry.setFileDataPumpFunction(function() {
|
|
386
|
+
var readStream = fs.createReadStream(realPath);
|
|
387
|
+
entry.state = Entry.FILE_DATA_IN_PROGRESS;
|
|
388
|
+
readStream.on("error", function(err) {
|
|
389
|
+
self.emit("error", err);
|
|
390
|
+
});
|
|
391
|
+
pumpFileDataReadStream(self, entry, readStream);
|
|
392
|
+
});
|
|
393
|
+
pumpEntries(self);
|
|
394
|
+
});
|
|
395
|
+
};
|
|
396
|
+
ZipFile.prototype.addReadStream = function(readStream, metadataPath, options) {
|
|
397
|
+
this.addReadStreamLazy(metadataPath, options, function(cb) {
|
|
398
|
+
cb(null, readStream);
|
|
399
|
+
});
|
|
400
|
+
};
|
|
401
|
+
ZipFile.prototype.addReadStreamLazy = function(metadataPath, options, getReadStreamFunction) {
|
|
402
|
+
var self = this;
|
|
403
|
+
if (typeof options === "function") {
|
|
404
|
+
getReadStreamFunction = options;
|
|
405
|
+
options = null;
|
|
406
|
+
}
|
|
407
|
+
if (options == null) options = {};
|
|
408
|
+
metadataPath = validateMetadataPath(metadataPath, false);
|
|
409
|
+
if (shouldIgnoreAdding(self)) return;
|
|
410
|
+
var entry = new Entry(metadataPath, false, options);
|
|
411
|
+
self.entries.push(entry);
|
|
412
|
+
entry.setFileDataPumpFunction(function() {
|
|
413
|
+
entry.state = Entry.FILE_DATA_IN_PROGRESS;
|
|
414
|
+
getReadStreamFunction(function(err, readStream) {
|
|
415
|
+
if (err) return self.emit("error", err);
|
|
416
|
+
pumpFileDataReadStream(self, entry, readStream);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
pumpEntries(self);
|
|
420
|
+
};
|
|
421
|
+
ZipFile.prototype.addBuffer = function(buffer, metadataPath, options) {
|
|
422
|
+
var self = this;
|
|
423
|
+
metadataPath = validateMetadataPath(metadataPath, false);
|
|
424
|
+
if (buffer.length > 1073741823) throw new Error("buffer too large: " + buffer.length + " > 1073741823");
|
|
425
|
+
if (options == null) options = {};
|
|
426
|
+
if (options.size != null) throw new Error("options.size not allowed");
|
|
427
|
+
if (shouldIgnoreAdding(self)) return;
|
|
428
|
+
var entry = new Entry(metadataPath, false, options);
|
|
429
|
+
entry.uncompressedSize = buffer.length;
|
|
430
|
+
entry.crc32 = crc32.unsigned(buffer);
|
|
431
|
+
entry.crcAndFileSizeKnown = true;
|
|
432
|
+
self.entries.push(entry);
|
|
433
|
+
if (entry.compressionLevel === 0) setCompressedBuffer(buffer);
|
|
434
|
+
else zlib.deflateRaw(buffer, { level: entry.compressionLevel }, function(err, compressedBuffer) {
|
|
435
|
+
setCompressedBuffer(compressedBuffer);
|
|
436
|
+
});
|
|
437
|
+
function setCompressedBuffer(compressedBuffer) {
|
|
438
|
+
entry.compressedSize = compressedBuffer.length;
|
|
439
|
+
entry.setFileDataPumpFunction(function() {
|
|
440
|
+
writeToOutputStream(self, compressedBuffer);
|
|
441
|
+
writeToOutputStream(self, entry.getDataDescriptor());
|
|
442
|
+
entry.state = Entry.FILE_DATA_DONE;
|
|
443
|
+
setImmediate(function() {
|
|
444
|
+
pumpEntries(self);
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
pumpEntries(self);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
ZipFile.prototype.addEmptyDirectory = function(metadataPath, options) {
|
|
451
|
+
var self = this;
|
|
452
|
+
metadataPath = validateMetadataPath(metadataPath, true);
|
|
453
|
+
if (options == null) options = {};
|
|
454
|
+
if (options.size != null) throw new Error("options.size not allowed");
|
|
455
|
+
if (options.compress != null) throw new Error("options.compress not allowed");
|
|
456
|
+
if (options.compressionLevel != null) throw new Error("options.compressionLevel not allowed");
|
|
457
|
+
if (shouldIgnoreAdding(self)) return;
|
|
458
|
+
var entry = new Entry(metadataPath, true, options);
|
|
459
|
+
self.entries.push(entry);
|
|
460
|
+
entry.setFileDataPumpFunction(function() {
|
|
461
|
+
writeToOutputStream(self, entry.getDataDescriptor());
|
|
462
|
+
entry.state = Entry.FILE_DATA_DONE;
|
|
463
|
+
pumpEntries(self);
|
|
464
|
+
});
|
|
465
|
+
pumpEntries(self);
|
|
466
|
+
};
|
|
467
|
+
var eocdrSignatureBuffer = bufferFrom([
|
|
468
|
+
80,
|
|
469
|
+
75,
|
|
470
|
+
5,
|
|
471
|
+
6
|
|
472
|
+
]);
|
|
473
|
+
ZipFile.prototype.end = function(options, calculatedTotalSizeCallback) {
|
|
474
|
+
if (typeof options === "function") {
|
|
475
|
+
calculatedTotalSizeCallback = options;
|
|
476
|
+
options = null;
|
|
477
|
+
}
|
|
478
|
+
if (options == null) options = {};
|
|
479
|
+
if (this.ended) return;
|
|
480
|
+
this.ended = true;
|
|
481
|
+
if (this.errored) return;
|
|
482
|
+
this.calculatedTotalSizeCallback = calculatedTotalSizeCallback;
|
|
483
|
+
this.forceZip64Eocd = !!options.forceZip64Format;
|
|
484
|
+
if (options.comment) {
|
|
485
|
+
if (typeof options.comment === "string") this.comment = encodeCp437(options.comment);
|
|
486
|
+
else this.comment = options.comment;
|
|
487
|
+
if (this.comment.length > 65535) throw new Error("comment is too large");
|
|
488
|
+
if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature");
|
|
489
|
+
} else this.comment = EMPTY_BUFFER;
|
|
490
|
+
pumpEntries(this);
|
|
491
|
+
};
|
|
492
|
+
function writeToOutputStream(self, buffer) {
|
|
493
|
+
self.outputStream.write(buffer);
|
|
494
|
+
self.outputStreamCursor += buffer.length;
|
|
495
|
+
}
|
|
496
|
+
function pumpFileDataReadStream(self, entry, readStream) {
|
|
497
|
+
var crc32Watcher = new Crc32Watcher();
|
|
498
|
+
var uncompressedSizeCounter = new ByteCounter();
|
|
499
|
+
var compressor = entry.compressionLevel !== 0 ? new zlib.DeflateRaw({ level: entry.compressionLevel }) : new PassThrough();
|
|
500
|
+
var compressedSizeCounter = new ByteCounter();
|
|
501
|
+
readStream.pipe(crc32Watcher).pipe(uncompressedSizeCounter).pipe(compressor).pipe(compressedSizeCounter).pipe(self.outputStream, { end: false });
|
|
502
|
+
compressedSizeCounter.on("end", function() {
|
|
503
|
+
entry.crc32 = crc32Watcher.crc32;
|
|
504
|
+
if (entry.uncompressedSize == null) entry.uncompressedSize = uncompressedSizeCounter.byteCount;
|
|
505
|
+
else if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", /* @__PURE__ */ new Error("file data stream has unexpected number of bytes"));
|
|
506
|
+
entry.compressedSize = compressedSizeCounter.byteCount;
|
|
507
|
+
self.outputStreamCursor += entry.compressedSize;
|
|
508
|
+
writeToOutputStream(self, entry.getDataDescriptor());
|
|
509
|
+
entry.state = Entry.FILE_DATA_DONE;
|
|
510
|
+
pumpEntries(self);
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
function determineCompressionLevel(options) {
|
|
514
|
+
if (options.compress != null && options.compressionLevel != null) {
|
|
515
|
+
if (!!options.compress !== !!options.compressionLevel) throw new Error("conflicting settings for compress and compressionLevel");
|
|
516
|
+
}
|
|
517
|
+
if (options.compressionLevel != null) return options.compressionLevel;
|
|
518
|
+
if (options.compress === false) return 0;
|
|
519
|
+
return 6;
|
|
520
|
+
}
|
|
521
|
+
function pumpEntries(self) {
|
|
522
|
+
if (self.allDone || self.errored) return;
|
|
523
|
+
if (self.ended && self.calculatedTotalSizeCallback != null) {
|
|
524
|
+
var calculatedTotalSize = calculateTotalSize(self);
|
|
525
|
+
if (calculatedTotalSize != null) {
|
|
526
|
+
self.calculatedTotalSizeCallback(calculatedTotalSize);
|
|
527
|
+
self.calculatedTotalSizeCallback = null;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
var entry = getFirstNotDoneEntry();
|
|
531
|
+
function getFirstNotDoneEntry() {
|
|
532
|
+
for (var i = 0; i < self.entries.length; i++) {
|
|
533
|
+
var entry = self.entries[i];
|
|
534
|
+
if (entry.state < Entry.FILE_DATA_DONE) return entry;
|
|
535
|
+
}
|
|
536
|
+
return null;
|
|
537
|
+
}
|
|
538
|
+
if (entry != null) {
|
|
539
|
+
if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return;
|
|
540
|
+
if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return;
|
|
541
|
+
entry.relativeOffsetOfLocalHeader = self.outputStreamCursor;
|
|
542
|
+
writeToOutputStream(self, entry.getLocalFileHeader());
|
|
543
|
+
entry.doFileDataPump();
|
|
544
|
+
} else if (self.ended) {
|
|
545
|
+
self.offsetOfStartOfCentralDirectory = self.outputStreamCursor;
|
|
546
|
+
self.entries.forEach(function(entry) {
|
|
547
|
+
writeToOutputStream(self, entry.getCentralDirectoryRecord());
|
|
548
|
+
});
|
|
549
|
+
writeToOutputStream(self, getEndOfCentralDirectoryRecord(self));
|
|
550
|
+
self.outputStream.end();
|
|
551
|
+
self.allDone = true;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function calculateTotalSize(self) {
|
|
555
|
+
var pretendOutputCursor = 0;
|
|
556
|
+
var centralDirectorySize = 0;
|
|
557
|
+
for (var i = 0; i < self.entries.length; i++) {
|
|
558
|
+
var entry = self.entries[i];
|
|
559
|
+
if (entry.compressionLevel !== 0) return -1;
|
|
560
|
+
if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) {
|
|
561
|
+
if (entry.uncompressedSize == null) return -1;
|
|
562
|
+
} else if (entry.uncompressedSize == null) return null;
|
|
563
|
+
entry.relativeOffsetOfLocalHeader = pretendOutputCursor;
|
|
564
|
+
var useZip64Format = entry.useZip64Format();
|
|
565
|
+
pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length;
|
|
566
|
+
pretendOutputCursor += entry.uncompressedSize;
|
|
567
|
+
if (!entry.crcAndFileSizeKnown) {
|
|
568
|
+
if (useZip64Format) pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE;
|
|
569
|
+
else pretendOutputCursor += DATA_DESCRIPTOR_SIZE;
|
|
570
|
+
}
|
|
571
|
+
centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length;
|
|
572
|
+
if (!entry.forceDosTimestamp) centralDirectorySize += INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE;
|
|
573
|
+
if (useZip64Format) centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE;
|
|
574
|
+
}
|
|
575
|
+
var endOfCentralDirectorySize = 0;
|
|
576
|
+
if (self.forceZip64Eocd || self.entries.length >= 65535 || centralDirectorySize >= 65535 || pretendOutputCursor >= 4294967295) endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE;
|
|
577
|
+
endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length;
|
|
578
|
+
return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize;
|
|
579
|
+
}
|
|
580
|
+
function shouldIgnoreAdding(self) {
|
|
581
|
+
if (self.ended) throw new Error("cannot add entries after calling end()");
|
|
582
|
+
if (self.errored) return true;
|
|
583
|
+
return false;
|
|
584
|
+
}
|
|
585
|
+
var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56;
|
|
586
|
+
var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20;
|
|
587
|
+
var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22;
|
|
588
|
+
function getEndOfCentralDirectoryRecord(self, actuallyJustTellMeHowLongItWouldBe) {
|
|
589
|
+
var needZip64Format = false;
|
|
590
|
+
var normalEntriesLength = self.entries.length;
|
|
591
|
+
if (self.forceZip64Eocd || self.entries.length >= 65535) {
|
|
592
|
+
normalEntriesLength = 65535;
|
|
593
|
+
needZip64Format = true;
|
|
594
|
+
}
|
|
595
|
+
var sizeOfCentralDirectory = self.outputStreamCursor - self.offsetOfStartOfCentralDirectory;
|
|
596
|
+
var normalSizeOfCentralDirectory = sizeOfCentralDirectory;
|
|
597
|
+
if (self.forceZip64Eocd || sizeOfCentralDirectory >= 4294967295) {
|
|
598
|
+
normalSizeOfCentralDirectory = 4294967295;
|
|
599
|
+
needZip64Format = true;
|
|
600
|
+
}
|
|
601
|
+
var normalOffsetOfStartOfCentralDirectory = self.offsetOfStartOfCentralDirectory;
|
|
602
|
+
if (self.forceZip64Eocd || self.offsetOfStartOfCentralDirectory >= 4294967295) {
|
|
603
|
+
normalOffsetOfStartOfCentralDirectory = 4294967295;
|
|
604
|
+
needZip64Format = true;
|
|
605
|
+
}
|
|
606
|
+
if (actuallyJustTellMeHowLongItWouldBe) {
|
|
607
|
+
if (needZip64Format) return ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE + END_OF_CENTRAL_DIRECTORY_RECORD_SIZE;
|
|
608
|
+
else return END_OF_CENTRAL_DIRECTORY_RECORD_SIZE;
|
|
609
|
+
}
|
|
610
|
+
var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length);
|
|
611
|
+
eocdrBuffer.writeUInt32LE(101010256, 0);
|
|
612
|
+
eocdrBuffer.writeUInt16LE(0, 4);
|
|
613
|
+
eocdrBuffer.writeUInt16LE(0, 6);
|
|
614
|
+
eocdrBuffer.writeUInt16LE(normalEntriesLength, 8);
|
|
615
|
+
eocdrBuffer.writeUInt16LE(normalEntriesLength, 10);
|
|
616
|
+
eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12);
|
|
617
|
+
eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16);
|
|
618
|
+
eocdrBuffer.writeUInt16LE(self.comment.length, 20);
|
|
619
|
+
self.comment.copy(eocdrBuffer, 22);
|
|
620
|
+
if (!needZip64Format) return eocdrBuffer;
|
|
621
|
+
var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE);
|
|
622
|
+
zip64EocdrBuffer.writeUInt32LE(101075792, 0);
|
|
623
|
+
writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4);
|
|
624
|
+
zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12);
|
|
625
|
+
zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14);
|
|
626
|
+
zip64EocdrBuffer.writeUInt32LE(0, 16);
|
|
627
|
+
zip64EocdrBuffer.writeUInt32LE(0, 20);
|
|
628
|
+
writeUInt64LE(zip64EocdrBuffer, self.entries.length, 24);
|
|
629
|
+
writeUInt64LE(zip64EocdrBuffer, self.entries.length, 32);
|
|
630
|
+
writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40);
|
|
631
|
+
writeUInt64LE(zip64EocdrBuffer, self.offsetOfStartOfCentralDirectory, 48);
|
|
632
|
+
var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE);
|
|
633
|
+
zip64EocdlBuffer.writeUInt32LE(117853008, 0);
|
|
634
|
+
zip64EocdlBuffer.writeUInt32LE(0, 4);
|
|
635
|
+
writeUInt64LE(zip64EocdlBuffer, self.outputStreamCursor, 8);
|
|
636
|
+
zip64EocdlBuffer.writeUInt32LE(1, 16);
|
|
637
|
+
return Buffer.concat([
|
|
638
|
+
zip64EocdrBuffer,
|
|
639
|
+
zip64EocdlBuffer,
|
|
640
|
+
eocdrBuffer
|
|
641
|
+
]);
|
|
642
|
+
}
|
|
643
|
+
function validateMetadataPath(metadataPath, isDirectory) {
|
|
644
|
+
if (metadataPath === "") throw new Error("empty metadataPath");
|
|
645
|
+
metadataPath = metadataPath.replace(/\\/g, "/");
|
|
646
|
+
if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath);
|
|
647
|
+
if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath);
|
|
648
|
+
var looksLikeDirectory = /\/$/.test(metadataPath);
|
|
649
|
+
if (isDirectory) {
|
|
650
|
+
if (!looksLikeDirectory) metadataPath += "/";
|
|
651
|
+
} else if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath);
|
|
652
|
+
return metadataPath;
|
|
653
|
+
}
|
|
654
|
+
var EMPTY_BUFFER = bufferAlloc(0);
|
|
655
|
+
function Entry(metadataPath, isDirectory, options) {
|
|
656
|
+
this.utf8FileName = bufferFrom(metadataPath);
|
|
657
|
+
if (this.utf8FileName.length > 65535) throw new Error("utf8 file name too long. " + utf8FileName.length + " > 65535");
|
|
658
|
+
this.isDirectory = isDirectory;
|
|
659
|
+
this.state = Entry.WAITING_FOR_METADATA;
|
|
660
|
+
this.setLastModDate(options.mtime != null ? options.mtime : /* @__PURE__ */ new Date());
|
|
661
|
+
this.forceDosTimestamp = !!options.forceDosTimestamp;
|
|
662
|
+
if (options.mode != null) this.setFileAttributesMode(options.mode);
|
|
663
|
+
else this.setFileAttributesMode(isDirectory ? 16893 : 33204);
|
|
664
|
+
if (isDirectory) {
|
|
665
|
+
this.crcAndFileSizeKnown = true;
|
|
666
|
+
this.crc32 = 0;
|
|
667
|
+
this.uncompressedSize = 0;
|
|
668
|
+
this.compressedSize = 0;
|
|
669
|
+
} else {
|
|
670
|
+
this.crcAndFileSizeKnown = false;
|
|
671
|
+
this.crc32 = null;
|
|
672
|
+
this.uncompressedSize = null;
|
|
673
|
+
this.compressedSize = null;
|
|
674
|
+
if (options.size != null) this.uncompressedSize = options.size;
|
|
675
|
+
}
|
|
676
|
+
if (isDirectory) this.compressionLevel = 0;
|
|
677
|
+
else this.compressionLevel = determineCompressionLevel(options);
|
|
678
|
+
this.forceZip64Format = !!options.forceZip64Format;
|
|
679
|
+
if (options.fileComment) {
|
|
680
|
+
if (typeof options.fileComment === "string") this.fileComment = bufferFrom(options.fileComment, "utf-8");
|
|
681
|
+
else this.fileComment = options.fileComment;
|
|
682
|
+
if (this.fileComment.length > 65535) throw new Error("fileComment is too large");
|
|
683
|
+
} else this.fileComment = EMPTY_BUFFER;
|
|
684
|
+
}
|
|
685
|
+
Entry.WAITING_FOR_METADATA = 0;
|
|
686
|
+
Entry.READY_TO_PUMP_FILE_DATA = 1;
|
|
687
|
+
Entry.FILE_DATA_IN_PROGRESS = 2;
|
|
688
|
+
Entry.FILE_DATA_DONE = 3;
|
|
689
|
+
Entry.prototype.setLastModDate = function(date) {
|
|
690
|
+
this.mtime = date;
|
|
691
|
+
var dosDateTime = dateToDosDateTime(date);
|
|
692
|
+
this.lastModFileTime = dosDateTime.time;
|
|
693
|
+
this.lastModFileDate = dosDateTime.date;
|
|
694
|
+
};
|
|
695
|
+
Entry.prototype.setFileAttributesMode = function(mode) {
|
|
696
|
+
if ((mode & 65535) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= 65535");
|
|
697
|
+
this.externalFileAttributes = mode << 16 >>> 0;
|
|
698
|
+
};
|
|
699
|
+
Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) {
|
|
700
|
+
this.doFileDataPump = doFileDataPump;
|
|
701
|
+
this.state = Entry.READY_TO_PUMP_FILE_DATA;
|
|
702
|
+
};
|
|
703
|
+
Entry.prototype.useZip64Format = function() {
|
|
704
|
+
return this.forceZip64Format || this.uncompressedSize != null && this.uncompressedSize > 4294967294 || this.compressedSize != null && this.compressedSize > 4294967294 || this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 4294967294;
|
|
705
|
+
};
|
|
706
|
+
var LOCAL_FILE_HEADER_FIXED_SIZE = 30;
|
|
707
|
+
var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20;
|
|
708
|
+
var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45;
|
|
709
|
+
var VERSION_MADE_BY = 831;
|
|
710
|
+
var FILE_NAME_IS_UTF8 = 2048;
|
|
711
|
+
var UNKNOWN_CRC32_AND_FILE_SIZES = 8;
|
|
712
|
+
Entry.prototype.getLocalFileHeader = function() {
|
|
713
|
+
var crc32 = 0;
|
|
714
|
+
var compressedSize = 0;
|
|
715
|
+
var uncompressedSize = 0;
|
|
716
|
+
if (this.crcAndFileSizeKnown) {
|
|
717
|
+
crc32 = this.crc32;
|
|
718
|
+
compressedSize = this.compressedSize;
|
|
719
|
+
uncompressedSize = this.uncompressedSize;
|
|
720
|
+
}
|
|
721
|
+
var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE);
|
|
722
|
+
var generalPurposeBitFlag = FILE_NAME_IS_UTF8;
|
|
723
|
+
if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES;
|
|
724
|
+
fixedSizeStuff.writeUInt32LE(67324752, 0);
|
|
725
|
+
fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4);
|
|
726
|
+
fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6);
|
|
727
|
+
fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8);
|
|
728
|
+
fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10);
|
|
729
|
+
fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12);
|
|
730
|
+
fixedSizeStuff.writeUInt32LE(crc32, 14);
|
|
731
|
+
fixedSizeStuff.writeUInt32LE(compressedSize, 18);
|
|
732
|
+
fixedSizeStuff.writeUInt32LE(uncompressedSize, 22);
|
|
733
|
+
fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26);
|
|
734
|
+
fixedSizeStuff.writeUInt16LE(0, 28);
|
|
735
|
+
return Buffer.concat([fixedSizeStuff, this.utf8FileName]);
|
|
736
|
+
};
|
|
737
|
+
var DATA_DESCRIPTOR_SIZE = 16;
|
|
738
|
+
var ZIP64_DATA_DESCRIPTOR_SIZE = 24;
|
|
739
|
+
Entry.prototype.getDataDescriptor = function() {
|
|
740
|
+
if (this.crcAndFileSizeKnown) return EMPTY_BUFFER;
|
|
741
|
+
if (!this.useZip64Format()) {
|
|
742
|
+
var buffer = bufferAlloc(DATA_DESCRIPTOR_SIZE);
|
|
743
|
+
buffer.writeUInt32LE(134695760, 0);
|
|
744
|
+
buffer.writeUInt32LE(this.crc32, 4);
|
|
745
|
+
buffer.writeUInt32LE(this.compressedSize, 8);
|
|
746
|
+
buffer.writeUInt32LE(this.uncompressedSize, 12);
|
|
747
|
+
return buffer;
|
|
748
|
+
} else {
|
|
749
|
+
var buffer = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE);
|
|
750
|
+
buffer.writeUInt32LE(134695760, 0);
|
|
751
|
+
buffer.writeUInt32LE(this.crc32, 4);
|
|
752
|
+
writeUInt64LE(buffer, this.compressedSize, 8);
|
|
753
|
+
writeUInt64LE(buffer, this.uncompressedSize, 16);
|
|
754
|
+
return buffer;
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46;
|
|
758
|
+
var INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE = 9;
|
|
759
|
+
var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28;
|
|
760
|
+
Entry.prototype.getCentralDirectoryRecord = function() {
|
|
761
|
+
var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE);
|
|
762
|
+
var generalPurposeBitFlag = FILE_NAME_IS_UTF8;
|
|
763
|
+
if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES;
|
|
764
|
+
var izutefBuffer = EMPTY_BUFFER;
|
|
765
|
+
if (!this.forceDosTimestamp) {
|
|
766
|
+
izutefBuffer = bufferAlloc(INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE);
|
|
767
|
+
izutefBuffer.writeUInt16LE(21589, 0);
|
|
768
|
+
izutefBuffer.writeUInt16LE(INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE - 4, 2);
|
|
769
|
+
izutefBuffer.writeUInt8(3, 4);
|
|
770
|
+
var timestamp = Math.floor(this.mtime.getTime() / 1e3);
|
|
771
|
+
if (timestamp < -2147483648) timestamp = -2147483648;
|
|
772
|
+
if (timestamp > 2147483647) timestamp = 2147483647;
|
|
773
|
+
izutefBuffer.writeUInt32LE(timestamp, 5);
|
|
774
|
+
}
|
|
775
|
+
var normalCompressedSize = this.compressedSize;
|
|
776
|
+
var normalUncompressedSize = this.uncompressedSize;
|
|
777
|
+
var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader;
|
|
778
|
+
var versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8;
|
|
779
|
+
var zeiefBuffer = EMPTY_BUFFER;
|
|
780
|
+
if (this.useZip64Format()) {
|
|
781
|
+
normalCompressedSize = 4294967295;
|
|
782
|
+
normalUncompressedSize = 4294967295;
|
|
783
|
+
normalRelativeOffsetOfLocalHeader = 4294967295;
|
|
784
|
+
versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64;
|
|
785
|
+
zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE);
|
|
786
|
+
zeiefBuffer.writeUInt16LE(1, 0);
|
|
787
|
+
zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2);
|
|
788
|
+
writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4);
|
|
789
|
+
writeUInt64LE(zeiefBuffer, this.compressedSize, 12);
|
|
790
|
+
writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20);
|
|
791
|
+
}
|
|
792
|
+
fixedSizeStuff.writeUInt32LE(33639248, 0);
|
|
793
|
+
fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4);
|
|
794
|
+
fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6);
|
|
795
|
+
fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8);
|
|
796
|
+
fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10);
|
|
797
|
+
fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12);
|
|
798
|
+
fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14);
|
|
799
|
+
fixedSizeStuff.writeUInt32LE(this.crc32, 16);
|
|
800
|
+
fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20);
|
|
801
|
+
fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24);
|
|
802
|
+
fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28);
|
|
803
|
+
fixedSizeStuff.writeUInt16LE(izutefBuffer.length + zeiefBuffer.length, 30);
|
|
804
|
+
fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32);
|
|
805
|
+
fixedSizeStuff.writeUInt16LE(0, 34);
|
|
806
|
+
fixedSizeStuff.writeUInt16LE(0, 36);
|
|
807
|
+
fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38);
|
|
808
|
+
fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42);
|
|
809
|
+
return Buffer.concat([
|
|
810
|
+
fixedSizeStuff,
|
|
811
|
+
this.utf8FileName,
|
|
812
|
+
izutefBuffer,
|
|
813
|
+
zeiefBuffer,
|
|
814
|
+
this.fileComment
|
|
815
|
+
]);
|
|
816
|
+
};
|
|
817
|
+
Entry.prototype.getCompressionMethod = function() {
|
|
818
|
+
return this.compressionLevel === 0 ? 0 : 8;
|
|
819
|
+
};
|
|
820
|
+
var minDosDate = new Date(1980, 0, 1);
|
|
821
|
+
var maxDosDate = new Date(2107, 11, 31, 23, 59, 58);
|
|
822
|
+
function dateToDosDateTime(jsDate) {
|
|
823
|
+
if (jsDate < minDosDate) jsDate = minDosDate;
|
|
824
|
+
else if (jsDate > maxDosDate) jsDate = maxDosDate;
|
|
825
|
+
var date = 0;
|
|
826
|
+
date |= jsDate.getDate() & 31;
|
|
827
|
+
date |= (jsDate.getMonth() + 1 & 15) << 5;
|
|
828
|
+
date |= (jsDate.getFullYear() - 1980 & 127) << 9;
|
|
829
|
+
var time = 0;
|
|
830
|
+
time |= Math.floor(jsDate.getSeconds() / 2);
|
|
831
|
+
time |= (jsDate.getMinutes() & 63) << 5;
|
|
832
|
+
time |= (jsDate.getHours() & 31) << 11;
|
|
833
|
+
return {
|
|
834
|
+
date,
|
|
835
|
+
time
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
function writeUInt64LE(buffer, n, offset) {
|
|
839
|
+
var high = Math.floor(n / 4294967296);
|
|
840
|
+
var low = n % 4294967296;
|
|
841
|
+
buffer.writeUInt32LE(low, offset);
|
|
842
|
+
buffer.writeUInt32LE(high, offset + 4);
|
|
843
|
+
}
|
|
844
|
+
util.inherits(ByteCounter, Transform);
|
|
845
|
+
function ByteCounter(options) {
|
|
846
|
+
Transform.call(this, options);
|
|
847
|
+
this.byteCount = 0;
|
|
848
|
+
}
|
|
849
|
+
ByteCounter.prototype._transform = function(chunk, encoding, cb) {
|
|
850
|
+
this.byteCount += chunk.length;
|
|
851
|
+
cb(null, chunk);
|
|
852
|
+
};
|
|
853
|
+
util.inherits(Crc32Watcher, Transform);
|
|
854
|
+
function Crc32Watcher(options) {
|
|
855
|
+
Transform.call(this, options);
|
|
856
|
+
this.crc32 = 0;
|
|
857
|
+
}
|
|
858
|
+
Crc32Watcher.prototype._transform = function(chunk, encoding, cb) {
|
|
859
|
+
this.crc32 = crc32.unsigned(chunk, this.crc32);
|
|
860
|
+
cb(null, chunk);
|
|
861
|
+
};
|
|
862
|
+
var cp437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
|
|
863
|
+
if (cp437.length !== 256) throw new Error("assertion failure");
|
|
864
|
+
var reverseCp437 = null;
|
|
865
|
+
function encodeCp437(string) {
|
|
866
|
+
if (/^[\x20-\x7e]*$/.test(string)) return bufferFrom(string, "utf-8");
|
|
867
|
+
if (reverseCp437 == null) {
|
|
868
|
+
reverseCp437 = {};
|
|
869
|
+
for (var i = 0; i < cp437.length; i++) reverseCp437[cp437[i]] = i;
|
|
870
|
+
}
|
|
871
|
+
var result = bufferAlloc(string.length);
|
|
872
|
+
for (var i = 0; i < string.length; i++) {
|
|
873
|
+
var b = reverseCp437[string[i]];
|
|
874
|
+
if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string[i]));
|
|
875
|
+
result[i] = b;
|
|
876
|
+
}
|
|
877
|
+
return result;
|
|
878
|
+
}
|
|
879
|
+
function bufferAlloc(size) {
|
|
880
|
+
bufferAlloc = modern;
|
|
881
|
+
try {
|
|
882
|
+
return bufferAlloc(size);
|
|
883
|
+
} catch (e) {
|
|
884
|
+
bufferAlloc = legacy;
|
|
885
|
+
return bufferAlloc(size);
|
|
886
|
+
}
|
|
887
|
+
function modern(size) {
|
|
888
|
+
return Buffer.allocUnsafe(size);
|
|
889
|
+
}
|
|
890
|
+
function legacy(size) {
|
|
891
|
+
return new Buffer(size);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
function bufferFrom(something, encoding) {
|
|
895
|
+
bufferFrom = modern;
|
|
896
|
+
try {
|
|
897
|
+
return bufferFrom(something, encoding);
|
|
898
|
+
} catch (e) {
|
|
899
|
+
bufferFrom = legacy;
|
|
900
|
+
return bufferFrom(something, encoding);
|
|
901
|
+
}
|
|
902
|
+
function modern(something, encoding) {
|
|
903
|
+
return Buffer.from(something, encoding);
|
|
904
|
+
}
|
|
905
|
+
function legacy(something, encoding) {
|
|
906
|
+
return new Buffer(something, encoding);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
function bufferIncludes(buffer, content) {
|
|
910
|
+
bufferIncludes = modern;
|
|
911
|
+
try {
|
|
912
|
+
return bufferIncludes(buffer, content);
|
|
913
|
+
} catch (e) {
|
|
914
|
+
bufferIncludes = legacy;
|
|
915
|
+
return bufferIncludes(buffer, content);
|
|
916
|
+
}
|
|
917
|
+
function modern(buffer, content) {
|
|
918
|
+
return buffer.includes(content);
|
|
919
|
+
}
|
|
920
|
+
function legacy(buffer, content) {
|
|
921
|
+
for (var i = 0; i <= buffer.length - content.length; i++) for (var j = 0;; j++) {
|
|
922
|
+
if (j === content.length) return true;
|
|
923
|
+
if (buffer[i + j] !== content[j]) break;
|
|
924
|
+
}
|
|
925
|
+
return false;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
})))(), 1);
|
|
929
|
+
const OUTPUT_MODE = 420;
|
|
930
|
+
const PRIVATE_TEMPORARY_PREFIX = ".rawr-agent-plugin-package-output-";
|
|
931
|
+
/**
|
|
932
|
+
* Builds the Cowork v1 package-output resource while retaining Node platform requirements.
|
|
933
|
+
* A provider-local semaphore serializes publication so staging, replacement, and verification
|
|
934
|
+
* cannot overlap within one resource instance.
|
|
935
|
+
*
|
|
936
|
+
* @param options - Provider test hooks; production callers normally use the default mechanics.
|
|
937
|
+
* @returns The archive encoder and serialized publisher consumed by lifecycle packaging.
|
|
938
|
+
*/
|
|
939
|
+
function makeAgentPluginPackageOutputResource(options = {}) {
|
|
940
|
+
const publicationSemaphore = Semaphore.makeUnsafe(1);
|
|
941
|
+
return {
|
|
942
|
+
encodeCoworkV1: Effect.fn("agentPluginPackageOutput.encodeCoworkV1")(encodeCoworkV1),
|
|
943
|
+
publish: (input) => publicationSemaphore.withPermits(1)(publishOutput(input, options))
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Realizes the Cowork package-output provider as a ready Node resource.
|
|
948
|
+
*
|
|
949
|
+
* Node platform services remain provider-owned and are attached to each
|
|
950
|
+
* returned operation, preserving Effect failure and cancellation semantics.
|
|
951
|
+
*/
|
|
952
|
+
function makeNodeAgentPluginPackageOutputResource(options = {}) {
|
|
953
|
+
const resource = makeAgentPluginPackageOutputResource(options);
|
|
954
|
+
return Object.freeze({
|
|
955
|
+
encodeCoworkV1: (input) => provideNodeServices$2(resource.encodeCoworkV1(input)),
|
|
956
|
+
publish: (input) => provideNodeServices$2(resource.publish(input))
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
function provideNodeServices$2(operation) {
|
|
960
|
+
return operation.pipe(Effect.provide(NodeServices.layer));
|
|
961
|
+
}
|
|
962
|
+
function encodeCoworkV1(request) {
|
|
963
|
+
return Effect.tryPromise({
|
|
964
|
+
try: () => encodeArchive(request),
|
|
965
|
+
catch: (cause) => failure$5("encode-archive", "ArchiveEncodingFailed", "archive-codec", void 0, errorMessage$3(cause))
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
function encodeArchive(request) {
|
|
969
|
+
const timestamp = new Date(request.fixedTimestamp);
|
|
970
|
+
if (!Number.isFinite(timestamp.getTime())) return Promise.reject(/* @__PURE__ */ new Error("Archive fixed timestamp is invalid"));
|
|
971
|
+
const archive = new import_yazl.ZipFile();
|
|
972
|
+
const chunks = [];
|
|
973
|
+
const output = new Promise((resolve, reject) => {
|
|
974
|
+
archive.once("error", reject);
|
|
975
|
+
archive.outputStream.on("data", (chunk) => {
|
|
976
|
+
chunks.push(Buffer$1.from(chunk));
|
|
977
|
+
});
|
|
978
|
+
archive.outputStream.once("error", reject);
|
|
979
|
+
archive.outputStream.once("end", () => resolve(new Uint8Array(Buffer$1.concat(chunks))));
|
|
980
|
+
});
|
|
981
|
+
for (const entry of request.entries) archive.addBuffer(Buffer$1.from(entry.bytes), entry.path, {
|
|
982
|
+
compress: request.compression !== "store",
|
|
983
|
+
forceDosTimestamp: true,
|
|
984
|
+
forceZip64Format: request.zip64,
|
|
985
|
+
mode: 32768 | entry.mode,
|
|
986
|
+
mtime: timestamp
|
|
987
|
+
});
|
|
988
|
+
archive.end({
|
|
989
|
+
forceZip64Format: request.zip64,
|
|
990
|
+
comment: request.comment
|
|
991
|
+
});
|
|
992
|
+
return output;
|
|
993
|
+
}
|
|
994
|
+
function publishOutput(input, options) {
|
|
995
|
+
const bytes = new Uint8Array(input.bytes);
|
|
996
|
+
return Effect.gen(function* () {
|
|
997
|
+
const fs = yield* FileSystem.FileSystem;
|
|
998
|
+
const paths = yield* Path.Path;
|
|
999
|
+
let committed = false;
|
|
1000
|
+
let cleanupAttempted = false;
|
|
1001
|
+
let createdTemporary;
|
|
1002
|
+
let temporary;
|
|
1003
|
+
let temporaryLinks = 1;
|
|
1004
|
+
const attempted = yield* Effect.result(Effect.gen(function* () {
|
|
1005
|
+
yield* validatePublicationInput(input);
|
|
1006
|
+
const parent = yield* captureParent(fs, paths, input.outputPath);
|
|
1007
|
+
const prior = yield* captureOutput(fs, input.outputPath, parent, input.maxPriorOutputBytes);
|
|
1008
|
+
yield* hitFailpoint(input, options.failpoints, "AfterOutputObserved");
|
|
1009
|
+
if (prior.kind === "Present" && (prior.file.mode & 511) === OUTPUT_MODE && equalBytes$1(prior.file.bytes, bytes)) {
|
|
1010
|
+
yield* verifyCapturedOutput(fs, prior.file, parent, input.maxPriorOutputBytes, "output-convergence");
|
|
1011
|
+
return Object.freeze({ kind: "ReadOnlyConverged" });
|
|
1012
|
+
}
|
|
1013
|
+
temporary = yield* allocateTemporaryFile(fs, paths, parent, bytes, (created) => {
|
|
1014
|
+
createdTemporary = created;
|
|
1015
|
+
}, (owned) => {
|
|
1016
|
+
temporary = owned;
|
|
1017
|
+
});
|
|
1018
|
+
yield* verifyTemporary(fs, paths, temporary, bytes);
|
|
1019
|
+
yield* hitFailpoint(input, options.failpoints, "BeforeCommit", temporary.path);
|
|
1020
|
+
yield* revalidateParent(fs, parent);
|
|
1021
|
+
yield* revalidatePrior(fs, input.outputPath, parent, prior, input.maxPriorOutputBytes);
|
|
1022
|
+
yield* revalidateOwnedTemporaryFile(fs, paths, temporary, 1, "publish-output");
|
|
1023
|
+
if (prior.kind === "Absent") {
|
|
1024
|
+
yield* fs.link(temporary.path, input.outputPath).pipe(mapPlatform$5("publish-output", "OutputCommitFailed", "output-no-replace", input.outputPath));
|
|
1025
|
+
committed = true;
|
|
1026
|
+
temporaryLinks = 2;
|
|
1027
|
+
cleanupAttempted = true;
|
|
1028
|
+
const released = yield* Effect.result(releaseOwnedTemporaryFile(fs, paths, temporary, temporaryLinks));
|
|
1029
|
+
if (released._tag === "Failure") return Object.freeze({
|
|
1030
|
+
kind: "OutputUnsettled",
|
|
1031
|
+
primaryFailure: failure$5("publish-output", "OutputVerifyFailed", "temporary-link-release", input.outputPath, "Output committed but the owned temporary link did not settle"),
|
|
1032
|
+
cleanupFailure: released.failure
|
|
1033
|
+
});
|
|
1034
|
+
temporary = void 0;
|
|
1035
|
+
createdTemporary = void 0;
|
|
1036
|
+
} else {
|
|
1037
|
+
yield* fs.rename(temporary.path, input.outputPath).pipe(mapPlatform$5("publish-output", "OutputCommitFailed", "output-atomic-replace", input.outputPath));
|
|
1038
|
+
committed = true;
|
|
1039
|
+
temporary = void 0;
|
|
1040
|
+
createdTemporary = void 0;
|
|
1041
|
+
}
|
|
1042
|
+
yield* hitFailpoint(input, options.failpoints, "AfterCommit");
|
|
1043
|
+
yield* syncFile(fs, parent.path, "output-parent-flush", "OutputVerifyFailed");
|
|
1044
|
+
yield* hitFailpoint(input, options.failpoints, "BeforeFinalVerification");
|
|
1045
|
+
yield* verifyPublishedOutput(fs, input.outputPath, parent, bytes);
|
|
1046
|
+
return Object.freeze({
|
|
1047
|
+
kind: "OutputReplacedVerified",
|
|
1048
|
+
priorOutput: prior.kind === "Absent" ? "Absent" : "Replaced"
|
|
1049
|
+
});
|
|
1050
|
+
}));
|
|
1051
|
+
const cleanup = temporary === void 0 && createdTemporary === void 0 || cleanupAttempted ? void 0 : yield* Effect.result(releaseTemporaryAllocation(fs, paths, createdTemporary, temporary, temporaryLinks));
|
|
1052
|
+
if (attempted._tag === "Failure") return Object.freeze({
|
|
1053
|
+
kind: committed ? "OutputUnsettled" : "RejectedBeforeOutputMutation",
|
|
1054
|
+
primaryFailure: attempted.failure,
|
|
1055
|
+
...cleanup?._tag === "Failure" ? { cleanupFailure: cleanup.failure } : {}
|
|
1056
|
+
});
|
|
1057
|
+
if (cleanup?._tag === "Failure") return Object.freeze({
|
|
1058
|
+
kind: committed ? "OutputUnsettled" : "RejectedBeforeOutputMutation",
|
|
1059
|
+
primaryFailure: failure$5("cleanup", "TemporaryFailed", "temporary-cleanup", temporary?.path ?? createdTemporary?.path, "Package output operation completed but its owned temporary did not settle"),
|
|
1060
|
+
cleanupFailure: cleanup.failure
|
|
1061
|
+
});
|
|
1062
|
+
return attempted.success;
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
function validatePublicationInput(input) {
|
|
1066
|
+
return Effect.try({
|
|
1067
|
+
try: () => {
|
|
1068
|
+
if (!(input.bytes instanceof Uint8Array)) throw new Error("Output bytes must be a Uint8Array");
|
|
1069
|
+
if (!Number.isSafeInteger(input.maxPriorOutputBytes) || input.maxPriorOutputBytes < 0) throw new Error("maxPriorOutputBytes must be a safe non-negative integer");
|
|
1070
|
+
},
|
|
1071
|
+
catch: (cause) => failure$5("publish-output", "InvalidInput", "request", input.outputPath, errorMessage$3(cause))
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
const captureParent = Effect.fn("agentPluginPackageOutput.captureParent")(function* (fs, paths, outputPath) {
|
|
1075
|
+
const parentPath = yield* Effect.try({
|
|
1076
|
+
try: () => {
|
|
1077
|
+
if (!paths.isAbsolute(outputPath) || paths.normalize(outputPath) !== outputPath || paths.resolve(outputPath) !== outputPath) throw new Error("Output path must be absolute and lexically canonical");
|
|
1078
|
+
const parent = paths.dirname(outputPath);
|
|
1079
|
+
const name = paths.basename(outputPath);
|
|
1080
|
+
if (name.length === 0 || paths.join(parent, name) !== outputPath) throw new Error("Output must name one direct child file");
|
|
1081
|
+
return parent;
|
|
1082
|
+
},
|
|
1083
|
+
catch: (cause) => failure$5("publish-output", "InvalidInput", "output-path", outputPath, errorMessage$3(cause))
|
|
1084
|
+
});
|
|
1085
|
+
if ((yield* fs.realPath(parentPath).pipe(mapPlatform$5("publish-output", "OutputParentUnsafe", "output-parent-realpath", parentPath))) !== parentPath) return yield* rejected("publish-output", "OutputParentUnsafe", "output-parent-realpath", parentPath, "Output parent must be its exact canonical path");
|
|
1086
|
+
const info = yield* fs.stat(parentPath).pipe(mapPlatform$5("publish-output", "OutputParentUnsafe", "output-parent", parentPath));
|
|
1087
|
+
if (info.type !== "Directory") return yield* rejected("publish-output", "OutputParentUnsafe", "output-parent", parentPath, "Output parent must be a directory");
|
|
1088
|
+
const ino = Option.getOrUndefined(info.ino);
|
|
1089
|
+
if (ino === void 0) return yield* rejected("publish-output", "OutputParentUnsafe", "output-parent", parentPath, "Output parent identity is unavailable");
|
|
1090
|
+
return Object.freeze({
|
|
1091
|
+
path: parentPath,
|
|
1092
|
+
dev: info.dev,
|
|
1093
|
+
ino
|
|
1094
|
+
});
|
|
1095
|
+
});
|
|
1096
|
+
const revalidateParent = Effect.fn("agentPluginPackageOutput.revalidateParent")(function* (fs, parent, operation = "publish-output") {
|
|
1097
|
+
const reason = operation === "cleanup" ? "TemporaryFailed" : "OutputParentUnsafe";
|
|
1098
|
+
const canonical = yield* fs.realPath(parent.path).pipe(mapPlatform$5(operation, reason, "output-parent-revalidation", parent.path));
|
|
1099
|
+
const info = yield* fs.stat(parent.path).pipe(mapPlatform$5(operation, reason, "output-parent-revalidation", parent.path));
|
|
1100
|
+
if (canonical !== parent.path || info.type !== "Directory" || info.dev !== parent.dev || Option.getOrUndefined(info.ino) !== parent.ino) return yield* rejected(operation, reason, "output-parent-revalidation", parent.path, "Output parent identity changed");
|
|
1101
|
+
});
|
|
1102
|
+
const captureOutput = Effect.fn("agentPluginPackageOutput.captureOutput")(function* (fs, outputPath, parent, maxBytes) {
|
|
1103
|
+
if (!(yield* fs.exists(outputPath).pipe(mapPlatform$5("publish-output", "FilesystemFailed", "output-exists", outputPath)))) return Object.freeze({ kind: "Absent" });
|
|
1104
|
+
const file = yield* captureRegularFile(fs, outputPath, parent, maxBytes, "OutputUnsafe", "output-capture");
|
|
1105
|
+
return Object.freeze({
|
|
1106
|
+
kind: "Present",
|
|
1107
|
+
file
|
|
1108
|
+
});
|
|
1109
|
+
});
|
|
1110
|
+
const captureRegularFile = Effect.fn("agentPluginPackageOutput.captureRegularFile")(function* (fs, filePath, parent, maxBytes, reason, phase) {
|
|
1111
|
+
const canonical = yield* fs.realPath(filePath).pipe(mapPlatform$5("publish-output", reason, `${phase}-realpath`, filePath));
|
|
1112
|
+
const info = yield* fs.stat(filePath).pipe(mapPlatform$5("publish-output", reason, phase, filePath));
|
|
1113
|
+
const ino = Option.getOrUndefined(info.ino);
|
|
1114
|
+
const nlink = Option.getOrUndefined(info.nlink);
|
|
1115
|
+
const mtime = Option.getOrUndefined(info.mtime)?.getTime();
|
|
1116
|
+
const size = Number(info.size);
|
|
1117
|
+
if (canonical !== filePath || info.type !== "File" || info.dev !== parent.dev || ino === void 0 || nlink !== 1 || mtime === void 0 || !Number.isSafeInteger(size) || size < 0 || size > maxBytes) return yield* rejected("publish-output", reason, phase, filePath, "Output must be one bounded canonical regular file in its captured parent");
|
|
1118
|
+
const bytes = yield* fs.readFile(filePath).pipe(mapPlatform$5("publish-output", reason, `${phase}-read`, filePath));
|
|
1119
|
+
if (bytes.byteLength !== size) return yield* rejected("publish-output", reason, `${phase}-read`, filePath, "Output size changed while it was read");
|
|
1120
|
+
const after = yield* fs.stat(filePath).pipe(mapPlatform$5("publish-output", reason, `${phase}-revalidation`, filePath));
|
|
1121
|
+
if (after.type !== "File" || after.dev !== info.dev || Option.getOrUndefined(after.ino) !== ino || after.mode !== info.mode || Number(after.size) !== size || Option.getOrUndefined(after.mtime)?.getTime() !== mtime || Option.getOrUndefined(after.nlink) !== 1) return yield* rejected("publish-output", reason, `${phase}-revalidation`, filePath, "Output identity changed while it was read");
|
|
1122
|
+
return Object.freeze({
|
|
1123
|
+
path: filePath,
|
|
1124
|
+
dev: info.dev,
|
|
1125
|
+
ino,
|
|
1126
|
+
mode: info.mode,
|
|
1127
|
+
size,
|
|
1128
|
+
mtime,
|
|
1129
|
+
bytes: new Uint8Array(bytes)
|
|
1130
|
+
});
|
|
1131
|
+
});
|
|
1132
|
+
const allocateTemporaryFile = Effect.fn("agentPluginPackageOutput.allocateTemporaryFile")(function* (fs, paths, parent, bytes, onCreated, onOwned) {
|
|
1133
|
+
yield* revalidateParent(fs, parent);
|
|
1134
|
+
const token = (yield* Effect.all([
|
|
1135
|
+
Random.nextInt,
|
|
1136
|
+
Random.nextInt,
|
|
1137
|
+
Random.nextInt,
|
|
1138
|
+
Random.nextInt
|
|
1139
|
+
])).map((value) => (value >>> 0).toString(16).padStart(8, "0")).join("");
|
|
1140
|
+
const temporaryPath = paths.join(parent.path, `${PRIVATE_TEMPORARY_PREFIX}${token}`);
|
|
1141
|
+
if (paths.dirname(temporaryPath) !== parent.path || !paths.basename(temporaryPath).startsWith(PRIVATE_TEMPORARY_PREFIX)) return yield* rejected("publish-output", "TemporaryFailed", "temporary-admission", temporaryPath, "Owned temporary must be one direct child of the exact output parent");
|
|
1142
|
+
const owned = yield* Effect.scoped(Effect.gen(function* () {
|
|
1143
|
+
const file = yield* fs.open(temporaryPath, {
|
|
1144
|
+
flag: "wx",
|
|
1145
|
+
mode: OUTPUT_MODE
|
|
1146
|
+
}).pipe(mapPlatform$5("publish-output", "TemporaryFailed", "temporary-create", temporaryPath));
|
|
1147
|
+
onCreated(Object.freeze({
|
|
1148
|
+
parent,
|
|
1149
|
+
path: temporaryPath
|
|
1150
|
+
}));
|
|
1151
|
+
const fileInfo = yield* file.stat.pipe(mapPlatform$5("publish-output", "TemporaryFailed", "temporary-identity", temporaryPath));
|
|
1152
|
+
const ino = Option.getOrUndefined(fileInfo.ino);
|
|
1153
|
+
if (fileInfo.type !== "File" || fileInfo.dev !== parent.dev || ino === void 0 || Option.getOrUndefined(fileInfo.nlink) !== 1) return yield* rejected("publish-output", "TemporaryFailed", "temporary-identity", temporaryPath, "Created temporary file descriptor did not provide one stable regular-file identity");
|
|
1154
|
+
const captured = Object.freeze({
|
|
1155
|
+
parent,
|
|
1156
|
+
path: temporaryPath,
|
|
1157
|
+
dev: fileInfo.dev,
|
|
1158
|
+
ino
|
|
1159
|
+
});
|
|
1160
|
+
onOwned(captured);
|
|
1161
|
+
yield* file.writeAll(bytes).pipe(mapPlatform$5("publish-output", "TemporaryFailed", "temporary-write", temporaryPath));
|
|
1162
|
+
yield* file.sync.pipe(mapPlatform$5("publish-output", "TemporaryFailed", "temporary-flush", temporaryPath));
|
|
1163
|
+
return captured;
|
|
1164
|
+
}));
|
|
1165
|
+
yield* fs.chmod(temporaryPath, OUTPUT_MODE).pipe(mapPlatform$5("publish-output", "TemporaryFailed", "temporary-mode", temporaryPath));
|
|
1166
|
+
yield* revalidateParent(fs, parent);
|
|
1167
|
+
yield* revalidateOwnedTemporaryFile(fs, paths, owned, 1, "publish-output");
|
|
1168
|
+
return owned;
|
|
1169
|
+
});
|
|
1170
|
+
const verifyTemporary = Effect.fn("agentPluginPackageOutput.verifyTemporary")(function* (fs, paths, owned, expectedBytes) {
|
|
1171
|
+
yield* revalidateOwnedTemporaryFile(fs, paths, owned, 1, "publish-output");
|
|
1172
|
+
const captured = yield* captureRegularFile(fs, owned.path, owned.parent, expectedBytes.byteLength, "TemporaryFailed", "temporary-verification");
|
|
1173
|
+
if (captured.dev !== owned.dev || captured.ino !== owned.ino || !equalBytes$1(captured.bytes, expectedBytes) || (captured.mode & 511) !== OUTPUT_MODE) return yield* rejected("publish-output", "TemporaryFailed", "temporary-verification", owned.path, "Owned temporary identity, bytes, or mode differ from the publication request");
|
|
1174
|
+
});
|
|
1175
|
+
const revalidateOwnedTemporaryFile = Effect.fn("agentPluginPackageOutput.revalidateOwnedTemporaryFile")(function* (fs, paths, owned, expectedLinks, operation) {
|
|
1176
|
+
yield* revalidateParent(fs, owned.parent, operation);
|
|
1177
|
+
if (paths.dirname(owned.path) !== owned.parent.path || !paths.basename(owned.path).startsWith(PRIVATE_TEMPORARY_PREFIX)) return yield* rejected(operation, "TemporaryFailed", "temporary-revalidation", owned.path, "Owned temporary escaped its exact output parent");
|
|
1178
|
+
const [canonical, info] = yield* Effect.all([fs.realPath(owned.path).pipe(mapPlatform$5(operation, "TemporaryFailed", "temporary-revalidation", owned.path)), fs.stat(owned.path).pipe(mapPlatform$5(operation, "TemporaryFailed", "temporary-revalidation", owned.path))]);
|
|
1179
|
+
if (canonical !== owned.path || info.type !== "File" || info.dev !== owned.dev || Option.getOrUndefined(info.ino) !== owned.ino || Option.getOrUndefined(info.nlink) !== expectedLinks) return yield* rejected(operation, "TemporaryFailed", "temporary-revalidation", owned.path, "Owned temporary identity changed");
|
|
1180
|
+
});
|
|
1181
|
+
const admitCreatedTemporaryFile = Effect.fn("agentPluginPackageOutput.admitCreatedTemporaryFile")(function* (fs, paths, created) {
|
|
1182
|
+
yield* revalidateParent(fs, created.parent, "cleanup");
|
|
1183
|
+
if (paths.dirname(created.path) !== created.parent.path || !paths.basename(created.path).startsWith(PRIVATE_TEMPORARY_PREFIX)) return yield* rejected("cleanup", "TemporaryFailed", "temporary-admission", created.path, "Created temporary escaped its exact output parent");
|
|
1184
|
+
const [canonical, info] = yield* Effect.all([fs.realPath(created.path).pipe(mapPlatform$5("cleanup", "TemporaryFailed", "temporary-admission", created.path)), fs.stat(created.path).pipe(mapPlatform$5("cleanup", "TemporaryFailed", "temporary-admission", created.path))]);
|
|
1185
|
+
const ino = Option.getOrUndefined(info.ino);
|
|
1186
|
+
if (canonical !== created.path || info.type !== "File" || info.dev !== created.parent.dev || ino === void 0 || Option.getOrUndefined(info.nlink) !== 1) return yield* rejected("cleanup", "TemporaryFailed", "temporary-admission", created.path, "Created temporary could not be admitted as one owned regular file");
|
|
1187
|
+
return Object.freeze({
|
|
1188
|
+
parent: created.parent,
|
|
1189
|
+
path: created.path,
|
|
1190
|
+
dev: info.dev,
|
|
1191
|
+
ino
|
|
1192
|
+
});
|
|
1193
|
+
});
|
|
1194
|
+
function releaseTemporaryAllocation(fs, paths, created, owned, expectedLinks) {
|
|
1195
|
+
if (owned !== void 0) return releaseOwnedTemporaryFile(fs, paths, owned, expectedLinks);
|
|
1196
|
+
if (created === void 0) return Effect.void;
|
|
1197
|
+
return admitCreatedTemporaryFile(fs, paths, created).pipe(Effect.flatMap((admitted) => releaseOwnedTemporaryFile(fs, paths, admitted, expectedLinks)));
|
|
1198
|
+
}
|
|
1199
|
+
const releaseOwnedTemporaryFile = Effect.fn("agentPluginPackageOutput.releaseOwnedTemporaryFile")(function* (fs, paths, owned, expectedLinks) {
|
|
1200
|
+
yield* revalidateOwnedTemporaryFile(fs, paths, owned, expectedLinks, "cleanup");
|
|
1201
|
+
yield* fs.remove(owned.path, {
|
|
1202
|
+
recursive: false,
|
|
1203
|
+
force: false
|
|
1204
|
+
}).pipe(mapPlatform$5("cleanup", "TemporaryFailed", "temporary-remove", owned.path));
|
|
1205
|
+
if (yield* fs.exists(owned.path).pipe(mapPlatform$5("cleanup", "TemporaryFailed", "temporary-remove-verification", owned.path))) return yield* rejected("cleanup", "TemporaryFailed", "temporary-remove-verification", owned.path, "Owned temporary cleanup did not settle");
|
|
1206
|
+
yield* Effect.scoped(Effect.gen(function* () {
|
|
1207
|
+
yield* (yield* fs.open(owned.parent.path, { flag: "r" }).pipe(mapPlatform$5("cleanup", "TemporaryFailed", "temporary-parent-flush", owned.parent.path))).sync.pipe(mapPlatform$5("cleanup", "TemporaryFailed", "temporary-parent-flush", owned.parent.path));
|
|
1208
|
+
}));
|
|
1209
|
+
});
|
|
1210
|
+
const revalidatePrior = Effect.fn("agentPluginPackageOutput.revalidatePrior")(function* (fs, outputPath, parent, prior, maxBytes) {
|
|
1211
|
+
const current = yield* captureOutput(fs, outputPath, parent, maxBytes).pipe(Effect.mapError((cause) => failure$5(cause.operation, "OutputChanged", cause.phase, cause.path, cause.detail)));
|
|
1212
|
+
if (prior.kind === "Absent") {
|
|
1213
|
+
if (current.kind !== "Absent") return yield* rejected("publish-output", "OutputChanged", "output-precommit", outputPath, "Absent output became occupied before no-replace publication");
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
if (current.kind !== "Present" || !sameFileIdentity(prior.file, current.file) || !equalBytes$1(prior.file.bytes, current.file.bytes)) return yield* rejected("publish-output", "OutputChanged", "output-precommit", outputPath, "Captured output changed before atomic replacement");
|
|
1217
|
+
});
|
|
1218
|
+
const verifyCapturedOutput = Effect.fn("agentPluginPackageOutput.verifyCapturedOutput")(function* (fs, captured, parent, maxBytes, phase) {
|
|
1219
|
+
const current = yield* captureRegularFile(fs, captured.path, parent, maxBytes, "OutputChanged", phase);
|
|
1220
|
+
if (!sameFileIdentity(captured, current) || !equalBytes$1(captured.bytes, current.bytes)) return yield* rejected("publish-output", "OutputChanged", phase, captured.path, "Captured output changed during convergence verification");
|
|
1221
|
+
});
|
|
1222
|
+
const verifyPublishedOutput = Effect.fn("agentPluginPackageOutput.verifyPublishedOutput")(function* (fs, outputPath, parent, expectedBytes) {
|
|
1223
|
+
yield* revalidateParent(fs, parent);
|
|
1224
|
+
const current = yield* captureRegularFile(fs, outputPath, parent, expectedBytes.byteLength, "OutputVerifyFailed", "output-final");
|
|
1225
|
+
if (!equalBytes$1(current.bytes, expectedBytes) || (current.mode & 511) !== OUTPUT_MODE) return yield* rejected("publish-output", "OutputVerifyFailed", "output-final", outputPath, "Published output bytes or mode differ from the publication request");
|
|
1226
|
+
});
|
|
1227
|
+
function syncFile(fs, candidate, phase, reason) {
|
|
1228
|
+
return Effect.scoped(Effect.gen(function* () {
|
|
1229
|
+
yield* (yield* fs.open(candidate, { flag: "r" }).pipe(mapPlatform$5("publish-output", reason, phase, candidate))).sync.pipe(mapPlatform$5("publish-output", reason, phase, candidate));
|
|
1230
|
+
}));
|
|
1231
|
+
}
|
|
1232
|
+
function hitFailpoint(input, failpoints, point, temporaryPath) {
|
|
1233
|
+
if (input.control?.onEvent === void 0 && failpoints === void 0) return Effect.void;
|
|
1234
|
+
const event = Object.freeze({
|
|
1235
|
+
point,
|
|
1236
|
+
outputPath: input.outputPath,
|
|
1237
|
+
...temporaryPath === void 0 ? {} : { temporaryPath }
|
|
1238
|
+
});
|
|
1239
|
+
return Effect.tryPromise({
|
|
1240
|
+
try: async () => {
|
|
1241
|
+
await input.control?.onEvent?.(event);
|
|
1242
|
+
await failpoints?.hit(point, event);
|
|
1243
|
+
},
|
|
1244
|
+
catch: (cause) => failure$5("publish-output", "FilesystemFailed", point, input.outputPath, `Provider failpoint failed: ${errorMessage$3(cause)}`)
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
function mapPlatform$5(operation, reason, phase, candidate) {
|
|
1248
|
+
return (effect) => effect.pipe(Effect.mapError((cause) => failure$5(operation, reason, phase, candidate, cause.message)));
|
|
1249
|
+
}
|
|
1250
|
+
function rejected(operation, reason, phase, candidate, detail) {
|
|
1251
|
+
return Effect.fail(failure$5(operation, reason, phase, candidate, detail));
|
|
1252
|
+
}
|
|
1253
|
+
function failure$5(operation, reason, phase, candidate, detail) {
|
|
1254
|
+
return Object.freeze({
|
|
1255
|
+
_tag: "PackageOutputFailure",
|
|
1256
|
+
operation,
|
|
1257
|
+
reason,
|
|
1258
|
+
phase,
|
|
1259
|
+
...candidate === void 0 ? {} : { path: candidate },
|
|
1260
|
+
detail
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
function sameFileIdentity(left, right) {
|
|
1264
|
+
return left.path === right.path && left.dev === right.dev && left.ino === right.ino && left.mode === right.mode && left.size === right.size && left.mtime === right.mtime;
|
|
1265
|
+
}
|
|
1266
|
+
function equalBytes$1(left, right) {
|
|
1267
|
+
return left.byteLength === right.byteLength && left.every((value, index) => value === right[index]);
|
|
1268
|
+
}
|
|
1269
|
+
function errorMessage$3(error) {
|
|
1270
|
+
return error instanceof Error ? error.message : String(error);
|
|
1271
|
+
}
|
|
1272
|
+
//#endregion
|
|
1273
|
+
//#region ../../resources/agent-plugin-package-output/dist/providers/cowork-v1-effect-platform-node/runtime.js
|
|
1274
|
+
/** Acquire a fresh capability factory without opening any caller-selected workspace or home. */
|
|
1275
|
+
function defineNodeAgentPluginPackageOutputRuntimeProvider() {
|
|
1276
|
+
return defineRuntimeProvider({
|
|
1277
|
+
id: "agent-plugin-package-output.cowork-v1-effect-platform-node",
|
|
1278
|
+
title: "Agent plugin package output (cowork-v1-effect-platform-node)",
|
|
1279
|
+
provides: AgentPluginPackageOutputRuntimeResource,
|
|
1280
|
+
requires: [],
|
|
1281
|
+
build: () => providerFx.acquireRelease({
|
|
1282
|
+
acquire: Effect.sync(() => makeNodeAgentPluginPackageOutputResource()),
|
|
1283
|
+
release: () => Effect.void
|
|
1284
|
+
})
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
//#endregion
|
|
1288
|
+
//#region ../../resources/child-process/dist/providers/effect-platform-node/index.js
|
|
1289
|
+
/** Captures native spawning capabilities without opening a child or retaining an operation scope. */
|
|
1290
|
+
function defineNodeChildProcessRuntimeProvider() {
|
|
1291
|
+
const filesystem = requireResource({
|
|
1292
|
+
resource: FilesystemRuntimeResource,
|
|
1293
|
+
reason: "Native child processes use the selected filesystem and path capabilities"
|
|
1294
|
+
});
|
|
1295
|
+
return defineRuntimeProvider({
|
|
1296
|
+
id: "child-process.effect-platform-node",
|
|
1297
|
+
title: "Native Node child process",
|
|
1298
|
+
provides: ChildProcessRuntimeResource,
|
|
1299
|
+
requires: [filesystem],
|
|
1300
|
+
build: ({ resources }) => providerFx.acquireRelease({
|
|
1301
|
+
acquire: Effect.scoped(Effect.gen(function* () {
|
|
1302
|
+
const ready = resources.get(filesystem);
|
|
1303
|
+
const context = yield* Layer.build(NodeChildProcessSpawner.layer).pipe(Effect.provideService(FileSystem.FileSystem, ready.fileSystem), Effect.provideService(Path.Path, ready.path));
|
|
1304
|
+
return Context.get(context, ChildProcessSpawner.ChildProcessSpawner);
|
|
1305
|
+
})),
|
|
1306
|
+
release: () => Effect.void
|
|
1307
|
+
})
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
//#endregion
|
|
1311
|
+
//#region ../../resources/content-workspace/contract.ts
|
|
1312
|
+
/** Maximum regular-file entries admitted by one disposable tree materialization. */
|
|
1313
|
+
const MAX_DISPOSABLE_CONTENT_TREE_ENTRIES = 262144;
|
|
1314
|
+
/** Maximum aggregate bytes admitted by one disposable tree materialization. */
|
|
1315
|
+
const MAX_DISPOSABLE_CONTENT_TREE_BYTES = 134217728;
|
|
1316
|
+
/** Maximum parent-root length admitted by disposable tree materialization. */
|
|
1317
|
+
const MAX_DISPOSABLE_CONTENT_TREE_PARENT_LENGTH = 16384;
|
|
1318
|
+
/** Maximum stable root length after the provider appends its caller-owned child name. */
|
|
1319
|
+
const MAX_DISPOSABLE_CONTENT_TREE_ROOT_LENGTH = 16640;
|
|
1320
|
+
const ContentRelativePathSchema = Refine(Type.String({
|
|
1321
|
+
minLength: 1,
|
|
1322
|
+
maxLength: 4096,
|
|
1323
|
+
description: "Canonical provider-neutral repository-relative path"
|
|
1324
|
+
}), (value) => !value.startsWith("/") && !value.endsWith("/") && !value.includes("\\") && !/[\u0000-\u001f\u007f]/u.test(value) && value.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".."), () => "Expected a canonical repository-relative path");
|
|
1325
|
+
const GitObjectIdSchema = Type.String({
|
|
1326
|
+
minLength: 40,
|
|
1327
|
+
maxLength: 64,
|
|
1328
|
+
pattern: "^(?:[0-9a-f]{40}|[0-9a-f]{64})$",
|
|
1329
|
+
description: "Lowercase SHA-1 or SHA-256 Git object identifier"
|
|
1330
|
+
});
|
|
1331
|
+
/** Portable Git modes admitted for regular content-workspace files. */
|
|
1332
|
+
const ContentFileModeSchema = Type.Union([Type.Literal("100644"), Type.Literal("100755")], { description: "Portable Git mode for one regular content-workspace file" });
|
|
1333
|
+
/** Structural schema for one provider-neutral regular Git tree fact. */
|
|
1334
|
+
const ContentTreeEntrySchema = ReadonlyObject(Type.Object({
|
|
1335
|
+
path: ContentRelativePathSchema,
|
|
1336
|
+
mode: ContentFileModeSchema,
|
|
1337
|
+
blob: GitObjectIdSchema
|
|
1338
|
+
}), { additionalProperties: false });
|
|
1339
|
+
const DisposableContentTreeBytesSchema = Refine(Type.Unsafe(Type.Unknown({ description: "Exact bytes for one disposable regular file" })), (value) => value instanceof Uint8Array && value.byteLength <= 134217728, () => "Expected a Uint8Array within the disposable tree byte bound");
|
|
1340
|
+
const DisposableContentTreeMaxEntriesSchema = Type.Integer({
|
|
1341
|
+
minimum: 1,
|
|
1342
|
+
maximum: MAX_DISPOSABLE_CONTENT_TREE_ENTRIES,
|
|
1343
|
+
description: "Maximum regular files the caller permits in the disposable tree"
|
|
1344
|
+
});
|
|
1345
|
+
const DisposableContentTreeMaxBytesSchema = Type.Integer({
|
|
1346
|
+
minimum: 1,
|
|
1347
|
+
maximum: MAX_DISPOSABLE_CONTENT_TREE_BYTES,
|
|
1348
|
+
description: "Maximum aggregate bytes the caller permits in the disposable tree"
|
|
1349
|
+
});
|
|
1350
|
+
const DisposableContentTreeDirectoryNameSchema = Refine(Type.String({
|
|
1351
|
+
minLength: 1,
|
|
1352
|
+
maxLength: 255,
|
|
1353
|
+
description: "Canonical direct-child name reserved by the caller for one disposable tree"
|
|
1354
|
+
}), (value) => value !== "." && value !== ".." && !value.includes("/") && !value.includes("\\") && !/[\u0000-\u001f\u007f]/u.test(value), () => "Expected one canonical filesystem child name");
|
|
1355
|
+
/** Structural schema for one exact disposable regular-file entry. */
|
|
1356
|
+
const DisposableContentTreeEntrySchema = ReadonlyObject(Type.Object({
|
|
1357
|
+
path: ContentRelativePathSchema,
|
|
1358
|
+
mode: ContentFileModeSchema,
|
|
1359
|
+
bytes: DisposableContentTreeBytesSchema
|
|
1360
|
+
}), { additionalProperties: false });
|
|
1361
|
+
/** Structural schema for one bounded caller-owned disposable tree request. */
|
|
1362
|
+
const MaterializeContentTreeInputSchema = ReadonlyObject(Type.Object({
|
|
1363
|
+
parentRoot: Type.String({
|
|
1364
|
+
minLength: 1,
|
|
1365
|
+
maxLength: MAX_DISPOSABLE_CONTENT_TREE_PARENT_LENGTH,
|
|
1366
|
+
description: "Normalized non-root absolute directory that owns the disposable tree lifetime"
|
|
1367
|
+
}),
|
|
1368
|
+
directoryName: DisposableContentTreeDirectoryNameSchema,
|
|
1369
|
+
entries: ReadonlyObject(Type.Array(DisposableContentTreeEntrySchema), {
|
|
1370
|
+
maxItems: MAX_DISPOSABLE_CONTENT_TREE_ENTRIES,
|
|
1371
|
+
description: "Exact regular-file entries in canonical path order"
|
|
1372
|
+
}),
|
|
1373
|
+
maxEntries: DisposableContentTreeMaxEntriesSchema,
|
|
1374
|
+
maxBytes: DisposableContentTreeMaxBytesSchema
|
|
1375
|
+
}), { additionalProperties: false });
|
|
1376
|
+
ReadonlyObject(Type.Object({ root: Type.String({
|
|
1377
|
+
minLength: 1,
|
|
1378
|
+
maxLength: MAX_DISPOSABLE_CONTENT_TREE_ROOT_LENGTH,
|
|
1379
|
+
description: "Stable direct child retained until the caller removes its disposable parent"
|
|
1380
|
+
}) }), { additionalProperties: false });
|
|
1381
|
+
/** Six-octal-digit mode reported by Git for one staged index entry. */
|
|
1382
|
+
const GitStagedIndexModeSchema = Type.String({
|
|
1383
|
+
pattern: "^[0-7]{6}$",
|
|
1384
|
+
description: "Six-octal-digit Git index mode"
|
|
1385
|
+
});
|
|
1386
|
+
/** Conflict stage reported by Git for one staged index entry. */
|
|
1387
|
+
const GitStagedIndexStageSchema = Type.Union([
|
|
1388
|
+
Type.Literal(0),
|
|
1389
|
+
Type.Literal(1),
|
|
1390
|
+
Type.Literal(2),
|
|
1391
|
+
Type.Literal(3)
|
|
1392
|
+
], { description: "Git index stage where zero is resolved and one through three are conflicts" });
|
|
1393
|
+
/** Structural schema for one provider-neutral staged Git index fact. */
|
|
1394
|
+
const GitStagedIndexEntrySchema = ReadonlyObject(Type.Object({
|
|
1395
|
+
path: ContentRelativePathSchema,
|
|
1396
|
+
mode: GitStagedIndexModeSchema,
|
|
1397
|
+
objectId: GitObjectIdSchema,
|
|
1398
|
+
stage: GitStagedIndexStageSchema
|
|
1399
|
+
}), { additionalProperties: false });
|
|
1400
|
+
/** Native Git classification retained for one tracked path without exposing its tag encoding. */
|
|
1401
|
+
const GitTrackedPathStatusSchema = Type.Union([
|
|
1402
|
+
Type.Literal("Cached"),
|
|
1403
|
+
Type.Literal("SkipWorktree"),
|
|
1404
|
+
Type.Literal("Unmerged")
|
|
1405
|
+
], { description: "Provider-neutral status reported by Git for one tracked path" });
|
|
1406
|
+
/** Structural schema for one provider-neutral tracked-path flag fact. */
|
|
1407
|
+
const GitTrackedPathFlagSchema = ReadonlyObject(Type.Object({
|
|
1408
|
+
path: ContentRelativePathSchema,
|
|
1409
|
+
status: GitTrackedPathStatusSchema,
|
|
1410
|
+
assumeUnchanged: Type.Boolean({ description: "Whether Git marks this tracked path assume-unchanged" })
|
|
1411
|
+
}), { additionalProperties: false });
|
|
1412
|
+
//#endregion
|
|
1413
|
+
//#region ../../resources/content-workspace/dist/providers/git-effect-platform-node/index.js
|
|
1414
|
+
const decoder$2 = new TextDecoder("utf-8", { fatal: true });
|
|
1415
|
+
const encoder = new TextEncoder();
|
|
1416
|
+
const contentTreeEntryValidator = Schema.Compile(ContentTreeEntrySchema);
|
|
1417
|
+
const gitStagedIndexEntryValidator = Schema.Compile(GitStagedIndexEntrySchema);
|
|
1418
|
+
const gitTrackedPathFlagValidator = Schema.Compile(GitTrackedPathFlagSchema);
|
|
1419
|
+
const materializeContentTreeInputValidator = Schema.Compile(MaterializeContentTreeInputSchema);
|
|
1420
|
+
const ATOMIC_FILE_PREFIX = ".rawr-content-workspace-";
|
|
1421
|
+
const CONTENT_TREE_STAGE_PREFIX = ".rawr-content-tree-stage-";
|
|
1422
|
+
const OBJECT_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u;
|
|
1423
|
+
const REF_PATTERN = /^refs\/[A-Za-z0-9][A-Za-z0-9._/-]*$/u;
|
|
1424
|
+
function makeCaptureBudget(limits) {
|
|
1425
|
+
return {
|
|
1426
|
+
entries: 0,
|
|
1427
|
+
bytes: 0,
|
|
1428
|
+
maxEntries: limits.maxEntries,
|
|
1429
|
+
maxBytes: limits.maxBytes
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Builds the Git-backed content-workspace resource with resource-instance capture authority.
|
|
1434
|
+
* The returned operations expose bounded repository facts and mutations while this provider owns
|
|
1435
|
+
* Git execution, path admission, and disposable-tree cleanup.
|
|
1436
|
+
*
|
|
1437
|
+
* @param options - Provider command configuration, primarily for controlled test runtimes.
|
|
1438
|
+
* @returns The platform-requiring resource consumed by lifecycle service composition.
|
|
1439
|
+
*/
|
|
1440
|
+
function makeContentWorkspaceResource(options = {}) {
|
|
1441
|
+
const gitExecutable = options.gitExecutable ?? "git";
|
|
1442
|
+
const captureAuthorities = /* @__PURE__ */ new Map();
|
|
1443
|
+
const consumedHandles = /* @__PURE__ */ new Set();
|
|
1444
|
+
const inspectWorkspace = Effect.fn("contentWorkspace.inspect")(function* (input) {
|
|
1445
|
+
const root = yield* requireCanonicalRoot(yield* FileSystem.FileSystem, input.locator, "inspect");
|
|
1446
|
+
if ((yield* gitText$1(gitExecutable, root, ["rev-parse", "--show-toplevel"], "inspect")) !== root) return yield* fail$4("inspect", "Aliased", root, "Workspace locator resolves to a different Git root");
|
|
1447
|
+
const [refName, commit, tree, objectFormat, remoteNames] = yield* Effect.all([
|
|
1448
|
+
gitText$1(gitExecutable, root, [
|
|
1449
|
+
"symbolic-ref",
|
|
1450
|
+
"--quiet",
|
|
1451
|
+
"HEAD"
|
|
1452
|
+
], "inspect"),
|
|
1453
|
+
gitText$1(gitExecutable, root, [
|
|
1454
|
+
"rev-parse",
|
|
1455
|
+
"--verify",
|
|
1456
|
+
"HEAD^{commit}"
|
|
1457
|
+
], "inspect"),
|
|
1458
|
+
gitText$1(gitExecutable, root, [
|
|
1459
|
+
"rev-parse",
|
|
1460
|
+
"--verify",
|
|
1461
|
+
"HEAD^{tree}"
|
|
1462
|
+
], "inspect"),
|
|
1463
|
+
gitObjectFormat$1(gitExecutable, root, "inspect"),
|
|
1464
|
+
gitLines(gitExecutable, root, ["remote"], "inspect")
|
|
1465
|
+
]);
|
|
1466
|
+
const remoteUrls = yield* Effect.forEach(remoteNames, (remote) => gitLines(gitExecutable, root, [
|
|
1467
|
+
"remote",
|
|
1468
|
+
"get-url",
|
|
1469
|
+
"--all",
|
|
1470
|
+
remote
|
|
1471
|
+
], "inspect"));
|
|
1472
|
+
return Object.freeze({
|
|
1473
|
+
root,
|
|
1474
|
+
refName,
|
|
1475
|
+
commit,
|
|
1476
|
+
tree,
|
|
1477
|
+
objectFormat,
|
|
1478
|
+
remoteUrls: Object.freeze(remoteUrls.flat().sort(compareText$6))
|
|
1479
|
+
});
|
|
1480
|
+
});
|
|
1481
|
+
const inspectGitWorkspace = Effect.fn("contentWorkspace.inspectGitWorkspace")(function* (input) {
|
|
1482
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1483
|
+
const executable = gitExecutable;
|
|
1484
|
+
yield* checked("inspect-git-workspace", () => validateGitInspectionInput(input));
|
|
1485
|
+
return yield* observeGitWorkspaceAnchor(fs, executable, input.locator, input, "inspect-git-workspace");
|
|
1486
|
+
});
|
|
1487
|
+
const inspectGitRef = Effect.fn("contentWorkspace.inspectGitRef")(function* (input) {
|
|
1488
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1489
|
+
const operation = "inspect-git-ref";
|
|
1490
|
+
const executable = gitExecutable;
|
|
1491
|
+
yield* checked(operation, () => {
|
|
1492
|
+
validateRefName(input.refName, operation);
|
|
1493
|
+
validateRemoteSelection(input.remoteSelection, operation);
|
|
1494
|
+
});
|
|
1495
|
+
const root = yield* requireExactGitRoot(fs, executable, input.locator, operation);
|
|
1496
|
+
const objectFormat = yield* gitObjectFormat$1(executable, root, operation);
|
|
1497
|
+
const commit = yield* requireExactCommit(executable, root, input.refName, operation);
|
|
1498
|
+
const tree = yield* gitText$1(executable, root, [
|
|
1499
|
+
"rev-parse",
|
|
1500
|
+
"--verify",
|
|
1501
|
+
"--end-of-options",
|
|
1502
|
+
`${commit}^{tree}`
|
|
1503
|
+
], operation);
|
|
1504
|
+
validateObjectForFormat(tree, objectFormat, "tree", operation);
|
|
1505
|
+
const remoteUrls = yield* readSelectedRemoteUrls(executable, root, input.remoteSelection, operation);
|
|
1506
|
+
return Object.freeze({
|
|
1507
|
+
root,
|
|
1508
|
+
refName: input.refName,
|
|
1509
|
+
commit,
|
|
1510
|
+
tree,
|
|
1511
|
+
objectFormat,
|
|
1512
|
+
remoteUrls
|
|
1513
|
+
});
|
|
1514
|
+
});
|
|
1515
|
+
const readGitTree = Effect.fn("contentWorkspace.readGitTree")(function* (input) {
|
|
1516
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1517
|
+
const executable = gitExecutable;
|
|
1518
|
+
const root = yield* requireExactGitRoot(fs, executable, input.root, "read-git-tree");
|
|
1519
|
+
yield* checked("read-git-tree", () => {
|
|
1520
|
+
validateObjectForFormat(input.tree, input.objectFormat, "tree", "read-git-tree");
|
|
1521
|
+
validateGitTreePaths(input.paths);
|
|
1522
|
+
validateLimit(input.maxEntries, "maxEntries", "read-git-tree");
|
|
1523
|
+
validateLimit(input.maxBytes, "maxBytes", "read-git-tree");
|
|
1524
|
+
});
|
|
1525
|
+
yield* requireGitObjectType(executable, root, input.tree, "tree", "read-git-tree");
|
|
1526
|
+
return yield* parseGitTreeOutput(yield* gitBytes$1(executable, root, [
|
|
1527
|
+
"ls-tree",
|
|
1528
|
+
"-r",
|
|
1529
|
+
"-z",
|
|
1530
|
+
"--full-tree",
|
|
1531
|
+
input.tree,
|
|
1532
|
+
"--",
|
|
1533
|
+
...input.paths.map((candidate) => `:(literal)${candidate}`)
|
|
1534
|
+
], "read-git-tree", input.maxBytes), input.objectFormat, input.maxEntries, root);
|
|
1535
|
+
});
|
|
1536
|
+
const readGitBlob = Effect.fn("contentWorkspace.readGitBlob")(function* (input) {
|
|
1537
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1538
|
+
const executable = gitExecutable;
|
|
1539
|
+
const root = yield* requireExactGitRoot(fs, executable, input.root, "read-git-blob");
|
|
1540
|
+
yield* checked("read-git-blob", () => {
|
|
1541
|
+
validateObjectForFormat(input.blob, input.objectFormat, "blob", "read-git-blob");
|
|
1542
|
+
validateLimit(input.maxBytes, "maxBytes", "read-git-blob");
|
|
1543
|
+
});
|
|
1544
|
+
yield* requireGitObjectType(executable, root, input.blob, "blob", "read-git-blob");
|
|
1545
|
+
return yield* gitBytes$1(executable, root, [
|
|
1546
|
+
"cat-file",
|
|
1547
|
+
"blob",
|
|
1548
|
+
input.blob
|
|
1549
|
+
], "read-git-blob", input.maxBytes);
|
|
1550
|
+
});
|
|
1551
|
+
const readGitBlobs = Effect.fn("contentWorkspace.readGitBlobs")(function* (input) {
|
|
1552
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1553
|
+
const operation = "read-git-blob";
|
|
1554
|
+
const executable = gitExecutable;
|
|
1555
|
+
return yield* readGitBlobBatch(executable, yield* requireExactGitRoot(fs, executable, input.root, operation), input, operation);
|
|
1556
|
+
});
|
|
1557
|
+
const captureGitWorkspaceEvidence = Effect.fn("contentWorkspace.captureGitWorkspaceEvidence")(function* (input) {
|
|
1558
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1559
|
+
const executable = gitExecutable;
|
|
1560
|
+
yield* checked("capture-git-evidence", () => validateGitEvidenceInput(input));
|
|
1561
|
+
const openingAnchor = yield* observeGitWorkspaceAnchor(fs, executable, input.root, input, "capture-git-evidence");
|
|
1562
|
+
const openingStatus = yield* readGitStatus(executable, input.root, input.maxBytes);
|
|
1563
|
+
const openingTrackedFlags = yield* readGitTrackedFlags(executable, input.root, input.admittedPaths, input.maxBytes);
|
|
1564
|
+
const worktreeObjectIds = yield* observeGitWorktreeObjectIds(fs, executable, openingAnchor.root, input.admittedPaths, input.objectFormat, input.maxWorktreeFileBytes, input.maxWorktreeBytes);
|
|
1565
|
+
const indexEntries = yield* gitBytes$1(executable, input.root, [
|
|
1566
|
+
"ls-files",
|
|
1567
|
+
"--stage",
|
|
1568
|
+
"-z"
|
|
1569
|
+
], "capture-git-evidence", input.maxBytes);
|
|
1570
|
+
const closingAnchor = yield* observeGitWorkspaceAnchor(fs, executable, input.root, input, "capture-git-evidence");
|
|
1571
|
+
const closingStatus = yield* readGitStatus(executable, input.root, input.maxBytes);
|
|
1572
|
+
const closingTrackedFlags = yield* readGitTrackedFlags(executable, input.root, input.admittedPaths, input.maxBytes);
|
|
1573
|
+
return Object.freeze({
|
|
1574
|
+
openingAnchor,
|
|
1575
|
+
openingStatus,
|
|
1576
|
+
openingTrackedFlags,
|
|
1577
|
+
worktreeObjectIds: Object.freeze(worktreeObjectIds),
|
|
1578
|
+
indexEntries,
|
|
1579
|
+
closingAnchor,
|
|
1580
|
+
closingStatus,
|
|
1581
|
+
closingTrackedFlags
|
|
1582
|
+
});
|
|
1583
|
+
});
|
|
1584
|
+
const observeGitStagedIndex = Effect.fn("contentWorkspace.observeGitStagedIndex")(function* (input) {
|
|
1585
|
+
const operation = "observe-git-staged-index";
|
|
1586
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1587
|
+
const executable = gitExecutable;
|
|
1588
|
+
yield* checked(operation, () => {
|
|
1589
|
+
validateRefName(input.refName, operation);
|
|
1590
|
+
validateRemoteSelection(input.remoteSelection, operation);
|
|
1591
|
+
validateLimit(input.maxEntries, "maxEntries", operation);
|
|
1592
|
+
validateLimit(input.maxIndexBytes, "maxIndexBytes", operation);
|
|
1593
|
+
validateLimit(input.maxBlobBytes, "maxBlobBytes", operation);
|
|
1594
|
+
if (input.materializedPaths.length > input.maxEntries || input.materializedRoots.length > input.maxEntries) throw invalidInput(operation, void 0, "Staged materialization selectors exceed maxEntries");
|
|
1595
|
+
validateCanonicalPathSet(input.materializedPaths, operation);
|
|
1596
|
+
validateCanonicalPathSet(input.materializedRoots, operation);
|
|
1597
|
+
});
|
|
1598
|
+
const opening = yield* observeGitStagedIndexBinding(fs, executable, input, operation);
|
|
1599
|
+
const objectIds = stagedRegularBlobObjectIds(opening.entries, input.materializedPaths, input.materializedRoots);
|
|
1600
|
+
const blobs = (yield* readGitBlobBatch(executable, opening.anchor.root, {
|
|
1601
|
+
blobs: objectIds,
|
|
1602
|
+
objectFormat: opening.anchor.objectFormat,
|
|
1603
|
+
maxBlobs: input.maxEntries,
|
|
1604
|
+
maxBlobBytes: input.maxBlobBytes,
|
|
1605
|
+
maxTotalBytes: input.maxBlobBytes
|
|
1606
|
+
}, operation)).map(({ blob: objectId, bytes }) => Object.freeze({
|
|
1607
|
+
objectId,
|
|
1608
|
+
bytes
|
|
1609
|
+
}));
|
|
1610
|
+
const closing = yield* observeClosingGitStagedIndexBinding(fs, executable, input, operation);
|
|
1611
|
+
return Object.freeze({
|
|
1612
|
+
opening,
|
|
1613
|
+
blobs: Object.freeze(blobs),
|
|
1614
|
+
closing
|
|
1615
|
+
});
|
|
1616
|
+
});
|
|
1617
|
+
const readGitBlobAtPath = Effect.fn("contentWorkspace.readGitBlobAtPath")(function* (input) {
|
|
1618
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1619
|
+
const executable = gitExecutable;
|
|
1620
|
+
const root = yield* requireExactGitRoot(fs, executable, input.root, "read-git-blob-at-path");
|
|
1621
|
+
yield* checked("read-git-blob-at-path", () => {
|
|
1622
|
+
validateRefName(input.refName, "read-git-blob-at-path");
|
|
1623
|
+
validateObject(input.commit, "commit", "read-git-blob-at-path");
|
|
1624
|
+
validateObject(input.tree, "tree", "read-git-blob-at-path");
|
|
1625
|
+
validateRelativePath(input.path, false, "read-git-blob-at-path");
|
|
1626
|
+
validateLimit(input.maxBytes, "maxBytes", "read-git-blob-at-path");
|
|
1627
|
+
});
|
|
1628
|
+
const refCommit = yield* requireExactCommit(executable, root, input.refName, "read-git-blob-at-path");
|
|
1629
|
+
if (!(yield* localGitAncestry(executable, root, input.commit, refCommit, "read-git-blob-at-path"))) return yield* fail$4("read-git-blob-at-path", "GitFailed", input.commit, "Selected commit is not reachable from the selected ref");
|
|
1630
|
+
const commit = yield* requireExactCommit(executable, root, input.commit, "read-git-blob-at-path");
|
|
1631
|
+
const tree = yield* gitText$1(executable, root, [
|
|
1632
|
+
"rev-parse",
|
|
1633
|
+
"--verify",
|
|
1634
|
+
"--end-of-options",
|
|
1635
|
+
`${commit}^{tree}`
|
|
1636
|
+
], "read-git-blob-at-path");
|
|
1637
|
+
if (tree !== input.tree) return yield* fail$4("read-git-blob-at-path", "IdentityChanged", input.tree, "Commit tree differs");
|
|
1638
|
+
const blob = yield* gitText$1(executable, root, [
|
|
1639
|
+
"rev-parse",
|
|
1640
|
+
"--verify",
|
|
1641
|
+
"--end-of-options",
|
|
1642
|
+
`${commit}:${input.path}`
|
|
1643
|
+
], "read-git-blob-at-path");
|
|
1644
|
+
validateObject(blob, "blob", "read-git-blob-at-path");
|
|
1645
|
+
yield* requireGitObjectType(executable, root, blob, "blob", "read-git-blob-at-path");
|
|
1646
|
+
const bytes = yield* gitBytes$1(executable, root, [
|
|
1647
|
+
"cat-file",
|
|
1648
|
+
"blob",
|
|
1649
|
+
blob
|
|
1650
|
+
], "read-git-blob-at-path", input.maxBytes);
|
|
1651
|
+
return Object.freeze({
|
|
1652
|
+
refCommit,
|
|
1653
|
+
commit,
|
|
1654
|
+
tree,
|
|
1655
|
+
blob,
|
|
1656
|
+
bytes
|
|
1657
|
+
});
|
|
1658
|
+
});
|
|
1659
|
+
const isLocalGitAncestor = Effect.fn("contentWorkspace.isLocalGitAncestor")(function* (input) {
|
|
1660
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1661
|
+
const executable = gitExecutable;
|
|
1662
|
+
const root = yield* requireExactGitRoot(fs, executable, input.root, "local-git-ancestry");
|
|
1663
|
+
yield* checked("local-git-ancestry", () => {
|
|
1664
|
+
validateObject(input.ancestorCommit, "ancestorCommit", "local-git-ancestry");
|
|
1665
|
+
validateObject(input.descendantCommit, "descendantCommit", "local-git-ancestry");
|
|
1666
|
+
});
|
|
1667
|
+
yield* requireExactCommit(executable, root, input.ancestorCommit, "local-git-ancestry");
|
|
1668
|
+
yield* requireExactCommit(executable, root, input.descendantCommit, "local-git-ancestry");
|
|
1669
|
+
return yield* localGitAncestry(executable, root, input.ancestorCommit, input.descendantCommit, "local-git-ancestry");
|
|
1670
|
+
});
|
|
1671
|
+
const listGitChangedPaths = Effect.fn("contentWorkspace.listGitChangedPaths")(function* (input) {
|
|
1672
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1673
|
+
const executable = gitExecutable;
|
|
1674
|
+
const root = yield* requireExactGitRoot(fs, executable, input.root, "list-git-changed-paths");
|
|
1675
|
+
yield* checked("list-git-changed-paths", () => {
|
|
1676
|
+
validateObject(input.fromCommit, "fromCommit", "list-git-changed-paths");
|
|
1677
|
+
validateObject(input.toCommit, "toCommit", "list-git-changed-paths");
|
|
1678
|
+
validateLimit(input.maxBytes, "maxBytes", "list-git-changed-paths");
|
|
1679
|
+
});
|
|
1680
|
+
yield* requireExactCommit(executable, root, input.fromCommit, "list-git-changed-paths");
|
|
1681
|
+
yield* requireExactCommit(executable, root, input.toCommit, "list-git-changed-paths");
|
|
1682
|
+
return yield* gitBytes$1(executable, root, [
|
|
1683
|
+
"diff",
|
|
1684
|
+
"--name-only",
|
|
1685
|
+
"--no-renames",
|
|
1686
|
+
"-z",
|
|
1687
|
+
input.fromCommit,
|
|
1688
|
+
input.toCommit,
|
|
1689
|
+
"--"
|
|
1690
|
+
], "list-git-changed-paths", input.maxBytes);
|
|
1691
|
+
});
|
|
1692
|
+
const readFile = Effect.fn("contentWorkspace.readFile")(function* (input) {
|
|
1693
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1694
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "read-file");
|
|
1695
|
+
return yield* readBoundedRegularFile(fs, yield* checked("read-file", () => {
|
|
1696
|
+
validateLimit(input.maxBytes, "maxBytes", "read-file");
|
|
1697
|
+
return resolveContained(root, input.path, false, "read-file");
|
|
1698
|
+
}), input.maxBytes, "read-file");
|
|
1699
|
+
});
|
|
1700
|
+
const readTree = Effect.fn("contentWorkspace.readTree")(function* (input) {
|
|
1701
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1702
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "read-tree");
|
|
1703
|
+
return yield* readLocalTree(fs, yield* checked("read-tree", () => {
|
|
1704
|
+
validateLimits(input.maxEntries, input.maxBytes, "read-tree");
|
|
1705
|
+
return resolveContained(root, input.path, true, "read-tree");
|
|
1706
|
+
}), input.objectFormat, input.maxEntries, input.maxBytes);
|
|
1707
|
+
});
|
|
1708
|
+
const materializeContentTree = Effect.fn("contentWorkspace.materializeContentTree")(function* (input) {
|
|
1709
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1710
|
+
if (!materializeContentTreeInputValidator.Check(input)) return yield* fail$4("materialize-content-tree", "InvalidInput", void 0, "Content tree input does not match the bounded resource contract");
|
|
1711
|
+
yield* checked("materialize-content-tree", () => validateContentTreeInput(input));
|
|
1712
|
+
const parent = yield* requireContentTreeParent(fs, input.parentRoot);
|
|
1713
|
+
const root = path.join(parent, input.directoryName);
|
|
1714
|
+
const present = yield* fs.exists(root).pipe(mapPlatform$4("materialize-content-tree", root));
|
|
1715
|
+
if (present) yield* requireContentTreeDirectory(fs, parent, root);
|
|
1716
|
+
if (present && (yield* contentTreeMatches(fs, parent, root, input))) return Object.freeze({ root });
|
|
1717
|
+
return yield* Effect.acquireUseRelease(fs.makeTempDirectory({
|
|
1718
|
+
directory: parent,
|
|
1719
|
+
prefix: CONTENT_TREE_STAGE_PREFIX
|
|
1720
|
+
}).pipe(mapPlatform$4("materialize-content-tree", parent)), (stage) => Effect.gen(function* () {
|
|
1721
|
+
yield* requireContentTreeStage(fs, parent, stage);
|
|
1722
|
+
yield* populateContentTree(fs, stage, input);
|
|
1723
|
+
yield* cutOverContentTree(fs, parent, root, stage, present);
|
|
1724
|
+
return Object.freeze({ root });
|
|
1725
|
+
}), (stage, useExit) => {
|
|
1726
|
+
if (Exit.isSuccess(useExit)) return Effect.void;
|
|
1727
|
+
return cleanupContentTreeStage(fs, parent, stage).pipe(Effect.catchCause((cleanupCause) => Effect.failCause(Cause.combine(useExit.cause, cleanupCause))));
|
|
1728
|
+
});
|
|
1729
|
+
});
|
|
1730
|
+
const capture = Effect.fn("contentWorkspace.capture")(function* (input) {
|
|
1731
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1732
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "capture");
|
|
1733
|
+
yield* requireGitWorkspaceRoot(gitExecutable, root, "capture");
|
|
1734
|
+
const rootIdentity = yield* fs.stat(root).pipe(mapPlatform$4("capture", root));
|
|
1735
|
+
yield* checked("capture", () => {
|
|
1736
|
+
validateOpaque(input.readToken, "readToken", "capture");
|
|
1737
|
+
validateLimits(input.maxEntries, input.maxBytes, "capture");
|
|
1738
|
+
validateDistinctPaths(input.paths, "capture");
|
|
1739
|
+
});
|
|
1740
|
+
const budget = makeCaptureBudget(input);
|
|
1741
|
+
const paths = yield* Effect.forEach(input.paths, (relative) => Effect.gen(function* () {
|
|
1742
|
+
const candidate = yield* checked("capture", () => resolveContained(root, relative, false, "capture"));
|
|
1743
|
+
if (!(yield* fs.exists(candidate).pipe(mapPlatform$4("capture", candidate)))) return Object.freeze({
|
|
1744
|
+
path: relative,
|
|
1745
|
+
entries: null
|
|
1746
|
+
});
|
|
1747
|
+
const captured = yield* captureTree(fs, candidate, "capture", budget);
|
|
1748
|
+
return Object.freeze({
|
|
1749
|
+
path: relative,
|
|
1750
|
+
entries: captured
|
|
1751
|
+
});
|
|
1752
|
+
}));
|
|
1753
|
+
const handle = randomUUID();
|
|
1754
|
+
const publicPaths = Object.freeze(paths.map((image) => image.path));
|
|
1755
|
+
captureAuthorities.set(handle, {
|
|
1756
|
+
handle,
|
|
1757
|
+
root,
|
|
1758
|
+
readToken: input.readToken,
|
|
1759
|
+
rootDev: rootIdentity.dev,
|
|
1760
|
+
rootIno: rootIdentity.ino,
|
|
1761
|
+
maxEntries: input.maxEntries,
|
|
1762
|
+
maxBytes: input.maxBytes,
|
|
1763
|
+
preimages: new Map(paths.map((image) => [image.path, image])),
|
|
1764
|
+
paths: publicPaths,
|
|
1765
|
+
postimages: /* @__PURE__ */ new Map(),
|
|
1766
|
+
mutatedPaths: /* @__PURE__ */ new Set(),
|
|
1767
|
+
restoredPaths: /* @__PURE__ */ new Set(),
|
|
1768
|
+
uncertainPaths: /* @__PURE__ */ new Set(),
|
|
1769
|
+
lifecycle: "Captured"
|
|
1770
|
+
});
|
|
1771
|
+
return Object.freeze({
|
|
1772
|
+
handle,
|
|
1773
|
+
readToken: input.readToken,
|
|
1774
|
+
paths: publicPaths
|
|
1775
|
+
});
|
|
1776
|
+
});
|
|
1777
|
+
const apply = Effect.fn("contentWorkspace.apply")(function* (input) {
|
|
1778
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1779
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "apply");
|
|
1780
|
+
yield* requireGitWorkspaceRoot(gitExecutable, root, "apply");
|
|
1781
|
+
yield* checked("apply", () => {
|
|
1782
|
+
validateOpaque(input.planDigest, "planDigest", "apply");
|
|
1783
|
+
validateOpaque(input.readToken, "readToken", "apply");
|
|
1784
|
+
validateOpaque(input.captureHandle, "captureHandle", "apply");
|
|
1785
|
+
});
|
|
1786
|
+
const authority = yield* requireCaptureAuthority(fs, captureAuthorities, consumedHandles, input.captureHandle, root, input.readToken, input.planDigest, "apply");
|
|
1787
|
+
if (authority.lifecycle === "Partial" || authority.lifecycle === "Applying" || authority.lifecycle === "Restoring") return yield* fail$4("apply", "HandleState", void 0, `Capture handle is ${authority.lifecycle}`);
|
|
1788
|
+
if (authority.lifecycle === "Restored") return yield* fail$4("apply", "HandleConsumed", void 0, "Capture handle has already been restored");
|
|
1789
|
+
yield* validateWriteSet(root, authority, input.writes);
|
|
1790
|
+
if ((yield* Effect.forEach(input.writes, (write) => writeIsExact(fs, root, write, makeCaptureBudget(authority)))).every(Boolean)) {
|
|
1791
|
+
authority.planDigest = input.planDigest;
|
|
1792
|
+
authority.lifecycle = authority.lifecycle === "Applied" ? "Applied" : "Converged";
|
|
1793
|
+
return receipt(input.planDigest, input.readToken, "Converged", []);
|
|
1794
|
+
}
|
|
1795
|
+
if (authority.lifecycle !== "Captured") return yield* fail$4("apply", "HandleState", void 0, `Capture handle cannot apply from ${authority.lifecycle}`);
|
|
1796
|
+
for (const write of input.writes) {
|
|
1797
|
+
const expected = authority.preimages.get(write.path);
|
|
1798
|
+
if (expected === void 0) return yield* fail$4("apply", "InvalidInput", write.path, "Write path has no captured preimage");
|
|
1799
|
+
if (!equalPreimage(yield* observePreimage(fs, root, write.path, "apply", makeCaptureBudget(authority)), expected)) return yield* fail$4("apply", "IdentityChanged", write.path, "Write path changed after capture");
|
|
1800
|
+
}
|
|
1801
|
+
authority.planDigest = input.planDigest;
|
|
1802
|
+
authority.lifecycle = "Applying";
|
|
1803
|
+
const changedPaths = [];
|
|
1804
|
+
for (const write of input.writes) {
|
|
1805
|
+
const expected = authority.preimages.get(write.path);
|
|
1806
|
+
if (expected === void 0) {
|
|
1807
|
+
authority.lifecycle = "Partial";
|
|
1808
|
+
return yield* fail$4("apply", "InvalidInput", write.path, "Write path lost its captured preimage");
|
|
1809
|
+
}
|
|
1810
|
+
if (!equalPreimage(yield* observePreimage(fs, root, write.path, "apply", makeCaptureBudget(authority)), expected)) {
|
|
1811
|
+
authority.lifecycle = "Partial";
|
|
1812
|
+
return yield* fail$4("apply", "IdentityChanged", write.path, "Write path changed immediately before mutation");
|
|
1813
|
+
}
|
|
1814
|
+
authority.mutatedPaths.add(write.path);
|
|
1815
|
+
const applied = yield* Effect.result(applyWrite(fs, root, write, makeCaptureBudget(authority)));
|
|
1816
|
+
const postimage = yield* Effect.result(observePreimage(fs, root, write.path, "apply", makeCaptureBudget(authority)));
|
|
1817
|
+
if (postimage._tag === "Success") authority.postimages.set(write.path, postimage.success);
|
|
1818
|
+
else authority.uncertainPaths.add(write.path);
|
|
1819
|
+
if (applied._tag === "Failure") {
|
|
1820
|
+
authority.lifecycle = "Partial";
|
|
1821
|
+
return yield* Effect.fail(applied.failure);
|
|
1822
|
+
}
|
|
1823
|
+
changedPaths.push(write.path);
|
|
1824
|
+
}
|
|
1825
|
+
authority.lifecycle = "Applied";
|
|
1826
|
+
return receipt(input.planDigest, input.readToken, "Applied", changedPaths);
|
|
1827
|
+
});
|
|
1828
|
+
const restore = Effect.fn("contentWorkspace.restore")(function* (input) {
|
|
1829
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1830
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "restore");
|
|
1831
|
+
yield* requireGitWorkspaceRoot(gitExecutable, root, "restore");
|
|
1832
|
+
yield* checked("restore", () => {
|
|
1833
|
+
validateOpaque(input.planDigest, "planDigest", "restore");
|
|
1834
|
+
validateOpaque(input.readToken, "readToken", "restore");
|
|
1835
|
+
validateOpaque(input.captureHandle, "captureHandle", "restore");
|
|
1836
|
+
});
|
|
1837
|
+
const authority = yield* requireCaptureAuthority(fs, captureAuthorities, consumedHandles, input.captureHandle, root, input.readToken, input.planDigest, "restore");
|
|
1838
|
+
if (authority.lifecycle === "Converged") {
|
|
1839
|
+
authority.lifecycle = "Restored";
|
|
1840
|
+
return receipt(input.planDigest, input.readToken, "Restored", []);
|
|
1841
|
+
}
|
|
1842
|
+
if (authority.lifecycle !== "Applied" && authority.lifecycle !== "Partial") return yield* fail$4("restore", authority.lifecycle === "Restored" ? "HandleConsumed" : "HandleState", void 0, `Capture handle cannot restore from ${authority.lifecycle}`);
|
|
1843
|
+
if (authority.uncertainPaths.size > 0) return yield* fail$4("restore", "HandleState", void 0, "Capture handle has an unobservable partial postimage");
|
|
1844
|
+
for (const relative of authority.paths) {
|
|
1845
|
+
const preimage = authority.preimages.get(relative);
|
|
1846
|
+
const postimage = authority.postimages.get(relative);
|
|
1847
|
+
if (preimage === void 0) return yield* fail$4("restore", "HandleState", relative, "Capture evidence is incomplete");
|
|
1848
|
+
const current = yield* observePreimage(fs, root, relative, "restore", makeCaptureBudget(authority));
|
|
1849
|
+
if (equalPreimage(current, preimage)) {
|
|
1850
|
+
if (authority.mutatedPaths.has(relative)) authority.restoredPaths.add(relative);
|
|
1851
|
+
continue;
|
|
1852
|
+
}
|
|
1853
|
+
if (postimage === void 0 || !equalPreimage(current, postimage)) {
|
|
1854
|
+
authority.lifecycle = "Partial";
|
|
1855
|
+
return yield* fail$4("restore", "IdentityChanged", relative, "Path changed after apply; restore refused");
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
authority.lifecycle = "Restoring";
|
|
1859
|
+
const restored = [];
|
|
1860
|
+
for (const relative of authority.paths) {
|
|
1861
|
+
if (!authority.mutatedPaths.has(relative) || authority.restoredPaths.has(relative)) continue;
|
|
1862
|
+
const preimage = authority.preimages.get(relative);
|
|
1863
|
+
const postimage = authority.postimages.get(relative);
|
|
1864
|
+
if (preimage === void 0 || postimage === void 0) {
|
|
1865
|
+
authority.lifecycle = "Partial";
|
|
1866
|
+
return yield* fail$4("restore", "HandleState", relative, "Restore evidence is incomplete");
|
|
1867
|
+
}
|
|
1868
|
+
const immediate = yield* observePreimage(fs, root, relative, "restore", makeCaptureBudget(authority));
|
|
1869
|
+
if (equalPreimage(immediate, preimage)) {
|
|
1870
|
+
authority.restoredPaths.add(relative);
|
|
1871
|
+
continue;
|
|
1872
|
+
}
|
|
1873
|
+
if (!equalPreimage(immediate, postimage)) {
|
|
1874
|
+
authority.lifecycle = "Partial";
|
|
1875
|
+
return yield* fail$4("restore", "IdentityChanged", relative, "Path changed immediately before restore");
|
|
1876
|
+
}
|
|
1877
|
+
const restoredPath = yield* Effect.result(restorePreimage(fs, root, preimage, makeCaptureBudget(authority)));
|
|
1878
|
+
if (restoredPath._tag === "Failure") {
|
|
1879
|
+
authority.lifecycle = "Partial";
|
|
1880
|
+
const observed = yield* Effect.result(observePreimage(fs, root, relative, "restore", makeCaptureBudget(authority)));
|
|
1881
|
+
if (observed._tag === "Failure") authority.uncertainPaths.add(relative);
|
|
1882
|
+
else if (equalPreimage(observed.success, preimage)) authority.restoredPaths.add(relative);
|
|
1883
|
+
return yield* Effect.fail(restoredPath.failure);
|
|
1884
|
+
}
|
|
1885
|
+
if (!equalPreimage(yield* observePreimage(fs, root, relative, "restore", makeCaptureBudget(authority)), preimage)) {
|
|
1886
|
+
authority.lifecycle = "Partial";
|
|
1887
|
+
return yield* fail$4("restore", "IdentityChanged", relative, "Restored path did not match its captured preimage");
|
|
1888
|
+
}
|
|
1889
|
+
authority.restoredPaths.add(relative);
|
|
1890
|
+
authority.postimages.set(relative, preimage);
|
|
1891
|
+
restored.push(relative);
|
|
1892
|
+
}
|
|
1893
|
+
authority.lifecycle = "Restored";
|
|
1894
|
+
return receipt(input.planDigest, input.readToken, "Restored", restored);
|
|
1895
|
+
});
|
|
1896
|
+
const settle = Effect.fn("contentWorkspace.settle")(function* (input) {
|
|
1897
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1898
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "settle");
|
|
1899
|
+
yield* requireGitWorkspaceRoot(gitExecutable, root, "settle");
|
|
1900
|
+
yield* checked("settle", () => {
|
|
1901
|
+
validateOpaque(input.planDigest, "planDigest", "settle");
|
|
1902
|
+
validateOpaque(input.readToken, "readToken", "settle");
|
|
1903
|
+
validateOpaque(input.captureHandle, "captureHandle", "settle");
|
|
1904
|
+
});
|
|
1905
|
+
const authority = yield* requireCaptureAuthority(fs, captureAuthorities, consumedHandles, input.captureHandle, root, input.readToken, input.planDigest, "settle");
|
|
1906
|
+
if (authority.lifecycle !== "Applied" && authority.lifecycle !== "Converged" && authority.lifecycle !== "Restored") return yield* fail$4("settle", "HandleState", void 0, `Capture handle cannot settle from ${authority.lifecycle}`);
|
|
1907
|
+
captureAuthorities.delete(input.captureHandle);
|
|
1908
|
+
consumedHandles.add(input.captureHandle);
|
|
1909
|
+
return Object.freeze({
|
|
1910
|
+
planDigest: input.planDigest,
|
|
1911
|
+
readToken: input.readToken,
|
|
1912
|
+
outcome: "Settled",
|
|
1913
|
+
handle: input.captureHandle
|
|
1914
|
+
});
|
|
1915
|
+
});
|
|
1916
|
+
const release = Effect.fn("contentWorkspace.release")(function* (input) {
|
|
1917
|
+
const fs = yield* FileSystem.FileSystem;
|
|
1918
|
+
const root = yield* requireCanonicalRoot(fs, input.root, "release");
|
|
1919
|
+
yield* requireGitWorkspaceRoot(gitExecutable, root, "release");
|
|
1920
|
+
yield* checked("release", () => {
|
|
1921
|
+
validateOpaque(input.readToken, "readToken", "release");
|
|
1922
|
+
validateOpaque(input.captureHandle, "captureHandle", "release");
|
|
1923
|
+
});
|
|
1924
|
+
const authority = yield* requireCaptureAuthority(fs, captureAuthorities, consumedHandles, input.captureHandle, root, input.readToken, void 0, "release");
|
|
1925
|
+
const noMutation = authority.lifecycle === "Captured" || authority.lifecycle === "Converged";
|
|
1926
|
+
const unsettled = authority.lifecycle === "Partial" || authority.lifecycle === "Applying" || authority.lifecycle === "Restoring";
|
|
1927
|
+
if (input.disposition === "NoMutation" && !noMutation) return yield* fail$4("release", "HandleState", void 0, `No-mutation release is false from ${authority.lifecycle}`);
|
|
1928
|
+
if (input.disposition === "UnsettledRecovery" && !unsettled) return yield* fail$4("release", "HandleState", void 0, `Unsettled release is false from ${authority.lifecycle}`);
|
|
1929
|
+
captureAuthorities.delete(input.captureHandle);
|
|
1930
|
+
consumedHandles.add(input.captureHandle);
|
|
1931
|
+
return Object.freeze({
|
|
1932
|
+
readToken: input.readToken,
|
|
1933
|
+
outcome: input.disposition === "NoMutation" ? "ReleasedUnmutated" : "ReleasedUnsettled",
|
|
1934
|
+
handle: input.captureHandle
|
|
1935
|
+
});
|
|
1936
|
+
});
|
|
1937
|
+
return Object.freeze({
|
|
1938
|
+
inspectWorkspace,
|
|
1939
|
+
inspectGitRef,
|
|
1940
|
+
inspectGitWorkspace,
|
|
1941
|
+
readGitTree,
|
|
1942
|
+
readGitBlob,
|
|
1943
|
+
readGitBlobs,
|
|
1944
|
+
captureGitWorkspaceEvidence,
|
|
1945
|
+
observeGitStagedIndex,
|
|
1946
|
+
readGitBlobAtPath,
|
|
1947
|
+
isLocalGitAncestor,
|
|
1948
|
+
listGitChangedPaths,
|
|
1949
|
+
readFile,
|
|
1950
|
+
readTree,
|
|
1951
|
+
materializeContentTree,
|
|
1952
|
+
capture,
|
|
1953
|
+
apply,
|
|
1954
|
+
restore,
|
|
1955
|
+
settle,
|
|
1956
|
+
release
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
/**
|
|
1960
|
+
* Realizes the Git content-workspace provider as a ready Effect resource.
|
|
1961
|
+
*
|
|
1962
|
+
* Node platform services remain provider-owned and are supplied lazily to each
|
|
1963
|
+
* operation, so callers retain Effect cancellation and typed failure behavior
|
|
1964
|
+
* without reconstructing effects from promises.
|
|
1965
|
+
*/
|
|
1966
|
+
function makeNodeContentWorkspaceResource(options = {}) {
|
|
1967
|
+
const resource = makeContentWorkspaceResource(options);
|
|
1968
|
+
return Object.freeze({
|
|
1969
|
+
inspectWorkspace: (input) => provideNodeServices$1(resource.inspectWorkspace(input)),
|
|
1970
|
+
inspectGitRef: (input) => provideNodeServices$1(resource.inspectGitRef(input)),
|
|
1971
|
+
inspectGitWorkspace: (input) => provideNodeServices$1(resource.inspectGitWorkspace(input)),
|
|
1972
|
+
readGitTree: (input) => provideNodeServices$1(resource.readGitTree(input)),
|
|
1973
|
+
readGitBlob: (input) => provideNodeServices$1(resource.readGitBlob(input)),
|
|
1974
|
+
readGitBlobs: (input) => provideNodeServices$1(resource.readGitBlobs(input)),
|
|
1975
|
+
captureGitWorkspaceEvidence: (input) => provideNodeServices$1(resource.captureGitWorkspaceEvidence(input)),
|
|
1976
|
+
observeGitStagedIndex: (input) => provideNodeServices$1(resource.observeGitStagedIndex(input)),
|
|
1977
|
+
readGitBlobAtPath: (input) => provideNodeServices$1(resource.readGitBlobAtPath(input)),
|
|
1978
|
+
isLocalGitAncestor: (input) => provideNodeServices$1(resource.isLocalGitAncestor(input)),
|
|
1979
|
+
listGitChangedPaths: (input) => provideNodeServices$1(resource.listGitChangedPaths(input)),
|
|
1980
|
+
readFile: (input) => provideNodeServices$1(resource.readFile(input)),
|
|
1981
|
+
readTree: (input) => provideNodeServices$1(resource.readTree(input)),
|
|
1982
|
+
materializeContentTree: (input) => provideNodeServices$1(resource.materializeContentTree(input)),
|
|
1983
|
+
capture: (input) => provideNodeServices$1(resource.capture(input)),
|
|
1984
|
+
apply: (input) => provideNodeServices$1(resource.apply(input)),
|
|
1985
|
+
restore: (input) => provideNodeServices$1(resource.restore(input)),
|
|
1986
|
+
settle: (input) => provideNodeServices$1(resource.settle(input)),
|
|
1987
|
+
release: (input) => provideNodeServices$1(resource.release(input))
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
function provideNodeServices$1(operation) {
|
|
1991
|
+
return operation.pipe(Effect.provide(NodeServices.layer));
|
|
1992
|
+
}
|
|
1993
|
+
function readLocalTree(fs, root, objectFormat, maxEntries, maxBytes) {
|
|
1994
|
+
const entries = [];
|
|
1995
|
+
let bytesRead = 0;
|
|
1996
|
+
const walk = (directory, relative) => Effect.gen(function* () {
|
|
1997
|
+
yield* requireExactExistingPath(fs, directory, "read-tree");
|
|
1998
|
+
if ((yield* fs.stat(directory).pipe(mapPlatform$4("read-tree", directory))).type !== "Directory") return yield* fail$4("read-tree", "UnsupportedEntry", directory, "Content tree root must be a directory");
|
|
1999
|
+
const names = (yield* fs.readDirectory(directory).pipe(mapPlatform$4("read-tree", directory))).sort(compareText$6);
|
|
2000
|
+
for (const name of names) {
|
|
2001
|
+
const childRelative = relative === "" ? name : `${relative}/${name}`;
|
|
2002
|
+
yield* checked("read-tree", () => validateRelativePath(childRelative, false, "read-tree"));
|
|
2003
|
+
const child = path.join(directory, name);
|
|
2004
|
+
yield* requireExactExistingPath(fs, child, "read-tree");
|
|
2005
|
+
const childInfo = yield* fs.stat(child).pipe(mapPlatform$4("read-tree", child));
|
|
2006
|
+
if (childInfo.type === "Directory") {
|
|
2007
|
+
yield* walk(child, childRelative);
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
if (childInfo.type !== "File") return yield* fail$4("read-tree", "UnsupportedEntry", childRelative, "Content tree contains a non-regular entry");
|
|
2011
|
+
if (entries.length >= maxEntries) return yield* fail$4("read-tree", "LimitExceeded", childRelative, "Content tree exceeds maxEntries");
|
|
2012
|
+
const remaining = maxBytes - bytesRead;
|
|
2013
|
+
if (remaining < 0) return yield* fail$4("read-tree", "LimitExceeded", childRelative, "Content tree exceeds maxBytes");
|
|
2014
|
+
const bytes = yield* readBoundedRegularFile(fs, child, remaining, "read-tree");
|
|
2015
|
+
bytesRead += bytes.byteLength;
|
|
2016
|
+
entries.push(Object.freeze({
|
|
2017
|
+
path: childRelative,
|
|
2018
|
+
mode: (childInfo.mode & 73) === 0 ? "100644" : "100755",
|
|
2019
|
+
blob: gitBlobId(bytes, objectFormat)
|
|
2020
|
+
}));
|
|
2021
|
+
}
|
|
2022
|
+
});
|
|
2023
|
+
return walk(root, "").pipe(Effect.map(() => Object.freeze(entries.sort((left, right) => compareText$6(left.path, right.path)))));
|
|
2024
|
+
}
|
|
2025
|
+
function captureTree(fs, root, operation, budget) {
|
|
2026
|
+
const entries = [];
|
|
2027
|
+
const walk = (candidate, relative) => Effect.gen(function* () {
|
|
2028
|
+
yield* requireExactExistingPath(fs, candidate, operation);
|
|
2029
|
+
const info = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2030
|
+
if (budget.entries >= budget.maxEntries) return yield* fail$4(operation, "LimitExceeded", candidate, "Captured paths exceed maxEntries");
|
|
2031
|
+
budget.entries += 1;
|
|
2032
|
+
if (info.type === "File") {
|
|
2033
|
+
const remaining = budget.maxBytes - budget.bytes;
|
|
2034
|
+
if (remaining < 0 || info.size > BigInt(remaining)) return yield* fail$4(operation, "LimitExceeded", candidate, "Captured paths exceed maxBytes");
|
|
2035
|
+
const bytes = yield* readBoundedRegularFile(fs, candidate, remaining, operation);
|
|
2036
|
+
budget.bytes += bytes.byteLength;
|
|
2037
|
+
entries.push(Object.freeze({
|
|
2038
|
+
kind: "File",
|
|
2039
|
+
path: relative,
|
|
2040
|
+
mode: info.mode & 511,
|
|
2041
|
+
bytes
|
|
2042
|
+
}));
|
|
2043
|
+
return;
|
|
2044
|
+
}
|
|
2045
|
+
if (info.type !== "Directory") return yield* fail$4(operation, "UnsupportedEntry", candidate, "Path preimage contains a non-regular entry");
|
|
2046
|
+
entries.push(Object.freeze({
|
|
2047
|
+
kind: "Directory",
|
|
2048
|
+
path: relative,
|
|
2049
|
+
mode: info.mode & 511
|
|
2050
|
+
}));
|
|
2051
|
+
const names = (yield* fs.readDirectory(candidate).pipe(mapPlatform$4(operation, candidate))).sort(compareText$6);
|
|
2052
|
+
for (const name of names) {
|
|
2053
|
+
const nextRelative = relative === "" ? name : `${relative}/${name}`;
|
|
2054
|
+
yield* checked(operation, () => validateRelativePath(nextRelative, false, operation));
|
|
2055
|
+
yield* walk(path.join(candidate, name), nextRelative);
|
|
2056
|
+
}
|
|
2057
|
+
});
|
|
2058
|
+
return walk(root, "").pipe(Effect.map(() => Object.freeze(entries)));
|
|
2059
|
+
}
|
|
2060
|
+
function removePathIfPresent(fs, candidate, operation, budget) {
|
|
2061
|
+
return Effect.gen(function* () {
|
|
2062
|
+
if (!(yield* fs.exists(candidate).pipe(mapPlatform$4(operation, candidate)))) return;
|
|
2063
|
+
const entries = yield* captureTree(fs, candidate, operation, budget);
|
|
2064
|
+
for (const entry of [...entries].reverse()) {
|
|
2065
|
+
const target = entry.path === "" ? candidate : path.join(candidate, ...entry.path.split("/"));
|
|
2066
|
+
yield* requireExactExistingPath(fs, target, operation);
|
|
2067
|
+
if (entry.kind === "File") yield* fs.remove(target).pipe(mapPlatform$4(operation, target));
|
|
2068
|
+
else yield* removeEmptyDirectory(fs, target, operation);
|
|
2069
|
+
}
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
function observePreimage(fs, root, relative, operation, budget) {
|
|
2073
|
+
return Effect.gen(function* () {
|
|
2074
|
+
const candidate = yield* checked(operation, () => resolveContained(root, relative, false, operation));
|
|
2075
|
+
if (!(yield* fs.exists(candidate).pipe(mapPlatform$4(operation, candidate)))) return Object.freeze({
|
|
2076
|
+
path: relative,
|
|
2077
|
+
entries: null
|
|
2078
|
+
});
|
|
2079
|
+
const entries = yield* captureTree(fs, candidate, operation, budget);
|
|
2080
|
+
return Object.freeze({
|
|
2081
|
+
path: relative,
|
|
2082
|
+
entries
|
|
2083
|
+
});
|
|
2084
|
+
});
|
|
2085
|
+
}
|
|
2086
|
+
function requireCaptureAuthority(fs, authorities, consumed, handle, root, readToken, planDigest, operation) {
|
|
2087
|
+
return Effect.gen(function* () {
|
|
2088
|
+
if (consumed.has(handle)) return yield* fail$4(operation, "HandleConsumed", void 0, "Capture handle was already settled");
|
|
2089
|
+
const authority = authorities.get(handle);
|
|
2090
|
+
if (authority === void 0) return yield* fail$4(operation, "InvalidHandle", void 0, "Capture handle is not owned by this provider");
|
|
2091
|
+
if (authority.root !== root) return yield* fail$4(operation, "WrongRoot", root, "Capture handle belongs to a different Git root");
|
|
2092
|
+
const rootIdentity = yield* fs.stat(root).pipe(mapPlatform$4(operation, root));
|
|
2093
|
+
if (rootIdentity.dev !== authority.rootDev || !Equal.equals(rootIdentity.ino, authority.rootIno)) return yield* fail$4(operation, "WrongRoot", root, "Capture handle Git-root filesystem identity changed");
|
|
2094
|
+
if (authority.readToken !== readToken) return yield* fail$4(operation, "WrongToken", void 0, "Capture handle readToken does not match");
|
|
2095
|
+
if (planDigest !== void 0 && authority.planDigest !== void 0 && authority.planDigest !== planDigest) return yield* fail$4(operation, "WrongPlan", void 0, "Capture handle belongs to a different write plan");
|
|
2096
|
+
if (operation !== "apply" && operation !== "release" && authority.planDigest === void 0) return yield* fail$4(operation, "WrongPlan", void 0, "Capture handle has not been bound to a write plan");
|
|
2097
|
+
return authority;
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
function validateDistinctPaths(paths, operation) {
|
|
2101
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2102
|
+
for (const relative of paths) {
|
|
2103
|
+
validateRelativePath(relative, false, operation);
|
|
2104
|
+
if (seen.has(relative)) throw invalidInput(operation, relative, "Capture contains duplicate paths");
|
|
2105
|
+
if ([...seen].some((existing) => pathsOverlap(existing, relative))) throw invalidInput(operation, relative, "Capture contains overlapping paths");
|
|
2106
|
+
seen.add(relative);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
function validateContentTreeInput(input) {
|
|
2110
|
+
const operation = "materialize-content-tree";
|
|
2111
|
+
if (input.entries.length > input.maxEntries) throw invalidInput(operation, void 0, "Content tree entries exceed maxEntries");
|
|
2112
|
+
let previousPath;
|
|
2113
|
+
let totalBytes = 0;
|
|
2114
|
+
const exactPaths = /* @__PURE__ */ new Set();
|
|
2115
|
+
for (const entry of input.entries) {
|
|
2116
|
+
if (previousPath !== void 0 && compareText$6(previousPath, entry.path) >= 0) throw invalidInput(operation, entry.path, "Content tree entries must be in strict canonical path order");
|
|
2117
|
+
previousPath = entry.path;
|
|
2118
|
+
exactPaths.add(entry.path);
|
|
2119
|
+
totalBytes += entry.bytes.byteLength;
|
|
2120
|
+
if (!Number.isSafeInteger(totalBytes) || totalBytes > input.maxBytes) throw invalidInput(operation, entry.path, "Content tree bytes exceed maxBytes");
|
|
2121
|
+
}
|
|
2122
|
+
for (const exactPath of exactPaths) {
|
|
2123
|
+
const segments = exactPath.split("/");
|
|
2124
|
+
for (let index = 1; index < segments.length; index += 1) {
|
|
2125
|
+
const ancestor = segments.slice(0, index).join("/");
|
|
2126
|
+
if (exactPaths.has(ancestor)) throw invalidInput(operation, exactPath, `Content tree file descends from file ${ancestor}`);
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
function requireContentTreeParent(fs, candidate) {
|
|
2131
|
+
const operation = "materialize-content-tree";
|
|
2132
|
+
return Effect.gen(function* () {
|
|
2133
|
+
if (!path.isAbsolute(candidate) || path.normalize(candidate) !== candidate || candidate === path.parse(candidate).root) return yield* fail$4(operation, "InvalidInput", candidate, "Content tree parent must be a normalized non-root absolute path");
|
|
2134
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$4(operation, candidate))) !== candidate) return yield* fail$4(operation, "Aliased", candidate, "Content tree parent must be an exact non-symbolic path");
|
|
2135
|
+
if ((yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate))).type !== "Directory") return yield* fail$4(operation, "UnsupportedEntry", candidate, "Content tree parent must be a directory");
|
|
2136
|
+
return candidate;
|
|
2137
|
+
});
|
|
2138
|
+
}
|
|
2139
|
+
function revalidateContentTreeParent(fs, parent) {
|
|
2140
|
+
const operation = "materialize-content-tree";
|
|
2141
|
+
return Effect.gen(function* () {
|
|
2142
|
+
const canonical = yield* fs.realPath(parent).pipe(mapPlatform$4(operation, parent));
|
|
2143
|
+
const info = yield* fs.stat(parent).pipe(mapPlatform$4(operation, parent));
|
|
2144
|
+
if (canonical !== parent || info.type !== "Directory") return yield* fail$4(operation, "IdentityChanged", parent, "Content tree parent path changed");
|
|
2145
|
+
});
|
|
2146
|
+
}
|
|
2147
|
+
function requireContentTreeDirectory(fs, parent, candidate) {
|
|
2148
|
+
const operation = "materialize-content-tree";
|
|
2149
|
+
return Effect.gen(function* () {
|
|
2150
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2151
|
+
if (path.dirname(candidate) !== parent) return yield* fail$4(operation, "IdentityChanged", candidate, "Disposable content tree must remain one direct child of its caller-owned parent");
|
|
2152
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$4(operation, candidate))) !== candidate) return yield* fail$4(operation, "Aliased", candidate, "Disposable content tree must be one exact non-symbolic directory");
|
|
2153
|
+
if ((yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate))).type !== "Directory") return yield* fail$4(operation, "UnsupportedEntry", candidate, "Disposable content tree must be a directory");
|
|
2154
|
+
});
|
|
2155
|
+
}
|
|
2156
|
+
function requireContentTreeStage(fs, parent, candidate) {
|
|
2157
|
+
const operation = "materialize-content-tree";
|
|
2158
|
+
if (!path.basename(candidate).startsWith(CONTENT_TREE_STAGE_PREFIX)) return fail$4(operation, "IdentityChanged", candidate, "Allocated content tree stage does not have the private stage prefix");
|
|
2159
|
+
return requireContentTreeDirectory(fs, parent, candidate);
|
|
2160
|
+
}
|
|
2161
|
+
function populateContentTree(fs, root, input) {
|
|
2162
|
+
const operation = "materialize-content-tree";
|
|
2163
|
+
return Effect.gen(function* () {
|
|
2164
|
+
const createdDirectories = /* @__PURE__ */ new Set([""]);
|
|
2165
|
+
for (const entry of input.entries) {
|
|
2166
|
+
const segments = entry.path.split("/");
|
|
2167
|
+
for (let index = 1; index < segments.length; index += 1) {
|
|
2168
|
+
const relativeDirectory = segments.slice(0, index).join("/");
|
|
2169
|
+
if (createdDirectories.has(relativeDirectory)) continue;
|
|
2170
|
+
const directory = path.join(root, ...relativeDirectory.split("/"));
|
|
2171
|
+
yield* fs.makeDirectory(directory, {
|
|
2172
|
+
recursive: false,
|
|
2173
|
+
mode: 448
|
|
2174
|
+
}).pipe(mapPlatform$4(operation, directory));
|
|
2175
|
+
yield* fs.chmod(directory, 448).pipe(mapPlatform$4(operation, directory));
|
|
2176
|
+
createdDirectories.add(relativeDirectory);
|
|
2177
|
+
}
|
|
2178
|
+
const destination = path.join(root, ...segments);
|
|
2179
|
+
const mode = fileMode(entry.mode);
|
|
2180
|
+
yield* fs.writeFile(destination, entry.bytes, {
|
|
2181
|
+
flag: "wx",
|
|
2182
|
+
mode
|
|
2183
|
+
}).pipe(mapPlatform$4(operation, destination));
|
|
2184
|
+
yield* fs.chmod(destination, mode).pipe(mapPlatform$4(operation, destination));
|
|
2185
|
+
}
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
function contentTreeMatches(fs, parent, root, input) {
|
|
2189
|
+
const operation = "materialize-content-tree";
|
|
2190
|
+
return Effect.gen(function* () {
|
|
2191
|
+
yield* requireContentTreeDirectory(fs, parent, root);
|
|
2192
|
+
const expectedBytes = input.entries.reduce((total, entry) => total + entry.bytes.byteLength, 0);
|
|
2193
|
+
const attempted = yield* Effect.result(readLocalTree(fs, root, "sha256", input.entries.length, expectedBytes).pipe(Effect.mapError((failure) => Object.freeze({
|
|
2194
|
+
...failure,
|
|
2195
|
+
operation
|
|
2196
|
+
}))));
|
|
2197
|
+
if (attempted._tag === "Failure") {
|
|
2198
|
+
if (attempted.failure.reason === "LimitExceeded") return false;
|
|
2199
|
+
return yield* Effect.fail(attempted.failure);
|
|
2200
|
+
}
|
|
2201
|
+
const observed = attempted.success;
|
|
2202
|
+
yield* requireContentTreeDirectory(fs, parent, root);
|
|
2203
|
+
if (observed.length !== input.entries.length) return false;
|
|
2204
|
+
return observed.every((entry, index) => {
|
|
2205
|
+
const expected = input.entries[index];
|
|
2206
|
+
return expected !== void 0 && entry.path === expected.path && entry.mode === expected.mode && entry.blob === gitBlobId(expected.bytes, "sha256");
|
|
2207
|
+
});
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
function removeContentTreeDirectory(fs, parent, candidate) {
|
|
2211
|
+
const operation = "materialize-content-tree";
|
|
2212
|
+
return Effect.gen(function* () {
|
|
2213
|
+
yield* requireContentTreeDirectory(fs, parent, candidate);
|
|
2214
|
+
yield* fs.remove(candidate, {
|
|
2215
|
+
recursive: true,
|
|
2216
|
+
force: false
|
|
2217
|
+
}).pipe(mapPlatform$4(operation, candidate));
|
|
2218
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
2221
|
+
function cleanupContentTreeStage(fs, parent, stage) {
|
|
2222
|
+
const operation = "materialize-content-tree";
|
|
2223
|
+
return Effect.gen(function* () {
|
|
2224
|
+
if (!(yield* fs.exists(stage).pipe(mapPlatform$4(operation, stage)))) return;
|
|
2225
|
+
yield* requireContentTreeStage(fs, parent, stage);
|
|
2226
|
+
yield* removeContentTreeDirectory(fs, parent, stage);
|
|
2227
|
+
});
|
|
2228
|
+
}
|
|
2229
|
+
function cutOverContentTree(fs, parent, root, stage, hadPreimage) {
|
|
2230
|
+
const operation = "materialize-content-tree";
|
|
2231
|
+
const backup = `${stage}.previous`;
|
|
2232
|
+
return Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
2233
|
+
const attempted = yield* Effect.exit(Effect.gen(function* () {
|
|
2234
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2235
|
+
yield* requireContentTreeStage(fs, parent, stage);
|
|
2236
|
+
yield* revalidateContentTreePreimage(fs, parent, root, hadPreimage);
|
|
2237
|
+
if (yield* fs.exists(backup).pipe(mapPlatform$4(operation, backup))) return yield* fail$4(operation, "IdentityChanged", backup, "Private content tree backup path became occupied before cutover");
|
|
2238
|
+
yield* restore(Effect.yieldNow);
|
|
2239
|
+
if (hadPreimage) {
|
|
2240
|
+
yield* fs.rename(root, backup).pipe(mapPlatform$4(operation, root));
|
|
2241
|
+
yield* requireContentTreeDirectory(fs, parent, backup);
|
|
2242
|
+
}
|
|
2243
|
+
yield* fs.rename(stage, root).pipe(mapPlatform$4(operation, root));
|
|
2244
|
+
yield* requireContentTreeDirectory(fs, parent, root);
|
|
2245
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2246
|
+
}));
|
|
2247
|
+
if (attempted._tag === "Failure") {
|
|
2248
|
+
const restored = yield* Effect.exit(restoreContentTreeCutover(fs, parent, root, stage, backup, hadPreimage));
|
|
2249
|
+
if (restored._tag === "Failure") return yield* Effect.failCause(Cause.combine(attempted.cause, restored.cause));
|
|
2250
|
+
return yield* Effect.failCause(attempted.cause);
|
|
2251
|
+
}
|
|
2252
|
+
if (hadPreimage) yield* removeContentTreeDirectory(fs, parent, backup).pipe(Effect.catchCause((cleanupCause) => cleanupCause.reasons.every(Cause.isFailReason) ? Effect.void : Effect.failCause(cleanupCause)));
|
|
2253
|
+
}));
|
|
2254
|
+
}
|
|
2255
|
+
function revalidateContentTreePreimage(fs, parent, root, hadPreimage) {
|
|
2256
|
+
const operation = "materialize-content-tree";
|
|
2257
|
+
return Effect.gen(function* () {
|
|
2258
|
+
const present = yield* fs.exists(root).pipe(mapPlatform$4(operation, root));
|
|
2259
|
+
if (!hadPreimage) {
|
|
2260
|
+
if (present) return yield* fail$4(operation, "IdentityChanged", root, "Absent disposable content tree became occupied before cutover");
|
|
2261
|
+
return;
|
|
2262
|
+
}
|
|
2263
|
+
if (!present) return yield* fail$4(operation, "IdentityChanged", root, "Prior disposable content tree disappeared before cutover");
|
|
2264
|
+
yield* requireContentTreeDirectory(fs, parent, root);
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
function restoreContentTreeCutover(fs, parent, root, stage, backup, hadPreimage) {
|
|
2268
|
+
const operation = "materialize-content-tree";
|
|
2269
|
+
return Effect.gen(function* () {
|
|
2270
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2271
|
+
const rootPresent = yield* fs.exists(root).pipe(mapPlatform$4(operation, root));
|
|
2272
|
+
const stagePresent = yield* fs.exists(stage).pipe(mapPlatform$4(operation, stage));
|
|
2273
|
+
if (!hadPreimage) {
|
|
2274
|
+
if (rootPresent) {
|
|
2275
|
+
if (stagePresent) return yield* fail$4(operation, "CleanupFailed", root, "Cannot distinguish an installed tree while its private stage also exists");
|
|
2276
|
+
yield* removeContentTreeDirectory(fs, parent, root);
|
|
2277
|
+
}
|
|
2278
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2279
|
+
return;
|
|
2280
|
+
}
|
|
2281
|
+
if (!(yield* fs.exists(backup).pipe(mapPlatform$4(operation, backup)))) {
|
|
2282
|
+
if (!rootPresent) return yield* fail$4(operation, "CleanupFailed", root, "Prior content tree and its private backup are both absent");
|
|
2283
|
+
yield* requireContentTreeDirectory(fs, parent, root);
|
|
2284
|
+
return;
|
|
2285
|
+
}
|
|
2286
|
+
yield* requireContentTreeDirectory(fs, parent, backup);
|
|
2287
|
+
if (rootPresent) {
|
|
2288
|
+
if (stagePresent) return yield* fail$4(operation, "CleanupFailed", root, "Cannot replace an unexpected root while the private stage still exists");
|
|
2289
|
+
yield* removeContentTreeDirectory(fs, parent, root);
|
|
2290
|
+
}
|
|
2291
|
+
yield* fs.rename(backup, root).pipe(mapPlatform$4(operation, root));
|
|
2292
|
+
yield* requireContentTreeDirectory(fs, parent, root);
|
|
2293
|
+
yield* revalidateContentTreeParent(fs, parent);
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
function validateGitTreePaths(paths) {
|
|
2297
|
+
if (paths.length === 0 || paths.length > 4096) throw invalidInput("read-git-tree", void 0, "Git tree selection requires between 1 and 4,096 paths");
|
|
2298
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2299
|
+
for (const relative of paths) {
|
|
2300
|
+
validateRelativePath(relative, false, "read-git-tree");
|
|
2301
|
+
if (seen.has(relative)) throw invalidInput("read-git-tree", relative, "Git tree selection contains a duplicate path");
|
|
2302
|
+
if ([...seen].some((existing) => pathsOverlap(existing, relative))) throw invalidInput("read-git-tree", relative, "Git tree selection contains overlapping paths");
|
|
2303
|
+
seen.add(relative);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
function validateWriteSet(root, authority, writes) {
|
|
2307
|
+
return checked("apply", () => {
|
|
2308
|
+
const writePaths = /* @__PURE__ */ new Set();
|
|
2309
|
+
for (const write of writes) {
|
|
2310
|
+
resolveContained(root, write.path, false, "apply");
|
|
2311
|
+
if (!authority.preimages.has(write.path)) throw invalidInput("apply", write.path, "Write path was not captured by this handle");
|
|
2312
|
+
if (writePaths.has(write.path)) throw invalidInput("apply", write.path, "Write plan contains duplicate paths");
|
|
2313
|
+
if ([...writePaths].some((existing) => pathsOverlap(existing, write.path))) throw invalidInput("apply", write.path, "Write plan contains overlapping paths");
|
|
2314
|
+
writePaths.add(write.path);
|
|
2315
|
+
if (write.kind === "ReplaceTree") {
|
|
2316
|
+
const entryPaths = /* @__PURE__ */ new Set();
|
|
2317
|
+
for (const entry of write.entries) {
|
|
2318
|
+
validateRelativePath(entry.path, false, "apply");
|
|
2319
|
+
if (entryPaths.has(entry.path)) throw invalidInput("apply", entry.path, "Replacement tree contains duplicate paths");
|
|
2320
|
+
if ([...entryPaths].some((existing) => pathsOverlap(existing, entry.path))) throw invalidInput("apply", entry.path, "Replacement tree contains a file/descendant collision");
|
|
2321
|
+
entryPaths.add(entry.path);
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
});
|
|
2326
|
+
}
|
|
2327
|
+
function equalPreimage(left, right) {
|
|
2328
|
+
if (left.path !== right.path) return false;
|
|
2329
|
+
if (left.entries === null || right.entries === null) return left.entries === right.entries;
|
|
2330
|
+
if (left.entries.length !== right.entries.length) return false;
|
|
2331
|
+
return left.entries.every((entry, index) => {
|
|
2332
|
+
const candidate = right.entries?.[index];
|
|
2333
|
+
if (candidate === void 0 || entry.kind !== candidate.kind || entry.path !== candidate.path || entry.mode !== candidate.mode) return false;
|
|
2334
|
+
return entry.kind === "Directory" || candidate.kind === "File" && equalBytes(entry.bytes, candidate.bytes);
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
function writeIsExact(fs, root, write, budget) {
|
|
2338
|
+
return Effect.gen(function* () {
|
|
2339
|
+
const current = yield* observePreimage(fs, root, write.path, "apply", budget);
|
|
2340
|
+
if (current.entries === null) return false;
|
|
2341
|
+
if (write.kind === "ReplaceFile") {
|
|
2342
|
+
const entry = current.entries[0];
|
|
2343
|
+
return current.entries.length === 1 && entry?.kind === "File" && entry.path === "" && entry.mode === fileMode(write.mode) && equalBytes(entry.bytes, write.bytes);
|
|
2344
|
+
}
|
|
2345
|
+
const expectedDirectories = /* @__PURE__ */ new Set([""]);
|
|
2346
|
+
const expectedFiles = /* @__PURE__ */ new Map();
|
|
2347
|
+
for (const entry of write.entries) {
|
|
2348
|
+
yield* checked("apply", () => validateRelativePath(entry.path, false, "apply"));
|
|
2349
|
+
expectedFiles.set(entry.path, entry);
|
|
2350
|
+
const segments = entry.path.split("/");
|
|
2351
|
+
for (let index = 1; index < segments.length; index += 1) expectedDirectories.add(segments.slice(0, index).join("/"));
|
|
2352
|
+
}
|
|
2353
|
+
const actualDirectories = current.entries.filter((entry) => entry.kind === "Directory");
|
|
2354
|
+
const actualFiles = current.entries.filter((entry) => entry.kind === "File");
|
|
2355
|
+
if (actualDirectories.length !== expectedDirectories.size || actualFiles.length !== expectedFiles.size) return false;
|
|
2356
|
+
if (actualDirectories.some((entry) => !expectedDirectories.has(entry.path))) return false;
|
|
2357
|
+
return actualFiles.every((entry) => {
|
|
2358
|
+
const expected = expectedFiles.get(entry.path);
|
|
2359
|
+
return expected !== void 0 && entry.mode === fileMode(expected.mode) && equalBytes(entry.bytes, expected.bytes);
|
|
2360
|
+
});
|
|
2361
|
+
});
|
|
2362
|
+
}
|
|
2363
|
+
function replaceTree(fs, candidate, entries, operation, budget) {
|
|
2364
|
+
return Effect.gen(function* () {
|
|
2365
|
+
yield* removePathIfPresent(fs, candidate, operation, budget);
|
|
2366
|
+
yield* ensureDirectoryChain(fs, path.dirname(candidate), operation);
|
|
2367
|
+
yield* fs.makeDirectory(candidate, {
|
|
2368
|
+
recursive: false,
|
|
2369
|
+
mode: 448
|
|
2370
|
+
}).pipe(mapPlatform$4(operation, candidate));
|
|
2371
|
+
yield* requireExactExistingPath(fs, candidate, operation);
|
|
2372
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2373
|
+
for (const entry of entries) {
|
|
2374
|
+
yield* checked(operation, () => validateRelativePath(entry.path, false, operation));
|
|
2375
|
+
if (seen.has(entry.path)) return yield* fail$4(operation, "InvalidInput", entry.path, "Replacement tree has duplicate paths");
|
|
2376
|
+
seen.add(entry.path);
|
|
2377
|
+
yield* writeAtomic(fs, path.join(candidate, ...entry.path.split("/")), entry.bytes, fileMode(entry.mode), operation);
|
|
2378
|
+
}
|
|
2379
|
+
});
|
|
2380
|
+
}
|
|
2381
|
+
function applyWrite(fs, root, write, budget) {
|
|
2382
|
+
return Effect.gen(function* () {
|
|
2383
|
+
const candidate = yield* checked("apply", () => resolveContained(root, write.path, false, "apply"));
|
|
2384
|
+
if (write.kind === "ReplaceFile") {
|
|
2385
|
+
yield* removePathIfPresent(fs, candidate, "apply", budget);
|
|
2386
|
+
yield* writeAtomic(fs, candidate, write.bytes, fileMode(write.mode), "apply");
|
|
2387
|
+
} else yield* replaceTree(fs, candidate, write.entries, "apply", budget);
|
|
2388
|
+
});
|
|
2389
|
+
}
|
|
2390
|
+
function restorePreimage(fs, root, preimage, budget) {
|
|
2391
|
+
return Effect.gen(function* () {
|
|
2392
|
+
const candidate = yield* checked("restore", () => resolveContained(root, preimage.path, false, "restore"));
|
|
2393
|
+
yield* removePathIfPresent(fs, candidate, "restore", budget);
|
|
2394
|
+
if (preimage.entries !== null) yield* restoreTree(fs, candidate, preimage.entries);
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
function restoreTree(fs, candidate, entries) {
|
|
2398
|
+
return Effect.gen(function* () {
|
|
2399
|
+
const directories = entries.filter((entry) => entry.kind === "Directory").sort((left, right) => left.path.length - right.path.length);
|
|
2400
|
+
for (const entry of directories) {
|
|
2401
|
+
const destination = entry.path === "" ? candidate : path.join(candidate, ...entry.path.split("/"));
|
|
2402
|
+
yield* ensureDirectoryChain(fs, path.dirname(destination), "restore");
|
|
2403
|
+
if (!(yield* fs.exists(destination).pipe(mapPlatform$4("restore", destination)))) yield* fs.makeDirectory(destination, {
|
|
2404
|
+
recursive: false,
|
|
2405
|
+
mode: entry.mode
|
|
2406
|
+
}).pipe(mapPlatform$4("restore", destination));
|
|
2407
|
+
yield* requireExactExistingPath(fs, destination, "restore");
|
|
2408
|
+
yield* fs.chmod(destination, entry.mode).pipe(mapPlatform$4("restore", destination));
|
|
2409
|
+
}
|
|
2410
|
+
for (const entry of entries) {
|
|
2411
|
+
if (entry.kind !== "File") continue;
|
|
2412
|
+
yield* writeAtomic(fs, entry.path === "" ? candidate : path.join(candidate, ...entry.path.split("/")), entry.bytes, entry.mode, "restore");
|
|
2413
|
+
}
|
|
2414
|
+
});
|
|
2415
|
+
}
|
|
2416
|
+
function writeAtomic(fs, destination, bytes, mode, operation) {
|
|
2417
|
+
return Effect.gen(function* () {
|
|
2418
|
+
const parent = path.dirname(destination);
|
|
2419
|
+
yield* ensureDirectoryChain(fs, parent, operation);
|
|
2420
|
+
const temporary = path.join(parent, `${ATOMIC_FILE_PREFIX}${randomUUID()}.tmp`);
|
|
2421
|
+
yield* Effect.acquireUseRelease(fs.writeFile(temporary, bytes, {
|
|
2422
|
+
flag: "wx",
|
|
2423
|
+
mode: 384
|
|
2424
|
+
}).pipe(mapPlatform$4(operation, temporary), Effect.as(temporary)), (owned) => Effect.gen(function* () {
|
|
2425
|
+
yield* fs.chmod(owned, mode).pipe(mapPlatform$4(operation, owned));
|
|
2426
|
+
yield* fs.rename(owned, destination).pipe(mapPlatform$4(operation, destination));
|
|
2427
|
+
}), (owned) => fs.exists(owned).pipe(Effect.flatMap((exists) => exists ? fs.remove(owned, { force: false }) : Effect.void), Effect.ignore));
|
|
2428
|
+
});
|
|
2429
|
+
}
|
|
2430
|
+
function readBoundedRegularFile(fs, candidate, maxBytes, operation) {
|
|
2431
|
+
return Effect.gen(function* () {
|
|
2432
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$4(operation, candidate))) !== candidate) return yield* fail$4(operation, "Aliased", candidate, "File path is not canonical");
|
|
2433
|
+
const before = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2434
|
+
if (before.type !== "File") return yield* fail$4(operation, "UnsupportedEntry", candidate, "Expected a regular file");
|
|
2435
|
+
if (before.size > BigInt(maxBytes)) return yield* fail$4(operation, "LimitExceeded", candidate, "File exceeds maxBytes");
|
|
2436
|
+
const bytes = yield* fs.readFile(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2437
|
+
const after = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2438
|
+
if (after.type !== "File" || before.dev !== after.dev || !Equal.equals(before.ino, after.ino) || before.size !== after.size || bytes.byteLength !== Number(after.size)) return yield* fail$4(operation, "IdentityChanged", candidate, "File identity changed while reading");
|
|
2439
|
+
return bytes;
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
function requireCanonicalRoot(fs, candidate, operation) {
|
|
2443
|
+
return Effect.gen(function* () {
|
|
2444
|
+
if (!path.isAbsolute(candidate) || path.normalize(candidate) !== candidate) return yield* fail$4(operation, "InvalidInput", candidate, "Workspace root must be a normalized absolute path");
|
|
2445
|
+
const canonical = yield* fs.realPath(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2446
|
+
const info = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2447
|
+
if (canonical !== candidate || info.type !== "Directory") return yield* fail$4(operation, "Aliased", candidate, "Workspace root must be a canonical directory");
|
|
2448
|
+
return candidate;
|
|
2449
|
+
});
|
|
2450
|
+
}
|
|
2451
|
+
function requireExactGitRoot(fs, executable, candidate, operation) {
|
|
2452
|
+
return Effect.gen(function* () {
|
|
2453
|
+
const root = yield* requireCanonicalRoot(fs, candidate, operation);
|
|
2454
|
+
if ((yield* gitText$1(executable, root, [
|
|
2455
|
+
"rev-parse",
|
|
2456
|
+
"--path-format=absolute",
|
|
2457
|
+
"--show-toplevel"
|
|
2458
|
+
], operation)) !== root) return yield* fail$4(operation, "Aliased", root, "Workspace locator is not the exact Git root");
|
|
2459
|
+
return root;
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
function observeGitWorkspaceAnchor(fs, executable, locator, input, operation) {
|
|
2463
|
+
return Effect.gen(function* () {
|
|
2464
|
+
const root = yield* requireExactGitRoot(fs, executable, locator, operation);
|
|
2465
|
+
const rootInfo = yield* fs.stat(root).pipe(mapPlatform$4(operation, root));
|
|
2466
|
+
const objectFormat = yield* gitObjectFormat$1(executable, root, operation);
|
|
2467
|
+
const refName = yield* gitText$1(executable, root, [
|
|
2468
|
+
"symbolic-ref",
|
|
2469
|
+
"--quiet",
|
|
2470
|
+
"HEAD"
|
|
2471
|
+
], operation);
|
|
2472
|
+
const commit = yield* requireExactCommit(executable, root, "HEAD", operation);
|
|
2473
|
+
const refCommit = yield* requireExactCommit(executable, root, refName, operation);
|
|
2474
|
+
const tree = yield* gitText$1(executable, root, [
|
|
2475
|
+
"rev-parse",
|
|
2476
|
+
"--verify",
|
|
2477
|
+
"--end-of-options",
|
|
2478
|
+
"HEAD^{tree}"
|
|
2479
|
+
], operation);
|
|
2480
|
+
validateObjectForFormat(tree, objectFormat, "tree", operation);
|
|
2481
|
+
const remoteUrls = yield* readSelectedRemoteUrls(executable, root, input.remoteSelection, operation);
|
|
2482
|
+
return Object.freeze({
|
|
2483
|
+
root,
|
|
2484
|
+
rootDevice: String(rootInfo.dev),
|
|
2485
|
+
rootInode: String(Option.getOrElse(rootInfo.ino, () => -1)),
|
|
2486
|
+
refName,
|
|
2487
|
+
commit,
|
|
2488
|
+
refCommit,
|
|
2489
|
+
tree,
|
|
2490
|
+
objectFormat,
|
|
2491
|
+
remoteUrls
|
|
2492
|
+
});
|
|
2493
|
+
});
|
|
2494
|
+
}
|
|
2495
|
+
function observeGitStagedIndexBinding(fs, executable, input, operation) {
|
|
2496
|
+
return Effect.gen(function* () {
|
|
2497
|
+
const anchor = yield* observeGitWorkspaceAnchor(fs, executable, input.locator, input, operation);
|
|
2498
|
+
const entries = yield* parseGitStagedIndexOutput(yield* gitBytes$1(executable, anchor.root, [
|
|
2499
|
+
"ls-files",
|
|
2500
|
+
"--stage",
|
|
2501
|
+
"-z"
|
|
2502
|
+
], operation, input.maxIndexBytes), anchor.objectFormat, input.maxEntries, anchor.root);
|
|
2503
|
+
return Object.freeze({
|
|
2504
|
+
anchor,
|
|
2505
|
+
entries
|
|
2506
|
+
});
|
|
2507
|
+
});
|
|
2508
|
+
}
|
|
2509
|
+
function observeClosingGitStagedIndexBinding(fs, executable, input, operation) {
|
|
2510
|
+
return Effect.gen(function* () {
|
|
2511
|
+
const root = yield* requireExactGitRoot(fs, executable, input.locator, operation);
|
|
2512
|
+
const output = yield* gitBytes$1(executable, root, [
|
|
2513
|
+
"ls-files",
|
|
2514
|
+
"--stage",
|
|
2515
|
+
"-z"
|
|
2516
|
+
], operation, input.maxIndexBytes);
|
|
2517
|
+
const anchor = yield* observeGitWorkspaceAnchor(fs, executable, root, input, operation);
|
|
2518
|
+
const entries = yield* parseGitStagedIndexOutput(output, anchor.objectFormat, input.maxEntries, root);
|
|
2519
|
+
return Object.freeze({
|
|
2520
|
+
anchor,
|
|
2521
|
+
entries
|
|
2522
|
+
});
|
|
2523
|
+
});
|
|
2524
|
+
}
|
|
2525
|
+
function stagedRegularBlobObjectIds(entries, materializedPaths, materializedRoots) {
|
|
2526
|
+
const objectIds = /* @__PURE__ */ new Set();
|
|
2527
|
+
for (const entry of entries) if ((materializedPaths.includes(entry.path) || materializedRoots.some((root) => entry.path === root || entry.path.startsWith(`${root}/`))) && entry.stage === 0 && (entry.mode === "100644" || entry.mode === "100755")) objectIds.add(entry.objectId);
|
|
2528
|
+
return Object.freeze([...objectIds].sort(compareText$6));
|
|
2529
|
+
}
|
|
2530
|
+
function observeGitWorktreeObjectIds(fs, executable, root, admittedPaths, objectFormat, maxFileBytes, maxTotalBytes) {
|
|
2531
|
+
const operation = "capture-git-evidence";
|
|
2532
|
+
return Effect.gen(function* () {
|
|
2533
|
+
if (admittedPaths.length === 0) return Object.freeze([]);
|
|
2534
|
+
const identities = yield* Effect.forEach(admittedPaths, (relativePath) => inspectGitWorktreeFileIdentity(fs, root, relativePath, maxFileBytes, operation), { concurrency: 32 });
|
|
2535
|
+
yield* checked(operation, () => requireAggregateWorktreeBound(identities, maxTotalBytes, operation));
|
|
2536
|
+
const outputLimit = yield* checked(operation, () => gitObjectIdLinesOutputLimit(admittedPaths.length, objectFormat, operation));
|
|
2537
|
+
const output = yield* runGitCommand$1(executable, root, [
|
|
2538
|
+
"hash-object",
|
|
2539
|
+
"--no-filters",
|
|
2540
|
+
"--stdin-paths"
|
|
2541
|
+
], operation, outputLimit, `${admittedPaths.join("\n")}\n`).pipe(Effect.flatMap((result) => result.exitCode === 0 ? Effect.succeed(result.stdout) : fail$4(operation, "GitFailed", root, gitFailureDetail$2(["hash-object", "--stdin-paths"], result.stderr))));
|
|
2542
|
+
const objectIds = yield* checked(operation, () => parseGitObjectIdLines(output, admittedPaths.length, objectFormat, operation));
|
|
2543
|
+
yield* Effect.forEach(identities, (identity) => revalidateGitWorktreeFileIdentity(fs, identity, operation), {
|
|
2544
|
+
concurrency: 32,
|
|
2545
|
+
discard: true
|
|
2546
|
+
});
|
|
2547
|
+
return Object.freeze(admittedPaths.map((relativePath, index) => Object.freeze({
|
|
2548
|
+
path: relativePath,
|
|
2549
|
+
objectId: objectIds[index]
|
|
2550
|
+
})));
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
function inspectGitWorktreeFileIdentity(fs, root, relativePath, maxBytes, operation) {
|
|
2554
|
+
const candidate = path.join(root, relativePath);
|
|
2555
|
+
return Effect.gen(function* () {
|
|
2556
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$4(operation, candidate))) !== candidate) return yield* fail$4(operation, "Aliased", candidate, "File path is not canonical");
|
|
2557
|
+
const observed = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2558
|
+
if (observed.type !== "File") return yield* fail$4(operation, "UnsupportedEntry", candidate, "Expected a regular file");
|
|
2559
|
+
if (observed.size > BigInt(maxBytes)) return yield* fail$4(operation, "LimitExceeded", candidate, "File exceeds maxBytes");
|
|
2560
|
+
return Object.freeze({
|
|
2561
|
+
candidate,
|
|
2562
|
+
device: observed.dev,
|
|
2563
|
+
inode: observed.ino,
|
|
2564
|
+
size: observed.size
|
|
2565
|
+
});
|
|
2566
|
+
});
|
|
2567
|
+
}
|
|
2568
|
+
function revalidateGitWorktreeFileIdentity(fs, identity, operation) {
|
|
2569
|
+
return Effect.gen(function* () {
|
|
2570
|
+
const canonical = yield* fs.realPath(identity.candidate).pipe(mapPlatform$4(operation, identity.candidate));
|
|
2571
|
+
const observed = yield* fs.stat(identity.candidate).pipe(mapPlatform$4(operation, identity.candidate));
|
|
2572
|
+
if (canonical !== identity.candidate || observed.type !== "File" || !Equal.equals(identity.device, observed.dev) || !Equal.equals(identity.inode, observed.ino) || identity.size !== observed.size) return yield* fail$4(operation, "IdentityChanged", identity.candidate, "File identity changed while hashing");
|
|
2573
|
+
});
|
|
2574
|
+
}
|
|
2575
|
+
function requireAggregateWorktreeBound(identities, maxBytes, operation) {
|
|
2576
|
+
let total = 0n;
|
|
2577
|
+
for (const identity of identities) {
|
|
2578
|
+
total += identity.size;
|
|
2579
|
+
if (total > BigInt(maxBytes)) throw failure$4(operation, "LimitExceeded", identity.candidate, "Admitted worktree files exceed maxBytes");
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
function gitObjectIdLinesOutputLimit(count, objectFormat, operation) {
|
|
2583
|
+
const outputBytes = count * ((objectFormat === "sha1" ? 40 : 64) + 1);
|
|
2584
|
+
if (!Number.isSafeInteger(outputBytes)) throw invalidInput(operation, void 0, "Git worktree object output bound exceeds a safe integer");
|
|
2585
|
+
return outputBytes;
|
|
2586
|
+
}
|
|
2587
|
+
function parseGitObjectIdLines(output, expectedCount, objectFormat, operation) {
|
|
2588
|
+
let encoded;
|
|
2589
|
+
try {
|
|
2590
|
+
encoded = decoder$2.decode(output);
|
|
2591
|
+
} catch {
|
|
2592
|
+
throw failure$4(operation, "GitFailed", void 0, "Git worktree object output is not UTF-8");
|
|
2593
|
+
}
|
|
2594
|
+
if (!encoded.endsWith("\n")) throw failure$4(operation, "GitFailed", void 0, "Git worktree object output is truncated");
|
|
2595
|
+
const objectIds = encoded.slice(0, -1).split("\n");
|
|
2596
|
+
const pattern = objectFormat === "sha1" ? /^[0-9a-f]{40}$/u : /^[0-9a-f]{64}$/u;
|
|
2597
|
+
if (objectIds.length !== expectedCount || objectIds.some((objectId) => !pattern.test(objectId))) throw failure$4(operation, "GitFailed", void 0, "Git worktree object output is malformed");
|
|
2598
|
+
return Object.freeze(objectIds);
|
|
2599
|
+
}
|
|
2600
|
+
function readSelectedRemoteUrls(executable, root, selection, operation) {
|
|
2601
|
+
if (selection.kind === "Named") return gitLines(executable, root, [
|
|
2602
|
+
"remote",
|
|
2603
|
+
"get-url",
|
|
2604
|
+
"--all",
|
|
2605
|
+
selection.remoteName
|
|
2606
|
+
], operation).pipe(Effect.map((urls) => Object.freeze([...urls])));
|
|
2607
|
+
return Effect.gen(function* () {
|
|
2608
|
+
const remoteNames = yield* gitLines(executable, root, ["remote"], operation);
|
|
2609
|
+
const remoteUrls = yield* Effect.forEach(remoteNames, (remoteName) => gitLines(executable, root, [
|
|
2610
|
+
"remote",
|
|
2611
|
+
"get-url",
|
|
2612
|
+
"--all",
|
|
2613
|
+
remoteName
|
|
2614
|
+
], operation));
|
|
2615
|
+
return Object.freeze(remoteUrls.flat().sort(compareText$6));
|
|
2616
|
+
});
|
|
2617
|
+
}
|
|
2618
|
+
function readGitStatus(executable, root, maxBytes) {
|
|
2619
|
+
return gitBytes$1(executable, root, [
|
|
2620
|
+
"--no-optional-locks",
|
|
2621
|
+
"status",
|
|
2622
|
+
"--porcelain=v2",
|
|
2623
|
+
"--branch",
|
|
2624
|
+
"-z",
|
|
2625
|
+
"--untracked-files=all",
|
|
2626
|
+
"--ignored=matching",
|
|
2627
|
+
"--ignore-submodules=none"
|
|
2628
|
+
], "capture-git-evidence", maxBytes);
|
|
2629
|
+
}
|
|
2630
|
+
function readGitTrackedFlags(executable, root, admittedPaths, maxBytes) {
|
|
2631
|
+
return Effect.gen(function* () {
|
|
2632
|
+
if (admittedPaths.length === 0) return Object.freeze([]);
|
|
2633
|
+
return yield* parseGitTrackedPathFlags(yield* gitBytes$1(executable, root, [
|
|
2634
|
+
"--literal-pathspecs",
|
|
2635
|
+
"ls-files",
|
|
2636
|
+
"-v",
|
|
2637
|
+
"-z",
|
|
2638
|
+
"--",
|
|
2639
|
+
...admittedPaths
|
|
2640
|
+
], "capture-git-evidence", maxBytes), admittedPaths, root);
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
2643
|
+
function requireGitObjectType(executable, root, object, expected, operation) {
|
|
2644
|
+
return gitText$1(executable, root, [
|
|
2645
|
+
"cat-file",
|
|
2646
|
+
"-t",
|
|
2647
|
+
object
|
|
2648
|
+
], operation).pipe(Effect.flatMap((observed) => observed === expected ? Effect.void : fail$4(operation, "UnsupportedEntry", object, `Git object is not a ${expected}`)));
|
|
2649
|
+
}
|
|
2650
|
+
function requireExactCommit(executable, root, candidate, operation) {
|
|
2651
|
+
return gitText$1(executable, root, [
|
|
2652
|
+
"rev-parse",
|
|
2653
|
+
"--verify",
|
|
2654
|
+
"--end-of-options",
|
|
2655
|
+
`${candidate}^{commit}`
|
|
2656
|
+
], operation).pipe(Effect.flatMap((observed) => candidate === "HEAD" || candidate.startsWith("refs/") || observed === candidate ? Effect.succeed(observed) : fail$4(operation, "IdentityChanged", candidate, "Git commit selection is not exact")));
|
|
2657
|
+
}
|
|
2658
|
+
function localGitAncestry(executable, root, ancestor, descendant, operation) {
|
|
2659
|
+
return gitExitCode(executable, root, [
|
|
2660
|
+
"merge-base",
|
|
2661
|
+
"--is-ancestor",
|
|
2662
|
+
ancestor,
|
|
2663
|
+
descendant
|
|
2664
|
+
], operation).pipe(Effect.flatMap((code) => {
|
|
2665
|
+
if (code === 0) return Effect.succeed(true);
|
|
2666
|
+
if (code === 1) return Effect.succeed(false);
|
|
2667
|
+
return fail$4(operation, "GitFailed", root, `Git ancestry query exited ${code}`);
|
|
2668
|
+
}));
|
|
2669
|
+
}
|
|
2670
|
+
function requireGitWorkspaceRoot(gitExecutable, root, operation) {
|
|
2671
|
+
return Effect.gen(function* () {
|
|
2672
|
+
if (root === path.parse(root).root) return yield* fail$4(operation, "InvalidInput", root, "Filesystem root cannot be a content workspace mutation root");
|
|
2673
|
+
if ((yield* gitText$1(gitExecutable, root, ["rev-parse", "--show-toplevel"], operation)) !== root) return yield* fail$4(operation, "Aliased", root, "Mutation root must be the exact Git workspace root");
|
|
2674
|
+
});
|
|
2675
|
+
}
|
|
2676
|
+
function requireExactExistingPath(fs, candidate, operation) {
|
|
2677
|
+
return Effect.gen(function* () {
|
|
2678
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$4(operation, candidate))) !== candidate) return yield* fail$4(operation, "Aliased", candidate, "Refusing to traverse an aliased or symbolic path");
|
|
2679
|
+
});
|
|
2680
|
+
}
|
|
2681
|
+
function ensureDirectoryChain(fs, directory, operation) {
|
|
2682
|
+
return Effect.gen(function* () {
|
|
2683
|
+
const parsed = path.parse(directory);
|
|
2684
|
+
const segments = directory.slice(parsed.root.length).split(path.sep).filter((segment) => segment !== "");
|
|
2685
|
+
let current = parsed.root;
|
|
2686
|
+
for (const segment of segments) {
|
|
2687
|
+
current = path.join(current, segment);
|
|
2688
|
+
if (!(yield* fs.exists(current).pipe(mapPlatform$4(operation, current)))) yield* fs.makeDirectory(current, {
|
|
2689
|
+
recursive: false,
|
|
2690
|
+
mode: 448
|
|
2691
|
+
}).pipe(mapPlatform$4(operation, current));
|
|
2692
|
+
yield* requireExactExistingPath(fs, current, operation);
|
|
2693
|
+
if ((yield* fs.stat(current).pipe(mapPlatform$4(operation, current))).type !== "Directory") return yield* fail$4(operation, "UnsupportedEntry", current, "Write parent must be a directory");
|
|
2694
|
+
}
|
|
2695
|
+
});
|
|
2696
|
+
}
|
|
2697
|
+
function removeEmptyDirectory(fs, candidate, operation) {
|
|
2698
|
+
return Effect.gen(function* () {
|
|
2699
|
+
yield* requireExactExistingPath(fs, candidate, operation);
|
|
2700
|
+
const before = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2701
|
+
const entries = yield* fs.readDirectory(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2702
|
+
if (before.type !== "Directory" || entries.length !== 0) return yield* fail$4(operation, "IdentityChanged", candidate, "Exact directory is no longer empty");
|
|
2703
|
+
yield* requireExactExistingPath(fs, candidate, operation);
|
|
2704
|
+
const after = yield* fs.stat(candidate).pipe(mapPlatform$4(operation, candidate));
|
|
2705
|
+
if (after.type !== "Directory" || before.dev !== after.dev || !Equal.equals(before.ino, after.ino)) return yield* fail$4(operation, "IdentityChanged", candidate, "Exact empty directory identity changed before removal");
|
|
2706
|
+
yield* fs.remove(candidate, {
|
|
2707
|
+
recursive: true,
|
|
2708
|
+
force: false
|
|
2709
|
+
}).pipe(mapPlatform$4(operation, candidate));
|
|
2710
|
+
});
|
|
2711
|
+
}
|
|
2712
|
+
function resolveContained(root, relative, allowEmpty, operation) {
|
|
2713
|
+
validateRelativePath(relative, allowEmpty, operation);
|
|
2714
|
+
if (relative === "") return root;
|
|
2715
|
+
const candidate = path.join(root, ...relative.split("/"));
|
|
2716
|
+
const offset = path.relative(root, candidate);
|
|
2717
|
+
if (offset === "" || offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw invalidInput(operation, relative, "Path escapes or aliases the workspace root");
|
|
2718
|
+
return candidate;
|
|
2719
|
+
}
|
|
2720
|
+
function validateRelativePath(relative, allowEmpty, operation) {
|
|
2721
|
+
if (allowEmpty && relative === "" || relative.length > 0 && relative.length <= 4096 && !relative.startsWith("/") && !relative.endsWith("/") && !relative.includes("\\") && !/[\u0000-\u001f\u007f]/u.test(relative) && relative.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..")) return;
|
|
2722
|
+
throw invalidInput(operation, relative, "Path must be a canonical repository-relative path");
|
|
2723
|
+
}
|
|
2724
|
+
function validateGitInspectionInput(input) {
|
|
2725
|
+
validateRefName(input.refName, "inspect-git-workspace");
|
|
2726
|
+
validateRemoteSelection(input.remoteSelection, "inspect-git-workspace");
|
|
2727
|
+
}
|
|
2728
|
+
function validateGitEvidenceInput(input) {
|
|
2729
|
+
validateRefName(input.refName, "capture-git-evidence");
|
|
2730
|
+
validateRemoteSelection(input.remoteSelection, "capture-git-evidence");
|
|
2731
|
+
validateLimit(input.maxPaths, "maxPaths", "capture-git-evidence");
|
|
2732
|
+
validateLimit(input.maxWorktreeFileBytes, "maxWorktreeFileBytes", "capture-git-evidence");
|
|
2733
|
+
validateLimit(input.maxWorktreeBytes, "maxWorktreeBytes", "capture-git-evidence");
|
|
2734
|
+
validateLimit(input.maxBytes, "maxBytes", "capture-git-evidence");
|
|
2735
|
+
if (input.objectFormat !== "sha1" && input.objectFormat !== "sha256") throw invalidInput("capture-git-evidence", input.objectFormat, "Unsupported Git object format");
|
|
2736
|
+
if (input.admittedPaths.length > input.maxPaths || input.consumedRoots.length > input.maxPaths) throw invalidInput("capture-git-evidence", void 0, "Git evidence paths exceed maxPaths");
|
|
2737
|
+
validateCanonicalPathSet(input.admittedPaths, "capture-git-evidence");
|
|
2738
|
+
validateCanonicalPathSet(input.consumedRoots, "capture-git-evidence");
|
|
2739
|
+
}
|
|
2740
|
+
function readGitBlobBatch(executable, root, input, operation) {
|
|
2741
|
+
return Effect.gen(function* () {
|
|
2742
|
+
const outputLimit = yield* checked(operation, () => {
|
|
2743
|
+
validateGitBlobBatchInput(input, operation);
|
|
2744
|
+
return gitBlobBatchOutputLimit(input, operation);
|
|
2745
|
+
});
|
|
2746
|
+
if (input.blobs.length === 0) return Object.freeze([]);
|
|
2747
|
+
const output = yield* runGitCommand$1(executable, root, ["cat-file", "--batch"], operation, outputLimit, `${input.blobs.join("\n")}\n`).pipe(Effect.flatMap((result) => result.exitCode === 0 ? Effect.succeed(result.stdout) : fail$4(operation, "GitFailed", root, gitFailureDetail$2(["cat-file", "--batch"], result.stderr))));
|
|
2748
|
+
return yield* checked(operation, () => parseGitBlobBatch(output, input, operation));
|
|
2749
|
+
});
|
|
2750
|
+
}
|
|
2751
|
+
function validateGitBlobBatchInput(input, operation) {
|
|
2752
|
+
validateLimit(input.maxBlobs, "maxBlobs", operation);
|
|
2753
|
+
validateLimit(input.maxBlobBytes, "maxBlobBytes", operation);
|
|
2754
|
+
validateLimit(input.maxTotalBytes, "maxTotalBytes", operation);
|
|
2755
|
+
if (input.blobs.length > input.maxBlobs) throw invalidInput(operation, void 0, "Git blob batch exceeds maxBlobs");
|
|
2756
|
+
const unique = /* @__PURE__ */ new Set();
|
|
2757
|
+
for (const blob of input.blobs) {
|
|
2758
|
+
validateObjectForFormat(blob, input.objectFormat, "blob", operation);
|
|
2759
|
+
if (unique.has(blob)) throw invalidInput(operation, blob, "Git blob batch must be distinct");
|
|
2760
|
+
unique.add(blob);
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
function gitBlobBatchOutputLimit(input, operation) {
|
|
2764
|
+
const objectIdBytes = input.objectFormat === "sha1" ? 40 : 64;
|
|
2765
|
+
const headerBytes = input.blobs.length * (objectIdBytes + 64);
|
|
2766
|
+
const outputBytes = input.maxTotalBytes + headerBytes;
|
|
2767
|
+
if (!Number.isSafeInteger(headerBytes) || !Number.isSafeInteger(outputBytes)) throw invalidInput(operation, void 0, "Git blob batch output bound exceeds a safe integer");
|
|
2768
|
+
return outputBytes;
|
|
2769
|
+
}
|
|
2770
|
+
function parseGitBlobBatch(output, input, operation) {
|
|
2771
|
+
const observations = [];
|
|
2772
|
+
let offset = 0;
|
|
2773
|
+
let totalBytes = 0;
|
|
2774
|
+
for (const expectedBlob of input.blobs) {
|
|
2775
|
+
const headerEnd = output.indexOf(10, offset);
|
|
2776
|
+
if (headerEnd < 0) throw failure$4(operation, "GitFailed", expectedBlob, "Git blob batch omitted an object header");
|
|
2777
|
+
const header = decodeGitBlobBatchHeader(output.subarray(offset, headerEnd), expectedBlob, operation);
|
|
2778
|
+
if (header === `${expectedBlob} missing`) throw failure$4(operation, "GitFailed", expectedBlob, "Git blob batch returned a missing object");
|
|
2779
|
+
const match = /^([0-9a-f]+) ([a-z][a-z0-9-]*) ([0-9]+)$/u.exec(header);
|
|
2780
|
+
if (match === null) throw failure$4(operation, "GitFailed", expectedBlob, "Git blob batch returned a malformed object header");
|
|
2781
|
+
if (match[1] !== expectedBlob) throw failure$4(operation, "GitFailed", expectedBlob, "Git blob batch returned a reordered object");
|
|
2782
|
+
if (match[2] !== "blob") throw failure$4(operation, "UnsupportedEntry", expectedBlob, "Git object is not a blob");
|
|
2783
|
+
const size = Number(match[3]);
|
|
2784
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > input.maxBlobBytes) throw failure$4(operation, "LimitExceeded", expectedBlob, "Git blob batch member exceeds maxBlobBytes");
|
|
2785
|
+
totalBytes += size;
|
|
2786
|
+
if (!Number.isSafeInteger(totalBytes) || totalBytes > input.maxTotalBytes) throw failure$4(operation, "LimitExceeded", expectedBlob, "Git blob batch exceeds maxTotalBytes");
|
|
2787
|
+
const contentStart = headerEnd + 1;
|
|
2788
|
+
const contentEnd = contentStart + size;
|
|
2789
|
+
if (contentEnd >= output.byteLength || output[contentEnd] !== 10) throw failure$4(operation, "GitFailed", expectedBlob, "Git blob batch returned truncated content");
|
|
2790
|
+
observations.push(Object.freeze({
|
|
2791
|
+
blob: expectedBlob,
|
|
2792
|
+
bytes: output.slice(contentStart, contentEnd)
|
|
2793
|
+
}));
|
|
2794
|
+
offset = contentEnd + 1;
|
|
2795
|
+
}
|
|
2796
|
+
if (offset !== output.byteLength) throw failure$4(operation, "GitFailed", void 0, "Git blob batch returned trailing output");
|
|
2797
|
+
return Object.freeze(observations);
|
|
2798
|
+
}
|
|
2799
|
+
function decodeGitBlobBatchHeader(header, expectedBlob, operation) {
|
|
2800
|
+
try {
|
|
2801
|
+
return decoder$2.decode(header);
|
|
2802
|
+
} catch {
|
|
2803
|
+
throw failure$4(operation, "GitFailed", expectedBlob, "Git blob batch returned a non-UTF-8 object header");
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
function parseGitTrackedPathFlags(output, admittedPaths, root) {
|
|
2807
|
+
return Effect.gen(function* () {
|
|
2808
|
+
if (output.byteLength === 0) return Object.freeze([]);
|
|
2809
|
+
if (output[output.byteLength - 1] !== 0) return yield* fail$4("capture-git-evidence", "GitFailed", root, "Git tracked-path output is truncated before its terminal NUL");
|
|
2810
|
+
const admitted = new Set(admittedPaths);
|
|
2811
|
+
const facts = [];
|
|
2812
|
+
const factsByPath = /* @__PURE__ */ new Map();
|
|
2813
|
+
let recordStart = 0;
|
|
2814
|
+
for (let index = 0; index < output.byteLength; index += 1) {
|
|
2815
|
+
if (output[index] !== 0) continue;
|
|
2816
|
+
if (index === recordStart) return yield* fail$4("capture-git-evidence", "GitFailed", root, "Git tracked-path output contains an empty record");
|
|
2817
|
+
const record = yield* Effect.try({
|
|
2818
|
+
try: () => decoder$2.decode(output.subarray(recordStart, index)),
|
|
2819
|
+
catch: () => failure$4("capture-git-evidence", "GitFailed", root, "Git tracked-path output contains invalid UTF-8")
|
|
2820
|
+
});
|
|
2821
|
+
recordStart = index + 1;
|
|
2822
|
+
const tag = record[0];
|
|
2823
|
+
if (tag === void 0 || record[1] !== " " || record.length < 3 || !/^[HSMhs]$/u.test(tag)) return yield* fail$4("capture-git-evidence", "GitFailed", root, "Git tracked-path output contains a malformed record");
|
|
2824
|
+
const entryPath = record.slice(2);
|
|
2825
|
+
const status = gitTrackedPathStatus(tag);
|
|
2826
|
+
if (status === void 0) return yield* fail$4("capture-git-evidence", "GitFailed", root, "Git tracked-path output contains an unsupported status tag");
|
|
2827
|
+
const fact = Object.freeze({
|
|
2828
|
+
path: entryPath,
|
|
2829
|
+
status,
|
|
2830
|
+
assumeUnchanged: tag === "h" || tag === "s"
|
|
2831
|
+
});
|
|
2832
|
+
if (!gitTrackedPathFlagValidator.Check(fact)) return yield* fail$4("capture-git-evidence", "UnsupportedEntry", entryPath, "Git tracked path is outside the tracked-path contract");
|
|
2833
|
+
if (!admitted.has(fact.path)) return yield* fail$4("capture-git-evidence", "UnsupportedEntry", fact.path, "Git returned a tracked path outside the admitted selection");
|
|
2834
|
+
const prior = factsByPath.get(fact.path);
|
|
2835
|
+
if (prior !== void 0 && (prior.status !== "Unmerged" || fact.status !== "Unmerged" || prior.count >= 3)) return yield* fail$4("capture-git-evidence", "GitFailed", fact.path, "Git tracked-path output contains an impossible index-state combination");
|
|
2836
|
+
factsByPath.set(fact.path, Object.freeze({
|
|
2837
|
+
status: fact.status,
|
|
2838
|
+
count: (prior?.count ?? 0) + 1
|
|
2839
|
+
}));
|
|
2840
|
+
facts.push(fact);
|
|
2841
|
+
}
|
|
2842
|
+
facts.sort((left, right) => compareText$6(left.path, right.path) || compareText$6(left.status, right.status) || Number(left.assumeUnchanged) - Number(right.assumeUnchanged));
|
|
2843
|
+
return Object.freeze(facts);
|
|
2844
|
+
});
|
|
2845
|
+
}
|
|
2846
|
+
function gitTrackedPathStatus(tag) {
|
|
2847
|
+
switch (tag.toUpperCase()) {
|
|
2848
|
+
case "H": return "Cached";
|
|
2849
|
+
case "S": return "SkipWorktree";
|
|
2850
|
+
case "M": return "Unmerged";
|
|
2851
|
+
default: return;
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
function parseGitStagedIndexOutput(output, objectFormat, maxEntries, root) {
|
|
2855
|
+
return Effect.gen(function* () {
|
|
2856
|
+
if (output.byteLength === 0) return Object.freeze([]);
|
|
2857
|
+
if (output[output.byteLength - 1] !== 0) return yield* fail$4("observe-git-staged-index", "GitFailed", root, "Git index output is truncated before its terminal NUL");
|
|
2858
|
+
const entries = [];
|
|
2859
|
+
const identities = /* @__PURE__ */ new Set();
|
|
2860
|
+
let recordStart = 0;
|
|
2861
|
+
for (let index = 0; index < output.byteLength; index += 1) {
|
|
2862
|
+
if (output[index] !== 0) continue;
|
|
2863
|
+
if (entries.length >= maxEntries) return yield* fail$4("observe-git-staged-index", "LimitExceeded", root, "Git index output exceeds maxEntries");
|
|
2864
|
+
if (index === recordStart) return yield* fail$4("observe-git-staged-index", "GitFailed", root, "Git index output contains an empty record");
|
|
2865
|
+
const record = yield* Effect.try({
|
|
2866
|
+
try: () => decoder$2.decode(output.subarray(recordStart, index)),
|
|
2867
|
+
catch: () => failure$4("observe-git-staged-index", "GitFailed", root, "Git index output contains invalid UTF-8")
|
|
2868
|
+
});
|
|
2869
|
+
recordStart = index + 1;
|
|
2870
|
+
const separator = record.indexOf(" ");
|
|
2871
|
+
if (separator <= 0) return yield* fail$4("observe-git-staged-index", "GitFailed", root, "Git index output contains a malformed record");
|
|
2872
|
+
const header = record.slice(0, separator);
|
|
2873
|
+
const entryPath = record.slice(separator + 1);
|
|
2874
|
+
const headerMatch = /^([0-7]{6}) ([0-9A-Za-z]+) ([0-3])$/u.exec(header);
|
|
2875
|
+
const mode = headerMatch?.[1];
|
|
2876
|
+
const objectId = headerMatch?.[2];
|
|
2877
|
+
const rawStage = headerMatch?.[3];
|
|
2878
|
+
if (mode === void 0 || objectId === void 0 || rawStage === void 0) return yield* fail$4("observe-git-staged-index", "GitFailed", root, "Git index output contains a malformed record header");
|
|
2879
|
+
const objectLength = objectFormat === "sha1" ? 40 : 64;
|
|
2880
|
+
if (objectId.length !== objectLength || !/^[0-9a-f]+$/u.test(objectId)) return yield* fail$4("observe-git-staged-index", "GitFailed", entryPath, "Git index output contains an object ID for a different or malformed object format");
|
|
2881
|
+
const entry = Object.freeze({
|
|
2882
|
+
path: entryPath,
|
|
2883
|
+
mode,
|
|
2884
|
+
objectId,
|
|
2885
|
+
stage: gitIndexStage(rawStage)
|
|
2886
|
+
});
|
|
2887
|
+
if (!gitStagedIndexEntryValidator.Check(entry)) return yield* fail$4("observe-git-staged-index", "UnsupportedEntry", entryPath, "Git index path is outside the staged-entry contract");
|
|
2888
|
+
const identity = `${entry.path}\0${entry.stage}`;
|
|
2889
|
+
if (identities.has(identity)) return yield* fail$4("observe-git-staged-index", "GitFailed", entry.path, "Git index output contains a duplicate path and stage");
|
|
2890
|
+
identities.add(identity);
|
|
2891
|
+
entries.push(entry);
|
|
2892
|
+
}
|
|
2893
|
+
entries.sort((left, right) => compareText$6(left.path, right.path) || left.stage - right.stage);
|
|
2894
|
+
return Object.freeze(entries);
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2897
|
+
function gitIndexStage(value) {
|
|
2898
|
+
switch (value) {
|
|
2899
|
+
case "0": return 0;
|
|
2900
|
+
case "1": return 1;
|
|
2901
|
+
case "2": return 2;
|
|
2902
|
+
case "3": return 3;
|
|
2903
|
+
default: throw new Error(`Unexpected Git index stage: ${value}`);
|
|
2904
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
function parseGitTreeOutput(output, objectFormat, maxEntries, root) {
|
|
2907
|
+
return Effect.gen(function* () {
|
|
2908
|
+
if (output.byteLength === 0) return Object.freeze([]);
|
|
2909
|
+
if (output[output.byteLength - 1] !== 0) return yield* fail$4("read-git-tree", "GitFailed", root, "Git tree output is truncated before its terminal NUL");
|
|
2910
|
+
const entries = [];
|
|
2911
|
+
const paths = /* @__PURE__ */ new Set();
|
|
2912
|
+
let recordStart = 0;
|
|
2913
|
+
for (let index = 0; index < output.byteLength; index += 1) {
|
|
2914
|
+
if (output[index] !== 0) continue;
|
|
2915
|
+
if (entries.length >= maxEntries) return yield* fail$4("read-git-tree", "LimitExceeded", root, "Git tree output exceeds maxEntries");
|
|
2916
|
+
if (index === recordStart) return yield* fail$4("read-git-tree", "GitFailed", root, "Git tree output contains an empty record");
|
|
2917
|
+
const record = yield* Effect.try({
|
|
2918
|
+
try: () => decoder$2.decode(output.subarray(recordStart, index)),
|
|
2919
|
+
catch: () => failure$4("read-git-tree", "GitFailed", root, "Git tree output contains invalid UTF-8")
|
|
2920
|
+
});
|
|
2921
|
+
recordStart = index + 1;
|
|
2922
|
+
const separator = record.indexOf(" ");
|
|
2923
|
+
if (separator <= 0) return yield* fail$4("read-git-tree", "GitFailed", root, "Git tree output contains a malformed record");
|
|
2924
|
+
const header = record.slice(0, separator);
|
|
2925
|
+
const entryPath = record.slice(separator + 1);
|
|
2926
|
+
const headerMatch = /^([0-7]{6}) ([a-z][a-z0-9-]*) ([0-9A-Za-z]+)$/u.exec(header);
|
|
2927
|
+
const mode = headerMatch?.[1];
|
|
2928
|
+
const objectType = headerMatch?.[2];
|
|
2929
|
+
const blob = headerMatch?.[3];
|
|
2930
|
+
if (mode === void 0 || objectType === void 0 || blob === void 0) return yield* fail$4("read-git-tree", "GitFailed", root, "Git tree output contains a malformed record header");
|
|
2931
|
+
if (mode !== "100644" && mode !== "100755" || objectType !== "blob") return yield* fail$4("read-git-tree", "UnsupportedEntry", entryPath, "Git tree contains a non-regular entry");
|
|
2932
|
+
const objectLength = objectFormat === "sha1" ? 40 : 64;
|
|
2933
|
+
if (blob.length !== objectLength || !/^[0-9a-f]+$/u.test(blob)) return yield* fail$4("read-git-tree", "GitFailed", entryPath, "Git tree output contains an object ID for a different or malformed object format");
|
|
2934
|
+
const entry = Object.freeze({
|
|
2935
|
+
path: entryPath,
|
|
2936
|
+
mode,
|
|
2937
|
+
blob
|
|
2938
|
+
});
|
|
2939
|
+
if (!contentTreeEntryValidator.Check(entry)) return yield* fail$4("read-git-tree", "UnsupportedEntry", entryPath, "Git tree path is outside the regular-entry contract");
|
|
2940
|
+
if (paths.has(entry.path)) return yield* fail$4("read-git-tree", "GitFailed", entry.path, "Git tree output contains a duplicate path");
|
|
2941
|
+
paths.add(entry.path);
|
|
2942
|
+
entries.push(entry);
|
|
2943
|
+
}
|
|
2944
|
+
entries.sort((left, right) => compareText$6(left.path, right.path));
|
|
2945
|
+
return Object.freeze(entries);
|
|
2946
|
+
});
|
|
2947
|
+
}
|
|
2948
|
+
function validateRemoteSelection(selection, operation) {
|
|
2949
|
+
if (selection.kind === "All" && Object.keys(selection).length === 1) return;
|
|
2950
|
+
if (selection.kind === "Named" && Object.keys(selection).length === 2 && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(selection.remoteName)) return;
|
|
2951
|
+
throw invalidInput(operation, void 0, "Git remote selection is not canonical");
|
|
2952
|
+
}
|
|
2953
|
+
function validateRefName(refName, operation) {
|
|
2954
|
+
if (REF_PATTERN.test(refName) && !refName.includes("..") && !refName.endsWith(".")) return;
|
|
2955
|
+
throw invalidInput(operation, refName, "Git ref must be one canonical full ref name");
|
|
2956
|
+
}
|
|
2957
|
+
function validateCanonicalPathSet(candidates, operation) {
|
|
2958
|
+
const unique = /* @__PURE__ */ new Set();
|
|
2959
|
+
for (const candidate of candidates) {
|
|
2960
|
+
validateRelativePath(candidate, false, operation);
|
|
2961
|
+
if (unique.has(candidate)) throw invalidInput(operation, candidate, "Git paths must be distinct");
|
|
2962
|
+
unique.add(candidate);
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
function validateLimits(maxEntries, maxBytes, operation) {
|
|
2966
|
+
validateLimit(maxEntries, "maxEntries", operation);
|
|
2967
|
+
validateLimit(maxBytes, "maxBytes", operation);
|
|
2968
|
+
}
|
|
2969
|
+
function validateLimit(value, label, operation) {
|
|
2970
|
+
if (!Number.isSafeInteger(value) || value < 1) throw invalidInput(operation, void 0, `${label} must be a positive safe integer`);
|
|
2971
|
+
}
|
|
2972
|
+
function validateOpaque(value, label, operation) {
|
|
2973
|
+
if (value.length === 0 || value.length > 4096 || /[\u0000-\u001f\u007f]/u.test(value)) throw invalidInput(operation, void 0, `${label} must be a bounded opaque value`);
|
|
2974
|
+
}
|
|
2975
|
+
function validateObject(value, label, operation) {
|
|
2976
|
+
if (!OBJECT_PATTERN.test(value)) throw invalidInput(operation, value, `${label} must be a Git object ID`);
|
|
2977
|
+
}
|
|
2978
|
+
function validateObjectForFormat(value, format, label, operation) {
|
|
2979
|
+
const expectedLength = format === "sha1" ? 40 : 64;
|
|
2980
|
+
if (value.length !== expectedLength || !/^[0-9a-f]+$/u.test(value)) throw invalidInput(operation, value, `${label} must match the selected Git object format`);
|
|
2981
|
+
}
|
|
2982
|
+
function gitObjectFormat$1(executable, root, operation) {
|
|
2983
|
+
return gitText$1(executable, root, ["rev-parse", "--show-object-format"], operation).pipe(Effect.flatMap((format) => format === "sha1" || format === "sha256" ? Effect.succeed(format === "sha1" ? "sha1" : "sha256") : fail$4(operation, "GitFailed", root, `Unsupported Git object format: ${format}`)));
|
|
2984
|
+
}
|
|
2985
|
+
function gitText$1(executable, root, args, operation) {
|
|
2986
|
+
return runGitCommand$1(executable, root, args, operation, 1048576).pipe(Effect.flatMap((result) => result.exitCode === 0 ? decodeGitOutput$2(result.stdout, operation, root) : fail$4(operation, "GitFailed", root, gitFailureDetail$2(args, result.stderr))), Effect.map((output) => output.trim()));
|
|
2987
|
+
}
|
|
2988
|
+
function gitLines(executable, root, args, operation) {
|
|
2989
|
+
return gitText$1(executable, root, args, operation).pipe(Effect.map((output) => output === "" ? [] : output.split("\n").filter((line) => line !== "")));
|
|
2990
|
+
}
|
|
2991
|
+
function gitBytes$1(executable, root, args, operation, maxBytes) {
|
|
2992
|
+
return runGitCommand$1(executable, root, args, operation, maxBytes).pipe(Effect.flatMap((result) => result.exitCode === 0 ? Effect.succeed(result.stdout) : fail$4(operation, "GitFailed", root, gitFailureDetail$2(args, result.stderr))));
|
|
2993
|
+
}
|
|
2994
|
+
function gitExitCode(executable, root, args, operation) {
|
|
2995
|
+
return runGitCommand$1(executable, root, args, operation, 65536).pipe(Effect.map((result) => result.exitCode));
|
|
2996
|
+
}
|
|
2997
|
+
function runGitCommand$1(executable, root, args, operation, maxStdoutBytes, stdin) {
|
|
2998
|
+
const stderrLimit = 65536;
|
|
2999
|
+
const command = ChildProcess.make(executable, args, {
|
|
3000
|
+
cwd: root,
|
|
3001
|
+
extendEnv: true,
|
|
3002
|
+
stdin: stdin === void 0 ? Stream.empty : Stream.make(encoder.encode(stdin)),
|
|
3003
|
+
forceKillAfter: "5 seconds"
|
|
3004
|
+
});
|
|
3005
|
+
return Effect.scoped(Effect.gen(function* () {
|
|
3006
|
+
const process = yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn(command).pipe(Effect.catchDefect((cause) => fail$4(operation, "GitFailed", root, errorMessage$2(cause))));
|
|
3007
|
+
const [stdout, stderr, exitCode] = yield* Effect.all([
|
|
3008
|
+
collectBoundedGitOutput(process.stdout, maxStdoutBytes, operation, root, "stdout"),
|
|
3009
|
+
collectBoundedGitOutput(process.stderr, stderrLimit, operation, root, "stderr"),
|
|
3010
|
+
process.exitCode
|
|
3011
|
+
], { concurrency: "unbounded" });
|
|
3012
|
+
return Object.freeze({
|
|
3013
|
+
stdout,
|
|
3014
|
+
stderr,
|
|
3015
|
+
exitCode: Number(exitCode)
|
|
3016
|
+
});
|
|
3017
|
+
})).pipe(Effect.catchTag("PlatformError", (cause) => fail$4(operation, "GitFailed", root, cause.message)));
|
|
3018
|
+
}
|
|
3019
|
+
function collectBoundedGitOutput(stream, maxBytes, operation, root, output) {
|
|
3020
|
+
return Effect.gen(function* () {
|
|
3021
|
+
const chunks = [];
|
|
3022
|
+
let length = 0;
|
|
3023
|
+
yield* Stream.runForEach(stream, (chunk) => {
|
|
3024
|
+
if (length + chunk.byteLength > maxBytes) return fail$4(operation, "LimitExceeded", root, `Git ${output} exceeds ${maxBytes} bytes`);
|
|
3025
|
+
chunks.push(chunk);
|
|
3026
|
+
length += chunk.byteLength;
|
|
3027
|
+
return Effect.void;
|
|
3028
|
+
});
|
|
3029
|
+
const bytes = new Uint8Array(length);
|
|
3030
|
+
let offset = 0;
|
|
3031
|
+
for (const chunk of chunks) {
|
|
3032
|
+
bytes.set(chunk, offset);
|
|
3033
|
+
offset += chunk.byteLength;
|
|
3034
|
+
}
|
|
3035
|
+
return bytes;
|
|
3036
|
+
});
|
|
3037
|
+
}
|
|
3038
|
+
function decodeGitOutput$2(bytes, operation, root) {
|
|
3039
|
+
return Effect.try({
|
|
3040
|
+
try: () => decoder$2.decode(bytes),
|
|
3041
|
+
catch: (cause) => failure$4(operation, "GitFailed", root, errorMessage$2(cause))
|
|
3042
|
+
});
|
|
3043
|
+
}
|
|
3044
|
+
function gitFailureDetail$2(args, stderr) {
|
|
3045
|
+
try {
|
|
3046
|
+
return decoder$2.decode(stderr).trim() || `Git ${args[0] ?? "command"} failed`;
|
|
3047
|
+
} catch {
|
|
3048
|
+
return `Git ${args[0] ?? "command"} failed with non-UTF-8 stderr`;
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
function gitBlobId(bytes, objectFormat) {
|
|
3052
|
+
const header = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
|
|
3053
|
+
const digest = createHash(objectFormat);
|
|
3054
|
+
digest.update(header);
|
|
3055
|
+
digest.update(bytes);
|
|
3056
|
+
return digest.digest("hex");
|
|
3057
|
+
}
|
|
3058
|
+
function fileMode(mode) {
|
|
3059
|
+
return mode === "100755" ? 493 : 420;
|
|
3060
|
+
}
|
|
3061
|
+
function receipt(planDigest, readToken, outcome, changedPaths) {
|
|
3062
|
+
return Object.freeze({
|
|
3063
|
+
planDigest,
|
|
3064
|
+
readToken,
|
|
3065
|
+
outcome,
|
|
3066
|
+
changedPaths: Object.freeze([...changedPaths])
|
|
3067
|
+
});
|
|
3068
|
+
}
|
|
3069
|
+
function equalBytes(left, right) {
|
|
3070
|
+
return left.byteLength === right.byteLength && left.every((value, index) => value === right[index]);
|
|
3071
|
+
}
|
|
3072
|
+
function pathsOverlap(left, right) {
|
|
3073
|
+
return left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`);
|
|
3074
|
+
}
|
|
3075
|
+
function mapPlatform$4(operation, candidate) {
|
|
3076
|
+
return (effect) => effect.pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (failure) => platformFailure$3(operation, candidate, failure)))));
|
|
3077
|
+
}
|
|
3078
|
+
function platformFailure$3(operation, candidate, cause, fallback = "FilesystemFailed") {
|
|
3079
|
+
return failure$4(operation, cause.reason._tag === "NotFound" ? "Missing" : fallback, candidate, cause.message);
|
|
3080
|
+
}
|
|
3081
|
+
function invalidInput(operation, candidate, detail) {
|
|
3082
|
+
return failure$4(operation, "InvalidInput", candidate, detail);
|
|
3083
|
+
}
|
|
3084
|
+
function checked(operation, evaluate) {
|
|
3085
|
+
return Effect.try({
|
|
3086
|
+
try: evaluate,
|
|
3087
|
+
catch: (cause) => isContentWorkspaceFailure(cause) ? cause : failure$4(operation, "InvalidInput", void 0, errorMessage$2(cause))
|
|
3088
|
+
});
|
|
3089
|
+
}
|
|
3090
|
+
function isContentWorkspaceFailure(input) {
|
|
3091
|
+
return typeof input === "object" && input !== null && "_tag" in input && input._tag === "ContentWorkspaceFailure";
|
|
3092
|
+
}
|
|
3093
|
+
function fail$4(operation, reason, candidate, detail) {
|
|
3094
|
+
return Effect.fail(failure$4(operation, reason, candidate, detail));
|
|
3095
|
+
}
|
|
3096
|
+
function failure$4(operation, reason, candidate, detail) {
|
|
3097
|
+
return Object.freeze({
|
|
3098
|
+
_tag: "ContentWorkspaceFailure",
|
|
3099
|
+
operation,
|
|
3100
|
+
reason,
|
|
3101
|
+
...candidate === void 0 ? {} : { path: candidate },
|
|
3102
|
+
detail
|
|
3103
|
+
});
|
|
3104
|
+
}
|
|
3105
|
+
function errorMessage$2(error) {
|
|
3106
|
+
return error instanceof Error ? error.message : String(error);
|
|
3107
|
+
}
|
|
3108
|
+
function compareText$6(left, right) {
|
|
3109
|
+
const leftBytes = encoder.encode(left);
|
|
3110
|
+
const rightBytes = encoder.encode(right);
|
|
3111
|
+
const length = Math.min(leftBytes.length, rightBytes.length);
|
|
3112
|
+
for (let index = 0; index < length; index += 1) {
|
|
3113
|
+
const difference = leftBytes[index] - rightBytes[index];
|
|
3114
|
+
if (difference !== 0) return difference;
|
|
3115
|
+
}
|
|
3116
|
+
return leftBytes.length - rightBytes.length;
|
|
3117
|
+
}
|
|
3118
|
+
//#endregion
|
|
3119
|
+
//#region ../../resources/content-workspace/dist/providers/git-effect-platform-node/runtime.js
|
|
3120
|
+
/** Acquire a fresh capability factory without opening any caller-selected workspace or home. */
|
|
3121
|
+
function defineNodeContentWorkspaceRuntimeProvider() {
|
|
3122
|
+
return defineRuntimeProvider({
|
|
3123
|
+
id: "content-workspace.git-effect-platform-node",
|
|
3124
|
+
title: "Content workspace (git-effect-platform-node)",
|
|
3125
|
+
provides: ContentWorkspaceRuntimeResource,
|
|
3126
|
+
requires: [],
|
|
3127
|
+
build: () => providerFx.acquireRelease({
|
|
3128
|
+
acquire: Effect.sync(() => makeNodeContentWorkspaceResource()),
|
|
3129
|
+
release: () => Effect.void
|
|
3130
|
+
})
|
|
3131
|
+
});
|
|
3132
|
+
}
|
|
3133
|
+
//#endregion
|
|
3134
|
+
//#region ../../resources/filesystem/dist/providers/effect-platform-node/index.js
|
|
3135
|
+
/** Declares stateless Node filesystem capabilities; individual operations own their handles. */
|
|
3136
|
+
function defineNodeFilesystemRuntimeProvider() {
|
|
3137
|
+
return defineRuntimeProvider({
|
|
3138
|
+
id: "filesystem.effect-platform-node",
|
|
3139
|
+
title: "Native Node filesystem",
|
|
3140
|
+
provides: FilesystemRuntimeResource,
|
|
3141
|
+
requires: [],
|
|
3142
|
+
build: () => providerFx.acquireRelease({
|
|
3143
|
+
acquire: Effect.scoped(Effect.gen(function* () {
|
|
3144
|
+
const context = yield* Layer.build(NodeServices.layer);
|
|
3145
|
+
return Object.freeze({
|
|
3146
|
+
fileSystem: Context.get(context, FileSystem.FileSystem),
|
|
3147
|
+
path: Context.get(context, Path.Path)
|
|
3148
|
+
});
|
|
3149
|
+
})),
|
|
3150
|
+
release: () => Effect.void
|
|
3151
|
+
})
|
|
3152
|
+
});
|
|
3153
|
+
}
|
|
3154
|
+
//#endregion
|
|
3155
|
+
//#region ../../resources/native-agent-provider/providers/effect-platform-node-shared.ts
|
|
3156
|
+
const MAX_PROCESS_OUTPUT_BYTES = 4194304;
|
|
3157
|
+
const PROCESS_START_TIMEOUT = "10 seconds";
|
|
3158
|
+
const PROCESS_RUN_TIMEOUT = "2 minutes";
|
|
3159
|
+
const PROCESS_FORCE_KILL_AFTER$2 = "5 seconds";
|
|
3160
|
+
const MAX_FAILURE_DETAIL = 4096;
|
|
3161
|
+
const processSemaphores = /* @__PURE__ */ new Map();
|
|
3162
|
+
/**
|
|
3163
|
+
* Acquires the bounded Node kernel used by one provider session.
|
|
3164
|
+
*
|
|
3165
|
+
* The concrete provider fixes its ordinary command before acquisition; the
|
|
3166
|
+
* caller supplies only the provider-owned home for this session.
|
|
3167
|
+
*/
|
|
3168
|
+
function acquireEffectPlatformNodeProvider(provider, command, input) {
|
|
3169
|
+
return Effect.gen(function* () {
|
|
3170
|
+
if (!Value.Check(NativeProviderSessionInputSchema, input)) return yield* fail$3(provider, "acquire", "InvalidInput", "not-started", void 0, "Provider session input is invalid");
|
|
3171
|
+
const fs = yield* FileSystem.FileSystem;
|
|
3172
|
+
const paths = yield* Path.Path;
|
|
3173
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
3174
|
+
const home = yield* requireCanonicalDirectory(fs, paths, provider, "acquire", input.home);
|
|
3175
|
+
const semaphore = processSemaphore(provider, home);
|
|
3176
|
+
const serialized = (operation, effect) => semaphore.withPermits(1)(requireCanonicalDirectory(fs, paths, provider, operation, home).pipe(Effect.andThen(effect)));
|
|
3177
|
+
const run = (operation, args) => runCommand({
|
|
3178
|
+
provider,
|
|
3179
|
+
operation,
|
|
3180
|
+
command,
|
|
3181
|
+
home,
|
|
3182
|
+
args,
|
|
3183
|
+
spawner
|
|
3184
|
+
});
|
|
3185
|
+
const mutation = (operation, args) => run(operation, args).pipe(Effect.as(Object.freeze({
|
|
3186
|
+
provider,
|
|
3187
|
+
operation,
|
|
3188
|
+
commandPhase: "command-returned"
|
|
3189
|
+
})));
|
|
3190
|
+
const requireLocalDirectory = (operation, candidate) => requireCanonicalDirectory(fs, paths, provider, operation, candidate);
|
|
3191
|
+
const readPluginEntry = (operation, root, request) => readBoundedPluginFile(fs, paths, provider, operation, home, root, request);
|
|
3192
|
+
return Object.freeze({
|
|
3193
|
+
provider,
|
|
3194
|
+
home,
|
|
3195
|
+
serialized,
|
|
3196
|
+
run,
|
|
3197
|
+
mutation,
|
|
3198
|
+
requireLocalDirectory,
|
|
3199
|
+
readPluginEntry,
|
|
3200
|
+
homePath: (...segments) => paths.join(home, ...segments)
|
|
3201
|
+
});
|
|
3202
|
+
});
|
|
3203
|
+
}
|
|
3204
|
+
/** Validates a marketplace source before a concrete provider constructs native arguments. */
|
|
3205
|
+
function requireMarketplaceSource(provider, operation, source) {
|
|
3206
|
+
return Value.Check(NativeMarketplaceSourceSchema, source) ? Effect.succeed(source) : fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Marketplace source is invalid");
|
|
3207
|
+
}
|
|
3208
|
+
/**
|
|
3209
|
+
* Parses and validates one provider JSON response without exposing untyped native payloads.
|
|
3210
|
+
*
|
|
3211
|
+
* @param provider - Provider that emitted the response.
|
|
3212
|
+
* @param operation - Native operation whose response is being decoded.
|
|
3213
|
+
* @param schema - TypeBox authority for the normalized response.
|
|
3214
|
+
* @param text - Raw native stdout to parse and validate.
|
|
3215
|
+
*/
|
|
3216
|
+
function decodeProviderJson(provider, operation, schema, text) {
|
|
3217
|
+
return Effect.try({
|
|
3218
|
+
try: () => JSON.parse(text),
|
|
3219
|
+
catch: (cause) => failure$3(provider, operation, "InvalidJson", "command-returned", void 0, errorMessage$1(cause))
|
|
3220
|
+
}).pipe(Effect.flatMap((value) => Value.Check(schema, value) ? Effect.succeed(value) : fail$3(provider, operation, "ProtocolFailed", "command-returned", void 0, "Provider JSON did not match the expected native response schema")));
|
|
3221
|
+
}
|
|
3222
|
+
/** Validates one marketplace identity before native removal argument construction. */
|
|
3223
|
+
function requireMarketplaceIdentityInput(provider, operation, input) {
|
|
3224
|
+
return Value.Check(NativeProviderMarketplaceIdentityInputSchema, input) ? Effect.succeed(input.identity) : fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Marketplace identity is not canonical");
|
|
3225
|
+
}
|
|
3226
|
+
/** Validates one provider-qualified plugin selector before native mutation. */
|
|
3227
|
+
function requirePluginSelectorInput(provider, operation, input) {
|
|
3228
|
+
return Value.Check(NativeProviderPluginSelectorInputSchema, input) ? Effect.succeed(input.selector) : fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Plugin selector is not canonical");
|
|
3229
|
+
}
|
|
3230
|
+
/** Validates one bounded point-addressed plugin-file read request. */
|
|
3231
|
+
function requirePluginFilesReadInput(provider, operation, input) {
|
|
3232
|
+
return Value.Check(NativeProviderPluginFilesReadInputSchema, input) ? Effect.succeed(input) : fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Plugin file batch request is invalid");
|
|
3233
|
+
}
|
|
3234
|
+
/**
|
|
3235
|
+
* Canonicalizes the Git fields used to construct one native marketplace source.
|
|
3236
|
+
*
|
|
3237
|
+
* @param provider - Provider that will consume the marketplace source.
|
|
3238
|
+
* @param operation - Native operation for typed failure attribution.
|
|
3239
|
+
* @param repositoryUrl - Canonical HTTPS Git repository URL.
|
|
3240
|
+
* @param revision - Cloneable provider selector selected by the caller.
|
|
3241
|
+
* @param sparsePaths - Bounded provider content roots to expose natively.
|
|
3242
|
+
*/
|
|
3243
|
+
function requireGitMarketplaceSource(provider, operation, repositoryUrl, revision, sparsePaths) {
|
|
3244
|
+
return Effect.gen(function* () {
|
|
3245
|
+
if (!Value.Check(CanonicalGitRepositoryUrlSchema, repositoryUrl)) return yield* fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Git marketplace repositoryUrl must be a canonical HTTPS .git URL");
|
|
3246
|
+
if (!/^[^\s#]+$/u.test(revision) || revision.length > 256) return yield* fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Git marketplace revision is not canonical");
|
|
3247
|
+
if (sparsePaths.length > 64) return yield* fail$3(provider, operation, "LimitExceeded", "not-started", void 0, "Git marketplace sparse path count exceeds the resource limit");
|
|
3248
|
+
const canonicalSparsePaths = sparsePaths.map((path) => canonicalSparsePath(path));
|
|
3249
|
+
if (canonicalSparsePaths.some((path) => path === void 0)) return yield* fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Git marketplace sparse paths must be canonical relative POSIX paths");
|
|
3250
|
+
const present = canonicalSparsePaths.filter((path) => path !== void 0);
|
|
3251
|
+
if (new Set(present).size !== present.length) return yield* fail$3(provider, operation, "InvalidInput", "not-started", void 0, "Git marketplace sparse paths must be unique");
|
|
3252
|
+
return Object.freeze({
|
|
3253
|
+
repositoryUrl,
|
|
3254
|
+
revision,
|
|
3255
|
+
sparsePaths: Object.freeze([...present].sort(compareText$5))
|
|
3256
|
+
});
|
|
3257
|
+
});
|
|
3258
|
+
}
|
|
3259
|
+
function runCommand(input) {
|
|
3260
|
+
const command = ChildProcess.make(input.command, input.args, {
|
|
3261
|
+
cwd: input.home,
|
|
3262
|
+
env: providerEnvironment(input.provider, input.home),
|
|
3263
|
+
extendEnv: true,
|
|
3264
|
+
stdin: "ignore",
|
|
3265
|
+
forceKillAfter: PROCESS_FORCE_KILL_AFTER$2
|
|
3266
|
+
});
|
|
3267
|
+
return Effect.scoped(input.spawner.spawn(command).pipe(Effect.mapError((cause) => platformFailure$2(input.provider, input.operation, void 0, cause, "CommandFailed", "not-started")), Effect.timeoutOrElse({
|
|
3268
|
+
duration: PROCESS_START_TIMEOUT,
|
|
3269
|
+
orElse: () => fail$3(input.provider, input.operation, "CommandTimedOut", "not-started", void 0, "Provider command did not start within its bounded timeout")
|
|
3270
|
+
}), Effect.flatMap((process) => Effect.all([
|
|
3271
|
+
collectBoundedOutput$3(process.stdout, input.provider, input.operation, "started"),
|
|
3272
|
+
collectBoundedOutput$3(process.stderr, input.provider, input.operation, "started"),
|
|
3273
|
+
process.exitCode.pipe(Effect.mapError((cause) => platformFailure$2(input.provider, input.operation, void 0, cause, "CommandFailed", "started")))
|
|
3274
|
+
], { concurrency: "unbounded" }).pipe(Effect.timeoutOrElse({
|
|
3275
|
+
duration: PROCESS_RUN_TIMEOUT,
|
|
3276
|
+
orElse: () => fail$3(input.provider, input.operation, "CommandTimedOut", "started", void 0, "Provider command exceeded its bounded execution timeout")
|
|
3277
|
+
}))), Effect.flatMap(([stdout, stderr, exitCode]) => Number(exitCode) === 0 ? Effect.succeed(Object.freeze({
|
|
3278
|
+
stdout,
|
|
3279
|
+
stderr
|
|
3280
|
+
})) : fail$3(input.provider, input.operation, "CommandFailed", "command-returned", void 0, `Provider command exited ${Number(exitCode)}: ${stderr.trim() || stdout.trim()}`))));
|
|
3281
|
+
}
|
|
3282
|
+
function collectBoundedOutput$3(stream, provider, operation, phase) {
|
|
3283
|
+
const initial = Object.freeze({
|
|
3284
|
+
chunks: Object.freeze([]),
|
|
3285
|
+
bytes: 0
|
|
3286
|
+
});
|
|
3287
|
+
return Stream.runFoldEffect(stream.pipe(Stream.mapError((cause) => platformFailure$2(provider, operation, void 0, cause, "CommandFailed", phase))), () => initial, (state, chunk) => {
|
|
3288
|
+
const bytes = state.bytes + chunk.byteLength;
|
|
3289
|
+
return bytes > MAX_PROCESS_OUTPUT_BYTES ? fail$3(provider, operation, "LimitExceeded", phase, void 0, "Provider command exceeded its bounded output limit") : Effect.succeed(Object.freeze({
|
|
3290
|
+
chunks: Object.freeze([...state.chunks, chunk]),
|
|
3291
|
+
bytes
|
|
3292
|
+
}));
|
|
3293
|
+
}).pipe(Effect.flatMap((state) => Effect.try({
|
|
3294
|
+
try: () => new TextDecoder("utf-8", { fatal: true }).decode(concatenate$2(state.chunks)),
|
|
3295
|
+
catch: (cause) => failure$3(provider, operation, "ProtocolFailed", phase, void 0, errorMessage$1(cause))
|
|
3296
|
+
})));
|
|
3297
|
+
}
|
|
3298
|
+
function readBoundedPluginFile(fs, paths, provider, operation, home, rootInput, input) {
|
|
3299
|
+
return Effect.gen(function* () {
|
|
3300
|
+
const relativePath = canonicalRelativeFile(input.relativePath);
|
|
3301
|
+
if (relativePath === void 0) return yield* fail$3(provider, operation, "InvalidInput", "not-started", input.relativePath, "Plugin file path must be one canonical relative POSIX file path");
|
|
3302
|
+
const root = yield* requireCanonicalDirectory(fs, paths, provider, operation, rootInput);
|
|
3303
|
+
if (!isContained(paths, home, root)) return yield* fail$3(provider, operation, "Aliased", "not-started", root, "Installed plugin root escaped the explicit provider home");
|
|
3304
|
+
const candidate = paths.join(root, ...relativePath.split("/"));
|
|
3305
|
+
if (!isContained(paths, root, candidate)) return yield* fail$3(provider, operation, "Aliased", "not-started", candidate, "Plugin file path escaped its installed package root");
|
|
3306
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$3(provider, operation, candidate, "not-started"))) !== candidate) return yield* fail$3(provider, operation, "Aliased", "not-started", candidate, "Plugin file path is aliased");
|
|
3307
|
+
const status = yield* fs.stat(candidate).pipe(mapPlatform$3(provider, operation, candidate, "not-started"));
|
|
3308
|
+
const size = Number(status.size);
|
|
3309
|
+
if (status.type !== "File") return yield* fail$3(provider, operation, "UnsupportedEntry", "not-started", candidate, "Plugin package entry is not a regular file");
|
|
3310
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > input.maxBytes) return yield* fail$3(provider, operation, "LimitExceeded", "not-started", candidate, "Plugin package file exceeds maxBytes");
|
|
3311
|
+
const bytes = yield* fs.readFile(candidate).pipe(mapPlatform$3(provider, operation, candidate, "not-started"));
|
|
3312
|
+
if (bytes.byteLength !== size) return yield* fail$3(provider, operation, "FilesystemFailed", "not-started", candidate, "Plugin package file size changed while reading");
|
|
3313
|
+
return Object.freeze({
|
|
3314
|
+
kind: "Read",
|
|
3315
|
+
relativePath,
|
|
3316
|
+
byteLength: bytes.byteLength,
|
|
3317
|
+
contentBase64: Buffer.from(bytes).toString("base64")
|
|
3318
|
+
});
|
|
3319
|
+
});
|
|
3320
|
+
}
|
|
3321
|
+
function requireCanonicalDirectory(fs, paths, provider, operation, candidate) {
|
|
3322
|
+
return Effect.gen(function* () {
|
|
3323
|
+
if (!isCanonicalAbsolutePath(paths, candidate)) return yield* fail$3(provider, operation, "InvalidInput", "not-started", candidate, "Directory must be an explicit canonical absolute path");
|
|
3324
|
+
if ((yield* fs.realPath(candidate).pipe(mapPlatform$3(provider, operation, candidate, "not-started"))) !== candidate) return yield* fail$3(provider, operation, "Aliased", "not-started", candidate, "Directory path is aliased");
|
|
3325
|
+
if ((yield* fs.stat(candidate).pipe(mapPlatform$3(provider, operation, candidate, "not-started"))).type !== "Directory") return yield* fail$3(provider, operation, "UnsupportedEntry", "not-started", candidate, "Path must be one existing directory");
|
|
3326
|
+
return candidate;
|
|
3327
|
+
});
|
|
3328
|
+
}
|
|
3329
|
+
function canonicalSparsePath(input) {
|
|
3330
|
+
if (input.length === 0 || input.length > 1024 || input.includes("\\") || input.startsWith("/")) return;
|
|
3331
|
+
const segments = input.split("/");
|
|
3332
|
+
return segments.some((segment) => segment === "" || segment === "." || segment === "..") ? void 0 : segments.join("/");
|
|
3333
|
+
}
|
|
3334
|
+
function canonicalRelativeFile(input) {
|
|
3335
|
+
return canonicalSparsePath(input);
|
|
3336
|
+
}
|
|
3337
|
+
function isCanonicalAbsolutePath(paths, candidate) {
|
|
3338
|
+
return candidate.length <= 16384 && paths.isAbsolute(candidate) && paths.normalize(candidate) === candidate && candidate !== paths.parse(candidate).root;
|
|
3339
|
+
}
|
|
3340
|
+
function isContained(paths, root, candidate) {
|
|
3341
|
+
const relative = paths.relative(root, candidate);
|
|
3342
|
+
return relative !== "" && relative !== ".." && !relative.startsWith(`..${paths.sep}`) && !paths.isAbsolute(relative);
|
|
3343
|
+
}
|
|
3344
|
+
function providerEnvironment(provider, home) {
|
|
3345
|
+
return provider === "codex" ? { CODEX_HOME: home } : { CLAUDE_CONFIG_DIR: home };
|
|
3346
|
+
}
|
|
3347
|
+
function processSemaphore(provider, home) {
|
|
3348
|
+
const key = `${provider}\u0000${home}`;
|
|
3349
|
+
const existing = processSemaphores.get(key);
|
|
3350
|
+
if (existing !== void 0) return existing;
|
|
3351
|
+
const created = Semaphore.makeUnsafe(1);
|
|
3352
|
+
processSemaphores.set(key, created);
|
|
3353
|
+
return created;
|
|
3354
|
+
}
|
|
3355
|
+
function concatenate$2(chunks) {
|
|
3356
|
+
const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
|
|
3357
|
+
const bytes = new Uint8Array(length);
|
|
3358
|
+
let offset = 0;
|
|
3359
|
+
for (const chunk of chunks) {
|
|
3360
|
+
bytes.set(chunk, offset);
|
|
3361
|
+
offset += chunk.byteLength;
|
|
3362
|
+
}
|
|
3363
|
+
return bytes;
|
|
3364
|
+
}
|
|
3365
|
+
function mapPlatform$3(provider, operation, candidate, phase, fallback = "FilesystemFailed") {
|
|
3366
|
+
return (effect) => effect.pipe(Effect.mapError((cause) => platformFailure$2(provider, operation, candidate, cause, fallback, phase)));
|
|
3367
|
+
}
|
|
3368
|
+
function platformFailure$2(provider, operation, candidate, cause, fallback, phase) {
|
|
3369
|
+
return failure$3(provider, operation, cause.reason._tag === "NotFound" ? "Missing" : fallback, phase, candidate, cause.message);
|
|
3370
|
+
}
|
|
3371
|
+
function fail$3(provider, operation, reason, phase, candidate, detail) {
|
|
3372
|
+
return Effect.fail(failure$3(provider, operation, reason, phase, candidate, detail));
|
|
3373
|
+
}
|
|
3374
|
+
function failure$3(provider, operation, reason, commandPhase, candidate, detail) {
|
|
3375
|
+
return Object.freeze({
|
|
3376
|
+
_tag: "NativeAgentProviderFailure",
|
|
3377
|
+
provider,
|
|
3378
|
+
operation,
|
|
3379
|
+
reason,
|
|
3380
|
+
commandPhase,
|
|
3381
|
+
...candidate === void 0 ? {} : { path: candidate },
|
|
3382
|
+
detail: detail.slice(0, MAX_FAILURE_DETAIL)
|
|
3383
|
+
});
|
|
3384
|
+
}
|
|
3385
|
+
function errorMessage$1(error) {
|
|
3386
|
+
return error instanceof Error ? error.message : String(error);
|
|
3387
|
+
}
|
|
3388
|
+
function compareText$5(left, right) {
|
|
3389
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
3390
|
+
}
|
|
3391
|
+
//#endregion
|
|
3392
|
+
//#region ../../resources/native-agent-provider/dist/providers/claude-effect-platform-node/index.js
|
|
3393
|
+
const NullableStringSchema$1 = Type.Union([Type.String(), Type.Null()]);
|
|
3394
|
+
const GitHubRepositorySchema = Type.String({
|
|
3395
|
+
pattern: "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$",
|
|
3396
|
+
minLength: 3,
|
|
3397
|
+
maxLength: 256
|
|
3398
|
+
});
|
|
3399
|
+
const ClaudeMarketplaceListSchema = Type.Array(Type.Object({
|
|
3400
|
+
name: Type.String(),
|
|
3401
|
+
source: Type.Optional(NullableStringSchema$1),
|
|
3402
|
+
url: Type.Optional(NullableStringSchema$1),
|
|
3403
|
+
repo: Type.Optional(Type.Union([GitHubRepositorySchema, Type.Null()])),
|
|
3404
|
+
path: Type.Optional(NullableStringSchema$1),
|
|
3405
|
+
installLocation: Type.Optional(NullableStringSchema$1),
|
|
3406
|
+
revision: Type.Optional(NullableStringSchema$1),
|
|
3407
|
+
ref: Type.Optional(NullableStringSchema$1)
|
|
3408
|
+
}, { additionalProperties: true }), { maxItems: 1024 });
|
|
3409
|
+
const ClaudePluginListSchema = Type.Array(Type.Object({
|
|
3410
|
+
id: Type.String(),
|
|
3411
|
+
version: Type.Optional(NullableStringSchema$1),
|
|
3412
|
+
enabled: Type.Optional(Type.Union([Type.Boolean(), Type.Null()])),
|
|
3413
|
+
installPath: Type.Optional(NullableStringSchema$1)
|
|
3414
|
+
}, { additionalProperties: true }), { maxItems: 4096 });
|
|
3415
|
+
const CLAUDE_CAPABILITIES = [
|
|
3416
|
+
"marketplace-list",
|
|
3417
|
+
"marketplace-add",
|
|
3418
|
+
"marketplace-remove",
|
|
3419
|
+
"marketplace-update",
|
|
3420
|
+
"plugin-list",
|
|
3421
|
+
"plugin-install",
|
|
3422
|
+
"plugin-enable",
|
|
3423
|
+
"plugin-disable",
|
|
3424
|
+
"plugin-remove",
|
|
3425
|
+
"plugin-update"
|
|
3426
|
+
];
|
|
3427
|
+
/**
|
|
3428
|
+
* Constructs the platform-requiring Claude provider without choosing a runtime.
|
|
3429
|
+
*/
|
|
3430
|
+
function makeClaudeEffectPlatformNodeProvider(options = {}) {
|
|
3431
|
+
const command = options.command ?? "claude";
|
|
3432
|
+
return Object.freeze({ acquire: (input) => acquireEffectPlatformNodeProvider("claude", command, input).pipe(Effect.map((kernel) => {
|
|
3433
|
+
const probe = () => kernel.serialized("probe", Effect.gen(function* () {
|
|
3434
|
+
const version = yield* kernel.run("probe", ["--version"]);
|
|
3435
|
+
return Object.freeze({
|
|
3436
|
+
provider: "claude",
|
|
3437
|
+
home: kernel.home,
|
|
3438
|
+
version: yield* requireVersion$1(version.stdout),
|
|
3439
|
+
capabilities: [...CLAUDE_CAPABILITIES]
|
|
3440
|
+
});
|
|
3441
|
+
}));
|
|
3442
|
+
const readInventory = () => claudeInventory(kernel);
|
|
3443
|
+
const inventory = () => kernel.serialized("inventory", readInventory());
|
|
3444
|
+
return Object.freeze({
|
|
3445
|
+
provider: "claude",
|
|
3446
|
+
home: kernel.home,
|
|
3447
|
+
probe,
|
|
3448
|
+
inventory,
|
|
3449
|
+
readPluginFiles: (request) => kernel.serialized("plugin-files-read", requirePluginFilesReadInput("claude", "plugin-files-read", request).pipe(Effect.flatMap((validated) => readInventory().pipe(Effect.flatMap((live) => selectPluginRoot$1(live.plugins, validated.selector).pipe(Effect.flatMap((root) => Effect.forEach(validated.files, (file) => kernel.readPluginEntry("plugin-files-read", root, file).pipe(Effect.catchIf((error) => error.reason === "Missing" || error.reason === "LimitExceeded", (error) => {
|
|
3450
|
+
const missing = Object.freeze({
|
|
3451
|
+
kind: error.reason === "Missing" ? "Missing" : "TooLarge",
|
|
3452
|
+
relativePath: file.relativePath
|
|
3453
|
+
});
|
|
3454
|
+
return Effect.succeed(missing);
|
|
3455
|
+
})), { concurrency: 1 }).pipe(Effect.map((files) => {
|
|
3456
|
+
return Object.freeze({
|
|
3457
|
+
selector: validated.selector,
|
|
3458
|
+
files: Object.freeze(files)
|
|
3459
|
+
});
|
|
3460
|
+
}))))))))),
|
|
3461
|
+
addMarketplace: (source) => kernel.serialized("marketplace-add", requireMarketplaceSource("claude", "marketplace-add", source).pipe(Effect.flatMap((validated) => claudeMarketplaceAddArgs(kernel, validated)), Effect.flatMap((args) => kernel.mutation("marketplace-add", args)))),
|
|
3462
|
+
removeMarketplace: (request) => kernel.serialized("marketplace-remove", requireMarketplaceIdentityInput("claude", "marketplace-remove", request).pipe(Effect.flatMap((identity) => kernel.mutation("marketplace-remove", [
|
|
3463
|
+
"plugin",
|
|
3464
|
+
"marketplace",
|
|
3465
|
+
"remove",
|
|
3466
|
+
identity,
|
|
3467
|
+
"--scope",
|
|
3468
|
+
"user"
|
|
3469
|
+
])))),
|
|
3470
|
+
installPlugin: (request) => kernel.serialized("plugin-install", requirePluginSelectorInput("claude", "plugin-install", request).pipe(Effect.flatMap((selector) => pluginMutation(kernel, "plugin-install", "install", selector)))),
|
|
3471
|
+
enablePlugin: (request) => kernel.serialized("plugin-enable", requirePluginSelectorInput("claude", "plugin-enable", request).pipe(Effect.flatMap((selector) => pluginMutation(kernel, "plugin-enable", "enable", selector)))),
|
|
3472
|
+
removePlugin: (request) => kernel.serialized("plugin-remove", requirePluginSelectorInput("claude", "plugin-remove", request).pipe(Effect.flatMap((selector) => pluginMutation(kernel, "plugin-remove", "uninstall", selector))))
|
|
3473
|
+
});
|
|
3474
|
+
})) });
|
|
3475
|
+
}
|
|
3476
|
+
/**
|
|
3477
|
+
* Constructs a ready Claude resource whose Node platform is supplied only while
|
|
3478
|
+
* acquiring a session.
|
|
3479
|
+
*/
|
|
3480
|
+
function makeNodeClaudeNativeAgentProviderResource(options = {}) {
|
|
3481
|
+
const provider = makeClaudeEffectPlatformNodeProvider(options);
|
|
3482
|
+
return Object.freeze({ acquire: (input) => provider.acquire(input).pipe(Effect.provide(NodeServices.layer)) });
|
|
3483
|
+
}
|
|
3484
|
+
function claudeInventory(kernel) {
|
|
3485
|
+
return Effect.gen(function* () {
|
|
3486
|
+
const marketplaceOutput = yield* kernel.run("inventory", [
|
|
3487
|
+
"plugin",
|
|
3488
|
+
"marketplace",
|
|
3489
|
+
"list",
|
|
3490
|
+
"--json"
|
|
3491
|
+
]);
|
|
3492
|
+
const pluginOutput = yield* kernel.run("inventory", [
|
|
3493
|
+
"plugin",
|
|
3494
|
+
"list",
|
|
3495
|
+
"--json"
|
|
3496
|
+
]);
|
|
3497
|
+
const marketplaceRecord = yield* decodeProviderJson("claude", "inventory", ClaudeMarketplaceListSchema, marketplaceOutput.stdout);
|
|
3498
|
+
const pluginRecord = yield* decodeProviderJson("claude", "inventory", ClaudePluginListSchema, pluginOutput.stdout);
|
|
3499
|
+
const marketplaces = yield* Effect.forEach(marketplaceRecord, normalizeMarketplace$1, { concurrency: 1 });
|
|
3500
|
+
const plugins = yield* Effect.forEach(pluginRecord, normalizePlugin$1, { concurrency: 1 });
|
|
3501
|
+
yield* requireUniqueInventory$1(marketplaces, plugins);
|
|
3502
|
+
const normalized = Object.freeze({
|
|
3503
|
+
provider: "claude",
|
|
3504
|
+
marketplaces: [...marketplaces].sort(byIdentity$1),
|
|
3505
|
+
plugins: [...plugins].sort(bySelector$1)
|
|
3506
|
+
});
|
|
3507
|
+
return Value.Check(NativeProviderInventorySchema, normalized) ? normalized : yield* Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude native inventory contains non-canonical facts"));
|
|
3508
|
+
});
|
|
3509
|
+
}
|
|
3510
|
+
function normalizeMarketplace$1(entry) {
|
|
3511
|
+
if (entry.source === "git") {
|
|
3512
|
+
const repositoryUrl = entry.url;
|
|
3513
|
+
const revision = entry.ref ?? entry.revision ?? null;
|
|
3514
|
+
return repositoryUrl !== null && repositoryUrl !== void 0 ? Effect.succeed(Object.freeze({
|
|
3515
|
+
identity: entry.name,
|
|
3516
|
+
source: Object.freeze({
|
|
3517
|
+
kind: "git",
|
|
3518
|
+
repositoryUrl,
|
|
3519
|
+
revision
|
|
3520
|
+
}),
|
|
3521
|
+
installedRoot: entry.installLocation ?? null
|
|
3522
|
+
})) : Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude Git marketplace omitted its URL"));
|
|
3523
|
+
}
|
|
3524
|
+
if (entry.source === "github") {
|
|
3525
|
+
const repository = entry.repo;
|
|
3526
|
+
return repository === null || repository === void 0 ? Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude GitHub marketplace omitted its repository")) : Effect.succeed(Object.freeze({
|
|
3527
|
+
identity: entry.name,
|
|
3528
|
+
source: Object.freeze({
|
|
3529
|
+
kind: "git",
|
|
3530
|
+
repositoryUrl: `https://github.com/${repository}.git`,
|
|
3531
|
+
revision: entry.ref ?? entry.revision ?? null
|
|
3532
|
+
}),
|
|
3533
|
+
installedRoot: entry.installLocation ?? null
|
|
3534
|
+
}));
|
|
3535
|
+
}
|
|
3536
|
+
if (entry.source === "directory") return entry.path === null || entry.path === void 0 ? Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude local marketplace omitted its source path")) : Effect.succeed(Object.freeze({
|
|
3537
|
+
identity: entry.name,
|
|
3538
|
+
source: Object.freeze({
|
|
3539
|
+
kind: "local",
|
|
3540
|
+
root: entry.path
|
|
3541
|
+
}),
|
|
3542
|
+
installedRoot: entry.installLocation ?? null
|
|
3543
|
+
}));
|
|
3544
|
+
return entry.source === null || entry.source === void 0 ? Effect.succeed(Object.freeze({
|
|
3545
|
+
identity: entry.name,
|
|
3546
|
+
source: null,
|
|
3547
|
+
installedRoot: entry.installLocation ?? null
|
|
3548
|
+
})) : Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude marketplace source kind is unsupported"));
|
|
3549
|
+
}
|
|
3550
|
+
function normalizePlugin$1(entry) {
|
|
3551
|
+
const separator = entry.id.lastIndexOf("@");
|
|
3552
|
+
if (separator <= 0 || separator === entry.id.length - 1) return Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude plugin id is not one selector"));
|
|
3553
|
+
const name = entry.id.slice(0, separator);
|
|
3554
|
+
const marketplaceIdentity = entry.id.slice(separator + 1);
|
|
3555
|
+
return Effect.succeed(Object.freeze({
|
|
3556
|
+
selector: entry.id,
|
|
3557
|
+
marketplaceIdentity,
|
|
3558
|
+
name,
|
|
3559
|
+
installed: true,
|
|
3560
|
+
enabled: entry.enabled ?? null,
|
|
3561
|
+
version: entry.version ?? null,
|
|
3562
|
+
root: entry.installPath ?? null
|
|
3563
|
+
}));
|
|
3564
|
+
}
|
|
3565
|
+
function requireUniqueInventory$1(marketplaces, plugins) {
|
|
3566
|
+
return new Set(marketplaces.map((entry) => entry.identity)).size === marketplaces.length && new Set(plugins.map((entry) => entry.selector)).size === plugins.length ? Effect.void : Effect.fail(providerFailure$1("inventory", "ProtocolFailed", "Claude native inventory contains duplicate identities"));
|
|
3567
|
+
}
|
|
3568
|
+
function selectPluginRoot$1(plugins, selector) {
|
|
3569
|
+
const matches = plugins.filter((entry) => entry.selector === selector && entry.installed);
|
|
3570
|
+
const selected = matches[0];
|
|
3571
|
+
if (matches.length !== 1 || selected === void 0) return Effect.fail(providerFailure$1("plugin-files-read", matches.length === 0 ? "Missing" : "ProtocolFailed", matches.length === 0 ? "Claude installed plugin selector is absent" : "Claude installed plugin selector is ambiguous"));
|
|
3572
|
+
return selected.root === null ? Effect.fail(providerFailure$1("plugin-files-read", "ProtocolFailed", "Claude installed plugin omitted its native package root")) : Effect.succeed(selected.root);
|
|
3573
|
+
}
|
|
3574
|
+
function claudeMarketplaceAddArgs(kernel, source) {
|
|
3575
|
+
if (source.kind === "local") return kernel.requireLocalDirectory("marketplace-add", source.root).pipe(Effect.map((root) => Object.freeze([
|
|
3576
|
+
"plugin",
|
|
3577
|
+
"marketplace",
|
|
3578
|
+
"add",
|
|
3579
|
+
root,
|
|
3580
|
+
"--scope",
|
|
3581
|
+
"user"
|
|
3582
|
+
])));
|
|
3583
|
+
return requireGitMarketplaceSource("claude", "marketplace-add", source.repositoryUrl, source.revision, source.sparsePaths).pipe(Effect.map((git) => Object.freeze([
|
|
3584
|
+
"plugin",
|
|
3585
|
+
"marketplace",
|
|
3586
|
+
"add",
|
|
3587
|
+
`${git.repositoryUrl}#${git.revision}`,
|
|
3588
|
+
"--scope",
|
|
3589
|
+
"user",
|
|
3590
|
+
...git.sparsePaths.length === 0 ? [] : ["--sparse", ...git.sparsePaths]
|
|
3591
|
+
])));
|
|
3592
|
+
}
|
|
3593
|
+
function pluginMutation(kernel, operation, action, selector) {
|
|
3594
|
+
return kernel.mutation(operation, [
|
|
3595
|
+
"plugin",
|
|
3596
|
+
action,
|
|
3597
|
+
selector,
|
|
3598
|
+
"--scope",
|
|
3599
|
+
"user"
|
|
3600
|
+
]);
|
|
3601
|
+
}
|
|
3602
|
+
function requireVersion$1(stdout) {
|
|
3603
|
+
const version = stdout.trim();
|
|
3604
|
+
return version.length > 0 && version.length <= 4096 ? Effect.succeed(version) : Effect.fail(providerFailure$1("probe", "ProtocolFailed", "Claude version output is empty or oversized"));
|
|
3605
|
+
}
|
|
3606
|
+
function providerFailure$1(operation, reason, detail) {
|
|
3607
|
+
return Object.freeze({
|
|
3608
|
+
_tag: "NativeAgentProviderFailure",
|
|
3609
|
+
provider: "claude",
|
|
3610
|
+
operation,
|
|
3611
|
+
reason,
|
|
3612
|
+
commandPhase: "command-returned",
|
|
3613
|
+
detail
|
|
3614
|
+
});
|
|
3615
|
+
}
|
|
3616
|
+
function byIdentity$1(left, right) {
|
|
3617
|
+
return compareText$4(left.identity, right.identity);
|
|
3618
|
+
}
|
|
3619
|
+
function bySelector$1(left, right) {
|
|
3620
|
+
return compareText$4(left.selector, right.selector);
|
|
3621
|
+
}
|
|
3622
|
+
function compareText$4(left, right) {
|
|
3623
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
3624
|
+
}
|
|
3625
|
+
//#endregion
|
|
3626
|
+
//#region ../../resources/native-agent-provider/dist/providers/claude-effect-platform-node/runtime.js
|
|
3627
|
+
/** Acquire a fresh capability factory without opening any caller-selected workspace or home. */
|
|
3628
|
+
function defineNodeClaudeNativeAgentProviderRuntimeProvider() {
|
|
3629
|
+
return defineRuntimeProvider({
|
|
3630
|
+
id: "native-agent-provider.claude.claude-effect-platform-node",
|
|
3631
|
+
title: "Claude native agent provider (claude-effect-platform-node)",
|
|
3632
|
+
provides: ClaudeNativeAgentProviderRuntimeResource,
|
|
3633
|
+
requires: [],
|
|
3634
|
+
build: () => providerFx.acquireRelease({
|
|
3635
|
+
acquire: Effect.sync(() => makeNodeClaudeNativeAgentProviderResource()),
|
|
3636
|
+
release: () => Effect.void
|
|
3637
|
+
})
|
|
3638
|
+
});
|
|
3639
|
+
}
|
|
3640
|
+
//#endregion
|
|
3641
|
+
//#region ../../resources/native-agent-provider/dist/providers/codex-effect-platform-node/index.js
|
|
3642
|
+
const NullableStringSchema = Type.Union([Type.String(), Type.Null()]);
|
|
3643
|
+
const CodexMarketplaceSourceSchema = Type.Union([Type.Object({
|
|
3644
|
+
sourceType: Type.Union([Type.Literal("git"), Type.Literal("local")]),
|
|
3645
|
+
source: Type.String()
|
|
3646
|
+
}, { additionalProperties: true }), Type.Null()]);
|
|
3647
|
+
const CodexMarketplaceListSchema = Type.Object({ marketplaces: Type.Array(Type.Object({
|
|
3648
|
+
name: Type.String(),
|
|
3649
|
+
root: Type.String(),
|
|
3650
|
+
marketplaceSource: Type.Optional(CodexMarketplaceSourceSchema)
|
|
3651
|
+
}, { additionalProperties: true }), { maxItems: 1024 }) }, { additionalProperties: true });
|
|
3652
|
+
const CodexPluginListSchema = Type.Object({ installed: Type.Array(Type.Object({
|
|
3653
|
+
pluginId: Type.String(),
|
|
3654
|
+
name: Type.String(),
|
|
3655
|
+
marketplaceName: Type.String(),
|
|
3656
|
+
version: Type.Optional(NullableStringSchema),
|
|
3657
|
+
installed: Type.Boolean(),
|
|
3658
|
+
enabled: Type.Optional(Type.Union([Type.Boolean(), Type.Null()]))
|
|
3659
|
+
}, { additionalProperties: true }), { maxItems: 4096 }) }, { additionalProperties: true });
|
|
3660
|
+
const CODEX_CAPABILITIES = [
|
|
3661
|
+
"marketplace-list",
|
|
3662
|
+
"marketplace-add",
|
|
3663
|
+
"marketplace-remove",
|
|
3664
|
+
"plugin-list",
|
|
3665
|
+
"plugin-install",
|
|
3666
|
+
"plugin-remove"
|
|
3667
|
+
];
|
|
3668
|
+
/**
|
|
3669
|
+
* Constructs the platform-requiring Codex provider without choosing a runtime.
|
|
3670
|
+
*/
|
|
3671
|
+
function makeCodexEffectPlatformNodeProvider(options = {}) {
|
|
3672
|
+
const command = options.command ?? "codex";
|
|
3673
|
+
return Object.freeze({ acquire: (input) => acquireEffectPlatformNodeProvider("codex", command, input).pipe(Effect.map((kernel) => {
|
|
3674
|
+
const probe = () => kernel.serialized("probe", Effect.gen(function* () {
|
|
3675
|
+
const version = yield* kernel.run("probe", ["--version"]);
|
|
3676
|
+
return Object.freeze({
|
|
3677
|
+
provider: "codex",
|
|
3678
|
+
home: kernel.home,
|
|
3679
|
+
version: yield* requireVersion(version.stdout),
|
|
3680
|
+
capabilities: [...CODEX_CAPABILITIES]
|
|
3681
|
+
});
|
|
3682
|
+
}));
|
|
3683
|
+
const readInventory = () => codexInventory(kernel);
|
|
3684
|
+
const inventory = () => kernel.serialized("inventory", readInventory());
|
|
3685
|
+
return Object.freeze({
|
|
3686
|
+
provider: "codex",
|
|
3687
|
+
home: kernel.home,
|
|
3688
|
+
probe,
|
|
3689
|
+
inventory,
|
|
3690
|
+
readPluginFiles: (request) => kernel.serialized("plugin-files-read", requirePluginFilesReadInput("codex", "plugin-files-read", request).pipe(Effect.flatMap((validated) => readInventory().pipe(Effect.flatMap((live) => selectPluginRoot(kernel, live.plugins, validated.selector).pipe(Effect.flatMap((root) => Effect.forEach(validated.files, (file) => kernel.readPluginEntry("plugin-files-read", root, file).pipe(Effect.catchIf((error) => error.reason === "Missing" || error.reason === "LimitExceeded", (error) => {
|
|
3691
|
+
const missing = Object.freeze({
|
|
3692
|
+
kind: error.reason === "Missing" ? "Missing" : "TooLarge",
|
|
3693
|
+
relativePath: file.relativePath
|
|
3694
|
+
});
|
|
3695
|
+
return Effect.succeed(missing);
|
|
3696
|
+
})), { concurrency: 1 }).pipe(Effect.map((files) => {
|
|
3697
|
+
return Object.freeze({
|
|
3698
|
+
selector: validated.selector,
|
|
3699
|
+
files: Object.freeze(files)
|
|
3700
|
+
});
|
|
3701
|
+
}))))))))),
|
|
3702
|
+
addMarketplace: (source) => kernel.serialized("marketplace-add", requireMarketplaceSource("codex", "marketplace-add", source).pipe(Effect.flatMap((validated) => codexMarketplaceAddArgs(kernel, validated)), Effect.flatMap((args) => kernel.mutation("marketplace-add", args)))),
|
|
3703
|
+
removeMarketplace: (request) => kernel.serialized("marketplace-remove", requireMarketplaceIdentityInput("codex", "marketplace-remove", request).pipe(Effect.flatMap((identity) => kernel.mutation("marketplace-remove", [
|
|
3704
|
+
"plugin",
|
|
3705
|
+
"marketplace",
|
|
3706
|
+
"remove",
|
|
3707
|
+
identity,
|
|
3708
|
+
"--json"
|
|
3709
|
+
])))),
|
|
3710
|
+
installPlugin: (request) => kernel.serialized("plugin-install", requirePluginSelectorInput("codex", "plugin-install", request).pipe(Effect.flatMap((selector) => kernel.mutation("plugin-install", [
|
|
3711
|
+
"plugin",
|
|
3712
|
+
"add",
|
|
3713
|
+
selector,
|
|
3714
|
+
"--json"
|
|
3715
|
+
])))),
|
|
3716
|
+
removePlugin: (request) => kernel.serialized("plugin-remove", requirePluginSelectorInput("codex", "plugin-remove", request).pipe(Effect.flatMap((selector) => kernel.mutation("plugin-remove", [
|
|
3717
|
+
"plugin",
|
|
3718
|
+
"remove",
|
|
3719
|
+
selector,
|
|
3720
|
+
"--json"
|
|
3721
|
+
]))))
|
|
3722
|
+
});
|
|
3723
|
+
})) });
|
|
3724
|
+
}
|
|
3725
|
+
/**
|
|
3726
|
+
* Constructs a ready Codex resource whose Node platform is supplied only while
|
|
3727
|
+
* acquiring a session.
|
|
3728
|
+
*/
|
|
3729
|
+
function makeNodeCodexNativeAgentProviderResource(options = {}) {
|
|
3730
|
+
const provider = makeCodexEffectPlatformNodeProvider(options);
|
|
3731
|
+
return Object.freeze({ acquire: (input) => provider.acquire(input).pipe(Effect.provide(NodeServices.layer)) });
|
|
3732
|
+
}
|
|
3733
|
+
function codexInventory(kernel) {
|
|
3734
|
+
return Effect.gen(function* () {
|
|
3735
|
+
const marketplaceOutput = yield* kernel.run("inventory", [
|
|
3736
|
+
"plugin",
|
|
3737
|
+
"marketplace",
|
|
3738
|
+
"list",
|
|
3739
|
+
"--json"
|
|
3740
|
+
]);
|
|
3741
|
+
const pluginOutput = yield* kernel.run("inventory", [
|
|
3742
|
+
"plugin",
|
|
3743
|
+
"list",
|
|
3744
|
+
"--json"
|
|
3745
|
+
]);
|
|
3746
|
+
const marketplaceRecord = yield* decodeProviderJson("codex", "inventory", CodexMarketplaceListSchema, marketplaceOutput.stdout);
|
|
3747
|
+
const pluginRecord = yield* decodeProviderJson("codex", "inventory", CodexPluginListSchema, pluginOutput.stdout);
|
|
3748
|
+
const marketplaces = yield* Effect.forEach(marketplaceRecord.marketplaces, normalizeMarketplace, { concurrency: 1 });
|
|
3749
|
+
const plugins = yield* Effect.forEach(pluginRecord.installed, normalizePlugin, { concurrency: 1 });
|
|
3750
|
+
yield* requireUniqueInventory(marketplaces, plugins);
|
|
3751
|
+
const normalized = Object.freeze({
|
|
3752
|
+
provider: "codex",
|
|
3753
|
+
marketplaces: [...marketplaces].sort(byIdentity),
|
|
3754
|
+
plugins: [...plugins].sort(bySelector)
|
|
3755
|
+
});
|
|
3756
|
+
return Value.Check(NativeProviderInventorySchema, normalized) ? normalized : yield* Effect.fail(providerFailure("inventory", "ProtocolFailed", "Codex native inventory contains non-canonical facts"));
|
|
3757
|
+
});
|
|
3758
|
+
}
|
|
3759
|
+
function normalizeMarketplace(entry) {
|
|
3760
|
+
const nativeSource = entry.marketplaceSource;
|
|
3761
|
+
if (nativeSource === null || nativeSource === void 0) return Effect.succeed(Object.freeze({
|
|
3762
|
+
identity: entry.name,
|
|
3763
|
+
source: null,
|
|
3764
|
+
installedRoot: entry.root
|
|
3765
|
+
}));
|
|
3766
|
+
const source = nativeSource.sourceType === "git" && nativeSource.source.startsWith("https://") ? Object.freeze({
|
|
3767
|
+
kind: "git",
|
|
3768
|
+
repositoryUrl: nativeSource.source,
|
|
3769
|
+
revision: null
|
|
3770
|
+
}) : nativeSource.sourceType === "local" && path.isAbsolute(nativeSource.source) ? Object.freeze({
|
|
3771
|
+
kind: "local",
|
|
3772
|
+
root: nativeSource.source
|
|
3773
|
+
}) : void 0;
|
|
3774
|
+
return source === void 0 ? Effect.fail(providerFailure("inventory", "ProtocolFailed", "Codex marketplace source is incomplete or non-canonical")) : Effect.succeed(Object.freeze({
|
|
3775
|
+
identity: entry.name,
|
|
3776
|
+
source,
|
|
3777
|
+
installedRoot: entry.root
|
|
3778
|
+
}));
|
|
3779
|
+
}
|
|
3780
|
+
function normalizePlugin(entry) {
|
|
3781
|
+
const expectedSelector = `${entry.name}@${entry.marketplaceName}`;
|
|
3782
|
+
return entry.pluginId === expectedSelector ? Effect.succeed(Object.freeze({
|
|
3783
|
+
selector: entry.pluginId,
|
|
3784
|
+
marketplaceIdentity: entry.marketplaceName,
|
|
3785
|
+
name: entry.name,
|
|
3786
|
+
installed: entry.installed,
|
|
3787
|
+
enabled: entry.enabled ?? null,
|
|
3788
|
+
version: entry.version ?? null,
|
|
3789
|
+
root: null
|
|
3790
|
+
})) : Effect.fail(providerFailure("inventory", "ProtocolFailed", "Codex plugin identity fields do not describe one selector"));
|
|
3791
|
+
}
|
|
3792
|
+
function requireUniqueInventory(marketplaces, plugins) {
|
|
3793
|
+
return new Set(marketplaces.map((entry) => entry.identity)).size === marketplaces.length && new Set(plugins.map((entry) => entry.selector)).size === plugins.length ? Effect.void : Effect.fail(providerFailure("inventory", "ProtocolFailed", "Codex native inventory contains duplicate identities"));
|
|
3794
|
+
}
|
|
3795
|
+
function selectPluginRoot(kernel, plugins, selector) {
|
|
3796
|
+
const matches = plugins.filter((entry) => entry.selector === selector && entry.installed);
|
|
3797
|
+
const selected = matches[0];
|
|
3798
|
+
if (matches.length !== 1 || selected === void 0) return Effect.fail(providerFailure("plugin-files-read", matches.length === 0 ? "Missing" : "ProtocolFailed", matches.length === 0 ? "Codex installed plugin selector is absent" : "Codex installed plugin selector is ambiguous"));
|
|
3799
|
+
if (selected.version === null) return Effect.fail(providerFailure("plugin-files-read", "ProtocolFailed", "Codex installed plugin omitted its version"));
|
|
3800
|
+
return Effect.succeed(kernel.homePath("plugins", "cache", selected.marketplaceIdentity, selected.name, selected.version));
|
|
3801
|
+
}
|
|
3802
|
+
function codexMarketplaceAddArgs(kernel, source) {
|
|
3803
|
+
if (source.kind === "local") return kernel.requireLocalDirectory("marketplace-add", source.root).pipe(Effect.map((root) => Object.freeze([
|
|
3804
|
+
"plugin",
|
|
3805
|
+
"marketplace",
|
|
3806
|
+
"add",
|
|
3807
|
+
root,
|
|
3808
|
+
"--json"
|
|
3809
|
+
])));
|
|
3810
|
+
return requireGitMarketplaceSource("codex", "marketplace-add", source.repositoryUrl, source.revision, source.sparsePaths).pipe(Effect.map((git) => Object.freeze([
|
|
3811
|
+
"plugin",
|
|
3812
|
+
"marketplace",
|
|
3813
|
+
"add",
|
|
3814
|
+
git.repositoryUrl,
|
|
3815
|
+
"--ref",
|
|
3816
|
+
git.revision,
|
|
3817
|
+
...git.sparsePaths.flatMap((path) => ["--sparse", path]),
|
|
3818
|
+
"--json"
|
|
3819
|
+
])));
|
|
3820
|
+
}
|
|
3821
|
+
function requireVersion(stdout) {
|
|
3822
|
+
const version = stdout.trim();
|
|
3823
|
+
return version.length > 0 && version.length <= 4096 ? Effect.succeed(version) : Effect.fail(providerFailure("probe", "ProtocolFailed", "Codex version output is empty or oversized"));
|
|
3824
|
+
}
|
|
3825
|
+
function providerFailure(operation, reason, detail) {
|
|
3826
|
+
return Object.freeze({
|
|
3827
|
+
_tag: "NativeAgentProviderFailure",
|
|
3828
|
+
provider: "codex",
|
|
3829
|
+
operation,
|
|
3830
|
+
reason,
|
|
3831
|
+
commandPhase: "command-returned",
|
|
3832
|
+
detail
|
|
3833
|
+
});
|
|
3834
|
+
}
|
|
3835
|
+
function byIdentity(left, right) {
|
|
3836
|
+
return compareText$3(left.identity, right.identity);
|
|
3837
|
+
}
|
|
3838
|
+
function bySelector(left, right) {
|
|
3839
|
+
return compareText$3(left.selector, right.selector);
|
|
3840
|
+
}
|
|
3841
|
+
function compareText$3(left, right) {
|
|
3842
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
3843
|
+
}
|
|
3844
|
+
//#endregion
|
|
3845
|
+
//#region ../../resources/native-agent-provider/dist/providers/codex-effect-platform-node/runtime.js
|
|
3846
|
+
/** Acquire a fresh capability factory without opening any caller-selected workspace or home. */
|
|
3847
|
+
function defineNodeCodexNativeAgentProviderRuntimeProvider() {
|
|
3848
|
+
return defineRuntimeProvider({
|
|
3849
|
+
id: "native-agent-provider.codex.codex-effect-platform-node",
|
|
3850
|
+
title: "Codex native agent provider (codex-effect-platform-node)",
|
|
3851
|
+
provides: CodexNativeAgentProviderRuntimeResource,
|
|
3852
|
+
requires: [],
|
|
3853
|
+
build: () => providerFx.acquireRelease({
|
|
3854
|
+
acquire: Effect.sync(() => makeNodeCodexNativeAgentProviderResource()),
|
|
3855
|
+
release: () => Effect.void
|
|
3856
|
+
})
|
|
3857
|
+
});
|
|
3858
|
+
}
|
|
3859
|
+
//#endregion
|
|
3860
|
+
//#region ../../resources/rule-evaluation/dist/providers/grit-effect-platform-node/index.js
|
|
3861
|
+
const TEMP_CATALOG_PREFIX = "habitat-rule-evaluation-";
|
|
3862
|
+
const GRIT_PATTERN_PREFIX = "habitat_rule_evaluation_";
|
|
3863
|
+
const MAX_GRIT_STDOUT_BYTES = 262144;
|
|
3864
|
+
const GRIT_REPORT_HEADROOM_BYTES = 262144;
|
|
3865
|
+
const MAX_GRIT_STDERR_BYTES = 16777216;
|
|
3866
|
+
/** Structural schema for Grit provider construction. */
|
|
3867
|
+
const GritRuleEvaluationProviderConfigSchema = ReadonlyObject(Type.Object({
|
|
3868
|
+
command: Type.String({
|
|
3869
|
+
minLength: 1,
|
|
3870
|
+
description: "Program invoked for Grit rule evaluation"
|
|
3871
|
+
}),
|
|
3872
|
+
args: Type.Array(Type.String(), { description: "Arguments placed before the provider-owned Grit check arguments" }),
|
|
3873
|
+
timeoutMs: Type.Integer({
|
|
3874
|
+
minimum: 1,
|
|
3875
|
+
description: "Maximum duration of one native Grit check"
|
|
3876
|
+
})
|
|
3877
|
+
}), { additionalProperties: false });
|
|
3878
|
+
const GritPositionSchema = Type.Object({
|
|
3879
|
+
line: Type.Integer({
|
|
3880
|
+
minimum: 1,
|
|
3881
|
+
description: "One-based Grit source line"
|
|
3882
|
+
}),
|
|
3883
|
+
col: Type.Integer({
|
|
3884
|
+
minimum: 1,
|
|
3885
|
+
description: "One-based Grit source column"
|
|
3886
|
+
}),
|
|
3887
|
+
offset: Type.Integer({
|
|
3888
|
+
minimum: 0,
|
|
3889
|
+
description: "Grit-native source offset"
|
|
3890
|
+
})
|
|
3891
|
+
}, {
|
|
3892
|
+
additionalProperties: false,
|
|
3893
|
+
description: "Grit-reported source position"
|
|
3894
|
+
});
|
|
3895
|
+
const GritResultSchema = Type.Object({
|
|
3896
|
+
check_id: Type.String({
|
|
3897
|
+
minLength: 1,
|
|
3898
|
+
description: "Grit check identity with evaluator suffix"
|
|
3899
|
+
}),
|
|
3900
|
+
local_name: Type.String({
|
|
3901
|
+
minLength: 1,
|
|
3902
|
+
description: "Local Grit catalog pattern name"
|
|
3903
|
+
}),
|
|
3904
|
+
path: Type.String({
|
|
3905
|
+
minLength: 1,
|
|
3906
|
+
description: "Grit-reported subject path"
|
|
3907
|
+
}),
|
|
3908
|
+
start: GritPositionSchema,
|
|
3909
|
+
end: GritPositionSchema,
|
|
3910
|
+
extra: Type.Object({
|
|
3911
|
+
message: Type.Union([Type.String(), Type.Null()], { description: "Optional Grit diagnostic message" }),
|
|
3912
|
+
severity: Type.Literal("error", { description: "Mechanical severity emitted by the scoped catalog" })
|
|
3913
|
+
}, {
|
|
3914
|
+
additionalProperties: false,
|
|
3915
|
+
description: "Additional Grit finding data"
|
|
3916
|
+
})
|
|
3917
|
+
}, { additionalProperties: false });
|
|
3918
|
+
const GritReportSchema = Type.Object({
|
|
3919
|
+
paths: Type.Array(Type.String({ minLength: 1 }), { description: "Subject paths included in the Grit report" }),
|
|
3920
|
+
results: Type.Array(GritResultSchema, { description: "Findings included in the Grit report" })
|
|
3921
|
+
}, { additionalProperties: false });
|
|
3922
|
+
const requestValidator = Schema.Compile(RuleEvaluationRequestSchema);
|
|
3923
|
+
const configValidator = Schema.Compile(GritRuleEvaluationProviderConfigSchema);
|
|
3924
|
+
/**
|
|
3925
|
+
* Creates a Grit-backed evaluator over Effect Platform filesystem, path, and
|
|
3926
|
+
* child-process services.
|
|
3927
|
+
*/
|
|
3928
|
+
function makeGritRuleEvaluationResource(config) {
|
|
3929
|
+
const evaluate = Effect.fn("ruleEvaluation.grit.evaluate")(function* (input) {
|
|
3930
|
+
if (!configValidator.Check(config)) return yield* fail$2("InvalidInput", "Grit provider configuration does not match its structural contract");
|
|
3931
|
+
if (!requestValidator.Check(input)) return yield* fail$2("InvalidInput", "Rule-evaluation request requires resolved programs and non-empty subject paths");
|
|
3932
|
+
const path = yield* Path.Path;
|
|
3933
|
+
if (input.subjectPaths.some((subjectPath) => !path.isAbsolute(subjectPath))) return yield* fail$2("InvalidInput", "Rule-evaluation subject paths must be caller-resolved absolute paths");
|
|
3934
|
+
const [firstProgram, ...remainingPrograms] = input.programs;
|
|
3935
|
+
if (firstProgram === void 0) return yield* fail$2("InvalidInput", "Rule-evaluation request requires at least one program");
|
|
3936
|
+
if (new Set(input.programs.map(({ id }) => id)).size !== input.programs.length) return yield* fail$2("InvalidInput", "Rule-evaluation program identities must be unique");
|
|
3937
|
+
const programs = [materializeProgram(firstProgram, 0), ...remainingPrograms.map((program) => materializeProgram(program, 0))];
|
|
3938
|
+
const evaluations = yield* Effect.forEach(programs, (program) => Effect.scoped(withScopedGritCatalog([program], (catalog) => runGritCheck(config, catalog, [program], input.subjectPaths))), { concurrency: 1 });
|
|
3939
|
+
return Object.freeze({ results: Object.freeze(evaluations.flatMap(({ results }) => results)) });
|
|
3940
|
+
});
|
|
3941
|
+
return Object.freeze({ evaluate });
|
|
3942
|
+
}
|
|
3943
|
+
function withScopedGritCatalog(programs, use) {
|
|
3944
|
+
return Effect.gen(function* () {
|
|
3945
|
+
const fs = yield* FileSystem.FileSystem;
|
|
3946
|
+
const path = yield* Path.Path;
|
|
3947
|
+
const root = yield* fs.makeTempDirectoryScoped({ prefix: TEMP_CATALOG_PREFIX }).pipe(mapPlatform$2("SetupFailed", "Failed to allocate temporary Grit catalog"));
|
|
3948
|
+
const catalog = Object.freeze({
|
|
3949
|
+
root,
|
|
3950
|
+
gritDirectory: path.join(root, ".grit"),
|
|
3951
|
+
userConfigDirectory: path.join(root, "user-config"),
|
|
3952
|
+
cacheDirectory: path.join(root, "cache")
|
|
3953
|
+
});
|
|
3954
|
+
yield* fs.makeDirectory(catalog.gritDirectory).pipe(mapPlatform$2("SetupFailed", "Failed to create Grit catalog directory"));
|
|
3955
|
+
yield* fs.makeDirectory(catalog.userConfigDirectory).pipe(mapPlatform$2("SetupFailed", "Failed to create Grit user-config directory"));
|
|
3956
|
+
yield* fs.makeDirectory(catalog.cacheDirectory).pipe(mapPlatform$2("SetupFailed", "Failed to create Grit cache directory"));
|
|
3957
|
+
yield* fs.writeFileString(path.join(catalog.gritDirectory, "grit.yaml"), renderGritCatalog(programs)).pipe(mapPlatform$2("SetupFailed", "Failed to write temporary Grit catalog"));
|
|
3958
|
+
return yield* use(catalog);
|
|
3959
|
+
});
|
|
3960
|
+
}
|
|
3961
|
+
function runGritCheck(config, catalog, programs, subjectPaths) {
|
|
3962
|
+
const stderrLimit = gritStderrLimit(subjectPaths);
|
|
3963
|
+
return Effect.gen(function* () {
|
|
3964
|
+
const process = yield* ChildProcess.make(config.command, [
|
|
3965
|
+
...config.args,
|
|
3966
|
+
"--json",
|
|
3967
|
+
"check",
|
|
3968
|
+
"--no-cache",
|
|
3969
|
+
"--grit-dir",
|
|
3970
|
+
catalog.gritDirectory,
|
|
3971
|
+
...subjectPaths
|
|
3972
|
+
], {
|
|
3973
|
+
cwd: catalog.root,
|
|
3974
|
+
env: {
|
|
3975
|
+
CLICOLOR: "0",
|
|
3976
|
+
FORCE_COLOR: "0",
|
|
3977
|
+
GRIT_CACHE_DIR: catalog.cacheDirectory,
|
|
3978
|
+
GRIT_DOWNLOADS_DISABLED: "true",
|
|
3979
|
+
GRIT_MAX_FILE_SIZE_BYTES: "0",
|
|
3980
|
+
GRIT_USER_CONFIG: catalog.userConfigDirectory,
|
|
3981
|
+
GRIT_TELEMETRY_DISABLED: "true",
|
|
3982
|
+
NO_COLOR: "1",
|
|
3983
|
+
RAYON_NUM_THREADS: "2"
|
|
3984
|
+
},
|
|
3985
|
+
extendEnv: true,
|
|
3986
|
+
stdin: "ignore",
|
|
3987
|
+
killSignal: "SIGTERM",
|
|
3988
|
+
forceKillAfter: "2 seconds"
|
|
3989
|
+
}).pipe(mapPlatform$2("ExecutionFailed", "Failed to start Grit"));
|
|
3990
|
+
const output = yield* Effect.all({
|
|
3991
|
+
stdout: collectBoundedOutput$2(process.stdout, "stdout", MAX_GRIT_STDOUT_BYTES),
|
|
3992
|
+
stderr: collectBoundedOutput$2(process.stderr, "stderr", stderrLimit),
|
|
3993
|
+
exitCode: process.exitCode.pipe(Effect.map(Number), mapPlatform$2("ExecutionFailed", "Failed to observe Grit exit"))
|
|
3994
|
+
}, { concurrency: "unbounded" });
|
|
3995
|
+
return Object.freeze(output);
|
|
3996
|
+
}).pipe(Effect.timeoutOrElse({
|
|
3997
|
+
duration: config.timeoutMs,
|
|
3998
|
+
orElse: () => fail$2("TimedOut", `Grit evaluation exceeded its ${config.timeoutMs}ms timeout`)
|
|
3999
|
+
})).pipe(Effect.flatMap((observation) => {
|
|
4000
|
+
if (observation.exitCode !== 0) {
|
|
4001
|
+
const detail = observation.stderr.trim() || observation.stdout.trim();
|
|
4002
|
+
return fail$2("ExecutionFailed", detail.length === 0 ? `Grit exited with code ${observation.exitCode}` : `Grit exited with code ${observation.exitCode}: ${detail}`);
|
|
4003
|
+
}
|
|
4004
|
+
if (observation.stdout.trim().length > 0) return fail$2("InvalidOutput", "Grit check emitted unexpected stdout alongside its stderr JSON report");
|
|
4005
|
+
return decodeGritReport(observation.stderr).pipe(Effect.flatMap((report) => resultFromGritReport(report, programs)));
|
|
4006
|
+
}));
|
|
4007
|
+
}
|
|
4008
|
+
function decodeGritReport(stderr) {
|
|
4009
|
+
const lines = stderr.split(/\r?\n/u).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
4010
|
+
if (lines.length === 0) return fail$2("InvalidOutput", "Grit check emitted no stderr JSON report");
|
|
4011
|
+
const reports = [];
|
|
4012
|
+
for (const line of lines) {
|
|
4013
|
+
let decoded;
|
|
4014
|
+
try {
|
|
4015
|
+
decoded = JSON.parse(line);
|
|
4016
|
+
} catch {
|
|
4017
|
+
continue;
|
|
4018
|
+
}
|
|
4019
|
+
try {
|
|
4020
|
+
reports.push(Value.Parse(GritReportSchema, decoded));
|
|
4021
|
+
} catch (error) {
|
|
4022
|
+
return fail$2("InvalidOutput", `Grit check emitted unexpected structured output: ${errorMessage(error)}`);
|
|
4023
|
+
}
|
|
4024
|
+
}
|
|
4025
|
+
const [report, ...additionalReports] = reports;
|
|
4026
|
+
if (report === void 0) return fail$2("InvalidOutput", "Grit check emitted no valid stderr JSON report");
|
|
4027
|
+
if (additionalReports.length > 0) return fail$2("InvalidOutput", "Grit check emitted multiple stderr JSON reports");
|
|
4028
|
+
return Effect.succeed(report);
|
|
4029
|
+
}
|
|
4030
|
+
function resultFromGritReport(report, programs) {
|
|
4031
|
+
const programsByPattern = new Map(programs.map((program) => [program.patternName, program]));
|
|
4032
|
+
const findingsByProgram = new Map(programs.map(({ id }) => [id, []]));
|
|
4033
|
+
for (const result of report.results) {
|
|
4034
|
+
const program = programsByPattern.get(result.local_name);
|
|
4035
|
+
if (program === void 0 || !result.check_id.startsWith(`#${result.local_name}/`)) return fail$2("InvalidOutput", `Grit check reported unexpected pattern identity '${result.local_name}'`);
|
|
4036
|
+
findingsByProgram.get(program.id)?.push(Object.freeze({
|
|
4037
|
+
path: result.path,
|
|
4038
|
+
start: Object.freeze({
|
|
4039
|
+
line: result.start.line,
|
|
4040
|
+
column: result.start.col,
|
|
4041
|
+
offset: result.start.offset
|
|
4042
|
+
}),
|
|
4043
|
+
end: Object.freeze({
|
|
4044
|
+
line: result.end.line,
|
|
4045
|
+
column: result.end.col,
|
|
4046
|
+
offset: result.end.offset
|
|
4047
|
+
}),
|
|
4048
|
+
message: result.extra.message
|
|
4049
|
+
}));
|
|
4050
|
+
}
|
|
4051
|
+
return Effect.succeed(Object.freeze({ results: Object.freeze(programs.map(({ id }) => Object.freeze({
|
|
4052
|
+
programId: id,
|
|
4053
|
+
findings: Object.freeze((findingsByProgram.get(id) ?? []).sort(compareFindings))
|
|
4054
|
+
}))) }));
|
|
4055
|
+
}
|
|
4056
|
+
function materializeProgram(program, index) {
|
|
4057
|
+
return Object.freeze({
|
|
4058
|
+
id: program.id,
|
|
4059
|
+
patternName: `${GRIT_PATTERN_PREFIX}${index}`,
|
|
4060
|
+
program: program.program
|
|
4061
|
+
});
|
|
4062
|
+
}
|
|
4063
|
+
function renderGritCatalog(programs) {
|
|
4064
|
+
return `${JSON.stringify({
|
|
4065
|
+
version: "0.0.2",
|
|
4066
|
+
patterns: programs.map(({ id, patternName, program }) => Object.freeze({
|
|
4067
|
+
name: patternName,
|
|
4068
|
+
title: id,
|
|
4069
|
+
level: "error",
|
|
4070
|
+
body: program
|
|
4071
|
+
}))
|
|
4072
|
+
}, void 0, 2)}\n`;
|
|
4073
|
+
}
|
|
4074
|
+
function collectBoundedOutput$2(stream, channel, outputLimit) {
|
|
4075
|
+
return Stream.runFoldEffect(stream.pipe(Stream.mapError((error) => failure$2("ExecutionFailed", `Failed to drain Grit ${channel}: ${error.message}`))), () => Object.freeze({
|
|
4076
|
+
buffer: new Uint8Array(outputLimit),
|
|
4077
|
+
bytes: 0
|
|
4078
|
+
}), (state, chunk) => {
|
|
4079
|
+
if (chunk.byteLength === 0) return Effect.succeed(state);
|
|
4080
|
+
const bytes = state.bytes + chunk.byteLength;
|
|
4081
|
+
return bytes > outputLimit ? fail$2("InvalidOutput", `Grit ${channel} exceeded its ${outputLimit}-byte output limit`) : Effect.sync(() => {
|
|
4082
|
+
state.buffer.set(chunk, state.bytes);
|
|
4083
|
+
return Object.freeze({
|
|
4084
|
+
buffer: state.buffer,
|
|
4085
|
+
bytes
|
|
4086
|
+
});
|
|
4087
|
+
});
|
|
4088
|
+
}).pipe(Effect.flatMap((state) => Effect.try({
|
|
4089
|
+
try: () => new TextDecoder("utf-8", { fatal: true }).decode(state.buffer.subarray(0, state.bytes)),
|
|
4090
|
+
catch: (error) => failure$2("InvalidOutput", `Grit ${channel} was not valid UTF-8: ${errorMessage(error)}`)
|
|
4091
|
+
})));
|
|
4092
|
+
}
|
|
4093
|
+
function gritStderrLimit(subjectPaths) {
|
|
4094
|
+
const encodedSubjectPaths = Buffer.byteLength(JSON.stringify(subjectPaths), "utf8");
|
|
4095
|
+
return Math.min(MAX_GRIT_STDERR_BYTES, encodedSubjectPaths + GRIT_REPORT_HEADROOM_BYTES);
|
|
4096
|
+
}
|
|
4097
|
+
function mapPlatform$2(reason, context) {
|
|
4098
|
+
return (effect) => effect.pipe(Effect.mapError((error) => failure$2(reason, `${context}: ${error.message}`)));
|
|
4099
|
+
}
|
|
4100
|
+
function fail$2(reason, detail) {
|
|
4101
|
+
return Effect.fail(failure$2(reason, detail));
|
|
4102
|
+
}
|
|
4103
|
+
function failure$2(reason, detail) {
|
|
4104
|
+
const normalized = detail.trim() || "Rule evaluation failed";
|
|
4105
|
+
const bounded = normalized.length <= 4096 ? normalized : `${normalized.slice(0, MAX_RULE_EVALUATION_FAILURE_DETAIL - 3)}...`;
|
|
4106
|
+
return Object.freeze({
|
|
4107
|
+
_tag: "RuleEvaluationFailure",
|
|
4108
|
+
reason,
|
|
4109
|
+
detail: bounded
|
|
4110
|
+
});
|
|
4111
|
+
}
|
|
4112
|
+
function errorMessage(error) {
|
|
4113
|
+
return error instanceof Error ? error.message : String(error);
|
|
4114
|
+
}
|
|
4115
|
+
function compareFindings(left, right) {
|
|
4116
|
+
return compareText$2(left.path, right.path) || left.start.line - right.start.line || left.start.column - right.start.column || left.start.offset - right.start.offset || left.end.line - right.end.line || left.end.column - right.end.column || left.end.offset - right.end.offset || compareText$2(left.message ?? "", right.message ?? "");
|
|
4117
|
+
}
|
|
4118
|
+
function compareText$2(left, right) {
|
|
4119
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
4120
|
+
}
|
|
4121
|
+
//#endregion
|
|
4122
|
+
//#region ../../resources/rule-evaluation/dist/providers/grit-effect-platform-node/runtime.js
|
|
4123
|
+
function defineGritRuleEvaluationRuntimeProvider() {
|
|
4124
|
+
return defineRuntimeProvider({
|
|
4125
|
+
id: "rule-evaluation.grit-effect-platform-node",
|
|
4126
|
+
title: "Grit rule evaluation",
|
|
4127
|
+
provides: RuleEvaluationRuntimeResource,
|
|
4128
|
+
requires: [],
|
|
4129
|
+
configSchema: RuntimeSchema.fromTypeBox(GritRuleEvaluationProviderConfigSchema),
|
|
4130
|
+
build: ({ config }) => providerFx.acquireRelease({
|
|
4131
|
+
acquire: Effect.scoped(Effect.gen(function* () {
|
|
4132
|
+
const context = yield* Layer.build(NodeServices.layer);
|
|
4133
|
+
const resource = makeGritRuleEvaluationResource(config);
|
|
4134
|
+
return Object.freeze({ evaluate: (input) => Effect.provideContext(resource.evaluate(input), context) });
|
|
4135
|
+
})),
|
|
4136
|
+
release: () => Effect.void
|
|
4137
|
+
})
|
|
4138
|
+
});
|
|
4139
|
+
}
|
|
4140
|
+
//#endregion
|
|
4141
|
+
//#region ../../resources/source-inventory/dist/providers/git-effect-platform-node/index.js
|
|
4142
|
+
const decoder$1 = new TextDecoder("utf-8", { fatal: true });
|
|
4143
|
+
const GIT_INVENTORY_ARGUMENTS = Object.freeze([
|
|
4144
|
+
"ls-files",
|
|
4145
|
+
"--cached",
|
|
4146
|
+
"--others",
|
|
4147
|
+
"--exclude-standard",
|
|
4148
|
+
"--stage",
|
|
4149
|
+
"--abbrev=1",
|
|
4150
|
+
"-t",
|
|
4151
|
+
"-z"
|
|
4152
|
+
]);
|
|
4153
|
+
const PROCESS_FORCE_KILL_AFTER$1 = "5 seconds";
|
|
4154
|
+
const STDERR_LIMIT$1 = 65536;
|
|
4155
|
+
const STDOUT_LIMIT = 67108864;
|
|
4156
|
+
const TRACKED_RECORD_PATTERN = /^[HSMRCK] (?<mode>100644|100755|120000|160000) [0-9a-f]{1,64} [0-3]\t(?<path>.+)$/su;
|
|
4157
|
+
const observeInputValidator = new Validator({}, ObserveSourceInventoryInputSchema);
|
|
4158
|
+
const sourcePathValidator = new Validator({}, SourceInventoryPathSchema);
|
|
4159
|
+
const sourceInventoryResultValidator = new Validator({}, SourceInventoryResultSchema);
|
|
4160
|
+
/** Structural schema for local-Git source-inventory provider construction. */
|
|
4161
|
+
const GitSourceInventoryProviderOptionsSchema = ReadonlyObject(Type.Object({ gitExecutable: Type.Optional(Type.String({
|
|
4162
|
+
minLength: 1,
|
|
4163
|
+
maxLength: MAX_SOURCE_INVENTORY_ROOT_LENGTH,
|
|
4164
|
+
pattern: "^[^\\u0000]+$",
|
|
4165
|
+
description: "Focused-test override for the ordinary Git executable"
|
|
4166
|
+
})) }), { additionalProperties: false });
|
|
4167
|
+
const providerOptionsValidator = new Validator({}, GitSourceInventoryProviderOptionsSchema);
|
|
4168
|
+
/** Creates a local-Git source inventory over Effect child-process services. */
|
|
4169
|
+
function makeGitSourceInventoryResource(options = {}) {
|
|
4170
|
+
const observe = Effect.fn("sourceInventory.git.observe")(function* (input) {
|
|
4171
|
+
if (!providerOptionsValidator.Check(options)) return yield* fail$1("InvalidInput", void 0, "Source-inventory provider options do not match their structural contract");
|
|
4172
|
+
if (!observeInputValidator.Check(input)) return yield* fail$1("InvalidInput", void 0, "Source-inventory input does not match the bounded resource contract");
|
|
4173
|
+
const command = yield* runGitInventory(options.gitExecutable ?? "git", input.root);
|
|
4174
|
+
if (command.exitCode !== 0) return yield* fail$1("CommandFailed", input.root, gitFailureDetail$1(command.exitCode, command.stderr));
|
|
4175
|
+
return yield* parseGitInventory(command.stdout, input.root, input.maxEntries);
|
|
4176
|
+
});
|
|
4177
|
+
return Object.freeze({ observe });
|
|
4178
|
+
}
|
|
4179
|
+
function runGitInventory(executable, root) {
|
|
4180
|
+
const command = ChildProcess.make(executable, GIT_INVENTORY_ARGUMENTS, {
|
|
4181
|
+
cwd: root,
|
|
4182
|
+
extendEnv: true,
|
|
4183
|
+
stdin: "ignore",
|
|
4184
|
+
forceKillAfter: PROCESS_FORCE_KILL_AFTER$1
|
|
4185
|
+
});
|
|
4186
|
+
return Effect.scoped(Effect.gen(function* () {
|
|
4187
|
+
const process = yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn(command).pipe(mapPlatform$1(root, "SetupFailed"));
|
|
4188
|
+
const [stdout, stderr, exitCode] = yield* Effect.all([
|
|
4189
|
+
collectBoundedOutput$1(process.stdout, STDOUT_LIMIT, "stdout", root),
|
|
4190
|
+
collectBoundedOutput$1(process.stderr, STDERR_LIMIT$1, "stderr", root),
|
|
4191
|
+
process.exitCode.pipe(mapPlatform$1(root, "CommandFailed"))
|
|
4192
|
+
], { concurrency: "unbounded" });
|
|
4193
|
+
return Object.freeze({
|
|
4194
|
+
stdout,
|
|
4195
|
+
stderr,
|
|
4196
|
+
exitCode: Number(exitCode)
|
|
4197
|
+
});
|
|
4198
|
+
}));
|
|
4199
|
+
}
|
|
4200
|
+
function collectBoundedOutput$1(stream, maxBytes, output, root) {
|
|
4201
|
+
const initial = Object.freeze({
|
|
4202
|
+
chunks: Object.freeze([]),
|
|
4203
|
+
bytes: 0
|
|
4204
|
+
});
|
|
4205
|
+
return Stream.runFoldEffect(stream.pipe(Stream.mapError((cause) => platformFailure$1(root, cause, "CommandFailed"))), () => initial, (state, chunk) => {
|
|
4206
|
+
const bytes = state.bytes + chunk.byteLength;
|
|
4207
|
+
if (bytes > maxBytes) return fail$1(output === "stdout" ? "LimitExceeded" : "CommandFailed", root, `Git ${output} exceeds the ${maxBytes}-byte source-inventory bound`);
|
|
4208
|
+
return Effect.succeed(Object.freeze({
|
|
4209
|
+
chunks: Object.freeze([...state.chunks, chunk]),
|
|
4210
|
+
bytes
|
|
4211
|
+
}));
|
|
4212
|
+
}).pipe(Effect.map((state) => concatenate$1(state.chunks, state.bytes)));
|
|
4213
|
+
}
|
|
4214
|
+
function parseGitInventory(bytes, root, maxEntries) {
|
|
4215
|
+
return decodeGitOutput$1(bytes, root).pipe(Effect.flatMap((text) => {
|
|
4216
|
+
if (text.length === 0) return checkedResult(Object.freeze({
|
|
4217
|
+
paths: Object.freeze([]),
|
|
4218
|
+
trackedNonFilePaths: Object.freeze([])
|
|
4219
|
+
}), root);
|
|
4220
|
+
if (!text.endsWith("\0")) return fail$1("InvalidOutput", root, "Git inventory output has a truncated NUL record");
|
|
4221
|
+
const facts = /* @__PURE__ */ new Map();
|
|
4222
|
+
for (const rawRecord of text.slice(0, -1).split("\0")) {
|
|
4223
|
+
if (rawRecord.length === 0) return fail$1("InvalidOutput", root, "Git inventory output contains an empty NUL record");
|
|
4224
|
+
const record = parseGitRecord(rawRecord);
|
|
4225
|
+
if (record === void 0) return fail$1("InvalidOutput", root, "Git ls-files emitted a malformed source-inventory record");
|
|
4226
|
+
if (!sourcePathValidator.Check(record.path)) return fail$1("InvalidOutput", root, "Git ls-files emitted an unsafe or non-canonical relative path");
|
|
4227
|
+
const existing = facts.get(record.path);
|
|
4228
|
+
if (existing !== void 0) {
|
|
4229
|
+
if (existing.source !== record.source) return fail$1("InvalidOutput", root, "Git ls-files reported one path as both tracked and untracked");
|
|
4230
|
+
if (existing.source === "tracked" && record.source === "tracked") facts.set(record.path, Object.freeze({
|
|
4231
|
+
source: "tracked",
|
|
4232
|
+
path: record.path,
|
|
4233
|
+
trackedNonFile: existing.trackedNonFile || record.trackedNonFile
|
|
4234
|
+
}));
|
|
4235
|
+
continue;
|
|
4236
|
+
}
|
|
4237
|
+
facts.set(record.path, record);
|
|
4238
|
+
if (facts.size > maxEntries) return fail$1("LimitExceeded", root, `Git-visible source inventory exceeds maxEntries ${maxEntries}`);
|
|
4239
|
+
}
|
|
4240
|
+
const paths = Array.from(facts.keys()).sort(compareText$1);
|
|
4241
|
+
const trackedNonFilePaths = Array.from(facts.values()).flatMap((record) => record.source === "tracked" && record.trackedNonFile ? [record.path] : []).sort(compareText$1);
|
|
4242
|
+
return checkedResult(Object.freeze({
|
|
4243
|
+
paths: Object.freeze(paths),
|
|
4244
|
+
trackedNonFilePaths: Object.freeze(trackedNonFilePaths)
|
|
4245
|
+
}), root);
|
|
4246
|
+
}));
|
|
4247
|
+
}
|
|
4248
|
+
function parseGitRecord(record) {
|
|
4249
|
+
if (record.startsWith("? ")) {
|
|
4250
|
+
const path = normalizeUntrackedPath(record.slice(2));
|
|
4251
|
+
return Object.freeze({
|
|
4252
|
+
source: "untracked",
|
|
4253
|
+
path
|
|
4254
|
+
});
|
|
4255
|
+
}
|
|
4256
|
+
const match = TRACKED_RECORD_PATTERN.exec(record);
|
|
4257
|
+
const mode = match?.groups?.mode;
|
|
4258
|
+
const path = match?.groups?.path;
|
|
4259
|
+
if (mode === void 0 || path === void 0) return void 0;
|
|
4260
|
+
return Object.freeze({
|
|
4261
|
+
source: "tracked",
|
|
4262
|
+
path,
|
|
4263
|
+
trackedNonFile: mode === "120000" || mode === "160000"
|
|
4264
|
+
});
|
|
4265
|
+
}
|
|
4266
|
+
function normalizeUntrackedPath(path) {
|
|
4267
|
+
return path.endsWith("/") && !path.endsWith("//") ? path.slice(0, -1) : path;
|
|
4268
|
+
}
|
|
4269
|
+
function checkedResult(result, root) {
|
|
4270
|
+
return sourceInventoryResultValidator.Check(result) ? Effect.succeed(result) : fail$1("InvalidOutput", root, "Git inventory could not be normalized to the source-inventory contract");
|
|
4271
|
+
}
|
|
4272
|
+
function decodeGitOutput$1(bytes, root) {
|
|
4273
|
+
return Effect.try({
|
|
4274
|
+
try: () => decoder$1.decode(bytes),
|
|
4275
|
+
catch: () => failure$1("InvalidOutput", root, "Git returned non-UTF-8 source-inventory output")
|
|
4276
|
+
});
|
|
4277
|
+
}
|
|
4278
|
+
function gitFailureDetail$1(exitCode, stderr) {
|
|
4279
|
+
let detail;
|
|
4280
|
+
try {
|
|
4281
|
+
detail = decoder$1.decode(stderr).trim();
|
|
4282
|
+
} catch {
|
|
4283
|
+
detail = "non-UTF-8 stderr";
|
|
4284
|
+
}
|
|
4285
|
+
return detail.length === 0 ? `Git ls-files exited ${exitCode}` : `Git ls-files exited ${exitCode}: ${detail}`;
|
|
4286
|
+
}
|
|
4287
|
+
function concatenate$1(chunks, length) {
|
|
4288
|
+
const bytes = new Uint8Array(length);
|
|
4289
|
+
let offset = 0;
|
|
4290
|
+
for (const chunk of chunks) {
|
|
4291
|
+
bytes.set(chunk, offset);
|
|
4292
|
+
offset += chunk.byteLength;
|
|
4293
|
+
}
|
|
4294
|
+
return bytes;
|
|
4295
|
+
}
|
|
4296
|
+
function mapPlatform$1(root, reason) {
|
|
4297
|
+
return (effect) => effect.pipe(Effect.mapError((cause) => platformFailure$1(root, cause, reason)));
|
|
4298
|
+
}
|
|
4299
|
+
function platformFailure$1(root, cause, reason) {
|
|
4300
|
+
return failure$1(reason, root, cause.message);
|
|
4301
|
+
}
|
|
4302
|
+
function fail$1(reason, root, detail) {
|
|
4303
|
+
return Effect.fail(failure$1(reason, root, detail));
|
|
4304
|
+
}
|
|
4305
|
+
function failure$1(reason, root, detail) {
|
|
4306
|
+
const normalized = detail.trim() || "Source-inventory observation failed";
|
|
4307
|
+
const boundedDetail = normalized.length <= 4096 ? normalized : `${normalized.slice(0, MAX_SOURCE_INVENTORY_FAILURE_DETAIL - 3)}...`;
|
|
4308
|
+
return Object.freeze({
|
|
4309
|
+
_tag: "SourceInventoryFailure",
|
|
4310
|
+
reason,
|
|
4311
|
+
...root === void 0 || root.length === 0 ? {} : { path: root },
|
|
4312
|
+
detail: boundedDetail
|
|
4313
|
+
});
|
|
4314
|
+
}
|
|
4315
|
+
function compareText$1(left, right) {
|
|
4316
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
4317
|
+
}
|
|
4318
|
+
//#endregion
|
|
4319
|
+
//#region ../../resources/source-inventory/dist/providers/git-effect-platform-node/runtime.js
|
|
4320
|
+
function defineGitSourceInventoryRuntimeProvider() {
|
|
4321
|
+
return defineRuntimeProvider({
|
|
4322
|
+
id: "source-inventory.git-effect-platform-node",
|
|
4323
|
+
title: "Git source inventory",
|
|
4324
|
+
provides: SourceInventoryRuntimeResource,
|
|
4325
|
+
requires: [],
|
|
4326
|
+
configSchema: RuntimeSchema.fromTypeBox(GitSourceInventoryProviderOptionsSchema),
|
|
4327
|
+
build: ({ config }) => providerFx.acquireRelease({
|
|
4328
|
+
acquire: Effect.scoped(Effect.gen(function* () {
|
|
4329
|
+
const context = yield* Layer.build(NodeServices.layer);
|
|
4330
|
+
const resource = makeGitSourceInventoryResource(config);
|
|
4331
|
+
return Object.freeze({ observe: (input) => Effect.provideContext(resource.observe(input), context) });
|
|
4332
|
+
})),
|
|
4333
|
+
release: () => Effect.void
|
|
4334
|
+
})
|
|
4335
|
+
});
|
|
4336
|
+
}
|
|
4337
|
+
//#endregion
|
|
4338
|
+
//#region ../../resources/versioned-content/dist/providers/git-effect-platform-node/index.js
|
|
4339
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
4340
|
+
const PRIVATE_GIT_PREFIX = "rawr-versioned-content-git-";
|
|
4341
|
+
const PROCESS_FORCE_KILL_AFTER = "5 seconds";
|
|
4342
|
+
const STDERR_LIMIT = 65536;
|
|
4343
|
+
const TEXT_OUTPUT_LIMIT = 1048576;
|
|
4344
|
+
const observeRemoteInputValidator = Schema.Compile(ObserveRemoteInputSchema);
|
|
4345
|
+
const materializeRemoteInputValidator = Schema.Compile(MaterializeRemoteInputSchema);
|
|
4346
|
+
const ancestryInputValidator = Schema.Compile(AncestryInputSchema);
|
|
4347
|
+
const versionedContentTreeEntryValidator = Schema.Compile(VersionedContentTreeEntrySchema);
|
|
4348
|
+
/**
|
|
4349
|
+
* Creates a Git-backed versioned-content resource over Effect platform
|
|
4350
|
+
* filesystem, path, and child-process services.
|
|
4351
|
+
*/
|
|
4352
|
+
function makeVersionedContentResource(options = {}) {
|
|
4353
|
+
const gitExecutable = options.gitExecutable ?? "git";
|
|
4354
|
+
const observeRemote = Effect.fn("versionedContent.observeRemote")(function* (input) {
|
|
4355
|
+
if (!observeRemoteInputValidator.Check(input)) return yield* fail("observe-remote", "InvalidInput", void 0, "Remote observation input does not match the bounded resource contract");
|
|
4356
|
+
return yield* withPrivateGitRepository(gitExecutable, input.repositoryIdentity, input.refName, true, "observe-remote", (root) => inspectFetchedTree(gitExecutable, root, input, "observe-remote"));
|
|
4357
|
+
});
|
|
4358
|
+
const materializeRemote = Effect.fn("versionedContent.materializeRemote")(function* (input) {
|
|
4359
|
+
if (!materializeRemoteInputValidator.Check(input)) return yield* fail("materialize-remote", "InvalidInput", void 0, "Remote materialization input does not match the bounded resource contract");
|
|
4360
|
+
return yield* withPrivateGitRepository(gitExecutable, input.repositoryIdentity, input.refName, false, "materialize-remote", (root) => Effect.gen(function* () {
|
|
4361
|
+
const observed = yield* inspectFetchedTree(gitExecutable, root, input, "materialize-remote");
|
|
4362
|
+
let totalBytes = 0;
|
|
4363
|
+
const entries = yield* Effect.forEach(observed.entries, (entry) => Effect.gen(function* () {
|
|
4364
|
+
const bytes = yield* gitBytes(gitExecutable, root, [
|
|
4365
|
+
"cat-file",
|
|
4366
|
+
"blob",
|
|
4367
|
+
entry.blob
|
|
4368
|
+
], "materialize-remote", input.maxBytes - totalBytes);
|
|
4369
|
+
totalBytes += bytes.byteLength;
|
|
4370
|
+
if (totalBytes > input.maxBytes) return yield* fail("materialize-remote", "LimitExceeded", entry.path, "Materialized tree exceeds the aggregate maxBytes bound");
|
|
4371
|
+
return Object.freeze({
|
|
4372
|
+
...entry,
|
|
4373
|
+
bytes
|
|
4374
|
+
});
|
|
4375
|
+
}), { concurrency: 1 });
|
|
4376
|
+
return Object.freeze({
|
|
4377
|
+
...observed,
|
|
4378
|
+
entries: Object.freeze(entries)
|
|
4379
|
+
});
|
|
4380
|
+
}));
|
|
4381
|
+
});
|
|
4382
|
+
const isAncestor = Effect.fn("versionedContent.isAncestor")(function* (input) {
|
|
4383
|
+
if (!ancestryInputValidator.Check(input)) return yield* fail("ancestry", "InvalidInput", void 0, "Ancestry input does not match the bounded resource contract");
|
|
4384
|
+
if (input.ancestorCommit.length !== input.descendantCommit.length) return yield* fail("ancestry", "InvalidInput", void 0, "Ancestry commit identifiers use different Git object formats");
|
|
4385
|
+
return yield* withPrivateGitRepository(gitExecutable, input.repositoryIdentity, input.refName, true, "ancestry", (root) => Effect.gen(function* () {
|
|
4386
|
+
const objectFormat = yield* gitObjectFormat(gitExecutable, root, "ancestry");
|
|
4387
|
+
if (!objectMatchesFormat(input.ancestorCommit, objectFormat) || !objectMatchesFormat(input.descendantCommit, objectFormat)) return yield* fail("ancestry", "InvalidInput", void 0, "Ancestry commit identifiers do not match the repository object format");
|
|
4388
|
+
const code = (yield* runGitCommand(gitExecutable, root, [
|
|
4389
|
+
"merge-base",
|
|
4390
|
+
"--is-ancestor",
|
|
4391
|
+
input.ancestorCommit,
|
|
4392
|
+
input.descendantCommit
|
|
4393
|
+
], "ancestry", STDERR_LIMIT)).exitCode;
|
|
4394
|
+
if (code === 0) return true;
|
|
4395
|
+
if (code === 1) return false;
|
|
4396
|
+
return yield* fail("ancestry", "CommandFailed", root, `Git ancestry command exited ${code}`);
|
|
4397
|
+
}));
|
|
4398
|
+
});
|
|
4399
|
+
return Object.freeze({
|
|
4400
|
+
observeRemote,
|
|
4401
|
+
materializeRemote,
|
|
4402
|
+
isAncestor
|
|
4403
|
+
});
|
|
4404
|
+
}
|
|
4405
|
+
/**
|
|
4406
|
+
* Realizes the Git provider as a ready Node resource while retaining typed
|
|
4407
|
+
* failures, scoped process cancellation, and guarded cleanup.
|
|
4408
|
+
*/
|
|
4409
|
+
function makeNodeVersionedContentResource(options = {}) {
|
|
4410
|
+
const resource = makeVersionedContentResource(options);
|
|
4411
|
+
return Object.freeze({
|
|
4412
|
+
observeRemote: (input) => provideNodeServices(resource.observeRemote(input)),
|
|
4413
|
+
materializeRemote: (input) => provideNodeServices(resource.materializeRemote(input)),
|
|
4414
|
+
isAncestor: (input) => provideNodeServices(resource.isAncestor(input))
|
|
4415
|
+
});
|
|
4416
|
+
}
|
|
4417
|
+
function provideNodeServices(operation) {
|
|
4418
|
+
return operation.pipe(Effect.provide(NodeServices.layer));
|
|
4419
|
+
}
|
|
4420
|
+
function inspectFetchedTree(gitExecutable, root, input, operation) {
|
|
4421
|
+
return Effect.gen(function* () {
|
|
4422
|
+
const commit = yield* gitText(gitExecutable, root, [
|
|
4423
|
+
"rev-parse",
|
|
4424
|
+
"--verify",
|
|
4425
|
+
"refs/rawr/content^{commit}"
|
|
4426
|
+
], operation);
|
|
4427
|
+
const tree = yield* gitText(gitExecutable, root, [
|
|
4428
|
+
"rev-parse",
|
|
4429
|
+
"--verify",
|
|
4430
|
+
input.sourcePath === "" ? "refs/rawr/content^{tree}" : `refs/rawr/content:${input.sourcePath}`
|
|
4431
|
+
], operation);
|
|
4432
|
+
const objectFormat = yield* gitObjectFormat(gitExecutable, root, operation);
|
|
4433
|
+
if (!objectMatchesFormat(commit, objectFormat) || !objectMatchesFormat(tree, objectFormat)) return yield* fail(operation, "CommandFailed", root, "Git returned commit or tree identifiers inconsistent with its object format");
|
|
4434
|
+
const entries = yield* parseGitTree(yield* gitBytes(gitExecutable, root, [
|
|
4435
|
+
"ls-tree",
|
|
4436
|
+
"-r",
|
|
4437
|
+
"-z",
|
|
4438
|
+
"--full-tree",
|
|
4439
|
+
tree
|
|
4440
|
+
], operation, input.maxEntries * 4200), input.maxEntries, objectFormat, operation, root);
|
|
4441
|
+
return Object.freeze({
|
|
4442
|
+
repositoryIdentity: input.repositoryIdentity,
|
|
4443
|
+
refName: input.refName,
|
|
4444
|
+
sourcePath: input.sourcePath,
|
|
4445
|
+
commit,
|
|
4446
|
+
tree,
|
|
4447
|
+
objectFormat,
|
|
4448
|
+
entries
|
|
4449
|
+
});
|
|
4450
|
+
});
|
|
4451
|
+
}
|
|
4452
|
+
function withPrivateGitRepository(gitExecutable, repositoryIdentity, refName, metadataOnly, operation, use) {
|
|
4453
|
+
return Effect.gen(function* () {
|
|
4454
|
+
const fs = yield* FileSystem.FileSystem;
|
|
4455
|
+
const paths = yield* Path.Path;
|
|
4456
|
+
return yield* Effect.acquireUseRelease(fs.makeTempDirectory({ prefix: PRIVATE_GIT_PREFIX }).pipe(mapPlatform(operation, void 0), Effect.map((root) => ({
|
|
4457
|
+
root,
|
|
4458
|
+
parent: paths.dirname(root)
|
|
4459
|
+
}))), (allocation) => Effect.uninterruptibleMask((restore) => validatePrivateGitRoot(fs, paths, allocation, operation).pipe(Effect.andThen(restore(Effect.gen(function* () {
|
|
4460
|
+
yield* gitText(gitExecutable, allocation.root, [
|
|
4461
|
+
"init",
|
|
4462
|
+
"--bare",
|
|
4463
|
+
"."
|
|
4464
|
+
], operation);
|
|
4465
|
+
yield* gitText(gitExecutable, allocation.root, [
|
|
4466
|
+
"remote",
|
|
4467
|
+
"add",
|
|
4468
|
+
"content",
|
|
4469
|
+
repositoryIdentity
|
|
4470
|
+
], operation);
|
|
4471
|
+
yield* gitText(gitExecutable, allocation.root, [
|
|
4472
|
+
"fetch",
|
|
4473
|
+
"--quiet",
|
|
4474
|
+
"--no-tags",
|
|
4475
|
+
...metadataOnly ? ["--filter=blob:none"] : [],
|
|
4476
|
+
"content",
|
|
4477
|
+
`+${refName}:refs/rawr/content`
|
|
4478
|
+
], operation);
|
|
4479
|
+
return yield* use(allocation.root);
|
|
4480
|
+
}))))), (allocation) => removeOwnedPrivateGitRoot(fs, paths, allocation));
|
|
4481
|
+
});
|
|
4482
|
+
}
|
|
4483
|
+
function validatePrivateGitRoot(fs, paths, allocation, operation) {
|
|
4484
|
+
return Effect.gen(function* () {
|
|
4485
|
+
const canonicalParent = yield* fs.realPath(allocation.parent).pipe(mapPlatform(operation, allocation.parent));
|
|
4486
|
+
const canonicalRoot = yield* fs.realPath(allocation.root).pipe(mapPlatform(operation, allocation.root));
|
|
4487
|
+
const identity = yield* fs.stat(canonicalRoot).pipe(mapPlatform(operation, canonicalRoot));
|
|
4488
|
+
allocation.root = canonicalRoot;
|
|
4489
|
+
allocation.parent = canonicalParent;
|
|
4490
|
+
allocation.identity = Object.freeze({
|
|
4491
|
+
dev: identity.dev,
|
|
4492
|
+
ino: identity.ino
|
|
4493
|
+
});
|
|
4494
|
+
if (!paths.isAbsolute(canonicalRoot) || paths.normalize(canonicalRoot) !== canonicalRoot || paths.dirname(canonicalRoot) !== canonicalParent || !paths.basename(canonicalRoot).startsWith(PRIVATE_GIT_PREFIX) || identity.type !== "Directory") return yield* fail(operation, "Aliased", allocation.root, "Private Git directory was not created at its exact owned path");
|
|
4495
|
+
});
|
|
4496
|
+
}
|
|
4497
|
+
function removeOwnedPrivateGitRoot(fs, paths, owned) {
|
|
4498
|
+
return Effect.gen(function* () {
|
|
4499
|
+
const canonicalParent = yield* fs.realPath(owned.parent).pipe(mapPlatform("cleanup", owned.parent, "CleanupFailed"));
|
|
4500
|
+
const canonicalRoot = yield* fs.realPath(owned.root).pipe(mapPlatform("cleanup", owned.root, "CleanupFailed"));
|
|
4501
|
+
const current = yield* fs.stat(owned.root).pipe(mapPlatform("cleanup", owned.root, "CleanupFailed"));
|
|
4502
|
+
if (canonicalParent !== owned.parent || canonicalRoot !== owned.root || !paths.isAbsolute(owned.root) || paths.normalize(owned.root) !== owned.root || paths.dirname(owned.root) !== owned.parent || !paths.basename(owned.root).startsWith(PRIVATE_GIT_PREFIX) || current.type !== "Directory" || owned.identity !== void 0 && current.dev !== owned.identity.dev || owned.identity !== void 0 && !Equal.equals(current.ino, owned.identity.ino)) return yield* fail("cleanup", "CleanupFailed", owned.root, "Refusing cleanup of an unowned or substituted private Git directory");
|
|
4503
|
+
yield* fs.remove(owned.root, {
|
|
4504
|
+
recursive: true,
|
|
4505
|
+
force: false
|
|
4506
|
+
}).pipe(mapPlatform("cleanup", owned.root, "CleanupFailed"));
|
|
4507
|
+
});
|
|
4508
|
+
}
|
|
4509
|
+
function parseGitTree(bytes, maxEntries, objectFormat, operation, root) {
|
|
4510
|
+
return decodeGitOutput(bytes, operation, root).pipe(Effect.flatMap((text) => {
|
|
4511
|
+
const entries = [];
|
|
4512
|
+
for (const raw of text.split("\0")) {
|
|
4513
|
+
if (raw.length === 0) continue;
|
|
4514
|
+
const match = /^(100644|100755) blob ([0-9a-f]{40}|[0-9a-f]{64})\t([^\0]+)$/u.exec(raw);
|
|
4515
|
+
if (match === null || match[1] === void 0 || match[2] === void 0 || match[3] === void 0) return fail(operation, "UnsupportedEntry", root, "Git tree contains a non-regular, malformed, or non-canonical entry");
|
|
4516
|
+
if (!objectMatchesFormat(match[2], objectFormat)) return fail(operation, "UnsupportedEntry", root, "Git tree entry identifier does not match the repository object format");
|
|
4517
|
+
const entry = Object.freeze({
|
|
4518
|
+
mode: contentFileMode(match[1]),
|
|
4519
|
+
blob: match[2],
|
|
4520
|
+
path: match[3]
|
|
4521
|
+
});
|
|
4522
|
+
if (!versionedContentTreeEntryValidator.Check(entry)) return fail(operation, "UnsupportedEntry", root, "Git tree entry falls outside the resource contract");
|
|
4523
|
+
entries.push(entry);
|
|
4524
|
+
if (entries.length > maxEntries) return fail(operation, "LimitExceeded", root, "Git tree exceeds maxEntries");
|
|
4525
|
+
}
|
|
4526
|
+
entries.sort((left, right) => compareText(left.path, right.path));
|
|
4527
|
+
for (let index = 1; index < entries.length; index += 1) if (entries[index - 1]?.path === entries[index]?.path) return fail(operation, "UnsupportedEntry", root, "Git tree contains duplicate regular-file paths");
|
|
4528
|
+
return Effect.succeed(Object.freeze(entries));
|
|
4529
|
+
}));
|
|
4530
|
+
}
|
|
4531
|
+
function gitObjectFormat(executable, root, operation) {
|
|
4532
|
+
return gitText(executable, root, ["rev-parse", "--show-object-format"], operation).pipe(Effect.flatMap((format) => format === "sha1" || format === "sha256" ? Effect.succeed(format) : fail(operation, "CommandFailed", root, `Git reported unsupported object format ${format || "<empty>"}`)));
|
|
4533
|
+
}
|
|
4534
|
+
function gitText(executable, root, args, operation) {
|
|
4535
|
+
return runGitCommand(executable, root, args, operation, TEXT_OUTPUT_LIMIT).pipe(Effect.flatMap((result) => result.exitCode === 0 ? decodeGitOutput(result.stdout, operation, root) : fail(operation, "CommandFailed", root, gitFailureDetail(args, result.exitCode, result.stderr))), Effect.map((output) => output.trim()));
|
|
4536
|
+
}
|
|
4537
|
+
function gitBytes(executable, root, args, operation, maxBytes) {
|
|
4538
|
+
return runGitCommand(executable, root, args, operation, maxBytes).pipe(Effect.flatMap((result) => result.exitCode === 0 ? Effect.succeed(result.stdout) : fail(operation, "CommandFailed", root, gitFailureDetail(args, result.exitCode, result.stderr))));
|
|
4539
|
+
}
|
|
4540
|
+
function runGitCommand(executable, root, args, operation, maxStdoutBytes) {
|
|
4541
|
+
const command = ChildProcess.make(executable, args, {
|
|
4542
|
+
cwd: root,
|
|
4543
|
+
extendEnv: true,
|
|
4544
|
+
stdin: "ignore",
|
|
4545
|
+
forceKillAfter: PROCESS_FORCE_KILL_AFTER
|
|
4546
|
+
});
|
|
4547
|
+
return Effect.scoped(Effect.gen(function* () {
|
|
4548
|
+
const process = yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn(command).pipe(mapPlatform(operation, root, "CommandFailed"));
|
|
4549
|
+
const [stdout, stderr, exitCode] = yield* Effect.all([
|
|
4550
|
+
collectBoundedOutput(process.stdout, maxStdoutBytes, operation, root, "stdout"),
|
|
4551
|
+
collectBoundedOutput(process.stderr, STDERR_LIMIT, operation, root, "stderr"),
|
|
4552
|
+
process.exitCode.pipe(mapPlatform(operation, root, "CommandFailed"))
|
|
4553
|
+
], { concurrency: "unbounded" });
|
|
4554
|
+
return Object.freeze({
|
|
4555
|
+
stdout,
|
|
4556
|
+
stderr,
|
|
4557
|
+
exitCode: Number(exitCode)
|
|
4558
|
+
});
|
|
4559
|
+
}));
|
|
4560
|
+
}
|
|
4561
|
+
function collectBoundedOutput(stream, maxBytes, operation, root, output) {
|
|
4562
|
+
const initial = Object.freeze({
|
|
4563
|
+
chunks: Object.freeze([]),
|
|
4564
|
+
bytes: 0
|
|
4565
|
+
});
|
|
4566
|
+
return Stream.runFoldEffect(stream.pipe(Stream.mapError((cause) => platformFailure(operation, root, cause, "CommandFailed"))), () => initial, (state, chunk) => {
|
|
4567
|
+
const bytes = state.bytes + chunk.byteLength;
|
|
4568
|
+
return bytes > maxBytes ? fail(operation, "LimitExceeded", root, `Git ${output} exceeds the ${maxBytes}-byte operation bound`) : Effect.succeed(Object.freeze({
|
|
4569
|
+
chunks: Object.freeze([...state.chunks, chunk]),
|
|
4570
|
+
bytes
|
|
4571
|
+
}));
|
|
4572
|
+
}).pipe(Effect.map((state) => concatenate(state.chunks, state.bytes)));
|
|
4573
|
+
}
|
|
4574
|
+
function decodeGitOutput(bytes, operation, root) {
|
|
4575
|
+
return Effect.try({
|
|
4576
|
+
try: () => decoder.decode(bytes),
|
|
4577
|
+
catch: () => failure(operation, "CommandFailed", root, "Git returned non-UTF-8 output for a textual operation")
|
|
4578
|
+
});
|
|
4579
|
+
}
|
|
4580
|
+
function gitFailureDetail(args, exitCode, stderr) {
|
|
4581
|
+
let detail;
|
|
4582
|
+
try {
|
|
4583
|
+
detail = decoder.decode(stderr).trim();
|
|
4584
|
+
} catch {
|
|
4585
|
+
detail = "non-UTF-8 stderr";
|
|
4586
|
+
}
|
|
4587
|
+
const command = args[0] ?? "command";
|
|
4588
|
+
return detail.length === 0 ? `Git ${command} exited ${exitCode}` : `Git ${command} exited ${exitCode}: ${detail}`;
|
|
4589
|
+
}
|
|
4590
|
+
function objectMatchesFormat(object, objectFormat) {
|
|
4591
|
+
return object.length === (objectFormat === "sha1" ? 40 : 64);
|
|
4592
|
+
}
|
|
4593
|
+
function contentFileMode(input) {
|
|
4594
|
+
return input === "100755" ? "100755" : "100644";
|
|
4595
|
+
}
|
|
4596
|
+
function concatenate(chunks, length) {
|
|
4597
|
+
const bytes = new Uint8Array(length);
|
|
4598
|
+
let offset = 0;
|
|
4599
|
+
for (const chunk of chunks) {
|
|
4600
|
+
bytes.set(chunk, offset);
|
|
4601
|
+
offset += chunk.byteLength;
|
|
4602
|
+
}
|
|
4603
|
+
return bytes;
|
|
4604
|
+
}
|
|
4605
|
+
function mapPlatform(operation, candidate, fallback = "FilesystemFailed") {
|
|
4606
|
+
return (effect) => effect.pipe(Effect.mapError((cause) => platformFailure(operation, candidate, cause, fallback)));
|
|
4607
|
+
}
|
|
4608
|
+
function platformFailure(operation, candidate, cause, fallback) {
|
|
4609
|
+
return failure(operation, fallback === "FilesystemFailed" && cause.reason._tag === "NotFound" ? "Missing" : fallback, candidate, cause.message);
|
|
4610
|
+
}
|
|
4611
|
+
function fail(operation, reason, candidate, detail) {
|
|
4612
|
+
return Effect.fail(failure(operation, reason, candidate, detail));
|
|
4613
|
+
}
|
|
4614
|
+
function failure(operation, reason, candidate, detail) {
|
|
4615
|
+
const normalized = detail.trim() || "Versioned-content operation failed";
|
|
4616
|
+
const boundedDetail = normalized.length <= 4096 ? normalized : `${normalized.slice(0, MAX_VERSIONED_CONTENT_FAILURE_DETAIL - 3)}...`;
|
|
4617
|
+
return Object.freeze({
|
|
4618
|
+
_tag: "VersionedContentFailure",
|
|
4619
|
+
operation,
|
|
4620
|
+
reason,
|
|
4621
|
+
...candidate === void 0 || candidate.length === 0 ? {} : { path: candidate },
|
|
4622
|
+
detail: boundedDetail
|
|
4623
|
+
});
|
|
4624
|
+
}
|
|
4625
|
+
function compareText(left, right) {
|
|
4626
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
4627
|
+
}
|
|
4628
|
+
//#endregion
|
|
4629
|
+
//#region ../../resources/versioned-content/dist/providers/git-effect-platform-node/runtime.js
|
|
4630
|
+
/** Acquire a fresh capability factory without opening any caller-selected workspace or home. */
|
|
4631
|
+
function defineNodeVersionedContentRuntimeProvider() {
|
|
4632
|
+
return defineRuntimeProvider({
|
|
4633
|
+
id: "versioned-content.git-effect-platform-node",
|
|
4634
|
+
title: "Versioned content (git-effect-platform-node)",
|
|
4635
|
+
provides: VersionedContentRuntimeResource,
|
|
4636
|
+
requires: [],
|
|
4637
|
+
build: () => providerFx.acquireRelease({
|
|
4638
|
+
acquire: Effect.sync(() => makeNodeVersionedContentResource()),
|
|
4639
|
+
release: () => Effect.void
|
|
4640
|
+
})
|
|
4641
|
+
});
|
|
4642
|
+
}
|
|
4643
|
+
//#endregion
|
|
4644
|
+
//#region runtime/profiles/local.ts
|
|
4645
|
+
const localProfile = defineRuntimeProfile({
|
|
4646
|
+
id: "local",
|
|
4647
|
+
providers: [
|
|
4648
|
+
providerSelection({
|
|
4649
|
+
resource: TelemetryRuntimeResource,
|
|
4650
|
+
provider: defineOpenTelemetryNodeRuntimeProvider({ releaseDeadline: () => ({ deadlineMonotonicMilliseconds: performance.now() + 5e3 }) }),
|
|
4651
|
+
config: {
|
|
4652
|
+
kind: "runtime.config",
|
|
4653
|
+
key: "habitat.telemetry"
|
|
4654
|
+
}
|
|
4655
|
+
}),
|
|
4656
|
+
providerSelection({
|
|
4657
|
+
resource: ContentWorkspaceRuntimeResource,
|
|
4658
|
+
provider: defineNodeContentWorkspaceRuntimeProvider()
|
|
4659
|
+
}),
|
|
4660
|
+
providerSelection({
|
|
4661
|
+
resource: AgentPluginPackageOutputRuntimeResource,
|
|
4662
|
+
provider: defineNodeAgentPluginPackageOutputRuntimeProvider()
|
|
4663
|
+
}),
|
|
4664
|
+
providerSelection({
|
|
4665
|
+
resource: VersionedContentRuntimeResource,
|
|
4666
|
+
provider: defineNodeVersionedContentRuntimeProvider()
|
|
4667
|
+
}),
|
|
4668
|
+
providerSelection({
|
|
4669
|
+
resource: CodexNativeAgentProviderRuntimeResource,
|
|
4670
|
+
provider: defineNodeCodexNativeAgentProviderRuntimeProvider()
|
|
4671
|
+
}),
|
|
4672
|
+
providerSelection({
|
|
4673
|
+
resource: ClaudeNativeAgentProviderRuntimeResource,
|
|
4674
|
+
provider: defineNodeClaudeNativeAgentProviderRuntimeProvider()
|
|
4675
|
+
}),
|
|
4676
|
+
providerSelection({
|
|
4677
|
+
resource: FilesystemRuntimeResource,
|
|
4678
|
+
provider: defineNodeFilesystemRuntimeProvider()
|
|
4679
|
+
}),
|
|
4680
|
+
providerSelection({
|
|
4681
|
+
resource: ChildProcessRuntimeResource,
|
|
4682
|
+
provider: defineNodeChildProcessRuntimeProvider()
|
|
4683
|
+
}),
|
|
4684
|
+
providerSelection({
|
|
4685
|
+
resource: SourceInventoryRuntimeResource,
|
|
4686
|
+
provider: defineGitSourceInventoryRuntimeProvider(),
|
|
4687
|
+
config: {
|
|
4688
|
+
kind: "runtime.config",
|
|
4689
|
+
key: "habitat.source-inventory"
|
|
4690
|
+
}
|
|
4691
|
+
}),
|
|
4692
|
+
providerSelection({
|
|
4693
|
+
resource: RuleEvaluationRuntimeResource,
|
|
4694
|
+
provider: defineGritRuleEvaluationRuntimeProvider(),
|
|
4695
|
+
config: {
|
|
4696
|
+
kind: "runtime.config",
|
|
4697
|
+
key: "habitat.rule-evaluation"
|
|
4698
|
+
}
|
|
4699
|
+
})
|
|
4700
|
+
],
|
|
4701
|
+
configSources: [{ kind: "memory" }],
|
|
4702
|
+
harnesses: ["habitat.oclif"]
|
|
4703
|
+
});
|
|
4704
|
+
//#endregion
|
|
4705
|
+
//#region cli.ts
|
|
4706
|
+
const entrypoint = defineEntrypoint({
|
|
4707
|
+
id: "habitat.cli",
|
|
4708
|
+
app: habitatApp,
|
|
4709
|
+
profile: localProfile,
|
|
4710
|
+
process: processes.cli,
|
|
4711
|
+
identity: {
|
|
4712
|
+
app: habitatApp.id,
|
|
4713
|
+
process: processes.cli.id,
|
|
4714
|
+
entrypoint: "habitat.cli",
|
|
4715
|
+
deployment: "local",
|
|
4716
|
+
source: "habitat.cli"
|
|
4717
|
+
}
|
|
4718
|
+
});
|
|
4719
|
+
function runHabitatProcess(input) {
|
|
4720
|
+
const host = createOclifHost({
|
|
4721
|
+
harnessId: "habitat.oclif",
|
|
4722
|
+
root: input.appRoot,
|
|
4723
|
+
sourceBundle: input.sourceBundle,
|
|
4724
|
+
args: input.args,
|
|
4725
|
+
...input.development ? { discoveryModule: "./src/oclif.ts" } : {}
|
|
4726
|
+
});
|
|
4727
|
+
const startup = () => startApp(entrypoint, {
|
|
4728
|
+
sources: input.sources(),
|
|
4729
|
+
integrations: [host.integration],
|
|
4730
|
+
finalization: {
|
|
4731
|
+
policy: "waitForNativeStop",
|
|
4732
|
+
deadlineMs: 1e4
|
|
4733
|
+
}
|
|
4734
|
+
});
|
|
4735
|
+
return input.terminal ? host.execute(startup) : host.run(startup);
|
|
4736
|
+
}
|
|
4737
|
+
//#endregion
|
|
4738
|
+
export { runHabitatProcess as n, entrypoint as t };
|