@pluv/persistence-cloudflare-transactional-storage 5.0.0 → 5.0.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.
- package/CHANGELOG.md +7 -0
- package/package.json +9 -9
- package/.turbo/turbo-build.log +0 -16
- package/dist/index.d.mts +0 -30
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -240
- package/dist/index.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pluv/persistence-cloudflare-transactional-storage",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.1",
|
|
4
4
|
"description": "@pluv/io crdt storage persistence for cloudflare via transactional storage",
|
|
5
5
|
"author": {
|
|
6
6
|
"email": "david@pluv.io",
|
|
@@ -20,16 +20,16 @@
|
|
|
20
20
|
"access": "public"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@pluv/io": "^5.0.
|
|
24
|
-
"@pluv/types": "^5.0.
|
|
23
|
+
"@pluv/io": "^5.0.1",
|
|
24
|
+
"@pluv/types": "^5.0.1"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@cloudflare/workers-types": "^
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
27
|
+
"@cloudflare/workers-types": "^5.20260823.1",
|
|
28
|
+
"@pluv/tsconfig": "^5.0.1",
|
|
29
|
+
"eslint": "^10.9.0",
|
|
30
|
+
"eslint-config-pluv": "^5.0.1",
|
|
31
|
+
"tsdown": "0.22.14",
|
|
32
|
+
"typescript": "^5.9.3"
|
|
33
33
|
},
|
|
34
34
|
"exports": {
|
|
35
35
|
".": "./dist/index.mjs",
|
package/.turbo/turbo-build.log
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
$ tsdown
|
|
2
|
-
[34mℹ[39m [34mtsdown v0.22.3[39m powered by [38;2;255;126;23mrolldown v1.1.2[39m
|
|
3
|
-
[34mℹ[39m config file: [4m/home/runner/work/pluv/pluv/packages/persistence-cloudflare-transactional-storage/tsdown.config.ts[24m
|
|
4
|
-
[34mℹ[39m entry: [34msrc/index.ts[39m
|
|
5
|
-
[34mℹ[39m target: [34mesnext[39m
|
|
6
|
-
[34mℹ[39m tsconfig: [34mtsconfig.json[39m
|
|
7
|
-
|
|
8
|
-
[43m WARN [49m `external` is deprecated. Use `deps.neverBundle` instead.
|
|
9
|
-
|
|
10
|
-
[34mℹ[39m Build start
|
|
11
|
-
[34mℹ[39m [2mdist/[22m[1mindex.mjs[22m [2m 8.22 kB[22m [2m│ gzip: 1.93 kB[22m
|
|
12
|
-
[34mℹ[39m [2mdist/[22mindex.mjs.map [2m17.34 kB[22m [2m│ gzip: 3.91 kB[22m
|
|
13
|
-
[34mℹ[39m [2mdist/[22mindex.d.mts.map [2m 0.73 kB[22m [2m│ gzip: 0.37 kB[22m
|
|
14
|
-
[34mℹ[39m [2mdist/[22m[32m[1mindex.d.mts[22m[39m [2m 1.32 kB[22m [2m│ gzip: 0.46 kB[22m
|
|
15
|
-
[34mℹ[39m 4 files, total: 27.61 kB
|
|
16
|
-
[32m✔[39m Build complete in [32m2279ms[39m
|
package/dist/index.d.mts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { AbstractPersistence } from "@pluv/io";
|
|
2
|
-
import { JsonObject } from "@pluv/types";
|
|
3
|
-
|
|
4
|
-
//#region src/PersistenceCloudflareTransactionalStorage.d.ts
|
|
5
|
-
interface PersistenceCloudflareTransactionalStorageConfig {
|
|
6
|
-
mode: "kv" | "sqlite";
|
|
7
|
-
}
|
|
8
|
-
declare class PersistenceCloudflareTransactionalStorage extends AbstractPersistence {
|
|
9
|
-
private _mode;
|
|
10
|
-
private _state;
|
|
11
|
-
private _initialized;
|
|
12
|
-
constructor(config: PersistenceCloudflareTransactionalStorageConfig);
|
|
13
|
-
addUser(room: string, connectionId: string, user: JsonObject | null): Promise<void>;
|
|
14
|
-
deleteStorageState(room: string): Promise<void>;
|
|
15
|
-
deleteUser(room: string, connectionId: string): Promise<void>;
|
|
16
|
-
deleteUsers(room: string): Promise<void>;
|
|
17
|
-
getStorageState(room: string): Promise<string | null>;
|
|
18
|
-
getUser(room: string, connectionId: string): Promise<JsonObject | null>;
|
|
19
|
-
getUsers(room: string): Promise<Map<[connectionId: string][0], JsonObject | null>>;
|
|
20
|
-
getUsersSize(room: string): Promise<number>;
|
|
21
|
-
initialize(roomContext: {
|
|
22
|
-
state: DurableObjectState;
|
|
23
|
-
}): typeof this;
|
|
24
|
-
setStorageState(room: string, state: string): Promise<void>;
|
|
25
|
-
private _getStorageKey;
|
|
26
|
-
private _getUserKey;
|
|
27
|
-
}
|
|
28
|
-
//#endregion
|
|
29
|
-
export { PersistenceCloudflareTransactionalStorage, type PersistenceCloudflareTransactionalStorageConfig };
|
|
30
|
-
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/PersistenceCloudflareTransactionalStorage.ts"],"mappings":";;;;UAiBiB,+CAAA;EACb,IAAI;AAAA;AAAA,cAEK,yCAAA,SAAkD,mBAAA;EAAA,QACnD,KAAA;EAAA,QACA,MAAA;EAAA,QACA,YAAA;cAEI,MAAA,EAAQ,+CAAA;EASP,OAAA,CACT,IAAA,UACA,YAAA,UACA,IAAA,EAAM,UAAA,UACP,OAAA;EAkCU,kBAAA,CAAmB,IAAA,WAAe,OAAA;EAoBlC,UAAA,CAAW,IAAA,UAAc,YAAA,WAAuB,OAAA;EAuBhD,WAAA,CAAY,IAAA,WAAe,OAAA;EAqC3B,eAAA,CAAgB,IAAA,WAAe,OAAA;EA6B/B,OAAA,CAAQ,IAAA,UAAc,YAAA,WAAuB,OAAA,CAAQ,UAAA;EAmCrD,QAAA,CACT,IAAA,WACD,OAAA,CAAQ,GAAA,EAAK,YAAA,cAA0B,UAAA;EAwC7B,YAAA,CAAa,IAAA,WAAe,OAAA;EAgClC,UAAA,CAAW,WAAA;IAAe,KAAA,EAAO,kBAAA;EAAA;EA8B3B,eAAA,CAAgB,IAAA,UAAc,KAAA,WAAgB,OAAA;EAAA,QA+CnD,cAAA;EAAA,QAQA,WAAA;AAAA"}
|
package/dist/index.mjs
DELETED
|
@@ -1,240 +0,0 @@
|
|
|
1
|
-
import { AbstractPersistence } from "@pluv/io";
|
|
2
|
-
//#region src/utils/castNumber.ts
|
|
3
|
-
const castNumber = (value) => {
|
|
4
|
-
return typeof value === "number" ? value : typeof value === "string" ? Number.parseInt(value, 10) : Number(value);
|
|
5
|
-
};
|
|
6
|
-
//#endregion
|
|
7
|
-
//#region src/utils/partitionByLength.ts
|
|
8
|
-
const partitionByLength = (arr, length) => {
|
|
9
|
-
if (!arr.length) return [];
|
|
10
|
-
return [arr.slice(0, length), ...partitionByLength(arr.slice(length), length)];
|
|
11
|
-
};
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/utils/sql.ts
|
|
14
|
-
const sql = (strings, ...values) => {
|
|
15
|
-
return strings.reduce((result, str, i) => {
|
|
16
|
-
return result + str.replace(/(\n[ \t]*)+/g, " ") + (i < values.length ? values[i] : "");
|
|
17
|
-
}, "").trim();
|
|
18
|
-
};
|
|
19
|
-
//#endregion
|
|
20
|
-
//#region src/PersistenceCloudflareTransactionalStorage.ts
|
|
21
|
-
/**
|
|
22
|
-
* !HACK
|
|
23
|
-
* @description The max amount of keys a Cloudflare transactional storage may delete at once
|
|
24
|
-
* @see https://developers.cloudflare.com/durable-objects/api/transactional-storage-api/#delete
|
|
25
|
-
* @date July 8, 2024
|
|
26
|
-
*/
|
|
27
|
-
const KV_CLOUDFLARE_DELETE_BATCH_LIMIT = 128;
|
|
28
|
-
const KV_STORAGE_PREFIX = "$PLUV_STORAGE;";
|
|
29
|
-
const KV_USER_PREFIX = "$PLUV_USER";
|
|
30
|
-
const SQLITE_STORAGE_TABLE = "__pluv_storage";
|
|
31
|
-
const SQLITE_USER_TABLE = "__pluv_user";
|
|
32
|
-
var PersistenceCloudflareTransactionalStorage = class PersistenceCloudflareTransactionalStorage extends AbstractPersistence {
|
|
33
|
-
_mode;
|
|
34
|
-
_state = null;
|
|
35
|
-
_initialized = null;
|
|
36
|
-
constructor(config) {
|
|
37
|
-
super();
|
|
38
|
-
const { mode } = config;
|
|
39
|
-
this._initialized = config._initialized;
|
|
40
|
-
this._mode = mode;
|
|
41
|
-
}
|
|
42
|
-
async addUser(room, connectionId, user) {
|
|
43
|
-
if (!this._initialized) return;
|
|
44
|
-
if (!this._state) return;
|
|
45
|
-
await this._initialized;
|
|
46
|
-
if (this._mode === "kv") {
|
|
47
|
-
await this._state.storage.put(this._getUserKey(room, connectionId), user);
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
if (!!(this._state.storage.sql.exec(sql`
|
|
51
|
-
SELECT id
|
|
52
|
-
FROM ${SQLITE_USER_TABLE}
|
|
53
|
-
WHERE id = ?;
|
|
54
|
-
`, connectionId).toArray()[0]?.count ?? 0)) return;
|
|
55
|
-
this._state.storage.sql.exec(sql`
|
|
56
|
-
INSERT INTO ${SQLITE_USER_TABLE} VALUES (?, ?, ?);
|
|
57
|
-
`, connectionId, JSON.stringify(user), room);
|
|
58
|
-
}
|
|
59
|
-
async deleteStorageState(room) {
|
|
60
|
-
if (!this._initialized) return;
|
|
61
|
-
if (!this._state) return;
|
|
62
|
-
await this._initialized;
|
|
63
|
-
if (this._mode === "kv") {
|
|
64
|
-
await this._state.storage.delete(this._getStorageKey(room));
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
this._state.storage.sql.exec(sql`
|
|
68
|
-
DELETE FROM ${SQLITE_STORAGE_TABLE}
|
|
69
|
-
WHERE room = ?;
|
|
70
|
-
`, room);
|
|
71
|
-
}
|
|
72
|
-
async deleteUser(room, connectionId) {
|
|
73
|
-
if (!this._initialized) return;
|
|
74
|
-
if (!this._state) return;
|
|
75
|
-
await this._initialized;
|
|
76
|
-
if (this._mode === "kv") {
|
|
77
|
-
await this._state.storage.delete(this._getUserKey(room, connectionId));
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
this._state.storage.sql.exec(sql`
|
|
81
|
-
DELETE FROM ${SQLITE_USER_TABLE}
|
|
82
|
-
WHERE room = ?
|
|
83
|
-
AND id = ?;
|
|
84
|
-
`, room, connectionId);
|
|
85
|
-
}
|
|
86
|
-
async deleteUsers(room) {
|
|
87
|
-
if (!this._initialized) return;
|
|
88
|
-
if (!this._state) return;
|
|
89
|
-
await this._initialized;
|
|
90
|
-
if (this._mode === "kv") {
|
|
91
|
-
const map = await this._state.storage.list({
|
|
92
|
-
allowConcurrency: true,
|
|
93
|
-
noCache: true,
|
|
94
|
-
prefix: `${KV_USER_PREFIX}::${room}`
|
|
95
|
-
});
|
|
96
|
-
const partitions = partitionByLength(Array.from(map.keys()), KV_CLOUDFLARE_DELETE_BATCH_LIMIT);
|
|
97
|
-
await this._state.storage.transaction(async (tx) => {
|
|
98
|
-
await partitions.reduce(async (promise, partition) => {
|
|
99
|
-
await promise;
|
|
100
|
-
await tx.delete(partition);
|
|
101
|
-
}, Promise.resolve());
|
|
102
|
-
});
|
|
103
|
-
return;
|
|
104
|
-
}
|
|
105
|
-
this._state.storage.sql.exec(sql`
|
|
106
|
-
DELETE FROM ${SQLITE_USER_TABLE}
|
|
107
|
-
WHERE room = ?;
|
|
108
|
-
`, room);
|
|
109
|
-
}
|
|
110
|
-
async getStorageState(room) {
|
|
111
|
-
if (!this._initialized) return null;
|
|
112
|
-
if (!this._state) return null;
|
|
113
|
-
await this._initialized;
|
|
114
|
-
if (this._mode === "kv") return await this._state.storage.get(this._getStorageKey(room)) ?? null;
|
|
115
|
-
const cursor = this._state.storage.sql.exec(sql`
|
|
116
|
-
SELECT room, data
|
|
117
|
-
FROM ${SQLITE_STORAGE_TABLE}
|
|
118
|
-
WHERE room = ?;
|
|
119
|
-
`, room);
|
|
120
|
-
try {
|
|
121
|
-
return cursor.one().data;
|
|
122
|
-
} catch {
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
async getUser(room, connectionId) {
|
|
127
|
-
if (!this._initialized) return null;
|
|
128
|
-
if (!this._state) return null;
|
|
129
|
-
await this._initialized;
|
|
130
|
-
if (this._mode === "kv") return await this._state.storage.get(this._getUserKey(room, connectionId)) ?? null;
|
|
131
|
-
const cursor = this._state.storage.sql.exec(sql`
|
|
132
|
-
SELECT id, data, room
|
|
133
|
-
FROM ${SQLITE_USER_TABLE}
|
|
134
|
-
WHERE room = ?
|
|
135
|
-
AND id = ?;
|
|
136
|
-
`, room, connectionId);
|
|
137
|
-
try {
|
|
138
|
-
const result = cursor.one();
|
|
139
|
-
return JSON.parse(result.data);
|
|
140
|
-
} catch {
|
|
141
|
-
return null;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
async getUsers(room) {
|
|
145
|
-
if (!this._initialized) return /* @__PURE__ */ new Map();
|
|
146
|
-
if (!this._state) return /* @__PURE__ */ new Map();
|
|
147
|
-
await this._initialized;
|
|
148
|
-
if (this._mode === "kv") return (await this._state.storage.list({ prefix: `${KV_USER_PREFIX}::${room}` }).then((map) => Array.from(map.entries()))).reduce((map, [key, user]) => {
|
|
149
|
-
const connectionId = key.split("::").slice(-1)[0];
|
|
150
|
-
return !!connectionId ? map.set(connectionId, user) : map;
|
|
151
|
-
}, /* @__PURE__ */ new Map());
|
|
152
|
-
return this._state.storage.sql.exec(sql`
|
|
153
|
-
SELECT id, room, data
|
|
154
|
-
FROM ${SQLITE_USER_TABLE}
|
|
155
|
-
WHERE room = ?;
|
|
156
|
-
`, room).toArray().reduce((map, { id, data }) => {
|
|
157
|
-
try {
|
|
158
|
-
const user = JSON.parse(data);
|
|
159
|
-
return map.set(id, user);
|
|
160
|
-
} catch {
|
|
161
|
-
return map;
|
|
162
|
-
}
|
|
163
|
-
}, /* @__PURE__ */ new Map());
|
|
164
|
-
}
|
|
165
|
-
async getUsersSize(room) {
|
|
166
|
-
if (!this._initialized) return 0;
|
|
167
|
-
if (!this._state) return 0;
|
|
168
|
-
await this._initialized;
|
|
169
|
-
if (this._mode) return (await this._state.storage.list({ prefix: `${KV_USER_PREFIX}::${room}` })).size;
|
|
170
|
-
const cursor = this._state.storage.sql.exec(sql`
|
|
171
|
-
SELECT COUNT(*) count
|
|
172
|
-
FROM ${SQLITE_USER_TABLE}
|
|
173
|
-
WHERE room = ?;
|
|
174
|
-
`, room);
|
|
175
|
-
try {
|
|
176
|
-
return castNumber(cursor.one().count);
|
|
177
|
-
} catch {
|
|
178
|
-
return 0;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
initialize(roomContext) {
|
|
182
|
-
const initialized = (async () => {
|
|
183
|
-
const { state } = roomContext;
|
|
184
|
-
this._state = state;
|
|
185
|
-
if (this._mode === "sqlite") this._state.storage.sql.exec(sql`
|
|
186
|
-
CREATE TABLE IF NOT EXISTS ${SQLITE_STORAGE_TABLE}(
|
|
187
|
-
room TEXT PRIMARY KEY,
|
|
188
|
-
data TEXT NOT NULL
|
|
189
|
-
);
|
|
190
|
-
CREATE TABLE IF NOT EXISTS ${SQLITE_USER_TABLE}(
|
|
191
|
-
id TEXT PRIMARY KEY,
|
|
192
|
-
data TEXT NOT NULL,
|
|
193
|
-
room TEXT NOT NULL
|
|
194
|
-
);
|
|
195
|
-
CREATE INDEX IF NOT EXISTS ${SQLITE_USER_TABLE}_room ON ${SQLITE_USER_TABLE}(room);
|
|
196
|
-
`);
|
|
197
|
-
return true;
|
|
198
|
-
})();
|
|
199
|
-
return new PersistenceCloudflareTransactionalStorage({
|
|
200
|
-
mode: this._mode,
|
|
201
|
-
_initialized: initialized
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
async setStorageState(room, state) {
|
|
205
|
-
if (!this._initialized) return;
|
|
206
|
-
if (!this._state) return;
|
|
207
|
-
await this._initialized;
|
|
208
|
-
if (this._mode === "kv") {
|
|
209
|
-
await this._state.storage.put(this._getStorageKey(room), state, { allowConcurrency: true });
|
|
210
|
-
return;
|
|
211
|
-
}
|
|
212
|
-
if (!!(this._state.storage.sql.exec(sql`
|
|
213
|
-
SELECT COUNT(*) as count
|
|
214
|
-
FROM ${SQLITE_STORAGE_TABLE}
|
|
215
|
-
WHERE room = ?;
|
|
216
|
-
`, room).toArray()[0]?.count ?? 0)) {
|
|
217
|
-
this._state.storage.sql.exec(sql`
|
|
218
|
-
UPDATE ${SQLITE_STORAGE_TABLE}
|
|
219
|
-
SET data = ?
|
|
220
|
-
WHERE room = ?;
|
|
221
|
-
`, state, room);
|
|
222
|
-
return;
|
|
223
|
-
}
|
|
224
|
-
this._state.storage.sql.exec(sql`
|
|
225
|
-
INSERT INTO ${SQLITE_STORAGE_TABLE} VALUES (?, ?);
|
|
226
|
-
`, room, state);
|
|
227
|
-
}
|
|
228
|
-
_getStorageKey(room) {
|
|
229
|
-
if (this._mode === "sqlite") throw new Error("Attempted to get kv key for sqlite storage");
|
|
230
|
-
return `${KV_STORAGE_PREFIX}::${room}`;
|
|
231
|
-
}
|
|
232
|
-
_getUserKey(room, connectionId) {
|
|
233
|
-
if (this._mode === "sqlite") throw new Error("Attempted to get kv key for sqlite storage");
|
|
234
|
-
return `${KV_USER_PREFIX}::${room}::${connectionId}`;
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
//#endregion
|
|
238
|
-
export { PersistenceCloudflareTransactionalStorage };
|
|
239
|
-
|
|
240
|
-
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/utils/castNumber.ts","../src/utils/partitionByLength.ts","../src/utils/sql.ts","../src/PersistenceCloudflareTransactionalStorage.ts"],"sourcesContent":["export const castNumber = (value: any): number => {\n return typeof value === \"number\"\n ? value\n : typeof value === \"string\"\n ? Number.parseInt(value, 10)\n : Number(value);\n};\n","export const partitionByLength = <T>(\n arr: readonly T[] | T[],\n length: number,\n): readonly (readonly T[])[] => {\n if (!arr.length) return [];\n\n const head = arr.slice(0, length);\n const tail = arr.slice(length);\n\n return [head, ...partitionByLength(tail, length)];\n};\n","export const sql = (strings: TemplateStringsArray, ...values: any[]): string => {\n return strings\n .reduce((result, str, i) => {\n // Compresses the string to a single line (not including the interpolated values)\n const cleaned = str.replace(/(\\n[ \\t]*)+/g, \" \");\n\n return result + cleaned + (i < values.length ? values[i] : \"\");\n }, \"\")\n .trim();\n};\n","import { AbstractPersistence } from \"@pluv/io\";\nimport type { JsonObject } from \"@pluv/types\";\nimport { castNumber, partitionByLength, sql } from \"./utils\";\n\n/**\n * !HACK\n * @description The max amount of keys a Cloudflare transactional storage may delete at once\n * @see https://developers.cloudflare.com/durable-objects/api/transactional-storage-api/#delete\n * @date July 8, 2024\n */\nconst KV_CLOUDFLARE_DELETE_BATCH_LIMIT = 128;\nconst KV_STORAGE_PREFIX = \"$PLUV_STORAGE;\";\nconst KV_USER_PREFIX = \"$PLUV_USER\";\n\nconst SQLITE_STORAGE_TABLE = \"__pluv_storage\";\nconst SQLITE_USER_TABLE = \"__pluv_user\";\n\nexport interface PersistenceCloudflareTransactionalStorageConfig {\n mode: \"kv\" | \"sqlite\";\n}\nexport class PersistenceCloudflareTransactionalStorage extends AbstractPersistence {\n private _mode: \"kv\" | \"sqlite\";\n private _state: DurableObjectState | null = null;\n private _initialized: Promise<true> | null = null;\n\n constructor(config: PersistenceCloudflareTransactionalStorageConfig) {\n super();\n\n const { mode } = config;\n\n this._initialized = (config as any)._initialized;\n this._mode = mode;\n }\n\n public async addUser(\n room: string,\n connectionId: string,\n user: JsonObject | null,\n ): Promise<void> {\n if (!this._initialized) return;\n if (!this._state) return;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n await this._state.storage.put(this._getUserKey(room, connectionId), user);\n return;\n }\n\n const result = this._state.storage.sql.exec<{ count: 0 }>(\n sql`\n SELECT id\n FROM ${SQLITE_USER_TABLE}\n WHERE id = ?;\n `,\n connectionId,\n );\n\n const existing = !!(result.toArray()[0]?.count ?? 0);\n\n if (existing) return;\n\n this._state.storage.sql.exec(\n sql`\n INSERT INTO ${SQLITE_USER_TABLE} VALUES (?, ?, ?);\n `,\n connectionId,\n JSON.stringify(user),\n room,\n );\n }\n\n public async deleteStorageState(room: string): Promise<void> {\n if (!this._initialized) return;\n if (!this._state) return;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n await this._state.storage.delete(this._getStorageKey(room));\n return;\n }\n\n this._state.storage.sql.exec(\n sql`\n DELETE FROM ${SQLITE_STORAGE_TABLE}\n WHERE room = ?;\n `,\n room,\n );\n }\n\n public async deleteUser(room: string, connectionId: string): Promise<void> {\n if (!this._initialized) return;\n if (!this._state) return;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n await this._state.storage.delete(this._getUserKey(room, connectionId));\n\n return;\n }\n\n this._state.storage.sql.exec(\n sql`\n DELETE FROM ${SQLITE_USER_TABLE}\n WHERE room = ?\n AND id = ?;\n `,\n room,\n connectionId,\n );\n }\n\n public async deleteUsers(room: string): Promise<void> {\n if (!this._initialized) return;\n if (!this._state) return;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n const map = await this._state.storage.list({\n allowConcurrency: true,\n noCache: true,\n prefix: `${KV_USER_PREFIX}::${room}`,\n });\n\n const partitions = partitionByLength(\n Array.from(map.keys()),\n KV_CLOUDFLARE_DELETE_BATCH_LIMIT,\n );\n\n await this._state.storage.transaction(async (tx) => {\n await partitions.reduce(async (promise, partition) => {\n await promise;\n await tx.delete(partition as string[]);\n }, Promise.resolve());\n });\n\n return;\n }\n\n this._state.storage.sql.exec(\n sql`\n DELETE FROM ${SQLITE_USER_TABLE}\n WHERE room = ?;\n `,\n room,\n );\n }\n\n public async getStorageState(room: string): Promise<string | null> {\n if (!this._initialized) return null;\n if (!this._state) return null;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n const storage = await this._state.storage.get<string>(this._getStorageKey(room));\n return storage ?? null;\n }\n\n const cursor = this._state.storage.sql.exec<{ room: string; data: string }>(\n sql`\n SELECT room, data\n FROM ${SQLITE_STORAGE_TABLE}\n WHERE room = ?;\n `,\n room,\n );\n\n try {\n const result = cursor.one();\n\n return result.data;\n } catch {\n return null;\n }\n }\n\n public async getUser(room: string, connectionId: string): Promise<JsonObject | null> {\n if (!this._initialized) return null;\n if (!this._state) return null;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n const user = await this._state.storage.get<JsonObject | null>(\n this._getUserKey(room, connectionId),\n );\n\n return user ?? null;\n }\n\n const cursor = this._state.storage.sql.exec<{ id: string; data: string; room: string }>(\n sql`\n SELECT id, data, room\n FROM ${SQLITE_USER_TABLE}\n WHERE room = ?\n AND id = ?;\n `,\n room,\n connectionId,\n );\n\n try {\n const result = cursor.one();\n const user = JSON.parse(result.data);\n\n return user;\n } catch {\n return null;\n }\n }\n\n public async getUsers(\n room: string,\n ): Promise<Map<[connectionId: string][0], JsonObject | null>> {\n if (!this._initialized) return new Map();\n if (!this._state) return new Map();\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n const entries = await this._state.storage\n .list<JsonObject | null>({\n prefix: `${KV_USER_PREFIX}::${room}`,\n })\n .then((map) => Array.from(map.entries()));\n\n return entries.reduce((map, [key, user]) => {\n const connectionId = key.split(\"::\").slice(-1)[0];\n\n return !!connectionId ? map.set(connectionId, user) : map;\n }, new Map<string, JsonObject | null>());\n }\n\n const cursor = this._state.storage.sql.exec<{ id: string; data: string; room: string }>(\n sql`\n SELECT id, room, data\n FROM ${SQLITE_USER_TABLE}\n WHERE room = ?;\n `,\n room,\n );\n\n return cursor.toArray().reduce((map, { id, data }) => {\n try {\n const user = JSON.parse(data) as JsonObject;\n\n return map.set(id, user);\n } catch {\n return map;\n }\n }, new Map<string, JsonObject | null>());\n }\n\n public async getUsersSize(room: string): Promise<number> {\n if (!this._initialized) return 0;\n if (!this._state) return 0;\n\n await this._initialized;\n\n if (this._mode) {\n const storage = await this._state.storage.list({\n prefix: `${KV_USER_PREFIX}::${room}`,\n });\n\n return storage.size;\n }\n\n const cursor = this._state.storage.sql.exec<{ count: number }>(\n sql`\n SELECT COUNT(*) count\n FROM ${SQLITE_USER_TABLE}\n WHERE room = ?;\n `,\n room,\n );\n\n try {\n const result = cursor.one();\n\n return castNumber(result.count);\n } catch {\n return 0;\n }\n }\n\n public initialize(roomContext: { state: DurableObjectState }): typeof this {\n const initialized = (async () => {\n const { state } = roomContext;\n\n this._state = state;\n\n if (this._mode === \"sqlite\") {\n this._state.storage.sql.exec(sql`\n CREATE TABLE IF NOT EXISTS ${SQLITE_STORAGE_TABLE}(\n room TEXT PRIMARY KEY,\n data TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS ${SQLITE_USER_TABLE}(\n id TEXT PRIMARY KEY,\n data TEXT NOT NULL,\n room TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS ${SQLITE_USER_TABLE}_room ON ${SQLITE_USER_TABLE}(room);\n `);\n }\n\n return true as const;\n })();\n\n return new PersistenceCloudflareTransactionalStorage({\n mode: this._mode,\n ...{ _initialized: initialized },\n }) as typeof this;\n }\n\n public async setStorageState(room: string, state: string): Promise<void> {\n if (!this._initialized) return;\n if (!this._state) return;\n\n await this._initialized;\n\n if (this._mode === \"kv\") {\n await this._state.storage.put(this._getStorageKey(room), state, {\n allowConcurrency: true,\n });\n return;\n }\n\n const result = this._state.storage.sql.exec<{ count: number }>(\n sql`\n SELECT COUNT(*) as count\n FROM ${SQLITE_STORAGE_TABLE}\n WHERE room = ?;\n `,\n room,\n );\n\n const existing = !!(result.toArray()[0]?.count ?? 0);\n\n if (existing) {\n this._state.storage.sql.exec(\n sql`\n UPDATE ${SQLITE_STORAGE_TABLE}\n SET data = ?\n WHERE room = ?;\n `,\n state,\n room,\n );\n\n return;\n }\n\n this._state.storage.sql.exec(\n sql`\n INSERT INTO ${SQLITE_STORAGE_TABLE} VALUES (?, ?);\n `,\n room,\n state,\n );\n }\n\n private _getStorageKey(room: string): string {\n if (this._mode === \"sqlite\") {\n throw new Error(\"Attempted to get kv key for sqlite storage\");\n }\n\n return `${KV_STORAGE_PREFIX}::${room}`;\n }\n\n private _getUserKey(room: string, connectionId: string): string {\n if (this._mode === \"sqlite\") {\n throw new Error(\"Attempted to get kv key for sqlite storage\");\n }\n\n return `${KV_USER_PREFIX}::${room}::${connectionId}`;\n }\n}\n"],"mappings":";;AAAA,MAAa,cAAc,UAAuB;CAC9C,OAAO,OAAO,UAAU,WAClB,QACA,OAAO,UAAU,WACf,OAAO,SAAS,OAAO,EAAE,IACzB,OAAO,KAAK;AACxB;;;ACNA,MAAa,qBACT,KACA,WAC4B;CAC5B,IAAI,CAAC,IAAI,QAAQ,OAAO,CAAC;CAKzB,OAAO,CAHM,IAAI,MAAM,GAAG,MAGf,GAAG,GAAG,kBAFJ,IAAI,MAAM,MAEe,GAAG,MAAM,CAAC;AACpD;;;ACVA,MAAa,OAAO,SAA+B,GAAG,WAA0B;CAC5E,OAAO,QACF,QAAQ,QAAQ,KAAK,MAAM;EAIxB,OAAO,SAFS,IAAI,QAAQ,gBAAgB,GAEtB,KAAK,IAAI,OAAO,SAAS,OAAO,KAAK;CAC/D,GAAG,EAAE,CAAC,CACL,KAAK;AACd;;;;;;;;;ACCA,MAAM,mCAAmC;AACzC,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AAEvB,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB;AAK1B,IAAa,4CAAb,MAAa,kDAAkD,oBAAoB;CAC/E;CACA,SAA4C;CAC5C,eAA6C;CAE7C,YAAY,QAAyD;EACjE,MAAM;EAEN,MAAM,EAAE,SAAS;EAEjB,KAAK,eAAgB,OAAe;EACpC,KAAK,QAAQ;CACjB;CAEA,MAAa,QACT,MACA,cACA,MACa;EACb,IAAI,CAAC,KAAK,cAAc;EACxB,IAAI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