-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
494 lines (457 loc) · 19 KB
/
index.ts
File metadata and controls
494 lines (457 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import type { Plugin, ViteDevServer } from 'vite'
import fs from 'node:fs'
import path from 'node:path'
import net from 'node:net'
import pc from 'picocolors'
type Options = {
/** Caddy Admin API base URL */
adminUrl?: string // default 'http://127.0.0.1:2019'
/** Caddy apps.http server id to use/create */
serverId?: string // default 'vite-dev'
/** Addresses for the dev server we manage in Caddy */
listen?: string[] // default [':80']
/**
* Choose the subdomain source (before the TLD) when no explicit `domain` is given:
* - 'folder' (default): use current folder name
* - 'pkg': use package.json "name"
*/
nameSource?: 'folder' | 'pkg'
/** Top-level domain (TLD) to use when building the domain (ignored if `domain` is set) */
tld?: string // default 'localhost'
/**
* Fully explicit domain to use (e.g., 'myapp.localhost' or 'myapp.local').
* If provided, overrides nameSource+tld.
*/
domain?: string
/**
* If an existing domain points to an active port that is NOT the current Vite port:
* - true (default): fail fast & explain
* - false: leave it alone and continue (no changes)
*/
failOnActiveDomain?: boolean
/**
* Insert the route at index 0 (before others) when creating a new one.
* Default: true
*/
insertFirst?: boolean
/** Print logs. Default: true */
verbose?: boolean
}
export default function domain(user: Options = {}): Plugin {
const opt: Required<Omit<Options, 'domain'>> & { domain?: string } = {
adminUrl: user.adminUrl ?? 'http://127.0.0.1:2019',
serverId: user.serverId ?? 'vite-dev',
listen: user.listen ?? [':443', ':80'],
nameSource: user.nameSource ?? 'folder',
tld: user.tld ?? 'localhost',
domain: user.domain,
failOnActiveDomain: user.failOnActiveDomain ?? true,
insertFirst: user.insertFirst ?? true,
verbose: user.verbose ?? false,
}
const log = (...args: unknown[]) => {
if (opt.verbose) console.log('[vite-plugin-domain]', ...args)
}
const warn = (...args: unknown[]) => console.warn('[vite-plugin-domain]', ...args)
const err = (...args: unknown[]) => console.error('[vite-plugin-domain]', ...args)
const adminOrigin = new URL(opt.adminUrl).origin
function withAdminHeaders(init: RequestInit = {}) {
const headers = new Headers(init.headers)
headers.set('origin', adminOrigin)
return { ...init, headers }
}
// ---------- HTTP helpers ----------
async function req(url: string, init?: RequestInit) {
const r = await fetch(url, withAdminHeaders(init))
const txt = await r.text()
if (!r.ok) throw new Error(`HTTP ${r.status} ${r.statusText} for ${url}\n${txt}`)
return txt ? JSON.parse(txt) : undefined
}
async function get<T = unknown>(url: string): Promise<T | undefined> {
const r = await fetch(url, withAdminHeaders())
if (!r.ok) return undefined
const t = await r.text()
return t ? (JSON.parse(t) as T) : (undefined as T | undefined)
}
const post = (url: string, body: unknown) =>
req(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
const put = (url: string, body: unknown) =>
req(url, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
const del = async (url: string) => {
const r = await fetch(url, withAdminHeaders({ method: 'DELETE' }))
if (!r.ok) throw new Error(`HTTP ${r.status} ${r.statusText} for ${url}\n${await r.text()}`)
}
// ---------- Domain helpers ----------
function slugFromFolder(): string {
return path
.basename(process.cwd())
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '')
}
function slugFromPkg(): string {
try {
const pkg = JSON.parse(
fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'),
)
const name = typeof pkg.name === 'string' ? pkg.name : slugFromFolder()
return String(name)
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '')
} catch {
return slugFromFolder()
}
}
function computeDomain(): string {
const env = process.env.VITE_PLUGIN_DOMAIN_VALUE?.trim().toLowerCase()
if (env) return env
if (opt.domain) return opt.domain
const base = opt.nameSource === 'pkg' ? slugFromPkg() : slugFromFolder()
return `${base}.${opt.tld}`
}
// ---------- Caddy bootstrap (HTTPS-first) ----------
async function ensureCaddyServerExists(domain: string) {
// If root config is null, seed both http+tls apps with internal issuer policy for this domain.
const root = await get(`${opt.adminUrl}/config/`)
if (root == null) {
await post(`${opt.adminUrl}/load`, {
apps: {
http: {
servers: {
[opt.serverId]: {
listen: opt.listen,
routes: [],
},
},
},
tls: {
automation: {
policies: [
{
subjects: [domain],
issuers: [{ module: 'internal' }],
},
],
},
},
},
})
log(
`Initialized Caddy config; server '${opt.serverId}' on ${opt.listen.join(', ')}; TLS internal for ${domain}`,
)
return
}
// Ensure server exists (and listens on desired ports)
const serverBase = `${opt.adminUrl}/config/apps/http/servers/${encodeURIComponent(opt.serverId)}`
const haveServer = await fetch(serverBase, withAdminHeaders({ method: 'GET' }))
if (!haveServer.ok) {
// Create parents as needed, then server
const ensurePath = async (p: string, payload: unknown) => {
const r = await fetch(p, withAdminHeaders({ method: 'GET' }))
if (!r.ok) await put(p, payload)
}
await ensurePath(`${opt.adminUrl}/config/apps`, {})
await ensurePath(`${opt.adminUrl}/config/apps/http`, { servers: {} })
await ensurePath(`${opt.adminUrl}/config/apps/http/servers`, {})
await put(serverBase, { listen: opt.listen, routes: [] })
log(`Created server '${opt.serverId}' on ${opt.listen.join(', ')}`)
} else {
// Make sure desired ports are present
const listenPath = `${serverBase}/listen`
const current: string[] | undefined = await get(listenPath)
const want = new Set(opt.listen)
const next = Array.from(new Set([...(current ?? []), ...want]))
if (!arraysEqual(current ?? [], next)) {
await put(listenPath, next)
log(`Updated '${opt.serverId}' listen → ${next.join(', ')}`)
}
// If automatic_https was previously disabled, re-enable by clearing/setting flag
const autoPath = `${serverBase}/automatic_https`
const auto: any = await get(autoPath)
if (auto?.disable === true) {
await put(autoPath, { ...auto, disable: false })
log(`Re-enabled automatic HTTPS on '${opt.serverId}'`)
}
}
// Ensure TLS automation policy (internal issuer) exists for this domain
await ensureTlsPolicy(domain)
}
async function ensureTlsPolicy(domain: string) {
const ensurePath = async (p: string, payload: unknown) => {
const r = await fetch(p, withAdminHeaders({ method: 'GET' }))
if (!r.ok) await put(p, payload)
}
await ensurePath(`${opt.adminUrl}/config/apps`, {})
// Create bare tls app if needed (non-destructive to other apps)
const tlsPath = `${opt.adminUrl}/config/apps/tls`
const haveTls = await fetch(tlsPath, withAdminHeaders({ method: 'GET' }))
if (!haveTls.ok) {
await put(tlsPath, { automation: { policies: [] } })
} else {
// ensure automation/policies containers exist
const autoPath = `${tlsPath}/automation`
const auto = await fetch(autoPath, withAdminHeaders({ method: 'GET' }))
if (!auto.ok) await put(autoPath, { policies: [] })
const polPath = `${autoPath}/policies`
const pol = await fetch(polPath, withAdminHeaders({ method: 'GET' }))
if (!pol.ok) await put(polPath, []) // initialize array
}
// Check for an existing internal-policy that covers this exact domain
const policies: any[] =
(await get(`${opt.adminUrl}/config/apps/tls/automation/policies`)) ?? []
const idx = policies.findIndex(
p =>
Array.isArray(p?.subjects) &&
p.subjects.includes(domain) &&
Array.isArray(p?.issuers) &&
p.issuers.some((i: any) => i?.module === 'internal'),
)
if (idx === -1) {
await post(`${opt.adminUrl}/config/apps/tls/automation/policies`, {
subjects: [domain],
issuers: [{ module: 'internal' }],
})
log(`Added TLS automation policy (internal) for ${domain}`)
} else {
log(`TLS automation policy already present for ${domain}`)
}
}
// ---------- Caddy routes ----------
type CaddyRoute = {
'@id'?: string
match?: Array<{ host?: string[] } & Record<string, unknown>>
handle?: Array<
| {
handler: 'reverse_proxy'
upstreams?: Array<{ dial?: string } & Record<string, unknown>>
}
| Record<string, unknown>
>
terminal?: boolean
[k: string]: unknown
}
async function getRoutes(): Promise<CaddyRoute[] | undefined> {
return get<CaddyRoute[]>(
`${opt.adminUrl}/config/apps/http/servers/${encodeURIComponent(opt.serverId)}/routes`,
)
}
function findRouteByHost(routes: CaddyRoute[] | undefined, host: string) {
if (!routes) return { route: undefined as CaddyRoute | undefined, index: -1 }
for (let i = 0; i < routes.length; i++) {
const r = routes[i]
const matches = Array.isArray(r.match) ? r.match : []
for (const m of matches) {
if (Array.isArray((m as any).host) && (m as any).host.includes(host)) {
return { route: r, index: i }
}
}
}
return { route: undefined, index: -1 }
}
function extractUpstreamPort(route: CaddyRoute): number | undefined {
const handlers = Array.isArray(route.handle) ? route.handle : []
for (const h of handlers) {
if ((h as any).handler === 'reverse_proxy') {
const ups = (h as any).upstreams
if (Array.isArray(ups) && ups.length > 0) {
const dial = ups[0]?.dial as string | undefined
if (dial) {
const m = /:(\d+)$/.exec(dial.trim())
if (m) return Number(m[1])
}
}
}
}
return undefined
}
async function addRoute(domain: string, port: number) {
const route: CaddyRoute = {
match: [{ host: [domain] }],
handle: [{ handler: 'reverse_proxy', upstreams: [{ dial: `localhost:${port}` }] }],
terminal: true,
}
const base = `${opt.adminUrl}/config/apps/http/servers/${encodeURIComponent(opt.serverId)}/routes`
if (opt.insertFirst) {
await put(`${base}/0`, route)
} else {
await post(base, route)
}
}
async function replaceRouteAt(index: number, domain: string, port: number) {
const base = `${opt.adminUrl}/config/apps/http/servers/${encodeURIComponent(opt.serverId)}/routes/${index}`
const updated: CaddyRoute = {
match: [{ host: [domain] }],
handle: [{ handler: 'reverse_proxy', upstreams: [{ dial: `localhost:${port}` }] }],
terminal: true,
}
await put(base, updated)
}
// ---------- Port liveness ----------
function isPortActive(port: number, host = '127.0.0.1', timeoutMs = 350): Promise<boolean> {
return new Promise(resolve => {
const socket = net.createConnection({ host, port })
const done = (val: boolean) => {
socket.removeAllListeners()
try {
socket.end()
socket.destroy()
} catch {}
resolve(val)
}
const timer = setTimeout(() => done(false), timeoutMs)
socket.once('connect', () => {
clearTimeout(timer)
done(true)
})
socket.once('error', () => {
clearTimeout(timer)
done(false)
})
})
}
// ---------- /etc/hosts check for .local ----------
function checkHostsForLocal(domain: string) {
if (!domain.endsWith('.local')) return
try {
const hosts = fs.readFileSync('/etc/hosts', 'utf8')
const present = hosts
.split(/\r?\n/)
.some(line =>
line.trim().startsWith('#')
? false
: line.split(/\s+/).slice(1).includes(domain),
)
if (!present) {
warn(
`Missing /etc/hosts entry for ${domain}. Add it with:\n` +
` sudo bash -c "echo '127.0.0.1 ${domain}' >> /etc/hosts"`,
)
}
} catch {
warn(
`Could not read /etc/hosts to verify ${domain}. If requests fail, add:\n` +
` sudo bash -c "echo '127.0.0.1 ${domain}' >> /etc/hosts"`,
)
}
}
// ---------- Main flow ----------
async function wireDomain(server: ViteDevServer) {
const addr = server.httpServer?.address()
const vitePort =
addr && typeof addr === 'object' && 'port' in addr ? (addr.port as number) : undefined
if (!vitePort) throw new Error('Unable to determine Vite dev server port')
const domain = computeDomain()
// HTTPS-first bootstrap (server + TLS policy)
await ensureCaddyServerExists(domain)
// /etc/hosts check (for .local)
checkHostsForLocal(domain)
// Route management (stable domain, port reconciliation)
const routes = await getRoutes()
const { route, index } = findRouteByHost(routes, domain)
if (!route) {
await addRoute(domain, vitePort)
printWhereToBrowse(domain)
return
}
const existingPort = extractUpstreamPort(route)
if (!existingPort) {
await replaceRouteAt(index, domain, vitePort)
printWhereToBrowse(domain)
return
}
const active = await isPortActive(existingPort)
if (active) {
if (existingPort === vitePort) {
printWhereToBrowse(domain)
return
}
const msg =
`Domain '${domain}' is already mapped to active port ${existingPort}. ` +
`Refusing to overwrite. Stop that service or choose a different domain.`
if (opt.failOnActiveDomain) {
// Fail the wiring for this domain but do not disrupt the Vite dev server.
// This keeps the dev process healthy while clearly reporting the issue.
err(msg)
return
} else {
warn(msg)
return
}
}
if (existingPort !== vitePort) {
await replaceRouteAt(index, domain, vitePort)
}
printWhereToBrowse(domain)
}
function printWhereToBrowse(domain: string) {
const httpsPort = pickHttpsPort(opt.listen)
const url =
httpsPort && httpsPort !== 443 ? `https://${domain}:${httpsPort}` : `https://${domain}`
console.log(` ➜ ${pc.bold('Domain')}: ${pc.cyan(url)} ${pc.dim('(via caddy)')}`)
}
function pickHttpsPort(listen: string[]): number | undefined {
const ports = listen
.map(a => {
const m = /:(\d+)$/.exec(a)
return m ? Number(m[1]) : undefined
})
.filter((n): n is number => typeof n === 'number')
if (ports.includes(443)) return 443
// prefer any port that's not 80
return ports.find(p => p !== 80)
}
function arraysEqual(a: string[], b: string[]) {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
return true
}
return {
name: 'vite-plugin-domain',
apply: 'serve',
// Ensure Vite dev server accepts our domain's Host header
// without requiring users to edit their config manually.
config(config) {
try {
const domain = computeDomain()
const current = config.server?.allowedHosts
// If user already allows all hosts, don't change anything
if (current === true) return
// Build the next allowed hosts list, preserving existing entries
const list = Array.isArray(current) ? [...current] : []
// Helper to see if an entry (with optional leading '.') covers the domain
const covers = (entry: string, host: string) =>
entry.startsWith('.') ? host === entry.slice(1) || host.endsWith(entry) : entry === host
if (!list.some(e => covers(e, domain))) {
list.push(domain)
if (opt.verbose) log(`Added ${domain} to Vite server.allowedHosts`)
}
return {
server: {
...(config.server ?? {}),
allowedHosts: list,
},
}
} catch (e) {
// Non-fatal: if anything goes wrong, don't block Vite startup
warn('failed to set server.allowedHosts automatically:', (e as any)?.message || e)
return
}
},
configureServer(server) {
server.httpServer?.once('listening', () => {
wireDomain(server).catch(e => {
err('setup failed:', e.message || e)
})
})
},
}
}