@timber-js/app 0.2.0-alpha.147 → 0.2.0-alpha.148
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/{actions-OIZ8siQu.js → actions-a0RczDnB.js} +8 -34
- package/dist/_chunks/{actions-OIZ8siQu.js.map → actions-a0RczDnB.js.map} +1 -1
- package/dist/_chunks/cache-api-Co-yI-gP.js +424 -0
- package/dist/_chunks/cache-api-Co-yI-gP.js.map +1 -0
- package/dist/_chunks/{metadata-routes-BjepjefT.js → canonicalize-P41GR6tY.js} +65 -2
- package/dist/_chunks/canonicalize-P41GR6tY.js.map +1 -0
- package/dist/_chunks/{cli-schema-sync-CQaxupHv.js → cli-schema-sync-DJDdyEae.js} +111 -260
- package/dist/_chunks/cli-schema-sync-DJDdyEae.js.map +1 -0
- package/dist/_chunks/cli-schema-sync-D_IhHEUW.js +2 -0
- package/dist/_chunks/{define-DMVhsipD.js → define-Bssfp6ot.js} +3 -33
- package/dist/_chunks/define-Bssfp6ot.js.map +1 -0
- package/dist/_chunks/{define-C3RvHQPK.js → define-CFmvb4Bt.js} +15 -7
- package/dist/_chunks/define-CFmvb4Bt.js.map +1 -0
- package/dist/_chunks/{href-validation-DyZIzfMJ.js → href-validation-FiA_rToW.js} +2 -1
- package/dist/_chunks/{href-validation-DyZIzfMJ.js.map → href-validation-FiA_rToW.js.map} +1 -1
- package/dist/_chunks/{tracing-M_zKubhk.js → logger-CM0clugc.js} +394 -107
- package/dist/_chunks/logger-CM0clugc.js.map +1 -0
- package/dist/_chunks/navigation-root-bUDZLw74.js.map +1 -1
- package/dist/_chunks/plugin-context-DurqFBuY.js +2 -0
- package/dist/_chunks/plugin-context-GfDWsdd2.js +268 -0
- package/dist/_chunks/plugin-context-GfDWsdd2.js.map +1 -0
- package/dist/_chunks/{resolve-schema-Dj8tQloi.js → resolve-schema-3iUvBV5T.js} +3 -30
- package/dist/_chunks/resolve-schema-3iUvBV5T.js.map +1 -0
- package/dist/_chunks/{schema-bridge-DK_89h8O.js → schema-bridge-BY3QLBL7.js} +35 -2
- package/dist/_chunks/schema-bridge-BY3QLBL7.js.map +1 -0
- package/dist/_chunks/tree-match-D2l830j2.js +102 -0
- package/dist/_chunks/tree-match-D2l830j2.js.map +1 -0
- package/dist/_chunks/use-segment-params-D1CzlgBo.js.map +1 -1
- package/dist/_chunks/{walkers-Ck4Y45XN.js → walkers-DvWDj453.js} +107 -82
- package/dist/_chunks/walkers-DvWDj453.js.map +1 -0
- package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +36 -14
- package/dist/adapters/cloudflare-kv-cache.js.map +1 -1
- package/dist/adapters/compress-module.d.ts +5 -4
- package/dist/adapters/compress-module.d.ts.map +1 -1
- package/dist/adapters/nitro.d.ts +1 -3
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +14 -134
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/cache/cache-api.d.ts.map +1 -1
- package/dist/cache/index.d.ts +3 -1
- package/dist/cache/index.d.ts.map +1 -1
- package/dist/cache/index.js +20 -235
- package/dist/cache/index.js.map +1 -1
- package/dist/cache/invalidation-epoch.d.ts +43 -0
- package/dist/cache/invalidation-epoch.d.ts.map +1 -0
- package/dist/cache/redis-handler.d.ts +13 -0
- package/dist/cache/redis-handler.d.ts.map +1 -1
- package/dist/cache/timber-cache.d.ts +17 -9
- package/dist/cache/timber-cache.d.ts.map +1 -1
- package/dist/cli-schema-sync.d.ts +21 -1
- package/dist/cli-schema-sync.d.ts.map +1 -1
- package/dist/cli.d.ts +12 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +26 -31
- package/dist/cli.js.map +1 -1
- package/dist/client/browser-entry/hmr.d.ts.map +1 -1
- package/dist/client/browser-entry/hydrate.d.ts.map +1 -1
- package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
- package/dist/client/browser-entry/router-init.d.ts.map +1 -1
- package/dist/client/history.d.ts +10 -17
- package/dist/client/history.d.ts.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.js +30 -33
- package/dist/client/internal.js.map +1 -1
- package/dist/client/navigation-api.d.ts +9 -2
- package/dist/client/navigation-api.d.ts.map +1 -1
- package/dist/client/navigation-context.d.ts +0 -11
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/navigation-root.d.ts +0 -5
- package/dist/client/navigation-root.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/rsc-fetch.d.ts.map +1 -1
- package/dist/client/use-search-params.d.ts +10 -5
- package/dist/client/use-search-params.d.ts.map +1 -1
- package/dist/codec.js +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/cookies/define-cookie.d.ts.map +1 -1
- package/dist/cookies/index.js +2 -4
- package/dist/cookies/index.js.map +1 -1
- package/dist/dev-tools/dev-page-shell.d.ts +1 -0
- package/dist/dev-tools/dev-page-shell.d.ts.map +1 -1
- package/dist/dev-tools/hydration-overlay.d.ts +11 -0
- package/dist/dev-tools/hydration-overlay.d.ts.map +1 -0
- package/dist/dev-tools/index.d.ts +1 -2
- package/dist/dev-tools/index.d.ts.map +1 -1
- package/dist/fonts/ast-walk.d.ts +68 -0
- package/dist/fonts/ast-walk.d.ts.map +1 -0
- package/dist/fonts/ast.d.ts +23 -11
- package/dist/fonts/ast.d.ts.map +1 -1
- package/dist/fonts/bundle.d.ts +3 -1
- package/dist/fonts/bundle.d.ts.map +1 -1
- package/dist/fonts/dev-middleware.d.ts +1 -1
- package/dist/fonts/dev-middleware.d.ts.map +1 -1
- package/dist/fonts/fallbacks.d.ts +0 -7
- package/dist/fonts/fallbacks.d.ts.map +1 -1
- package/dist/fonts/google.d.ts +4 -2
- package/dist/fonts/google.d.ts.map +1 -1
- package/dist/fonts/local.d.ts +3 -3
- package/dist/fonts/local.d.ts.map +1 -1
- package/dist/fonts/paths.d.ts +43 -0
- package/dist/fonts/paths.d.ts.map +1 -0
- package/dist/fonts/pipeline.d.ts +7 -21
- package/dist/fonts/pipeline.d.ts.map +1 -1
- package/dist/fonts/transform.d.ts.map +1 -1
- package/dist/fonts/virtual-modules.d.ts +1 -18
- package/dist/fonts/virtual-modules.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +609 -406
- package/dist/index.js.map +1 -1
- package/dist/params/index.js +1 -1
- package/dist/params/resolve-schema.d.ts.map +1 -1
- package/dist/plugin-context.d.ts +28 -5
- package/dist/plugin-context.d.ts.map +1 -1
- package/dist/plugins/cache.d.ts +13 -5
- package/dist/plugins/cache.d.ts.map +1 -1
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/fonts.d.ts +1 -2
- package/dist/plugins/fonts.d.ts.map +1 -1
- package/dist/plugins/routing.d.ts.map +1 -1
- package/dist/routing/codegen.d.ts.map +1 -1
- package/dist/routing/convention-lint.d.ts.map +1 -1
- package/dist/routing/file-cache.d.ts +8 -0
- package/dist/routing/file-cache.d.ts.map +1 -0
- package/dist/routing/index.js +2 -2
- package/dist/routing/interception.d.ts +0 -5
- package/dist/routing/interception.d.ts.map +1 -1
- package/dist/routing/manifest-codegen.d.ts +32 -0
- package/dist/routing/manifest-codegen.d.ts.map +1 -0
- package/dist/routing/scanner.d.ts.map +1 -1
- package/dist/schema-bridge.d.ts +15 -0
- package/dist/schema-bridge.d.ts.map +1 -1
- package/dist/search-params/define.d.ts.map +1 -1
- package/dist/search-params/index.js +7 -3
- package/dist/search-params/index.js.map +1 -1
- package/dist/search-params/wrappers.d.ts.map +1 -1
- package/dist/segment-params/define.d.ts.map +1 -1
- package/dist/segment-params/index.js +1 -1
- package/dist/server/access-gate.d.ts.map +1 -1
- package/dist/server/actions.d.ts +0 -14
- package/dist/server/actions.d.ts.map +1 -1
- package/dist/server/build-manifest.d.ts +0 -29
- package/dist/server/build-manifest.d.ts.map +1 -1
- package/dist/server/canonicalize.d.ts +10 -0
- package/dist/server/canonicalize.d.ts.map +1 -1
- package/dist/server/deny-renderer.d.ts +1 -1
- package/dist/server/deny-renderer.d.ts.map +1 -1
- package/dist/server/html-injector-core.d.ts +8 -0
- package/dist/server/html-injector-core.d.ts.map +1 -1
- package/dist/server/html-injectors.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/internal.d.ts +1 -5
- package/dist/server/internal.d.ts.map +1 -1
- package/dist/server/internal.js +12 -171
- package/dist/server/internal.js.map +1 -1
- package/dist/server/node-stream-transforms.d.ts +0 -11
- package/dist/server/node-stream-transforms.d.ts.map +1 -1
- package/dist/server/render-utils.d.ts +25 -0
- package/dist/server/render-utils.d.ts.map +1 -0
- package/dist/server/route-element-builder.d.ts +11 -25
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
- package/dist/server/rsc-entry/helpers.d.ts +2 -18
- package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
- package/dist/server/ssr-render.d.ts.map +1 -1
- package/dist/shared/href-validation.d.ts.map +1 -1
- package/dist/shims/image.d.ts +15 -15
- package/package.json +2 -2
- package/src/adapters/cloudflare-kv-cache.ts +56 -19
- package/src/adapters/compress-module.ts +27 -118
- package/src/adapters/nitro.ts +3 -41
- package/src/adapters/raw-imports.d.ts +5 -0
- package/src/cache/cache-api.ts +9 -1
- package/src/cache/index.ts +5 -2
- package/src/cache/invalidation-epoch.ts +93 -0
- package/src/cache/redis-handler.ts +33 -2
- package/src/cache/timber-cache.ts +109 -53
- package/src/cli-schema-sync.ts +123 -30
- package/src/cli.ts +33 -37
- package/src/client/browser-entry/hmr.ts +0 -11
- package/src/client/browser-entry/hydrate.ts +39 -5
- package/src/client/browser-entry/post-hydration.ts +6 -15
- package/src/client/browser-entry/router-init.ts +98 -3
- package/src/client/history.ts +10 -24
- package/src/client/navigation-api.ts +14 -9
- package/src/client/navigation-context.ts +1 -21
- package/src/client/navigation-root.tsx +0 -8
- package/src/client/router.ts +18 -8
- package/src/client/rsc-fetch.ts +7 -2
- package/src/client/use-search-params.ts +10 -5
- package/src/config-validation.ts +33 -25
- package/src/cookies/define-cookie.ts +2 -18
- package/src/dev-tools/dev-page-shell.ts +6 -2
- package/src/dev-tools/hydration-overlay.ts +158 -0
- package/src/dev-tools/index.ts +3 -16
- package/src/fonts/ast-walk.ts +235 -0
- package/src/fonts/ast.ts +91 -249
- package/src/fonts/bundle.ts +16 -9
- package/src/fonts/dev-middleware.ts +16 -5
- package/src/fonts/fallbacks.ts +0 -23
- package/src/fonts/google.ts +7 -3
- package/src/fonts/local.ts +7 -6
- package/src/fonts/paths.ts +58 -0
- package/src/fonts/pipeline.ts +27 -48
- package/src/fonts/transform.ts +27 -0
- package/src/fonts/virtual-modules.ts +1 -57
- package/src/index.ts +5 -11
- package/src/params/resolve-schema.ts +2 -34
- package/src/plugin-context.ts +95 -17
- package/src/plugins/cache.ts +64 -17
- package/src/plugins/dev-server.ts +61 -9
- package/src/plugins/fonts.ts +21 -6
- package/src/plugins/routing.ts +5 -348
- package/src/routing/codegen.ts +3 -2
- package/src/routing/convention-lint.ts +4 -3
- package/src/routing/file-cache.ts +23 -0
- package/src/routing/interception.ts +2 -21
- package/src/routing/manifest-codegen.ts +290 -0
- package/src/routing/scanner.ts +5 -17
- package/src/routing/schema-validation.ts +2 -2
- package/src/schema-bridge.ts +63 -2
- package/src/search-params/define.ts +34 -2
- package/src/search-params/wrappers.ts +21 -3
- package/src/segment-params/define.ts +2 -62
- package/src/server/access-gate.tsx +8 -0
- package/src/server/actions.ts +8 -31
- package/src/server/build-manifest.ts +0 -56
- package/src/server/canonicalize.ts +6 -3
- package/src/server/deny-renderer.ts +6 -0
- package/src/server/html-injector-core.ts +19 -0
- package/src/server/html-injectors.ts +14 -4
- package/src/server/internal.ts +1 -18
- package/src/server/node-stream-transforms.ts +5 -72
- package/src/server/render-utils.ts +31 -0
- package/src/server/route-element-builder.ts +77 -47
- package/src/server/rsc-entry/error-renderer.ts +1 -0
- package/src/server/rsc-entry/helpers.ts +6 -34
- package/src/server/rsc-entry/index.ts +11 -0
- package/src/server/rsc-entry/render-route.ts +7 -9
- package/src/server/rsc-entry/rsc-payload.ts +2 -1
- package/src/server/rsc-entry/ssr-renderer.ts +2 -2
- package/src/server/ssr-render.ts +1 -11
- package/src/shared/href-validation.ts +8 -0
- package/dist/_chunks/cli-schema-sync-CBiMEtqa.js +0 -2
- package/dist/_chunks/cli-schema-sync-CQaxupHv.js.map +0 -1
- package/dist/_chunks/define-C3RvHQPK.js.map +0 -1
- package/dist/_chunks/define-DMVhsipD.js.map +0 -1
- package/dist/_chunks/handler-store-BVDgyTh7.js +0 -78
- package/dist/_chunks/handler-store-BVDgyTh7.js.map +0 -1
- package/dist/_chunks/logger-Dt-jQaBO.js +0 -291
- package/dist/_chunks/logger-Dt-jQaBO.js.map +0 -1
- package/dist/_chunks/metadata-routes-BjepjefT.js.map +0 -1
- package/dist/_chunks/resolve-schema-Dj8tQloi.js.map +0 -1
- package/dist/_chunks/schema-bridge-DK_89h8O.js.map +0 -1
- package/dist/_chunks/tracing-M_zKubhk.js.map +0 -1
- package/dist/_chunks/walkers-Ck4Y45XN.js.map +0 -1
- package/dist/_chunks/warnings-CNPXaypM.js +0 -125
- package/dist/_chunks/warnings-CNPXaypM.js.map +0 -1
- package/dist/client/link-pending-store.d.ts +0 -65
- package/dist/client/link-pending-store.d.ts.map +0 -1
- package/dist/client/nav-link-store.d.ts +0 -27
- package/dist/client/nav-link-store.d.ts.map +0 -1
- package/dist/dev-tools/warnings.d.ts +0 -109
- package/dist/dev-tools/warnings.d.ts.map +0 -1
- package/dist/server/flush.d.ts +0 -74
- package/dist/server/flush.d.ts.map +0 -1
- package/src/client/link-pending-store.ts +0 -116
- package/src/client/nav-link-store.ts +0 -37
- package/src/dev-tools/warnings.ts +0 -238
- package/src/server/flush.ts +0 -183
package/dist/cache/index.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import { d as logSwrRefetchFailed } from "../_chunks/logger-Dt-jQaBO.js";
|
|
3
|
-
import { t as fnv1aHash } from "../_chunks/fast-hash-D6hIVt1Y.js";
|
|
4
|
-
import { n as setCacheHandler, r as getWaitUntil, t as getCacheHandler } from "../_chunks/handler-store-BVDgyTh7.js";
|
|
1
|
+
import { i as setDefaultSingleflightTimeout, n as getCacheHandler, r as setCacheHandler, t as cache } from "../_chunks/cache-api-Co-yI-gP.js";
|
|
5
2
|
//#region src/cache/sizeof.ts
|
|
6
3
|
/**
|
|
7
4
|
* Lightweight byte-size estimation for cache entries.
|
|
@@ -76,14 +73,25 @@ var RedisCacheHandler = class {
|
|
|
76
73
|
const expiresAt = Date.now() + opts.ttl * 1e3;
|
|
77
74
|
const payload = JSON.stringify({
|
|
78
75
|
value,
|
|
79
|
-
expiresAt
|
|
76
|
+
expiresAt,
|
|
77
|
+
tags: opts.tags
|
|
80
78
|
});
|
|
81
79
|
const redisTtlSeconds = Math.max(opts.ttl * 2 + 60, 120);
|
|
82
80
|
await this.client.set(ck, payload, redisTtlSeconds);
|
|
83
|
-
for (const tag of opts.tags)
|
|
81
|
+
for (const tag of opts.tags) {
|
|
82
|
+
await this.client.sadd(this.tagKey(tag), key);
|
|
83
|
+
if (await this.client.ttl(this.tagKey(tag)) < redisTtlSeconds) await this.client.expire(this.tagKey(tag), redisTtlSeconds);
|
|
84
|
+
}
|
|
84
85
|
}
|
|
85
86
|
async invalidate(opts) {
|
|
86
|
-
if (opts.key)
|
|
87
|
+
if (opts.key) {
|
|
88
|
+
const raw = await this.client.get(this.cacheKey(opts.key));
|
|
89
|
+
if (raw !== null) {
|
|
90
|
+
const entry = JSON.parse(raw);
|
|
91
|
+
if (entry.tags) await Promise.all(entry.tags.map((tag) => this.client.srem(this.tagKey(tag), opts.key)));
|
|
92
|
+
}
|
|
93
|
+
await this.client.del(this.cacheKey(opts.key));
|
|
94
|
+
}
|
|
87
95
|
if (opts.tag) {
|
|
88
96
|
const tk = this.tagKey(opts.tag);
|
|
89
97
|
const keys = await this.client.smembers(tk);
|
|
@@ -93,231 +101,6 @@ var RedisCacheHandler = class {
|
|
|
93
101
|
}
|
|
94
102
|
};
|
|
95
103
|
//#endregion
|
|
96
|
-
//#region src/cache/stable-stringify.ts
|
|
97
|
-
/**
|
|
98
|
-
* Deterministic JSON serialization with sorted object keys.
|
|
99
|
-
* Used for cache key generation — ensures { a: 1, b: 2 } and { b: 2, a: 1 }
|
|
100
|
-
* produce the same string.
|
|
101
|
-
*
|
|
102
|
-
* Matches JSON.stringify semantics for toJSON: Date serializes to its ISO
|
|
103
|
-
* string, URL to its href, and class instances with a custom toJSON use it.
|
|
104
|
-
* Map and Set serialize their entries explicitly (insertion-order
|
|
105
|
-
* independent). Values that would serialize lossily — functions, symbols,
|
|
106
|
-
* and non-plain objects with no enumerable own state (RegExp, class
|
|
107
|
-
* instances holding data behind getters or internal slots) — throw instead:
|
|
108
|
-
* every such value would collapse to the same cache key, silently returning
|
|
109
|
-
* one argument's cached data for another (TIM-1020).
|
|
110
|
-
*/
|
|
111
|
-
function stableStringify(value) {
|
|
112
|
-
if (value === null || value === void 0) return String(value);
|
|
113
|
-
const type = typeof value;
|
|
114
|
-
if (type === "function" || type === "symbol") throw new TypeError(`stableStringify: cannot serialize a ${type} into a stable cache key — all such values would collide. Provide an explicit \`key\` option to cache().`);
|
|
115
|
-
if (type !== "object") return JSON.stringify(value);
|
|
116
|
-
if (Array.isArray(value)) return "[" + value.map((item) => stableStringify(item)).join(",") + "]";
|
|
117
|
-
const withToJSON = value;
|
|
118
|
-
if (typeof withToJSON.toJSON === "function") {
|
|
119
|
-
const json = withToJSON.toJSON();
|
|
120
|
-
if (json !== value) return stableStringify(json);
|
|
121
|
-
}
|
|
122
|
-
if (value instanceof Map) return "Map(" + [...value.entries()].map(([k, v]) => stableStringify(k) + "=>" + stableStringify(v)).sort().join(",") + ")";
|
|
123
|
-
if (value instanceof Set) return "Set(" + [...value].map((member) => stableStringify(member)).sort().join(",") + ")";
|
|
124
|
-
const obj = value;
|
|
125
|
-
const keys = Object.keys(obj).sort();
|
|
126
|
-
const pairs = [];
|
|
127
|
-
for (const key of keys) {
|
|
128
|
-
if (obj[key] === void 0) continue;
|
|
129
|
-
if (key === "toJSON" && typeof obj[key] === "function") continue;
|
|
130
|
-
pairs.push(JSON.stringify(key) + ":" + stableStringify(obj[key]));
|
|
131
|
-
}
|
|
132
|
-
if (pairs.length === 0) {
|
|
133
|
-
const proto = Object.getPrototypeOf(value);
|
|
134
|
-
if (proto !== Object.prototype && proto !== null) {
|
|
135
|
-
const name = value.constructor?.name || "Object";
|
|
136
|
-
throw new TypeError(`stableStringify: ${name} instance has no serializable own state — all instances would share one cache key. Provide an explicit \`key\` option to cache(), or add a toJSON() method.`);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
return "{" + pairs.join(",") + "}";
|
|
140
|
-
}
|
|
141
|
-
//#endregion
|
|
142
|
-
//#region src/cache/singleflight.ts
|
|
143
|
-
/**
|
|
144
|
-
* Error thrown when a singleflight call exceeds `timeoutMs`.
|
|
145
|
-
* Exported so callers can distinguish timeout from other errors.
|
|
146
|
-
*/
|
|
147
|
-
var SingleflightTimeoutError = class extends Error {
|
|
148
|
-
constructor(key, timeoutMs) {
|
|
149
|
-
super(`Singleflight timeout: key "${key}" exceeded ${timeoutMs}ms`);
|
|
150
|
-
this.name = "SingleflightTimeoutError";
|
|
151
|
-
}
|
|
152
|
-
};
|
|
153
|
-
function createSingleflight(opts) {
|
|
154
|
-
const inflight = /* @__PURE__ */ new Map();
|
|
155
|
-
const timeoutMs = opts?.timeoutMs;
|
|
156
|
-
return { do(key, fn) {
|
|
157
|
-
const existing = inflight.get(key);
|
|
158
|
-
if (existing) return existing;
|
|
159
|
-
let promise;
|
|
160
|
-
if (timeoutMs != null && timeoutMs > 0) promise = new Promise((resolve, reject) => {
|
|
161
|
-
const timer = setTimeout(() => reject(new SingleflightTimeoutError(key, timeoutMs)), timeoutMs);
|
|
162
|
-
try {
|
|
163
|
-
fn().then((value) => {
|
|
164
|
-
clearTimeout(timer);
|
|
165
|
-
resolve(value);
|
|
166
|
-
}, (err) => {
|
|
167
|
-
clearTimeout(timer);
|
|
168
|
-
reject(err);
|
|
169
|
-
});
|
|
170
|
-
} catch (err) {
|
|
171
|
-
clearTimeout(timer);
|
|
172
|
-
reject(err);
|
|
173
|
-
}
|
|
174
|
-
});
|
|
175
|
-
else promise = fn();
|
|
176
|
-
const tracked = promise.finally(() => {
|
|
177
|
-
inflight.delete(key);
|
|
178
|
-
});
|
|
179
|
-
inflight.set(key, tracked);
|
|
180
|
-
return tracked;
|
|
181
|
-
} };
|
|
182
|
-
}
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region src/cache/timber-cache.ts
|
|
185
|
-
var defaultSingleflight = createSingleflight();
|
|
186
|
-
/**
|
|
187
|
-
* Generate a cache key from function identity and serialized args.
|
|
188
|
-
*
|
|
189
|
-
* Uses FNV-1a (fast non-crypto hash) instead of SHA-256. Cache keys don't
|
|
190
|
-
* need collision resistance — they need speed. The fnId prefix provides
|
|
191
|
-
* namespace isolation; the hash covers the args.
|
|
192
|
-
*
|
|
193
|
-
* See TIM-370 for perf motivation.
|
|
194
|
-
*/
|
|
195
|
-
function defaultKeyGenerator(fnId, args) {
|
|
196
|
-
const raw = fnId + ":" + stableStringify(args);
|
|
197
|
-
return fnId + ":" + fnv1aHash(raw);
|
|
198
|
-
}
|
|
199
|
-
/**
|
|
200
|
-
* Resolve tags from the options — supports static array or function form.
|
|
201
|
-
*/
|
|
202
|
-
function resolveTags(opts, args) {
|
|
203
|
-
if (!opts.tags) return [];
|
|
204
|
-
if (Array.isArray(opts.tags)) return opts.tags;
|
|
205
|
-
return opts.tags(...args);
|
|
206
|
-
}
|
|
207
|
-
var unstableIdCounter = 0;
|
|
208
|
-
var hasWarnedUnstableId = false;
|
|
209
|
-
/**
|
|
210
|
-
* Creates a cached wrapper around an async function.
|
|
211
|
-
*
|
|
212
|
-
* - SHA-256 default keys with normalized JSON args
|
|
213
|
-
* - Singleflight: concurrent misses → single execution
|
|
214
|
-
* - SWR: serve stale immediately, background refetch
|
|
215
|
-
* - Tags as string[] or function of args
|
|
216
|
-
* - No ALS dependency for correctness — cache() works outside a request
|
|
217
|
-
* context. The waitUntil ALS bridge is read optionally so the SWR
|
|
218
|
-
* background refetch survives handler return on Workers/Lambda.
|
|
219
|
-
*
|
|
220
|
-
* Cache hits/misses are recorded as OTEL span events on the enclosing
|
|
221
|
-
* span (not child spans). The DevSpanProcessor reads these for dev log output.
|
|
222
|
-
*/
|
|
223
|
-
function createCache(fn, opts, handler, stableId) {
|
|
224
|
-
let fnId;
|
|
225
|
-
if (stableId) fnId = stableId;
|
|
226
|
-
else if (opts.key) fnId = `timber-cache:${unstableIdCounter++}`;
|
|
227
|
-
else {
|
|
228
|
-
fnId = `timber-cache:unstable:${unstableIdCounter++}`;
|
|
229
|
-
if (!hasWarnedUnstableId && typeof process !== "undefined" && process.env.NODE_ENV !== "test") {
|
|
230
|
-
hasWarnedUnstableId = true;
|
|
231
|
-
console.warn("[timber] cache() called without a stable ID or explicit key function. Cache keys will use a process-local counter which is unstable across cold starts. Run through the timber Vite plugin or provide an explicit `key` option to fix this.");
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
const sf = opts.timeoutMs ? createSingleflight({ timeoutMs: opts.timeoutMs }) : defaultSingleflight;
|
|
235
|
-
return (async (...args) => {
|
|
236
|
-
const key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId, args);
|
|
237
|
-
const cacheStart = performance.now();
|
|
238
|
-
const cached = await handler.get(key);
|
|
239
|
-
if (cached && !cached.stale) {
|
|
240
|
-
addSpanEventSync("timber.cache.hit", {
|
|
241
|
-
key,
|
|
242
|
-
duration_ms: Math.round(performance.now() - cacheStart)
|
|
243
|
-
});
|
|
244
|
-
return cached.value;
|
|
245
|
-
}
|
|
246
|
-
if (cached && cached.stale && opts.staleWhileRevalidate) {
|
|
247
|
-
addSpanEventSync("timber.cache.hit", {
|
|
248
|
-
key,
|
|
249
|
-
duration_ms: Math.round(performance.now() - cacheStart),
|
|
250
|
-
stale: true
|
|
251
|
-
});
|
|
252
|
-
const refetch = sf.do(`swr:${key}`, async () => {
|
|
253
|
-
try {
|
|
254
|
-
const fresh = await fn(...args);
|
|
255
|
-
const tags = resolveTags(opts, args);
|
|
256
|
-
await handler.set(key, fresh, {
|
|
257
|
-
ttl: opts.ttl,
|
|
258
|
-
tags
|
|
259
|
-
});
|
|
260
|
-
} catch (err) {
|
|
261
|
-
logSwrRefetchFailed({
|
|
262
|
-
cacheKey: key,
|
|
263
|
-
error: err
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
}).catch(() => {});
|
|
267
|
-
getWaitUntil()?.(refetch);
|
|
268
|
-
return cached.value;
|
|
269
|
-
}
|
|
270
|
-
const result = await sf.do(key, () => fn(...args));
|
|
271
|
-
const tags = resolveTags(opts, args);
|
|
272
|
-
await handler.set(key, result, {
|
|
273
|
-
ttl: opts.ttl,
|
|
274
|
-
tags
|
|
275
|
-
});
|
|
276
|
-
addSpanEventSync("timber.cache.miss", {
|
|
277
|
-
key,
|
|
278
|
-
duration_ms: Math.round(performance.now() - cacheStart)
|
|
279
|
-
});
|
|
280
|
-
return result;
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
/**
|
|
284
|
-
* Invalidate cache entries by tag or key.
|
|
285
|
-
*/
|
|
286
|
-
createCache.invalidate = async function invalidate(handler, opts) {
|
|
287
|
-
await handler.invalidate(opts);
|
|
288
|
-
};
|
|
289
|
-
//#endregion
|
|
290
|
-
//#region src/cache/cache-api.ts
|
|
291
|
-
/**
|
|
292
|
-
* Public caching API: `cache(fn, opts)`.
|
|
293
|
-
*
|
|
294
|
-
* Wraps an async function with cross-request caching. Uses the configured
|
|
295
|
-
* cache handler (defaults to MemoryCacheHandler, overridable via timber.config.ts).
|
|
296
|
-
*
|
|
297
|
-
* ```ts
|
|
298
|
-
* import { cache } from '@timber-js/app/cache';
|
|
299
|
-
*
|
|
300
|
-
* const getUser = cache(
|
|
301
|
-
* async (id: string) => db.users.findUnique({ where: { id } }),
|
|
302
|
-
* { ttl: 60, tags: (id) => [`user:${id}`] }
|
|
303
|
-
* );
|
|
304
|
-
* ```
|
|
305
|
-
*/
|
|
306
|
-
function cache(fn, opts, stableId) {
|
|
307
|
-
return createCache(fn, opts, getCacheHandler(), stableId);
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* Invalidate cache entries by tag or key.
|
|
311
|
-
*
|
|
312
|
-
* ```ts
|
|
313
|
-
* cache.invalidate({ tag: 'products' });
|
|
314
|
-
* cache.invalidate({ key: 'user:abc' });
|
|
315
|
-
* ```
|
|
316
|
-
*/
|
|
317
|
-
cache.invalidate = async function invalidate(opts) {
|
|
318
|
-
await getCacheHandler().invalidate(opts);
|
|
319
|
-
};
|
|
320
|
-
//#endregion
|
|
321
104
|
//#region src/cache/index.ts
|
|
322
105
|
var MemoryCacheHandler = class {
|
|
323
106
|
store = /* @__PURE__ */ new Map();
|
|
@@ -325,10 +108,12 @@ var MemoryCacheHandler = class {
|
|
|
325
108
|
maxBytes;
|
|
326
109
|
maxEntryBytes;
|
|
327
110
|
currentBytes = 0;
|
|
111
|
+
_trackBytes;
|
|
328
112
|
constructor(opts) {
|
|
329
113
|
this.maxEntries = opts?.maxEntries ?? opts?.maxSize ?? 1e3;
|
|
330
114
|
this.maxBytes = opts?.maxBytes;
|
|
331
115
|
this.maxEntryBytes = opts?.maxEntryBytes;
|
|
116
|
+
this._trackBytes = this.maxBytes !== void 0 || this.maxEntryBytes !== void 0;
|
|
332
117
|
}
|
|
333
118
|
async get(key) {
|
|
334
119
|
const entry = this.store.get(key);
|
|
@@ -342,7 +127,7 @@ var MemoryCacheHandler = class {
|
|
|
342
127
|
};
|
|
343
128
|
}
|
|
344
129
|
async set(key, value, opts) {
|
|
345
|
-
const byteSize = estimateByteSize(value);
|
|
130
|
+
const byteSize = this._trackBytes ? estimateByteSize(value) : 0;
|
|
346
131
|
if (this.maxEntryBytes !== void 0 && byteSize > this.maxEntryBytes) return;
|
|
347
132
|
if (this.store.has(key)) {
|
|
348
133
|
const existing = this.store.get(key);
|
|
@@ -381,7 +166,7 @@ var MemoryCacheHandler = class {
|
|
|
381
166
|
get size() {
|
|
382
167
|
return this.store.size;
|
|
383
168
|
}
|
|
384
|
-
/** Estimated total byte size of all cached values. */
|
|
169
|
+
/** Estimated total byte size of all cached values. Only tracked when maxBytes or maxEntryBytes is configured; returns 0 otherwise. */
|
|
385
170
|
get bytes() {
|
|
386
171
|
return this.currentBytes;
|
|
387
172
|
}
|
|
@@ -396,6 +181,6 @@ var MemoryCacheHandler = class {
|
|
|
396
181
|
}
|
|
397
182
|
};
|
|
398
183
|
//#endregion
|
|
399
|
-
export { MemoryCacheHandler, RedisCacheHandler, cache, estimateByteSize, getCacheHandler, setCacheHandler };
|
|
184
|
+
export { MemoryCacheHandler, RedisCacheHandler, cache, estimateByteSize, getCacheHandler, setCacheHandler, setDefaultSingleflightTimeout };
|
|
400
185
|
|
|
401
186
|
//# sourceMappingURL=index.js.map
|
package/dist/cache/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/cache/sizeof.ts","../../src/cache/redis-handler.ts","../../src/cache/stable-stringify.ts","../../src/cache/singleflight.ts","../../src/cache/timber-cache.ts","../../src/cache/cache-api.ts","../../src/cache/index.ts"],"sourcesContent":["/**\n * Lightweight byte-size estimation for cache entries.\n *\n * Estimates the in-memory byte cost of a JavaScript value using\n * JSON.stringify().length * 2 (UTF-16 char width). This is a rough\n * approximation — it doesn't account for V8 object overhead, Map\n * metadata, or non-serializable values — but it's fast and good\n * enough for cache budget enforcement.\n *\n * Values that fail JSON serialization (circular references, BigInt,\n * etc.) return 0, allowing the entry to be cached without counting\n * toward the byte budget. This is a conservative choice: it's better\n * to cache and undercount than to reject the entry.\n */\n\n/**\n * Estimate the byte size of a value.\n *\n * Uses `JSON.stringify(value).length * 2` to approximate UTF-16\n * in-memory size. Returns 0 if the value is not serializable.\n */\nexport function estimateByteSize(value: unknown): number {\n try {\n const json = JSON.stringify(value);\n if (json === undefined) return 0;\n // Each JS string character is 2 bytes (UTF-16)\n return json.length * 2;\n } catch (e) {\n // Circular reference or non-serializable value\n console.debug('[timber] sizeof estimation failed:', e instanceof Error ? e.message : e);\n return 0;\n }\n}\n","import type { CacheHandler } from './index';\n\n/**\n * Minimal Redis client contract for `RedisCacheHandler`.\n *\n * This is deliberately NOT the native shape of any client library. ioredis,\n * node-redis v4, and @upstash/redis all disagree on TTL argument shapes\n * (positional `'EX'` vs `{ EX }` vs `{ ex }`), method casing (`sadd` vs\n * `sAdd`), and array handling in `del` — a contract that pattern-matches one\n * client lets another silently drop the expiry (TIM-1030: node-redis ignored\n * the positional `'EX'` and wrote keys with no TTL). Instead, TTL semantics\n * are explicit in the signature and you adapt your client with a thin\n * wrapper, so a mismatch is a type error rather than silent unbounded\n * keyspace growth.\n *\n * @example ioredis\n * ```ts\n * import Redis from 'ioredis';\n * const redis = new Redis(process.env.REDIS_URL);\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, 'EX', ttl),\n * expire: (k, s) => redis.expire(k, s),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, ...m),\n * smembers: (k) => redis.smembers(k),\n * };\n * ```\n *\n * @example node-redis v4\n * ```ts\n * import { createClient } from 'redis';\n * const redis = createClient({ url: process.env.REDIS_URL });\n * await redis.connect();\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { EX: ttl }),\n * expire: (k, s) => redis.expire(k, s),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sAdd(k, m),\n * smembers: (k) => redis.sMembers(k),\n * };\n * ```\n *\n * @example @upstash/redis\n * ```ts\n * import { Redis } from '@upstash/redis';\n * // automaticDeserialization must be off: the handler stores JSON strings\n * // and parses them itself — auto-parsing would hand back objects.\n * const redis = new Redis({ url, token, automaticDeserialization: false });\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { ex: ttl }),\n * expire: (k, s) => redis.expire(k, s),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, m[0], ...m.slice(1)),\n * smembers: (k) => redis.smembers(k),\n * };\n * ```\n */\nexport interface RedisClient {\n /** `GET key` — the stored string, or null when absent. */\n get(key: string): Promise<string | null>;\n /**\n * `SET key value EX ttlSeconds` — store with an expiry. The TTL is a\n * required positional argument so no adapter can forget it.\n */\n set(key: string, value: string, ttlSeconds: number): Promise<unknown>;\n /** `EXPIRE key seconds` — set/refresh a key's TTL (used for tag sets). */\n expire(key: string, seconds: number): Promise<unknown>;\n /** `DEL key` — delete a single key. Multi-key deletes loop per key. */\n del(key: string): Promise<unknown>;\n /** `SADD key member [member ...]` — add members to a set. */\n sadd(key: string, ...members: string[]): Promise<unknown>;\n /** `SMEMBERS key` — all members of a set. */\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 wrapped to the {@link RedisClient} contract —\n * see the adapter examples on the interface for ioredis, node-redis v4, and\n * @upstash/redis.\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, 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 // One del per key: the only multi-key shape every client accepts.\n // ioredis takes del(...keys), node-redis takes del(key | key[]), and\n // @upstash/redis takes del(...keys) but breaks on an array argument.\n await Promise.all(keys.map((k) => this.client.del(this.cacheKey(k))));\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 *\n * Matches JSON.stringify semantics for toJSON: Date serializes to its ISO\n * string, URL to its href, and class instances with a custom toJSON use it.\n * Map and Set serialize their entries explicitly (insertion-order\n * independent). Values that would serialize lossily — functions, symbols,\n * and non-plain objects with no enumerable own state (RegExp, class\n * instances holding data behind getters or internal slots) — throw instead:\n * every such value would collapse to the same cache key, silently returning\n * one argument's cached data for another (TIM-1020).\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return String(value);\n\n const type = typeof value;\n if (type === 'function' || type === 'symbol') {\n throw new TypeError(\n `stableStringify: cannot serialize a ${type} into a stable cache key — ` +\n 'all such values would collide. Provide an explicit `key` option to cache().'\n );\n }\n if (type !== 'object') return JSON.stringify(value);\n\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).join(',') + ']';\n }\n\n // Honor toJSON like JSON.stringify does (Date → ISO string, URL → href,\n // custom class serialization). JSON.stringify does not re-invoke toJSON\n // on the value it returns, so a toJSON that returns `this` falls through\n // to plain own-property serialization instead of recursing forever.\n const withToJSON = value as { toJSON?: () => unknown };\n if (typeof withToJSON.toJSON === 'function') {\n const json = withToJSON.toJSON();\n if (json !== value) return stableStringify(json);\n }\n\n // Map/Set have no enumerable own properties — serialize entries explicitly.\n // Entries are sorted after serialization so insertion order doesn't change\n // the key. The Map(/Set( prefixes can't collide with object ('{'), array\n // ('['), or string ('\"') output.\n if (value instanceof Map) {\n const entries = [...value.entries()].map(\n ([k, v]) => stableStringify(k) + '=>' + stableStringify(v)\n );\n return 'Map(' + entries.sort().join(',') + ')';\n }\n if (value instanceof Set) {\n const members = [...value].map((member) => stableStringify(member));\n return 'Set(' + members.sort().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 // A callable own toJSON only reaches this loop via the returns-`this`\n // fall-through above. It's the serialization protocol, not data —\n // JSON.stringify omits it too.\n if (key === 'toJSON' && typeof obj[key] === 'function') continue;\n pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n\n // A non-plain object that serializes to '{}' carries its state behind\n // getters or internal slots (RegExp, sessions, ORM entities). Serializing\n // it would give every instance the same cache key.\n if (pairs.length === 0) {\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n const name = (value as object).constructor?.name || 'Object';\n throw new TypeError(\n `stableStringify: ${name} instance has no serializable own state — ` +\n 'all instances would share one cache key. Provide an explicit `key` ' +\n 'option to cache(), or add a toJSON() method.'\n );\n }\n }\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 *\n * An optional `timeoutMs` prevents hung `fn()` calls from permanently\n * blocking all future callers for that key. When set, `fn()` is raced\n * against a timeout — if the timeout fires first, the promise rejects\n * with `SingleflightTimeoutError`, `finally` cleans up the key, and\n * subsequent callers can retry. See TIM-518.\n */\n\nexport interface SingleflightOptions {\n /** Maximum time (ms) a coalesced call may run before being rejected. */\n timeoutMs?: number;\n}\n\nexport interface Singleflight {\n do<T>(key: string, fn: () => Promise<T>): Promise<T>;\n}\n\n/**\n * Error thrown when a singleflight call exceeds `timeoutMs`.\n * Exported so callers can distinguish timeout from other errors.\n */\nexport class SingleflightTimeoutError extends Error {\n constructor(key: string, timeoutMs: number) {\n super(`Singleflight timeout: key \"${key}\" exceeded ${timeoutMs}ms`);\n this.name = 'SingleflightTimeoutError';\n }\n}\n\nexport function createSingleflight(opts?: SingleflightOptions): Singleflight {\n const inflight = new Map<string, Promise<unknown>>();\n const timeoutMs = opts?.timeoutMs;\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 let promise: Promise<T>;\n\n if (timeoutMs != null && timeoutMs > 0) {\n // Race fn() against a timeout to prevent hung calls from\n // permanently blocking the key. See TIM-518.\n promise = new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new SingleflightTimeoutError(key, timeoutMs)),\n timeoutMs\n );\n // Wrap in try/catch so a synchronous throw from fn()\n // (e.g. argument validation) still clears the timer.\n // Without this, the timer leaks until expiry.\n try {\n fn().then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n }\n );\n } catch (err) {\n clearTimeout(timer);\n reject(err);\n }\n });\n } else {\n promise = fn();\n }\n\n const tracked = promise.finally(() => {\n inflight.delete(key);\n });\n\n inflight.set(key, tracked);\n return tracked as Promise<T>;\n },\n };\n}\n","import type { CacheHandler, CacheOptions } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\nimport { addSpanEventSync } from '../server/tracing.js';\nimport { logSwrRefetchFailed } from '../server/logger.js';\nimport { getWaitUntil } from '../server/waituntil-bridge.js';\nimport { fnv1aHash } from './fast-hash.js';\n\nconst defaultSingleflight = 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\nlet unstableIdCounter = 0;\nlet hasWarnedUnstableId = false;\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 for correctness — cache() works outside a request\n * context. The waitUntil ALS bridge is read optionally so the SWR\n * background refetch survives handler return on Workers/Lambda.\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 stableId?: string\n): Fn {\n let fnId: string;\n if (stableId) {\n fnId = stableId;\n } else if (opts.key) {\n // Explicit key function — fnId is only used for singleflight, not for\n // cache keys, so a counter is acceptable here.\n fnId = `timber-cache:${unstableIdCounter++}`;\n } else {\n fnId = `timber-cache:unstable:${unstableIdCounter++}`;\n if (\n !hasWarnedUnstableId &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'test'\n ) {\n hasWarnedUnstableId = true;\n console.warn(\n '[timber] cache() called without a stable ID or explicit key function. ' +\n 'Cache keys will use a process-local counter which is unstable across ' +\n 'cold starts. Run through the timber Vite plugin or provide an explicit ' +\n '`key` option to fix this.'\n );\n }\n }\n const sf = opts.timeoutMs\n ? createSingleflight({ timeoutMs: opts.timeoutMs })\n : defaultSingleflight;\n\n // Cast to Fn to preserve the original function's generic call signature.\n // Without this, generic type parameters (e.g. <T> in apiFetch<T>) are\n // erased and callers lose type safety on the return type.\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 const refetch = sf\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 (err) {\n // Failed refetch — stale entry continues to be served.\n logSwrRefetchFailed({ cacheKey: key, error: err });\n }\n })\n .catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n // Platforms that cancel work when the handler returns (Cloudflare\n // Workers, Lambda) would otherwise kill the refetch mid-flight —\n // stale data re-served forever. Register the (never-rejecting)\n // refetch with the request's waitUntil; undefined outside a request\n // context or on platforms without lifecycle extension (Node servers\n // keep floating promises alive, so behavior there is unchanged).\n getWaitUntil()?.(refetch);\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight\n const result = await sf.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 }) as unknown as Fn;\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 { CacheOptions } from './index';\nimport { createCache } from './timber-cache';\nimport { getCacheHandler } from './handler-store';\n\n/**\n * Public caching API: `cache(fn, opts)`.\n *\n * Wraps an async function with cross-request caching. Uses the configured\n * cache handler (defaults to MemoryCacheHandler, overridable via timber.config.ts).\n *\n * ```ts\n * import { cache } from '@timber-js/app/cache';\n *\n * const getUser = cache(\n * async (id: string) => db.users.findUnique({ where: { id } }),\n * { ttl: 60, tags: (id) => [`user:${id}`] }\n * );\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function cache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n stableId?: string\n): Fn {\n return createCache(fn, opts, getCacheHandler(), stableId);\n}\n\n/**\n * Invalidate cache entries by tag or key.\n *\n * ```ts\n * cache.invalidate({ tag: 'products' });\n * cache.invalidate({ key: 'user:abc' });\n * ```\n */\ncache.invalidate = async function invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n await getCacheHandler().invalidate(opts);\n};\n","// @timber-js/app/cache — Caching primitives\n\nimport { estimateByteSize } from './sizeof.js';\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 /** Timeout (ms) for singleflight-coalesced calls. Prevents hung fn() from\n * permanently blocking all future callers for the same cache key. See TIM-518. */\n timeoutMs?: number;\n}\n\nexport interface MemoryCacheHandlerOptions {\n /** Maximum number of entries. Oldest accessed entries are evicted first. Default: 1000. */\n maxEntries?: number;\n /**\n * @deprecated Use `maxEntries` instead. Will be removed in a future release.\n * Alias for `maxEntries` — maximum number of entries (not bytes).\n */\n maxSize?: number;\n /** Maximum total byte budget for all cached values. Oldest entries are evicted when exceeded. Default: no limit. */\n maxBytes?: number;\n /** Maximum byte size for a single cache entry. Entries exceeding this are silently dropped. Default: no limit. */\n maxEntryBytes?: number;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<\n string,\n { value: unknown; expiresAt: number; tags: string[]; byteSize: number }\n >();\n private maxEntries: number;\n private maxBytes: number | undefined;\n private maxEntryBytes: number | undefined;\n private currentBytes = 0;\n\n constructor(opts?: MemoryCacheHandlerOptions) {\n // maxEntries takes precedence over deprecated maxSize\n this.maxEntries = opts?.maxEntries ?? opts?.maxSize ?? 1000;\n this.maxBytes = opts?.maxBytes;\n this.maxEntryBytes = opts?.maxEntryBytes;\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 const byteSize = estimateByteSize(value);\n\n // Reject entries exceeding per-entry byte limit\n if (this.maxEntryBytes !== undefined && byteSize > this.maxEntryBytes) {\n return;\n }\n\n // If key already exists, delete first to refresh insertion order and reclaim bytes\n if (this.store.has(key)) {\n const existing = this.store.get(key)!;\n this.currentBytes -= existing.byteSize;\n this.store.delete(key);\n }\n\n // Evict oldest entries (front of Map) if at entry count capacity\n while (this.store.size >= this.maxEntries) {\n this.evictOldest();\n }\n\n // Evict oldest entries if byte budget would be exceeded\n if (this.maxBytes !== undefined) {\n while (this.currentBytes + byteSize > this.maxBytes && this.store.size > 0) {\n this.evictOldest();\n }\n // If the single entry exceeds the total byte budget, don't store it\n if (this.currentBytes + byteSize > this.maxBytes) {\n return;\n }\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n byteSize,\n });\n this.currentBytes += byteSize;\n }\n\n async invalidate(opts: { key?: string; tag?: string }) {\n if (opts.key) {\n const entry = this.store.get(opts.key);\n if (entry) {\n this.currentBytes -= entry.byteSize;\n this.store.delete(opts.key);\n }\n }\n if (opts.tag) {\n for (const [key, entry] of this.store) {\n if (entry.tags.includes(opts.tag)) {\n this.currentBytes -= entry.byteSize;\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 /** Estimated total byte size of all cached values. */\n get bytes(): number {\n return this.currentBytes;\n }\n\n /** Evict the oldest entry (front of Map). */\n private evictOldest(): void {\n const oldest = this.store.keys().next().value;\n if (oldest !== undefined) {\n const entry = this.store.get(oldest)!;\n this.currentBytes -= entry.byteSize;\n this.store.delete(oldest);\n }\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler';\nexport type { RedisClient } from './redis-handler';\nexport { cache } from './cache-api';\nexport { setCacheHandler, getCacheHandler } from './handler-store';\n// NOTE: registerCachedFunction (runtime for 'use cache' directive) removed.\n// Future feature pending design doc. See design/06-caching.md.\nexport { estimateByteSize } from './sizeof';\n// stableStringify, createSingleflight, and SingleflightTimeoutError are\n// internal utilities used by the cache implementation. They are not\n// re-exported here — import directly from the source files if needed\n// within the package. See TIM-720.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAiB,OAAwB;CACvD,IAAI;EACF,MAAM,OAAO,KAAK,UAAU,KAAK;EACjC,IAAI,SAAS,KAAA,GAAW,OAAO;EAE/B,OAAO,KAAK,SAAS;CACvB,SAAS,GAAG;EAEV,QAAQ,MAAM,sCAAsC,aAAa,QAAQ,EAAE,UAAU,CAAC;EACtF,OAAO;CACT;AACF;;;AC8CA,IAAM,aAAa;AACnB,IAAM,aAAa;;;;;;;;;;;;AAanB,IAAa,oBAAb,MAAuD;CACrD;CACA;CAEA,YAAY,QAAqB,MAA4B;EAC3D,KAAK,SAAS;EACd,KAAK,SAAS,MAAM,UAAU;CAChC;CAEA,SAAiB,KAAqB;EACpC,OAAO,GAAG,KAAK,SAAS,aAAa;CACvC;CAEA,OAAe,KAAqB;EAClC,OAAO,GAAG,KAAK,SAAS,aAAa;CACvC;CAEA,MAAM,IAAI,KAAiE;EACzE,MAAM,MAAM,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,GAAG,CAAC;EACpD,IAAI,QAAQ,MAAM,OAAO;EAEzB,MAAM,QAAQ,KAAK,MAAM,GAAG;EAC5B,MAAM,QAAQ,KAAK,IAAI,IAAI,MAAM;EACjC,OAAO;GAAE,OAAO,MAAM;GAAO;EAAM;CACrC;CAEA,MAAM,IAAI,KAAa,OAAgB,MAAs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;CACvB;CAEA,MAAM,WAAW,MAAsC;EACrD,IAAI,KAAK,KAAK;GACZ,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,GAAG;GACrC,IAAI,OAAO;IACT,KAAK,gBAAgB,MAAM;IAC3B,KAAK,MAAM,OAAO,KAAK,GAAG;GAC5B;EACF;EACA,IAAI,KAAK;QACF,MAAM,CAAC,KAAK,UAAU,KAAK,OAC9B,IAAI,MAAM,KAAK,SAAS,KAAK,GAAG,GAAG;IACjC,KAAK,gBAAgB,MAAM;IAC3B,KAAK,MAAM,OAAO,GAAG;GACvB;;CAGN;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAI,QAAgB;EAClB,OAAO,KAAK;CACd;;CAGA,cAA4B;EAC1B,MAAM,SAAS,KAAK,MAAM,KAAK,EAAE,KAAK,EAAE;EACxC,IAAI,WAAW,KAAA,GAAW;GACxB,MAAM,QAAQ,KAAK,MAAM,IAAI,MAAM;GACnC,KAAK,gBAAgB,MAAM;GAC3B,KAAK,MAAM,OAAO,MAAM;EAC1B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/cache/sizeof.ts","../../src/cache/redis-handler.ts","../../src/cache/index.ts"],"sourcesContent":["/**\n * Lightweight byte-size estimation for cache entries.\n *\n * Estimates the in-memory byte cost of a JavaScript value using\n * JSON.stringify().length * 2 (UTF-16 char width). This is a rough\n * approximation — it doesn't account for V8 object overhead, Map\n * metadata, or non-serializable values — but it's fast and good\n * enough for cache budget enforcement.\n *\n * Values that fail JSON serialization (circular references, BigInt,\n * etc.) return 0, allowing the entry to be cached without counting\n * toward the byte budget. This is a conservative choice: it's better\n * to cache and undercount than to reject the entry.\n */\n\n/**\n * Estimate the byte size of a value.\n *\n * Uses `JSON.stringify(value).length * 2` to approximate UTF-16\n * in-memory size. Returns 0 if the value is not serializable.\n */\nexport function estimateByteSize(value: unknown): number {\n try {\n const json = JSON.stringify(value);\n if (json === undefined) return 0;\n // Each JS string character is 2 bytes (UTF-16)\n return json.length * 2;\n } catch (e) {\n // Circular reference or non-serializable value\n console.debug('[timber] sizeof estimation failed:', e instanceof Error ? e.message : e);\n return 0;\n }\n}\n","import type { CacheHandler } from './index';\n\n/**\n * Minimal Redis client contract for `RedisCacheHandler`.\n *\n * This is deliberately NOT the native shape of any client library. ioredis,\n * node-redis v4, and @upstash/redis all disagree on TTL argument shapes\n * (positional `'EX'` vs `{ EX }` vs `{ ex }`), method casing (`sadd` vs\n * `sAdd`), and array handling in `del` — a contract that pattern-matches one\n * client lets another silently drop the expiry (TIM-1030: node-redis ignored\n * the positional `'EX'` and wrote keys with no TTL). Instead, TTL semantics\n * are explicit in the signature and you adapt your client with a thin\n * wrapper, so a mismatch is a type error rather than silent unbounded\n * keyspace growth.\n *\n * @example ioredis\n * ```ts\n * import Redis from 'ioredis';\n * const redis = new Redis(process.env.REDIS_URL);\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, 'EX', ttl),\n * expire: (k, s) => redis.expire(k, s),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, ...m),\n * srem: (k, ...m) => redis.srem(k, ...m),\n * smembers: (k) => redis.smembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n *\n * @example node-redis v4\n * ```ts\n * import { createClient } from 'redis';\n * const redis = createClient({ url: process.env.REDIS_URL });\n * await redis.connect();\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { EX: ttl }),\n * expire: (k, s) => redis.expire(k, s),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sAdd(k, m),\n * srem: (k, ...m) => redis.sRem(k, m),\n * smembers: (k) => redis.sMembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n *\n * @example @upstash/redis\n * ```ts\n * import { Redis } from '@upstash/redis';\n * // automaticDeserialization must be off: the handler stores JSON strings\n * // and parses them itself — auto-parsing would hand back objects.\n * const redis = new Redis({ url, token, automaticDeserialization: false });\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { ex: ttl }),\n * expire: (k, s) => redis.expire(k, s),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, m[0], ...m.slice(1)),\n * srem: (k, ...m) => redis.srem(k, m[0], ...m.slice(1)),\n * smembers: (k) => redis.smembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n */\nexport interface RedisClient {\n /** `GET key` — the stored string, or null when absent. */\n get(key: string): Promise<string | null>;\n /**\n * `SET key value EX ttlSeconds` — store with an expiry. The TTL is a\n * required positional argument so no adapter can forget it.\n */\n set(key: string, value: string, ttlSeconds: number): Promise<unknown>;\n /** `EXPIRE key seconds` — set/refresh a key's TTL (used for tag sets). */\n expire(key: string, seconds: number): Promise<unknown>;\n /** `DEL key` — delete a single key. Multi-key deletes loop per key. */\n del(key: string): Promise<unknown>;\n /** `SADD key member [member ...]` — add members to a set. */\n sadd(key: string, ...members: string[]): Promise<unknown>;\n /** `SREM key member [member ...]` — remove members from a set. */\n srem(key: string, ...members: string[]): Promise<unknown>;\n /** `SMEMBERS key` — all members of a set. */\n smembers(key: string): Promise<string[]>;\n /**\n * `TTL key` — remaining time-to-live in seconds. Returns -2 if the key does\n * not exist, -1 if the key exists but has no expiry.\n */\n ttl(key: string): Promise<number>;\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 wrapped to the {@link RedisClient} contract —\n * see the adapter examples on the interface for ioredis, node-redis v4, and\n * @upstash/redis.\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, tags: opts.tags });\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, redisTtlSeconds);\n\n // Track key membership in each tag set, and expire the set so it doesn't\n // outlive all its members. Only extend the TTL, never shorten — a short-TTL\n // entry must not shrink a tag set that already contains long-TTL entries,\n // otherwise invalidate({tag}) would miss the long-lived entries.\n for (const tag of opts.tags) {\n await this.client.sadd(this.tagKey(tag), key);\n const currentTtl = await this.client.ttl(this.tagKey(tag));\n // Only extend, never shorten. -2 = key doesn't exist (rare race after\n // sadd), -1 = no expiry (new set or legacy — set initial TTL), positive\n // but shorter = extend. A longer current TTL means a longer-lived entry\n // set it first — don't shorten.\n if (currentTtl < redisTtlSeconds) {\n await this.client.expire(this.tagKey(tag), redisTtlSeconds);\n }\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\n const raw = await this.client.get(this.cacheKey(opts.key));\n if (raw !== null) {\n const entry = JSON.parse(raw) as { tags?: string[] };\n if (entry.tags) {\n await Promise.all(entry.tags.map((tag) => this.client.srem(this.tagKey(tag), opts.key!)));\n }\n }\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 // One del per key: the only multi-key shape every client accepts.\n // ioredis takes del(...keys), node-redis takes del(key | key[]), and\n // @upstash/redis takes del(...keys) but breaks on an array argument.\n await Promise.all(keys.map((k) => this.client.del(this.cacheKey(k))));\n\n // Clean up the tag set itself\n await this.client.del(tk);\n }\n }\n}\n","// @timber-js/app/cache — Caching primitives\n\nimport { estimateByteSize } from './sizeof.js';\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 /** Timeout (ms) for singleflight-coalesced calls. Prevents hung fn() from\n * permanently blocking all future callers for the same cache key. See TIM-518. */\n timeoutMs?: number;\n}\n\nexport interface MemoryCacheHandlerOptions {\n /** Maximum number of entries. Oldest accessed entries are evicted first. Default: 1000. */\n maxEntries?: number;\n /**\n * @deprecated Use `maxEntries` instead. Will be removed in a future release.\n * Alias for `maxEntries` — maximum number of entries (not bytes).\n */\n maxSize?: number;\n /** Maximum total byte budget for all cached values. Oldest entries are evicted when exceeded. Default: no limit. */\n maxBytes?: number;\n /** Maximum byte size for a single cache entry. Entries exceeding this are silently dropped. Default: no limit. */\n maxEntryBytes?: number;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<\n string,\n { value: unknown; expiresAt: number; tags: string[]; byteSize: number }\n >();\n private maxEntries: number;\n private maxBytes: number | undefined;\n private maxEntryBytes: number | undefined;\n private currentBytes = 0;\n private readonly _trackBytes: boolean;\n\n constructor(opts?: MemoryCacheHandlerOptions) {\n // maxEntries takes precedence over deprecated maxSize\n this.maxEntries = opts?.maxEntries ?? opts?.maxSize ?? 1000;\n this.maxBytes = opts?.maxBytes;\n this.maxEntryBytes = opts?.maxEntryBytes;\n this._trackBytes = this.maxBytes !== undefined || this.maxEntryBytes !== undefined;\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 const byteSize = this._trackBytes ? estimateByteSize(value) : 0;\n\n // Reject entries exceeding per-entry byte limit\n if (this.maxEntryBytes !== undefined && byteSize > this.maxEntryBytes) {\n return;\n }\n\n // If key already exists, delete first to refresh insertion order and reclaim bytes\n if (this.store.has(key)) {\n const existing = this.store.get(key)!;\n this.currentBytes -= existing.byteSize;\n this.store.delete(key);\n }\n\n // Evict oldest entries (front of Map) if at entry count capacity\n while (this.store.size >= this.maxEntries) {\n this.evictOldest();\n }\n\n // Evict oldest entries if byte budget would be exceeded\n if (this.maxBytes !== undefined) {\n while (this.currentBytes + byteSize > this.maxBytes && this.store.size > 0) {\n this.evictOldest();\n }\n // If the single entry exceeds the total byte budget, don't store it\n if (this.currentBytes + byteSize > this.maxBytes) {\n return;\n }\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n byteSize,\n });\n this.currentBytes += byteSize;\n }\n\n async invalidate(opts: { key?: string; tag?: string }) {\n if (opts.key) {\n const entry = this.store.get(opts.key);\n if (entry) {\n this.currentBytes -= entry.byteSize;\n this.store.delete(opts.key);\n }\n }\n if (opts.tag) {\n for (const [key, entry] of this.store) {\n if (entry.tags.includes(opts.tag)) {\n this.currentBytes -= entry.byteSize;\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 /** Estimated total byte size of all cached values. Only tracked when maxBytes or maxEntryBytes is configured; returns 0 otherwise. */\n get bytes(): number {\n return this.currentBytes;\n }\n\n /** Evict the oldest entry (front of Map). */\n private evictOldest(): void {\n const oldest = this.store.keys().next().value;\n if (oldest !== undefined) {\n const entry = this.store.get(oldest)!;\n this.currentBytes -= entry.byteSize;\n this.store.delete(oldest);\n }\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler';\nexport type { RedisClient } from './redis-handler';\nexport { cache } from './cache-api';\nexport { setCacheHandler, getCacheHandler } from './handler-store';\nexport { setDefaultSingleflightTimeout } from './timber-cache';\n// NOTE: registerCachedFunction (runtime for 'use cache' directive) removed.\n// Future feature pending design doc. See design/06-caching.md.\nexport { estimateByteSize } from './sizeof';\n// stableStringify, createSingleflight, and SingleflightTimeoutError are\n// internal utilities used by the cache implementation. They are not\n// re-exported here — import directly from the source files if needed\n// within the package. See TIM-720.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAiB,OAAwB;CACvD,IAAI;EACF,MAAM,OAAO,KAAK,UAAU,KAAK;EACjC,IAAI,SAAS,KAAA,GAAW,OAAO;EAE/B,OAAO,KAAK,SAAS;CACvB,SAAS,GAAG;EAEV,QAAQ,MAAM,sCAAsC,aAAa,QAAQ,EAAE,UAAU,CAAC;EACtF,OAAO;CACT;AACF;;;AC2DA,IAAM,aAAa;AACnB,IAAM,aAAa;;;;;;;;;;;;AAanB,IAAa,oBAAb,MAAuD;CACrD;CACA;CAEA,YAAY,QAAqB,MAA4B;EAC3D,KAAK,SAAS;EACd,KAAK,SAAS,MAAM,UAAU;CAChC;CAEA,SAAiB,KAAqB;EACpC,OAAO,GAAG,KAAK,SAAS,aAAa;CACvC;CAEA,OAAe,KAAqB;EAClC,OAAO,GAAG,KAAK,SAAS,aAAa;CACvC;CAEA,MAAM,IAAI,KAAiE;EACzE,M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AAK,UACtC;EAEJ;EAEA,KAAK,MAAM,IAAI,KAAK;GAClB;GACA,WAAW,KAAK,IAAI,IAAI,KAAK,MAAM;GACnC,MAAM,KAAK;GACX;EACF,CAAC;EACD,KAAK,gBAAgB;CACvB;CAEA,MAAM,WAAW,MAAsC;EACrD,IAAI,KAAK,KAAK;GACZ,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,GAAG;GACrC,IAAI,OAAO;IACT,KAAK,gBAAgB,MAAM;IAC3B,KAAK,MAAM,OAAO,KAAK,GAAG;GAC5B;EACF;EACA,IAAI,KAAK;QACF,MAAM,CAAC,KAAK,UAAU,KAAK,OAC9B,IAAI,MAAM,KAAK,SAAS,KAAK,GAAG,GAAG;IACjC,KAAK,gBAAgB,MAAM;IAC3B,KAAK,MAAM,OAAO,GAAG;GACvB;;CAGN;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,MAAM;CACpB;;CAGA,IAAI,QAAgB;EAClB,OAAO,KAAK;CACd;;CAGA,cAA4B;EAC1B,MAAM,SAAS,KAAK,MAAM,KAAK,EAAE,KAAK,EAAE;EACxC,IAAI,WAAW,KAAA,GAAW;GACxB,MAAM,QAAQ,KAAK,MAAM,IAAI,MAAM;GACnC,KAAK,gBAAgB,MAAM;GAC3B,KAAK,MAAM,OAAO,MAAM;EAC1B;CACF;AACF"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-process invalidation epoch tracking for timber.cache (TIM-1028).
|
|
3
|
+
*
|
|
4
|
+
* handler.set for a cache miss runs after `fn()` resolves. An explicit
|
|
5
|
+
* `cache.invalidate({ tag })` / `revalidateTag` that lands while fn is in
|
|
6
|
+
* flight would otherwise be silently undone — the just-invalidated value
|
|
7
|
+
* re-stored as fresh for the full TTL, resurrecting pre-mutation data.
|
|
8
|
+
*
|
|
9
|
+
* Every invalidation bumps a monotonic epoch and records it against the
|
|
10
|
+
* invalidated key/tag. Before storing a result, the cache wrapper checks
|
|
11
|
+
* whether its key or any of its tags were invalidated after fn started and
|
|
12
|
+
* skips the write if so. Skipping is always safe: the only cost is one
|
|
13
|
+
* extra cache miss on the next call.
|
|
14
|
+
*
|
|
15
|
+
* Scope: per-process, like the singleflight map. An invalidation issued by
|
|
16
|
+
* another instance against a shared handler (Redis/KV) during fn flight is
|
|
17
|
+
* not observable here — closing that window fully would require store-level
|
|
18
|
+
* versioning, which no CacheHandler backend offers.
|
|
19
|
+
*/
|
|
20
|
+
/** The current epoch. Capture before running fn(), pass to wasInvalidatedSince. */
|
|
21
|
+
export declare function currentInvalidationEpoch(): number;
|
|
22
|
+
/**
|
|
23
|
+
* Record an invalidation. Call BEFORE handler.invalidate() so an execution
|
|
24
|
+
* whose set-check races the invalidation errs toward skipping the write.
|
|
25
|
+
*/
|
|
26
|
+
export declare function recordInvalidation(opts: {
|
|
27
|
+
key?: string;
|
|
28
|
+
tag?: string;
|
|
29
|
+
}): void;
|
|
30
|
+
/**
|
|
31
|
+
* Whether the key or any tag was invalidated after `startEpoch` (the epoch
|
|
32
|
+
* captured when fn started executing).
|
|
33
|
+
*/
|
|
34
|
+
export declare function wasInvalidatedSince(startEpoch: number, key: string, tags: string[]): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* The highest epoch at which the key or any of the tags was invalidated
|
|
37
|
+
* (0 if never). Used to scope the singleflight key: callers arriving after
|
|
38
|
+
* an invalidation must not coalesce onto a flight that started before it —
|
|
39
|
+
* they would receive the pre-invalidation result the invalidation was
|
|
40
|
+
* issued to discard.
|
|
41
|
+
*/
|
|
42
|
+
export declare function lastInvalidationEpochFor(key: string, tags: string[]): number;
|
|
43
|
+
//# sourceMappingURL=invalidation-epoch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invalidation-epoch.d.ts","sourceRoot":"","sources":["../../src/cache/invalidation-epoch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAwBH,mFAAmF;AACnF,wBAAgB,wBAAwB,IAAI,MAAM,CAEjD;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAI7E;AAaD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAE5F;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAS5E"}
|
|
@@ -22,7 +22,9 @@ import type { CacheHandler } from './index';
|
|
|
22
22
|
* expire: (k, s) => redis.expire(k, s),
|
|
23
23
|
* del: (k) => redis.del(k),
|
|
24
24
|
* sadd: (k, ...m) => redis.sadd(k, ...m),
|
|
25
|
+
* srem: (k, ...m) => redis.srem(k, ...m),
|
|
25
26
|
* smembers: (k) => redis.smembers(k),
|
|
27
|
+
* ttl: (k) => redis.ttl(k),
|
|
26
28
|
* };
|
|
27
29
|
* ```
|
|
28
30
|
*
|
|
@@ -37,7 +39,9 @@ import type { CacheHandler } from './index';
|
|
|
37
39
|
* expire: (k, s) => redis.expire(k, s),
|
|
38
40
|
* del: (k) => redis.del(k),
|
|
39
41
|
* sadd: (k, ...m) => redis.sAdd(k, m),
|
|
42
|
+
* srem: (k, ...m) => redis.sRem(k, m),
|
|
40
43
|
* smembers: (k) => redis.sMembers(k),
|
|
44
|
+
* ttl: (k) => redis.ttl(k),
|
|
41
45
|
* };
|
|
42
46
|
* ```
|
|
43
47
|
*
|
|
@@ -53,7 +57,9 @@ import type { CacheHandler } from './index';
|
|
|
53
57
|
* expire: (k, s) => redis.expire(k, s),
|
|
54
58
|
* del: (k) => redis.del(k),
|
|
55
59
|
* sadd: (k, ...m) => redis.sadd(k, m[0], ...m.slice(1)),
|
|
60
|
+
* srem: (k, ...m) => redis.srem(k, m[0], ...m.slice(1)),
|
|
56
61
|
* smembers: (k) => redis.smembers(k),
|
|
62
|
+
* ttl: (k) => redis.ttl(k),
|
|
57
63
|
* };
|
|
58
64
|
* ```
|
|
59
65
|
*/
|
|
@@ -71,8 +77,15 @@ export interface RedisClient {
|
|
|
71
77
|
del(key: string): Promise<unknown>;
|
|
72
78
|
/** `SADD key member [member ...]` — add members to a set. */
|
|
73
79
|
sadd(key: string, ...members: string[]): Promise<unknown>;
|
|
80
|
+
/** `SREM key member [member ...]` — remove members from a set. */
|
|
81
|
+
srem(key: string, ...members: string[]): Promise<unknown>;
|
|
74
82
|
/** `SMEMBERS key` — all members of a set. */
|
|
75
83
|
smembers(key: string): Promise<string[]>;
|
|
84
|
+
/**
|
|
85
|
+
* `TTL key` — remaining time-to-live in seconds. Returns -2 if the key does
|
|
86
|
+
* not exist, -1 if the key exists but has no expiry.
|
|
87
|
+
*/
|
|
88
|
+
ttl(key: string): Promise<number>;
|
|
76
89
|
}
|
|
77
90
|
/**
|
|
78
91
|
* Redis-backed CacheHandler for distributed caching.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis-handler.d.ts","sourceRoot":"","sources":["../../src/cache/redis-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C
|
|
1
|
+
{"version":3,"file":"redis-handler.d.ts","sourceRoot":"","sources":["../../src/cache/redis-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AACH,MAAM,WAAW,WAAW;IAC1B,0DAA0D;IAC1D,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACzC;;;OAGG;IACH,GAAG,C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AE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BtF,UAAU,CAAC,IAAI,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAyBtE"}
|
|
@@ -1,11 +1,25 @@
|
|
|
1
1
|
import type { CacheHandler, CacheOptions } from './index';
|
|
2
|
+
/**
|
|
3
|
+
* Set the timeout for the module-level default singleflight.
|
|
4
|
+
* Called at framework boot with renderTimeoutMs from timber.config.ts so that
|
|
5
|
+
* cache calls without a per-call timeoutMs still get deadlock protection.
|
|
6
|
+
* See design/06-caching.md §"Singleflight Timeout — Deadlock Risk".
|
|
7
|
+
*/
|
|
8
|
+
export declare function setDefaultSingleflightTimeout(timeoutMs: number): void;
|
|
2
9
|
/**
|
|
3
10
|
* Creates a cached wrapper around an async function.
|
|
4
11
|
*
|
|
5
|
-
* -
|
|
6
|
-
* - Singleflight: concurrent misses → single execution
|
|
12
|
+
* - FNV-1a default keys with normalized JSON args
|
|
13
|
+
* - Singleflight: concurrent misses → single execution AND single
|
|
14
|
+
* handler.set — the write happens inside the coalesced callback (TIM-1028)
|
|
15
|
+
* - Writes are skipped when the key/tags were invalidated while fn was in
|
|
16
|
+
* flight, so explicit invalidation is never silently undone (TIM-1028)
|
|
7
17
|
* - SWR: serve stale immediately, background refetch
|
|
8
18
|
* - Tags as string[] or function of args
|
|
19
|
+
* - The handler is resolved per invocation via `getHandler`, never captured
|
|
20
|
+
* at wrapper-creation time — module-scope cache() wrappers created before
|
|
21
|
+
* the framework's boot wiring calls setCacheHandler() still use the
|
|
22
|
+
* configured handler once it arrives (TIM-1029)
|
|
9
23
|
* - No ALS dependency for correctness — cache() works outside a request
|
|
10
24
|
* context. The waitUntil ALS bridge is read optionally so the SWR
|
|
11
25
|
* background refetch survives handler return on Workers/Lambda.
|
|
@@ -13,11 +27,5 @@ import type { CacheHandler, CacheOptions } from './index';
|
|
|
13
27
|
* Cache hits/misses are recorded as OTEL span events on the enclosing
|
|
14
28
|
* span (not child spans). The DevSpanProcessor reads these for dev log output.
|
|
15
29
|
*/
|
|
16
|
-
export declare function createCache<Fn extends (...args: any[]) => Promise<any>>(fn: Fn, opts: CacheOptions<Fn>,
|
|
17
|
-
export declare namespace createCache {
|
|
18
|
-
var invalidate: (handler: CacheHandler, opts: {
|
|
19
|
-
key?: string;
|
|
20
|
-
tag?: string;
|
|
21
|
-
}) => Promise<void>;
|
|
22
|
-
}
|
|
30
|
+
export declare function createCache<Fn extends (...args: any[]) => Promise<any>>(fn: Fn, opts: CacheOptions<Fn>, getHandler: () => CacheHandler, stableId?: string): Fn;
|
|
23
31
|
//# sourceMappingURL=timber-cache.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;AAe1D;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAErE;AAoED;;;;;;;;;;;;;;;;;;;;GAoBG;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,UAAU,EAAE,MAAM,YAAY,EAC9B,QAAQ,CAAC,EAAE,MAAM,GAChB,EAAE,CAoGJ"}
|
|
@@ -10,9 +10,29 @@
|
|
|
10
10
|
* Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.
|
|
11
11
|
*/
|
|
12
12
|
export declare function collectDynamicSegments(appDir: string): string[];
|
|
13
|
+
/**
|
|
14
|
+
* Locate the `segmentParams: { ... }` block in a schema file.
|
|
15
|
+
* Returns the indices of the opening and matching closing brace, or null
|
|
16
|
+
* if no segmentParams property is found. Comments and strings are masked
|
|
17
|
+
* first, so a JSDoc example mentioning `segmentParams: { ... }` above the
|
|
18
|
+
* real defineSchema call is not mistaken for the block, and braces inside
|
|
19
|
+
* comments/strings don't skew the depth count. The search is anchored to
|
|
20
|
+
* the `defineSchema(` call when present, so helper objects with their own
|
|
21
|
+
* segmentParams property earlier in the file are skipped.
|
|
22
|
+
*/
|
|
23
|
+
export declare function findSegmentParamsBlock(content: string): {
|
|
24
|
+
openBrace: number;
|
|
25
|
+
closeBrace: number;
|
|
26
|
+
} | null;
|
|
13
27
|
/**
|
|
14
28
|
* Parse existing bracket keys from an app/schema.ts file.
|
|
15
|
-
*
|
|
29
|
+
* Scoped to the segmentParams: { ... } block — bracket keys elsewhere in
|
|
30
|
+
* the file (unrelated objects, comments above defineSchema) are ignored.
|
|
31
|
+
* Comments inside the block are masked, so a commented-out entry does not
|
|
32
|
+
* count as registered.
|
|
33
|
+
*
|
|
34
|
+
* The key charset matches the route classifier (segment-classify.ts):
|
|
35
|
+
* any character except `]`, so hyphenated params like '[my-param]' parse.
|
|
16
36
|
*/
|
|
17
37
|
export declare function parseExistingSchemaKeys(content: string): string[];
|
|
18
38
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-schema-sync.d.ts","sourceRoot":"","sources":["../src/cli-schema-sync.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAK/D;
|
|
1
|
+
{"version":3,"file":"cli-schema-sync.d.ts","sourceRoot":"","sources":["../src/cli-schema-sync.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAK/D;AAoED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,GACd;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAoBlD;AAED;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAajE;AAKD;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMjE;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAI1D;AA6ID,MAAM,WAAW,gBAAgB;IAC/B,wCAAwC;IACxC,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,iDAAiD;IACjD,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,gCAAgC;IAChC,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,4DAA4D;IAC5D,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,6CAA6C;IAC7C,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,gBAAgB,CA8DnE"}
|