deserved 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -8
- package/chunk-6mm4k23z.js +38 -0
- package/cli.js +2 -36
- package/handlers.d.ts +4 -5
- package/index.d.ts +2 -1
- package/index.js +1 -35
- package/live.d.ts +17 -0
- package/log.d.ts +6 -0
- package/options.d.ts +26 -0
- package/package.json +1 -1
- package/server.d.ts +5 -41
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# deserved
|
|
2
2
|
|
|
3
|
-
Tiny (
|
|
3
|
+
Tiny (8.7 kB gzip), zero-dep Bun static server.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
bunx deserved .
|
|
@@ -30,10 +30,12 @@ bunx deserved [path] [options]
|
|
|
30
30
|
| `-w, --watch` | Live reload via SSE |
|
|
31
31
|
| `-o, --open` | Open the browser |
|
|
32
32
|
| `--cors` | Enable CORS |
|
|
33
|
-
| `--no-dir` |
|
|
34
|
-
| `--cache` | Long-lived, immutable cache headers for assets |
|
|
35
|
-
| `--no-compress` |
|
|
33
|
+
| `--dir`, `--no-dir` | Directory listing (default on) |
|
|
34
|
+
| `--cache`, `--no-cache` | Long-lived, immutable cache headers for assets (default off) |
|
|
35
|
+
| `--compress`, `--no-compress` | zstd/gzip compression (default on) |
|
|
36
36
|
| `-q, --quiet` | Suppress request logs |
|
|
37
|
+
| `-h, --help` | Show help |
|
|
38
|
+
| `-v, --version` | Show version |
|
|
37
39
|
|
|
38
40
|
## Examples
|
|
39
41
|
|
|
@@ -68,17 +70,32 @@ CLI (`DEFAULT_OPTIONS`). It resolves to `{ port, hostname, url, stop() }`;
|
|
|
68
70
|
`stop()` closes the server and, if `watch: true` was passed, the file
|
|
69
71
|
watcher. Unlike the CLI, a bind failure (e.g. a port already in use) rejects
|
|
70
72
|
the promise instead of exiting the process. A `port` passed to `serve()` is
|
|
71
|
-
always treated as explicit — it never hops to another port.
|
|
73
|
+
always treated as explicit — it never hops to another port. `quiet: true`
|
|
74
|
+
silences all output, including the startup banner.
|
|
75
|
+
|
|
76
|
+
To mount the file server inside your own `Bun.serve()`, use the request
|
|
77
|
+
handler directly (it takes the same `Partial<Options>`; `watch` needs
|
|
78
|
+
`serve()`, which owns the file watcher):
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { createHandler } from "deserved";
|
|
82
|
+
|
|
83
|
+
Bun.serve({ fetch: createHandler({ root: "dist", spa: true, quiet: true }) });
|
|
84
|
+
```
|
|
72
85
|
|
|
73
86
|
## Features
|
|
74
87
|
|
|
75
88
|
- `Bun.file()` / `Bun.serve()`: no streams plumbing
|
|
89
|
+
- Clean URLs: `/about` serves `about.html` or `about/index.html`
|
|
76
90
|
- ETag + `304`
|
|
77
91
|
- Range requests (`206`) for media
|
|
78
92
|
- SPA mode (HTML Accept only; assets still 404)
|
|
79
|
-
-
|
|
93
|
+
- Custom `404.html` for browser requests
|
|
94
|
+
- Optional live reload (`--watch`) via Server-Sent Events; tabs reconnect and reload after a server restart
|
|
80
95
|
- CSS-only changes hot-swap stylesheets in place instead of a full page reload
|
|
81
|
-
-
|
|
96
|
+
- zstd or gzip compression, negotiated per request
|
|
82
97
|
- Cache headers off by default (`no-cache`); opt in per-run with `--cache` for long-lived, immutable asset caching
|
|
83
98
|
- Directory listings (disable with `--no-dir`)
|
|
84
|
-
-
|
|
99
|
+
- Dotfiles (`.env`, `.git/`) are never served, except `/.well-known/`
|
|
100
|
+
- Symlinks can't escape the served root
|
|
101
|
+
- Colored request logs (plain when piped or with `NO_COLOR`)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var t={root:".",port:3000,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};import{readdirSync as Ae,realpathSync as ie,statSync as U}from"fs";import{extname as Oe,isAbsolute as Me,join as ce,resolve as ae,sep as le}from"path";var{escapeHTML:M}=globalThis.Bun;var P="/__live.js",F="/__events",j=`(()=>{let down=false;const e=new EventSource("/__events");e.onopen=()=>{if(down)location.reload()};e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{if(down&&e.readyState===2)location.reload();down=true}})()`;function z(i){let c=i.toLowerCase().lastIndexOf("</body>");if(c===-1)return i+'<script src="/__live.js"></script>';return i.slice(0,c)+'<script src="/__live.js"></script>'+i.slice(c)}var L={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};function q(){let i=new Set,c=new TextEncoder,a=c.encode(`: ping
|
|
3
|
+
|
|
4
|
+
`),l=setInterval(()=>{for(let m of i)try{m.enqueue(a)}catch{i.delete(m)}},8000);l.unref();function p(){let m,h=new ReadableStream({start(y){m=y,i.add(y),y.enqueue(c.encode(`retry: 500
|
|
5
|
+
: connected
|
|
6
|
+
|
|
7
|
+
`))},cancel(){i.delete(m)}});return new Response(h,{headers:L})}function u(m="reload"){let h=c.encode(`data: ${m}
|
|
8
|
+
|
|
9
|
+
`);for(let y of i)try{y.enqueue(h)}catch{i.delete(y)}}function d(){clearInterval(l);for(let m of i)try{m.close()}catch{}i.clear()}return{subscribe:p,broadcast:u,close:d}}function G(i){return i.split(/[/\\]/).some((c)=>c.startsWith(".")||c==="node_modules")}function V(i){if(i.length===0)return"reload";return i.every((c)=>c?.endsWith(".css"))?"css":"reload"}function ye(i,c){return i===!0&&!c.NO_COLOR}var be=ye(process.stdout.isTTY,process.env),O=(i)=>be?`\x1B[${i}m`:"",w={reset:O(0),dim:O(2),green:O(32),yellow:O(33),red:O(31),cyan:O(36),bold:O(1)},xe=/[\x00-\x1f\x7f]/g,we=/[\x00-\x1f\x7f]/;function Ce(i){return we.test(i)?i.replace(xe,""):i}var Re=`${w.green}\u2713${w.reset}`,ve=`${w.yellow}\u25CB${w.reset}`,$e=`${w.red}\u2717${w.reset}`,{dim:Ee,reset:Te}=w,D=[];function Se(){if(D.length===1)queueMicrotask(_)}function _(){if(D.length===0)return;let i=D.join(`
|
|
10
|
+
`);D=[],process.stdout.write(`${i}
|
|
11
|
+
`)}function B(i,c,a,l){if(l)return;let p=c<300?Re:c<400?ve:$e;D.push(`${p} ${Ee}${i}${Te} ${c} ${Ce(a)}`),Se()}function I(i,c=!1){if(c)return;console.log(`${w.cyan}\u2502${w.reset} ${i}`)}function K(i,c,a,l){if(console.log(),console.log(` ${w.bold}deserved${w.reset} ${w.dim}serving${w.reset} ${c}`),console.log(` ${w.green}->${w.reset} ${w.cyan}${i}${w.reset}`),l)console.log(` ${w.green}->${w.reset} ${w.cyan}${l}${w.reset}`);if(a.length)console.log(` ${w.dim}${a.join(" ")}${w.reset}`);console.log()}function J(i,c){if(i)return;console.log(`${w.yellow}*${w.reset} ${c}`)}var De=new TextEncoder,Y="application/octet-stream",He={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function ze(i,c){let a=i.type;if(a&&a!==Y&&a!=="")return a;let l=Oe(c).toLowerCase();return He[l]??Y}function Ie(i){let c=i.indexOf(";"),a=(c===-1?i:i.slice(0,c)).trim().toLowerCase();return a.startsWith("text/")||a==="application/javascript"||a==="text/javascript"||a==="application/json"||a==="application/xml"||a==="image/svg+xml"||a.endsWith("+json")||a.endsWith("+xml")}function Ne(i){return i.startsWith("text/html")}function Pe(i,c,a=""){return`"${i}-${Math.trunc(c)}${a}"`}function ue(i){return`W/${i}`}function X(i){return i.startsWith("W/")?i.slice(2):i}function Fe(i,c){if(i.indexOf(",")===-1)return X(i.trim())===c;return i.split(",").some((a)=>X(a.trim())===c)}function Le(i,c){let a=i.headers.get("If-Modified-Since");if(!a)return!1;let l=Date.parse(a);if(Number.isNaN(l))return!1;return Math.trunc(c/1000)*1000<=l}function _e(i,c,a){let l=i.headers.get("If-None-Match");return l?Fe(l,c):Le(i,a)}function Be(i,c,a){let l=i.headers.get("If-Range");if(!l)return!0;if(l.startsWith('"')||l.startsWith("W/"))return l===c;let p=Date.parse(l);if(Number.isNaN(p))return!1;return p===Math.trunc(a/1000)*1000}function We(i){let c=i.headers.get("Accept");if(!c||c==="*/*")return!0;return c.includes("text/html")||c.includes("application/xhtml")}function ke(i){let c=i.headers.get("Accept-Encoding");if(!c)return null;if(!c.includes("q=0")){if(c.includes("zstd"))return"zstd";if(c.includes("gzip"))return"gzip";return null}let a=new Set;for(let l of c.split(",")){let[p="",...u]=l.split(";"),d=u.map((m)=>m.trim()).find((m)=>m.startsWith("q="));if(d!==void 0&&Number(d.slice(2))===0)continue;a.add(p.trim().toLowerCase())}if(a.has("zstd"))return"zstd";if(a.has("gzip"))return"gzip";return null}function Ue(i){if(i.startsWith("/__"))return!1;let c=i.lastIndexOf("/");if(c===i.length-1)return!0;return i.indexOf(".",c+1)===-1}var N="/.well-known";function je(i){let c=i.startsWith(N)&&(i.length===N.length||i[N.length]==="/")?N.length:0;return i.indexOf("/.",c)!==-1}function qe(i,c,a){if(!c)return null;let l=a.replace(/^\/+/,""),p=Xe(l);for(let u of p){let d=me(i,u);if(!d)continue;let m=ge(c,d);if(!m)continue;let h=de(m,Ye(u));if(h)return h}return null}function de(i,c){try{let a=U(i);if(a.isFile())return{path:i,file:Bun.file(i),size:a.size,mtimeMs:a.mtimeMs,kind:c}}catch{}return null}var Ge=4096;function Ve(i,c){if(i.size<c)return;let a=i.keys().next().value;if(a!==void 0)i.delete(a)}function fe(i,c,a){i.delete(c),i.set(c,a)}var Ke=500;function Je(i,c,a){let l=new Map,p=new Map;function u(f,x,C,v){let g=f.get(x);if(g&&(a||Date.now()-g.at<Ke)){let S=g.value===null?null:v(g.value);if(g.value===null||S!==null)return fe(f,x,g),S}let b=C(x);return Ve(f,Ge),f.set(x,{value:b,at:Date.now()}),b}let d=(f)=>qe(i,c,f),m=(f)=>Ze(i,c,f),h=a?(f)=>f:(f)=>de(f.path,f.kind),y=(f)=>pe(f)?f:null;return{resolveCached:(f)=>u(l,f,d,h),resolveDirCached:(f)=>u(p,f,m,y),invalidate:()=>{l.clear(),p.clear()},size:()=>l.size}}function pe(i){try{return U(i).isDirectory()}catch{return!1}}function Ye(i){if(i.endsWith("/index.html"))return"dir-index";if(i.endsWith(".html"))return"html-ext";return"file"}function Xe(i){if(!i||i===".")return["index.html"];let c=i.endsWith("/"),a=c?i.slice(0,-1):i;if(!a)return["index.html"];if(c)return[`${a}/index.html`];return[a,`${a}.html`,`${a}/index.html`]}function me(i,c){let a=Me(i)?i:ae(i),l=ce(a,c);if(l!==a&&!l.startsWith(a+le))return null;return l}function ge(i,c){try{let a=ie(c);if(a!==i&&!a.startsWith(i+le))return null;return a}catch{return null}}function Qe(i){try{return ie(i)}catch{return null}}function Ze(i,c,a){if(!c)return null;let l=a.replace(/^\/+/,"").replace(/\/+$/,""),p=me(i,l||".");if(!p)return null;let u=ge(c,p);return u&&pe(u)?u:null}function et(i){if(i===null)return"-";if(i<1024)return`${i} B`;if(i<1048576)return`${(i/1024).toFixed(1)} kB`;return`${(i/1048576).toFixed(1)} MB`}function tt(i){if(i===null)return"-";let c=new Date(i),a=c.getFullYear(),l=String(c.getMonth()+1).padStart(2,"0"),p=String(c.getDate()).padStart(2,"0"),u=String(c.getHours()).padStart(2,"0"),d=String(c.getMinutes()).padStart(2,"0");return`${a}-${l}-${p} ${u}:${d}`}function nt(i){let c=Ae(i,{withFileTypes:!0}),a=[];for(let l of c){if(l.name.startsWith("."))continue;let p=l.isDirectory(),u=null,d=null;if(!p)try{let m=U(ce(i,l.name));u=m.size,d=m.mtimeMs}catch{}a.push({name:l.name,dir:p,size:u,mtimeMs:d})}return a.sort((l,p)=>{if(l.dir!==p.dir)return l.dir?-1:1;return l.name.localeCompare(p.name)})}function rt(i,c){let a=i.endsWith("/")?i:`${i}/`,l=Q(a),p=st(i),u=M(i),d=c.map((h)=>{let y=ot(l,encodeURIComponent(h.name))+(h.dir?"/":""),f=h.dir?`${h.name}/`:h.name,x=et(h.size),C=tt(h.mtimeMs);return` <li><a href="${M(y)}">${M(f)}</a> <span class="meta">${M(x)}</span> <span class="meta">${M(C)}</span></li>`}).join(`
|
|
12
|
+
`),m=p!==null?` <li><a href="${M(Q(p))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
|
|
13
|
+
`:"";return`<!DOCTYPE html>
|
|
14
|
+
<html lang="en">
|
|
15
|
+
<head>
|
|
16
|
+
<meta charset="utf-8">
|
|
17
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
18
|
+
<title>Index of ${u}</title>
|
|
19
|
+
<style>
|
|
20
|
+
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
21
|
+
body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
22
|
+
h1 { font-size: 1.1rem; font-weight: 600; }
|
|
23
|
+
ul { list-style: none; padding: 0; }
|
|
24
|
+
li { padding: 0.2rem 0; display: flex; gap: 2rem; }
|
|
25
|
+
li a { color: inherit; text-decoration: none; flex: 1; }
|
|
26
|
+
li a:hover { text-decoration: underline; }
|
|
27
|
+
.meta { text-align: right; min-width: 5rem; opacity: 0.6; }
|
|
28
|
+
</style>
|
|
29
|
+
</head>
|
|
30
|
+
<body>
|
|
31
|
+
<h1>Index of ${u||"/"}</h1>
|
|
32
|
+
<ul>
|
|
33
|
+
${m}${d}
|
|
34
|
+
</ul>
|
|
35
|
+
</body>
|
|
36
|
+
</html>
|
|
37
|
+
`}function st(i){if(i==="/"||i==="")return null;let c=i.replace(/\/+$/,""),a=c.lastIndexOf("/");if(a<=0)return"/";return c.slice(0,a+1)}function Q(i){return i.split("/").map(encodeURIComponent).join("/")}function ot(i,c){if(i==="/")return`/${c}`;return`${i.replace(/\/+$/,"")}/${c}`}function it(i){let c=i.indexOf("//"),a=i.indexOf("/",c===-1?0:c+2);if(a===-1)return"/";let l=i.length,p=i.indexOf("?",a);if(p!==-1&&p<l)l=p;let u=i.indexOf("#",a);if(u!==-1&&u<l)l=u;let d=i.slice(a,l);return d===""?"/":d}function r(i={},c){let a={...t,...i},l=ae(a.root),p=Qe(l),u=Je(l,p,a.watch),d=dt(),m={opts:a,hub:c,resolveCached:u.resolveCached,resolveDirCached:u.resolveDirCached,getCompressed:d.getCompressed,notFound:null},h=async function(f){let x=it(f.url),C=f.method.toUpperCase(),v;if(x.includes("%"))try{v=decodeURIComponent(x)}catch{let g=new Response("Bad Request",{status:400});return W(C,x,a,g)}else v=x;try{return await ct(f,C,v,x,m)}catch(g){console.error(g);let b=new Response("Internal Server Error",{status:500});return W(C,x,a,b)}};return h.invalidateResolutionCache=()=>{u.invalidate(),m.notFound=null},h.invalidateCompressedCache=d.invalidate,h.resolutionCacheSize=u.size,h.compressedCacheBytes=d.bytes,h}function W(i,c,a,l){return B(i,l.status,c,a.quiet),he(i,k(l,a))}function Z(i,c){let a=i.replace(/^\/+/,"/");return new Response(null,{status:301,headers:{Location:`${a}/${new URL(c).search}`}})}function ee(i,c,a=200){return new Response(c.watch?z(i):i,{status:a,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}})}async function ct(i,c,a,l,p){let{opts:u,hub:d,resolveCached:m,resolveDirCached:h,getCompressed:y}=p,f=(g)=>W(c,a,u,g);if(u.cors&&c==="OPTIONS")return f(new Response(null,{status:204}));if(c!=="GET"&&c!=="HEAD"){let g=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return f(g)}if(u.watch&&a===P){let g=new Response(j,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return f(g)}if(u.watch&&a===F&&d){if(c==="HEAD")return f(new Response(null,{headers:L}));let g=d.subscribe();return B(c,200,a,u.quiet),k(g,u)}if(a===P||a===F)return he(c,k(new Response("Not Found",{status:404}),u));let x=je(a),C=x?null:m(a);if(C){if(C.kind==="dir-index"&&!a.endsWith("/"))return f(Z(l,i.url));return f(await ne(y,i,C,u))}let v=We(i);if(u.spa&&v&&Ue(a)){let g=m("/");if(g)return f(await ne(y,i,g,u,!0))}if(u.dir&&!x){let g=h(a);if(g){if(!a.endsWith("/"))return f(Z(l,i.url));let b=rt(a,nt(g));return f(ee(b,u))}}if(v){let g=m("/404.html");if(g){let b=p.notFound,S=b&&b.size===g.size&&b.mtimeMs===g.mtimeMs?b.html:await(async()=>{let E=await g.file.text();return p.notFound={size:g.size,mtimeMs:g.mtimeMs,html:E},E})();return f(ee(S,u,404))}}return f(new Response("Not Found",{status:404}))}var at=67108864;async function lt(i){let c=new CompressionStream("gzip"),a=c.writable.getWriter();return a.write(i),a.close(),new Uint8Array(await new Response(c.readable).arrayBuffer())}async function ut(i,c){if(i==="zstd")return new Uint8Array(await Bun.zstdCompress(c));return lt(c)}function dt(){let i=new Map,c=0,a=new Map;function l(d,m){let h=i.get(d);if(h)c-=h.data.size;fe(i,d,m),c+=m.data.size;while(c>at&&i.size>1){let y=i.keys().next().value;if(y===void 0)break;let f=i.get(y);if(i.delete(y),f)c-=f.data.size}}let p=async(d,m,h)=>{let y=`${d.key}:${m}`,f=i.get(y);if(f&&f.size===d.size&&f.mtimeMs===d.mtimeMs)return l(y,f),f.data;let x=a.get(y);if(x&&x.size===d.size&&x.mtimeMs===d.mtimeMs)return x.promise;let C=(async()=>{try{let g=await h(),b=new Blob([await ut(m,g)]);return l(y,{size:d.size,mtimeMs:d.mtimeMs,data:b}),b}catch{return null}})(),v={size:d.size,mtimeMs:d.mtimeMs,promise:C};return a.set(y,v),C.finally(()=>{if(a.get(y)===v)a.delete(y)}),C};function u(){i.clear(),c=0,a.clear()}return{getCompressed:p,invalidate:u,bytes:()=>c}}async function te(i,c,a,l,p){let u=await i(l,c,p);if(!u)return null;return a["Content-Encoding"]=c,a["Content-Length"]=String(u.size),a.ETag=ue(a.ETag??""),delete a["Accept-Ranges"],a.Vary="Accept-Encoding",new Response(u,{status:200,headers:a})}async function ne(i,c,a,l,p=!1){let{path:u,file:d,size:m,mtimeMs:h}=a,y=ze(d,u),f=p||Ne(y),x=Pe(m,h,l.watch&&f?"-live":""),C=l.compress&&Ie(y),v=l.watch&&f,g=C&&(v||m<2000000)?ke(c):null;if(_e(c,x,h)){let R=oe(x,l,f,h);if(C)R.Vary="Accept-Encoding";if(g)R.ETag=ue(x);return new Response(null,{status:304,headers:R})}let b=oe(x,l,f,h);if(b["Content-Type"]=y,b["Accept-Ranges"]="bytes",C)b.Vary="Accept-Encoding";let S=c.headers.get("Range"),E=S&&Be(c,x,h)?S:null;if(E&&c.method==="GET"){let R=pt(E,m);if(R==="invalid")return b["Content-Range"]=`bytes */${m}`,new Response(null,{status:416,headers:b});if(R){let{start:T,end:A}=R,H=A-T+1;return b["Content-Range"]=`bytes ${T}-${A}/${m}`,b["Content-Length"]=String(H),new Response(d.slice(T,A+1),{status:206,headers:b})}}if(v){if(g){let T=await te(i,g,b,{key:`${u}\x00live`,size:m,mtimeMs:h},async()=>De.encode(z(await d.text())));if(T)return T}let R=z(await d.text());return b["Content-Length"]=String(Buffer.byteLength(R)),new Response(R,{status:200,headers:b})}if(g){let R=await te(i,g,b,{key:u,size:m,mtimeMs:h},()=>d.bytes());if(R)return R}return b["Content-Length"]=String(m),new Response(d,{status:200,headers:b})}var re=Number.NaN,se="";function ft(i){if(i!==re)re=i,se=new Date(i).toUTCString();return se}function oe(i,c,a,l){return{ETag:i,"Last-Modified":ft(l),"Cache-Control":c.watch||!c.cache||a?"no-cache":"public, max-age=31536000, immutable"}}function pt(i,c){let a=/^bytes=(\d*)-(\d*)$/.exec(i.trim());if(!a)return null;let l=a[1],p=a[2],u,d;if(l===""&&p==="")return"invalid";if(l===""){let m=Number(p);if(!Number.isFinite(m)||m<=0)return"invalid";u=Math.max(0,c-m),d=c-1}else u=Number(l),d=p===""?c-1:Number(p);if(!Number.isFinite(u)||!Number.isFinite(d)||u<0||d<u||u>=c)return"invalid";return d=Math.min(d,c-1),{start:u,end:d}}function k(i,c){if(!c.cors)return i;return i.headers.set("Access-Control-Allow-Origin","*"),i.headers.set("Access-Control-Allow-Headers","*"),i.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),i}function he(i,c){if(i!=="HEAD")return c;return new Response(null,{status:c.status,statusText:c.statusText,headers:c.headers})}import{statSync as mt,watch as gt}from"fs";import{networkInterfaces as ht}from"os";import{relative as yt,resolve as bt}from"path";class e extends Error{constructor(i,c){super(i,c);this.name="RootError"}}class n extends Error{constructor(i,c,a){super(`could not bind to ${i}:${c}`,a);this.name="BindError"}}var xt=10;function wt(i){if(i&&typeof i==="object"&&"code"in i&&i.code==="EADDRINUSE")return!0;let c=i instanceof Error?i.message:String(i);return/EADDRINUSE|address already in use/i.test(c)}function Ct(i,c){return`http://${i.includes(":")?`[${i}]`:i}:${c}`}function Rt(){let i=ht();for(let c of Object.values(i))for(let a of c??[])if(a.family==="IPv4"&&!a.internal)return a.address;return null}function vt(i){if(process.platform==="darwin")return["open",i];if(process.platform==="win32")return["cmd","/c","start","",i];return["xdg-open",i]}function $t(i){try{Bun.spawn(vt(i),{stdout:"ignore",stderr:"ignore"}).unref()}catch{console.error(`Could not open browser for ${i}`)}}function Et(i){try{if(!mt(i).isDirectory())throw new e(`not a directory: ${i}`)}catch(c){if(c instanceof e)throw c;if(c instanceof Error&&"code"in c&&c.code==="ENOENT")throw new e(`directory not found: ${i}`);throw new e(`not a directory: ${i}`)}}async function s(i,{portExplicit:c=!1,banner:a=!0}={}){let l=bt(i.root);Et(l);let p=i.watch?q():void 0,u=r({...i,root:l},p),d=i.host==="localhost"?"127.0.0.1":i.host,m=!c&&i.port!==0?xt:0,h;for(let E=0;!h;E++){let R=i.port+E;try{h=Bun.serve({port:R,hostname:d,fetch:u})}catch(T){if(E>=m||!wt(T))throw new n(i.host,R,{cause:T});continue}if(E>0)I(`port ${i.port} in use, using ${R}`,i.quiet)}let y=i.host==="0.0.0.0"||i.host==="::",f=y?"localhost":i.host,x=Ct(f,h.port??i.port),C=y?Rt():null,v=C?`http://${C}:${h.port}`:void 0,g=[];if(i.spa)g.push("--spa");if(i.watch)g.push("--watch");if(i.cors)g.push("--cors");if(!i.dir)g.push("--no-dir");if(!i.compress)g.push("--no-compress");if(i.cache)g.push("--cache");if(a)K(x,yt(process.cwd(),l)||".",g,v);let b;if(i.watch&&p){let E=null,R=new Set;b=gt(l,{recursive:!0},(T,A)=>{if(A&&G(A))return;if(u.invalidateResolutionCache(),u.invalidateCompressedCache(),R.add(A),E)clearTimeout(E);E=setTimeout(()=>{let H=V([...R]);R.clear(),J(i.quiet,H),p.broadcast(H)},80)}),I("watching for changes",i.quiet)}let S=async()=>{b?.close(),p?.close(),await h.stop(),_(),I("server stopped",i.quiet)};if(i.open)$t(x);return{port:h.port??i.port,hostname:f,url:x,stop:S}}async function o(i={}){let c={...t,...i};return s(c,{portExplicit:i.port!==void 0,banner:!c.quiet})}
|
|
38
|
+
export{t,r,e,n,s,o};
|
package/cli.js
CHANGED
|
@@ -1,40 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{
|
|
4
|
-
`),s=a!==null?` <li><a href="${S(Y(a))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
|
|
5
|
-
`:"";return`<!DOCTYPE html>
|
|
6
|
-
<html lang="en">
|
|
7
|
-
<head>
|
|
8
|
-
<meta charset="utf-8">
|
|
9
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10
|
-
<title>Index of ${o}</title>
|
|
11
|
-
<style>
|
|
12
|
-
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
13
|
-
body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
14
|
-
h1 { font-size: 1.1rem; font-weight: 600; }
|
|
15
|
-
ul { list-style: none; padding: 0; }
|
|
16
|
-
li { padding: 0.2rem 0; display: flex; gap: 2rem; }
|
|
17
|
-
li a { color: inherit; text-decoration: none; flex: 1; }
|
|
18
|
-
li a:hover { text-decoration: underline; }
|
|
19
|
-
.meta { text-align: right; min-width: 5rem; opacity: 0.6; }
|
|
20
|
-
</style>
|
|
21
|
-
</head>
|
|
22
|
-
<body>
|
|
23
|
-
<h1>Index of ${o||"/"}</h1>
|
|
24
|
-
<ul>
|
|
25
|
-
${s}${i}
|
|
26
|
-
</ul>
|
|
27
|
-
</body>
|
|
28
|
-
</html>
|
|
29
|
-
`}function Ue(e){if(e==="/"||e==="")return null;let t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");if(n<=0)return"/";return t.slice(0,n+1)}function Y(e){return e.split("/").map(encodeURIComponent).join("/")}function je(e,t){if(e==="/")return`/${t}`;return`${e.replace(/\/+$/,"")}/${t}`}function qe(e){let t=e.indexOf("//"),n=e.indexOf("/",t===-1?0:t+2);if(n===-1)return"/";let r=e.length,a=e.indexOf("?",n);if(a!==-1&&a<r)r=a;let o=e.indexOf("#",n);if(o!==-1&&o<r)r=o;let i=e.slice(n,r);return i===""?"/":i}function ue(e,t){let n=oe(e.root),r=Fe(n),a=ze(n,r,e.watch),o=Je(),i={opts:e,hub:t,resolveCached:a.resolveCached,resolveDirCached:a.resolveDirCached,getCompressed:o.getCompressed,notFound:null},s=async function(u){let d=qe(u.url),p=u.method.toUpperCase(),m;if(d.includes("%"))try{m=decodeURIComponent(d)}catch{let l=new Response("Bad Request",{status:400});return F(p,d,e,l)}else m=d;try{return await Ge(u,p,m,d,i)}catch(l){console.error(l);let b=new Response("Internal Server Error",{status:500});return F(p,d,e,b)}};return s.invalidateResolutionCache=()=>{a.invalidate(),i.notFound=null},s.invalidateCompressedCache=o.invalidate,s.resolutionCacheSize=a.size,s.compressedCacheBytes=o.bytes,s}function F(e,t,n,r){return k(e,r.status,t,n.quiet),de(e,M(r,n))}function J(e,t){return new Response(null,{status:301,headers:{Location:`${e}/${new URL(t).search}`}})}function X(e,t,n=200){return new Response(t.watch?P(e):e,{status:n,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}})}async function Ge(e,t,n,r,a){let{opts:o,hub:i,resolveCached:s,resolveDirCached:c,getCompressed:u}=a,d=(l)=>F(t,n,o,l);if(t!=="GET"&&t!=="HEAD"){let l=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return d(l)}if(o.watch&&n===D){let l=new Response(fe,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return d(l)}if(o.watch&&n===I&&i){let l=i.subscribe();return k(t,200,n,o.quiet),M(l,o)}if(n===D||n===I)return de(t,M(new Response("Not Found",{status:404}),o));let p=s(n);if(p){if(p.kind==="dir-index"&&!n.endsWith("/"))return d(J(r,e.url));return d(await Z(u,e,p,o))}let m=Oe(e);if(o.spa&&m&&Ie(n)){let l=s("/");if(l)return d(await Z(u,e,l,o,!0))}if(o.dir){let l=c(n);if(l){if(!n.endsWith("/"))return d(J(r,e.url));let b=We(n,_e(l));return d(X(b,o))}}if(m){let l=s("/404.html");if(l){let b=a.notFound,y=b&&b.size===l.size&&b.mtimeMs===l.mtimeMs?b.html:await(async()=>{let h=await l.file.text();return a.notFound={size:l.size,mtimeMs:l.mtimeMs,html:h},h})();return d(X(y,o,404))}}return d(new Response("Not Found",{status:404}))}var Ve=67108864;async function Ke(e){let t=new CompressionStream("gzip"),n=t.writable.getWriter();return n.write(e),n.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}async function Ye(e,t){if(e==="zstd")return new Uint8Array(await Bun.zstdCompress(t));return Ke(t)}function Je(){let e=new Map,t=0,n=new Map;function r(i,s){let c=e.get(i);if(c)e.delete(i),t-=c.data.size;e.set(i,s),t+=s.data.size;while(t>Ve&&e.size>1){let u=e.keys().next().value;if(u===void 0)break;let d=e.get(u);if(e.delete(u),d)t-=d.data.size}}let a=async(i,s,c)=>{let u=`${i.key}:${s}`,d=e.get(u);if(d&&d.size===i.size&&d.mtimeMs===i.mtimeMs)return r(u,d),d.data;let p=n.get(u);if(p&&p.size===i.size&&p.mtimeMs===i.mtimeMs)return p.promise;let m=(async()=>{try{let b=await c(),y=new Blob([await Ye(s,b)]);return r(u,{size:i.size,mtimeMs:i.mtimeMs,data:y}),y}catch{return null}})(),l={size:i.size,mtimeMs:i.mtimeMs,promise:m};return n.set(u,l),m.finally(()=>{if(n.get(u)===l)n.delete(u)}),m};function o(){e.clear(),t=0,n.clear()}return{getCompressed:a,invalidate:o,bytes:()=>t}}async function Q(e,t,n,r,a){let o=De(t);if(!o)return null;let i=await e(r,o,a);if(!i)return null;return n["Content-Encoding"]=o,n["Content-Length"]=String(i.size),delete n["Accept-Ranges"],n.Vary="Accept-Encoding",new Response(i,{status:200,headers:n})}async function Z(e,t,n,r,a=!1){let{path:o,file:i,size:s,mtimeMs:c}=n,u=Re(i,o),d=a||$e(u),p=Ee(s,c,r.watch&&d?"-live":""),m=r.compress&&Ce(u);if(Ae(t,p,c)){let h=ne(p,r,d,c);if(m)h.Vary="Accept-Encoding";return new Response(null,{status:304,headers:h})}let l=ne(p,r,d,c);if(l["Content-Type"]=u,l["Accept-Ranges"]="bytes",m)l.Vary="Accept-Encoding";let b=t.headers.get("Range"),y=b&&Me(t,p,c)?b:null;if(y&&t.method==="GET"){let h=Qe(y,s);if(h==="invalid")return l["Content-Range"]=`bytes */${s}`,new Response(null,{status:416,headers:l});if(h){let{start:w,end:g}=h,x=g-w+1;return l["Content-Range"]=`bytes ${w}-${g}/${s}`,l["Content-Length"]=String(x),new Response(i.slice(w,g+1),{status:206,headers:l})}}if(t.method==="HEAD")return l["Content-Length"]=String(s),new Response(null,{status:200,headers:l});if(r.watch&&d&&t.method==="GET"){if(m){let w=await Q(e,t,l,{key:`${o}\x00live`,size:s,mtimeMs:c},async()=>we.encode(P(await i.text())));if(w)return w}let h=P(await i.text());return l["Content-Length"]=String(Buffer.byteLength(h)),new Response(h,{status:200,headers:l})}if(m&&t.method==="GET"&&s<2000000){let h=await Q(e,t,l,{key:o,size:s,mtimeMs:c},()=>i.bytes());if(h)return h}return l["Content-Length"]=String(s),new Response(i,{status:200,headers:l})}var ee=Number.NaN,te="";function Xe(e){if(e!==ee)ee=e,te=new Date(e).toUTCString();return te}function ne(e,t,n,r){return{ETag:e,"Last-Modified":Xe(r),"Cache-Control":t.watch||!t.cache||n?"no-cache":"public, max-age=31536000, immutable"}}function Qe(e,t){let n=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!n)return null;let r=n[1],a=n[2],o,i;if(r===""&&a==="")return"invalid";if(r===""){let s=Number(a);if(!Number.isFinite(s)||s<=0)return"invalid";o=Math.max(0,t-s),i=t-1}else o=Number(r),i=a===""?t-1:Number(a);if(!Number.isFinite(o)||!Number.isFinite(i)||o<0||i<o||o>=t)return"invalid";return i=Math.min(i,t-1),{start:o,end:i}}function M(e,t){if(!t.cors)return e;return e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Headers","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e}function de(e,t){if(e!=="HEAD")return t;return new Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})}var L={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class v extends Error{constructor(e,t){super(e,t);this.name="RootError"}}class T extends Error{constructor(e,t,n){super(`could not bind to ${e}:${t}`,n);this.name="BindError"}}var st=10;function pe(e){if(e&&typeof e==="object"&&"code"in e&&e.code==="EADDRINUSE")return!0;let t=e instanceof Error?e.message:String(e);return/EADDRINUSE|address already in use/i.test(t)}var D="/__live.js",I="/__events",fe=`(()=>{const e=new EventSource("${I}");e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,me=`<script src="${D}"></script>`;function ot(e,t){return`http://${e.includes(":")?`[${e}]`:e}:${t}`}function P(e){let t=e.toLowerCase().lastIndexOf("</body>");if(t===-1)return e+me;return e.slice(0,t)+me+e.slice(t)}function it(){let e=new Set,t=new TextEncoder,n=t.encode(`: ping
|
|
30
|
-
|
|
31
|
-
`),r=setInterval(()=>{for(let s of e)try{s.enqueue(n)}catch{e.delete(s)}},8000);r.unref();function a(){let s,c=new ReadableStream({start(u){s=u,e.add(u),u.enqueue(t.encode(`: connected
|
|
32
|
-
|
|
33
|
-
`))},cancel(){e.delete(s)}});return new Response(c,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function o(s="reload"){let c=t.encode(`data: ${s}
|
|
34
|
-
|
|
35
|
-
`);for(let u of e)try{u.enqueue(c)}catch{e.delete(u)}}function i(){clearInterval(r);for(let s of e)try{s.close()}catch{}e.clear()}return{subscribe:a,broadcast:o,close:i}}var f={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},ct=/[\x00-\x1f\x7f]/g,at=/[\x00-\x1f\x7f]/;function lt(e){return at.test(e)?e.replace(ct,""):e}var ut=`${f.green}\u2713${f.reset}`,dt=`${f.yellow}\u25CB${f.reset}`,ft=`${f.red}\u2717${f.reset}`,{dim:pt,reset:mt}=f,O=[];function ht(){if(O.length===1)queueMicrotask(he)}function he(){if(O.length===0)return;let e=O.join(`
|
|
36
|
-
`);O=[],process.stdout.write(`${e}
|
|
37
|
-
`)}function k(e,t,n,r){if(r)return;let a=t<300?ut:t<400?dt:ft;O.push(`${a} ${pt}${e}${mt} ${t} ${lt(n)}`),ht()}function B(e,t=!1){if(t)return;console.log(`${f.cyan}\u2502${f.reset} ${e}`)}function gt(e){return e.split(/[/\\]/).some((t)=>t.startsWith(".")||t==="node_modules")}function bt(e){if(e.length===0)return"reload";return e.every((t)=>t?.endsWith(".css"))?"css":"reload"}function yt(){let e=tt();for(let t of Object.values(e))for(let n of t??[])if(n.family==="IPv4"&&!n.internal)return n.address;return null}function xt(e,t,n,r){if(console.log(),console.log(` ${f.bold}deserved${f.reset} ${f.dim}serving${f.reset} ${t}`),console.log(` ${f.green}->${f.reset} ${f.cyan}${e}${f.reset}`),r)console.log(` ${f.green}->${f.reset} ${f.cyan}${r}${f.reset}`);if(n.length)console.log(` ${f.dim}${n.join(" ")}${f.reset}`);console.log()}function wt(e,t){if(e)return;console.log(`${f.yellow}*${f.reset} ${t}`)}function vt(e){if(process.platform==="darwin")return["open",e];if(process.platform==="win32")return["cmd","/c","start","",e];return["xdg-open",e]}async function Rt(e){try{await Bun.spawn(vt(e),{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${e}`)}}function Ct(e){try{if(!Ze(e).isDirectory())throw new v(`not a directory: ${e}`)}catch(t){if(t instanceof v)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new v(`directory not found: ${e}`);throw new v(`not a directory: ${e}`)}}async function _(e){let t=rt(e.root);Ct(t);let n=e.watch?it():void 0,r=ue({...e,root:t},n),a=e.host==="localhost"?"127.0.0.1":e.host,o=async(g)=>{if(e.cors&&g.method==="OPTIONS")return M(new Response(null,{status:204}),e);return r(g)},i=(g)=>Bun.serve({port:g,hostname:a,fetch:o}),s=!e.portExplicit&&e.port!==0,c,u=e.port;try{c=i(u)}catch(g){if(!s||!pe(g))throw new T(e.host,u,{cause:g});let x,R=e.port,C=g;for(let E=1;E<=st;E++){R=e.port+E;try{x=i(R),u=R;break}catch(N){if(!pe(N))throw new T(e.host,R,{cause:N});C=N}}if(!x)throw new T(e.host,R,{cause:C});c=x,B(`port ${e.port} in use, using ${u}`,e.quiet)}let d=e.host==="0.0.0.0"||e.host==="::",p=d?"localhost":e.host,m=ot(p,c.port??e.port),l=d?yt():null,b=l?`http://${l}:${c.port}`:void 0,y=[];if(e.spa)y.push("--spa");if(e.watch)y.push("--watch");if(e.cors)y.push("--cors");if(!e.dir)y.push("--no-dir");if(!e.compress)y.push("--no-compress");if(e.cache)y.push("--cache");xt(m,nt(process.cwd(),t)||".",y,b);let h;if(e.watch&&n){let g=null,x=new Set;h=et(t,{recursive:!0},(R,C)=>{if(C&>(C))return;if(r.invalidateResolutionCache(),r.invalidateCompressedCache(),x.add(C),g)clearTimeout(g);g=setTimeout(()=>{let E=bt([...x]);x.clear(),wt(e.quiet,E),n.broadcast(E)},80)}),B("watching for changes",e.quiet)}let w=async()=>{h?.close(),n?.close(),await c.stop(),he(),B("server stopped",e.quiet)};if(e.open)await Rt(m);return{port:c.port??e.port,hostname:p,url:m,stop:w}}async function Ft(e={}){let t=e.portExplicit??e.port!==void 0;return _({...L,...e,portExplicit:t})}function Et(){console.log(`
|
|
3
|
+
import{t,e,n,s}from"./chunk-6mm4k23z.js";import{resolve as w}from"path";var v="0.6.0";function y(){console.log(`
|
|
38
4
|
deserved - tiny Bun static file server
|
|
39
5
|
|
|
40
6
|
Usage
|
|
@@ -64,4 +30,4 @@ ${s}${i}
|
|
|
64
30
|
deserved dist --port 8080
|
|
65
31
|
deserved docs --watch --open
|
|
66
32
|
PORT=8080 deserved dist
|
|
67
|
-
`)}function
|
|
33
|
+
`)}var E=new Map([["-s",["spa",!0]],["--spa",["spa",!0]],["-w",["watch",!0]],["--watch",["watch",!0]],["-o",["open",!0]],["--open",["open",!0]],["--cors",["cors",!0]],["--dir",["dir",!0]],["--no-dir",["dir",!1]],["--cache",["cache",!0]],["--no-cache",["cache",!1]],["--compress",["compress",!0]],["--no-compress",["compress",!1]],["-q",["quiet",!0]],["--quiet",["quiet",!0]]]),S=new Map([["-p","port"],["--port","port"],["-H","host"],["--host","host"]]);function R(c,p=Bun.env){let i=c.slice(2),o={...t},h,f=!1;for(let d=0;d<i.length;d++){let r=i[d];if(r===void 0)break;if(r==="-h"||r==="--help")y(),process.exit(0);if(r==="-v"||r==="--version")console.log(v),process.exit(0);let m=E.get(r);if(m){o[m[0]]=m[1];continue}let a=r.startsWith("--")?r.indexOf("="):-1,b=a===-1?r:r.slice(0,a),g=S.get(b);if(g){let l=a===-1?i[++d]:r.slice(a+1);if(!l||a===-1&&l.startsWith("-"))u(`Missing value for ${b}`);if(g==="port")o.port=x(l,a===-1?l:r),f=!0;else o.host=l;continue}if(r.startsWith("-"))u(`Unknown option: ${r}`);if(h!==void 0)u(`Unexpected argument: ${r}`);h=r}if(!f&&p.PORT!==void 0)o.port=x(p.PORT,p.PORT);return o.root=w(h??o.root),{...o,portExplicit:f}}function x(c,p){let i=Number(c);if(c.trim()===""||!Number.isInteger(i)||i<0||i>65535)u(`Invalid port: ${p}`);return i}function u(c){console.error(`Error: ${c}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let c=R(process.argv),p;try{p=await s(c,{portExplicit:c.portExplicit})}catch(o){if(o instanceof e)console.error(`Error: ${o.message}`),console.error("Run deserved --help."),process.exit(1);if(o instanceof n)console.error(`Error: ${o.message}`),console.error(o.cause instanceof Error?o.cause.message:String(o.cause)),process.exit(1);throw o}let i=async()=>{await p.stop(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}export{R as parseArgs};
|
package/handlers.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type Hub } from "./live";
|
|
2
|
+
import { type Options } from "./options";
|
|
2
3
|
export type ResolvedFile = {
|
|
3
4
|
path: string;
|
|
4
5
|
file: Bun.BunFile;
|
|
@@ -13,12 +14,10 @@ export type Handler = {
|
|
|
13
14
|
resolutionCacheSize(): number;
|
|
14
15
|
compressedCacheBytes(): number;
|
|
15
16
|
};
|
|
16
|
-
type Hub = ReturnType<typeof createSseHub>;
|
|
17
17
|
export declare function contentType(file: Bun.BunFile, path: string): string;
|
|
18
18
|
export declare function isCompressible(type: string): boolean;
|
|
19
19
|
export declare function isHtml(type: string): boolean;
|
|
20
20
|
export declare function makeEtag(size: number, mtimeMs: number, tag?: string): string;
|
|
21
|
-
export declare function notModified(req: Request, etag: string): boolean;
|
|
22
21
|
export declare function notModifiedSince(req: Request, mtimeMs: number): boolean;
|
|
23
22
|
export declare function isNotModified(req: Request, etag: string, mtimeMs: number): boolean;
|
|
24
23
|
export declare function ifRangeSatisfied(req: Request, etag: string, mtimeMs: number): boolean;
|
|
@@ -26,12 +25,12 @@ export declare function acceptsHtml(req: Request): boolean;
|
|
|
26
25
|
export type CompressionEncoding = "zstd" | "gzip";
|
|
27
26
|
export declare function pickEncoding(req: Request): CompressionEncoding | null;
|
|
28
27
|
export declare function shouldSpaFallback(pathname: string): boolean;
|
|
28
|
+
export declare function isHiddenPath(pathname: string): boolean;
|
|
29
29
|
export declare function resolveFileWithRoot(rootAbs: string, realRoot: string | null, pathname: string): ResolvedFile | null;
|
|
30
30
|
export declare const RESOLUTION_CACHE_LIMIT = 4096;
|
|
31
31
|
export declare const RESOLUTION_TTL_MS = 500;
|
|
32
32
|
export declare function buildCandidates(relative: string): string[];
|
|
33
33
|
export declare function safeJoin(root: string, relative: string): string | null;
|
|
34
|
-
export declare function realContainedPath(rootAbs: string, full: string): string | null;
|
|
35
34
|
export declare function resolveDirWithRoot(rootAbs: string, realRoot: string | null, pathname: string): string | null;
|
|
36
35
|
type DirEntry = {
|
|
37
36
|
name: string;
|
|
@@ -41,7 +40,7 @@ type DirEntry = {
|
|
|
41
40
|
};
|
|
42
41
|
export declare function listDir(dir: string): DirEntry[];
|
|
43
42
|
export declare function directoryListing(pathname: string, entries: DirEntry[]): string;
|
|
44
|
-
export declare function createHandler(
|
|
43
|
+
export declare function createHandler(options?: Partial<Options>, hub?: Hub): Handler;
|
|
45
44
|
export declare const COMPRESSED_CACHE_BYTE_BUDGET: number;
|
|
46
45
|
export declare function compress(encoding: CompressionEncoding, raw: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>>;
|
|
47
46
|
export declare function baseHeaders(etag: string, opts: Options, isHtmlFile: boolean, mtimeMs: number): Record<string, string>;
|
package/index.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
export { createHandler } from "./handlers";
|
|
2
|
-
export {
|
|
2
|
+
export { DEFAULT_OPTIONS, type Options } from "./options";
|
|
3
|
+
export { BindError, RootError, type ServerHandle, serve } from "./server";
|
package/index.js
CHANGED
|
@@ -1,36 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
|
|
4
|
-
`),r=setInterval(()=>{for(let s of e)try{s.enqueue(n)}catch{e.delete(s)}},8000);r.unref();function c(){let s,a=new ReadableStream({start(u){s=u,e.add(u),u.enqueue(t.encode(`: connected
|
|
5
|
-
|
|
6
|
-
`))},cancel(){e.delete(s)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function o(s="reload"){let a=t.encode(`data: ${s}
|
|
7
|
-
|
|
8
|
-
`);for(let u of e)try{u.enqueue(a)}catch{e.delete(u)}}function i(){clearInterval(r);for(let s of e)try{s.close()}catch{}e.clear()}return{subscribe:c,broadcast:o,close:i}}var f={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},Ce=/[\x00-\x1f\x7f]/g,Re=/[\x00-\x1f\x7f]/;function ve(e){return Re.test(e)?e.replace(Ce,""):e}var $e=`${f.green}\u2713${f.reset}`,Ee=`${f.yellow}\u25CB${f.reset}`,Se=`${f.red}\u2717${f.reset}`,{dim:Te,reset:Ae}=f,A=[];function Me(){if(A.length===1)queueMicrotask(j)}function j(){if(A.length===0)return;let e=A.join(`
|
|
9
|
-
`);A=[],process.stdout.write(`${e}
|
|
10
|
-
`)}function B(e,t,n,r){if(r)return;let c=t<300?$e:t<400?Ee:Se;A.push(`${c} ${Te}${e}${Ae} ${t} ${ve(n)}`),Me()}function P(e,t=!1){if(t)return;console.log(`${f.cyan}\u2502${f.reset} ${e}`)}function Oe(e){return e.split(/[/\\]/).some((t)=>t.startsWith(".")||t==="node_modules")}function De(e){if(e.length===0)return"reload";return e.every((t)=>t?.endsWith(".css"))?"css":"reload"}function ze(){let e=ge();for(let t of Object.values(e))for(let n of t??[])if(n.family==="IPv4"&&!n.internal)return n.address;return null}function He(e,t,n,r){if(console.log(),console.log(` ${f.bold}deserved${f.reset} ${f.dim}serving${f.reset} ${t}`),console.log(` ${f.green}->${f.reset} ${f.cyan}${e}${f.reset}`),r)console.log(` ${f.green}->${f.reset} ${f.cyan}${r}${f.reset}`);if(n.length)console.log(` ${f.dim}${n.join(" ")}${f.reset}`);console.log()}function Ie(e,t){if(e)return;console.log(`${f.yellow}*${f.reset} ${t}`)}function Fe(e){if(process.platform==="darwin")return["open",e];if(process.platform==="win32")return["cmd","/c","start","",e];return["xdg-open",e]}async function Pe(e){try{await Bun.spawn(Fe(e),{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${e}`)}}function Ne(e){try{if(!pe(e).isDirectory())throw new E(`not a directory: ${e}`)}catch(t){if(t instanceof E)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new E(`directory not found: ${e}`);throw new E(`not a directory: ${e}`)}}async function q(e){let t=ye(e.root);Ne(t);let n=e.watch?we():void 0,r=N({...e,root:t},n),c=e.host==="localhost"?"127.0.0.1":e.host,o=async(h)=>{if(e.cors&&h.method==="OPTIONS")return M(new Response(null,{status:204}),e);return r(h)},i=(h)=>Bun.serve({port:h,hostname:c,fetch:o}),s=!e.portExplicit&&e.port!==0,a,u=e.port;try{a=i(u)}catch(h){if(!s||!_(h))throw new T(e.host,u,{cause:h});let b,C=e.port,R=h;for(let v=1;v<=xe;v++){C=e.port+v;try{b=i(C),u=C;break}catch(F){if(!_(F))throw new T(e.host,C,{cause:F});R=F}}if(!b)throw new T(e.host,C,{cause:R});a=b,P(`port ${e.port} in use, using ${u}`,e.quiet)}let d=e.host==="0.0.0.0"||e.host==="::",p=d?"localhost":e.host,m=be(p,a.port??e.port),l=d?ze():null,y=l?`http://${l}:${a.port}`:void 0,x=[];if(e.spa)x.push("--spa");if(e.watch)x.push("--watch");if(e.cors)x.push("--cors");if(!e.dir)x.push("--no-dir");if(!e.compress)x.push("--no-compress");if(e.cache)x.push("--cache");He(m,he(process.cwd(),t)||".",x,y);let g;if(e.watch&&n){let h=null,b=new Set;g=me(t,{recursive:!0},(C,R)=>{if(R&&Oe(R))return;if(r.invalidateResolutionCache(),r.invalidateCompressedCache(),b.add(R),h)clearTimeout(h);h=setTimeout(()=>{let v=De([...b]);b.clear(),Ie(e.quiet,v),n.broadcast(v)},80)}),P("watching for changes",e.quiet)}let w=async()=>{g?.close(),n?.close(),await a.stop(),j(),P("server stopped",e.quiet)};if(e.open)await Pe(m);return{port:a.port??e.port,hostname:p,url:m,stop:w}}async function Be(e={}){let t=e.portExplicit??e.port!==void 0;return q({...U,...e,portExplicit:t})}var Ue=new TextEncoder,G="application/octet-stream",We={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function je(e,t){let n=e.type;if(n&&n!==G&&n!=="")return n;let r=_e(t).toLowerCase();return We[r]??G}function qe(e){let t=e.indexOf(";"),n=(t===-1?e:e.slice(0,t)).trim().toLowerCase();return n.startsWith("text/")||n==="application/javascript"||n==="text/javascript"||n==="application/json"||n==="application/xml"||n==="image/svg+xml"||n.endsWith("+json")||n.endsWith("+xml")}function Ge(e){return e.startsWith("text/html")}function Ve(e,t,n=""){return`"${e}-${Math.trunc(t)}${n}"`}function V(e){return e.startsWith("W/")?e.slice(2):e}function Ke(e,t){if(e.indexOf(",")===-1)return V(e.trim())===t;return e.split(",").some((n)=>V(n.trim())===t)}function Ye(e,t){let n=e.headers.get("If-Modified-Since");if(!n)return!1;let r=Date.parse(n);if(Number.isNaN(r))return!1;return Math.trunc(t/1000)*1000<=r}function Je(e,t,n){let r=e.headers.get("If-None-Match");return r?Ke(r,t):Ye(e,n)}function Xe(e,t,n){let r=e.headers.get("If-Range");if(!r)return!0;if(r.startsWith('"')||r.startsWith("W/"))return r===t;let c=Date.parse(r);if(Number.isNaN(c))return!1;return c===Math.trunc(n/1000)*1000}function Qe(e){let t=e.headers.get("Accept");if(!t||t==="*/*")return!0;return t.includes("text/html")||t.includes("application/xhtml")}function Ze(e){let t=e.headers.get("Accept-Encoding")??"";if(t.includes("zstd"))return"zstd";if(t.includes("gzip"))return"gzip";return null}function et(e){if(e.startsWith("/__"))return!1;let t=e.lastIndexOf("/");if(t===e.length-1)return!0;return e.indexOf(".",t+1)===-1}function tt(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,""),c=st(r);for(let o of c){let i=ue(e,o);if(!i)continue;let s=de(t,i);if(!s)continue;let a=le(s,rt(o));if(a)return a}return null}function le(e,t){try{let n=I(e);if(n.isFile())return{path:e,file:Bun.file(e),size:n.size,mtimeMs:n.mtimeMs,kind:t}}catch{}return null}var K=4096;function Y(e,t){if(e.size<t)return;let n=e.keys().next().value;if(n!==void 0)e.delete(n)}function O(e,t,n){e.delete(t),e.set(t,n)}var J=500;function nt(e,t,n){let r=new Map,c=new Map;function o(s){let a=r.get(s);if(a&&(n||Date.now()-a.at<J)){if(a.value===null)return O(r,s,a),null;if(n)return O(r,s,a),a.value;let d=le(a.value.path,a.value.kind);if(d)return O(r,s,a),d}let u=tt(e,t,s);return Y(r,K),r.set(s,{value:u,at:Date.now()}),u}function i(s){let a=c.get(s);if(a&&(n||Date.now()-a.at<J)){if(a.value===null)return O(c,s,a),null;try{if(I(a.value).isDirectory())return O(c,s,a),a.value}catch{}}let u=it(e,t,s);return Y(c,K),c.set(s,{value:u,at:Date.now()}),u}return{resolveCached:o,resolveDirCached:i,invalidate:()=>{r.clear(),c.clear()},size:()=>r.size}}function rt(e){if(e.endsWith("/index.html"))return"dir-index";if(e.endsWith(".html"))return"html-ext";return"file"}function st(e){if(!e||e===".")return["index.html"];let t=e.endsWith("/"),n=t?e.slice(0,-1):e;if(!n)return["index.html"];if(t)return[`${n}/index.html`];return[n,`${n}.html`,`${n}/index.html`]}function ue(e,t){let n=ke(e)?e:ce(e),r=ie(n,t);if(r!==n&&!r.startsWith(n+ae))return null;return r}function de(e,t){try{let n=oe(t);if(n!==e&&!n.startsWith(e+ae))return null;return n}catch{return null}}function ot(e){try{return oe(e)}catch{return null}}function it(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,"").replace(/\/+$/,""),c=ue(e,r||".");if(!c)return null;let o=de(t,c);if(!o)return null;try{return I(o).isDirectory()?o:null}catch{return null}}function ct(e){if(e===null)return"-";if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} kB`;return`${(e/1048576).toFixed(1)} MB`}function at(e){if(e===null)return"-";let t=new Date(e),n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),c=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${c} ${o}:${i}`}function lt(e){let t=Le(e,{withFileTypes:!0}),n=[];for(let r of t){if(r.name.startsWith("."))continue;let c=r.isDirectory(),o=null,i=null;if(!c)try{let s=I(ie(e,r.name));o=s.size,i=s.mtimeMs}catch{}n.push({name:r.name,dir:c,size:o,mtimeMs:i})}return n.sort((r,c)=>{if(r.dir!==c.dir)return r.dir?-1:1;return r.name.localeCompare(c.name)})}function ut(e,t){let n=e.endsWith("/")?e:`${e}/`,r=X(n),c=dt(e),o=S(e),i=t.map((a)=>{let u=ft(r,encodeURIComponent(a.name))+(a.dir?"/":""),d=a.dir?`${a.name}/`:a.name,p=ct(a.size),m=at(a.mtimeMs);return` <li><a href="${S(u)}">${S(d)}</a> <span class="meta">${S(p)}</span> <span class="meta">${S(m)}</span></li>`}).join(`
|
|
11
|
-
`),s=c!==null?` <li><a href="${S(X(c))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
|
|
12
|
-
`:"";return`<!DOCTYPE html>
|
|
13
|
-
<html lang="en">
|
|
14
|
-
<head>
|
|
15
|
-
<meta charset="utf-8">
|
|
16
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
17
|
-
<title>Index of ${o}</title>
|
|
18
|
-
<style>
|
|
19
|
-
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
20
|
-
body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
21
|
-
h1 { font-size: 1.1rem; font-weight: 600; }
|
|
22
|
-
ul { list-style: none; padding: 0; }
|
|
23
|
-
li { padding: 0.2rem 0; display: flex; gap: 2rem; }
|
|
24
|
-
li a { color: inherit; text-decoration: none; flex: 1; }
|
|
25
|
-
li a:hover { text-decoration: underline; }
|
|
26
|
-
.meta { text-align: right; min-width: 5rem; opacity: 0.6; }
|
|
27
|
-
</style>
|
|
28
|
-
</head>
|
|
29
|
-
<body>
|
|
30
|
-
<h1>Index of ${o||"/"}</h1>
|
|
31
|
-
<ul>
|
|
32
|
-
${s}${i}
|
|
33
|
-
</ul>
|
|
34
|
-
</body>
|
|
35
|
-
</html>
|
|
36
|
-
`}function dt(e){if(e==="/"||e==="")return null;let t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");if(n<=0)return"/";return t.slice(0,n+1)}function X(e){return e.split("/").map(encodeURIComponent).join("/")}function ft(e,t){if(e==="/")return`/${t}`;return`${e.replace(/\/+$/,"")}/${t}`}function pt(e){let t=e.indexOf("//"),n=e.indexOf("/",t===-1?0:t+2);if(n===-1)return"/";let r=e.length,c=e.indexOf("?",n);if(c!==-1&&c<r)r=c;let o=e.indexOf("#",n);if(o!==-1&&o<r)r=o;let i=e.slice(n,r);return i===""?"/":i}function N(e,t){let n=ce(e.root),r=ot(n),c=nt(n,r,e.watch),o=xt(),i={opts:e,hub:t,resolveCached:c.resolveCached,resolveDirCached:c.resolveDirCached,getCompressed:o.getCompressed,notFound:null},s=async function(u){let d=pt(u.url),p=u.method.toUpperCase(),m;if(d.includes("%"))try{m=decodeURIComponent(d)}catch{let l=new Response("Bad Request",{status:400});return L(p,d,e,l)}else m=d;try{return await mt(u,p,m,d,i)}catch(l){console.error(l);let y=new Response("Internal Server Error",{status:500});return L(p,d,e,y)}};return s.invalidateResolutionCache=()=>{c.invalidate(),i.notFound=null},s.invalidateCompressedCache=o.invalidate,s.resolutionCacheSize=c.size,s.compressedCacheBytes=o.bytes,s}function L(e,t,n,r){return B(e,r.status,t,n.quiet),fe(e,M(r,n))}function Q(e,t){return new Response(null,{status:301,headers:{Location:`${e}/${new URL(t).search}`}})}function Z(e,t,n=200){return new Response(t.watch?H(e):e,{status:n,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}})}async function mt(e,t,n,r,c){let{opts:o,hub:i,resolveCached:s,resolveDirCached:a,getCompressed:u}=c,d=(l)=>L(t,n,o,l);if(t!=="GET"&&t!=="HEAD"){let l=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return d(l)}if(o.watch&&n===D){let l=new Response(W,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return d(l)}if(o.watch&&n===z&&i){let l=i.subscribe();return B(t,200,n,o.quiet),M(l,o)}if(n===D||n===z)return fe(t,M(new Response("Not Found",{status:404}),o));let p=s(n);if(p){if(p.kind==="dir-index"&&!n.endsWith("/"))return d(Q(r,e.url));return d(await te(u,e,p,o))}let m=Qe(e);if(o.spa&&m&&et(n)){let l=s("/");if(l)return d(await te(u,e,l,o,!0))}if(o.dir){let l=a(n);if(l){if(!n.endsWith("/"))return d(Q(r,e.url));let y=ut(n,lt(l));return d(Z(y,o))}}if(m){let l=s("/404.html");if(l){let y=c.notFound,x=y&&y.size===l.size&&y.mtimeMs===l.mtimeMs?y.html:await(async()=>{let g=await l.file.text();return c.notFound={size:l.size,mtimeMs:l.mtimeMs,html:g},g})();return d(Z(x,o,404))}}return d(new Response("Not Found",{status:404}))}var gt=67108864;async function ht(e){let t=new CompressionStream("gzip"),n=t.writable.getWriter();return n.write(e),n.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}async function yt(e,t){if(e==="zstd")return new Uint8Array(await Bun.zstdCompress(t));return ht(t)}function xt(){let e=new Map,t=0,n=new Map;function r(i,s){let a=e.get(i);if(a)e.delete(i),t-=a.data.size;e.set(i,s),t+=s.data.size;while(t>gt&&e.size>1){let u=e.keys().next().value;if(u===void 0)break;let d=e.get(u);if(e.delete(u),d)t-=d.data.size}}let c=async(i,s,a)=>{let u=`${i.key}:${s}`,d=e.get(u);if(d&&d.size===i.size&&d.mtimeMs===i.mtimeMs)return r(u,d),d.data;let p=n.get(u);if(p&&p.size===i.size&&p.mtimeMs===i.mtimeMs)return p.promise;let m=(async()=>{try{let y=await a(),x=new Blob([await yt(s,y)]);return r(u,{size:i.size,mtimeMs:i.mtimeMs,data:x}),x}catch{return null}})(),l={size:i.size,mtimeMs:i.mtimeMs,promise:m};return n.set(u,l),m.finally(()=>{if(n.get(u)===l)n.delete(u)}),m};function o(){e.clear(),t=0,n.clear()}return{getCompressed:c,invalidate:o,bytes:()=>t}}async function ee(e,t,n,r,c){let o=Ze(t);if(!o)return null;let i=await e(r,o,c);if(!i)return null;return n["Content-Encoding"]=o,n["Content-Length"]=String(i.size),delete n["Accept-Ranges"],n.Vary="Accept-Encoding",new Response(i,{status:200,headers:n})}async function te(e,t,n,r,c=!1){let{path:o,file:i,size:s,mtimeMs:a}=n,u=je(i,o),d=c||Ge(u),p=Ve(s,a,r.watch&&d?"-live":""),m=r.compress&&qe(u);if(Je(t,p,a)){let g=se(p,r,d,a);if(m)g.Vary="Accept-Encoding";return new Response(null,{status:304,headers:g})}let l=se(p,r,d,a);if(l["Content-Type"]=u,l["Accept-Ranges"]="bytes",m)l.Vary="Accept-Encoding";let y=t.headers.get("Range"),x=y&&Xe(t,p,a)?y:null;if(x&&t.method==="GET"){let g=wt(x,s);if(g==="invalid")return l["Content-Range"]=`bytes */${s}`,new Response(null,{status:416,headers:l});if(g){let{start:w,end:h}=g,b=h-w+1;return l["Content-Range"]=`bytes ${w}-${h}/${s}`,l["Content-Length"]=String(b),new Response(i.slice(w,h+1),{status:206,headers:l})}}if(t.method==="HEAD")return l["Content-Length"]=String(s),new Response(null,{status:200,headers:l});if(r.watch&&d&&t.method==="GET"){if(m){let w=await ee(e,t,l,{key:`${o}\x00live`,size:s,mtimeMs:a},async()=>Ue.encode(H(await i.text())));if(w)return w}let g=H(await i.text());return l["Content-Length"]=String(Buffer.byteLength(g)),new Response(g,{status:200,headers:l})}if(m&&t.method==="GET"&&s<2000000){let g=await ee(e,t,l,{key:o,size:s,mtimeMs:a},()=>i.bytes());if(g)return g}return l["Content-Length"]=String(s),new Response(i,{status:200,headers:l})}var ne=Number.NaN,re="";function bt(e){if(e!==ne)ne=e,re=new Date(e).toUTCString();return re}function se(e,t,n,r){return{ETag:e,"Last-Modified":bt(r),"Cache-Control":t.watch||!t.cache||n?"no-cache":"public, max-age=31536000, immutable"}}function wt(e,t){let n=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!n)return null;let r=n[1],c=n[2],o,i;if(r===""&&c==="")return"invalid";if(r===""){let s=Number(c);if(!Number.isFinite(s)||s<=0)return"invalid";o=Math.max(0,t-s),i=t-1}else o=Number(r),i=c===""?t-1:Number(c);if(!Number.isFinite(o)||!Number.isFinite(i)||o<0||i<o||o>=t)return"invalid";return i=Math.min(i,t-1),{start:o,end:i}}function M(e,t){if(!t.cors)return e;return e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Headers","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e}function fe(e,t){if(e!=="HEAD")return t;return new Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})}export{T as BindError,U as DEFAULT_OPTIONS,E as RootError,N as createHandler,Be as serve,q as startServer};
|
|
2
|
+
import{t,r,e,n,o}from"./chunk-6mm4k23z.js";export{n as BindError,t as DEFAULT_OPTIONS,e as RootError,r as createHandler,o as serve};
|
package/live.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const LIVE_PATH = "/__live.js";
|
|
2
|
+
export declare const EVENTS_PATH = "/__events";
|
|
3
|
+
export declare const LIVE_SCRIPT = "(()=>{let down=false;const e=new EventSource(\"/__events\");e.onopen=()=>{if(down)location.reload()};e.onmessage=(m)=>{if(m.data===\"css\"){for(const l of document.querySelectorAll('link[rel=\"stylesheet\"]')){const h=l.href.split(\"?\")[0];l.href=h+\"?t=\"+Date.now()}}else{location.reload()}};e.onerror=()=>{if(down&&e.readyState===2)location.reload();down=true}})()";
|
|
4
|
+
export declare function injectLiveReload(html: string): string;
|
|
5
|
+
export declare const SSE_HEADERS: {
|
|
6
|
+
"Content-Type": string;
|
|
7
|
+
"Cache-Control": string;
|
|
8
|
+
Connection: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function createSseHub(): {
|
|
11
|
+
subscribe: () => Response;
|
|
12
|
+
broadcast: (data?: string) => void;
|
|
13
|
+
close: () => void;
|
|
14
|
+
};
|
|
15
|
+
export type Hub = ReturnType<typeof createSseHub>;
|
|
16
|
+
export declare function isIgnoredWatchPath(filename: string): boolean;
|
|
17
|
+
export declare function classifyBatch(files: (string | null)[]): "css" | "reload";
|
package/log.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function shouldColor(isTTY: boolean | undefined, env: Record<string, string | undefined>): boolean;
|
|
2
|
+
export declare function flushLogs(): void;
|
|
3
|
+
export declare function logRequest(method: string, status: number, path: string, quiet: boolean): void;
|
|
4
|
+
export declare function logInfo(msg: string, quiet?: boolean): void;
|
|
5
|
+
export declare function logBanner(url: string, root: string, flags: string[], networkUrl?: string): void;
|
|
6
|
+
export declare function logReload(quiet: boolean, kind: "css" | "reload"): void;
|
package/options.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type Options = {
|
|
2
|
+
root: string;
|
|
3
|
+
port: number;
|
|
4
|
+
host: string;
|
|
5
|
+
spa: boolean;
|
|
6
|
+
watch: boolean;
|
|
7
|
+
open: boolean;
|
|
8
|
+
cors: boolean;
|
|
9
|
+
dir: boolean;
|
|
10
|
+
cache: boolean;
|
|
11
|
+
compress: boolean;
|
|
12
|
+
quiet: boolean;
|
|
13
|
+
};
|
|
14
|
+
export declare const DEFAULT_OPTIONS: {
|
|
15
|
+
root: string;
|
|
16
|
+
port: number;
|
|
17
|
+
host: string;
|
|
18
|
+
spa: false;
|
|
19
|
+
watch: false;
|
|
20
|
+
open: false;
|
|
21
|
+
cors: false;
|
|
22
|
+
dir: true;
|
|
23
|
+
cache: false;
|
|
24
|
+
compress: true;
|
|
25
|
+
quiet: false;
|
|
26
|
+
};
|
package/package.json
CHANGED
package/server.d.ts
CHANGED
|
@@ -1,31 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
root: string;
|
|
3
|
-
port: number;
|
|
4
|
-
portExplicit: boolean;
|
|
5
|
-
host: string;
|
|
6
|
-
spa: boolean;
|
|
7
|
-
watch: boolean;
|
|
8
|
-
open: boolean;
|
|
9
|
-
cors: boolean;
|
|
10
|
-
dir: boolean;
|
|
11
|
-
cache: boolean;
|
|
12
|
-
compress: boolean;
|
|
13
|
-
quiet: boolean;
|
|
14
|
-
};
|
|
15
|
-
export declare const DEFAULT_OPTIONS: {
|
|
16
|
-
root: string;
|
|
17
|
-
port: number;
|
|
18
|
-
portExplicit: false;
|
|
19
|
-
host: string;
|
|
20
|
-
spa: false;
|
|
21
|
-
watch: false;
|
|
22
|
-
open: false;
|
|
23
|
-
cors: false;
|
|
24
|
-
dir: true;
|
|
25
|
-
cache: false;
|
|
26
|
-
compress: true;
|
|
27
|
-
quiet: false;
|
|
28
|
-
};
|
|
1
|
+
import { type Options } from "./options";
|
|
29
2
|
export type ServerHandle = {
|
|
30
3
|
port: number;
|
|
31
4
|
hostname: string;
|
|
@@ -38,19 +11,10 @@ export declare class RootError extends Error {
|
|
|
38
11
|
export declare class BindError extends Error {
|
|
39
12
|
constructor(host: string, port: number, options?: ErrorOptions);
|
|
40
13
|
}
|
|
41
|
-
export declare const LIVE_PATH = "/__live.js";
|
|
42
|
-
export declare const EVENTS_PATH = "/__events";
|
|
43
|
-
export declare const LIVE_SCRIPT = "(()=>{const e=new EventSource(\"/__events\");e.onmessage=(m)=>{if(m.data===\"css\"){for(const l of document.querySelectorAll('link[rel=\"stylesheet\"]')){const h=l.href.split(\"?\")[0];l.href=h+\"?t=\"+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()";
|
|
44
14
|
export declare function formatUrl(host: string, port: number): string;
|
|
45
|
-
export
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
broadcast: (data?: string) => void;
|
|
49
|
-
close: () => void;
|
|
15
|
+
export type StartOptions = {
|
|
16
|
+
portExplicit?: boolean;
|
|
17
|
+
banner?: boolean;
|
|
50
18
|
};
|
|
51
|
-
export declare function
|
|
52
|
-
export declare function logRequest(method: string, status: number, path: string, quiet: boolean): void;
|
|
53
|
-
export declare function isIgnoredWatchPath(filename: string): boolean;
|
|
54
|
-
export declare function classifyBatch(files: (string | null)[]): "css" | "reload";
|
|
55
|
-
export declare function startServer(opts: Options): Promise<ServerHandle>;
|
|
19
|
+
export declare function startServer(opts: Options, { portExplicit, banner }?: StartOptions): Promise<ServerHandle>;
|
|
56
20
|
export declare function serve(options?: Partial<Options>): Promise<ServerHandle>;
|