barejs 0.2.7 → 0.2.8

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.
@@ -0,0 +1,217 @@
1
+ import { escapeHtml, raw, type HtmlString } from './html';
2
+
3
+ export { escapeHtml, raw, type HtmlString };
4
+
5
+ export type JSXChild =
6
+ | JSXNode
7
+ | HtmlString
8
+ | string
9
+ | number
10
+ | boolean
11
+ | null
12
+ | undefined
13
+ | JSXChild[];
14
+
15
+ export type Component<P = any> = (props: P) => JSXChild | Promise<JSXChild>;
16
+
17
+ export interface JSXNode {
18
+ readonly $$bareJsx: true;
19
+ type: string | typeof Fragment | typeof Suspense | Component<any>;
20
+ props: Record<string, any>;
21
+ }
22
+
23
+ export const Fragment = Symbol.for('barejs.jsx.Fragment');
24
+ export const Suspense = Symbol.for('barejs.jsx.Suspense');
25
+
26
+ const VOID_ELEMENTS = new Set([
27
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
28
+ 'link', 'meta', 'param', 'source', 'track', 'wbr'
29
+ ]);
30
+
31
+ const BOOLEAN_ATTRS = new Set([
32
+ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls',
33
+ 'default', 'defer', 'disabled', 'formnovalidate', 'hidden', 'inert', 'ismap',
34
+ 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline',
35
+ 'readonly', 'required', 'reversed', 'selected'
36
+ ]);
37
+
38
+ export const jsx = (
39
+ type: JSXNode['type'],
40
+ props: Record<string, any> | null
41
+ ): JSXNode => ({
42
+ $$bareJsx: true,
43
+ type,
44
+ props: props ?? {}
45
+ });
46
+
47
+ export const jsxs = jsx;
48
+ export const jsxDEV = jsx;
49
+
50
+ const isJsxNode = (v: unknown): v is JSXNode =>
51
+ typeof v === 'object' && v !== null && (v as any).$$bareJsx === true;
52
+
53
+ const isHtmlString = (v: unknown): v is HtmlString =>
54
+ typeof v === 'object' && v !== null && (v as any).__bareHtml === true;
55
+
56
+ const styleToString = (style: Record<string, any>): string => {
57
+ let out = '';
58
+ for (const [k, v] of Object.entries(style)) {
59
+ if (v === null || v === undefined || v === false) continue;
60
+ const prop = k.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
61
+ out += `${prop}:${String(v)};`;
62
+ }
63
+ return out;
64
+ };
65
+
66
+ const renderAttrs = (props: Record<string, any>): string => {
67
+ let out = '';
68
+ for (const [rawKey, val] of Object.entries(props)) {
69
+ if (rawKey === 'children' || rawKey === 'key' || rawKey === 'dangerouslySetInnerHTML') continue;
70
+ if (val === null || val === undefined || val === false) continue;
71
+ const key = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey;
72
+ if (key === 'style' && typeof val === 'object') {
73
+ const css = styleToString(val);
74
+ if (css) out += ` style="${escapeHtml(css)}"`;
75
+ continue;
76
+ }
77
+ if (val === true) {
78
+ out += BOOLEAN_ATTRS.has(key.toLowerCase()) ? ` ${key}` : ` ${key}="true"`;
79
+ continue;
80
+ }
81
+ out += ` ${key}="${escapeHtml(String(val))}"`;
82
+ }
83
+ return out;
84
+ };
85
+
86
+ interface PendingSuspense {
87
+ id: number;
88
+ promise: Promise<string>;
89
+ }
90
+
91
+ const renderNodeInternal = async (
92
+ node: JSXChild | Promise<JSXChild>,
93
+ pending?: PendingSuspense[]
94
+ ): Promise<string> => {
95
+ const resolved = node instanceof Promise ? await node : node;
96
+ if (resolved === null || resolved === undefined || typeof resolved === 'boolean') return '';
97
+ if (typeof resolved === 'string') return escapeHtml(resolved);
98
+ if (typeof resolved === 'number') return String(resolved);
99
+ if (isHtmlString(resolved)) return resolved.value;
100
+ if (Array.isArray(resolved)) {
101
+ let out = '';
102
+ for (let i = 0; i < resolved.length; i++) {
103
+ out += await renderNodeInternal(resolved[i], pending);
104
+ }
105
+ return out;
106
+ }
107
+ if (!isJsxNode(resolved)) return escapeHtml(String(resolved));
108
+
109
+ const { type, props } = resolved;
110
+
111
+ if (type === Fragment) {
112
+ return renderNodeInternal(props.children, pending);
113
+ }
114
+
115
+ if (type === Suspense) {
116
+ if (pending) {
117
+ const id = pending.length;
118
+ const fallbackHtml = await renderNodeInternal(props.fallback ?? '', undefined);
119
+ const childPromise = renderNodeInternal(props.children, pending);
120
+ pending.push({ id, promise: childPromise });
121
+ return `<template id="B:${id}"></template>${fallbackHtml}<!--/B:${id}-->`;
122
+ }
123
+ return renderNodeInternal(props.children, undefined);
124
+ }
125
+
126
+ if (typeof type === 'function') {
127
+ const out = type(props);
128
+ return renderNodeInternal(out, pending);
129
+ }
130
+
131
+ const tag = String(type);
132
+ const attrs = renderAttrs(props);
133
+ if (VOID_ELEMENTS.has(tag.toLowerCase())) {
134
+ return `<${tag}${attrs}>`;
135
+ }
136
+ if (props.dangerouslySetInnerHTML && typeof props.dangerouslySetInnerHTML.__html === 'string') {
137
+ return `<${tag}${attrs}>${props.dangerouslySetInnerHTML.__html}</${tag}>`;
138
+ }
139
+ const inner = await renderNodeInternal(props.children, pending);
140
+ return `<${tag}${attrs}>${inner}</${tag}>`;
141
+ };
142
+
143
+ /** Renders a JSX tree (including async components) to an HTML string. */
144
+ export const renderToString = async (node: JSXChild): Promise<string> => {
145
+ return renderNodeInternal(node, undefined);
146
+ };
147
+
148
+ const SWAP_SCRIPT_FN =
149
+ '<script>function $B(i,t){var a=document.getElementById("B:"+i),b=document.getElementById("S:"+i);if(!a||!b)return;var p=a.parentNode,n=a.nextSibling;while(n&&!(n.nodeType===8&&n.data==="/B:"+i)){var x=n.nextSibling;p.removeChild(n);n=x;}p.insertBefore(b.content,n);p.removeChild(a);if(n)p.removeChild(n);b.remove();}</script>';
150
+
151
+ /**
152
+ * Streams a JSX tree as a Web `ReadableStream<Uint8Array>`, flushing `<Suspense fallback>`
153
+ * immediately and streaming out-of-order `<template>` replacement chunks as async children resolve.
154
+ */
155
+ export const renderToReadableStream = (node: JSXChild): ReadableStream<Uint8Array> => {
156
+ const encoder = new TextEncoder();
157
+ return new ReadableStream<Uint8Array>({
158
+ async start(controller) {
159
+ try {
160
+ const pending: PendingSuspense[] = [];
161
+ const shell = await renderNodeInternal(node, pending);
162
+ controller.enqueue(encoder.encode(shell));
163
+
164
+ if (pending.length > 0) {
165
+ controller.enqueue(encoder.encode(SWAP_SCRIPT_FN));
166
+ const settled = new Set<number>();
167
+ while (settled.size < pending.length) {
168
+ const batch = pending.filter((p) => !settled.has(p.id));
169
+ await Promise.all(
170
+ batch.map(async (item) => {
171
+ settled.add(item.id);
172
+ const html = await item.promise;
173
+ const chunk = `<template id="S:${item.id}">${html}</template><script>$B(${item.id})</script>`;
174
+ controller.enqueue(encoder.encode(chunk));
175
+ })
176
+ );
177
+ }
178
+ }
179
+ controller.close();
180
+ } catch (err) {
181
+ controller.error(err);
182
+ }
183
+ }
184
+ });
185
+ };
186
+
187
+ /** Convenience helper returning a `text/html; charset=utf-8` Response from a JSX tree. */
188
+ export const htmlResponse = async (
189
+ node: JSXChild,
190
+ status = 200,
191
+ headers?: Record<string, string> | Headers
192
+ ): Promise<Response> => {
193
+ const h = new Headers(headers as any);
194
+ if (!h.has('content-type')) h.set('content-type', 'text/html; charset=utf-8');
195
+ return new Response(await renderToString(node), { status, headers: h });
196
+ };
197
+
198
+ /** Convenience helper returning a streaming `text/html; charset=utf-8` Response with `<Suspense>` support. */
199
+ export const streamResponse = (
200
+ node: JSXChild,
201
+ status = 200,
202
+ headers?: Record<string, string> | Headers
203
+ ): Response => {
204
+ const h = new Headers(headers as any);
205
+ if (!h.has('content-type')) h.set('content-type', 'text/html; charset=utf-8');
206
+ return new Response(renderToReadableStream(node), { status, headers: h });
207
+ };
208
+
209
+ export namespace JSX {
210
+ export type Element = JSXNode;
211
+ export interface ElementChildrenAttribute {
212
+ children: {};
213
+ }
214
+ export interface IntrinsicElements {
215
+ [elemName: string]: Record<string, any>;
216
+ }
217
+ }
@@ -0,0 +1,110 @@
1
+ export interface SSGFileWriter {
2
+ mkdir(path: string, opts?: { recursive?: boolean }): Promise<any>;
3
+ writeFile(path: string, data: Uint8Array | string): Promise<any>;
4
+ }
5
+
6
+ export interface ToSSGOptions {
7
+ /** Output directory on disk (default: `'./static'`). */
8
+ dir?: string;
9
+ /** Additional concrete routes to pre-render (useful for parameterized routes like `['/posts/hello']`). */
10
+ routes?: string[];
11
+ /** Emit `/about` as `/about/index.html` instead of `/about.html` (default: `false`). */
12
+ dirIndex?: boolean;
13
+ /** Optional custom filesystem writer (useful for testing or non-Node runtimes). */
14
+ fs?: SSGFileWriter;
15
+ /** Base origin used when invoking `app.fetch` (default: `'http://localhost'`). */
16
+ origin?: string;
17
+ }
18
+
19
+ export interface ToSSGResult {
20
+ success: boolean;
21
+ files: string[];
22
+ error?: Error;
23
+ }
24
+
25
+ interface FetchableApp {
26
+ fetch(req: Request): Response | Promise<Response>;
27
+ routes?: Array<{ method: string; path: string }>;
28
+ }
29
+
30
+ const routeToFilePath = (dir: string, routePath: string, contentType: string, dirIndex: boolean): string => {
31
+ const cleanDir = dir.replace(/\/+$/, '');
32
+ const norm = routePath.startsWith('/') ? routePath : '/' + routePath;
33
+ if (norm === '/' || norm === '') return `${cleanDir}/index.html`;
34
+
35
+ const lastSeg = norm.slice(norm.lastIndexOf('/') + 1);
36
+ if (lastSeg.includes('.')) {
37
+ return `${cleanDir}${norm}`;
38
+ }
39
+
40
+ const ct = contentType.toLowerCase();
41
+ if (ct.includes('application/json')) return `${cleanDir}${norm}.json`;
42
+ if (ct.includes('text/plain')) return `${cleanDir}${norm}.txt`;
43
+ if (ct.includes('application/xml') || ct.includes('text/xml')) return `${cleanDir}${norm}.xml`;
44
+
45
+ return dirIndex ? `${cleanDir}${norm}/index.html` : `${cleanDir}${norm}.html`;
46
+ };
47
+
48
+ /**
49
+ * Build-time Static Site Generator (`toSSG`).
50
+ * Pre-renders static `GET` routes (plus any explicit `options.routes`) into static files.
51
+ */
52
+ export const toSSG = async (app: FetchableApp, options: ToSSGOptions = {}): Promise<ToSSGResult> => {
53
+ const dir = options.dir ?? './static';
54
+ const dirIndex = options.dirIndex ?? false;
55
+ const origin = (options.origin ?? 'http://localhost').replace(/\/+$/, '');
56
+ const files: string[] = [];
57
+
58
+ try {
59
+ let writer: SSGFileWriter;
60
+ if (options.fs) {
61
+ writer = options.fs;
62
+ } else {
63
+ const nodeFs = await import('node:fs/promises');
64
+ writer = {
65
+ mkdir: (p, o) => nodeFs.mkdir(p, o),
66
+ writeFile: (p, d) => nodeFs.writeFile(p, d)
67
+ };
68
+ }
69
+
70
+ const targets = new Set<string>();
71
+ if (Array.isArray(app.routes)) {
72
+ for (let i = 0; i < app.routes.length; i++) {
73
+ const r = app.routes[i]!;
74
+ if (r.method !== 'GET') continue;
75
+ const p = r.path || '/';
76
+ if (p.includes(':') || p.includes('*')) continue;
77
+ targets.add(p.startsWith('/') ? p : '/' + p);
78
+ }
79
+ }
80
+ if (options.routes) {
81
+ for (let i = 0; i < options.routes.length; i++) {
82
+ const p = options.routes[i]!;
83
+ targets.add(p.startsWith('/') ? p : '/' + p);
84
+ }
85
+ }
86
+
87
+ for (const routePath of targets) {
88
+ const res = await app.fetch(new Request(`${origin}${routePath}`, { method: 'GET' }));
89
+ if (res.status < 200 || res.status >= 300) continue;
90
+
91
+ const ct = res.headers.get('content-type') ?? 'text/html';
92
+ const outPath = routeToFilePath(dir, routePath, ct, dirIndex);
93
+ const parentDir = outPath.slice(0, outPath.lastIndexOf('/'));
94
+ if (parentDir) {
95
+ await writer.mkdir(parentDir, { recursive: true });
96
+ }
97
+ const bytes = new Uint8Array(await res.arrayBuffer());
98
+ await writer.writeFile(outPath, bytes);
99
+ files.push(outPath);
100
+ }
101
+
102
+ return { success: true, files };
103
+ } catch (err) {
104
+ return {
105
+ success: false,
106
+ files,
107
+ error: err instanceof Error ? err : new Error(String(err))
108
+ };
109
+ }
110
+ };