@histoire/dev-proxy 0.0.0-stage → 1.0.0-beta.3

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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/dist/appearance.d.ts +11 -0
  4. package/dist/appearance.js +11 -0
  5. package/dist/browser/chunks/transitions-3JvGwb-W.js +71 -0
  6. package/dist/browser/demo.js +50 -0
  7. package/dist/browser/lifecycle.js +55 -0
  8. package/dist/client/demo.d.ts +1 -0
  9. package/dist/client/demo.js +46 -0
  10. package/dist/client/lifecycle.d.ts +1 -0
  11. package/dist/client/lifecycle.js +73 -0
  12. package/dist/client/mark.d.ts +2 -0
  13. package/dist/client/mark.js +8 -0
  14. package/dist/client/page.d.ts +14 -0
  15. package/dist/client/page.js +18 -0
  16. package/dist/client/playground.d.ts +5 -0
  17. package/dist/client/playground.js +32 -0
  18. package/dist/client/status.d.ts +3 -0
  19. package/dist/client/status.js +9 -0
  20. package/dist/client/styles.d.ts +2 -0
  21. package/dist/client/styles.js +139 -0
  22. package/dist/client/transitions.d.ts +8 -0
  23. package/dist/client/transitions.js +45 -0
  24. package/dist/config/discovery.d.ts +12 -0
  25. package/dist/config/discovery.js +57 -0
  26. package/dist/config/index.d.ts +4 -0
  27. package/dist/config/index.js +4 -0
  28. package/dist/config/inputs.d.ts +18 -0
  29. package/dist/config/inputs.js +29 -0
  30. package/dist/config/snapshots.d.ts +16 -0
  31. package/dist/config/snapshots.js +25 -0
  32. package/dist/config/watcher.d.ts +12 -0
  33. package/dist/config/watcher.js +108 -0
  34. package/dist/index.d.ts +64 -0
  35. package/dist/index.js +303 -0
  36. package/dist/lifecycle/coordinator.d.ts +51 -0
  37. package/dist/lifecycle/coordinator.js +244 -0
  38. package/dist/lifecycle/index.d.ts +3 -0
  39. package/dist/lifecycle/index.js +2 -0
  40. package/dist/lifecycle/wait.d.ts +2 -0
  41. package/dist/lifecycle/wait.js +22 -0
  42. package/dist/process/child.d.ts +55 -0
  43. package/dist/process/child.js +191 -0
  44. package/dist/protocol.d.ts +182 -0
  45. package/dist/protocol.js +77 -0
  46. package/dist/server/events.d.ts +11 -0
  47. package/dist/server/events.js +37 -0
  48. package/dist/server/http.d.ts +19 -0
  49. package/dist/server/http.js +139 -0
  50. package/dist/server/listener.d.ts +5 -0
  51. package/dist/server/listener.js +53 -0
  52. package/dist/server/observe.d.ts +47 -0
  53. package/dist/server/observe.js +59 -0
  54. package/package.json +58 -3
@@ -0,0 +1,139 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { createServer } from 'node:http';
3
+ import { isIP } from 'node:net';
4
+ import { renderLoadingPage } from '../client/page.js';
5
+ import { designPlaygroundPath, renderDesignPlayground } from '../client/playground.js';
6
+ import { createStatusChannel } from './events.js';
7
+ import { observeRequest } from './observe.js';
8
+ /** Trust the published hostname and Vite's default local hosts for proxy-owned responses. */
9
+ function isTrustedHost(host, publicHostname) {
10
+ if (!host)
11
+ return false;
12
+ const hostname = (host.startsWith('[') ? host.slice(1, host.indexOf(']')) : host.replace(/:\d+$/, '')).toLowerCase();
13
+ return hostname === publicHostname || hostname === 'localhost' || hostname.endsWith('.localhost') || isIP(hostname) !== 0;
14
+ }
15
+ /** Stable HTTP listener delegates only after coherent generation readiness. */
16
+ export function createProxyHttp(read, restart, observer, readPublicHostname) {
17
+ /** Exchange counter; only used when an observer exists. */
18
+ let exchanges = 0;
19
+ let target;
20
+ let proxy;
21
+ const sockets = new Set();
22
+ const upgraded = new Set();
23
+ const events = createStatusChannel(read);
24
+ const assets = new Map();
25
+ const server = createServer(async (request, response) => {
26
+ const pathname = (request.url ?? '/').split('?')[0];
27
+ // Registered before any dispatch. Proxy-owned routes (status stream, loading assets, restart) are not traffic of the project.
28
+ const observation = observer && !pathname.startsWith('/__histoire/dev/') ? observeRequest(request, response, ++exchanges, observer) : undefined;
29
+ try {
30
+ // Proxied runtime requests keep Vite's own host policy; everything answered here is checked.
31
+ if (!(target && proxy && !pathname.startsWith('/__histoire/dev/')) && !isTrustedHost(request.headers.host, readPublicHostname?.())) {
32
+ response.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
33
+ response.end('Blocked host');
34
+ return;
35
+ }
36
+ if (pathname === '/__histoire/dev/restart' && request.method === 'POST') {
37
+ // Cross-site pages can send simple POSTs without reading responses; only accept own origin.
38
+ if (request.headers.origin !== `http://${request.headers.host}`) {
39
+ response.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' }).end('Cross-origin restart refused');
40
+ return;
41
+ }
42
+ // Outcome reaches the page over the status stream.
43
+ void restart().catch(() => { });
44
+ response.writeHead(202, { 'cache-control': 'no-store' }).end();
45
+ return;
46
+ }
47
+ if (pathname === '/__histoire/dev/events' && request.method === 'GET')
48
+ return events.connect(request, response);
49
+ if (pathname === designPlaygroundPath && ['GET', 'HEAD'].includes(request.method ?? '')) {
50
+ const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
51
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
52
+ response.end(request.method === 'HEAD' ? undefined : renderDesignPlayground(query, read()));
53
+ return;
54
+ }
55
+ if (pathname.startsWith('/__histoire/dev/')) {
56
+ const name = pathname.slice('/__histoire/dev/'.length);
57
+ // Entries share code through bundler chunks, which must be served next to them.
58
+ if (/^(?:lifecycle|demo|chunks\/[\w-]+)\.js$/.test(name) && ['GET', 'HEAD'].includes(request.method ?? '')) {
59
+ if (!assets.has(name))
60
+ assets.set(name, readFile(new URL(`../browser/${name}`, import.meta.url), 'utf8'));
61
+ const asset = await assets.get(name);
62
+ response.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
63
+ response.end(request.method === 'HEAD' ? undefined : asset);
64
+ return;
65
+ }
66
+ response.writeHead(404).end('Not found');
67
+ return;
68
+ }
69
+ if (target && proxy) {
70
+ await proxy.web(request, response, { target });
71
+ return;
72
+ }
73
+ const document = request.headers.accept?.includes('text/html') || request.headers['sec-fetch-dest'] === 'document';
74
+ // Fetch defaults to */* for extensionless APIs too. Only root has a
75
+ // document fallback; all other routes require explicit navigation intent.
76
+ const html = ['GET', 'HEAD'].includes(request.method ?? '') && (document || (pathname === '/' && !request.headers.accept?.includes('application/json')));
77
+ response.writeHead(html ? 200 : 503, { 'content-type': html ? 'text/html; charset=utf-8' : 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
78
+ response.end(request.method === 'HEAD' ? undefined : html ? renderLoadingPage(read()) : 'Histoire runtime unavailable');
79
+ }
80
+ catch {
81
+ // Appending text to a partially proxied body would corrupt it; abort instead.
82
+ if (response.headersSent) {
83
+ observation?.fail();
84
+ response.destroy();
85
+ return;
86
+ }
87
+ response.writeHead(503, { 'content-type': 'text/plain', 'cache-control': 'no-store' });
88
+ response.end('Histoire runtime unavailable');
89
+ }
90
+ });
91
+ server.on('connection', (socket) => {
92
+ sockets.add(socket);
93
+ socket.once('close', () => sockets.delete(socket));
94
+ });
95
+ server.on('upgrade', (request, socket, head) => {
96
+ if (!target || !proxy) {
97
+ socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
98
+ return;
99
+ }
100
+ upgraded.add(socket);
101
+ socket.once('close', () => upgraded.delete(socket));
102
+ void proxy.ws(request, socket, { target }, head).catch(() => socket.destroy());
103
+ });
104
+ return {
105
+ server,
106
+ events,
107
+ /** Forwarding library is deliberately absent from initial listener import graph. */
108
+ async prepare() {
109
+ proxy = (await import('httpxy')).createProxyServer({ xfwd: true, ws: true });
110
+ },
111
+ /** Withdraw target synchronously and retire old runtime WebSockets. */
112
+ setTarget(next) {
113
+ target = next;
114
+ if (!next) {
115
+ for (const socket of upgraded)
116
+ socket.destroy();
117
+ upgraded.clear();
118
+ }
119
+ },
120
+ /** Release the bound address while keeping the server reusable for another bind. */
121
+ async unlisten() {
122
+ if (!server.listening)
123
+ return;
124
+ const closing = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
125
+ for (const socket of sockets)
126
+ socket.destroy();
127
+ await closing;
128
+ },
129
+ /** Join listener close after terminating owned streams and idle connections. */
130
+ async close() {
131
+ target = undefined;
132
+ events.close();
133
+ const closing = server.listening ? new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())) : Promise.resolve();
134
+ for (const socket of sockets)
135
+ socket.destroy();
136
+ await closing;
137
+ },
138
+ };
139
+ }
@@ -0,0 +1,5 @@
1
+ import type { Server } from 'node:http';
2
+ /** Check the effective port before opening or moving a listener. */
3
+ export declare function assertValidPort(port: unknown): asserts port is number;
4
+ /** Binds public address before any project modules load, retaining occupied-port fallback. */
5
+ export declare function listen(server: Server, port: number, host?: string | boolean): Promise<string>;
@@ -0,0 +1,53 @@
1
+ import { isIP } from 'node:net';
2
+ /** Check the effective port before opening or moving a listener. */
3
+ export function assertValidPort(port) {
4
+ if (typeof port !== 'number' || !Number.isInteger(port) || port < 0 || port > 65535)
5
+ throw new Error('Port must be an integer from 0 to 65535');
6
+ }
7
+ /** Host handed to `server.listen`; undefined binds every interface. */
8
+ function getBindHost(host) {
9
+ if (typeof host === 'string')
10
+ return host;
11
+ return host ? undefined : 'localhost';
12
+ }
13
+ /** Host shown in the public origin; a name is kept so `localhost` never becomes `[::1]`, which Vite mangles in asset URLs. */
14
+ function getPublicHost(bindHost, address) {
15
+ if (bindHost && !isIP(bindHost))
16
+ return bindHost;
17
+ if (['::', '0.0.0.0'].includes(address))
18
+ return 'localhost';
19
+ return address.includes(':') ? `[${address}]` : address;
20
+ }
21
+ /** Binds public address before any project modules load, retaining occupied-port fallback. */
22
+ export async function listen(server, port, host = 'localhost') {
23
+ assertValidPort(port);
24
+ const bindHost = getBindHost(host);
25
+ for (;;) {
26
+ try {
27
+ await new Promise((resolve, reject) => {
28
+ /** Rejects this bind attempt and drops its success listener. */
29
+ function failed(error) {
30
+ server.off('listening', ready);
31
+ reject(error);
32
+ }
33
+ /** Resolves this bind attempt and drops its failure listener. */
34
+ function ready() {
35
+ server.off('error', failed);
36
+ resolve();
37
+ }
38
+ server.once('error', failed).once('listening', ready);
39
+ server.listen(port, bindHost);
40
+ });
41
+ break;
42
+ }
43
+ catch (error) {
44
+ if (error.code !== 'EADDRINUSE' || port === 0 || port >= 65535)
45
+ throw error;
46
+ port++;
47
+ }
48
+ }
49
+ const address = server.address();
50
+ if (!address || typeof address === 'string')
51
+ throw new Error('Unable to resolve Histoire proxy address');
52
+ return `http://${getPublicHost(bindHost, address.address)}:${address.port}`;
53
+ }
@@ -0,0 +1,47 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** How a public HTTP exchange ended. */
3
+ export type ProxyRequestOutcome = 'completed' | 'failed' | 'aborted';
4
+ /**
5
+ * Framework-neutral observation of one public HTTP exchange. Carries no query, header,
6
+ * cookie or body: only what is needed to list real traffic. `key` is unique per proxy
7
+ * and joins the two phases of one exchange.
8
+ */
9
+ export type ProxyRequestEvent = {
10
+ phase: 'start';
11
+ key: number;
12
+ method: string;
13
+ pathname: string;
14
+ } | {
15
+ phase: 'end';
16
+ key: number;
17
+ method: string;
18
+ pathname: string;
19
+ status?: number;
20
+ outcome: ProxyRequestOutcome;
21
+ durationMs: number;
22
+ };
23
+ /** Receives request events; failures of the observer never reach the HTTP exchange. */
24
+ export type ProxyRequestObserver = (event: ProxyRequestEvent) => void;
25
+ /** Handle returned for an observed exchange. */
26
+ export interface RequestObservation {
27
+ /** Marks the exchange as failed by the proxy itself (e.g. it destroyed a half-sent response). */
28
+ fail: () => void;
29
+ }
30
+ /**
31
+ * Pathname of a request target without query or fragment. Handles origin-form and
32
+ * absolute-form targets; anything unparseable becomes `/`.
33
+ * @param target Raw `request.url`.
34
+ */
35
+ export declare function pathnameOf(target: string | undefined): string;
36
+ /**
37
+ * Observes one exchange. Must be called before the request is dispatched, so every
38
+ * outcome is seen. Registers a single `close` listener on the response, which Node emits
39
+ * after a normal finish and also when the client connection ends early; `finished` guards
40
+ * against a second emission. An exchange whose response was not completely written when
41
+ * `close` fired is `aborted`, even if backend work finishes later.
42
+ * @param request Incoming request (only method and target are read).
43
+ * @param response Outgoing response (never wrapped or modified).
44
+ * @param key Unique exchange key.
45
+ * @param observer Consumer of the events.
46
+ */
47
+ export declare function observeRequest(request: IncomingMessage, response: ServerResponse, key: number, observer: ProxyRequestObserver): RequestObservation;
@@ -0,0 +1,59 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ /** Longest pathname handed to observers; a longer one is cut (retention is bounded again by consumers). */
3
+ const PATHNAME_MAX = 2048;
4
+ /**
5
+ * Pathname of a request target without query or fragment. Handles origin-form and
6
+ * absolute-form targets; anything unparseable becomes `/`.
7
+ * @param target Raw `request.url`.
8
+ */
9
+ export function pathnameOf(target) {
10
+ let path = target ?? '/';
11
+ if (!path.startsWith('/')) {
12
+ try {
13
+ path = new URL(path).pathname;
14
+ }
15
+ catch {
16
+ return '/';
17
+ }
18
+ }
19
+ const cut = path.search(/[?#]/);
20
+ return (cut === -1 ? path : path.slice(0, cut)).slice(0, PATHNAME_MAX);
21
+ }
22
+ /** Observer faults (including rejected promises) must not alter forwarding, nor produce diagnostics of their own. */
23
+ function emit(observer, event) {
24
+ try {
25
+ const result = observer(event);
26
+ if (result && typeof result.catch === 'function')
27
+ result.catch(() => { });
28
+ }
29
+ catch { }
30
+ }
31
+ /**
32
+ * Observes one exchange. Must be called before the request is dispatched, so every
33
+ * outcome is seen. Registers a single `close` listener on the response, which Node emits
34
+ * after a normal finish and also when the client connection ends early; `finished` guards
35
+ * against a second emission. An exchange whose response was not completely written when
36
+ * `close` fired is `aborted`, even if backend work finishes later.
37
+ * @param request Incoming request (only method and target are read).
38
+ * @param response Outgoing response (never wrapped or modified).
39
+ * @param key Unique exchange key.
40
+ * @param observer Consumer of the events.
41
+ */
42
+ export function observeRequest(request, response, key, observer) {
43
+ const startedAt = performance.now();
44
+ const method = (request.method ?? 'GET').slice(0, 32);
45
+ const pathname = pathnameOf(request.url);
46
+ let finished = false;
47
+ let failed = false;
48
+ emit(observer, { phase: 'start', key, method, pathname });
49
+ response.once('close', () => {
50
+ if (finished)
51
+ return;
52
+ finished = true;
53
+ const complete = response.writableFinished;
54
+ const status = response.headersSent ? response.statusCode : undefined;
55
+ const outcome = !complete && !failed ? 'aborted' : failed || (status !== undefined && status >= 500) ? 'failed' : 'completed';
56
+ emit(observer, { phase: 'end', key, method, pathname, ...(status === undefined ? {} : { status }), outcome, durationMs: Math.round((performance.now() - startedAt) * 10) / 10 });
57
+ });
58
+ return { fail: () => void (failed = true) };
59
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@histoire/dev-proxy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "1.0.0-beta.3",
5
+ "description": "Early HTTP hosting and process lifecycle for Histoire development",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Akryum/histoire.git",
10
+ "directory": "packages/histoire-dev-proxy"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./lifecycle": {
21
+ "types": "./dist/lifecycle/index.d.ts",
22
+ "default": "./dist/lifecycle/index.js"
23
+ },
24
+ "./config": {
25
+ "types": "./dist/config/index.d.ts",
26
+ "default": "./dist/config/index.js"
27
+ },
28
+ "./protocol": {
29
+ "types": "./dist/protocol.d.ts",
30
+ "default": "./dist/protocol.js"
31
+ },
32
+ "./appearance": {
33
+ "types": "./dist/appearance.d.ts",
34
+ "default": "./dist/appearance.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22.12.0"
42
+ },
43
+ "dependencies": {
44
+ "chokidar": "^4.0.1",
45
+ "httpxy": "^0.1.7",
46
+ "open": "^10.2.0"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.10.1",
50
+ "@typescript/native": "npm:typescript@7.0.2",
51
+ "concurrently": "^9.1.0",
52
+ "typescript": "npm:@typescript/typescript6@6.0.2",
53
+ "vite": "^8.3.5",
54
+ "vitest": "5.1.1"
55
+ },
56
+ "scripts": {
57
+ "build": "rimraf dist && tsc && vite build",
58
+ "watch": "concurrently \"tsc -w\" \"vite build --watch\"",
59
+ "test": "vitest run"
60
+ }
6
61
  }