memx 0.0.7 → 0.1.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 (78) hide show
  1. package/dist/buffers.cjs +50 -0
  2. package/dist/buffers.cjs.map +6 -0
  3. package/dist/buffers.d.ts +14 -0
  4. package/dist/buffers.mjs +25 -0
  5. package/dist/buffers.mjs.map +6 -0
  6. package/dist/client.cjs +251 -0
  7. package/dist/client.cjs.map +6 -0
  8. package/dist/client.d.ts +76 -0
  9. package/dist/client.mjs +216 -0
  10. package/dist/client.mjs.map +6 -0
  11. package/dist/cluster.cjs +147 -0
  12. package/dist/cluster.cjs.map +6 -0
  13. package/dist/cluster.d.ts +60 -0
  14. package/dist/cluster.mjs +112 -0
  15. package/dist/cluster.mjs.map +6 -0
  16. package/dist/connection.cjs +186 -0
  17. package/dist/connection.cjs.map +6 -0
  18. package/dist/connection.d.ts +18 -0
  19. package/dist/connection.mjs +151 -0
  20. package/dist/connection.mjs.map +6 -0
  21. package/dist/constants.cjs +140 -0
  22. package/dist/constants.cjs.map +6 -0
  23. package/dist/constants.d.ts +87 -0
  24. package/dist/constants.mjs +107 -0
  25. package/dist/constants.mjs.map +6 -0
  26. package/dist/decode.cjs +101 -0
  27. package/dist/decode.cjs.map +6 -0
  28. package/dist/decode.d.ts +16 -0
  29. package/dist/decode.mjs +66 -0
  30. package/dist/decode.mjs.map +6 -0
  31. package/dist/encode.cjs +70 -0
  32. package/dist/encode.cjs.map +6 -0
  33. package/dist/encode.d.ts +20 -0
  34. package/dist/encode.mjs +45 -0
  35. package/dist/encode.mjs.map +6 -0
  36. package/dist/fake.cjs +183 -0
  37. package/dist/fake.cjs.map +6 -0
  38. package/dist/fake.d.ts +53 -0
  39. package/dist/fake.mjs +157 -0
  40. package/dist/fake.mjs.map +6 -0
  41. package/dist/index.cjs +57 -0
  42. package/dist/index.cjs.map +6 -0
  43. package/dist/index.d.ts +12 -0
  44. package/dist/index.mjs +15 -1460
  45. package/dist/index.mjs.map +2 -2
  46. package/dist/internals.cjs +58 -0
  47. package/dist/internals.cjs.map +6 -0
  48. package/dist/internals.d.ts +7 -0
  49. package/dist/internals.mjs +21 -0
  50. package/dist/internals.mjs.map +6 -0
  51. package/dist/server.cjs +468 -0
  52. package/dist/server.cjs.map +6 -0
  53. package/dist/server.d.ts +59 -0
  54. package/dist/server.mjs +443 -0
  55. package/dist/server.mjs.map +6 -0
  56. package/dist/types.cjs +19 -0
  57. package/dist/types.cjs.map +6 -0
  58. package/dist/types.d.ts +239 -0
  59. package/dist/types.mjs +1 -0
  60. package/dist/types.mjs.map +6 -0
  61. package/dist/utils.cjs +182 -0
  62. package/dist/utils.cjs.map +6 -0
  63. package/dist/utils.d.ts +22 -0
  64. package/dist/utils.mjs +145 -0
  65. package/dist/utils.mjs.map +6 -0
  66. package/package.json +29 -27
  67. package/src/client.ts +25 -23
  68. package/src/cluster.ts +6 -3
  69. package/src/connection.ts +8 -4
  70. package/src/decode.ts +5 -2
  71. package/src/encode.ts +5 -2
  72. package/src/fake.ts +34 -33
  73. package/src/internals.ts +7 -7
  74. package/src/server.ts +47 -45
  75. package/src/utils.ts +7 -4
  76. package/dist/index.js +0 -1496
  77. package/dist/index.js.map +0 -6
  78. package/index.d.ts +0 -710
package/dist/index.mjs CHANGED
@@ -1,1463 +1,18 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __export = (target, all) => {
21
- for (var name in all)
22
- __defProp(target, name, { get: all[name], enumerable: true });
23
- };
24
-
25
- // src/decode.ts
26
- var decode_exports = {};
27
- __export(decode_exports, {
28
- Decoder: () => Decoder
29
- });
30
-
31
- // src/constants.ts
32
- var constants_exports = {};
33
- __export(constants_exports, {
34
- BUFFERS: () => BUFFERS,
35
- DATA_TYPE: () => DATA_TYPE,
36
- EMPTY_BUFFER: () => EMPTY_BUFFER,
37
- FLAGS: () => FLAGS,
38
- MAGIC: () => MAGIC,
39
- OFFSETS: () => OFFSETS,
40
- OPCODE: () => OPCODE,
41
- STATUS: () => STATUS,
42
- VBUCKET: () => VBUCKET
43
- });
44
- var EMPTY_BUFFER = Buffer.alloc(0);
45
- var FLAGS = /* @__PURE__ */ ((FLAGS2) => {
46
- FLAGS2[FLAGS2["BUFFER"] = 0] = "BUFFER";
47
- FLAGS2[FLAGS2["BIGINT"] = 3402235904] = "BIGINT";
48
- FLAGS2[FLAGS2["BOOLEAN"] = 3402235905] = "BOOLEAN";
49
- FLAGS2[FLAGS2["NUMBER"] = 3402235906] = "NUMBER";
50
- FLAGS2[FLAGS2["STRING"] = 3402235907] = "STRING";
51
- FLAGS2[FLAGS2["NULL"] = 3402235918] = "NULL";
52
- FLAGS2[FLAGS2["JSON"] = 3402235919] = "JSON";
53
- FLAGS2[FLAGS2["UINT8ARRAY"] = 3402235920] = "UINT8ARRAY";
54
- FLAGS2[FLAGS2["UINT8CLAMPEDARRAY"] = 3402235921] = "UINT8CLAMPEDARRAY";
55
- FLAGS2[FLAGS2["UINT16ARRAY"] = 3402235922] = "UINT16ARRAY";
56
- FLAGS2[FLAGS2["UINT32ARRAY"] = 3402235923] = "UINT32ARRAY";
57
- FLAGS2[FLAGS2["INT8ARRAY"] = 3402235924] = "INT8ARRAY";
58
- FLAGS2[FLAGS2["INT16ARRAY"] = 3402235925] = "INT16ARRAY";
59
- FLAGS2[FLAGS2["INT32ARRAY"] = 3402235926] = "INT32ARRAY";
60
- FLAGS2[FLAGS2["BIGUINT64ARRAY"] = 3402235927] = "BIGUINT64ARRAY";
61
- FLAGS2[FLAGS2["BIGINT64ARRAY"] = 3402235928] = "BIGINT64ARRAY";
62
- FLAGS2[FLAGS2["FLOAT32ARRAY"] = 3402235929] = "FLOAT32ARRAY";
63
- FLAGS2[FLAGS2["FLOAT64ARRAY"] = 3402235930] = "FLOAT64ARRAY";
64
- return FLAGS2;
65
- })(FLAGS || {});
66
- var BUFFERS = /* @__PURE__ */ ((BUFFERS2) => {
67
- BUFFERS2[BUFFERS2["POOL_SIZE"] = 64] = "POOL_SIZE";
68
- BUFFERS2[BUFFERS2["BUFFER_SIZE"] = 8192] = "BUFFER_SIZE";
69
- BUFFERS2[BUFFERS2["HEADER_SIZE"] = 24] = "HEADER_SIZE";
70
- BUFFERS2[BUFFERS2["KEY_SIZE"] = 250] = "KEY_SIZE";
71
- BUFFERS2[BUFFERS2["KEY_TOO_BIG"] = 251] = "KEY_TOO_BIG";
72
- return BUFFERS2;
73
- })(BUFFERS || {});
74
- var OFFSETS = /* @__PURE__ */ ((OFFSETS2) => {
75
- OFFSETS2[OFFSETS2["MAGIC_$8"] = 0] = "MAGIC_$8";
76
- OFFSETS2[OFFSETS2["OPCODE_$8"] = 1] = "OPCODE_$8";
77
- OFFSETS2[OFFSETS2["KEY_LENGTH_$16"] = 2] = "KEY_LENGTH_$16";
78
- OFFSETS2[OFFSETS2["EXTRAS_LENGTH_$8"] = 4] = "EXTRAS_LENGTH_$8";
79
- OFFSETS2[OFFSETS2["DATA_TYPE_$8"] = 5] = "DATA_TYPE_$8";
80
- OFFSETS2[OFFSETS2["STATUS_$16"] = 6] = "STATUS_$16";
81
- OFFSETS2[OFFSETS2["BODY_LENGTH_$32"] = 8] = "BODY_LENGTH_$32";
82
- OFFSETS2[OFFSETS2["SEQUENCE_$32"] = 12] = "SEQUENCE_$32";
83
- OFFSETS2[OFFSETS2["CAS_$64"] = 16] = "CAS_$64";
84
- OFFSETS2[OFFSETS2["BODY"] = 24] = "BODY";
85
- return OFFSETS2;
86
- })(OFFSETS || {});
87
- var MAGIC = /* @__PURE__ */ ((MAGIC2) => {
88
- MAGIC2[MAGIC2["REQUEST"] = 128] = "REQUEST";
89
- MAGIC2[MAGIC2["RESPONSE"] = 129] = "RESPONSE";
90
- return MAGIC2;
91
- })(MAGIC || {});
92
- var STATUS = /* @__PURE__ */ ((STATUS2) => {
93
- STATUS2[STATUS2["OK"] = 0] = "OK";
94
- STATUS2[STATUS2["KEY_NOT_FOUND"] = 1] = "KEY_NOT_FOUND";
95
- STATUS2[STATUS2["KEY_EXISTS"] = 2] = "KEY_EXISTS";
96
- STATUS2[STATUS2["TOO_LARGE"] = 3] = "TOO_LARGE";
97
- STATUS2[STATUS2["INVALID_ARGS"] = 4] = "INVALID_ARGS";
98
- STATUS2[STATUS2["ITEM_NOT_STORED"] = 5] = "ITEM_NOT_STORED";
99
- STATUS2[STATUS2["NON_NUMERIC_VALUE"] = 6] = "NON_NUMERIC_VALUE";
100
- STATUS2[STATUS2["WRONG_VBUCKET"] = 7] = "WRONG_VBUCKET";
101
- STATUS2[STATUS2["AUTH_ERROR"] = 8] = "AUTH_ERROR";
102
- STATUS2[STATUS2["AUTH_CONTINUE"] = 9] = "AUTH_CONTINUE";
103
- STATUS2[STATUS2["UNKNOWN_COMMAND"] = 129] = "UNKNOWN_COMMAND";
104
- STATUS2[STATUS2["OUT_OF_MEMORY"] = 130] = "OUT_OF_MEMORY";
105
- STATUS2[STATUS2["NOT_SUPPORTED"] = 131] = "NOT_SUPPORTED";
106
- STATUS2[STATUS2["INTERNAL_ERROR"] = 132] = "INTERNAL_ERROR";
107
- STATUS2[STATUS2["BUSY"] = 133] = "BUSY";
108
- STATUS2[STATUS2["TEMPORARY_FAILURE"] = 134] = "TEMPORARY_FAILURE";
109
- return STATUS2;
110
- })(STATUS || {});
111
- var OPCODE = /* @__PURE__ */ ((OPCODE3) => {
112
- OPCODE3[OPCODE3["GET"] = 0] = "GET";
113
- OPCODE3[OPCODE3["SET"] = 1] = "SET";
114
- OPCODE3[OPCODE3["ADD"] = 2] = "ADD";
115
- OPCODE3[OPCODE3["REPLACE"] = 3] = "REPLACE";
116
- OPCODE3[OPCODE3["DELETE"] = 4] = "DELETE";
117
- OPCODE3[OPCODE3["INCREMENT"] = 5] = "INCREMENT";
118
- OPCODE3[OPCODE3["DECREMENT"] = 6] = "DECREMENT";
119
- OPCODE3[OPCODE3["QUIT"] = 7] = "QUIT";
120
- OPCODE3[OPCODE3["FLUSH"] = 8] = "FLUSH";
121
- OPCODE3[OPCODE3["NOOP"] = 10] = "NOOP";
122
- OPCODE3[OPCODE3["VERSION"] = 11] = "VERSION";
123
- OPCODE3[OPCODE3["APPEND"] = 14] = "APPEND";
124
- OPCODE3[OPCODE3["PREPEND"] = 15] = "PREPEND";
125
- OPCODE3[OPCODE3["STAT"] = 16] = "STAT";
126
- OPCODE3[OPCODE3["TOUCH"] = 28] = "TOUCH";
127
- OPCODE3[OPCODE3["GAT"] = 29] = "GAT";
128
- return OPCODE3;
129
- })(OPCODE || {});
130
- var DATA_TYPE = /* @__PURE__ */ ((DATA_TYPE2) => {
131
- DATA_TYPE2[DATA_TYPE2["RAW"] = 0] = "RAW";
132
- return DATA_TYPE2;
133
- })(DATA_TYPE || {});
134
- var VBUCKET = /* @__PURE__ */ ((VBUCKET2) => {
135
- VBUCKET2[VBUCKET2["NIL"] = 0] = "NIL";
136
- return VBUCKET2;
137
- })(VBUCKET || {});
138
-
139
- // src/buffers.ts
140
- var pool = new Array(64 /* POOL_SIZE */);
141
- var offset = -1;
142
- function allocateBuffer(size) {
143
- if (size > 8192 /* BUFFER_SIZE */) {
144
- const buffer2 = Buffer.allocUnsafeSlow(size);
145
- buffer2.recycle = () => void 0;
146
- return buffer2;
147
- }
148
- const buffer = offset >= 0 ? pool[offset--] : Buffer.allocUnsafeSlow(8192 /* BUFFER_SIZE */);
149
- const recyclable = buffer.subarray(0, size);
150
- let recycled = false;
151
- recyclable.recycle = () => queueMicrotask(() => {
152
- if (offset >= 64 /* POOL_SIZE */ || recycled)
153
- return;
154
- pool[++offset] = buffer;
155
- recycled = true;
156
- });
157
- return recyclable;
158
- }
159
-
160
- // src/decode.ts
161
- import assert from "assert";
162
- var Decoder = class {
163
- #consumer;
164
- #header = Buffer.allocUnsafeSlow(24);
165
- #body;
166
- #pos = 0;
167
- constructor(consumer) {
168
- this.#consumer = consumer;
169
- }
170
- append(buffer, start, end) {
171
- const header = this.#header;
172
- while (start < end) {
173
- if (this.#pos < 24) {
174
- const copied = buffer.copy(header, this.#pos, start, end);
175
- this.#pos += copied;
176
- start += copied;
177
- }
178
- if (this.#pos < 24)
179
- return;
180
- let extras = EMPTY_BUFFER;
181
- let key = EMPTY_BUFFER;
182
- let value = EMPTY_BUFFER;
183
- let recycle = () => void 0;
184
- const bodyLength = header.readUInt32BE(8 /* BODY_LENGTH_$32 */);
185
- if (bodyLength) {
186
- const body = this.#body || (this.#body = allocateBuffer(bodyLength));
187
- const copied = buffer.copy(body, this.#pos - 24, start, end);
188
- this.#pos += copied;
189
- start += copied;
190
- if (this.#pos - 24 < body.length)
191
- return;
192
- const keyLength = header.readUInt16BE(2 /* KEY_LENGTH_$16 */);
193
- const extrasLength = header.readUInt8(4 /* EXTRAS_LENGTH_$8 */);
194
- const valueLength = bodyLength - keyLength - extrasLength;
195
- key = keyLength ? body.subarray(extrasLength, extrasLength + keyLength) : EMPTY_BUFFER;
196
- value = valueLength ? body.subarray(extrasLength + keyLength) : EMPTY_BUFFER;
197
- extras = extrasLength ? body.subarray(0, extrasLength) : EMPTY_BUFFER;
198
- recycle = () => void body.recycle();
199
- }
200
- const packet = {
201
- opcode: header.readUInt8(1 /* OPCODE_$8 */),
202
- status: header.readUInt16BE(6 /* STATUS_$16 */),
203
- sequence: header.readUInt32BE(12 /* SEQUENCE_$32 */),
204
- cas: header.readBigUInt64BE(16 /* CAS_$64 */),
205
- extras,
206
- key,
207
- value,
208
- recycle
209
- };
210
- const magic = header.readUInt8(0 /* MAGIC_$8 */);
211
- const dataType = header.readUInt8(5 /* DATA_TYPE_$8 */);
212
- assert.equal(magic, 129 /* RESPONSE */, "Invalid magic in header");
213
- assert.equal(dataType, 0 /* RAW */, "Invalid data type in header");
214
- this.#pos = 0;
215
- this.#body = void 0;
216
- this.#consumer(packet);
217
- }
218
- }
219
- };
220
-
221
- // src/encode.ts
222
- var encode_exports = {};
223
- __export(encode_exports, {
224
- Encoder: () => Encoder
225
- });
226
- var CONSTANTS = /* @__PURE__ */ ((CONSTANTS2) => {
227
- CONSTANTS2[CONSTANTS2["HEADER_SIZE"] = 24] = "HEADER_SIZE";
228
- return CONSTANTS2;
229
- })(CONSTANTS || {});
230
- var Encoder = class {
231
- encode(packet, seq = 0) {
232
- const {
233
- opcode,
234
- sequence = seq,
235
- cas = 0n,
236
- extras = EMPTY_BUFFER,
237
- extrasOffset = 0,
238
- extrasLength = extras.length,
239
- key = EMPTY_BUFFER,
240
- keyOffset = 0,
241
- keyLength = key.length,
242
- value = EMPTY_BUFFER,
243
- valueOffset = 0,
244
- valueLength = value.length
245
- } = packet;
246
- const bodyLength = extrasLength + keyLength + valueLength;
247
- const length = bodyLength + 24 /* HEADER_SIZE */;
248
- const buffer = allocateBuffer(length);
249
- buffer.writeUInt8(128 /* REQUEST */, 0 /* MAGIC_$8 */);
250
- buffer.writeUInt8(opcode, 1 /* OPCODE_$8 */);
251
- buffer.writeUInt16BE(keyLength, 2 /* KEY_LENGTH_$16 */);
252
- buffer.writeUInt8(extrasLength, 4 /* EXTRAS_LENGTH_$8 */);
253
- buffer.writeUInt8(0 /* RAW */, 5 /* DATA_TYPE_$8 */);
254
- buffer.writeUInt16BE(0 /* NIL */, 6 /* STATUS_$16 */);
255
- buffer.writeUInt32BE(bodyLength, 8 /* BODY_LENGTH_$32 */);
256
- buffer.writeUInt32BE(sequence, 12 /* SEQUENCE_$32 */);
257
- buffer.writeBigUInt64BE(cas, 16 /* CAS_$64 */);
258
- let pos = 24;
259
- if (extrasLength)
260
- pos += extras.copy(buffer, pos, extrasOffset, extrasOffset + extrasLength);
261
- if (keyLength)
262
- pos += key.copy(buffer, pos, keyOffset, keyOffset + keyLength);
263
- if (valueLength)
264
- pos += value.copy(buffer, pos, valueOffset, valueOffset + valueLength);
265
- return buffer;
266
- }
267
- };
268
-
269
- // src/connection.ts
270
- var connection_exports = {};
271
- __export(connection_exports, {
272
- Connection: () => Connection
273
- });
274
-
275
- // src/internals.ts
276
- import assert2 from "assert";
277
- import { types } from "util";
278
- var socketFinalizationRegistry = new FinalizationRegistry((socket) => {
279
- if (!socket.destroyed)
280
- socket.destroy();
281
- });
282
- function typedArrayFlags(value) {
283
- const flags = types.isUint8Array(value) ? 3402235920 /* UINT8ARRAY */ : types.isUint8ClampedArray(value) ? 3402235921 /* UINT8CLAMPEDARRAY */ : types.isUint16Array(value) ? 3402235922 /* UINT16ARRAY */ : types.isUint32Array(value) ? 3402235923 /* UINT32ARRAY */ : types.isInt8Array(value) ? 3402235924 /* INT8ARRAY */ : types.isInt16Array(value) ? 3402235925 /* INT16ARRAY */ : types.isInt32Array(value) ? 3402235926 /* INT32ARRAY */ : types.isBigUint64Array(value) ? 3402235927 /* BIGUINT64ARRAY */ : types.isBigInt64Array(value) ? 3402235928 /* BIGINT64ARRAY */ : types.isFloat32Array(value) ? 3402235929 /* FLOAT32ARRAY */ : types.isFloat64Array(value) ? 3402235930 /* FLOAT64ARRAY */ : assert2.fail("Unsupported kind of TypedArray");
284
- return flags;
285
- }
286
- function logPromiseError(promise, message) {
287
- return promise.catch((error) => console.log(message, error)).then(() => void 0);
288
- }
289
-
290
- // src/connection.ts
291
- import assert3 from "assert";
292
- import net from "net";
293
- var Deferred = class {
294
- #resolve;
295
- #reject;
296
- #packets = [];
297
- promise;
298
- opcode;
299
- constructor(opcode) {
300
- this.opcode = opcode;
301
- this.promise = new Promise((resolve, reject) => {
302
- this.#resolve = resolve;
303
- this.#reject = reject;
304
- });
305
- }
306
- append(packet) {
307
- this.#packets.push(packet);
308
- }
309
- resolve(packet) {
310
- this.#packets.push(packet);
311
- this.#resolve(this.#packets);
312
- }
313
- reject(error) {
314
- this.#reject(error);
315
- }
316
- };
317
- var Connection = class {
318
- #decoder = new Decoder((packet) => this.#receive(packet));
319
- #encoder = new Encoder();
320
- #buffer = Buffer.allocUnsafeSlow(8192 /* BUFFER_SIZE */);
321
- #defers = /* @__PURE__ */ new Map();
322
- #factory;
323
- #socket;
324
- #sequence = 0;
325
- #timeout;
326
- #host;
327
- #port;
328
- constructor(options) {
329
- assert3(options, "No options specified");
330
- const {
331
- host,
332
- port = 11211,
333
- timeout = 1e3,
334
- factory = net.connect
335
- } = options;
336
- this.#factory = factory;
337
- assert3(host, "No host name specified");
338
- assert3(port > 0 && port < 65536 && Math.floor(port) == port, `Invalid port ${port}`);
339
- this.#timeout = timeout;
340
- this.#host = host;
341
- this.#port = port;
342
- }
343
- get connected() {
344
- return !!this.#socket;
345
- }
346
- get host() {
347
- return this.#host;
348
- }
349
- get port() {
350
- return this.#port;
351
- }
352
- get timeout() {
353
- return this.#timeout;
354
- }
355
- #connect() {
356
- return this.#socket || (this.#socket = new Promise((resolve, reject) => {
357
- const socket = this.#factory({
358
- host: this.#host,
359
- port: this.#port,
360
- timeout: this.#timeout,
361
- onread: {
362
- buffer: this.#buffer,
363
- callback: (bytes, buffer) => {
364
- this.#decoder.append(buffer, 0, bytes);
365
- return true;
366
- }
367
- }
368
- });
369
- socket.on("timeout", () => socket.destroy(new Error("Timeout")));
370
- socket.on("error", reject);
371
- socket.on("close", () => {
372
- socketFinalizationRegistry.unregister(this);
373
- this.#socket = void 0;
374
- });
375
- socket.on("connect", () => {
376
- socketFinalizationRegistry.register(this, socket, this);
377
- socket.off("error", reject);
378
- socket.on("error", (error) => {
379
- for (const deferred of this.#defers.values()) {
380
- process.nextTick(() => deferred.reject(error));
381
- }
382
- this.#defers.clear();
383
- this.#socket = void 0;
384
- });
385
- socket.unref();
386
- resolve(socket);
387
- });
388
- }));
389
- }
390
- #receive(packet) {
391
- const deferred = this.#defers.get(packet.sequence);
392
- if (deferred) {
393
- if (deferred.opcode === packet.opcode) {
394
- if (packet.opcode === 16 /* STAT */ && packet.key.length !== 0) {
395
- return deferred.append(packet);
396
- }
397
- return deferred.resolve(packet);
398
- } else {
399
- const sent = `0x${deferred.opcode.toString(16).padStart(2, "0")}`;
400
- const received = `0x${packet.opcode.toString(16).padStart(2, "0")}`;
401
- return deferred.reject(new Error(`Opcode mismatch (sent=${sent}, received=${received})`));
402
- }
403
- }
404
- }
405
- async send(packet) {
406
- const sequence = ++this.#sequence;
407
- const buffer = this.#encoder.encode(packet, sequence);
408
- const deferred = new Deferred(packet.opcode);
409
- this.#defers.set(sequence, deferred);
410
- const socket = await this.#connect();
411
- socket.write(buffer, (error) => {
412
- buffer.recycle();
413
- if (error)
414
- return deferred.reject(error);
415
- });
416
- const timeout = setTimeout(() => deferred.reject(new Error("No response")), this.#timeout);
417
- return deferred.promise.finally(() => {
418
- clearTimeout(timeout);
419
- this.#defers.delete(sequence);
420
- });
421
- }
422
- async destroy() {
423
- const socket = await this.#socket;
424
- if (!socket)
425
- return false;
426
- return new Promise((resolve, reject) => {
427
- socket.once("error", reject).once("close", resolve).destroy();
428
- });
429
- }
430
- };
431
-
432
- // src/server.ts
433
- var statsBigInt = [
434
- "auth_cmds",
435
- "auth_errors",
436
- "bytes",
437
- "bytes_read",
438
- "bytes_written",
439
- "cas_badval",
440
- "cas_hits",
441
- "cas_misses",
442
- "cmd_flush",
443
- "cmd_get",
444
- "cmd_set",
445
- "cmd_touch",
446
- "conn_yields",
447
- "crawler_items_checked",
448
- "crawler_reclaimed",
449
- "curr_items",
450
- "decr_hits",
451
- "decr_misses",
452
- "delete_hits",
453
- "delete_misses",
454
- "direct_reclaims",
455
- "evicted_active",
456
- "evicted_unfetched",
457
- "evictions",
458
- "expired_unfetched",
459
- "get_expired",
460
- "get_flushed",
461
- "get_hits",
462
- "get_misses",
463
- "hash_bytes",
464
- "idle_kicks",
465
- "incr_hits",
466
- "incr_misses",
467
- "limit_maxbytes",
468
- "listen_disabled_num",
469
- "log_watcher_sent",
470
- "log_watcher_skipped",
471
- "log_watchers",
472
- "log_worker_dropped",
473
- "log_worker_written",
474
- "lru_crawler_running",
475
- "lru_crawler_starts",
476
- "lru_maintainer_juggles",
477
- "lrutail_reflocked",
478
- "malloc_fails",
479
- "moves_to_cold",
480
- "moves_to_warm",
481
- "moves_within_lru",
482
- "read_buf_bytes",
483
- "read_buf_bytes_free",
484
- "read_buf_count",
485
- "read_buf_oom",
486
- "reclaimed",
487
- "rejected_connections",
488
- "response_obj_bytes",
489
- "response_obj_count",
490
- "response_obj_oom",
491
- "round_robin_fallback",
492
- "slab_reassign_busy_deletes",
493
- "slab_reassign_busy_items",
494
- "slab_reassign_chunk_rescues",
495
- "slab_reassign_evictions_nomem",
496
- "slab_reassign_inline_reclaim",
497
- "slab_reassign_rescues",
498
- "slabs_moved",
499
- "store_no_memory",
500
- "store_too_large",
501
- "time_in_listen_disabled_us",
502
- "total_items",
503
- "touch_hits",
504
- "touch_misses",
505
- "unexpected_napi_ids"
506
- ];
507
- var statsNumber = [
508
- "connection_structures",
509
- "curr_connections",
510
- "hash_power_level",
511
- "max_connections",
512
- "pid",
513
- "pointer_size",
514
- "reserved_fds",
515
- "slab_global_page_pool",
516
- "threads",
517
- "time",
518
- "total_connections",
519
- "uptime"
520
- ];
521
- var statsBoolean = ["accepting_conns", "hash_is_expanding", "slab_reassign_running"];
522
- var statsMicroseconds = ["rusage_system", "rusage_user"];
523
- function injectStats(key, value, stats) {
524
- if (!key)
525
- return stats;
526
- if (statsBigInt.includes(key)) {
527
- stats[key] = BigInt(value);
528
- } else if (statsNumber.includes(key)) {
529
- stats[key] = Number(value);
530
- } else if (statsBoolean.includes(key)) {
531
- stats[key] = !!Number(value);
532
- } else if (statsMicroseconds.includes(key)) {
533
- const splits = value.split(".");
534
- stats[key] = BigInt(`${splits[0]}${splits[1].padEnd(6, "0")}`);
535
- } else {
536
- stats[key] = value;
537
- }
538
- return stats;
539
- }
540
- function fail(packet, key) {
541
- const message = packet.value.toString("utf-8") || "Unknown Error";
542
- const status = STATUS[packet.status] || `0x${packet.status.toString(16).padStart(4, "0")}`;
543
- throw new Error(`${message} (status=${status}${key ? `, key=${key}` : ""})`);
544
- }
545
- var ServerAdapter = class {
546
- #buffer = Buffer.alloc(251 /* KEY_TOO_BIG */ + 20);
547
- #connection;
548
- #ttl;
549
- #id;
550
- constructor(options) {
551
- this.#connection = new Connection(options);
552
- this.#ttl = options.ttl || 0;
553
- this.#id = `${this.#connection.host}:${this.#connection.port}`;
554
- }
555
- get connected() {
556
- return this.#connection.connected;
557
- }
558
- get host() {
559
- return this.#connection.host;
560
- }
561
- get port() {
562
- return this.#connection.port;
563
- }
564
- get timeout() {
565
- return this.#connection.timeout;
566
- }
567
- get ttl() {
568
- return this.#ttl;
569
- }
570
- get id() {
571
- return this.#id;
572
- }
573
- #writeKey(key, offset2 = 0) {
574
- const keyLength = this.#buffer.write(key, offset2, 251 /* KEY_TOO_BIG */, "utf-8");
575
- if (keyLength > 250 /* KEY_SIZE */)
576
- throw new Error(`Key too long (len=${keyLength})`);
577
- return keyLength;
578
- }
579
- async #get(key, ttl) {
580
- let keyOffset = 0;
581
- if (ttl !== void 0)
582
- keyOffset = this.#buffer.writeUInt32BE(ttl);
583
- const keyLength = this.#writeKey(key, keyOffset);
584
- const [response] = await this.#connection.send({
585
- opcode: ttl ? 29 /* GAT */ : 0 /* GET */,
586
- extras: this.#buffer,
587
- extrasOffset: 0,
588
- extrasLength: keyOffset,
589
- key: this.#buffer,
590
- keyOffset,
591
- keyLength
592
- });
593
- switch (response.status) {
594
- case 0 /* OK */:
595
- return {
596
- value: response.value,
597
- flags: response.extras.readUInt32BE(),
598
- cas: response.cas,
599
- recycle: () => response.recycle()
600
- };
601
- case 1 /* KEY_NOT_FOUND */:
602
- return;
603
- default:
604
- fail(response, key);
605
- }
606
- }
607
- async get(key) {
608
- return this.#get(key);
609
- }
610
- async gat(key, ttl) {
611
- return this.#get(key, ttl || 2592e3);
612
- }
613
- async touch(key, ttl) {
614
- const timeToLive = ttl ?? this.#ttl;
615
- const keyOffset = this.#buffer.writeUInt32BE(timeToLive);
616
- const keyLength = this.#writeKey(key, keyOffset);
617
- const [response] = await this.#connection.send({
618
- opcode: 28 /* TOUCH */,
619
- extras: this.#buffer,
620
- extrasOffset: 0,
621
- extrasLength: keyOffset,
622
- key: this.#buffer,
623
- keyOffset,
624
- keyLength
625
- });
626
- try {
627
- switch (response.status) {
628
- case 0 /* OK */:
629
- return true;
630
- case 1 /* KEY_NOT_FOUND */:
631
- return false;
632
- default:
633
- fail(response, key);
634
- }
635
- } finally {
636
- response.recycle();
637
- }
638
- }
639
- async #sar(opcode, key, value, options) {
640
- const { flags = 0, cas = 0n, ttl = this.#ttl } = options;
641
- let keyOffset;
642
- keyOffset = this.#buffer.writeUInt32BE(flags);
643
- keyOffset = this.#buffer.writeUInt32BE(ttl, keyOffset);
644
- const keyLength = this.#writeKey(key, keyOffset);
645
- const [response] = await this.#connection.send({
646
- opcode,
647
- cas,
648
- extras: this.#buffer,
649
- extrasOffset: 0,
650
- extrasLength: keyOffset,
651
- key: this.#buffer,
652
- keyOffset,
653
- keyLength,
654
- value
655
- });
656
- try {
657
- switch (response.status) {
658
- case 0 /* OK */:
659
- return response.cas;
660
- case 1 /* KEY_NOT_FOUND */:
661
- case 2 /* KEY_EXISTS */:
662
- return;
663
- default:
664
- fail(response, key);
665
- }
666
- } finally {
667
- response.recycle();
668
- }
669
- }
670
- set(key, value, options = {}) {
671
- return this.#sar(1 /* SET */, key, value, options);
672
- }
673
- add(key, value, options = {}) {
674
- return this.#sar(2 /* ADD */, key, value, options);
675
- }
676
- replace(key, value, options = {}) {
677
- return this.#sar(3 /* REPLACE */, key, value, options);
678
- }
679
- async #pend(opcode, key, value, options) {
680
- const { cas = 0n } = options;
681
- const keyLength = this.#writeKey(key);
682
- const [response] = await this.#connection.send({
683
- opcode,
684
- cas,
685
- key: Buffer.from(key, "utf-8"),
686
- keyOffset: 0,
687
- keyLength,
688
- value
689
- });
690
- try {
691
- switch (response.status) {
692
- case 0 /* OK */:
693
- return true;
694
- case 5 /* ITEM_NOT_STORED */:
695
- case 2 /* KEY_EXISTS */:
696
- return false;
697
- default:
698
- fail(response, key);
699
- }
700
- } finally {
701
- response.recycle();
702
- }
703
- }
704
- append(key, value, options = {}) {
705
- return this.#pend(14 /* APPEND */, key, value, options);
706
- }
707
- prepend(key, value, options = {}) {
708
- return this.#pend(15 /* PREPEND */, key, value, options);
709
- }
710
- async #counter(opcode, key, delta, options) {
711
- const {
712
- initial,
713
- cas = 0n,
714
- ttl = this.#ttl
715
- } = options;
716
- let keyOffset;
717
- keyOffset = this.#buffer.writeBigUInt64BE(BigInt(delta));
718
- keyOffset = this.#buffer.writeBigUInt64BE(BigInt(initial || 0n), keyOffset);
719
- keyOffset = this.#buffer.writeUInt32BE(initial == void 0 ? 4294967295 : ttl, keyOffset);
720
- const keyLength = this.#writeKey(key, keyOffset);
721
- const [response] = await this.#connection.send({
722
- opcode,
723
- extras: this.#buffer,
724
- extrasOffset: 0,
725
- extrasLength: keyOffset,
726
- key: this.#buffer,
727
- keyOffset,
728
- keyLength,
729
- cas
730
- });
731
- try {
732
- switch (response.status) {
733
- case 0 /* OK */:
734
- return {
735
- value: response.value.readBigUInt64BE(0),
736
- cas: response.cas
737
- };
738
- case 1 /* KEY_NOT_FOUND */:
739
- case 2 /* KEY_EXISTS */:
740
- return;
741
- default:
742
- fail(response, key);
743
- }
744
- } finally {
745
- response.recycle();
746
- }
747
- }
748
- increment(key, delta = 1, options = {}) {
749
- return this.#counter(5 /* INCREMENT */, key, delta, options);
750
- }
751
- decrement(key, delta = 1, options = {}) {
752
- return this.#counter(6 /* DECREMENT */, key, delta, options);
753
- }
754
- async delete(key, options = {}) {
755
- const { cas = 0n } = options;
756
- const keyLength = this.#writeKey(key);
757
- const [response] = await this.#connection.send({
758
- opcode: 4 /* DELETE */,
759
- key: this.#buffer,
760
- keyOffset: 0,
761
- keyLength,
762
- cas
763
- });
764
- try {
765
- switch (response.status) {
766
- case 0 /* OK */:
767
- return true;
768
- case 1 /* KEY_NOT_FOUND */:
769
- case 2 /* KEY_EXISTS */:
770
- return false;
771
- default:
772
- fail(response, key);
773
- }
774
- } finally {
775
- response.recycle();
776
- }
777
- }
778
- async flush(ttl = 0) {
779
- const extrasLength = ttl ? this.#buffer.writeUInt32BE(ttl) : 0;
780
- const [response] = await this.#connection.send({
781
- opcode: 8 /* FLUSH */,
782
- extras: this.#buffer,
783
- extrasOffset: 0,
784
- extrasLength
785
- });
786
- try {
787
- switch (response.status) {
788
- case 0 /* OK */:
789
- return;
790
- default:
791
- fail(response);
792
- }
793
- } finally {
794
- response.recycle();
795
- }
796
- }
797
- async noop() {
798
- const [response] = await this.#connection.send({
799
- opcode: 10 /* NOOP */
800
- });
801
- try {
802
- switch (response.status) {
803
- case 0 /* OK */:
804
- return;
805
- default:
806
- fail(response);
807
- }
808
- } finally {
809
- response.recycle();
810
- }
811
- }
812
- async quit() {
813
- const [response] = await this.#connection.send({
814
- opcode: 7 /* QUIT */
815
- });
816
- try {
817
- switch (response.status) {
818
- case 0 /* OK */:
819
- return;
820
- default:
821
- fail(response);
822
- }
823
- } finally {
824
- response.recycle();
825
- }
826
- }
827
- async version() {
828
- const [response] = await this.#connection.send({
829
- opcode: 11 /* VERSION */
830
- });
831
- try {
832
- switch (response.status) {
833
- case 0 /* OK */:
834
- return { [this.#id]: response.value.toString("utf-8") };
835
- default:
836
- fail(response);
837
- }
838
- } finally {
839
- response.recycle();
840
- }
841
- }
842
- async stats() {
843
- const responses = await this.#connection.send({
844
- opcode: 16 /* STAT */
845
- });
846
- const stats = responses.reduce((result, packet) => {
847
- try {
848
- if (packet.status !== 0 /* OK */)
849
- fail(packet);
850
- const key = packet.key.toString("utf-8");
851
- const value = packet.value.toString("utf-8");
852
- return injectStats(key, value, result);
853
- } finally {
854
- packet.recycle();
855
- }
856
- }, {});
857
- return { [this.#id]: stats };
858
- }
859
- };
860
-
861
- // src/cluster.ts
862
- import assert4 from "assert";
863
- function parseHosts(hosts) {
864
- const result = [];
865
- if (!hosts)
866
- return result;
867
- for (const part of hosts.split(",")) {
868
- const [host, p] = part.split(":");
869
- const port = parseInt(p) || void 0;
870
- result.push({ host, port });
871
- }
872
- return result;
873
- }
874
- var ClusterAdapter = class {
875
- servers;
876
- ttl;
877
- constructor(serversOrOptions) {
878
- if (Array.isArray(serversOrOptions)) {
879
- this.servers = [...serversOrOptions];
880
- } else if (serversOrOptions) {
881
- const { ttl, timeout, hosts: defs } = serversOrOptions;
882
- const hosts = [];
883
- if (Array.isArray(defs)) {
884
- defs.forEach((def) => {
885
- if (typeof def === "string")
886
- hosts.push(...parseHosts(def));
887
- else
888
- hosts.push(__spreadValues({ port: 11211 }, def));
889
- });
890
- } else {
891
- hosts.push(...parseHosts(defs));
892
- }
893
- this.servers = hosts.map((host) => new ServerAdapter(__spreadValues({ ttl, timeout }, host)));
894
- } else {
895
- const hosts = parseHosts(process.env.MEMCACHED_HOSTS);
896
- const ttl = process.env.MEMCACHED_TTL && parseInt(process.env.MEMCACHED_TTL) || void 0;
897
- const timeout = process.env.MEMCACHED_TIMEOUT && parseInt(process.env.MEMCACHED_TIMEOUT) || void 0;
898
- this.servers = hosts.map((host) => new ServerAdapter(__spreadValues({ ttl, timeout }, host)));
899
- }
900
- if (this.servers.length < 1)
901
- throw new Error("No hosts configured");
902
- if (this.servers.length === 1)
903
- this.server = () => this.servers[0];
904
- this.ttl = this.servers[0].ttl;
905
- this.servers.slice(1).forEach((server) => {
906
- assert4.equal(server.ttl, this.ttl, `TTL Mismatch (${server.ttl} != ${this.ttl})`);
907
- });
908
- Object.freeze(this.servers);
909
- }
910
- server(key) {
911
- const length = key.length;
912
- let hash = 0;
913
- for (let i = 0; i < length; i++)
914
- hash = hash * 31 + key.charCodeAt(i);
915
- return this.servers[hash % this.servers.length];
916
- }
917
- get(key) {
918
- return this.server(key).get(key);
919
- }
920
- gat(key, ttl) {
921
- return this.server(key).gat(key, ttl);
922
- }
923
- touch(key, ttl) {
924
- return this.server(key).touch(key, ttl);
925
- }
926
- set(key, value, options) {
927
- return this.server(key).set(key, value, options);
928
- }
929
- add(key, value, options) {
930
- return this.server(key).add(key, value, options);
931
- }
932
- replace(key, value, options) {
933
- return this.server(key).replace(key, value, options);
934
- }
935
- append(key, value, options) {
936
- return this.server(key).append(key, value, options);
937
- }
938
- prepend(key, value, options) {
939
- return this.server(key).prepend(key, value, options);
940
- }
941
- increment(key, delta, options) {
942
- return this.server(key).increment(key, delta, options);
943
- }
944
- decrement(key, delta, options) {
945
- return this.server(key).decrement(key, delta, options);
946
- }
947
- delete(key, options) {
948
- return this.server(key).delete(key, options);
949
- }
950
- async flush(ttl) {
951
- await Promise.all(this.servers.map((server) => server.flush(ttl)));
952
- }
953
- async noop() {
954
- await Promise.all(this.servers.map((server) => server.noop()));
955
- }
956
- async quit() {
957
- await Promise.all(this.servers.map((server) => server.quit()));
958
- }
959
- async version() {
960
- const versions = await Promise.all(this.servers.map((server) => server.version()));
961
- return versions.reduce((v1, v2) => __spreadValues(__spreadValues({}, v1), v2));
962
- }
963
- async stats() {
964
- const stats = await Promise.all(this.servers.map((server) => server.stats()));
965
- return stats.reduce((v1, v2) => __spreadValues(__spreadValues({}, v1), v2));
966
- }
967
- };
968
-
969
- // src/client.ts
970
- import assert5 from "assert";
971
- import { types as types2 } from "util";
972
- function replacer(key, value) {
973
- if (typeof this[key] === "bigint")
974
- return ["\0__$BIGINT$__\0", this[key].toString()];
975
- if (this[key] instanceof Date)
976
- return ["\0__$DATE$__\0", this[key].toISOString()];
977
- if (this[key] instanceof Set)
978
- return ["\0__$SET$__\0", ...value];
979
- if (this[key] instanceof Map)
980
- return ["\0__$MAP$__\0", ...value.entries()];
981
- return value;
982
- }
983
- function reviver(key, value) {
984
- if (Array.isArray(value)) {
985
- switch (value[0]) {
986
- case "\0__$BIGINT$__\0":
987
- return BigInt(value[1]);
988
- case "\0__$DATE$__\0":
989
- return new Date(value[1]);
990
- case "\0__$SET$__\0":
991
- return new Set(value.slice(1));
992
- case "\0__$MAP$__\0":
993
- return new Map(value.slice(1));
994
- }
995
- }
996
- return value;
997
- }
998
- function toBuffer(value, options) {
999
- if (Buffer.isBuffer(value))
1000
- return [value, __spreadProps(__spreadValues({}, options), { flags: 0 /* BUFFER */ })];
1001
- switch (typeof value) {
1002
- case "bigint":
1003
- return [Buffer.from(value.toString(), "utf-8"), __spreadProps(__spreadValues({}, options), { flags: 3402235904 /* BIGINT */ })];
1004
- case "boolean":
1005
- return [Buffer.alloc(1, value ? 255 : 0), __spreadProps(__spreadValues({}, options), { flags: 3402235905 /* BOOLEAN */ })];
1006
- case "number":
1007
- return [Buffer.from(value.toString(), "utf-8"), __spreadProps(__spreadValues({}, options), { flags: 3402235906 /* NUMBER */ })];
1008
- case "string":
1009
- return [Buffer.from(value, "utf-8"), __spreadProps(__spreadValues({}, options), { flags: 3402235907 /* STRING */ })];
1010
- case "object":
1011
- break;
1012
- default:
1013
- assert5.fail(`Unable to store value of type "${typeof value}"`);
1014
- }
1015
- if (types2.isTypedArray(value)) {
1016
- const flags = typedArrayFlags(value);
1017
- const buffer = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
1018
- return [buffer, __spreadProps(__spreadValues({}, options), { flags })];
1019
- }
1020
- if (value === null)
1021
- return [EMPTY_BUFFER, __spreadProps(__spreadValues({}, options), { flags: 3402235918 /* NULL */ })];
1022
- const json = JSON.stringify(value, replacer);
1023
- return [Buffer.from(json, "utf-8"), __spreadProps(__spreadValues({}, options), { flags: 3402235919 /* JSON */ })];
1024
- }
1025
- function fromBuffer(result) {
1026
- try {
1027
- const { flags, value, cas } = result;
1028
- switch (flags) {
1029
- case 3402235904 /* BIGINT */:
1030
- return { value: BigInt(value.toString("utf-8")), cas };
1031
- case 3402235905 /* BOOLEAN */:
1032
- return { value: !!value[0], cas };
1033
- case 3402235906 /* NUMBER */:
1034
- return { value: Number(value.toString("utf-8")), cas };
1035
- case 3402235907 /* STRING */:
1036
- return { value: value.toString("utf-8"), cas };
1037
- case 3402235918 /* NULL */:
1038
- return { value: null, cas };
1039
- case 3402235919 /* JSON */:
1040
- return { value: JSON.parse(value.toString("utf-8"), reviver), cas };
1041
- case 3402235920 /* UINT8ARRAY */:
1042
- return { value: makeTypedArray(Uint8Array, value), cas };
1043
- case 3402235921 /* UINT8CLAMPEDARRAY */:
1044
- return { value: makeTypedArray(Uint8ClampedArray, value), cas };
1045
- case 3402235922 /* UINT16ARRAY */:
1046
- return { value: makeTypedArray(Uint16Array, value), cas };
1047
- case 3402235923 /* UINT32ARRAY */:
1048
- return { value: makeTypedArray(Uint32Array, value), cas };
1049
- case 3402235924 /* INT8ARRAY */:
1050
- return { value: makeTypedArray(Int8Array, value), cas };
1051
- case 3402235925 /* INT16ARRAY */:
1052
- return { value: makeTypedArray(Int16Array, value), cas };
1053
- case 3402235926 /* INT32ARRAY */:
1054
- return { value: makeTypedArray(Int32Array, value), cas };
1055
- case 3402235927 /* BIGUINT64ARRAY */:
1056
- return { value: makeTypedArray(BigUint64Array, value), cas };
1057
- case 3402235928 /* BIGINT64ARRAY */:
1058
- return { value: makeTypedArray(BigInt64Array, value), cas };
1059
- case 3402235929 /* FLOAT32ARRAY */:
1060
- return { value: makeTypedArray(Float32Array, value), cas };
1061
- case 3402235930 /* FLOAT64ARRAY */:
1062
- return { value: makeTypedArray(Float64Array, value), cas };
1063
- case 0 /* BUFFER */:
1064
- default:
1065
- return { value: Buffer.from(value), cas };
1066
- }
1067
- } finally {
1068
- result.recycle();
1069
- }
1070
- }
1071
- function makeTypedArray(constructor, source) {
1072
- const clone = Buffer.from(source);
1073
- const { buffer, byteOffset, byteLength } = clone;
1074
- return new constructor(buffer, byteOffset, byteLength / constructor.BYTES_PER_ELEMENT);
1075
- }
1076
- var MemxClient = class {
1077
- #adapter;
1078
- #prefix;
1079
- constructor(adapterOrOptions) {
1080
- if (!adapterOrOptions) {
1081
- this.#adapter = new ClusterAdapter();
1082
- } else if ("get" in adapterOrOptions) {
1083
- this.#adapter = adapterOrOptions;
1084
- } else if ("hosts" in adapterOrOptions) {
1085
- this.#adapter = new ClusterAdapter(adapterOrOptions);
1086
- }
1087
- this.#prefix = "";
1088
- assert5(this.#adapter, "Invalid client constructor arguments");
1089
- }
1090
- get adapter() {
1091
- return this.#adapter;
1092
- }
1093
- get prefix() {
1094
- return this.#prefix;
1095
- }
1096
- withPrefix(prefix) {
1097
- assert5(prefix, "Invalid prefix");
1098
- const client = new MemxClient(this.#adapter);
1099
- client.#prefix = prefix;
1100
- return client;
1101
- }
1102
- async get(key) {
1103
- const result = await this.#adapter.get(this.#prefix + key);
1104
- return result && fromBuffer(result).value;
1105
- }
1106
- async gat(key, ttl) {
1107
- const result = await this.#adapter.gat(this.#prefix + key, ttl);
1108
- return result && fromBuffer(result).value;
1109
- }
1110
- async getc(key) {
1111
- const result = await this.#adapter.get(this.#prefix + key);
1112
- return result && fromBuffer(result);
1113
- }
1114
- async gatc(key, ttl) {
1115
- const result = await this.#adapter.gat(this.#prefix + key, ttl);
1116
- return result && fromBuffer(result);
1117
- }
1118
- async set(key, value, options) {
1119
- return this.#adapter.set(this.#prefix + key, ...toBuffer(value, options));
1120
- }
1121
- async add(key, value, options) {
1122
- return this.#adapter.add(this.#prefix + key, ...toBuffer(value, options));
1123
- }
1124
- async replace(key, value, options) {
1125
- return this.#adapter.replace(this.#prefix + key, ...toBuffer(value, options));
1126
- }
1127
- append(key, value, options) {
1128
- return this.#adapter.append(this.#prefix + key, ...toBuffer(value, options));
1129
- }
1130
- prepend(key, value, options) {
1131
- return this.#adapter.prepend(this.#prefix + key, ...toBuffer(value, options));
1132
- }
1133
- async increment(key, delta, options) {
1134
- const counter = await this.#adapter.increment(this.#prefix + key, delta, options);
1135
- if ((options == null ? void 0 : options.initial) !== void 0 && (counter == null ? void 0 : counter.value) === BigInt(options.initial)) {
1136
- const cas = await this.replace(key, counter.value, { cas: counter.cas, ttl: options.ttl });
1137
- counter.cas = cas ?? counter.cas;
1138
- }
1139
- return counter;
1140
- }
1141
- async decrement(key, delta, options) {
1142
- const counter = await this.#adapter.decrement(this.#prefix + key, delta, options);
1143
- if ((options == null ? void 0 : options.initial) !== void 0 && (counter == null ? void 0 : counter.value) === BigInt(options.initial)) {
1144
- const cas = await this.replace(key, counter.value, { cas: counter.cas, ttl: options.ttl });
1145
- counter.cas = cas ?? counter.cas;
1146
- }
1147
- return counter;
1148
- }
1149
- touch(key, ttl) {
1150
- return this.#adapter.touch(this.#prefix + key, ttl);
1151
- }
1152
- delete(key, options) {
1153
- return this.#adapter.delete(this.#prefix + key, options);
1154
- }
1155
- flush(ttl) {
1156
- return this.#adapter.flush(ttl);
1157
- }
1158
- noop() {
1159
- return this.#adapter.noop();
1160
- }
1161
- quit() {
1162
- return this.#adapter.quit();
1163
- }
1164
- version() {
1165
- return this.#adapter.version();
1166
- }
1167
- stats() {
1168
- return this.#adapter.stats();
1169
- }
1170
- };
1171
-
1172
- // src/fake.ts
1173
- function toExp(ttl = 0) {
1174
- if (ttl === 0)
1175
- return Number.MAX_SAFE_INTEGER;
1176
- return Date.now() + ttl * 1e3;
1177
- }
1178
- var FakeAdapter = class {
1179
- #cache = /* @__PURE__ */ new Map();
1180
- #cas = 1n;
1181
- ttl = 0;
1182
- #get(key) {
1183
- if (key.length > 250)
1184
- throw new TypeError(`Key too long (len=${key.length})`);
1185
- const entry = this.#cache.get(key);
1186
- if (!entry)
1187
- return;
1188
- if (Date.now() > entry.exp) {
1189
- this.#cache.delete(key);
1190
- return;
1191
- }
1192
- return entry;
1193
- }
1194
- #set(key, value, flags, ttl) {
1195
- this.#cache.set(key, {
1196
- value,
1197
- flags: flags || 0,
1198
- cas: ++this.#cas,
1199
- exp: toExp(ttl)
1200
- });
1201
- return this.#cas;
1202
- }
1203
- async get(key) {
1204
- const entry = this.#get(key);
1205
- if (!entry)
1206
- return;
1207
- return {
1208
- value: entry.value,
1209
- flags: entry.flags,
1210
- cas: entry.cas,
1211
- recycle: () => void 0
1212
- };
1213
- }
1214
- async gat(key, ttl) {
1215
- const entry = this.#get(key);
1216
- if (!entry)
1217
- return;
1218
- entry.exp = toExp(ttl);
1219
- return {
1220
- value: entry.value,
1221
- flags: entry.flags,
1222
- cas: entry.cas,
1223
- recycle: () => void 0
1224
- };
1225
- }
1226
- async touch(key, ttl) {
1227
- const entry = this.#get(key);
1228
- if (entry)
1229
- entry.exp = toExp(ttl);
1230
- return !!entry;
1231
- }
1232
- async set(key, value, options = {}) {
1233
- const entry = this.#get(key);
1234
- if (entry && options.cas !== void 0 && entry.cas !== options.cas) {
1235
- return;
1236
- }
1237
- return this.#set(key, value, options.flags, options.ttl);
1238
- }
1239
- async add(key, value, options = {}) {
1240
- if (this.#get(key))
1241
- return;
1242
- return this.#set(key, value, options.flags, options.ttl);
1243
- }
1244
- async replace(key, value, options = {}) {
1245
- if (!this.#get(key))
1246
- return;
1247
- return this.#set(key, value, options.flags, options.ttl);
1248
- }
1249
- async append(key, value, options = {}) {
1250
- const entry = this.#get(key);
1251
- if (!entry)
1252
- return false;
1253
- if (options.cas !== void 0 && options.cas !== entry.cas)
1254
- return false;
1255
- entry.value = Buffer.concat([entry.value, value]);
1256
- return true;
1257
- }
1258
- async prepend(key, value, options = {}) {
1259
- const entry = this.#get(key);
1260
- if (!entry)
1261
- return false;
1262
- if (options.cas !== void 0 && options.cas !== entry.cas)
1263
- return false;
1264
- entry.value = Buffer.concat([value, entry.value]);
1265
- return true;
1266
- }
1267
- async #counter(key, delta, options) {
1268
- const entry = this.#get(key);
1269
- if (!entry) {
1270
- if (options.initial !== void 0) {
1271
- const value = Buffer.from(options.initial.toString());
1272
- this.#set(key, value, void 0, options.ttl);
1273
- return { value: BigInt(options.initial), cas: this.#cas };
1274
- } else {
1275
- return;
1276
- }
1277
- }
1278
- if (options.cas !== void 0 && options.cas !== entry.cas)
1279
- return;
1280
- try {
1281
- const value = BigInt(entry.value.toString("utf-8")) + BigInt(delta);
1282
- this.#set(key, Buffer.from(value.toString()), void 0, options.ttl);
1283
- return { value, cas: this.#cas };
1284
- } catch (error) {
1285
- throw new TypeError(`${error.message} (status=NON_NUMERIC_VALUE, key=${key})`);
1286
- }
1287
- }
1288
- increment(key, delta = 1n, options = {}) {
1289
- return this.#counter(key, delta, options);
1290
- }
1291
- decrement(key, delta = 1n, options = {}) {
1292
- return this.#counter(key, -delta, options);
1293
- }
1294
- async delete(key, options = {}) {
1295
- const entry = this.#get(key);
1296
- if (entry && options.cas !== void 0 && entry.cas !== options.cas) {
1297
- return false;
1298
- }
1299
- return this.#cache.delete(key);
1300
- }
1301
- async flush(ttl) {
1302
- if (!ttl)
1303
- return this.#cache.clear();
1304
- const wait = toExp(ttl) - Date.now();
1305
- setTimeout(() => this.#cache.clear(), wait);
1306
- }
1307
- async noop() {
1308
- }
1309
- async quit() {
1310
- }
1311
- async version() {
1312
- return { fake: "0.0.0-fake" };
1313
- }
1314
- async stats() {
1315
- return { fake: { version: "0.0.0-fake" } };
1316
- }
1317
- };
1318
- var MemxFakeClient = class extends MemxClient {
1319
- constructor() {
1320
- super(new FakeAdapter());
1321
- }
1322
- };
1323
-
1324
- // src/utils.ts
1325
- import assert6 from "assert";
1326
- var Factory = class {
1327
- #factory;
1328
- #client;
1329
- #ttl;
1330
- constructor(client, factory, ttl) {
1331
- assert6(typeof factory === "function", "Invalid or no factory specified");
1332
- assert6(client, "No client specified");
1333
- this.#factory = factory;
1334
- this.#client = client;
1335
- this.#ttl = ttl;
1336
- }
1337
- async get(key) {
1338
- const cached = await this.#client.getc(key);
1339
- if (cached) {
1340
- void logPromiseError(this.#client.touch(key), `Factory error touching key "${this.#client.prefix}${key}"`);
1341
- return cached.value;
1342
- }
1343
- const created = await this.#factory(key);
1344
- if (created) {
1345
- void logPromiseError(this.#client.set(key, created, { ttl: this.#ttl }), `Factory error setting key "${this.#client.prefix}${key}"`);
1346
- }
1347
- return created;
1348
- }
1349
- };
1350
- var Bundle = class {
1351
- #client;
1352
- #name;
1353
- #ttl;
1354
- constructor(client, name, ttl) {
1355
- assert6(client, "No client specified");
1356
- assert6(name, "No bundle name specified");
1357
- this.#client = client;
1358
- this.#name = name;
1359
- this.#ttl = ttl || 0;
1360
- }
1361
- async #appendKey(key) {
1362
- await logPromiseError((async () => {
1363
- const added = await this.#client.add(this.#name, key, { ttl: this.#ttl });
1364
- if (!added) {
1365
- await this.#client.append(this.#name, `\0${key}`);
1366
- await this.#client.touch(this.#name, this.#ttl);
1367
- }
1368
- })(), `Bundle "${this.#client.prefix}${this.#name}" error recording key "${key}"`);
1369
- }
1370
- async #removeKey(key) {
1371
- await logPromiseError((async () => {
1372
- const result = await this.#client.getc(this.#name);
1373
- if (!result)
1374
- return;
1375
- const keys = result.value.split("\0").filter((k) => k !== key).join("\0");
1376
- await this.#client.set(this.#name, keys, { cas: result.cas, ttl: this.#ttl });
1377
- })(), `Bundle "${this.#client.prefix}${this.#name}" error clearing key "${key}"`);
1378
- }
1379
- async add(key, value) {
1380
- await this.#client.set(`${this.#name}:${key}`, value, { ttl: this.#ttl });
1381
- await this.#appendKey(key);
1382
- }
1383
- async get(key) {
1384
- const result = await this.#client.getc(`${this.#name}:${key}`);
1385
- if (result)
1386
- return result.value;
1387
- await this.#removeKey(key);
1388
- }
1389
- async delete(key) {
1390
- await this.#client.delete(`${this.#name}:${key}`);
1391
- await this.#removeKey(key);
1392
- }
1393
- async list() {
1394
- const result = await this.#client.getc(this.#name);
1395
- if (!result)
1396
- return {};
1397
- const results = {};
1398
- const promises = [];
1399
- for (const key of new Set(result.value.split("\0"))) {
1400
- promises.push(this.#client.getc(`${this.#name}:${key}`).then((result2) => {
1401
- if (result2)
1402
- results[key] = result2.value;
1403
- }));
1404
- }
1405
- await Promise.all(promises);
1406
- await logPromiseError(this.#client.set(this.#name, Object.keys(results).join("\0"), { cas: result.cas, ttl: this.#ttl }), `Bundle "${this.#client.prefix}${this.#name}" error compacting keys`);
1407
- return results;
1408
- }
1409
- };
1410
- var PoorManLock = class {
1411
- #client;
1412
- #name;
1413
- constructor(client, name) {
1414
- assert6(client, "No client specified");
1415
- assert6(name, "No lock name specified");
1416
- this.#client = client;
1417
- this.#name = name;
1418
- }
1419
- async execute(executor, options) {
1420
- const { timeout = 5e3, owner = false } = options || {};
1421
- const end = Date.now() + timeout;
1422
- let cas;
1423
- do {
1424
- cas = await this.#client.add(this.#name, owner, { ttl: 2 });
1425
- if (cas !== void 0)
1426
- break;
1427
- await new Promise((resolve) => setTimeout(resolve, 100));
1428
- } while (Date.now() < end);
1429
- if (cas === void 0) {
1430
- const other = await this.#client.getc(this.#name);
1431
- const owner2 = other && other.value ? `"${other.value}"` : "anonymous";
1432
- throw new Error(`Lock "${this.#client.prefix}${this.#name}" timeout (owner=${owner2})`);
1433
- }
1434
- const interval = setInterval(() => {
1435
- void logPromiseError((async () => {
1436
- const replaced = await this.#client.replace(this.#name, owner, { ttl: 2, cas });
1437
- assert6(replaced !== void 0, `Lock "${this.#client.prefix}${this.#name}" not replaced`);
1438
- cas = replaced;
1439
- })(), `Error extending lock "${this.#client.prefix}${this.#name}"`);
1440
- }, 100);
1441
- try {
1442
- return await executor();
1443
- } finally {
1444
- clearInterval(interval);
1445
- await logPromiseError(this.#client.delete(this.#name, { cas }), `Error deleting lock "${this.#client.prefix}${this.#name}"`);
1446
- }
1447
- }
1448
- };
1
+ // index.ts
2
+ import * as decode from "./decode.mjs";
3
+ import * as encode from "./encode.mjs";
4
+ import * as constants from "./constants.mjs";
5
+ import * as connection from "./connection.mjs";
6
+ export * from "./fake.mjs";
7
+ export * from "./types.mjs";
8
+ export * from "./cluster.mjs";
9
+ export * from "./server.mjs";
10
+ export * from "./client.mjs";
11
+ export * from "./utils.mjs";
1449
12
  export {
1450
- Bundle,
1451
- ClusterAdapter,
1452
- Factory,
1453
- FakeAdapter,
1454
- MemxClient,
1455
- MemxFakeClient,
1456
- PoorManLock,
1457
- ServerAdapter,
1458
- connection_exports as connection,
1459
- constants_exports as constants,
1460
- decode_exports as decode,
1461
- encode_exports as encode
13
+ connection,
14
+ constants,
15
+ decode,
16
+ encode
1462
17
  };
1463
18
  //# sourceMappingURL=index.mjs.map