buncargo 3.2.0 → 3.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ import {
2
+ createDevEnvironment
3
+ } from "./index-2bcjw5n0.js";
4
+
5
+ // src/loader/cache.ts
6
+ var cachedEnv = null;
7
+ function setCachedDevEnv(env) {
8
+ cachedEnv = env;
9
+ }
10
+ function getCachedDevEnv() {
11
+ return cachedEnv;
12
+ }
13
+ function clearDevEnvCache() {
14
+ cachedEnv = null;
15
+ }
16
+ // src/loader/find-config-file.ts
17
+ import { existsSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ var CONFIG_FILES = [
20
+ "dev.config.ts",
21
+ "dev.config.js",
22
+ "dev-tools.config.ts",
23
+ "dev-tools.config.js"
24
+ ];
25
+ function findConfigFile(startDir) {
26
+ let currentDir = startDir;
27
+ while (true) {
28
+ for (const file of CONFIG_FILES) {
29
+ const configPath = join(currentDir, file);
30
+ if (existsSync(configPath)) {
31
+ return configPath;
32
+ }
33
+ }
34
+ const parentDir = dirname(currentDir);
35
+ if (parentDir === currentDir) {
36
+ return null;
37
+ }
38
+ currentDir = parentDir;
39
+ }
40
+ }
41
+ // src/loader/load-dev-env.ts
42
+ async function loadDevEnv(options) {
43
+ if (!options?.reload) {
44
+ const cached = getCachedDevEnv();
45
+ if (cached)
46
+ return cached;
47
+ }
48
+ const cwd = options?.cwd ?? process.cwd();
49
+ const configPath = findConfigFile(cwd);
50
+ if (configPath) {
51
+ const mod = await import(configPath);
52
+ const config = mod.default;
53
+ if (!config?.projectPrefix || !config?.services) {
54
+ throw new Error(`Invalid config in "${configPath}". Use defineDevConfig() and export as default.`);
55
+ }
56
+ const env = createDevEnvironment(config);
57
+ setCachedDevEnv(env);
58
+ return env;
59
+ }
60
+ throw new Error("No config file found. Create dev.config.ts with: export default defineDevConfig({ ... })");
61
+ }
62
+
63
+ // src/loader/index.ts
64
+ function getDevEnv() {
65
+ const env = getCachedDevEnv();
66
+ if (!env) {
67
+ throw new Error("Dev environment not loaded. Call loadDevEnv() first.");
68
+ }
69
+ return env;
70
+ }
71
+
72
+ export { clearDevEnvCache, CONFIG_FILES, findConfigFile, loadDevEnv, getDevEnv };
@@ -0,0 +1,415 @@
1
+ import {
2
+ sleep
3
+ } from "./index-fkgqg6w2.js";
4
+
5
+ // src/core/quick-tunnel/index.ts
6
+ import { existsSync } from "node:fs";
7
+ import { createInterface } from "node:readline";
8
+
9
+ // src/core/quick-tunnel/cloudflared-process.ts
10
+ import { spawn } from "node:child_process";
11
+
12
+ // src/core/quick-tunnel/constants.ts
13
+ import { tmpdir } from "node:os";
14
+ import path from "node:path";
15
+ var CLOUDFLARED_VERSION = process.env.CLOUDFLARED_VERSION || "2023.10.0";
16
+ var RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/";
17
+ var cloudflaredBinPath = path.join(tmpdir(), "buncargo-cloudflared", process.platform === "win32" ? `cloudflared.${CLOUDFLARED_VERSION}.exe` : `cloudflared.${CLOUDFLARED_VERSION}`);
18
+ var cloudflaredNotice = `
19
+ \uD83D\uDD25 Your installation of cloudflared software constitutes a symbol of your signature
20
+ indicating that you accept the terms of the Cloudflare License, Terms and Privacy Policy.
21
+
22
+ ❯ License: \`https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/license/\`
23
+ ❯ Terms: \`https://www.cloudflare.com/terms/\`
24
+ ❯ Privacy Policy: \`https://www.cloudflare.com/privacypolicy/\`
25
+ `;
26
+
27
+ // src/core/quick-tunnel/cloudflared-process.ts
28
+ var urlRegexPipe = /\|\s+(https?:\/\/\S+)/;
29
+ var urlRegexTryCloudflare = /(https:\/\/[a-zA-Z0-9][-a-zA-Z0-9.]*\.trycloudflare\.com)\b/;
30
+ var MAX_CAPTURED_LOG = 24000;
31
+ function parseQuickTunnelUrlFromOutput(log) {
32
+ const pipe = log.match(urlRegexPipe);
33
+ if (pipe?.[1]) {
34
+ return pipe[1];
35
+ }
36
+ const direct = log.match(urlRegexTryCloudflare);
37
+ return direct?.[1] ?? null;
38
+ }
39
+ function startCloudflaredTunnel(options) {
40
+ const args = ["tunnel"];
41
+ for (const [key, value] of Object.entries(options)) {
42
+ if (typeof value === "string") {
43
+ args.push(`${key}`, value);
44
+ } else if (typeof value === "number") {
45
+ args.push(`${key}`, value.toString());
46
+ } else if (value === null) {
47
+ args.push(`${key}`);
48
+ }
49
+ }
50
+ if (args.length === 1) {
51
+ args.push("--url", "localhost:8080");
52
+ }
53
+ const child = spawn(cloudflaredBinPath, args, {
54
+ stdio: ["ignore", "pipe", "pipe"]
55
+ });
56
+ if (process.env.DEBUG) {
57
+ child.stdout?.pipe(process.stdout);
58
+ child.stderr?.pipe(process.stderr);
59
+ }
60
+ let settled = false;
61
+ let urlResolver;
62
+ let urlRejector;
63
+ const url = new Promise((resolve, reject) => {
64
+ urlResolver = (v) => {
65
+ if (!settled) {
66
+ settled = true;
67
+ resolve(v);
68
+ }
69
+ };
70
+ urlRejector = (e) => {
71
+ if (!settled) {
72
+ settled = true;
73
+ reject(e);
74
+ }
75
+ };
76
+ });
77
+ const log = { buf: "" };
78
+ const append = (data) => {
79
+ log.buf += data.toString();
80
+ if (log.buf.length > MAX_CAPTURED_LOG) {
81
+ log.buf = log.buf.slice(-MAX_CAPTURED_LOG);
82
+ }
83
+ const url2 = parseQuickTunnelUrlFromOutput(log.buf);
84
+ if (url2) {
85
+ urlResolver(url2);
86
+ }
87
+ };
88
+ child.stdout?.on("data", append).on("error", urlRejector);
89
+ child.stderr?.on("data", append).on("error", urlRejector);
90
+ child.on("exit", (code, signal) => {
91
+ if (!settled) {
92
+ const tail = log.buf.trimEnd();
93
+ const excerpt = tail.length > 1200 ? `…${tail.slice(-1200)}` : tail;
94
+ const detail = excerpt ? `
95
+ cloudflared output (tail):
96
+ ${excerpt}` : "";
97
+ urlRejector(new Error(`cloudflared exited before a tunnel URL was parsed (code=${code}, signal=${signal ?? "none"}). ` + `Parallel quick-tunnel requests are often rate-limited; buncargo starts tunnels sequentially with a short pause. ` + `If this persists, try fewer expose targets or increase BUNCARGO_EXPOSE_TUNNEL_STAGGER_MS.${detail}`));
98
+ }
99
+ });
100
+ child.on("error", urlRejector);
101
+ const stop = () => child.kill("SIGINT");
102
+ return { url, child, stop };
103
+ }
104
+
105
+ // src/core/quick-tunnel/install.ts
106
+ import { execSync } from "node:child_process";
107
+ import fs from "node:fs";
108
+ import https from "node:https";
109
+ import path2 from "node:path";
110
+ var LINUX_URL = {
111
+ arm64: "cloudflared-linux-arm64",
112
+ arm: "cloudflared-linux-arm",
113
+ x64: "cloudflared-linux-amd64",
114
+ ia32: "cloudflared-linux-386"
115
+ };
116
+ var MACOS_URL = {
117
+ arm64: "cloudflared-darwin-amd64.tgz",
118
+ x64: "cloudflared-darwin-amd64.tgz"
119
+ };
120
+ var WINDOWS_URL = {
121
+ x64: "cloudflared-windows-amd64.exe",
122
+ ia32: "cloudflared-windows-386.exe"
123
+ };
124
+ function resolveBase(version) {
125
+ if (version === "latest") {
126
+ return `${RELEASE_BASE}latest/download/`;
127
+ }
128
+ return `${RELEASE_BASE}download/${version}/`;
129
+ }
130
+ function installCloudflared(to = cloudflaredBinPath, version = CLOUDFLARED_VERSION) {
131
+ switch (process.platform) {
132
+ case "linux": {
133
+ return installLinux(to, version);
134
+ }
135
+ case "darwin": {
136
+ return installMacos(to, version);
137
+ }
138
+ case "win32": {
139
+ return installWindows(to, version);
140
+ }
141
+ default: {
142
+ throw new Error(`Unsupported platform: ${process.platform}`);
143
+ }
144
+ }
145
+ }
146
+ async function installLinux(to, version = CLOUDFLARED_VERSION) {
147
+ const file = LINUX_URL[process.arch];
148
+ if (file === undefined) {
149
+ throw new Error(`Unsupported architecture: ${process.arch}`);
150
+ }
151
+ await download(resolveBase(version) + file, to);
152
+ fs.chmodSync(to, 493);
153
+ return to;
154
+ }
155
+ async function installMacos(to, version = CLOUDFLARED_VERSION) {
156
+ const file = MACOS_URL[process.arch];
157
+ if (file === undefined) {
158
+ throw new Error(`Unsupported architecture: ${process.arch}`);
159
+ }
160
+ await download(resolveBase(version) + file, `${to}.tgz`);
161
+ if (process.env.DEBUG) {
162
+ console.log(`Extracting to ${to}`);
163
+ }
164
+ execSync(`tar -xzf ${path2.basename(`${to}.tgz`)}`, {
165
+ cwd: path2.dirname(to)
166
+ });
167
+ fs.unlinkSync(`${to}.tgz`);
168
+ fs.renameSync(`${path2.dirname(to)}/cloudflared`, to);
169
+ return to;
170
+ }
171
+ async function installWindows(to, version = CLOUDFLARED_VERSION) {
172
+ const file = WINDOWS_URL[process.arch];
173
+ if (file === undefined) {
174
+ throw new Error(`Unsupported architecture: ${process.arch}`);
175
+ }
176
+ await download(resolveBase(version) + file, to);
177
+ return to;
178
+ }
179
+ function download(url, to, redirect = 0) {
180
+ if (redirect === 0) {
181
+ if (process.env.DEBUG) {
182
+ console.log(`Downloading ${url} to ${to}`);
183
+ }
184
+ } else if (process.env.DEBUG) {
185
+ console.log(`Redirecting to ${url}`);
186
+ }
187
+ return new Promise((resolve, reject) => {
188
+ if (!fs.existsSync(path2.dirname(to))) {
189
+ fs.mkdirSync(path2.dirname(to), { recursive: true });
190
+ }
191
+ let done = true;
192
+ const file = fs.createWriteStream(to);
193
+ const request = https.get(url, (res) => {
194
+ if (res.statusCode === 302 && res.headers.location !== undefined) {
195
+ const redirection = res.headers.location;
196
+ done = false;
197
+ file.close(() => {
198
+ download(redirection, to, redirect + 1).then(resolve, reject);
199
+ });
200
+ return;
201
+ }
202
+ res.pipe(file);
203
+ });
204
+ file.on("finish", () => {
205
+ if (done) {
206
+ file.close(() => {
207
+ resolve(to);
208
+ });
209
+ }
210
+ });
211
+ request.on("error", (err) => {
212
+ fs.unlink(to, () => {
213
+ reject(err);
214
+ });
215
+ });
216
+ file.on("error", (err) => {
217
+ fs.unlink(to, () => {
218
+ reject(err);
219
+ });
220
+ });
221
+ request.end();
222
+ });
223
+ }
224
+
225
+ // src/core/quick-tunnel/index.ts
226
+ var MAX_QUICK_TUNNEL_ATTEMPTS = 5;
227
+ function isQuickTunnelRateLimitedError(message) {
228
+ return message.includes("429") || message.includes("Too Many Requests") || message.includes('status_code="429');
229
+ }
230
+ async function startCloudflaredTunnelWithRetry(cfArgs) {
231
+ for (let attempt = 1;attempt <= MAX_QUICK_TUNNEL_ATTEMPTS; attempt++) {
232
+ const tunnel = startCloudflaredTunnel(cfArgs);
233
+ try {
234
+ await tunnel.url;
235
+ return tunnel;
236
+ } catch (e) {
237
+ const msg = String(e);
238
+ if (attempt < MAX_QUICK_TUNNEL_ATTEMPTS && isQuickTunnelRateLimitedError(msg)) {
239
+ const delayMs = 2000 * attempt;
240
+ console.log(`Cloudflare quick tunnel rate-limited (${attempt}/${MAX_QUICK_TUNNEL_ATTEMPTS}), retrying in ${delayMs}ms…`);
241
+ await sleep(delayMs);
242
+ continue;
243
+ }
244
+ throw e;
245
+ }
246
+ }
247
+ throw new Error("startCloudflaredTunnelWithRetry: exhausted attempts");
248
+ }
249
+ function resolvedLocalUrl(opts) {
250
+ return opts.url ?? `${opts.protocol || "http"}://${opts.hostname ?? "localhost"}:${opts.port ?? 3000}`;
251
+ }
252
+ function envAcceptsCloudflareNotice() {
253
+ const v = process.env.BUNCARGO_ACCEPT_CLOUDFLARE_NOTICE;
254
+ const u = process.env.UNTUN_ACCEPT_CLOUDFLARE_NOTICE;
255
+ return v === "1" || v === "true" || u === "1" || u === "true";
256
+ }
257
+ async function promptInstallCloudflared() {
258
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
259
+ return false;
260
+ }
261
+ return new Promise((resolve) => {
262
+ const rl = createInterface({
263
+ input: process.stdin,
264
+ output: process.stdout
265
+ });
266
+ rl.question("Do you agree with the above terms and wish to install the binary from GitHub? (y/N) ", (answer) => {
267
+ rl.close();
268
+ resolve(/^y(es)?$/i.test(answer.trim()));
269
+ });
270
+ });
271
+ }
272
+ async function startQuickTunnel(opts) {
273
+ const url = resolvedLocalUrl(opts);
274
+ console.log(`Starting cloudflared tunnel to ${url}`);
275
+ if (!existsSync(cloudflaredBinPath)) {
276
+ console.log(cloudflaredNotice);
277
+ const canInstall = opts.acceptCloudflareNotice || envAcceptsCloudflareNotice() || await promptInstallCloudflared();
278
+ if (!canInstall) {
279
+ console.error("Skipping tunnel setup.");
280
+ return;
281
+ }
282
+ await installCloudflared();
283
+ }
284
+ const cfArgs = { "--url": url };
285
+ if (!opts.verifyTLS) {
286
+ cfArgs["--no-tls-verify"] = null;
287
+ }
288
+ const tunnel = await startCloudflaredTunnelWithRetry(cfArgs);
289
+ const cleanup = async () => {
290
+ tunnel.stop();
291
+ };
292
+ return {
293
+ getURL: async () => await tunnel.url,
294
+ close: cleanup
295
+ };
296
+ }
297
+
298
+ // src/core/tunnel.ts
299
+ function parseExposeNames(exposeValue) {
300
+ if (exposeValue === undefined)
301
+ return null;
302
+ const names = exposeValue.split(",").map((name) => name.trim()).filter(Boolean);
303
+ return new Set(names);
304
+ }
305
+ async function resolvePublicUrl(tunnel) {
306
+ if (typeof tunnel.getURL === "function") {
307
+ return await tunnel.getURL();
308
+ }
309
+ return tunnel.url ?? tunnel.publicUrl ?? tunnel.tunnelUrl ?? null;
310
+ }
311
+ function toCloseFn(tunnel) {
312
+ const close = tunnel.close ?? tunnel.stop ?? tunnel.destroy;
313
+ if (!close)
314
+ return async () => {};
315
+ return async () => {
316
+ await close();
317
+ };
318
+ }
319
+ function resolveExposeTargets(env, exposeValue) {
320
+ const requestedNames = parseExposeNames(exposeValue);
321
+ const knownTargets = new Map;
322
+ const enabledTargets = new Map;
323
+ for (const [name, config] of Object.entries(env.services)) {
324
+ const port = env.ports[name];
325
+ if (port === undefined)
326
+ continue;
327
+ const target = { kind: "service", name, port };
328
+ knownTargets.set(name, target);
329
+ if (config.expose === true) {
330
+ enabledTargets.set(name, target);
331
+ }
332
+ }
333
+ for (const [name, config] of Object.entries(env.apps)) {
334
+ const port = env.ports[name];
335
+ if (port === undefined)
336
+ continue;
337
+ const target = { kind: "app", name, port };
338
+ knownTargets.set(name, target);
339
+ if (config.expose === true) {
340
+ enabledTargets.set(name, target);
341
+ }
342
+ }
343
+ if (requestedNames === null) {
344
+ return {
345
+ targets: Array.from(enabledTargets.values()),
346
+ unknownNames: [],
347
+ notEnabledNames: []
348
+ };
349
+ }
350
+ const unknownNames = [];
351
+ const notEnabledNames = [];
352
+ const targets = [];
353
+ for (const name of requestedNames) {
354
+ if (!knownTargets.has(name)) {
355
+ unknownNames.push(name);
356
+ continue;
357
+ }
358
+ const enabledTarget = enabledTargets.get(name);
359
+ if (!enabledTarget) {
360
+ notEnabledNames.push(name);
361
+ continue;
362
+ }
363
+ targets.push(enabledTarget);
364
+ }
365
+ return { targets, unknownNames, notEnabledNames };
366
+ }
367
+ function resolveExposeTunnelStaggerMs() {
368
+ const raw = process.env.BUNCARGO_EXPOSE_TUNNEL_STAGGER_MS;
369
+ if (raw === undefined || raw === "") {
370
+ return 900;
371
+ }
372
+ const n = Number.parseInt(raw, 10);
373
+ return Number.isFinite(n) && n >= 0 ? n : 900;
374
+ }
375
+ async function startPublicTunnels(targets, options = {}) {
376
+ const start = options.start ?? ((input) => startQuickTunnel(input));
377
+ const staggerMs = resolveExposeTunnelStaggerMs();
378
+ const tunnels = [];
379
+ try {
380
+ let index = 0;
381
+ for (const target of targets) {
382
+ if (index > 0 && staggerMs > 0) {
383
+ await sleep(staggerMs);
384
+ }
385
+ index += 1;
386
+ const localUrl = `http://localhost:${target.port}`;
387
+ const tunnel = await start({
388
+ url: localUrl
389
+ });
390
+ if (tunnel === undefined) {
391
+ throw new Error(`Tunnel for "${target.name}" could not be started (cloudflared missing or install declined)`);
392
+ }
393
+ const publicUrl = await resolvePublicUrl(tunnel);
394
+ if (!publicUrl) {
395
+ throw new Error(`Tunnel for "${target.name}" did not provide a public URL`);
396
+ }
397
+ tunnels.push({
398
+ kind: target.kind,
399
+ name: target.name,
400
+ localUrl,
401
+ publicUrl,
402
+ close: toCloseFn(tunnel)
403
+ });
404
+ }
405
+ return tunnels;
406
+ } catch (e) {
407
+ await stopPublicTunnels(tunnels);
408
+ throw e;
409
+ }
410
+ }
411
+ async function stopPublicTunnels(tunnels) {
412
+ await Promise.allSettled(tunnels.map((tunnel) => tunnel.close()));
413
+ }
414
+
415
+ export { resolveExposeTargets, startPublicTunnels, stopPublicTunnels };