deserved 0.6.0 → 0.6.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # deserved
2
2
 
3
- Tiny (8.7 kB gzip), zero-dep Bun static server.
3
+ A tiny Bun static file server: SPA, live reload, zero dependencies.
4
4
 
5
5
  ```bash
6
6
  bunx deserved .
@@ -51,9 +51,9 @@ bunx deserved dist --watch
51
51
  PORT=8080 bunx deserved dist
52
52
  ```
53
53
 
54
- The default port (`3000`, or `$PORT` if set) hops to the next free port (up
55
- to 10 tries) if it's taken; an explicit `--port` never does — it fails
56
- cleanly instead.
54
+ The default port (`3000`, or `$PORT` if set) hops to the next free port
55
+ (up to 10 tries) if it's taken; an explicit `--port` never does:
56
+ it fails cleanly instead.
57
57
 
58
58
  ## Programmatic use
59
59
 
@@ -65,17 +65,21 @@ console.log(server.url);
65
65
  await server.stop();
66
66
  ```
67
67
 
68
- `serve()` accepts a `Partial<Options>`, merged over the same defaults as the
69
- CLI (`DEFAULT_OPTIONS`). It resolves to `{ port, hostname, url, stop() }`;
70
- `stop()` closes the server and, if `watch: true` was passed, the file
71
- watcher. Unlike the CLI, a bind failure (e.g. a port already in use) rejects
72
- the promise instead of exiting the process. A `port` passed to `serve()` is
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):
68
+ `serve()` accepts a `Partial<Options>`,
69
+ merged over the same defaults as the CLI (`DEFAULT_OPTIONS`).
70
+ It resolves to `{ port, hostname, url, stop() }`;
71
+ `stop()` closes the server and, if `watch: true` was passed,
72
+ the file watcher.
73
+ Unlike the CLI, a bind failure (a port already in use) rejects the
74
+ promise instead of exiting the process.
75
+ A `port` passed to `serve()` is always treated as explicit:
76
+ it never hops to another port.
77
+ `quiet: true` silences all output, including the startup banner.
78
+
79
+ To mount the file server inside your own `Bun.serve()`,
80
+ use the request handler directly
81
+ (it takes the same `Partial<Options>`; `watch` needs `serve()`, which
82
+ owns the file watcher):
79
83
 
80
84
  ```ts
81
85
  import { createHandler } from "deserved";
@@ -91,10 +95,13 @@ Bun.serve({ fetch: createHandler({ root: "dist", spa: true, quiet: true }) });
91
95
  - Range requests (`206`) for media
92
96
  - SPA mode (HTML Accept only; assets still 404)
93
97
  - Custom `404.html` for browser requests
94
- - Optional live reload (`--watch`) via Server-Sent Events; tabs reconnect and reload after a server restart
95
- - CSS-only changes hot-swap stylesheets in place instead of a full page reload
98
+ - Optional live reload (`--watch`) via Server-Sent Events;
99
+ tabs reconnect and reload after a server restart
100
+ - CSS-only changes hot-swap stylesheets in place instead of a full page
101
+ reload
96
102
  - zstd or gzip compression, negotiated per request
97
- - Cache headers off by default (`no-cache`); opt in per-run with `--cache` for long-lived, immutable asset caching
103
+ - Cache headers off by default (`no-cache`);
104
+ opt in per-run with `--cache` for long-lived, immutable asset caching
98
105
  - Directory listings (disable with `--no-dir`)
99
106
  - Dotfiles (`.env`, `.git/`) are never served, except `/.well-known/`
100
107
  - Symlinks can't escape the served root
package/index.d.ts CHANGED
@@ -1,3 +1,62 @@
1
- export { createHandler } from "./handlers";
2
- export { DEFAULT_OPTIONS, type Options } from "./options";
3
- export { BindError, RootError, type ServerHandle, serve } from "./server";
1
+ export declare function createHandler(options?: Partial<Options>, hub?: Hub): Handler;
2
+ /** The server's settings; the CLI's flags set the same keys. */
3
+ export type Options = {
4
+ root: string;
5
+ port: number;
6
+ host: string;
7
+ spa: boolean;
8
+ watch: boolean;
9
+ open: boolean;
10
+ cors: boolean;
11
+ dir: boolean;
12
+ cache: boolean;
13
+ compress: boolean;
14
+ quiet: boolean;
15
+ };
16
+ type Hub = ReturnType<typeof createSseHub>;
17
+ declare function createSseHub(): {
18
+ subscribe: () => Response;
19
+ broadcast: (data?: string) => void;
20
+ close: () => void;
21
+ };
22
+ type Handler = {
23
+ (req: Request): Promise<Response>;
24
+ invalidateResolutionCache(): void;
25
+ invalidateCompressedCache(): void;
26
+ resolutionCacheSize(): number;
27
+ compressedCacheBytes(): number;
28
+ };
29
+ /** The settings `serve()` and the CLI start from. */
30
+ export declare const DEFAULT_OPTIONS: {
31
+ root: string;
32
+ port: number;
33
+ host: string;
34
+ spa: false;
35
+ watch: false;
36
+ open: false;
37
+ cors: false;
38
+ dir: true;
39
+ cache: false;
40
+ compress: true;
41
+ quiet: false;
42
+ };
43
+ /** The server couldn't listen on the host and port. */
44
+ export declare class BindError extends Error {
45
+ constructor(host: string, port: number, options?: ErrorOptions);
46
+ }
47
+ /** The root to serve doesn't exist or isn't a directory. */
48
+ export declare class RootError extends Error {
49
+ constructor(message: string, options?: ErrorOptions);
50
+ }
51
+ /** A running server: where it listens, and `stop()` to close it. */
52
+ export type ServerHandle = {
53
+ port: number;
54
+ hostname: string;
55
+ url: string;
56
+ stop: () => Promise<void>;
57
+ };
58
+ /**
59
+ * Starts a server for `options.root`, over the defaults; a bind failure
60
+ * rejects instead of exiting.
61
+ */
62
+ export declare function serve(options?: Partial<Options>): Promise<ServerHandle>;
package/package.json CHANGED
@@ -1,23 +1,27 @@
1
1
  {
2
2
  "name": "deserved",
3
- "version": "0.6.0",
4
- "description": "A tiny Bun static file server: SPA, live reload, zero dependencies",
3
+ "version": "0.6.1",
4
+ "description": "A tiny Bun static file server: SPA, live reload, zero dependencies.",
5
5
  "license": "MIT",
6
- "type": "module",
7
- "bin": {
8
- "deserved": "./cli.js"
6
+ "author": "Eric Liu (https://github.com/metonym)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/metonym/deserved.git"
9
10
  },
10
- "module": "./index.js",
11
+ "homepage": "https://github.com/metonym/deserved",
12
+ "bugs": "https://github.com/metonym/deserved/issues",
13
+ "type": "module",
11
14
  "exports": {
12
15
  ".": {
13
16
  "types": "./index.d.ts",
14
- "default": "./index.js"
15
- }
17
+ "default": "./src/index.ts"
18
+ },
19
+ "./package.json": "./package.json"
16
20
  },
17
- "repository": {
18
- "type": "git",
19
- "url": "https://github.com/metonym/deserved"
21
+ "bin": {
22
+ "deserved": "src/cli.ts"
20
23
  },
21
- "main": "./index.js",
22
- "types": "./index.d.ts"
24
+ "engines": {
25
+ "bun": ">=1.4.0"
26
+ }
23
27
  }
package/src/cli.ts ADDED
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env bun
2
+ import { resolve } from "node:path";
3
+
4
+ import { version as VERSION } from "../package.json";
5
+ import { DEFAULT_OPTIONS, type Options } from "./options";
6
+ import { BindError, RootError, startServer } from "./server";
7
+
8
+ function printHelp() {
9
+ console.log(`
10
+ deserved - tiny Bun static file server
11
+
12
+ Usage
13
+ deserved [path] [options]
14
+
15
+ Options
16
+ -p, --port <n> Port (default: 3000, or $PORT; hops to the next
17
+ free port unless set explicitly)
18
+ -H, --host <host> Hostname (default: localhost)
19
+ -s, --spa SPA fallback to index.html
20
+ -w, --watch Live reload on file changes
21
+ -o, --open Open browser
22
+ --cors Enable CORS
23
+ --dir Enable directory listing (default)
24
+ --no-dir Disable directory listing
25
+ --cache Long-lived, immutable cache headers for assets
26
+ --no-cache Disable cache headers (default)
27
+ --compress zstd or gzip, negotiated per request (default)
28
+ --no-compress Disable compression
29
+ -q, --quiet Suppress request logs
30
+ -h, --help Show help
31
+ -v, --version Show version
32
+
33
+ Examples
34
+ deserved .
35
+ deserved dist --spa
36
+ deserved dist --port 8080
37
+ deserved docs --watch --open
38
+ PORT=8080 deserved dist
39
+ `);
40
+ }
41
+
42
+ type CliOptions = Options & { portExplicit: boolean };
43
+
44
+ type BooleanOption = {
45
+ [K in keyof Options]: Options[K] extends boolean ? K : never;
46
+ }[keyof Options];
47
+
48
+ // A Map, not an object literal, so arguments like `constructor` or
49
+ // `__proto__` can't hit prototype keys.
50
+ const BOOLEAN_FLAGS = new Map<string, [BooleanOption, boolean]>([
51
+ ["-s", ["spa", true]],
52
+ ["--spa", ["spa", true]],
53
+ ["-w", ["watch", true]],
54
+ ["--watch", ["watch", true]],
55
+ ["-o", ["open", true]],
56
+ ["--open", ["open", true]],
57
+ ["--cors", ["cors", true]],
58
+ ["--dir", ["dir", true]],
59
+ ["--no-dir", ["dir", false]],
60
+ ["--cache", ["cache", true]],
61
+ ["--no-cache", ["cache", false]],
62
+ ["--compress", ["compress", true]],
63
+ ["--no-compress", ["compress", false]],
64
+ ["-q", ["quiet", true]],
65
+ ["--quiet", ["quiet", true]],
66
+ ]);
67
+
68
+ const VALUE_FLAGS = new Map<string, "port" | "host">([
69
+ ["-p", "port"],
70
+ ["--port", "port"],
71
+ ["-H", "host"],
72
+ ["--host", "host"],
73
+ ]);
74
+
75
+ export function parseArgs(
76
+ argv: string[],
77
+ env: Record<string, string | undefined> = Bun.env,
78
+ ): CliOptions {
79
+ const args = argv.slice(2);
80
+ const opts: Options = { ...DEFAULT_OPTIONS };
81
+ let root: string | undefined;
82
+ let portFlagSet = false;
83
+
84
+ for (let i = 0; i < args.length; i++) {
85
+ const a = args[i];
86
+ if (a === undefined) break;
87
+
88
+ if (a === "-h" || a === "--help") {
89
+ printHelp();
90
+ process.exit(0);
91
+ }
92
+ if (a === "-v" || a === "--version") {
93
+ console.log(VERSION);
94
+ process.exit(0);
95
+ }
96
+
97
+ const bool = BOOLEAN_FLAGS.get(a);
98
+ if (bool) {
99
+ opts[bool[0]] = bool[1];
100
+ continue;
101
+ }
102
+
103
+ // `--port=8080` carries its value inline; `-p 8080` takes the next arg.
104
+ const eq = a.startsWith("--") ? a.indexOf("=") : -1;
105
+ const flag = eq === -1 ? a : a.slice(0, eq);
106
+ const key = VALUE_FLAGS.get(flag);
107
+ if (key) {
108
+ const value = eq === -1 ? args[++i] : a.slice(eq + 1);
109
+ if (!value || (eq === -1 && value.startsWith("-"))) {
110
+ fail(`Missing value for ${flag}`);
111
+ }
112
+ if (key === "port") {
113
+ opts.port = parsePort(value, eq === -1 ? value : a);
114
+ portFlagSet = true;
115
+ } else {
116
+ opts.host = value;
117
+ }
118
+ continue;
119
+ }
120
+
121
+ if (a.startsWith("-")) fail(`Unknown option: ${a}`);
122
+ if (root !== undefined) fail(`Unexpected argument: ${a}`);
123
+ root = a;
124
+ }
125
+
126
+ if (!portFlagSet && env.PORT !== undefined) {
127
+ opts.port = parsePort(env.PORT, env.PORT);
128
+ }
129
+ opts.root = resolve(root ?? opts.root);
130
+ return { ...opts, portExplicit: portFlagSet };
131
+ }
132
+
133
+ // `shown` is what the error message echoes back (the whole `--port=x` flag
134
+ // for the inline form, the bare value otherwise).
135
+ function parsePort(value: string, shown: string): number {
136
+ const n = Number(value);
137
+ if (value.trim() === "" || !Number.isInteger(n) || n < 0 || n > 65535)
138
+ fail(`Invalid port: ${shown}`);
139
+ return n;
140
+ }
141
+
142
+ function fail(msg: string): never {
143
+ console.error(`Error: ${msg}`);
144
+ console.error("Run deserved --help.");
145
+ process.exit(1);
146
+ }
147
+
148
+ if (import.meta.main) {
149
+ const opts = parseArgs(process.argv);
150
+
151
+ let handle: Awaited<ReturnType<typeof startServer>>;
152
+ try {
153
+ handle = await startServer(opts, { portExplicit: opts.portExplicit });
154
+ } catch (err) {
155
+ if (err instanceof RootError) {
156
+ console.error(`Error: ${err.message}`);
157
+ console.error("Run deserved --help.");
158
+ process.exit(1);
159
+ }
160
+ if (err instanceof BindError) {
161
+ console.error(`Error: ${err.message}`);
162
+ console.error(
163
+ err.cause instanceof Error ? err.cause.message : String(err.cause),
164
+ );
165
+ process.exit(1);
166
+ }
167
+ throw err;
168
+ }
169
+
170
+ const shutdown = async () => {
171
+ await handle.stop();
172
+ process.exit(0);
173
+ };
174
+ process.on("SIGINT", shutdown);
175
+ process.on("SIGTERM", shutdown);
176
+ }