@open-mercato/cache 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8687.1.adb16f62b3

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 (61) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +27 -21
  3. package/README.md +30 -0
  4. package/dist/codec.js +1 -74
  5. package/dist/codec.js.map +2 -2
  6. package/dist/defaults.js +1 -6
  7. package/dist/defaults.js.map +2 -2
  8. package/dist/errors.js +1 -12
  9. package/dist/errors.js.map +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/patterns.js +1 -35
  12. package/dist/patterns.js.map +2 -2
  13. package/dist/provider.js +440 -0
  14. package/dist/provider.js.map +7 -0
  15. package/dist/redisConnection.js +2 -0
  16. package/dist/redisConnection.js.map +7 -0
  17. package/dist/service.js +320 -80
  18. package/dist/service.js.map +3 -3
  19. package/dist/strategies/jsonfile.js +1 -186
  20. package/dist/strategies/jsonfile.js.map +3 -3
  21. package/dist/strategies/memory.js +1 -196
  22. package/dist/strategies/memory.js.map +3 -3
  23. package/dist/strategies/redis.js +1 -443
  24. package/dist/strategies/redis.js.map +3 -3
  25. package/dist/strategies/sqlite.js +1 -196
  26. package/dist/strategies/sqlite.js.map +3 -3
  27. package/dist/testing/conformance.js +448 -0
  28. package/dist/testing/conformance.js.map +7 -0
  29. package/dist/testing/index.js +12 -0
  30. package/dist/testing/index.js.map +7 -0
  31. package/dist/testing/remote.js +182 -0
  32. package/dist/testing/remote.js.map +7 -0
  33. package/fixtures/build-conformance-host.mjs +58 -0
  34. package/fixtures/cache-provider-fixture/index.d.ts +18 -0
  35. package/fixtures/cache-provider-fixture/index.js +307 -0
  36. package/fixtures/cache-provider-fixture/package.json +25 -0
  37. package/fixtures/conformance-child.mjs +41 -0
  38. package/jest.config.cjs +3 -1
  39. package/package.json +10 -2
  40. package/src/__tests__/cache-di-contract-docs.test.ts +2 -2
  41. package/src/__tests__/conformance.memory-provider.test.ts +77 -0
  42. package/src/__tests__/provider-fixture.packed.test.ts +178 -0
  43. package/src/__tests__/provider.test.ts +469 -0
  44. package/src/__tests__/service.provider.test.ts +513 -0
  45. package/src/__tests__/service.test.ts +94 -3
  46. package/src/codec.ts +1 -94
  47. package/src/defaults.ts +1 -2
  48. package/src/errors.ts +1 -14
  49. package/src/index.ts +4 -0
  50. package/src/patterns.ts +1 -40
  51. package/src/provider.ts +641 -0
  52. package/src/redisConnection.ts +1 -0
  53. package/src/service.ts +396 -89
  54. package/src/strategies/jsonfile.ts +1 -242
  55. package/src/strategies/memory.ts +1 -275
  56. package/src/strategies/redis.ts +1 -615
  57. package/src/strategies/sqlite.ts +1 -292
  58. package/src/testing/conformance.ts +569 -0
  59. package/src/testing/index.ts +11 -0
  60. package/src/testing/remote.ts +240 -0
  61. package/src/types.ts +8 -106
@@ -0,0 +1,641 @@
1
+ import type { CacheStrategy } from './types'
2
+ import type { CacheCodecOptions } from './codec'
3
+ import { decodeCacheText, encodeCacheText, resolveCacheCodecConfig } from './codec'
4
+ import { matchCacheKeyPattern } from './patterns'
5
+
6
+ export const CACHE_PROVIDER_API_VERSION = 1
7
+
8
+ export type CacheProviderPlacement = 'local' | 'shared'
9
+
10
+ export type CacheProviderSettingsIssue = {
11
+ path: ReadonlyArray<PropertyKey>
12
+ message: string
13
+ code?: string
14
+ }
15
+
16
+ export type CacheProviderSettingsParseResult<TConfig> =
17
+ | { success: true; data: TConfig }
18
+ | { success: false; error: { issues: ReadonlyArray<CacheProviderSettingsIssue> } }
19
+
20
+ export type CacheProviderSettingsSchema<TConfig> = {
21
+ safeParse(input: unknown): CacheProviderSettingsParseResult<TConfig>
22
+ }
23
+
24
+ export type CacheProviderLogMeta = Record<string, unknown>
25
+
26
+ export type CacheProviderLogger = {
27
+ warn(message: string, meta?: CacheProviderLogMeta): void
28
+ error(message: string, meta?: CacheProviderLogMeta): void
29
+ }
30
+
31
+ export type CacheProviderHelpers = {
32
+ encode(json: string): string | Buffer
33
+ /**
34
+ * Throws on a corrupt or truncated frame. Providers MUST catch the error,
35
+ * treat the record as a miss and may delete it; never surface it to callers.
36
+ */
37
+ decode(raw: string | Buffer): string
38
+ matchPattern(key: string, pattern: string): boolean
39
+ }
40
+
41
+ export type CacheProviderHostContext = {
42
+ namespace: string
43
+ defaultTtl?: number
44
+ codec: CacheCodecOptions
45
+ helpers: CacheProviderHelpers
46
+ logger: CacheProviderLogger
47
+ }
48
+
49
+ export type CacheProviderCapability = {
50
+ placement: CacheProviderPlacement
51
+ }
52
+
53
+ export type CacheProviderDefinition<TConfig> = {
54
+ apiVersion: typeof CACHE_PROVIDER_API_VERSION
55
+ id: string
56
+ settings: CacheProviderSettingsSchema<TConfig>
57
+ capability(config: TConfig): CacheProviderCapability
58
+ /**
59
+ * Returns a base strategy over already tenant-scoped physical keys. The host
60
+ * wrapper stores one record per logical entry. `deleteByTags`, `cleanup`
61
+ * and `clear` MUST count each removed physical record once.
62
+ */
63
+ create(config: TConfig, context: CacheProviderHostContext): CacheStrategy | Promise<CacheStrategy>
64
+ redact?(config: TConfig): Record<string, unknown>
65
+ }
66
+
67
+ export type CacheProviderRegistration = {
68
+ id: string
69
+ load: () => Promise<CacheProviderDefinition<unknown>>
70
+ settings: () => unknown
71
+ }
72
+
73
+ export type ResolvedCacheProvider<TConfig = unknown> = {
74
+ id: string
75
+ definition: CacheProviderDefinition<TConfig>
76
+ config: TConfig
77
+ placement: CacheProviderPlacement
78
+ namespace: string
79
+ }
80
+
81
+ export type CacheProviderEnv = Record<string, string | undefined>
82
+
83
+ export type ResolveCacheProviderOptions = {
84
+ env?: CacheProviderEnv
85
+ selectedId?: string | null
86
+ }
87
+
88
+ export type CacheProviderErrorCode =
89
+ | 'invalid_registration'
90
+ | 'duplicate_id'
91
+ | 'reserved_id'
92
+ | 'not_registered'
93
+ | 'load_failed'
94
+ | 'id_mismatch'
95
+ | 'unsupported_api_version'
96
+ | 'invalid_settings'
97
+ | 'missing_namespace'
98
+ | 'invalid_namespace'
99
+ | 'conflicting_selection'
100
+ | 'unavailable'
101
+ | 'timeout'
102
+ | 'not_resolved'
103
+
104
+ export type CacheProviderErrorOptions = {
105
+ providerId?: string
106
+ fieldPaths?: string[]
107
+ cause?: unknown
108
+ }
109
+
110
+ export class CacheProviderError extends Error {
111
+ public readonly code: CacheProviderErrorCode
112
+ public readonly providerId?: string
113
+ public readonly fieldPaths?: string[]
114
+ declare public readonly originalError?: unknown
115
+
116
+ constructor(code: CacheProviderErrorCode, message: string, options: CacheProviderErrorOptions = {}) {
117
+ super(message)
118
+ this.name = 'CacheProviderError'
119
+ this.code = code
120
+ if (options.providerId !== undefined) this.providerId = options.providerId
121
+ if (options.fieldPaths !== undefined) this.fieldPaths = [...options.fieldPaths]
122
+ Object.defineProperty(this, 'originalError', {
123
+ value: options.cause,
124
+ enumerable: false,
125
+ writable: false,
126
+ configurable: false,
127
+ })
128
+ }
129
+
130
+ toJSON(): { name: string; code: CacheProviderErrorCode; message: string; providerId?: string; fieldPaths?: string[] } {
131
+ return {
132
+ name: this.name,
133
+ code: this.code,
134
+ message: this.message,
135
+ ...(this.providerId !== undefined ? { providerId: this.providerId } : {}),
136
+ ...(this.fieldPaths !== undefined ? { fieldPaths: [...this.fieldPaths] } : {}),
137
+ }
138
+ }
139
+ }
140
+
141
+ export function isCacheProviderError(error: unknown): error is CacheProviderError {
142
+ return error instanceof CacheProviderError
143
+ || (error instanceof Error && error.name === 'CacheProviderError' && typeof (error as { code?: unknown }).code === 'string')
144
+ }
145
+
146
+ const CACHE_PROVIDER_ERROR_CODES: ReadonlySet<string> = new Set<CacheProviderErrorCode>([
147
+ 'invalid_registration',
148
+ 'duplicate_id',
149
+ 'reserved_id',
150
+ 'not_registered',
151
+ 'load_failed',
152
+ 'id_mismatch',
153
+ 'unsupported_api_version',
154
+ 'invalid_settings',
155
+ 'missing_namespace',
156
+ 'invalid_namespace',
157
+ 'conflicting_selection',
158
+ 'unavailable',
159
+ 'timeout',
160
+ 'not_resolved',
161
+ ])
162
+
163
+ /**
164
+ * Pass a real `CacheProviderError` from this module through unchanged; wrap any
165
+ * other error (including one that only looks like a `CacheProviderError`) into a
166
+ * host-authored error so provider-controlled messages never reach callers or logs.
167
+ * A look-alike keeps its `code` when it is a known code; everything else becomes
168
+ * `unavailable`. The original error stays reachable only as a non-enumerable cause.
169
+ */
170
+ export function toSanitizedCacheProviderError(
171
+ error: unknown,
172
+ fallback: { message: string; providerId?: string },
173
+ ): CacheProviderError {
174
+ if (error instanceof CacheProviderError) return error
175
+ const lookalikeCode = isCacheProviderError(error) ? (error as { code: string }).code : null
176
+ const code: CacheProviderErrorCode = lookalikeCode !== null && CACHE_PROVIDER_ERROR_CODES.has(lookalikeCode)
177
+ ? lookalikeCode as CacheProviderErrorCode
178
+ : 'unavailable'
179
+ return new CacheProviderError(code, fallback.message, {
180
+ ...(fallback.providerId !== undefined ? { providerId: fallback.providerId } : {}),
181
+ cause: error,
182
+ })
183
+ }
184
+
185
+ export const CACHE_PROVIDER_ENV = 'CACHE_PROVIDER'
186
+ export const CACHE_PROVIDER_NAMESPACE_ENV = 'CACHE_PROVIDER_NAMESPACE'
187
+ export const RESERVED_CACHE_PROVIDER_IDS: ReadonlyArray<string> = ['memory', 'redis', 'sqlite', 'jsonfile']
188
+
189
+ const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/
190
+ const NAMESPACE_PATTERN = /^[a-zA-Z0-9._-]{1,64}$/
191
+ const SENSITIVE_META_KEY_PATTERN = /(pass|secret|token|key|credential|auth|cookie|session|dsn|url|uri|endpoint|cert)/i
192
+ const URL_USER_INFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*@/gi
193
+ const SECRET_PAIR_PATTERN = /\b([a-z0-9_.-]*(?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|access[_-]?key|auth|credentials?)[a-z0-9_.-]*)(\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s;,&]+)/gi
194
+
195
+ export function defineCacheProvider<TConfig>(
196
+ definition: Omit<CacheProviderDefinition<TConfig>, 'apiVersion'>,
197
+ ): CacheProviderDefinition<TConfig> {
198
+ return { ...definition, apiVersion: CACHE_PROVIDER_API_VERSION }
199
+ }
200
+
201
+ export function defineCacheProviderRegistration<TConfig>(registration: {
202
+ id: string
203
+ load: () => Promise<CacheProviderDefinition<TConfig>>
204
+ settings: () => unknown
205
+ }): CacheProviderRegistration {
206
+ return {
207
+ id: registration.id,
208
+ load: registration.load as () => Promise<CacheProviderDefinition<unknown>>,
209
+ settings: registration.settings,
210
+ }
211
+ }
212
+
213
+ export function readSelectedCacheProviderId(env: CacheProviderEnv = process.env): string | null {
214
+ const raw = env[CACHE_PROVIDER_ENV]
215
+ if (typeof raw !== 'string') return null
216
+ const value = raw.trim()
217
+ return value.length > 0 ? value : null
218
+ }
219
+
220
+ function describeId(id: unknown): string {
221
+ return typeof id === 'string' && PROVIDER_ID_PATTERN.test(id) ? id : '<invalid>'
222
+ }
223
+
224
+ function isReservedProviderId(id: string): boolean {
225
+ return RESERVED_CACHE_PROVIDER_IDS.includes(id) || !id.includes('/')
226
+ }
227
+
228
+ function assertProviderIdSyntax(id: unknown, subject: string): asserts id is string {
229
+ if (typeof id !== 'string' || id.length === 0) {
230
+ throw new CacheProviderError('invalid_registration', `${subject} must declare a non-empty provider id`)
231
+ }
232
+ if (isReservedProviderId(id)) {
233
+ throw new CacheProviderError(
234
+ 'reserved_id',
235
+ `${subject} uses a reserved cache provider id; provider ids must be namespaced as "<scope>/<name>" and must not be a built-in strategy name`,
236
+ )
237
+ }
238
+ if (!PROVIDER_ID_PATTERN.test(id)) {
239
+ throw new CacheProviderError(
240
+ 'invalid_registration',
241
+ `${subject} uses an invalid cache provider id; expected "<scope>/<name>" with lowercase letters, digits, ".", "_" or "-"`,
242
+ )
243
+ }
244
+ }
245
+
246
+ export function validateCacheProviderRegistrations(registrations: ReadonlyArray<CacheProviderRegistration>): void {
247
+ if (!Array.isArray(registrations)) {
248
+ throw new CacheProviderError('invalid_registration', 'Cache provider registrations must be an array')
249
+ }
250
+ const seen = new Set<string>()
251
+ registrations.forEach((registration, index) => {
252
+ const subject = `Cache provider registration #${index}`
253
+ if (typeof registration !== 'object' || registration === null) {
254
+ throw new CacheProviderError('invalid_registration', `${subject} must be an object`)
255
+ }
256
+ assertProviderIdSyntax(registration.id, subject)
257
+ if (typeof registration.load !== 'function') {
258
+ throw new CacheProviderError('invalid_registration', `Cache provider "${registration.id}" registration must declare a load() function`, { providerId: registration.id })
259
+ }
260
+ if (typeof registration.settings !== 'function') {
261
+ throw new CacheProviderError('invalid_registration', `Cache provider "${registration.id}" registration must declare a settings() function`, { providerId: registration.id })
262
+ }
263
+ if (seen.has(registration.id)) {
264
+ throw new CacheProviderError('duplicate_id', `Cache provider "${registration.id}" is registered more than once`, { providerId: registration.id })
265
+ }
266
+ seen.add(registration.id)
267
+ })
268
+ }
269
+
270
+ function formatFieldPath(path: ReadonlyArray<PropertyKey>): string {
271
+ if (!Array.isArray(path) || path.length === 0) return '(root)'
272
+ return path
273
+ .map((segment) => (typeof segment === 'symbol' ? segment.description ?? 'symbol' : String(segment)))
274
+ .join('.')
275
+ }
276
+
277
+ function collectFieldPaths(issues: unknown): string[] {
278
+ if (!Array.isArray(issues)) return ['(root)']
279
+ const paths = new Set<string>()
280
+ for (const issue of issues) {
281
+ const path = typeof issue === 'object' && issue !== null ? (issue as { path?: unknown }).path : undefined
282
+ paths.add(formatFieldPath(Array.isArray(path) ? path : []))
283
+ }
284
+ return paths.size > 0 ? Array.from(paths) : ['(root)']
285
+ }
286
+
287
+ function assertDefinitionShape(definition: unknown, id: string): asserts definition is CacheProviderDefinition<unknown> {
288
+ if (typeof definition !== 'object' || definition === null) {
289
+ throw new CacheProviderError('invalid_registration', `Cache provider "${id}" load() did not return a provider definition`, { providerId: id })
290
+ }
291
+ const candidate = definition as Record<string, unknown>
292
+ if (candidate.apiVersion !== CACHE_PROVIDER_API_VERSION) {
293
+ throw new CacheProviderError(
294
+ 'unsupported_api_version',
295
+ `Cache provider "${id}" targets an unsupported provider API version; this host supports version ${CACHE_PROVIDER_API_VERSION}`,
296
+ { providerId: id },
297
+ )
298
+ }
299
+ if (candidate.id !== id) {
300
+ throw new CacheProviderError(
301
+ 'id_mismatch',
302
+ `Cache provider registration "${id}" loaded a definition declaring id "${describeId(candidate.id)}"`,
303
+ { providerId: id },
304
+ )
305
+ }
306
+ const settings = candidate.settings as { safeParse?: unknown } | undefined
307
+ if (typeof settings !== 'object' || settings === null || typeof settings.safeParse !== 'function') {
308
+ throw new CacheProviderError('invalid_registration', `Cache provider "${id}" must declare a settings schema with safeParse()`, { providerId: id })
309
+ }
310
+ if (typeof candidate.capability !== 'function' || typeof candidate.create !== 'function') {
311
+ throw new CacheProviderError('invalid_registration', `Cache provider "${id}" must declare capability() and create()`, { providerId: id })
312
+ }
313
+ if (candidate.redact !== undefined && typeof candidate.redact !== 'function') {
314
+ throw new CacheProviderError('invalid_registration', `Cache provider "${id}" redact must be a function when declared`, { providerId: id })
315
+ }
316
+ }
317
+
318
+ function resolveNamespace(env: CacheProviderEnv, id: string): string {
319
+ const raw = env[CACHE_PROVIDER_NAMESPACE_ENV]
320
+ const value = typeof raw === 'string' ? raw.trim() : ''
321
+ if (!value) {
322
+ throw new CacheProviderError(
323
+ 'missing_namespace',
324
+ `Cache provider "${id}" requires ${CACHE_PROVIDER_NAMESPACE_ENV} to be set to a stable deployment namespace`,
325
+ { providerId: id },
326
+ )
327
+ }
328
+ return validateCacheProviderNamespace(value, id)
329
+ }
330
+
331
+ export function validateCacheProviderNamespace(namespace: unknown, providerId?: string): string {
332
+ if (typeof namespace !== 'string' || !NAMESPACE_PATTERN.test(namespace)) {
333
+ throw new CacheProviderError(
334
+ 'invalid_namespace',
335
+ `Cache provider namespace must be 1-64 characters of letters, digits, ".", "_" or "-"`,
336
+ providerId !== undefined ? { providerId } : {},
337
+ )
338
+ }
339
+ return namespace
340
+ }
341
+
342
+ export async function resolveCacheProvider(
343
+ registrations: ReadonlyArray<CacheProviderRegistration>,
344
+ options: ResolveCacheProviderOptions = {},
345
+ ): Promise<ResolvedCacheProvider | null> {
346
+ const env = options.env ?? process.env
347
+ const explicit = typeof options.selectedId === 'string' ? options.selectedId.trim() : ''
348
+ const selectedId = explicit.length > 0 ? explicit : readSelectedCacheProviderId(env)
349
+ if (!selectedId) return null
350
+ validateCacheProviderRegistrations(registrations)
351
+
352
+ if (isReservedProviderId(selectedId)) {
353
+ throw new CacheProviderError(
354
+ 'reserved_id',
355
+ `${CACHE_PROVIDER_ENV} must name a registered "<scope>/<name>" provider; built-in strategies are selected with CACHE_STRATEGY`,
356
+ )
357
+ }
358
+
359
+ const registration = registrations.find((entry) => entry.id === selectedId)
360
+ if (!registration) {
361
+ throw new CacheProviderError(
362
+ 'not_registered',
363
+ `Cache provider "${describeId(selectedId)}" is selected but not registered by the application`,
364
+ PROVIDER_ID_PATTERN.test(selectedId) ? { providerId: selectedId } : {},
365
+ )
366
+ }
367
+ const id = registration.id
368
+
369
+ let definition: unknown
370
+ try {
371
+ definition = await registration.load()
372
+ } catch (error) {
373
+ throw new CacheProviderError('load_failed', `Cache provider "${id}" failed to load`, { providerId: id, cause: error })
374
+ }
375
+ assertDefinitionShape(definition, id)
376
+
377
+ let rawSettings: unknown
378
+ try {
379
+ rawSettings = registration.settings()
380
+ } catch (error) {
381
+ throw new CacheProviderError('invalid_settings', `Cache provider "${id}" settings could not be evaluated`, { providerId: id, cause: error })
382
+ }
383
+
384
+ let parsed: CacheProviderSettingsParseResult<unknown>
385
+ try {
386
+ parsed = definition.settings.safeParse(rawSettings)
387
+ } catch (error) {
388
+ throw new CacheProviderError('invalid_settings', `Cache provider "${id}" settings could not be validated`, { providerId: id, cause: error })
389
+ }
390
+ if (!parsed || typeof parsed !== 'object' || parsed.success !== true) {
391
+ const issues = parsed && typeof parsed === 'object' && parsed.success === false ? parsed.error?.issues : undefined
392
+ const fieldPaths = collectFieldPaths(issues)
393
+ throw new CacheProviderError(
394
+ 'invalid_settings',
395
+ `Cache provider "${id}" settings are invalid at: ${fieldPaths.join(', ')}`,
396
+ { providerId: id, fieldPaths },
397
+ )
398
+ }
399
+ const config = parsed.data
400
+
401
+ const namespace = resolveNamespace(env, id)
402
+
403
+ let capability: CacheProviderCapability
404
+ try {
405
+ capability = definition.capability(config)
406
+ } catch (error) {
407
+ throw new CacheProviderError('invalid_registration', `Cache provider "${id}" capability() failed`, { providerId: id, cause: error })
408
+ }
409
+ const placement = capability && typeof capability === 'object' ? capability.placement : undefined
410
+ if (placement !== 'local' && placement !== 'shared') {
411
+ throw new CacheProviderError('invalid_registration', `Cache provider "${id}" capability() must report placement "local" or "shared"`, { providerId: id })
412
+ }
413
+
414
+ return { id, definition, config, placement, namespace }
415
+ }
416
+
417
+ function scrubSecretsInText(value: string): string {
418
+ return value
419
+ .replace(URL_USER_INFO_PATTERN, '$1***@')
420
+ .replace(SECRET_PAIR_PATTERN, '$1$2***')
421
+ }
422
+
423
+ function sanitizeLogMeta(meta: CacheProviderLogMeta | undefined): CacheProviderLogMeta | undefined {
424
+ if (!meta || typeof meta !== 'object') return undefined
425
+ const sanitized: CacheProviderLogMeta = {}
426
+ for (const [key, value] of Object.entries(meta)) {
427
+ if (SENSITIVE_META_KEY_PATTERN.test(key)) {
428
+ sanitized[key] = '[redacted]'
429
+ } else if (value instanceof Error) {
430
+ sanitized[key] = { name: value.name }
431
+ } else if (value === null || typeof value === 'number' || typeof value === 'boolean') {
432
+ sanitized[key] = value
433
+ } else if (typeof value === 'string') {
434
+ const scrubbed = scrubSecretsInText(value)
435
+ sanitized[key] = scrubbed.length > 200 ? `${scrubbed.slice(0, 200)}…` : scrubbed
436
+ } else {
437
+ sanitized[key] = '[omitted]'
438
+ }
439
+ }
440
+ return sanitized
441
+ }
442
+
443
+ export function createCacheProviderLogger(providerId: string): CacheProviderLogger {
444
+ const prefix = `[cache] provider ${describeId(providerId)}:`
445
+ return {
446
+ warn(message, meta) {
447
+ const safe = sanitizeLogMeta(meta)
448
+ if (safe) console.warn(`${prefix} ${message}`, safe)
449
+ else console.warn(`${prefix} ${message}`)
450
+ },
451
+ error(message, meta) {
452
+ const safe = sanitizeLogMeta(meta)
453
+ if (safe) console.error(`${prefix} ${message}`, safe)
454
+ else console.error(`${prefix} ${message}`)
455
+ },
456
+ }
457
+ }
458
+
459
+ export function createCacheProviderHostContext(
460
+ provider: Pick<ResolvedCacheProvider, 'id' | 'namespace'>,
461
+ options: { defaultTtl?: number; codec?: CacheCodecOptions } = {},
462
+ ): CacheProviderHostContext {
463
+ const codec: CacheCodecOptions = { ...(options.codec ?? {}) }
464
+ const codecConfig = resolveCacheCodecConfig(codec)
465
+ return {
466
+ namespace: validateCacheProviderNamespace(provider.namespace, provider.id),
467
+ ...(options.defaultTtl !== undefined ? { defaultTtl: options.defaultTtl } : {}),
468
+ codec,
469
+ helpers: {
470
+ encode: (json) => encodeCacheText(json, codecConfig),
471
+ decode: (raw) => decodeCacheText(raw),
472
+ matchPattern: (key, pattern) => matchCacheKeyPattern(key, pattern),
473
+ },
474
+ logger: createCacheProviderLogger(provider.id),
475
+ }
476
+ }
477
+
478
+ const SELECTION_STATE_KEY = Symbol.for('@open-mercato/cache/provider-selection')
479
+
480
+ type CacheProviderSelectionKey = {
481
+ registrations: ReadonlyArray<CacheProviderRegistration>
482
+ selectedId: string | null
483
+ namespace: string | null
484
+ }
485
+
486
+ type CacheProviderSelectionMemo = CacheProviderSelectionKey & {
487
+ pending: Promise<ResolvedCacheProvider | null>
488
+ settled: { provider: ResolvedCacheProvider | null } | null
489
+ failure: CacheProviderError | null
490
+ }
491
+
492
+ type CacheProviderManifest = { cacheProviders?: unknown }
493
+ type CacheProviderManifestLoader = () => Promise<CacheProviderManifest>
494
+
495
+ type CacheProviderSelectionState = {
496
+ manifest: {
497
+ load: CacheProviderManifestLoader
498
+ pending?: Promise<void>
499
+ loaded?: boolean
500
+ } | null
501
+ registrations: ReadonlyArray<CacheProviderRegistration>
502
+ memo: CacheProviderSelectionMemo | null
503
+ }
504
+
505
+ type GlobalWithSelectionState = typeof globalThis & {
506
+ [SELECTION_STATE_KEY]?: CacheProviderSelectionState
507
+ }
508
+
509
+ function createSelectionState(): CacheProviderSelectionState {
510
+ return { manifest: null, registrations: [], memo: null }
511
+ }
512
+
513
+ function selectionState(): CacheProviderSelectionState {
514
+ const scope = globalThis as GlobalWithSelectionState
515
+ if (!scope[SELECTION_STATE_KEY]) {
516
+ scope[SELECTION_STATE_KEY] = createSelectionState()
517
+ }
518
+ return scope[SELECTION_STATE_KEY]
519
+ }
520
+
521
+ function readSelectionKey(state: CacheProviderSelectionState, env: CacheProviderEnv): CacheProviderSelectionKey {
522
+ const rawNamespace = env[CACHE_PROVIDER_NAMESPACE_ENV]
523
+ const namespace = typeof rawNamespace === 'string' ? rawNamespace.trim() : ''
524
+ return {
525
+ registrations: state.registrations,
526
+ selectedId: readSelectedCacheProviderId(env),
527
+ namespace: namespace.length > 0 ? namespace : null,
528
+ }
529
+ }
530
+
531
+ function matchesSelectionKey(memo: CacheProviderSelectionMemo, key: CacheProviderSelectionKey): boolean {
532
+ return memo.registrations === key.registrations
533
+ && memo.selectedId === key.selectedId
534
+ && memo.namespace === key.namespace
535
+ }
536
+
537
+ /**
538
+ * Register the application's cache providers. Replacing the registrations
539
+ * discards any memoized selection so the next `prepareCacheProviderSelection()`
540
+ * resolves against the new list.
541
+ */
542
+ export function setCacheProviderRegistrations(registrations: ReadonlyArray<CacheProviderRegistration>): void {
543
+ const state = selectionState()
544
+ state.manifest = null
545
+ state.registrations = Array.isArray(registrations) ? [...registrations] : registrations
546
+ state.memo = null
547
+ }
548
+
549
+ /** The web bootstrap supplies a bundler-visible import without evaluating app config. */
550
+ export function setCacheProviderManifestLoader(load: CacheProviderManifestLoader): void {
551
+ const state = selectionState()
552
+ if (state.manifest && (state.manifest.load === load || process.env.NODE_ENV === 'production')) return
553
+ state.manifest = { load }
554
+ state.registrations = []
555
+ state.memo = null
556
+ }
557
+
558
+ export function readCacheProviderManifest(manifest: CacheProviderManifest): CacheProviderRegistration[] {
559
+ if (!Array.isArray(manifest.cacheProviders)) {
560
+ throw new CacheProviderError(
561
+ 'invalid_registration',
562
+ 'The cache provider manifest must export a cacheProviders array. Run yarn generate and check src/providers/cache.ts.',
563
+ )
564
+ }
565
+ return manifest.cacheProviders as CacheProviderRegistration[]
566
+ }
567
+
568
+ export function getCacheProviderRegistrations(): ReadonlyArray<CacheProviderRegistration> {
569
+ return selectionState().registrations
570
+ }
571
+
572
+ /**
573
+ * Resolve the selected provider once per (registrations, `CACHE_PROVIDER`,
574
+ * `CACHE_PROVIDER_NAMESPACE`) combination. A call whose combination differs from
575
+ * the memoized one re-resolves. A `not_registered` failure against an empty
576
+ * registration list is not memoized, so registering the manifest later recovers.
577
+ */
578
+ export function prepareCacheProviderSelection(options: { env?: CacheProviderEnv } = {}): Promise<ResolvedCacheProvider | null> {
579
+ const state = selectionState()
580
+ const env = options.env ?? process.env
581
+ const manifest = state.manifest
582
+ if (manifest && !manifest.loaded && readSelectedCacheProviderId(env)) {
583
+ manifest.pending ??= Promise.resolve().then(manifest.load).then((loaded) => {
584
+ if (state.manifest !== manifest) return
585
+ state.registrations = [...readCacheProviderManifest(loaded)]
586
+ state.memo = null
587
+ manifest.loaded = true
588
+ }).catch((error: unknown) => {
589
+ throw toSanitizedCacheProviderError(error, {
590
+ message: 'The cache provider manifest could not be loaded. Check src/providers/cache.ts.',
591
+ })
592
+ })
593
+ return manifest.pending.then(() => prepareCacheProviderSelection(options))
594
+ }
595
+ const key = readSelectionKey(state, env)
596
+ if (state.memo && matchesSelectionKey(state.memo, key)) return state.memo.pending
597
+ const memo: CacheProviderSelectionMemo = {
598
+ ...key,
599
+ pending: Promise.resolve(null),
600
+ settled: null,
601
+ failure: null,
602
+ }
603
+ memo.pending = resolveCacheProvider(key.registrations, { env }).then(
604
+ (provider) => {
605
+ memo.settled = { provider }
606
+ return provider
607
+ },
608
+ (error: unknown) => {
609
+ const failure = toSanitizedCacheProviderError(error, { message: 'Cache provider selection failed' })
610
+ if (failure.code === 'not_registered' && key.registrations.length === 0) {
611
+ if (state.memo === memo) state.memo = null
612
+ } else {
613
+ memo.failure = failure
614
+ }
615
+ throw failure
616
+ },
617
+ )
618
+ state.memo = memo
619
+ return memo.pending
620
+ }
621
+
622
+ export function getPreparedCacheProvider(env: CacheProviderEnv = process.env): ResolvedCacheProvider | null {
623
+ const selectedId = readSelectedCacheProviderId(env)
624
+ if (!selectedId) return null
625
+ const state = selectionState()
626
+ const memo = state.memo
627
+ if (memo && matchesSelectionKey(memo, readSelectionKey(state, env))) {
628
+ if (memo.failure) throw memo.failure
629
+ if (memo.settled?.provider) return memo.settled.provider
630
+ }
631
+ throw new CacheProviderError(
632
+ 'not_resolved',
633
+ `${CACHE_PROVIDER_ENV} is set but the cache provider selection has not been prepared; call prepareCacheProviderSelection() during bootstrap before creating the cache service`,
634
+ PROVIDER_ID_PATTERN.test(selectedId) ? { providerId: selectedId } : {},
635
+ )
636
+ }
637
+
638
+ export function resetCacheProviderSelectionForTests(): void {
639
+ const scope = globalThis as GlobalWithSelectionState
640
+ scope[SELECTION_STATE_KEY] = createSelectionState()
641
+ }
@@ -0,0 +1 @@
1
+ export * from '@open-mercato/cache-provider-kit/redisConnection'