@sifr-dev/loom 0.0.0-stage → 1.0.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/CHANGELOG.md +112 -0
- package/LICENSE +21 -0
- package/README.ar.md +253 -0
- package/README.md +262 -2
- package/dist/browser.js +2717 -0
- package/dist/cli.js +15 -0
- package/dist/index.js +4854 -0
- package/dist/types/args.d.ts +14 -0
- package/dist/types/base64.d.ts +9 -0
- package/dist/types/browser.d.ts +57 -0
- package/dist/types/canonical.d.ts +20 -0
- package/dist/types/cli.d.ts +12 -0
- package/dist/types/commands/context.d.ts +30 -0
- package/dist/types/commands/diff.d.ts +18 -0
- package/dist/types/commands/doctor.d.ts +19 -0
- package/dist/types/commands/export.d.ts +30 -0
- package/dist/types/commands/migrate.d.ts +9 -0
- package/dist/types/commands/serve.d.ts +18 -0
- package/dist/types/commands/snapshot.d.ts +15 -0
- package/dist/types/commands/sync.d.ts +17 -0
- package/dist/types/commands/verify.d.ts +9 -0
- package/dist/types/commands/watch.d.ts +25 -0
- package/dist/types/compute.d.ts +49 -0
- package/dist/types/concurrency.d.ts +31 -0
- package/dist/types/config.d.ts +132 -0
- package/dist/types/diff.d.ts +57 -0
- package/dist/types/digest.d.ts +11 -0
- package/dist/types/entities.d.ts +27 -0
- package/dist/types/errors.d.ts +37 -0
- package/dist/types/fs.d.ts +23 -0
- package/dist/types/github/cache.d.ts +44 -0
- package/dist/types/github/client.d.ts +91 -0
- package/dist/types/github/collect.d.ts +36 -0
- package/dist/types/github/discovery.d.ts +39 -0
- package/dist/types/github/fixture.d.ts +26 -0
- package/dist/types/github/guard.d.ts +14 -0
- package/dist/types/github/memory-cache.d.ts +34 -0
- package/dist/types/index.d.ts +44 -0
- package/dist/types/log.d.ts +16 -0
- package/dist/types/metrics.d.ts +21 -0
- package/dist/types/migrate.d.ts +24 -0
- package/dist/types/pipeline.d.ts +73 -0
- package/dist/types/queue.d.ts +33 -0
- package/dist/types/sdk.d.ts +165 -0
- package/dist/types/secrets.d.ts +28 -0
- package/dist/types/serve-handler.d.ts +46 -0
- package/dist/types/sha256.d.ts +13 -0
- package/dist/types/site-module.d.ts +23 -0
- package/dist/types/site.d.ts +135 -0
- package/dist/types/snapshot.d.ts +16 -0
- package/dist/types/store.d.ts +119 -0
- package/dist/types/triggers.d.ts +67 -0
- package/dist/types/types.d.ts +176 -0
- package/dist/types/version.d.ts +7 -0
- package/dist/types/webhook/delivery.d.ts +45 -0
- package/dist/types/webhook/receiver.d.ts +46 -0
- package/dist/types/webhook/signature.d.ts +43 -0
- package/docs/CONFIGURATION.md +213 -0
- package/docs/DEPLOYMENT.md +316 -0
- package/docs/SDK.md +351 -0
- package/docs/SITE_CONTRACT.md +318 -0
- package/docs/VERIFICATION.md +130 -0
- package/package.json +83 -4
- package/schema/site@1.json +188 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4854 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __esm = (fn, res, err) => () => {
|
|
3
|
+
if (fn)
|
|
4
|
+
try {
|
|
5
|
+
res = fn(fn = 0);
|
|
6
|
+
} catch (e) {
|
|
7
|
+
err = [e];
|
|
8
|
+
}
|
|
9
|
+
if (err)
|
|
10
|
+
throw err[0];
|
|
11
|
+
return res;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// src/github/memory-cache.ts
|
|
15
|
+
class MemoryCache {
|
|
16
|
+
#entries = new Map;
|
|
17
|
+
get(key) {
|
|
18
|
+
return this.#entries.get(key);
|
|
19
|
+
}
|
|
20
|
+
set(key, entry) {
|
|
21
|
+
this.#entries.set(key, entry);
|
|
22
|
+
}
|
|
23
|
+
async save() {}
|
|
24
|
+
size() {
|
|
25
|
+
return this.#entries.size;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/canonical.ts
|
|
30
|
+
function encode(value, path) {
|
|
31
|
+
if (value === null)
|
|
32
|
+
return "null";
|
|
33
|
+
switch (typeof value) {
|
|
34
|
+
case "boolean":
|
|
35
|
+
return value ? "true" : "false";
|
|
36
|
+
case "number": {
|
|
37
|
+
if (!Number.isFinite(value)) {
|
|
38
|
+
throw new CanonicalJsonError(`non-finite number at ${path}`);
|
|
39
|
+
}
|
|
40
|
+
return JSON.stringify(value === 0 ? 0 : value);
|
|
41
|
+
}
|
|
42
|
+
case "string":
|
|
43
|
+
return JSON.stringify(value);
|
|
44
|
+
case "object":
|
|
45
|
+
break;
|
|
46
|
+
default:
|
|
47
|
+
throw new CanonicalJsonError(`unsupported ${typeof value} at ${path}`);
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(value)) {
|
|
50
|
+
const parts = [];
|
|
51
|
+
for (let index = 0;index < value.length; index += 1) {
|
|
52
|
+
const item = value[index];
|
|
53
|
+
if (item === undefined) {
|
|
54
|
+
throw new CanonicalJsonError(`undefined array element at ${path}[${index}]`);
|
|
55
|
+
}
|
|
56
|
+
parts.push(encode(item, `${path}[${index}]`));
|
|
57
|
+
}
|
|
58
|
+
return `[${parts.join(",")}]`;
|
|
59
|
+
}
|
|
60
|
+
const record = value;
|
|
61
|
+
const proto = Object.getPrototypeOf(record);
|
|
62
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
63
|
+
throw new CanonicalJsonError(`non-plain object at ${path}`);
|
|
64
|
+
}
|
|
65
|
+
const keys = Object.keys(record).sort();
|
|
66
|
+
const parts = [];
|
|
67
|
+
for (const key of keys) {
|
|
68
|
+
const item = record[key];
|
|
69
|
+
if (item === undefined)
|
|
70
|
+
continue;
|
|
71
|
+
parts.push(`${JSON.stringify(key)}:${encode(item, `${path}.${key}`)}`);
|
|
72
|
+
}
|
|
73
|
+
return `{${parts.join(",")}}`;
|
|
74
|
+
}
|
|
75
|
+
function canonicalize(value) {
|
|
76
|
+
return encode(value, "$");
|
|
77
|
+
}
|
|
78
|
+
var CanonicalJsonError;
|
|
79
|
+
var init_canonical = __esm(() => {
|
|
80
|
+
CanonicalJsonError = class CanonicalJsonError extends Error {
|
|
81
|
+
name = "CanonicalJsonError";
|
|
82
|
+
};
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// src/fs.ts
|
|
86
|
+
import { open, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "fs/promises";
|
|
87
|
+
import { dirname, join } from "path";
|
|
88
|
+
async function writeFileAtomic(path, data) {
|
|
89
|
+
const dir = dirname(path);
|
|
90
|
+
await mkdir(dir, { recursive: true });
|
|
91
|
+
tempCounter += 1;
|
|
92
|
+
const temp = `${path}.${process.pid}.${tempCounter}.tmp`;
|
|
93
|
+
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
94
|
+
const handle = await open(temp, "w", 420);
|
|
95
|
+
try {
|
|
96
|
+
await handle.writeFile(bytes);
|
|
97
|
+
await handle.sync();
|
|
98
|
+
} finally {
|
|
99
|
+
await handle.close();
|
|
100
|
+
}
|
|
101
|
+
await rename(temp, path);
|
|
102
|
+
try {
|
|
103
|
+
const dirHandle = await open(dir, "r");
|
|
104
|
+
try {
|
|
105
|
+
await dirHandle.sync();
|
|
106
|
+
} finally {
|
|
107
|
+
await dirHandle.close();
|
|
108
|
+
}
|
|
109
|
+
} catch {}
|
|
110
|
+
}
|
|
111
|
+
async function readTextIfExists(path) {
|
|
112
|
+
try {
|
|
113
|
+
return await readFile(path, "utf8");
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (error.code === "ENOENT")
|
|
116
|
+
return null;
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function readJsonIfExists(path) {
|
|
121
|
+
const text = await readTextIfExists(path);
|
|
122
|
+
if (text === null)
|
|
123
|
+
return null;
|
|
124
|
+
return JSON.parse(text);
|
|
125
|
+
}
|
|
126
|
+
async function exists(path) {
|
|
127
|
+
try {
|
|
128
|
+
await stat(path);
|
|
129
|
+
return true;
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (error.code === "ENOENT")
|
|
132
|
+
return false;
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function ensureDir(path) {
|
|
137
|
+
await mkdir(path, { recursive: true });
|
|
138
|
+
}
|
|
139
|
+
async function quarantineFile(path, reason = "corrupt") {
|
|
140
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
141
|
+
const target = `${path}.${reason}-${stamp}`;
|
|
142
|
+
try {
|
|
143
|
+
await rename(path, target);
|
|
144
|
+
return target;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error.code === "ENOENT")
|
|
147
|
+
return null;
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async function removeStaleTempFiles(dir, maxAgeMs = 60 * 60 * 1000) {
|
|
152
|
+
let names;
|
|
153
|
+
try {
|
|
154
|
+
names = await readdir(dir);
|
|
155
|
+
} catch {
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
|
158
|
+
let removed = 0;
|
|
159
|
+
const now = Date.now();
|
|
160
|
+
for (const name of names) {
|
|
161
|
+
if (!name.endsWith(".tmp"))
|
|
162
|
+
continue;
|
|
163
|
+
const path = join(dir, name);
|
|
164
|
+
try {
|
|
165
|
+
const info = await stat(path);
|
|
166
|
+
if (maxAgeMs <= 0 || now - info.mtimeMs > maxAgeMs) {
|
|
167
|
+
await unlink(path);
|
|
168
|
+
removed += 1;
|
|
169
|
+
}
|
|
170
|
+
} catch {}
|
|
171
|
+
}
|
|
172
|
+
return removed;
|
|
173
|
+
}
|
|
174
|
+
var tempCounter = 0;
|
|
175
|
+
var init_fs = () => {};
|
|
176
|
+
|
|
177
|
+
// src/github/cache.ts
|
|
178
|
+
function isEntry(value) {
|
|
179
|
+
if (value === null || typeof value !== "object")
|
|
180
|
+
return false;
|
|
181
|
+
const entry = value;
|
|
182
|
+
return typeof entry["etag"] === "string" && entry["etag"].length > 0 && "body" in entry;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
class FileCache {
|
|
186
|
+
#path;
|
|
187
|
+
#entries;
|
|
188
|
+
#dirty = false;
|
|
189
|
+
constructor(path, entries) {
|
|
190
|
+
this.#path = path;
|
|
191
|
+
this.#entries = entries;
|
|
192
|
+
}
|
|
193
|
+
static async open(path) {
|
|
194
|
+
return (await FileCache.openWithRecovery(path)).cache;
|
|
195
|
+
}
|
|
196
|
+
static async openWithRecovery(path) {
|
|
197
|
+
const text = await readTextIfExists(path);
|
|
198
|
+
if (text === null) {
|
|
199
|
+
return { cache: new FileCache(path, new Map), recovered: false, quarantined: null };
|
|
200
|
+
}
|
|
201
|
+
let file = null;
|
|
202
|
+
try {
|
|
203
|
+
file = JSON.parse(text);
|
|
204
|
+
} catch {
|
|
205
|
+
file = null;
|
|
206
|
+
}
|
|
207
|
+
const knownSchema = file !== null && typeof file.schema === "string" && (file.schema === CACHE_SCHEMA || LEGACY_CACHE_SCHEMAS.includes(file.schema));
|
|
208
|
+
if (file === null || !knownSchema || file.entries === null || typeof file.entries !== "object") {
|
|
209
|
+
const quarantined = await quarantineFile(path, "corrupt-cache");
|
|
210
|
+
return { cache: new FileCache(path, new Map), recovered: true, quarantined };
|
|
211
|
+
}
|
|
212
|
+
const entries = new Map;
|
|
213
|
+
let dropped = 0;
|
|
214
|
+
for (const [key, entry] of Object.entries(file.entries)) {
|
|
215
|
+
if (isEntry(entry))
|
|
216
|
+
entries.set(key, entry);
|
|
217
|
+
else
|
|
218
|
+
dropped += 1;
|
|
219
|
+
}
|
|
220
|
+
const cache = new FileCache(path, entries);
|
|
221
|
+
if (file.schema !== CACHE_SCHEMA || dropped > 0) {
|
|
222
|
+
cache.#dirty = true;
|
|
223
|
+
await cache.save();
|
|
224
|
+
}
|
|
225
|
+
return { cache, recovered: file.schema !== CACHE_SCHEMA || dropped > 0, quarantined: null };
|
|
226
|
+
}
|
|
227
|
+
get(key) {
|
|
228
|
+
return this.#entries.get(key);
|
|
229
|
+
}
|
|
230
|
+
set(key, entry) {
|
|
231
|
+
const previous = this.#entries.get(key);
|
|
232
|
+
if (previous && previous.etag === entry.etag && canonicalize(previous.body) === canonicalize(entry.body)) {
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
this.#entries.set(key, entry);
|
|
236
|
+
this.#dirty = true;
|
|
237
|
+
}
|
|
238
|
+
delete(key) {
|
|
239
|
+
const removed = this.#entries.delete(key);
|
|
240
|
+
if (removed)
|
|
241
|
+
this.#dirty = true;
|
|
242
|
+
return removed;
|
|
243
|
+
}
|
|
244
|
+
async save() {
|
|
245
|
+
if (!this.#dirty)
|
|
246
|
+
return;
|
|
247
|
+
const entries = {};
|
|
248
|
+
for (const key of [...this.#entries.keys()].sort()) {
|
|
249
|
+
const entry = this.#entries.get(key);
|
|
250
|
+
if (entry)
|
|
251
|
+
entries[key] = entry;
|
|
252
|
+
}
|
|
253
|
+
const payload = { schema: CACHE_SCHEMA, entries };
|
|
254
|
+
await writeFileAtomic(this.#path, `${JSON.stringify(payload, null, 2)}
|
|
255
|
+
`);
|
|
256
|
+
this.#dirty = false;
|
|
257
|
+
}
|
|
258
|
+
size() {
|
|
259
|
+
return this.#entries.size;
|
|
260
|
+
}
|
|
261
|
+
prune(maxAgeMs, nowMs = Date.now()) {
|
|
262
|
+
let removed = 0;
|
|
263
|
+
for (const [key, entry] of this.#entries) {
|
|
264
|
+
const fetched = Date.parse(entry.fetchedAt);
|
|
265
|
+
if (Number.isFinite(fetched) && nowMs - fetched > maxAgeMs) {
|
|
266
|
+
this.#entries.delete(key);
|
|
267
|
+
this.#dirty = true;
|
|
268
|
+
removed += 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return removed;
|
|
272
|
+
}
|
|
273
|
+
static async inspect(path) {
|
|
274
|
+
const text = await readTextIfExists(path);
|
|
275
|
+
if (text === null)
|
|
276
|
+
return { present: false, valid: false, entries: 0, schema: null };
|
|
277
|
+
try {
|
|
278
|
+
const file = JSON.parse(text);
|
|
279
|
+
const valid = typeof file.schema === "string" && (file.schema === CACHE_SCHEMA || LEGACY_CACHE_SCHEMAS.includes(file.schema)) && file.entries !== null && typeof file.entries === "object";
|
|
280
|
+
return {
|
|
281
|
+
present: true,
|
|
282
|
+
valid,
|
|
283
|
+
entries: valid ? Object.values(file.entries).filter(isEntry).length : 0,
|
|
284
|
+
schema: typeof file.schema === "string" ? file.schema : null
|
|
285
|
+
};
|
|
286
|
+
} catch {
|
|
287
|
+
return { present: true, valid: false, entries: 0, schema: null };
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
var CACHE_SCHEMA = "loom/http-cache@1", LEGACY_CACHE_SCHEMAS;
|
|
292
|
+
var init_cache = __esm(() => {
|
|
293
|
+
init_canonical();
|
|
294
|
+
init_fs();
|
|
295
|
+
LEGACY_CACHE_SCHEMAS = ["loom/http-cache@0"];
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
// src/webhook/delivery.ts
|
|
299
|
+
class DeliveryLog {
|
|
300
|
+
#path;
|
|
301
|
+
#deliveries;
|
|
302
|
+
#payloads;
|
|
303
|
+
#ids;
|
|
304
|
+
constructor(path, file) {
|
|
305
|
+
this.#path = path;
|
|
306
|
+
this.#deliveries = file.deliveries;
|
|
307
|
+
this.#payloads = file.payloads;
|
|
308
|
+
this.#ids = new Set(file.deliveries.map((record) => record.id));
|
|
309
|
+
}
|
|
310
|
+
static async open(path) {
|
|
311
|
+
return (await DeliveryLog.openWithRecovery(path)).log;
|
|
312
|
+
}
|
|
313
|
+
static async openWithRecovery(path) {
|
|
314
|
+
const text = await readTextIfExists(path);
|
|
315
|
+
if (text === null) {
|
|
316
|
+
return {
|
|
317
|
+
log: new DeliveryLog(path, { schema: WEBHOOK_STATE_SCHEMA, deliveries: [], payloads: [] }),
|
|
318
|
+
recovered: false,
|
|
319
|
+
quarantined: null
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
let file = null;
|
|
323
|
+
try {
|
|
324
|
+
file = JSON.parse(text);
|
|
325
|
+
} catch {
|
|
326
|
+
file = null;
|
|
327
|
+
}
|
|
328
|
+
const valid = file !== null && file.schema === WEBHOOK_STATE_SCHEMA && Array.isArray(file.deliveries) && Array.isArray(file.payloads);
|
|
329
|
+
if (file === null || !valid) {
|
|
330
|
+
const quarantined = await quarantineFile(path, "corrupt-webhook-state");
|
|
331
|
+
return {
|
|
332
|
+
log: new DeliveryLog(path, { schema: WEBHOOK_STATE_SCHEMA, deliveries: [], payloads: [] }),
|
|
333
|
+
recovered: true,
|
|
334
|
+
quarantined
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const byId = new Map;
|
|
338
|
+
for (const record of file.deliveries) {
|
|
339
|
+
if (record && typeof record.id === "string")
|
|
340
|
+
byId.set(record.id, record);
|
|
341
|
+
}
|
|
342
|
+
const deliveries = [...byId.values()];
|
|
343
|
+
const payloads = file.payloads.filter((record) => record && typeof record.hash === "string" && typeof record.at === "string");
|
|
344
|
+
const recovered = deliveries.length !== file.deliveries.length;
|
|
345
|
+
return {
|
|
346
|
+
log: new DeliveryLog(path, { schema: WEBHOOK_STATE_SCHEMA, deliveries, payloads }),
|
|
347
|
+
recovered,
|
|
348
|
+
quarantined: null
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
get size() {
|
|
352
|
+
return this.#deliveries.length;
|
|
353
|
+
}
|
|
354
|
+
has(id) {
|
|
355
|
+
return this.#ids.has(id);
|
|
356
|
+
}
|
|
357
|
+
hasPayload(hash, windowMs, nowMs = Date.now()) {
|
|
358
|
+
return this.#payloads.some((record) => record.hash === hash && nowMs - Date.parse(record.at) <= windowMs);
|
|
359
|
+
}
|
|
360
|
+
async record(record, payloadHash = null) {
|
|
361
|
+
if (this.#ids.has(record.id))
|
|
362
|
+
return false;
|
|
363
|
+
this.#deliveries.push(record);
|
|
364
|
+
this.#ids.add(record.id);
|
|
365
|
+
if (payloadHash)
|
|
366
|
+
this.#payloads.push({ hash: payloadHash, at: record.at });
|
|
367
|
+
this.#trim(Date.parse(record.at));
|
|
368
|
+
await this.save();
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
#trim(nowMs) {
|
|
372
|
+
if (this.#deliveries.length > MAX_DELIVERIES) {
|
|
373
|
+
this.#deliveries = this.#deliveries.slice(-MAX_DELIVERIES);
|
|
374
|
+
this.#ids = new Set(this.#deliveries.map((record) => record.id));
|
|
375
|
+
}
|
|
376
|
+
this.#payloads = this.#payloads.filter((record) => nowMs - Date.parse(record.at) <= DELIVERY_TTL_MS).slice(-MAX_PAYLOADS);
|
|
377
|
+
this.#deliveries = this.#deliveries.filter((record) => nowMs - Date.parse(record.at) <= DELIVERY_TTL_MS);
|
|
378
|
+
if (this.#deliveries.length !== this.#ids.size) {
|
|
379
|
+
this.#ids = new Set(this.#deliveries.map((record) => record.id));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
async save() {
|
|
383
|
+
const file = {
|
|
384
|
+
schema: WEBHOOK_STATE_SCHEMA,
|
|
385
|
+
deliveries: this.#deliveries,
|
|
386
|
+
payloads: this.#payloads
|
|
387
|
+
};
|
|
388
|
+
await writeFileAtomic(this.#path, `${JSON.stringify(file, null, 2)}
|
|
389
|
+
`);
|
|
390
|
+
}
|
|
391
|
+
toJSON() {
|
|
392
|
+
return {
|
|
393
|
+
schema: WEBHOOK_STATE_SCHEMA,
|
|
394
|
+
deliveries: [...this.#deliveries],
|
|
395
|
+
payloads: [...this.#payloads]
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
var WEBHOOK_STATE_SCHEMA = "loom/webhook-state@1", MAX_DELIVERIES = 1000, MAX_PAYLOADS = 1000, DELIVERY_TTL_MS;
|
|
400
|
+
var init_delivery = __esm(() => {
|
|
401
|
+
init_fs();
|
|
402
|
+
DELIVERY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// src/sdk.ts
|
|
406
|
+
import { resolve } from "path";
|
|
407
|
+
|
|
408
|
+
// src/secrets.ts
|
|
409
|
+
var SECRET_PATTERNS = [
|
|
410
|
+
{ name: "github-token", pattern: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g },
|
|
411
|
+
{ name: "github-pat", pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g },
|
|
412
|
+
{ name: "openai-key", pattern: /\bsk-[A-Za-z0-9]{20,}\b/g },
|
|
413
|
+
{ name: "slack-token", pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g },
|
|
414
|
+
{ name: "aws-access-key", pattern: /\bAKIA[0-9A-Z]{16}\b/g },
|
|
415
|
+
{ name: "private-key", pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/g },
|
|
416
|
+
{ name: "jwt", pattern: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g },
|
|
417
|
+
{ name: "vercel-hook", pattern: /https:\/\/api\.vercel\.com\/v1\/deploy-hooks\/[A-Za-z0-9]{8,}/g }
|
|
418
|
+
];
|
|
419
|
+
function findSecrets(text) {
|
|
420
|
+
const matches = [];
|
|
421
|
+
for (const { name, pattern } of SECRET_PATTERNS) {
|
|
422
|
+
pattern.lastIndex = 0;
|
|
423
|
+
let match;
|
|
424
|
+
while ((match = pattern.exec(text)) !== null) {
|
|
425
|
+
matches.push({ pattern: name, offset: match.index });
|
|
426
|
+
if (matches.length >= 20)
|
|
427
|
+
return matches;
|
|
428
|
+
if (match[0].length === 0)
|
|
429
|
+
pattern.lastIndex += 1;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return matches.sort((a, b) => a.offset - b.offset);
|
|
433
|
+
}
|
|
434
|
+
function redactUrl(raw) {
|
|
435
|
+
try {
|
|
436
|
+
const url = new URL(raw);
|
|
437
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
438
|
+
const shape = segments.map((segment) => segment.length > 12 ? "\u2026" : segment).join("/");
|
|
439
|
+
return `${url.origin}/${shape}${url.search ? "?\u2026" : ""}`;
|
|
440
|
+
} catch {
|
|
441
|
+
return "<invalid-url>";
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
function redactText(text) {
|
|
445
|
+
let output = text;
|
|
446
|
+
for (const { name, pattern } of SECRET_PATTERNS) {
|
|
447
|
+
pattern.lastIndex = 0;
|
|
448
|
+
output = output.replace(pattern, `<redacted:${name}>`);
|
|
449
|
+
}
|
|
450
|
+
output = output.replace(/(https?:\/\/)[^/@\s]+@/g, "$1<redacted>@");
|
|
451
|
+
return output;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/errors.ts
|
|
455
|
+
var EXIT = {
|
|
456
|
+
ok: 0,
|
|
457
|
+
failure: 1,
|
|
458
|
+
usage: 2,
|
|
459
|
+
verifyFailed: 3,
|
|
460
|
+
guardViolation: 4,
|
|
461
|
+
unauthorized: 5,
|
|
462
|
+
partial: 6,
|
|
463
|
+
unchanged: 7,
|
|
464
|
+
busy: 8
|
|
465
|
+
};
|
|
466
|
+
var EXIT_FOR_CODE = {
|
|
467
|
+
usage: EXIT.usage,
|
|
468
|
+
config_invalid: EXIT.usage,
|
|
469
|
+
github_error: EXIT.failure,
|
|
470
|
+
rate_limit_exhausted: EXIT.failure,
|
|
471
|
+
repo_not_public: EXIT.guardViolation,
|
|
472
|
+
repo_invalid: EXIT.guardViolation,
|
|
473
|
+
store_corrupt: EXIT.verifyFailed,
|
|
474
|
+
snapshot_missing: EXIT.failure,
|
|
475
|
+
verify_failed: EXIT.verifyFailed,
|
|
476
|
+
signature_invalid: EXIT.unauthorized,
|
|
477
|
+
payload_invalid: EXIT.usage,
|
|
478
|
+
trigger_failed: EXIT.failure,
|
|
479
|
+
secret_missing: EXIT.failure,
|
|
480
|
+
secret_detected: EXIT.failure,
|
|
481
|
+
network_error: EXIT.failure,
|
|
482
|
+
cancelled: EXIT.failure,
|
|
483
|
+
partial_failure: EXIT.partial,
|
|
484
|
+
queue_full: EXIT.busy,
|
|
485
|
+
lock_busy: EXIT.busy,
|
|
486
|
+
schema_unsupported: EXIT.usage
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
class LoomError extends Error {
|
|
490
|
+
name = "LoomError";
|
|
491
|
+
code;
|
|
492
|
+
detail;
|
|
493
|
+
constructor(code, message, detail = {}) {
|
|
494
|
+
super(message);
|
|
495
|
+
this.code = code;
|
|
496
|
+
this.detail = Object.freeze({ ...detail });
|
|
497
|
+
}
|
|
498
|
+
get exitCode() {
|
|
499
|
+
return EXIT_FOR_CODE[this.code] ?? EXIT.failure;
|
|
500
|
+
}
|
|
501
|
+
get hint() {
|
|
502
|
+
return hintFor(this.code);
|
|
503
|
+
}
|
|
504
|
+
toJSON() {
|
|
505
|
+
return {
|
|
506
|
+
ok: false,
|
|
507
|
+
code: this.code,
|
|
508
|
+
message: this.message,
|
|
509
|
+
detail: this.detail,
|
|
510
|
+
...this.hint ? { hint: this.hint } : {}
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
var HINTS = {
|
|
515
|
+
github_error: "Check the repository name and GitHub status; run `loom doctor` for configuration.",
|
|
516
|
+
rate_limit_exhausted: "Set GITHUB_TOKEN (or --token-env) to raise the limit, or retry after the reset time.",
|
|
517
|
+
repo_not_public: "Loom only reads public repositories; remove private/internal entries from `repos`.",
|
|
518
|
+
repo_invalid: "Repository entries must be `owner/name` with no path tricks.",
|
|
519
|
+
store_corrupt: "Run `loom verify`; restore the named object or run `loom doctor --fix` for cache-only corruption.",
|
|
520
|
+
snapshot_missing: "Run `loom sync` before `loom diff`/`loom export`, or pass --from none.",
|
|
521
|
+
verify_failed: "Do not deploy a failed store. Re-sync from the source or restore a known-good object.",
|
|
522
|
+
signature_invalid: "Check the webhook secret and that the raw request body was forwarded unchanged.",
|
|
523
|
+
payload_invalid: "Send the raw GitHub webhook body with its original headers.",
|
|
524
|
+
trigger_failed: "The snapshot is committed; the durable outbox will retry on the next sync.",
|
|
525
|
+
secret_missing: "Export the named environment variable; secrets are never read from config files.",
|
|
526
|
+
secret_detected: "A credential-shaped value reached the public payload. Rotate it and fix the source field.",
|
|
527
|
+
network_error: "Check connectivity and the GitHub status page; transient errors are retried.",
|
|
528
|
+
cancelled: "The operation was cancelled by a signal; it is safe to retry.",
|
|
529
|
+
partial_failure: "Some repositories could not be read and had no previous copy; fix access and re-run.",
|
|
530
|
+
queue_full: "The sync queue is saturated; retry after the Retry-After interval.",
|
|
531
|
+
lock_busy: "Another Loom process owns this store; retry after it exits.",
|
|
532
|
+
schema_unsupported: "Run `loom migrate` or upgrade Loom; this build will not silently reinterpret old data."
|
|
533
|
+
};
|
|
534
|
+
function hintFor(code) {
|
|
535
|
+
return HINTS[code] ?? null;
|
|
536
|
+
}
|
|
537
|
+
function isLoomError(value) {
|
|
538
|
+
return value instanceof LoomError;
|
|
539
|
+
}
|
|
540
|
+
function configError(message, detail = {}) {
|
|
541
|
+
return new LoomError("config_invalid", message, detail);
|
|
542
|
+
}
|
|
543
|
+
function guardError(message, detail = {}) {
|
|
544
|
+
return new LoomError("repo_not_public", message, detail);
|
|
545
|
+
}
|
|
546
|
+
function describeError(error) {
|
|
547
|
+
if (isLoomError(error)) {
|
|
548
|
+
return {
|
|
549
|
+
code: error.code,
|
|
550
|
+
message: redactText(error.message),
|
|
551
|
+
detail: { ...error.detail },
|
|
552
|
+
...error.hint ? { hint: error.hint } : {}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
if (error instanceof Error) {
|
|
556
|
+
return { code: "unexpected", message: redactText(error.message), detail: {} };
|
|
557
|
+
}
|
|
558
|
+
return { code: "unexpected", message: redactText(String(error)), detail: {} };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/config.ts
|
|
562
|
+
var CONFIG_SCHEMA = "loom/config@1";
|
|
563
|
+
var DEFAULT_CONFIG = {
|
|
564
|
+
schema: CONFIG_SCHEMA,
|
|
565
|
+
repos: [],
|
|
566
|
+
branches: ["main"],
|
|
567
|
+
releases: 5,
|
|
568
|
+
includeLatestCommit: true,
|
|
569
|
+
aliases: {},
|
|
570
|
+
ownerAliases: {},
|
|
571
|
+
discovery: { owners: [], include: [], exclude: [], includeArchived: false, includeForks: false },
|
|
572
|
+
collect: {
|
|
573
|
+
readme: false,
|
|
574
|
+
readmeExcerptChars: 600,
|
|
575
|
+
branches: false,
|
|
576
|
+
branchLimit: 10,
|
|
577
|
+
extraBranches: [],
|
|
578
|
+
commitComments: false,
|
|
579
|
+
commitCommentLimit: 20,
|
|
580
|
+
issueComments: false,
|
|
581
|
+
issueCommentLimit: 20,
|
|
582
|
+
workflows: false,
|
|
583
|
+
workflowLimit: 10,
|
|
584
|
+
ciRuns: 5
|
|
585
|
+
},
|
|
586
|
+
store: ".loom",
|
|
587
|
+
githubBaseUrl: "https://api.github.com",
|
|
588
|
+
triggers: [],
|
|
589
|
+
webhook: {
|
|
590
|
+
path: "/webhook",
|
|
591
|
+
secretEnv: "LOOM_WEBHOOK_SECRET",
|
|
592
|
+
toleranceSeconds: 300,
|
|
593
|
+
maxBodyBytes: 1048576
|
|
594
|
+
},
|
|
595
|
+
watch: { intervalSeconds: 60 },
|
|
596
|
+
serve: { pollIntervalSeconds: 0, queueDepth: 32, shutdownTimeoutSeconds: 30, syncTimeoutSeconds: 120 }
|
|
597
|
+
};
|
|
598
|
+
var OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
|
|
599
|
+
var REPO_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
|
|
600
|
+
var GLOB_SEGMENT = /^[A-Za-z0-9._?*-]{1,100}$/;
|
|
601
|
+
function isRepoName(value) {
|
|
602
|
+
if (value.length > 140 || value.includes("..") || value.includes("//"))
|
|
603
|
+
return false;
|
|
604
|
+
const parts = value.split("/");
|
|
605
|
+
if (parts.length !== 2)
|
|
606
|
+
return false;
|
|
607
|
+
const [owner, repo] = parts;
|
|
608
|
+
return OWNER_PATTERN.test(owner) && REPO_PATTERN.test(repo) && repo !== "." && repo !== "..";
|
|
609
|
+
}
|
|
610
|
+
function isRepoGlob(value) {
|
|
611
|
+
if (value.length === 0 || value.length > 140 || value.includes("..") || value.includes("//"))
|
|
612
|
+
return false;
|
|
613
|
+
const parts = value.split("/");
|
|
614
|
+
if (parts.length !== 2)
|
|
615
|
+
return false;
|
|
616
|
+
const [owner, repo] = parts;
|
|
617
|
+
return GLOB_SEGMENT.test(owner) && GLOB_SEGMENT.test(repo) && repo !== "." && repo !== ".." && owner !== "." && owner !== "..";
|
|
618
|
+
}
|
|
619
|
+
function repoGlobMatches(pattern, repo) {
|
|
620
|
+
const source = pattern.toLowerCase().replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
621
|
+
return new RegExp(`^${source}$`).test(repo.toLowerCase());
|
|
622
|
+
}
|
|
623
|
+
function repoKey(value) {
|
|
624
|
+
return value.toLowerCase();
|
|
625
|
+
}
|
|
626
|
+
function resolveOwnerAlias(owner, aliases) {
|
|
627
|
+
const map = new Map;
|
|
628
|
+
for (const [from, to] of Object.entries(aliases))
|
|
629
|
+
map.set(from.toLowerCase(), to);
|
|
630
|
+
let current = owner;
|
|
631
|
+
const seen = new Set([owner.toLowerCase()]);
|
|
632
|
+
for (let depth = 0;depth < 8; depth += 1) {
|
|
633
|
+
const next = map.get(current.toLowerCase());
|
|
634
|
+
if (!next || seen.has(next.toLowerCase()))
|
|
635
|
+
return current;
|
|
636
|
+
seen.add(next.toLowerCase());
|
|
637
|
+
current = next;
|
|
638
|
+
}
|
|
639
|
+
return current;
|
|
640
|
+
}
|
|
641
|
+
function splitRepoName(fullName) {
|
|
642
|
+
if (!isRepoName(fullName))
|
|
643
|
+
return null;
|
|
644
|
+
const slash = fullName.indexOf("/");
|
|
645
|
+
return { owner: fullName.slice(0, slash), name: fullName.slice(slash + 1) };
|
|
646
|
+
}
|
|
647
|
+
function canonicalRepoKey(fullName, ownerAliases) {
|
|
648
|
+
const parts = splitRepoName(fullName);
|
|
649
|
+
if (!parts)
|
|
650
|
+
return fullName.toLowerCase();
|
|
651
|
+
return `${resolveOwnerAlias(parts.owner, ownerAliases)}/${parts.name}`.toLowerCase();
|
|
652
|
+
}
|
|
653
|
+
function canonicalRepoDisplay(fullName, ownerAliases) {
|
|
654
|
+
const parts = splitRepoName(fullName);
|
|
655
|
+
if (!parts)
|
|
656
|
+
return fullName;
|
|
657
|
+
const owner = resolveOwnerAlias(parts.owner, ownerAliases);
|
|
658
|
+
return owner === parts.owner ? fullName : `${owner}/${parts.name}`;
|
|
659
|
+
}
|
|
660
|
+
function expectObject(value, path) {
|
|
661
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
662
|
+
throw configError(`${path} must be an object`);
|
|
663
|
+
}
|
|
664
|
+
return value;
|
|
665
|
+
}
|
|
666
|
+
function expectString(value, path) {
|
|
667
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
668
|
+
throw configError(`${path} must be a non-empty string`);
|
|
669
|
+
}
|
|
670
|
+
return value;
|
|
671
|
+
}
|
|
672
|
+
function expectBoolean(value, path) {
|
|
673
|
+
if (typeof value !== "boolean")
|
|
674
|
+
throw configError(`${path} must be a boolean`);
|
|
675
|
+
return value;
|
|
676
|
+
}
|
|
677
|
+
function expectInt(value, path, min, max) {
|
|
678
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
|
|
679
|
+
throw configError(`${path} must be an integer between ${min} and ${max}`);
|
|
680
|
+
}
|
|
681
|
+
return value;
|
|
682
|
+
}
|
|
683
|
+
function parseTriggers(value) {
|
|
684
|
+
if (value === undefined)
|
|
685
|
+
return [];
|
|
686
|
+
if (!Array.isArray(value))
|
|
687
|
+
throw configError("triggers must be an array");
|
|
688
|
+
return value.map((raw, index) => {
|
|
689
|
+
const path = `triggers[${index}]`;
|
|
690
|
+
const item = expectObject(raw, path);
|
|
691
|
+
const kind = expectString(item["kind"], `${path}.kind`);
|
|
692
|
+
switch (kind) {
|
|
693
|
+
case "vercel":
|
|
694
|
+
return { kind, urlEnv: expectString(item["urlEnv"], `${path}.urlEnv`) };
|
|
695
|
+
case "github-dispatch": {
|
|
696
|
+
const repo = expectString(item["repo"], `${path}.repo`);
|
|
697
|
+
if (!isRepoName(repo))
|
|
698
|
+
throw configError(`${path}.repo must be owner/name`);
|
|
699
|
+
return {
|
|
700
|
+
kind,
|
|
701
|
+
repo,
|
|
702
|
+
eventType: expectString(item["eventType"] ?? "loom-sync", `${path}.eventType`),
|
|
703
|
+
tokenEnv: expectString(item["tokenEnv"] ?? "GITHUB_TOKEN", `${path}.tokenEnv`)
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
case "webhook": {
|
|
707
|
+
const secretEnv = item["secretEnv"];
|
|
708
|
+
if (secretEnv !== undefined && secretEnv !== null && typeof secretEnv !== "string") {
|
|
709
|
+
throw configError(`${path}.secretEnv must be a string or null`);
|
|
710
|
+
}
|
|
711
|
+
return {
|
|
712
|
+
kind,
|
|
713
|
+
urlEnv: expectString(item["urlEnv"], `${path}.urlEnv`),
|
|
714
|
+
secretEnv: typeof secretEnv === "string" && secretEnv.length > 0 ? secretEnv : null
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
default:
|
|
718
|
+
throw configError(`${path}.kind is unknown: ${kind}`);
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
function parseDiscovery(value) {
|
|
723
|
+
if (value === undefined) {
|
|
724
|
+
return { owners: [], include: [], exclude: [], includeArchived: false, includeForks: false };
|
|
725
|
+
}
|
|
726
|
+
const root = expectObject(value, "discovery");
|
|
727
|
+
const owners = [];
|
|
728
|
+
if (root["owners"] !== undefined) {
|
|
729
|
+
if (!Array.isArray(root["owners"]))
|
|
730
|
+
throw configError("discovery.owners must be an array of GitHub logins");
|
|
731
|
+
const seen = new Set;
|
|
732
|
+
for (const [index, entry] of root["owners"].entries()) {
|
|
733
|
+
const owner = expectString(entry, `discovery.owners[${index}]`);
|
|
734
|
+
if (!OWNER_PATTERN.test(owner))
|
|
735
|
+
throw configError(`discovery.owners[${index}] is not a GitHub login: ${owner}`);
|
|
736
|
+
const key = owner.toLowerCase();
|
|
737
|
+
if (seen.has(key))
|
|
738
|
+
continue;
|
|
739
|
+
seen.add(key);
|
|
740
|
+
owners.push(owner);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const globs = (name) => {
|
|
744
|
+
const raw = root[name];
|
|
745
|
+
if (raw === undefined)
|
|
746
|
+
return [];
|
|
747
|
+
if (!Array.isArray(raw))
|
|
748
|
+
throw configError(`discovery.${name} must be an array of owner/name globs`);
|
|
749
|
+
const out = [];
|
|
750
|
+
for (const [index, entry] of raw.entries()) {
|
|
751
|
+
const pattern = expectString(entry, `discovery.${name}[${index}]`);
|
|
752
|
+
if (!isRepoGlob(pattern))
|
|
753
|
+
throw configError(`discovery.${name}[${index}] is not an owner/name glob: ${pattern}`);
|
|
754
|
+
out.push(pattern);
|
|
755
|
+
}
|
|
756
|
+
return out;
|
|
757
|
+
};
|
|
758
|
+
return {
|
|
759
|
+
owners,
|
|
760
|
+
include: globs("include"),
|
|
761
|
+
exclude: globs("exclude"),
|
|
762
|
+
includeArchived: root["includeArchived"] === undefined ? false : expectBoolean(root["includeArchived"], "discovery.includeArchived"),
|
|
763
|
+
includeForks: root["includeForks"] === undefined ? false : expectBoolean(root["includeForks"], "discovery.includeForks")
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
function parseCollect(value) {
|
|
767
|
+
const defaults = structuredClone(DEFAULT_CONFIG.collect);
|
|
768
|
+
if (value === undefined)
|
|
769
|
+
return defaults;
|
|
770
|
+
const root = expectObject(value, "collect");
|
|
771
|
+
const bool = (name) => {
|
|
772
|
+
const raw = root[name];
|
|
773
|
+
if (raw === undefined)
|
|
774
|
+
return defaults[name];
|
|
775
|
+
return expectBoolean(raw, `collect.${String(name)}`);
|
|
776
|
+
};
|
|
777
|
+
const int = (name, min, max) => {
|
|
778
|
+
const raw = root[name];
|
|
779
|
+
if (raw === undefined)
|
|
780
|
+
return defaults[name];
|
|
781
|
+
return expectInt(raw, `collect.${String(name)}`, min, max);
|
|
782
|
+
};
|
|
783
|
+
const extraBranches = [];
|
|
784
|
+
if (root["extraBranches"] !== undefined) {
|
|
785
|
+
if (!Array.isArray(root["extraBranches"]))
|
|
786
|
+
throw configError("collect.extraBranches must be an array");
|
|
787
|
+
const seen = new Set;
|
|
788
|
+
for (const [index, entry] of root["extraBranches"].entries()) {
|
|
789
|
+
const branch = expectString(entry, `collect.extraBranches[${index}]`);
|
|
790
|
+
if (branch.startsWith("refs/") || branch.includes("..") || branch.includes(" ")) {
|
|
791
|
+
throw configError(`collect.extraBranches[${index}] must be a plain branch name`);
|
|
792
|
+
}
|
|
793
|
+
if (seen.has(branch))
|
|
794
|
+
continue;
|
|
795
|
+
seen.add(branch);
|
|
796
|
+
extraBranches.push(branch);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return {
|
|
800
|
+
readme: bool("readme"),
|
|
801
|
+
readmeExcerptChars: int("readmeExcerptChars", 0, 20000),
|
|
802
|
+
branches: bool("branches"),
|
|
803
|
+
branchLimit: int("branchLimit", 1, 100),
|
|
804
|
+
extraBranches,
|
|
805
|
+
commitComments: bool("commitComments"),
|
|
806
|
+
commitCommentLimit: int("commitCommentLimit", 0, 100),
|
|
807
|
+
issueComments: bool("issueComments"),
|
|
808
|
+
issueCommentLimit: int("issueCommentLimit", 0, 100),
|
|
809
|
+
workflows: bool("workflows"),
|
|
810
|
+
workflowLimit: int("workflowLimit", 0, 100),
|
|
811
|
+
ciRuns: int("ciRuns", 1, 100)
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
function parseConfig(raw) {
|
|
815
|
+
const root = expectObject(raw, "config");
|
|
816
|
+
const merged = structuredClone(DEFAULT_CONFIG);
|
|
817
|
+
if (root["schema"] !== undefined && root["schema"] !== CONFIG_SCHEMA) {
|
|
818
|
+
throw configError(`config.schema must be "${CONFIG_SCHEMA}"`, { found: root["schema"] });
|
|
819
|
+
}
|
|
820
|
+
if (root["repos"] !== undefined) {
|
|
821
|
+
if (!Array.isArray(root["repos"]))
|
|
822
|
+
throw configError("repos must be an array of owner/name strings");
|
|
823
|
+
const seen = new Set;
|
|
824
|
+
const repos = [];
|
|
825
|
+
for (const [index, entry] of root["repos"].entries()) {
|
|
826
|
+
const repo = expectString(entry, `repos[${index}]`);
|
|
827
|
+
if (!isRepoName(repo)) {
|
|
828
|
+
throw new LoomError("repo_invalid", `repos[${index}] is not a valid public repository name: ${repo}`);
|
|
829
|
+
}
|
|
830
|
+
const key = repoKey(repo);
|
|
831
|
+
if (seen.has(key))
|
|
832
|
+
continue;
|
|
833
|
+
seen.add(key);
|
|
834
|
+
repos.push(repo);
|
|
835
|
+
}
|
|
836
|
+
merged.repos = repos;
|
|
837
|
+
}
|
|
838
|
+
if (root["branches"] !== undefined) {
|
|
839
|
+
if (!Array.isArray(root["branches"]) || root["branches"].length === 0) {
|
|
840
|
+
throw configError("branches must be a non-empty array");
|
|
841
|
+
}
|
|
842
|
+
merged.branches = root["branches"].map((entry, index) => {
|
|
843
|
+
const branch = expectString(entry, `branches[${index}]`);
|
|
844
|
+
if (branch.startsWith("refs/") || branch.includes("..")) {
|
|
845
|
+
throw configError(`branches[${index}] must be a branch name without refs/ prefix`);
|
|
846
|
+
}
|
|
847
|
+
return branch;
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
if (root["releases"] !== undefined)
|
|
851
|
+
merged.releases = expectInt(root["releases"], "releases", 0, 100);
|
|
852
|
+
if (root["includeLatestCommit"] !== undefined) {
|
|
853
|
+
merged.includeLatestCommit = expectBoolean(root["includeLatestCommit"], "includeLatestCommit");
|
|
854
|
+
}
|
|
855
|
+
if (root["store"] !== undefined) {
|
|
856
|
+
const store = expectString(root["store"], "store");
|
|
857
|
+
if (store.startsWith("/") || store.includes("..")) {
|
|
858
|
+
throw configError("store must be a relative path inside the project");
|
|
859
|
+
}
|
|
860
|
+
merged.store = store;
|
|
861
|
+
}
|
|
862
|
+
if (root["githubBaseUrl"] !== undefined) {
|
|
863
|
+
const url = expectString(root["githubBaseUrl"], "githubBaseUrl");
|
|
864
|
+
const parsed = URL.canParse(url) ? new URL(url) : null;
|
|
865
|
+
if (!parsed || parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
866
|
+
throw configError("githubBaseUrl must be an http(s) URL");
|
|
867
|
+
}
|
|
868
|
+
merged.githubBaseUrl = url.replace(/\/$/, "");
|
|
869
|
+
}
|
|
870
|
+
if (root["aliases"] !== undefined) {
|
|
871
|
+
const aliases = expectObject(root["aliases"], "aliases");
|
|
872
|
+
const out = {};
|
|
873
|
+
for (const [from, to] of Object.entries(aliases)) {
|
|
874
|
+
if (!isRepoName(from))
|
|
875
|
+
throw configError(`aliases key is not owner/name: ${from}`);
|
|
876
|
+
const target = expectString(to, `aliases.${from}`);
|
|
877
|
+
if (!isRepoName(target))
|
|
878
|
+
throw configError(`aliases.${from} is not owner/name: ${target}`);
|
|
879
|
+
if (repoKey(from) === repoKey(target))
|
|
880
|
+
throw configError(`aliases.${from} points at itself`);
|
|
881
|
+
out[from] = target;
|
|
882
|
+
}
|
|
883
|
+
merged.aliases = out;
|
|
884
|
+
}
|
|
885
|
+
if (root["ownerAliases"] !== undefined) {
|
|
886
|
+
const ownerAliases = expectObject(root["ownerAliases"], "ownerAliases");
|
|
887
|
+
const out = {};
|
|
888
|
+
for (const [from, to] of Object.entries(ownerAliases)) {
|
|
889
|
+
if (!OWNER_PATTERN.test(from))
|
|
890
|
+
throw configError(`ownerAliases key is not a GitHub login: ${from}`);
|
|
891
|
+
const target = expectString(to, `ownerAliases.${from}`);
|
|
892
|
+
if (!OWNER_PATTERN.test(target))
|
|
893
|
+
throw configError(`ownerAliases.${from} is not a GitHub login: ${target}`);
|
|
894
|
+
if (from.toLowerCase() === target.toLowerCase()) {
|
|
895
|
+
throw configError(`ownerAliases.${from} points at itself`);
|
|
896
|
+
}
|
|
897
|
+
out[from] = target;
|
|
898
|
+
}
|
|
899
|
+
merged.ownerAliases = out;
|
|
900
|
+
}
|
|
901
|
+
merged.discovery = parseDiscovery(root["discovery"]);
|
|
902
|
+
merged.collect = parseCollect(root["collect"]);
|
|
903
|
+
merged.triggers = parseTriggers(root["triggers"]);
|
|
904
|
+
if (root["webhook"] !== undefined) {
|
|
905
|
+
const webhook = expectObject(root["webhook"], "webhook");
|
|
906
|
+
if (webhook["path"] !== undefined) {
|
|
907
|
+
const path = expectString(webhook["path"], "webhook.path");
|
|
908
|
+
if (!path.startsWith("/"))
|
|
909
|
+
throw configError("webhook.path must start with /");
|
|
910
|
+
merged.webhook.path = path;
|
|
911
|
+
}
|
|
912
|
+
if (webhook["secretEnv"] !== undefined) {
|
|
913
|
+
merged.webhook.secretEnv = expectString(webhook["secretEnv"], "webhook.secretEnv");
|
|
914
|
+
}
|
|
915
|
+
if (webhook["toleranceSeconds"] !== undefined) {
|
|
916
|
+
merged.webhook.toleranceSeconds = expectInt(webhook["toleranceSeconds"], "webhook.toleranceSeconds", 0, 3600);
|
|
917
|
+
}
|
|
918
|
+
if (webhook["maxBodyBytes"] !== undefined) {
|
|
919
|
+
merged.webhook.maxBodyBytes = expectInt(webhook["maxBodyBytes"], "webhook.maxBodyBytes", 1024, 10485760);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
if (root["watch"] !== undefined) {
|
|
923
|
+
const watch = expectObject(root["watch"], "watch");
|
|
924
|
+
if (watch["intervalSeconds"] !== undefined) {
|
|
925
|
+
merged.watch.intervalSeconds = expectInt(watch["intervalSeconds"], "watch.intervalSeconds", 1, 86400);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
if (root["serve"] !== undefined) {
|
|
929
|
+
const serve = expectObject(root["serve"], "serve");
|
|
930
|
+
if (serve["pollIntervalSeconds"] !== undefined) {
|
|
931
|
+
merged.serve.pollIntervalSeconds = expectInt(serve["pollIntervalSeconds"], "serve.pollIntervalSeconds", 0, 86400);
|
|
932
|
+
}
|
|
933
|
+
if (serve["queueDepth"] !== undefined) {
|
|
934
|
+
merged.serve.queueDepth = expectInt(serve["queueDepth"], "serve.queueDepth", 1, 1e4);
|
|
935
|
+
}
|
|
936
|
+
if (serve["shutdownTimeoutSeconds"] !== undefined) {
|
|
937
|
+
merged.serve.shutdownTimeoutSeconds = expectInt(serve["shutdownTimeoutSeconds"], "serve.shutdownTimeoutSeconds", 1, 600);
|
|
938
|
+
}
|
|
939
|
+
if (serve["syncTimeoutSeconds"] !== undefined) {
|
|
940
|
+
merged.serve.syncTimeoutSeconds = expectInt(serve["syncTimeoutSeconds"], "serve.syncTimeoutSeconds", 1, 3600);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
return merged;
|
|
944
|
+
}
|
|
945
|
+
async function loadConfig(path) {
|
|
946
|
+
if (path === null)
|
|
947
|
+
return structuredClone(DEFAULT_CONFIG);
|
|
948
|
+
const runtime = globalThis.Bun;
|
|
949
|
+
if (runtime === undefined || typeof runtime.file !== "function") {
|
|
950
|
+
throw configError("loadConfig needs Bun file access; in a browser pass a config object to parseConfig instead", { path });
|
|
951
|
+
}
|
|
952
|
+
const file = runtime.file(path);
|
|
953
|
+
if (!await file.exists()) {
|
|
954
|
+
if (path === "loom.config.json")
|
|
955
|
+
return structuredClone(DEFAULT_CONFIG);
|
|
956
|
+
throw configError(`config file not found: ${path}`);
|
|
957
|
+
}
|
|
958
|
+
let raw;
|
|
959
|
+
try {
|
|
960
|
+
raw = JSON.parse(await file.text());
|
|
961
|
+
} catch (error) {
|
|
962
|
+
throw configError(`config is not valid JSON: ${path}`, { reason: error.message });
|
|
963
|
+
}
|
|
964
|
+
return parseConfig(raw);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// src/github/guard.ts
|
|
968
|
+
function asRecord(value) {
|
|
969
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
970
|
+
}
|
|
971
|
+
function assertPublicRepo(requested, payload) {
|
|
972
|
+
const record = asRecord(payload);
|
|
973
|
+
if (!record) {
|
|
974
|
+
throw new LoomError("github_error", `repository payload for ${requested} is not an object`, { repo: requested });
|
|
975
|
+
}
|
|
976
|
+
const fullName = record["full_name"];
|
|
977
|
+
if (typeof fullName !== "string" || fullName.length === 0) {
|
|
978
|
+
throw new LoomError("github_error", `repository payload for ${requested} has no full_name`, { repo: requested });
|
|
979
|
+
}
|
|
980
|
+
if (repoKey(fullName) !== repoKey(requested)) {
|
|
981
|
+
const requestedParts = requested.split("/");
|
|
982
|
+
const returnedParts = fullName.split("/");
|
|
983
|
+
const sameName = requestedParts.length === 2 && returnedParts.length === 2 && requestedParts[1]?.toLowerCase() === returnedParts[1]?.toLowerCase();
|
|
984
|
+
if (!sameName) {
|
|
985
|
+
throw new LoomError("github_error", `requested ${requested} but GitHub returned ${fullName}`, {
|
|
986
|
+
repo: requested,
|
|
987
|
+
returned: fullName
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
if (record["private"] === true) {
|
|
992
|
+
throw guardError(`refusing to snapshot private repository ${fullName}`, { repo: fullName });
|
|
993
|
+
}
|
|
994
|
+
const visibility = record["visibility"];
|
|
995
|
+
if (typeof visibility === "string" && visibility !== "public") {
|
|
996
|
+
throw guardError(`refusing to snapshot ${visibility} repository ${fullName}`, { repo: fullName });
|
|
997
|
+
}
|
|
998
|
+
const id = record["id"];
|
|
999
|
+
if (typeof id !== "number") {
|
|
1000
|
+
throw new LoomError("github_error", `repository payload for ${requested} has no numeric id`, { repo: requested });
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
id,
|
|
1004
|
+
fullName,
|
|
1005
|
+
private: false,
|
|
1006
|
+
...typeof visibility === "string" ? { visibility } : {},
|
|
1007
|
+
archived: record["archived"] === true
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
function assertRepoRequest(value) {
|
|
1011
|
+
if (!isRepoName(value)) {
|
|
1012
|
+
throw new LoomError("repo_invalid", `not a valid owner/name repository: ${value}`, { repo: value });
|
|
1013
|
+
}
|
|
1014
|
+
return value;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// src/base64.ts
|
|
1018
|
+
var BASE64_ALPHABET = /[^A-Za-z0-9+/]/g;
|
|
1019
|
+
function decodeBase64(value) {
|
|
1020
|
+
let clean = value.replace(BASE64_ALPHABET, "");
|
|
1021
|
+
const remainder = clean.length % 4;
|
|
1022
|
+
if (remainder === 1)
|
|
1023
|
+
clean = clean.slice(0, -1);
|
|
1024
|
+
else if (remainder === 2)
|
|
1025
|
+
clean += "==";
|
|
1026
|
+
else if (remainder === 3)
|
|
1027
|
+
clean += "=";
|
|
1028
|
+
const binary = atob(clean);
|
|
1029
|
+
const bytes = new Uint8Array(binary.length);
|
|
1030
|
+
for (let index = 0;index < binary.length; index += 1)
|
|
1031
|
+
bytes[index] = binary.charCodeAt(index);
|
|
1032
|
+
return new TextDecoder("utf-8").decode(bytes);
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// src/types.ts
|
|
1036
|
+
var SNAPSHOT_SCHEMA = "loom/snapshot@1";
|
|
1037
|
+
function snapshotStats(payload) {
|
|
1038
|
+
let releases = 0;
|
|
1039
|
+
let readmes = 0;
|
|
1040
|
+
let branches = 0;
|
|
1041
|
+
let commitComments = 0;
|
|
1042
|
+
let issueComments = 0;
|
|
1043
|
+
let workflows = 0;
|
|
1044
|
+
const languages = new Set;
|
|
1045
|
+
for (const repo of payload.repos) {
|
|
1046
|
+
releases += repo.releases.length;
|
|
1047
|
+
if (repo.readme)
|
|
1048
|
+
readmes += 1;
|
|
1049
|
+
branches += repo.branches?.length ?? 0;
|
|
1050
|
+
commitComments += repo.commitComments?.length ?? 0;
|
|
1051
|
+
issueComments += repo.issueComments?.length ?? 0;
|
|
1052
|
+
workflows += repo.workflows?.length ?? 0;
|
|
1053
|
+
for (const name of Object.keys(repo.languages))
|
|
1054
|
+
languages.add(name);
|
|
1055
|
+
}
|
|
1056
|
+
return {
|
|
1057
|
+
repos: payload.repos.length,
|
|
1058
|
+
releases,
|
|
1059
|
+
languages: languages.size,
|
|
1060
|
+
errors: payload.errors.length,
|
|
1061
|
+
readmes,
|
|
1062
|
+
branches,
|
|
1063
|
+
commitComments,
|
|
1064
|
+
issueComments,
|
|
1065
|
+
workflows
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// src/concurrency.ts
|
|
1070
|
+
class CancelledError extends Error {
|
|
1071
|
+
name = "CancelledError";
|
|
1072
|
+
constructor(message = "operation cancelled") {
|
|
1073
|
+
super(message);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
function throwIfAborted(signal) {
|
|
1077
|
+
if (signal?.aborted) {
|
|
1078
|
+
const reason = signal.reason;
|
|
1079
|
+
throw new CancelledError(reason instanceof Error ? reason.message : "operation cancelled");
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
function combineSignals(signals) {
|
|
1083
|
+
const present = signals.filter((signal) => signal !== undefined);
|
|
1084
|
+
if (present.length === 0)
|
|
1085
|
+
return;
|
|
1086
|
+
if (present.length === 1)
|
|
1087
|
+
return present[0];
|
|
1088
|
+
return AbortSignal.any(present);
|
|
1089
|
+
}
|
|
1090
|
+
async function mapLimitSettled(items, limit, worker, signal) {
|
|
1091
|
+
const results = new Array(items.length);
|
|
1092
|
+
if (items.length === 0)
|
|
1093
|
+
return results;
|
|
1094
|
+
const bound = Math.max(1, Math.min(Math.floor(limit), items.length));
|
|
1095
|
+
let cursor = 0;
|
|
1096
|
+
const run = async () => {
|
|
1097
|
+
for (;; ) {
|
|
1098
|
+
throwIfAborted(signal);
|
|
1099
|
+
const index = cursor;
|
|
1100
|
+
cursor += 1;
|
|
1101
|
+
if (index >= items.length)
|
|
1102
|
+
return;
|
|
1103
|
+
try {
|
|
1104
|
+
results[index] = { ok: true, value: await worker(items[index], index) };
|
|
1105
|
+
} catch (error) {
|
|
1106
|
+
results[index] = { ok: false, error };
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
await Promise.all(Array.from({ length: bound }, () => run()));
|
|
1111
|
+
throwIfAborted(signal);
|
|
1112
|
+
return results;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// src/github/collect.ts
|
|
1116
|
+
function record(value) {
|
|
1117
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1118
|
+
}
|
|
1119
|
+
function text(value, fallback = null) {
|
|
1120
|
+
return typeof value === "string" && value.length > 0 ? value : fallback;
|
|
1121
|
+
}
|
|
1122
|
+
function count(value) {
|
|
1123
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
1124
|
+
}
|
|
1125
|
+
function flag(value) {
|
|
1126
|
+
return value === true;
|
|
1127
|
+
}
|
|
1128
|
+
function list(value) {
|
|
1129
|
+
return Array.isArray(value) ? value : [];
|
|
1130
|
+
}
|
|
1131
|
+
function languageMap(value) {
|
|
1132
|
+
const raw = record(value) ?? {};
|
|
1133
|
+
const out = {};
|
|
1134
|
+
for (const [name, bytes] of Object.entries(raw)) {
|
|
1135
|
+
if (typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0)
|
|
1136
|
+
out[name] = bytes;
|
|
1137
|
+
}
|
|
1138
|
+
return out;
|
|
1139
|
+
}
|
|
1140
|
+
function parseRelease(value) {
|
|
1141
|
+
const raw = record(value);
|
|
1142
|
+
if (!raw)
|
|
1143
|
+
return null;
|
|
1144
|
+
const tag = text(raw["tag_name"]);
|
|
1145
|
+
if (!tag)
|
|
1146
|
+
return null;
|
|
1147
|
+
const id = typeof raw["id"] === "number" ? raw["id"] : tag;
|
|
1148
|
+
return {
|
|
1149
|
+
id,
|
|
1150
|
+
tag,
|
|
1151
|
+
name: text(raw["name"]),
|
|
1152
|
+
publishedAt: text(raw["published_at"] ?? raw["created_at"]),
|
|
1153
|
+
prerelease: flag(raw["prerelease"]),
|
|
1154
|
+
draft: flag(raw["draft"]),
|
|
1155
|
+
url: text(raw["html_url"])
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
function parseHead(value) {
|
|
1159
|
+
const raw = record(value);
|
|
1160
|
+
if (!raw)
|
|
1161
|
+
return null;
|
|
1162
|
+
const sha = text(raw["sha"]);
|
|
1163
|
+
if (!sha)
|
|
1164
|
+
return null;
|
|
1165
|
+
const commit = record(raw["commit"]) ?? {};
|
|
1166
|
+
const author = record(commit["author"]) ?? {};
|
|
1167
|
+
return {
|
|
1168
|
+
sha,
|
|
1169
|
+
message: text(commit["message"]) ?? "",
|
|
1170
|
+
author: text(author["name"]),
|
|
1171
|
+
committedAt: text(author["date"]),
|
|
1172
|
+
url: text(raw["html_url"]) ?? ""
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
async function optional(fn) {
|
|
1176
|
+
try {
|
|
1177
|
+
return await fn();
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
if (error instanceof LoomError && (error.detail["status"] === 404 || error.detail["status"] === 410)) {
|
|
1180
|
+
return null;
|
|
1181
|
+
}
|
|
1182
|
+
throw error;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
function parseReadme(value, excerptChars) {
|
|
1186
|
+
const raw = record(value);
|
|
1187
|
+
if (!raw)
|
|
1188
|
+
return null;
|
|
1189
|
+
const path = text(raw["path"]) ?? text(raw["name"]);
|
|
1190
|
+
const sha = text(raw["sha"]);
|
|
1191
|
+
if (!path || !sha)
|
|
1192
|
+
return null;
|
|
1193
|
+
const encoding = text(raw["encoding"]);
|
|
1194
|
+
let excerpt = null;
|
|
1195
|
+
const content = text(raw["content"]);
|
|
1196
|
+
if (content && excerptChars > 0) {
|
|
1197
|
+
const encodedSlice = content.slice(0, Math.ceil(excerptChars * 4 / 3) + 8);
|
|
1198
|
+
try {
|
|
1199
|
+
const decoded = decodeBase64(encodedSlice);
|
|
1200
|
+
excerpt = decoded.slice(0, excerptChars).replace(/\s+$/u, "");
|
|
1201
|
+
if (excerpt.length === 0)
|
|
1202
|
+
excerpt = null;
|
|
1203
|
+
} catch {
|
|
1204
|
+
excerpt = null;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
return {
|
|
1208
|
+
path,
|
|
1209
|
+
sha,
|
|
1210
|
+
size: count(raw["size"]),
|
|
1211
|
+
encoding,
|
|
1212
|
+
htmlUrl: text(raw["html_url"]),
|
|
1213
|
+
downloadUrl: text(raw["download_url"]),
|
|
1214
|
+
excerpt
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
function parseBranch(value, defaultBranch) {
|
|
1218
|
+
const raw = record(value);
|
|
1219
|
+
if (!raw)
|
|
1220
|
+
return null;
|
|
1221
|
+
const name = text(raw["name"]);
|
|
1222
|
+
const commit = record(raw["commit"]) ?? {};
|
|
1223
|
+
const sha = text(commit["sha"]);
|
|
1224
|
+
if (!name || !sha)
|
|
1225
|
+
return null;
|
|
1226
|
+
return { name, sha, protected: flag(raw["protected"]), default: name === defaultBranch };
|
|
1227
|
+
}
|
|
1228
|
+
function parseCommitComment(value) {
|
|
1229
|
+
const raw = record(value);
|
|
1230
|
+
if (!raw)
|
|
1231
|
+
return null;
|
|
1232
|
+
const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
|
|
1233
|
+
if (id === null)
|
|
1234
|
+
return null;
|
|
1235
|
+
const user = record(raw["user"]) ?? {};
|
|
1236
|
+
return {
|
|
1237
|
+
id,
|
|
1238
|
+
body: text(raw["body"]) ?? "",
|
|
1239
|
+
author: text(user["login"]),
|
|
1240
|
+
createdAt: text(raw["created_at"]),
|
|
1241
|
+
url: text(raw["html_url"]),
|
|
1242
|
+
commitSha: text(raw["commit_id"])
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
function parseIssueComment(value) {
|
|
1246
|
+
const raw = record(value);
|
|
1247
|
+
if (!raw)
|
|
1248
|
+
return null;
|
|
1249
|
+
const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
|
|
1250
|
+
if (id === null)
|
|
1251
|
+
return null;
|
|
1252
|
+
const user = record(raw["user"]) ?? {};
|
|
1253
|
+
const issueUrl = text(raw["issue_url"]);
|
|
1254
|
+
const issueNumber = issueUrl === null ? null : Number.parseInt(issueUrl.slice(issueUrl.lastIndexOf("/") + 1), 10);
|
|
1255
|
+
return {
|
|
1256
|
+
id,
|
|
1257
|
+
body: text(raw["body"]) ?? "",
|
|
1258
|
+
author: text(user["login"]),
|
|
1259
|
+
createdAt: text(raw["created_at"]),
|
|
1260
|
+
url: text(raw["html_url"]),
|
|
1261
|
+
issueNumber: Number.isFinite(issueNumber) ? issueNumber : null
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
function parseWorkflow(value) {
|
|
1265
|
+
const raw = record(value);
|
|
1266
|
+
if (!raw)
|
|
1267
|
+
return null;
|
|
1268
|
+
const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
|
|
1269
|
+
const name = text(raw["name"]);
|
|
1270
|
+
const path = text(raw["path"]);
|
|
1271
|
+
if (id === null || !name || !path)
|
|
1272
|
+
return null;
|
|
1273
|
+
return { id, name, path, state: text(raw["state"]) ?? "unknown" };
|
|
1274
|
+
}
|
|
1275
|
+
function parseCi(value) {
|
|
1276
|
+
const raw = record(value);
|
|
1277
|
+
if (!raw)
|
|
1278
|
+
return null;
|
|
1279
|
+
const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
|
|
1280
|
+
if (id === null)
|
|
1281
|
+
return null;
|
|
1282
|
+
return {
|
|
1283
|
+
workflow: text(raw["name"]),
|
|
1284
|
+
runId: id,
|
|
1285
|
+
status: text(raw["status"]),
|
|
1286
|
+
conclusion: text(raw["conclusion"]),
|
|
1287
|
+
branch: text(raw["head_branch"]),
|
|
1288
|
+
sha: text(raw["head_sha"]),
|
|
1289
|
+
url: text(raw["html_url"]),
|
|
1290
|
+
updatedAt: text(raw["updated_at"])
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
async function collectRepo(options, requested) {
|
|
1294
|
+
const { client } = options;
|
|
1295
|
+
const ownerAliases = options.ownerAliases ?? {};
|
|
1296
|
+
const target = canonicalRepoDisplay(requested, ownerAliases);
|
|
1297
|
+
const metaResponse = await client.get(`/repos/${target}`);
|
|
1298
|
+
if (metaResponse.body === null) {
|
|
1299
|
+
throw new LoomError("github_error", `no repository metadata for ${target}`, { repo: target });
|
|
1300
|
+
}
|
|
1301
|
+
const meta = record(metaResponse.body);
|
|
1302
|
+
if (!meta) {
|
|
1303
|
+
throw new LoomError("github_error", `repository metadata for ${target} is not an object`, {
|
|
1304
|
+
repo: target
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
const identity = assertPublicRepo(target, meta);
|
|
1308
|
+
const fullName = canonicalRepoDisplay(identity.fullName, ownerAliases);
|
|
1309
|
+
const defaultBranch = text(meta["default_branch"], "main") ?? "main";
|
|
1310
|
+
const languagesResponse = await client.get(`/repos/${fullName}/languages`);
|
|
1311
|
+
const languages = languageMap(languagesResponse.body);
|
|
1312
|
+
const releases = [];
|
|
1313
|
+
const wanted = Math.max(0, Math.min(100, options.releases ?? 0));
|
|
1314
|
+
if (wanted > 0) {
|
|
1315
|
+
const response = await client.getAll(`/repos/${fullName}/releases?per_page=${wanted}`);
|
|
1316
|
+
for (const entry of response.items) {
|
|
1317
|
+
const release = parseRelease(entry);
|
|
1318
|
+
if (release && !release.draft)
|
|
1319
|
+
releases.push(release);
|
|
1320
|
+
}
|
|
1321
|
+
releases.sort((a, b) => {
|
|
1322
|
+
const left = a.publishedAt ?? "";
|
|
1323
|
+
const right = b.publishedAt ?? "";
|
|
1324
|
+
if (left !== right)
|
|
1325
|
+
return left > right ? -1 : 1;
|
|
1326
|
+
return a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0;
|
|
1327
|
+
});
|
|
1328
|
+
releases.splice(wanted);
|
|
1329
|
+
}
|
|
1330
|
+
let head = null;
|
|
1331
|
+
if (options.includeLatestCommit !== false) {
|
|
1332
|
+
const response = await client.get(`/repos/${fullName}/commits?per_page=1&sha=${encodeURIComponent(defaultBranch)}`);
|
|
1333
|
+
head = parseHead(list(response.body)[0]);
|
|
1334
|
+
}
|
|
1335
|
+
const collect = options.collect;
|
|
1336
|
+
const extra = {};
|
|
1337
|
+
if (collect?.readme) {
|
|
1338
|
+
const response = await optional(() => client.get(`/repos/${fullName}/readme`));
|
|
1339
|
+
extra.readme = response?.body ? parseReadme(response.body, collect.readmeExcerptChars) : null;
|
|
1340
|
+
}
|
|
1341
|
+
if (collect?.branches) {
|
|
1342
|
+
const response = await optional(() => client.get(`/repos/${fullName}/branches?per_page=${collect.branchLimit}`));
|
|
1343
|
+
const branches = [];
|
|
1344
|
+
for (const entry of list(response?.body)) {
|
|
1345
|
+
const branch = parseBranch(entry, defaultBranch);
|
|
1346
|
+
if (branch)
|
|
1347
|
+
branches.push(branch);
|
|
1348
|
+
}
|
|
1349
|
+
for (const name of collect.extraBranches) {
|
|
1350
|
+
if (branches.length >= collect.branchLimit)
|
|
1351
|
+
break;
|
|
1352
|
+
if (branches.some((branch) => branch.name === name))
|
|
1353
|
+
continue;
|
|
1354
|
+
const one = await optional(() => client.get(`/repos/${fullName}/branches/${encodeURIComponent(name)}`));
|
|
1355
|
+
const branch = one?.body ? parseBranch(one.body, defaultBranch) : null;
|
|
1356
|
+
if (branch)
|
|
1357
|
+
branches.push(branch);
|
|
1358
|
+
}
|
|
1359
|
+
if (!branches.some((branch) => branch.default) && branches.length < collect.branchLimit) {
|
|
1360
|
+
const one = await optional(() => client.get(`/repos/${fullName}/branches/${encodeURIComponent(defaultBranch)}`));
|
|
1361
|
+
const branch = one?.body ? parseBranch(one.body, defaultBranch) : null;
|
|
1362
|
+
if (branch)
|
|
1363
|
+
branches.push(branch);
|
|
1364
|
+
}
|
|
1365
|
+
extra.branches = branches.slice(0, collect.branchLimit);
|
|
1366
|
+
}
|
|
1367
|
+
if (collect?.commitComments && collect.commitCommentLimit > 0) {
|
|
1368
|
+
const response = await optional(() => client.get(`/repos/${fullName}/comments?per_page=${collect.commitCommentLimit}`));
|
|
1369
|
+
extra.commitComments = list(response?.body).map(parseCommitComment).filter((comment) => comment !== null).slice(0, collect.commitCommentLimit);
|
|
1370
|
+
}
|
|
1371
|
+
if (collect?.issueComments && collect.issueCommentLimit > 0) {
|
|
1372
|
+
const response = await optional(() => client.get(`/repos/${fullName}/issues/comments?per_page=${collect.issueCommentLimit}`));
|
|
1373
|
+
extra.issueComments = list(response?.body).map(parseIssueComment).filter((comment) => comment !== null).slice(0, collect.issueCommentLimit);
|
|
1374
|
+
}
|
|
1375
|
+
if (collect?.workflows) {
|
|
1376
|
+
const [definitions, runs] = await Promise.all([
|
|
1377
|
+
optional(() => client.get(`/repos/${fullName}/actions/workflows?per_page=${collect.workflowLimit}`)),
|
|
1378
|
+
optional(() => client.get(`/repos/${fullName}/actions/runs?branch=${encodeURIComponent(defaultBranch)}&per_page=${collect.ciRuns}`))
|
|
1379
|
+
]);
|
|
1380
|
+
const definitionBody = record(definitions?.body) ?? {};
|
|
1381
|
+
extra.workflows = list(definitionBody["workflows"]).map(parseWorkflow).filter((workflow) => workflow !== null).slice(0, collect.workflowLimit);
|
|
1382
|
+
const runBody = record(runs?.body) ?? {};
|
|
1383
|
+
extra.ci = parseCi(list(runBody["workflow_runs"])[0]);
|
|
1384
|
+
}
|
|
1385
|
+
const licenseRecord = record(meta["license"]);
|
|
1386
|
+
const metaHtmlUrl = text(meta["html_url"]);
|
|
1387
|
+
const htmlUrlIsCanonical = metaHtmlUrl !== null && metaHtmlUrl.toLowerCase().endsWith(`/${fullName.toLowerCase()}`);
|
|
1388
|
+
return {
|
|
1389
|
+
id: fullName.toLowerCase(),
|
|
1390
|
+
fullName,
|
|
1391
|
+
description: text(meta["description"]),
|
|
1392
|
+
homepage: text(meta["homepage"]),
|
|
1393
|
+
topics: list(meta["topics"]).filter((topic) => typeof topic === "string"),
|
|
1394
|
+
language: text(meta["language"]),
|
|
1395
|
+
languages,
|
|
1396
|
+
license: licenseRecord ? text(licenseRecord["spdx_id"]) : null,
|
|
1397
|
+
stars: count(meta["stargazers_count"]),
|
|
1398
|
+
forks: count(meta["forks_count"]),
|
|
1399
|
+
watchers: count(meta["subscribers_count"] ?? meta["watchers_count"]),
|
|
1400
|
+
openIssues: count(meta["open_issues_count"]),
|
|
1401
|
+
archived: flag(meta["archived"]),
|
|
1402
|
+
fork: flag(meta["fork"]),
|
|
1403
|
+
defaultBranch,
|
|
1404
|
+
createdAt: text(meta["created_at"]),
|
|
1405
|
+
updatedAt: text(meta["updated_at"]),
|
|
1406
|
+
pushedAt: text(meta["pushed_at"]),
|
|
1407
|
+
htmlUrl: htmlUrlIsCanonical ? metaHtmlUrl : `https://github.com/${fullName}`,
|
|
1408
|
+
visibility: "public",
|
|
1409
|
+
releases,
|
|
1410
|
+
head,
|
|
1411
|
+
...extra
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
async function collectSnapshot(options) {
|
|
1415
|
+
const requests = options.repos.map((repo) => assertRepoRequest(repo));
|
|
1416
|
+
const previous = new Map;
|
|
1417
|
+
for (const repo of options.previous?.repos ?? [])
|
|
1418
|
+
previous.set(repo.id.toLowerCase(), repo);
|
|
1419
|
+
const settled = await mapLimitSettled(requests, options.concurrency ?? 4, (repo) => collectRepo(options, repo), options.signal).catch((error) => {
|
|
1420
|
+
if (error instanceof CancelledError) {
|
|
1421
|
+
throw new LoomError("cancelled", "repository collection cancelled", { cancelled: true });
|
|
1422
|
+
}
|
|
1423
|
+
throw error;
|
|
1424
|
+
});
|
|
1425
|
+
const repos = [];
|
|
1426
|
+
const errors = [];
|
|
1427
|
+
const detectedAliases = new Map;
|
|
1428
|
+
let hardFailure = null;
|
|
1429
|
+
settled.forEach((result, index) => {
|
|
1430
|
+
const requested = requests[index];
|
|
1431
|
+
const key = requested.toLowerCase();
|
|
1432
|
+
if (result.ok) {
|
|
1433
|
+
const actual = result.value.fullName;
|
|
1434
|
+
if (repoKey(requested) !== repoKey(actual)) {
|
|
1435
|
+
const before = splitRepoName(requested);
|
|
1436
|
+
const after = splitRepoName(actual);
|
|
1437
|
+
if (before && after && before.name.toLowerCase() === after.name.toLowerCase()) {
|
|
1438
|
+
detectedAliases.set(before.owner, after.owner);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
repos.push(result.value);
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
const failure = describeError(result.error);
|
|
1445
|
+
if (!options.tolerateErrors) {
|
|
1446
|
+
hardFailure ??= result.error instanceof LoomError ? result.error : new LoomError("github_error", failure.message);
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
const retained = previous.get(key);
|
|
1450
|
+
if (retained)
|
|
1451
|
+
repos.push(structuredClone(retained));
|
|
1452
|
+
errors.push({
|
|
1453
|
+
repo: key,
|
|
1454
|
+
code: failure.code,
|
|
1455
|
+
message: failure.message,
|
|
1456
|
+
...retained ? { retained: true } : {}
|
|
1457
|
+
});
|
|
1458
|
+
options.logger?.("repo failed; recorded", {
|
|
1459
|
+
repo: requested,
|
|
1460
|
+
code: failure.code,
|
|
1461
|
+
retained: Boolean(retained)
|
|
1462
|
+
});
|
|
1463
|
+
});
|
|
1464
|
+
if (hardFailure)
|
|
1465
|
+
throw hardFailure;
|
|
1466
|
+
const collect = options.collect;
|
|
1467
|
+
const collectSource = collect && (collect.readme || collect.branches || collect.commitComments || collect.issueComments || collect.workflows) ? {
|
|
1468
|
+
readme: collect.readme,
|
|
1469
|
+
branches: collect.branches,
|
|
1470
|
+
extraBranches: [...collect.extraBranches].sort(),
|
|
1471
|
+
branchLimit: collect.branchLimit,
|
|
1472
|
+
commitComments: collect.commitComments,
|
|
1473
|
+
commitCommentLimit: collect.commitCommentLimit,
|
|
1474
|
+
issueComments: collect.issueComments,
|
|
1475
|
+
issueCommentLimit: collect.issueCommentLimit,
|
|
1476
|
+
workflows: collect.workflows,
|
|
1477
|
+
workflowLimit: collect.workflowLimit,
|
|
1478
|
+
ciRuns: collect.ciRuns
|
|
1479
|
+
} : undefined;
|
|
1480
|
+
const mergedOwnerAliases = { ...options.ownerAliases ?? {} };
|
|
1481
|
+
for (const [from, to] of detectedAliases) {
|
|
1482
|
+
if (!(from.toLowerCase() in mergedOwnerAliases))
|
|
1483
|
+
mergedOwnerAliases[from] = to;
|
|
1484
|
+
}
|
|
1485
|
+
return {
|
|
1486
|
+
schema: SNAPSHOT_SCHEMA,
|
|
1487
|
+
source: {
|
|
1488
|
+
kind: "github",
|
|
1489
|
+
api: options.client.baseUrl,
|
|
1490
|
+
repos: requests,
|
|
1491
|
+
releases: options.releases ?? 0,
|
|
1492
|
+
includeLatestCommit: options.includeLatestCommit !== false,
|
|
1493
|
+
...Object.keys(mergedOwnerAliases).length > 0 ? {
|
|
1494
|
+
ownerAliases: Object.entries(mergedOwnerAliases).map(([from, to]) => ({ from, to })).sort((a, b) => a.from.toLowerCase() < b.from.toLowerCase() ? -1 : 1)
|
|
1495
|
+
} : {},
|
|
1496
|
+
...options.identity ? { identity: options.identity } : {},
|
|
1497
|
+
...collectSource ? { collect: collectSource } : {},
|
|
1498
|
+
...options.discovery ? { discovery: options.discovery } : {}
|
|
1499
|
+
},
|
|
1500
|
+
repos,
|
|
1501
|
+
errors
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
// src/github/discovery.ts
|
|
1506
|
+
function record2(value) {
|
|
1507
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1508
|
+
}
|
|
1509
|
+
function skipReason(value, owner, config) {
|
|
1510
|
+
const raw = record2(value);
|
|
1511
|
+
if (!raw)
|
|
1512
|
+
return { fullName: null, reason: "invalid" };
|
|
1513
|
+
const fullName = raw["full_name"];
|
|
1514
|
+
if (typeof fullName !== "string" || !isRepoName(fullName))
|
|
1515
|
+
return { fullName: null, reason: "invalid" };
|
|
1516
|
+
if (raw["private"] === true)
|
|
1517
|
+
return { fullName, reason: "not-public" };
|
|
1518
|
+
const visibility = raw["visibility"];
|
|
1519
|
+
if (typeof visibility === "string" && visibility !== "public") {
|
|
1520
|
+
return { fullName, reason: "not-public" };
|
|
1521
|
+
}
|
|
1522
|
+
const ownerRecord = record2(raw["owner"]);
|
|
1523
|
+
const login = ownerRecord && typeof ownerRecord["login"] === "string" ? ownerRecord["login"] : null;
|
|
1524
|
+
const listedOwner = fullName.slice(0, fullName.indexOf("/"));
|
|
1525
|
+
if (repoKey(login ?? listedOwner) !== repoKey(owner))
|
|
1526
|
+
return { fullName, reason: "wrong-owner" };
|
|
1527
|
+
if (raw["archived"] === true && !config.includeArchived)
|
|
1528
|
+
return { fullName, reason: "archived" };
|
|
1529
|
+
if (raw["fork"] === true && !config.includeForks)
|
|
1530
|
+
return { fullName, reason: "fork" };
|
|
1531
|
+
if (config.exclude.some((pattern) => repoGlobMatches(pattern, fullName))) {
|
|
1532
|
+
return { fullName, reason: "excluded" };
|
|
1533
|
+
}
|
|
1534
|
+
if (config.include.length > 0 && !config.include.some((pattern) => repoGlobMatches(pattern, fullName))) {
|
|
1535
|
+
return { fullName, reason: "not-included" };
|
|
1536
|
+
}
|
|
1537
|
+
return { fullName, reason: null };
|
|
1538
|
+
}
|
|
1539
|
+
async function ownerIdentity(client, owner, ownerAliases) {
|
|
1540
|
+
let requested = owner;
|
|
1541
|
+
let candidate = owner;
|
|
1542
|
+
if (owner.toLowerCase() === "me") {
|
|
1543
|
+
const self = await client.get("/user");
|
|
1544
|
+
const login = record2(self.body)?.["login"];
|
|
1545
|
+
if (typeof login !== "string" || !login) {
|
|
1546
|
+
throw new LoomError("github_error", "GET /user did not return a login", { owner });
|
|
1547
|
+
}
|
|
1548
|
+
candidate = login;
|
|
1549
|
+
} else {
|
|
1550
|
+
candidate = resolveOwnerAlias(owner, ownerAliases);
|
|
1551
|
+
}
|
|
1552
|
+
let response;
|
|
1553
|
+
try {
|
|
1554
|
+
response = await client.get(`/users/${encodeURIComponent(candidate)}`);
|
|
1555
|
+
} catch (error) {
|
|
1556
|
+
if (error instanceof LoomError && error.detail["status"] === 404) {
|
|
1557
|
+
throw new LoomError("github_error", `owner ${requested} no longer exists; add ownerAliases["${requested}"] = "<current login>"`, { owner: requested, canonical: candidate });
|
|
1558
|
+
}
|
|
1559
|
+
throw error;
|
|
1560
|
+
}
|
|
1561
|
+
const body = record2(response.body);
|
|
1562
|
+
if (!body) {
|
|
1563
|
+
throw new LoomError("github_error", `owner metadata for ${candidate} is not an object`, { owner: candidate });
|
|
1564
|
+
}
|
|
1565
|
+
const login = typeof body["login"] === "string" && body["login"].length > 0 ? body["login"] : candidate;
|
|
1566
|
+
const type = body["type"];
|
|
1567
|
+
const kind = type === "Organization" ? "orgs" : "users";
|
|
1568
|
+
const alias = requested.toLowerCase() !== "me" && requested.toLowerCase() !== login.toLowerCase() ? { from: requested, to: login } : null;
|
|
1569
|
+
return { login, kind, alias };
|
|
1570
|
+
}
|
|
1571
|
+
async function discoverRepositories(options) {
|
|
1572
|
+
const { client, config } = options;
|
|
1573
|
+
const configuredAliases = options.ownerAliases ?? {};
|
|
1574
|
+
const counts = {
|
|
1575
|
+
selected: 0,
|
|
1576
|
+
"not-public": 0,
|
|
1577
|
+
archived: 0,
|
|
1578
|
+
fork: 0,
|
|
1579
|
+
excluded: 0,
|
|
1580
|
+
"not-included": 0,
|
|
1581
|
+
invalid: 0,
|
|
1582
|
+
"wrong-owner": 0
|
|
1583
|
+
};
|
|
1584
|
+
const selected = [];
|
|
1585
|
+
const canonicalOwners = [];
|
|
1586
|
+
const aliases = new Map;
|
|
1587
|
+
let identity = null;
|
|
1588
|
+
for (const owner of config.owners) {
|
|
1589
|
+
const resolved = await ownerIdentity(client, owner, configuredAliases);
|
|
1590
|
+
if (owner.toLowerCase() === "me")
|
|
1591
|
+
identity = resolved.login;
|
|
1592
|
+
if (resolved.alias)
|
|
1593
|
+
aliases.set(resolved.alias.from.toLowerCase(), resolved.alias);
|
|
1594
|
+
canonicalOwners.push(resolved.login);
|
|
1595
|
+
const listing = await client.getAll(`/${resolved.kind}/${encodeURIComponent(resolved.login)}/repos?type=public`);
|
|
1596
|
+
for (const entry of listing.items) {
|
|
1597
|
+
const verdict = skipReason(entry, resolved.login, config);
|
|
1598
|
+
if (verdict.reason !== null || verdict.fullName === null) {
|
|
1599
|
+
counts[verdict.reason ?? "invalid"] += 1;
|
|
1600
|
+
continue;
|
|
1601
|
+
}
|
|
1602
|
+
selected.push(verdict.fullName);
|
|
1603
|
+
}
|
|
1604
|
+
options.logger?.("discovery owner scanned", {
|
|
1605
|
+
owner: resolved.login,
|
|
1606
|
+
kind: resolved.kind,
|
|
1607
|
+
listed: listing.items.length,
|
|
1608
|
+
pages: listing.pages,
|
|
1609
|
+
notModified: listing.notModified
|
|
1610
|
+
});
|
|
1611
|
+
}
|
|
1612
|
+
const unique = new Map;
|
|
1613
|
+
for (const repo of selected) {
|
|
1614
|
+
const key = repoKey(repo);
|
|
1615
|
+
if (!unique.has(key))
|
|
1616
|
+
unique.set(key, repo);
|
|
1617
|
+
}
|
|
1618
|
+
const repos = [...unique.values()].sort((a, b) => {
|
|
1619
|
+
const left = a.toLowerCase();
|
|
1620
|
+
const right = b.toLowerCase();
|
|
1621
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
1622
|
+
});
|
|
1623
|
+
counts.selected = repos.length;
|
|
1624
|
+
options.logger?.("discovery complete", { ...counts });
|
|
1625
|
+
return {
|
|
1626
|
+
repos,
|
|
1627
|
+
owners: [...new Set(canonicalOwners.map((owner) => owner.toLowerCase()))].sort(),
|
|
1628
|
+
ownerAliases: [...aliases.values()].sort((a, b) => a.from.toLowerCase() < b.from.toLowerCase() ? -1 : a.from.toLowerCase() > b.from.toLowerCase() ? 1 : 0),
|
|
1629
|
+
identity,
|
|
1630
|
+
counts
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
// src/version.ts
|
|
1635
|
+
var VERSION = "1.0.0";
|
|
1636
|
+
var USER_AGENT = `loom-sync/${VERSION} (+https://github.com/Sifr-Dev/Loom)`;
|
|
1637
|
+
|
|
1638
|
+
// src/github/client.ts
|
|
1639
|
+
var API_VERSION = "2022-11-28";
|
|
1640
|
+
var DEFAULT_USER_AGENT = USER_AGENT;
|
|
1641
|
+
function integer(value) {
|
|
1642
|
+
if (value === null)
|
|
1643
|
+
return null;
|
|
1644
|
+
const parsed = Number.parseInt(value, 10);
|
|
1645
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1646
|
+
}
|
|
1647
|
+
function parseRateLimit(headers, nowMs = Date.now()) {
|
|
1648
|
+
const reset = integer(headers.get("x-ratelimit-reset"));
|
|
1649
|
+
const retryAfterRaw = headers.get("retry-after");
|
|
1650
|
+
let retryAfterSeconds = null;
|
|
1651
|
+
if (retryAfterRaw !== null) {
|
|
1652
|
+
const seconds = Number.parseInt(retryAfterRaw, 10);
|
|
1653
|
+
if (Number.isFinite(seconds) && String(seconds) === retryAfterRaw.trim()) {
|
|
1654
|
+
retryAfterSeconds = Math.max(0, seconds);
|
|
1655
|
+
} else {
|
|
1656
|
+
const dateMs = Date.parse(retryAfterRaw);
|
|
1657
|
+
if (Number.isFinite(dateMs))
|
|
1658
|
+
retryAfterSeconds = Math.max(0, Math.ceil((dateMs - nowMs) / 1000));
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
return {
|
|
1662
|
+
limit: integer(headers.get("x-ratelimit-limit")),
|
|
1663
|
+
remaining: integer(headers.get("x-ratelimit-remaining")),
|
|
1664
|
+
used: integer(headers.get("x-ratelimit-used")),
|
|
1665
|
+
resetAt: reset === null ? null : new Date(reset * 1000).toISOString(),
|
|
1666
|
+
retryAfterSeconds
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
function nextLink(header, baseUrl) {
|
|
1670
|
+
if (!header)
|
|
1671
|
+
return null;
|
|
1672
|
+
for (const part of header.split(",")) {
|
|
1673
|
+
const match = /<([^>]+)>\s*;\s*rel="?([a-z]+)"?/.exec(part.trim());
|
|
1674
|
+
if (match && match[2] === "next" && match[1]) {
|
|
1675
|
+
try {
|
|
1676
|
+
return new URL(match[1], baseUrl).toString();
|
|
1677
|
+
} catch {
|
|
1678
|
+
return null;
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
class GitHubClient {
|
|
1686
|
+
baseUrl;
|
|
1687
|
+
#token;
|
|
1688
|
+
#userAgent;
|
|
1689
|
+
#cache;
|
|
1690
|
+
#fetch;
|
|
1691
|
+
#sleep;
|
|
1692
|
+
#now;
|
|
1693
|
+
#maxRetries;
|
|
1694
|
+
#retryBaseMs;
|
|
1695
|
+
#retryMaxMs;
|
|
1696
|
+
#jitter;
|
|
1697
|
+
#random;
|
|
1698
|
+
#maxRateLimitWaitMs;
|
|
1699
|
+
#rateLimitReserve;
|
|
1700
|
+
#requestTimeoutMs;
|
|
1701
|
+
#perPage;
|
|
1702
|
+
#maxPages;
|
|
1703
|
+
#signal;
|
|
1704
|
+
#logger;
|
|
1705
|
+
#requests = 0;
|
|
1706
|
+
#notModified = 0;
|
|
1707
|
+
#retries = 0;
|
|
1708
|
+
#rateLimitWaits = 0;
|
|
1709
|
+
#waitMs = 0;
|
|
1710
|
+
#lastRateLimit = null;
|
|
1711
|
+
#statuses = {};
|
|
1712
|
+
constructor(options = {}) {
|
|
1713
|
+
this.baseUrl = (options.baseUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
1714
|
+
this.#token = options.token && options.token.length > 0 ? options.token : null;
|
|
1715
|
+
this.#userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
|
|
1716
|
+
this.#cache = options.cache ?? { get: () => {
|
|
1717
|
+
return;
|
|
1718
|
+
}, set: () => {}, save: async () => {}, size: () => 0 };
|
|
1719
|
+
this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
1720
|
+
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1721
|
+
this.#now = options.now ?? (() => Date.now());
|
|
1722
|
+
this.#maxRetries = Math.max(0, options.maxRetries ?? 4);
|
|
1723
|
+
this.#retryBaseMs = options.retryBaseMs ?? 100;
|
|
1724
|
+
this.#retryMaxMs = options.retryMaxMs ?? 2000;
|
|
1725
|
+
this.#jitter = options.jitter ?? true;
|
|
1726
|
+
this.#random = options.random ?? Math.random;
|
|
1727
|
+
this.#maxRateLimitWaitMs = options.maxRateLimitWaitMs ?? 60000;
|
|
1728
|
+
this.#rateLimitReserve = options.rateLimitReserve ?? 0;
|
|
1729
|
+
this.#requestTimeoutMs = options.requestTimeoutMs ?? 15000;
|
|
1730
|
+
this.#perPage = options.perPage ?? 100;
|
|
1731
|
+
this.#maxPages = options.maxPages ?? 20;
|
|
1732
|
+
this.#signal = options.signal;
|
|
1733
|
+
this.#logger = options.logger ?? (() => {});
|
|
1734
|
+
}
|
|
1735
|
+
get stats() {
|
|
1736
|
+
return {
|
|
1737
|
+
requests: this.#requests,
|
|
1738
|
+
notModified: this.#notModified,
|
|
1739
|
+
retries: this.#retries,
|
|
1740
|
+
rateLimitWaits: this.#rateLimitWaits,
|
|
1741
|
+
waitMs: this.#waitMs,
|
|
1742
|
+
lastRateLimit: this.#lastRateLimit,
|
|
1743
|
+
statuses: { ...this.#statuses }
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
url(pathOrUrl) {
|
|
1747
|
+
if (/^https?:\/\//.test(pathOrUrl))
|
|
1748
|
+
return pathOrUrl;
|
|
1749
|
+
const path = pathOrUrl.startsWith("/") ? pathOrUrl : `/${pathOrUrl}`;
|
|
1750
|
+
return `${this.baseUrl}${path}`;
|
|
1751
|
+
}
|
|
1752
|
+
#headers(url) {
|
|
1753
|
+
const headers = new Headers({
|
|
1754
|
+
accept: "application/vnd.github+json",
|
|
1755
|
+
"x-github-api-version": API_VERSION,
|
|
1756
|
+
"user-agent": this.#userAgent
|
|
1757
|
+
});
|
|
1758
|
+
if (this.#token)
|
|
1759
|
+
headers.set("authorization", `Bearer ${this.#token}`);
|
|
1760
|
+
const cached = this.#cache.get(url);
|
|
1761
|
+
if (cached)
|
|
1762
|
+
headers.set("if-none-match", cached.etag);
|
|
1763
|
+
return headers;
|
|
1764
|
+
}
|
|
1765
|
+
#backoff(attempt) {
|
|
1766
|
+
const ceiling = Math.min(this.#retryMaxMs, this.#retryBaseMs * 2 ** attempt);
|
|
1767
|
+
if (!this.#jitter)
|
|
1768
|
+
return ceiling;
|
|
1769
|
+
return Math.max(0, Math.floor(this.#random() * ceiling));
|
|
1770
|
+
}
|
|
1771
|
+
#rateLimitWaitMs(response) {
|
|
1772
|
+
const rate = parseRateLimit(response.headers, this.#now());
|
|
1773
|
+
this.#lastRateLimit = rate;
|
|
1774
|
+
const retryAfterMs = rate.retryAfterSeconds === null ? null : rate.retryAfterSeconds * 1000;
|
|
1775
|
+
const resetMs = rate.resetAt === null ? null : Math.max(0, Date.parse(rate.resetAt) - this.#now());
|
|
1776
|
+
if (response.status === 429) {
|
|
1777
|
+
return retryAfterMs ?? resetMs ?? this.#backoff(0);
|
|
1778
|
+
}
|
|
1779
|
+
if (response.status === 403) {
|
|
1780
|
+
if (rate.remaining === 0)
|
|
1781
|
+
return resetMs ?? retryAfterMs ?? null;
|
|
1782
|
+
if (retryAfterMs !== null)
|
|
1783
|
+
return retryAfterMs;
|
|
1784
|
+
if (rate.remaining === null && resetMs !== null)
|
|
1785
|
+
return resetMs;
|
|
1786
|
+
}
|
|
1787
|
+
return null;
|
|
1788
|
+
}
|
|
1789
|
+
async#wait(ms, signal) {
|
|
1790
|
+
throwIfAborted(signal);
|
|
1791
|
+
if (ms <= 0)
|
|
1792
|
+
return;
|
|
1793
|
+
this.#waitMs += ms;
|
|
1794
|
+
if (!signal) {
|
|
1795
|
+
await this.#sleep(ms);
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
await new Promise((resolve, reject) => {
|
|
1799
|
+
const onAbort = () => {
|
|
1800
|
+
cleanup();
|
|
1801
|
+
reject(new CancelledError("cancelled while waiting"));
|
|
1802
|
+
};
|
|
1803
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
1804
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1805
|
+
this.#sleep(ms).then(() => {
|
|
1806
|
+
cleanup();
|
|
1807
|
+
resolve();
|
|
1808
|
+
}, (error) => {
|
|
1809
|
+
cleanup();
|
|
1810
|
+
reject(error);
|
|
1811
|
+
});
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
async#awaitBudget(signal) {
|
|
1815
|
+
const rate = this.#lastRateLimit;
|
|
1816
|
+
if (!rate || rate.remaining === null || rate.remaining > this.#rateLimitReserve)
|
|
1817
|
+
return;
|
|
1818
|
+
if (rate.resetAt === null)
|
|
1819
|
+
return;
|
|
1820
|
+
const waitMs = Math.max(0, Date.parse(rate.resetAt) - this.#now());
|
|
1821
|
+
if (waitMs <= 0)
|
|
1822
|
+
return;
|
|
1823
|
+
if (waitMs > this.#maxRateLimitWaitMs) {
|
|
1824
|
+
throw new LoomError("rate_limit_exhausted", "GitHub rate limit exhausted before the next request", {
|
|
1825
|
+
resetAt: rate.resetAt,
|
|
1826
|
+
waitMs,
|
|
1827
|
+
remaining: rate.remaining
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
this.#rateLimitWaits += 1;
|
|
1831
|
+
this.#logger("rate limit: waiting for reset", { waitMs, resetAt: rate.resetAt });
|
|
1832
|
+
await this.#wait(waitMs, signal);
|
|
1833
|
+
}
|
|
1834
|
+
async#http(url, options) {
|
|
1835
|
+
const cached = this.#cache.get(url);
|
|
1836
|
+
let lastError = null;
|
|
1837
|
+
const outer = combineSignals([this.#signal, options.signal]);
|
|
1838
|
+
if (outer?.aborted) {
|
|
1839
|
+
throw new LoomError("cancelled", `GET ${redactUrl(url)} cancelled`, { url: redactUrl(url) });
|
|
1840
|
+
}
|
|
1841
|
+
for (let attempt = 0;attempt <= this.#maxRetries; attempt += 1) {
|
|
1842
|
+
if (outer?.aborted) {
|
|
1843
|
+
throw new LoomError("cancelled", `GET ${redactUrl(url)} cancelled`, { url: redactUrl(url) });
|
|
1844
|
+
}
|
|
1845
|
+
if (attempt > 0)
|
|
1846
|
+
this.#retries += 1;
|
|
1847
|
+
await this.#awaitBudget(outer);
|
|
1848
|
+
let response;
|
|
1849
|
+
try {
|
|
1850
|
+
this.#requests += 1;
|
|
1851
|
+
response = await this.#fetch(url, {
|
|
1852
|
+
method: "GET",
|
|
1853
|
+
headers: this.#headers(url),
|
|
1854
|
+
signal: combineSignals([outer, AbortSignal.timeout(this.#requestTimeoutMs)]),
|
|
1855
|
+
redirect: "follow"
|
|
1856
|
+
});
|
|
1857
|
+
} catch (error) {
|
|
1858
|
+
if (outer?.aborted || error instanceof CancelledError) {
|
|
1859
|
+
throw new LoomError("cancelled", `GET ${redactUrl(url)} cancelled`, { url: redactUrl(url) });
|
|
1860
|
+
}
|
|
1861
|
+
const aborted = error instanceof Error && error.name === "AbortError";
|
|
1862
|
+
lastError = new LoomError("network_error", `GET ${redactUrl(url)} failed${aborted ? " (timeout)" : ""}: ${error.message}`, { url: redactUrl(url), attempt, timeout: aborted });
|
|
1863
|
+
if (attempt < this.#maxRetries) {
|
|
1864
|
+
const wait = this.#backoff(attempt);
|
|
1865
|
+
this.#logger("retry: network error", { url: redactUrl(url), attempt, waitMs: wait });
|
|
1866
|
+
await this.#wait(wait, outer);
|
|
1867
|
+
continue;
|
|
1868
|
+
}
|
|
1869
|
+
throw lastError;
|
|
1870
|
+
}
|
|
1871
|
+
this.#statuses[String(response.status)] = (this.#statuses[String(response.status)] ?? 0) + 1;
|
|
1872
|
+
this.#lastRateLimit = parseRateLimit(response.headers, this.#now());
|
|
1873
|
+
if (response.status === 304) {
|
|
1874
|
+
this.#notModified += 1;
|
|
1875
|
+
const entry = cached;
|
|
1876
|
+
if (!entry && !options.allowUncached304) {
|
|
1877
|
+
throw new LoomError("store_corrupt", "GitHub answered 304 but no cached body exists", {
|
|
1878
|
+
url: redactUrl(url)
|
|
1879
|
+
});
|
|
1880
|
+
}
|
|
1881
|
+
return {
|
|
1882
|
+
status: 304,
|
|
1883
|
+
body: entry?.body ?? null,
|
|
1884
|
+
etag: entry?.etag ?? response.headers.get("etag"),
|
|
1885
|
+
fromCache: true,
|
|
1886
|
+
next: entry?.next ?? null
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
if (response.status >= 200 && response.status < 300) {
|
|
1890
|
+
const text = await response.text();
|
|
1891
|
+
let body = null;
|
|
1892
|
+
if (text.length > 0) {
|
|
1893
|
+
try {
|
|
1894
|
+
body = JSON.parse(text);
|
|
1895
|
+
} catch {
|
|
1896
|
+
throw new LoomError("github_error", `GET ${redactUrl(url)} returned non-JSON`, {
|
|
1897
|
+
url: redactUrl(url),
|
|
1898
|
+
status: response.status
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
const etag = response.headers.get("etag");
|
|
1903
|
+
const next = nextLink(response.headers.get("link"), url);
|
|
1904
|
+
if (etag) {
|
|
1905
|
+
this.#cache.set(url, { etag, body, fetchedAt: new Date(this.#now()).toISOString(), next });
|
|
1906
|
+
}
|
|
1907
|
+
return { status: 200, body, etag, fromCache: false, next };
|
|
1908
|
+
}
|
|
1909
|
+
const rateWait = this.#rateLimitWaitMs(response);
|
|
1910
|
+
if (rateWait !== null) {
|
|
1911
|
+
if (rateWait <= this.#maxRateLimitWaitMs && attempt < this.#maxRetries) {
|
|
1912
|
+
this.#rateLimitWaits += 1;
|
|
1913
|
+
this.#logger("retry: rate limited", { url: redactUrl(url), status: response.status, waitMs: rateWait });
|
|
1914
|
+
await this.#wait(rateWait, outer);
|
|
1915
|
+
continue;
|
|
1916
|
+
}
|
|
1917
|
+
throw new LoomError("rate_limit_exhausted", "GitHub rate limit exhausted", {
|
|
1918
|
+
url: redactUrl(url),
|
|
1919
|
+
status: response.status,
|
|
1920
|
+
resetAt: this.#lastRateLimit?.resetAt ?? null,
|
|
1921
|
+
waitMs: rateWait
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
const transient = response.status >= 500 || response.status === 408 || response.status === 425;
|
|
1925
|
+
if (transient && attempt < this.#maxRetries) {
|
|
1926
|
+
const retryAfter = this.#lastRateLimit?.retryAfterSeconds;
|
|
1927
|
+
const wait = retryAfter !== null && retryAfter !== undefined ? retryAfter * 1000 : this.#backoff(attempt);
|
|
1928
|
+
this.#logger("retry: server error", { url: redactUrl(url), status: response.status, waitMs: wait });
|
|
1929
|
+
await this.#wait(wait, outer);
|
|
1930
|
+
continue;
|
|
1931
|
+
}
|
|
1932
|
+
const text = await response.text();
|
|
1933
|
+
let message = text.slice(0, 300);
|
|
1934
|
+
let body = null;
|
|
1935
|
+
try {
|
|
1936
|
+
body = JSON.parse(text);
|
|
1937
|
+
if (body && typeof body === "object" && typeof body.message === "string") {
|
|
1938
|
+
message = body.message;
|
|
1939
|
+
}
|
|
1940
|
+
} catch {}
|
|
1941
|
+
throw new LoomError("github_error", `GET ${redactUrl(url)} failed with ${response.status}: ${message}`, {
|
|
1942
|
+
url: redactUrl(url),
|
|
1943
|
+
status: response.status,
|
|
1944
|
+
rateLimit: this.#lastRateLimit
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
throw lastError ?? new LoomError("github_error", `GET ${redactUrl(url)} failed`, { url: redactUrl(url) });
|
|
1948
|
+
}
|
|
1949
|
+
async get(pathOrUrl, options = {}) {
|
|
1950
|
+
const url = this.url(pathOrUrl);
|
|
1951
|
+
const result = await this.#http(url, options);
|
|
1952
|
+
return result;
|
|
1953
|
+
}
|
|
1954
|
+
async getAll(pathOrUrl, options = {}) {
|
|
1955
|
+
const first = this.url(pathOrUrl);
|
|
1956
|
+
const start = new URL(first);
|
|
1957
|
+
if (!start.searchParams.has("per_page"))
|
|
1958
|
+
start.searchParams.set("per_page", String(this.#perPage));
|
|
1959
|
+
let cursor = start.toString();
|
|
1960
|
+
const seen = new Set;
|
|
1961
|
+
const items = [];
|
|
1962
|
+
let pages = 0;
|
|
1963
|
+
let allNotModified = true;
|
|
1964
|
+
while (cursor !== null) {
|
|
1965
|
+
if (pages >= this.#maxPages) {
|
|
1966
|
+
throw new LoomError("github_error", `pagination exceeded ${this.#maxPages} pages`, { url: redactUrl(first) });
|
|
1967
|
+
}
|
|
1968
|
+
if (seen.has(cursor)) {
|
|
1969
|
+
throw new LoomError("github_error", `pagination loop at ${redactUrl(cursor)}`, { url: redactUrl(cursor) });
|
|
1970
|
+
}
|
|
1971
|
+
seen.add(cursor);
|
|
1972
|
+
const page = await this.#http(cursor, options);
|
|
1973
|
+
pages += 1;
|
|
1974
|
+
if (page.status === 304) {
|
|
1975
|
+
if (Array.isArray(page.body))
|
|
1976
|
+
items.push(...page.body);
|
|
1977
|
+
else
|
|
1978
|
+
allNotModified = false;
|
|
1979
|
+
} else {
|
|
1980
|
+
allNotModified = false;
|
|
1981
|
+
if (!Array.isArray(page.body)) {
|
|
1982
|
+
throw new LoomError("github_error", `expected an array from ${redactUrl(cursor)}`, {
|
|
1983
|
+
url: redactUrl(cursor)
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
items.push(...page.body);
|
|
1987
|
+
}
|
|
1988
|
+
cursor = page.next;
|
|
1989
|
+
}
|
|
1990
|
+
return { items, pages, notModified: allNotModified && pages > 0 };
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
// src/digest.ts
|
|
1994
|
+
init_canonical();
|
|
1995
|
+
|
|
1996
|
+
// src/sha256.ts
|
|
1997
|
+
var K = new Uint32Array([
|
|
1998
|
+
1116352408,
|
|
1999
|
+
1899447441,
|
|
2000
|
+
3049323471,
|
|
2001
|
+
3921009573,
|
|
2002
|
+
961987163,
|
|
2003
|
+
1508970993,
|
|
2004
|
+
2453635748,
|
|
2005
|
+
2870763221,
|
|
2006
|
+
3624381080,
|
|
2007
|
+
310598401,
|
|
2008
|
+
607225278,
|
|
2009
|
+
1426881987,
|
|
2010
|
+
1925078388,
|
|
2011
|
+
2162078206,
|
|
2012
|
+
2614888103,
|
|
2013
|
+
3248222580,
|
|
2014
|
+
3835390401,
|
|
2015
|
+
4022224774,
|
|
2016
|
+
264347078,
|
|
2017
|
+
604807628,
|
|
2018
|
+
770255983,
|
|
2019
|
+
1249150122,
|
|
2020
|
+
1555081692,
|
|
2021
|
+
1996064986,
|
|
2022
|
+
2554220882,
|
|
2023
|
+
2821834349,
|
|
2024
|
+
2952996808,
|
|
2025
|
+
3210313671,
|
|
2026
|
+
3336571891,
|
|
2027
|
+
3584528711,
|
|
2028
|
+
113926993,
|
|
2029
|
+
338241895,
|
|
2030
|
+
666307205,
|
|
2031
|
+
773529912,
|
|
2032
|
+
1294757372,
|
|
2033
|
+
1396182291,
|
|
2034
|
+
1695183700,
|
|
2035
|
+
1986661051,
|
|
2036
|
+
2177026350,
|
|
2037
|
+
2456956037,
|
|
2038
|
+
2730485921,
|
|
2039
|
+
2820302411,
|
|
2040
|
+
3259730800,
|
|
2041
|
+
3345764771,
|
|
2042
|
+
3516065817,
|
|
2043
|
+
3600352804,
|
|
2044
|
+
4094571909,
|
|
2045
|
+
275423344,
|
|
2046
|
+
430227734,
|
|
2047
|
+
506948616,
|
|
2048
|
+
659060556,
|
|
2049
|
+
883997877,
|
|
2050
|
+
958139571,
|
|
2051
|
+
1322822218,
|
|
2052
|
+
1537002063,
|
|
2053
|
+
1747873779,
|
|
2054
|
+
1955562222,
|
|
2055
|
+
2024104815,
|
|
2056
|
+
2227730452,
|
|
2057
|
+
2361852424,
|
|
2058
|
+
2428436474,
|
|
2059
|
+
2756734187,
|
|
2060
|
+
3204031479,
|
|
2061
|
+
3329325298
|
|
2062
|
+
]);
|
|
2063
|
+
function rotr(value, bits) {
|
|
2064
|
+
return value >>> bits | value << 32 - bits;
|
|
2065
|
+
}
|
|
2066
|
+
function sha256Bytes(input) {
|
|
2067
|
+
const length = input.length;
|
|
2068
|
+
const blocks = Math.ceil((length + 9) / 64);
|
|
2069
|
+
const padded = new Uint8Array(blocks * 64);
|
|
2070
|
+
padded.set(input);
|
|
2071
|
+
padded[length] = 128;
|
|
2072
|
+
const view = new DataView(padded.buffer);
|
|
2073
|
+
const bitsHigh = Math.floor(length / 536870912);
|
|
2074
|
+
const bitsLow = length * 8 >>> 0;
|
|
2075
|
+
view.setUint32(padded.length - 8, bitsHigh);
|
|
2076
|
+
view.setUint32(padded.length - 4, bitsLow);
|
|
2077
|
+
const state = new Uint32Array([
|
|
2078
|
+
1779033703,
|
|
2079
|
+
3144134277,
|
|
2080
|
+
1013904242,
|
|
2081
|
+
2773480762,
|
|
2082
|
+
1359893119,
|
|
2083
|
+
2600822924,
|
|
2084
|
+
528734635,
|
|
2085
|
+
1541459225
|
|
2086
|
+
]);
|
|
2087
|
+
const w = new Uint32Array(64);
|
|
2088
|
+
for (let offset = 0;offset < padded.length; offset += 64) {
|
|
2089
|
+
for (let index = 0;index < 16; index += 1)
|
|
2090
|
+
w[index] = view.getUint32(offset + index * 4);
|
|
2091
|
+
for (let index = 16;index < 64; index += 1) {
|
|
2092
|
+
const w15 = w[index - 15];
|
|
2093
|
+
const w2 = w[index - 2];
|
|
2094
|
+
const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ w15 >>> 3;
|
|
2095
|
+
const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ w2 >>> 10;
|
|
2096
|
+
w[index] = w[index - 16] + s0 + w[index - 7] + s1 >>> 0;
|
|
2097
|
+
}
|
|
2098
|
+
let a = state[0];
|
|
2099
|
+
let b = state[1];
|
|
2100
|
+
let c = state[2];
|
|
2101
|
+
let d = state[3];
|
|
2102
|
+
let e = state[4];
|
|
2103
|
+
let f = state[5];
|
|
2104
|
+
let g = state[6];
|
|
2105
|
+
let h = state[7];
|
|
2106
|
+
for (let index = 0;index < 64; index += 1) {
|
|
2107
|
+
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
2108
|
+
const ch = e & f ^ ~e & g;
|
|
2109
|
+
const temp1 = h + s1 + ch + K[index] + w[index] >>> 0;
|
|
2110
|
+
const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
2111
|
+
const maj = a & b ^ a & c ^ b & c;
|
|
2112
|
+
const temp2 = s0 + maj >>> 0;
|
|
2113
|
+
h = g;
|
|
2114
|
+
g = f;
|
|
2115
|
+
f = e;
|
|
2116
|
+
e = d + temp1 >>> 0;
|
|
2117
|
+
d = c;
|
|
2118
|
+
c = b;
|
|
2119
|
+
b = a;
|
|
2120
|
+
a = temp1 + temp2 >>> 0;
|
|
2121
|
+
}
|
|
2122
|
+
state[0] = state[0] + a >>> 0;
|
|
2123
|
+
state[1] = state[1] + b >>> 0;
|
|
2124
|
+
state[2] = state[2] + c >>> 0;
|
|
2125
|
+
state[3] = state[3] + d >>> 0;
|
|
2126
|
+
state[4] = state[4] + e >>> 0;
|
|
2127
|
+
state[5] = state[5] + f >>> 0;
|
|
2128
|
+
state[6] = state[6] + g >>> 0;
|
|
2129
|
+
state[7] = state[7] + h >>> 0;
|
|
2130
|
+
}
|
|
2131
|
+
const digest = new Uint8Array(32);
|
|
2132
|
+
const out = new DataView(digest.buffer);
|
|
2133
|
+
for (let index = 0;index < 8; index += 1)
|
|
2134
|
+
out.setUint32(index * 4, state[index]);
|
|
2135
|
+
return digest;
|
|
2136
|
+
}
|
|
2137
|
+
var HEX = "0123456789abcdef";
|
|
2138
|
+
function sha256Hex(input) {
|
|
2139
|
+
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
2140
|
+
const digest = sha256Bytes(bytes);
|
|
2141
|
+
let hex = "";
|
|
2142
|
+
for (const byte of digest)
|
|
2143
|
+
hex += `${HEX[byte >>> 4] ?? "0"}${HEX[byte & 15] ?? "0"}`;
|
|
2144
|
+
return hex;
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
// src/digest.ts
|
|
2148
|
+
var DIGEST_PREFIX = "sha256:";
|
|
2149
|
+
function digestOf(value) {
|
|
2150
|
+
return `${DIGEST_PREFIX}${sha256Hex(canonicalize(value))}`;
|
|
2151
|
+
}
|
|
2152
|
+
function isDigest(value) {
|
|
2153
|
+
return /^sha256:[0-9a-f]{64}$/.test(value);
|
|
2154
|
+
}
|
|
2155
|
+
function assertDigest(value) {
|
|
2156
|
+
if (!isDigest(value)) {
|
|
2157
|
+
throw new TypeError(`not a Loom digest: ${value}`);
|
|
2158
|
+
}
|
|
2159
|
+
return value;
|
|
2160
|
+
}
|
|
2161
|
+
function digestHex(digest) {
|
|
2162
|
+
return assertDigest(digest).slice(DIGEST_PREFIX.length);
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
// src/snapshot.ts
|
|
2166
|
+
function byCodeUnit(a, b) {
|
|
2167
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
2168
|
+
}
|
|
2169
|
+
function normalizeSnapshot(payload) {
|
|
2170
|
+
const repos = [...payload.repos].map((repo) => ({
|
|
2171
|
+
...repo,
|
|
2172
|
+
topics: [...new Set(repo.topics)].sort(byCodeUnit),
|
|
2173
|
+
releases: [...repo.releases].filter((release) => !release.draft).sort((a, b) => {
|
|
2174
|
+
const left = a.publishedAt ?? "";
|
|
2175
|
+
const right = b.publishedAt ?? "";
|
|
2176
|
+
if (left !== right)
|
|
2177
|
+
return left > right ? -1 : 1;
|
|
2178
|
+
return byCodeUnit(a.tag, b.tag);
|
|
2179
|
+
}),
|
|
2180
|
+
...repo.branches ? {
|
|
2181
|
+
branches: [...repo.branches].sort((a, b) => Number(b.default) - Number(a.default) || byCodeUnit(a.name, b.name))
|
|
2182
|
+
} : {},
|
|
2183
|
+
...repo.commitComments ? {
|
|
2184
|
+
commitComments: [...repo.commitComments].sort((a, b) => byCodeUnit(b.createdAt ?? "", a.createdAt ?? "") || byCodeUnit(String(a.id), String(b.id)))
|
|
2185
|
+
} : {},
|
|
2186
|
+
...repo.issueComments ? {
|
|
2187
|
+
issueComments: [...repo.issueComments].sort((a, b) => byCodeUnit(b.createdAt ?? "", a.createdAt ?? "") || byCodeUnit(String(a.id), String(b.id)))
|
|
2188
|
+
} : {},
|
|
2189
|
+
...repo.workflows ? { workflows: [...repo.workflows].sort((a, b) => byCodeUnit(String(a.id), String(b.id))) } : {}
|
|
2190
|
+
})).sort((a, b) => byCodeUnit(a.id, b.id));
|
|
2191
|
+
const seen = new Set;
|
|
2192
|
+
const unique = repos.filter((repo) => {
|
|
2193
|
+
if (seen.has(repo.id))
|
|
2194
|
+
return false;
|
|
2195
|
+
seen.add(repo.id);
|
|
2196
|
+
return true;
|
|
2197
|
+
});
|
|
2198
|
+
const errors = [...payload.errors].sort((a, b) => byCodeUnit(a.repo, b.repo) || byCodeUnit(a.code, b.code));
|
|
2199
|
+
return {
|
|
2200
|
+
schema: SNAPSHOT_SCHEMA,
|
|
2201
|
+
source: {
|
|
2202
|
+
...payload.source,
|
|
2203
|
+
repos: [...new Set(payload.source.repos.map((repo) => repo.toLowerCase()))].sort(byCodeUnit),
|
|
2204
|
+
...payload.source.ownerAliases ? {
|
|
2205
|
+
ownerAliases: [...new Map(payload.source.ownerAliases.map((entry) => [entry.from.toLowerCase(), entry])).values()].sort((a, b) => byCodeUnit(a.from.toLowerCase(), b.from.toLowerCase()))
|
|
2206
|
+
} : {},
|
|
2207
|
+
...payload.source.discovery ? {
|
|
2208
|
+
discovery: {
|
|
2209
|
+
...payload.source.discovery,
|
|
2210
|
+
owners: [...new Set(payload.source.discovery.owners.map((owner) => owner.toLowerCase()))].sort(byCodeUnit),
|
|
2211
|
+
include: [...new Set(payload.source.discovery.include)].sort(byCodeUnit),
|
|
2212
|
+
exclude: [...new Set(payload.source.discovery.exclude)].sort(byCodeUnit)
|
|
2213
|
+
}
|
|
2214
|
+
} : {}
|
|
2215
|
+
},
|
|
2216
|
+
repos: unique,
|
|
2217
|
+
errors
|
|
2218
|
+
};
|
|
2219
|
+
}
|
|
2220
|
+
function buildSnapshot(payload) {
|
|
2221
|
+
const normalized = normalizeSnapshot(payload);
|
|
2222
|
+
return { payload: normalized, id: digestOf(normalized) };
|
|
2223
|
+
}
|
|
2224
|
+
function snapshotId(payload) {
|
|
2225
|
+
return digestOf(payload);
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
// src/compute.ts
|
|
2229
|
+
function ownerAliasesOf(snapshot) {
|
|
2230
|
+
const out = {};
|
|
2231
|
+
for (const entry of snapshot.payload.source.ownerAliases ?? [])
|
|
2232
|
+
out[entry.from] = entry.to;
|
|
2233
|
+
return out;
|
|
2234
|
+
}
|
|
2235
|
+
function createClient(options, cache, baseUrl, fixture) {
|
|
2236
|
+
return new GitHubClient({
|
|
2237
|
+
baseUrl,
|
|
2238
|
+
token: options.token ?? null,
|
|
2239
|
+
cache,
|
|
2240
|
+
...fixture ? { fetch: fixture.fetch } : options.fetch ? { fetch: options.fetch } : {},
|
|
2241
|
+
...options.sleep ? { sleep: options.sleep } : {},
|
|
2242
|
+
...options.now ? { now: options.now } : {},
|
|
2243
|
+
...options.logger ? { logger: options.logger } : {},
|
|
2244
|
+
...options.signal ? { signal: options.signal } : {}
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
async function computeSnapshot(options) {
|
|
2248
|
+
const explicit = options.config.repos;
|
|
2249
|
+
const discovery = options.config.discovery;
|
|
2250
|
+
if (explicit.length === 0 && discovery.owners.length === 0) {
|
|
2251
|
+
throw new LoomError("config_invalid", "no repositories configured; add repos or discovery.owners to loom.config.json");
|
|
2252
|
+
}
|
|
2253
|
+
const fixture = options.fixture ?? null;
|
|
2254
|
+
const cache = options.cache === null ? new MemoryCache : options.cache ?? new MemoryCache;
|
|
2255
|
+
const client = createClient(options, cache, fixture?.baseUrl ?? options.config.githubBaseUrl, fixture?.transport ?? null);
|
|
2256
|
+
let discovered = [];
|
|
2257
|
+
let discoverySource;
|
|
2258
|
+
let identity = null;
|
|
2259
|
+
const ownerAliases = { ...options.config.ownerAliases };
|
|
2260
|
+
if (discovery.owners.length > 0) {
|
|
2261
|
+
const result = await discoverRepositories({
|
|
2262
|
+
client,
|
|
2263
|
+
config: discovery,
|
|
2264
|
+
ownerAliases,
|
|
2265
|
+
...options.signal ? { signal: options.signal } : {},
|
|
2266
|
+
...options.logger ? { logger: options.logger } : {}
|
|
2267
|
+
});
|
|
2268
|
+
discovered = result.repos;
|
|
2269
|
+
identity = result.identity;
|
|
2270
|
+
for (const alias of result.ownerAliases)
|
|
2271
|
+
ownerAliases[alias.from] = alias.to;
|
|
2272
|
+
discoverySource = {
|
|
2273
|
+
owners: result.owners,
|
|
2274
|
+
include: [...discovery.include].sort(),
|
|
2275
|
+
exclude: [...discovery.exclude].sort(),
|
|
2276
|
+
includeArchived: discovery.includeArchived,
|
|
2277
|
+
includeForks: discovery.includeForks,
|
|
2278
|
+
selected: result.repos.length
|
|
2279
|
+
};
|
|
2280
|
+
}
|
|
2281
|
+
const seen = new Set;
|
|
2282
|
+
const requests = [];
|
|
2283
|
+
const explicitCanonical = explicit.map((repo) => canonicalRepoDisplay(repo, ownerAliases));
|
|
2284
|
+
for (const repo of [...explicitCanonical, ...discovered]) {
|
|
2285
|
+
const key = canonicalRepoKey(repo, ownerAliases);
|
|
2286
|
+
if (seen.has(key))
|
|
2287
|
+
continue;
|
|
2288
|
+
seen.add(key);
|
|
2289
|
+
requests.push(canonicalRepoDisplay(repo, ownerAliases));
|
|
2290
|
+
}
|
|
2291
|
+
if (requests.length === 0) {
|
|
2292
|
+
throw new LoomError("config_invalid", "discovery selected no repositories; refusing an empty snapshot");
|
|
2293
|
+
}
|
|
2294
|
+
const payload = await collectSnapshot({
|
|
2295
|
+
client,
|
|
2296
|
+
repos: requests,
|
|
2297
|
+
releases: options.config.releases,
|
|
2298
|
+
includeLatestCommit: options.config.includeLatestCommit,
|
|
2299
|
+
collect: options.config.collect,
|
|
2300
|
+
ownerAliases,
|
|
2301
|
+
...identity ? { identity } : {},
|
|
2302
|
+
...options.tolerateErrors ? { tolerateErrors: true } : {},
|
|
2303
|
+
...options.previous ? { previous: options.previous } : {},
|
|
2304
|
+
...options.concurrency ? { concurrency: options.concurrency } : {},
|
|
2305
|
+
...options.signal ? { signal: options.signal } : {},
|
|
2306
|
+
...discoverySource ? { discovery: discoverySource } : {},
|
|
2307
|
+
...options.logger ? { logger: options.logger } : {}
|
|
2308
|
+
});
|
|
2309
|
+
const snapshot = buildSnapshot(payload);
|
|
2310
|
+
return {
|
|
2311
|
+
snapshot,
|
|
2312
|
+
payload: snapshot.payload,
|
|
2313
|
+
client,
|
|
2314
|
+
fixture: fixture?.transport ?? null,
|
|
2315
|
+
cache,
|
|
2316
|
+
stats: snapshotStats(snapshot.payload)
|
|
2317
|
+
};
|
|
2318
|
+
}
|
|
2319
|
+
|
|
2320
|
+
// src/diff.ts
|
|
2321
|
+
init_canonical();
|
|
2322
|
+
|
|
2323
|
+
// src/entities.ts
|
|
2324
|
+
function repoFields(repo) {
|
|
2325
|
+
const {
|
|
2326
|
+
releases: _releases,
|
|
2327
|
+
head: _head,
|
|
2328
|
+
readme: _readme,
|
|
2329
|
+
branches: _branches,
|
|
2330
|
+
commitComments: _commitComments,
|
|
2331
|
+
issueComments: _issueComments,
|
|
2332
|
+
workflows: _workflows,
|
|
2333
|
+
ci: _ci,
|
|
2334
|
+
...fields
|
|
2335
|
+
} = repo;
|
|
2336
|
+
return fields;
|
|
2337
|
+
}
|
|
2338
|
+
function repoEntityId(repo) {
|
|
2339
|
+
return `repo:${repo.toLowerCase()}`;
|
|
2340
|
+
}
|
|
2341
|
+
function releaseEntityId(repo, tag) {
|
|
2342
|
+
return `release:${repo.toLowerCase()}@${tag}`;
|
|
2343
|
+
}
|
|
2344
|
+
function headEntityId(repo) {
|
|
2345
|
+
return `head:${repo.toLowerCase()}`;
|
|
2346
|
+
}
|
|
2347
|
+
function readmeEntityId(repo) {
|
|
2348
|
+
return `readme:${repo.toLowerCase()}`;
|
|
2349
|
+
}
|
|
2350
|
+
function branchEntityId(repo, branch) {
|
|
2351
|
+
return `branch:${repo.toLowerCase()}@${branch}`;
|
|
2352
|
+
}
|
|
2353
|
+
function commitCommentEntityId(repo, id) {
|
|
2354
|
+
return `commit-comment:${repo.toLowerCase()}@${id}`;
|
|
2355
|
+
}
|
|
2356
|
+
function issueCommentEntityId(repo, id) {
|
|
2357
|
+
return `issue-comment:${repo.toLowerCase()}@${id}`;
|
|
2358
|
+
}
|
|
2359
|
+
function workflowEntityId(repo, id) {
|
|
2360
|
+
return `workflow:${repo.toLowerCase()}@${id}`;
|
|
2361
|
+
}
|
|
2362
|
+
function ciEntityId(repo) {
|
|
2363
|
+
return `ci:${repo.toLowerCase()}`;
|
|
2364
|
+
}
|
|
2365
|
+
var KIND_BY_PREFIX = [
|
|
2366
|
+
["commit-comment:", "commit-comment"],
|
|
2367
|
+
["issue-comment:", "issue-comment"],
|
|
2368
|
+
["release:", "release"],
|
|
2369
|
+
["branch:", "branch"],
|
|
2370
|
+
["workflow:", "workflow"],
|
|
2371
|
+
["readme:", "readme"],
|
|
2372
|
+
["head:", "head"],
|
|
2373
|
+
["repo:", "repo"],
|
|
2374
|
+
["ci:", "ci"]
|
|
2375
|
+
];
|
|
2376
|
+
function entityKindOf(id) {
|
|
2377
|
+
for (const [prefix, kind] of KIND_BY_PREFIX) {
|
|
2378
|
+
if (id.startsWith(prefix))
|
|
2379
|
+
return kind;
|
|
2380
|
+
}
|
|
2381
|
+
return null;
|
|
2382
|
+
}
|
|
2383
|
+
var AT_KINDS = new Set(["release", "branch", "commit-comment", "issue-comment", "workflow"]);
|
|
2384
|
+
function repoOfEntityId(id) {
|
|
2385
|
+
const kind = entityKindOf(id);
|
|
2386
|
+
if (kind === null)
|
|
2387
|
+
return null;
|
|
2388
|
+
const rest = id.slice(id.indexOf(":") + 1);
|
|
2389
|
+
if (AT_KINDS.has(kind)) {
|
|
2390
|
+
const at = rest.lastIndexOf("@");
|
|
2391
|
+
return at === -1 ? rest : rest.slice(0, at);
|
|
2392
|
+
}
|
|
2393
|
+
return rest;
|
|
2394
|
+
}
|
|
2395
|
+
function entity(kind, id, repo, fields) {
|
|
2396
|
+
return { id, kind, repo, fingerprint: digestOf(fields), fields };
|
|
2397
|
+
}
|
|
2398
|
+
function entitiesFromSnapshot(payload) {
|
|
2399
|
+
const out = new Map;
|
|
2400
|
+
for (const repo of payload.repos) {
|
|
2401
|
+
const meta = repoFields(repo);
|
|
2402
|
+
out.set(repoEntityId(repo.id), entity("repo", repoEntityId(repo.id), repo.id, meta));
|
|
2403
|
+
for (const release of repo.releases) {
|
|
2404
|
+
out.set(releaseEntityId(repo.id, release.tag), entity("release", releaseEntityId(repo.id, release.tag), repo.id, {
|
|
2405
|
+
repo: repo.id,
|
|
2406
|
+
...release
|
|
2407
|
+
}));
|
|
2408
|
+
}
|
|
2409
|
+
if (repo.head) {
|
|
2410
|
+
out.set(headEntityId(repo.id), entity("head", headEntityId(repo.id), repo.id, {
|
|
2411
|
+
repo: repo.id,
|
|
2412
|
+
...repo.head
|
|
2413
|
+
}));
|
|
2414
|
+
}
|
|
2415
|
+
if (repo.readme) {
|
|
2416
|
+
out.set(readmeEntityId(repo.id), entity("readme", readmeEntityId(repo.id), repo.id, { repo: repo.id, ...repo.readme }));
|
|
2417
|
+
}
|
|
2418
|
+
for (const branch of repo.branches ?? []) {
|
|
2419
|
+
out.set(branchEntityId(repo.id, branch.name), entity("branch", branchEntityId(repo.id, branch.name), repo.id, {
|
|
2420
|
+
repo: repo.id,
|
|
2421
|
+
...branch
|
|
2422
|
+
}));
|
|
2423
|
+
}
|
|
2424
|
+
for (const comment of repo.commitComments ?? []) {
|
|
2425
|
+
out.set(commitCommentEntityId(repo.id, comment.id), entity("commit-comment", commitCommentEntityId(repo.id, comment.id), repo.id, {
|
|
2426
|
+
repo: repo.id,
|
|
2427
|
+
...comment
|
|
2428
|
+
}));
|
|
2429
|
+
}
|
|
2430
|
+
for (const comment of repo.issueComments ?? []) {
|
|
2431
|
+
out.set(issueCommentEntityId(repo.id, comment.id), entity("issue-comment", issueCommentEntityId(repo.id, comment.id), repo.id, {
|
|
2432
|
+
repo: repo.id,
|
|
2433
|
+
...comment
|
|
2434
|
+
}));
|
|
2435
|
+
}
|
|
2436
|
+
for (const workflow of repo.workflows ?? []) {
|
|
2437
|
+
out.set(workflowEntityId(repo.id, workflow.id), entity("workflow", workflowEntityId(repo.id, workflow.id), repo.id, {
|
|
2438
|
+
repo: repo.id,
|
|
2439
|
+
...workflow
|
|
2440
|
+
}));
|
|
2441
|
+
}
|
|
2442
|
+
if (repo.ci) {
|
|
2443
|
+
out.set(ciEntityId(repo.id), entity("ci", ciEntityId(repo.id), repo.id, { repo: repo.id, ...repo.ci }));
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
return out;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// src/diff.ts
|
|
2450
|
+
var DIFF_SCHEMA = "loom/diff@1";
|
|
2451
|
+
function normalizeAliases(aliases, ownerAliases) {
|
|
2452
|
+
const map = new Map;
|
|
2453
|
+
for (const [from, to] of Object.entries(aliases)) {
|
|
2454
|
+
map.set(canonicalRepoKey(from, ownerAliases), canonicalRepoKey(to, ownerAliases));
|
|
2455
|
+
}
|
|
2456
|
+
return map;
|
|
2457
|
+
}
|
|
2458
|
+
function resolveRepoAlias(repo, aliases, ownerAliases = {}) {
|
|
2459
|
+
const map = normalizeAliases(aliases, ownerAliases);
|
|
2460
|
+
let current = canonicalRepoKey(repo, ownerAliases);
|
|
2461
|
+
const seen = new Set([current]);
|
|
2462
|
+
for (let depth = 0;depth < 8; depth += 1) {
|
|
2463
|
+
const next = map.get(current);
|
|
2464
|
+
if (!next || seen.has(next))
|
|
2465
|
+
return current;
|
|
2466
|
+
seen.add(next);
|
|
2467
|
+
current = next;
|
|
2468
|
+
}
|
|
2469
|
+
return current;
|
|
2470
|
+
}
|
|
2471
|
+
function rewriteEntityId(id, aliases, ownerAliases = {}) {
|
|
2472
|
+
const repo = repoOfEntityId(id);
|
|
2473
|
+
if (repo === null)
|
|
2474
|
+
return id;
|
|
2475
|
+
const resolved = resolveRepoAlias(repo, aliases, ownerAliases);
|
|
2476
|
+
if (resolved === repo)
|
|
2477
|
+
return id;
|
|
2478
|
+
const colon = id.indexOf(":");
|
|
2479
|
+
const rest = id.slice(colon + 1);
|
|
2480
|
+
const at = rest.lastIndexOf("@");
|
|
2481
|
+
return at === -1 ? `${id.slice(0, colon)}:${resolved}` : `${id.slice(0, colon)}:${resolved}@${rest.slice(at + 1)}`;
|
|
2482
|
+
}
|
|
2483
|
+
function changedFields(before, after) {
|
|
2484
|
+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
2485
|
+
const changed = [];
|
|
2486
|
+
for (const key of keys) {
|
|
2487
|
+
const left = key in before ? canonicalize(before[key]) : "";
|
|
2488
|
+
const right = key in after ? canonicalize(after[key]) : "";
|
|
2489
|
+
if (left !== right)
|
|
2490
|
+
changed.push(key);
|
|
2491
|
+
}
|
|
2492
|
+
return changed.sort(byCodeUnit);
|
|
2493
|
+
}
|
|
2494
|
+
function eventFor(entity, kind, previous) {
|
|
2495
|
+
const base = {
|
|
2496
|
+
id: entity.id,
|
|
2497
|
+
kind,
|
|
2498
|
+
entity: entity.kind,
|
|
2499
|
+
repo: entity.repo,
|
|
2500
|
+
fingerprint: kind === "removed" ? null : entity.fingerprint,
|
|
2501
|
+
previousFingerprint: kind === "added" ? null : kind === "removed" ? entity.fingerprint : previous?.fingerprint ?? null
|
|
2502
|
+
};
|
|
2503
|
+
if (kind === "updated" && previous) {
|
|
2504
|
+
return {
|
|
2505
|
+
...base,
|
|
2506
|
+
fields: changedFields(previous.fields, entity.fields),
|
|
2507
|
+
...previous.id !== entity.id ? { previousId: previous.id } : {}
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
return { ...base, fields: [] };
|
|
2511
|
+
}
|
|
2512
|
+
function compareEvents(a, b) {
|
|
2513
|
+
return byCodeUnit(a.id, b.id) || byCodeUnit(a.kind, b.kind);
|
|
2514
|
+
}
|
|
2515
|
+
function diffSnapshots(from, to, options = {}) {
|
|
2516
|
+
const aliases = options.aliases ?? {};
|
|
2517
|
+
const ownerAliases = options.ownerAliases ?? {};
|
|
2518
|
+
const before = from === null ? new Map : entitiesFromSnapshot(from.payload);
|
|
2519
|
+
const after = entitiesFromSnapshot(to.payload);
|
|
2520
|
+
const events = [];
|
|
2521
|
+
const renames = [];
|
|
2522
|
+
const pairedOldIds = new Set;
|
|
2523
|
+
const addedIds = [...after.keys()].filter((id) => !before.has(id)).sort(byCodeUnit);
|
|
2524
|
+
const removedIds = [...before.keys()].filter((id) => !after.has(id)).sort(byCodeUnit);
|
|
2525
|
+
const pairedNewIds = new Set;
|
|
2526
|
+
for (const oldId of removedIds) {
|
|
2527
|
+
const rewritten = rewriteEntityId(oldId, aliases, ownerAliases);
|
|
2528
|
+
if (rewritten === oldId || !after.has(rewritten) || before.has(rewritten))
|
|
2529
|
+
continue;
|
|
2530
|
+
if (pairedNewIds.has(rewritten))
|
|
2531
|
+
continue;
|
|
2532
|
+
const previous = before.get(oldId);
|
|
2533
|
+
const next = after.get(rewritten);
|
|
2534
|
+
if (previous.kind !== next.kind)
|
|
2535
|
+
continue;
|
|
2536
|
+
pairedOldIds.add(oldId);
|
|
2537
|
+
pairedNewIds.add(rewritten);
|
|
2538
|
+
events.push(eventFor(next, "updated", previous));
|
|
2539
|
+
renames.push({ from: oldId, to: rewritten });
|
|
2540
|
+
}
|
|
2541
|
+
for (const id of addedIds) {
|
|
2542
|
+
if (pairedNewIds.has(id))
|
|
2543
|
+
continue;
|
|
2544
|
+
events.push(eventFor(after.get(id), "added"));
|
|
2545
|
+
}
|
|
2546
|
+
for (const id of removedIds) {
|
|
2547
|
+
if (pairedOldIds.has(id))
|
|
2548
|
+
continue;
|
|
2549
|
+
events.push(eventFor(before.get(id), "removed"));
|
|
2550
|
+
}
|
|
2551
|
+
const commonIds = [...after.keys()].filter((id) => before.has(id)).sort(byCodeUnit);
|
|
2552
|
+
for (const id of commonIds) {
|
|
2553
|
+
const previous = before.get(id);
|
|
2554
|
+
const next = after.get(id);
|
|
2555
|
+
if (previous.fingerprint !== next.fingerprint) {
|
|
2556
|
+
events.push(eventFor(next, "updated", previous));
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
events.sort(compareEvents);
|
|
2560
|
+
const summary = {
|
|
2561
|
+
added: events.filter((event) => event.kind === "added").length,
|
|
2562
|
+
updated: events.filter((event) => event.kind === "updated").length,
|
|
2563
|
+
removed: events.filter((event) => event.kind === "removed").length,
|
|
2564
|
+
renamed: events.filter((event) => event.previousId !== undefined).length,
|
|
2565
|
+
total: events.length
|
|
2566
|
+
};
|
|
2567
|
+
return {
|
|
2568
|
+
schema: DIFF_SCHEMA,
|
|
2569
|
+
from: from?.id ?? null,
|
|
2570
|
+
to: to.id,
|
|
2571
|
+
changed: events.length > 0,
|
|
2572
|
+
summary,
|
|
2573
|
+
renames,
|
|
2574
|
+
events
|
|
2575
|
+
};
|
|
2576
|
+
}
|
|
2577
|
+
function describeEvent(event) {
|
|
2578
|
+
const suffix = event.previousId ? ` (renamed from ${event.previousId})` : "";
|
|
2579
|
+
const fields = event.fields.length > 0 ? ` [${event.fields.join(", ")}]` : "";
|
|
2580
|
+
return `${event.kind.padEnd(7)} ${event.id}${fields}${suffix}`;
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2583
|
+
// src/pipeline.ts
|
|
2584
|
+
init_cache();
|
|
2585
|
+
|
|
2586
|
+
// src/github/fixture.ts
|
|
2587
|
+
function normaliseKey(key) {
|
|
2588
|
+
const [method, target] = key.split(/\s+/, 2);
|
|
2589
|
+
return `${method?.toUpperCase() ?? "GET"} ${target ?? ""}`;
|
|
2590
|
+
}
|
|
2591
|
+
function searchWithoutPaging(search) {
|
|
2592
|
+
const params = new URLSearchParams(search);
|
|
2593
|
+
params.delete("per_page");
|
|
2594
|
+
params.delete("page");
|
|
2595
|
+
const text = params.toString();
|
|
2596
|
+
return text.length > 0 ? `?${text}` : "";
|
|
2597
|
+
}
|
|
2598
|
+
function createFixtureTransport(file) {
|
|
2599
|
+
const routes = new Map;
|
|
2600
|
+
for (const [key, value] of Object.entries(file.routes)) {
|
|
2601
|
+
routes.set(normaliseKey(key), value);
|
|
2602
|
+
}
|
|
2603
|
+
const requests = [];
|
|
2604
|
+
const missing = [];
|
|
2605
|
+
const cursors = new Map;
|
|
2606
|
+
const byPath = new Map;
|
|
2607
|
+
for (const key of routes.keys()) {
|
|
2608
|
+
const path = key.split(" ")[1]?.split("?")[0] ?? "";
|
|
2609
|
+
const list = byPath.get(path) ?? [];
|
|
2610
|
+
list.push(key);
|
|
2611
|
+
byPath.set(path, list);
|
|
2612
|
+
}
|
|
2613
|
+
const resolve = (method, url) => {
|
|
2614
|
+
const exact = `${method} ${url.pathname}${url.search}`;
|
|
2615
|
+
const direct = routes.get(exact);
|
|
2616
|
+
if (direct !== undefined)
|
|
2617
|
+
return { key: exact, route: direct };
|
|
2618
|
+
const loose = `${method} ${url.pathname}${searchWithoutPaging(url.search)}`;
|
|
2619
|
+
const looseRoute = routes.get(loose);
|
|
2620
|
+
if (looseRoute !== undefined)
|
|
2621
|
+
return { key: loose, route: looseRoute };
|
|
2622
|
+
const candidates = byPath.get(url.pathname) ?? [];
|
|
2623
|
+
if (candidates.length === 1) {
|
|
2624
|
+
const key = candidates[0];
|
|
2625
|
+
return { key, route: routes.get(key) };
|
|
2626
|
+
}
|
|
2627
|
+
return null;
|
|
2628
|
+
};
|
|
2629
|
+
const fetchImpl = async (input, init) => {
|
|
2630
|
+
const method = (init?.method ?? "GET").toUpperCase();
|
|
2631
|
+
const url = new URL(input);
|
|
2632
|
+
requests.push(`${method} ${url.pathname}${url.search}`);
|
|
2633
|
+
const found = resolve(method, url);
|
|
2634
|
+
if (!found) {
|
|
2635
|
+
missing.push(`${method} ${url.pathname}${url.search}`);
|
|
2636
|
+
return new Response(JSON.stringify({ message: "Not Found (fixture)" }), {
|
|
2637
|
+
status: 404,
|
|
2638
|
+
headers: { "content-type": "application/json" }
|
|
2639
|
+
});
|
|
2640
|
+
}
|
|
2641
|
+
let entry;
|
|
2642
|
+
if (Array.isArray(found.route)) {
|
|
2643
|
+
const index = cursors.get(found.key) ?? 0;
|
|
2644
|
+
entry = found.route[Math.min(index, found.route.length - 1)];
|
|
2645
|
+
cursors.set(found.key, index + 1);
|
|
2646
|
+
} else {
|
|
2647
|
+
entry = found.route;
|
|
2648
|
+
}
|
|
2649
|
+
const status = entry.status ?? 200;
|
|
2650
|
+
const headers = new Headers({ "content-type": "application/json", ...entry.headers ?? {} });
|
|
2651
|
+
if (entry.etag)
|
|
2652
|
+
headers.set("etag", entry.etag);
|
|
2653
|
+
if (entry.link)
|
|
2654
|
+
headers.set("link", entry.link);
|
|
2655
|
+
const requestHeaders = new Headers(init?.headers ?? {});
|
|
2656
|
+
const ifNoneMatch = requestHeaders.get("if-none-match");
|
|
2657
|
+
if (status === 200 && entry.etag && ifNoneMatch === entry.etag) {
|
|
2658
|
+
return new Response(null, { status: 304, headers: entry.etag ? { etag: entry.etag } : {} });
|
|
2659
|
+
}
|
|
2660
|
+
if (status === 204 || entry.body === undefined) {
|
|
2661
|
+
return new Response(null, { status, headers });
|
|
2662
|
+
}
|
|
2663
|
+
return new Response(JSON.stringify(entry.body), { status, headers });
|
|
2664
|
+
};
|
|
2665
|
+
return { fetch: fetchImpl, requests, missing };
|
|
2666
|
+
}
|
|
2667
|
+
|
|
2668
|
+
// src/store.ts
|
|
2669
|
+
init_canonical();
|
|
2670
|
+
import { open as open2, readdir as readdir2, unlink as unlink2 } from "fs/promises";
|
|
2671
|
+
import { join as join2 } from "path";
|
|
2672
|
+
init_fs();
|
|
2673
|
+
var MANIFEST_SCHEMA = "loom/manifest@1";
|
|
2674
|
+
var OUTBOX_SCHEMA = "loom/outbox@1";
|
|
2675
|
+
var STORE_VERSION = 1;
|
|
2676
|
+
|
|
2677
|
+
class SnapshotStore {
|
|
2678
|
+
root;
|
|
2679
|
+
warnings = [];
|
|
2680
|
+
constructor(root) {
|
|
2681
|
+
this.root = root;
|
|
2682
|
+
}
|
|
2683
|
+
static async open(root, options = {}) {
|
|
2684
|
+
const store = new SnapshotStore(root);
|
|
2685
|
+
if (options.create !== false)
|
|
2686
|
+
await ensureDir(store.objectsDir);
|
|
2687
|
+
return store;
|
|
2688
|
+
}
|
|
2689
|
+
get objectsDir() {
|
|
2690
|
+
return join2(this.root, "objects");
|
|
2691
|
+
}
|
|
2692
|
+
get manifestPath() {
|
|
2693
|
+
return join2(this.root, "manifest.json");
|
|
2694
|
+
}
|
|
2695
|
+
get cachePath() {
|
|
2696
|
+
return join2(this.root, "cache", "http.json");
|
|
2697
|
+
}
|
|
2698
|
+
get webhookStatePath() {
|
|
2699
|
+
return join2(this.root, "webhook-state.json");
|
|
2700
|
+
}
|
|
2701
|
+
get outboxPath() {
|
|
2702
|
+
return join2(this.root, "outbox.json");
|
|
2703
|
+
}
|
|
2704
|
+
get lockPath() {
|
|
2705
|
+
return join2(this.root, "loom.lock");
|
|
2706
|
+
}
|
|
2707
|
+
get sitePath() {
|
|
2708
|
+
return join2(this.root, "site.json");
|
|
2709
|
+
}
|
|
2710
|
+
objectPath(digest) {
|
|
2711
|
+
const hex = digestHex(digest);
|
|
2712
|
+
return join2(this.objectsDir, hex.slice(0, 2), `${hex.slice(2)}.json`);
|
|
2713
|
+
}
|
|
2714
|
+
async has(digest) {
|
|
2715
|
+
return exists(this.objectPath(digest));
|
|
2716
|
+
}
|
|
2717
|
+
async put(value) {
|
|
2718
|
+
const text = canonicalize(value);
|
|
2719
|
+
const secrets = findSecrets(text);
|
|
2720
|
+
if (secrets.length > 0) {
|
|
2721
|
+
throw new LoomError("secret_detected", "refusing to store a snapshot that matches a credential pattern", {
|
|
2722
|
+
patterns: secrets.map((match) => match.pattern),
|
|
2723
|
+
offsets: secrets.map((match) => match.offset)
|
|
2724
|
+
});
|
|
2725
|
+
}
|
|
2726
|
+
const digest = digestOf(value);
|
|
2727
|
+
const path = this.objectPath(digest);
|
|
2728
|
+
if (await exists(path)) {
|
|
2729
|
+
return { digest, path, created: false, bytes: Buffer.byteLength(text) };
|
|
2730
|
+
}
|
|
2731
|
+
await writeFileAtomic(path, text);
|
|
2732
|
+
return { digest, path, created: true, bytes: Buffer.byteLength(text) };
|
|
2733
|
+
}
|
|
2734
|
+
async get(digest) {
|
|
2735
|
+
const path = this.objectPath(digest);
|
|
2736
|
+
const text = await readTextIfExists(path);
|
|
2737
|
+
if (text === null) {
|
|
2738
|
+
throw new LoomError("snapshot_missing", `snapshot object is missing: ${digest}`, { digest, path });
|
|
2739
|
+
}
|
|
2740
|
+
try {
|
|
2741
|
+
return JSON.parse(text);
|
|
2742
|
+
} catch (error) {
|
|
2743
|
+
throw new LoomError("store_corrupt", `snapshot object is not JSON: ${digest}`, {
|
|
2744
|
+
digest,
|
|
2745
|
+
reason: error.message
|
|
2746
|
+
});
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
async getSnapshot(digest) {
|
|
2750
|
+
const payload = await this.get(digest);
|
|
2751
|
+
return { payload, id: digest };
|
|
2752
|
+
}
|
|
2753
|
+
async readManifest() {
|
|
2754
|
+
const manifest = await readJsonIfExists(this.manifestPath);
|
|
2755
|
+
if (manifest === null)
|
|
2756
|
+
return null;
|
|
2757
|
+
if (manifest.schema !== MANIFEST_SCHEMA || typeof manifest.snapshot !== "string") {
|
|
2758
|
+
throw new LoomError("store_corrupt", "manifest.json has an unknown schema", {
|
|
2759
|
+
schema: manifest.schema
|
|
2760
|
+
});
|
|
2761
|
+
}
|
|
2762
|
+
return manifest;
|
|
2763
|
+
}
|
|
2764
|
+
async head() {
|
|
2765
|
+
const manifest = await this.readManifest();
|
|
2766
|
+
if (manifest === null)
|
|
2767
|
+
return null;
|
|
2768
|
+
return this.getSnapshot(manifest.snapshot);
|
|
2769
|
+
}
|
|
2770
|
+
async readOutbox() {
|
|
2771
|
+
const raw = await readJsonIfExists(this.outboxPath);
|
|
2772
|
+
if (raw === null)
|
|
2773
|
+
return null;
|
|
2774
|
+
const outbox = raw;
|
|
2775
|
+
const valid = outbox !== null && typeof outbox === "object" && outbox.schema === OUTBOX_SCHEMA && typeof outbox.snapshot === "string" && typeof outbox.nextAttemptAt === "string" && typeof outbox.attempts === "number" && outbox.diff !== null && typeof outbox.diff === "object" && Array.isArray(outbox.diff.events);
|
|
2776
|
+
if (!valid) {
|
|
2777
|
+
const quarantined = await quarantineFile(this.outboxPath, "corrupt-outbox");
|
|
2778
|
+
this.warnings.push(`outbox was invalid; quarantined at ${quarantined ?? this.outboxPath}`);
|
|
2779
|
+
return null;
|
|
2780
|
+
}
|
|
2781
|
+
return outbox;
|
|
2782
|
+
}
|
|
2783
|
+
async writeOutbox(outbox) {
|
|
2784
|
+
await writeFileAtomic(this.outboxPath, `${JSON.stringify(outbox, null, 2)}
|
|
2785
|
+
`);
|
|
2786
|
+
}
|
|
2787
|
+
async clearOutbox() {
|
|
2788
|
+
await unlink2(this.outboxPath).catch((error) => {
|
|
2789
|
+
if (error.code !== "ENOENT")
|
|
2790
|
+
throw error;
|
|
2791
|
+
});
|
|
2792
|
+
}
|
|
2793
|
+
async acquireLock(options = {}) {
|
|
2794
|
+
const staleMs = options.staleMs ?? 10 * 60 * 1000;
|
|
2795
|
+
const now = options.now ?? Date.now;
|
|
2796
|
+
await ensureDir(this.root);
|
|
2797
|
+
for (let attempt = 0;attempt < 2; attempt += 1) {
|
|
2798
|
+
try {
|
|
2799
|
+
const handle = await open2(this.lockPath, "wx", 420);
|
|
2800
|
+
try {
|
|
2801
|
+
await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: new Date(now()).toISOString() }));
|
|
2802
|
+
} finally {
|
|
2803
|
+
await handle.close();
|
|
2804
|
+
}
|
|
2805
|
+
let released = false;
|
|
2806
|
+
return {
|
|
2807
|
+
path: this.lockPath,
|
|
2808
|
+
release: async () => {
|
|
2809
|
+
if (released)
|
|
2810
|
+
return;
|
|
2811
|
+
released = true;
|
|
2812
|
+
await unlink2(this.lockPath).catch((error) => {
|
|
2813
|
+
if (error.code !== "ENOENT")
|
|
2814
|
+
throw error;
|
|
2815
|
+
});
|
|
2816
|
+
}
|
|
2817
|
+
};
|
|
2818
|
+
} catch (error) {
|
|
2819
|
+
if (error.code !== "EEXIST")
|
|
2820
|
+
throw error;
|
|
2821
|
+
const existing = await readJsonIfExists(this.lockPath);
|
|
2822
|
+
const acquiredAt = existing?.acquiredAt ? Date.parse(existing.acquiredAt) : Number.NaN;
|
|
2823
|
+
const stale = !Number.isFinite(acquiredAt) || now() - acquiredAt > staleMs;
|
|
2824
|
+
if (!stale || attempt > 0) {
|
|
2825
|
+
throw new LoomError("lock_busy", "store is locked by another Loom process", {
|
|
2826
|
+
lock: this.lockPath,
|
|
2827
|
+
pid: existing?.pid ?? null,
|
|
2828
|
+
acquiredAt: existing?.acquiredAt ?? null
|
|
2829
|
+
});
|
|
2830
|
+
}
|
|
2831
|
+
this.warnings.push(`removed stale lock ${this.lockPath}`);
|
|
2832
|
+
await unlink2(this.lockPath).catch(() => {
|
|
2833
|
+
return;
|
|
2834
|
+
});
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
throw new LoomError("lock_busy", "store is locked by another Loom process", { lock: this.lockPath });
|
|
2838
|
+
}
|
|
2839
|
+
async recover() {
|
|
2840
|
+
const report = { tempFilesRemoved: 0, quarantined: [], warnings: [] };
|
|
2841
|
+
report.tempFilesRemoved += await removeStaleTempFiles(this.root, 0);
|
|
2842
|
+
report.tempFilesRemoved += await removeStaleTempFiles(join2(this.root, "cache"), 0);
|
|
2843
|
+
let prefixes = [];
|
|
2844
|
+
try {
|
|
2845
|
+
prefixes = await readdir2(this.objectsDir);
|
|
2846
|
+
} catch {
|
|
2847
|
+
prefixes = [];
|
|
2848
|
+
}
|
|
2849
|
+
for (const prefix of prefixes) {
|
|
2850
|
+
if (/^[0-9a-f]{2}$/.test(prefix)) {
|
|
2851
|
+
report.tempFilesRemoved += await removeStaleTempFiles(join2(this.objectsDir, prefix), 0);
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
await Promise.resolve().then(() => init_cache());
|
|
2855
|
+
const cache = await FileCache.openWithRecovery(this.cachePath);
|
|
2856
|
+
if (cache.quarantined) {
|
|
2857
|
+
report.quarantined.push(cache.quarantined);
|
|
2858
|
+
report.warnings.push("http cache was corrupt and has been quarantined");
|
|
2859
|
+
}
|
|
2860
|
+
await Promise.resolve().then(() => init_delivery());
|
|
2861
|
+
const delivery = await DeliveryLog.openWithRecovery(this.webhookStatePath);
|
|
2862
|
+
if (delivery.quarantined) {
|
|
2863
|
+
report.quarantined.push(delivery.quarantined);
|
|
2864
|
+
report.warnings.push("webhook state was corrupt and has been quarantined");
|
|
2865
|
+
}
|
|
2866
|
+
const outbox = await readJsonIfExists(this.outboxPath);
|
|
2867
|
+
if (outbox !== null) {
|
|
2868
|
+
const parsed = outbox;
|
|
2869
|
+
if (parsed.schema !== OUTBOX_SCHEMA) {
|
|
2870
|
+
const quarantined = await quarantineFile(this.outboxPath, "corrupt-outbox");
|
|
2871
|
+
if (quarantined)
|
|
2872
|
+
report.quarantined.push(quarantined);
|
|
2873
|
+
report.warnings.push("dispatch outbox was invalid and has been quarantined");
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
this.warnings.push(...report.warnings);
|
|
2877
|
+
return report;
|
|
2878
|
+
}
|
|
2879
|
+
async commit(snapshot, meta) {
|
|
2880
|
+
const put = await this.put(snapshot.payload);
|
|
2881
|
+
if (put.digest !== snapshot.id) {
|
|
2882
|
+
throw new LoomError("store_corrupt", "snapshot id does not match its canonical content", {
|
|
2883
|
+
expected: snapshot.id,
|
|
2884
|
+
actual: put.digest
|
|
2885
|
+
});
|
|
2886
|
+
}
|
|
2887
|
+
const existing = await this.readManifest();
|
|
2888
|
+
if (existing && existing.snapshot === snapshot.id)
|
|
2889
|
+
return existing;
|
|
2890
|
+
const manifest = {
|
|
2891
|
+
schema: MANIFEST_SCHEMA,
|
|
2892
|
+
snapshot: snapshot.id,
|
|
2893
|
+
createdAt: meta.createdAt ?? new Date().toISOString(),
|
|
2894
|
+
stats: snapshotStats(snapshot.payload),
|
|
2895
|
+
source: snapshot.payload.source
|
|
2896
|
+
};
|
|
2897
|
+
await writeFileAtomic(this.manifestPath, `${JSON.stringify(manifest, null, 2)}
|
|
2898
|
+
`);
|
|
2899
|
+
return manifest;
|
|
2900
|
+
}
|
|
2901
|
+
async listDigests() {
|
|
2902
|
+
const digests = [];
|
|
2903
|
+
let prefixes;
|
|
2904
|
+
try {
|
|
2905
|
+
prefixes = (await readdir2(this.objectsDir)).sort();
|
|
2906
|
+
} catch {
|
|
2907
|
+
return digests;
|
|
2908
|
+
}
|
|
2909
|
+
for (const prefix of prefixes) {
|
|
2910
|
+
if (!/^[0-9a-f]{2}$/.test(prefix))
|
|
2911
|
+
continue;
|
|
2912
|
+
let names;
|
|
2913
|
+
try {
|
|
2914
|
+
names = (await readdir2(join2(this.objectsDir, prefix))).sort();
|
|
2915
|
+
} catch {
|
|
2916
|
+
continue;
|
|
2917
|
+
}
|
|
2918
|
+
for (const name of names) {
|
|
2919
|
+
if (!/^[0-9a-f]{62}\.json$/.test(name))
|
|
2920
|
+
continue;
|
|
2921
|
+
digests.push(`sha256:${prefix}${name.slice(0, 62)}`);
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
return digests;
|
|
2925
|
+
}
|
|
2926
|
+
async verify() {
|
|
2927
|
+
const checks = [];
|
|
2928
|
+
const problems = [];
|
|
2929
|
+
const check = (name, ok, detail) => {
|
|
2930
|
+
checks.push({ name, ok, detail });
|
|
2931
|
+
if (!ok)
|
|
2932
|
+
problems.push(`${name}: ${detail}`);
|
|
2933
|
+
};
|
|
2934
|
+
const manifest = await readJsonIfExists(this.manifestPath);
|
|
2935
|
+
check("manifest-present", manifest !== null, manifest === null ? "manifest.json not found" : "found");
|
|
2936
|
+
let current = null;
|
|
2937
|
+
let objects = 0;
|
|
2938
|
+
if (manifest) {
|
|
2939
|
+
check("manifest-schema", manifest.schema === MANIFEST_SCHEMA, `schema=${String(manifest.schema)}`);
|
|
2940
|
+
const digestOk = typeof manifest.snapshot === "string" && /^sha256:[0-9a-f]{64}$/.test(manifest.snapshot);
|
|
2941
|
+
check("manifest-snapshot-id", digestOk, digestOk ? manifest.snapshot : "invalid digest");
|
|
2942
|
+
current = digestOk ? manifest.snapshot : null;
|
|
2943
|
+
if (current) {
|
|
2944
|
+
const path = this.objectPath(current);
|
|
2945
|
+
const text = await readTextIfExists(path);
|
|
2946
|
+
check("snapshot-present", text !== null, text === null ? `missing ${path}` : "found");
|
|
2947
|
+
if (text !== null) {
|
|
2948
|
+
const hex = digestHex(current);
|
|
2949
|
+
const byteHash = sha256Hex(new TextEncoder().encode(text));
|
|
2950
|
+
check("snapshot-bytes", byteHash === hex, byteHash === hex ? "bytes hash to their name" : `bytes hash ${byteHash}`);
|
|
2951
|
+
let parsed = null;
|
|
2952
|
+
try {
|
|
2953
|
+
parsed = JSON.parse(text);
|
|
2954
|
+
check("snapshot-json", true, "parses");
|
|
2955
|
+
} catch (error) {
|
|
2956
|
+
check("snapshot-json", false, error.message);
|
|
2957
|
+
}
|
|
2958
|
+
if (parsed) {
|
|
2959
|
+
const canonical = canonicalize(parsed);
|
|
2960
|
+
check("snapshot-canonical", canonical === text, canonical === text ? "byte-identical to canonical form" : "blob is not canonical JSON");
|
|
2961
|
+
const shapeOk = parsed.schema === SNAPSHOT_SCHEMA && Array.isArray(parsed.repos) && Array.isArray(parsed.errors) && parsed.source !== null && typeof parsed.source === "object";
|
|
2962
|
+
check("snapshot-schema", shapeOk, shapeOk ? `schema=${String(parsed.schema)}` : `malformed payload; schema=${String(parsed.schema)}`);
|
|
2963
|
+
const recomputed = snapshotId(parsed);
|
|
2964
|
+
check("snapshot-id", recomputed === current, recomputed === current ? current : recomputed);
|
|
2965
|
+
if (shapeOk) {
|
|
2966
|
+
const expected = snapshotStats(parsed);
|
|
2967
|
+
check("manifest-stats", JSON.stringify(expected) === JSON.stringify(manifest.stats), `expected ${JSON.stringify(expected)}`);
|
|
2968
|
+
const repoIds = parsed.repos.map((repo) => repo.id);
|
|
2969
|
+
const sorted = [...repoIds].sort();
|
|
2970
|
+
const ordered = repoIds.every((id, index) => id === sorted[index]);
|
|
2971
|
+
check("snapshot-order", ordered, ordered ? "repositories sorted by id" : "repositories out of order");
|
|
2972
|
+
const releaseOk = parsed.repos.every((repo) => {
|
|
2973
|
+
if (!Array.isArray(repo.releases))
|
|
2974
|
+
return false;
|
|
2975
|
+
if (repo.releases.some((release) => release.draft))
|
|
2976
|
+
return false;
|
|
2977
|
+
for (let index = 1;index < repo.releases.length; index += 1) {
|
|
2978
|
+
const previous = repo.releases[index - 1];
|
|
2979
|
+
const current = repo.releases[index];
|
|
2980
|
+
const left = previous.publishedAt ?? "";
|
|
2981
|
+
const right = current.publishedAt ?? "";
|
|
2982
|
+
if (left < right || left === right && previous.tag > current.tag)
|
|
2983
|
+
return false;
|
|
2984
|
+
}
|
|
2985
|
+
return true;
|
|
2986
|
+
});
|
|
2987
|
+
check("snapshot-releases", releaseOk, releaseOk ? "releases are non-draft and newest first" : "release order or draft flag is invalid");
|
|
2988
|
+
} else {
|
|
2989
|
+
check("manifest-stats", false, "payload has no repos array");
|
|
2990
|
+
check("snapshot-order", false, "payload has no repos array");
|
|
2991
|
+
check("snapshot-releases", false, "payload has no repos array");
|
|
2992
|
+
}
|
|
2993
|
+
check("no-secrets", findSecrets(text).length === 0, findSecrets(text).map((match) => match.pattern).join(", ") || "no credential patterns");
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
const digests = await this.listDigests();
|
|
2999
|
+
objects = digests.length;
|
|
3000
|
+
const bad = [];
|
|
3001
|
+
const secretHits = [];
|
|
3002
|
+
for (const digest of digests) {
|
|
3003
|
+
const text = await readTextIfExists(this.objectPath(digest));
|
|
3004
|
+
if (text === null) {
|
|
3005
|
+
bad.push(`${digest} (missing)`);
|
|
3006
|
+
continue;
|
|
3007
|
+
}
|
|
3008
|
+
const hash = sha256Hex(new TextEncoder().encode(text));
|
|
3009
|
+
if (hash !== digestHex(digest)) {
|
|
3010
|
+
bad.push(`${digest} (hash ${hash.slice(0, 12)}\u2026)`);
|
|
3011
|
+
continue;
|
|
3012
|
+
}
|
|
3013
|
+
const secrets = findSecrets(text);
|
|
3014
|
+
if (secrets.length > 0)
|
|
3015
|
+
secretHits.push(`${digest} (${secrets.map((match) => match.pattern).join(",")})`);
|
|
3016
|
+
}
|
|
3017
|
+
check("objects-addressed", bad.length === 0, bad.length === 0 ? `${digests.length} objects verified` : bad.join("; "));
|
|
3018
|
+
check("objects-secret-free", secretHits.length === 0, secretHits.length === 0 ? "clean" : secretHits.join("; "));
|
|
3019
|
+
check("store-version", manifest === null || manifest.schema === MANIFEST_SCHEMA, manifest === null ? `store v${STORE_VERSION} (empty)` : `store v${STORE_VERSION}`);
|
|
3020
|
+
let outboxRaw = null;
|
|
3021
|
+
let outboxParseError = null;
|
|
3022
|
+
try {
|
|
3023
|
+
outboxRaw = await readJsonIfExists(this.outboxPath);
|
|
3024
|
+
} catch (error) {
|
|
3025
|
+
outboxParseError = error.message;
|
|
3026
|
+
}
|
|
3027
|
+
if (outboxParseError !== null) {
|
|
3028
|
+
check("outbox-valid", false, `outbox is not JSON: ${outboxParseError}`);
|
|
3029
|
+
check("outbox-target", false, "skipped");
|
|
3030
|
+
} else if (outboxRaw === null) {
|
|
3031
|
+
check("outbox-valid", true, "absent");
|
|
3032
|
+
check("outbox-target", true, "absent");
|
|
3033
|
+
} else {
|
|
3034
|
+
const outboxOk = outboxRaw.schema === OUTBOX_SCHEMA && typeof outboxRaw.snapshot === "string" && /^sha256:[0-9a-f]{64}$/.test(outboxRaw.snapshot) && typeof outboxRaw.attempts === "number" && Array.isArray(outboxRaw.diff?.events);
|
|
3035
|
+
check("outbox-valid", outboxOk, outboxOk ? `pending ${outboxRaw.snapshot}` : "malformed outbox");
|
|
3036
|
+
if (outboxOk && current !== null && outboxRaw.snapshot !== current) {
|
|
3037
|
+
check("outbox-target", false, `outbox targets ${outboxRaw.snapshot} but manifest is ${current}; run loom sync --dispatch`);
|
|
3038
|
+
} else {
|
|
3039
|
+
check("outbox-target", true, outboxOk ? "targets the current snapshot" : "skipped");
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
let siteRaw = null;
|
|
3043
|
+
let siteParseError = null;
|
|
3044
|
+
try {
|
|
3045
|
+
siteRaw = await readJsonIfExists(this.sitePath);
|
|
3046
|
+
} catch (error) {
|
|
3047
|
+
siteParseError = error.message;
|
|
3048
|
+
}
|
|
3049
|
+
if (siteParseError !== null) {
|
|
3050
|
+
check("site-record", false, `site.json is not JSON: ${siteParseError}`);
|
|
3051
|
+
check("site-record-snapshot", false, "skipped");
|
|
3052
|
+
} else if (siteRaw === null) {
|
|
3053
|
+
check("site-record", true, "absent");
|
|
3054
|
+
check("site-record-snapshot", true, "absent");
|
|
3055
|
+
} else {
|
|
3056
|
+
const siteOk = siteRaw.schema === "loom/site@1" && typeof siteRaw.snapshot === "string";
|
|
3057
|
+
check("site-record", siteOk, siteOk ? `schema=${String(siteRaw.schema)}` : "malformed site.json");
|
|
3058
|
+
check("site-record-snapshot", siteOk && (current === null || siteRaw.snapshot === current), siteOk ? `snapshot=${String(siteRaw.snapshot)}` : "skipped");
|
|
3059
|
+
}
|
|
3060
|
+
return {
|
|
3061
|
+
schema: "loom/verify@1",
|
|
3062
|
+
ok: problems.length === 0,
|
|
3063
|
+
snapshot: current,
|
|
3064
|
+
objects,
|
|
3065
|
+
checks,
|
|
3066
|
+
problems
|
|
3067
|
+
};
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
|
|
3071
|
+
// src/webhook/signature.ts
|
|
3072
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
3073
|
+
var DELIVERY_HEADER = "x-github-delivery";
|
|
3074
|
+
var EVENT_HEADER = "x-github-event";
|
|
3075
|
+
var TIMESTAMP_HEADER = "x-loom-timestamp";
|
|
3076
|
+
function hmacSha256Hex(secret, payload) {
|
|
3077
|
+
return createHmac("sha256", secret).update(payload).digest("hex");
|
|
3078
|
+
}
|
|
3079
|
+
function signBody(secret, payload) {
|
|
3080
|
+
return `sha256=${hmacSha256Hex(secret, payload)}`;
|
|
3081
|
+
}
|
|
3082
|
+
function timingSafeHexEqual(left, right) {
|
|
3083
|
+
if (!/^[0-9a-fA-F]*$/.test(left) || !/^[0-9a-fA-F]*$/.test(right))
|
|
3084
|
+
return false;
|
|
3085
|
+
const a = Buffer.from(left, "hex");
|
|
3086
|
+
const b = Buffer.from(right, "hex");
|
|
3087
|
+
if (a.length !== b.length) {
|
|
3088
|
+
timingSafeEqual(a, a);
|
|
3089
|
+
return false;
|
|
3090
|
+
}
|
|
3091
|
+
return timingSafeEqual(a, b);
|
|
3092
|
+
}
|
|
3093
|
+
function parseSignatureHeader(header) {
|
|
3094
|
+
const separator = header.indexOf("=");
|
|
3095
|
+
if (separator <= 0)
|
|
3096
|
+
return null;
|
|
3097
|
+
const algorithm = header.slice(0, separator).trim().toLowerCase();
|
|
3098
|
+
const hex = header.slice(separator + 1).trim();
|
|
3099
|
+
if (algorithm.length === 0 || hex.length === 0)
|
|
3100
|
+
return null;
|
|
3101
|
+
return { algorithm, hex };
|
|
3102
|
+
}
|
|
3103
|
+
function verifySignature(options) {
|
|
3104
|
+
const mode = options.mode ?? "github";
|
|
3105
|
+
const header = options.signature;
|
|
3106
|
+
if (!header)
|
|
3107
|
+
return { valid: false, reason: "missing signature header" };
|
|
3108
|
+
const parsed = parseSignatureHeader(header);
|
|
3109
|
+
if (parsed === null)
|
|
3110
|
+
return { valid: false, reason: "malformed signature header" };
|
|
3111
|
+
if (parsed.algorithm !== "sha256")
|
|
3112
|
+
return { valid: false, reason: `unsupported algorithm: ${parsed.algorithm}` };
|
|
3113
|
+
if (!/^[0-9a-f]{64}$/.test(parsed.hex))
|
|
3114
|
+
return { valid: false, reason: "malformed signature header" };
|
|
3115
|
+
let message = options.body;
|
|
3116
|
+
let timestamp = null;
|
|
3117
|
+
if (mode === "signed-timestamp") {
|
|
3118
|
+
const raw = options.timestamp;
|
|
3119
|
+
if (!raw || !/^\d{1,12}$/.test(raw))
|
|
3120
|
+
return { valid: false, reason: "missing or invalid timestamp header" };
|
|
3121
|
+
timestamp = Number.parseInt(raw, 10);
|
|
3122
|
+
const now = options.nowMs ?? Date.now();
|
|
3123
|
+
const tolerance = (options.toleranceSeconds ?? 300) * 1000;
|
|
3124
|
+
if (Math.abs(now - timestamp * 1000) > tolerance) {
|
|
3125
|
+
return { valid: false, reason: "timestamp outside tolerance" };
|
|
3126
|
+
}
|
|
3127
|
+
const prefix = new TextEncoder().encode(`${raw}.`);
|
|
3128
|
+
const combined = new Uint8Array(prefix.length + options.body.length);
|
|
3129
|
+
combined.set(prefix, 0);
|
|
3130
|
+
combined.set(options.body, prefix.length);
|
|
3131
|
+
message = combined;
|
|
3132
|
+
}
|
|
3133
|
+
const expected = hmacSha256Hex(options.secret, message);
|
|
3134
|
+
if (!timingSafeHexEqual(expected, parsed.hex))
|
|
3135
|
+
return { valid: false, reason: "signature mismatch" };
|
|
3136
|
+
return { valid: true, timestamp };
|
|
3137
|
+
}
|
|
3138
|
+
|
|
3139
|
+
// src/triggers.ts
|
|
3140
|
+
var TRIGGER_SCHEMA = "loom/trigger@1";
|
|
3141
|
+
var TRIGGER_EVENT_HEADER = "X-Loom-Event";
|
|
3142
|
+
var TRIGGER_SIGNATURE_HEADER = "X-Loom-Signature-256";
|
|
3143
|
+
var TRIGGER_DELIVERY_HEADER = "X-Loom-Delivery";
|
|
3144
|
+
var TRIGGER_ATTEMPT_HEADER = "X-Loom-Attempt";
|
|
3145
|
+
var MAX_EVENTS = 50;
|
|
3146
|
+
function publicPlan(plan) {
|
|
3147
|
+
const { url: _url, ...rest } = plan;
|
|
3148
|
+
return rest;
|
|
3149
|
+
}
|
|
3150
|
+
function triggerPayload(diff, context = {}) {
|
|
3151
|
+
return {
|
|
3152
|
+
schema: TRIGGER_SCHEMA,
|
|
3153
|
+
delivery: context.idempotencyKey ?? null,
|
|
3154
|
+
attempt: context.attempt ?? null,
|
|
3155
|
+
snapshot: diff.to,
|
|
3156
|
+
previousSnapshot: diff.from,
|
|
3157
|
+
changed: diff.changed,
|
|
3158
|
+
summary: diff.summary,
|
|
3159
|
+
events: diff.events.slice(0, MAX_EVENTS),
|
|
3160
|
+
truncated: diff.events.length > MAX_EVENTS
|
|
3161
|
+
};
|
|
3162
|
+
}
|
|
3163
|
+
function envValue(env, name) {
|
|
3164
|
+
const value = env[name];
|
|
3165
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
3166
|
+
}
|
|
3167
|
+
function deliveryHeaders(context) {
|
|
3168
|
+
const headers = {};
|
|
3169
|
+
if (context.idempotencyKey)
|
|
3170
|
+
headers[TRIGGER_DELIVERY_HEADER] = context.idempotencyKey;
|
|
3171
|
+
if (context.attempt !== undefined)
|
|
3172
|
+
headers[TRIGGER_ATTEMPT_HEADER] = String(context.attempt);
|
|
3173
|
+
return headers;
|
|
3174
|
+
}
|
|
3175
|
+
function planTriggers(configs, context) {
|
|
3176
|
+
const env = context.env ?? process.env;
|
|
3177
|
+
const body = JSON.stringify(triggerPayload(context.diff, context));
|
|
3178
|
+
const delivery = deliveryHeaders(context);
|
|
3179
|
+
return configs.map((config, index) => {
|
|
3180
|
+
const base = { index, kind: config.kind, method: "POST", body };
|
|
3181
|
+
switch (config.kind) {
|
|
3182
|
+
case "vercel": {
|
|
3183
|
+
const url = envValue(env, config.urlEnv);
|
|
3184
|
+
return {
|
|
3185
|
+
...base,
|
|
3186
|
+
url,
|
|
3187
|
+
target: url ? redactUrl(url) : `<${config.urlEnv}>`,
|
|
3188
|
+
headers: { "content-type": "application/json", ...delivery },
|
|
3189
|
+
body: null,
|
|
3190
|
+
requiresEnv: config.urlEnv,
|
|
3191
|
+
ready: url !== null,
|
|
3192
|
+
skipReason: url === null ? `missing environment variable ${config.urlEnv}` : null
|
|
3193
|
+
};
|
|
3194
|
+
}
|
|
3195
|
+
case "github-dispatch": {
|
|
3196
|
+
const token = envValue(env, config.tokenEnv);
|
|
3197
|
+
return {
|
|
3198
|
+
...base,
|
|
3199
|
+
url: `https://api.github.com/repos/${config.repo}/dispatches`,
|
|
3200
|
+
target: `https://api.github.com/repos/${config.repo}/dispatches`,
|
|
3201
|
+
headers: {
|
|
3202
|
+
"content-type": "application/json",
|
|
3203
|
+
accept: "application/vnd.github+json",
|
|
3204
|
+
authorization: token ? "Bearer <redacted>" : "<missing>",
|
|
3205
|
+
"x-github-api-version": "2022-11-28",
|
|
3206
|
+
...delivery
|
|
3207
|
+
},
|
|
3208
|
+
body: JSON.stringify({
|
|
3209
|
+
event_type: config.eventType,
|
|
3210
|
+
client_payload: triggerPayload(context.diff, context)
|
|
3211
|
+
}),
|
|
3212
|
+
requiresEnv: config.tokenEnv,
|
|
3213
|
+
ready: token !== null,
|
|
3214
|
+
skipReason: token === null ? `missing environment variable ${config.tokenEnv}` : null
|
|
3215
|
+
};
|
|
3216
|
+
}
|
|
3217
|
+
case "webhook": {
|
|
3218
|
+
const url = envValue(env, config.urlEnv);
|
|
3219
|
+
const secret = config.secretEnv ? envValue(env, config.secretEnv) : null;
|
|
3220
|
+
const headers = {
|
|
3221
|
+
"content-type": "application/json",
|
|
3222
|
+
"user-agent": "loom-sync/0.1",
|
|
3223
|
+
[TRIGGER_EVENT_HEADER]: "loom.snapshot",
|
|
3224
|
+
...delivery
|
|
3225
|
+
};
|
|
3226
|
+
if (secret)
|
|
3227
|
+
headers[TRIGGER_SIGNATURE_HEADER] = signBody(secret, body);
|
|
3228
|
+
const missing = url === null ? config.urlEnv : config.secretEnv && secret === null ? config.secretEnv : null;
|
|
3229
|
+
return {
|
|
3230
|
+
...base,
|
|
3231
|
+
url,
|
|
3232
|
+
target: url ? redactUrl(url) : `<${config.urlEnv}>`,
|
|
3233
|
+
headers,
|
|
3234
|
+
requiresEnv: missing,
|
|
3235
|
+
ready: missing === null,
|
|
3236
|
+
skipReason: missing === null ? null : `missing environment variable ${missing}`
|
|
3237
|
+
};
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
});
|
|
3241
|
+
}
|
|
3242
|
+
async function dispatchPlan(plans, context) {
|
|
3243
|
+
const doFetch = context.fetch ?? ((input, init) => fetch(input, init));
|
|
3244
|
+
const env = context.env ?? process.env;
|
|
3245
|
+
const results = [];
|
|
3246
|
+
for (const plan of plans) {
|
|
3247
|
+
if (context.dryRun) {
|
|
3248
|
+
results.push({
|
|
3249
|
+
index: plan.index,
|
|
3250
|
+
kind: plan.kind,
|
|
3251
|
+
target: plan.target,
|
|
3252
|
+
ok: true,
|
|
3253
|
+
status: null,
|
|
3254
|
+
dryRun: true,
|
|
3255
|
+
skipped: false,
|
|
3256
|
+
error: null
|
|
3257
|
+
});
|
|
3258
|
+
continue;
|
|
3259
|
+
}
|
|
3260
|
+
if (!plan.ready || plan.url === null) {
|
|
3261
|
+
results.push({
|
|
3262
|
+
index: plan.index,
|
|
3263
|
+
kind: plan.kind,
|
|
3264
|
+
target: plan.target,
|
|
3265
|
+
ok: false,
|
|
3266
|
+
status: null,
|
|
3267
|
+
dryRun: false,
|
|
3268
|
+
skipped: true,
|
|
3269
|
+
error: plan.skipReason
|
|
3270
|
+
});
|
|
3271
|
+
continue;
|
|
3272
|
+
}
|
|
3273
|
+
const headers = new Headers(plan.headers);
|
|
3274
|
+
if (plan.kind === "github-dispatch") {
|
|
3275
|
+
const token = plan.requiresEnv ? envValue(env, plan.requiresEnv) : null;
|
|
3276
|
+
if (!token) {
|
|
3277
|
+
results.push({
|
|
3278
|
+
index: plan.index,
|
|
3279
|
+
kind: plan.kind,
|
|
3280
|
+
target: plan.target,
|
|
3281
|
+
ok: false,
|
|
3282
|
+
status: null,
|
|
3283
|
+
dryRun: false,
|
|
3284
|
+
skipped: true,
|
|
3285
|
+
error: `missing environment variable ${plan.requiresEnv ?? "token"}`
|
|
3286
|
+
});
|
|
3287
|
+
continue;
|
|
3288
|
+
}
|
|
3289
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
3290
|
+
}
|
|
3291
|
+
try {
|
|
3292
|
+
const response = await doFetch(plan.url, {
|
|
3293
|
+
method: "POST",
|
|
3294
|
+
headers,
|
|
3295
|
+
body: plan.body,
|
|
3296
|
+
signal: combineSignals([context.signal, AbortSignal.timeout(context.timeoutMs ?? 15000)])
|
|
3297
|
+
});
|
|
3298
|
+
const ok = response.status >= 200 && response.status < 300;
|
|
3299
|
+
context.logger?.("trigger dispatched", { kind: plan.kind, target: plan.target, status: response.status });
|
|
3300
|
+
results.push({
|
|
3301
|
+
index: plan.index,
|
|
3302
|
+
kind: plan.kind,
|
|
3303
|
+
target: plan.target,
|
|
3304
|
+
ok,
|
|
3305
|
+
status: response.status,
|
|
3306
|
+
dryRun: false,
|
|
3307
|
+
skipped: false,
|
|
3308
|
+
error: ok ? null : `HTTP ${response.status}`
|
|
3309
|
+
});
|
|
3310
|
+
} catch (error) {
|
|
3311
|
+
context.logger?.("trigger failed", { kind: plan.kind, target: plan.target, error: error.message });
|
|
3312
|
+
results.push({
|
|
3313
|
+
index: plan.index,
|
|
3314
|
+
kind: plan.kind,
|
|
3315
|
+
target: plan.target,
|
|
3316
|
+
ok: false,
|
|
3317
|
+
status: null,
|
|
3318
|
+
dryRun: false,
|
|
3319
|
+
skipped: false,
|
|
3320
|
+
error: error.message
|
|
3321
|
+
});
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
return results;
|
|
3325
|
+
}
|
|
3326
|
+
async function dispatchTriggers(configs, context) {
|
|
3327
|
+
const plans = planTriggers(configs, context);
|
|
3328
|
+
if (!context.allowMissing && !context.dryRun) {
|
|
3329
|
+
const missing = plans.filter((plan) => !plan.ready);
|
|
3330
|
+
if (missing.length > 0) {
|
|
3331
|
+
throw new LoomError("secret_missing", missing[0]?.skipReason ?? "trigger is not configured", {
|
|
3332
|
+
targets: missing.map((plan) => plan.kind)
|
|
3333
|
+
});
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
const results = await dispatchPlan(plans, context);
|
|
3337
|
+
return { plans: plans.map(publicPlan), results };
|
|
3338
|
+
}
|
|
3339
|
+
|
|
3340
|
+
// src/pipeline.ts
|
|
3341
|
+
var FIXTURE_FILE = "responses.json";
|
|
3342
|
+
async function loadFixture(dir) {
|
|
3343
|
+
const path = dir.endsWith(".json") ? dir : `${dir}/${FIXTURE_FILE}`;
|
|
3344
|
+
const runtime = globalThis.Bun;
|
|
3345
|
+
if (runtime === undefined || typeof runtime.file !== "function") {
|
|
3346
|
+
throw new LoomError("usage", "loading a fixture file needs Bun; pass recorded routes to the fixture transport instead", {
|
|
3347
|
+
path
|
|
3348
|
+
});
|
|
3349
|
+
}
|
|
3350
|
+
const file = runtime.file(path);
|
|
3351
|
+
if (!await file.exists()) {
|
|
3352
|
+
throw new LoomError("usage", `fixture file not found: ${path}`, { path });
|
|
3353
|
+
}
|
|
3354
|
+
const parsed = await file.json();
|
|
3355
|
+
if (!parsed || typeof parsed !== "object" || typeof parsed.routes !== "object") {
|
|
3356
|
+
throw new LoomError("usage", `fixture file has no routes: ${path}`, { path });
|
|
3357
|
+
}
|
|
3358
|
+
return {
|
|
3359
|
+
transport: createFixtureTransport(parsed),
|
|
3360
|
+
baseUrl: typeof parsed.baseUrl === "string" ? parsed.baseUrl : "https://api.github.com"
|
|
3361
|
+
};
|
|
3362
|
+
}
|
|
3363
|
+
async function computeSnapshot2(options) {
|
|
3364
|
+
const { fixtureDir, ...rest } = options;
|
|
3365
|
+
const fixture = fixtureDir ? await loadFixture(fixtureDir) : null;
|
|
3366
|
+
return computeSnapshot({ ...rest, fixture });
|
|
3367
|
+
}
|
|
3368
|
+
function nextAttempt(nowMs, attempts) {
|
|
3369
|
+
const delay = Math.min(5 * 60000, 5000 * 2 ** Math.max(0, attempts - 1));
|
|
3370
|
+
return new Date(nowMs + delay).toISOString();
|
|
3371
|
+
}
|
|
3372
|
+
async function runSync(options) {
|
|
3373
|
+
const startedAt = Date.now();
|
|
3374
|
+
const store = options.store;
|
|
3375
|
+
const lock = options.lock ? await store.acquireLock() : null;
|
|
3376
|
+
try {
|
|
3377
|
+
let cache = options.cache;
|
|
3378
|
+
if (cache === undefined) {
|
|
3379
|
+
if (options.dryRun) {
|
|
3380
|
+
cache = new MemoryCache;
|
|
3381
|
+
} else {
|
|
3382
|
+
const opened = await FileCache.openWithRecovery(store.cachePath);
|
|
3383
|
+
cache = opened.cache;
|
|
3384
|
+
if (opened.quarantined) {
|
|
3385
|
+
options.logger?.("http cache quarantined", { path: opened.quarantined });
|
|
3386
|
+
}
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
const previous = await store.head();
|
|
3390
|
+
const computed = await computeSnapshot2({ ...options, cache, previous: previous?.payload ?? null });
|
|
3391
|
+
const diff = diffSnapshots(previous, computed.snapshot, {
|
|
3392
|
+
aliases: options.config.aliases,
|
|
3393
|
+
ownerAliases: ownerAliasesOf(computed.snapshot)
|
|
3394
|
+
});
|
|
3395
|
+
let status = "unchanged";
|
|
3396
|
+
let manifest = await store.readManifest();
|
|
3397
|
+
let committed = false;
|
|
3398
|
+
let triggers = { plans: [], results: [], deferred: false };
|
|
3399
|
+
let outbox = {
|
|
3400
|
+
pending: false,
|
|
3401
|
+
snapshot: null,
|
|
3402
|
+
attempts: 0,
|
|
3403
|
+
nextAttemptAt: null
|
|
3404
|
+
};
|
|
3405
|
+
const failedWithoutCopy = computed.payload.errors.some((error) => error.retained !== true);
|
|
3406
|
+
const blocked = !options.dryRun && failedWithoutCopy && computed.payload.errors.length > 0;
|
|
3407
|
+
if (blocked) {
|
|
3408
|
+
status = "partial";
|
|
3409
|
+
const pending = await store.readOutbox();
|
|
3410
|
+
if (pending) {
|
|
3411
|
+
outbox = {
|
|
3412
|
+
pending: true,
|
|
3413
|
+
snapshot: pending.snapshot,
|
|
3414
|
+
attempts: pending.attempts,
|
|
3415
|
+
nextAttemptAt: pending.nextAttemptAt
|
|
3416
|
+
};
|
|
3417
|
+
}
|
|
3418
|
+
} else if (diff.changed && options.dryRun) {
|
|
3419
|
+
status = "would-change";
|
|
3420
|
+
if (options.dispatch) {
|
|
3421
|
+
triggers = {
|
|
3422
|
+
...await dispatchTriggers(options.config.triggers, {
|
|
3423
|
+
diff,
|
|
3424
|
+
env: options.env ?? process.env,
|
|
3425
|
+
dryRun: true,
|
|
3426
|
+
...options.signal ? { signal: options.signal } : {},
|
|
3427
|
+
...options.logger ? { logger: options.logger } : {}
|
|
3428
|
+
}),
|
|
3429
|
+
deferred: false
|
|
3430
|
+
};
|
|
3431
|
+
}
|
|
3432
|
+
} else if (diff.changed) {
|
|
3433
|
+
let pending = null;
|
|
3434
|
+
if (options.dispatch) {
|
|
3435
|
+
const nowMs = options.now?.() ?? Date.now();
|
|
3436
|
+
pending = {
|
|
3437
|
+
schema: OUTBOX_SCHEMA,
|
|
3438
|
+
snapshot: computed.snapshot.id,
|
|
3439
|
+
previous: diff.from,
|
|
3440
|
+
createdAt: new Date(nowMs).toISOString(),
|
|
3441
|
+
attempts: 0,
|
|
3442
|
+
nextAttemptAt: new Date(nowMs).toISOString(),
|
|
3443
|
+
diff
|
|
3444
|
+
};
|
|
3445
|
+
await store.writeOutbox(pending);
|
|
3446
|
+
}
|
|
3447
|
+
manifest = await store.commit(computed.snapshot, {
|
|
3448
|
+
source: computed.snapshot.payload.source,
|
|
3449
|
+
...options.clock ? { createdAt: options.clock().toISOString() } : {}
|
|
3450
|
+
});
|
|
3451
|
+
status = "created";
|
|
3452
|
+
committed = true;
|
|
3453
|
+
if (pending) {
|
|
3454
|
+
const result = await dispatchPendingOutbox(store, pending, options);
|
|
3455
|
+
triggers = result.triggers;
|
|
3456
|
+
outbox = result.outbox;
|
|
3457
|
+
}
|
|
3458
|
+
} else if (options.dispatch) {
|
|
3459
|
+
const headId = previous?.id ?? computed.snapshot.id;
|
|
3460
|
+
const pending = await store.readOutbox();
|
|
3461
|
+
if (pending && pending.snapshot === headId) {
|
|
3462
|
+
const result = await dispatchPendingOutbox(store, pending, options);
|
|
3463
|
+
triggers = result.triggers;
|
|
3464
|
+
outbox = result.outbox;
|
|
3465
|
+
} else if (pending) {
|
|
3466
|
+
options.logger?.("dropping stale outbox for a superseded snapshot", {
|
|
3467
|
+
outbox: pending.snapshot,
|
|
3468
|
+
head: headId
|
|
3469
|
+
});
|
|
3470
|
+
await store.clearOutbox();
|
|
3471
|
+
}
|
|
3472
|
+
} else {
|
|
3473
|
+
const pending = await store.readOutbox();
|
|
3474
|
+
if (pending) {
|
|
3475
|
+
outbox = {
|
|
3476
|
+
pending: true,
|
|
3477
|
+
snapshot: pending.snapshot,
|
|
3478
|
+
attempts: pending.attempts,
|
|
3479
|
+
nextAttemptAt: pending.nextAttemptAt
|
|
3480
|
+
};
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3483
|
+
if (cache && "save" in cache)
|
|
3484
|
+
await cache.save();
|
|
3485
|
+
const resultSnapshot = committed || status === "would-change" ? computed.snapshot : previous ?? computed.snapshot;
|
|
3486
|
+
return {
|
|
3487
|
+
status,
|
|
3488
|
+
snapshot: resultSnapshot,
|
|
3489
|
+
previous,
|
|
3490
|
+
diff,
|
|
3491
|
+
manifest,
|
|
3492
|
+
stats: snapshotStats(resultSnapshot.payload),
|
|
3493
|
+
errors: computed.payload.errors,
|
|
3494
|
+
triggers,
|
|
3495
|
+
outbox,
|
|
3496
|
+
requests: computed.client.stats.requests,
|
|
3497
|
+
notModified: computed.client.stats.notModified,
|
|
3498
|
+
retries: computed.client.stats.retries,
|
|
3499
|
+
rateLimitWaits: computed.client.stats.rateLimitWaits,
|
|
3500
|
+
durationMs: Date.now() - startedAt,
|
|
3501
|
+
fixtureMissing: computed.fixture?.missing ?? []
|
|
3502
|
+
};
|
|
3503
|
+
} finally {
|
|
3504
|
+
await lock?.release();
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
async function dispatchPendingOutbox(store, pending, options) {
|
|
3508
|
+
const nowMs = options.now?.() ?? Date.now();
|
|
3509
|
+
const next = Date.parse(pending.nextAttemptAt);
|
|
3510
|
+
if (Number.isFinite(next) && next > nowMs) {
|
|
3511
|
+
return {
|
|
3512
|
+
triggers: { plans: [], results: [], deferred: true },
|
|
3513
|
+
outbox: {
|
|
3514
|
+
pending: true,
|
|
3515
|
+
snapshot: pending.snapshot,
|
|
3516
|
+
attempts: pending.attempts,
|
|
3517
|
+
nextAttemptAt: pending.nextAttemptAt
|
|
3518
|
+
}
|
|
3519
|
+
};
|
|
3520
|
+
}
|
|
3521
|
+
const result = await dispatchTriggers(options.config.triggers, {
|
|
3522
|
+
diff: pending.diff,
|
|
3523
|
+
env: options.env ?? process.env,
|
|
3524
|
+
dryRun: false,
|
|
3525
|
+
allowMissing: options.allowMissingTriggers ?? false,
|
|
3526
|
+
idempotencyKey: pending.snapshot,
|
|
3527
|
+
attempt: pending.attempts + 1,
|
|
3528
|
+
...options.signal ? { signal: options.signal } : {},
|
|
3529
|
+
...options.dispatchFetch ? { fetch: options.dispatchFetch } : {},
|
|
3530
|
+
...options.logger ? { logger: options.logger } : {}
|
|
3531
|
+
});
|
|
3532
|
+
const failed = result.results.some((entry) => !entry.ok && !entry.dryRun);
|
|
3533
|
+
if (!failed) {
|
|
3534
|
+
await store.clearOutbox();
|
|
3535
|
+
return {
|
|
3536
|
+
triggers: { ...result, deferred: false },
|
|
3537
|
+
outbox: { pending: false, snapshot: null, attempts: 0, nextAttemptAt: null }
|
|
3538
|
+
};
|
|
3539
|
+
}
|
|
3540
|
+
const attempts = pending.attempts + 1;
|
|
3541
|
+
const retry = {
|
|
3542
|
+
...pending,
|
|
3543
|
+
attempts,
|
|
3544
|
+
nextAttemptAt: nextAttempt(nowMs, attempts)
|
|
3545
|
+
};
|
|
3546
|
+
await store.writeOutbox(retry);
|
|
3547
|
+
return {
|
|
3548
|
+
triggers: { ...result, deferred: true },
|
|
3549
|
+
outbox: {
|
|
3550
|
+
pending: true,
|
|
3551
|
+
snapshot: pending.snapshot,
|
|
3552
|
+
attempts,
|
|
3553
|
+
nextAttemptAt: retry.nextAttemptAt
|
|
3554
|
+
}
|
|
3555
|
+
};
|
|
3556
|
+
}
|
|
3557
|
+
|
|
3558
|
+
// src/site.ts
|
|
3559
|
+
var SITE_SCHEMA = "loom/site@1";
|
|
3560
|
+
function splitName(fullName) {
|
|
3561
|
+
const slash = fullName.indexOf("/");
|
|
3562
|
+
if (slash === -1)
|
|
3563
|
+
return { owner: "", name: fullName };
|
|
3564
|
+
return { owner: fullName.slice(0, slash), name: fullName.slice(slash + 1) };
|
|
3565
|
+
}
|
|
3566
|
+
function rewriteOwnerInUrl(url, ownerAliases) {
|
|
3567
|
+
if (url === null)
|
|
3568
|
+
return null;
|
|
3569
|
+
let out = url;
|
|
3570
|
+
for (const [from, to] of Object.entries(ownerAliases)) {
|
|
3571
|
+
const escaped = from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3572
|
+
out = out.replace(new RegExp(`/${escaped}/`, "gi"), `/${to}/`);
|
|
3573
|
+
}
|
|
3574
|
+
return out;
|
|
3575
|
+
}
|
|
3576
|
+
function siteRelease(release, ownerAliases) {
|
|
3577
|
+
return {
|
|
3578
|
+
tag: release.tag,
|
|
3579
|
+
name: release.name,
|
|
3580
|
+
publishedAt: release.publishedAt,
|
|
3581
|
+
prerelease: release.prerelease,
|
|
3582
|
+
url: rewriteOwnerInUrl(release.url, ownerAliases)
|
|
3583
|
+
};
|
|
3584
|
+
}
|
|
3585
|
+
function siteHead(head, ownerAliases) {
|
|
3586
|
+
return {
|
|
3587
|
+
sha: head.sha,
|
|
3588
|
+
shortSha: head.sha.slice(0, 12),
|
|
3589
|
+
message: head.message,
|
|
3590
|
+
author: head.author,
|
|
3591
|
+
committedAt: head.committedAt,
|
|
3592
|
+
url: rewriteOwnerInUrl(head.url, ownerAliases) ?? ""
|
|
3593
|
+
};
|
|
3594
|
+
}
|
|
3595
|
+
function languagesOf(repo) {
|
|
3596
|
+
return Object.entries(repo.languages).map(([name, bytes]) => ({ name, bytes })).sort((a, b) => b.bytes - a.bytes || byCodeUnit(a.name, b.name));
|
|
3597
|
+
}
|
|
3598
|
+
function siteBranches(repo) {
|
|
3599
|
+
return (repo.branches ?? []).map((branch) => ({
|
|
3600
|
+
name: branch.name,
|
|
3601
|
+
sha: branch.sha,
|
|
3602
|
+
shortSha: branch.sha.slice(0, 12),
|
|
3603
|
+
protected: branch.protected,
|
|
3604
|
+
default: branch.default
|
|
3605
|
+
})).sort((a, b) => Number(b.default) - Number(a.default) || byCodeUnit(a.name, b.name));
|
|
3606
|
+
}
|
|
3607
|
+
function siteComments(comments) {
|
|
3608
|
+
return comments.map((comment) => ({
|
|
3609
|
+
id: comment.id,
|
|
3610
|
+
body: comment.body,
|
|
3611
|
+
author: comment.author,
|
|
3612
|
+
createdAt: comment.createdAt,
|
|
3613
|
+
url: comment.url
|
|
3614
|
+
})).sort((a, b) => byCodeUnit(b.createdAt ?? "", a.createdAt ?? "") || byCodeUnit(String(a.id), String(b.id)));
|
|
3615
|
+
}
|
|
3616
|
+
function siteCi(repo) {
|
|
3617
|
+
if (!repo.ci)
|
|
3618
|
+
return null;
|
|
3619
|
+
return {
|
|
3620
|
+
workflow: repo.ci.workflow,
|
|
3621
|
+
runId: repo.ci.runId,
|
|
3622
|
+
status: repo.ci.status,
|
|
3623
|
+
conclusion: repo.ci.conclusion,
|
|
3624
|
+
branch: repo.ci.branch,
|
|
3625
|
+
sha: repo.ci.sha,
|
|
3626
|
+
shortSha: repo.ci.sha === null ? null : repo.ci.sha.slice(0, 12),
|
|
3627
|
+
url: repo.ci.url,
|
|
3628
|
+
updatedAt: repo.ci.updatedAt
|
|
3629
|
+
};
|
|
3630
|
+
}
|
|
3631
|
+
function siteProject(repo, ownerAliases = {}) {
|
|
3632
|
+
const split = splitName(repo.fullName);
|
|
3633
|
+
const owner = resolveOwnerAlias(split.owner, ownerAliases);
|
|
3634
|
+
const fullName = owner === split.owner ? repo.fullName : `${owner}/${split.name}`;
|
|
3635
|
+
const htmlUrl = rewriteOwnerInUrl(repo.htmlUrl, ownerAliases) ?? `https://github.com/${fullName}`;
|
|
3636
|
+
const releases = repo.releases.map((release) => siteRelease(release, ownerAliases));
|
|
3637
|
+
return {
|
|
3638
|
+
id: `${owner}/${split.name}`.toLowerCase(),
|
|
3639
|
+
slug: split.name.toLowerCase(),
|
|
3640
|
+
owner,
|
|
3641
|
+
name: split.name,
|
|
3642
|
+
fullName,
|
|
3643
|
+
description: repo.description,
|
|
3644
|
+
homepage: repo.homepage,
|
|
3645
|
+
topics: [...repo.topics],
|
|
3646
|
+
language: repo.language,
|
|
3647
|
+
languages: languagesOf(repo),
|
|
3648
|
+
license: repo.license,
|
|
3649
|
+
stars: repo.stars,
|
|
3650
|
+
forks: repo.forks,
|
|
3651
|
+
watchers: repo.watchers,
|
|
3652
|
+
openIssues: repo.openIssues,
|
|
3653
|
+
archived: repo.archived,
|
|
3654
|
+
fork: repo.fork,
|
|
3655
|
+
defaultBranch: repo.defaultBranch,
|
|
3656
|
+
htmlUrl,
|
|
3657
|
+
createdAt: repo.createdAt,
|
|
3658
|
+
updatedAt: repo.updatedAt,
|
|
3659
|
+
pushedAt: repo.pushedAt,
|
|
3660
|
+
release: releases[0] ?? null,
|
|
3661
|
+
releases,
|
|
3662
|
+
head: repo.head === null ? null : siteHead(repo.head, ownerAliases),
|
|
3663
|
+
...repo.readme !== undefined ? {
|
|
3664
|
+
readme: repo.readme === null ? null : {
|
|
3665
|
+
path: repo.readme.path,
|
|
3666
|
+
sha: repo.readme.sha,
|
|
3667
|
+
size: repo.readme.size,
|
|
3668
|
+
htmlUrl: repo.readme.htmlUrl,
|
|
3669
|
+
downloadUrl: repo.readme.downloadUrl,
|
|
3670
|
+
excerpt: repo.readme.excerpt
|
|
3671
|
+
}
|
|
3672
|
+
} : {},
|
|
3673
|
+
...repo.branches ? { branches: siteBranches(repo) } : {},
|
|
3674
|
+
...repo.commitComments ? { commitComments: siteComments(repo.commitComments) } : {},
|
|
3675
|
+
...repo.issueComments ? { issueComments: siteComments(repo.issueComments) } : {},
|
|
3676
|
+
...repo.workflows ? {
|
|
3677
|
+
workflows: [...repo.workflows].map((workflow) => ({
|
|
3678
|
+
id: workflow.id,
|
|
3679
|
+
name: workflow.name,
|
|
3680
|
+
path: workflow.path,
|
|
3681
|
+
state: workflow.state
|
|
3682
|
+
})).sort((a, b) => byCodeUnit(String(a.id), String(b.id)))
|
|
3683
|
+
} : {},
|
|
3684
|
+
...repo.ci !== undefined ? { ci: siteCi(repo) } : {}
|
|
3685
|
+
};
|
|
3686
|
+
}
|
|
3687
|
+
function buildSiteRecord(snapshot, options = {}) {
|
|
3688
|
+
const ownerAliases = options.ownerAliases ?? {};
|
|
3689
|
+
const repoAliases = options.aliases ?? {};
|
|
3690
|
+
const projects = snapshot.payload.repos.map((repo) => siteProject(repo, ownerAliases)).sort((a, b) => byCodeUnit(a.id, b.id));
|
|
3691
|
+
const errors = [...snapshot.payload.errors].sort((a, b) => byCodeUnit(a.repo, b.repo) || byCodeUnit(a.code, b.code));
|
|
3692
|
+
const ownerAliasList = Object.keys(ownerAliases).map((from) => ({
|
|
3693
|
+
from: from.toLowerCase(),
|
|
3694
|
+
to: resolveOwnerAlias(from, ownerAliases).toLowerCase()
|
|
3695
|
+
})).filter((entry) => entry.from !== entry.to).sort((a, b) => byCodeUnit(a.from, b.from));
|
|
3696
|
+
const aliases = Object.keys(repoAliases).map((from) => ({
|
|
3697
|
+
from: canonicalRepoKey(from, ownerAliases),
|
|
3698
|
+
to: resolveRepoAlias(from, repoAliases, ownerAliases)
|
|
3699
|
+
})).filter((entry) => entry.from !== entry.to).sort((a, b) => byCodeUnit(a.from, b.from));
|
|
3700
|
+
return {
|
|
3701
|
+
schema: SITE_SCHEMA,
|
|
3702
|
+
snapshot: snapshot.id,
|
|
3703
|
+
complete: errors.every((error) => error.retained === true),
|
|
3704
|
+
projects,
|
|
3705
|
+
aliases,
|
|
3706
|
+
ownerAliases: ownerAliasList,
|
|
3707
|
+
errors
|
|
3708
|
+
};
|
|
3709
|
+
}
|
|
3710
|
+
function siteDigest(record) {
|
|
3711
|
+
return digestOf(record);
|
|
3712
|
+
}
|
|
3713
|
+
|
|
3714
|
+
// src/site-module.ts
|
|
3715
|
+
init_canonical();
|
|
3716
|
+
var CURATED_FIELDS = [
|
|
3717
|
+
"tagline",
|
|
3718
|
+
"category",
|
|
3719
|
+
"maturity",
|
|
3720
|
+
"flagship",
|
|
3721
|
+
"morphology",
|
|
3722
|
+
"narrative",
|
|
3723
|
+
"capabilities",
|
|
3724
|
+
"benchmarks",
|
|
3725
|
+
"links"
|
|
3726
|
+
];
|
|
3727
|
+
function sorted(value) {
|
|
3728
|
+
if (Array.isArray(value))
|
|
3729
|
+
return value.map(sorted);
|
|
3730
|
+
if (value !== null && typeof value === "object") {
|
|
3731
|
+
const out = {};
|
|
3732
|
+
for (const key of Object.keys(value).sort(byCodeUnit)) {
|
|
3733
|
+
out[key] = sorted(value[key]);
|
|
3734
|
+
}
|
|
3735
|
+
return out;
|
|
3736
|
+
}
|
|
3737
|
+
return value;
|
|
3738
|
+
}
|
|
3739
|
+
function pretty(value) {
|
|
3740
|
+
return JSON.stringify(sorted(value), null, 2);
|
|
3741
|
+
}
|
|
3742
|
+
function projectUnion(projects) {
|
|
3743
|
+
if (projects.length === 0)
|
|
3744
|
+
return "never";
|
|
3745
|
+
return projects.map((project) => JSON.stringify(project.id)).join(" | ");
|
|
3746
|
+
}
|
|
3747
|
+
function selfContainedTypes() {
|
|
3748
|
+
return [
|
|
3749
|
+
"export type SiteRelease = {",
|
|
3750
|
+
" tag: string;",
|
|
3751
|
+
" name: string | null;",
|
|
3752
|
+
" publishedAt: string | null;",
|
|
3753
|
+
" prerelease: boolean;",
|
|
3754
|
+
" url: string | null;",
|
|
3755
|
+
"};",
|
|
3756
|
+
"",
|
|
3757
|
+
"export type SiteHead = {",
|
|
3758
|
+
" sha: string;",
|
|
3759
|
+
" shortSha: string;",
|
|
3760
|
+
" message: string;",
|
|
3761
|
+
" author: string | null;",
|
|
3762
|
+
" committedAt: string | null;",
|
|
3763
|
+
" url: string;",
|
|
3764
|
+
"};",
|
|
3765
|
+
"",
|
|
3766
|
+
"export type SiteReadme = {",
|
|
3767
|
+
" path: string;",
|
|
3768
|
+
" sha: string;",
|
|
3769
|
+
" size: number;",
|
|
3770
|
+
" htmlUrl: string | null;",
|
|
3771
|
+
" downloadUrl: string | null;",
|
|
3772
|
+
" excerpt: string | null;",
|
|
3773
|
+
"};",
|
|
3774
|
+
"",
|
|
3775
|
+
"export type SiteBranch = {",
|
|
3776
|
+
" name: string;",
|
|
3777
|
+
" sha: string;",
|
|
3778
|
+
" shortSha: string;",
|
|
3779
|
+
" protected: boolean;",
|
|
3780
|
+
" default: boolean;",
|
|
3781
|
+
"};",
|
|
3782
|
+
"",
|
|
3783
|
+
"export type SiteComment = {",
|
|
3784
|
+
" id: number | string;",
|
|
3785
|
+
" body: string;",
|
|
3786
|
+
" author: string | null;",
|
|
3787
|
+
" createdAt: string | null;",
|
|
3788
|
+
" url: string | null;",
|
|
3789
|
+
"};",
|
|
3790
|
+
"",
|
|
3791
|
+
"export type SiteWorkflow = {",
|
|
3792
|
+
" id: number | string;",
|
|
3793
|
+
" name: string;",
|
|
3794
|
+
" path: string;",
|
|
3795
|
+
" state: string;",
|
|
3796
|
+
"};",
|
|
3797
|
+
"",
|
|
3798
|
+
"export type SiteCi = {",
|
|
3799
|
+
" workflow: string | null;",
|
|
3800
|
+
" runId: number | string;",
|
|
3801
|
+
" status: string | null;",
|
|
3802
|
+
" conclusion: string | null;",
|
|
3803
|
+
" branch: string | null;",
|
|
3804
|
+
" sha: string | null;",
|
|
3805
|
+
" shortSha: string | null;",
|
|
3806
|
+
" url: string | null;",
|
|
3807
|
+
" updatedAt: string | null;",
|
|
3808
|
+
"};",
|
|
3809
|
+
"",
|
|
3810
|
+
"export type SiteProject = {",
|
|
3811
|
+
" id: string;",
|
|
3812
|
+
" slug: string;",
|
|
3813
|
+
" owner: string;",
|
|
3814
|
+
" name: string;",
|
|
3815
|
+
" fullName: string;",
|
|
3816
|
+
" description: string | null;",
|
|
3817
|
+
" homepage: string | null;",
|
|
3818
|
+
" topics: string[];",
|
|
3819
|
+
" language: string | null;",
|
|
3820
|
+
" languages: { name: string; bytes: number }[];",
|
|
3821
|
+
" license: string | null;",
|
|
3822
|
+
" stars: number;",
|
|
3823
|
+
" forks: number;",
|
|
3824
|
+
" watchers: number;",
|
|
3825
|
+
" openIssues: number;",
|
|
3826
|
+
" archived: boolean;",
|
|
3827
|
+
" fork: boolean;",
|
|
3828
|
+
" defaultBranch: string;",
|
|
3829
|
+
" htmlUrl: string;",
|
|
3830
|
+
" createdAt: string | null;",
|
|
3831
|
+
" updatedAt: string | null;",
|
|
3832
|
+
" pushedAt: string | null;",
|
|
3833
|
+
" release: SiteRelease | null;",
|
|
3834
|
+
" releases: SiteRelease[];",
|
|
3835
|
+
" head: SiteHead | null;",
|
|
3836
|
+
" readme?: SiteReadme | null;",
|
|
3837
|
+
" branches?: SiteBranch[];",
|
|
3838
|
+
" commitComments?: SiteComment[];",
|
|
3839
|
+
" issueComments?: SiteComment[];",
|
|
3840
|
+
" workflows?: SiteWorkflow[];",
|
|
3841
|
+
" ci?: SiteCi | null;",
|
|
3842
|
+
"};",
|
|
3843
|
+
"",
|
|
3844
|
+
"export type SiteRecord = {",
|
|
3845
|
+
' schema: "loom/site@1";',
|
|
3846
|
+
" snapshot: string;",
|
|
3847
|
+
" complete: boolean;",
|
|
3848
|
+
" projects: SiteProject[];",
|
|
3849
|
+
" aliases: { from: string; to: string }[];",
|
|
3850
|
+
" ownerAliases: { from: string; to: string }[];",
|
|
3851
|
+
" errors: { repo: string; code: string; message: string; retained?: true }[];",
|
|
3852
|
+
"};"
|
|
3853
|
+
];
|
|
3854
|
+
}
|
|
3855
|
+
function renderSiteModule(record, options = {}) {
|
|
3856
|
+
const requested = options.packageName;
|
|
3857
|
+
const selfContained = requested === null || requested === "" || requested === "none" || requested === "self-contained";
|
|
3858
|
+
const packageName = selfContained ? null : requested ?? "@sifr-dev/loom";
|
|
3859
|
+
const curated = options.curated ?? {};
|
|
3860
|
+
const normalizedCurated = {};
|
|
3861
|
+
for (const [id, entry] of Object.entries(curated))
|
|
3862
|
+
normalizedCurated[id.toLowerCase()] = entry;
|
|
3863
|
+
const curatedIds = Object.keys(normalizedCurated).sort(byCodeUnit);
|
|
3864
|
+
const curatedBlock = curatedIds.length === 0 ? "{}" : pretty(normalizedCurated);
|
|
3865
|
+
const union = projectUnion(record.projects);
|
|
3866
|
+
const lines = [];
|
|
3867
|
+
lines.push("/**");
|
|
3868
|
+
lines.push(" * AUTO-GENERATED by Loom - do not edit by hand.");
|
|
3869
|
+
lines.push(` * Source snapshot: ${record.schema} ${record.snapshot}`);
|
|
3870
|
+
lines.push(selfContained ? " * Regenerate: loom export --format ts --package none --out <this file>" : " * Regenerate: loom export --format ts --out <this file>");
|
|
3871
|
+
lines.push(` * Generated by: ${options.generatedBy ?? "loom export"}`);
|
|
3872
|
+
lines.push(" */");
|
|
3873
|
+
if (packageName !== null) {
|
|
3874
|
+
lines.push(`import type { SiteProject } from ${JSON.stringify(packageName)};`);
|
|
3875
|
+
} else {
|
|
3876
|
+
lines.push(...selfContainedTypes());
|
|
3877
|
+
}
|
|
3878
|
+
lines.push("");
|
|
3879
|
+
lines.push(`export const SNAPSHOT = ${JSON.stringify(record.snapshot)};`);
|
|
3880
|
+
lines.push(`export const COMPLETE = ${record.complete ? "true" : "false"};`);
|
|
3881
|
+
lines.push("");
|
|
3882
|
+
lines.push("export type ProjectId = " + union + ";");
|
|
3883
|
+
lines.push("");
|
|
3884
|
+
lines.push("/** Curated fields a site may overlay; every one is optional. */");
|
|
3885
|
+
lines.push("export type CuratedProject = {");
|
|
3886
|
+
for (const field of CURATED_FIELDS) {
|
|
3887
|
+
const type = field === "flagship" ? "boolean" : field === "capabilities" || field === "benchmarks" || field === "links" ? "string[]" : "string";
|
|
3888
|
+
lines.push(` ${field}?: ${type};`);
|
|
3889
|
+
}
|
|
3890
|
+
lines.push(" [key: string]: unknown;");
|
|
3891
|
+
lines.push("};");
|
|
3892
|
+
lines.push("");
|
|
3893
|
+
lines.push("/** Generic discovered records, sorted by stable project id. */");
|
|
3894
|
+
lines.push(`export const PROJECTS: readonly SiteProject[] = ${pretty(record.projects)};`);
|
|
3895
|
+
lines.push("");
|
|
3896
|
+
lines.push("/** Optional enrichment owned by the site, keyed by project id. */");
|
|
3897
|
+
lines.push(`export const CURATED: Partial<Record<ProjectId, CuratedProject>> = ${curatedBlock};`);
|
|
3898
|
+
lines.push("");
|
|
3899
|
+
lines.push("export type EnrichedProject = SiteProject & { curated?: CuratedProject };");
|
|
3900
|
+
lines.push("");
|
|
3901
|
+
lines.push("export function enrich(curated: Partial<Record<ProjectId, CuratedProject>> = CURATED): EnrichedProject[] {");
|
|
3902
|
+
lines.push(" return PROJECTS.map((project) => {");
|
|
3903
|
+
lines.push(" const extra = curated[project.id as ProjectId];");
|
|
3904
|
+
lines.push(" return extra ? { ...project, curated: extra } : { ...project };");
|
|
3905
|
+
lines.push(" });");
|
|
3906
|
+
lines.push("}");
|
|
3907
|
+
lines.push("");
|
|
3908
|
+
lines.push("export const ALIASES = " + pretty(record.aliases) + ";");
|
|
3909
|
+
lines.push("export const OWNER_ALIASES = " + pretty(record.ownerAliases) + ";");
|
|
3910
|
+
lines.push("export const ERRORS = " + pretty(record.errors) + ";");
|
|
3911
|
+
lines.push("");
|
|
3912
|
+
lines.push("export default PROJECTS;");
|
|
3913
|
+
lines.push("");
|
|
3914
|
+
return lines.join(`
|
|
3915
|
+
`);
|
|
3916
|
+
}
|
|
3917
|
+
function siteModuleDigest(record, options = {}) {
|
|
3918
|
+
return canonicalize(renderSiteModule(record, options));
|
|
3919
|
+
}
|
|
3920
|
+
// src/webhook/receiver.ts
|
|
3921
|
+
function header(headers, name) {
|
|
3922
|
+
const value = headers.get(name);
|
|
3923
|
+
return value === null || value.length === 0 ? null : value;
|
|
3924
|
+
}
|
|
3925
|
+
function record3(value) {
|
|
3926
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3927
|
+
}
|
|
3928
|
+
function str(value) {
|
|
3929
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
class WebhookReceiver {
|
|
3933
|
+
#secrets;
|
|
3934
|
+
#deliveries;
|
|
3935
|
+
#branches;
|
|
3936
|
+
#branchDiscovery;
|
|
3937
|
+
#mode;
|
|
3938
|
+
#toleranceSeconds;
|
|
3939
|
+
#maxBodyBytes;
|
|
3940
|
+
#now;
|
|
3941
|
+
#repoAllowed;
|
|
3942
|
+
#logger;
|
|
3943
|
+
constructor(options) {
|
|
3944
|
+
const secrets = Array.isArray(options.secrets) ? options.secrets : [options.secrets];
|
|
3945
|
+
this.#secrets = secrets.filter((secret) => secret.length > 0);
|
|
3946
|
+
if (this.#secrets.length === 0)
|
|
3947
|
+
throw new Error("WebhookReceiver requires at least one secret");
|
|
3948
|
+
this.#deliveries = options.deliveries;
|
|
3949
|
+
this.#branches = [...options.branches ?? []];
|
|
3950
|
+
this.#branchDiscovery = options.branchDiscovery ?? true;
|
|
3951
|
+
this.#mode = options.mode ?? "github";
|
|
3952
|
+
this.#toleranceSeconds = options.toleranceSeconds ?? 300;
|
|
3953
|
+
this.#maxBodyBytes = options.maxBodyBytes ?? 1048576;
|
|
3954
|
+
this.#now = options.now ?? (() => Date.now());
|
|
3955
|
+
this.#repoAllowed = options.repoAllowed ?? (() => true);
|
|
3956
|
+
this.#logger = options.logger ?? (() => {});
|
|
3957
|
+
}
|
|
3958
|
+
#decision(kind, reason, partial = {}) {
|
|
3959
|
+
return {
|
|
3960
|
+
kind,
|
|
3961
|
+
event: partial.event ?? "",
|
|
3962
|
+
delivery: partial.delivery ?? "",
|
|
3963
|
+
action: partial.action ?? "none",
|
|
3964
|
+
repo: partial.repo ?? null,
|
|
3965
|
+
ref: partial.ref ?? null,
|
|
3966
|
+
payloadHash: partial.payloadHash ?? "",
|
|
3967
|
+
reason
|
|
3968
|
+
};
|
|
3969
|
+
}
|
|
3970
|
+
async handle(input) {
|
|
3971
|
+
const body = input.body;
|
|
3972
|
+
const payloadHash = sha256Hex(body);
|
|
3973
|
+
if (body.length > this.#maxBodyBytes) {
|
|
3974
|
+
return this.#decision("invalid", `body exceeds ${this.#maxBodyBytes} bytes`, { payloadHash });
|
|
3975
|
+
}
|
|
3976
|
+
const event = header(input.headers, EVENT_HEADER);
|
|
3977
|
+
if (event === null)
|
|
3978
|
+
return this.#decision("invalid", "missing X-GitHub-Event", { payloadHash });
|
|
3979
|
+
const delivery = header(input.headers, DELIVERY_HEADER);
|
|
3980
|
+
if (delivery === null)
|
|
3981
|
+
return this.#decision("invalid", "missing X-GitHub-Delivery", { event, payloadHash });
|
|
3982
|
+
const signature = header(input.headers, "x-hub-signature-256");
|
|
3983
|
+
const timestamp = header(input.headers, TIMESTAMP_HEADER);
|
|
3984
|
+
let verified = false;
|
|
3985
|
+
let lastReason = "signature mismatch";
|
|
3986
|
+
for (const secret of this.#secrets) {
|
|
3987
|
+
const result = verifySignature({
|
|
3988
|
+
secret,
|
|
3989
|
+
body,
|
|
3990
|
+
signature,
|
|
3991
|
+
mode: this.#mode,
|
|
3992
|
+
timestamp,
|
|
3993
|
+
toleranceSeconds: this.#toleranceSeconds,
|
|
3994
|
+
nowMs: this.#now()
|
|
3995
|
+
});
|
|
3996
|
+
if (result.valid) {
|
|
3997
|
+
verified = true;
|
|
3998
|
+
break;
|
|
3999
|
+
}
|
|
4000
|
+
lastReason = result.reason;
|
|
4001
|
+
}
|
|
4002
|
+
if (!verified) {
|
|
4003
|
+
this.#logger("webhook rejected: signature", { event, delivery, reason: lastReason });
|
|
4004
|
+
return this.#decision("unauthorized", lastReason, { event, delivery, payloadHash });
|
|
4005
|
+
}
|
|
4006
|
+
const payloadText = new TextDecoder().decode(body);
|
|
4007
|
+
let payload = null;
|
|
4008
|
+
try {
|
|
4009
|
+
payload = record3(JSON.parse(payloadText));
|
|
4010
|
+
} catch {
|
|
4011
|
+
payload = null;
|
|
4012
|
+
}
|
|
4013
|
+
if (payload === null) {
|
|
4014
|
+
return this.#decision("invalid", "body is not a JSON object", { event, delivery, payloadHash });
|
|
4015
|
+
}
|
|
4016
|
+
if (this.#mode === "signed-timestamp" && this.#deliveries.hasPayload(payloadHash, this.#toleranceSeconds * 1000, this.#now())) {
|
|
4017
|
+
return this.#decision("duplicate", "identical signed payload inside the replay window", {
|
|
4018
|
+
event,
|
|
4019
|
+
delivery,
|
|
4020
|
+
payloadHash
|
|
4021
|
+
});
|
|
4022
|
+
}
|
|
4023
|
+
if (this.#deliveries.has(delivery)) {
|
|
4024
|
+
return this.#decision("duplicate", "delivery id already processed", { event, delivery, payloadHash });
|
|
4025
|
+
}
|
|
4026
|
+
const repoRecord = record3(payload["repository"]);
|
|
4027
|
+
const repo = repoRecord ? str(repoRecord["full_name"]) : null;
|
|
4028
|
+
if (repo !== null && !isRepoName(repo)) {
|
|
4029
|
+
return this.#decision("invalid", `repository is not owner/name: ${repo}`, { event, delivery, repo, payloadHash });
|
|
4030
|
+
}
|
|
4031
|
+
if (repo !== null && !this.#repoAllowed(repo)) {
|
|
4032
|
+
return this.#decision("ignored", "repository is not watched by this Loom", { event, delivery, repo, payloadHash });
|
|
4033
|
+
}
|
|
4034
|
+
return this.#classify(event, delivery, repo, payload, payloadHash);
|
|
4035
|
+
}
|
|
4036
|
+
async markDelivered(decision) {
|
|
4037
|
+
if (decision.delivery.length === 0)
|
|
4038
|
+
return;
|
|
4039
|
+
await this.#deliveries.record({
|
|
4040
|
+
id: decision.delivery,
|
|
4041
|
+
at: new Date(this.#now()).toISOString(),
|
|
4042
|
+
event: decision.event,
|
|
4043
|
+
repo: decision.repo
|
|
4044
|
+
}, this.#mode === "signed-timestamp" ? decision.payloadHash : null);
|
|
4045
|
+
}
|
|
4046
|
+
seen(delivery) {
|
|
4047
|
+
return this.#deliveries.has(delivery);
|
|
4048
|
+
}
|
|
4049
|
+
#classify(event, delivery, repo, payload, payloadHash) {
|
|
4050
|
+
const base = { event, delivery, repo, payloadHash };
|
|
4051
|
+
switch (event) {
|
|
4052
|
+
case "ping":
|
|
4053
|
+
return this.#decision("accepted", "ping", { ...base, action: "none", ref: null });
|
|
4054
|
+
case "push": {
|
|
4055
|
+
const ref = str(payload["ref"]) ?? "";
|
|
4056
|
+
if (ref.startsWith("refs/tags/")) {
|
|
4057
|
+
return this.#decision("ignored", "tag push; releases are handled by the release event", {
|
|
4058
|
+
...base,
|
|
4059
|
+
ref
|
|
4060
|
+
});
|
|
4061
|
+
}
|
|
4062
|
+
if (!ref.startsWith("refs/heads/")) {
|
|
4063
|
+
return this.#decision("ignored", `unsupported ref: ${ref}`, { ...base, ref });
|
|
4064
|
+
}
|
|
4065
|
+
const branch = ref.slice("refs/heads/".length);
|
|
4066
|
+
const forced = payload["forced"] === true;
|
|
4067
|
+
const deleted = payload["deleted"] === true;
|
|
4068
|
+
const repoRecord = record3(payload["repository"]);
|
|
4069
|
+
const defaultBranch = repoRecord ? str(repoRecord["default_branch"]) : null;
|
|
4070
|
+
const watched = this.#branches.length === 0 || this.#branches.includes(branch) || this.#branchDiscovery && defaultBranch !== null && defaultBranch === branch;
|
|
4071
|
+
if (!watched) {
|
|
4072
|
+
return this.#decision("ignored", `branch ${branch} is not watched`, { ...base, ref });
|
|
4073
|
+
}
|
|
4074
|
+
const reason = `${deleted ? "branch deleted" : "push"}${forced ? " (forced)" : ""} on ${branch}`;
|
|
4075
|
+
return this.#decision("accepted", reason, { ...base, action: "sync", ref });
|
|
4076
|
+
}
|
|
4077
|
+
case "repository_dispatch": {
|
|
4078
|
+
const eventType = str(payload["action"]) ?? str(payload["event_type"]) ?? "unknown";
|
|
4079
|
+
return this.#decision("accepted", `repository_dispatch: ${eventType}`, {
|
|
4080
|
+
...base,
|
|
4081
|
+
action: "sync",
|
|
4082
|
+
ref: null
|
|
4083
|
+
});
|
|
4084
|
+
}
|
|
4085
|
+
case "release": {
|
|
4086
|
+
const action = str(payload["action"]) ?? "unknown";
|
|
4087
|
+
if (action === "published" || action === "released" || action === "prereleased") {
|
|
4088
|
+
return this.#decision("accepted", `release ${action}`, { ...base, action: "sync" });
|
|
4089
|
+
}
|
|
4090
|
+
return this.#decision("ignored", `release ${action} does not change the public surface`, base);
|
|
4091
|
+
}
|
|
4092
|
+
case "repository": {
|
|
4093
|
+
const action = str(payload["action"]) ?? "unknown";
|
|
4094
|
+
if (action === "renamed" || action === "deleted" || action === "archived" || action === "unarchived") {
|
|
4095
|
+
return this.#decision("accepted", `repository ${action}`, { ...base, action: "sync" });
|
|
4096
|
+
}
|
|
4097
|
+
return this.#decision("ignored", `repository ${action} does not change the public surface`, base);
|
|
4098
|
+
}
|
|
4099
|
+
default:
|
|
4100
|
+
return this.#decision("ignored", `event ${event} is not deploy-relevant`, base);
|
|
4101
|
+
}
|
|
4102
|
+
}
|
|
4103
|
+
}
|
|
4104
|
+
|
|
4105
|
+
// src/sdk.ts
|
|
4106
|
+
init_delivery();
|
|
4107
|
+
async function fileExists(path) {
|
|
4108
|
+
const runtime = globalThis;
|
|
4109
|
+
if (runtime.Bun?.file)
|
|
4110
|
+
return runtime.Bun.file(path).exists();
|
|
4111
|
+
try {
|
|
4112
|
+
const { access } = await import("fs/promises");
|
|
4113
|
+
await access(path);
|
|
4114
|
+
return true;
|
|
4115
|
+
} catch {
|
|
4116
|
+
return false;
|
|
4117
|
+
}
|
|
4118
|
+
}
|
|
4119
|
+
var RECOGNISED = [CONFIG_SCHEMA];
|
|
4120
|
+
|
|
4121
|
+
class Loom {
|
|
4122
|
+
config;
|
|
4123
|
+
store;
|
|
4124
|
+
#options;
|
|
4125
|
+
#plugins;
|
|
4126
|
+
#listeners = new Set;
|
|
4127
|
+
#controller = new AbortController;
|
|
4128
|
+
#inflight = new Set;
|
|
4129
|
+
#receiver = null;
|
|
4130
|
+
#closed = false;
|
|
4131
|
+
constructor(config, store, options) {
|
|
4132
|
+
this.config = config;
|
|
4133
|
+
this.store = store;
|
|
4134
|
+
this.#options = options;
|
|
4135
|
+
this.#plugins = [...options.plugins ?? []];
|
|
4136
|
+
}
|
|
4137
|
+
static async open(input, options = {}) {
|
|
4138
|
+
const cwd = options.cwd ?? process.cwd();
|
|
4139
|
+
let config;
|
|
4140
|
+
if (typeof input === "string") {
|
|
4141
|
+
config = await loadConfig(resolve(cwd, input));
|
|
4142
|
+
} else if (input === undefined || input === null) {
|
|
4143
|
+
const candidate = resolve(cwd, "loom.config.json");
|
|
4144
|
+
config = await fileExists(candidate) ? await loadConfig(candidate) : await loadConfig(null);
|
|
4145
|
+
} else {
|
|
4146
|
+
config = parseConfig(input);
|
|
4147
|
+
}
|
|
4148
|
+
const root = resolve(cwd, config.store);
|
|
4149
|
+
const store = await SnapshotStore.open(root, { create: options.createStore !== false });
|
|
4150
|
+
return new Loom(config, store, options);
|
|
4151
|
+
}
|
|
4152
|
+
static attach(config, store, options = {}) {
|
|
4153
|
+
return new Loom(config, store, options);
|
|
4154
|
+
}
|
|
4155
|
+
get closed() {
|
|
4156
|
+
return this.#closed;
|
|
4157
|
+
}
|
|
4158
|
+
get token() {
|
|
4159
|
+
if (this.#options.token !== undefined) {
|
|
4160
|
+
return this.#options.token && this.#options.token.length > 0 ? this.#options.token : null;
|
|
4161
|
+
}
|
|
4162
|
+
const name = this.#options.tokenEnv ?? "GITHUB_TOKEN";
|
|
4163
|
+
const value = (this.#options.env ?? process.env)[name];
|
|
4164
|
+
return value && value.length > 0 ? value : null;
|
|
4165
|
+
}
|
|
4166
|
+
#signal(extra) {
|
|
4167
|
+
if (!extra)
|
|
4168
|
+
return this.#controller.signal;
|
|
4169
|
+
return AbortSignal.any([this.#controller.signal, extra]);
|
|
4170
|
+
}
|
|
4171
|
+
#guard() {
|
|
4172
|
+
if (this.#closed)
|
|
4173
|
+
throw new LoomError("cancelled", "Loom instance is closed", { closed: true });
|
|
4174
|
+
}
|
|
4175
|
+
#track(promise) {
|
|
4176
|
+
this.#inflight.add(promise);
|
|
4177
|
+
promise.finally(() => this.#inflight.delete(promise)).catch(() => {});
|
|
4178
|
+
return promise;
|
|
4179
|
+
}
|
|
4180
|
+
#emit(event) {
|
|
4181
|
+
for (const listener of this.#listeners) {
|
|
4182
|
+
try {
|
|
4183
|
+
listener(event);
|
|
4184
|
+
} catch {}
|
|
4185
|
+
}
|
|
4186
|
+
}
|
|
4187
|
+
#pluginContext() {
|
|
4188
|
+
return { config: this.config, storeRoot: this.store.root, now: new Date(this.#options.now?.() ?? Date.now()) };
|
|
4189
|
+
}
|
|
4190
|
+
subscribe(listener) {
|
|
4191
|
+
this.#listeners.add(listener);
|
|
4192
|
+
return () => this.#listeners.delete(listener);
|
|
4193
|
+
}
|
|
4194
|
+
use(plugin) {
|
|
4195
|
+
this.#plugins.push(plugin);
|
|
4196
|
+
return this;
|
|
4197
|
+
}
|
|
4198
|
+
async discover(options = {}) {
|
|
4199
|
+
this.#guard();
|
|
4200
|
+
const client = await this.#client();
|
|
4201
|
+
return discoverRepositories({
|
|
4202
|
+
client,
|
|
4203
|
+
config: this.config.discovery,
|
|
4204
|
+
...this.#options.logger ? { logger: this.#options.logger } : {},
|
|
4205
|
+
signal: this.#signal(options.signal)
|
|
4206
|
+
});
|
|
4207
|
+
}
|
|
4208
|
+
async#client() {
|
|
4209
|
+
const cache = this.#options.cache === null ? new MemoryCache : this.#options.cache ?? new MemoryCache;
|
|
4210
|
+
const fixture = this.#options.fixtureDir ? await loadFixture(this.#options.fixtureDir) : null;
|
|
4211
|
+
return new GitHubClient({
|
|
4212
|
+
baseUrl: fixture?.baseUrl ?? this.config.githubBaseUrl,
|
|
4213
|
+
token: this.token,
|
|
4214
|
+
cache,
|
|
4215
|
+
...fixture ? { fetch: fixture.transport.fetch } : this.#options.fetch ? { fetch: this.#options.fetch } : {},
|
|
4216
|
+
...this.#options.now ? { now: this.#options.now } : {},
|
|
4217
|
+
...this.#options.logger ? { logger: this.#options.logger } : {}
|
|
4218
|
+
});
|
|
4219
|
+
}
|
|
4220
|
+
async sync(options = {}) {
|
|
4221
|
+
this.#guard();
|
|
4222
|
+
const dryRun = options.dryRun === true;
|
|
4223
|
+
const env = options.env ?? this.#options.env ?? process.env;
|
|
4224
|
+
const run = (async () => {
|
|
4225
|
+
const outcome = await runSync({
|
|
4226
|
+
config: this.config,
|
|
4227
|
+
store: this.store,
|
|
4228
|
+
token: this.token,
|
|
4229
|
+
dryRun,
|
|
4230
|
+
dispatch: options.dispatch === true,
|
|
4231
|
+
allowMissingTriggers: options.allowMissingTriggers === true,
|
|
4232
|
+
tolerateErrors: options.tolerateErrors ?? this.#options.tolerateErrors ?? false,
|
|
4233
|
+
lock: options.lock ?? !dryRun,
|
|
4234
|
+
env,
|
|
4235
|
+
signal: this.#signal(options.signal),
|
|
4236
|
+
...this.#options.fixtureDir ? { fixtureDir: this.#options.fixtureDir } : {},
|
|
4237
|
+
...this.#options.dispatchFetch ? { dispatchFetch: this.#options.dispatchFetch } : {},
|
|
4238
|
+
...(options.concurrency ?? this.#options.concurrency) !== undefined ? { concurrency: options.concurrency ?? this.#options.concurrency } : {},
|
|
4239
|
+
...this.#options.now ? { now: this.#options.now } : {},
|
|
4240
|
+
...this.#options.logger ? { logger: this.#options.logger } : {}
|
|
4241
|
+
});
|
|
4242
|
+
return outcome;
|
|
4243
|
+
})();
|
|
4244
|
+
try {
|
|
4245
|
+
const outcome = await this.#track(run);
|
|
4246
|
+
const context = this.#pluginContext();
|
|
4247
|
+
for (const plugin of this.#plugins)
|
|
4248
|
+
await plugin.onSnapshot?.(outcome.snapshot, context);
|
|
4249
|
+
for (const plugin of this.#plugins)
|
|
4250
|
+
await plugin.onDiff?.(outcome.diff, context);
|
|
4251
|
+
if (outcome.triggers.results.length > 0) {
|
|
4252
|
+
for (const plugin of this.#plugins)
|
|
4253
|
+
await plugin.onDeploy?.(outcome.triggers.results, context);
|
|
4254
|
+
this.#emit({ type: "deploy", results: outcome.triggers.results });
|
|
4255
|
+
}
|
|
4256
|
+
this.#emit({ type: "snapshot", snapshot: outcome.snapshot });
|
|
4257
|
+
this.#emit({ type: "diff", diff: outcome.diff });
|
|
4258
|
+
this.#emit({ type: "sync", outcome });
|
|
4259
|
+
return outcome;
|
|
4260
|
+
} catch (error) {
|
|
4261
|
+
const context = this.#pluginContext();
|
|
4262
|
+
for (const plugin of this.#plugins) {
|
|
4263
|
+
try {
|
|
4264
|
+
plugin.onError?.(error, context);
|
|
4265
|
+
} catch {}
|
|
4266
|
+
}
|
|
4267
|
+
this.#emit({ type: "error", error });
|
|
4268
|
+
throw error;
|
|
4269
|
+
}
|
|
4270
|
+
}
|
|
4271
|
+
async snapshot() {
|
|
4272
|
+
this.#guard();
|
|
4273
|
+
const computed = await computeSnapshot2({
|
|
4274
|
+
config: this.config,
|
|
4275
|
+
token: this.token,
|
|
4276
|
+
...this.#options.fixtureDir ? { fixtureDir: this.#options.fixtureDir } : {},
|
|
4277
|
+
...this.#options.fetch ? { fetch: this.#options.fetch } : {},
|
|
4278
|
+
...this.#options.now ? { now: this.#options.now } : {},
|
|
4279
|
+
...this.#options.logger ? { logger: this.#options.logger } : {},
|
|
4280
|
+
tolerateErrors: this.#options.tolerateErrors ?? false,
|
|
4281
|
+
...this.#options.concurrency !== undefined ? { concurrency: this.#options.concurrency } : {}
|
|
4282
|
+
});
|
|
4283
|
+
return computed.snapshot;
|
|
4284
|
+
}
|
|
4285
|
+
async diff(options = {}) {
|
|
4286
|
+
this.#guard();
|
|
4287
|
+
const from = options.from === undefined ? await this.store.head() : options.from;
|
|
4288
|
+
const to = options.to ?? await this.store.head();
|
|
4289
|
+
if (to === null)
|
|
4290
|
+
throw new LoomError("snapshot_missing", "store has no snapshot to diff");
|
|
4291
|
+
return diffSnapshots(from, to, { aliases: this.config.aliases });
|
|
4292
|
+
}
|
|
4293
|
+
async siteRecord(snapshot) {
|
|
4294
|
+
const source = snapshot ?? await this.store.head();
|
|
4295
|
+
if (source === null)
|
|
4296
|
+
throw new LoomError("snapshot_missing", "store has no snapshot; run sync first");
|
|
4297
|
+
return buildSiteRecord(source, {
|
|
4298
|
+
aliases: this.config.aliases,
|
|
4299
|
+
ownerAliases: { ...this.config.ownerAliases, ...ownerAliasesOf(source) }
|
|
4300
|
+
});
|
|
4301
|
+
}
|
|
4302
|
+
async siteModule(options = {}) {
|
|
4303
|
+
return renderSiteModule(await this.siteRecord(), options);
|
|
4304
|
+
}
|
|
4305
|
+
async siteDigest() {
|
|
4306
|
+
return siteDigest(await this.siteRecord());
|
|
4307
|
+
}
|
|
4308
|
+
async receiver(options = {}) {
|
|
4309
|
+
this.#guard();
|
|
4310
|
+
if (this.#receiver)
|
|
4311
|
+
return this.#receiver;
|
|
4312
|
+
const env = this.#options.env ?? process.env;
|
|
4313
|
+
const fromEnv = env[this.config.webhook.secretEnv];
|
|
4314
|
+
const secrets = options.secrets ?? (options.secret ? [options.secret] : fromEnv ? [fromEnv] : []);
|
|
4315
|
+
if (secrets.length === 0) {
|
|
4316
|
+
throw new LoomError("secret_missing", `webhook secret ${this.config.webhook.secretEnv} is not set`, {
|
|
4317
|
+
env: this.config.webhook.secretEnv
|
|
4318
|
+
});
|
|
4319
|
+
}
|
|
4320
|
+
const deliveries = await DeliveryLog.open(this.store.webhookStatePath);
|
|
4321
|
+
this.#receiver = new WebhookReceiver({
|
|
4322
|
+
secrets,
|
|
4323
|
+
deliveries,
|
|
4324
|
+
branches: this.config.branches,
|
|
4325
|
+
branchDiscovery: true,
|
|
4326
|
+
toleranceSeconds: this.config.webhook.toleranceSeconds,
|
|
4327
|
+
maxBodyBytes: this.config.webhook.maxBodyBytes
|
|
4328
|
+
});
|
|
4329
|
+
return this.#receiver;
|
|
4330
|
+
}
|
|
4331
|
+
async verifyWebhook(input, options = {}) {
|
|
4332
|
+
return (await this.receiver(options)).handle(input);
|
|
4333
|
+
}
|
|
4334
|
+
async close() {
|
|
4335
|
+
if (this.#closed)
|
|
4336
|
+
return;
|
|
4337
|
+
this.#closed = true;
|
|
4338
|
+
this.#controller.abort();
|
|
4339
|
+
await Promise.allSettled([...this.#inflight]);
|
|
4340
|
+
this.#listeners.clear();
|
|
4341
|
+
}
|
|
4342
|
+
async drain() {
|
|
4343
|
+
return this.close();
|
|
4344
|
+
}
|
|
4345
|
+
static describeError(error) {
|
|
4346
|
+
if (error instanceof LoomError)
|
|
4347
|
+
return { repo: "", code: error.code, message: error.message };
|
|
4348
|
+
return { code: "unexpected", message: error instanceof Error ? error.message : String(error) };
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
function createLoom(input, options = {}) {
|
|
4352
|
+
return Loom.open(input, options);
|
|
4353
|
+
}
|
|
4354
|
+
function createGitHubClient(config, options = {}) {
|
|
4355
|
+
const env = options.env ?? process.env;
|
|
4356
|
+
const token = options.token !== undefined ? options.token : env[options.tokenEnv ?? "GITHUB_TOKEN"] ?? null;
|
|
4357
|
+
return new GitHubClient({
|
|
4358
|
+
baseUrl: config.githubBaseUrl,
|
|
4359
|
+
token,
|
|
4360
|
+
cache: options.cache === null ? new MemoryCache : options.cache ?? new MemoryCache,
|
|
4361
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
4362
|
+
...options.now ? { now: options.now } : {},
|
|
4363
|
+
...options.logger ? { logger: options.logger } : {}
|
|
4364
|
+
});
|
|
4365
|
+
}
|
|
4366
|
+
var SUPPORTED_CONFIG_SCHEMAS = RECOGNISED;
|
|
4367
|
+
|
|
4368
|
+
// src/index.ts
|
|
4369
|
+
init_cache();
|
|
4370
|
+
init_delivery();
|
|
4371
|
+
|
|
4372
|
+
// src/metrics.ts
|
|
4373
|
+
function labelKey(labels) {
|
|
4374
|
+
if (!labels)
|
|
4375
|
+
return "";
|
|
4376
|
+
const pairs = Object.entries(labels).filter(([, value]) => value !== undefined && value !== null).map(([key, value]) => `${key}="${escape(String(value))}"`).sort();
|
|
4377
|
+
return pairs.join(",");
|
|
4378
|
+
}
|
|
4379
|
+
function escape(value) {
|
|
4380
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
|
|
4381
|
+
}
|
|
4382
|
+
|
|
4383
|
+
class Metrics {
|
|
4384
|
+
#counters = new Map;
|
|
4385
|
+
#gauges = new Map;
|
|
4386
|
+
increment(name, labels, by = 1) {
|
|
4387
|
+
const bucket = this.#counters.get(name) ?? new Map;
|
|
4388
|
+
const key = labelKey(labels);
|
|
4389
|
+
const current = bucket.get(key);
|
|
4390
|
+
bucket.set(key, { labels: labels ?? {}, value: (current?.value ?? 0) + by });
|
|
4391
|
+
this.#counters.set(name, bucket);
|
|
4392
|
+
}
|
|
4393
|
+
gauge(name, value, labels) {
|
|
4394
|
+
const bucket = this.#gauges.get(name) ?? new Map;
|
|
4395
|
+
bucket.set(labelKey(labels), { labels: labels ?? {}, value });
|
|
4396
|
+
this.#gauges.set(name, bucket);
|
|
4397
|
+
}
|
|
4398
|
+
observeDuration(name, startMs, labels) {
|
|
4399
|
+
this.#gauges.set(`${name}_milliseconds`, new Map([
|
|
4400
|
+
[labelKey(labels), { labels: labels ?? {}, value: Math.max(0, Date.now() - startMs) }]
|
|
4401
|
+
]));
|
|
4402
|
+
}
|
|
4403
|
+
snapshot() {
|
|
4404
|
+
const out = {};
|
|
4405
|
+
for (const [name, bucket] of this.#counters)
|
|
4406
|
+
out[name] = [...bucket.values()];
|
|
4407
|
+
for (const [name, bucket] of this.#gauges)
|
|
4408
|
+
out[name] = [...bucket.values()];
|
|
4409
|
+
return out;
|
|
4410
|
+
}
|
|
4411
|
+
render() {
|
|
4412
|
+
const lines = [];
|
|
4413
|
+
const emit = (name, type) => {
|
|
4414
|
+
const bucket = (type === "counter" ? this.#counters : this.#gauges).get(name);
|
|
4415
|
+
if (!bucket)
|
|
4416
|
+
return;
|
|
4417
|
+
lines.push(`# TYPE ${name} ${type}`);
|
|
4418
|
+
for (const sample of bucket.values()) {
|
|
4419
|
+
const labels = labelKey(sample.labels);
|
|
4420
|
+
lines.push(`${name}${labels ? `{${labels}}` : ""} ${sample.value}`);
|
|
4421
|
+
}
|
|
4422
|
+
};
|
|
4423
|
+
for (const name of [...this.#counters.keys()].sort())
|
|
4424
|
+
emit(name, "counter");
|
|
4425
|
+
for (const name of [...this.#gauges.keys()].sort())
|
|
4426
|
+
emit(name, "gauge");
|
|
4427
|
+
return `${lines.join(`
|
|
4428
|
+
`)}
|
|
4429
|
+
`;
|
|
4430
|
+
}
|
|
4431
|
+
}
|
|
4432
|
+
|
|
4433
|
+
// src/queue.ts
|
|
4434
|
+
class SyncQueue {
|
|
4435
|
+
#maxDepth;
|
|
4436
|
+
#onDepth;
|
|
4437
|
+
#entries = [];
|
|
4438
|
+
#known = new Map;
|
|
4439
|
+
#active = null;
|
|
4440
|
+
#running = false;
|
|
4441
|
+
#closed = false;
|
|
4442
|
+
#enqueued = 0;
|
|
4443
|
+
#completed = 0;
|
|
4444
|
+
#failed = 0;
|
|
4445
|
+
#rejectedFull = 0;
|
|
4446
|
+
#deduped = 0;
|
|
4447
|
+
constructor(options = {}) {
|
|
4448
|
+
this.#maxDepth = Math.max(0, options.maxDepth ?? 32);
|
|
4449
|
+
this.#onDepth = options.onDepth;
|
|
4450
|
+
}
|
|
4451
|
+
get stats() {
|
|
4452
|
+
return {
|
|
4453
|
+
depth: this.#entries.length,
|
|
4454
|
+
active: this.#active === null ? 0 : 1,
|
|
4455
|
+
enqueued: this.#enqueued,
|
|
4456
|
+
completed: this.#completed,
|
|
4457
|
+
failed: this.#failed,
|
|
4458
|
+
rejectedFull: this.#rejectedFull,
|
|
4459
|
+
deduped: this.#deduped,
|
|
4460
|
+
closed: this.#closed
|
|
4461
|
+
};
|
|
4462
|
+
}
|
|
4463
|
+
#emit() {
|
|
4464
|
+
this.#onDepth?.(this.#entries.length, this.#active === null ? 0 : 1);
|
|
4465
|
+
}
|
|
4466
|
+
enqueue(key, job) {
|
|
4467
|
+
if (this.#closed) {
|
|
4468
|
+
const promise = Promise.reject(new LoomError("queue_full", "sync queue is closed"));
|
|
4469
|
+
promise.catch(() => {});
|
|
4470
|
+
return { state: "closed", promise };
|
|
4471
|
+
}
|
|
4472
|
+
const existing = this.#known.get(key);
|
|
4473
|
+
if (existing) {
|
|
4474
|
+
this.#deduped += 1;
|
|
4475
|
+
return { state: "duplicate", promise: existing };
|
|
4476
|
+
}
|
|
4477
|
+
if (this.#entries.length >= this.#maxDepth) {
|
|
4478
|
+
this.#rejectedFull += 1;
|
|
4479
|
+
const promise = Promise.reject(new LoomError("queue_full", "sync queue is full", { depth: this.#entries.length, maxDepth: this.#maxDepth }));
|
|
4480
|
+
promise.catch(() => {});
|
|
4481
|
+
return { state: "full", promise };
|
|
4482
|
+
}
|
|
4483
|
+
let resolve;
|
|
4484
|
+
let reject;
|
|
4485
|
+
const promise = new Promise((res, rej) => {
|
|
4486
|
+
resolve = res;
|
|
4487
|
+
reject = rej;
|
|
4488
|
+
});
|
|
4489
|
+
const entry = { key, job, resolve, reject };
|
|
4490
|
+
this.#entries.push(entry);
|
|
4491
|
+
this.#known.set(key, promise);
|
|
4492
|
+
this.#enqueued += 1;
|
|
4493
|
+
this.#emit();
|
|
4494
|
+
this.#pump();
|
|
4495
|
+
return { state: "accepted", promise };
|
|
4496
|
+
}
|
|
4497
|
+
async#pump() {
|
|
4498
|
+
if (this.#running)
|
|
4499
|
+
return;
|
|
4500
|
+
this.#running = true;
|
|
4501
|
+
try {
|
|
4502
|
+
for (;; ) {
|
|
4503
|
+
const entry = this.#entries.shift();
|
|
4504
|
+
if (!entry)
|
|
4505
|
+
break;
|
|
4506
|
+
this.#active = { key: entry.key, promise: Promise.resolve() };
|
|
4507
|
+
this.#emit();
|
|
4508
|
+
try {
|
|
4509
|
+
const value = await entry.job();
|
|
4510
|
+
this.#completed += 1;
|
|
4511
|
+
entry.resolve(value);
|
|
4512
|
+
} catch (error) {
|
|
4513
|
+
this.#failed += 1;
|
|
4514
|
+
entry.reject(error);
|
|
4515
|
+
} finally {
|
|
4516
|
+
this.#known.delete(entry.key);
|
|
4517
|
+
this.#active = null;
|
|
4518
|
+
this.#emit();
|
|
4519
|
+
}
|
|
4520
|
+
}
|
|
4521
|
+
} finally {
|
|
4522
|
+
this.#running = false;
|
|
4523
|
+
}
|
|
4524
|
+
}
|
|
4525
|
+
async drain(timeoutMs = 30000) {
|
|
4526
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
4527
|
+
while (this.#entries.length > 0 || this.#active !== null) {
|
|
4528
|
+
if (Date.now() >= deadline)
|
|
4529
|
+
return { drained: false, stats: this.stats };
|
|
4530
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
4531
|
+
}
|
|
4532
|
+
return { drained: true, stats: this.stats };
|
|
4533
|
+
}
|
|
4534
|
+
close() {
|
|
4535
|
+
this.#closed = true;
|
|
4536
|
+
this.#emit();
|
|
4537
|
+
}
|
|
4538
|
+
}
|
|
4539
|
+
|
|
4540
|
+
// src/serve-handler.ts
|
|
4541
|
+
var WEBHOOK_RESPONSE_SCHEMA = "loom/webhook-response@1";
|
|
4542
|
+
function json(status, body, headers = {}) {
|
|
4543
|
+
return new Response(JSON.stringify(body), {
|
|
4544
|
+
status,
|
|
4545
|
+
headers: {
|
|
4546
|
+
"content-type": "application/json; charset=utf-8",
|
|
4547
|
+
"cache-control": "no-store",
|
|
4548
|
+
...headers
|
|
4549
|
+
}
|
|
4550
|
+
});
|
|
4551
|
+
}
|
|
4552
|
+
function webhookBody(decision, extra = {}) {
|
|
4553
|
+
return {
|
|
4554
|
+
schema: WEBHOOK_RESPONSE_SCHEMA,
|
|
4555
|
+
ok: true,
|
|
4556
|
+
kind: decision.kind,
|
|
4557
|
+
event: decision.event,
|
|
4558
|
+
delivery: decision.delivery,
|
|
4559
|
+
...extra
|
|
4560
|
+
};
|
|
4561
|
+
}
|
|
4562
|
+
function createHandler(deps) {
|
|
4563
|
+
const log = deps.logger ?? (() => {});
|
|
4564
|
+
const metrics = deps.metrics ?? new Metrics;
|
|
4565
|
+
const startedAt = new Date().toISOString();
|
|
4566
|
+
let closing = false;
|
|
4567
|
+
let pollTimer = null;
|
|
4568
|
+
const queue = deps.queue ?? new SyncQueue({
|
|
4569
|
+
maxDepth: deps.config.serve.queueDepth,
|
|
4570
|
+
onDepth: (depth, active) => {
|
|
4571
|
+
metrics.gauge("loom_queue_depth", depth);
|
|
4572
|
+
metrics.gauge("loom_queue_active", active);
|
|
4573
|
+
}
|
|
4574
|
+
});
|
|
4575
|
+
const runJob = async (decision, producer) => {
|
|
4576
|
+
const started = Date.now();
|
|
4577
|
+
const trigger = decision.delivery.startsWith("poll:") ? "poll" : "webhook";
|
|
4578
|
+
try {
|
|
4579
|
+
const outcome = await producer();
|
|
4580
|
+
metrics.increment("loom_sync_total", {
|
|
4581
|
+
trigger,
|
|
4582
|
+
status: outcome.status,
|
|
4583
|
+
changed: String(outcome.diff.changed)
|
|
4584
|
+
});
|
|
4585
|
+
metrics.gauge("loom_sync_duration_milliseconds", Date.now() - started);
|
|
4586
|
+
metrics.gauge("loom_snapshot_repositories", outcome.stats.repos, { snapshot: outcome.snapshot.id });
|
|
4587
|
+
return outcome;
|
|
4588
|
+
} catch (error) {
|
|
4589
|
+
metrics.increment("loom_sync_total", { trigger, status: "failed", changed: "unknown" });
|
|
4590
|
+
throw error;
|
|
4591
|
+
}
|
|
4592
|
+
};
|
|
4593
|
+
const runSync = (decision) => runJob(decision, () => deps.onSync(decision));
|
|
4594
|
+
const handler = async (request) => {
|
|
4595
|
+
const url = new URL(request.url);
|
|
4596
|
+
if (request.method === "GET" && url.pathname === "/healthz") {
|
|
4597
|
+
try {
|
|
4598
|
+
const manifest = await deps.store.readManifest();
|
|
4599
|
+
metrics.increment("loom_http_requests_total", { route: "/healthz", status: 200 });
|
|
4600
|
+
return json(200, {
|
|
4601
|
+
ok: true,
|
|
4602
|
+
service: "loom",
|
|
4603
|
+
closing,
|
|
4604
|
+
snapshot: manifest?.snapshot ?? null,
|
|
4605
|
+
createdAt: manifest?.createdAt ?? null,
|
|
4606
|
+
queue: queue.stats
|
|
4607
|
+
});
|
|
4608
|
+
} catch (error) {
|
|
4609
|
+
const failure = describeError(error);
|
|
4610
|
+
metrics.increment("loom_http_requests_total", { route: "/healthz", status: 503 });
|
|
4611
|
+
return json(503, { ok: false, service: "loom", error: failure.code, message: failure.message });
|
|
4612
|
+
}
|
|
4613
|
+
}
|
|
4614
|
+
if (request.method === "GET" && url.pathname === "/readyz") {
|
|
4615
|
+
if (closing) {
|
|
4616
|
+
metrics.increment("loom_http_requests_total", { route: "/readyz", status: 503 });
|
|
4617
|
+
return json(503, { ok: false, closing: true });
|
|
4618
|
+
}
|
|
4619
|
+
try {
|
|
4620
|
+
await deps.store.readManifest();
|
|
4621
|
+
metrics.increment("loom_http_requests_total", { route: "/readyz", status: 200 });
|
|
4622
|
+
return json(200, { ok: true, queue: queue.stats });
|
|
4623
|
+
} catch (error) {
|
|
4624
|
+
const failure = describeError(error);
|
|
4625
|
+
metrics.increment("loom_http_requests_total", { route: "/readyz", status: 503 });
|
|
4626
|
+
return json(503, { ok: false, error: failure.code, message: failure.message });
|
|
4627
|
+
}
|
|
4628
|
+
}
|
|
4629
|
+
if (request.method === "GET" && url.pathname === "/state") {
|
|
4630
|
+
try {
|
|
4631
|
+
const manifest = await deps.store.readManifest();
|
|
4632
|
+
metrics.increment("loom_http_requests_total", { route: "/state", status: 200 });
|
|
4633
|
+
return json(200, { ok: true, manifest });
|
|
4634
|
+
} catch (error) {
|
|
4635
|
+
const failure = describeError(error);
|
|
4636
|
+
metrics.increment("loom_http_requests_total", { route: "/state", status: 503 });
|
|
4637
|
+
return json(503, { ok: false, error: failure.code, message: failure.message });
|
|
4638
|
+
}
|
|
4639
|
+
}
|
|
4640
|
+
if (request.method === "GET" && url.pathname === "/metrics") {
|
|
4641
|
+
metrics.gauge("loom_queue_depth", queue.stats.depth);
|
|
4642
|
+
metrics.gauge("loom_queue_active", queue.stats.active);
|
|
4643
|
+
metrics.increment("loom_http_requests_total", { route: "/metrics", status: 200 });
|
|
4644
|
+
return new Response(metrics.render(), {
|
|
4645
|
+
status: 200,
|
|
4646
|
+
headers: { "content-type": "text/plain; version=0.0.4; charset=utf-8", "cache-control": "no-store" }
|
|
4647
|
+
});
|
|
4648
|
+
}
|
|
4649
|
+
if (url.pathname !== deps.config.webhook.path) {
|
|
4650
|
+
metrics.increment("loom_http_requests_total", { route: "not_found", status: 404 });
|
|
4651
|
+
return json(404, { ok: false, error: "not_found" });
|
|
4652
|
+
}
|
|
4653
|
+
if (request.method !== "POST") {
|
|
4654
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 405 });
|
|
4655
|
+
return json(405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
|
|
4656
|
+
}
|
|
4657
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
4658
|
+
if (Number.isFinite(declared) && declared > deps.config.webhook.maxBodyBytes) {
|
|
4659
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 413 });
|
|
4660
|
+
return json(413, { ok: false, error: "payload_too_large" });
|
|
4661
|
+
}
|
|
4662
|
+
let body;
|
|
4663
|
+
try {
|
|
4664
|
+
const buffer = new Uint8Array(await request.arrayBuffer());
|
|
4665
|
+
if (buffer.length > deps.config.webhook.maxBodyBytes) {
|
|
4666
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 413 });
|
|
4667
|
+
return json(413, { ok: false, error: "payload_too_large" });
|
|
4668
|
+
}
|
|
4669
|
+
body = buffer;
|
|
4670
|
+
} catch {
|
|
4671
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 400 });
|
|
4672
|
+
return json(400, { ok: false, error: "unreadable_body" });
|
|
4673
|
+
}
|
|
4674
|
+
let decision;
|
|
4675
|
+
try {
|
|
4676
|
+
decision = await deps.receiver.handle({ headers: request.headers, body });
|
|
4677
|
+
} catch (error) {
|
|
4678
|
+
const failure = describeError(error);
|
|
4679
|
+
log("webhook handler failed", { code: failure.code });
|
|
4680
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 500 });
|
|
4681
|
+
return json(500, { ok: false, error: failure.code });
|
|
4682
|
+
}
|
|
4683
|
+
if (decision.kind === "unauthorized") {
|
|
4684
|
+
metrics.increment("loom_webhook_total", { kind: decision.kind, event: decision.event });
|
|
4685
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 401 });
|
|
4686
|
+
return json(401, webhookBody(decision, { ok: false, reason: decision.reason }));
|
|
4687
|
+
}
|
|
4688
|
+
if (decision.kind === "invalid") {
|
|
4689
|
+
metrics.increment("loom_webhook_total", { kind: decision.kind, event: decision.event });
|
|
4690
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 400 });
|
|
4691
|
+
return json(400, webhookBody(decision, { ok: false, reason: decision.reason }));
|
|
4692
|
+
}
|
|
4693
|
+
if (decision.kind === "duplicate") {
|
|
4694
|
+
metrics.increment("loom_webhook_total", { kind: decision.kind, event: decision.event });
|
|
4695
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 202 });
|
|
4696
|
+
return json(202, webhookBody(decision, { reason: decision.reason }));
|
|
4697
|
+
}
|
|
4698
|
+
if (decision.kind === "ignored" || decision.action !== "sync") {
|
|
4699
|
+
await deps.receiver.markDelivered(decision);
|
|
4700
|
+
metrics.increment("loom_webhook_total", { kind: decision.kind, event: decision.event });
|
|
4701
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 202 });
|
|
4702
|
+
return json(202, webhookBody(decision, { reason: decision.reason, action: decision.action }));
|
|
4703
|
+
}
|
|
4704
|
+
if (closing) {
|
|
4705
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 503 });
|
|
4706
|
+
return json(503, webhookBody(decision, { ok: false, reason: "shutting down" }), { "retry-after": "5" });
|
|
4707
|
+
}
|
|
4708
|
+
const key = decision.delivery;
|
|
4709
|
+
const enqueued = queue.enqueue(key, async () => {
|
|
4710
|
+
const outcome = await runSync(decision);
|
|
4711
|
+
await deps.receiver.markDelivered(decision);
|
|
4712
|
+
return outcome;
|
|
4713
|
+
});
|
|
4714
|
+
if (enqueued.state === "full") {
|
|
4715
|
+
metrics.increment("loom_queue_rejected_total");
|
|
4716
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 503 });
|
|
4717
|
+
log("webhook rejected: queue full", { delivery: decision.delivery, depth: queue.stats.depth });
|
|
4718
|
+
return json(503, webhookBody(decision, {
|
|
4719
|
+
ok: false,
|
|
4720
|
+
error: "queue_full",
|
|
4721
|
+
reason: "sync queue is full; retry later",
|
|
4722
|
+
queue: queue.stats
|
|
4723
|
+
}), { "retry-after": "5" });
|
|
4724
|
+
}
|
|
4725
|
+
if (enqueued.state === "duplicate") {
|
|
4726
|
+
metrics.increment("loom_webhook_total", { kind: "duplicate", event: decision.event });
|
|
4727
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 202 });
|
|
4728
|
+
return json(202, webhookBody(decision, { kind: "duplicate", reason: "delivery already queued" }));
|
|
4729
|
+
}
|
|
4730
|
+
if (enqueued.state === "closed") {
|
|
4731
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 503 });
|
|
4732
|
+
return json(503, webhookBody(decision, { ok: false, reason: "shutting down" }), { "retry-after": "5" });
|
|
4733
|
+
}
|
|
4734
|
+
metrics.increment("loom_webhook_total", { kind: "accepted", event: decision.event });
|
|
4735
|
+
try {
|
|
4736
|
+
const outcome = await enqueued.promise;
|
|
4737
|
+
metrics.increment("loom_deploy_total", { changed: String(outcome.diff.changed) });
|
|
4738
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status: 202 });
|
|
4739
|
+
return json(202, webhookBody(decision, {
|
|
4740
|
+
action: "sync",
|
|
4741
|
+
repo: decision.repo,
|
|
4742
|
+
ref: decision.ref,
|
|
4743
|
+
changed: outcome.diff.changed,
|
|
4744
|
+
snapshot: outcome.snapshot.id,
|
|
4745
|
+
status: outcome.status,
|
|
4746
|
+
events: outcome.diff.summary,
|
|
4747
|
+
triggers: outcome.triggers.results.map((result) => ({
|
|
4748
|
+
kind: result.kind,
|
|
4749
|
+
ok: result.ok,
|
|
4750
|
+
status: result.status,
|
|
4751
|
+
skipped: result.skipped
|
|
4752
|
+
})),
|
|
4753
|
+
outbox: outcome.outbox
|
|
4754
|
+
}));
|
|
4755
|
+
} catch (error) {
|
|
4756
|
+
const failure = describeError(error);
|
|
4757
|
+
const retryable = error instanceof LoomError && (error.code === "rate_limit_exhausted" || error.code === "cancelled" || error.code === "lock_busy");
|
|
4758
|
+
const status = retryable ? 503 : 500;
|
|
4759
|
+
log("sync failed; delivery not recorded", { code: failure.code, delivery: decision.delivery });
|
|
4760
|
+
metrics.increment("loom_http_requests_total", { route: "webhook", status });
|
|
4761
|
+
return json(status, webhookBody(decision, { ok: false, error: failure.code, message: failure.message, hint: failure.hint }), status === 503 ? { "retry-after": "30" } : {});
|
|
4762
|
+
}
|
|
4763
|
+
};
|
|
4764
|
+
if (deps.onPoll && deps.config.serve.pollIntervalSeconds > 0) {
|
|
4765
|
+
const intervalMs = deps.config.serve.pollIntervalSeconds * 1000;
|
|
4766
|
+
pollTimer = setInterval(() => {
|
|
4767
|
+
if (closing)
|
|
4768
|
+
return;
|
|
4769
|
+
const decision = {
|
|
4770
|
+
kind: "accepted",
|
|
4771
|
+
event: "schedule",
|
|
4772
|
+
delivery: `poll:${Date.now()}`,
|
|
4773
|
+
action: "sync",
|
|
4774
|
+
repo: null,
|
|
4775
|
+
ref: null,
|
|
4776
|
+
payloadHash: "",
|
|
4777
|
+
reason: "reconciliation poll"
|
|
4778
|
+
};
|
|
4779
|
+
const enqueued = queue.enqueue(decision.delivery, () => deps.onPoll ? runJob(decision, deps.onPoll) : runSync(decision));
|
|
4780
|
+
if (enqueued.state === "full") {
|
|
4781
|
+
metrics.increment("loom_queue_rejected_total");
|
|
4782
|
+
log("poll skipped: queue full", { depth: queue.stats.depth });
|
|
4783
|
+
} else if (enqueued.state === "accepted") {
|
|
4784
|
+
enqueued.promise.catch((error) => {
|
|
4785
|
+
log("poll sync failed", { code: describeError(error).code });
|
|
4786
|
+
});
|
|
4787
|
+
}
|
|
4788
|
+
}, intervalMs);
|
|
4789
|
+
pollTimer.unref?.();
|
|
4790
|
+
}
|
|
4791
|
+
const close = () => {
|
|
4792
|
+
closing = true;
|
|
4793
|
+
if (pollTimer !== null)
|
|
4794
|
+
clearInterval(pollTimer);
|
|
4795
|
+
pollTimer = null;
|
|
4796
|
+
queue.close();
|
|
4797
|
+
};
|
|
4798
|
+
Object.defineProperty(handler, "metrics", { value: metrics });
|
|
4799
|
+
Object.defineProperty(handler, "queue", { value: queue });
|
|
4800
|
+
Object.defineProperty(handler, "drain", {
|
|
4801
|
+
value: (timeoutMs) => queue.drain(timeoutMs ?? deps.config.serve.shutdownTimeoutSeconds * 1000)
|
|
4802
|
+
});
|
|
4803
|
+
Object.defineProperty(handler, "close", { value: close });
|
|
4804
|
+
Object.defineProperty(handler, "stats", {
|
|
4805
|
+
value: () => ({ queue: queue.stats, startedAt })
|
|
4806
|
+
});
|
|
4807
|
+
return handler;
|
|
4808
|
+
}
|
|
4809
|
+
export {
|
|
4810
|
+
CONFIG_SCHEMA,
|
|
4811
|
+
DEFAULT_CONFIG,
|
|
4812
|
+
DeliveryLog,
|
|
4813
|
+
EXIT,
|
|
4814
|
+
FileCache,
|
|
4815
|
+
GitHubClient,
|
|
4816
|
+
Loom,
|
|
4817
|
+
LoomError,
|
|
4818
|
+
MemoryCache,
|
|
4819
|
+
Metrics,
|
|
4820
|
+
SITE_SCHEMA,
|
|
4821
|
+
SNAPSHOT_SCHEMA,
|
|
4822
|
+
SUPPORTED_CONFIG_SCHEMAS,
|
|
4823
|
+
SnapshotStore,
|
|
4824
|
+
SyncQueue,
|
|
4825
|
+
VERSION,
|
|
4826
|
+
WebhookReceiver,
|
|
4827
|
+
buildSiteRecord,
|
|
4828
|
+
computeSnapshot2 as computeSnapshot,
|
|
4829
|
+
createFixtureTransport,
|
|
4830
|
+
createGitHubClient,
|
|
4831
|
+
createHandler,
|
|
4832
|
+
createLoom,
|
|
4833
|
+
describeEvent,
|
|
4834
|
+
diffSnapshots,
|
|
4835
|
+
discoverRepositories,
|
|
4836
|
+
isRepoGlob,
|
|
4837
|
+
isRepoName,
|
|
4838
|
+
loadConfig,
|
|
4839
|
+
loadFixture,
|
|
4840
|
+
nextLink,
|
|
4841
|
+
parseConfig,
|
|
4842
|
+
parseRateLimit,
|
|
4843
|
+
renderSiteModule,
|
|
4844
|
+
repoGlobMatches,
|
|
4845
|
+
repoKey,
|
|
4846
|
+
resolveRepoAlias,
|
|
4847
|
+
runSync,
|
|
4848
|
+
signBody,
|
|
4849
|
+
siteDigest,
|
|
4850
|
+
siteModuleDigest,
|
|
4851
|
+
siteProject,
|
|
4852
|
+
snapshotStats,
|
|
4853
|
+
verifySignature
|
|
4854
|
+
};
|