tricache 0.7.0 → 0.7.1

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 (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
@@ -1,151 +1,154 @@
1
- /**
2
- * tricache/prisma — First-class Prisma Client extension for TriCache.
3
- *
4
- * Usage:
5
- * import { PrismaClient } from '@prisma/client';
6
- * import { withTriCache } from 'tricache/prisma';
7
- *
8
- * const prisma = new PrismaClient().$extends(
9
- * withTriCache({
10
- * cache,
11
- * defaultTtl: 300,
12
- * autoInvalidate: true, // Invalidate model tags on create/update/delete
13
- * })
14
- * );
15
- *
16
- * // Query with cache options:
17
- * const users = await prisma.user.findMany({
18
- * where: { active: true },
19
- * cache: { ttl: 60, tags: ['users'], swr: 30 },
20
- * });
21
- */
22
-
23
- import type { CacheService } from '../cache-service.js';
24
- import type { WrapOptions } from '../types.js';
25
- import crypto from 'crypto';
26
-
27
- export interface PrismaCacheQueryOptions extends WrapOptions {
28
- /** Explicit cache key. Defaults to SHA-256 hash of (model + operation + args). */
29
- key?: string;
30
- /** Explicit tags for invalidation. Automatically includes `[model.toLowerCase()]`. */
31
- tags?: string[];
32
- }
33
-
34
- export interface PrismaTriCacheOptions {
35
- /** TriCache instance to use for caching. */
36
- cache: CacheService;
37
- /** Default TTL in seconds for cached queries (default: 300 s). */
38
- defaultTtl?: number;
39
- /** Whether to automatically invalidate model tags on write operations (default: true). */
40
- autoInvalidate?: boolean;
41
- /** Automatically cache all read queries even if `cache` options are not provided (default: false). */
42
- autoCache?: boolean;
43
- }
44
-
45
- const READ_OPERATIONS = new Set([
46
- 'findUnique',
47
- 'findUniqueOrThrow',
48
- 'findFirst',
49
- 'findFirstOrThrow',
50
- 'findMany',
51
- 'count',
52
- 'aggregate',
53
- 'groupBy',
54
- ]);
55
-
56
- const MUTATION_OPERATIONS = new Set([
57
- 'create',
58
- 'createMany',
59
- 'createManyAndReturn',
60
- 'update',
61
- 'updateMany',
62
- 'updateManyAndReturn',
63
- 'upsert',
64
- 'delete',
65
- 'deleteMany',
66
- ]);
67
-
68
- /** Recursively sorts object keys for deterministic serialization of nested query filters */
69
- function deterministicStringify(val: unknown): string {
70
- if (val === null || typeof val !== 'object') {
71
- return JSON.stringify(val);
72
- }
73
- if (Array.isArray(val)) {
74
- return `[${val.map(deterministicStringify).join(',')}]`;
75
- }
76
- const obj = val as Record<string, unknown>;
77
- const keys = Object.keys(obj).sort();
78
- return `{${keys.map(k => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(',')}}`;
79
- }
80
-
81
- /** Generate a deterministic SHA-256 hash key for a Prisma query. */
82
- export function generatePrismaCacheKey(model: string, operation: string, args: unknown): string {
83
- const normalized = deterministicStringify({ model, operation, args });
84
- const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
85
- return `prisma:${model.toLowerCase()}:${operation}:${hash}`;
86
- }
87
-
88
- /**
89
- * Creates a Prisma Client Extension for TriCache.
90
- */
91
- export function withTriCache(options: PrismaTriCacheOptions) {
92
- const { cache, defaultTtl = 300, autoInvalidate = true, autoCache = false } = options;
93
-
94
- return {
95
- name: 'tricache-prisma-extension',
96
- query: {
97
- $allModels: {
98
- async $allOperations({ model, operation, args, query }: {
99
- model: string;
100
- operation: string;
101
- args: Record<string, unknown> | undefined;
102
- query: (args: unknown) => Promise<unknown>;
103
- }) {
104
- const modelTag = model.toLowerCase();
105
-
106
- // Auto-invalidation on write operations
107
- if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
108
- const result = await query(args);
109
- await cache.invalidateTag(modelTag);
110
- return result;
111
- }
112
-
113
- // Read operations
114
- if (READ_OPERATIONS.has(operation)) {
115
- const queryArgs = args ?? {};
116
- const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
117
-
118
- if (cacheConfig !== undefined || autoCache) {
119
- const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
120
- ? cacheConfig
121
- : {};
122
-
123
- // Clone args without the `cache` property to pass clean args to Prisma query engine
124
- const { cache: _c, ...cleanArgs } = queryArgs as Record<string, unknown>;
125
-
126
- const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
127
- const tags = [...new Set([modelTag, ...(opts.tags ?? [])])];
128
-
129
- return cache.wrap(
130
- key,
131
- () => query(cleanArgs),
132
- {
133
- ttl: opts.ttl ?? defaultTtl,
134
- swr: opts.swr,
135
- priority: opts.priority,
136
- tags,
137
- dependsOn: opts.dependsOn,
138
- refreshAhead: opts.refreshAhead,
139
- xfetchBeta: opts.xfetchBeta,
140
- notFoundTtl: opts.notFoundTtl,
141
- },
142
- );
143
- }
144
- }
145
-
146
- return query(args);
147
- },
148
- },
149
- },
150
- };
151
- }
1
+ /**
2
+ * tricache/prisma — First-class Prisma Client extension for TriCache.
3
+ *
4
+ * Usage:
5
+ * import { PrismaClient } from '@prisma/client';
6
+ * import { withTriCache } from 'tricache/prisma';
7
+ *
8
+ * const prisma = new PrismaClient().$extends(
9
+ * withTriCache({
10
+ * cache,
11
+ * defaultTtl: 300,
12
+ * autoInvalidate: true, // Invalidate model tags on create/update/delete
13
+ * })
14
+ * );
15
+ *
16
+ * // Query with cache options:
17
+ * const users = await prisma.user.findMany({
18
+ * where: { active: true },
19
+ * cache: { ttl: 60, tags: ['users'], swr: 30 },
20
+ * });
21
+ */
22
+
23
+ import type { CacheService } from '../cache-service.js';
24
+ import type { WrapOptions } from '../types.js';
25
+ import crypto from 'crypto';
26
+
27
+ export interface PrismaCacheQueryOptions extends WrapOptions {
28
+ /** Explicit cache key. Defaults to SHA-256 hash of (model + operation + args). */
29
+ key?: string;
30
+ /** Explicit tags for invalidation. Automatically includes `[model.toLowerCase()]`. */
31
+ tags?: string[];
32
+ }
33
+
34
+ export interface PrismaTriCacheOptions {
35
+ /** TriCache instance to use for caching. */
36
+ cache: CacheService;
37
+ /** Default TTL in seconds for cached queries (default: 300 s). */
38
+ defaultTtl?: number;
39
+ /** Whether to automatically invalidate model tags on write operations (default: true). */
40
+ autoInvalidate?: boolean;
41
+ /** Automatically cache all read queries even if `cache` options are not provided (default: false). */
42
+ autoCache?: boolean;
43
+ }
44
+
45
+ const READ_OPERATIONS = new Set([
46
+ 'findUnique',
47
+ 'findUniqueOrThrow',
48
+ 'findFirst',
49
+ 'findFirstOrThrow',
50
+ 'findMany',
51
+ 'count',
52
+ 'aggregate',
53
+ 'groupBy',
54
+ ]);
55
+
56
+ const MUTATION_OPERATIONS = new Set([
57
+ 'create',
58
+ 'createMany',
59
+ 'createManyAndReturn',
60
+ 'update',
61
+ 'updateMany',
62
+ 'updateManyAndReturn',
63
+ 'upsert',
64
+ 'delete',
65
+ 'deleteMany',
66
+ ]);
67
+
68
+ /** Recursively sorts object keys for deterministic serialization of nested query filters */
69
+ function deterministicStringify(val: unknown): string {
70
+ if (val === null || typeof val !== 'object') {
71
+ return JSON.stringify(val);
72
+ }
73
+ if (Array.isArray(val)) {
74
+ return `[${val.map(deterministicStringify).join(',')}]`;
75
+ }
76
+ const obj = val as Record<string, unknown>;
77
+ const keys = Object.keys(obj).sort();
78
+ return `{${keys.map(k => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(',')}}`;
79
+ }
80
+
81
+ /** Generate a deterministic SHA-256 hash key for a Prisma query. */
82
+ export function generatePrismaCacheKey(model: string, operation: string, args: unknown): string {
83
+ const normalized = deterministicStringify({ model, operation, args });
84
+ const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
85
+ return `prisma:${model.toLowerCase()}:${operation}:${hash}`;
86
+ }
87
+
88
+ /**
89
+ * Creates a Prisma Client Extension for TriCache.
90
+ */
91
+ export function withTriCache(options: PrismaTriCacheOptions) {
92
+ const { cache, defaultTtl = 300, autoInvalidate = true, autoCache = false } = options;
93
+
94
+ return {
95
+ name: 'tricache-prisma-extension',
96
+ query: {
97
+ $allModels: {
98
+ async $allOperations({ model, operation, args, query }: {
99
+ model: string;
100
+ operation: string;
101
+ args: Record<string, unknown> | undefined;
102
+ query: (args: unknown) => Promise<unknown>;
103
+ }) {
104
+ const modelTag = model.toLowerCase();
105
+
106
+ // Auto-invalidation on write operations
107
+ if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
108
+ // Strip the cache pseudo-option here too — the read path removes it,
109
+ // but the mutation path forwarded it verbatim to the Prisma engine.
110
+ const { cache: _cacheOpt, ...cleanMutationArgs } = (args ?? {}) as Record<string, unknown>;
111
+ const result = await query(cleanMutationArgs);
112
+ await cache.invalidateTag(modelTag);
113
+ return result;
114
+ }
115
+
116
+ // Read operations
117
+ if (READ_OPERATIONS.has(operation)) {
118
+ const queryArgs = args ?? {};
119
+ const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
120
+
121
+ if (cacheConfig !== undefined || autoCache) {
122
+ const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
123
+ ? cacheConfig
124
+ : {};
125
+
126
+ // Clone args without the `cache` property to pass clean args to Prisma query engine
127
+ const { cache: _c, ...cleanArgs } = queryArgs as Record<string, unknown>;
128
+
129
+ const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
130
+ const tags = [...new Set([modelTag, ...(opts.tags ?? [])])];
131
+
132
+ return cache.wrap(
133
+ key,
134
+ () => query(cleanArgs),
135
+ {
136
+ ttl: opts.ttl ?? defaultTtl,
137
+ swr: opts.swr,
138
+ priority: opts.priority,
139
+ tags,
140
+ dependsOn: opts.dependsOn,
141
+ refreshAhead: opts.refreshAhead,
142
+ xfetchBeta: opts.xfetchBeta,
143
+ notFoundTtl: opts.notFoundTtl,
144
+ },
145
+ );
146
+ }
147
+ }
148
+
149
+ return query(args);
150
+ },
151
+ },
152
+ },
153
+ };
154
+ }