@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,45 @@
1
+ import { statusTitle } from './status.js';
2
+ /** Latest requested swap; an older pending swap must not overwrite a newer state. */
3
+ let version = 0;
4
+ /** Whether the viewer asked for no motion; transitions then apply instantly. */
5
+ function reducedMotion() {
6
+ return matchMedia('(prefers-reduced-motion: reduce)').matches;
7
+ }
8
+ /**
9
+ * Applies one public state to the startup page. CSS reacts to `body[data-status]` (logo, failure
10
+ * outcome); the headline text slides out and back in so successive states read as a sequence.
11
+ */
12
+ export function applyStatus(state) {
13
+ const status = document.getElementById('status');
14
+ const title = statusTitle(state.status);
15
+ // A cleared error keeps its old text while the outcome collapses; only a new error replaces it.
16
+ if (state.error)
17
+ document.getElementById('detail').textContent = state.error;
18
+ if (document.body.dataset.status === state.status && status.textContent === title)
19
+ return;
20
+ document.body.dataset.status = state.status;
21
+ const current = ++version;
22
+ /** Swaps headline text and tone together so color and shimmer change with the words. */
23
+ const swap = () => {
24
+ status.textContent = title;
25
+ status.dataset.tone = state.status;
26
+ };
27
+ if (reducedMotion()) {
28
+ swap();
29
+ return;
30
+ }
31
+ status.getAnimations().forEach(animation => animation.cancel());
32
+ const leave = status.animate([{ opacity: 1, transform: 'none' }, { opacity: 0, transform: 'translateY(-6px)' }], { duration: 140, easing: 'ease-in', fill: 'forwards' });
33
+ void leave.finished.then(() => {
34
+ if (current !== version)
35
+ return;
36
+ swap();
37
+ leave.cancel();
38
+ status.animate([{ opacity: 0, transform: 'translateY(6px)' }, { opacity: 1, transform: 'none' }], { duration: 260, easing: 'cubic-bezier(.2, .8, .2, 1)' });
39
+ }, () => { });
40
+ }
41
+ /** Fades the startup screen out, then resolves; callers navigate afterwards. */
42
+ export function leaveStartup() {
43
+ document.body.dataset.leaving = '';
44
+ return new Promise(resolve => setTimeout(resolve, reducedMotion() ? 0 : 200));
45
+ }
@@ -0,0 +1,12 @@
1
+ /** Histoire config discovery priority, shared with runtime config loader. */
2
+ export declare const configFileNames: string[];
3
+ /** Vite config discovery priority. */
4
+ export declare const viteConfigFileNames: string[];
5
+ /** Finds selected Histoire configuration without importing or evaluating it. */
6
+ export declare function resolveConfigFile(cwd?: string, configFile?: string): string | null;
7
+ /** Resolves ordered discovery candidates below one directory. */
8
+ export declare function localConfigFiles(root: string, names: readonly string[]): string[];
9
+ /** Covers local candidates which can supersede selected inherited configuration. */
10
+ export declare function histoireConfigFiles(root: string, config: string | undefined, acquired: string | null): string[];
11
+ /** Retains selected inputs plus paths that can overtake them by priority. */
12
+ export declare function watchedConfigFiles(candidates: readonly string[], current: string | null, acquired: string | null): string[];
@@ -0,0 +1,57 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ /** Histoire config discovery priority, shared with runtime config loader. */
4
+ export const configFileNames = ['histoire.config.ts', 'histoire.config.js', '.histoire.ts', '.histoire.js'];
5
+ /** Vite config discovery priority. */
6
+ export const viteConfigFileNames = ['vite.config.js', 'vite.config.mjs', 'vite.config.ts', 'vite.config.cjs', 'vite.config.mts', 'vite.config.cts'];
7
+ /** Finds selected Histoire configuration without importing or evaluating it. */
8
+ export function resolveConfigFile(cwd = process.cwd(), configFile) {
9
+ if (configFile)
10
+ return path.resolve(cwd, configFile);
11
+ let directory = path.resolve(cwd);
12
+ while (directory !== path.dirname(directory)) {
13
+ for (const name of configFileNames) {
14
+ const file = path.join(directory, name);
15
+ if (existsSync(file))
16
+ return file;
17
+ }
18
+ directory = path.dirname(directory);
19
+ }
20
+ return null;
21
+ }
22
+ /** Resolves ordered discovery candidates below one directory. */
23
+ export function localConfigFiles(root, names) {
24
+ return names.map(name => path.join(root, name));
25
+ }
26
+ /** Covers local candidates which can supersede selected inherited configuration. */
27
+ export function histoireConfigFiles(root, config, acquired) {
28
+ if (config)
29
+ return [];
30
+ const acquiredDirectory = acquired ? path.dirname(acquired) : null;
31
+ const directories = [root];
32
+ let directory = root;
33
+ if (acquiredDirectory) {
34
+ while (directory !== acquiredDirectory) {
35
+ const parent = path.dirname(directory);
36
+ if (parent === directory)
37
+ break;
38
+ directories.push(parent);
39
+ directory = parent;
40
+ }
41
+ }
42
+ return directories.flatMap((directory) => {
43
+ const index = directory === acquiredDirectory && acquired ? configFileNames.indexOf(path.basename(acquired)) : -1;
44
+ return localConfigFiles(directory, index < 0 ? configFileNames : configFileNames.slice(0, index + 1));
45
+ });
46
+ }
47
+ /** Retains selected inputs plus paths that can overtake them by priority. */
48
+ export function watchedConfigFiles(candidates, current, acquired) {
49
+ const selected = current ?? acquired;
50
+ const index = selected ? candidates.indexOf(selected) : -1;
51
+ const files = new Set(index < 0 ? candidates : candidates.slice(0, index + 1));
52
+ if (current)
53
+ files.add(current);
54
+ if (acquired)
55
+ files.add(acquired);
56
+ return [...files];
57
+ }
@@ -0,0 +1,4 @@
1
+ export * from './discovery.js';
2
+ export * from './inputs.js';
3
+ export * from './snapshots.js';
4
+ export * from './watcher.js';
@@ -0,0 +1,4 @@
1
+ export * from './discovery.js';
2
+ export * from './inputs.js';
3
+ export * from './snapshots.js';
4
+ export * from './watcher.js';
@@ -0,0 +1,18 @@
1
+ import type { WatchInput } from '../protocol.js';
2
+ import type { ConfigurationRevision, FileSnapshot } from './snapshots.js';
3
+ /** Build identical priority-aware inputs for CLI proxy and SDK compatibility watches. */
4
+ export declare function configurationWatchInputs(options: {
5
+ /** Project root. */
6
+ root: string;
7
+ /** Explicit Histoire config selection. */
8
+ config?: string;
9
+ /** Vite config selected by acquired runtime, or acquisition snapshot by default. */
10
+ viteFile?: string | null;
11
+ /** Pre-evaluation bytes close watcher-installation races. */
12
+ revision?: ConfigurationRevision;
13
+ /** Loader-known imported local modules. */
14
+ dependencies?: {
15
+ histoire: ReadonlyMap<string, FileSnapshot>;
16
+ vite: ReadonlyMap<string, FileSnapshot>;
17
+ };
18
+ }): Promise<WatchInput[]>;
@@ -0,0 +1,29 @@
1
+ import path from 'node:path';
2
+ import { histoireConfigFiles, localConfigFiles, resolveConfigFile, viteConfigFileNames, watchedConfigFiles } from './discovery.js';
3
+ import { readFileSnapshot } from './snapshots.js';
4
+ /** Build identical priority-aware inputs for CLI proxy and SDK compatibility watches. */
5
+ export async function configurationWatchInputs(options) {
6
+ const root = path.resolve(options.root);
7
+ const revision = options.revision;
8
+ const histoireFile = resolveConfigFile(root, options.config);
9
+ const viteFile = options.viteFile === undefined ? revision?.viteConfigFile ?? null : options.viteFile;
10
+ const files = new Map();
11
+ for (const file of watchedConfigFiles(localConfigFiles(root, viteConfigFileNames), viteFile, revision?.viteConfigFile ?? null))
12
+ files.set(file, 'Vite');
13
+ const histoireCandidates = histoireConfigFiles(root, options.config, revision?.histoireFile ?? histoireFile);
14
+ for (const file of watchedConfigFiles(histoireCandidates, histoireFile, revision?.histoireFile ?? null))
15
+ files.set(file, 'Histoire');
16
+ const loaded = new Map();
17
+ for (const [source, modules] of [['Histoire', options.dependencies?.histoire], ['Vite', options.dependencies?.vite]]) {
18
+ for (const [file, snapshot] of modules ?? []) {
19
+ if (files.has(file))
20
+ continue;
21
+ files.set(file, source);
22
+ loaded.set(file, snapshot);
23
+ }
24
+ }
25
+ return Promise.all([...files].map(async ([file, source]) => {
26
+ const bytes = revision?.snapshots.has(file) ? revision.snapshots.get(file) : loaded.has(file) ? loaded.get(file) : await readFileSnapshot(file);
27
+ return { file, source, bytes: bytes?.toString('base64') ?? null };
28
+ }));
29
+ }
@@ -0,0 +1,16 @@
1
+ import type { Buffer } from 'node:buffer';
2
+ /** Exact file contents; undefined represents absence. */
3
+ export type FileSnapshot = Buffer | undefined;
4
+ /** Acquisition inputs compared after watcher installation. */
5
+ export interface ConfigurationRevision {
6
+ /** Selected Histoire config, including explicit missing path. */
7
+ histoireFile: string | null;
8
+ /** Selected Vite config. */
9
+ viteConfigFile: string | null;
10
+ /** Bytes captured before project evaluation. */
11
+ snapshots: ReadonlyMap<string, FileSnapshot>;
12
+ }
13
+ /** Reads absence distinctly from an empty config. */
14
+ export declare function readFileSnapshot(file: string): Promise<FileSnapshot>;
15
+ /** Captures config inputs before one runtime begins acquisition. */
16
+ export declare function captureProjectConfigurationRevision(root: string, config?: string): Promise<ConfigurationRevision>;
@@ -0,0 +1,25 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { histoireConfigFiles, localConfigFiles, resolveConfigFile, viteConfigFileNames } from './discovery.js';
4
+ /** Reads absence distinctly from an empty config. */
5
+ export async function readFileSnapshot(file) {
6
+ try {
7
+ return await readFile(file);
8
+ }
9
+ catch (error) {
10
+ if (error.code === 'ENOENT')
11
+ return;
12
+ throw error;
13
+ }
14
+ }
15
+ /** Captures config inputs before one runtime begins acquisition. */
16
+ export async function captureProjectConfigurationRevision(root, config) {
17
+ root = path.resolve(root);
18
+ const histoireFile = resolveConfigFile(root, config);
19
+ const viteFiles = localConfigFiles(root, viteConfigFileNames);
20
+ const files = new Set([...histoireConfigFiles(root, config, histoireFile), ...viteFiles]);
21
+ if (histoireFile)
22
+ files.add(path.resolve(histoireFile));
23
+ const snapshots = new Map(await Promise.all([...files].map(async (file) => [file, await readFileSnapshot(file)])));
24
+ return { histoireFile, viteConfigFile: viteFiles.find(file => snapshots.get(file) !== undefined) ?? null, snapshots };
25
+ }
@@ -0,0 +1,12 @@
1
+ import type { Buffer } from 'node:buffer';
2
+ import type { WatchInput } from '../protocol.js';
3
+ /** Owns byte-aware directory watches, retaining dependencies through failed loads. */
4
+ export declare function watchConfiguration(inputs: readonly WatchInput[], changed: (source: string, file: string) => void, onError?: (error: unknown) => void): Promise<{
5
+ update: (next: readonly WatchInput[], isCurrent?: () => boolean) => Promise<void>;
6
+ /** A successful generation retires stale dependency paths; failures retain last known set. */
7
+ replace(next: readonly WatchInput[], isCurrent?: () => boolean): Promise<void>;
8
+ /** Stops callbacks before joining pending reads and closing filesystem handles. */
9
+ close(): Promise<void>;
10
+ }>;
11
+ /** Encodes captured bytes only for trusted runtime-to-parent transport. */
12
+ export declare function encodeWatchInputs(snapshots: ReadonlyMap<string, Buffer | undefined>, source?: string): WatchInput[];
@@ -0,0 +1,103 @@
1
+ import path from 'node:path';
2
+ import chokidar from 'chokidar';
3
+ import { readFileSnapshot } from './snapshots.js';
4
+ /** Owns byte-aware directory watches, retaining dependencies through failed loads. */
5
+ export async function watchConfiguration(inputs, changed, onError = console.error) {
6
+ const files = new Map();
7
+ let stopped = false;
8
+ let changes = Promise.resolve();
9
+ const watchers = new Map();
10
+ const directories = new Set();
11
+ /** Serial reads suppress duplicate add/change events without dropping later bytes. */
12
+ function inspect(file) {
13
+ file = path.resolve(file);
14
+ if (stopped || !files.has(file))
15
+ return;
16
+ changes = changes.then(async () => {
17
+ const previous = files.get(file);
18
+ if (stopped || !previous)
19
+ return;
20
+ const next = (await readFileSnapshot(file))?.toString('base64') ?? null;
21
+ if (stopped || next === previous.bytes)
22
+ return;
23
+ files.set(file, { ...previous, bytes: next });
24
+ changed(previous.source, file);
25
+ }).catch((error) => {
26
+ if (!stopped)
27
+ onError(error);
28
+ });
29
+ }
30
+ /** Merge evaluation snapshots, subscribe new directories, then reconcile missed edits. */
31
+ async function update(next, isCurrent = () => true) {
32
+ if (stopped || !isCurrent())
33
+ return;
34
+ const added = new Set();
35
+ for (const input of next) {
36
+ const file = path.resolve(input.file);
37
+ files.set(file, { ...input, file });
38
+ const directory = path.dirname(file);
39
+ if (!directories.has(directory)) {
40
+ directories.add(directory);
41
+ added.add(directory);
42
+ }
43
+ }
44
+ if (added.size) {
45
+ const watcher = chokidar.watch([...added], { ignoreInitial: true, depth: 0 });
46
+ watchers.set(watcher, added);
47
+ watcher.on('add', inspect).on('change', inspect).on('unlink', inspect).on('error', onError);
48
+ // Every new dependency directory gets a scan barrier before reconciliation;
49
+ // otherwise edits between its first stat and subscription could disappear.
50
+ await new Promise((resolve, reject) => {
51
+ watcher.once('ready', resolve);
52
+ watcher.once('error', reject);
53
+ });
54
+ }
55
+ if (stopped || !isCurrent())
56
+ return;
57
+ for (const input of next)
58
+ inspect(input.file);
59
+ await changes;
60
+ }
61
+ try {
62
+ await update(inputs);
63
+ }
64
+ catch (error) {
65
+ await Promise.all([...watchers.keys()].map(watcher => watcher.close()));
66
+ throw error;
67
+ }
68
+ return {
69
+ update,
70
+ /** A successful generation retires stale dependency paths; failures retain last known set. */
71
+ async replace(next, isCurrent = () => true) {
72
+ if (stopped || !isCurrent())
73
+ return;
74
+ const retained = new Set(next.map(input => path.resolve(input.file)));
75
+ for (const file of files.keys()) {
76
+ if (!retained.has(file))
77
+ files.delete(file);
78
+ }
79
+ const activeDirectories = new Set([...retained].map(file => path.dirname(file)));
80
+ const closing = [];
81
+ for (const [watcher, paths] of watchers) {
82
+ if ([...paths].some(path => activeDirectories.has(path)))
83
+ continue;
84
+ watchers.delete(watcher);
85
+ for (const directory of paths)
86
+ directories.delete(directory);
87
+ closing.push(watcher.close());
88
+ }
89
+ await Promise.all(closing);
90
+ await update(next, isCurrent);
91
+ },
92
+ /** Stops callbacks before joining pending reads and closing filesystem handles. */
93
+ async close() {
94
+ stopped = true;
95
+ await Promise.all([...watchers.keys()].map(watcher => watcher.close()));
96
+ await changes;
97
+ },
98
+ };
99
+ }
100
+ /** Encodes captured bytes only for trusted runtime-to-parent transport. */
101
+ export function encodeWatchInputs(snapshots, source = 'Histoire') {
102
+ return [...snapshots].map(([file, bytes]) => ({ file, source, bytes: bytes?.toString('base64') ?? null }));
103
+ }
@@ -0,0 +1,64 @@
1
+ import type { PublicState, RestartCause, RestartRequest, RuntimeCommand, RuntimeEvent, RuntimeOutput, RuntimeReply, RuntimeSendResult, RuntimeStatus } from './protocol.js';
2
+ import type { ProxyRequestObserver } from './server/observe.js';
3
+ export type { ProxyRequestEvent, ProxyRequestObserver, ProxyRequestOutcome } from './server/observe.js';
4
+ /** Lightweight parent inputs; runtime executable remains an external adapter. */
5
+ export interface DevProxyOptions {
6
+ /** Project working directory. */
7
+ root?: string;
8
+ /** Explicit config path relative to root. */
9
+ config?: string;
10
+ /** Public port; zero asks OS for an ephemeral port. */
11
+ port?: number;
12
+ /** Public interface, default localhost. */
13
+ host?: string | boolean;
14
+ /** Open public URL once listener binds. */
15
+ open?: boolean;
16
+ /** Framework runtime executable owned by proxy. */
17
+ runtime: URL;
18
+ /** Serializable runtime-specific CLI options. */
19
+ runtimeOptions?: Record<string, unknown>;
20
+ /** Captured credential, never inherited by project config through env. */
21
+ token?: string;
22
+ /** Graceful child winddown budget; default 10000ms. */
23
+ shutdownTimeout?: number;
24
+ /** Observe public listener before project work begins. */
25
+ onListening?: (url: string) => void;
26
+ /** Optional terminal/application observation; receives detached browser-safe state. */
27
+ onStatus?: (state: Readonly<PublicState>) => void;
28
+ /** Takes over runtime stdout/stderr (each chunk delivered once); without it the streams are piped unchanged. */
29
+ onOutput?: (output: RuntimeOutput) => void;
30
+ /** Receives reply/event frames from the current runtime generation. */
31
+ onRuntimeMessage?: (message: RuntimeReply | RuntimeEvent) => void;
32
+ /** A runtime generation can no longer answer: winddown began or the process exited. */
33
+ onRuntimeRetired?: (generation: string) => void;
34
+ /** Called once per restart transition, as it begins, with its merged cause. Never called for the first start. */
35
+ onRestart?: (cause: RestartCause) => void;
36
+ /** Called when a runtime generation is spawned; `fresh` generations bypass cached catalog and dependency reuse. */
37
+ onRuntimeStart?: (info: {
38
+ generation: string;
39
+ fresh: boolean;
40
+ }) => void;
41
+ /**
42
+ * Observes public HTTP exchanges (forwarded and proxy-answered startup responses, not the proxy's own
43
+ * status stream and assets, not WebSocket upgrades). Without it nothing is allocated or listened to.
44
+ */
45
+ onRequest?: ProxyRequestObserver;
46
+ /** Receives proxy diagnostics; without it they go to `console.error`. */
47
+ onDiagnostic?: (message: string) => void;
48
+ }
49
+ /** Bind first; child startup and project imports happen after handle is available. */
50
+ export declare function startDevProxy(options: DevProxyOptions): Promise<{
51
+ /** Actual public address, including OS-selected or fallback port. */
52
+ url: string;
53
+ /** Initial runtime acquisition; watcher remains live after rejection. */
54
+ ready: Promise<void>;
55
+ /** Latest public availability, independent of any runtime process. */
56
+ readonly status: RuntimeStatus;
57
+ restart: (request?: RestartRequest) => Promise<void>;
58
+ /** Opens an absolute URL in the default browser on demand (terminal action); unrelated to the one-shot `open` option. */
59
+ openBrowser(target: string): Promise<void>;
60
+ /** Delivers a command to the current ready runtime; never queues for an unknown successor. */
61
+ sendRuntimeCommand(command: Omit<RuntimeCommand, 'type' | 'generation'>): Promise<RuntimeSendResult>;
62
+ /** Stop observation/admission synchronously before joining child shutdown. */
63
+ close(): Promise<void>;
64
+ }>;