unplugin-https-reverse-proxy 4.1.0-beta.3 → 4.1.0-beta.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.
@@ -19,458 +19,21 @@ import {
19
19
  } from "./chunk-RKHJN6KY.js";
20
20
 
21
21
  // src/index.ts
22
- import process8 from "node:process";
22
+ import process9 from "node:process";
23
23
  import { Table } from "console-table-printer";
24
24
  import c from "picocolors";
25
25
  import { createUnplugin } from "unplugin";
26
26
 
27
27
  // src/caddy/index.ts
28
28
  import { execFile } from "node:child_process";
29
- import { chmodSync, createWriteStream, existsSync as existsSync5, mkdirSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
30
- import { readFile as readFile3, unlink as unlink3, writeFile as writeFile2 } from "node:fs/promises";
29
+ import { chmodSync, createWriteStream, existsSync as existsSync5, mkdirSync, unlinkSync as unlinkSync2 } from "node:fs";
30
+ import { readFile as readFile3, unlink, writeFile as writeFile2 } from "node:fs/promises";
31
31
  import { platform as platform3 } from "node:os";
32
32
  import { join as join6 } from "node:path";
33
- import process7 from "node:process";
34
-
35
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/system.mjs
36
- var ReactiveFlags;
37
- (function(ReactiveFlags2) {
38
- ReactiveFlags2[ReactiveFlags2["None"] = 0] = "None";
39
- ReactiveFlags2[ReactiveFlags2["Mutable"] = 1] = "Mutable";
40
- ReactiveFlags2[ReactiveFlags2["Watching"] = 2] = "Watching";
41
- ReactiveFlags2[ReactiveFlags2["RecursedCheck"] = 4] = "RecursedCheck";
42
- ReactiveFlags2[ReactiveFlags2["Recursed"] = 8] = "Recursed";
43
- ReactiveFlags2[ReactiveFlags2["Dirty"] = 16] = "Dirty";
44
- ReactiveFlags2[ReactiveFlags2["Pending"] = 32] = "Pending";
45
- })(ReactiveFlags || (ReactiveFlags = {}));
46
- function createReactiveSystem({ update, notify: notify2, unwatched }) {
47
- let currentVersion = 0;
48
- return {
49
- link: link2,
50
- unlink: unlink4,
51
- propagate: propagate2,
52
- checkDirty: checkDirty2,
53
- endTracking: endTracking2,
54
- startTracking: startTracking2,
55
- shallowPropagate: shallowPropagate2
56
- };
57
- function link2(dep, sub) {
58
- const prevDep = sub.depsTail;
59
- if (prevDep !== void 0 && prevDep.dep === dep) {
60
- return;
61
- }
62
- const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
63
- if (nextDep !== void 0 && nextDep.dep === dep) {
64
- nextDep.version = currentVersion;
65
- sub.depsTail = nextDep;
66
- return;
67
- }
68
- const prevSub = dep.subsTail;
69
- if (prevSub !== void 0 && prevSub.version === currentVersion && prevSub.sub === sub) {
70
- return;
71
- }
72
- const newLink = sub.depsTail = dep.subsTail = {
73
- version: currentVersion,
74
- dep,
75
- sub,
76
- prevDep,
77
- nextDep,
78
- prevSub,
79
- nextSub: void 0
80
- };
81
- if (nextDep !== void 0) {
82
- nextDep.prevDep = newLink;
83
- }
84
- if (prevDep !== void 0) {
85
- prevDep.nextDep = newLink;
86
- } else {
87
- sub.deps = newLink;
88
- }
89
- if (prevSub !== void 0) {
90
- prevSub.nextSub = newLink;
91
- } else {
92
- dep.subs = newLink;
93
- }
94
- }
95
- function unlink4(link3, sub = link3.sub) {
96
- const dep = link3.dep;
97
- const prevDep = link3.prevDep;
98
- const nextDep = link3.nextDep;
99
- const nextSub = link3.nextSub;
100
- const prevSub = link3.prevSub;
101
- if (nextDep !== void 0) {
102
- nextDep.prevDep = prevDep;
103
- } else {
104
- sub.depsTail = prevDep;
105
- }
106
- if (prevDep !== void 0) {
107
- prevDep.nextDep = nextDep;
108
- } else {
109
- sub.deps = nextDep;
110
- }
111
- if (nextSub !== void 0) {
112
- nextSub.prevSub = prevSub;
113
- } else {
114
- dep.subsTail = prevSub;
115
- }
116
- if (prevSub !== void 0) {
117
- prevSub.nextSub = nextSub;
118
- } else if ((dep.subs = nextSub) === void 0) {
119
- unwatched(dep);
120
- }
121
- return nextDep;
122
- }
123
- function propagate2(link3) {
124
- let next2 = link3.nextSub;
125
- let stack;
126
- top:
127
- do {
128
- const sub = link3.sub;
129
- let flags = sub.flags;
130
- if (!(flags & 60)) {
131
- sub.flags = flags | 32;
132
- } else if (!(flags & 12)) {
133
- flags = 0;
134
- } else if (!(flags & 4)) {
135
- sub.flags = flags & ~8 | 32;
136
- } else if (!(flags & 48) && isValidLink(link3, sub)) {
137
- sub.flags = flags | 40;
138
- flags &= 1;
139
- } else {
140
- flags = 0;
141
- }
142
- if (flags & 2) {
143
- notify2(sub);
144
- }
145
- if (flags & 1) {
146
- const subSubs = sub.subs;
147
- if (subSubs !== void 0) {
148
- const nextSub = (link3 = subSubs).nextSub;
149
- if (nextSub !== void 0) {
150
- stack = { value: next2, prev: stack };
151
- next2 = nextSub;
152
- }
153
- continue;
154
- }
155
- }
156
- if ((link3 = next2) !== void 0) {
157
- next2 = link3.nextSub;
158
- continue;
159
- }
160
- while (stack !== void 0) {
161
- link3 = stack.value;
162
- stack = stack.prev;
163
- if (link3 !== void 0) {
164
- next2 = link3.nextSub;
165
- continue top;
166
- }
167
- }
168
- break;
169
- } while (true);
170
- }
171
- function startTracking2(sub) {
172
- ++currentVersion;
173
- sub.depsTail = void 0;
174
- sub.flags = sub.flags & ~56 | 4;
175
- }
176
- function endTracking2(sub) {
177
- const depsTail = sub.depsTail;
178
- let toRemove = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
179
- while (toRemove !== void 0) {
180
- toRemove = unlink4(toRemove, sub);
181
- }
182
- sub.flags &= ~4;
183
- }
184
- function checkDirty2(link3, sub) {
185
- let stack;
186
- let checkDepth = 0;
187
- top:
188
- do {
189
- const dep = link3.dep;
190
- const flags = dep.flags;
191
- let dirty = false;
192
- if (sub.flags & 16) {
193
- dirty = true;
194
- } else if ((flags & 17) === 17) {
195
- if (update(dep)) {
196
- const subs = dep.subs;
197
- if (subs.nextSub !== void 0) {
198
- shallowPropagate2(subs);
199
- }
200
- dirty = true;
201
- }
202
- } else if ((flags & 33) === 33) {
203
- if (link3.nextSub !== void 0 || link3.prevSub !== void 0) {
204
- stack = { value: link3, prev: stack };
205
- }
206
- link3 = dep.deps;
207
- sub = dep;
208
- ++checkDepth;
209
- continue;
210
- }
211
- if (!dirty) {
212
- const nextDep = link3.nextDep;
213
- if (nextDep !== void 0) {
214
- link3 = nextDep;
215
- continue;
216
- }
217
- }
218
- while (checkDepth--) {
219
- const firstSub = sub.subs;
220
- const hasMultipleSubs = firstSub.nextSub !== void 0;
221
- if (hasMultipleSubs) {
222
- link3 = stack.value;
223
- stack = stack.prev;
224
- } else {
225
- link3 = firstSub;
226
- }
227
- if (dirty) {
228
- if (update(sub)) {
229
- if (hasMultipleSubs) {
230
- shallowPropagate2(firstSub);
231
- }
232
- sub = link3.sub;
233
- continue;
234
- }
235
- } else {
236
- sub.flags &= ~32;
237
- }
238
- sub = link3.sub;
239
- const nextDep = link3.nextDep;
240
- if (nextDep !== void 0) {
241
- link3 = nextDep;
242
- continue top;
243
- }
244
- dirty = false;
245
- }
246
- return dirty;
247
- } while (true);
248
- }
249
- function shallowPropagate2(link3) {
250
- do {
251
- const sub = link3.sub;
252
- const flags = sub.flags;
253
- if ((flags & 48) === 32) {
254
- sub.flags = flags | 16;
255
- if (flags & 2) {
256
- notify2(sub);
257
- }
258
- }
259
- } while ((link3 = link3.nextSub) !== void 0);
260
- }
261
- function isValidLink(checkLink, sub) {
262
- let link3 = sub.depsTail;
263
- while (link3 !== void 0) {
264
- if (link3 === checkLink) {
265
- return true;
266
- }
267
- link3 = link3.prevDep;
268
- }
269
- return false;
270
- }
271
- }
272
-
273
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/index.mjs
274
- var queuedEffects = [];
275
- var { link, unlink, propagate, checkDirty, endTracking, startTracking, shallowPropagate } = createReactiveSystem({
276
- update(signal2) {
277
- if ("getter" in signal2) {
278
- return updateComputed(signal2);
279
- } else {
280
- return updateSignal(signal2, signal2.value);
281
- }
282
- },
283
- notify,
284
- unwatched(node2) {
285
- if ("getter" in node2) {
286
- let toRemove = node2.deps;
287
- if (toRemove !== void 0) {
288
- node2.flags = 17;
289
- do {
290
- toRemove = unlink(toRemove, node2);
291
- } while (toRemove !== void 0);
292
- }
293
- } else if (!("previousValue" in node2)) {
294
- effectOper.call(node2);
295
- }
296
- }
297
- });
298
- var batchDepth = 0;
299
- var notifyIndex = 0;
300
- var queuedEffectsLength = 0;
301
- var activeSub;
302
- var activeScope;
303
- function setCurrentSub(sub) {
304
- const prevSub = activeSub;
305
- activeSub = sub;
306
- return prevSub;
307
- }
308
- function signal(initialValue) {
309
- return signalOper.bind({
310
- previousValue: initialValue,
311
- value: initialValue,
312
- subs: void 0,
313
- subsTail: void 0,
314
- flags: 1
315
- });
316
- }
317
- function computed(getter) {
318
- return computedOper.bind({
319
- value: void 0,
320
- subs: void 0,
321
- subsTail: void 0,
322
- deps: void 0,
323
- depsTail: void 0,
324
- flags: 17,
325
- getter
326
- });
327
- }
328
- function effect(fn) {
329
- const e = {
330
- fn,
331
- subs: void 0,
332
- subsTail: void 0,
333
- deps: void 0,
334
- depsTail: void 0,
335
- flags: 2
336
- };
337
- if (activeSub !== void 0) {
338
- link(e, activeSub);
339
- } else if (activeScope !== void 0) {
340
- link(e, activeScope);
341
- }
342
- const prev = setCurrentSub(e);
343
- try {
344
- e.fn();
345
- } finally {
346
- setCurrentSub(prev);
347
- }
348
- return effectOper.bind(e);
349
- }
350
- function updateComputed(c2) {
351
- const prevSub = setCurrentSub(c2);
352
- startTracking(c2);
353
- try {
354
- const oldValue = c2.value;
355
- return oldValue !== (c2.value = c2.getter(oldValue));
356
- } finally {
357
- setCurrentSub(prevSub);
358
- endTracking(c2);
359
- }
360
- }
361
- function updateSignal(s, value2) {
362
- s.flags = 1;
363
- return s.previousValue !== (s.previousValue = value2);
364
- }
365
- function notify(e) {
366
- const flags = e.flags;
367
- if (!(flags & 64)) {
368
- e.flags = flags | 64;
369
- const subs = e.subs;
370
- if (subs !== void 0) {
371
- notify(subs.sub);
372
- } else {
373
- queuedEffects[queuedEffectsLength++] = e;
374
- }
375
- }
376
- }
377
- function run(e, flags) {
378
- if (flags & 16 || flags & 32 && checkDirty(e.deps, e)) {
379
- const prev = setCurrentSub(e);
380
- startTracking(e);
381
- try {
382
- e.fn();
383
- } finally {
384
- setCurrentSub(prev);
385
- endTracking(e);
386
- }
387
- return;
388
- } else if (flags & 32) {
389
- e.flags = flags & ~32;
390
- }
391
- let link2 = e.deps;
392
- while (link2 !== void 0) {
393
- const dep = link2.dep;
394
- const depFlags = dep.flags;
395
- if (depFlags & 64) {
396
- run(dep, dep.flags = depFlags & ~64);
397
- }
398
- link2 = link2.nextDep;
399
- }
400
- }
401
- function flush() {
402
- while (notifyIndex < queuedEffectsLength) {
403
- const effect2 = queuedEffects[notifyIndex];
404
- queuedEffects[notifyIndex++] = void 0;
405
- run(effect2, effect2.flags &= ~64);
406
- }
407
- notifyIndex = 0;
408
- queuedEffectsLength = 0;
409
- }
410
- function computedOper() {
411
- const flags = this.flags;
412
- if (flags & 16 || flags & 32 && checkDirty(this.deps, this)) {
413
- if (updateComputed(this)) {
414
- const subs = this.subs;
415
- if (subs !== void 0) {
416
- shallowPropagate(subs);
417
- }
418
- }
419
- } else if (flags & 32) {
420
- this.flags = flags & ~32;
421
- }
422
- if (activeSub !== void 0) {
423
- link(this, activeSub);
424
- } else if (activeScope !== void 0) {
425
- link(this, activeScope);
426
- }
427
- return this.value;
428
- }
429
- function signalOper(...value2) {
430
- if (value2.length) {
431
- if (this.value !== (this.value = value2[0])) {
432
- this.flags = 17;
433
- const subs = this.subs;
434
- if (subs !== void 0) {
435
- propagate(subs);
436
- if (!batchDepth) {
437
- flush();
438
- }
439
- }
440
- }
441
- } else {
442
- const value3 = this.value;
443
- if (this.flags & 16) {
444
- if (updateSignal(this, value3)) {
445
- const subs = this.subs;
446
- if (subs !== void 0) {
447
- shallowPropagate(subs);
448
- }
449
- }
450
- }
451
- if (activeSub !== void 0) {
452
- link(this, activeSub);
453
- }
454
- return value3;
455
- }
456
- }
457
- function effectOper() {
458
- let dep = this.deps;
459
- while (dep !== void 0) {
460
- dep = unlink(dep, this);
461
- }
462
- const sub = this.subs;
463
- if (sub !== void 0) {
464
- unlink(sub);
465
- }
466
- this.flags = 0;
467
- }
468
-
469
- // src/caddy/index.ts
33
+ import process8 from "node:process";
470
34
  import { got } from "got-cjs";
471
35
  import { HttpProxyAgent } from "http-proxy-agent";
472
36
  import { HttpsProxyAgent } from "https-proxy-agent";
473
- import * as lockfile from "proper-lockfile";
474
37
 
475
38
  // node_modules/.pnpm/@ark+util@0.46.0/node_modules/@ark/util/out/arrays.js
476
39
  var liftArray = (data) => Array.isArray(data) ? data : [data];
@@ -13420,8 +12983,9 @@ async function genCaddyfile(ctx) {
13420
12983
  }
13421
12984
 
13422
12985
  // src/caddy/config.ts
13423
- import { existsSync as existsSync2, readFileSync as readFileSync2, watch, writeFileSync } from "node:fs";
13424
- import { unlink as unlink2 } from "node:fs/promises";
12986
+ import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
12987
+ import process3 from "node:process";
12988
+ import * as lockfile from "proper-lockfile";
13425
12989
 
13426
12990
  // src/caddy/constants.ts
13427
12991
  import os from "node:os";
@@ -13553,56 +13117,108 @@ var supportList = [
13553
13117
  ];
13554
13118
 
13555
13119
  // src/caddy/config.ts
13556
- function useCaddyConfig() {
13557
- const configContentRef = signal("{}");
13558
- const configJsonRef = computed(() => {
13559
- try {
13560
- return JSON.parse(configContentRef());
13561
- } catch {
13562
- return void 0;
13563
- }
13564
- });
13565
- function setConfigContent() {
13566
- if (!existsSync2(caddyConfigPath)) {
13567
- writeFileSync(caddyConfigPath, "{}");
13568
- }
13569
- try {
13570
- configContentRef(readFileSync2(caddyConfigPath, "utf-8"));
13571
- } catch {
13572
- configContentRef("");
13573
- }
13120
+ function isAlive(pid) {
13121
+ if (pid === void 0)
13122
+ return true;
13123
+ try {
13124
+ process3.kill(pid, 0);
13125
+ return true;
13126
+ } catch {
13127
+ return false;
13574
13128
  }
13575
- if (!existsSync2(caddyConfigPath)) {
13576
- writeFileSync(caddyConfigPath, "{}");
13129
+ }
13130
+ function readConfig() {
13131
+ if (!existsSync2(caddyConfigPath))
13132
+ return {};
13133
+ let parsed2;
13134
+ try {
13135
+ parsed2 = JSON.parse(readFileSync2(caddyConfigPath, "utf-8"));
13136
+ } catch {
13137
+ return {};
13577
13138
  }
13578
- const watchCaddyConfig = watch(caddyConfigPath, () => {
13579
- setConfigContent();
13580
- });
13581
- function writeCaddyConfig(_proxies) {
13582
- const proxies = configJsonRef() || {};
13583
- _proxies.forEach((p) => {
13584
- let base = p.base || "/";
13585
- if (!base.startsWith("/"))
13586
- base = `/${base}`;
13587
- if (base !== "/" && !base.endsWith("/"))
13588
- base = `${base}/`;
13589
- const index = `${p.target}${p.portSuffix}${base}`;
13590
- proxies[index] = { ...p, base };
13591
- });
13592
- const content = JSON.stringify(proxies, null, 2);
13593
- configContentRef(content);
13594
- return writeFileSync(caddyConfigPath, content);
13139
+ const alive = {};
13140
+ for (const [key, entry] of Object.entries(parsed2)) {
13141
+ if (isAlive(entry == null ? void 0 : entry.ownerPid))
13142
+ alive[key] = entry;
13595
13143
  }
13596
- async function cleanUp() {
13597
- await unlink2(caddyConfigPath).catch(() => {
13598
- });
13599
- configContentRef("{}");
13600
- watchCaddyConfig.close();
13144
+ return alive;
13145
+ }
13146
+ function writeConfig(proxies) {
13147
+ const content = JSON.stringify(proxies, null, 2);
13148
+ const temp = `${caddyConfigPath}.${process3.pid}.tmp`;
13149
+ writeFileSync(temp, content);
13150
+ renameSync(temp, caddyConfigPath);
13151
+ }
13152
+ async function mutateConfig(lock3, mutate) {
13153
+ const release = await lock3.acquire();
13154
+ try {
13155
+ const proxies = readConfig();
13156
+ mutate(proxies);
13157
+ writeConfig(proxies);
13158
+ return proxies;
13159
+ } finally {
13160
+ release();
13601
13161
  }
13162
+ }
13163
+ function useCaddyConfig(options = {}) {
13164
+ const lock3 = options.lock ?? createFileLock();
13602
13165
  return {
13603
- configJsonRef,
13604
- writeCaddyConfig,
13605
- cleanUp
13166
+ configJsonRef: () => existsSync2(caddyConfigPath) ? readConfig() : void 0,
13167
+ async writeCaddyConfig(_proxies, key) {
13168
+ await mutateConfig(lock3, (proxies) => {
13169
+ for (const p of _proxies)
13170
+ proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: process3.pid };
13171
+ });
13172
+ },
13173
+ async removeProxy(key) {
13174
+ const proxies = await mutateConfig(lock3, (current) => {
13175
+ for (const route of Object.keys(current)) {
13176
+ if (route.endsWith(`#${key}`))
13177
+ delete current[route];
13178
+ }
13179
+ });
13180
+ if (Object.keys(proxies).length === 0)
13181
+ removeConfigFile();
13182
+ },
13183
+ readProxies: () => readConfig(),
13184
+ async cleanUp() {
13185
+ removeConfigFile();
13186
+ }
13187
+ };
13188
+ }
13189
+ function removeConfigFile() {
13190
+ try {
13191
+ if (existsSync2(caddyConfigPath))
13192
+ unlinkSync(caddyConfigPath);
13193
+ } catch {
13194
+ }
13195
+ }
13196
+ function normalizeBase(base) {
13197
+ let out = base || "/";
13198
+ if (!out.startsWith("/"))
13199
+ out = `/${out}`;
13200
+ if (out !== "/" && !out.endsWith("/"))
13201
+ out = `${out}/`;
13202
+ return out;
13203
+ }
13204
+ function routeKey(proxy, ownerKey) {
13205
+ return `${proxy.target}${proxy.portSuffix}${normalizeBase(proxy.base)}#${ownerKey}`;
13206
+ }
13207
+ function createFileLock() {
13208
+ return {
13209
+ async acquire() {
13210
+ if (!existsSync2(caddyConfigPath))
13211
+ writeFileSync(caddyConfigPath, "{}");
13212
+ const release = await lockfile.lock(caddyConfigPath, {
13213
+ realpath: false,
13214
+ stale: 1e4,
13215
+ retries: { retries: 20, minTimeout: 10, maxTimeout: 100 }
13216
+ });
13217
+ return () => {
13218
+ void release().catch(() => {
13219
+ });
13220
+ };
13221
+ }
13606
13222
  };
13607
13223
  }
13608
13224
 
@@ -13620,15 +13236,15 @@ function isCaddyReloadCancellation(line) {
13620
13236
  import { Buffer as Buffer2 } from "node:buffer";
13621
13237
  import { EventEmitter } from "node:events";
13622
13238
  import { dirname as dirname3, join as join5 } from "node:path";
13623
- import process6 from "node:process";
13239
+ import process7 from "node:process";
13624
13240
  import { fileURLToPath } from "node:url";
13625
13241
 
13626
13242
  // src/privileged/entry.ts
13627
13243
  import { existsSync as existsSync3 } from "node:fs";
13628
13244
  import { dirname as dirname2, join as join3 } from "node:path";
13629
- import process3 from "node:process";
13245
+ import process4 from "node:process";
13630
13246
  function resolveHelperEntry(options) {
13631
- const { moduleDir, nodeBin = process3.execPath, exists: exists2 = existsSync3 } = options;
13247
+ const { moduleDir, nodeBin = process4.execPath, exists: exists2 = existsSync3 } = options;
13632
13248
  for (const name of ["privileged-helper.js", "privileged-helper.cjs", "privileged-helper.mjs"]) {
13633
13249
  const candidate = findUp(moduleDir, name, exists2);
13634
13250
  if (candidate)
@@ -13659,16 +13275,17 @@ import { existsSync as existsSync4 } from "node:fs";
13659
13275
  import { readFile as readFile2, writeFile } from "node:fs/promises";
13660
13276
  import { platform as platform2 } from "node:os";
13661
13277
  import { join as join4 } from "node:path";
13278
+ import * as lockfile2 from "proper-lockfile";
13662
13279
 
13663
13280
  // src/privileged/launch.ts
13664
13281
  import { spawn as spawn2, spawnSync } from "node:child_process";
13665
13282
  import { randomBytes } from "node:crypto";
13666
13283
  import { platform } from "node:os";
13667
- import process5 from "node:process";
13284
+ import process6 from "node:process";
13668
13285
 
13669
13286
  // src/privileged/client.ts
13670
13287
  import { connect } from "node:net";
13671
- import process4 from "node:process";
13288
+ import process5 from "node:process";
13672
13289
  var FORWARDED_ENV_KEYS = [
13673
13290
  "HOME",
13674
13291
  "USER",
@@ -13681,7 +13298,7 @@ var FORWARDED_ENV_KEYS = [
13681
13298
  "NO_PROXY",
13682
13299
  "no_proxy"
13683
13300
  ];
13684
- function collectForwardedEnv(source = process4.env) {
13301
+ function collectForwardedEnv(source = process5.env) {
13685
13302
  const result = {};
13686
13303
  for (const key of FORWARDED_ENV_KEYS) {
13687
13304
  const value2 = source[key];
@@ -13917,9 +13534,9 @@ function authenticateSudo(sudoCommand = "sudo", options = {}) {
13917
13534
  return { ok: true };
13918
13535
  if (options.target) {
13919
13536
  for (const line of describePasswordReason(options.target, options.https ?? false))
13920
- process5.stderr.write(`${line}
13537
+ process6.stderr.write(`${line}
13921
13538
  `);
13922
- process5.stderr.write("\n");
13539
+ process6.stderr.write("\n");
13923
13540
  }
13924
13541
  if (spawnSync(sudoCommand, ["-v"], { stdio: "inherit" }).status === 0)
13925
13542
  return { ok: true };
@@ -13945,7 +13562,7 @@ async function startPrivilegedHelper(options) {
13945
13562
  sudoCommand = "sudo",
13946
13563
  skipAuth = false,
13947
13564
  direct = false,
13948
- env: env2 = process5.env,
13565
+ env: env2 = process6.env,
13949
13566
  log,
13950
13567
  connectTimeoutMs = 12e4
13951
13568
  } = options;
@@ -13964,8 +13581,8 @@ async function startPrivilegedHelper(options) {
13964
13581
  socketPath,
13965
13582
  "--token",
13966
13583
  token,
13967
- ...typeof process5.getuid === "function" ? ["--owner-uid", String(process5.getuid())] : [],
13968
- ...typeof process5.getgid === "function" ? ["--owner-gid", String(process5.getgid())] : [],
13584
+ ...typeof process6.getuid === "function" ? ["--owner-uid", String(process6.getuid())] : [],
13585
+ ...typeof process6.getgid === "function" ? ["--owner-gid", String(process6.getgid())] : [],
13969
13586
  ...options.caddyStoragePath ? ["--caddy-storage", options.caddyStoragePath] : [],
13970
13587
  "--caddy",
13971
13588
  options.caddyBin,
@@ -13974,7 +13591,7 @@ async function startPrivilegedHelper(options) {
13974
13591
  ];
13975
13592
  let child;
13976
13593
  if (!direct && platform() === "win32") {
13977
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process5.cwd() });
13594
+ await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process6.cwd() });
13978
13595
  } else {
13979
13596
  const command = direct ? helperEntry : sudoCommand;
13980
13597
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -14031,21 +13648,34 @@ function sessionSocketPath(runtimeDir) {
14031
13648
  }
14032
13649
  async function openHelperSession(scope2) {
14033
13650
  const socketPath = sessionSocketPath(scope2.runtimeDir);
14034
- if (existsSync4(socketPath) || platform2() === "win32") {
14035
- const token2 = await readToken(scope2.runtimeDir);
14036
- if (token2) {
14037
- const reused = await connectExistingHelper(socketPath, token2);
14038
- if (reused) {
14039
- return {
14040
- client: reused,
14041
- reused: true,
14042
- close: async () => {
14043
- await reused.close();
14044
- }
14045
- };
14046
- }
14047
- }
13651
+ const release = await acquireStartLock(scope2.runtimeDir);
13652
+ try {
13653
+ const reused = await tryReuse(socketPath, scope2);
13654
+ if (reused)
13655
+ return reused;
13656
+ return await startNew(socketPath, scope2);
13657
+ } finally {
13658
+ release();
14048
13659
  }
13660
+ }
13661
+ async function tryReuse(socketPath, scope2) {
13662
+ if (!existsSync4(socketPath) && platform2() !== "win32")
13663
+ return void 0;
13664
+ const token = await readToken(scope2.runtimeDir);
13665
+ if (!token)
13666
+ return void 0;
13667
+ const reused = await connectExistingHelper(socketPath, token);
13668
+ if (!reused)
13669
+ return void 0;
13670
+ return {
13671
+ client: reused,
13672
+ reused: true,
13673
+ close: async () => {
13674
+ await reused.close();
13675
+ }
13676
+ };
13677
+ }
13678
+ async function startNew(socketPath, scope2) {
14049
13679
  const token = createHelperToken();
14050
13680
  const started = await startPrivilegedHelper({
14051
13681
  socketPath,
@@ -14071,6 +13701,22 @@ async function openHelperSession(scope2) {
14071
13701
  }
14072
13702
  };
14073
13703
  }
13704
+ async function acquireStartLock(runtimeDir) {
13705
+ const lockPath = join4(runtimeDir, "helper.start.lock");
13706
+ try {
13707
+ await writeFile(lockPath, "", { flag: "a" });
13708
+ } catch {
13709
+ }
13710
+ const release = await lockfile2.lock(lockPath, {
13711
+ realpath: false,
13712
+ stale: 3e4,
13713
+ retries: { retries: 100, minTimeout: 50, maxTimeout: 200 }
13714
+ });
13715
+ return () => {
13716
+ void release().catch(() => {
13717
+ });
13718
+ };
13719
+ }
14074
13720
  async function readToken(runtimeDir) {
14075
13721
  try {
14076
13722
  const content = await readFile2(tokenPath(runtimeDir), "utf8");
@@ -14129,7 +13775,7 @@ var HelperCaddyProcess = class extends EventEmitter {
14129
13775
  }
14130
13776
  };
14131
13777
  function caddyStoragePath() {
14132
- return process6.platform === "win32" ? join5(process6.env.AppData ?? "", "Caddy") : join5(process6.env.HOME ?? "", "Library/Application Support/Caddy");
13778
+ return process7.platform === "win32" ? join5(process7.env.AppData ?? "", "Caddy") : join5(process7.env.HOME ?? "", "Library/Application Support/Caddy");
14133
13779
  }
14134
13780
  function openPrivilegedSession(runtimeDir, options) {
14135
13781
  const env2 = resolvePrivilegedEnv();
@@ -14279,15 +13925,15 @@ async function download() {
14279
13925
  const file = createWriteStream(caddyPath);
14280
13926
  let _platform = platform3().toString();
14281
13927
  _platform === "win32" && (_platform = "windows");
14282
- let _arch = process7.arch.toString();
13928
+ let _arch = process8.arch.toString();
14283
13929
  _arch === "x64" && (_arch = "amd64");
14284
13930
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
14285
13931
  if (!support)
14286
13932
  return reject2(new Error("not support"));
14287
13933
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
14288
- existsSync5(caddyPath) && unlinkSync(caddyPath);
14289
- const httpProxy = process7.env.HTTP_PROXY || process7.env.http_proxy;
14290
- const httpsProxy = process7.env.HTTPS_PROXY || process7.env.https_proxy;
13934
+ existsSync5(caddyPath) && unlinkSync2(caddyPath);
13935
+ const httpProxy = process8.env.HTTP_PROXY || process8.env.http_proxy;
13936
+ const httpsProxy = process8.env.HTTPS_PROXY || process8.env.https_proxy;
14291
13937
  const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
14292
13938
  const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
14293
13939
  const chmodCaddyOnce = once(() => {
@@ -14303,7 +13949,7 @@ async function download() {
14303
13949
  chmodCaddyOnce();
14304
13950
  }).pipe(file).on("finish", () => {
14305
13951
  logProgressOver();
14306
- if (process7.platform === "win32")
13952
+ if (process8.platform === "win32")
14307
13953
  return resolve2(caddyPath);
14308
13954
  chmodSync(caddyPath, 493);
14309
13955
  resolve2(caddyPath);
@@ -14353,26 +13999,17 @@ var defaultDependencies = {
14353
13999
  caddyBin: caddyPath,
14354
14000
  caddyConfigPath: caddyFilePath,
14355
14001
  reason
14356
- })
14002
+ }),
14003
+ config: () => getCaddyConfig()
14357
14004
  };
14358
14005
  var CaddyInstant = class {
14359
14006
  constructor(deps = {}) {
14360
14007
  this.inited = false;
14361
14008
  this.stoped = false;
14362
- /** has locked when start */
14363
- this.locked = false;
14364
14009
  this._stopEffects = [];
14010
+ /** Identifies this instance's routes in the shared config. */
14011
+ this.proxyKey = `${process8.pid}-${Math.random().toString(36).slice(2, 8)}`;
14365
14012
  this.deps = { ...defaultDependencies, ...deps };
14366
- this.locked = this.checkLock();
14367
- }
14368
- checkLock() {
14369
- if (!existsSync5(caddyLockFilePath))
14370
- writeFileSync2(caddyLockFilePath, "");
14371
- try {
14372
- return lockfile.checkSync(caddyLockFilePath);
14373
- } catch {
14374
- return false;
14375
- }
14376
14013
  }
14377
14014
  /**
14378
14015
  * Connects to the privileged helper, starting it once if needed. It is
@@ -14396,7 +14033,7 @@ var CaddyInstant = class {
14396
14033
  }
14397
14034
  get caddyRoot() {
14398
14035
  return join6(
14399
- process7.platform === "win32" ? `${process7.env.AppData}/Caddy` : `${process7.env.HOME}/Library/Application Support/Caddy`,
14036
+ process8.platform === "win32" ? `${process8.env.AppData}/Caddy` : `${process8.env.HOME}/Library/Application Support/Caddy`,
14400
14037
  "./pki/authorities/local"
14401
14038
  );
14402
14039
  }
@@ -14404,7 +14041,7 @@ var CaddyInstant = class {
14404
14041
  return await writeFile2(caddyFilePath, this.caddyfile || "");
14405
14042
  }
14406
14043
  async deleteCaddyfile() {
14407
- return await unlink3(caddyFilePath);
14044
+ return await unlink(caddyFilePath);
14408
14045
  }
14409
14046
  async init() {
14410
14047
  await download();
@@ -14442,9 +14079,15 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14442
14079
  if (!health.healthy)
14443
14080
  throw new Error(formatTlsHealthFailure(targetHost, health));
14444
14081
  }
14082
+ /**
14083
+ * Regenerates the Caddyfile from the config on disk.
14084
+ *
14085
+ * Reading the file rather than a cached view matters here: another project
14086
+ * may have added its route since this instance last looked.
14087
+ */
14445
14088
  async updateCaddyfile() {
14446
- const { configJsonRef } = getCaddyConfig();
14447
- const proxies = Object.values(configJsonRef() || {});
14089
+ const { readProxies } = this.deps.config();
14090
+ const proxies = Object.values(readProxies());
14448
14091
  const ctx = validateTemplateContext({
14449
14092
  caddy_root: this.caddyRoot,
14450
14093
  proxies
@@ -14493,7 +14136,7 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14493
14136
  const session = await this.session({ target: targetHost, https });
14494
14137
  await session.client.call("hosts.add", { ip: sourceHost, host: targetHost });
14495
14138
  consola.success("update host success\n");
14496
- const normalizeBase = (b) => {
14139
+ const normalizeBase2 = (b) => {
14497
14140
  let out = b || "/";
14498
14141
  if (!out.startsWith("/"))
14499
14142
  out = `/${out}`;
@@ -14501,7 +14144,7 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14501
14144
  out = `${out}/`;
14502
14145
  return out;
14503
14146
  };
14504
- const baseNormalized = normalizeBase(base);
14147
+ const baseNormalized = normalizeBase2(base);
14505
14148
  const proxies = [
14506
14149
  {
14507
14150
  target: targetHost,
@@ -14512,27 +14155,12 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14512
14155
  healthCheck
14513
14156
  }
14514
14157
  ];
14515
- const { writeCaddyConfig } = getCaddyConfig();
14516
- writeCaddyConfig(proxies);
14158
+ const { writeCaddyConfig } = this.deps.config();
14159
+ await writeCaddyConfig(proxies, this.proxyKey);
14517
14160
  await this.updateCaddyfile();
14518
- let skipInitialCaddyfileEffect = true;
14519
- this._stopEffects.push(
14520
- effect(() => {
14521
- getCaddyConfig().configJsonRef();
14522
- if (skipInitialCaddyfileEffect) {
14523
- skipInitialCaddyfileEffect = false;
14524
- return;
14525
- }
14526
- void this.updateCaddyfile();
14527
- })
14528
- );
14529
- if (!existsSync5(caddyLockFilePath))
14530
- writeFileSync2(caddyLockFilePath, "");
14531
- if (!this.locked) {
14532
- await session.client.call("port.free", { port: 443 });
14533
- if (process7.platform === "win32" || !https)
14534
- await session.client.call("port.free", { port: 80 });
14535
- }
14161
+ await session.client.call("port.free", { port: 443 });
14162
+ if (process8.platform === "win32" || !https)
14163
+ await session.client.call("port.free", { port: 80 });
14536
14164
  return new Promise((resolve2, reject2) => {
14537
14165
  let startupCheckStarted = false;
14538
14166
  const resolveWhenReady = async () => {
@@ -14546,106 +14174,89 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14546
14174
  }
14547
14175
  resolve2();
14548
14176
  } catch (error) {
14549
- if (!this.locked)
14550
- await this.baseCleanup(restore);
14177
+ await this.baseCleanup(restore);
14551
14178
  reject2(error);
14552
14179
  }
14553
14180
  };
14554
14181
  const setupCleanup = () => {
14555
- process7.on("SIGINT", async () => {
14182
+ process8.on("SIGINT", async () => {
14556
14183
  if (this.stoped)
14557
14184
  return;
14558
- process7.stdin.resume();
14185
+ process8.stdin.resume();
14559
14186
  try {
14560
14187
  await this.baseCleanup(restore);
14561
14188
  } finally {
14562
14189
  this.stoped = true;
14563
- process7.nextTick(() => {
14564
- process7.exit();
14190
+ process8.nextTick(() => {
14191
+ process8.exit();
14565
14192
  });
14566
14193
  }
14567
14194
  });
14568
- const originalExit = process7.exit.bind(process7);
14569
- process7.exit = async (code) => {
14195
+ const originalExit = process8.exit.bind(process8);
14196
+ process8.exit = async (code) => {
14570
14197
  if (this.stoped)
14571
14198
  return originalExit(code);
14572
- process7.stdin.resume();
14199
+ process8.stdin.resume();
14573
14200
  try {
14574
14201
  await this.baseCleanup();
14575
14202
  } finally {
14576
14203
  this.stoped = true;
14577
- process7.nextTick(() => {
14204
+ process8.nextTick(() => {
14578
14205
  originalExit(code);
14579
14206
  });
14580
14207
  }
14581
14208
  };
14582
14209
  };
14583
- if (!this.locked) {
14584
- lockfile.lockSync(caddyLockFilePath);
14585
- setupCleanup();
14586
- void (async () => {
14587
- try {
14588
- const child = new HelperCaddyProcess(session.client);
14589
- this._caddyChild = child;
14590
- await session.client.call("caddy.start");
14591
- child.on("exit", (code) => {
14592
- if (code !== null && code !== 0)
14593
- reject2(new Error(`Caddy exited with code ${code}`));
14594
- });
14595
- child.stderr.on("data", async (data) => {
14596
- const lines = data.toString().split("\n").map((line) => line.trim());
14597
- for (const line of lines) {
14598
- showCaddyLog && line && console.info(line);
14599
- if (isCaddyReloadCancellation(line)) {
14600
- consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14601
- continue;
14602
- }
14603
- try {
14604
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14605
- if (line.includes("parsing caddyfile tokens")) {
14606
- consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14210
+ setupCleanup();
14211
+ void (async () => {
14212
+ try {
14213
+ const child = new HelperCaddyProcess(session.client);
14214
+ this._caddyChild = child;
14215
+ await session.client.call("caddy.start");
14216
+ child.on("exit", (code) => {
14217
+ if (code !== null && code !== 0)
14218
+ reject2(new Error(`Caddy exited with code ${code}`));
14219
+ });
14220
+ child.stderr.on("data", async (data) => {
14221
+ const lines = data.toString().split("\n").map((line) => line.trim());
14222
+ for (const line of lines) {
14223
+ showCaddyLog && line && console.info(line);
14224
+ if (isCaddyReloadCancellation(line)) {
14225
+ consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14226
+ continue;
14227
+ }
14228
+ try {
14229
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14230
+ if (line.includes("parsing caddyfile tokens")) {
14231
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14607
14232
 
14608
14233
  ${line}
14609
14234
  `);
14610
- await this.baseCleanup();
14611
- process7.exit();
14612
- } else {
14613
- consola.error(`${line}
14235
+ await this.baseCleanup();
14236
+ process8.exit();
14237
+ } else {
14238
+ consola.error(`${line}
14614
14239
  `);
14615
- return reject2(line);
14616
- }
14240
+ return reject2(line);
14617
14241
  }
14618
- } catch {
14619
14242
  }
14620
- if (line.includes("config file changed"))
14621
- consola.success("Detect added a new reverse proxy config, restarted.\n");
14622
- if (line.includes("caddy proxying") || line.includes("serving initial"))
14623
- void resolveWhenReady();
14243
+ } catch {
14624
14244
  }
14625
- });
14626
- child.stdout.on("data", (data) => {
14627
- consola.info(data.toString());
14628
- void resolveWhenReady();
14629
- });
14630
- } catch (error) {
14631
- if (!this.locked)
14632
- await this.baseCleanup(restore);
14633
- reject2(error);
14634
- }
14635
- })();
14636
- } else {
14637
- consola.info("Caddy is running in another process.");
14638
- void (async () => {
14639
- try {
14640
- if (https)
14641
- await this.ensureTlsReady(targetHost);
14642
- setupCleanup();
14643
- resolve2();
14644
- } catch (error) {
14645
- reject2(error);
14646
- }
14647
- })();
14648
- }
14245
+ if (line.includes("config file changed"))
14246
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
14247
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
14248
+ void resolveWhenReady();
14249
+ }
14250
+ });
14251
+ child.stdout.on("data", (data) => {
14252
+ consola.info(data.toString());
14253
+ void resolveWhenReady();
14254
+ });
14255
+ } catch (error) {
14256
+ await this.baseCleanup(restore);
14257
+ reject2(error);
14258
+ }
14259
+ })();
14649
14260
  });
14650
14261
  }
14651
14262
  async baseCleanup(restore = true) {
@@ -14669,18 +14280,9 @@ ${line}
14669
14280
  consola.fail("Restore host failed.\n");
14670
14281
  }
14671
14282
  }
14672
- if (!this.locked && !this.stoped) {
14673
- await this.stopCaddy();
14283
+ if (!this.stoped) {
14674
14284
  try {
14675
- await lockfile.unlock(caddyLockFilePath).catch(() => {
14676
- });
14677
- await unlink3(caddyFilePath).catch(() => {
14678
- });
14679
- await unlink3(caddyLockFilePath).catch(() => {
14680
- });
14681
- if (caddyConfig) {
14682
- await caddyConfig.cleanUp();
14683
- }
14285
+ await this.deps.config().removeProxy(this.proxyKey);
14684
14286
  } catch (e) {
14685
14287
  consola.error(e);
14686
14288
  }
@@ -14692,7 +14294,7 @@ ${line}
14692
14294
  var config;
14693
14295
  var caddy;
14694
14296
  var hmrSseBridgeActive = false;
14695
- var cwd = process8.cwd();
14297
+ var cwd = process9.cwd();
14696
14298
  function colorUrl(url2) {
14697
14299
  return c.green(url2.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
14698
14300
  }
@@ -14803,7 +14405,7 @@ var unpluginFactory = (options) => ({
14803
14405
  },
14804
14406
  webpack(compiler) {
14805
14407
  var _a4, _b3, _c2;
14806
- if (process8.env.NODE_ENV !== "development")
14408
+ if (process9.env.NODE_ENV !== "development")
14807
14409
  return;
14808
14410
  const {
14809
14411
  enable = true,
@@ -14824,7 +14426,7 @@ var unpluginFactory = (options) => ({
14824
14426
  port: 8080,
14825
14427
  ...compiler.options.devServer,
14826
14428
  // @ts-expect-error vuecli
14827
- ...(_a4 = process8.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14429
+ ...(_a4 = process9.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14828
14430
  };
14829
14431
  const source = `${devServer.host}:${devServer.port}`;
14830
14432
  if (isPrivilegeDenied())
@@ -14843,7 +14445,7 @@ var unpluginFactory = (options) => ({
14843
14445
  const _close = (_c2 = compiler.close) == null ? void 0 : _c2.bind(compiler);
14844
14446
  if (_close) {
14845
14447
  compiler.close = async (callback) => {
14846
- process8.on("exit", () => {
14448
+ process9.on("exit", () => {
14847
14449
  _close && _close(callback);
14848
14450
  });
14849
14451
  };
@@ -14874,7 +14476,7 @@ var unpluginFactory = (options) => ({
14874
14476
  },
14875
14477
  async rspack(compiler) {
14876
14478
  var _a4, _b3, _c2, _d2;
14877
- if (process8.env.NODE_ENV !== "development")
14479
+ if (process9.env.NODE_ENV !== "development")
14878
14480
  return;
14879
14481
  const {
14880
14482
  enable = true,