@timber-js/app 0.1.57 → 0.2.0-alpha.10
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/dist/_chunks/{als-registry-k-AtAQ9R.js → als-registry-B7DbZ2hS.js} +1 -1
- package/dist/_chunks/{als-registry-k-AtAQ9R.js.map → als-registry-B7DbZ2hS.js.map} +1 -1
- package/dist/_chunks/debug-gwlJkDuf.js +108 -0
- package/dist/_chunks/debug-gwlJkDuf.js.map +1 -0
- package/dist/_chunks/{format-DNt20Kt8.js → format-DviM89f0.js} +3 -2
- package/dist/_chunks/format-DviM89f0.js.map +1 -0
- package/dist/_chunks/{interception-DGDIjDbR.js → interception-BOoWmLUA.js} +2 -2
- package/dist/_chunks/{interception-DGDIjDbR.js.map → interception-BOoWmLUA.js.map} +1 -1
- package/dist/_chunks/{metadata-routes-CQCnF4VK.js → metadata-routes-Cjmvi3rQ.js} +1 -1
- package/dist/_chunks/{metadata-routes-CQCnF4VK.js.map → metadata-routes-Cjmvi3rQ.js.map} +1 -1
- package/dist/_chunks/{request-context-CRj2Zh1E.js → request-context-DIkVh_jG.js} +5 -4
- package/dist/_chunks/request-context-DIkVh_jG.js.map +1 -0
- package/dist/_chunks/{ssr-data-DLnbYpj1.js → ssr-data-MjmprTmO.js} +1 -1
- package/dist/_chunks/{ssr-data-DLnbYpj1.js.map → ssr-data-MjmprTmO.js.map} +1 -1
- package/dist/_chunks/{tracing-DF0G3FB7.js → tracing-CemImE6h.js} +17 -3
- package/dist/_chunks/{tracing-DF0G3FB7.js.map → tracing-CemImE6h.js.map} +1 -1
- package/dist/_chunks/{use-cookie-dDbpCTx-.js → use-cookie-DX-l1_5E.js} +2 -2
- package/dist/_chunks/{use-cookie-dDbpCTx-.js.map → use-cookie-DX-l1_5E.js.map} +1 -1
- package/dist/_chunks/{use-query-states-DAhgj8Gx.js → use-query-states-D5KaffOK.js} +1 -1
- package/dist/_chunks/{use-query-states-DAhgj8Gx.js.map → use-query-states-D5KaffOK.js.map} +1 -1
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/cache/fast-hash.d.ts +22 -0
- package/dist/cache/fast-hash.d.ts.map +1 -0
- package/dist/cache/index.js +52 -10
- package/dist/cache/index.js.map +1 -1
- package/dist/cache/register-cached-function.d.ts.map +1 -1
- package/dist/cache/timber-cache.d.ts.map +1 -1
- package/dist/client/browser-entry.d.ts +1 -2
- package/dist/client/browser-entry.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +136 -94
- package/dist/client/index.js.map +1 -1
- package/dist/client/link.d.ts +12 -9
- package/dist/client/link.d.ts.map +1 -1
- package/dist/client/navigation-context.d.ts +9 -3
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/segment-context.d.ts +1 -1
- package/dist/client/segment-context.d.ts.map +1 -1
- package/dist/client/segment-merger.d.ts.map +1 -1
- package/dist/client/stale-reload.d.ts.map +1 -1
- package/dist/client/top-loader.d.ts.map +1 -1
- package/dist/client/transition-root.d.ts +1 -1
- package/dist/client/transition-root.d.ts.map +1 -1
- package/dist/cookies/index.js +4 -4
- package/dist/fonts/local.d.ts +4 -2
- package/dist/fonts/local.d.ts.map +1 -1
- package/dist/index.d.ts +38 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +255 -21
- package/dist/index.js.map +1 -1
- package/dist/plugins/build-report.d.ts +11 -1
- package/dist/plugins/build-report.d.ts.map +1 -1
- package/dist/plugins/chunks.d.ts +9 -1
- package/dist/plugins/chunks.d.ts.map +1 -1
- package/dist/plugins/entries.d.ts +7 -0
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/plugins/fonts.d.ts +9 -1
- package/dist/plugins/fonts.d.ts.map +1 -1
- package/dist/plugins/mdx.d.ts +6 -0
- package/dist/plugins/mdx.d.ts.map +1 -1
- package/dist/plugins/server-bundle.d.ts.map +1 -1
- package/dist/routing/index.js +1 -1
- package/dist/search-params/index.js +1 -1
- package/dist/server/access-gate.d.ts.map +1 -1
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/debug.d.ts +82 -0
- package/dist/server/debug.d.ts.map +1 -0
- package/dist/server/deny-renderer.d.ts.map +1 -1
- package/dist/server/dev-warnings.d.ts.map +1 -1
- package/dist/server/index.js +22 -13
- package/dist/server/index.js.map +1 -1
- package/dist/server/logger.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/primitives.d.ts.map +1 -1
- package/dist/server/request-context.d.ts.map +1 -1
- package/dist/server/response-cache.d.ts +54 -0
- package/dist/server/response-cache.d.ts.map +1 -0
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-stream.d.ts +6 -0
- package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
- package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
- package/dist/server/rsc-prop-warnings.d.ts.map +1 -1
- package/dist/server/tracing.d.ts +10 -0
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/server/waituntil-bridge.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/adapters/nitro.ts +6 -1
- package/src/cache/fast-hash.ts +34 -0
- package/src/cache/register-cached-function.ts +7 -3
- package/src/cache/timber-cache.ts +17 -10
- package/src/client/browser-entry.ts +16 -24
- package/src/client/index.ts +1 -1
- package/src/client/link.tsx +97 -34
- package/src/client/navigation-context.ts +54 -14
- package/src/client/router.ts +4 -6
- package/src/client/segment-context.ts +6 -1
- package/src/client/segment-merger.ts +2 -8
- package/src/client/stale-reload.ts +5 -7
- package/src/client/top-loader.tsx +23 -15
- package/src/client/transition-root.tsx +7 -1
- package/src/fonts/local.ts +7 -3
- package/src/index.ts +41 -0
- package/src/plugins/build-report.ts +23 -3
- package/src/plugins/chunks.ts +9 -1
- package/src/plugins/entries.ts +10 -4
- package/src/plugins/fonts.ts +171 -19
- package/src/plugins/mdx.ts +9 -5
- package/src/plugins/server-bundle.ts +4 -0
- package/src/server/access-gate.tsx +3 -2
- package/src/server/action-client.ts +15 -5
- package/src/server/debug.ts +137 -0
- package/src/server/deny-renderer.ts +3 -2
- package/src/server/dev-warnings.ts +2 -1
- package/src/server/logger.ts +4 -3
- package/src/server/pipeline.ts +7 -0
- package/src/server/primitives.ts +2 -1
- package/src/server/request-context.ts +3 -2
- package/src/server/response-cache.ts +410 -0
- package/src/server/route-element-builder.ts +1 -6
- package/src/server/rsc-entry/index.ts +61 -14
- package/src/server/rsc-entry/rsc-payload.ts +42 -7
- package/src/server/rsc-entry/rsc-stream.ts +10 -5
- package/src/server/rsc-entry/ssr-renderer.ts +12 -5
- package/src/server/rsc-prop-warnings.ts +3 -1
- package/src/server/tracing.ts +23 -0
- package/src/server/waituntil-bridge.ts +4 -1
- package/dist/_chunks/format-DNt20Kt8.js.map +0 -1
- package/dist/_chunks/request-context-CRj2Zh1E.js.map +0 -1
- package/dist/client/browser-links.d.ts +0 -32
- package/dist/client/browser-links.d.ts.map +0 -1
- package/dist/client/link-navigate-interceptor.d.ts +0 -28
- package/dist/client/link-navigate-interceptor.d.ts.map +0 -1
- package/src/client/browser-links.ts +0 -90
- package/src/client/link-navigate-interceptor.tsx +0 -62
package/dist/cache/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import "../_chunks/als-registry-
|
|
2
|
-
import {
|
|
3
|
-
import { createHash } from "node:crypto";
|
|
1
|
+
import "../_chunks/als-registry-B7DbZ2hS.js";
|
|
2
|
+
import { n as addSpanEventSync } from "../_chunks/tracing-CemImE6h.js";
|
|
4
3
|
//#region src/cache/redis-handler.ts
|
|
5
4
|
var KEY_PREFIX = "timber:cache:";
|
|
6
5
|
var TAG_PREFIX = "timber:tag:";
|
|
@@ -96,14 +95,53 @@ function createSingleflight() {
|
|
|
96
95
|
} };
|
|
97
96
|
}
|
|
98
97
|
//#endregion
|
|
98
|
+
//#region src/cache/fast-hash.ts
|
|
99
|
+
/**
|
|
100
|
+
* Fast non-cryptographic hash for cache keys.
|
|
101
|
+
*
|
|
102
|
+
* FNV-1a 64-bit produces a well-distributed hash with a collision
|
|
103
|
+
* probability of ~1 in 5 billion at 77k keys (birthday paradox).
|
|
104
|
+
* Not suitable for security, but ideal for cache key generation
|
|
105
|
+
* where we need speed over crypto strength.
|
|
106
|
+
*
|
|
107
|
+
* Uses BigInt for 64-bit arithmetic — supported in all modern runtimes
|
|
108
|
+
* including Cloudflare Workers. No node:crypto dependency.
|
|
109
|
+
*
|
|
110
|
+
* See TIM-370.
|
|
111
|
+
*/
|
|
112
|
+
var FNV_OFFSET_BASIS = 14695981039346656037n;
|
|
113
|
+
var FNV_PRIME = 1099511628211n;
|
|
114
|
+
var MASK_64 = 18446744073709551615n;
|
|
115
|
+
/**
|
|
116
|
+
* Compute a 64-bit FNV-1a hash of a string, returned as a 16-char hex string.
|
|
117
|
+
*
|
|
118
|
+
* 64 bits gives ~5 billion keys before a 50% collision probability
|
|
119
|
+
* (birthday paradox), making accidental collisions effectively impossible
|
|
120
|
+
* for cache key use cases.
|
|
121
|
+
*/
|
|
122
|
+
function fnv1aHash(input) {
|
|
123
|
+
let hash = FNV_OFFSET_BASIS;
|
|
124
|
+
for (let i = 0; i < input.length; i++) {
|
|
125
|
+
hash ^= BigInt(input.charCodeAt(i));
|
|
126
|
+
hash = hash * FNV_PRIME & MASK_64;
|
|
127
|
+
}
|
|
128
|
+
return hash.toString(16).padStart(16, "0");
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
99
131
|
//#region src/cache/timber-cache.ts
|
|
100
132
|
var singleflight$1 = createSingleflight();
|
|
101
133
|
/**
|
|
102
|
-
* Generate a
|
|
134
|
+
* Generate a cache key from function identity and serialized args.
|
|
135
|
+
*
|
|
136
|
+
* Uses FNV-1a (fast non-crypto hash) instead of SHA-256. Cache keys don't
|
|
137
|
+
* need collision resistance — they need speed. The fnId prefix provides
|
|
138
|
+
* namespace isolation; the hash covers the args.
|
|
139
|
+
*
|
|
140
|
+
* See TIM-370 for perf motivation.
|
|
103
141
|
*/
|
|
104
142
|
function defaultKeyGenerator(fnId, args) {
|
|
105
143
|
const raw = fnId + ":" + stableStringify(args);
|
|
106
|
-
return
|
|
144
|
+
return fnId + ":" + fnv1aHash(raw);
|
|
107
145
|
}
|
|
108
146
|
/**
|
|
109
147
|
* Resolve tags from the options — supports static array or function form.
|
|
@@ -133,14 +171,14 @@ function createCache(fn, opts, handler) {
|
|
|
133
171
|
const cacheStart = performance.now();
|
|
134
172
|
const cached = await handler.get(key);
|
|
135
173
|
if (cached && !cached.stale) {
|
|
136
|
-
|
|
174
|
+
addSpanEventSync("timber.cache.hit", {
|
|
137
175
|
key,
|
|
138
176
|
duration_ms: Math.round(performance.now() - cacheStart)
|
|
139
177
|
});
|
|
140
178
|
return cached.value;
|
|
141
179
|
}
|
|
142
180
|
if (cached && cached.stale && opts.staleWhileRevalidate) {
|
|
143
|
-
|
|
181
|
+
addSpanEventSync("timber.cache.hit", {
|
|
144
182
|
key,
|
|
145
183
|
duration_ms: Math.round(performance.now() - cacheStart),
|
|
146
184
|
stale: true
|
|
@@ -163,7 +201,7 @@ function createCache(fn, opts, handler) {
|
|
|
163
201
|
ttl: opts.ttl,
|
|
164
202
|
tags
|
|
165
203
|
});
|
|
166
|
-
|
|
204
|
+
addSpanEventSync("timber.cache.miss", {
|
|
167
205
|
key,
|
|
168
206
|
duration_ms: Math.round(performance.now() - cacheStart)
|
|
169
207
|
});
|
|
@@ -190,11 +228,15 @@ var REQUEST_SPECIFIC_PROPS = new Set([
|
|
|
190
228
|
"headers"
|
|
191
229
|
]);
|
|
192
230
|
/**
|
|
193
|
-
* Generate a
|
|
231
|
+
* Generate a cache key from a stable function ID and serialized args.
|
|
232
|
+
*
|
|
233
|
+
* Uses FNV-1a (fast non-crypto hash) instead of SHA-256. The id prefix
|
|
234
|
+
* provides namespace isolation; the hash covers the args.
|
|
235
|
+
* See TIM-370.
|
|
194
236
|
*/
|
|
195
237
|
function generateKey(id, args) {
|
|
196
238
|
const raw = id + ":" + stableStringify(args);
|
|
197
|
-
return
|
|
239
|
+
return id + ":" + fnv1aHash(raw);
|
|
198
240
|
}
|
|
199
241
|
/**
|
|
200
242
|
* Resolve tags from options — supports static array or function form.
|
package/dist/cache/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/cache/redis-handler.ts","../../src/cache/stable-stringify.ts","../../src/cache/singleflight.ts","../../src/cache/timber-cache.ts","../../src/cache/register-cached-function.ts","../../src/cache/index.ts"],"sourcesContent":["import type { CacheHandler } from './index';\n\n/**\n * Minimal Redis client interface — compatible with ioredis, node-redis, and\n * Cloudflare Workers Redis bindings. We depend on the interface, not the\n * implementation, so users bring their own Redis client.\n */\nexport interface RedisClient {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ...args: unknown[]): Promise<unknown>;\n del(key: string | string[]): Promise<number>;\n sadd(key: string, ...members: string[]): Promise<number>;\n smembers(key: string): Promise<string[]>;\n}\n\nconst KEY_PREFIX = 'timber:cache:';\nconst TAG_PREFIX = 'timber:tag:';\n\n/**\n * Redis-backed CacheHandler for distributed caching.\n *\n * All instances sharing the same Redis see each other's cache entries and\n * invalidations. Tag-based invalidation uses Redis Sets to track which keys\n * belong to which tags.\n *\n * Bring your own Redis client — any client implementing the RedisClient\n * interface works (ioredis, node-redis, @upstash/redis, etc.).\n */\nexport class RedisCacheHandler implements CacheHandler {\n private client: RedisClient;\n private prefix: string;\n\n constructor(client: RedisClient, opts?: { prefix?: string }) {\n this.client = client;\n this.prefix = opts?.prefix ?? '';\n }\n\n private cacheKey(key: string): string {\n return `${this.prefix}${KEY_PREFIX}${key}`;\n }\n\n private tagKey(tag: string): string {\n return `${this.prefix}${TAG_PREFIX}${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const raw = await this.client.get(this.cacheKey(key));\n if (raw === null) return null;\n\n const entry = JSON.parse(raw) as { value: unknown; expiresAt: number };\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void> {\n const ck = this.cacheKey(key);\n const expiresAt = Date.now() + opts.ttl * 1000;\n const payload = JSON.stringify({ value, expiresAt });\n\n // Redis TTL with generous margin beyond the logical TTL to allow SWR reads\n // on stale entries. The logical staleness is determined by expiresAt.\n // We use 2x TTL + 60s as the Redis expiry so stale entries remain\n // available for SWR background refetches.\n const redisTtlSeconds = Math.max(opts.ttl * 2 + 60, 120);\n await this.client.set(ck, payload, 'EX', redisTtlSeconds);\n\n // Track key membership in each tag set\n for (const tag of opts.tags) {\n await this.client.sadd(this.tagKey(tag), key);\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\n await this.client.del(this.cacheKey(opts.key));\n }\n\n if (opts.tag) {\n const tk = this.tagKey(opts.tag);\n const keys = await this.client.smembers(tk);\n\n if (keys.length > 0) {\n const cacheKeys = keys.map((k) => this.cacheKey(k));\n await this.client.del(cacheKeys);\n }\n\n // Clean up the tag set itself\n await this.client.del(tk);\n }\n }\n}\n","/**\n * Deterministic JSON serialization with sorted object keys.\n * Used for cache key generation — ensures { a: 1, b: 2 } and { b: 2, a: 1 }\n * produce the same string.\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).join(',') + ']';\n }\n\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const pairs: string[] = [];\n for (const key of keys) {\n if (obj[key] === undefined) continue;\n pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n return '{' + pairs.join(',') + '}';\n}\n","/**\n * Singleflight coalesces concurrent calls with the same key into a single\n * execution. All callers receive the same result (or error).\n *\n * Per-process, in-memory. Each process coalesces independently.\n */\nexport interface Singleflight {\n do<T>(key: string, fn: () => Promise<T>): Promise<T>;\n}\n\nexport function createSingleflight(): Singleflight {\n const inflight = new Map<string, Promise<unknown>>();\n\n return {\n do<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\n const promise = fn().finally(() => {\n inflight.delete(key);\n });\n inflight.set(key, promise);\n return promise;\n },\n };\n}\n","import { createHash } from 'node:crypto';\nimport type { CacheHandler, CacheOptions } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\nimport { addSpanEvent } from '#/server/tracing.js';\n\nconst singleflight = createSingleflight();\n\n/**\n * Generate a SHA-256 cache key from function identity and serialized args.\n */\nfunction defaultKeyGenerator(fnId: string, args: unknown[]): string {\n const raw = fnId + ':' + stableStringify(args);\n return createHash('sha256').update(raw).digest('hex');\n}\n\n/**\n * Resolve tags from the options — supports static array or function form.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveTags<Fn extends (...args: any[]) => any>(\n opts: CacheOptions<Fn>,\n args: Parameters<Fn>\n): string[] {\n if (!opts.tags) return [];\n if (Array.isArray(opts.tags)) return opts.tags;\n return opts.tags(...args);\n}\n\n// Counter for generating unique function IDs when no explicit key is provided.\nlet fnIdCounter = 0;\n\n/**\n * Creates a cached wrapper around an async function.\n *\n * - SHA-256 default keys with normalized JSON args\n * - Singleflight: concurrent misses → single execution\n * - SWR: serve stale immediately, background refetch\n * - Tags as string[] or function of args\n * - No ALS dependency\n *\n * Cache hits/misses are recorded as OTEL span events on the enclosing\n * span (not child spans). The DevSpanProcessor reads these for dev log output.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createCache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n handler: CacheHandler\n): (...args: Parameters<Fn>) => Promise<Awaited<ReturnType<Fn>>> {\n const fnId = `timber-cache:${fnIdCounter++}`;\n\n return async (...args: Parameters<Fn>): Promise<Awaited<ReturnType<Fn>>> => {\n const key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId, args);\n\n const cacheStart = performance.now();\n const cached = await handler.get(key);\n\n if (cached && !cached.stale) {\n // Record as OTEL span event on enclosing span (not a child span)\n await addSpanEvent('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n if (cached && cached.stale && opts.staleWhileRevalidate) {\n // Record stale cache hit as OTEL span event\n await addSpanEvent('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n stale: true,\n });\n // Serve stale immediately, trigger background refetch\n singleflight\n .do(`swr:${key}`, async () => {\n try {\n const fresh = await fn(...args);\n const tags = resolveTags(opts, args);\n await handler.set(key, fresh, { ttl: opts.ttl, tags });\n } catch {\n // Failed refetch — stale entry continues to be served.\n // Error is swallowed per design doc: \"Error is logged.\"\n }\n })\n .catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight\n const result = await singleflight.do(key, () => fn(...args));\n const tags = resolveTags(opts, args);\n await handler.set(key, result, { ttl: opts.ttl, tags });\n\n // Record cache miss as OTEL span event\n await addSpanEvent('timber.cache.miss', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n\n return result as Awaited<ReturnType<Fn>>;\n };\n}\n\n/**\n * Invalidate cache entries by tag or key.\n */\ncreateCache.invalidate = async function invalidate(\n handler: CacheHandler,\n opts: { key?: string; tag?: string }\n): Promise<void> {\n await handler.invalidate(opts);\n};\n","import { createHash } from 'node:crypto';\nimport type { CacheHandler } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\n\nconst singleflight = createSingleflight();\n\n// Prop names that suggest request-specific data — triggers dev warning for \"use cache\" components.\nconst REQUEST_SPECIFIC_PROPS = new Set([\n 'cookies',\n 'cookie',\n 'session',\n 'sessionId',\n 'token',\n 'authorization',\n 'auth',\n 'headers',\n]);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RegisterCachedFunctionOptions<Fn extends (...args: any[]) => any> {\n ttl: number;\n id: string;\n tags?: string[] | ((...args: Parameters<Fn>) => string[]);\n /** True when the cached function is a React component (PascalCase name). */\n isComponent?: boolean;\n}\n\n/**\n * Generate a SHA-256 cache key from a stable function ID and serialized args.\n */\nfunction generateKey(id: string, args: unknown[]): string {\n const raw = id + ':' + stableStringify(args);\n return createHash('sha256').update(raw).digest('hex');\n}\n\n/**\n * Resolve tags from options — supports static array or function form.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveTags<Fn extends (...args: any[]) => any>(\n opts: RegisterCachedFunctionOptions<Fn>,\n args: Parameters<Fn>\n): string[] {\n if (!opts.tags) return [];\n if (Array.isArray(opts.tags)) return opts.tags;\n return opts.tags(...args);\n}\n\n/**\n * Checks if component props contain request-specific keys and emits a dev warning.\n * Only runs when process.env.NODE_ENV !== 'production'.\n */\nfunction warnRequestSpecificProps(id: string, props: unknown): void {\n if (typeof props !== 'object' || props === null) return;\n const keys = Object.keys(props);\n const suspicious = keys.filter((k) => REQUEST_SPECIFIC_PROPS.has(k.toLowerCase()));\n if (suspicious.length > 0) {\n console.warn(\n `[timber] \"use cache\" component ${id} received request-specific props: ${suspicious.join(', ')}. ` +\n `This may serve one user's cached render to another user. ` +\n `Remove request-specific data from props or remove \"use cache\".`\n );\n }\n}\n\n/**\n * Runtime for the \"use cache\" directive transform. Wraps an async function\n * with caching using the same cache handler as timber.cache.\n *\n * The stable `id` (file path + function name) ensures cache keys are consistent\n * across builds. Args/props are hashed with SHA-256 for the per-call key.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function registerCachedFunction<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: RegisterCachedFunctionOptions<Fn>,\n handler: CacheHandler\n): (...args: Parameters<Fn>) => Promise<Awaited<ReturnType<Fn>>> {\n return async (...args: Parameters<Fn>): Promise<Awaited<ReturnType<Fn>>> => {\n // Dev-mode warning for components with request-specific props\n if (opts.isComponent && process.env.NODE_ENV !== 'production' && args.length > 0) {\n warnRequestSpecificProps(opts.id, args[0]);\n }\n\n const key = generateKey(opts.id, args);\n const cached = await handler.get(key);\n\n if (cached && !cached.stale) {\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss or stale — execute with singleflight\n const result = await singleflight.do(key, () => fn(...args));\n const tags = resolveTags(opts, args);\n await handler.set(key, result, { ttl: opts.ttl, tags });\n return result as Awaited<ReturnType<Fn>>;\n };\n}\n","// @timber-js/app/cache — Caching primitives\n\nexport interface CacheHandler {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface CacheOptions<Fn extends (...args: any[]) => any> {\n ttl: number;\n key?: (...args: Parameters<Fn>) => string;\n staleWhileRevalidate?: boolean;\n tags?: string[] | ((...args: Parameters<Fn>) => string[]);\n}\n\nexport interface MemoryCacheHandlerOptions {\n /** Maximum number of entries. Oldest accessed entries are evicted first. Default: 1000. */\n maxSize?: number;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<string, { value: unknown; expiresAt: number; tags: string[] }>();\n private maxSize: number;\n\n constructor(opts?: MemoryCacheHandlerOptions) {\n this.maxSize = opts?.maxSize ?? 1000;\n }\n\n async get(key: string) {\n const entry = this.store.get(key);\n if (!entry) return null;\n\n // Move to end of Map (most recently used) for LRU ordering\n this.store.delete(key);\n this.store.set(key, entry);\n\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(key: string, value: unknown, opts: { ttl: number; tags: string[] }) {\n // If key already exists, delete first to refresh insertion order\n if (this.store.has(key)) {\n this.store.delete(key);\n }\n\n // Evict oldest entries (front of Map) if at capacity\n while (this.store.size >= this.maxSize) {\n const oldest = this.store.keys().next().value;\n if (oldest !== undefined) {\n this.store.delete(oldest);\n } else {\n break;\n }\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n });\n }\n\n async invalidate(opts: { key?: string; tag?: string }) {\n if (opts.key) {\n this.store.delete(opts.key);\n }\n if (opts.tag) {\n for (const [key, entry] of this.store) {\n if (entry.tags.includes(opts.tag)) {\n this.store.delete(key);\n }\n }\n }\n }\n\n /** Number of entries currently in the cache. */\n get size(): number {\n return this.store.size;\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler';\nexport type { RedisClient } from './redis-handler';\nexport { createCache } from './timber-cache';\nexport { registerCachedFunction } from './register-cached-function';\nexport type { RegisterCachedFunctionOptions } from './register-cached-function';\nexport { stableStringify } from './stable-stringify';\nexport { createSingleflight } from './singleflight';\nexport type { Singleflight } from './singleflight';\n"],"mappings":";;;;AAeA,IAAM,aAAa;AACnB,IAAM,aAAa;;;;;;;;;;;AAYnB,IAAa,oBAAb,MAAuD;CACrD;CACA;CAEA,YAAY,QAAqB,MAA4B;AAC3D,OAAK,SAAS;AACd,OAAK,SAAS,MAAM,UAAU;;CAGhC,SAAiB,KAAqB;AACpC,SAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,OAAe,KAAqB;AAClC,SAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,MAAM,IAAI,KAAiE;EACzE,MAAM,MAAM,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,IAAI,CAAC;AACrD,MAAI,QAAQ,KAAM,QAAO;EAEzB,MAAM,QAAQ,KAAK,MAAM,IAAI;EAC7B,MAAM,QAAQ,KAAK,KAAK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GACtC,MAAM,SAAS,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC;AACxC,OAAI,WAAW,KAAA,EACb,MAAK,MAAM,OAAO,OAAO;OAEzB;;AAIJ,OAAK,MAAM,IAAI,KAAK;GAClB;GACA,WAAW,KAAK,KAAK,GAAG,KAAK,MAAM;GACnC,MAAM,KAAK;GACZ,CAAC;;CAGJ,MAAM,WAAW,MAAsC;AACrD,MAAI,KAAK,IACP,MAAK,MAAM,OAAO,KAAK,IAAI;AAE7B,MAAI,KAAK;QACF,MAAM,CAAC,KAAK,UAAU,KAAK,MAC9B,KAAI,MAAM,KAAK,SAAS,KAAK,IAAI,CAC/B,MAAK,MAAM,OAAO,IAAI;;;;CAO9B,IAAI,OAAe;AACjB,SAAO,KAAK,MAAM"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/cache/redis-handler.ts","../../src/cache/stable-stringify.ts","../../src/cache/singleflight.ts","../../src/cache/fast-hash.ts","../../src/cache/timber-cache.ts","../../src/cache/register-cached-function.ts","../../src/cache/index.ts"],"sourcesContent":["import type { CacheHandler } from './index';\n\n/**\n * Minimal Redis client interface — compatible with ioredis, node-redis, and\n * Cloudflare Workers Redis bindings. We depend on the interface, not the\n * implementation, so users bring their own Redis client.\n */\nexport interface RedisClient {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ...args: unknown[]): Promise<unknown>;\n del(key: string | string[]): Promise<number>;\n sadd(key: string, ...members: string[]): Promise<number>;\n smembers(key: string): Promise<string[]>;\n}\n\nconst KEY_PREFIX = 'timber:cache:';\nconst TAG_PREFIX = 'timber:tag:';\n\n/**\n * Redis-backed CacheHandler for distributed caching.\n *\n * All instances sharing the same Redis see each other's cache entries and\n * invalidations. Tag-based invalidation uses Redis Sets to track which keys\n * belong to which tags.\n *\n * Bring your own Redis client — any client implementing the RedisClient\n * interface works (ioredis, node-redis, @upstash/redis, etc.).\n */\nexport class RedisCacheHandler implements CacheHandler {\n private client: RedisClient;\n private prefix: string;\n\n constructor(client: RedisClient, opts?: { prefix?: string }) {\n this.client = client;\n this.prefix = opts?.prefix ?? '';\n }\n\n private cacheKey(key: string): string {\n return `${this.prefix}${KEY_PREFIX}${key}`;\n }\n\n private tagKey(tag: string): string {\n return `${this.prefix}${TAG_PREFIX}${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const raw = await this.client.get(this.cacheKey(key));\n if (raw === null) return null;\n\n const entry = JSON.parse(raw) as { value: unknown; expiresAt: number };\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void> {\n const ck = this.cacheKey(key);\n const expiresAt = Date.now() + opts.ttl * 1000;\n const payload = JSON.stringify({ value, expiresAt });\n\n // Redis TTL with generous margin beyond the logical TTL to allow SWR reads\n // on stale entries. The logical staleness is determined by expiresAt.\n // We use 2x TTL + 60s as the Redis expiry so stale entries remain\n // available for SWR background refetches.\n const redisTtlSeconds = Math.max(opts.ttl * 2 + 60, 120);\n await this.client.set(ck, payload, 'EX', redisTtlSeconds);\n\n // Track key membership in each tag set\n for (const tag of opts.tags) {\n await this.client.sadd(this.tagKey(tag), key);\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\n await this.client.del(this.cacheKey(opts.key));\n }\n\n if (opts.tag) {\n const tk = this.tagKey(opts.tag);\n const keys = await this.client.smembers(tk);\n\n if (keys.length > 0) {\n const cacheKeys = keys.map((k) => this.cacheKey(k));\n await this.client.del(cacheKeys);\n }\n\n // Clean up the tag set itself\n await this.client.del(tk);\n }\n }\n}\n","/**\n * Deterministic JSON serialization with sorted object keys.\n * Used for cache key generation — ensures { a: 1, b: 2 } and { b: 2, a: 1 }\n * produce the same string.\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).join(',') + ']';\n }\n\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const pairs: string[] = [];\n for (const key of keys) {\n if (obj[key] === undefined) continue;\n pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n return '{' + pairs.join(',') + '}';\n}\n","/**\n * Singleflight coalesces concurrent calls with the same key into a single\n * execution. All callers receive the same result (or error).\n *\n * Per-process, in-memory. Each process coalesces independently.\n */\nexport interface Singleflight {\n do<T>(key: string, fn: () => Promise<T>): Promise<T>;\n}\n\nexport function createSingleflight(): Singleflight {\n const inflight = new Map<string, Promise<unknown>>();\n\n return {\n do<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\n const promise = fn().finally(() => {\n inflight.delete(key);\n });\n inflight.set(key, promise);\n return promise;\n },\n };\n}\n","/**\n * Fast non-cryptographic hash for cache keys.\n *\n * FNV-1a 64-bit produces a well-distributed hash with a collision\n * probability of ~1 in 5 billion at 77k keys (birthday paradox).\n * Not suitable for security, but ideal for cache key generation\n * where we need speed over crypto strength.\n *\n * Uses BigInt for 64-bit arithmetic — supported in all modern runtimes\n * including Cloudflare Workers. No node:crypto dependency.\n *\n * See TIM-370.\n */\n\n// FNV-1a constants for 64-bit hash\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst MASK_64 = 0xffffffffffffffffn;\n\n/**\n * Compute a 64-bit FNV-1a hash of a string, returned as a 16-char hex string.\n *\n * 64 bits gives ~5 billion keys before a 50% collision probability\n * (birthday paradox), making accidental collisions effectively impossible\n * for cache key use cases.\n */\nexport function fnv1aHash(input: string): string {\n let hash = FNV_OFFSET_BASIS;\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i));\n hash = (hash * FNV_PRIME) & MASK_64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n","import type { CacheHandler, CacheOptions } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\nimport { addSpanEventSync } from '#/server/tracing.js';\nimport { fnv1aHash } from './fast-hash.js';\n\nconst singleflight = createSingleflight();\n\n/**\n * Generate a cache key from function identity and serialized args.\n *\n * Uses FNV-1a (fast non-crypto hash) instead of SHA-256. Cache keys don't\n * need collision resistance — they need speed. The fnId prefix provides\n * namespace isolation; the hash covers the args.\n *\n * See TIM-370 for perf motivation.\n */\nfunction defaultKeyGenerator(fnId: string, args: unknown[]): string {\n const raw = fnId + ':' + stableStringify(args);\n return fnId + ':' + fnv1aHash(raw);\n}\n\n/**\n * Resolve tags from the options — supports static array or function form.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveTags<Fn extends (...args: any[]) => any>(\n opts: CacheOptions<Fn>,\n args: Parameters<Fn>\n): string[] {\n if (!opts.tags) return [];\n if (Array.isArray(opts.tags)) return opts.tags;\n return opts.tags(...args);\n}\n\n// Counter for generating unique function IDs when no explicit key is provided.\nlet fnIdCounter = 0;\n\n/**\n * Creates a cached wrapper around an async function.\n *\n * - SHA-256 default keys with normalized JSON args\n * - Singleflight: concurrent misses → single execution\n * - SWR: serve stale immediately, background refetch\n * - Tags as string[] or function of args\n * - No ALS dependency\n *\n * Cache hits/misses are recorded as OTEL span events on the enclosing\n * span (not child spans). The DevSpanProcessor reads these for dev log output.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createCache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n handler: CacheHandler\n): (...args: Parameters<Fn>) => Promise<Awaited<ReturnType<Fn>>> {\n const fnId = `timber-cache:${fnIdCounter++}`;\n\n return async (...args: Parameters<Fn>): Promise<Awaited<ReturnType<Fn>>> => {\n const key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId, args);\n\n const cacheStart = performance.now();\n const cached = await handler.get(key);\n\n if (cached && !cached.stale) {\n // Record as OTEL span event on enclosing span (not a child span).\n // Fire-and-forget — no microtask overhead on the cache hot path.\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n if (cached && cached.stale && opts.staleWhileRevalidate) {\n // Record stale cache hit as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n stale: true,\n });\n // Serve stale immediately, trigger background refetch\n singleflight\n .do(`swr:${key}`, async () => {\n try {\n const fresh = await fn(...args);\n const tags = resolveTags(opts, args);\n await handler.set(key, fresh, { ttl: opts.ttl, tags });\n } catch {\n // Failed refetch — stale entry continues to be served.\n // Error is swallowed per design doc: \"Error is logged.\"\n }\n })\n .catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight\n const result = await singleflight.do(key, () => fn(...args));\n const tags = resolveTags(opts, args);\n await handler.set(key, result, { ttl: opts.ttl, tags });\n\n // Record cache miss as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.miss', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n\n return result as Awaited<ReturnType<Fn>>;\n };\n}\n\n/**\n * Invalidate cache entries by tag or key.\n */\ncreateCache.invalidate = async function invalidate(\n handler: CacheHandler,\n opts: { key?: string; tag?: string }\n): Promise<void> {\n await handler.invalidate(opts);\n};\n","import type { CacheHandler } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\nimport { fnv1aHash } from './fast-hash.js';\n\nconst singleflight = createSingleflight();\n\n// Prop names that suggest request-specific data — triggers dev warning for \"use cache\" components.\nconst REQUEST_SPECIFIC_PROPS = new Set([\n 'cookies',\n 'cookie',\n 'session',\n 'sessionId',\n 'token',\n 'authorization',\n 'auth',\n 'headers',\n]);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RegisterCachedFunctionOptions<Fn extends (...args: any[]) => any> {\n ttl: number;\n id: string;\n tags?: string[] | ((...args: Parameters<Fn>) => string[]);\n /** True when the cached function is a React component (PascalCase name). */\n isComponent?: boolean;\n}\n\n/**\n * Generate a cache key from a stable function ID and serialized args.\n *\n * Uses FNV-1a (fast non-crypto hash) instead of SHA-256. The id prefix\n * provides namespace isolation; the hash covers the args.\n * See TIM-370.\n */\nfunction generateKey(id: string, args: unknown[]): string {\n const raw = id + ':' + stableStringify(args);\n return id + ':' + fnv1aHash(raw);\n}\n\n/**\n * Resolve tags from options — supports static array or function form.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveTags<Fn extends (...args: any[]) => any>(\n opts: RegisterCachedFunctionOptions<Fn>,\n args: Parameters<Fn>\n): string[] {\n if (!opts.tags) return [];\n if (Array.isArray(opts.tags)) return opts.tags;\n return opts.tags(...args);\n}\n\n/**\n * Checks if component props contain request-specific keys and emits a dev warning.\n * Only runs when process.env.NODE_ENV !== 'production'.\n */\nfunction warnRequestSpecificProps(id: string, props: unknown): void {\n if (typeof props !== 'object' || props === null) return;\n const keys = Object.keys(props);\n const suspicious = keys.filter((k) => REQUEST_SPECIFIC_PROPS.has(k.toLowerCase()));\n if (suspicious.length > 0) {\n console.warn(\n `[timber] \"use cache\" component ${id} received request-specific props: ${suspicious.join(', ')}. ` +\n `This may serve one user's cached render to another user. ` +\n `Remove request-specific data from props or remove \"use cache\".`\n );\n }\n}\n\n/**\n * Runtime for the \"use cache\" directive transform. Wraps an async function\n * with caching using the same cache handler as timber.cache.\n *\n * The stable `id` (file path + function name) ensures cache keys are consistent\n * across builds. Args/props are hashed with SHA-256 for the per-call key.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function registerCachedFunction<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: RegisterCachedFunctionOptions<Fn>,\n handler: CacheHandler\n): (...args: Parameters<Fn>) => Promise<Awaited<ReturnType<Fn>>> {\n return async (...args: Parameters<Fn>): Promise<Awaited<ReturnType<Fn>>> => {\n // Dev-mode warning for components with request-specific props\n if (opts.isComponent && process.env.NODE_ENV !== 'production' && args.length > 0) {\n warnRequestSpecificProps(opts.id, args[0]);\n }\n\n const key = generateKey(opts.id, args);\n const cached = await handler.get(key);\n\n if (cached && !cached.stale) {\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss or stale — execute with singleflight\n const result = await singleflight.do(key, () => fn(...args));\n const tags = resolveTags(opts, args);\n await handler.set(key, result, { ttl: opts.ttl, tags });\n return result as Awaited<ReturnType<Fn>>;\n };\n}\n","// @timber-js/app/cache — Caching primitives\n\nexport interface CacheHandler {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface CacheOptions<Fn extends (...args: any[]) => any> {\n ttl: number;\n key?: (...args: Parameters<Fn>) => string;\n staleWhileRevalidate?: boolean;\n tags?: string[] | ((...args: Parameters<Fn>) => string[]);\n}\n\nexport interface MemoryCacheHandlerOptions {\n /** Maximum number of entries. Oldest accessed entries are evicted first. Default: 1000. */\n maxSize?: number;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<string, { value: unknown; expiresAt: number; tags: string[] }>();\n private maxSize: number;\n\n constructor(opts?: MemoryCacheHandlerOptions) {\n this.maxSize = opts?.maxSize ?? 1000;\n }\n\n async get(key: string) {\n const entry = this.store.get(key);\n if (!entry) return null;\n\n // Move to end of Map (most recently used) for LRU ordering\n this.store.delete(key);\n this.store.set(key, entry);\n\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(key: string, value: unknown, opts: { ttl: number; tags: string[] }) {\n // If key already exists, delete first to refresh insertion order\n if (this.store.has(key)) {\n this.store.delete(key);\n }\n\n // Evict oldest entries (front of Map) if at capacity\n while (this.store.size >= this.maxSize) {\n const oldest = this.store.keys().next().value;\n if (oldest !== undefined) {\n this.store.delete(oldest);\n } else {\n break;\n }\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n });\n }\n\n async invalidate(opts: { key?: string; tag?: string }) {\n if (opts.key) {\n this.store.delete(opts.key);\n }\n if (opts.tag) {\n for (const [key, entry] of this.store) {\n if (entry.tags.includes(opts.tag)) {\n this.store.delete(key);\n }\n }\n }\n }\n\n /** Number of entries currently in the cache. */\n get size(): number {\n return this.store.size;\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler';\nexport type { RedisClient } from './redis-handler';\nexport { createCache } from './timber-cache';\nexport { registerCachedFunction } from './register-cached-function';\nexport type { RegisterCachedFunctionOptions } from './register-cached-function';\nexport { stableStringify } from './stable-stringify';\nexport { createSingleflight } from './singleflight';\nexport type { Singleflight } from './singleflight';\n"],"mappings":";;;AAeA,IAAM,aAAa;AACnB,IAAM,aAAa;;;;;;;;;;;AAYnB,IAAa,oBAAb,MAAuD;CACrD;CACA;CAEA,YAAY,QAAqB,MAA4B;AAC3D,OAAK,SAAS;AACd,OAAK,SAAS,MAAM,UAAU;;CAGhC,SAAiB,KAAqB;AACpC,SAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,OAAe,KAAqB;AAClC,SAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,MAAM,IAAI,KAAiE;EACzE,MAAM,MAAM,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,IAAI,CAAC;AACrD,MAAI,QAAQ,KAAM,QAAO;EAEzB,MAAM,QAAQ,KAAK,MAAM,IAAI;EAC7B,MAAM,QAAQ,KAAK,KAAK,GAAG,MAAM;AACjC,SAAO;GAAE,OAAO,MAAM;GAAO;GAAO;;CAGtC,MAAM,IAAI,KAAa,OAAgB,MAAsD;EAC3F,MAAM,KAAK,KAAK,SAAS,IAAI;EAC7B,MAAM,YAAY,KAAK,KAAK,GAAG,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K,MAAM,IAAI,IAAI,CACrB,MAAK,MAAM,OAAO,IAAI;AAIxB,SAAO,KAAK,MAAM,QAAQ,KAAK,SAAS;GACtC,MAAM,SAAS,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC;AACxC,OAAI,WAAW,KAAA,EACb,MAAK,MAAM,OAAO,OAAO;OAEzB;;AAIJ,OAAK,MAAM,IAAI,KAAK;GAClB;GACA,WAAW,KAAK,KAAK,GAAG,KAAK,MAAM;GACnC,MAAM,KAAK;GACZ,CAAC;;CAGJ,MAAM,WAAW,MAAsC;AACrD,MAAI,KAAK,IACP,MAAK,MAAM,OAAO,KAAK,IAAI;AAE7B,MAAI,KAAK;QACF,MAAM,CAAC,KAAK,UAAU,KAAK,MAC9B,KAAI,MAAM,KAAK,SAAS,KAAK,IAAI,CAC/B,MAAK,MAAM,OAAO,IAAI;;;;CAO9B,IAAI,OAAe;AACjB,SAAO,KAAK,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register-cached-function.d.ts","sourceRoot":"","sources":["../../src/cache/register-cached-function.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"register-cached-function.d.ts","sourceRoot":"","sources":["../../src/cache/register-cached-function.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAoB5C,MAAM,WAAW,6BAA6B,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG;IAC/E,GAAG,EAAE,MAAM,CAAC;IACZ,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,EAAE,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC;IAC1D,4EAA4E;IAC5E,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AA4CD;;;;;;GAMG;AAEH,wBAAgB,sBAAsB,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EAChF,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,6BAA6B,CAAC,EAAE,CAAC,EACvC,OAAO,EAAE,YAAY,GACpB,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAoB/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timber-cache.d.ts","sourceRoot":"","sources":["../../src/cache/timber-cache.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"timber-cache.d.ts","sourceRoot":"","sources":["../../src/cache/timber-cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAsC1D;;;;;;;;;;;GAWG;AAEH,wBAAgB,WAAW,CAAC,EAAE,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EACrE,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,YAAY,CAAC,EAAE,CAAC,EACtB,OAAO,EAAE,YAAY,GACpB,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAyD/D;yBA7De,WAAW;8BAmEhB,YAAY,QACf;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,KACnC,OAAO,CAAC,IAAI,CAAC"}
|
|
@@ -12,8 +12,7 @@
|
|
|
12
12
|
* 3. Setting up client-side navigation for subsequent page transitions
|
|
13
13
|
*
|
|
14
14
|
* After hydration, the browser entry:
|
|
15
|
-
* -
|
|
16
|
-
* - Listens for mouseenter on <a data-timber-prefetch> for hover prefetch
|
|
15
|
+
* - Link click handling is per-component (Link's onClick), not global delegation
|
|
17
16
|
* - Listens for popstate events for back/forward navigation
|
|
18
17
|
*
|
|
19
18
|
* Design docs: 18-build-system.md §"Entry Files", 19-client-navigation.md
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-entry.d.ts","sourceRoot":"","sources":["../../src/client/browser-entry.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"browser-entry.d.ts","sourceRoot":"","sources":["../../src/client/browser-entry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG"}
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { JsonSerializable, RenderErrorDigest } from './types';
|
|
2
2
|
export { Link, interpolateParams, resolveHref, validateLinkHref, buildLinkProps } from './link';
|
|
3
3
|
export type { LinkProps, LinkPropsWithHref, LinkPropsWithParams } from './link';
|
|
4
|
-
export type { OnNavigateHandler, OnNavigateEvent } from './link
|
|
4
|
+
export type { OnNavigateHandler, OnNavigateEvent } from './link';
|
|
5
5
|
export { createRouter } from './router';
|
|
6
6
|
export type { RouterInstance, NavigationOptions, RouterDeps, RscDecoder, RootRenderer, } from './router';
|
|
7
7
|
export { useNavigationPending } from './use-navigation-pending';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAGA,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAGnE,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,WAAW,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAChG,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAChF,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot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AAG9D,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACtE,YAAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAGvF,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAG3D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAClG,YAAY,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAGxE,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,YAAY,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGtE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAClE,YAAY,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAG1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,YAAY,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC"}
|
package/dist/client/index.js
CHANGED
|
@@ -1,37 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { a as _setCurrentParams, c as cachedSearchParams, i as _setCachedSearch, l as currentParams, n as getSsrData, o as _setGlobalRouter, r as setSsrData, s as cachedSearch, t as clearSsrData, u as globalRouter } from "../_chunks/ssr-data-
|
|
3
|
-
import { n as useQueryStates, t as bindUseQueryStates } from "../_chunks/use-query-states-
|
|
4
|
-
import { t as useCookie } from "../_chunks/use-cookie-
|
|
2
|
+
import { a as _setCurrentParams, c as cachedSearchParams, i as _setCachedSearch, l as currentParams, n as getSsrData, o as _setGlobalRouter, r as setSsrData, s as cachedSearch, t as clearSsrData, u as globalRouter } from "../_chunks/ssr-data-MjmprTmO.js";
|
|
3
|
+
import { n as useQueryStates, t as bindUseQueryStates } from "../_chunks/use-query-states-D5KaffOK.js";
|
|
4
|
+
import { t as useCookie } from "../_chunks/use-cookie-DX-l1_5E.js";
|
|
5
5
|
import { TimberErrorBoundary } from "./error-boundary.js";
|
|
6
|
-
import React, { cloneElement, createContext, createElement, isValidElement, useActionState as useActionState$1, useContext,
|
|
6
|
+
import React, { cloneElement, createContext, createElement, isValidElement, useActionState as useActionState$1, useContext, useMemo, useSyncExternalStore, useTransition } from "react";
|
|
7
7
|
import { jsx } from "react/jsx-runtime";
|
|
8
|
-
//#region src/client/link-navigate-interceptor.tsx
|
|
9
|
-
/** Symbol used to store the onNavigate callback on anchor elements. */
|
|
10
|
-
var ON_NAVIGATE_KEY = "__timberOnNavigate";
|
|
11
|
-
/**
|
|
12
|
-
* Client component rendered inside <Link> that attaches the onNavigate
|
|
13
|
-
* callback to the closest <a> ancestor via a DOM property. The callback
|
|
14
|
-
* is cleaned up on unmount.
|
|
15
|
-
*
|
|
16
|
-
* Renders no extra DOM — just a transparent wrapper.
|
|
17
|
-
*/
|
|
18
|
-
function LinkNavigateInterceptor({ onNavigate, children }) {
|
|
19
|
-
const ref = useRef(null);
|
|
20
|
-
useEffect(() => {
|
|
21
|
-
const anchor = ref.current?.closest("a");
|
|
22
|
-
if (!anchor) return;
|
|
23
|
-
anchor[ON_NAVIGATE_KEY] = onNavigate;
|
|
24
|
-
return () => {
|
|
25
|
-
delete anchor[ON_NAVIGATE_KEY];
|
|
26
|
-
};
|
|
27
|
-
}, [onNavigate]);
|
|
28
|
-
return /* @__PURE__ */ jsx("span", {
|
|
29
|
-
ref,
|
|
30
|
-
style: { display: "contents" },
|
|
31
|
-
children
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
//#endregion
|
|
35
8
|
//#region src/client/use-link-status.ts
|
|
36
9
|
/**
|
|
37
10
|
* React context provided by <Link>. Holds the pending status
|
|
@@ -93,9 +66,15 @@ function useLinkStatus() {
|
|
|
93
66
|
* that depend on these APIs are safe to call from any environment —
|
|
94
67
|
* they return null or no-op when the APIs aren't available.
|
|
95
68
|
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
69
|
+
* SINGLETON GUARANTEE: All shared mutable state uses globalThis via
|
|
70
|
+
* Symbol.for keys. The RSC client bundler can duplicate this module
|
|
71
|
+
* across chunks (browser-entry graph + client-reference graph). With
|
|
72
|
+
* ESM output, each chunk gets its own module scope — module-level
|
|
73
|
+
* variables would create separate singleton instances per chunk.
|
|
74
|
+
* globalThis guarantees a single instance regardless of duplication.
|
|
75
|
+
*
|
|
76
|
+
* This workaround will be removed when Rolldown ships `format: 'app'`
|
|
77
|
+
* (module registry format that deduplicates like webpack/Turbopack).
|
|
99
78
|
* See design/27-chunking-strategy.md.
|
|
100
79
|
*
|
|
101
80
|
* See design/19-client-navigation.md §"NavigationContext"
|
|
@@ -104,14 +83,25 @@ function useLinkStatus() {
|
|
|
104
83
|
* The context is created lazily to avoid calling createContext at module
|
|
105
84
|
* level. In the RSC environment, React.createContext doesn't exist —
|
|
106
85
|
* calling it at import time would crash the server.
|
|
86
|
+
*
|
|
87
|
+
* Context instances are stored on globalThis (NOT in module-level
|
|
88
|
+
* variables) because the ESM bundler can duplicate this module across
|
|
89
|
+
* chunks. Module-level variables would create separate instances per
|
|
90
|
+
* chunk — the provider in TransitionRoot (index chunk) would use
|
|
91
|
+
* context A while the consumer in LinkStatusProvider (shared chunk)
|
|
92
|
+
* reads from context B. globalThis guarantees a single instance.
|
|
93
|
+
*
|
|
94
|
+
* See design/27-chunking-strategy.md §"Singleton Safety"
|
|
107
95
|
*/
|
|
108
|
-
var
|
|
109
|
-
var
|
|
96
|
+
var NAV_CTX_KEY = Symbol.for("__timber_nav_ctx");
|
|
97
|
+
var PENDING_CTX_KEY = Symbol.for("__timber_pending_nav_ctx");
|
|
110
98
|
function getOrCreateContext() {
|
|
111
|
-
|
|
99
|
+
const existing = globalThis[NAV_CTX_KEY];
|
|
100
|
+
if (existing !== void 0) return existing;
|
|
112
101
|
if (typeof React.createContext === "function") {
|
|
113
|
-
|
|
114
|
-
|
|
102
|
+
const ctx = React.createContext(null);
|
|
103
|
+
globalThis[NAV_CTX_KEY] = ctx;
|
|
104
|
+
return ctx;
|
|
115
105
|
}
|
|
116
106
|
}
|
|
117
107
|
/**
|
|
@@ -144,27 +134,42 @@ function NavigationProvider({ value, children }) {
|
|
|
144
134
|
* NavigationProvider with the correct params/pathname.
|
|
145
135
|
*
|
|
146
136
|
* This is NOT used by hooks directly — hooks read from React context.
|
|
137
|
+
*
|
|
138
|
+
* Stored on globalThis (like the context instances above) because the
|
|
139
|
+
* router lives in one chunk while renderRoot lives in another. Module-
|
|
140
|
+
* level variables would be separate per chunk.
|
|
147
141
|
*/
|
|
148
|
-
var
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
142
|
+
var NAV_STATE_KEY = Symbol.for("__timber_nav_state");
|
|
143
|
+
function _getNavStateStore() {
|
|
144
|
+
const g = globalThis;
|
|
145
|
+
if (!g[NAV_STATE_KEY]) g[NAV_STATE_KEY] = { current: {
|
|
146
|
+
params: {},
|
|
147
|
+
pathname: "/"
|
|
148
|
+
} };
|
|
149
|
+
return g[NAV_STATE_KEY];
|
|
150
|
+
}
|
|
152
151
|
function setNavigationState(state) {
|
|
153
|
-
|
|
152
|
+
_getNavStateStore().current = state;
|
|
154
153
|
}
|
|
155
154
|
function getNavigationState() {
|
|
156
|
-
return
|
|
155
|
+
return _getNavStateStore().current;
|
|
157
156
|
}
|
|
158
157
|
/**
|
|
159
158
|
* Separate context for the in-flight navigation URL. Provided by
|
|
160
159
|
* TransitionRoot (urgent useState), consumed by LinkStatusProvider
|
|
161
160
|
* and useNavigationPending.
|
|
161
|
+
*
|
|
162
|
+
* Uses globalThis via Symbol.for for the same reason as NavigationContext
|
|
163
|
+
* above — the bundler may duplicate this module across chunks, and module-
|
|
164
|
+
* level variables would create separate context instances.
|
|
162
165
|
*/
|
|
163
166
|
function getOrCreatePendingContext() {
|
|
164
|
-
|
|
167
|
+
const existing = globalThis[PENDING_CTX_KEY];
|
|
168
|
+
if (existing !== void 0) return existing;
|
|
165
169
|
if (typeof React.createContext === "function") {
|
|
166
|
-
|
|
167
|
-
|
|
170
|
+
const ctx = React.createContext(null);
|
|
171
|
+
globalThis[PENDING_CTX_KEY] = ctx;
|
|
172
|
+
return ctx;
|
|
168
173
|
}
|
|
169
174
|
}
|
|
170
175
|
/**
|
|
@@ -194,6 +199,30 @@ function LinkStatusProvider({ href, children }) {
|
|
|
194
199
|
});
|
|
195
200
|
}
|
|
196
201
|
//#endregion
|
|
202
|
+
//#region src/client/router-ref.ts
|
|
203
|
+
/**
|
|
204
|
+
* Set the global router instance. Called once during bootstrap.
|
|
205
|
+
*/
|
|
206
|
+
function setGlobalRouter(router) {
|
|
207
|
+
_setGlobalRouter(router);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Get the global router instance. Throws if called before bootstrap.
|
|
211
|
+
* Used by client-side hooks (useNavigationPending, etc.)
|
|
212
|
+
*/
|
|
213
|
+
function getRouter() {
|
|
214
|
+
if (!globalRouter) throw new Error("[timber] Router not initialized. getRouter() was called before bootstrap().");
|
|
215
|
+
return globalRouter;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Get the global router instance or null if not yet initialized.
|
|
219
|
+
* Used by useRouter() methods to avoid silent failures — callers
|
|
220
|
+
* can log a meaningful warning instead of silently no-oping.
|
|
221
|
+
*/
|
|
222
|
+
function getRouterOrNull() {
|
|
223
|
+
return globalRouter;
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
197
226
|
//#region src/client/link.tsx
|
|
198
227
|
/**
|
|
199
228
|
* Reject dangerous URL schemes that could execute script.
|
|
@@ -263,44 +292,81 @@ function resolveHref(href, params, searchParams) {
|
|
|
263
292
|
function buildLinkProps(props) {
|
|
264
293
|
const resolvedHref = resolveHref(props.href, props.params, props.searchParams);
|
|
265
294
|
validateLinkHref(resolvedHref);
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
295
|
+
return { href: resolvedHref };
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Should this click be intercepted for SPA navigation?
|
|
299
|
+
*
|
|
300
|
+
* Returns false (pass through to browser) when:
|
|
301
|
+
* - Modified keys are held (Ctrl, Meta, Shift, Alt) — open in new tab
|
|
302
|
+
* - The click is not the primary button
|
|
303
|
+
* - The event was already prevented by a parent handler
|
|
304
|
+
* - The link has target="_blank" or similar
|
|
305
|
+
* - The link has a download attribute
|
|
306
|
+
* - The href is external
|
|
307
|
+
*/
|
|
308
|
+
function shouldInterceptClick(event, resolvedHref) {
|
|
309
|
+
if (event.button !== 0) return false;
|
|
310
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;
|
|
311
|
+
if (event.defaultPrevented) return false;
|
|
312
|
+
const anchor = event.currentTarget;
|
|
313
|
+
if (anchor.target && anchor.target !== "_self") return false;
|
|
314
|
+
if (anchor.hasAttribute("download")) return false;
|
|
315
|
+
if (!isInternalHref(resolvedHref)) return false;
|
|
316
|
+
return true;
|
|
273
317
|
}
|
|
274
318
|
/**
|
|
275
319
|
* Navigation link with progressive enhancement.
|
|
276
320
|
*
|
|
277
321
|
* Renders as a plain `<a>` tag — works without JavaScript. When the client
|
|
278
|
-
* runtime is active,
|
|
279
|
-
*
|
|
322
|
+
* runtime is active, the Link's onClick handler triggers RSC-based client
|
|
323
|
+
* navigation via the router. No global event delegation — each Link owns
|
|
324
|
+
* its own click handling.
|
|
280
325
|
*
|
|
281
326
|
* Supports typed routes via codegen overloads. At runtime:
|
|
282
327
|
* - `params` prop interpolates dynamic segments in the href pattern
|
|
283
328
|
* - `searchParams` prop serializes query parameters via a SearchParamsDefinition
|
|
284
329
|
*/
|
|
285
|
-
function Link({ href, prefetch, scroll, params, searchParams, onNavigate, children, ...rest }) {
|
|
286
|
-
const
|
|
330
|
+
function Link({ href, prefetch, scroll, params, searchParams, onNavigate, onClick: userOnClick, onMouseEnter: userOnMouseEnter, children, ...rest }) {
|
|
331
|
+
const { href: resolvedHref } = buildLinkProps({
|
|
287
332
|
href,
|
|
288
|
-
prefetch,
|
|
289
|
-
scroll,
|
|
290
333
|
params,
|
|
291
334
|
searchParams
|
|
292
335
|
});
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
336
|
+
const internal = isInternalHref(resolvedHref);
|
|
337
|
+
const handleClick = internal ? (event) => {
|
|
338
|
+
userOnClick?.(event);
|
|
339
|
+
if (!shouldInterceptClick(event, resolvedHref)) return;
|
|
340
|
+
if (onNavigate) {
|
|
341
|
+
let prevented = false;
|
|
342
|
+
onNavigate({ preventDefault: () => {
|
|
343
|
+
prevented = true;
|
|
344
|
+
} });
|
|
345
|
+
if (prevented) {
|
|
346
|
+
event.preventDefault();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const router = getRouterOrNull();
|
|
351
|
+
if (!router) return;
|
|
352
|
+
event.preventDefault();
|
|
353
|
+
const shouldScroll = scroll !== false;
|
|
354
|
+
router.navigate(resolvedHref, { scroll: shouldScroll });
|
|
355
|
+
} : userOnClick;
|
|
356
|
+
const handleMouseEnter = internal && prefetch ? (event) => {
|
|
357
|
+
userOnMouseEnter?.(event);
|
|
358
|
+
const router = getRouterOrNull();
|
|
359
|
+
if (router) router.prefetch(resolvedHref);
|
|
360
|
+
} : userOnMouseEnter;
|
|
297
361
|
return /* @__PURE__ */ jsx("a", {
|
|
298
362
|
...rest,
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
363
|
+
href: resolvedHref,
|
|
364
|
+
onClick: handleClick,
|
|
365
|
+
onMouseEnter: handleMouseEnter,
|
|
366
|
+
children: /* @__PURE__ */ jsx(LinkStatusProvider, {
|
|
367
|
+
href: resolvedHref,
|
|
368
|
+
children
|
|
369
|
+
})
|
|
304
370
|
});
|
|
305
371
|
}
|
|
306
372
|
//#endregion
|
|
@@ -1105,30 +1171,6 @@ function useNavigationPending() {
|
|
|
1105
1171
|
return usePendingNavigationUrl() !== null;
|
|
1106
1172
|
}
|
|
1107
1173
|
//#endregion
|
|
1108
|
-
//#region src/client/router-ref.ts
|
|
1109
|
-
/**
|
|
1110
|
-
* Set the global router instance. Called once during bootstrap.
|
|
1111
|
-
*/
|
|
1112
|
-
function setGlobalRouter(router) {
|
|
1113
|
-
_setGlobalRouter(router);
|
|
1114
|
-
}
|
|
1115
|
-
/**
|
|
1116
|
-
* Get the global router instance. Throws if called before bootstrap.
|
|
1117
|
-
* Used by client-side hooks (useNavigationPending, etc.)
|
|
1118
|
-
*/
|
|
1119
|
-
function getRouter() {
|
|
1120
|
-
if (!globalRouter) throw new Error("[timber] Router not initialized. getRouter() was called before bootstrap().");
|
|
1121
|
-
return globalRouter;
|
|
1122
|
-
}
|
|
1123
|
-
/**
|
|
1124
|
-
* Get the global router instance or null if not yet initialized.
|
|
1125
|
-
* Used by useRouter() methods to avoid silent failures — callers
|
|
1126
|
-
* can log a meaningful warning instead of silently no-oping.
|
|
1127
|
-
*/
|
|
1128
|
-
function getRouterOrNull() {
|
|
1129
|
-
return globalRouter;
|
|
1130
|
-
}
|
|
1131
|
-
//#endregion
|
|
1132
1174
|
//#region src/client/use-router.ts
|
|
1133
1175
|
/**
|
|
1134
1176
|
* useRouter() — client-side hook for programmatic navigation.
|