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

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 +103 -0
  34. package/dist/index.d.ts +64 -0
  35. package/dist/index.js +272 -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 +53 -0
  43. package/dist/process/child.js +185 -0
  44. package/dist/protocol.d.ts +166 -0
  45. package/dist/protocol.js +75 -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 +17 -0
  49. package/dist/server/http.js +130 -0
  50. package/dist/server/listener.d.ts +3 -0
  51. package/dist/server/listener.js +34 -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,185 @@
1
+ import { fork, spawn } from 'node:child_process';
2
+ import { isChildMessage } from '../protocol.js';
3
+ /** Starts one IPC runtime and joins its entire lifetime before ownership transfer. */
4
+ export function startRuntimeChild(options) {
5
+ const diagnostic = options.onDiagnostic ?? ((message) => console.error(message));
6
+ /** Observer faults must never disturb process ownership. */
7
+ function guarded(action) {
8
+ try {
9
+ action();
10
+ }
11
+ catch (error) {
12
+ try {
13
+ diagnostic(`Histoire runtime observer failed: ${error instanceof Error ? error.message : String(error)}`);
14
+ }
15
+ catch { }
16
+ }
17
+ }
18
+ let retired = false;
19
+ /** Signals retirement exactly once. */
20
+ function retire() {
21
+ if (retired)
22
+ return;
23
+ retired = true;
24
+ if (options.onRetire)
25
+ guarded(options.onRetire);
26
+ }
27
+ const environment = { ...process.env };
28
+ delete environment.HISTOIRE_MCP_TOKEN;
29
+ const child = fork(options.entry, [], { cwd: options.root, env: environment, detached: process.platform !== 'win32', execArgv: [], stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
30
+ // Without an observer the streams keep their historical direct piping.
31
+ const outputListeners = [];
32
+ if (options.onOutput) {
33
+ const observe = options.onOutput;
34
+ for (const stream of ['stdout', 'stderr']) {
35
+ const source = child[stream];
36
+ const onData = (chunk) => guarded(() => observe({ stream, generation: options.generation, chunk }));
37
+ const onEnd = () => guarded(() => observe({ stream, generation: options.generation }));
38
+ source.on('data', onData);
39
+ source.once('end', onEnd);
40
+ outputListeners.push(() => {
41
+ source.off('data', onData);
42
+ source.off('end', onEnd);
43
+ });
44
+ }
45
+ }
46
+ else {
47
+ child.stdout.pipe(process.stdout, { end: false });
48
+ child.stderr.pipe(process.stderr, { end: false });
49
+ }
50
+ let closing;
51
+ let settled = false;
52
+ let backend;
53
+ let resolve;
54
+ let reject;
55
+ const ready = new Promise((yes, no) => {
56
+ resolve = yes;
57
+ reject = no;
58
+ });
59
+ void ready.catch(() => {
60
+ });
61
+ const exited = new Promise(resolve => child.once('exit', () => resolve()));
62
+ let messages = Promise.resolve();
63
+ child.on('error', reject);
64
+ child.on('message', (raw) => {
65
+ if (!isChildMessage(raw) || raw.generation !== options.generation || closing)
66
+ return;
67
+ if (raw.type === 'restart') {
68
+ // Only a served generation may ask; startup failures already report through `failed`.
69
+ if (settled && options.onRestartRequest)
70
+ guarded(() => options.onRestartRequest({ source: raw.source, fresh: raw.fresh === true }));
71
+ return;
72
+ }
73
+ if (raw.type === 'runtime-reply' || raw.type === 'runtime-event') {
74
+ // Runtime traffic is independent of the startup message chain.
75
+ if (options.onRuntimeMessage)
76
+ guarded(() => options.onRuntimeMessage(raw));
77
+ return;
78
+ }
79
+ messages = messages.then(async () => {
80
+ if (closing)
81
+ return;
82
+ if (raw.type === 'watch')
83
+ await options.onWatch(raw.inputs, raw.complete === true);
84
+ if (raw.type === 'failed')
85
+ reject(new Error(raw.error));
86
+ if (raw.type === 'ready') {
87
+ await options.onReady?.();
88
+ if (closing)
89
+ return;
90
+ backend = raw;
91
+ settled = true;
92
+ resolve();
93
+ }
94
+ }).catch(reject);
95
+ });
96
+ child.once('exit', (code, signal) => {
97
+ retire();
98
+ const error = new Error(`Histoire runtime exited (${signal ?? code ?? 'unknown'})`);
99
+ reject(error);
100
+ if (settled && !closing)
101
+ options.onExit(error);
102
+ });
103
+ const message = { type: 'start', generation: options.generation, publicOrigin: options.publicOrigin, options: options.options, token: options.token };
104
+ child.send(message, error => error && reject(error));
105
+ /** Waits bounded time without retaining a timer once process exits. */
106
+ async function wait(milliseconds) {
107
+ if (child.exitCode !== null || child.signalCode !== null)
108
+ return true;
109
+ let timer;
110
+ try {
111
+ return await Promise.race([exited.then(() => true), new Promise((resolve) => {
112
+ timer = setTimeout(() => resolve(false), milliseconds);
113
+ })]);
114
+ }
115
+ finally {
116
+ clearTimeout(timer);
117
+ }
118
+ }
119
+ /** Kills only this detached ownership group, including ordinary runtime descendants. */
120
+ async function killTree() {
121
+ if (!child.pid)
122
+ return;
123
+ if (process.platform === 'win32') {
124
+ await new Promise((resolve, reject) => {
125
+ const kill = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
126
+ kill.once('error', reject);
127
+ kill.once('exit', code => code === 0 ? resolve() : reject(new Error('Unable to terminate Histoire runtime tree')));
128
+ });
129
+ }
130
+ else {
131
+ try {
132
+ process.kill(-child.pid, 'SIGKILL');
133
+ }
134
+ catch (error) {
135
+ if (error.code !== 'ESRCH')
136
+ throw error;
137
+ }
138
+ }
139
+ }
140
+ return {
141
+ ready,
142
+ /** Latest backend metadata remains private to parent proxy. */
143
+ get backend() {
144
+ return backend;
145
+ },
146
+ /** Process identity used only by parent diagnostics and ownership tests. */
147
+ pid: child.pid,
148
+ /** Hands a command to this process; resolves once IPC accepted the frame. */
149
+ sendRuntimeCommand(command) {
150
+ if (closing || !settled || !child.connected)
151
+ return Promise.resolve({ ok: false, reason: 'closed' });
152
+ // Envelope fields last: a stray `type` or `generation` on the command can never readdress it.
153
+ const message = { ...command, type: 'runtime-command', generation: options.generation };
154
+ return new Promise((resolve) => {
155
+ child.send(message, error => resolve(error ? { ok: false, reason: 'closed' } : { ok: true, generation: options.generation }));
156
+ });
157
+ },
158
+ /** IPC first permits framework cleanup; forced tree termination is last resort. */
159
+ close() {
160
+ return closing ??= (async () => {
161
+ retire();
162
+ reject(new Error('Histoire runtime closed'));
163
+ if (child.connected) {
164
+ child.send({ type: 'shutdown' }, () => {
165
+ });
166
+ }
167
+ if (!await wait(options.shutdownTimeout ?? 10_000)) {
168
+ diagnostic('Histoire runtime winddown timed out; terminating owned process tree');
169
+ await killTree();
170
+ if (!await wait(3000))
171
+ throw new Error('Histoire runtime termination could not be confirmed');
172
+ }
173
+ // Successful exit must not leave inherited descendants holding ports.
174
+ if (process.platform !== 'win32')
175
+ await killTree();
176
+ child.stdout.unpipe(process.stdout);
177
+ child.stderr.unpipe(process.stderr);
178
+ for (const stop of outputListeners)
179
+ stop();
180
+ if (child.connected)
181
+ child.disconnect();
182
+ })();
183
+ },
184
+ };
185
+ }
@@ -0,0 +1,166 @@
1
+ import { Buffer } from 'node:buffer';
2
+ /** Public lifecycle, also used by SDK compatibility adapters. */
3
+ export type RuntimeStatus = 'starting' | 'ready' | 'restarting' | 'failed' | 'closed';
4
+ /** Configuration bytes captured at evaluation, encoded only for private IPC. */
5
+ export interface WatchInput {
6
+ /** Absolute local configuration/dependency path. */
7
+ file: string;
8
+ /** Source shown in terminal diagnostics. */
9
+ source: string;
10
+ /** Base64 bytes; null records a missing file. */
11
+ bytes: string | null;
12
+ }
13
+ /** Browser-safe snapshot; excludes backend address, process IDs and secrets. */
14
+ export interface PublicState {
15
+ /** Current availability. */
16
+ status: RuntimeStatus;
17
+ /** Opaque process generation. */
18
+ generation: string;
19
+ /** Current application mount. */
20
+ base: string;
21
+ /** Short failure detail, when startup failed. */
22
+ error?: string;
23
+ }
24
+ /** Why a runtime generation is being replaced. */
25
+ export type RestartCauseKind =
26
+ /** Explicit request by the embedding application (keyboard, API). */
27
+ 'manual'
28
+ /** A watched configuration or dependency file changed; `source` labels it. */
29
+ | 'config'
30
+ /** The served page asked for a restart. */
31
+ | 'browser'
32
+ /** The runtime process exited unexpectedly; `source` carries the exit detail. */
33
+ | 'exit'
34
+ /** The runtime asked to be replaced by a new process (e.g. after a plugin change); `source` labels why. */
35
+ | 'runtime';
36
+ /** Observed reason of one restart transition, delivered once per transition. */
37
+ export interface RestartCause {
38
+ kind: RestartCauseKind;
39
+ /** Short origin label (watched file source or exit detail). */
40
+ source?: string;
41
+ /** The next generation skips cached catalog restoration and forces dependency optimization. */
42
+ fresh: boolean;
43
+ }
44
+ /** Input of a restart request; omitted fields mean an ordinary manual restart. */
45
+ export interface RestartRequest {
46
+ cause?: RestartCauseKind;
47
+ source?: string;
48
+ /** Request a one-shot fresh next generation; never lost when coalesced with another cause. */
49
+ fresh?: boolean;
50
+ }
51
+ /** Frozen bounds for generic runtime frames; payload semantics belong to the framework adapter. */
52
+ export declare const RUNTIME_FRAME_MAX_BYTES: number;
53
+ /** Longest accepted runtime restart label. */
54
+ export declare const RESTART_SOURCE_MAX_LENGTH = 200;
55
+ /** Longest accepted correlation, operation and event identifier. */
56
+ export declare const RUNTIME_ID_MAX_LENGTH = 100;
57
+ /** Framework-neutral request carried to the current generation only. */
58
+ export interface RuntimeCommand {
59
+ type: 'runtime-command';
60
+ /** Generation the sender believes is current; receivers ignore mismatches. */
61
+ generation: string;
62
+ /** Correlation identifier echoed by the matching reply. */
63
+ id: string;
64
+ /** Recognized operation name, validated by the framework adapter. */
65
+ operation: string;
66
+ /** Detached JSON arguments. */
67
+ args?: unknown;
68
+ }
69
+ /** Failure carried by a negative runtime reply. */
70
+ export interface RuntimeFailure {
71
+ /** Stable machine-readable code. */
72
+ code: string;
73
+ /** Short human-readable detail. */
74
+ message: string;
75
+ }
76
+ /** Correlated answer to one runtime command. */
77
+ export type RuntimeReply = {
78
+ type: 'runtime-reply';
79
+ generation: string;
80
+ id: string;
81
+ } & ({
82
+ ok: true;
83
+ result?: unknown;
84
+ } | {
85
+ ok: false;
86
+ error: RuntimeFailure;
87
+ });
88
+ /** Uncorrelated generation-scoped observation. */
89
+ export interface RuntimeEvent {
90
+ type: 'runtime-event';
91
+ generation: string;
92
+ /** Recognized event name. */
93
+ event: string;
94
+ /** Detached JSON payload. */
95
+ data?: unknown;
96
+ }
97
+ /** Why a command could not be handed to a runtime process. */
98
+ export type RuntimeSendFailure = 'starting' | 'restarting' | 'failed' | 'closed';
99
+ /** Outcome of handing a command to the current ready runtime. */
100
+ export type RuntimeSendResult = {
101
+ ok: true;
102
+ generation: string;
103
+ } | {
104
+ ok: false;
105
+ reason: RuntimeSendFailure;
106
+ };
107
+ /** Raw runtime stream observation; an absent chunk marks the end of that stream. */
108
+ export interface RuntimeOutput {
109
+ stream: 'stdout' | 'stderr';
110
+ generation: string;
111
+ chunk?: Buffer;
112
+ }
113
+ /** Parent starts one runtime exactly once and requests graceful winddown. */
114
+ export type ParentMessage = {
115
+ type: 'start';
116
+ generation: string;
117
+ publicOrigin: string;
118
+ options: Record<string, unknown>;
119
+ token?: string;
120
+ } | {
121
+ type: 'shutdown';
122
+ } | RuntimeCommand;
123
+ /** Runtime reports observations; only parent decides public availability/restarts. */
124
+ export type ChildMessage = {
125
+ type: 'watch';
126
+ generation: string;
127
+ inputs: WatchInput[];
128
+ complete?: boolean;
129
+ } | {
130
+ type: 'ready';
131
+ generation: string;
132
+ target: string;
133
+ base: string;
134
+ open?: boolean | string;
135
+ } | {
136
+ type: 'failed';
137
+ generation: string;
138
+ error: string;
139
+ }
140
+ /** Ready runtime asks the parent for a full process replacement; only the parent restarts. */
141
+ | {
142
+ type: 'restart';
143
+ generation: string;
144
+ source: string;
145
+ fresh?: boolean;
146
+ } | RuntimeReply | RuntimeEvent;
147
+ /** Non-empty identifier within the frozen length bound. */
148
+ export declare function isIdentifier(value: unknown): value is string;
149
+ /** Serialized frames above the frozen bound (or unserializable ones) are rejected. */
150
+ export declare function isBoundedFrame(value: unknown): boolean;
151
+ /**
152
+ * Whether the child will accept a command: identifiers within bounds, and the frame still within
153
+ * its bound once wrapped in the `runtime-command` envelope it travels in (generation of the longest
154
+ * accepted length). Senders refuse anything else up front instead of waiting for a dropped reply.
155
+ * @param command Correlation ID, operation and arguments of the command.
156
+ */
157
+ export declare function isBoundedCommand(command: Omit<RuntimeCommand, 'type' | 'generation'>): boolean;
158
+ /** Accept a finite, bounded command addressed to the receiving generation. */
159
+ export declare function isRuntimeCommand(value: unknown): value is RuntimeCommand;
160
+ /**
161
+ * Whether a child-sent workbench base is a same-origin absolute path. Backslashes are rejected
162
+ * because URL parsers treat them as slashes (`/\\evil.com` resolves to another host).
163
+ */
164
+ export declare function isSafeBase(base: unknown): base is string;
165
+ /** Accept finite, generation-scoped frames before dispatching across IPC. */
166
+ export declare function isChildMessage(value: unknown): value is ChildMessage;
@@ -0,0 +1,75 @@
1
+ import { Buffer } from 'node:buffer';
2
+ /** Frozen bounds for generic runtime frames; payload semantics belong to the framework adapter. */
3
+ export const RUNTIME_FRAME_MAX_BYTES = 256 * 1024;
4
+ /** Longest accepted runtime restart label. */
5
+ export const RESTART_SOURCE_MAX_LENGTH = 200;
6
+ /** Longest accepted correlation, operation and event identifier. */
7
+ export const RUNTIME_ID_MAX_LENGTH = 100;
8
+ /** Non-empty identifier within the frozen length bound. */
9
+ export function isIdentifier(value) {
10
+ return typeof value === 'string' && value.length > 0 && value.length <= RUNTIME_ID_MAX_LENGTH;
11
+ }
12
+ /** Serialized frames above the frozen bound (or unserializable ones) are rejected. */
13
+ export function isBoundedFrame(value) {
14
+ try {
15
+ return Buffer.byteLength(JSON.stringify(value)) <= RUNTIME_FRAME_MAX_BYTES;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ /**
22
+ * Whether the child will accept a command: identifiers within bounds, and the frame still within
23
+ * its bound once wrapped in the `runtime-command` envelope it travels in (generation of the longest
24
+ * accepted length). Senders refuse anything else up front instead of waiting for a dropped reply.
25
+ * @param command Correlation ID, operation and arguments of the command.
26
+ */
27
+ export function isBoundedCommand(command) {
28
+ return isIdentifier(command.id) && isIdentifier(command.operation) && isBoundedFrame({ ...command, type: 'runtime-command', generation: 'x'.repeat(RUNTIME_ID_MAX_LENGTH) });
29
+ }
30
+ /** Accept a finite, bounded command addressed to the receiving generation. */
31
+ export function isRuntimeCommand(value) {
32
+ if (!value || typeof value !== 'object')
33
+ return false;
34
+ const message = value;
35
+ return message.type === 'runtime-command' && isIdentifier(message.generation) && isIdentifier(message.id) && isIdentifier(message.operation) && isBoundedFrame(value);
36
+ }
37
+ /**
38
+ * Whether a child-sent workbench base is a same-origin absolute path. Backslashes are rejected
39
+ * because URL parsers treat them as slashes (`/\\evil.com` resolves to another host).
40
+ */
41
+ export function isSafeBase(base) {
42
+ if (typeof base !== 'string' || !base.startsWith('/') || base.startsWith('//') || base.includes('\\'))
43
+ return false;
44
+ try {
45
+ return new URL(base, 'http://x').origin === 'http://x';
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ /** Accept finite, generation-scoped frames before dispatching across IPC. */
52
+ export function isChildMessage(value) {
53
+ if (!value || typeof value !== 'object')
54
+ return false;
55
+ const message = value;
56
+ if (typeof message.generation !== 'string' || message.generation.length > 100)
57
+ return false;
58
+ if (message.type === 'runtime-reply') {
59
+ if (!isIdentifier(message.id) || typeof message.ok !== 'boolean')
60
+ return false;
61
+ const error = message.error;
62
+ if (!message.ok && !(error && isIdentifier(error.code) && typeof error.message === 'string' && error.message.length <= 4096))
63
+ return false;
64
+ return isBoundedFrame(value);
65
+ }
66
+ if (message.type === 'runtime-event')
67
+ return isIdentifier(message.event) && isBoundedFrame(value);
68
+ if (message.type === 'failed')
69
+ return typeof message.error === 'string' && message.error.length <= 4096;
70
+ if (message.type === 'restart')
71
+ return typeof message.source === 'string' && message.source.length > 0 && message.source.length <= RESTART_SOURCE_MAX_LENGTH && (message.fresh === undefined || typeof message.fresh === 'boolean');
72
+ if (message.type === 'ready')
73
+ return typeof message.target === 'string' && /^http:\/\/127\.0\.0\.1:\d+$/.test(message.target) && isSafeBase(message.base);
74
+ return message.type === 'watch' && Array.isArray(message.inputs) && message.inputs.length <= 10000 && message.inputs.every(input => input && typeof input.file === 'string' && typeof input.source === 'string' && (input.bytes === null || typeof input.bytes === 'string'));
75
+ }
@@ -0,0 +1,11 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { PublicState } from '../protocol.js';
3
+ /** SSE channel independent of Vite and runtime process lifetime. */
4
+ export declare function createStatusChannel(read: () => PublicState): {
5
+ /** Immediately publish latest state on reconnect. */
6
+ connect(_request: IncomingMessage, response: ServerResponse): void;
7
+ /** State snapshots supersede previous observations; no event replay buffer needed. */
8
+ publish(): void;
9
+ /** End streams before closing listener. */
10
+ close(): void;
11
+ };
@@ -0,0 +1,37 @@
1
+ /** SSE channel independent of Vite and runtime process lifetime. */
2
+ export function createStatusChannel(read) {
3
+ const clients = new Set();
4
+ /** Drop slow/disconnected consumers instead of buffering unbounded state. */
5
+ function write(response, data) {
6
+ if (!response.write(data)) {
7
+ clients.delete(response);
8
+ response.destroy();
9
+ }
10
+ }
11
+ const heartbeat = setInterval(() => {
12
+ for (const response of clients)
13
+ write(response, ': heartbeat\n\n');
14
+ }, 15_000);
15
+ heartbeat.unref();
16
+ return {
17
+ /** Immediately publish latest state on reconnect. */
18
+ connect(_request, response) {
19
+ response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', 'connection': 'keep-alive', 'x-accel-buffering': 'no' });
20
+ clients.add(response);
21
+ response.once('close', () => clients.delete(response));
22
+ write(response, `data: ${JSON.stringify(read())}\n\n`);
23
+ },
24
+ /** State snapshots supersede previous observations; no event replay buffer needed. */
25
+ publish() {
26
+ for (const response of clients)
27
+ write(response, `data: ${JSON.stringify(read())}\n\n`);
28
+ },
29
+ /** End streams before closing listener. */
30
+ close() {
31
+ clearInterval(heartbeat);
32
+ for (const response of clients)
33
+ response.end();
34
+ clients.clear();
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,17 @@
1
+ import type { PublicState } from '../protocol.js';
2
+ import type { ProxyRequestObserver } from './observe.js';
3
+ /** Stable HTTP listener delegates only after coherent generation readiness. */
4
+ export declare function createProxyHttp(read: () => PublicState, restart: () => Promise<void>, observer?: ProxyRequestObserver): {
5
+ server: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
6
+ events: {
7
+ connect(_request: import("http").IncomingMessage, response: import("http").ServerResponse): void;
8
+ publish(): void;
9
+ close(): void;
10
+ };
11
+ /** Forwarding library is deliberately absent from initial listener import graph. */
12
+ prepare(): Promise<void>;
13
+ /** Withdraw target synchronously and retire old runtime WebSockets. */
14
+ setTarget(next?: string): void;
15
+ /** Join listener close after terminating owned streams and idle connections. */
16
+ close(): Promise<void>;
17
+ };
@@ -0,0 +1,130 @@
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
+ /** Proxy-owned responses expose startup errors; reject DNS-rebinding hosts like Vite's default allowedHosts. */
9
+ function isTrustedHost(host) {
10
+ if (!host)
11
+ return false;
12
+ const hostname = host.startsWith('[') ? host.slice(1, host.indexOf(']')) : host.replace(/:\d+$/, '');
13
+ return 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) {
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)) {
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
+ /** Join listener close after terminating owned streams and idle connections. */
121
+ async close() {
122
+ target = undefined;
123
+ events.close();
124
+ const closing = server.listening ? new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())) : Promise.resolve();
125
+ for (const socket of sockets)
126
+ socket.destroy();
127
+ await closing;
128
+ },
129
+ };
130
+ }
@@ -0,0 +1,3 @@
1
+ import type { Server } from 'node:http';
2
+ /** Binds public address before any project modules load, retaining occupied-port fallback. */
3
+ export declare function listen(server: Server, port: number, host?: string | boolean): Promise<string>;
@@ -0,0 +1,34 @@
1
+ /** Binds public address before any project modules load, retaining occupied-port fallback. */
2
+ export async function listen(server, port, host = 'localhost') {
3
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
4
+ throw new Error('Port must be an integer from 0 to 65535');
5
+ for (;;) {
6
+ try {
7
+ await new Promise((resolve, reject) => {
8
+ /** Rejects this bind attempt and drops its success listener. */
9
+ function failed(error) {
10
+ server.off('listening', ready);
11
+ reject(error);
12
+ }
13
+ /** Resolves this bind attempt and drops its failure listener. */
14
+ function ready() {
15
+ server.off('error', failed);
16
+ resolve();
17
+ }
18
+ server.once('error', failed).once('listening', ready);
19
+ server.listen(port, typeof host === 'string' ? host : host ? undefined : 'localhost');
20
+ });
21
+ break;
22
+ }
23
+ catch (error) {
24
+ if (error.code !== 'EADDRINUSE' || port === 0 || port >= 65535)
25
+ throw error;
26
+ port++;
27
+ }
28
+ }
29
+ const address = server.address();
30
+ if (!address || typeof address === 'string')
31
+ throw new Error('Unable to resolve Histoire proxy address');
32
+ const hostname = address.address === '::' || address.address === '0.0.0.0' ? 'localhost' : address.address;
33
+ return `http://${hostname.includes(':') ? `[${hostname}]` : hostname}:${address.port}`;
34
+ }