deserved 0.3.0 → 0.4.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 +24 -1
- package/cli.js +19 -14
- package/index.js +34 -0
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ bunx deserved [path] [options]
|
|
|
24
24
|
|
|
25
25
|
| Flag | Description |
|
|
26
26
|
|------|-------------|
|
|
27
|
-
| `-p, --port <n>` | Port (default `3000`) |
|
|
27
|
+
| `-p, --port <n>` | Port (default `3000`, or `$PORT`) |
|
|
28
28
|
| `-H, --host <host>` | Hostname (default `localhost`) |
|
|
29
29
|
| `-s, --spa` | SPA fallback to `index.html` |
|
|
30
30
|
| `-w, --watch` | Live reload via SSE |
|
|
@@ -46,8 +46,30 @@ bunx deserved dist --host 0.0.0.0
|
|
|
46
46
|
bunx deserved dist --open
|
|
47
47
|
bunx deserved dist --cors
|
|
48
48
|
bunx deserved dist --watch
|
|
49
|
+
PORT=8080 bunx deserved dist
|
|
49
50
|
```
|
|
50
51
|
|
|
52
|
+
The default port (`3000`, or `$PORT` if set) hops to the next free port (up
|
|
53
|
+
to 10 tries) if it's taken; an explicit `--port` never does — it fails
|
|
54
|
+
cleanly instead.
|
|
55
|
+
|
|
56
|
+
## Programmatic use
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { serve } from "deserved";
|
|
60
|
+
|
|
61
|
+
const server = await serve({ root: "dist", port: 0, quiet: true });
|
|
62
|
+
console.log(server.url);
|
|
63
|
+
await server.stop();
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`serve()` accepts a `Partial<Options>`, merged over the same defaults as the
|
|
67
|
+
CLI (`DEFAULT_OPTIONS`). It resolves to `{ port, hostname, url, stop() }`;
|
|
68
|
+
`stop()` closes the server and, if `watch: true` was passed, the file
|
|
69
|
+
watcher. Unlike the CLI, a bind failure (e.g. a port already in use) rejects
|
|
70
|
+
the promise instead of exiting the process. A `port` passed to `serve()` is
|
|
71
|
+
always treated as explicit — it never hops to another port.
|
|
72
|
+
|
|
51
73
|
## Features
|
|
52
74
|
|
|
53
75
|
- `Bun.file()` / `Bun.serve()`: no streams plumbing
|
|
@@ -55,6 +77,7 @@ bunx deserved dist --watch
|
|
|
55
77
|
- Range requests (`206`) for media
|
|
56
78
|
- SPA mode (HTML Accept only; assets still 404)
|
|
57
79
|
- Optional live reload (`--watch`) via Server-Sent Events
|
|
80
|
+
- CSS-only changes hot-swap stylesheets in place instead of a full page reload
|
|
58
81
|
- Gzip compression
|
|
59
82
|
- Cache headers off by default (`no-cache`); opt in per-run with `--cache` for long-lived, immutable asset caching
|
|
60
83
|
- Directory listings (disable with `--no-dir`)
|
package/cli.js
CHANGED
|
@@ -1,42 +1,46 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{resolve as
|
|
4
|
-
`),
|
|
3
|
+
import{resolve as W5}from"path";var c="0.4.0";import{statSync as i0,watch as m0}from"fs";import{networkInterfaces as p0}from"os";import{relative as l0,resolve as h0}from"path";import{readdirSync as Z0,realpathSync as s,statSync as C}from"fs";import{extname as Y0,join as r,normalize as N0,resolve as a,sep as t}from"path";import{promisify as X0}from"util";import{gzip as D0}from"zlib";var{escapeHTML:S}=globalThis.Bun;var J0=new TextEncoder,n="application/octet-stream",V0={".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 j0($,x){let O=$.type;if(O&&O!==n&&O!=="")return O;let G=Y0(x).toLowerCase();return V0[G]??n}function q($){let x=$.split(";")[0]?.trim().toLowerCase()??"";return x.startsWith("text/")||x==="application/javascript"||x==="text/javascript"||x==="application/json"||x==="application/xml"||x==="image/svg+xml"||x.endsWith("+json")||x.endsWith("+xml")}function u0($){return $.startsWith("text/html")}function I0($,x,O=""){return`"${$}-${Math.trunc(x)}${O}"`}function k0($,x){let O=$.headers.get("If-None-Match");if(!O)return!1;return O.split(",").some((G)=>G.trim().replace(/^W\//,"")===x)}function B0($,x){let O=$.headers.get("If-Modified-Since");if(!O)return!1;let G=Date.parse(O);if(Number.isNaN(G))return!1;return Math.trunc(x/1000)*1000<=G}function w0($,x,O){return $.headers.get("If-None-Match")?k0($,x):B0($,O)}function U0($,x,O){let G=$.headers.get("If-Range");if(!G)return!0;if(G.startsWith('"')||G.startsWith("W/"))return G===x;let Z=Date.parse(G);if(Number.isNaN(Z))return!1;return Z===Math.trunc(O/1000)*1000}function i($){let x=$.headers.get("Accept");if(!x||x==="*/*")return!0;return x.includes("text/html")||x.includes("application/xhtml")}function F0($){let x=$.headers.get("Accept-Encoding")??"";if(x.includes("zstd"))return"zstd";if(x.includes("gzip"))return"gzip";return null}function S0($){if($.startsWith("/__"))return!1;let x=$.slice($.lastIndexOf("/")+1);if(!x)return!0;if(x.includes("."))return!1;return!0}function _0($,x,O){if(!x)return null;let G=O.replace(/^\/+/,""),Z=z0(G);for(let N of Z){let W=e($,N);if(!W)continue;let Q=$0(x,W);if(!Q)continue;try{let Y=C(Q);if(Y.isFile())return{path:Q,file:Bun.file(Q),size:Y.size,mtimeMs:Y.mtimeMs,kind:L0(N)}}catch{}}return null}var K0=4096,T0=500;function P0($,x,O){let G=new Map;function Z(N){let W=G.get(N);if(W&&(O||Date.now()-W.at<T0)){if(W.value===null)return null;try{let Y=C(W.value.real);if(Y.isFile())return{path:W.value.real,file:Bun.file(W.value.real),size:Y.size,mtimeMs:Y.mtimeMs,kind:W.value.kind}}catch{}}let Q=_0($,x,N);if(G.size>=K0)G.clear();return G.set(N,{value:Q?{real:Q.path,kind:Q.kind}:null,at:Date.now()}),Q}return{resolveCached:Z,invalidate:()=>G.clear(),size:()=>G.size}}function L0($){if($.endsWith("/index.html"))return"dir-index";if($.endsWith(".html")&&!$.endsWith("/index.html"))return"html-ext";return"file"}function z0($){if(!$||$===".")return["index.html"];let x=$.endsWith("/")?$.slice(0,-1):$;if(!x)return["index.html"];if($.endsWith("/"))return[`${x}/index.html`];return[x,`${x}.html`,`${x}/index.html`]}function e($,x){let O=a($),G=N0(r(O,x));if(G!==O&&!G.startsWith(O+t))return null;return G}function $0($,x){try{let O=s(x);if(O!==$&&!O.startsWith($+t))return null;return O}catch{return null}}var m=new Map;function H0($){let x=m.get($);if(x===void 0){try{x=s($)}catch{x=null}m.set($,x)}return x}function f0($,x,O){if(!x)return null;let G=O.replace(/^\/+/,"").replace(/\/+$/,""),Z=e($,G||".");if(!Z)return null;let N=$0(x,Z);if(!N)return null;try{if(C(N).isDirectory())return N}catch{return null}return null}function E0($){if($===null)return"-";if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} kB`;return`${($/1048576).toFixed(1)} MB`}function M0($){if($===null)return"-";let x=new Date($),O=x.getFullYear(),G=String(x.getMonth()+1).padStart(2,"0"),Z=String(x.getDate()).padStart(2,"0"),N=String(x.getHours()).padStart(2,"0"),W=String(x.getMinutes()).padStart(2,"0");return`${O}-${G}-${Z} ${N}:${W}`}function A0($){return Z0($,{withFileTypes:!0}).filter((x)=>!x.name.startsWith(".")).map((x)=>{let O=x.isDirectory(),G=null,Z=null;if(!O)try{let N=C(r($,x.name));G=N.size,Z=N.mtimeMs}catch{}return{name:x.name,dir:O,size:G,mtimeMs:Z}}).sort((x,O)=>{if(x.dir!==O.dir)return x.dir?-1:1;return x.name.localeCompare(O.name)})}function v0($,x){let O=$.endsWith("/")?$:`${$}/`,G=p(O),Z=C0($),N=x.map((Q)=>{let Y=R0(G,encodeURIComponent(Q.name))+(Q.dir?"/":""),X=Q.dir?`${Q.name}/`:Q.name,J=E0(Q.size),u=M0(Q.mtimeMs);return` <li><a href="${S(Y)}">${S(X)}</a> <span class="meta">${S(J)}</span> <span class="meta">${S(u)}</span></li>`}).join(`
|
|
4
|
+
`),W=Z!==null?` <li><a href="${S(p(Z))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
|
|
5
5
|
`:"";return`<!DOCTYPE html>
|
|
6
6
|
<html lang="en">
|
|
7
7
|
<head>
|
|
8
8
|
<meta charset="utf-8">
|
|
9
9
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10
|
-
<title>Index of ${
|
|
10
|
+
<title>Index of ${S($)}</title>
|
|
11
11
|
<style>
|
|
12
12
|
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
13
|
-
body { max-width:
|
|
13
|
+
body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
14
14
|
h1 { font-size: 1.1rem; font-weight: 600; }
|
|
15
15
|
ul { list-style: none; padding: 0; }
|
|
16
|
-
li { padding: 0.2rem 0; }
|
|
17
|
-
a { color: inherit; text-decoration: none; }
|
|
18
|
-
a:hover { text-decoration: underline; }
|
|
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; }
|
|
19
20
|
</style>
|
|
20
21
|
</head>
|
|
21
22
|
<body>
|
|
22
|
-
<h1>Index of ${
|
|
23
|
+
<h1>Index of ${S($||"/")}</h1>
|
|
23
24
|
<ul>
|
|
24
|
-
${
|
|
25
|
+
${W}${N}
|
|
25
26
|
</ul>
|
|
26
27
|
</body>
|
|
27
28
|
</html>
|
|
28
|
-
`}function
|
|
29
|
+
`}function C0($){if($==="/"||$==="")return null;let x=$.replace(/\/+$/,""),O=x.lastIndexOf("/");if(O<=0)return"/";return x.slice(0,O+1)}function p($){return $.split("/").map(encodeURIComponent).join("/")}function R0($,x){if($==="/")return`/${x}`;return`${$.replace(/\/+$/,"")}/${x}`}function x0($,x){let O=a($.root),G=H0(O),Z=P0(O,G,$.watch),N=c0(),W=async function(Y){let X=new URL(Y.url),J=Y.method.toUpperCase(),u;if(X.pathname.includes("%"))try{u=decodeURIComponent(X.pathname)}catch{let I=new Response("Bad Request",{status:400});return _(J,400,X.pathname,$.quiet),z(J,H(I,$))}else u=X.pathname;try{return await q0(Y,J,u,X,$,x,O,G,Z.resolveCached,N.getCompressed)}catch(I){console.error(I);let D=new Response("Internal Server Error",{status:500});return _(J,500,X.pathname,$.quiet),z(J,H(D,$))}};return W.invalidateResolutionCache=Z.invalidate,W.invalidateCompressedCache=N.invalidate,W.resolutionCacheSize=Z.size,W.compressedCacheBytes=N.bytes,W}function l($,x){let O=`${$.pathname}/${$.search}`,G=new Response(null,{status:301,headers:{Location:O}});return H(G,x)}async function q0($,x,O,G,Z,N,W,Q,Y,X){let J=(D)=>{return _(x,D.status,O,Z.quiet),z(x,H(D,Z))};if(x!=="GET"&&x!=="HEAD"){let D=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return J(D)}if(Z.watch&&O===A){let D=new Response(O0,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return J(D)}if(Z.watch&&O===v&&N){let D=N.subscribe();return _(x,200,O,Z.quiet),H(D,Z)}if(O===A||O===v)return z(x,H(new Response("Not Found",{status:404}),Z));let u=Y(O);if(u){if(u.kind==="dir-index"&&!O.endsWith("/")){let k=l(G,Z);return _(x,k.status,O,Z.quiet),z(x,k)}let D=await d(X,$,u,Z);return J(D)}if(Z.spa&&i($)&&S0(O)){let D=Y("/");if(D){let k=await d(X,$,D,Z,!0);return J(k)}}if(Z.dir){let D=f0(W,Q,O);if(D){if(!O.endsWith("/")){let B=l(G,Z);return _(x,B.status,O,Z.quiet),z(x,B)}let k=A0(D),j=v0(O,k),w=Z.watch?M(j):j,U=new Response(w,{headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return J(U)}}if(i($)){let D=Y("/404.html");if(D){let k=await D.file.text(),j=Z.watch?M(k):k,w=new Response(j,{status:404,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return J(w)}}let I=new Response("Not Found",{status:404});return J(I)}var g0=67108864,b0=X0(D0);async function y0($,x){if($==="zstd")return new Uint8Array(await Bun.zstdCompress(x));return new Uint8Array(await b0(x))}function c0(){let $=new Map,x=0,O=new Map;function G(W,Q){let Y=$.get(W);if(Y)$.delete(W),x-=Y.data.byteLength;$.set(W,Q),x+=Q.data.byteLength;while(x>g0&&$.size>1){let X=$.keys().next().value;if(X===void 0)break;let J=$.get(X);if($.delete(X),J)x-=J.data.byteLength}}let Z=async(W,Q,Y)=>{let X=`${W.key}:${Q}`,J=$.get(X);if(J&&J.size===W.size&&J.mtimeMs===W.mtimeMs)return G(X,J),J.data;let u=O.get(X);if(u&&u.size===W.size&&u.mtimeMs===W.mtimeMs)return u.promise;let I={size:W.size,mtimeMs:W.mtimeMs,promise:Promise.resolve(null)};return I.promise=(async()=>{try{let D=await Y(),k=await y0(Q,D);return G(X,{size:W.size,mtimeMs:W.mtimeMs,data:k}),k}catch{return null}finally{if(O.get(X)?.promise===I.promise)O.delete(X)}})(),O.set(X,I),I.promise};function N(){$.clear(),x=0,O.clear()}return{getCompressed:Z,invalidate:N,bytes:()=>x}}async function h($,x,O,G,Z){let N=F0(x);if(!N)return null;let W=await $(G,N,Z);if(!W)return null;return O.set("Content-Encoding",N),O.set("Content-Length",String(W.byteLength)),O.delete("Accept-Ranges"),O.set("Vary","Accept-Encoding"),new Response(W,{status:200,headers:O})}async function d($,x,O,G,Z=!1){let{path:N,file:W,size:Q,mtimeMs:Y}=O,X=j0(W,N),J=Z||u0(X),u=I0(Q,Y,G.watch&&J?"-live":""),I=G.compress&&q(X);if(w0(x,u,Y)){let j=o(u,G,J,Y);if(I)j.set("Vary","Accept-Encoding");return new Response(null,{status:304,headers:j})}let D=o(u,G,J,Y);if(D.set("Content-Type",X),D.set("Accept-Ranges","bytes"),I)D.set("Vary","Accept-Encoding");let k=x.headers.get("Range")&&U0(x,u,Y)?x.headers.get("Range"):null;if(k&&x.method==="GET"){let j=n0(k,Q);if(j==="invalid")return D.set("Content-Range",`bytes */${Q}`),new Response(null,{status:416,headers:D});if(j){let{start:w,end:U}=j,B=U-w+1;return D.set("Content-Range",`bytes ${w}-${U}/${Q}`),D.set("Content-Length",String(B)),new Response(W.slice(w,U+1),{status:206,headers:D})}}if(x.method==="HEAD")return D.set("Content-Length",String(Q)),new Response(null,{status:200,headers:D});if(G.watch&&J&&x.method==="GET"){if(G.compress&&q(X)){let w=await h($,x,D,{key:`${N}\x00live`,size:Q,mtimeMs:Y},async()=>J0.encode(M(await W.text())));if(w)return w}let j=M(await W.text());return D.set("Content-Length",String(Buffer.byteLength(j))),new Response(j,{status:200,headers:D})}if(G.compress&&x.method==="GET"&&q(X)&&Q<2000000){let j=await h($,x,D,{key:N,size:Q,mtimeMs:Y},async()=>new Uint8Array(await W.arrayBuffer()));if(j)return j}return D.set("Content-Length",String(Q)),new Response(W,{status:200,headers:D})}function o($,x,O,G){let Z=new Headers;if(Z.set("ETag",$),Z.set("Last-Modified",new Date(G).toUTCString()),x.watch||!x.cache||O)return Z.set("Cache-Control","no-cache"),Z;return Z.set("Cache-Control","public, max-age=31536000, immutable"),Z}function n0($,x){let O=/^bytes=(\d*)-(\d*)$/.exec($.trim());if(!O)return null;let G=O[1],Z=O[2],N,W;if(G===""&&Z==="")return"invalid";if(G===""){let Q=Number(Z);if(!Number.isFinite(Q)||Q<=0)return"invalid";N=Math.max(0,x-Q),W=x-1}else N=Number(G),W=Z===""?x-1:Number(Z);if(!Number.isFinite(N)||!Number.isFinite(W)||N<0||W<N||N>=x)return"invalid";return W=Math.min(W,x-1),{start:N,end:W}}function H($,x){if(!x.cors)return $;return $.headers.set("Access-Control-Allow-Origin","*"),$.headers.set("Access-Control-Allow-Headers","*"),$.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),$}function z($,x){if($!=="HEAD")return x;return new Response(null,{status:x.status,statusText:x.statusText,headers:x.headers})}var b={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class K extends Error{constructor($,x){super($,x);this.name="RootError"}}class f extends Error{constructor($,x,O){super(`could not bind to ${$}:${x}`,O);this.name="BindError"}}var d0=10;function G0($){if($&&typeof $==="object"&&"code"in $&&$.code==="EADDRINUSE")return!0;let x=$ instanceof Error?$.message:String($);return/EADDRINUSE|address already in use/i.test(x)}var A="/__live.js",v="/__events",O0=`(()=>{const e=new EventSource("${v}");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)}})()`,Q0=`<script src="${A}"></script>`;function o0($,x){return`http://${$.includes(":")?`[${$}]`:$}:${x}`}function M($){let x=$.toLowerCase().lastIndexOf("</body>");if(x===-1)return $+Q0;return $.slice(0,x)+Q0+$.slice(x)}function s0(){let $=new Set,x=new TextEncoder,O=x.encode(`: ping
|
|
29
30
|
|
|
30
|
-
`)
|
|
31
|
+
`),G=setInterval(()=>{for(let Q of $)try{Q.enqueue(O)}catch{$.delete(Q)}},8000);G.unref();function Z(){let Q,Y=new ReadableStream({start(X){Q=X,$.add(X),X.enqueue(x.encode(`: connected
|
|
31
32
|
|
|
32
|
-
`)
|
|
33
|
+
`))},cancel(){$.delete(Q)}});return new Response(Y,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function N(Q="reload"){let Y=x.encode(`data: ${Q}
|
|
34
|
+
|
|
35
|
+
`);for(let X of $)try{X.enqueue(Y)}catch{$.delete(X)}}function W(){clearInterval(G);for(let Q of $)try{Q.close()}catch{}$.clear()}return{subscribe:Z,broadcast:N,close:W}}var V={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},r0=/[\x00-\x1f\x7f]/g;function a0($){return $.replace(r0,"")}function _($,x,O,G){if(G)return;let Z=x<300?`${V.green}\u2713${V.reset}`:x<400?`${V.yellow}\u25CB${V.reset}`:`${V.red}\u2717${V.reset}`;console.log(`${Z} ${V.dim}${$}${V.reset} ${x} ${a0(O)}`)}function g($,x=!1){if(x)return;console.log(`${V.cyan}\u2502${V.reset} ${$}`)}function t0($){return $.split(/[/\\]/).some((x)=>x.startsWith(".")||x==="node_modules")}function e0($){if($.length===0)return"reload";return $.every((x)=>x?.endsWith(".css"))?"css":"reload"}function $5(){let $=p0();for(let x of Object.values($))for(let O of x??[])if(O.family==="IPv4"&&!O.internal)return O.address;return null}function x5($,x,O,G){if(console.log(),console.log(` ${V.bold}deserved${V.reset} ${V.dim}serving${V.reset} ${x}`),console.log(` ${V.green}->${V.reset} ${V.cyan}${$}${V.reset}`),G)console.log(` ${V.green}->${V.reset} ${V.cyan}${G}${V.reset}`);if(O.length)console.log(` ${V.dim}${O.join(" ")}${V.reset}`);console.log()}function O5($,x){if($)return;console.log(`${V.yellow}*${V.reset} ${x}`)}async function G5($){let x=process.platform;try{if(x==="darwin")await Bun.spawn(["open",$],{stdout:"ignore",stderr:"ignore"}).exited;else if(x==="win32")await Bun.spawn(["cmd","/c","start","",$],{stdout:"ignore",stderr:"ignore"}).exited;else await Bun.spawn(["xdg-open",$],{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${$}`)}}function Q5($){try{if(!i0($).isDirectory())throw new K(`not a directory: ${$}`)}catch(x){if(x instanceof K)throw x;if(x instanceof Error&&"code"in x&&x.code==="ENOENT")throw new K(`directory not found: ${$}`);throw new K(`not a directory: ${$}`)}}async function y($){let x=h0($.root);Q5(x);let O=$.watch?s0():void 0,G=x0({...$,root:x},O),Z=$.host==="localhost"?"127.0.0.1":$.host,N=async(B)=>{if($.cors&&B.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"*","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS"}});return G(B)},W=(B)=>Bun.serve({port:B,hostname:Z,fetch:N}),Q=!$.portExplicit&&$.port!==0,Y,X=$.port;try{Y=W(X)}catch(B){if(!Q||!G0(B))throw new f($.host,X,{cause:B});let F,T=$.port,P=B;for(let L=1;L<=d0;L++){T=$.port+L;try{F=W(T),X=T;break}catch(R){if(!G0(R))throw new f($.host,T,{cause:R});P=R}}if(!F)throw new f($.host,T,{cause:P});Y=F,g(`port ${$.port} in use, using ${X}`,$.quiet)}let J=$.host==="0.0.0.0"||$.host==="::",u=J?"localhost":$.host,I=o0(u,Y.port??$.port),D=J?$5():null,k=D?`http://${D}:${Y.port}`:void 0,j=[];if($.spa)j.push("--spa");if($.watch)j.push("--watch");if($.cors)j.push("--cors");if(!$.dir)j.push("--no-dir");if(!$.compress)j.push("--no-compress");if($.cache)j.push("--cache");x5(I,l0(process.cwd(),x)||".",j,k);let w;if($.watch&&O){let B=null,F=new Set;w=m0(x,{recursive:!0},(T,P)=>{if(P&&t0(P))return;if(G.invalidateResolutionCache(),G.invalidateCompressedCache(),F.add(P),B)clearTimeout(B);B=setTimeout(()=>{let L=e0([...F]);F.clear(),O5($.quiet,L),O.broadcast(L)},80)}),g("watching for changes",$.quiet)}let U=async()=>{w?.close(),O?.close(),await Y.stop(),g("server stopped",$.quiet)};if($.open)await G5(I);return{port:Y.port??$.port,hostname:u,url:I,stop:U}}async function F5($={}){let x=$.portExplicit??$.port!==void 0;return y({...b,...$,portExplicit:x})}function Z5(){console.log(`
|
|
33
36
|
deserved - tiny Bun static file server
|
|
34
37
|
|
|
35
38
|
Usage
|
|
36
39
|
deserved [path] [options]
|
|
37
40
|
|
|
38
41
|
Options
|
|
39
|
-
-p, --port <n> Port (default: 3000
|
|
42
|
+
-p, --port <n> Port (default: 3000, or $PORT; hops to the next
|
|
43
|
+
free port unless set explicitly)
|
|
40
44
|
-H, --host <host> Hostname (default: localhost)
|
|
41
45
|
-s, --spa SPA fallback to index.html
|
|
42
46
|
-w, --watch Live reload on file changes
|
|
@@ -57,4 +61,5 @@ ${X}${Z}
|
|
|
57
61
|
deserved dist --spa
|
|
58
62
|
deserved dist --port 8080
|
|
59
63
|
deserved docs --watch --open
|
|
60
|
-
|
|
64
|
+
PORT=8080 deserved dist
|
|
65
|
+
`)}function Y5($,x=Bun.env){let O=$.slice(2),G={...b},Z=G.root,N=!1;for(let W=0;W<O.length;W++){let Q=O[W];if(Q===void 0)break;if(Q==="-h"||Q==="--help")Z5(),process.exit(0);if(Q==="-v"||Q==="--version")console.log(c),process.exit(0);if(Q==="-s"||Q==="--spa"){G.spa=!0;continue}if(Q==="-w"||Q==="--watch"){G.watch=!0;continue}if(Q==="-o"||Q==="--open"){G.open=!0;continue}if(Q==="--cors"){G.cors=!0;continue}if(Q==="--dir"){G.dir=!0;continue}if(Q==="--no-dir"){G.dir=!1;continue}if(Q==="--cache"){G.cache=!0;continue}if(Q==="--no-cache"){G.cache=!1;continue}if(Q==="--compress"){G.compress=!0;continue}if(Q==="--no-compress"){G.compress=!1;continue}if(Q==="-q"||Q==="--quiet"){G.quiet=!0;continue}if(Q==="-p"||Q==="--port"){let Y=O[++W];if(!Y||Y.startsWith("-"))E(`Missing value for ${Q}`);let X=Number(Y);if(!Number.isInteger(X)||X<0||X>65535)E(`Invalid port: ${Y}`);G.port=X,N=!0;continue}if(Q==="-H"||Q==="--host"){let Y=O[++W];if(!Y||Y.startsWith("-"))E(`Missing value for ${Q}`);G.host=Y;continue}if(Q.startsWith("--port=")){let Y=Number(Q.slice(7));if(!Number.isInteger(Y)||Y<0||Y>65535)E(`Invalid port: ${Q}`);G.port=Y,N=!0;continue}if(Q.startsWith("--host=")){G.host=Q.slice(7);continue}if(Q.startsWith("-"))E(`Unknown option: ${Q}`);Z=Q}if(!N&&x.PORT!==void 0){let W=Number(x.PORT);if(!Number.isInteger(W)||W<0||W>65535)E(`Invalid port: ${x.PORT}`);G.port=W}return G.portExplicit=N,G.root=W5(Z),G}function E($){console.error(`Error: ${$}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let $=Y5(process.argv),x;try{x=await y($)}catch(G){if(G instanceof K)console.error(`Error: ${G.message}`),console.error("Run deserved --help."),process.exit(1);if(G instanceof f)console.error(`Error: ${G.message}`),console.error(G.cause instanceof Error?G.cause.message:String(G.cause)),process.exit(1);throw G}let O=async()=>{await x.stop(),process.exit(0)};process.on("SIGINT",O),process.on("SIGTERM",O)}export{Y5 as parseArgs};
|
package/index.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{readdirSync as LQ,realpathSync as s,statSync as q}from"fs";import{extname as wQ,join as t,normalize as zQ,resolve as e,sep as QQ}from"path";import{promisify as SQ}from"util";import{gzip as HQ}from"zlib";var{escapeHTML:w}=globalThis.Bun;import{statSync as YQ,watch as GQ}from"fs";import{networkInterfaces as XQ}from"os";import{relative as JQ,resolve as WQ}from"path";var m={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class P extends Error{constructor(Q,Z){super(Q,Z);this.name="RootError"}}class E extends Error{constructor(Q,Z,$){super(`could not bind to ${Q}:${Z}`,$);this.name="BindError"}}var OQ=10;function g(Q){if(Q&&typeof Q==="object"&&"code"in Q&&Q.code==="EADDRINUSE")return!0;let Z=Q instanceof Error?Q.message:String(Q);return/EADDRINUSE|address already in use/i.test(Z)}var C="/__live.js",R="/__events",c=`(()=>{const e=new EventSource("${R}");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)}})()`,b=`<script src="${C}"></script>`;function VQ(Q,Z){return`http://${Q.includes(":")?`[${Q}]`:Q}:${Z}`}function A(Q){let Z=Q.toLowerCase().lastIndexOf("</body>");if(Z===-1)return Q+b;return Q.slice(0,Z)+b+Q.slice(Z)}function jQ(){let Q=new Set,Z=new TextEncoder,$=Z.encode(`: ping
|
|
3
|
+
|
|
4
|
+
`),Y=setInterval(()=>{for(let J of Q)try{J.enqueue($)}catch{Q.delete(J)}},8000);Y.unref();function G(){let J,V=new ReadableStream({start(j){J=j,Q.add(j),j.enqueue(Z.encode(`: connected
|
|
5
|
+
|
|
6
|
+
`))},cancel(){Q.delete(J)}});return new Response(V,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function W(J="reload"){let V=Z.encode(`data: ${J}
|
|
7
|
+
|
|
8
|
+
`);for(let j of Q)try{j.enqueue(V)}catch{Q.delete(j)}}function X(){clearInterval(Y);for(let J of Q)try{J.close()}catch{}Q.clear()}return{subscribe:G,broadcast:W,close:X}}var N={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},DQ=/[\x00-\x1f\x7f]/g;function NQ(Q){return Q.replace(DQ,"")}function L(Q,Z,$,Y){if(Y)return;let G=Z<300?`${N.green}\u2713${N.reset}`:Z<400?`${N.yellow}\u25CB${N.reset}`:`${N.red}\u2717${N.reset}`;console.log(`${G} ${N.dim}${Q}${N.reset} ${Z} ${NQ($)}`)}function y(Q,Z=!1){if(Z)return;console.log(`${N.cyan}\u2502${N.reset} ${Q}`)}function xQ(Q){return Q.split(/[/\\]/).some((Z)=>Z.startsWith(".")||Z==="node_modules")}function BQ(Q){if(Q.length===0)return"reload";return Q.every((Z)=>Z?.endsWith(".css"))?"css":"reload"}function UQ(){let Q=XQ();for(let Z of Object.values(Q))for(let $ of Z??[])if($.family==="IPv4"&&!$.internal)return $.address;return null}function kQ(Q,Z,$,Y){if(console.log(),console.log(` ${N.bold}deserved${N.reset} ${N.dim}serving${N.reset} ${Z}`),console.log(` ${N.green}->${N.reset} ${N.cyan}${Q}${N.reset}`),Y)console.log(` ${N.green}->${N.reset} ${N.cyan}${Y}${N.reset}`);if($.length)console.log(` ${N.dim}${$.join(" ")}${N.reset}`);console.log()}function FQ(Q,Z){if(Q)return;console.log(`${N.yellow}*${N.reset} ${Z}`)}async function _Q(Q){let Z=process.platform;try{if(Z==="darwin")await Bun.spawn(["open",Q],{stdout:"ignore",stderr:"ignore"}).exited;else if(Z==="win32")await Bun.spawn(["cmd","/c","start","",Q],{stdout:"ignore",stderr:"ignore"}).exited;else await Bun.spawn(["xdg-open",Q],{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${Q}`)}}function IQ(Q){try{if(!YQ(Q).isDirectory())throw new P(`not a directory: ${Q}`)}catch(Z){if(Z instanceof P)throw Z;if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")throw new P(`directory not found: ${Q}`);throw new P(`not a directory: ${Q}`)}}async function h(Q){let Z=WQ(Q.root);IQ(Z);let $=Q.watch?jQ():void 0,Y=u({...Q,root:Z},$),G=Q.host==="localhost"?"127.0.0.1":Q.host,W=async(F)=>{if(Q.cors&&F.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"*","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS"}});return Y(F)},X=(F)=>Bun.serve({port:F,hostname:G,fetch:W}),J=!Q.portExplicit&&Q.port!==0,V,j=Q.port;try{V=X(j)}catch(F){if(!J||!g(F))throw new E(Q.host,j,{cause:F});let K,z=Q.port,S=F;for(let H=1;H<=OQ;H++){z=Q.port+H;try{K=X(z),j=z;break}catch(v){if(!g(v))throw new E(Q.host,z,{cause:v});S=v}}if(!K)throw new E(Q.host,z,{cause:S});V=K,y(`port ${Q.port} in use, using ${j}`,Q.quiet)}let D=Q.host==="0.0.0.0"||Q.host==="::",B=D?"localhost":Q.host,U=VQ(B,V.port??Q.port),O=D?UQ():null,k=O?`http://${O}:${V.port}`:void 0,x=[];if(Q.spa)x.push("--spa");if(Q.watch)x.push("--watch");if(Q.cors)x.push("--cors");if(!Q.dir)x.push("--no-dir");if(!Q.compress)x.push("--no-compress");if(Q.cache)x.push("--cache");kQ(U,JQ(process.cwd(),Z)||".",x,k);let _;if(Q.watch&&$){let F=null,K=new Set;_=GQ(Z,{recursive:!0},(z,S)=>{if(S&&xQ(S))return;if(Y.invalidateResolutionCache(),Y.invalidateCompressedCache(),K.add(S),F)clearTimeout(F);F=setTimeout(()=>{let H=BQ([...K]);K.clear(),FQ(Q.quiet,H),$.broadcast(H)},80)}),y("watching for changes",Q.quiet)}let I=async()=>{_?.close(),$?.close(),await V.stop(),y("server stopped",Q.quiet)};if(Q.open)await _Q(U);return{port:V.port??Q.port,hostname:B,url:U,stop:I}}async function KQ(Q={}){let Z=Q.portExplicit??Q.port!==void 0;return h({...m,...Q,portExplicit:Z})}var PQ=new TextEncoder,l="application/octet-stream",TQ={".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 MQ(Q,Z){let $=Q.type;if($&&$!==l&&$!=="")return $;let Y=wQ(Z).toLowerCase();return TQ[Y]??l}function f(Q){let Z=Q.split(";")[0]?.trim().toLowerCase()??"";return Z.startsWith("text/")||Z==="application/javascript"||Z==="text/javascript"||Z==="application/json"||Z==="application/xml"||Z==="image/svg+xml"||Z.endsWith("+json")||Z.endsWith("+xml")}function EQ(Q){return Q.startsWith("text/html")}function AQ(Q,Z,$=""){return`"${Q}-${Math.trunc(Z)}${$}"`}function CQ(Q,Z){let $=Q.headers.get("If-None-Match");if(!$)return!1;return $.split(",").some((Y)=>Y.trim().replace(/^W\//,"")===Z)}function RQ(Q,Z){let $=Q.headers.get("If-Modified-Since");if(!$)return!1;let Y=Date.parse($);if(Number.isNaN(Y))return!1;return Math.trunc(Z/1000)*1000<=Y}function qQ(Q,Z,$){return Q.headers.get("If-None-Match")?CQ(Q,Z):RQ(Q,$)}function vQ(Q,Z,$){let Y=Q.headers.get("If-Range");if(!Y)return!0;if(Y.startsWith('"')||Y.startsWith("W/"))return Y===Z;let G=Date.parse(Y);if(Number.isNaN(G))return!1;return G===Math.trunc($/1000)*1000}function p(Q){let Z=Q.headers.get("Accept");if(!Z||Z==="*/*")return!0;return Z.includes("text/html")||Z.includes("application/xhtml")}function yQ(Q){let Z=Q.headers.get("Accept-Encoding")??"";if(Z.includes("zstd"))return"zstd";if(Z.includes("gzip"))return"gzip";return null}function uQ(Q){if(Q.startsWith("/__"))return!1;let Z=Q.slice(Q.lastIndexOf("/")+1);if(!Z)return!0;if(Z.includes("."))return!1;return!0}function fQ(Q,Z,$){if(!Z)return null;let Y=$.replace(/^\/+/,""),G=hQ(Y);for(let W of G){let X=ZQ(Q,W);if(!X)continue;let J=$Q(Z,X);if(!J)continue;try{let V=q(J);if(V.isFile())return{path:J,file:Bun.file(J),size:V.size,mtimeMs:V.mtimeMs,kind:cQ(W)}}catch{}}return null}var gQ=4096,bQ=500;function mQ(Q,Z,$){let Y=new Map;function G(W){let X=Y.get(W);if(X&&($||Date.now()-X.at<bQ)){if(X.value===null)return null;try{let V=q(X.value.real);if(V.isFile())return{path:X.value.real,file:Bun.file(X.value.real),size:V.size,mtimeMs:V.mtimeMs,kind:X.value.kind}}catch{}}let J=fQ(Q,Z,W);if(Y.size>=gQ)Y.clear();return Y.set(W,{value:J?{real:J.path,kind:J.kind}:null,at:Date.now()}),J}return{resolveCached:G,invalidate:()=>Y.clear(),size:()=>Y.size}}function cQ(Q){if(Q.endsWith("/index.html"))return"dir-index";if(Q.endsWith(".html")&&!Q.endsWith("/index.html"))return"html-ext";return"file"}function hQ(Q){if(!Q||Q===".")return["index.html"];let Z=Q.endsWith("/")?Q.slice(0,-1):Q;if(!Z)return["index.html"];if(Q.endsWith("/"))return[`${Z}/index.html`];return[Z,`${Z}.html`,`${Z}/index.html`]}function ZQ(Q,Z){let $=e(Q),Y=zQ(t($,Z));if(Y!==$&&!Y.startsWith($+QQ))return null;return Y}function $Q(Q,Z){try{let $=s(Z);if($!==Q&&!$.startsWith(Q+QQ))return null;return $}catch{return null}}var n=new Map;function lQ(Q){let Z=n.get(Q);if(Z===void 0){try{Z=s(Q)}catch{Z=null}n.set(Q,Z)}return Z}function pQ(Q,Z,$){if(!Z)return null;let Y=$.replace(/^\/+/,"").replace(/\/+$/,""),G=ZQ(Q,Y||".");if(!G)return null;let W=$Q(Z,G);if(!W)return null;try{if(q(W).isDirectory())return W}catch{return null}return null}function nQ(Q){if(Q===null)return"-";if(Q<1024)return`${Q} B`;if(Q<1048576)return`${(Q/1024).toFixed(1)} kB`;return`${(Q/1048576).toFixed(1)} MB`}function iQ(Q){if(Q===null)return"-";let Z=new Date(Q),$=Z.getFullYear(),Y=String(Z.getMonth()+1).padStart(2,"0"),G=String(Z.getDate()).padStart(2,"0"),W=String(Z.getHours()).padStart(2,"0"),X=String(Z.getMinutes()).padStart(2,"0");return`${$}-${Y}-${G} ${W}:${X}`}function dQ(Q){return LQ(Q,{withFileTypes:!0}).filter((Z)=>!Z.name.startsWith(".")).map((Z)=>{let $=Z.isDirectory(),Y=null,G=null;if(!$)try{let W=q(t(Q,Z.name));Y=W.size,G=W.mtimeMs}catch{}return{name:Z.name,dir:$,size:Y,mtimeMs:G}}).sort((Z,$)=>{if(Z.dir!==$.dir)return Z.dir?-1:1;return Z.name.localeCompare($.name)})}function oQ(Q,Z){let $=Q.endsWith("/")?Q:`${Q}/`,Y=i($),G=rQ(Q),W=Z.map((J)=>{let V=aQ(Y,encodeURIComponent(J.name))+(J.dir?"/":""),j=J.dir?`${J.name}/`:J.name,D=nQ(J.size),B=iQ(J.mtimeMs);return` <li><a href="${w(V)}">${w(j)}</a> <span class="meta">${w(D)}</span> <span class="meta">${w(B)}</span></li>`}).join(`
|
|
9
|
+
`),X=G!==null?` <li><a href="${w(i(G))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
|
|
10
|
+
`:"";return`<!DOCTYPE html>
|
|
11
|
+
<html lang="en">
|
|
12
|
+
<head>
|
|
13
|
+
<meta charset="utf-8">
|
|
14
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
15
|
+
<title>Index of ${w(Q)}</title>
|
|
16
|
+
<style>
|
|
17
|
+
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
18
|
+
body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
19
|
+
h1 { font-size: 1.1rem; font-weight: 600; }
|
|
20
|
+
ul { list-style: none; padding: 0; }
|
|
21
|
+
li { padding: 0.2rem 0; display: flex; gap: 2rem; }
|
|
22
|
+
li a { color: inherit; text-decoration: none; flex: 1; }
|
|
23
|
+
li a:hover { text-decoration: underline; }
|
|
24
|
+
.meta { text-align: right; min-width: 5rem; opacity: 0.6; }
|
|
25
|
+
</style>
|
|
26
|
+
</head>
|
|
27
|
+
<body>
|
|
28
|
+
<h1>Index of ${w(Q||"/")}</h1>
|
|
29
|
+
<ul>
|
|
30
|
+
${X}${W}
|
|
31
|
+
</ul>
|
|
32
|
+
</body>
|
|
33
|
+
</html>
|
|
34
|
+
`}function rQ(Q){if(Q==="/"||Q==="")return null;let Z=Q.replace(/\/+$/,""),$=Z.lastIndexOf("/");if($<=0)return"/";return Z.slice(0,$+1)}function i(Q){return Q.split("/").map(encodeURIComponent).join("/")}function aQ(Q,Z){if(Q==="/")return`/${Z}`;return`${Q.replace(/\/+$/,"")}/${Z}`}function u(Q,Z){let $=e(Q.root),Y=lQ($),G=mQ($,Y,Q.watch),W=ZZ(),X=async function(V){let j=new URL(V.url),D=V.method.toUpperCase(),B;if(j.pathname.includes("%"))try{B=decodeURIComponent(j.pathname)}catch{let U=new Response("Bad Request",{status:400});return L(D,400,j.pathname,Q.quiet),T(D,M(U,Q))}else B=j.pathname;try{return await sQ(V,D,B,j,Q,Z,$,Y,G.resolveCached,W.getCompressed)}catch(U){console.error(U);let O=new Response("Internal Server Error",{status:500});return L(D,500,j.pathname,Q.quiet),T(D,M(O,Q))}};return X.invalidateResolutionCache=G.invalidate,X.invalidateCompressedCache=W.invalidate,X.resolutionCacheSize=G.size,X.compressedCacheBytes=W.bytes,X}function d(Q,Z){let $=`${Q.pathname}/${Q.search}`,Y=new Response(null,{status:301,headers:{Location:$}});return M(Y,Z)}async function sQ(Q,Z,$,Y,G,W,X,J,V,j){let D=(O)=>{return L(Z,O.status,$,G.quiet),T(Z,M(O,G))};if(Z!=="GET"&&Z!=="HEAD"){let O=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return D(O)}if(G.watch&&$===C){let O=new Response(c,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return D(O)}if(G.watch&&$===R&&W){let O=W.subscribe();return L(Z,200,$,G.quiet),M(O,G)}if($===C||$===R)return T(Z,M(new Response("Not Found",{status:404}),G));let B=V($);if(B){if(B.kind==="dir-index"&&!$.endsWith("/")){let k=d(Y,G);return L(Z,k.status,$,G.quiet),T(Z,k)}let O=await r(j,Q,B,G);return D(O)}if(G.spa&&p(Q)&&uQ($)){let O=V("/");if(O){let k=await r(j,Q,O,G,!0);return D(k)}}if(G.dir){let O=pQ(X,J,$);if(O){if(!$.endsWith("/")){let F=d(Y,G);return L(Z,F.status,$,G.quiet),T(Z,F)}let k=dQ(O),x=oQ($,k),_=G.watch?A(x):x,I=new Response(_,{headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return D(I)}}if(p(Q)){let O=V("/404.html");if(O){let k=await O.file.text(),x=G.watch?A(k):k,_=new Response(x,{status:404,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return D(_)}}let U=new Response("Not Found",{status:404});return D(U)}var tQ=67108864,eQ=SQ(HQ);async function QZ(Q,Z){if(Q==="zstd")return new Uint8Array(await Bun.zstdCompress(Z));return new Uint8Array(await eQ(Z))}function ZZ(){let Q=new Map,Z=0,$=new Map;function Y(X,J){let V=Q.get(X);if(V)Q.delete(X),Z-=V.data.byteLength;Q.set(X,J),Z+=J.data.byteLength;while(Z>tQ&&Q.size>1){let j=Q.keys().next().value;if(j===void 0)break;let D=Q.get(j);if(Q.delete(j),D)Z-=D.data.byteLength}}let G=async(X,J,V)=>{let j=`${X.key}:${J}`,D=Q.get(j);if(D&&D.size===X.size&&D.mtimeMs===X.mtimeMs)return Y(j,D),D.data;let B=$.get(j);if(B&&B.size===X.size&&B.mtimeMs===X.mtimeMs)return B.promise;let U={size:X.size,mtimeMs:X.mtimeMs,promise:Promise.resolve(null)};return U.promise=(async()=>{try{let O=await V(),k=await QZ(J,O);return Y(j,{size:X.size,mtimeMs:X.mtimeMs,data:k}),k}catch{return null}finally{if($.get(j)?.promise===U.promise)$.delete(j)}})(),$.set(j,U),U.promise};function W(){Q.clear(),Z=0,$.clear()}return{getCompressed:G,invalidate:W,bytes:()=>Z}}async function o(Q,Z,$,Y,G){let W=yQ(Z);if(!W)return null;let X=await Q(Y,W,G);if(!X)return null;return $.set("Content-Encoding",W),$.set("Content-Length",String(X.byteLength)),$.delete("Accept-Ranges"),$.set("Vary","Accept-Encoding"),new Response(X,{status:200,headers:$})}async function r(Q,Z,$,Y,G=!1){let{path:W,file:X,size:J,mtimeMs:V}=$,j=MQ(X,W),D=G||EQ(j),B=AQ(J,V,Y.watch&&D?"-live":""),U=Y.compress&&f(j);if(qQ(Z,B,V)){let x=a(B,Y,D,V);if(U)x.set("Vary","Accept-Encoding");return new Response(null,{status:304,headers:x})}let O=a(B,Y,D,V);if(O.set("Content-Type",j),O.set("Accept-Ranges","bytes"),U)O.set("Vary","Accept-Encoding");let k=Z.headers.get("Range")&&vQ(Z,B,V)?Z.headers.get("Range"):null;if(k&&Z.method==="GET"){let x=$Z(k,J);if(x==="invalid")return O.set("Content-Range",`bytes */${J}`),new Response(null,{status:416,headers:O});if(x){let{start:_,end:I}=x,F=I-_+1;return O.set("Content-Range",`bytes ${_}-${I}/${J}`),O.set("Content-Length",String(F)),new Response(X.slice(_,I+1),{status:206,headers:O})}}if(Z.method==="HEAD")return O.set("Content-Length",String(J)),new Response(null,{status:200,headers:O});if(Y.watch&&D&&Z.method==="GET"){if(Y.compress&&f(j)){let _=await o(Q,Z,O,{key:`${W}\x00live`,size:J,mtimeMs:V},async()=>PQ.encode(A(await X.text())));if(_)return _}let x=A(await X.text());return O.set("Content-Length",String(Buffer.byteLength(x))),new Response(x,{status:200,headers:O})}if(Y.compress&&Z.method==="GET"&&f(j)&&J<2000000){let x=await o(Q,Z,O,{key:W,size:J,mtimeMs:V},async()=>new Uint8Array(await X.arrayBuffer()));if(x)return x}return O.set("Content-Length",String(J)),new Response(X,{status:200,headers:O})}function a(Q,Z,$,Y){let G=new Headers;if(G.set("ETag",Q),G.set("Last-Modified",new Date(Y).toUTCString()),Z.watch||!Z.cache||$)return G.set("Cache-Control","no-cache"),G;return G.set("Cache-Control","public, max-age=31536000, immutable"),G}function $Z(Q,Z){let $=/^bytes=(\d*)-(\d*)$/.exec(Q.trim());if(!$)return null;let Y=$[1],G=$[2],W,X;if(Y===""&&G==="")return"invalid";if(Y===""){let J=Number(G);if(!Number.isFinite(J)||J<=0)return"invalid";W=Math.max(0,Z-J),X=Z-1}else W=Number(Y),X=G===""?Z-1:Number(G);if(!Number.isFinite(W)||!Number.isFinite(X)||W<0||X<W||W>=Z)return"invalid";return X=Math.min(X,Z-1),{start:W,end:X}}function M(Q,Z){if(!Z.cors)return Q;return Q.headers.set("Access-Control-Allow-Origin","*"),Q.headers.set("Access-Control-Allow-Headers","*"),Q.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),Q}function T(Q,Z){if(Q!=="HEAD")return Z;return new Response(null,{status:Z.status,statusText:Z.statusText,headers:Z.headers})}export{h as startServer,KQ as serve,u as createHandler,P as RootError,m as DEFAULT_OPTIONS,E as BindError};
|
package/package.json
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "deserved",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "A tiny Bun static file server: SPA, live reload, zero dependencies",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"deserved": "./cli.js"
|
|
9
|
-
}
|
|
9
|
+
},
|
|
10
|
+
"module": "./index.js",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./index.js"
|
|
13
|
+
},
|
|
14
|
+
"main": "./index.js"
|
|
10
15
|
}
|