@geekmidas/cache 1.1.2 → 10.0.0-alpha.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 (81) hide show
  1. package/dist/expo.cjs +2 -1
  2. package/dist/expo.cjs.map +1 -1
  3. package/dist/expo.d.cts +1 -1
  4. package/dist/expo.d.mts +1 -1
  5. package/dist/expo.mjs +2 -1
  6. package/dist/expo.mjs.map +1 -1
  7. package/dist/file.cjs +2 -1
  8. package/dist/file.cjs.map +1 -1
  9. package/dist/file.d.cts +1 -1
  10. package/dist/file.d.mts +1 -1
  11. package/dist/file.mjs +2 -1
  12. package/dist/file.mjs.map +1 -1
  13. package/dist/index-1sNRIo6N.d.mts +64 -0
  14. package/dist/index-1sNRIo6N.d.mts.map +1 -0
  15. package/dist/index-CNQ50bVk.d.cts +64 -0
  16. package/dist/index-CNQ50bVk.d.cts.map +1 -0
  17. package/dist/index.cjs +7 -2
  18. package/dist/index.d.cts +2 -2
  19. package/dist/index.d.mts +2 -2
  20. package/dist/index.mjs +3 -2
  21. package/dist/memory.cjs +2 -1
  22. package/dist/memory.cjs.map +1 -1
  23. package/dist/memory.d.cts +1 -1
  24. package/dist/memory.d.mts +1 -1
  25. package/dist/memory.mjs +2 -1
  26. package/dist/memory.mjs.map +1 -1
  27. package/dist/postgres.cjs +155 -0
  28. package/dist/postgres.cjs.map +1 -0
  29. package/dist/postgres.d.cts +75 -0
  30. package/dist/postgres.d.cts.map +1 -0
  31. package/dist/postgres.d.mts +75 -0
  32. package/dist/postgres.d.mts.map +1 -0
  33. package/dist/postgres.mjs +152 -0
  34. package/dist/postgres.mjs.map +1 -0
  35. package/dist/redis.cjs +70 -0
  36. package/dist/redis.cjs.map +1 -0
  37. package/dist/redis.d.cts +31 -0
  38. package/dist/redis.d.cts.map +1 -0
  39. package/dist/redis.d.mts +31 -0
  40. package/dist/redis.d.mts.map +1 -0
  41. package/dist/redis.mjs +67 -0
  42. package/dist/redis.mjs.map +1 -0
  43. package/dist/registry-CITg73zW.cjs +65 -0
  44. package/dist/registry-CITg73zW.cjs.map +1 -0
  45. package/dist/registry-CT0b-rjB.mjs +41 -0
  46. package/dist/registry-CT0b-rjB.mjs.map +1 -0
  47. package/dist/registry.cjs +6 -0
  48. package/dist/registry.d.cts +2 -0
  49. package/dist/registry.d.mts +2 -0
  50. package/dist/registry.mjs +3 -0
  51. package/dist/{src-CrE4Nl5T.mjs → src-DVpoP03o.mjs} +1 -1
  52. package/dist/{src-CrE4Nl5T.mjs.map → src-DVpoP03o.mjs.map} +1 -1
  53. package/dist/{src-zfYb7mdS.cjs → src-ysNIqjnr.cjs} +1 -1
  54. package/dist/{src-zfYb7mdS.cjs.map → src-ysNIqjnr.cjs.map} +1 -1
  55. package/dist/upstash.cjs +41 -0
  56. package/dist/upstash.cjs.map +1 -1
  57. package/dist/upstash.d.cts +27 -3
  58. package/dist/upstash.d.cts.map +1 -1
  59. package/dist/upstash.d.mts +27 -3
  60. package/dist/upstash.d.mts.map +1 -1
  61. package/dist/upstash.mjs +39 -1
  62. package/dist/upstash.mjs.map +1 -1
  63. package/package.json +45 -3
  64. package/CHANGELOG.md +0 -32
  65. package/dist/index-BSYYdwRm.d.cts +0 -36
  66. package/dist/index-BSYYdwRm.d.cts.map +0 -1
  67. package/dist/index-Dx96gr-9.d.mts +0 -36
  68. package/dist/index-Dx96gr-9.d.mts.map +0 -1
  69. package/src/__benchmarks__/memory.bench.ts +0 -51
  70. package/src/__tests__/cache.spec.ts +0 -144
  71. package/src/__tests__/file.spec.ts +0 -192
  72. package/src/__tests__/integration.spec.ts +0 -282
  73. package/src/__tests__/memory.spec.ts +0 -134
  74. package/src/__tests__/upstash.spec.ts +0 -276
  75. package/src/expo.ts +0 -50
  76. package/src/file.ts +0 -126
  77. package/src/index.ts +0 -48
  78. package/src/memory.ts +0 -38
  79. package/src/upstash.ts +0 -41
  80. package/tsconfig.json +0 -9
  81. package/tsdown.config.ts +0 -5
@@ -0,0 +1,75 @@
1
+ import { Cache, CacheDriver } from "./index-CNQ50bVk.cjs";
2
+ import { Pool } from "pg";
3
+
4
+ //#region src/postgres.d.ts
5
+
6
+ interface PostgresCacheOptions {
7
+ /**
8
+ * The table to keep entries in, schema-qualified if it needs to be.
9
+ *
10
+ * Defaults to `cache`. It resolves against the connection's `search_path`,
11
+ * which the role carries — so a tenant's cache lands in the tenant's schema
12
+ * without anything here knowing the schema's name.
13
+ */
14
+ table?: string;
15
+ }
16
+ declare class PostgresCache implements Cache {
17
+ private readonly pool;
18
+ private readonly table;
19
+ constructor(pool: Pool, options?: PostgresCacheOptions);
20
+ get<T>(key: string): Promise<T | undefined>;
21
+ set<T>(key: string, value: T, ttl?: number): Promise<void>;
22
+ delete(key: string): Promise<void>;
23
+ ttl(key: string): Promise<number>;
24
+ /**
25
+ * Delete every expired entry.
26
+ *
27
+ * Optional: reads already ignore them. Worth running occasionally so the
28
+ * table does not grow without bound in a workload that writes many keys once.
29
+ */
30
+ sweep(): Promise<number>;
31
+ private query;
32
+ /**
33
+ * The table name as an identifier.
34
+ *
35
+ * Quoted per segment so a schema-qualified name stays two identifiers rather
36
+ * than becoming one with a dot in it. The name comes from configuration
37
+ * rather than from a request, so this is defence rather than sanitisation.
38
+ */
39
+ private identifier;
40
+ }
41
+ /**
42
+ * The `postgres://` driver.
43
+ *
44
+ * One pool per URL, cached for the life of the process: a cache that opened a
45
+ * connection per call would be slower than the thing it exists to speed up, and
46
+ * a Lambda reusing a warm container should reuse the pool with it.
47
+ *
48
+ * `pg` is imported at the top of this module rather than lazily, because the
49
+ * *module* is the lazy boundary — an app caching in Redis never imports
50
+ * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
51
+ * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
52
+ */
53
+ declare const postgresCacheDriver: CacheDriver;
54
+ /**
55
+ * The DDL a Postgres-backed cache needs, for whoever applies DDL.
56
+ *
57
+ * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
58
+ * statements run in-process from `gkm dev` and from a provisioner inside a VPC,
59
+ * and one implementation is what stops "works locally, fails deployed".
60
+ *
61
+ * Run as the schema's **owner**. The role a handler connects as cannot create a
62
+ * table, which is the point of the split and the reason this is not done lazily.
63
+ */
64
+ declare function cacheTableStatements(options?: PostgresCacheOptions): {
65
+ describe: string;
66
+ exists?: {
67
+ sql: string;
68
+ values: unknown[];
69
+ };
70
+ sql: string;
71
+ }[];
72
+ //# sourceMappingURL=postgres.d.ts.map
73
+ //#endregion
74
+ export { PostgresCache, PostgresCacheOptions, cacheTableStatements, postgresCacheDriver };
75
+ //# sourceMappingURL=postgres.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.cts","names":[],"sources":["../src/postgres.ts"],"sourcesContent":[],"mappings":";;;;;UA0BiB,oBAAA;;;;;;;;;;cAaJ,aAAA,YAAyB;;;oBAIb,gBACd;uBAKiB,QAAQ;6BAUF,kBAAkB;uBAgBxB;oBAIH;;;;;;;WAuBT;;;;;;;;;;;;;;;;;;;;;;;cAyCH,qBAAqB;;;;;;;;;;;iBA6DlB,oBAAA,WAA8B"}
@@ -0,0 +1,75 @@
1
+ import { Cache, CacheDriver } from "./index-1sNRIo6N.mjs";
2
+ import { Pool } from "pg";
3
+
4
+ //#region src/postgres.d.ts
5
+
6
+ interface PostgresCacheOptions {
7
+ /**
8
+ * The table to keep entries in, schema-qualified if it needs to be.
9
+ *
10
+ * Defaults to `cache`. It resolves against the connection's `search_path`,
11
+ * which the role carries — so a tenant's cache lands in the tenant's schema
12
+ * without anything here knowing the schema's name.
13
+ */
14
+ table?: string;
15
+ }
16
+ declare class PostgresCache implements Cache {
17
+ private readonly pool;
18
+ private readonly table;
19
+ constructor(pool: Pool, options?: PostgresCacheOptions);
20
+ get<T>(key: string): Promise<T | undefined>;
21
+ set<T>(key: string, value: T, ttl?: number): Promise<void>;
22
+ delete(key: string): Promise<void>;
23
+ ttl(key: string): Promise<number>;
24
+ /**
25
+ * Delete every expired entry.
26
+ *
27
+ * Optional: reads already ignore them. Worth running occasionally so the
28
+ * table does not grow without bound in a workload that writes many keys once.
29
+ */
30
+ sweep(): Promise<number>;
31
+ private query;
32
+ /**
33
+ * The table name as an identifier.
34
+ *
35
+ * Quoted per segment so a schema-qualified name stays two identifiers rather
36
+ * than becoming one with a dot in it. The name comes from configuration
37
+ * rather than from a request, so this is defence rather than sanitisation.
38
+ */
39
+ private identifier;
40
+ }
41
+ /**
42
+ * The `postgres://` driver.
43
+ *
44
+ * One pool per URL, cached for the life of the process: a cache that opened a
45
+ * connection per call would be slower than the thing it exists to speed up, and
46
+ * a Lambda reusing a warm container should reuse the pool with it.
47
+ *
48
+ * `pg` is imported at the top of this module rather than lazily, because the
49
+ * *module* is the lazy boundary — an app caching in Redis never imports
50
+ * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
51
+ * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
52
+ */
53
+ declare const postgresCacheDriver: CacheDriver;
54
+ /**
55
+ * The DDL a Postgres-backed cache needs, for whoever applies DDL.
56
+ *
57
+ * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
58
+ * statements run in-process from `gkm dev` and from a provisioner inside a VPC,
59
+ * and one implementation is what stops "works locally, fails deployed".
60
+ *
61
+ * Run as the schema's **owner**. The role a handler connects as cannot create a
62
+ * table, which is the point of the split and the reason this is not done lazily.
63
+ */
64
+ declare function cacheTableStatements(options?: PostgresCacheOptions): {
65
+ describe: string;
66
+ exists?: {
67
+ sql: string;
68
+ values: unknown[];
69
+ };
70
+ sql: string;
71
+ }[];
72
+ //# sourceMappingURL=postgres.d.ts.map
73
+ //#endregion
74
+ export { PostgresCache, PostgresCacheOptions, cacheTableStatements, postgresCacheDriver };
75
+ //# sourceMappingURL=postgres.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.mts","names":[],"sources":["../src/postgres.ts"],"sourcesContent":[],"mappings":";;;;;UA0BiB,oBAAA;;;;;;;;;;cAaJ,aAAA,YAAyB;;;oBAIb,gBACd;uBAKiB,QAAQ;6BAUF,kBAAkB;uBAgBxB;oBAIH;;;;;;;WAuBT;;;;;;;;;;;;;;;;;;;;;;;cAyCH,qBAAqB;;;;;;;;;;;iBA6DlB,oBAAA,WAA8B"}
@@ -0,0 +1,152 @@
1
+ import pg from "pg";
2
+
3
+ //#region src/postgres.ts
4
+ const DEFAULT_TABLE = "cache";
5
+ var PostgresCache = class {
6
+ table;
7
+ constructor(pool, options = {}) {
8
+ this.pool = pool;
9
+ this.table = options.table ?? DEFAULT_TABLE;
10
+ }
11
+ async get(key) {
12
+ const { rows } = await this.query(`SELECT value FROM ${this.identifier()}
13
+ WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [key]);
14
+ return rows[0]?.value;
15
+ }
16
+ async set(key, value, ttl) {
17
+ await this.query(`INSERT INTO ${this.identifier()} (key, value, expires_at)
18
+ VALUES ($1, $2::jsonb, ${ttl === void 0 ? "NULL" : "now() + ($3 || ' seconds')::interval"})
19
+ ON CONFLICT (key) DO UPDATE
20
+ SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`, ttl === void 0 ? [key, JSON.stringify(value)] : [
21
+ key,
22
+ JSON.stringify(value),
23
+ String(ttl)
24
+ ]);
25
+ }
26
+ async delete(key) {
27
+ await this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);
28
+ }
29
+ async ttl(key) {
30
+ const { rows } = await this.query(`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds
31
+ FROM ${this.identifier()}
32
+ WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`, [key]);
33
+ const row = rows[0];
34
+ if (!row) return 0;
35
+ return row.seconds ?? 0;
36
+ }
37
+ /**
38
+ * Delete every expired entry.
39
+ *
40
+ * Optional: reads already ignore them. Worth running occasionally so the
41
+ * table does not grow without bound in a workload that writes many keys once.
42
+ */
43
+ async sweep() {
44
+ const { rowCount } = await this.query(`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`);
45
+ return rowCount ?? 0;
46
+ }
47
+ async query(sql, values = []) {
48
+ const result = await this.pool.query(sql, values);
49
+ return {
50
+ rows: result.rows,
51
+ rowCount: result.rowCount
52
+ };
53
+ }
54
+ /**
55
+ * The table name as an identifier.
56
+ *
57
+ * Quoted per segment so a schema-qualified name stays two identifiers rather
58
+ * than becoming one with a dot in it. The name comes from configuration
59
+ * rather than from a request, so this is defence rather than sanitisation.
60
+ */
61
+ identifier() {
62
+ return quote(this.table);
63
+ }
64
+ };
65
+ /**
66
+ * The `postgres://` driver.
67
+ *
68
+ * One pool per URL, cached for the life of the process: a cache that opened a
69
+ * connection per call would be slower than the thing it exists to speed up, and
70
+ * a Lambda reusing a warm container should reuse the pool with it.
71
+ *
72
+ * `pg` is imported at the top of this module rather than lazily, because the
73
+ * *module* is the lazy boundary — an app caching in Redis never imports
74
+ * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same
75
+ * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.
76
+ */
77
+ const postgresCacheDriver = {
78
+ scheme: "postgres:",
79
+ create(url) {
80
+ const { connectionString, table } = split(url);
81
+ const existing = pools.get(connectionString);
82
+ const pool = existing ?? new pg.Pool({ connectionString });
83
+ if (!existing) pools.set(connectionString, pool);
84
+ return new PostgresCache(pool, table ? { table } : {});
85
+ }
86
+ };
87
+ /**
88
+ * A cache URL as its two facts: where to connect, and what to read.
89
+ *
90
+ * `table` is removed from the string handed to `pg` rather than left on it,
91
+ * because a Postgres connection string carries libpq parameters and an unknown
92
+ * one is not guaranteed to be ignored — and because the pool should be shared
93
+ * by every cache in the database, which only works if the key does not vary
94
+ * per cache.
95
+ */
96
+ function split(url) {
97
+ try {
98
+ const parsed = new URL(url);
99
+ const table = parsed.searchParams.get("table") ?? void 0;
100
+ if (!table) return { connectionString: url };
101
+ parsed.searchParams.delete("table");
102
+ return {
103
+ connectionString: parsed.toString(),
104
+ table
105
+ };
106
+ } catch {
107
+ return { connectionString: url };
108
+ }
109
+ }
110
+ const pools = /* @__PURE__ */ new Map();
111
+ /**
112
+ * The DDL a Postgres-backed cache needs, for whoever applies DDL.
113
+ *
114
+ * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same
115
+ * statements run in-process from `gkm dev` and from a provisioner inside a VPC,
116
+ * and one implementation is what stops "works locally, fails deployed".
117
+ *
118
+ * Run as the schema's **owner**. The role a handler connects as cannot create a
119
+ * table, which is the point of the split and the reason this is not done lazily.
120
+ */
121
+ function cacheTableStatements(options = {}) {
122
+ const table = options.table ?? DEFAULT_TABLE;
123
+ const [schema, name] = table.includes(".") ? table.split(".") : [void 0, table];
124
+ const qualified = quote(table);
125
+ return [{
126
+ describe: `cache table ${table}`,
127
+ exists: {
128
+ sql: schema ? "SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2" : "SELECT 1 FROM information_schema.tables WHERE table_name = $1",
129
+ values: schema ? [schema, name] : [name]
130
+ },
131
+ sql: `CREATE TABLE ${qualified} (
132
+ key text PRIMARY KEY,
133
+ value jsonb NOT NULL,
134
+ expires_at timestamptz
135
+ )`
136
+ }, {
137
+ describe: `cache expiry index on ${table}`,
138
+ sql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}
139
+ ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`
140
+ }];
141
+ }
142
+ /** A possibly schema-qualified name, quoted per segment. */
143
+ function quote(table) {
144
+ return table.split(".").map((part) => `"${part.replace(/"/g, "\"\"")}"`).join(".");
145
+ }
146
+ function indexName(table) {
147
+ return `"${table.replace(/[^a-zA-Z0-9]/g, "_")}_expires_at_idx"`;
148
+ }
149
+
150
+ //#endregion
151
+ export { PostgresCache, cacheTableStatements, postgresCacheDriver };
152
+ //# sourceMappingURL=postgres.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.mjs","names":["pool: Pool","options: PostgresCacheOptions","key: string","value: T","ttl?: number","sql: string","values: unknown[]","postgresCacheDriver: CacheDriver","url: string","table: string"],"sources":["../src/postgres.ts"],"sourcesContent":["/**\n * A cache that lives in a database you already have.\n *\n * The backend with no infrastructure. A cache is a table; the database is the\n * one the application already declared, so an idle stage costs nothing extra\n * and there is one fewer thing to provision, secure and pay for. It is slower\n * than Redis and that is the trade: for session lookups, rate-limit counters and\n * memoised API responses at ordinary volumes, a primary-key hit on a small table\n * is not the thing that will be slow.\n *\n * **The table is provisioned, not created on first use.** That is the one place\n * this differs from pg-boss, and the reason is the role split: a handler\n * connects as a role that may read and write rows and may not create anything,\n * so a driver issuing `CREATE TABLE` would fail on exactly the deployment where\n * the roles are doing their job. The DDL is exported instead — see\n * {@link cacheTableStatements} — and applied by whatever applies the rest.\n *\n * Reads filter on expiry and delete lazily, so an expired row is never returned\n * even if nothing has swept it; a sweep is an optimisation, not a correctness\n * requirement.\n */\n\nimport pg, { type Pool } from 'pg';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport interface PostgresCacheOptions {\n\t/**\n\t * The table to keep entries in, schema-qualified if it needs to be.\n\t *\n\t * Defaults to `cache`. It resolves against the connection's `search_path`,\n\t * which the role carries — so a tenant's cache lands in the tenant's schema\n\t * without anything here knowing the schema's name.\n\t */\n\ttable?: string;\n}\n\nconst DEFAULT_TABLE = 'cache';\n\nexport class PostgresCache implements Cache {\n\tprivate readonly table: string;\n\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\toptions: PostgresCacheOptions = {},\n\t) {\n\t\tthis.table = options.table ?? DEFAULT_TABLE;\n\t}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst { rows } = await this.query<{ value: T }>(\n\t\t\t`SELECT value FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\treturn rows[0]?.value;\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\t// `now() + interval` computed by the server, not by this process: a\n\t\t// client whose clock is minutes off would otherwise write entries that\n\t\t// expire early or late, and clock skew is not a thing to debug through a\n\t\t// cache.\n\t\tawait this.query(\n\t\t\t`INSERT INTO ${this.identifier()} (key, value, expires_at)\n\t\t\t VALUES ($1, $2::jsonb, ${ttl === undefined ? 'NULL' : \"now() + ($3 || ' seconds')::interval\"})\n\t\t\t ON CONFLICT (key) DO UPDATE\n\t\t\t SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at`,\n\t\t\tttl === undefined\n\t\t\t\t? [key, JSON.stringify(value)]\n\t\t\t\t: [key, JSON.stringify(value), String(ttl)],\n\t\t);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.query(`DELETE FROM ${this.identifier()} WHERE key = $1`, [key]);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst { rows } = await this.query<{ seconds: number | null }>(\n\t\t\t`SELECT EXTRACT(EPOCH FROM (expires_at - now()))::int AS seconds\n\t\t\t FROM ${this.identifier()}\n\t\t\t WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,\n\t\t\t[key],\n\t\t);\n\n\t\tconst row = rows[0];\n\t\tif (!row) return 0;\n\n\t\t// A row with no expiry has no time *left* to report. Zero is what the\n\t\t// interface says a missing key returns, and \"never expires\" is closer to\n\t\t// that than to any number this could invent.\n\t\treturn row.seconds ?? 0;\n\t}\n\n\t/**\n\t * Delete every expired entry.\n\t *\n\t * Optional: reads already ignore them. Worth running occasionally so the\n\t * table does not grow without bound in a workload that writes many keys once.\n\t */\n\tasync sweep(): Promise<number> {\n\t\tconst { rowCount } = await this.query(\n\t\t\t`DELETE FROM ${this.identifier()} WHERE expires_at <= now()`,\n\t\t);\n\n\t\treturn rowCount ?? 0;\n\t}\n\n\tprivate async query<T>(\n\t\tsql: string,\n\t\tvalues: unknown[] = [],\n\t): Promise<{ rows: T[]; rowCount: number | null }> {\n\t\tconst result = await this.pool.query(sql, values);\n\n\t\treturn { rows: result.rows as T[], rowCount: result.rowCount };\n\t}\n\n\t/**\n\t * The table name as an identifier.\n\t *\n\t * Quoted per segment so a schema-qualified name stays two identifiers rather\n\t * than becoming one with a dot in it. The name comes from configuration\n\t * rather than from a request, so this is defence rather than sanitisation.\n\t */\n\tprivate identifier(): string {\n\t\treturn quote(this.table);\n\t}\n}\n\n/**\n * The `postgres://` driver.\n *\n * One pool per URL, cached for the life of the process: a cache that opened a\n * connection per call would be slower than the thing it exists to speed up, and\n * a Lambda reusing a warm container should reuse the pool with it.\n *\n * `pg` is imported at the top of this module rather than lazily, because the\n * *module* is the lazy boundary — an app caching in Redis never imports\n * `@geekmidas/cache/postgres` and so never resolves the driver behind it. Same\n * arrangement `@geekmidas/storage/aws` uses for the AWS SDK.\n */\nexport const postgresCacheDriver: CacheDriver = {\n\tscheme: 'postgres:',\n\tcreate(url) {\n\t\t// The table travels in the URL, the way pg-boss's schema does.\n\t\t//\n\t\t// It has to, because a database-backed cache has no address of its own:\n\t\t// two caches in one database resolve the *same* connection string, so a\n\t\t// client built from the URL alone cannot tell them apart and both would\n\t\t// read and write one table — sharing a keyspace and evicting each other's\n\t\t// keys. The parameter is what makes the address identify the cache.\n\t\tconst { connectionString, table } = split(url);\n\n\t\tconst existing = pools.get(connectionString);\n\t\tconst pool = existing ?? new pg.Pool({ connectionString });\n\t\tif (!existing) pools.set(connectionString, pool);\n\n\t\t// One pool per database, shared by every cache in it — the table is the\n\t\t// client's, not the pool's.\n\t\treturn new PostgresCache(pool, table ? { table } : {});\n\t},\n};\n\n/**\n * A cache URL as its two facts: where to connect, and what to read.\n *\n * `table` is removed from the string handed to `pg` rather than left on it,\n * because a Postgres connection string carries libpq parameters and an unknown\n * one is not guaranteed to be ignored — and because the pool should be shared\n * by every cache in the database, which only works if the key does not vary\n * per cache.\n */\nfunction split(url: string): { connectionString: string; table?: string } {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tconst table = parsed.searchParams.get('table') ?? undefined;\n\n\t\tif (!table) return { connectionString: url };\n\n\t\tparsed.searchParams.delete('table');\n\n\t\treturn { connectionString: parsed.toString(), table };\n\t} catch {\n\t\t// Not a URL `URL` can parse. The driver's job is not to validate one, so\n\t\t// this hands it to `pg` unchanged and lets that failure be the one\n\t\t// reported.\n\t\treturn { connectionString: url };\n\t}\n}\n\nconst pools = new Map<string, Pool>();\n\n/**\n * The DDL a Postgres-backed cache needs, for whoever applies DDL.\n *\n * Generation only, in the shape `@geekmidas/db/pg/roles` uses — the same\n * statements run in-process from `gkm dev` and from a provisioner inside a VPC,\n * and one implementation is what stops \"works locally, fails deployed\".\n *\n * Run as the schema's **owner**. The role a handler connects as cannot create a\n * table, which is the point of the split and the reason this is not done lazily.\n */\nexport function cacheTableStatements(options: PostgresCacheOptions = {}): {\n\tdescribe: string;\n\texists?: { sql: string; values: unknown[] };\n\tsql: string;\n}[] {\n\tconst table = options.table ?? DEFAULT_TABLE;\n\tconst [schema, name] = table.includes('.')\n\t\t? (table.split('.') as [string, string])\n\t\t: [undefined, table];\n\tconst qualified = quote(table);\n\n\treturn [\n\t\t{\n\t\t\tdescribe: `cache table ${table}`,\n\t\t\texists: {\n\t\t\t\tsql: schema\n\t\t\t\t\t? 'SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2'\n\t\t\t\t\t: 'SELECT 1 FROM information_schema.tables WHERE table_name = $1',\n\t\t\t\tvalues: schema ? [schema, name] : [name],\n\t\t\t},\n\t\t\tsql: `CREATE TABLE ${qualified} (\n\t\t\t\tkey text PRIMARY KEY,\n\t\t\t\tvalue jsonb NOT NULL,\n\t\t\t\texpires_at timestamptz\n\t\t\t)`,\n\t\t},\n\t\t{\n\t\t\t// Only the expiring rows: a partial index stays small in a cache whose\n\t\t\t// entries mostly never expire, and the sweep only ever looks at those.\n\t\t\tdescribe: `cache expiry index on ${table}`,\n\t\t\tsql: `CREATE INDEX IF NOT EXISTS ${indexName(table)}\n\t\t\t ON ${qualified} (expires_at) WHERE expires_at IS NOT NULL`,\n\t\t},\n\t];\n}\n\n/** A possibly schema-qualified name, quoted per segment. */\nfunction quote(table: string): string {\n\treturn table\n\t\t.split('.')\n\t\t.map((part) => `\"${part.replace(/\"/g, '\"\"')}\"`)\n\t\t.join('.');\n}\n\nfunction indexName(table: string): string {\n\treturn `\"${table.replace(/[^a-zA-Z0-9]/g, '_')}_expires_at_idx\"`;\n}\n"],"mappings":"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"}
package/dist/redis.cjs ADDED
@@ -0,0 +1,70 @@
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const ioredis = require_chunk.__toESM(require("ioredis"));
3
+
4
+ //#region src/redis.ts
5
+ var RedisCache = class {
6
+ constructor(client) {
7
+ this.client = client;
8
+ }
9
+ async get(key) {
10
+ const value = await this.client.get(key);
11
+ if (value === null) return void 0;
12
+ try {
13
+ return JSON.parse(value);
14
+ } catch {
15
+ return value;
16
+ }
17
+ }
18
+ async set(key, value, ttl) {
19
+ const encoded = JSON.stringify(value);
20
+ if (ttl === void 0) {
21
+ await this.client.set(key, encoded);
22
+ return;
23
+ }
24
+ await this.client.set(key, encoded, "EX", ttl);
25
+ }
26
+ async delete(key) {
27
+ await this.client.del(key);
28
+ }
29
+ async ttl(key) {
30
+ const seconds = await this.client.ttl(key);
31
+ return seconds < 0 ? 0 : seconds;
32
+ }
33
+ };
34
+ /**
35
+ * The `redis://` and `rediss://` driver.
36
+ *
37
+ * One client per URL for the life of the process — a Redis connection is a
38
+ * socket, and opening one per cache call is the thing that makes people
39
+ * conclude a cache is not worth having.
40
+ *
41
+ * `ioredis` is imported at the top of this module because the *module* is the
42
+ * lazy boundary: an app caching in Postgres never imports
43
+ * `@geekmidas/cache/redis`, and so never resolves it.
44
+ */
45
+ const redisCacheDriver = {
46
+ scheme: "redis:",
47
+ create: (url) => new RedisCache(clientFor(url))
48
+ };
49
+ /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
50
+ const redissCacheDriver = {
51
+ scheme: "rediss:",
52
+ create: (url) => new RedisCache(clientFor(url))
53
+ };
54
+ const clients = /* @__PURE__ */ new Map();
55
+ function clientFor(url) {
56
+ const existing = clients.get(url);
57
+ if (existing) return existing;
58
+ const client = new ioredis.Redis(url, {
59
+ maxRetriesPerRequest: 2,
60
+ enableOfflineQueue: false
61
+ });
62
+ clients.set(url, client);
63
+ return client;
64
+ }
65
+
66
+ //#endregion
67
+ exports.RedisCache = RedisCache;
68
+ exports.redisCacheDriver = redisCacheDriver;
69
+ exports.redissCacheDriver = redissCacheDriver;
70
+ //# sourceMappingURL=redis.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.cjs","names":["client: Redis","key: string","value: T","ttl?: number","redisCacheDriver: CacheDriver","redissCacheDriver: CacheDriver","url: string","Redis"],"sources":["../src/redis.ts"],"sourcesContent":["/**\n * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.\n *\n * The sibling of the Upstash client rather than a replacement for it. Upstash\n * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and\n * no connection pool; this speaks the wire protocol, which is what ElastiCache\n * offers and what a container next to your app is cheapest on.\n *\n * Choosing one is a deployment decision, and the local target follows it: pick\n * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP\n * proxy in front of it. Either way dev and prod speak the same protocol, which\n * is the property that matters — a cache that behaves differently in the two\n * places is worse than a slower one.\n */\n\nimport { Redis } from 'ioredis';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport class RedisCache implements Cache {\n\tconstructor(private readonly client: Redis) {}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst value = await this.client.get(key);\n\t\tif (value === null) return undefined;\n\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\t// Written by something that did not go through `set`. Returning the\n\t\t\t// raw string is more useful than throwing on a value somebody put\n\t\t\t// there on purpose.\n\t\t\treturn value as unknown as T;\n\t\t}\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\tconst encoded = JSON.stringify(value);\n\n\t\tif (ttl === undefined) {\n\t\t\tawait this.client.set(key, encoded);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.client.set(key, encoded, 'EX', ttl);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.client.del(key);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst seconds = await this.client.ttl(key);\n\n\t\t// Redis reports -2 for a key that does not exist and -1 for one with no\n\t\t// expiry. The interface says zero for a missing key, and \"never expires\"\n\t\t// has no time left to report either — so both become zero rather than\n\t\t// leaking sentinel values a caller would have to know about.\n\t\treturn seconds < 0 ? 0 : seconds;\n\t}\n}\n\n/**\n * The `redis://` and `rediss://` driver.\n *\n * One client per URL for the life of the process — a Redis connection is a\n * socket, and opening one per cache call is the thing that makes people\n * conclude a cache is not worth having.\n *\n * `ioredis` is imported at the top of this module because the *module* is the\n * lazy boundary: an app caching in Postgres never imports\n * `@geekmidas/cache/redis`, and so never resolves it.\n */\nexport const redisCacheDriver: CacheDriver = {\n\tscheme: 'redis:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\n/** The TLS form. ElastiCache Serverless requires it; the same client handles both. */\nexport const redissCacheDriver: CacheDriver = {\n\tscheme: 'rediss:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\nconst clients = new Map<string, Redis>();\n\nfunction clientFor(url: string): Redis {\n\tconst existing = clients.get(url);\n\tif (existing) return existing;\n\n\tconst client = new Redis(url, {\n\t\t// A cache miss is recoverable and a hung request is not. Failing fast and\n\t\t// letting the caller treat it as a miss is the behaviour a cache should\n\t\t// have; retrying forever turns a degraded cache into a degraded app.\n\t\tmaxRetriesPerRequest: 2,\n\t\tenableOfflineQueue: false,\n\t});\n\n\tclients.set(url, client);\n\n\treturn client;\n}\n"],"mappings":";;;;AAmBA,IAAa,aAAb,MAAyC;CACxC,YAA6BA,QAAe;EAAf;CAAiB;CAE9C,MAAM,IAAOC,KAAqC;EACjD,MAAM,QAAQ,MAAM,KAAK,OAAO,IAAI,IAAI;AACxC,MAAI,UAAU,KAAM;AAEpB,MAAI;AACH,UAAO,KAAK,MAAM,MAAM;EACxB,QAAO;AAIP,UAAO;EACP;CACD;CAED,MAAM,IAAOA,KAAaC,OAAUC,KAA6B;EAChE,MAAM,UAAU,KAAK,UAAU,MAAM;AAErC,MAAI,gBAAmB;AACtB,SAAM,KAAK,OAAO,IAAI,KAAK,QAAQ;AACnC;EACA;AAED,QAAM,KAAK,OAAO,IAAI,KAAK,SAAS,MAAM,IAAI;CAC9C;CAED,MAAM,OAAOF,KAA4B;AACxC,QAAM,KAAK,OAAO,IAAI,IAAI;CAC1B;CAED,MAAM,IAAIA,KAA8B;EACvC,MAAM,UAAU,MAAM,KAAK,OAAO,IAAI,IAAI;AAM1C,SAAO,UAAU,IAAI,IAAI;CACzB;AACD;;;;;;;;;;;;AAaD,MAAaG,mBAAgC;CAC5C,QAAQ;CACR,QAAQ,CAAC,QAAQ,IAAI,WAAW,UAAU,IAAI;AAC9C;;AAGD,MAAaC,oBAAiC;CAC7C,QAAQ;CACR,QAAQ,CAAC,QAAQ,IAAI,WAAW,UAAU,IAAI;AAC9C;AAED,MAAM,0BAAU,IAAI;AAEpB,SAAS,UAAUC,KAAoB;CACtC,MAAM,WAAW,QAAQ,IAAI,IAAI;AACjC,KAAI,SAAU,QAAO;CAErB,MAAM,SAAS,IAAIC,cAAM,KAAK;EAI7B,sBAAsB;EACtB,oBAAoB;CACpB;AAED,SAAQ,IAAI,KAAK,OAAO;AAExB,QAAO;AACP"}
@@ -0,0 +1,31 @@
1
+ import { Cache, CacheDriver } from "./index-CNQ50bVk.cjs";
2
+ import { Redis } from "ioredis";
3
+
4
+ //#region src/redis.d.ts
5
+
6
+ declare class RedisCache implements Cache {
7
+ private readonly client;
8
+ constructor(client: Redis);
9
+ get<T>(key: string): Promise<T | undefined>;
10
+ set<T>(key: string, value: T, ttl?: number): Promise<void>;
11
+ delete(key: string): Promise<void>;
12
+ ttl(key: string): Promise<number>;
13
+ }
14
+ /**
15
+ * The `redis://` and `rediss://` driver.
16
+ *
17
+ * One client per URL for the life of the process — a Redis connection is a
18
+ * socket, and opening one per cache call is the thing that makes people
19
+ * conclude a cache is not worth having.
20
+ *
21
+ * `ioredis` is imported at the top of this module because the *module* is the
22
+ * lazy boundary: an app caching in Postgres never imports
23
+ * `@geekmidas/cache/redis`, and so never resolves it.
24
+ */
25
+ declare const redisCacheDriver: CacheDriver;
26
+ /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
27
+ declare const redissCacheDriver: CacheDriver;
28
+ //# sourceMappingURL=redis.d.ts.map
29
+ //#endregion
30
+ export { RedisCache, redisCacheDriver, redissCacheDriver };
31
+ //# sourceMappingURL=redis.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.d.cts","names":[],"sources":["../src/redis.ts"],"sourcesContent":[],"mappings":";;;;;cAmBa,UAAA,YAAsB;;sBACG;uBAEV,QAAQ;6BAcF,kBAAkB;uBAWxB;oBAIH;;;;;;;;;;;;;cAsBZ,kBAAkB;;cAMlB,mBAAmB"}
@@ -0,0 +1,31 @@
1
+ import { Cache, CacheDriver } from "./index-1sNRIo6N.mjs";
2
+ import { Redis } from "ioredis";
3
+
4
+ //#region src/redis.d.ts
5
+
6
+ declare class RedisCache implements Cache {
7
+ private readonly client;
8
+ constructor(client: Redis);
9
+ get<T>(key: string): Promise<T | undefined>;
10
+ set<T>(key: string, value: T, ttl?: number): Promise<void>;
11
+ delete(key: string): Promise<void>;
12
+ ttl(key: string): Promise<number>;
13
+ }
14
+ /**
15
+ * The `redis://` and `rediss://` driver.
16
+ *
17
+ * One client per URL for the life of the process — a Redis connection is a
18
+ * socket, and opening one per cache call is the thing that makes people
19
+ * conclude a cache is not worth having.
20
+ *
21
+ * `ioredis` is imported at the top of this module because the *module* is the
22
+ * lazy boundary: an app caching in Postgres never imports
23
+ * `@geekmidas/cache/redis`, and so never resolves it.
24
+ */
25
+ declare const redisCacheDriver: CacheDriver;
26
+ /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
27
+ declare const redissCacheDriver: CacheDriver;
28
+ //# sourceMappingURL=redis.d.ts.map
29
+ //#endregion
30
+ export { RedisCache, redisCacheDriver, redissCacheDriver };
31
+ //# sourceMappingURL=redis.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.d.mts","names":[],"sources":["../src/redis.ts"],"sourcesContent":[],"mappings":";;;;;cAmBa,UAAA,YAAsB;;sBACG;uBAEV,QAAQ;6BAcF,kBAAkB;uBAWxB;oBAIH;;;;;;;;;;;;;cAsBZ,kBAAkB;;cAMlB,mBAAmB"}
package/dist/redis.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import { Redis } from "ioredis";
2
+
3
+ //#region src/redis.ts
4
+ var RedisCache = class {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ async get(key) {
9
+ const value = await this.client.get(key);
10
+ if (value === null) return void 0;
11
+ try {
12
+ return JSON.parse(value);
13
+ } catch {
14
+ return value;
15
+ }
16
+ }
17
+ async set(key, value, ttl) {
18
+ const encoded = JSON.stringify(value);
19
+ if (ttl === void 0) {
20
+ await this.client.set(key, encoded);
21
+ return;
22
+ }
23
+ await this.client.set(key, encoded, "EX", ttl);
24
+ }
25
+ async delete(key) {
26
+ await this.client.del(key);
27
+ }
28
+ async ttl(key) {
29
+ const seconds = await this.client.ttl(key);
30
+ return seconds < 0 ? 0 : seconds;
31
+ }
32
+ };
33
+ /**
34
+ * The `redis://` and `rediss://` driver.
35
+ *
36
+ * One client per URL for the life of the process — a Redis connection is a
37
+ * socket, and opening one per cache call is the thing that makes people
38
+ * conclude a cache is not worth having.
39
+ *
40
+ * `ioredis` is imported at the top of this module because the *module* is the
41
+ * lazy boundary: an app caching in Postgres never imports
42
+ * `@geekmidas/cache/redis`, and so never resolves it.
43
+ */
44
+ const redisCacheDriver = {
45
+ scheme: "redis:",
46
+ create: (url) => new RedisCache(clientFor(url))
47
+ };
48
+ /** The TLS form. ElastiCache Serverless requires it; the same client handles both. */
49
+ const redissCacheDriver = {
50
+ scheme: "rediss:",
51
+ create: (url) => new RedisCache(clientFor(url))
52
+ };
53
+ const clients = /* @__PURE__ */ new Map();
54
+ function clientFor(url) {
55
+ const existing = clients.get(url);
56
+ if (existing) return existing;
57
+ const client = new Redis(url, {
58
+ maxRetriesPerRequest: 2,
59
+ enableOfflineQueue: false
60
+ });
61
+ clients.set(url, client);
62
+ return client;
63
+ }
64
+
65
+ //#endregion
66
+ export { RedisCache, redisCacheDriver, redissCacheDriver };
67
+ //# sourceMappingURL=redis.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.mjs","names":["client: Redis","key: string","value: T","ttl?: number","redisCacheDriver: CacheDriver","redissCacheDriver: CacheDriver","url: string"],"sources":["../src/redis.ts"],"sourcesContent":["/**\n * A cache over the Redis wire protocol — ElastiCache, Valkey, or a Redis you run.\n *\n * The sibling of the Upstash client rather than a replacement for it. Upstash\n * speaks HTTP, which is what makes it reachable from a Lambda with no VPC and\n * no connection pool; this speaks the wire protocol, which is what ElastiCache\n * offers and what a container next to your app is cheapest on.\n *\n * Choosing one is a deployment decision, and the local target follows it: pick\n * `elasticache` and dev runs plain Redis, pick `upstash` and dev runs the HTTP\n * proxy in front of it. Either way dev and prod speak the same protocol, which\n * is the property that matters — a cache that behaves differently in the two\n * places is worse than a slower one.\n */\n\nimport { Redis } from 'ioredis';\nimport type { Cache } from './index';\nimport type { CacheDriver } from './registry';\n\nexport class RedisCache implements Cache {\n\tconstructor(private readonly client: Redis) {}\n\n\tasync get<T>(key: string): Promise<T | undefined> {\n\t\tconst value = await this.client.get(key);\n\t\tif (value === null) return undefined;\n\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\t// Written by something that did not go through `set`. Returning the\n\t\t\t// raw string is more useful than throwing on a value somebody put\n\t\t\t// there on purpose.\n\t\t\treturn value as unknown as T;\n\t\t}\n\t}\n\n\tasync set<T>(key: string, value: T, ttl?: number): Promise<void> {\n\t\tconst encoded = JSON.stringify(value);\n\n\t\tif (ttl === undefined) {\n\t\t\tawait this.client.set(key, encoded);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.client.set(key, encoded, 'EX', ttl);\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tawait this.client.del(key);\n\t}\n\n\tasync ttl(key: string): Promise<number> {\n\t\tconst seconds = await this.client.ttl(key);\n\n\t\t// Redis reports -2 for a key that does not exist and -1 for one with no\n\t\t// expiry. The interface says zero for a missing key, and \"never expires\"\n\t\t// has no time left to report either — so both become zero rather than\n\t\t// leaking sentinel values a caller would have to know about.\n\t\treturn seconds < 0 ? 0 : seconds;\n\t}\n}\n\n/**\n * The `redis://` and `rediss://` driver.\n *\n * One client per URL for the life of the process — a Redis connection is a\n * socket, and opening one per cache call is the thing that makes people\n * conclude a cache is not worth having.\n *\n * `ioredis` is imported at the top of this module because the *module* is the\n * lazy boundary: an app caching in Postgres never imports\n * `@geekmidas/cache/redis`, and so never resolves it.\n */\nexport const redisCacheDriver: CacheDriver = {\n\tscheme: 'redis:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\n/** The TLS form. ElastiCache Serverless requires it; the same client handles both. */\nexport const redissCacheDriver: CacheDriver = {\n\tscheme: 'rediss:',\n\tcreate: (url) => new RedisCache(clientFor(url)),\n};\n\nconst clients = new Map<string, Redis>();\n\nfunction clientFor(url: string): Redis {\n\tconst existing = clients.get(url);\n\tif (existing) return existing;\n\n\tconst client = new Redis(url, {\n\t\t// A cache miss is recoverable and a hung request is not. Failing fast and\n\t\t// letting the caller treat it as a miss is the behaviour a cache should\n\t\t// have; retrying forever turns a degraded cache into a degraded app.\n\t\tmaxRetriesPerRequest: 2,\n\t\tenableOfflineQueue: false,\n\t});\n\n\tclients.set(url, client);\n\n\treturn client;\n}\n"],"mappings":";;;AAmBA,IAAa,aAAb,MAAyC;CACxC,YAA6BA,QAAe;EAAf;CAAiB;CAE9C,MAAM,IAAOC,KAAqC;EACjD,MAAM,QAAQ,MAAM,KAAK,OAAO,IAAI,IAAI;AACxC,MAAI,UAAU,KAAM;AAEpB,MAAI;AACH,UAAO,KAAK,MAAM,MAAM;EACxB,QAAO;AAIP,UAAO;EACP;CACD;CAED,MAAM,IAAOA,KAAaC,OAAUC,KAA6B;EAChE,MAAM,UAAU,KAAK,UAAU,MAAM;AAErC,MAAI,gBAAmB;AACtB,SAAM,KAAK,OAAO,IAAI,KAAK,QAAQ;AACnC;EACA;AAED,QAAM,KAAK,OAAO,IAAI,KAAK,SAAS,MAAM,IAAI;CAC9C;CAED,MAAM,OAAOF,KAA4B;AACxC,QAAM,KAAK,OAAO,IAAI,IAAI;CAC1B;CAED,MAAM,IAAIA,KAA8B;EACvC,MAAM,UAAU,MAAM,KAAK,OAAO,IAAI,IAAI;AAM1C,SAAO,UAAU,IAAI,IAAI;CACzB;AACD;;;;;;;;;;;;AAaD,MAAaG,mBAAgC;CAC5C,QAAQ;CACR,QAAQ,CAAC,QAAQ,IAAI,WAAW,UAAU,IAAI;AAC9C;;AAGD,MAAaC,oBAAiC;CAC7C,QAAQ;CACR,QAAQ,CAAC,QAAQ,IAAI,WAAW,UAAU,IAAI;AAC9C;AAED,MAAM,0BAAU,IAAI;AAEpB,SAAS,UAAUC,KAAoB;CACtC,MAAM,WAAW,QAAQ,IAAI,IAAI;AACjC,KAAI,SAAU,QAAO;CAErB,MAAM,SAAS,IAAI,MAAM,KAAK;EAI7B,sBAAsB;EACtB,oBAAoB;CACpB;AAED,SAAQ,IAAI,KAAK,OAAO;AAExB,QAAO;AACP"}
@@ -0,0 +1,65 @@
1
+
2
+ //#region src/registry.ts
3
+ const drivers = /* @__PURE__ */ new Map();
4
+ /** Make a driver available to {@link createCacheClient}. Idempotent. */
5
+ function registerCacheDriver(driver) {
6
+ drivers.set(driver.scheme, driver);
7
+ }
8
+ /** Which schemes are currently registered — the useful half of a failure. */
9
+ function registeredCacheSchemes() {
10
+ return [...drivers.keys()].sort();
11
+ }
12
+ /**
13
+ * Build a client for a URL.
14
+ *
15
+ * @throws {UnregisteredCacheScheme} when no driver handles the scheme, which in
16
+ * practice means the entry point registered a different one — the backend and
17
+ * the build disagreeing, caught at the first cache call rather than never.
18
+ */
19
+ function createCacheClient(url) {
20
+ const scheme = schemeOf(url);
21
+ const driver = drivers.get(scheme);
22
+ if (!driver) throw new UnregisteredCacheScheme(url, scheme, registeredCacheSchemes());
23
+ return driver.create(url);
24
+ }
25
+ /** No driver handles the scheme in a cache URL. */
26
+ var UnregisteredCacheScheme = class extends Error {
27
+ constructor(url, scheme, registered) {
28
+ super(`No cache driver handles '${scheme}'. ` + (registered.length ? `Registered: ${registered.join(", ")}.` : "Nothing is registered.") + " The scheme comes from the backend the target provisioned, so this is usually a build that registered a different one.");
29
+ this.url = url;
30
+ this.scheme = scheme;
31
+ this.registered = registered;
32
+ this.name = "UnregisteredCacheScheme";
33
+ }
34
+ };
35
+ function schemeOf(url) {
36
+ const separator = url.indexOf(":");
37
+ return separator === -1 ? "" : url.slice(0, separator + 1);
38
+ }
39
+
40
+ //#endregion
41
+ Object.defineProperty(exports, 'UnregisteredCacheScheme', {
42
+ enumerable: true,
43
+ get: function () {
44
+ return UnregisteredCacheScheme;
45
+ }
46
+ });
47
+ Object.defineProperty(exports, 'createCacheClient', {
48
+ enumerable: true,
49
+ get: function () {
50
+ return createCacheClient;
51
+ }
52
+ });
53
+ Object.defineProperty(exports, 'registerCacheDriver', {
54
+ enumerable: true,
55
+ get: function () {
56
+ return registerCacheDriver;
57
+ }
58
+ });
59
+ Object.defineProperty(exports, 'registeredCacheSchemes', {
60
+ enumerable: true,
61
+ get: function () {
62
+ return registeredCacheSchemes;
63
+ }
64
+ });
65
+ //# sourceMappingURL=registry-CITg73zW.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry-CITg73zW.cjs","names":["driver: CacheDriver","url: string","scheme: string","registered: readonly string[]"],"sources":["../src/registry.ts"],"sourcesContent":["/**\n * Cache drivers, keyed by URL scheme.\n *\n * The same shape `@geekmidas/storage` uses, for the same reason: a construct is\n * handed one URL and the scheme in it picks the client. That is what lets the\n * *backend* be a deployment choice rather than an application one — an app\n * caching in Postgres and an app caching in Upstash are the same code.\n *\n * Registration is explicit rather than an import side effect, because a\n * side-effecting module is exactly what a bundler is entitled to drop — and\n * because an app that caches in Postgres should never resolve a Redis client.\n */\n\nimport type { Cache } from './index';\n\n/** What a driver has to supply: a scheme it answers to, and a client for a URL. */\nexport interface CacheDriver {\n\t/** Including the colon, as `URL.protocol` reports it — `redis:`, `https:`. */\n\tscheme: string;\n\tcreate(url: string): Cache;\n}\n\nconst drivers = new Map<string, CacheDriver>();\n\n/** Make a driver available to {@link createCacheClient}. Idempotent. */\nexport function registerCacheDriver(driver: CacheDriver): void {\n\tdrivers.set(driver.scheme, driver);\n}\n\n/** Which schemes are currently registered — the useful half of a failure. */\nexport function registeredCacheSchemes(): string[] {\n\treturn [...drivers.keys()].sort();\n}\n\n/**\n * Build a client for a URL.\n *\n * @throws {UnregisteredCacheScheme} when no driver handles the scheme, which in\n * practice means the entry point registered a different one — the backend and\n * the build disagreeing, caught at the first cache call rather than never.\n */\nexport function createCacheClient(url: string): Cache {\n\tconst scheme = schemeOf(url);\n\tconst driver = drivers.get(scheme);\n\n\tif (!driver) {\n\t\tthrow new UnregisteredCacheScheme(url, scheme, registeredCacheSchemes());\n\t}\n\n\treturn driver.create(url);\n}\n\n/** No driver handles the scheme in a cache URL. */\nexport class UnregisteredCacheScheme extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly scheme: string,\n\t\treadonly registered: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`No cache driver handles '${scheme}'. ` +\n\t\t\t\t(registered.length\n\t\t\t\t\t? `Registered: ${registered.join(', ')}.`\n\t\t\t\t\t: 'Nothing is registered.') +\n\t\t\t\t' The scheme comes from the backend the target provisioned, so this ' +\n\t\t\t\t'is usually a build that registered a different one.',\n\t\t);\n\t\tthis.name = 'UnregisteredCacheScheme';\n\t}\n}\n\nfunction schemeOf(url: string): string {\n\tconst separator = url.indexOf(':');\n\treturn separator === -1 ? '' : url.slice(0, separator + 1);\n}\n"],"mappings":";;AAsBA,MAAM,0BAAU,IAAI;;AAGpB,SAAgB,oBAAoBA,QAA2B;AAC9D,SAAQ,IAAI,OAAO,QAAQ,OAAO;AAClC;;AAGD,SAAgB,yBAAmC;AAClD,QAAO,CAAC,GAAG,QAAQ,MAAM,AAAC,EAAC,MAAM;AACjC;;;;;;;;AASD,SAAgB,kBAAkBC,KAAoB;CACrD,MAAM,SAAS,SAAS,IAAI;CAC5B,MAAM,SAAS,QAAQ,IAAI,OAAO;AAElC,MAAK,OACJ,OAAM,IAAI,wBAAwB,KAAK,QAAQ,wBAAwB;AAGxE,QAAO,OAAO,OAAO,IAAI;AACzB;;AAGD,IAAa,0BAAb,cAA6C,MAAM;CAClD,YACUA,KACAC,QACAC,YACR;AACD,SACE,2BAA2B,OAAO,QACjC,WAAW,UACR,cAAc,WAAW,KAAK,KAAK,CAAC,KACrC,4BACH,yHAED;EAXQ;EACA;EACA;AAUT,OAAK,OAAO;CACZ;AACD;AAED,SAAS,SAASF,KAAqB;CACtC,MAAM,YAAY,IAAI,QAAQ,IAAI;AAClC,QAAO,cAAc,KAAK,KAAK,IAAI,MAAM,GAAG,YAAY,EAAE;AAC1D"}