weifuwu 0.17.26 → 0.18.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.
package/README.md CHANGED
@@ -88,7 +88,7 @@ app.get('/admin', mw, handler) // route-level
88
88
 
89
89
  ## Module Patterns
90
90
 
91
- All modules follow one of 5 patterns. The pattern letter is marked in each module's heading.
91
+ All modules follow one of 6 patterns. The pattern letter is marked in each module's heading.
92
92
 
93
93
  | Pattern | How to mount | Example |
94
94
  |---------|-------------|---------|
@@ -105,13 +105,28 @@ All modules follow one of 5 patterns. The pattern letter is marked in each modul
105
105
  ### agent [C]
106
106
 
107
107
  ```ts
108
- const a = agent({ pg })
108
+ const a = agent({ pg, model: openai('gpt-4o'), embeddingModel: openai.embedding('text-embedding-3-small') })
109
109
  await a.migrate()
110
110
  app.use('/api', a.router())
111
- await a.addKnowledge(agentId, 'Title', 'docs')
112
- a.run(agentId, { task: 'summarize' })
111
+ await a.addKnowledge(agentId, 'Title', 'some knowledge content')
112
+ a.run(agentId, { input: 'summarize the data', stream: true })
113
113
  ```
114
114
 
115
+ | Option | Type | Default | Description |
116
+ |--------|------|---------|-------------|
117
+ | `pg` | `object` | — | PostgreSQL client |
118
+ | `model` | `object` | — | AI model (e.g. `openai('gpt-4o')`) |
119
+ | `embeddingModel` | `object` | — | Embedding model for knowledge search |
120
+ | `embeddingDimension` | `number` | `1536` | Embedding vector dimension |
121
+ | `tools` | `object[]` | — | Custom tool definitions |
122
+
123
+ | Method | Description |
124
+ |--------|-------------|
125
+ | `.run(agentId, { input, stream?, messages? })` | Execute agent with input |
126
+ | `.addKnowledge(agentId, title, content)` | Add knowledge document |
127
+ | `.router()` | REST + WS API |
128
+ | `.close()` | Cleanup |
129
+
115
130
  ### aiStream [E]
116
131
 
117
132
  ```ts
@@ -147,17 +162,29 @@ app.use('/', a.router())
147
162
  ```ts
148
163
  app.use(auth({ token: 'sk-123' })) // static token
149
164
  app.use(auth({ header: 'X-API-Key', token: 'my-key' })) // custom header
150
- app.use(auth({ verify: async (token) => ({ sub: 'abc' }) })) // custom verify
165
+ app.use(auth({ verify: async (token, req) => ({ sub: 'abc' }) })) // custom verify → sets ctx.user
151
166
  app.get('/protected', auth({ proxy: 'http://auth:3000/validate' }), handler)
152
167
  ```
153
168
 
169
+ | Option | Type | Default | Description |
170
+ |--------|------|---------|-------------|
171
+ | `token` | `string` | — | Static token to match |
172
+ | `header` | `string` | `'Authorization'` | Header name |
173
+ | `verify` | `(token, req) => object\|null` | — | Verify function, return value sets `ctx.user` |
174
+ | `proxy` | `string` | — | Auth service URL to proxy requests to |
175
+
154
176
  ### compress [A]
155
177
 
156
178
  ```ts
157
- app.use(compress()) // brotli > gzip > deflate
158
- app.use(compress({ threshold: 2048 })) // only > 2KB
179
+ app.use(compress()) // brotli > gzip > deflate (min 1KB)
180
+ app.use(compress({ threshold: 2048, level: 4 })) // custom threshold and level
159
181
  ```
160
182
 
183
+ | Option | Type | Default | Description |
184
+ |--------|------|---------|-------------|
185
+ | `threshold` | `number` | `1024` | Minimum byte size to compress |
186
+ | `level` | `number` | `6` | Compression level (zlib) |
187
+
161
188
  ### cors [A]
162
189
 
163
190
  ```ts
@@ -167,18 +194,28 @@ app.use(cors({ origin: (o) => o.endsWith('.trusted.com') && o }))
167
194
  app.use(cors({ credentials: true, maxAge: 3600 }))
168
195
  ```
169
196
 
197
+ | Option | Type | Default | Description |
198
+ |--------|------|---------|-------------|
199
+ | `origin` | `string\|string[]\|function` | `'*'` | Allowed origins |
200
+ | `methods` | `string[]` | `['GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS']` | Allowed methods |
201
+ | `allowedHeaders` | `string[]` | — | Custom allowed headers |
202
+ | `exposedHeaders` | `string[]` | — | Response headers exposed to client |
203
+ | `credentials` | `boolean` | `false` | Allow cookies/credentials |
204
+ | `maxAge` | `number` | — | Preflight cache duration (seconds) |
205
+
170
206
  ### csrf [A]
171
207
 
172
208
  ```ts
173
209
  app.use(csrf())
174
- // ctx.csrfToken available in handlers
175
- // Auto-validates X-CSRF-Token header on POST/PUT/DELETE/PATCH
210
+ // ctx.csrfToken set on GET/HEAD/OPTIONS
211
+ // Auto-validates x-csrf-token or x-xsrf-token header on POST/PUT/DELETE/PATCH
212
+ // Falls back to body field matching the key name
176
213
  ```
177
214
 
178
215
  | Option | Default | Description |
179
216
  |--------|---------|-------------|
180
217
  | `cookie` | `'_csrf'` | Cookie name |
181
- | `header` | `'x-csrf-token'` | Header name |
218
+ | `header` | `'x-csrf-token'` | Header name (also accepts `x-xsrf-token`) |
182
219
  | `key` | `'_csrf'` | Body field fallback |
183
220
  | `excludeMethods` | `['GET','HEAD','OPTIONS']` | Skip validation |
184
221
 
@@ -186,31 +223,57 @@ app.use(csrf())
186
223
 
187
224
  ```ts
188
225
  import { deploy, defineConfig } from 'weifuwu'
189
- const config = defineConfig({ apps: [{ name: 'api', dir: './api', domain: 'api.example.com', port: 3001 }] })
190
- await deploy(config)
226
+ const config = defineConfig({
227
+ domain: 'example.com',
228
+ apps: {
229
+ api: { repo: 'git@github.com:user/api.git', entry: 'app.ts', port: 3001, subdomain: 'api' },
230
+ },
231
+ })
232
+ const server = await deploy(config)
233
+ // server.close(), server.ready, server.url
234
+ // server.apps.list(), server.apps.status(name), server.apps.deploy(name)
191
235
  ```
192
236
 
193
237
  ### health [D]
194
238
 
195
239
  ```ts
196
- app.use(health()) // GET /health → 200
197
- app.use(health({ checks: { db: async () => { await pg.sql`SELECT 1`; return { ok: true } } } }))
240
+ app.use(health({ path: '/health' }))
241
+ // Returns 200 on success, 503 when check throws
198
242
  ```
199
243
 
244
+ | Option | Type | Default | Description |
245
+ |--------|------|---------|-------------|
246
+ | `path` | `string` | `'/health'` | Health check endpoint |
247
+ | `check` | `() => Promise<void>` | — | Async function; throws → 503 |
248
+
200
249
  ### helmet [A]
201
250
 
202
- 13 security headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, etc.
251
+ 15 security headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, etc.
203
252
 
204
253
  ```ts
205
254
  app.use(helmet())
206
255
  app.use(helmet({ contentSecurityPolicy: "default-src 'self'", xFrameOptions: 'DENY' }))
207
256
  ```
208
257
 
258
+ | Option | Default | Description |
259
+ |--------|---------|-------------|
260
+ | `contentSecurityPolicy` | `"default-src 'self'"` | CSP policy |
261
+ | `xFrameOptions` | `'SAMEORIGIN'` | Frame-embedding policy |
262
+ | `strictTransportSecurity` | `'max-age=15552000; includeSubDomains'` | HSTS |
263
+ | `referrerPolicy` | `'no-referrer'` | Referrer header |
264
+ | `xContentTypeOptions` | `'nosniff'` | MIME sniffing protection |
265
+ | `permissionsPolicy` | — | Feature permissions policy |
266
+ | `crossOriginEmbedderPolicy` | — | COEP header |
267
+ | `crossOriginOpenerPolicy` | — | COOP header |
268
+ | `crossOriginResourcePolicy` | — | CORP header |
269
+
209
270
  ### iii [C] — Worker / Function / Trigger
210
271
 
211
272
  ```ts
273
+ import { createWorker } from 'weifuwu'
212
274
  const engine = iii({ pg, redis })
213
275
  app.use('/iii', engine.router())
276
+ app.ws('/iii', engine.wsHandler())
214
277
 
215
278
  const w = createWorker('orders')
216
279
  w.registerFunction('orders::create', async (payload) => db.query('INSERT INTO orders ...', [payload.items]))
@@ -221,8 +284,15 @@ await engine.trigger({ function_id: 'orders::create', payload: { items: ['apple'
221
284
  | Method | Description |
222
285
  |--------|-------------|
223
286
  | `.addWorker(w)` | Register a worker |
224
- | `.trigger({ function_id, payload, action? })` | Invoke a function (sync or void) |
287
+ | `.removeWorker(w)` | Remove a worker |
288
+ | `.trigger({ function_id, payload, action?, timeout_ms? })` | Invoke a function |
289
+ | `.listWorkers()` | List registered workers |
290
+ | `.listFunctions()` | List registered functions |
291
+ | `.listTriggers()` | List registered triggers |
225
292
  | `.router()` | REST + WS API |
293
+ | `.wsHandler()` | WebSocket handler |
294
+ | `.migrate()` | DB setup |
295
+ | `.shutdown()` | Clean shutdown |
226
296
 
227
297
  ### logdb [C]
228
298
 
@@ -233,9 +303,14 @@ const logger = logdb({ pg })
233
303
  await logger.migrate()
234
304
  app.use('/logs', logger.router())
235
305
  await logger.clean(12) // drop partitions older than 12 months
236
- await logger.log({ level: 'info', source: 'app', message: 'hello' })
306
+ await logger.log({ level: 'info', source: 'app', message: 'hello', metadata: { userId: 1 } })
237
307
  ```
238
308
 
309
+ | Option | Type | Default | Description |
310
+ |--------|------|---------|-------------|
311
+ | `pg` | `object` | — | PostgreSQL client |
312
+ | `table` | `string` | `'_log_entries'` | Table name |
313
+
239
314
  | Method | Path | Description |
240
315
  |--------|------|-------------|
241
316
  | POST | `/` | Create log entry |
@@ -252,10 +327,16 @@ app.use(logger({ format: 'combined' })) // with query params
252
327
  ### mailer
253
328
 
254
329
  ```ts
255
- const mail = mailer({ host: 'smtp.example.com', port: 587, auth: { user, pass } })
256
- await mail.send({ to: 'user@test.com', subject: 'Hello', text: 'Body', html: '<p>Body</p>' })
330
+ const mail = mailer({ from: 'noreply@example.com', transport: 'smtp://user:pass@smtp.example.com:587' })
331
+ await mail.send({ to: 'user@test.com', subject: 'Hello', text: 'Body', html: '<p>Body</p>', cc: 'admin@test.com' })
257
332
  ```
258
333
 
334
+ | Option | Type | Default | Description |
335
+ |--------|------|---------|-------------|
336
+ | `transport` | `string\|object` | — | Nodemailer transport config or connection string |
337
+ | `from` | `string` | — | Default sender address |
338
+ | `send` | `function` | — | Custom send function (alternative to transport) |
339
+
259
340
  ### messager [C]
260
341
 
261
342
  Real-time chat with channels, WebSocket, agent routing.
@@ -263,21 +344,44 @@ Real-time chat with channels, WebSocket, agent routing.
263
344
  ```ts
264
345
  const msg = messager({ pg, agents, redis: redis() })
265
346
  await msg.migrate()
266
- app.ws('/ws', u.middleware(), msg.wsHandler())
267
- await msg.send(channelId, 'System message', { sender_type: 'system' })
347
+ app.ws('/ws', msg.wsHandler())
348
+ await msg.send(channelId, 'System message', { sender_type: 'system', sender_id: 'bot' })
268
349
  ```
269
350
 
351
+ | Method | Description |
352
+ |--------|-------------|
353
+ | `.wsHandler()` | WebSocket handler (channels, typing, read receipts) |
354
+ | `.send(channel, content, opts?)` | Send message to channel |
355
+ | `.router()` | REST API |
356
+ | `.close()` | Cleanup |
357
+
270
358
  ### opencode [C]
271
359
 
272
360
  AI programming assistant.
273
361
 
274
362
  ```ts
275
- const oc = await opencode({ pg, permissions: { bash: { allow: true }, write: { allow: false } } })
363
+ const oc = await opencode({
364
+ pg,
365
+ model: openai('gpt-4o'),
366
+ workspace: '/home/user/project',
367
+ permissions: { bash: { allow: true }, write: { allow: false } },
368
+ })
276
369
  await oc.migrate()
277
370
  app.use('/opencode', await oc.router())
278
371
  app.ws('/opencode', oc.wsHandler())
279
372
  ```
280
373
 
374
+ | Option | Type | Default | Description |
375
+ |--------|------|---------|-------------|
376
+ | `pg` | `object` | — | PostgreSQL client |
377
+ | `model` | `object` | — | AI model |
378
+ | `baseURL` | `string` | — | OpenAI-compatible API base URL |
379
+ | `apiKey` | `string` | — | API key for the model |
380
+ | `workspace` | `string` | — | Project directory |
381
+ | `systemPrompt` | `string` | — | Custom system prompt |
382
+ | `skills` | `object[]` | — | Custom skill definitions |
383
+ | `permissions` | `object` | — | Tool permission rules |
384
+
281
385
  ### postgres [B]
282
386
 
283
387
  ```ts
@@ -285,6 +389,14 @@ const pg = postgres() // reads DATABASE_URL
285
389
  app.use(pg) // injects ctx.sql
286
390
  ```
287
391
 
392
+ | Option | Type | Default | Description |
393
+ |--------|------|---------|-------------|
394
+ | `connection` | `string` | `DATABASE_URL` env | PostgreSQL connection string |
395
+ | `max` | `number` | `10` | Max pool connections |
396
+ | `ssl` | `boolean\|object` | — | SSL options |
397
+ | `idle_timeout` | `number` | `30` | Idle timeout (seconds) |
398
+ | `connect_timeout` | `number` | `30` | Connection timeout |
399
+
288
400
  ```ts
289
401
  // Type-safe DDL
290
402
  const users = pgTable('_users', { id: serial('id').primaryKey(), name: text('name').notNull(), email: text('email').unique().notNull(), active: boolean('active').default(true), ...timestamps() })
@@ -308,6 +420,7 @@ Locale detection + theme + translations. `/__lang/:locale` and `/__theme/:theme`
308
420
  ```ts
309
421
  app.use(preferences({ dir: './locales', locale: { default: 'en' }, theme: { default: 'system' } }))
310
422
  // ctx.prefs.locale, ctx.prefs.theme, ctx.t('key'), ctx.setPref('locale', 'zh')
423
+ // ctx.setPref() returns a 302 Response with Set-Cookie — return it from your handler
311
424
  // GET /__lang/zh → 302 + Set-Cookie (or JSON if Accept: application/json)
312
425
  // GET /__theme/dark → same pattern
313
426
  ```
@@ -335,34 +448,69 @@ const { theme, resolvedTheme, setTheme } = useTheme()
335
448
 
336
449
  ```ts
337
450
  const q = queue({ redis })
451
+ app.use(q) // injects ctx.queue
338
452
  await q.add('send-email', { to: 'user@test.com' }, { cron: '0 8 * * *' })
339
453
  ```
340
454
 
455
+ | Option | Type | Default | Description |
456
+ |--------|------|---------|-------------|
457
+ | `redis` | `object` | — | Redis client |
458
+ | `url` | `string` | — | Redis URL (alternative to client) |
459
+ | `prefix` | `string` | `'queue:'` | Redis key prefix |
460
+ | `pollInterval` | `number` | `1000` | Poll interval (ms) |
461
+
462
+ | Method | Description |
463
+ |--------|-------------|
464
+ | `.add(name, data, opts?)` | Add job to queue |
465
+ | `.process(handler)` | Register job processor |
466
+ | `.run()` | Start processing |
467
+ | `.stop()` | Stop processing |
468
+ | `.close()` | Cleanup |
469
+
341
470
  ### rateLimit [B]
342
471
 
343
472
  ```ts
344
473
  app.use(rateLimit({ max: 100, window: 60_000 })) // 100 req/min
345
474
  app.get('/api', rateLimit({ max: 10 }), handler) // per-route
346
475
  app.use(rateLimit({ key: (req) => req.headers.get('x-api-key') ?? 'anonymous' }))
476
+ // Sets X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After headers
347
477
  // m.stop() — clear interval
348
478
  ```
349
479
 
480
+ | Option | Type | Default | Description |
481
+ |--------|------|---------|-------------|
482
+ | `max` | `number` | `100` | Max requests per window |
483
+ | `window` | `number` | `60_000` | Window duration (ms) |
484
+ | `key` | `(req) => string` | IP-based | Key function |
485
+ | `message` | `string` | `'Too Many Requests'` | 429 response body |
486
+
350
487
  ### redis [B]
351
488
 
352
489
  ```ts
353
- const r = redis() // reads REDIS_URL
354
- app.use(r) // injects ctx.redis
490
+ const r = redis() // reads REDIS_URL
491
+ app.use(r) // injects ctx.redis
355
492
  await ctx.redis.set('key', 'value')
356
493
  // r.close() — cleanup
357
494
  ```
358
495
 
496
+ | Option | Type | Default | Description |
497
+ |--------|------|---------|-------------|
498
+ | `url` | `string` | `REDIS_URL` env | Redis connection string |
499
+ | (all ioredis options) | — | — | Passed directly to ioredis |
500
+
359
501
  ### requestId [A]
360
502
 
361
503
  ```ts
362
504
  app.use(requestId())
505
+ app.use(requestId({ header: 'X-Request-Id', generator: () => crypto.randomUUID() }))
363
506
  // Sets X-Request-ID header on responses, available as ctx.requestId
364
507
  ```
365
508
 
509
+ | Option | Type | Default | Description |
510
+ |--------|------|---------|-------------|
511
+ | `header` | `string` | `'X-Request-ID'` | Header name to read/write |
512
+ | `generator` | `() => string` | `crypto.randomUUID()` | ID generator |
513
+
366
514
  ### seo [D] + seoMiddleware [A]
367
515
 
368
516
  ```ts
@@ -372,6 +520,8 @@ app.use(seo({ baseUrl: 'https://example.com', robots: [{ userAgent: '*', allow:
372
520
  app.use(seoMiddleware({ headers: { 'X-Robots-Tag': (path) => path.startsWith('/admin') ? 'noindex' : undefined } }))
373
521
  ```
374
522
 
523
+ Also exports `seoTags(config)` for generating meta/og/twitter tags as an HTML string.
524
+
375
525
  ### tenant [C]
376
526
 
377
527
  Multi-tenant BaaS with dynamic table API and GraphQL.
@@ -387,29 +537,58 @@ app.use('/graphql', t.graphql()) // dynamic GraphQL
387
537
  ### upload [A]
388
538
 
389
539
  ```ts
390
- app.post('/upload', upload({ dir: './uploads', maxFileSize: 10_485_760 }), (req, ctx) => {
391
- // ctx.parsed.files.avatar → { name, type, size, path }
540
+ app.post('/upload', upload({ dir: './uploads', maxFileSize: 10_485_760, allowedTypes: ['image/jpeg', 'image/png'] }), (req, ctx) => {
541
+ // ctx.parsed.files.avatar → { name, type, size, path } or { name, type, size, buffer } (when no dir)
542
+ // Multiple files with same field name → array
392
543
  // ctx.parsed.fields.title → 'hello'
393
544
  })
394
545
  ```
395
546
 
547
+ | Option | Type | Default | Description |
548
+ |--------|------|---------|-------------|
549
+ | `dir` | `string` | — | Write files to disk (omit for in-memory) |
550
+ | `maxFileSize` | `number` | — | Max bytes per file |
551
+ | `allowedTypes` | `string[]` | — | Allowed MIME types |
552
+
396
553
  ### user [C]
397
554
 
555
+ Authentication: register, login, JWT, OAuth2.
556
+
398
557
  ```ts
399
558
  const auth = user({ pg, jwtSecret: process.env.JWT_SECRET! })
400
559
  await auth.migrate()
401
- app.use('/auth', auth.router()) // POST /register, POST /login
560
+ app.use('/auth', auth.router()) // POST /register, POST /login, OAuth2 routes
402
561
  app.get('/me', auth.middleware(), (req, ctx) => Response.json(ctx.user))
403
562
  ```
404
563
 
564
+ | Option | Type | Default | Description |
565
+ |--------|------|---------|-------------|
566
+ | `pg` | `object` | — | PostgreSQL client |
567
+ | `jwtSecret` | `string` | — | JWT signing secret |
568
+ | `table` | `string` | `'_users'` | Users table name |
569
+ | `expiresIn` | `string` | `'7d'` | JWT expiration |
570
+ | `oauth2` | `object` | — | OAuth2 client config (PKCE flow) |
571
+
572
+ | Method | Description |
573
+ |--------|-------------|
574
+ | `.register(data)` | Register a new user programmatically |
575
+ | `.login(data)` | Log in programmatically |
576
+ | `.verify(token)` | Verify JWT token |
577
+ | `.router()` | REST routes (register, login, OAuth2) |
578
+ | `.middleware()` | JWT verify middleware — sets `ctx.user` |
579
+
405
580
  ### validate [A]
406
581
 
407
582
  ```ts
408
583
  import { z } from 'zod'
409
584
  const CreateUser = z.object({ name: z.string().min(1), email: z.string().email() })
410
- app.post('/users', validate({ body: CreateUser }), (req, ctx) => {
585
+ app.post('/users', validate({ body: CreateUser, query: z.object({ ref: z.string().optional() }) }), (req, ctx) => {
411
586
  // ctx.parsed.body — typed & validated
587
+ // ctx.parsed.query — typed & validated
588
+ // ctx.parsed.params — typed & validated (for dynamic routes)
589
+ // ctx.parsed.headers — typed & validated
412
590
  })
591
+ // Validation failure: returns 400 with { error: 'Validation failed', issues: [...] }
413
592
  ```
414
593
 
415
594
  ---
@@ -481,17 +660,27 @@ const loading = useNavigating() // reactive loading state
481
660
 
482
661
  ```tsx
483
662
  import { useWebsocket, useAction, useFetch, useQueryState, createStore, Head } from 'weifuwu/react'
484
- import { useLocale, useTheme, applyTheme, addInterceptor, useLoaderData } from 'weifuwu/react'
663
+ import { useLocale, useTheme, applyTheme, addInterceptor, useLoaderData, useFlashMessage } from 'weifuwu/react'
485
664
 
486
665
  // WebSocket — auto-reconnecting
487
- const { send, lastMessage, readyState } = useWebsocket('/ws/chat', { onMessage: (d) => console.log(d), reconnect: { maxRetries: 10, delay: 3000 } })
666
+ const { send, lastMessage, readyState, close, reconnect } = useWebsocket('/ws/chat', {
667
+ onMessage: (d) => console.log(d),
668
+ reconnect: { maxRetries: 10, delay: 3000 },
669
+ protocols: [], // optional sub-protocols
670
+ enabled: true, // pause/resume connection
671
+ })
488
672
 
489
673
  // Form action
490
- const { submit, data, error, pending } = useAction('/api/feedback', { method: 'POST' })
491
- // Auto-reads _csrf cookie, sends as X-CSRF-Token
674
+ const { submit, data, error, pending, reset } = useAction('/api/feedback', {
675
+ method: 'POST',
676
+ headers: { 'X-Custom': 'value' },
677
+ onSuccess: (data) => console.log(data),
678
+ onError: (err) => console.error(err),
679
+ })
680
+ // Auto-reads _csrf cookie, sends as x-csrf-token or x-xsrf-token
492
681
 
493
682
  // Data fetching — cache + dedup + mutate
494
- const { data, error, loading, mutate } = useFetch('/api/posts', { fallback: loadData })
683
+ const { data, error, loading, mutate } = useFetch('/api/posts', { fallback: loadData, ttl: 30_000 })
495
684
 
496
685
  // URL query state
497
686
  const [q, setQ] = useQueryState('q', '')
@@ -503,9 +692,10 @@ const count = useStore(s => s.count)
503
692
 
504
693
  // Per-page meta tags
505
694
  <Head><title>Page Title</title><meta name="description" content="..." /></Head>
506
-
507
695
  ```
508
696
 
697
+ **`TsxContext`** — React context holding page data (`params`, `query`, `user`, `parsed`, `prefs`, `env`). Used internally by hooks; rarely needed directly.
698
+
509
699
  ### Locale & Theme
510
700
 
511
701
  ```tsx
@@ -520,7 +710,7 @@ function LangSwitch() {
520
710
  |--------|-------------|
521
711
  | `locale` | Current locale string (from `ctx.prefs.locale`) |
522
712
  | `setLocale(locale)` | Switch locale (calls `navigate('/__lang/' + locale)`) |
523
- | `t` | Translation function (same as `useCtx().t`) |
713
+ | `t` | Translate a key using loaded locale messages |
524
714
 
525
715
  ```tsx
526
716
  import { useTheme } from 'weifuwu/react'
@@ -571,11 +761,19 @@ addInterceptor(async (url) => {
571
761
  ### Flash messages
572
762
 
573
763
  ```ts
574
- // Server
764
+ // Server — set flash cookie on redirect, auto-cleared after first read
575
765
  return ctx.setPref('flash', JSON.stringify({ type: 'success', message: 'Done' })) // 302 + Set-Cookie
766
+ ```
767
+
768
+ ```tsx
769
+ // Client
770
+ import { useFlashMessage } from 'weifuwu/react'
576
771
 
577
- // Client (tsx)
578
- function Toast() { const { prefs } = useCtx(); const flash = prefs?.flash ? JSON.parse(prefs.flash) : null; ... }
772
+ function Toast() {
773
+ const flash = useFlashMessage<{ type: string; message: string }>()
774
+ if (!flash) return null
775
+ return <div className={`toast toast-${flash.type}`}>{flash.message}</div>
776
+ }
579
777
  ```
580
778
 
581
779
  ### Dev mode
package/cli.ts CHANGED
@@ -70,6 +70,10 @@ async function cmdInit(name: string) {
70
70
  '',
71
71
  'This is a [weifuwu](https://weifuwu.io) HTTP application — pure Node.js, no build step.',
72
72
  '',
73
+ '## Before you start',
74
+ '',
75
+ 'Read `node_modules/weifuwu/README.md` first. Understand every module and API before writing any code. The weifuwu framework has its own patterns, types, and conventions — do not guess or assume.',
76
+ '',
73
77
  '## Commands',
74
78
  '',
75
79
  '- `npm run dev` — start dev server with `--watch`',
package/dist/cli.js CHANGED
@@ -61,6 +61,10 @@ async function cmdInit(name) {
61
61
  "",
62
62
  "This is a [weifuwu](https://weifuwu.io) HTTP application \u2014 pure Node.js, no build step.",
63
63
  "",
64
+ "## Before you start",
65
+ "",
66
+ "Read `node_modules/weifuwu/README.md` first. Understand every module and API before writing any code. The weifuwu framework has its own patterns, types, and conventions \u2014 do not guess or assume.",
67
+ "",
64
68
  "## Commands",
65
69
  "",
66
70
  "- `npm run dev` \u2014 start dev server with `--watch`",
package/dist/index.js CHANGED
@@ -7207,7 +7207,6 @@ function preferences(options) {
7207
7207
  globalThis.__LOCALE_DATA__ = msgs;
7208
7208
  ctx.parsed = { ...ctx.parsed, __localeData: msgs };
7209
7209
  }
7210
- ;
7211
7210
  ctx.setPref = (name, value) => {
7212
7211
  const cookieOpts = [`${name}=${encodeURIComponent(value)}`, "Path=/", "SameSite=Lax"];
7213
7212
  const referer = req.headers.get("referer") || "/";
package/dist/react.d.ts CHANGED
@@ -9,3 +9,4 @@ export { createStore, useFetch, useQueryState } from './client-state.ts';
9
9
  export type { StoreApi } from './client-state.ts';
10
10
  export { useLocale } from './client-locale.ts';
11
11
  export { useTheme, applyTheme } from './client-theme.ts';
12
+ export { useFlashMessage } from './use-flash-message.ts';
package/dist/react.js CHANGED
@@ -604,6 +604,18 @@ function useTheme() {
604
604
  setTheme: (t) => navigate("/__theme/" + t)
605
605
  };
606
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
+ }
607
619
  export {
608
620
  Head,
609
621
  Link,
@@ -614,6 +626,7 @@ export {
614
626
  navigate,
615
627
  useAction,
616
628
  useFetch,
629
+ useFlashMessage,
617
630
  useLoaderData,
618
631
  useLocale,
619
632
  useNavigate,
package/dist/types.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface Context {
5
5
  parsed?: Record<string, unknown>;
6
6
  mountPath?: string;
7
7
  t?: (key: string, params?: Record<string, string>, fallback?: string) => string;
8
+ setPref?: (name: string, value: string) => Response;
8
9
  prefs?: Record<string, string>;
9
10
  env?: Record<string, string>;
10
11
  }
@@ -0,0 +1 @@
1
+ export declare function useFlashMessage<T = any>(): T | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "weifuwu",
3
- "version": "0.17.26",
3
+ "version": "0.18.0",
4
4
  "description": "Web-standard HTTP framework for Node.js — (req, ctx) => Response",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",