deserved 0.1.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/LICENSE +21 -0
- package/README.md +61 -0
- package/cli.js +60 -0
- package/package.json +10 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eric Liu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# deserved
|
|
2
|
+
|
|
3
|
+
Tiny, zero-dependency Bun static file server.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bunx deserved .
|
|
7
|
+
bunx deserved dist --spa
|
|
8
|
+
bunx deserved dist --watch --open
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
bun add -g deserved
|
|
15
|
+
# or one-shot
|
|
16
|
+
bunx deserved dist --spa
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bunx deserved [path] [options]
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
| Flag | Description |
|
|
26
|
+
|------|-------------|
|
|
27
|
+
| `-p, --port <n>` | Port (default `3000`) |
|
|
28
|
+
| `-H, --host <host>` | Hostname (default `localhost`) |
|
|
29
|
+
| `-s, --spa` | SPA fallback to `index.html` |
|
|
30
|
+
| `-w, --watch` | Live reload via SSE |
|
|
31
|
+
| `-o, --open` | Open the browser |
|
|
32
|
+
| `--cors` | Enable CORS |
|
|
33
|
+
| `--no-dir` | Disable directory listing |
|
|
34
|
+
| `--no-cache` | Disable cache headers |
|
|
35
|
+
| `--no-compress` | Disable gzip |
|
|
36
|
+
| `-q, --quiet` | Suppress request logs |
|
|
37
|
+
|
|
38
|
+
## Examples
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
bunx deserved .
|
|
42
|
+
bunx deserved dist
|
|
43
|
+
bunx deserved dist --spa
|
|
44
|
+
bunx deserved dist --port 8080
|
|
45
|
+
bunx deserved dist --host 0.0.0.0
|
|
46
|
+
bunx deserved dist --open
|
|
47
|
+
bunx deserved dist --cors
|
|
48
|
+
bunx deserved dist --watch
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Features
|
|
52
|
+
|
|
53
|
+
- `Bun.file()` / `Bun.serve()`: no streams plumbing
|
|
54
|
+
- ETag + `304`
|
|
55
|
+
- Range requests (`206`) for media
|
|
56
|
+
- SPA mode (HTML Accept only; assets still 404)
|
|
57
|
+
- Optional live reload (`--watch`) via Server-Sent Events
|
|
58
|
+
- Gzip compression
|
|
59
|
+
- Smart cache headers (HTML `no-cache`, assets long-lived)
|
|
60
|
+
- Directory listings (disable with `--no-dir`)
|
|
61
|
+
- Colored request logs
|
package/cli.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
import{resolve as M0}from"path";var L="0.1.0";import{watch as j0}from"fs";import{networkInterfaces as I0}from"os";import{relative as V0,resolve as E0}from"path";import{readdirSync as o,realpathSync as z,statSync as A}from"fs";import{extname as r,join as s,normalize as t,resolve as S,sep as c}from"path";var{escapeHTML:_}=globalThis.Bun;var a=new TextEncoder,T="application/octet-stream",e={".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 u0(u,$){let O=u.type;if(O&&O!==T&&O!=="")return O;let D=r($).toLowerCase();return e[D]??T}function M(u){let $=u.split(";")[0]?.trim().toLowerCase()??"";return $.startsWith("text/")||$==="application/javascript"||$==="text/javascript"||$==="application/json"||$==="application/xml"||$==="image/svg+xml"||$.endsWith("+json")||$.endsWith("+xml")}function $0(u){return u.startsWith("text/html")}function O0(u,$,O=""){return`"${u}-${Math.trunc($)}${O}"`}function W0(u,$){let O=u.headers.get("If-None-Match");if(!O)return!1;return O.split(",").some((D)=>D.trim().replace(/^W\//,"")===$)}function D0(u,$){let O=u.headers.get("If-Modified-Since");if(!O)return!1;let D=Date.parse(O);if(Number.isNaN(D))return!1;return Math.trunc($/1000)*1000<=D}function Q0(u,$,O){return u.headers.get("If-None-Match")?W0(u,$):D0(u,O)}function Y0(u){let $=u.headers.get("Accept");if(!$||$==="*/*")return!0;return $.includes("text/html")||$.includes("application/xhtml")}function Z0(u){return(u.headers.get("Accept-Encoding")??"").includes("gzip")}function X0(u){if(u.startsWith("/__"))return!1;let $=u.slice(u.lastIndexOf("/")+1);if(!$)return!0;if($.includes("."))return!1;return!0}function H(u,$){let O=S(u),D=i(O);if(!D)return null;let Z=$.replace(/^\/+/,""),Q=G0(Z);for(let W of Q){let k=b(O,W);if(!k)continue;let B=R(D,k);if(!B)continue;try{let X=A(B);if(X.isFile())return{path:B,file:Bun.file(B),size:X.size,mtimeMs:X.mtimeMs}}catch{}}return null}function G0(u){if(!u||u===".")return["index.html"];let $=u.endsWith("/")?u.slice(0,-1):u;if(!$)return["index.html"];if(u.endsWith("/"))return[`${$}/index.html`];return[$,`${$}.html`,`${$}/index.html`]}function b(u,$){let O=S(u),D=t(s(O,$));if(D!==O&&!D.startsWith(O+c))return null;return D}function R(u,$){try{let O=z($);if(O!==u&&!O.startsWith(u+c))return null;return O}catch{return null}}var n=new Map;function i(u){let $=n.get(u);if($===void 0){try{$=z(u)}catch{$=null}n.set(u,$)}return $}function N0(u,$){let O=S(u),D=i(O);if(!D)return null;let Z=$.replace(/^\/+/,"").replace(/\/+$/,""),Q=b(O,Z||".");if(!Q)return null;let W=R(D,Q);if(!W)return null;try{if(A(W).isDirectory())return W}catch{return null}return null}function k0(u){return o(u,{withFileTypes:!0}).filter(($)=>!$.name.startsWith(".")).map(($)=>({name:$.name,dir:$.isDirectory()})).sort(($,O)=>{if($.dir!==O.dir)return $.dir?-1:1;return $.name.localeCompare(O.name)})}function x0(u,$){let O=u.endsWith("/")?u:`${u}/`,D=B0(u),Z=$.map((W)=>{let k=J0(O,W.name)+(W.dir?"/":""),B=W.dir?`${W.name}/`:W.name;return` <li><a href="${_(k)}">${_(B)}</a></li>`}).join(`
|
|
4
|
+
`),Q=D!==null?` <li><a href="${_(D)}">../</a></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 ${_(u)}</title>
|
|
11
|
+
<style>
|
|
12
|
+
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
13
|
+
body { max-width: 40rem; 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; }
|
|
17
|
+
a { color: inherit; text-decoration: none; }
|
|
18
|
+
a:hover { text-decoration: underline; }
|
|
19
|
+
</style>
|
|
20
|
+
</head>
|
|
21
|
+
<body>
|
|
22
|
+
<h1>Index of ${_(u||"/")}</h1>
|
|
23
|
+
<ul>
|
|
24
|
+
${Q}${Z}
|
|
25
|
+
</ul>
|
|
26
|
+
</body>
|
|
27
|
+
</html>
|
|
28
|
+
`}function B0(u){if(u==="/"||u==="")return null;let $=u.replace(/\/+$/,""),O=$.lastIndexOf("/");if(O<=0)return"/";return $.slice(0,O+1)}function J0(u,$){if(u==="/")return`/${$}`;return`${u.replace(/\/+$/,"")}/${$}`}function q(u,$){return async function(D){let Z=new URL(D.url),Q=decodeURIComponent(Z.pathname),W=D.method.toUpperCase();if(W!=="GET"&&W!=="HEAD"){let X=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return I(W,405,Q,u.quiet),j(X,u)}if(u.watch&&Q===P){let X=new Response(d,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return I(W,200,Q,u.quiet),E(W,j(X,u))}if(u.watch&&Q===f&&$){let X=$.subscribe();return I(W,200,Q,u.quiet),j(X,u)}if(Q===P||Q===f)return E(W,j(new Response("Not Found",{status:404}),u));let k=H(u.root,Q);if(k){let X=await y(D,k,u);return I(W,X.status,Q,u.quiet),E(W,j(X,u))}if(u.spa&&Y0(D)&&X0(Q)){let X=H(u.root,"/");if(X){let U=await y(D,X,u,!0);return I(W,U.status,Q,u.quiet),E(W,j(U,u))}}if(u.dir){let X=N0(u.root,Q);if(X){let U=k0(X),G=x0(Q,U),K=u.watch?w(G):G,J=new Response(K,{headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return I(W,200,Q,u.quiet),E(W,j(J,u))}}let B=new Response("Not Found",{status:404});return I(W,404,Q,u.quiet),E(W,j(B,u))}}var v=new Map;async function K0(u,$){let O=v.get(u.key);if(O&&O.size===u.size&&O.mtimeMs===u.mtimeMs)return O.gz;try{let D=Bun.gzipSync(await $());return v.set(u.key,{size:u.size,mtimeMs:u.mtimeMs,gz:D}),D}catch{return null}}async function C(u,$,O,D){if(!Z0(u))return null;let Z=await K0(O,D);if(!Z)return null;return $.set("Content-Encoding","gzip"),$.set("Content-Length",String(Z.byteLength)),$.delete("Accept-Ranges"),$.append("Vary","Accept-Encoding"),new Response(Z,{status:200,headers:$})}async function y(u,$,O,D=!1){let{path:Z,file:Q,size:W,mtimeMs:k}=$,B=u0(Q,Z),X=D||$0(B),U=O0(W,k,O.watch&&X?"-live":"");if(Q0(u,U,k))return new Response(null,{status:304,headers:g(U,O,X,k)});let G=g(U,O,X,k);G.set("Content-Type",B),G.set("Accept-Ranges","bytes");let K=u.headers.get("Range");if(K&&u.method==="GET"){let J=U0(K,W);if(J==="invalid")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${W}`}});if(J){let{start:Y,end:x}=J,V=x-Y+1,l=await Q.slice(Y,x+1).arrayBuffer();return G.set("Content-Range",`bytes ${Y}-${x}/${W}`),G.set("Content-Length",String(V)),new Response(l,{status:206,headers:G})}}if(O.watch&&X&&u.method==="GET"){if(O.compress&&M(B)){let Y=await C(u,G,{key:`${Z}\x00live`,size:W,mtimeMs:k},async()=>a.encode(w(await Q.text())));if(Y)return Y}let J=w(await Q.text());return G.set("Content-Length",String(Buffer.byteLength(J))),new Response(J,{status:200,headers:G})}if(O.compress&&u.method==="GET"&&M(B)&&W<2000000){let J=await C(u,G,{key:Z,size:W,mtimeMs:k},async()=>new Uint8Array(await Q.arrayBuffer()));if(J)return J}return G.set("Content-Length",String(W)),new Response(Q,{status:200,headers:G})}function g(u,$,O,D){let Z=new Headers;if(Z.set("ETag",u),Z.set("Last-Modified",new Date(D).toUTCString()),$.watch||!$.cache||O)return Z.set("Cache-Control","no-cache"),Z;return Z.set("Cache-Control","public, max-age=31536000, immutable"),Z}function U0(u,$){let O=/^bytes=(\d*)-(\d*)$/.exec(u.trim());if(!O)return null;let D=O[1],Z=O[2],Q,W;if(D===""&&Z==="")return"invalid";if(D===""){let k=Number(Z);if(!Number.isFinite(k)||k<=0)return"invalid";Q=Math.max(0,$-k),W=$-1}else Q=Number(D),W=Z===""?$-1:Number(Z);if(!Number.isFinite(Q)||!Number.isFinite(W)||Q<0||W<Q||Q>=$)return"invalid";return W=Math.min(W,$-1),{start:Q,end:W}}function j(u,$){if(!$.cors)return u;let O=new Headers(u.headers);return O.set("Access-Control-Allow-Origin","*"),O.set("Access-Control-Allow-Headers","*"),O.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),new Response(u.body,{status:u.status,statusText:u.statusText,headers:O})}function E(u,$){if(u!=="HEAD")return $;return new Response(null,{status:$.status,statusText:$.statusText,headers:$.headers})}var P="/__live.js",f="/__events",d=`(()=>{const e=new EventSource("${f}");e.onmessage=()=>location.reload();e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,m=`<script src="${P}"></script>`;function w(u){let $=u.toLowerCase().lastIndexOf("</body>");if($===-1)return u+m;return u.slice(0,$)+m+u.slice($)}function _0(){let u=new Set,$=new TextEncoder;function O(){let Z,Q=new ReadableStream({start(W){Z=W,u.add(W),W.enqueue($.encode(`: connected
|
|
29
|
+
|
|
30
|
+
`))},cancel(){u.delete(Z)}});return new Response(Q,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function D(Z="reload"){let Q=$.encode(`data: ${Z}
|
|
31
|
+
|
|
32
|
+
`);for(let W of u)try{W.enqueue(Q)}catch{u.delete(W)}}return{subscribe:O,broadcast:D}}var N={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},F0=/[\x00-\x1f\x7f]/g;function P0(u){return u.replace(F0,"")}function I(u,$,O,D){if(D)return;let Z=$<300?`${N.green}\u2713${N.reset}`:$<400?`${N.yellow}\u25CB${N.reset}`:`${N.red}\u2717${N.reset}`;console.log(`${Z} ${N.dim}${u}${N.reset} ${$} ${P0(O)}`)}function f0(u,$=!1){if($)return;console.log(`${N.cyan}\u2502${N.reset} ${u}`)}function w0(){let u=I0();for(let $ of Object.values(u))for(let O of $??[])if(O.family==="IPv4"&&!O.internal)return O.address;return null}function S0(u,$,O,D){if(console.log(),console.log(` ${N.bold}deserved${N.reset} ${N.dim}serving${N.reset} ${$}`),console.log(` ${N.green}->${N.reset} ${N.cyan}${u}${N.reset}`),D)console.log(` ${N.green}->${N.reset} ${N.cyan}${D}${N.reset}`);if(O.length)console.log(` ${N.dim}${O.join(" ")}${N.reset}`);console.log()}function L0(u){if(u)return;console.log(`${N.yellow}*${N.reset} reload`)}async function T0(u){let $=process.platform;try{if($==="darwin")await Bun.spawn(["open",u],{stdout:"ignore",stderr:"ignore"}).exited;else if($==="win32")await Bun.spawn(["cmd","/c","start","",u],{stdout:"ignore",stderr:"ignore"}).exited;else await Bun.spawn(["xdg-open",u],{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${u}`)}}async function h(u){let $=E0(u.root),O=u.watch?_0():void 0,D=q({...u,root:$},O),Z=u.host==="localhost"?"127.0.0.1":u.host,Q;try{Q=Bun.serve({port:u.port,hostname:Z,fetch:async(K)=>{if(u.cors&&K.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 D(K)}})}catch(K){console.error(`Error: could not bind to ${u.host}:${u.port}`),console.error(K instanceof Error?K.message:String(K)),process.exit(1)}let W=u.host==="0.0.0.0"||u.host==="::",B=`http://${W?"localhost":u.host}:${Q.port}`,X=W?w0():null,U=X?`http://${X}:${Q.port}`:void 0,G=[];if(u.spa)G.push("--spa");if(u.watch)G.push("--watch");if(u.cors)G.push("--cors");if(!u.dir)G.push("--no-dir");if(!u.compress)G.push("--no-compress");if(!u.cache)G.push("--no-cache");if(S0(B,V0(process.cwd(),$)||".",G,U),u.watch&&O){let K=null,J=j0($,{recursive:!0},(Y,x)=>{if(x?.includes("node_modules")||x?.startsWith("."))return;if(K)clearTimeout(K);K=setTimeout(()=>{L0(u.quiet),O.broadcast("reload")},80)});process.on("SIGINT",()=>{J.close(),Q.stop(),process.exit(0)}),f0("watching for changes",u.quiet)}if(u.open)await T0(B);return Q}function H0(){console.log(`
|
|
33
|
+
deserved - tiny Bun static file server
|
|
34
|
+
|
|
35
|
+
Usage
|
|
36
|
+
deserved [path] [options]
|
|
37
|
+
|
|
38
|
+
Options
|
|
39
|
+
-p, --port <n> Port (default: 3000)
|
|
40
|
+
-H, --host <host> Hostname (default: localhost)
|
|
41
|
+
-s, --spa SPA fallback to index.html
|
|
42
|
+
-w, --watch Live reload on file changes
|
|
43
|
+
-o, --open Open browser
|
|
44
|
+
--cors Enable CORS
|
|
45
|
+
--dir Enable directory listing (default)
|
|
46
|
+
--no-dir Disable directory listing
|
|
47
|
+
--cache Cache headers (default)
|
|
48
|
+
--no-cache Disable cache headers
|
|
49
|
+
--compress Gzip (default)
|
|
50
|
+
--no-compress Disable compression
|
|
51
|
+
-q, --quiet Suppress request logs
|
|
52
|
+
-h, --help Show help
|
|
53
|
+
-v, --version Show version
|
|
54
|
+
|
|
55
|
+
Examples
|
|
56
|
+
deserved .
|
|
57
|
+
deserved dist --spa
|
|
58
|
+
deserved dist --port 8080
|
|
59
|
+
deserved docs --watch --open
|
|
60
|
+
`)}function n0(u){let $=u.slice(2),O=".",D=3000,Z="localhost",Q=!1,W=!1,k=!1,B=!1,X=!0,U=!0,G=!0,K=!1;for(let J=0;J<$.length;J++){let Y=$[J];if(Y===void 0)break;if(Y==="-h"||Y==="--help")H0(),process.exit(0);if(Y==="-v"||Y==="--version")console.log(L),process.exit(0);if(Y==="-s"||Y==="--spa"){Q=!0;continue}if(Y==="-w"||Y==="--watch"){W=!0;continue}if(Y==="-o"||Y==="--open"){k=!0;continue}if(Y==="--cors"){B=!0;continue}if(Y==="--dir"){X=!0;continue}if(Y==="--no-dir"){X=!1;continue}if(Y==="--cache"){U=!0;continue}if(Y==="--no-cache"){U=!1;continue}if(Y==="--compress"){G=!0;continue}if(Y==="--no-compress"){G=!1;continue}if(Y==="-q"||Y==="--quiet"){K=!0;continue}if(Y==="-p"||Y==="--port"){let x=$[++J];if(!x||x.startsWith("-"))F(`Missing value for ${Y}`);let V=Number(x);if(!Number.isInteger(V)||V<0||V>65535)F(`Invalid port: ${x}`);D=V;continue}if(Y==="-H"||Y==="--host"){let x=$[++J];if(!x||x.startsWith("-"))F(`Missing value for ${Y}`);Z=x;continue}if(Y.startsWith("--port=")){let x=Number(Y.slice(7));if(!Number.isInteger(x)||x<0||x>65535)F(`Invalid port: ${Y}`);D=x;continue}if(Y.startsWith("--host=")){Z=Y.slice(7);continue}if(Y.startsWith("-"))F(`Unknown option: ${Y}`);O=Y}return{root:M0(O),port:D,host:Z,spa:Q,watch:W,open:k,cors:B,dir:X,cache:U,compress:G,quiet:K}}function F(u){console.error(`Error: ${u}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let u=n0(process.argv);await h(u)}export{n0 as parseArgs};
|