hadars 0.2.0 → 0.2.2-rc.0

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,332 @@
1
+ import {
2
+ renderPreflight,
3
+ renderToString
4
+ } from "./chunk-LY5MTHFV.js";
5
+ import {
6
+ createElement
7
+ } from "./chunk-OS3V4CPN.js";
8
+
9
+ // src/utils/cookies.ts
10
+ var parseCookies = (cookieString) => {
11
+ const cookies = {};
12
+ if (!cookieString) {
13
+ return cookies;
14
+ }
15
+ const pairs = cookieString.split(";");
16
+ for (const pair of pairs) {
17
+ const index = pair.indexOf("=");
18
+ if (index > -1) {
19
+ const key = pair.slice(0, index).trim();
20
+ const value = pair.slice(index + 1).trim();
21
+ try {
22
+ cookies[key] = decodeURIComponent(value);
23
+ } catch {
24
+ cookies[key] = value;
25
+ }
26
+ }
27
+ }
28
+ return cookies;
29
+ };
30
+
31
+ // src/utils/request.tsx
32
+ var parseRequest = (request) => {
33
+ const url = new URL(request.url);
34
+ const cookies = request.headers.get("Cookie") || "";
35
+ const cookieRecord = parseCookies(cookies);
36
+ return Object.assign(request, { pathname: url.pathname, search: url.search, location: url.pathname + url.search, cookies: cookieRecord });
37
+ };
38
+
39
+ // src/utils/proxyHandler.tsx
40
+ var cloneHeaders = (headers) => {
41
+ return new Headers(headers);
42
+ };
43
+ var getCORSHeaders = (req) => {
44
+ const origin = req.headers.get("Origin") || "*";
45
+ return {
46
+ "Access-Control-Allow-Origin": origin,
47
+ "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
48
+ "Access-Control-Allow-Headers": req.headers.get("Access-Control-Request-Headers") || "*",
49
+ "Access-Control-Allow-Credentials": "true"
50
+ };
51
+ };
52
+ var createProxyHandler = (options) => {
53
+ const { proxy, proxyCORS } = options;
54
+ if (!proxy) {
55
+ return () => void 0;
56
+ }
57
+ if (typeof proxy === "function") {
58
+ return async (req) => {
59
+ if (req.method === "OPTIONS" && options.proxyCORS) {
60
+ return new Response(null, {
61
+ status: 204,
62
+ headers: getCORSHeaders(req)
63
+ });
64
+ }
65
+ const res = await proxy(req);
66
+ if (res && proxyCORS) {
67
+ const modifiedHeaders = new Headers(res.headers);
68
+ Object.entries(getCORSHeaders(req)).forEach(([key, value]) => {
69
+ modifiedHeaders.set(key, value);
70
+ });
71
+ return new Response(res.body, {
72
+ status: res.status,
73
+ statusText: res.statusText,
74
+ headers: modifiedHeaders
75
+ });
76
+ }
77
+ return res || void 0;
78
+ };
79
+ }
80
+ const proxyRules = Object.entries(proxy).sort((a, b) => b[0].length - a[0].length);
81
+ return async (req) => {
82
+ for (const [path, target] of proxyRules) {
83
+ if (req.pathname.startsWith(path)) {
84
+ if (req.method === "OPTIONS" && proxyCORS) {
85
+ return new Response(null, {
86
+ status: 204,
87
+ headers: getCORSHeaders(req)
88
+ });
89
+ }
90
+ const targetURL = new URL(target);
91
+ targetURL.pathname = targetURL.pathname.replace(/\/$/, "") + req.pathname.slice(path.length);
92
+ targetURL.search = req.search;
93
+ const sendHeaders = cloneHeaders(req.headers);
94
+ sendHeaders.set("Host", targetURL.host);
95
+ const hasBody = !["GET", "HEAD"].includes(req.method);
96
+ const proxyReq = new Request(targetURL.toString(), {
97
+ method: req.method,
98
+ headers: sendHeaders,
99
+ body: hasBody ? req.body : void 0,
100
+ redirect: "follow",
101
+ // Node.js (undici) requires duplex:'half' when body is a ReadableStream
102
+ ...hasBody ? { duplex: "half" } : {}
103
+ });
104
+ const res = await fetch(proxyReq);
105
+ const body = await res.arrayBuffer();
106
+ const clonedRes = new Headers(res.headers);
107
+ clonedRes.delete("content-length");
108
+ clonedRes.delete("content-encoding");
109
+ if (proxyCORS) {
110
+ Object.entries(getCORSHeaders(req)).forEach(([key, value]) => {
111
+ clonedRes.set(key, value);
112
+ });
113
+ }
114
+ return new Response(body, {
115
+ status: res.status,
116
+ statusText: res.statusText,
117
+ headers: clonedRes
118
+ });
119
+ }
120
+ }
121
+ return void 0;
122
+ };
123
+ };
124
+
125
+ // src/utils/response.tsx
126
+ var ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
127
+ var escAttr = (s) => s.replace(/[&<>"]/g, (c) => ESC[c] ?? c);
128
+ var escText = (s) => s.replace(/[&<>]/g, (c) => ESC[c] ?? c);
129
+ var ATTR = {
130
+ className: "class",
131
+ htmlFor: "for",
132
+ httpEquiv: "http-equiv",
133
+ charSet: "charset",
134
+ crossOrigin: "crossorigin",
135
+ noModule: "nomodule",
136
+ referrerPolicy: "referrerpolicy",
137
+ fetchPriority: "fetchpriority",
138
+ hrefLang: "hreflang"
139
+ };
140
+ function renderHeadTag(tag, id, opts, selfClose = false) {
141
+ let attrs = ` id="${escAttr(id)}"`;
142
+ let inner = "";
143
+ for (const [k, v] of Object.entries(opts)) {
144
+ if (k === "key" || k === "children") continue;
145
+ if (k === "dangerouslySetInnerHTML") {
146
+ inner = v.__html ?? "";
147
+ continue;
148
+ }
149
+ const attr = ATTR[k] ?? k;
150
+ if (v === true) attrs += ` ${attr}`;
151
+ else if (v !== false && v != null) attrs += ` ${attr}="${escAttr(String(v))}"`;
152
+ }
153
+ return selfClose ? `<${tag}${attrs}>` : `<${tag}${attrs}>${inner}</${tag}>`;
154
+ }
155
+ function buildHeadHtml(seoData) {
156
+ let html = `<title>${escText(seoData.title ?? "")}</title>`;
157
+ for (const [id, opts] of Object.entries(seoData.meta))
158
+ html += renderHeadTag("meta", id, opts, true);
159
+ for (const [id, opts] of Object.entries(seoData.link))
160
+ html += renderHeadTag("link", id, opts, true);
161
+ for (const [id, opts] of Object.entries(seoData.style))
162
+ html += renderHeadTag("style", id, opts);
163
+ for (const [id, opts] of Object.entries(seoData.script))
164
+ html += renderHeadTag("script", id, opts);
165
+ return html;
166
+ }
167
+ var getReactResponse = async (req, opts) => {
168
+ const App = opts.document.body;
169
+ const { getInitProps, getFinalProps } = opts.document;
170
+ const context = {
171
+ head: { title: "Hadars App", meta: {}, link: {}, style: {}, script: {}, status: 200 }
172
+ };
173
+ let props = {
174
+ ...getInitProps ? await getInitProps(req, opts.staticCtx) : {},
175
+ location: req.location,
176
+ context
177
+ };
178
+ const unsuspend = { cache: /* @__PURE__ */ new Map() };
179
+ globalThis.__hadarsUnsuspend = unsuspend;
180
+ globalThis.__hadarsContext = context;
181
+ const element = createElement(App, props);
182
+ try {
183
+ await renderPreflight(element);
184
+ } finally {
185
+ globalThis.__hadarsUnsuspend = null;
186
+ globalThis.__hadarsContext = null;
187
+ }
188
+ const status = context.head.status;
189
+ const getAppBody = async () => {
190
+ globalThis.__hadarsUnsuspend = unsuspend;
191
+ globalThis.__hadarsContext = context;
192
+ try {
193
+ return await renderToString(element);
194
+ } finally {
195
+ globalThis.__hadarsUnsuspend = null;
196
+ globalThis.__hadarsContext = null;
197
+ }
198
+ };
199
+ const finalize = async () => {
200
+ const restProps = getFinalProps ? await getFinalProps(props) : props;
201
+ const serverData = {};
202
+ let hasServerData = false;
203
+ for (const [key, entry] of unsuspend.cache) {
204
+ if (entry.status === "fulfilled") {
205
+ serverData[key] = entry.value;
206
+ hasServerData = true;
207
+ }
208
+ }
209
+ return {
210
+ clientProps: {
211
+ ...restProps,
212
+ location: req.location,
213
+ ...hasServerData ? { __serverData: serverData } : {}
214
+ }
215
+ };
216
+ };
217
+ return { head: context.head, status, getAppBody, finalize };
218
+ };
219
+
220
+ // src/utils/ssrHandler.ts
221
+ var HEAD_MARKER = '<meta name="HADARS_HEAD">';
222
+ var BODY_MARKER = '<meta name="HADARS_BODY">';
223
+ var encoder = new TextEncoder();
224
+ async function buildSsrHtml(bodyHtml, clientProps, headHtml, getPrecontentHtml) {
225
+ const [precontentHtml, postContent] = await Promise.resolve(getPrecontentHtml(headHtml));
226
+ const scriptContent = JSON.stringify({ hadars: { props: clientProps } }).replace(/</g, "\\u003c");
227
+ return precontentHtml + `<div id="app">${bodyHtml}</div><script id="hadars" type="application/json">${scriptContent}</script>` + postContent;
228
+ }
229
+ var makePrecontentHtmlGetter = (htmlFilePromise) => {
230
+ let preHead = null;
231
+ let postHead = null;
232
+ let postContent = null;
233
+ return (headHtml) => {
234
+ if (preHead !== null) {
235
+ return [preHead + headHtml + postHead, postContent];
236
+ }
237
+ return htmlFilePromise.then((html) => {
238
+ const headEnd = html.indexOf(HEAD_MARKER);
239
+ const contentStart = html.indexOf(BODY_MARKER);
240
+ preHead = html.slice(0, headEnd);
241
+ postHead = html.slice(headEnd + HEAD_MARKER.length, contentStart);
242
+ postContent = html.slice(contentStart + BODY_MARKER.length);
243
+ return [preHead + headHtml + postHead, postContent];
244
+ });
245
+ };
246
+ };
247
+ async function transformStream(data, stream) {
248
+ const writer = stream.writable.getWriter();
249
+ writer.write(data);
250
+ writer.close();
251
+ const chunks = [];
252
+ const reader = stream.readable.getReader();
253
+ while (true) {
254
+ const { done, value } = await reader.read();
255
+ if (done) break;
256
+ chunks.push(value);
257
+ }
258
+ const total = chunks.reduce((n, c) => n + c.length, 0);
259
+ const out = new Uint8Array(total);
260
+ let offset = 0;
261
+ for (const c of chunks) {
262
+ out.set(c, offset);
263
+ offset += c.length;
264
+ }
265
+ return out;
266
+ }
267
+ var gzipCompress = (d) => transformStream(d, new globalThis.CompressionStream("gzip"));
268
+ var gzipDecompress = (d) => transformStream(d, new globalThis.DecompressionStream("gzip"));
269
+ async function buildCacheEntry(res, ttl) {
270
+ const buf = await res.arrayBuffer();
271
+ const body = await gzipCompress(new Uint8Array(buf));
272
+ const headers = [];
273
+ res.headers.forEach((v, k) => {
274
+ if (k.toLowerCase() !== "content-encoding" && k.toLowerCase() !== "content-length") {
275
+ headers.push([k, v]);
276
+ }
277
+ });
278
+ headers.push(["content-encoding", "gzip"]);
279
+ return { body, status: res.status, headers, expiresAt: ttl != null ? Date.now() + ttl : null };
280
+ }
281
+ async function serveFromEntry(entry, req) {
282
+ const accept = req.headers.get("Accept-Encoding") ?? "";
283
+ if (accept.includes("gzip")) {
284
+ return new Response(entry.body.buffer, { status: entry.status, headers: entry.headers });
285
+ }
286
+ const plain = await gzipDecompress(entry.body);
287
+ const headers = entry.headers.filter(([k]) => k.toLowerCase() !== "content-encoding");
288
+ return new Response(plain.buffer, { status: entry.status, headers });
289
+ }
290
+ function createRenderCache(opts, handler) {
291
+ const store = /* @__PURE__ */ new Map();
292
+ const inFlight = /* @__PURE__ */ new Map();
293
+ return async (req, ctx) => {
294
+ const hadarsReq = parseRequest(req);
295
+ const cacheOpts = await opts(hadarsReq);
296
+ const key = cacheOpts?.key ?? null;
297
+ if (key != null) {
298
+ const entry = store.get(key);
299
+ if (entry) {
300
+ const expired = entry.expiresAt != null && Date.now() >= entry.expiresAt;
301
+ if (!expired) return serveFromEntry(entry, req);
302
+ store.delete(key);
303
+ }
304
+ let flight = inFlight.get(key);
305
+ if (!flight) {
306
+ const ttl = cacheOpts?.ttl;
307
+ flight = handler(new Request(req), ctx).then(async (res) => {
308
+ if (!res || res.status < 200 || res.status >= 300 || res.headers.has("set-cookie")) {
309
+ return null;
310
+ }
311
+ const newEntry2 = await buildCacheEntry(res, ttl);
312
+ store.set(key, newEntry2);
313
+ return newEntry2;
314
+ }).catch(() => null).finally(() => inFlight.delete(key));
315
+ inFlight.set(key, flight);
316
+ }
317
+ const newEntry = await flight;
318
+ if (newEntry) return serveFromEntry(newEntry, req);
319
+ }
320
+ return handler(req, ctx);
321
+ };
322
+ }
323
+
324
+ export {
325
+ parseRequest,
326
+ createProxyHandler,
327
+ buildHeadHtml,
328
+ getReactResponse,
329
+ buildSsrHtml,
330
+ makePrecontentHtmlGetter,
331
+ createRenderCache
332
+ };