@mono-lit/utility 0.0.0-stage โ 0.0.1
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/LICENSE.md +54 -0
- package/README.md +156 -2
- package/dist/app-roots-BJsIxzjk.d.ts +91 -0
- package/dist/app-roots-CvJnmXcs.js +128 -0
- package/dist/config-node-UzJrXg0Z.js +76 -0
- package/dist/config-node.d.ts +977 -0
- package/dist/config-node.js +7 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +3 -0
- package/dist/create-config-D3m6xTaQ.d.ts +733 -0
- package/dist/create-config-DdL3Fh6T.js +357 -0
- package/dist/fetching.d.ts +239 -0
- package/dist/fetching.js +867 -0
- package/dist/generate-CJ7MtcDd.js +291 -0
- package/dist/index-C2hZeNkq.d.ts +365 -0
- package/dist/index-ClrZbU7n.d.ts +518 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +939 -0
- package/dist/merge-file-C5nzi_MY.d.ts +122 -0
- package/dist/merge-file-CtyKTu5L.js +133 -0
- package/dist/mock-db-5mJTObSC.js +1282 -0
- package/dist/mock-db.d.ts +2 -0
- package/dist/mock-db.js +4 -0
- package/dist/mono-alias-DNDm-jB_.js +508 -0
- package/dist/mono-clone.mjs +958 -0
- package/dist/mono-db.d.ts +1 -0
- package/dist/mono-db.js +151 -0
- package/dist/mono-env.mjs +231 -0
- package/dist/mono-git.mjs +798 -0
- package/dist/mono-link-YlOQ2PVS.js +488 -0
- package/dist/mono-prepare.d.ts +1 -0
- package/dist/mono-prepare.js +27 -0
- package/dist/mono-skills.d.ts +1 -0
- package/dist/mono-skills.js +830 -0
- package/dist/mono-tsconfig-D2qRL9_R.js +204 -0
- package/dist/mono.mjs +34 -0
- package/dist/nuxt-layers-DP1m7f1-.js +176 -0
- package/dist/nuxt-layers.d.ts +34 -0
- package/dist/nuxt-layers.js +3 -0
- package/dist/nuxt-runtime.d.ts +18 -0
- package/dist/nuxt-runtime.js +102 -0
- package/dist/nuxt.d.ts +386 -0
- package/dist/nuxt.js +590 -0
- package/dist/runtime-C_IWNrAG.js +5817 -0
- package/dist/runtime.d.ts +2583 -0
- package/dist/runtime.js +4 -0
- package/dist/session-Bk985AIM.js +1721 -0
- package/dist/types-B6FdB7LJ.d.ts +57 -0
- package/dist/universal-B2eD9xho.d.ts +97 -0
- package/dist/universal-BNTo_83u.js +599 -0
- package/dist/virtual-mono-apps.d.ts +16 -0
- package/dist/vite.d.ts +940 -0
- package/dist/vite.js +1132 -0
- package/package.json +141 -3
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import https from "node:https";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { execSync } from "node:child_process";
|
|
7
|
+
import dotenv from "dotenv";
|
|
8
|
+
import {
|
|
9
|
+
runGit,
|
|
10
|
+
materializeGitTree,
|
|
11
|
+
swapIntoPlace,
|
|
12
|
+
sweepStrayStages,
|
|
13
|
+
stagePathFor,
|
|
14
|
+
parseGithubUrl,
|
|
15
|
+
resolveTransport,
|
|
16
|
+
resolveGitMethod,
|
|
17
|
+
parseSyncArgv,
|
|
18
|
+
accessCacheGet,
|
|
19
|
+
accessCacheSet,
|
|
20
|
+
isShortSha,
|
|
21
|
+
ago,
|
|
22
|
+
refDirCandidates,
|
|
23
|
+
validateAppEntry,
|
|
24
|
+
resolveAppSource,
|
|
25
|
+
resolveRefDir,
|
|
26
|
+
pickSubtree,
|
|
27
|
+
MONO_APPS_DIR,
|
|
28
|
+
orphanAppDirs,
|
|
29
|
+
appDirToPrune,
|
|
30
|
+
staleCacheKeys,
|
|
31
|
+
staleAccessKeys,
|
|
32
|
+
pruneMonoTsconfigPaths,
|
|
33
|
+
resolvePrune,
|
|
34
|
+
} from "./mono-git.mjs";
|
|
35
|
+
|
|
36
|
+
dotenv.config();
|
|
37
|
+
|
|
38
|
+
const argv = parseSyncArgv(process.argv.slice(2));
|
|
39
|
+
|
|
40
|
+
function findMonoConfigFile(cwd = process.cwd()) {
|
|
41
|
+
const names = [
|
|
42
|
+
'mono.config.ts',
|
|
43
|
+
'mono.config.js',
|
|
44
|
+
'mono.config.mjs',
|
|
45
|
+
'mono.config.cjs',
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
for (const name of names) {
|
|
49
|
+
const file = path.resolve(cwd, name);
|
|
50
|
+
|
|
51
|
+
if (exists(file)) {
|
|
52
|
+
return file;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Cannot find mono config file. Expected one of: ${names.join(', ')}`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function stripCommentsSafe(code) {
|
|
62
|
+
let out = ''
|
|
63
|
+
let quote = null
|
|
64
|
+
let escaped = false
|
|
65
|
+
let inLineComment = false
|
|
66
|
+
let inBlockComment = false
|
|
67
|
+
|
|
68
|
+
for (let i = 0; i < code.length; i++) {
|
|
69
|
+
const ch = code[i]
|
|
70
|
+
const next = code[i + 1]
|
|
71
|
+
|
|
72
|
+
if (inLineComment) {
|
|
73
|
+
if (ch === '\n') {
|
|
74
|
+
inLineComment = false
|
|
75
|
+
out += ch
|
|
76
|
+
}
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (inBlockComment) {
|
|
81
|
+
if (ch === '*' && next === '/') {
|
|
82
|
+
inBlockComment = false
|
|
83
|
+
i++
|
|
84
|
+
}
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (quote) {
|
|
89
|
+
out += ch
|
|
90
|
+
|
|
91
|
+
if (escaped) {
|
|
92
|
+
escaped = false
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (ch === '\\') {
|
|
97
|
+
escaped = true
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (ch === quote) {
|
|
102
|
+
quote = null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
109
|
+
quote = ch
|
|
110
|
+
out += ch
|
|
111
|
+
continue
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (ch === '/' && next === '/') {
|
|
115
|
+
inLineComment = true
|
|
116
|
+
i++
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (ch === '/' && next === '*') {
|
|
121
|
+
inBlockComment = true
|
|
122
|
+
i++
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
out += ch
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return out
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function findMatchingBracket(code, startIndex, openChar, closeChar) {
|
|
133
|
+
let depth = 0
|
|
134
|
+
let quote = null
|
|
135
|
+
let escaped = false
|
|
136
|
+
|
|
137
|
+
for (let i = startIndex; i < code.length; i++) {
|
|
138
|
+
const ch = code[i]
|
|
139
|
+
|
|
140
|
+
if (quote) {
|
|
141
|
+
if (escaped) {
|
|
142
|
+
escaped = false
|
|
143
|
+
continue
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (ch === '\\') {
|
|
147
|
+
escaped = true
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (ch === quote) {
|
|
152
|
+
quote = null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
159
|
+
quote = ch
|
|
160
|
+
continue
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (ch === openChar) {
|
|
164
|
+
depth++
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (ch === closeChar) {
|
|
168
|
+
depth--
|
|
169
|
+
|
|
170
|
+
if (depth === 0) {
|
|
171
|
+
return i
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return -1
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function extractAppsArrayText(code) {
|
|
180
|
+
const clean = stripCommentsSafe(code)
|
|
181
|
+
|
|
182
|
+
const appsMatch = /\bapps\s*:/.exec(clean)
|
|
183
|
+
|
|
184
|
+
if (!appsMatch) {
|
|
185
|
+
return null
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const afterApps = appsMatch.index + appsMatch[0].length
|
|
189
|
+
const arrayStart = clean.indexOf('[', afterApps)
|
|
190
|
+
|
|
191
|
+
if (arrayStart === -1) {
|
|
192
|
+
throw new Error(`Found "apps:" but value is not an array literal.`)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const arrayEnd = findMatchingBracket(clean, arrayStart, '[', ']')
|
|
196
|
+
|
|
197
|
+
if (arrayEnd === -1) {
|
|
198
|
+
throw new Error(`Cannot find closing "]" for apps array.`)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return clean.slice(arrayStart, arrayEnd + 1)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function parseAppsArray(arrayText) {
|
|
205
|
+
/**
|
|
206
|
+
* This evaluates only the extracted apps array, not the whole mono.config.ts.
|
|
207
|
+
*
|
|
208
|
+
* It supports JS object syntax:
|
|
209
|
+
* - single quotes
|
|
210
|
+
* - trailing commas
|
|
211
|
+
* - unquoted object keys
|
|
212
|
+
*
|
|
213
|
+
* Keep apps static. Do not use variables or functions inside apps.
|
|
214
|
+
*/
|
|
215
|
+
const apps = Function(`"use strict"; return (${arrayText});`)();
|
|
216
|
+
|
|
217
|
+
if (!Array.isArray(apps)) {
|
|
218
|
+
throw new Error(`mono config "apps" must be an array.`);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
for (const app of apps) {
|
|
222
|
+
const problem = validateAppEntry(app);
|
|
223
|
+
if (problem) {
|
|
224
|
+
throw new Error(
|
|
225
|
+
`Every mono app needs "name" and at least one of "url" / "path" (${problem}). Invalid item: ${JSON.stringify(app)}`
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return apps;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function readAppsFromMonoConfig() {
|
|
234
|
+
const configFile = findMonoConfigFile();
|
|
235
|
+
const code = fs.readFileSync(configFile, 'utf8');
|
|
236
|
+
|
|
237
|
+
const appsText = extractAppsArrayText(code);
|
|
238
|
+
|
|
239
|
+
// `found` is NOT `apps.length > 0`. An absent `apps:` key and an explicit
|
|
240
|
+
// `apps: []` look identical downstream but mean opposite things to the prune:
|
|
241
|
+
// "I could not read a list" must never delete every clone, while "the list is
|
|
242
|
+
// empty" legitimately does. Only the second sets `found`.
|
|
243
|
+
if (!appsText) {
|
|
244
|
+
console.log(`No apps array found in ${configFile}.`);
|
|
245
|
+
return { apps: [], found: false };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const apps = parseAppsArray(appsText);
|
|
249
|
+
|
|
250
|
+
console.log(`๐ฆ Loaded ${apps.length} app(s) from ${path.basename(configFile)}`);
|
|
251
|
+
|
|
252
|
+
return { apps, found: true };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// const apps = JSON.parse(fs.readFileSync("mono.apps.json", "utf8"));
|
|
256
|
+
|
|
257
|
+
function rmrf(p) {
|
|
258
|
+
fs.rmSync(p, { recursive: true, force: true });
|
|
259
|
+
}
|
|
260
|
+
function mkdirp(p) {
|
|
261
|
+
fs.mkdirSync(p, { recursive: true });
|
|
262
|
+
}
|
|
263
|
+
function exists(p) {
|
|
264
|
+
try {
|
|
265
|
+
fs.accessSync(p);
|
|
266
|
+
return true;
|
|
267
|
+
} catch {
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* A cloned app ships a `tsconfig.json` whose `extends`/`references` point at
|
|
274
|
+
* GENERATED tsconfigs that only exist locally and are gitignored, so the clone's
|
|
275
|
+
* GitHub archive never contains them:
|
|
276
|
+
* - `.nuxt/tsconfig.*.json` (created by `nuxi prepare`)
|
|
277
|
+
* - `.mono/tsconfig.json` (created by `mono prepare`)
|
|
278
|
+
* In a cloned mono app those don't exist, so loading the clone's `.vue`/`.ts`/
|
|
279
|
+
* `mono.config.ts` fails with "Tsconfig not found" (vite/plugin-vue & jiti resolve
|
|
280
|
+
* the nearest tsconfig per file). Strip the `.nuxt`/`.mono`-pointing
|
|
281
|
+
* `extends`/`references` so the clone's tsconfig is harmless to any host; editor
|
|
282
|
+
* `paths` etc. are kept.
|
|
283
|
+
*/
|
|
284
|
+
function sanitizeClonedTsconfig(dir) {
|
|
285
|
+
const file = path.join(dir, "tsconfig.json");
|
|
286
|
+
if (!exists(file)) return;
|
|
287
|
+
|
|
288
|
+
let json;
|
|
289
|
+
try {
|
|
290
|
+
json = JSON.parse(stripCommentsSafe(fs.readFileSync(file, "utf8")));
|
|
291
|
+
} catch {
|
|
292
|
+
return; // non-JSON / JSONC with trailing commas โ leave it untouched
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Matches refs to generated, gitignored tsconfigs that won't exist in a clone.
|
|
296
|
+
const pointsToGenerated = (v) => {
|
|
297
|
+
const s = String(v ?? "").replace(/\\/g, "/");
|
|
298
|
+
return s.includes(".nuxt") || s.includes(".mono");
|
|
299
|
+
};
|
|
300
|
+
let changed = false;
|
|
301
|
+
|
|
302
|
+
if (Array.isArray(json.references)) {
|
|
303
|
+
const kept = json.references.filter((r) => !pointsToGenerated(r?.path));
|
|
304
|
+
if (kept.length !== json.references.length) {
|
|
305
|
+
if (kept.length) json.references = kept;
|
|
306
|
+
else delete json.references;
|
|
307
|
+
changed = true;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (typeof json.extends === "string" && pointsToGenerated(json.extends)) {
|
|
312
|
+
delete json.extends;
|
|
313
|
+
changed = true;
|
|
314
|
+
} else if (Array.isArray(json.extends)) {
|
|
315
|
+
const kept = json.extends.filter((e) => !pointsToGenerated(e));
|
|
316
|
+
if (kept.length !== json.extends.length) {
|
|
317
|
+
if (kept.length) json.extends = kept;
|
|
318
|
+
else delete json.extends;
|
|
319
|
+
changed = true;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (changed) {
|
|
324
|
+
fs.writeFileSync(file, JSON.stringify(json, null, 2), "utf8");
|
|
325
|
+
console.log(`๐งน Sanitized cloned tsconfig (.nuxt/.mono refs) in ${path.basename(dir)}/tsconfig.json`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const { apps, found: appsDeclared } = readAppsFromMonoConfig();
|
|
330
|
+
|
|
331
|
+
// NOTE: no early exit on an empty list. `apps: []` is a valid statement โ "this
|
|
332
|
+
// host federates nothing" โ and the prune below is what acts on it. Bailing here
|
|
333
|
+
// (as this did) meant emptying `apps[]` left every clone on disk forever.
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
337
|
+
|
|
338
|
+
const agent = new https.Agent({
|
|
339
|
+
keepAlive: true,
|
|
340
|
+
maxSockets: 6,
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
async function withRetry(fn, { retries = 4, baseDelayMs = 800, label = "request" } = {}) {
|
|
344
|
+
let lastErr;
|
|
345
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
346
|
+
try {
|
|
347
|
+
return await fn(attempt);
|
|
348
|
+
} catch (e) {
|
|
349
|
+
lastErr = e;
|
|
350
|
+
const code = e?.code || "";
|
|
351
|
+
const isRetryable =
|
|
352
|
+
code === "ETIMEDOUT" ||
|
|
353
|
+
code === "ECONNRESET" ||
|
|
354
|
+
code === "EAI_AGAIN" ||
|
|
355
|
+
code === "ENOTFOUND";
|
|
356
|
+
|
|
357
|
+
if (!isRetryable || attempt === retries) break;
|
|
358
|
+
|
|
359
|
+
const delay = baseDelayMs * Math.pow(2, attempt);
|
|
360
|
+
console.log(`โ ๏ธ ${label} failed (${code || e.message}). Retry in ${delay}ms...`);
|
|
361
|
+
await sleep(delay);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
throw lastErr;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function httpGetJson(url, token, { timeoutMs = 20000 } = {}) {
|
|
368
|
+
return withRetry(
|
|
369
|
+
() =>
|
|
370
|
+
new Promise((resolve, reject) => {
|
|
371
|
+
const req = https.get(
|
|
372
|
+
url,
|
|
373
|
+
{
|
|
374
|
+
agent,
|
|
375
|
+
headers: {
|
|
376
|
+
"User-Agent": "vite-app-downloader",
|
|
377
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
378
|
+
Accept: "application/vnd.github+json",
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
(res) => {
|
|
382
|
+
// follow redirect
|
|
383
|
+
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
384
|
+
res.resume();
|
|
385
|
+
return resolve(httpGetJson(res.headers.location, token, { timeoutMs }));
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
let data = "";
|
|
389
|
+
res.setEncoding("utf8");
|
|
390
|
+
res.on("data", (c) => (data += c));
|
|
391
|
+
res.on("end", () => {
|
|
392
|
+
if (res.statusCode !== 200) {
|
|
393
|
+
return reject(
|
|
394
|
+
new Error(`GitHub API failed ${res.statusCode} ${res.statusMessage}: ${data}`)
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
resolve(JSON.parse(data));
|
|
399
|
+
} catch (e) {
|
|
400
|
+
reject(e);
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
);
|
|
405
|
+
|
|
406
|
+
req.setTimeout(timeoutMs, () => req.destroy(Object.assign(new Error("timeout"), { code: "ETIMEDOUT" })));
|
|
407
|
+
req.on("error", reject);
|
|
408
|
+
}),
|
|
409
|
+
{ label: "GitHub API" }
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async function getLatestCommitSha(owner, repo, ref, token) {
|
|
414
|
+
const url = `https://api.github.com/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}`;
|
|
415
|
+
const json = await httpGetJson(url, token);
|
|
416
|
+
if (!json?.sha) throw new Error(`Cannot read commit sha for ${owner}/${repo}@${ref}`);
|
|
417
|
+
return json.sha;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// ---------------------------------------------------------------------------
|
|
421
|
+
// Transport selection.
|
|
422
|
+
//
|
|
423
|
+
// Prefer the machine's OWN git credentials over the shared PAT. A collaborator
|
|
424
|
+
// who has been invited to the repo can `git ls-remote` it with no token, and
|
|
425
|
+
// that single call also hands us the head SHA โ so the git path makes ZERO
|
|
426
|
+
// GitHub REST requests and burns no rate limit. Everyone else falls back to the
|
|
427
|
+
// existing token + archive-ZIP path, with a warning telling them what to ask for.
|
|
428
|
+
// ---------------------------------------------------------------------------
|
|
429
|
+
const ACCESS_TTL_MS = Number(process.env.MONO_SYNC_ACCESS_TTL_MS) || 6 * 60 * 60 * 1000;
|
|
430
|
+
const RECHECK_ACCESS = process.env.MONO_SYNC_RECHECK_ACCESS === "1" || argv.recheckAccess === true;
|
|
431
|
+
// Generous on purpose. This is a hang cap, NOT a latency budget: the flags in
|
|
432
|
+
// mono-git.mjs are what actually stop a Git Credential Manager dialog blocking
|
|
433
|
+
// forever. Measured on a real (slow) link, a SUCCESSFUL probe took ~22s โ 10s of
|
|
434
|
+
// that is plain round-trip to github.com and ~5s is the `gh` credential helper โ
|
|
435
|
+
// so anything near 20s would reject working collaborators and silently push them
|
|
436
|
+
// back onto the token.
|
|
437
|
+
const PROBE_TIMEOUT_MS = Number(process.env.MONO_SYNC_PROBE_TIMEOUT_MS) || 60000;
|
|
438
|
+
const FETCH_TIMEOUT_MS = Number(process.env.MONO_SYNC_FETCH_TIMEOUT_MS) || 180000;
|
|
439
|
+
|
|
440
|
+
// 'auto' = shallow `clone`, falling back to `init`+`fetch`. See materializeGitTree
|
|
441
|
+
// for the measurements; only override this for a git setup that mishandles one.
|
|
442
|
+
const GIT_METHOD = resolveGitMethod({ argv });
|
|
443
|
+
|
|
444
|
+
let _gitInstalled;
|
|
445
|
+
function gitInstalled() {
|
|
446
|
+
if (_gitInstalled === undefined) _gitInstalled = runGit(["--version"], { timeoutMs: 10000 }).ok;
|
|
447
|
+
return _gitInstalled;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const warnedOnce = new Set();
|
|
451
|
+
function warnOnce(key, msg) {
|
|
452
|
+
if (warnedOnce.has(key)) return;
|
|
453
|
+
warnedOnce.add(key);
|
|
454
|
+
console.log(msg);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* @returns {{sha: string, remoteUrl: string, ref: string, dir: string} | null}
|
|
459
|
+
* `null` means "use the token transport". Throws when there is nothing to fall
|
|
460
|
+
* back to (`transport: 'git'`, or no token configured), or when the ref itself
|
|
461
|
+
* does not exist. `ref`/`dir` are the RESOLVED split of the deep URL โ the ref
|
|
462
|
+
* git must actually fetch, and the folder to extract from the clone.
|
|
463
|
+
*/
|
|
464
|
+
function tryGitTransport({ app, owner, repo, refAndDir, mode, token }) {
|
|
465
|
+
const slug = `${owner}/${repo}`;
|
|
466
|
+
const hasToken = Boolean(token);
|
|
467
|
+
|
|
468
|
+
// Either hand back `null` (caller uses the token) or fail the app loudly.
|
|
469
|
+
const giveUp = (reason) => {
|
|
470
|
+
if (mode === "git") throw new Error(`${reason} (transport: 'git' โ no token fallback)`);
|
|
471
|
+
if (!hasToken) {
|
|
472
|
+
throw new Error(
|
|
473
|
+
`${reason}, and no token to fall back to` +
|
|
474
|
+
(app.envToken ? ` (${app.envToken} is empty)` : ` (no "envToken" configured)`)
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
return null;
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
if (!gitInstalled()) {
|
|
481
|
+
warnOnce("no-git", `โ ๏ธ git is not on PATH โ cannot sync without a token.`);
|
|
482
|
+
return giveUp("git is not installed");
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// A short (7..39 hex) ref resolves via REST but is not fetchable by git. Any
|
|
486
|
+
// candidate may be the real one, so bail to REST if any could be a short sha.
|
|
487
|
+
const candidates = refDirCandidates(refAndDir);
|
|
488
|
+
if (candidates.some((c) => isShortSha(c.ref))) {
|
|
489
|
+
warnOnce(`short-sha:${slug}`, `โ ๏ธ Ref "${refAndDir}" contains a short sha โ git cannot fetch it.`);
|
|
490
|
+
return giveUp(`ref "${refAndDir}" contains a short sha`);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (!RECHECK_ACCESS) {
|
|
494
|
+
const hit = accessCacheGet(accessCache, slug, { ttlMs: ACCESS_TTL_MS });
|
|
495
|
+
if (hit) {
|
|
496
|
+
const then = mode === "git" ? "" : hasToken ? " Using the token." : "";
|
|
497
|
+
console.log(`โช๏ธ No git access to ${slug} (checked ${ago(hit.checkedAt)}).${then}`);
|
|
498
|
+
console.log(` Set MONO_SYNC_RECHECK_ACCESS=1 to probe again.`);
|
|
499
|
+
needsInvite.add(slug);
|
|
500
|
+
return giveUp(`no git access to ${slug}`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const probe = resolveRefDir({ owner, repo, refAndDir, timeoutMs: PROBE_TIMEOUT_MS });
|
|
505
|
+
|
|
506
|
+
if (probe.ok) {
|
|
507
|
+
// Access restored (an invite landed) โ drop the stale negative immediately.
|
|
508
|
+
if (accessCache[slug]) {
|
|
509
|
+
delete accessCache[slug];
|
|
510
|
+
saveAccessCache();
|
|
511
|
+
}
|
|
512
|
+
console.log(`๐ Git access OK โ no token needed.`);
|
|
513
|
+
return { sha: probe.sha, remoteUrl: probe.remoteUrl, ref: probe.ref, dir: probe.dir };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (probe.kind === "ref-missing") {
|
|
517
|
+
// We can reach the repo; the ref is simply wrong. The token path would 404
|
|
518
|
+
// on it too, so fail fast with the useful message instead โ naming every
|
|
519
|
+
// split tried, so a deep-URL typo says which folder/ref was the problem.
|
|
520
|
+
throw new Error(
|
|
521
|
+
`Ref "${refAndDir}" not found in ${slug} (tried as branch/tag: ${probe.tried.join(", ")}).`
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (probe.kind === "network" || probe.kind === "timeout") {
|
|
526
|
+
// Transient. Never cache this, or one flaky moment pins a collaborator to
|
|
527
|
+
// the token for the whole TTL.
|
|
528
|
+
console.log(`โ ๏ธ Cannot reach github.com over git (${probe.detail || "timed out"}). Falling back to the token.`);
|
|
529
|
+
return giveUp(`cannot reach ${slug} over git`);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (probe.kind === "no-access") {
|
|
533
|
+
if (probe.why === "bad-credential") {
|
|
534
|
+
console.log(`โ ๏ธ Your saved git credential for github.com was rejected (${probe.detail}).`);
|
|
535
|
+
console.log(` Re-authenticate โ \`gh auth login\`, or update the github.com entry in Windows Credential Manager.`);
|
|
536
|
+
} else if (probe.why === "no-credential") {
|
|
537
|
+
console.log(`โ ๏ธ No git credential for github.com on this machine.`);
|
|
538
|
+
console.log(` Sign in once (\`gh auth login\`) and ask the owner of ${slug} to invite you as a collaborator,`);
|
|
539
|
+
console.log(` then \`mono sync\` needs no token at all.`);
|
|
540
|
+
} else {
|
|
541
|
+
console.log(`โ ๏ธ You are not invited to "${slug}" โ no git access to this repo.`);
|
|
542
|
+
console.log(` To get access without a token, ask the owner to invite you as a collaborator,`);
|
|
543
|
+
console.log(` then you can sync without a token.`);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
accessCacheSet(accessCache, slug, { why: probe.why, detail: probe.detail });
|
|
547
|
+
saveAccessCache();
|
|
548
|
+
needsInvite.add(slug);
|
|
549
|
+
|
|
550
|
+
if (hasToken && mode !== "git") console.log(` Falling back to the token in ${app.envToken}.`);
|
|
551
|
+
return giveUp(`no git access to ${slug}`);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
console.log(`โ ๏ธ git probe of ${slug} failed (${probe.detail || probe.kind}). Falling back to the token.`);
|
|
555
|
+
return giveUp(`git probe of ${slug} failed`);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function downloadToFile(url, destZip, token, { timeoutMs = 30000 } = {}) {
|
|
559
|
+
return withRetry(
|
|
560
|
+
() =>
|
|
561
|
+
new Promise((resolve, reject) => {
|
|
562
|
+
const file = fs.createWriteStream(destZip);
|
|
563
|
+
const req = https.get(
|
|
564
|
+
url,
|
|
565
|
+
{
|
|
566
|
+
agent,
|
|
567
|
+
headers: {
|
|
568
|
+
"User-Agent": "vite-app-downloader",
|
|
569
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
570
|
+
Accept: "application/vnd.github+json",
|
|
571
|
+
},
|
|
572
|
+
},
|
|
573
|
+
(res) => {
|
|
574
|
+
// follow redirect (GitHub archive redirects often)
|
|
575
|
+
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
576
|
+
res.resume();
|
|
577
|
+
file.close();
|
|
578
|
+
return resolve(downloadToFile(res.headers.location, destZip, token, { timeoutMs }));
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (res.statusCode !== 200) {
|
|
582
|
+
res.resume();
|
|
583
|
+
file.close();
|
|
584
|
+
return reject(new Error(`Download failed ${res.statusCode} ${res.statusMessage}`));
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
res.pipe(file);
|
|
588
|
+
file.on("finish", () => file.close(resolve));
|
|
589
|
+
}
|
|
590
|
+
);
|
|
591
|
+
|
|
592
|
+
req.setTimeout(timeoutMs, () => req.destroy(Object.assign(new Error("timeout"), { code: "ETIMEDOUT" })));
|
|
593
|
+
req.on("error", (err) => {
|
|
594
|
+
file.close(() => {
|
|
595
|
+
try { fs.unlinkSync(destZip); } catch { }
|
|
596
|
+
reject(err);
|
|
597
|
+
});
|
|
598
|
+
});
|
|
599
|
+
}),
|
|
600
|
+
{ label: "ZIP download" }
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Token transport: download the archive ZIP and unpack it into `destDir`.
|
|
606
|
+
*
|
|
607
|
+
* Unchanged behaviour, just pointed at a staging dir instead of straight at
|
|
608
|
+
* `outDir`. Note this still needs a POSIX `unzip` on PATH โ the git transport
|
|
609
|
+
* above does not, so on Windows this path only works for people who are NOT
|
|
610
|
+
* collaborators, which is precisely the case we now try hardest to avoid.
|
|
611
|
+
*
|
|
612
|
+
* `dir` (deep /tree/ URLs) picks the subfolder out of the extracted archive
|
|
613
|
+
* instead of the repo root, so both transports land the same tree.
|
|
614
|
+
*
|
|
615
|
+
* @returns {Promise<string>} the sha that was downloaded
|
|
616
|
+
*/
|
|
617
|
+
async function materializeZipTree({ owner, repo, sha, token, destDir, dir = "" }) {
|
|
618
|
+
const zipUrl = `https://github.com/${owner}/${repo}/archive/${sha}.zip`;
|
|
619
|
+
const tmpWorkDir = fs.mkdtempSync(path.join(os.tmpdir(), `repo-dl-${repo}-`));
|
|
620
|
+
const zipFile = path.join(tmpWorkDir, `archive.zip`);
|
|
621
|
+
const extractDir = path.join(tmpWorkDir, `extract`);
|
|
622
|
+
|
|
623
|
+
try {
|
|
624
|
+
await downloadToFile(zipUrl, zipFile, token);
|
|
625
|
+
mkdirp(extractDir);
|
|
626
|
+
execSync(`unzip -q "${zipFile}" -d "${extractDir}"`, { stdio: "inherit" });
|
|
627
|
+
|
|
628
|
+
const [top] = fs.readdirSync(extractDir);
|
|
629
|
+
if (!top) throw new Error("Zip extraction failed");
|
|
630
|
+
|
|
631
|
+
const src = dir
|
|
632
|
+
? path.join(extractDir, top, ...dir.split("/").filter(Boolean))
|
|
633
|
+
: path.join(extractDir, top);
|
|
634
|
+
if (dir && !exists(src)) {
|
|
635
|
+
throw new Error(
|
|
636
|
+
`Folder "${dir}" not found in ${owner}/${repo}@${sha.slice(0, 7)} (from the /tree/ URL).`
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
mkdirp(destDir);
|
|
641
|
+
fs.cpSync(src, destDir, { recursive: true });
|
|
642
|
+
|
|
643
|
+
return sha;
|
|
644
|
+
} finally {
|
|
645
|
+
rmrf(tmpWorkDir);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Token-transport deep-URL resolution: same candidate order as the git probe
|
|
651
|
+
* (`refDirCandidates`), but each split is tried against REST `/commits/<ref>`
|
|
652
|
+
* instead of `ls-remote`. A 404 means "this split is not a ref" โ try the next.
|
|
653
|
+
* Anything else (rate limit, auth) is real and must surface.
|
|
654
|
+
*/
|
|
655
|
+
async function resolveRefDirViaRest(owner, repo, refAndDir, token) {
|
|
656
|
+
let lastErr;
|
|
657
|
+
for (const c of refDirCandidates(refAndDir)) {
|
|
658
|
+
try {
|
|
659
|
+
return { ref: c.ref, dir: c.dir, sha: await getLatestCommitSha(owner, repo, c.ref, token) };
|
|
660
|
+
} catch (e) {
|
|
661
|
+
if (!/404|No commit found/i.test(String(e?.message || ""))) throw e;
|
|
662
|
+
lastErr = e;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
throw new Error(
|
|
666
|
+
`Ref "${refAndDir}" not found in ${owner}/${repo} (${lastErr?.message || "no such branch or tag"}).`
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// --- lock + commit cache (ONLY sha stored) ---
|
|
671
|
+
// Kept under `.mono/` alongside the generated tsconfig so all mono-managed
|
|
672
|
+
// artifacts live in one place (was `.cache/`).
|
|
673
|
+
const cacheDir = path.resolve(".mono");
|
|
674
|
+
mkdirp(cacheDir);
|
|
675
|
+
|
|
676
|
+
const lockFile = path.join(cacheDir, "clone.lock");
|
|
677
|
+
let lockFd;
|
|
678
|
+
try {
|
|
679
|
+
lockFd = fs.openSync(lockFile, "wx"); // fails if exists
|
|
680
|
+
fs.writeFileSync(lockFd, String(process.pid));
|
|
681
|
+
} catch (e) {
|
|
682
|
+
if (e.code === "EEXIST") {
|
|
683
|
+
console.log(`โ Another sync is running (lock: ${lockFile}). Skipping.`);
|
|
684
|
+
process.exit(0);
|
|
685
|
+
}
|
|
686
|
+
throw e;
|
|
687
|
+
}
|
|
688
|
+
process.on("exit", () => {
|
|
689
|
+
try { if (lockFd) fs.closeSync(lockFd); } catch { }
|
|
690
|
+
try { fs.unlinkSync(lockFile); } catch { }
|
|
691
|
+
});
|
|
692
|
+
process.on("SIGINT", () => process.exit(130));
|
|
693
|
+
process.on("SIGTERM", () => process.exit(143));
|
|
694
|
+
|
|
695
|
+
const cacheFile = path.join(cacheDir, "apps-commit-cache.json");
|
|
696
|
+
let commitCache = {};
|
|
697
|
+
if (exists(cacheFile)) {
|
|
698
|
+
try {
|
|
699
|
+
commitCache = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
|
700
|
+
} catch {
|
|
701
|
+
commitCache = {};
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// --- access cache (ONLY negative results; see mono-git.mjs accessCacheGet) ---
|
|
706
|
+
// Separate file from the commit cache so nothing reading that one has to migrate.
|
|
707
|
+
// Keyed by `owner/repo` โ access is repo-level, not ref-level.
|
|
708
|
+
const accessCacheFile = path.join(cacheDir, "apps-access-cache.json");
|
|
709
|
+
let accessCache = {};
|
|
710
|
+
if (exists(accessCacheFile)) {
|
|
711
|
+
try {
|
|
712
|
+
accessCache = JSON.parse(fs.readFileSync(accessCacheFile, "utf8"));
|
|
713
|
+
} catch {
|
|
714
|
+
accessCache = {};
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
function saveAccessCache() {
|
|
718
|
+
try {
|
|
719
|
+
fs.writeFileSync(accessCacheFile, JSON.stringify(accessCache, null, 2), "utf8");
|
|
720
|
+
} catch { }
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** Repos that still needed the PAT because this machine has no git access. */
|
|
724
|
+
const needsInvite = new Set();
|
|
725
|
+
|
|
726
|
+
// Every clone lives here. Deliberately NOT per-app configurable: the alias/
|
|
727
|
+
// ecosystem scanners in src/ all hardcode `.mono/apps`, and pointing the prune
|
|
728
|
+
// below at an arbitrary directory would let it delete a tree mono never created.
|
|
729
|
+
const appsDir = path.resolve(MONO_APPS_DIR);
|
|
730
|
+
|
|
731
|
+
// Clear staging dirs left by a crashed run. Safe: the lock above guarantees we
|
|
732
|
+
// are the only sync in flight.
|
|
733
|
+
sweepStrayStages(appsDir);
|
|
734
|
+
|
|
735
|
+
// --- prune apps that left mono.config ---------------------------------------
|
|
736
|
+
// Runs BEFORE the sync loop and touches no network, so a removed app disappears
|
|
737
|
+
// even when a surviving app fails to download.
|
|
738
|
+
const pruned = [];
|
|
739
|
+
|
|
740
|
+
if (appsDeclared && resolvePrune({ argv })) {
|
|
741
|
+
const keepNames = apps.map((a) => a.name);
|
|
742
|
+
const keepKeys = new Set();
|
|
743
|
+
const keepSlugs = new Set();
|
|
744
|
+
|
|
745
|
+
for (const app of apps) {
|
|
746
|
+
// A path-only app has no cache entries to keep. Its NAME still protects a
|
|
747
|
+
// stale clone under .mono/apps (`keepNames`), which is shadowed by the
|
|
748
|
+
// path, never read, and deliberately never deleted here.
|
|
749
|
+
if (!app.url) continue;
|
|
750
|
+
try {
|
|
751
|
+
const { owner, repo, ref } = parseGithubUrl(app.url);
|
|
752
|
+
keepSlugs.add(`${owner}/${repo}`);
|
|
753
|
+
keepKeys.add(`${owner}/${repo}@${ref}`);
|
|
754
|
+
} catch {
|
|
755
|
+
// A malformed url only costs this app its cache entries (they get rebuilt
|
|
756
|
+
// on the next successful sync). Directory pruning keys off `name`, never
|
|
757
|
+
// the url, so a typo here can never delete a tree.
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
for (const name of orphanAppDirs(appsDir, keepNames)) {
|
|
762
|
+
// Not `path.join`: `appDirToPrune` re-derives the path and refuses anything
|
|
763
|
+
// that escapes `.mono/apps`. Belt to the name-keyed braces above.
|
|
764
|
+
const dir = appDirToPrune(appsDir, name);
|
|
765
|
+
try {
|
|
766
|
+
rmrf(dir);
|
|
767
|
+
pruned.push(name);
|
|
768
|
+
console.log(`๐งน Removed app "${name}" (${path.relative(process.cwd(), dir) || dir})`);
|
|
769
|
+
} catch (e) {
|
|
770
|
+
console.log(`โ ๏ธ Could not remove ${dir}: ${e.message}`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
const droppedCache = staleCacheKeys(commitCache, keepKeys);
|
|
775
|
+
if (droppedCache.length) {
|
|
776
|
+
for (const key of droppedCache) delete commitCache[key];
|
|
777
|
+
fs.writeFileSync(cacheFile, JSON.stringify(commitCache, null, 2), "utf8");
|
|
778
|
+
console.log(` โณ dropped ${droppedCache.length} commit-cache entr${droppedCache.length === 1 ? "y" : "ies"} (${droppedCache.join(", ")})`);
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const droppedAccess = staleAccessKeys(accessCache, keepSlugs);
|
|
782
|
+
if (droppedAccess.length) {
|
|
783
|
+
for (const slug of droppedAccess) delete accessCache[slug];
|
|
784
|
+
saveAccessCache();
|
|
785
|
+
console.log(` โณ dropped ${droppedAccess.length} access-cache entr${droppedAccess.length === 1 ? "y" : "ies"} (${droppedAccess.join(", ")})`);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// The generated tsconfig still maps `@<name>/*` at a directory that is now
|
|
789
|
+
// gone. `mono prepare` rebuilds this file from the directory scan, so this
|
|
790
|
+
// only covers the gap until it next runs โ but a mapping to a missing folder
|
|
791
|
+
// is worse than no mapping.
|
|
792
|
+
if (pruned.length) {
|
|
793
|
+
const aliases = pruneMonoTsconfigPaths(path.join(cacheDir, "tsconfig.json"), pruned);
|
|
794
|
+
if (aliases.length) console.log(` โณ dropped ${aliases.length} tsconfig alias(es) (${aliases.join(", ")})`);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (!apps.length) {
|
|
799
|
+
console.log(appsDeclared ? "mono.config declares no apps โ nothing to sync." : "No apps found in mono.config.");
|
|
800
|
+
process.exit(0);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
const succeeded = [];
|
|
804
|
+
const failed = [];
|
|
805
|
+
const linked = [];
|
|
806
|
+
|
|
807
|
+
for (const app of apps) {
|
|
808
|
+
try {
|
|
809
|
+
const outDir = path.join(appsDir, app.name);
|
|
810
|
+
|
|
811
|
+
// Read in place? Then there is nothing to clone โ decided before any
|
|
812
|
+
// network call, and the commit cache is left untouched.
|
|
813
|
+
const source = resolveAppSource(app);
|
|
814
|
+
if (source.kind === "path") {
|
|
815
|
+
const rel = path.relative(process.cwd(), source.dir) || source.dir;
|
|
816
|
+
console.log(`\n๐ ${app.name}: linked to ${rel} โ nothing to clone.`);
|
|
817
|
+
if (fs.existsSync(outDir)) {
|
|
818
|
+
console.log(` โน๏ธ a stale clone sits at ${path.relative(process.cwd(), outDir)}; it is shadowed by path and left alone โ delete it if you want.`);
|
|
819
|
+
}
|
|
820
|
+
linked.push({ name: app.name, dir: rel });
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
if (source.kind === "path-missing") {
|
|
824
|
+
if (!app.url) {
|
|
825
|
+
throw new Error(`path '${app.path}' not found (looked in ${source.dir}) and no url is declared โ nothing to fall back to.`);
|
|
826
|
+
}
|
|
827
|
+
console.log(`\nโ ๏ธ ${app.name}: path '${app.path}' not found (looked in ${source.dir}) โ syncing from GitHub instead.`);
|
|
828
|
+
}
|
|
829
|
+
const token = app.envToken ? process.env[app.envToken] : undefined;
|
|
830
|
+
|
|
831
|
+
// `ref` here is the RAW /tree/ remainder ("main/nuxt-remote") โ kept whole
|
|
832
|
+
// for the cache key so it stays stable without a network round-trip in the
|
|
833
|
+
// prune pass. The ref/dir split of it is resolved per transport below.
|
|
834
|
+
const { owner, repo, ref: refAndDir } = parseGithubUrl(app.url);
|
|
835
|
+
const cacheKey = `${owner}/${repo}@${refAndDir}`;
|
|
836
|
+
|
|
837
|
+
console.log(`\n==> Check ${app.name} (${cacheKey})`);
|
|
838
|
+
|
|
839
|
+
const mode = resolveTransport({ app, argv });
|
|
840
|
+
const git = mode === "token" ? null : tryGitTransport({ app, owner, repo, refAndDir, mode, token });
|
|
841
|
+
|
|
842
|
+
let latestSha;
|
|
843
|
+
// The folder half of the resolved deep URL ('' for a whole-repo app).
|
|
844
|
+
let subDir = git?.dir || "";
|
|
845
|
+
if (git) {
|
|
846
|
+
// `ls-remote` already told us โ no REST call, no rate limit spent.
|
|
847
|
+
latestSha = git.sha;
|
|
848
|
+
} else {
|
|
849
|
+
try {
|
|
850
|
+
const rest = await resolveRefDirViaRest(owner, repo, refAndDir, token);
|
|
851
|
+
latestSha = rest.sha;
|
|
852
|
+
subDir = rest.dir;
|
|
853
|
+
} catch (e) {
|
|
854
|
+
throw new Error(`Cannot resolve ${cacheKey}: ${e.code || e.message}`);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
const lastSha = commitCache[cacheKey];
|
|
859
|
+
let via = git ? "git" : "token";
|
|
860
|
+
|
|
861
|
+
if (lastSha === latestSha && exists(outDir)) {
|
|
862
|
+
console.log(`โช๏ธ No changes (${latestSha.slice(0, 7)}). Skip download.`);
|
|
863
|
+
succeeded.push({ name: app.name, cacheKey, sha: latestSha, via });
|
|
864
|
+
continue;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
console.log(
|
|
868
|
+
lastSha
|
|
869
|
+
? `๐งฉ Changed ${String(lastSha).slice(0, 7)} -> ${latestSha.slice(0, 7)}. Downloading...`
|
|
870
|
+
: `๐ First time download (${latestSha.slice(0, 7)}).`
|
|
871
|
+
);
|
|
872
|
+
|
|
873
|
+
// Build into a staging dir on the SAME volume as outDir, then swap. The old
|
|
874
|
+
// tree survives until the new one is complete, so a failed download no
|
|
875
|
+
// longer leaves the app directory deleted.
|
|
876
|
+
mkdirp(appsDir);
|
|
877
|
+
const stage = stagePathFor(appsDir, app.name);
|
|
878
|
+
// A deep URL clones the WHOLE repo into a second staging dir first, then the
|
|
879
|
+
// folder moves out of it; a whole-repo URL clones straight into the stage.
|
|
880
|
+
const repoStage = subDir ? stagePathFor(appsDir, `${app.name}-repo`) : stage;
|
|
881
|
+
|
|
882
|
+
try {
|
|
883
|
+
let finalSha;
|
|
884
|
+
if (git) {
|
|
885
|
+
console.log(
|
|
886
|
+
subDir
|
|
887
|
+
? `๐ฅ Downloading via git (depth 1, folder "${subDir}")...`
|
|
888
|
+
: `๐ฅ Downloading via git (depth 1)...`
|
|
889
|
+
);
|
|
890
|
+
const got = materializeGitTree({
|
|
891
|
+
remoteUrl: git.remoteUrl,
|
|
892
|
+
ref: git.ref,
|
|
893
|
+
sha: latestSha,
|
|
894
|
+
destDir: repoStage,
|
|
895
|
+
timeoutMs: FETCH_TIMEOUT_MS,
|
|
896
|
+
method: GIT_METHOD,
|
|
897
|
+
});
|
|
898
|
+
finalSha = got.sha;
|
|
899
|
+
// Which of the two git methods actually served it. `clone` is the fast
|
|
900
|
+
// path; seeing `fetch` here means either a pinned commit sha or a clone
|
|
901
|
+
// that failed and was retried.
|
|
902
|
+
via = `git (${got.method})`;
|
|
903
|
+
if (subDir) pickSubtree(repoStage, subDir, stage);
|
|
904
|
+
if (finalSha !== latestSha) {
|
|
905
|
+
console.log(`๐งฉ Ref moved during download -> ${finalSha.slice(0, 7)}.`);
|
|
906
|
+
}
|
|
907
|
+
} else {
|
|
908
|
+
finalSha = await materializeZipTree({ owner, repo, sha: latestSha, token, destDir: stage, dir: subDir });
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// Strip repo plumbing BEFORE the swap, so outDir is never momentarily a
|
|
912
|
+
// nested git repo (the git transport really does create a .git dir).
|
|
913
|
+
rmrf(path.join(stage, ".git"));
|
|
914
|
+
rmrf(path.join(stage, ".github"));
|
|
915
|
+
|
|
916
|
+
swapIntoPlace(stage, outDir);
|
|
917
|
+
|
|
918
|
+
// Make a cloned Nuxt app's tsconfig harmless to a Vite host (drop `.nuxt`
|
|
919
|
+
// refs that don't exist without `nuxi prepare`). After the swap, so its
|
|
920
|
+
// log line names the real app dir rather than the staging dir.
|
|
921
|
+
sanitizeClonedTsconfig(outDir);
|
|
922
|
+
|
|
923
|
+
commitCache[cacheKey] = finalSha;
|
|
924
|
+
fs.writeFileSync(cacheFile, JSON.stringify(commitCache, null, 2), "utf8");
|
|
925
|
+
|
|
926
|
+
console.log(`โ
Stored in ${outDir}`);
|
|
927
|
+
succeeded.push({ name: app.name, cacheKey, sha: finalSha, via });
|
|
928
|
+
} finally {
|
|
929
|
+
rmrf(stage);
|
|
930
|
+
if (repoStage !== stage) rmrf(repoStage);
|
|
931
|
+
}
|
|
932
|
+
} catch (e) {
|
|
933
|
+
console.log(`โ ${app.name}: ${e.message}`);
|
|
934
|
+
failed.push({ name: app.name, url: app.url, reason: e.message });
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
console.log(`\n===== Summary =====`);
|
|
939
|
+
console.log(`โ
Success (${succeeded.length}):`);
|
|
940
|
+
for (const s of succeeded) console.log(` โข ${s.name} (${s.cacheKey} @ ${s.sha.slice(0, 7)}) via ${s.via}`);
|
|
941
|
+
console.log(`โ Failed (${failed.length}):`);
|
|
942
|
+
for (const f of failed) console.log(` โข ${f.name}: ${f.reason}`);
|
|
943
|
+
if (linked.length) {
|
|
944
|
+
console.log(`๐ Linked (${linked.length}):`);
|
|
945
|
+
for (const l of linked) console.log(` โข ${l.name} (${l.dir}, read in place)`);
|
|
946
|
+
}
|
|
947
|
+
if (pruned.length) {
|
|
948
|
+
console.log(`๐งน Pruned (${pruned.length}):`);
|
|
949
|
+
for (const name of pruned) console.log(` โข ${name} (removed from mono.config)`);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
if (needsInvite.size) {
|
|
953
|
+
console.log(`\n๐ก ${needsInvite.size} repo(s) still need a token on this machine.`);
|
|
954
|
+
console.log(` Ask the owner to invite you as a collaborator, then sync works with no token:`);
|
|
955
|
+
for (const slug of needsInvite) console.log(` โข https://github.com/${slug}/settings/access`);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
if (failed.length) process.exitCode = 1;
|