@rexezuge/runtime 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/base/AbstractDurableObjectWorker.js +1 -38
  2. package/dist/base/AbstractDurableObjectWorker.js.map +7 -1
  3. package/dist/base/AbstractEntrypointWorker.js +1 -35
  4. package/dist/base/AbstractEntrypointWorker.js.map +7 -1
  5. package/dist/base/AbstractQueueWorker.js +1 -13
  6. package/dist/base/AbstractQueueWorker.js.map +7 -1
  7. package/dist/base/AbstractWorkflowWorker.js +1 -13
  8. package/dist/base/AbstractWorkflowWorker.js.map +7 -1
  9. package/dist/base/index.js +1 -5
  10. package/dist/base/index.js.map +7 -1
  11. package/dist/config/AppConfiguration.d.ts +6 -2
  12. package/dist/config/AppConfiguration.d.ts.map +1 -1
  13. package/dist/config/AppConfiguration.js +1 -63
  14. package/dist/config/AppConfiguration.js.map +7 -1
  15. package/dist/config/ConfigurationDefaults.d.ts +3 -1
  16. package/dist/config/ConfigurationDefaults.d.ts.map +1 -1
  17. package/dist/config/ConfigurationDefaults.js +1 -12
  18. package/dist/config/ConfigurationDefaults.js.map +7 -1
  19. package/dist/config/EnvParser.d.ts +3 -1
  20. package/dist/config/EnvParser.d.ts.map +1 -1
  21. package/dist/config/EnvParser.js +1 -59
  22. package/dist/config/EnvParser.js.map +7 -1
  23. package/dist/config/index.js +1 -4
  24. package/dist/config/index.js.map +7 -1
  25. package/dist/di/Container.js +1 -48
  26. package/dist/di/Container.js.map +7 -1
  27. package/dist/di/RequestScope.js +1 -22
  28. package/dist/di/RequestScope.js.map +7 -1
  29. package/dist/di/index.js +1 -3
  30. package/dist/di/index.js.map +7 -1
  31. package/dist/index.js +1 -18
  32. package/dist/index.js.map +7 -1
  33. package/dist/kv/KvCache.js +1 -197
  34. package/dist/kv/KvCache.js.map +7 -1
  35. package/dist/kv/KvDomains.js +1 -101
  36. package/dist/kv/KvDomains.js.map +7 -1
  37. package/dist/kv/index.js +1 -3
  38. package/dist/kv/index.js.map +7 -1
  39. package/dist/logger.js +1 -47
  40. package/dist/logger.js.map +7 -1
  41. package/dist/scheduled/index.d.ts +21 -7
  42. package/dist/scheduled/index.d.ts.map +1 -1
  43. package/dist/scheduled/index.js +1 -151
  44. package/dist/scheduled/index.js.map +7 -1
  45. package/package.json +2 -2
@@ -1 +1,7 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/di/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC","sourcesContent":["export { Container } from './Container.ts';\nexport type { Factory, Token } from './Container.ts';\nexport { asScopedContext, getRequestScope, setRequestScope } from './RequestScope.ts';\nexport type { ScopedContext } from './RequestScope.ts';\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/di/index.ts"],
4
+ "sourcesContent": ["export { Container } from './Container.ts';\nexport type { Factory, Token } from './Container.ts';\nexport { asScopedContext, getRequestScope, setRequestScope } from './RequestScope.ts';\nexport type { ScopedContext } from './RequestScope.ts';\n"],
5
+ "mappings": "AAAA,OAAS,aAAAA,MAAiB,iBAE1B,OAAS,mBAAAC,EAAiB,mBAAAC,EAAiB,mBAAAC,MAAuB",
6
+ "names": ["Container", "asScopedContext", "getRequestScope", "setRequestScope"]
7
+ }
package/dist/index.js CHANGED
@@ -1,18 +1 @@
1
- /**
2
- * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,
3
- * worker bases, logger, KV cache. Zero dependencies (the one platform import
4
- * is type-only, resolved through each consumer's generated wrangler types).
5
- */
6
- export { Container } from "./di/Container.js";
7
- export { asScopedContext, getRequestScope, setRequestScope } from "./di/RequestScope.js";
8
- export { AppConfiguration } from "./config/AppConfiguration.js";
9
- export { EnvParser } from "./config/EnvParser.js";
10
- export { DEFAULT_SITE_URL } from "./config/ConfigurationDefaults.js";
11
- export { AbstractEntrypointWorker } from "./base/AbstractEntrypointWorker.js";
12
- export { AbstractDurableObjectWorker } from "./base/AbstractDurableObjectWorker.js";
13
- export { AbstractQueueWorker } from "./base/AbstractQueueWorker.js";
14
- export { AbstractWorkflowWorker } from "./base/AbstractWorkflowWorker.js";
15
- export { createLogger, isLogLevel, resolveLogLevel } from "./logger.js";
16
- export { KvCache, KV_DOMAINS, buildKvKey, clampTtl, digest128 } from "./kv/index.js";
17
- export { AbstractScheduledTask, TaskRegistry } from "./scheduled/index.js";
18
- //# sourceMappingURL=index.js.map
1
+ import{Container as o}from"./di/Container.js";import{asScopedContext as p,getRequestScope as s,setRequestScope as a}from"./di/RequestScope.js";import{AppConfiguration as c}from"./config/AppConfiguration.js";import{EnvParser as x}from"./config/EnvParser.js";import{DEFAULT_SITE_URL as b}from"./config/ConfigurationDefaults.js";import{AbstractEntrypointWorker as i}from"./base/AbstractEntrypointWorker.js";import{AbstractDurableObjectWorker as u}from"./base/AbstractDurableObjectWorker.js";import{AbstractQueueWorker as k}from"./base/AbstractQueueWorker.js";import{AbstractWorkflowWorker as v}from"./base/AbstractWorkflowWorker.js";import{createLogger as d,isLogLevel as T,resolveLogLevel as W}from"./logger.js";import{KvCache as E,KV_DOMAINS as K,buildKvKey as R,clampTtl as y,digest128 as D}from"./kv/index.js";import{AbstractScheduledTask as h,TaskRegistry as q}from"./scheduled/index.js";export{u as AbstractDurableObjectWorker,i as AbstractEntrypointWorker,k as AbstractQueueWorker,h as AbstractScheduledTask,v as AbstractWorkflowWorker,c as AppConfiguration,o as Container,b as DEFAULT_SITE_URL,x as EnvParser,K as KV_DOMAINS,E as KvCache,q as TaskRegistry,p as asScopedContext,R as buildKvKey,y as clampTtl,d as createLogger,D as digest128,s as getRequestScope,T as isLogLevel,W as resolveLogLevel,a as setRequestScope};
package/dist/index.js.map CHANGED
@@ -1 +1,7 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEzF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAE9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAE1E,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAExE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAErF,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["/**\n * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,\n * worker bases, logger, KV cache. Zero dependencies (the one platform import\n * is type-only, resolved through each consumer's generated wrangler types).\n */\n\nexport { Container } from './di/Container.ts';\nexport type { Factory, Token } from './di/Container.ts';\nexport { asScopedContext, getRequestScope, setRequestScope } from './di/RequestScope.ts';\nexport type { ScopedContext } from './di/RequestScope.ts';\nexport { AppConfiguration } from './config/AppConfiguration.ts';\nexport { EnvParser } from './config/EnvParser.ts';\nexport { DEFAULT_SITE_URL } from './config/ConfigurationDefaults.ts';\nexport { AbstractEntrypointWorker } from './base/AbstractEntrypointWorker.ts';\nexport type { WorkerExecutionContext, WorkerScheduledController } from './base/AbstractEntrypointWorker.ts';\nexport { AbstractDurableObjectWorker } from './base/AbstractDurableObjectWorker.ts';\nexport { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';\nexport type { WorkerMessageBatch } from './base/AbstractQueueWorker.ts';\nexport { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';\nexport type { WorkflowEventLike, WorkflowStepLike } from './base/AbstractWorkflowWorker.ts';\nexport { createLogger, isLogLevel, resolveLogLevel } from './logger.ts';\nexport type { LogLevel, Logger } from './logger.ts';\nexport { KvCache, KV_DOMAINS, buildKvKey, clampTtl, digest128 } from './kv/index.ts';\nexport type { KvDomainDef, KvDomainName, KvNamespaceLike } from './kv/index.ts';\nexport { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary } from './scheduled/index.ts';\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,\n * worker bases, logger, KV cache. Zero dependencies (the one platform import\n * is type-only, resolved through each consumer's generated wrangler types).\n */\n\nexport { Container } from './di/Container.ts';\nexport type { Factory, Token } from './di/Container.ts';\nexport { asScopedContext, getRequestScope, setRequestScope } from './di/RequestScope.ts';\nexport type { ScopedContext } from './di/RequestScope.ts';\nexport { AppConfiguration } from './config/AppConfiguration.ts';\nexport { EnvParser } from './config/EnvParser.ts';\nexport { DEFAULT_SITE_URL } from './config/ConfigurationDefaults.ts';\nexport { AbstractEntrypointWorker } from './base/AbstractEntrypointWorker.ts';\nexport type { WorkerExecutionContext, WorkerScheduledController } from './base/AbstractEntrypointWorker.ts';\nexport { AbstractDurableObjectWorker } from './base/AbstractDurableObjectWorker.ts';\nexport { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';\nexport type { WorkerMessageBatch } from './base/AbstractQueueWorker.ts';\nexport { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';\nexport type { WorkflowEventLike, WorkflowStepLike } from './base/AbstractWorkflowWorker.ts';\nexport { createLogger, isLogLevel, resolveLogLevel } from './logger.ts';\nexport type { LogLevel, Logger } from './logger.ts';\nexport { KvCache, KV_DOMAINS, buildKvKey, clampTtl, digest128 } from './kv/index.ts';\nexport type { KvDomainDef, KvDomainName, KvNamespaceLike } from './kv/index.ts';\nexport { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary } from './scheduled/index.ts';\n"],
5
+ "mappings": "AAMA,OAAS,aAAAA,MAAiB,oBAE1B,OAAS,mBAAAC,EAAiB,mBAAAC,EAAiB,mBAAAC,MAAuB,uBAElE,OAAS,oBAAAC,MAAwB,+BACjC,OAAS,aAAAC,MAAiB,wBAC1B,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,4BAAAC,MAAgC,qCAEzC,OAAS,+BAAAC,MAAmC,wCAC5C,OAAS,uBAAAC,MAA2B,gCAEpC,OAAS,0BAAAC,MAA8B,mCAEvC,OAAS,gBAAAC,EAAc,cAAAC,EAAY,mBAAAC,MAAuB,cAE1D,OAAS,WAAAC,EAAS,cAAAC,EAAY,cAAAC,EAAY,YAAAC,EAAU,aAAAC,MAAiB,gBAErE,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB",
6
+ "names": ["Container", "asScopedContext", "getRequestScope", "setRequestScope", "AppConfiguration", "EnvParser", "DEFAULT_SITE_URL", "AbstractEntrypointWorker", "AbstractDurableObjectWorker", "AbstractQueueWorker", "AbstractWorkflowWorker", "createLogger", "isLogLevel", "resolveLogLevel", "KvCache", "KV_DOMAINS", "buildKvKey", "clampTtl", "digest128", "AbstractScheduledTask", "TaskRegistry"]
7
+ }
@@ -1,197 +1 @@
1
- import { createLogger } from "../logger.js";
2
- import { KV_DOMAINS, buildKvKey, clampTtl, utf8ByteLength } from "./KvDomains.js";
3
- /**
4
- * `KvCache` — typed facade over the single `CACHE` KV binding.
5
- *
6
- * Converged from `backend-runtime/src/kv/KvCache.ts`, identical in the four
7
- * repos that cache through KV. Semantics are fail-soft by design: reads return
8
- * `null` on miss, missing binding, or backend error; writes return `false`
9
- * when skipped (no binding, oversize value, backend error) and `true` when
10
- * stored. Callers treat KV as a pure optimization — D1/DO stay authoritative.
11
- */
12
- const logger = createLogger('KvCache');
13
- const PURGE_LIST_LIMIT = 1000;
14
- const PURGE_MAX_PAGES = 10;
15
- class KvCache {
16
- namespace;
17
- constructor(namespace) {
18
- this.namespace = namespace;
19
- }
20
- get available() {
21
- return !!this.namespace;
22
- }
23
- async getText(domain, parts) {
24
- const ns = this.namespace;
25
- if (!ns)
26
- return null;
27
- try {
28
- return await ns.get(buildKvKey(domain, parts));
29
- }
30
- catch (error) {
31
- logger.debug(`KV get failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);
32
- return null;
33
- }
34
- }
35
- async putText(domain, parts, value, options) {
36
- const ns = this.namespace;
37
- if (!ns)
38
- return false;
39
- // No unknown-domain check: `buildKvKey` below throws for one, and the
40
- // return type has never been able to express that. A silent `false` here
41
- // would have made an unknown domain look like a namespace miss.
42
- const def = KV_DOMAINS[domain];
43
- if (utf8ByteLength(value) > def.maxValueBytes) {
44
- logger.debug(`KV put skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);
45
- return false;
46
- }
47
- try {
48
- const ttl = clampTtl(options?.ttlSeconds, domain);
49
- await ns.put(buildKvKey(domain, parts), value, { expirationTtl: ttl });
50
- return true;
51
- }
52
- catch (error) {
53
- logger.debug(`KV put failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);
54
- return false;
55
- }
56
- }
57
- async getJson(domain, parts) {
58
- const raw = await this.getText(domain, parts);
59
- if (raw === null)
60
- return null;
61
- try {
62
- return JSON.parse(raw);
63
- }
64
- catch {
65
- return null;
66
- }
67
- }
68
- async putJson(domain, parts, value, options) {
69
- let raw;
70
- try {
71
- raw = JSON.stringify(value);
72
- }
73
- catch {
74
- return false;
75
- }
76
- return typeof raw === 'string' && this.putText(domain, parts, raw, options);
77
- }
78
- /**
79
- * Binary read for the `asset` domain: value bytes plus `{etag, contentType}`
80
- * KV metadata in a single entry. Legacy base64-JSON entries carry no metadata
81
- * and read as a miss here — the caller falls back to `getJson` for one TTL
82
- * window rather than this layer knowing the legacy shape.
83
- */
84
- async getBinary(domain, parts) {
85
- const ns = this.namespace;
86
- if (!ns || typeof ns.getWithMetadata !== 'function')
87
- return null;
88
- try {
89
- const res = await ns.getWithMetadata(buildKvKey(domain, parts), 'arrayBuffer');
90
- if (!res || res.value == null)
91
- return null;
92
- const value = res.value;
93
- let bytes = null;
94
- if (value instanceof ArrayBuffer) {
95
- bytes = new Uint8Array(value.slice(0));
96
- }
97
- else if (value instanceof Uint8Array) {
98
- bytes = value.slice();
99
- }
100
- else if (typeof value === 'string') {
101
- bytes = new TextEncoder().encode(value);
102
- }
103
- if (!bytes)
104
- return null;
105
- const meta = res.metadata;
106
- if (typeof meta !== 'object' || meta === null || typeof meta.etag !== 'string' || meta.etag === '')
107
- return null;
108
- return { bytes, metadata: { etag: meta.etag, contentType: typeof meta.contentType === 'string' ? meta.contentType : null } };
109
- }
110
- catch (error) {
111
- logger.debug(`KV getBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);
112
- return null;
113
- }
114
- }
115
- /**
116
- * Binary write for the `asset` domain. Size is enforced on raw bytes (no
117
- * base64 inflation) and failures stay fail-soft like `putText`.
118
- */
119
- async putBinary(domain, parts, bytes, metadata, options) {
120
- const ns = this.namespace;
121
- if (!ns)
122
- return false;
123
- if (!(bytes instanceof Uint8Array)) {
124
- logger.debug(`KV putBinary skipped for ${domain}: value is not bytes.`);
125
- return false;
126
- }
127
- const def = KV_DOMAINS[domain];
128
- if (bytes.byteLength > def.maxValueBytes) {
129
- logger.debug(`KV putBinary skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);
130
- return false;
131
- }
132
- if (typeof metadata?.etag !== 'string' || metadata.etag === '') {
133
- logger.debug(`KV putBinary skipped for ${domain}: missing etag metadata.`);
134
- return false;
135
- }
136
- try {
137
- const ttl = clampTtl(options?.ttlSeconds, domain);
138
- const contentType = typeof metadata.contentType === 'string' ? metadata.contentType : null;
139
- await ns.put(buildKvKey(domain, parts), bytes.slice().buffer, {
140
- expirationTtl: ttl,
141
- metadata: { etag: metadata.etag, contentType },
142
- });
143
- return true;
144
- }
145
- catch (error) {
146
- logger.debug(`KV putBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);
147
- return false;
148
- }
149
- }
150
- async del(domain, parts) {
151
- const ns = this.namespace;
152
- if (!ns)
153
- return;
154
- try {
155
- await ns.delete(buildKvKey(domain, parts));
156
- }
157
- catch (error) {
158
- logger.debug(`KV delete failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);
159
- }
160
- }
161
- /**
162
- * Delete every key under a prefix, page-capped. Restarts from the start after
163
- * each page: deleting while a positional cursor advances would skip keys.
164
- */
165
- async purgePrefix(domain, parts = []) {
166
- const ns = this.namespace;
167
- if (!ns)
168
- return 0;
169
- const prefix = parts.length === 0 ? `${domain}:` : buildKvKey(domain, parts);
170
- let deleted = 0;
171
- try {
172
- for (let page = 0; page < PURGE_MAX_PAGES; page += 1) {
173
- const result = await ns.list({ prefix, limit: PURGE_LIST_LIMIT });
174
- if (result.keys.length === 0)
175
- return deleted;
176
- for (const key of result.keys) {
177
- await ns.delete(key.name);
178
- deleted += 1;
179
- }
180
- if (result.keys.length < PURGE_LIST_LIMIT)
181
- return deleted;
182
- }
183
- // The cap was hit with a full page still coming back, so keys remain and
184
- // the caller sees a count indistinguishable from a complete purge. A
185
- // write-invalidation that silently under-purges serves pre-write bytes
186
- // for a whole TTL while reporting success, so this is never silent.
187
- logger.warn(`KV purge for ${domain} hit the ${PURGE_MAX_PAGES * PURGE_LIST_LIMIT}-key page cap; ` + `at least one key may survive invalidation`);
188
- return deleted;
189
- }
190
- catch (error) {
191
- logger.warn(`KV purge for ${domain} failed: ${error instanceof Error ? error.message : String(error)}`);
192
- return deleted;
193
- }
194
- }
195
- }
196
- export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES };
197
- //# sourceMappingURL=KvCache.js.map
1
+ import{createLogger as h}from"../logger.js";import{KV_DOMAINS as g,buildKvKey as c,clampTtl as y,utf8ByteLength as d}from"./KvDomains.js";const u=h("KvCache"),f=1e3,o=10;class ${namespace;constructor(e){this.namespace=e}get available(){return!!this.namespace}async getText(e,i){const r=this.namespace;if(!r)return null;try{return await r.get(c(e,i))}catch(t){return u.debug(`KV get failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}async putText(e,i,r,t){const n=this.namespace;if(!n)return!1;const s=g[e];if(d(r)>s.maxValueBytes)return u.debug(`KV put skipped for ${e}: value exceeds ${s.maxValueBytes} bytes.`),!1;try{const a=y(t?.ttlSeconds,e);return await n.put(c(e,i),r,{expirationTtl:a}),!0}catch(a){return u.debug(`KV put failed for ${e}: ${a instanceof Error?a.message:String(a)}`),!1}}async getJson(e,i){const r=await this.getText(e,i);if(r===null)return null;try{return JSON.parse(r)}catch{return null}}async putJson(e,i,r,t){let n;try{n=JSON.stringify(r)}catch{return!1}return typeof n=="string"&&this.putText(e,i,n,t)}async getBinary(e,i){const r=this.namespace;if(!r||typeof r.getWithMetadata!="function")return null;try{const t=await r.getWithMetadata(c(e,i),"arrayBuffer");if(!t||t.value==null)return null;const n=t.value;let s=null;if(n instanceof ArrayBuffer?s=new Uint8Array(n.slice(0)):n instanceof Uint8Array?s=n.slice():typeof n=="string"&&(s=new TextEncoder().encode(n)),!s)return null;const a=t.metadata;return typeof a!="object"||a===null||typeof a.etag!="string"||a.etag===""?null:{bytes:s,metadata:{etag:a.etag,contentType:typeof a.contentType=="string"?a.contentType:null}}}catch(t){return u.debug(`KV getBinary failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}async putBinary(e,i,r,t,n){const s=this.namespace;if(!s)return!1;if(!(r instanceof Uint8Array))return u.debug(`KV putBinary skipped for ${e}: value is not bytes.`),!1;const a=g[e];if(r.byteLength>a.maxValueBytes)return u.debug(`KV putBinary skipped for ${e}: value exceeds ${a.maxValueBytes} bytes.`),!1;if(typeof t?.etag!="string"||t.etag==="")return u.debug(`KV putBinary skipped for ${e}: missing etag metadata.`),!1;try{const l=y(n?.ttlSeconds,e),p=typeof t.contentType=="string"?t.contentType:null;return await s.put(c(e,i),r.slice().buffer,{expirationTtl:l,metadata:{etag:t.etag,contentType:p}}),!0}catch(l){return u.debug(`KV putBinary failed for ${e}: ${l instanceof Error?l.message:String(l)}`),!1}}async del(e,i){const r=this.namespace;if(r)try{await r.delete(c(e,i))}catch(t){u.debug(`KV delete failed for ${e}: ${t instanceof Error?t.message:String(t)}`)}}async purgePrefix(e,i=[]){const r=this.namespace;if(!r)return 0;const t=i.length===0?`${e}:`:c(e,i);let n=0;try{for(let s=0;s<o;s+=1){const a=await r.list({prefix:t,limit:f});if(a.keys.length===0)return n;for(const l of a.keys)await r.delete(l.name),n+=1;if(a.keys.length<f)return n}return u.warn(`KV purge for ${e} hit the ${o*f}-key page cap; at least one key may survive invalidation`),n}catch(s){return u.warn(`KV purge for ${e} failed: ${s instanceof Error?s.message:String(s)}`),n}}}export{$ as KvCache,f as PURGE_LIST_LIMIT,o as PURGE_MAX_PAGES};
@@ -1 +1,7 @@
1
- {"version":3,"file":"KvCache.js","sourceRoot":"","sources":["../../src/kv/KvCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAGlF;;;;;;;;GAQG;AAEH,MAAM,MAAM,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAqCvC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAC9B,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,MAAM,OAAO;IACyB;IAApC,YAAoC,SAAkC;QA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esContent":["import { createLogger } from '../logger.ts';\nimport { KV_DOMAINS, buildKvKey, clampTtl, utf8ByteLength } from './KvDomains.ts';\nimport type { KvDomainName } from './KvDomains.ts';\n\n/**\n * `KvCache` — typed facade over the single `CACHE` KV binding.\n *\n * Converged from `backend-runtime/src/kv/KvCache.ts`, identical in the four\n * repos that cache through KV. Semantics are fail-soft by design: reads return\n * `null` on miss, missing binding, or backend error; writes return `false`\n * when skipped (no binding, oversize value, backend error) and `true` when\n * stored. Callers treat KV as a pure optimization — D1/DO stay authoritative.\n */\n\nconst logger = createLogger('KvCache');\n\ninterface KvListPage {\n keys: Array<{ name: string }>;\n list_complete: boolean;\n cursor?: string;\n}\n\ninterface KvGetWithMetadataResult {\n value: string | ArrayBuffer | null;\n metadata: unknown;\n}\n\ninterface KvNamespaceLike {\n get(key: string): Promise<string | null>;\n get(key: string, type: 'text'): Promise<string | null>;\n get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;\n getWithMetadata?(key: string, type: 'arrayBuffer'): Promise<KvGetWithMetadataResult>;\n put(key: string, value: string | ArrayBuffer, options?: { expirationTtl?: number; metadata?: unknown }): Promise<void>;\n delete(key: string): Promise<unknown>;\n list(options: { prefix: string; limit?: number; cursor?: string }): Promise<KvListPage>;\n}\n\ninterface KvPutOptions {\n ttlSeconds?: number;\n}\n\ninterface KvFileMetadata {\n etag: string;\n contentType: string | null;\n}\n\ninterface KvBinaryEntry {\n bytes: Uint8Array;\n metadata: KvFileMetadata;\n}\n\nconst PURGE_LIST_LIMIT = 1000;\nconst PURGE_MAX_PAGES = 10;\n\nclass KvCache {\n public constructor(private readonly namespace?: KvNamespaceLike | null) {}\n\n public get available(): boolean {\n return !!this.namespace;\n }\n\n public async getText(domain: KvDomainName, parts: readonly string[]): Promise<string | null> {\n const ns = this.namespace;\n if (!ns) return null;\n try {\n return await ns.get(buildKvKey(domain, parts));\n } catch (error) {\n logger.debug(`KV get failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n }\n\n public async putText(domain: KvDomainName, parts: readonly string[], value: string, options?: KvPutOptions): Promise<boolean> {\n const ns = this.namespace;\n if (!ns) return false;\n // No unknown-domain check: `buildKvKey` below throws for one, and the\n // return type has never been able to express that. A silent `false` here\n // would have made an unknown domain look like a namespace miss.\n const def = KV_DOMAINS[domain];\n if (utf8ByteLength(value) > def.maxValueBytes) {\n logger.debug(`KV put skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);\n return false;\n }\n try {\n const ttl = clampTtl(options?.ttlSeconds, domain);\n await ns.put(buildKvKey(domain, parts), value, { expirationTtl: ttl });\n return true;\n } catch (error) {\n logger.debug(`KV put failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n public async getJson<T>(domain: KvDomainName, parts: readonly string[]): Promise<T | null> {\n const raw = await this.getText(domain, parts);\n if (raw === null) return null;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n\n public async putJson(domain: KvDomainName, parts: readonly string[], value: unknown, options?: KvPutOptions): Promise<boolean> {\n let raw: unknown;\n try {\n raw = JSON.stringify(value);\n } catch {\n return false;\n }\n return typeof raw === 'string' && this.putText(domain, parts, raw, options);\n }\n\n /**\n * Binary read for the `asset` domain: value bytes plus `{etag, contentType}`\n * KV metadata in a single entry. Legacy base64-JSON entries carry no metadata\n * and read as a miss here — the caller falls back to `getJson` for one TTL\n * window rather than this layer knowing the legacy shape.\n */\n public async getBinary(domain: KvDomainName, parts: readonly string[]): Promise<KvBinaryEntry | null> {\n const ns = this.namespace;\n if (!ns || typeof ns.getWithMetadata !== 'function') return null;\n try {\n const res = await ns.getWithMetadata(buildKvKey(domain, parts), 'arrayBuffer');\n if (!res || res.value == null) return null;\n const value: unknown = res.value;\n let bytes: Uint8Array | null = null;\n if (value instanceof ArrayBuffer) {\n bytes = new Uint8Array(value.slice(0));\n } else if (value instanceof Uint8Array) {\n bytes = value.slice();\n } else if (typeof value === 'string') {\n bytes = new TextEncoder().encode(value);\n }\n if (!bytes) return null;\n const meta = res.metadata as { etag?: unknown; contentType?: unknown } | null | undefined;\n if (typeof meta !== 'object' || meta === null || typeof meta.etag !== 'string' || meta.etag === '') return null;\n return { bytes, metadata: { etag: meta.etag, contentType: typeof meta.contentType === 'string' ? meta.contentType : null } };\n } catch (error) {\n logger.debug(`KV getBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n }\n\n /**\n * Binary write for the `asset` domain. Size is enforced on raw bytes (no\n * base64 inflation) and failures stay fail-soft like `putText`.\n */\n public async putBinary(\n domain: KvDomainName,\n parts: readonly string[],\n bytes: Uint8Array,\n metadata: { etag: string; contentType: string | null },\n options?: KvPutOptions,\n ): Promise<boolean> {\n const ns = this.namespace;\n if (!ns) return false;\n if (!(bytes instanceof Uint8Array)) {\n logger.debug(`KV putBinary skipped for ${domain}: value is not bytes.`);\n return false;\n }\n const def = KV_DOMAINS[domain];\n if (bytes.byteLength > def.maxValueBytes) {\n logger.debug(`KV putBinary skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);\n return false;\n }\n if (typeof metadata?.etag !== 'string' || metadata.etag === '') {\n logger.debug(`KV putBinary skipped for ${domain}: missing etag metadata.`);\n return false;\n }\n try {\n const ttl = clampTtl(options?.ttlSeconds, domain);\n const contentType = typeof metadata.contentType === 'string' ? metadata.contentType : null;\n await ns.put(buildKvKey(domain, parts), bytes.slice().buffer, {\n expirationTtl: ttl,\n metadata: { etag: metadata.etag, contentType },\n });\n return true;\n } catch (error) {\n logger.debug(`KV putBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n public async del(domain: KvDomainName, parts: readonly string[]): Promise<void> {\n const ns = this.namespace;\n if (!ns) return;\n try {\n await ns.delete(buildKvKey(domain, parts));\n } catch (error) {\n logger.debug(`KV delete failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Delete every key under a prefix, page-capped. Restarts from the start after\n * each page: deleting while a positional cursor advances would skip keys.\n */\n public async purgePrefix(domain: KvDomainName, parts: readonly string[] = []): Promise<number> {\n const ns = this.namespace;\n if (!ns) return 0;\n const prefix = parts.length === 0 ? `${domain}:` : buildKvKey(domain, parts);\n let deleted = 0;\n try {\n for (let page = 0; page < PURGE_MAX_PAGES; page += 1) {\n const result = await ns.list({ prefix, limit: PURGE_LIST_LIMIT });\n if (result.keys.length === 0) return deleted;\n for (const key of result.keys) {\n await ns.delete(key.name);\n deleted += 1;\n }\n if (result.keys.length < PURGE_LIST_LIMIT) return deleted;\n }\n // The cap was hit with a full page still coming back, so keys remain and\n // the caller sees a count indistinguishable from a complete purge. A\n // write-invalidation that silently under-purges serves pre-write bytes\n // for a whole TTL while reporting success, so this is never silent.\n logger.warn(\n `KV purge for ${domain} hit the ${PURGE_MAX_PAGES * PURGE_LIST_LIMIT}-key page cap; ` + `at least one key may survive invalidation`,\n );\n return deleted;\n } catch (error) {\n logger.warn(`KV purge for ${domain} failed: ${error instanceof Error ? error.message : String(error)}`);\n return deleted;\n }\n }\n}\n\nexport { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES };\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions };\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kv/KvCache.ts"],
4
+ "sourcesContent": ["import { createLogger } from '../logger.ts';\nimport { KV_DOMAINS, buildKvKey, clampTtl, utf8ByteLength } from './KvDomains.ts';\nimport type { KvDomainName } from './KvDomains.ts';\n\n/**\n * `KvCache` — typed facade over the single `CACHE` KV binding.\n *\n * Converged from `backend-runtime/src/kv/KvCache.ts`, identical in the four\n * repos that cache through KV. Semantics are fail-soft by design: reads return\n * `null` on miss, missing binding, or backend error; writes return `false`\n * when skipped (no binding, oversize value, backend error) and `true` when\n * stored. Callers treat KV as a pure optimization — D1/DO stay authoritative.\n */\n\nconst logger = createLogger('KvCache');\n\ninterface KvListPage {\n keys: Array<{ name: string }>;\n list_complete: boolean;\n cursor?: string;\n}\n\ninterface KvGetWithMetadataResult {\n value: string | ArrayBuffer | null;\n metadata: unknown;\n}\n\ninterface KvNamespaceLike {\n get(key: string): Promise<string | null>;\n get(key: string, type: 'text'): Promise<string | null>;\n get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;\n getWithMetadata?(key: string, type: 'arrayBuffer'): Promise<KvGetWithMetadataResult>;\n put(key: string, value: string | ArrayBuffer, options?: { expirationTtl?: number; metadata?: unknown }): Promise<void>;\n delete(key: string): Promise<unknown>;\n list(options: { prefix: string; limit?: number; cursor?: string }): Promise<KvListPage>;\n}\n\ninterface KvPutOptions {\n ttlSeconds?: number;\n}\n\ninterface KvFileMetadata {\n etag: string;\n contentType: string | null;\n}\n\ninterface KvBinaryEntry {\n bytes: Uint8Array;\n metadata: KvFileMetadata;\n}\n\nconst PURGE_LIST_LIMIT = 1000;\nconst PURGE_MAX_PAGES = 10;\n\nclass KvCache {\n public constructor(private readonly namespace?: KvNamespaceLike | null) {}\n\n public get available(): boolean {\n return !!this.namespace;\n }\n\n public async getText(domain: KvDomainName, parts: readonly string[]): Promise<string | null> {\n const ns = this.namespace;\n if (!ns) return null;\n try {\n return await ns.get(buildKvKey(domain, parts));\n } catch (error) {\n logger.debug(`KV get failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n }\n\n public async putText(domain: KvDomainName, parts: readonly string[], value: string, options?: KvPutOptions): Promise<boolean> {\n const ns = this.namespace;\n if (!ns) return false;\n // No unknown-domain check: `buildKvKey` below throws for one, and the\n // return type has never been able to express that. A silent `false` here\n // would have made an unknown domain look like a namespace miss.\n const def = KV_DOMAINS[domain];\n if (utf8ByteLength(value) > def.maxValueBytes) {\n logger.debug(`KV put skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);\n return false;\n }\n try {\n const ttl = clampTtl(options?.ttlSeconds, domain);\n await ns.put(buildKvKey(domain, parts), value, { expirationTtl: ttl });\n return true;\n } catch (error) {\n logger.debug(`KV put failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n public async getJson<T>(domain: KvDomainName, parts: readonly string[]): Promise<T | null> {\n const raw = await this.getText(domain, parts);\n if (raw === null) return null;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n\n public async putJson(domain: KvDomainName, parts: readonly string[], value: unknown, options?: KvPutOptions): Promise<boolean> {\n let raw: unknown;\n try {\n raw = JSON.stringify(value);\n } catch {\n return false;\n }\n return typeof raw === 'string' && this.putText(domain, parts, raw, options);\n }\n\n /**\n * Binary read for the `asset` domain: value bytes plus `{etag, contentType}`\n * KV metadata in a single entry. Legacy base64-JSON entries carry no metadata\n * and read as a miss here — the caller falls back to `getJson` for one TTL\n * window rather than this layer knowing the legacy shape.\n */\n public async getBinary(domain: KvDomainName, parts: readonly string[]): Promise<KvBinaryEntry | null> {\n const ns = this.namespace;\n if (!ns || typeof ns.getWithMetadata !== 'function') return null;\n try {\n const res = await ns.getWithMetadata(buildKvKey(domain, parts), 'arrayBuffer');\n if (!res || res.value == null) return null;\n const value: unknown = res.value;\n let bytes: Uint8Array | null = null;\n if (value instanceof ArrayBuffer) {\n bytes = new Uint8Array(value.slice(0));\n } else if (value instanceof Uint8Array) {\n bytes = value.slice();\n } else if (typeof value === 'string') {\n bytes = new TextEncoder().encode(value);\n }\n if (!bytes) return null;\n const meta = res.metadata as { etag?: unknown; contentType?: unknown } | null | undefined;\n if (typeof meta !== 'object' || meta === null || typeof meta.etag !== 'string' || meta.etag === '') return null;\n return { bytes, metadata: { etag: meta.etag, contentType: typeof meta.contentType === 'string' ? meta.contentType : null } };\n } catch (error) {\n logger.debug(`KV getBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n }\n\n /**\n * Binary write for the `asset` domain. Size is enforced on raw bytes (no\n * base64 inflation) and failures stay fail-soft like `putText`.\n */\n public async putBinary(\n domain: KvDomainName,\n parts: readonly string[],\n bytes: Uint8Array,\n metadata: { etag: string; contentType: string | null },\n options?: KvPutOptions,\n ): Promise<boolean> {\n const ns = this.namespace;\n if (!ns) return false;\n if (!(bytes instanceof Uint8Array)) {\n logger.debug(`KV putBinary skipped for ${domain}: value is not bytes.`);\n return false;\n }\n const def = KV_DOMAINS[domain];\n if (bytes.byteLength > def.maxValueBytes) {\n logger.debug(`KV putBinary skipped for ${domain}: value exceeds ${def.maxValueBytes} bytes.`);\n return false;\n }\n if (typeof metadata?.etag !== 'string' || metadata.etag === '') {\n logger.debug(`KV putBinary skipped for ${domain}: missing etag metadata.`);\n return false;\n }\n try {\n const ttl = clampTtl(options?.ttlSeconds, domain);\n const contentType = typeof metadata.contentType === 'string' ? metadata.contentType : null;\n await ns.put(buildKvKey(domain, parts), bytes.slice().buffer, {\n expirationTtl: ttl,\n metadata: { etag: metadata.etag, contentType },\n });\n return true;\n } catch (error) {\n logger.debug(`KV putBinary failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n public async del(domain: KvDomainName, parts: readonly string[]): Promise<void> {\n const ns = this.namespace;\n if (!ns) return;\n try {\n await ns.delete(buildKvKey(domain, parts));\n } catch (error) {\n logger.debug(`KV delete failed for ${domain}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Delete every key under a prefix, page-capped. Restarts from the start after\n * each page: deleting while a positional cursor advances would skip keys.\n */\n public async purgePrefix(domain: KvDomainName, parts: readonly string[] = []): Promise<number> {\n const ns = this.namespace;\n if (!ns) return 0;\n const prefix = parts.length === 0 ? `${domain}:` : buildKvKey(domain, parts);\n let deleted = 0;\n try {\n for (let page = 0; page < PURGE_MAX_PAGES; page += 1) {\n const result = await ns.list({ prefix, limit: PURGE_LIST_LIMIT });\n if (result.keys.length === 0) return deleted;\n for (const key of result.keys) {\n await ns.delete(key.name);\n deleted += 1;\n }\n if (result.keys.length < PURGE_LIST_LIMIT) return deleted;\n }\n // The cap was hit with a full page still coming back, so keys remain and\n // the caller sees a count indistinguishable from a complete purge. A\n // write-invalidation that silently under-purges serves pre-write bytes\n // for a whole TTL while reporting success, so this is never silent.\n logger.warn(\n `KV purge for ${domain} hit the ${PURGE_MAX_PAGES * PURGE_LIST_LIMIT}-key page cap; at least one key may survive invalidation`,\n );\n return deleted;\n } catch (error) {\n logger.warn(`KV purge for ${domain} failed: ${error instanceof Error ? error.message : String(error)}`);\n return deleted;\n }\n }\n}\n\nexport { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES };\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions };\n"],
5
+ "mappings": "AAAA,OAAS,gBAAAA,MAAoB,eAC7B,OAAS,cAAAC,EAAY,cAAAC,EAAY,YAAAC,EAAU,kBAAAC,MAAsB,iBAajE,MAAMC,EAASL,EAAa,SAAS,EAqC/BM,EAAmB,IACnBC,EAAkB,GAExB,MAAMC,CAAO,CACyB,UAApC,YAAoCC,EAAkC,CAAlC,KAAA,UAAAA,CAAqC,CAEzE,IAAW,WAAS,CAClB,MAAO,CAAC,CAAC,KAAK,SAChB,CAEO,MAAM,QAAQC,EAAsBC,EAAwB,CACjE,MAAMC,EAAK,KAAK,UAChB,GAAI,CAACA,EAAI,OAAO,KAChB,GAAI,CACF,OAAO,MAAMA,EAAG,IAAIV,EAAWQ,EAAQC,CAAK,CAAC,CAC/C,OAASE,EAAO,CACd,OAAAR,EAAO,MAAM,qBAAqBK,CAAM,KAAKG,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,EAC9F,IACT,CACF,CAEO,MAAM,QAAQH,EAAsBC,EAA0BG,EAAeC,EAAsB,CACxG,MAAMH,EAAK,KAAK,UAChB,GAAI,CAACA,EAAI,MAAO,GAIhB,MAAMI,EAAMf,EAAWS,CAAM,EAC7B,GAAIN,EAAeU,CAAK,EAAIE,EAAI,cAC9B,OAAAX,EAAO,MAAM,sBAAsBK,CAAM,mBAAmBM,EAAI,aAAa,SAAS,EAC/E,GAET,GAAI,CACF,M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AKA,EACL,GAAI,CACF,MAAMA,EAAG,OAAOV,EAAWQ,EAAQC,CAAK,CAAC,CAC3C,OAASE,EAAO,CACdR,EAAO,MAAM,wBAAwBK,CAAM,KAAKG,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAC1G,CACF,CAMO,MAAM,YAAYH,EAAsBC,EAA2B,CAAA,EAAE,CAC1E,MAAMC,EAAK,KAAK,UAChB,GAAI,CAACA,EAAI,MAAO,GAChB,MAAMY,EAASb,EAAM,SAAW,EAAI,GAAGD,CAAM,IAAMR,EAAWQ,EAAQC,CAAK,EAC3E,IAAIc,EAAU,EACd,GAAI,CACF,QAASC,EAAO,EAAGA,EAAOnB,EAAiBmB,GAAQ,EAAG,CACpD,MAAMC,EAAS,MAAMf,EAAG,KAAK,CAAE,OAAAY,EAAQ,MAAOlB,CAAgB,CAAE,EAChE,GAAIqB,EAAO,KAAK,SAAW,EAAG,OAAOF,EACrC,UAAWG,KAAOD,EAAO,KACvB,MAAMf,EAAG,OAAOgB,EAAI,IAAI,EACxBH,GAAW,EAEb,GAAIE,EAAO,KAAK,OAASrB,EAAkB,OAAOmB,CACpD,CAKA,OAAApB,EAAO,KACL,gBAAgBK,CAAM,YAAYH,EAAkBD,CAAgB,0DAA0D,EAEzHmB,CACT,OAASZ,EAAO,CACd,OAAAR,EAAO,KAAK,gBAAgBK,CAAM,YAAYG,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,EAC/FY,CACT,CACF",
6
+ "names": ["createLogger", "KV_DOMAINS", "buildKvKey", "clampTtl", "utf8ByteLength", "logger", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "KvCache", "namespace", "domain", "parts", "ns", "error", "value", "options", "def", "ttl", "raw", "res", "bytes", "meta", "metadata", "contentType", "prefix", "deleted", "page", "result", "key"]
7
+ }
@@ -1,101 +1 @@
1
- /**
2
- * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.
3
- *
4
- * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,
5
- * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets
6
- * of names). The domains are generalized to the three the whole family shares;
7
- * a consumer with a different cache vocabulary renames its call sites (clients
8
- * adapt) rather than extending the registry, because an open registry is how
9
- * prefix collisions start.
10
- *
11
- * Rationale: D1 and the Durable Object stay the source of truth. KV is a
12
- * loss-tolerant, read-heavy cache only — a miss or eviction must always be
13
- * recoverable by recompute. Call sites never touch `env.CACHE` directly; they
14
- * go through `KvCache` with a closed `KvDomainName` registry so prefixes cannot
15
- * collide and TTL/size policy lives in one table.
16
- */
17
- const KV_KEY_VERSION = 'v1';
18
- const KV_MAX_KEY_LENGTH = 512;
19
- const KV_MIN_TTL_SECONDS = 60;
20
- const KV_DOMAINS = {
21
- session: {
22
- ttlSeconds: 300,
23
- maxValueBytes: 65_536,
24
- description: 'Per-user session/profile snapshots; invalidated on any credential change.',
25
- },
26
- asset: {
27
- ttlSeconds: 300,
28
- maxValueBytes: 10_485_760,
29
- description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',
30
- },
31
- metadata: {
32
- ttlSeconds: 120,
33
- maxValueBytes: 1_048_576,
34
- description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',
35
- },
36
- };
37
- /**
38
- * 128-bit digest built from four independent FNV-1a lanes.
39
- *
40
- * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key
41
- * exceeds the platform's 512-character limit, and the longest keys embed a
42
- * user-controlled path or name. A 32-bit digest over a shared keyspace is
43
- * collision-searchable — someone who controls names in their own scope could
44
- * grind a colliding key and read another tenant's cached bytes. Four lanes over
45
- * the same bytes with different offsets/primes cost one extra pass and take a
46
- * birthday collision to ~2^64 work, which is not worth attacking.
47
- *
48
- * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.
49
- */
50
- function digest128(input) {
51
- const LANES = 4;
52
- const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];
53
- let out = '';
54
- for (let lane = 0; lane < LANES; lane += 1) {
55
- let hash = offsets[lane];
56
- const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;
57
- for (let i = 0; i < input.length; i += 1) {
58
- hash ^= input.codePointAt(i) ?? 0;
59
- hash = Math.imul(hash, prime);
60
- }
61
- out += (hash >>> 0).toString(16).padStart(8, '0');
62
- }
63
- return out;
64
- }
65
- function sanitizeSegment(segment) {
66
- const trimmed = segment.trim();
67
- if (!trimmed)
68
- throw new Error('KV key segment must not be empty.');
69
- return encodeURIComponent(trimmed);
70
- }
71
- function buildKvKey(domain, parts) {
72
- const def = KV_DOMAINS[domain];
73
- if (!def)
74
- throw new Error(`Unknown KV domain: ${domain}.`);
75
- if (parts.length === 0)
76
- throw new Error(`KV domain ${domain} requires at least one key part.`);
77
- const prefix = `${domain}:${KV_KEY_VERSION}:`;
78
- const joined = parts.map((part) => sanitizeSegment(part)).join(':');
79
- const full = prefix + joined;
80
- if (full.length <= KV_MAX_KEY_LENGTH)
81
- return full;
82
- // Deterministic overflow form. Note the consequence for invalidation: an
83
- // overflowing key does not start with the plain prefix, so `purgePrefix` on
84
- // the parts will not match it. Callers must therefore bound the key material
85
- // they cache (path length, identifier length) — the digest is a crash guard,
86
- // not a caching strategy.
87
- return `${prefix}h:${digest128(joined)}`;
88
- }
89
- function utf8ByteLength(value) {
90
- return new TextEncoder().encode(value).length;
91
- }
92
- /**
93
- * Resolve a TTL, defaulting to the domain's own. Every domain declares a
94
- * required `ttlSeconds`, so there is no "no TTL" case to represent.
95
- */
96
- function clampTtl(ttlSeconds, domain) {
97
- const effective = ttlSeconds ?? KV_DOMAINS[domain].ttlSeconds;
98
- return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : KV_DOMAINS[domain].ttlSeconds;
99
- }
100
- export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };
101
- //# sourceMappingURL=KvDomains.js.map
1
+ const S="v1",d=512,f=60,r={session:{ttlSeconds:300,maxValueBytes:65536,description:"Per-user session/profile snapshots; invalidated on any credential change."},asset:{ttlSeconds:300,maxValueBytes:10485760,description:"Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write."},metadata:{ttlSeconds:120,maxValueBytes:1048576,description:"Listing/derived snapshots keyed by owner or collection; invalidated on mutation."}};function _(e){const s=[2166136261,3266489909,668265263,374761393];let i="";for(let n=0;n<4;n+=1){let o=s[n];const a=16777619+n*2654435769;for(let c=0;c<e.length;c+=1)o^=e.codePointAt(c)??0,o=Math.imul(o,a);i+=(o>>>0).toString(16).padStart(8,"0")}return i}function l(e){const t=e.trim();if(!t)throw new Error("KV key segment must not be empty.");return encodeURIComponent(t)}function u(e,t){if(!r[e])throw new Error(`Unknown KV domain: ${e}.`);if(t.length===0)throw new Error(`KV domain ${e} requires at least one key part.`);const i=`${e}:v1:`,n=t.map(a=>l(a)).join(":"),o=i+n;return o.length<=512?o:`${i}h:${_(n)}`}function h(e){return new TextEncoder().encode(e).length}function m(e,t){const s=e??r[t].ttlSeconds;return Number.isFinite(s)?Math.max(60,Math.floor(s)):r[t].ttlSeconds}export{r as KV_DOMAINS,d as KV_MAX_KEY_LENGTH,f as KV_MIN_TTL_SECONDS,u as buildKvKey,m as clampTtl,_ as digest128,l as sanitizeSegment,h as utf8ByteLength};
@@ -1 +1,7 @@
1
- {"version":3,"file":"KvDomains.js","sourceRoot":"","sources":["../../src/kv/KvDomains.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAU9B,MAAM,UAAU,GAAsC;IACpD,OAAO,EAAE;QACP,UAAU,EAAE,GAAG;QACf,aAAa,EAAE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,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC;AAC1H,CAAC;AAED,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC","sourcesContent":["/**\n * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.\n *\n * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets\n * of names). The domains are generalized to the three the whole family shares;\n * a consumer with a different cache vocabulary renames its call sites (clients\n * adapt) rather than extending the registry, because an open registry is how\n * prefix collisions start.\n *\n * Rationale: D1 and the Durable Object stay the source of truth. KV is a\n * loss-tolerant, read-heavy cache only — a miss or eviction must always be\n * recoverable by recompute. Call sites never touch `env.CACHE` directly; they\n * go through `KvCache` with a closed `KvDomainName` registry so prefixes cannot\n * collide and TTL/size policy lives in one table.\n */\nconst KV_KEY_VERSION = 'v1';\nconst KV_MAX_KEY_LENGTH = 512;\nconst KV_MIN_TTL_SECONDS = 60;\n\ntype KvDomainName = 'session' | 'asset' | 'metadata';\n\ninterface KvDomainDef {\n ttlSeconds: number;\n maxValueBytes: number;\n description: string;\n}\n\nconst KV_DOMAINS: Record<KvDomainName, KvDomainDef> = {\n session: {\n ttlSeconds: 300,\n maxValueBytes: 65_536,\n description: 'Per-user session/profile snapshots; invalidated on any credential change.',\n },\n asset: {\n ttlSeconds: 300,\n maxValueBytes: 10_485_760,\n description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',\n },\n metadata: {\n ttlSeconds: 120,\n maxValueBytes: 1_048_576,\n description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',\n },\n};\n\n/**\n * 128-bit digest built from four independent FNV-1a lanes.\n *\n * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key\n * exceeds the platform's 512-character limit, and the longest keys embed a\n * user-controlled path or name. A 32-bit digest over a shared keyspace is\n * collision-searchable — someone who controls names in their own scope could\n * grind a colliding key and read another tenant's cached bytes. Four lanes over\n * the same bytes with different offsets/primes cost one extra pass and take a\n * birthday collision to ~2^64 work, which is not worth attacking.\n *\n * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.\n */\nfunction digest128(input: string): string {\n const LANES = 4;\n const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];\n let out = '';\n for (let lane = 0; lane < LANES; lane += 1) {\n let hash = offsets[lane] as number;\n const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.codePointAt(i) ?? 0;\n hash = Math.imul(hash, prime);\n }\n out += (hash >>> 0).toString(16).padStart(8, '0');\n }\n return out;\n}\n\nfunction sanitizeSegment(segment: string): string {\n const trimmed = segment.trim();\n if (!trimmed) throw new Error('KV key segment must not be empty.');\n return encodeURIComponent(trimmed);\n}\n\nfunction buildKvKey(domain: KvDomainName, parts: readonly string[]): string {\n const def = KV_DOMAINS[domain];\n if (!def) throw new Error(`Unknown KV domain: ${domain}.`);\n if (parts.length === 0) throw new Error(`KV domain ${domain} requires at least one key part.`);\n const prefix = `${domain}:${KV_KEY_VERSION}:`;\n const joined = parts.map((part) => sanitizeSegment(part)).join(':');\n const full = prefix + joined;\n if (full.length <= KV_MAX_KEY_LENGTH) return full;\n // Deterministic overflow form. Note the consequence for invalidation: an\n // overflowing key does not start with the plain prefix, so `purgePrefix` on\n // the parts will not match it. Callers must therefore bound the key material\n // they cache (path length, identifier length) — the digest is a crash guard,\n // not a caching strategy.\n return `${prefix}h:${digest128(joined)}`;\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Resolve a TTL, defaulting to the domain's own. Every domain declares a\n * required `ttlSeconds`, so there is no \"no TTL\" case to represent.\n */\nfunction clampTtl(ttlSeconds: number | undefined, domain: KvDomainName): number {\n const effective = ttlSeconds ?? KV_DOMAINS[domain].ttlSeconds;\n return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : KV_DOMAINS[domain].ttlSeconds;\n}\n\nexport { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };\nexport type { KvDomainDef, KvDomainName };\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kv/KvDomains.ts"],
4
+ "sourcesContent": ["/**\n * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.\n *\n * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets\n * of names). The domains are generalized to the three the whole family shares;\n * a consumer with a different cache vocabulary renames its call sites (clients\n * adapt) rather than extending the registry, because an open registry is how\n * prefix collisions start.\n *\n * Rationale: D1 and the Durable Object stay the source of truth. KV is a\n * loss-tolerant, read-heavy cache only — a miss or eviction must always be\n * recoverable by recompute. Call sites never touch `env.CACHE` directly; they\n * go through `KvCache` with a closed `KvDomainName` registry so prefixes cannot\n * collide and TTL/size policy lives in one table.\n */\nconst KV_KEY_VERSION = 'v1';\nconst KV_MAX_KEY_LENGTH = 512;\nconst KV_MIN_TTL_SECONDS = 60;\n\ntype KvDomainName = 'session' | 'asset' | 'metadata';\n\ninterface KvDomainDef {\n ttlSeconds: number;\n maxValueBytes: number;\n description: string;\n}\n\nconst KV_DOMAINS: Record<KvDomainName, KvDomainDef> = {\n session: {\n ttlSeconds: 300,\n maxValueBytes: 65_536,\n description: 'Per-user session/profile snapshots; invalidated on any credential change.',\n },\n asset: {\n ttlSeconds: 300,\n maxValueBytes: 10_485_760,\n description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',\n },\n metadata: {\n ttlSeconds: 120,\n maxValueBytes: 1_048_576,\n description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',\n },\n};\n\n/**\n * 128-bit digest built from four independent FNV-1a lanes.\n *\n * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key\n * exceeds the platform's 512-character limit, and the longest keys embed a\n * user-controlled path or name. A 32-bit digest over a shared keyspace is\n * collision-searchable — someone who controls names in their own scope could\n * grind a colliding key and read another tenant's cached bytes. Four lanes over\n * the same bytes with different offsets/primes cost one extra pass and take a\n * birthday collision to ~2^64 work, which is not worth attacking.\n *\n * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.\n */\nfunction digest128(input: string): string {\n const LANES = 4;\n const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];\n let out = '';\n for (let lane = 0; lane < LANES; lane += 1) {\n let hash = offsets[lane];\n const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.codePointAt(i) ?? 0;\n hash = Math.imul(hash, prime);\n }\n out += (hash >>> 0).toString(16).padStart(8, '0');\n }\n return out;\n}\n\nfunction sanitizeSegment(segment: string): string {\n const trimmed = segment.trim();\n if (!trimmed) throw new Error('KV key segment must not be empty.');\n return encodeURIComponent(trimmed);\n}\n\nfunction buildKvKey(domain: KvDomainName, parts: readonly string[]): string {\n const def = KV_DOMAINS[domain];\n if (!def) throw new Error(`Unknown KV domain: ${domain}.`);\n if (parts.length === 0) throw new Error(`KV domain ${domain} requires at least one key part.`);\n const prefix = `${domain}:${KV_KEY_VERSION}:`;\n const joined = parts.map((part) => sanitizeSegment(part)).join(':');\n const full = prefix + joined;\n if (full.length <= KV_MAX_KEY_LENGTH) return full;\n // Deterministic overflow form. Note the consequence for invalidation: an\n // overflowing key does not start with the plain prefix, so `purgePrefix` on\n // the parts will not match it. Callers must therefore bound the key material\n // they cache (path length, identifier length) — the digest is a crash guard,\n // not a caching strategy.\n return `${prefix}h:${digest128(joined)}`;\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Resolve a TTL, defaulting to the domain's own. Every domain declares a\n * required `ttlSeconds`, so there is no \"no TTL\" case to represent.\n */\nfunction clampTtl(ttlSeconds: number | undefined, domain: KvDomainName): number {\n const effective = ttlSeconds ?? KV_DOMAINS[domain].ttlSeconds;\n return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : KV_DOMAINS[domain].ttlSeconds;\n}\n\nexport { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };\nexport type { KvDomainDef, KvDomainName };\n"],
5
+ "mappings": "AAgBA,MAAMA,EAAiB,KACjBC,EAAoB,IACpBC,EAAqB,GAUrBC,EAAgD,CACpD,QAAS,CACP,WAAY,IACZ,cAAe,MACf,YAAa,6EAEf,MAAO,CACL,WAAY,IACZ,cAAe,SACf,YAAa,uGAEf,SAAU,CACR,WAAY,IACZ,cAAe,QACf,YAAa,qFAiBjB,SAASC,EAAUC,EAAa,CAE9B,MAAMC,EAAU,CAAC,WAAe,WAAe,UAAe,SAAa,EAC3E,IAAIC,EAAM,GACV,QAASC,EAAO,EAAGA,EAAO,EAAOA,GAAQ,EAAG,CAC1C,IAAIC,EAAOH,EAAQE,CAAI,EACvB,MAAME,EAAQ,SAAgBF,EAAO,WACrC,QAASG,EAAI,EAAGA,EAAIN,EAAM,OAAQM,GAAK,EACrCF,GAAQJ,EAAM,YAAYM,CAAC,GAAK,EAChCF,EAAO,KAAK,KAAKA,EAAMC,CAAK,EAE9BH,IAAQE,IAAS,GAAG,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAClD,CACA,OAAOF,CACT,CAEA,SAASK,EAAgBC,EAAe,CACtC,MAAMC,EAAUD,EAAQ,KAAI,EAC5B,GAAI,CAACC,EAAS,MAAM,IAAI,MAAM,mCAAmC,EACjE,OAAO,mBAAmBA,CAAO,CACnC,CAEA,SAASC,EAAWC,EAAsBC,EAAwB,CAEhE,GAAI,CADQd,EAAWa,CAAM,EACnB,MAAM,IAAI,MAAM,sBAAsBA,CAAM,GAAG,EACzD,GAAIC,EAAM,SAAW,EAAG,MAAM,IAAI,MAAM,aAAaD,CAAM,kCAAkC,EAC7F,MAAME,EAAS,GAAGF,CAAM,OAClBG,EAASF,EAAM,IAAKG,GAASR,EAAgBQ,CAAI,CAAC,EAAE,KAAK,GAAG,EAC5DC,EAAOH,EAASC,EACtB,OAAIE,EAAK,QAAU,IAA0BA,EAMtC,GAAGH,CAAM,KAAKd,EAAUe,CAAM,CAAC,EACxC,CAEA,SAASG,EAAeC,EAAa,CACnC,OAAO,IAAI,YAAW,EAAG,OAAOA,CAAK,EAAE,MACzC,CAMA,SAASC,EAASC,EAAgCT,EAAoB,CACpE,MAAMU,EAAYD,GAActB,EAAWa,CAAM,EAAE,WACnD,OAAO,OAAO,SAASU,CAAS,EAAI,KAAK,IAAI,GAAoB,KAAK,MAAMA,CAAS,CAAC,EAAIvB,EAAWa,CAAM,EAAE,UAC/G",
6
+ "names": ["KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KV_DOMAINS", "digest128", "input", "offsets", "out", "lane", "hash", "prime", "i", "sanitizeSegment", "segment", "trimmed", "buildKvKey", "domain", "parts", "prefix", "joined", "part", "full", "utf8ByteLength", "value", "clampTtl", "ttlSeconds", "effective"]
7
+ }
package/dist/kv/index.js CHANGED
@@ -1,3 +1 @@
1
- export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from "./KvCache.js";
2
- export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, } from "./KvDomains.js";
3
- //# sourceMappingURL=index.js.map
1
+ import{KvCache as t,PURGE_LIST_LIMIT as K,PURGE_MAX_PAGES as E}from"./KvCache.js";import{KV_DOMAINS as T,KV_MAX_KEY_LENGTH as I,KV_MIN_TTL_SECONDS as L,buildKvKey as M,clampTtl as i,digest128 as m,sanitizeSegment as o,utf8ByteLength as r}from"./KvDomains.js";export{T as KV_DOMAINS,I as KV_MAX_KEY_LENGTH,L as KV_MIN_TTL_SECONDS,t as KvCache,K as PURGE_LIST_LIMIT,E as PURGE_MAX_PAGES,M as buildKvKey,i as clampTtl,m as digest128,o as sanitizeSegment,r as utf8ByteLength};
@@ -1 +1,7 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/kv/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE1E,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,MAAM,gBAAgB,CAAC","sourcesContent":["export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache.ts';\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';\nexport {\n KV_DOMAINS,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n buildKvKey,\n clampTtl,\n digest128,\n sanitizeSegment,\n utf8ByteLength,\n} from './KvDomains.ts';\nexport type { KvDomainDef, KvDomainName } from './KvDomains.ts';\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kv/index.ts"],
4
+ "sourcesContent": ["export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache.ts';\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';\nexport {\n KV_DOMAINS,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n buildKvKey,\n clampTtl,\n digest128,\n sanitizeSegment,\n utf8ByteLength,\n} from './KvDomains.ts';\nexport type { KvDomainDef, KvDomainName } from './KvDomains.ts';\n"],
5
+ "mappings": "AAAA,OAAS,WAAAA,EAAS,oBAAAC,EAAkB,mBAAAC,MAAuB,eAE3D,OACE,cAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK",
6
+ "names": ["KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "KV_DOMAINS", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "buildKvKey", "clampTtl", "digest128", "sanitizeSegment", "utf8ByteLength"]
7
+ }
package/dist/logger.js CHANGED
@@ -1,47 +1 @@
1
- const LOG_LEVELS = {
2
- debug: 0,
3
- info: 1,
4
- warn: 2,
5
- error: 3,
6
- };
7
- function isLogLevel(level) {
8
- return ['debug', 'info', 'warn', 'error'].includes(level);
9
- }
10
- function resolveLogLevel(env) {
11
- const fromInjected = env !== null && typeof env === 'object' ? env['LOG_LEVEL'] : undefined;
12
- const fromEnv = globalThis.process?.env?.LOG_LEVEL;
13
- const level = fromInjected ?? fromEnv ?? 'info';
14
- return isLogLevel(level) ? level : 'info';
15
- }
16
- function createLogger(namespace, fullRepoName, env) {
17
- const currentLevel = resolveLogLevel(env);
18
- const minLevel = LOG_LEVELS[currentLevel];
19
- const argsStr = [fullRepoName, namespace]
20
- .filter(Boolean)
21
- .map((s) => `[${s}]`)
22
- .join(' ');
23
- return {
24
- debug: (...args) => {
25
- if (LOG_LEVELS.debug >= minLevel) {
26
- console.debug(`[DEBUG] ${argsStr}`, ...args);
27
- }
28
- },
29
- info: (...args) => {
30
- if (LOG_LEVELS.info >= minLevel) {
31
- console.info(`[INFO] ${argsStr}`, ...args);
32
- }
33
- },
34
- warn: (...args) => {
35
- if (LOG_LEVELS.warn >= minLevel) {
36
- console.warn(`[WARN] ${argsStr}`, ...args);
37
- }
38
- },
39
- error: (...args) => {
40
- if (LOG_LEVELS.error >= minLevel) {
41
- console.error(`[ERROR] ${argsStr}`, ...args);
42
- }
43
- },
44
- };
45
- }
46
- export { createLogger, isLogLevel, resolveLogLevel };
47
- //# sourceMappingURL=logger.js.map
1
+ const n={debug:0,info:1,warn:2,error:3};function l(e){return["debug","info","warn","error"].includes(e)}function s(e){const c=e!==null&&typeof e=="object"?e.LOG_LEVEL:void 0,f=globalThis.process?.env?.LOG_LEVEL,r=c??f??"info";return l(r)?r:"info"}function L(e,c,f){const r=s(f),i=n[r],t=[c,e].filter(Boolean).map(o=>`[${o}]`).join(" ");return{debug:(...o)=>{n.debug>=i&&console.debug(`[DEBUG] ${t}`,...o)},info:(...o)=>{n.info>=i&&console.info(`[INFO] ${t}`,...o)},warn:(...o)=>{n.warn>=i&&console.warn(`[WARN] ${t}`,...o)},error:(...o)=>{n.error>=i&&console.error(`[ERROR] ${t}`,...o)}}}export{L as createLogger,l as isLogLevel,s as resolveLogLevel};
@@ -1 +1,7 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAeA,MAAM,UAAU,GAA6B;IAC3C,KAAK,EAAE,CAAC;IACR,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;CACA,CAAC;AAEX,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAW,CAAC,QAAQ,CAAC,KAAiB,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,eAAe,CAAC,GAAa;IACpC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,GAA0C,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpI,MAAM,OAAO,GAAI,UAAyE,CAAC,OAAO,EAAE,GAAG,EAAE,SAAS,CAAC;IACnH,MAAM,KAAK,GAAG,YAAY,IAAI,OAAO,IAAI,MAA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,CAAC,WAAW,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;YAC/C,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,CAAC","sourcesContent":["/**\n * `KvLogger` — the family's console logger with a level floor.\n *\n * Converged from `backend-runtime/src/logger.ts`, which is identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Sonic, Mail-Otter and Mail-Meow (the\n * copies in AWS/ChordDHT's `shared` are the same shape without the env floor).\n *\n * The level resolves from an injected `env` first, then `process.env`, then\n * `info`: Workers have no `process.env` at runtime, so an injected object is\n * the configuration path, and `process.env` is a local-tooling affordance. An\n * unrecognized level floors at `info` rather than throwing — a typo in\n * `LOG_LEVEL` costing a worker a cold start is not a trade worth making.\n */\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n} as const;\n\nfunction isLogLevel(level: string): level is LogLevel {\n return (['debug', 'info', 'warn', 'error'] as const).includes(level as LogLevel);\n}\n\nfunction resolveLogLevel(env?: unknown): LogLevel {\n const fromInjected = env !== null && typeof env === 'object' ? (env as Record<string, string | undefined>)['LOG_LEVEL'] : undefined;\n const fromEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.LOG_LEVEL;\n const level = fromInjected ?? fromEnv ?? 'info';\n return isLogLevel(level) ? level : 'info';\n}\n\ninterface Logger {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\nfunction createLogger(namespace?: string, fullRepoName?: string, env?: unknown): Logger {\n const currentLevel = resolveLogLevel(env);\n const minLevel = LOG_LEVELS[currentLevel];\n\n const argsStr = [fullRepoName, namespace]\n .filter(Boolean)\n .map((s) => `[${s}]`)\n .join(' ');\n\n return {\n debug: (...args: unknown[]): void => {\n if (LOG_LEVELS.debug >= minLevel) {\n console.debug(`[DEBUG] ${argsStr}`, ...args);\n }\n },\n info: (...args: unknown[]): void => {\n if (LOG_LEVELS.info >= minLevel) {\n console.info(`[INFO] ${argsStr}`, ...args);\n }\n },\n warn: (...args: unknown[]): void => {\n if (LOG_LEVELS.warn >= minLevel) {\n console.warn(`[WARN] ${argsStr}`, ...args);\n }\n },\n error: (...args: unknown[]): void => {\n if (LOG_LEVELS.error >= minLevel) {\n console.error(`[ERROR] ${argsStr}`, ...args);\n }\n },\n };\n}\n\nexport { createLogger, isLogLevel, resolveLogLevel };\nexport type { LogLevel, Logger };\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/logger.ts"],
4
+ "sourcesContent": ["/**\n * `KvLogger` — the family's console logger with a level floor.\n *\n * Converged from `backend-runtime/src/logger.ts`, which is identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Sonic, Mail-Otter and Mail-Meow (the\n * copies in AWS/ChordDHT's `shared` are the same shape without the env floor).\n *\n * The level resolves from an injected `env` first, then `process.env`, then\n * `info`: Workers have no `process.env` at runtime, so an injected object is\n * the configuration path, and `process.env` is a local-tooling affordance. An\n * unrecognized level floors at `info` rather than throwing — a typo in\n * `LOG_LEVEL` costing a worker a cold start is not a trade worth making.\n */\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n} as const;\n\nfunction isLogLevel(level: string): level is LogLevel {\n return (['debug', 'info', 'warn', 'error'] as const).includes(level as LogLevel);\n}\n\nfunction resolveLogLevel(env?: unknown): LogLevel {\n const fromInjected = env !== null && typeof env === 'object' ? (env as Record<string, string | undefined>)['LOG_LEVEL'] : undefined;\n const fromEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.LOG_LEVEL;\n const level = fromInjected ?? fromEnv ?? 'info';\n return isLogLevel(level) ? level : 'info';\n}\n\ninterface Logger {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\nfunction createLogger(namespace?: string, fullRepoName?: string, env?: unknown): Logger {\n const currentLevel = resolveLogLevel(env);\n const minLevel = LOG_LEVELS[currentLevel];\n\n const argsStr = [fullRepoName, namespace]\n .filter(Boolean)\n .map((s) => `[${s}]`)\n .join(' ');\n\n return {\n debug: (...args: unknown[]): void => {\n if (LOG_LEVELS.debug >= minLevel) {\n console.debug(`[DEBUG] ${argsStr}`, ...args);\n }\n },\n info: (...args: unknown[]): void => {\n if (LOG_LEVELS.info >= minLevel) {\n console.info(`[INFO] ${argsStr}`, ...args);\n }\n },\n warn: (...args: unknown[]): void => {\n if (LOG_LEVELS.warn >= minLevel) {\n console.warn(`[WARN] ${argsStr}`, ...args);\n }\n },\n error: (...args: unknown[]): void => {\n if (LOG_LEVELS.error >= minLevel) {\n console.error(`[ERROR] ${argsStr}`, ...args);\n }\n },\n };\n}\n\nexport { createLogger, isLogLevel, resolveLogLevel };\nexport type { LogLevel, Logger };\n"],
5
+ "mappings": "AAeA,MAAMA,EAAuC,CAC3C,MAAO,EACP,KAAM,EACN,KAAM,EACN,MAAO,GAGT,SAASC,EAAWC,EAAa,CAC/B,MAAQ,CAAC,QAAS,OAAQ,OAAQ,OAAO,EAAY,SAASA,CAAiB,CACjF,CAEA,SAASC,EAAgBC,EAAa,CACpC,MAAMC,EAAeD,IAAQ,MAAQ,OAAOA,GAAQ,SAAYA,EAA2C,UAAe,OACpHE,EAAW,WAA0E,SAAS,KAAK,UACnGJ,EAAQG,GAAgBC,GAAW,OACzC,OAAOL,EAAWC,CAAK,EAAIA,EAAQ,MACrC,CASA,SAASK,EAAaC,EAAoBC,EAAuBL,EAAa,CAC5E,MAAMM,EAAeP,EAAgBC,CAAG,EAClCO,EAAWX,EAAWU,CAAY,EAElCE,EAAU,CAACH,EAAcD,CAAS,EACrC,OAAO,OAAO,EACd,IAAKK,GAAM,IAAIA,CAAC,GAAG,EACnB,KAAK,GAAG,EAEX,MAAO,CACL,MAAO,IAAIC,IAAyB,CAC9Bd,EAAW,OAASW,GACtB,QAAQ,MAAM,WAAWC,CAAO,GAAI,GAAGE,CAAI,CAE/C,EACA,KAAM,IAAIA,IAAyB,CAC7Bd,EAAW,MAAQW,GACrB,QAAQ,KAAK,UAAUC,CAAO,GAAI,GAAGE,CAAI,CAE7C,EACA,KAAM,IAAIA,IAAyB,CAC7Bd,EAAW,MAAQW,GACrB,QAAQ,KAAK,UAAUC,CAAO,GAAI,GAAGE,CAAI,CAE7C,EACA,MAAO,IAAIA,IAAyB,CAC9Bd,EAAW,OAASW,GACtB,QAAQ,MAAM,WAAWC,CAAO,GAAI,GAAGE,CAAI,CAE/C,EAEJ",
6
+ "names": ["LOG_LEVELS", "isLogLevel", "level", "resolveLogLevel", "env", "fromInjected", "fromEnv", "createLogger", "namespace", "fullRepoName", "currentLevel", "minLevel", "argsStr", "s", "args"]
7
+ }