weifuwu 0.18.2 → 0.18.4

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 (78) hide show
  1. package/cli.ts +10 -101
  2. package/dist/cli.js +7 -95
  3. package/dist/dist/agent/client.d.ts +2 -0
  4. package/dist/dist/agent/index.d.ts +2 -0
  5. package/dist/dist/agent/migrate.d.ts +6 -0
  6. package/dist/dist/agent/rest.d.ts +13 -0
  7. package/dist/dist/agent/run.d.ts +17 -0
  8. package/dist/dist/agent/types.d.ts +51 -0
  9. package/dist/dist/ai/workflow.d.ts +14 -0
  10. package/dist/dist/analytics.d.ts +15 -0
  11. package/dist/dist/client-locale.d.ts +5 -0
  12. package/dist/dist/client-pref.d.ts +3 -0
  13. package/dist/dist/client-state.d.ts +22 -0
  14. package/dist/dist/client-theme.d.ts +7 -0
  15. package/dist/dist/compress.d.ts +6 -0
  16. package/dist/dist/cookie.d.ts +12 -0
  17. package/dist/dist/deploy/config.d.ts +2 -0
  18. package/dist/dist/deploy/gateway.d.ts +2 -0
  19. package/dist/dist/deploy/index.d.ts +4 -0
  20. package/dist/dist/deploy/manager.d.ts +16 -0
  21. package/dist/dist/deploy/process.d.ts +14 -0
  22. package/dist/dist/deploy/types.d.ts +62 -0
  23. package/dist/dist/head.d.ts +6 -0
  24. package/dist/dist/helmet.d.ts +18 -0
  25. package/dist/dist/iii/client.d.ts +2 -0
  26. package/dist/dist/iii/index.d.ts +4 -0
  27. package/dist/dist/iii/register-worker.d.ts +10 -0
  28. package/dist/dist/iii/rest.d.ts +3 -0
  29. package/dist/dist/iii/stream.d.ts +82 -0
  30. package/dist/dist/iii/types.d.ts +133 -0
  31. package/dist/dist/iii/worker.d.ts +2 -0
  32. package/dist/dist/iii/ws.d.ts +29 -0
  33. package/dist/dist/index.js +8180 -0
  34. package/dist/dist/messager/agent.d.ts +6 -0
  35. package/dist/dist/messager/client.d.ts +2 -0
  36. package/dist/dist/messager/index.d.ts +2 -0
  37. package/dist/dist/messager/migrate.d.ts +2 -0
  38. package/dist/dist/messager/rest.d.ts +15 -0
  39. package/dist/dist/messager/types.d.ts +56 -0
  40. package/dist/dist/messager/ws.d.ts +14 -0
  41. package/dist/dist/preferences.d.ts +14 -0
  42. package/dist/dist/react.d.ts +12 -0
  43. package/dist/dist/react.js +637 -0
  44. package/dist/dist/request-id.d.ts +6 -0
  45. package/dist/dist/seo.d.ts +39 -0
  46. package/dist/dist/ssr/compile.d.ts +2 -0
  47. package/dist/{ssr → dist/ssr}/index.d.ts +1 -1
  48. package/dist/{ssr → dist/ssr}/index.js +372 -375
  49. package/dist/dist/ssr/ssr.d.ts +2 -0
  50. package/dist/dist/tenant/client.d.ts +2 -0
  51. package/dist/dist/tenant/graphql.d.ts +3 -0
  52. package/dist/dist/tenant/index.d.ts +2 -0
  53. package/dist/dist/tenant/migrate.d.ts +6 -0
  54. package/dist/dist/tenant/rest.d.ts +3 -0
  55. package/dist/dist/tenant/schema.d.ts +5 -0
  56. package/dist/dist/tenant/types.d.ts +48 -0
  57. package/dist/dist/tenant/utils.d.ts +10 -0
  58. package/dist/dist/types.d.ts +19 -0
  59. package/dist/dist/use-flash-message.d.ts +1 -0
  60. package/dist/error-boundary.d.ts +2 -0
  61. package/dist/index.d.ts +7 -0
  62. package/dist/index.js +213 -53
  63. package/dist/layout.d.ts +2 -0
  64. package/dist/live.d.ts +6 -0
  65. package/dist/not-found.d.ts +2 -0
  66. package/dist/router.d.ts +9 -9
  67. package/dist/ssr.d.ts +2 -0
  68. package/dist/stream.d.ts +14 -0
  69. package/dist/tailwind.d.ts +2 -0
  70. package/package.json +3 -4
  71. package/dist/ssr/ssr.d.ts +0 -3
  72. /package/dist/{ssr/compile.d.ts → compile.d.ts} +0 -0
  73. /package/dist/{ssr → dist/ssr}/error-boundary.d.ts +0 -0
  74. /package/dist/{ssr → dist/ssr}/layout.d.ts +0 -0
  75. /package/dist/{ssr → dist/ssr}/live.d.ts +0 -0
  76. /package/dist/{ssr → dist/ssr}/not-found.d.ts +0 -0
  77. /package/dist/{ssr → dist/ssr}/stream.d.ts +0 -0
  78. /package/dist/{ssr → dist/ssr}/tailwind.d.ts +0 -0
@@ -0,0 +1,637 @@
1
+ // use-websocket.ts
2
+ import { useEffect, useRef, useCallback, useState } from "react";
3
+ var RECONNECT_DELAY = 3e3;
4
+ var MAX_RETRIES = 10;
5
+ function resolveUrl(url) {
6
+ return typeof url === "function" ? url() : url;
7
+ }
8
+ function useWebsocket(url, options) {
9
+ const { onMessage, reconnect: reconnectOpt = true, protocols, enabled = true } = options ?? {};
10
+ const [lastMessage, setLastMessage] = useState(null);
11
+ const [readyState, setReadyState] = useState(WebSocket.CLOSED);
12
+ const wsRef = useRef(null);
13
+ const retryRef = useRef(0);
14
+ const timerRef = useRef(void 0);
15
+ const mountedRef = useRef(true);
16
+ const shouldReconnectRef = useRef(true);
17
+ const urlRef = useRef(url);
18
+ const optsRef = useRef({ onMessage, reconnectOpt, protocols });
19
+ urlRef.current = url;
20
+ optsRef.current = { onMessage, reconnectOpt, protocols };
21
+ const cleanup = useCallback(() => {
22
+ clearTimeout(timerRef.current);
23
+ wsRef.current?.close();
24
+ wsRef.current = null;
25
+ }, []);
26
+ const connect = useCallback(() => {
27
+ if (!mountedRef.current || !enabled) return;
28
+ const resolved = resolveUrl(urlRef.current);
29
+ if (!resolved) return;
30
+ wsRef.current?.close();
31
+ const ws = new WebSocket(resolved, optsRef.current.protocols);
32
+ wsRef.current = ws;
33
+ setReadyState(WebSocket.CONNECTING);
34
+ ws.addEventListener("open", () => {
35
+ if (!mountedRef.current) return;
36
+ retryRef.current = 0;
37
+ setReadyState(WebSocket.OPEN);
38
+ });
39
+ ws.addEventListener("message", (e) => {
40
+ if (!mountedRef.current) return;
41
+ const data = typeof e.data === "string" ? e.data : String(e.data);
42
+ setLastMessage(data);
43
+ optsRef.current.onMessage?.(data);
44
+ });
45
+ ws.addEventListener("close", () => {
46
+ if (!mountedRef.current) return;
47
+ setReadyState(WebSocket.CLOSED);
48
+ const ro = optsRef.current.reconnectOpt;
49
+ if (ro && shouldReconnectRef.current && mountedRef.current) {
50
+ const maxRetries = typeof ro === "object" ? ro.maxRetries ?? MAX_RETRIES : MAX_RETRIES;
51
+ const delay = typeof ro === "object" ? ro.delay ?? RECONNECT_DELAY : RECONNECT_DELAY;
52
+ if (retryRef.current < maxRetries) {
53
+ retryRef.current++;
54
+ timerRef.current = setTimeout(() => connect(), delay);
55
+ }
56
+ }
57
+ });
58
+ }, [enabled]);
59
+ useEffect(() => {
60
+ mountedRef.current = true;
61
+ shouldReconnectRef.current = true;
62
+ if (enabled) connect();
63
+ return () => {
64
+ mountedRef.current = false;
65
+ cleanup();
66
+ };
67
+ }, [enabled, connect, cleanup]);
68
+ const send = useCallback((data) => {
69
+ wsRef.current?.send(data);
70
+ }, []);
71
+ const close = useCallback(() => {
72
+ shouldReconnectRef.current = false;
73
+ cleanup();
74
+ setReadyState(WebSocket.CLOSED);
75
+ }, [cleanup]);
76
+ const reconnectFn = useCallback(() => {
77
+ retryRef.current = 0;
78
+ shouldReconnectRef.current = true;
79
+ cleanup();
80
+ connect();
81
+ }, [cleanup, connect]);
82
+ return { send, close, readyState, lastMessage, reconnect: reconnectFn };
83
+ }
84
+
85
+ // use-action.ts
86
+ import { useState as useState2, useCallback as useCallback2, useRef as useRef2 } from "react";
87
+ function getCsrfToken() {
88
+ if (typeof document === "undefined") return void 0;
89
+ const match = document.cookie.match(/(?:^|;\s*)_csrf=([^;]+)/);
90
+ return match ? decodeURIComponent(match[1]) : void 0;
91
+ }
92
+ function useAction(url, options) {
93
+ const { method = "POST", headers, onSuccess, onError } = options ?? {};
94
+ const [data, setData] = useState2(null);
95
+ const [error, setError] = useState2(null);
96
+ const [pending, setPending] = useState2(false);
97
+ const mountedRef = useRef2(true);
98
+ const submit = useCallback2(async (body) => {
99
+ setPending(true);
100
+ setError(null);
101
+ try {
102
+ const csrfToken = getCsrfToken();
103
+ const hdrs = { ...headers };
104
+ if (csrfToken) hdrs["x-csrf-token"] = csrfToken;
105
+ if (body && typeof body === "object" && !(body instanceof FormData)) {
106
+ hdrs["content-type"] = "application/json";
107
+ }
108
+ const res = await fetch(url, {
109
+ method,
110
+ headers: hdrs,
111
+ body: body instanceof FormData ? body : body !== void 0 ? JSON.stringify(body) : void 0
112
+ });
113
+ if (!res.ok) {
114
+ const text = await res.text();
115
+ throw new Error(text || `HTTP ${res.status}`);
116
+ }
117
+ const result = res.status === 204 ? void 0 : await res.json();
118
+ if (mountedRef.current) {
119
+ setData(result);
120
+ onSuccess?.(result);
121
+ }
122
+ return result;
123
+ } catch (err) {
124
+ const e = err instanceof Error ? err : new Error(String(err));
125
+ if (mountedRef.current) {
126
+ setError(e);
127
+ onError?.(e);
128
+ }
129
+ return void 0;
130
+ } finally {
131
+ if (mountedRef.current) setPending(false);
132
+ }
133
+ }, [url, method, headers, onSuccess, onError]);
134
+ const reset = useCallback2(() => {
135
+ setData(null);
136
+ setError(null);
137
+ }, []);
138
+ return { submit, data, error, pending, reset };
139
+ }
140
+
141
+ // client-router.ts
142
+ import { createElement, useCallback as useCallback3, useState as useState3, useEffect as useEffect2 } from "react";
143
+
144
+ // client-pref.ts
145
+ var interceptors = [];
146
+ function addInterceptor(fn) {
147
+ interceptors.push(fn);
148
+ }
149
+ async function runInterceptors(url) {
150
+ for (const fn of interceptors) {
151
+ if (await fn(url)) return true;
152
+ }
153
+ return false;
154
+ }
155
+
156
+ // client-router.ts
157
+ var _navigating = false;
158
+ var _listeners = [];
159
+ function onNavigate(fn) {
160
+ _listeners.push(fn);
161
+ return () => {
162
+ _listeners = _listeners.filter((l) => l !== fn);
163
+ };
164
+ }
165
+ function setNavigating(v) {
166
+ _navigating = v;
167
+ for (const fn of _listeners) fn(v);
168
+ }
169
+ async function navigate(href) {
170
+ if (typeof document === "undefined") return;
171
+ const url = new URL(href, location.origin);
172
+ if (url.origin !== location.origin) {
173
+ location.href = href;
174
+ return;
175
+ }
176
+ if (await runInterceptors(url)) return;
177
+ const scrollPos = [window.scrollX, window.scrollY];
178
+ setNavigating(true);
179
+ try {
180
+ const html = await fetch(url.pathname + url.search, {
181
+ headers: { accept: "text/html" }
182
+ }).then((r) => r.text());
183
+ const doc = new DOMParser().parseFromString(html, "text/html");
184
+ const rootEl = doc.getElementById("__weifuwu_root");
185
+ if (!rootEl) {
186
+ location.href = href;
187
+ return;
188
+ }
189
+ const newHtml = rootEl.innerHTML;
190
+ const propsMatch = html.match(/window\.__WEIFUWU_PROPS=(.+?)<\/script>/);
191
+ if (!propsMatch) {
192
+ location.href = href;
193
+ return;
194
+ }
195
+ const bundleMatch = html.match(/src="(\/__wfw\/client\/[^"]+\.js)"/);
196
+ const bundleUrl = bundleMatch ? bundleMatch[1] : null;
197
+ applyHead(html);
198
+ const currentRoot = document.getElementById("__weifuwu_root");
199
+ if (!currentRoot) {
200
+ location.href = href;
201
+ return;
202
+ }
203
+ ;
204
+ window.__WEIFUWU_PROPS = JSON.parse(propsMatch[1]);
205
+ history.pushState(null, "", url.pathname + url.search);
206
+ currentRoot.innerHTML = newHtml;
207
+ const ctxMatch = html.match(/window\.__WEIFUWU_CTX=(.+?)<\/script>/);
208
+ if (ctxMatch) {
209
+ try {
210
+ window.__WEIFUWU_CTX = JSON.parse(ctxMatch[1]);
211
+ } catch {
212
+ }
213
+ }
214
+ const localeMatch = html.match(/window\.__LOCALE_DATA__=(.+?)<\/script>/);
215
+ if (localeMatch) {
216
+ try {
217
+ window.__LOCALE_DATA__ = JSON.parse(localeMatch[1]);
218
+ } catch {
219
+ }
220
+ }
221
+ if (bundleUrl) {
222
+ try {
223
+ await import(
224
+ /* @vite-ignore */
225
+ `${bundleUrl}`
226
+ );
227
+ } catch (e) {
228
+ console.error("[weifuwu/router] hydration failed:", e);
229
+ location.href = href;
230
+ }
231
+ }
232
+ window.scrollTo(scrollPos[0], scrollPos[1]);
233
+ } finally {
234
+ setNavigating(false);
235
+ }
236
+ }
237
+ function applyHead(html) {
238
+ const match = html.match(/<template id="__wfw_head">([\s\S]*?)<\/template>/);
239
+ if (!match) return;
240
+ const headHtml = match[1];
241
+ const titleMatch = headHtml.match(/<title>([^<]*)<\/title>/);
242
+ if (titleMatch) document.title = titleMatch[1];
243
+ const doc = new DOMParser().parseFromString(headHtml, "text/html");
244
+ const newMeta = doc.querySelectorAll("meta");
245
+ const existing = document.querySelectorAll("head meta");
246
+ const newNames = new Set(Array.from(newMeta).map((m) => m.getAttribute("name") || m.getAttribute("property") || ""));
247
+ for (const el of existing) {
248
+ const key = el.getAttribute("name") || el.getAttribute("property") || "";
249
+ if (!newNames.has(key)) el.remove();
250
+ }
251
+ for (const el of newMeta) {
252
+ const key = el.getAttribute("name") || el.getAttribute("property") || "";
253
+ let existingEl = null;
254
+ if (key) {
255
+ for (const m of document.head.querySelectorAll("meta")) {
256
+ if (m.getAttribute("name") === key || m.getAttribute("property") === key) {
257
+ existingEl = m;
258
+ break;
259
+ }
260
+ }
261
+ }
262
+ if (existingEl) {
263
+ for (const attr of el.attributes) existingEl.setAttribute(attr.name, attr.value);
264
+ } else {
265
+ document.head.appendChild(el.cloneNode());
266
+ }
267
+ }
268
+ const newLink = doc.querySelector('link[rel="canonical"]');
269
+ const existingLink = document.querySelector('link[rel="canonical"]');
270
+ if (newLink) {
271
+ if (existingLink) existingLink.setAttribute("href", newLink.getAttribute("href") || "");
272
+ else document.head.appendChild(newLink.cloneNode());
273
+ } else if (existingLink) {
274
+ existingLink.remove();
275
+ }
276
+ }
277
+ function useNavigate() {
278
+ return useCallback3((href) => navigate(href), []);
279
+ }
280
+ function useNavigating() {
281
+ const [v, setV] = useState3(false);
282
+ useEffect2(() => onNavigate(setV), []);
283
+ return v;
284
+ }
285
+ var prefetchCache = /* @__PURE__ */ new Map();
286
+ var PREFETCH_TTL = 6e4;
287
+ function Link({ href, children, onClick, prefetch, ...props }) {
288
+ const doNavigate = useNavigate();
289
+ useEffect2(() => {
290
+ if (!prefetch) return;
291
+ let el = document.querySelector(`a[href="${CSS.escape(href)}"]`);
292
+ if (!el) {
293
+ for (const a of document.querySelectorAll("a")) {
294
+ if (a.getAttribute("href") === href) {
295
+ el = a;
296
+ break;
297
+ }
298
+ }
299
+ }
300
+ if (!el) return;
301
+ const observer = new IntersectionObserver(([entry]) => {
302
+ if (entry.isIntersecting) prefetchPage(href);
303
+ }, { rootMargin: "200px" });
304
+ observer.observe(el);
305
+ return () => observer.disconnect();
306
+ }, [href, prefetch]);
307
+ const handleMouseEnter = useCallback3(() => {
308
+ if (prefetch) prefetchPage(href);
309
+ }, [href, prefetch]);
310
+ const handleClick = useCallback3((e) => {
311
+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
312
+ e.preventDefault();
313
+ doNavigate(href);
314
+ onClick?.(e);
315
+ }, [href, onClick, doNavigate]);
316
+ return createElement("a", {
317
+ href,
318
+ onClick: handleClick,
319
+ onMouseEnter: handleMouseEnter,
320
+ ...props
321
+ }, children);
322
+ }
323
+ async function prefetchPage(href) {
324
+ const cached = prefetchCache.get(href);
325
+ if (cached && Date.now() - cached.fetched < PREFETCH_TTL) return;
326
+ try {
327
+ const html = await fetch(href, { headers: { accept: "text/html" } }).then((r) => r.text());
328
+ prefetchCache.set(href, { html, fetched: Date.now() });
329
+ } catch {
330
+ }
331
+ }
332
+
333
+ // tsx-context.ts
334
+ import { createContext } from "react";
335
+ var DEFAULT_CTX = { params: {}, query: {}, parsed: {}, prefs: {}, loaderData: {}, env: {}, user: {} };
336
+ var KEY = "__WEIFUWU_CTX_STORE";
337
+ function getStore() {
338
+ if (typeof globalThis !== "undefined" && globalThis[KEY]) {
339
+ return globalThis[KEY];
340
+ }
341
+ const s = {
342
+ _ctx: DEFAULT_CTX,
343
+ _snapshot: { params: DEFAULT_CTX.params, query: DEFAULT_CTX.query, user: DEFAULT_CTX.user, parsed: DEFAULT_CTX.parsed, prefs: DEFAULT_CTX.prefs, env: DEFAULT_CTX.env },
344
+ _listeners: /* @__PURE__ */ new Set(),
345
+ _alsGetStore: null
346
+ };
347
+ if (typeof globalThis !== "undefined") {
348
+ globalThis[KEY] = s;
349
+ }
350
+ return s;
351
+ }
352
+ var store = getStore();
353
+ function setCtx(value) {
354
+ store._ctx = { ...store._ctx, ...value };
355
+ store._snapshot = { params: store._ctx.params, query: store._ctx.query, user: store._ctx.user, parsed: store._ctx.parsed, prefs: store._ctx.prefs, env: store._ctx.env };
356
+ store._listeners.forEach((fn) => fn());
357
+ }
358
+ function useCtx() {
359
+ const alsStore = store._alsGetStore?.();
360
+ const base = alsStore ?? store._ctx;
361
+ const data = typeof window !== "undefined" ? window.__WEIFUWU_CTX : null;
362
+ return { ...base, ...data };
363
+ }
364
+ function useLoaderData() {
365
+ const alsStore = store._alsGetStore?.();
366
+ const base = alsStore ?? store._ctx;
367
+ const data = typeof window !== "undefined" ? window.__WEIFUWU_CTX : null;
368
+ return { ...base, ...data }.loaderData;
369
+ }
370
+ var TsxContext = createContext(DEFAULT_CTX);
371
+
372
+ // head.tsx
373
+ import { createElement as createElement2 } from "react";
374
+ function Head({ children }) {
375
+ return createElement2("template", { id: "__wfw_head" }, children);
376
+ }
377
+
378
+ // client-state.ts
379
+ import { useSyncExternalStore as useSyncExternalStore2, useCallback as useCallback4, useEffect as useEffect3, useRef as useRef3, useState as useState4 } from "react";
380
+ function createStore(initial) {
381
+ let state = { ...initial };
382
+ const listeners = /* @__PURE__ */ new Set();
383
+ const getState = () => state;
384
+ const setState = (partial) => {
385
+ const next = typeof partial === "function" ? partial(state) : partial;
386
+ state = { ...state, ...next };
387
+ listeners.forEach((fn) => fn());
388
+ };
389
+ const subscribe = (listener) => {
390
+ listeners.add(listener);
391
+ return () => {
392
+ listeners.delete(listener);
393
+ };
394
+ };
395
+ const useStore = ((selector) => useSyncExternalStore2(
396
+ subscribe,
397
+ () => selector ? selector(state) : state
398
+ ));
399
+ useStore.getState = getState;
400
+ useStore.setState = setState;
401
+ useStore.subscribe = subscribe;
402
+ return useStore;
403
+ }
404
+ var dataCache = /* @__PURE__ */ new Map();
405
+ var inflight = /* @__PURE__ */ new Map();
406
+ var CACHE_TTL = 6e4;
407
+ function useFetch(url, options) {
408
+ const ttl = options?.ttl ?? CACHE_TTL;
409
+ const [state, setState] = useState4({
410
+ data: options?.fallback,
411
+ loading: !options?.fallback && !!url
412
+ });
413
+ const urlRef = useRef3(url);
414
+ urlRef.current = url;
415
+ useEffect3(() => {
416
+ if (!url) {
417
+ setState({ data: void 0, loading: false });
418
+ return;
419
+ }
420
+ if (typeof window === "undefined") return;
421
+ const u = url;
422
+ let cancelled = false;
423
+ const cached = dataCache.get(u);
424
+ if (cached && Date.now() - cached.timestamp < ttl) {
425
+ if (!cancelled) setState({
426
+ data: cached.data,
427
+ error: cached.error,
428
+ loading: false
429
+ });
430
+ return;
431
+ }
432
+ async function doFetch() {
433
+ if (!inflight.has(u)) {
434
+ inflight.set(u, fetch(u).then((r) => {
435
+ if (!r.ok) throw new Error(r.statusText || `HTTP ${r.status}`);
436
+ return r.json();
437
+ }));
438
+ }
439
+ const promise = inflight.get(u);
440
+ try {
441
+ const data = await promise;
442
+ dataCache.set(u, { data, error: null, timestamp: Date.now() });
443
+ if (!cancelled) setState({ data, loading: false });
444
+ } catch (err) {
445
+ dataCache.set(u, { data: null, error: err, timestamp: Date.now() });
446
+ if (!cancelled) setState({ error: err, loading: false });
447
+ }
448
+ }
449
+ doFetch();
450
+ return () => {
451
+ cancelled = true;
452
+ };
453
+ }, [url, ttl]);
454
+ const mutate = useCallback4(async (data) => {
455
+ const u = urlRef.current;
456
+ if (!u) return;
457
+ const uStr = u;
458
+ if (data !== void 0) {
459
+ dataCache.set(uStr, { data, error: null, timestamp: Date.now() });
460
+ setState({ data, loading: false, error: void 0 });
461
+ return;
462
+ }
463
+ inflight.delete(uStr);
464
+ try {
465
+ const res = await fetch(uStr);
466
+ if (!res.ok) throw new Error(res.statusText || `HTTP ${res.status}`);
467
+ const newData = await res.json();
468
+ dataCache.set(uStr, { data: newData, error: null, timestamp: Date.now() });
469
+ setState({ data: newData, loading: false, error: void 0 });
470
+ } catch (err) {
471
+ setState({ error: err, loading: false });
472
+ }
473
+ }, []);
474
+ return { data: state.data, error: state.error, loading: state.loading, mutate };
475
+ }
476
+ function notifyQueryListeners() {
477
+ if (typeof window === "undefined") return;
478
+ window.dispatchEvent(new PopStateEvent("popstate"));
479
+ }
480
+ function useQueryState(key, defaultValue = "") {
481
+ function getSnapshot() {
482
+ if (typeof window === "undefined") return defaultValue;
483
+ const params = new URLSearchParams(window.location.search);
484
+ return params.get(key) ?? defaultValue;
485
+ }
486
+ const value = useSyncExternalStore2(
487
+ (cb) => {
488
+ if (typeof window === "undefined") return () => {
489
+ };
490
+ window.addEventListener("popstate", cb);
491
+ return () => window.removeEventListener("popstate", cb);
492
+ },
493
+ getSnapshot,
494
+ () => defaultValue
495
+ );
496
+ const setValue = useCallback4((val) => {
497
+ if (typeof window === "undefined") return;
498
+ const resolved = typeof val === "function" ? val(getSnapshot()) : val;
499
+ const url = new URL(window.location.href);
500
+ if (resolved === defaultValue || resolved === "") {
501
+ url.searchParams.delete(key);
502
+ } else {
503
+ url.searchParams.set(key, resolved);
504
+ }
505
+ window.history.replaceState(null, "", url.toString());
506
+ notifyQueryListeners();
507
+ }, [key, defaultValue]);
508
+ return [value, setValue];
509
+ }
510
+
511
+ // client-locale.ts
512
+ function buildT() {
513
+ const messages = typeof window !== "undefined" ? window.__LOCALE_DATA__ : globalThis.__LOCALE_DATA__;
514
+ if (!messages) return (key, _p, fb) => fb ?? key;
515
+ return (key, params, fallback) => {
516
+ const msg = key.split(".").reduce((o, k) => o?.[k], messages);
517
+ if (msg === void 0 || msg === null) return fallback ?? key;
518
+ if (!params) return String(msg);
519
+ let result = String(msg);
520
+ for (const [k, v] of Object.entries(params)) result = result.replace(`{${k}}`, v);
521
+ return result;
522
+ };
523
+ }
524
+ addInterceptor(async (url) => {
525
+ const m = url.pathname.match(/^\/__lang\/(\w+)$/);
526
+ if (!m) return false;
527
+ try {
528
+ const res = await fetch(url.pathname, {
529
+ headers: { accept: "application/json" }
530
+ });
531
+ const data = await res.json();
532
+ const ctx = { ...window.__WEIFUWU_CTX || {}, params: {}, query: {} };
533
+ ctx.prefs = { ...ctx.prefs, locale: data.locale };
534
+ if (data.messages) window.__LOCALE_DATA__ = data.messages;
535
+ window.__WEIFUWU_CTX = ctx;
536
+ setCtx(ctx);
537
+ } catch {
538
+ location.href = url.href;
539
+ }
540
+ return true;
541
+ });
542
+ function useLocale() {
543
+ const ctx = useCtx();
544
+ return {
545
+ locale: ctx.prefs.locale,
546
+ setLocale: (locale) => navigate("/__lang/" + locale),
547
+ t: buildT()
548
+ };
549
+ }
550
+
551
+ // client-theme.ts
552
+ import { useEffect as useEffect4 } from "react";
553
+ function resolveTheme(theme) {
554
+ if (theme === "system") {
555
+ if (typeof window === "undefined") return "light";
556
+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
557
+ }
558
+ return theme;
559
+ }
560
+ var _mqListener = null;
561
+ function applyTheme(theme) {
562
+ if (typeof document === "undefined") return;
563
+ const resolved = resolveTheme(theme);
564
+ document.documentElement.dataset.theme = resolved;
565
+ if (theme === "system") {
566
+ if (!_mqListener) {
567
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
568
+ mq.addEventListener("change", (e) => {
569
+ if (window.__WEIFUWU_CTX?.prefs?.theme === "system") {
570
+ document.documentElement.dataset.theme = e.matches ? "dark" : "light";
571
+ }
572
+ });
573
+ _mqListener = mq;
574
+ }
575
+ }
576
+ }
577
+ addInterceptor(async (url) => {
578
+ const m = url.pathname.match(/^\/__theme\/(\w+)$/);
579
+ if (!m) return false;
580
+ try {
581
+ const res = await fetch(url.pathname, {
582
+ headers: { accept: "application/json" }
583
+ });
584
+ const data = await res.json();
585
+ const ctx = { ...window.__WEIFUWU_CTX || {}, params: {}, query: {} };
586
+ ctx.prefs = { ...ctx.prefs, theme: data.theme };
587
+ window.__WEIFUWU_CTX = ctx;
588
+ applyTheme(data.theme);
589
+ setCtx(ctx);
590
+ } catch {
591
+ location.href = url.href;
592
+ }
593
+ return true;
594
+ });
595
+ function useTheme() {
596
+ const ctx = useCtx();
597
+ const theme = ctx.prefs.theme ?? "system";
598
+ useEffect4(() => {
599
+ applyTheme(theme);
600
+ }, [theme]);
601
+ return {
602
+ theme,
603
+ resolvedTheme: resolveTheme(theme),
604
+ setTheme: (t) => navigate("/__theme/" + t)
605
+ };
606
+ }
607
+
608
+ // use-flash-message.ts
609
+ import { useState as useState5 } from "react";
610
+ function useFlashMessage() {
611
+ const [flash] = useState5(() => {
612
+ if (typeof window === "undefined") return null;
613
+ const raw = window.__WEIFUWU_CTX?.prefs?.flash;
614
+ if (!raw) return null;
615
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
616
+ });
617
+ return flash;
618
+ }
619
+ export {
620
+ Head,
621
+ Link,
622
+ TsxContext,
623
+ addInterceptor,
624
+ applyTheme,
625
+ createStore,
626
+ navigate,
627
+ useAction,
628
+ useFetch,
629
+ useFlashMessage,
630
+ useLoaderData,
631
+ useLocale,
632
+ useNavigate,
633
+ useNavigating,
634
+ useQueryState,
635
+ useTheme,
636
+ useWebsocket
637
+ };
@@ -0,0 +1,6 @@
1
+ import type { Middleware } from './types.ts';
2
+ export interface RequestIdOptions {
3
+ header?: string;
4
+ generator?: () => string;
5
+ }
6
+ export declare function requestId(options?: RequestIdOptions): Middleware;
@@ -0,0 +1,39 @@
1
+ import type { Middleware } from './types.ts';
2
+ import { Router } from './router.ts';
3
+ export interface RobotsRule {
4
+ userAgent?: string;
5
+ allow?: string | string[];
6
+ disallow?: string | string[];
7
+ }
8
+ export interface SitemapUrl {
9
+ loc: string;
10
+ lastmod?: string;
11
+ changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
12
+ priority?: number;
13
+ }
14
+ export interface SitemapConfig {
15
+ urls?: SitemapUrl[];
16
+ resolve?: () => SitemapUrl[] | Promise<SitemapUrl[]>;
17
+ cacheTTL?: number;
18
+ }
19
+ export interface SeoHeadersConfig {
20
+ 'X-Robots-Tag'?: string | ((path: string) => string | undefined);
21
+ }
22
+ export interface SeoOptions {
23
+ robots?: RobotsRule[];
24
+ sitemap?: SitemapConfig;
25
+ headers?: SeoHeadersConfig;
26
+ baseUrl?: string;
27
+ }
28
+ export declare function seoMiddleware(options?: SeoOptions): Middleware;
29
+ export declare function seo(options?: SeoOptions): Router;
30
+ export interface SeoTagsConfig {
31
+ title?: string;
32
+ description?: string;
33
+ ogImage?: string;
34
+ ogTitle?: string;
35
+ ogDescription?: string;
36
+ twitterCard?: 'summary' | 'summary_large_image';
37
+ canonical?: string;
38
+ }
39
+ export declare function seoTags(config: SeoTagsConfig): string;
@@ -0,0 +1,2 @@
1
+ export declare function clearCompileCache(): void;
2
+ export declare function compileTsx(path: string): Promise<any>;
@@ -1,4 +1,4 @@
1
- export { ssr, ssrBundleHandler } from './ssr.ts';
1
+ export { ssr } from './ssr.ts';
2
2
  export { layout } from './layout.ts';
3
3
  export { tailwind } from './tailwind.ts';
4
4
  export { notFound } from './not-found.ts';