@tinyshed/tinystore 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +262 -0
  3. package/bin/tinystore.js +50 -0
  4. package/dist/background.d.ts +30 -0
  5. package/dist/background.js +93 -0
  6. package/dist/blobs.d.ts +98 -0
  7. package/dist/blobs.js +299 -0
  8. package/dist/cancel.d.ts +14 -0
  9. package/dist/cancel.js +22 -0
  10. package/dist/clock.d.ts +21 -0
  11. package/dist/clock.js +35 -0
  12. package/dist/config.d.ts +60 -0
  13. package/dist/config.js +417 -0
  14. package/dist/connection.d.ts +78 -0
  15. package/dist/connection.js +405 -0
  16. package/dist/console.d.ts +48 -0
  17. package/dist/console.js +195 -0
  18. package/dist/errors.d.ts +103 -0
  19. package/dist/errors.js +158 -0
  20. package/dist/handles.d.ts +28 -0
  21. package/dist/handles.js +37 -0
  22. package/dist/index.d.ts +21 -0
  23. package/dist/index.js +7 -0
  24. package/dist/jobs.d.ts +304 -0
  25. package/dist/jobs.js +684 -0
  26. package/dist/kv.d.ts +283 -0
  27. package/dist/kv.js +815 -0
  28. package/dist/limiter.d.ts +45 -0
  29. package/dist/limiter.js +68 -0
  30. package/dist/logger.d.ts +96 -0
  31. package/dist/logger.js +243 -0
  32. package/dist/metrics.d.ts +249 -0
  33. package/dist/metrics.js +610 -0
  34. package/dist/once.d.ts +31 -0
  35. package/dist/once.js +116 -0
  36. package/dist/quota.d.ts +44 -0
  37. package/dist/quota.js +98 -0
  38. package/dist/records.d.ts +182 -0
  39. package/dist/records.js +346 -0
  40. package/dist/runtime/bun.d.ts +2 -0
  41. package/dist/runtime/bun.js +164 -0
  42. package/dist/runtime/node.d.ts +2 -0
  43. package/dist/runtime/node.js +157 -0
  44. package/dist/runtime/shared.d.ts +25 -0
  45. package/dist/runtime/shared.js +45 -0
  46. package/dist/runtime.d.ts +48 -0
  47. package/dist/runtime.js +4 -0
  48. package/dist/schema.d.ts +39 -0
  49. package/dist/schema.js +21 -0
  50. package/dist/session.d.ts +120 -0
  51. package/dist/session.js +546 -0
  52. package/dist/sql.d.ts +121 -0
  53. package/dist/sql.js +342 -0
  54. package/dist/store.d.ts +103 -0
  55. package/dist/store.js +153 -0
  56. package/dist/time.d.ts +35 -0
  57. package/dist/time.js +44 -0
  58. package/dist/trace.d.ts +18 -0
  59. package/dist/trace.js +22 -0
  60. package/dist/wire/codec.d.ts +90 -0
  61. package/dist/wire/codec.js +383 -0
  62. package/dist/wire/frame.d.ts +41 -0
  63. package/dist/wire/frame.js +102 -0
  64. package/dist/wire/messages.d.ts +1403 -0
  65. package/dist/wire/messages.js +472 -0
  66. package/dist/wire/msgpack.d.ts +93 -0
  67. package/dist/wire/msgpack.js +680 -0
  68. package/package.json +40 -0
  69. package/src/background.ts +108 -0
  70. package/src/blobs.ts +437 -0
  71. package/src/cancel.ts +26 -0
  72. package/src/clock.ts +45 -0
  73. package/src/config.ts +501 -0
  74. package/src/connection.ts +512 -0
  75. package/src/console.ts +228 -0
  76. package/src/errors.ts +211 -0
  77. package/src/handles.ts +68 -0
  78. package/src/index.ts +92 -0
  79. package/src/jobs.ts +963 -0
  80. package/src/kv.ts +1093 -0
  81. package/src/limiter.ts +99 -0
  82. package/src/logger.ts +326 -0
  83. package/src/metrics.ts +896 -0
  84. package/src/once.ts +142 -0
  85. package/src/quota.ts +137 -0
  86. package/src/records.ts +537 -0
  87. package/src/runtime/bun.ts +190 -0
  88. package/src/runtime/node.ts +177 -0
  89. package/src/runtime/shared.ts +61 -0
  90. package/src/runtime.ts +57 -0
  91. package/src/schema.ts +69 -0
  92. package/src/session.ts +665 -0
  93. package/src/sql.ts +478 -0
  94. package/src/store.ts +219 -0
  95. package/src/time.ts +87 -0
  96. package/src/trace.ts +32 -0
  97. package/src/wire/codec.ts +445 -0
  98. package/src/wire/frame.ts +139 -0
  99. package/src/wire/messages.ts +562 -0
  100. package/src/wire/msgpack.ts +712 -0
@@ -0,0 +1,98 @@
1
+ import { type Link } from './connection.ts';
2
+ import { type Page } from './handles.ts';
3
+ import { type Duration, type Time } from './time.ts';
4
+ import type { Key } from './wire/codec.ts';
5
+ export interface BlobObject {
6
+ /** its path under the folder that returned it */
7
+ key: string;
8
+ size: number;
9
+ /** quoted, as an HTTP header carries it: equal bytes, one ETag */
10
+ etag: string;
11
+ contentType: string | undefined;
12
+ modified: Date;
13
+ /** undefined for an object that does not expire */
14
+ expires: Date | undefined;
15
+ meta: Record<string, string>;
16
+ }
17
+ export interface WriteOptions {
18
+ contentType?: string;
19
+ /** replaces all of an object's meta; a copy keeps its source's when absent */
20
+ meta?: Record<string, string>;
21
+ ttl?: Duration;
22
+ expireAt?: Time;
23
+ /** writes only while the key holds a live object with one of these ETags, as If-Match spells them */
24
+ ifMatch?: string;
25
+ /** writes only where no live object is */
26
+ ifNoneMatch?: boolean;
27
+ }
28
+ export interface PutOptions extends WriteOptions {
29
+ /** the body's length, when it cannot say itself: one that disagrees leaves nothing */
30
+ size?: number;
31
+ signal?: AbortSignal;
32
+ }
33
+ /** What a put takes: bytes, text, a Blob or a file, or a stream of bytes. */
34
+ export type Body = Uint8Array | ArrayBuffer | string | Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
35
+ /** An object being read: what it is, and its bytes as a stream to consume or cancel. */
36
+ export interface Download extends BlobObject {
37
+ /** its bytes; a whole read whose bytes changed ends with CorruptError before its last */
38
+ readonly body: ReadableStream<Uint8Array>;
39
+ bytes(): Promise<Uint8Array>;
40
+ text(): Promise<string>;
41
+ json(): Promise<unknown>;
42
+ }
43
+ export declare class Blobs {
44
+ #private;
45
+ constructor(link: Link);
46
+ bucket(name: string, options?: {
47
+ defaultTtl?: Duration;
48
+ maxSize?: number;
49
+ }): BlobBucket;
50
+ }
51
+ /** A bucket's objects under one folder of owners, the root when there are none. */
52
+ export declare class BlobBucket {
53
+ #private;
54
+ readonly name: string;
55
+ constructor(link: Link, name: string, open: Uint8Array, owners: (string | Uint8Array)[]);
56
+ /** The folder below this one that the owners name, each a segment: `of('users', 7)`. */
57
+ of(...owners: Key[]): BlobBucket;
58
+ /** The object at a key, undefined when it holds none. */
59
+ stat(key: string): Promise<BlobObject | undefined>;
60
+ delete(key: string, options?: Pick<WriteOptions, 'ifMatch'>): Promise<void>;
61
+ /** Writes to a key an object naming the source's bytes, which are neither read nor written. */
62
+ copy(from: string, to: string, options?: WriteOptions): Promise<BlobObject>;
63
+ /** Copy and the source's removal in one write. */
64
+ move(from: string, to: string, options?: WriteOptions): Promise<BlobObject>;
65
+ /** The objects under this folder and their bytes, counted from their rows. */
66
+ usage(): Promise<{
67
+ objects: number;
68
+ bytes: number;
69
+ }>;
70
+ /** Removes this folder's objects and every folder's under it, at once however many. */
71
+ clear(): Promise<void>;
72
+ /** A page of the objects under this folder, its folders included, in the byte order of their paths. */
73
+ scan(options?: {
74
+ prefix?: string;
75
+ after?: string;
76
+ limit?: number;
77
+ }): Promise<Page<BlobObject, string>>;
78
+ all(options?: {
79
+ prefix?: string;
80
+ limit?: number;
81
+ }): AsyncGenerator<BlobObject>;
82
+ /**
83
+ * Writes an object, returning once it is durable: whatever the key held is
84
+ * replaced at the commit, whole, and an upload that does not commit leaves
85
+ * nothing. A Blob, a file among them, gives its size and its type.
86
+ */
87
+ put(key: string, body: Body, options?: PutOptions): Promise<BlobObject>;
88
+ /**
89
+ * Reads an object, undefined when the key holds none: what it is at once,
90
+ * and its bytes as its body is read. A range, from offset and length bytes
91
+ * long, is not checked against the object's hash.
92
+ */
93
+ get(key: string, options?: {
94
+ offset?: number;
95
+ length?: number;
96
+ signal?: AbortSignal;
97
+ }): Promise<Download | undefined>;
98
+ }
package/dist/blobs.js ADDED
@@ -0,0 +1,299 @@
1
+ // The application's files in blobs/, as Go's blobs package keeps them:
2
+ // objects under keys that are paths, their bytes streamed both ways in DATA
3
+ // of 64 KiB at most, a whole read checked against the object's hash.
4
+ import { download } from './connection.js';
5
+ import { ClosedError, InvalidError, OutcomeUnknownError } from './errors.js';
6
+ import { checkName, handleOn } from './handles.js';
7
+ import { LostError, watch } from './session.js';
8
+ import { dateOf, ms, unixMs } from './time.js';
9
+ import { BlobsBucket, BlobsCall, BlobsObject, BlobsPage, BlobsTotal, methods, } from './wire/messages.js';
10
+ /** The most a DATA frame carries, so that no transfer holds the connection long. */
11
+ const chunk = 64 << 10;
12
+ export class Blobs {
13
+ #link;
14
+ constructor(link) {
15
+ this.#link = link;
16
+ }
17
+ bucket(name, options) {
18
+ checkName(name, 'bucket');
19
+ const open = BlobsBucket.encode({
20
+ name,
21
+ defaultTtl: options?.defaultTtl === undefined ? undefined : ms(options.defaultTtl),
22
+ maxSize: options?.maxSize,
23
+ });
24
+ return new BlobBucket(this.#link, name, open, []);
25
+ }
26
+ }
27
+ function ownerText(owner) {
28
+ if (typeof owner === 'number' || typeof owner === 'bigint') {
29
+ if (typeof owner === 'number' && !Number.isSafeInteger(owner)) {
30
+ throw new InvalidError(`the owner ${owner} is not an integer; an owner is text or an integer`);
31
+ }
32
+ return String(owner);
33
+ }
34
+ return owner;
35
+ }
36
+ const lossy = new TextDecoder();
37
+ function objectOf(o) {
38
+ const meta = {};
39
+ for (const [name, value] of Object.entries(o.meta ?? {})) {
40
+ meta[name] = typeof value === 'string' ? value : lossy.decode(value);
41
+ }
42
+ return {
43
+ key: o.key ?? '',
44
+ size: o.size ?? 0,
45
+ etag: o.etag ?? '',
46
+ contentType: o.contentType,
47
+ modified: new Date(o.modified ?? 0),
48
+ expires: dateOf(o.expires),
49
+ meta,
50
+ };
51
+ }
52
+ function writeFields(options) {
53
+ return {
54
+ contentType: options?.contentType,
55
+ meta: options?.meta,
56
+ ttl: options?.ttl === undefined ? undefined : ms(options.ttl),
57
+ expireAt: options?.expireAt === undefined ? undefined : unixMs(options.expireAt),
58
+ ifMatch: options?.ifMatch,
59
+ ifNoneMatch: options?.ifNoneMatch === true ? true : undefined,
60
+ };
61
+ }
62
+ /** A bucket's objects under one folder of owners, the root when there are none. */
63
+ export class BlobBucket {
64
+ name;
65
+ #link;
66
+ #open;
67
+ #owners;
68
+ constructor(link, name, open, owners) {
69
+ this.#link = link;
70
+ this.name = name;
71
+ this.#open = open;
72
+ this.#owners = owners;
73
+ }
74
+ /** The folder below this one that the owners name, each a segment: `of('users', 7)`. */
75
+ of(...owners) {
76
+ return new BlobBucket(this.#link, this.name, this.#open, [
77
+ ...this.#owners,
78
+ ...owners.map(ownerText),
79
+ ]);
80
+ }
81
+ async #call(connection, fields) {
82
+ const handle = await handleOn(connection, methods['blobs.open'], this.#open);
83
+ return BlobsCall.encode({
84
+ handle,
85
+ owners: this.#owners.length > 0 ? this.#owners : undefined,
86
+ ...fields,
87
+ });
88
+ }
89
+ async #one(method, fields, idempotence) {
90
+ return this.#link.run(idempotence, async (connection) => connection.session.call(methods[method], await this.#call(connection, fields)));
91
+ }
92
+ /** The object at a key, undefined when it holds none. */
93
+ async stat(key) {
94
+ const o = BlobsObject.decode(await this.#one('blobs.stat', { key }, 'read'));
95
+ return o.found === true ? objectOf(o) : undefined;
96
+ }
97
+ async delete(key, options) {
98
+ await this.#one('blobs.delete', { key, ifMatch: options?.ifMatch }, 'write');
99
+ }
100
+ /** Writes to a key an object naming the source's bytes, which are neither read nor written. */
101
+ async copy(from, to, options) {
102
+ return objectOf(BlobsObject.decode(await this.#one('blobs.copy', { key: from, to, ...writeFields(options) }, 'write')));
103
+ }
104
+ /** Copy and the source's removal in one write. */
105
+ async move(from, to, options) {
106
+ return objectOf(BlobsObject.decode(await this.#one('blobs.move', { key: from, to, ...writeFields(options) }, 'write')));
107
+ }
108
+ /** The objects under this folder and their bytes, counted from their rows. */
109
+ async usage() {
110
+ const total = BlobsTotal.decode(await this.#one('blobs.usage', {}, 'read'));
111
+ return { objects: total.objects ?? 0, bytes: total.bytes ?? 0 };
112
+ }
113
+ /** Removes this folder's objects and every folder's under it, at once however many. */
114
+ async clear() {
115
+ await this.#one('blobs.clear', {}, 'write');
116
+ }
117
+ /** A page of the objects under this folder, its folders included, in the byte order of their paths. */
118
+ async scan(options) {
119
+ const got = await this.#link.run('read', async (connection) => download(connection, methods['blobs.scan'], await this.#call(connection, {
120
+ prefix: options?.prefix,
121
+ after: options?.after,
122
+ limit: options?.limit,
123
+ })));
124
+ const page = BlobsPage.decode(got.trailer);
125
+ return {
126
+ items: got.items.map(item => objectOf(BlobsObject.decode(item))),
127
+ next: page.more === true ? (page.after ?? '') : undefined,
128
+ };
129
+ }
130
+ async *all(options) {
131
+ let after;
132
+ for (;;) {
133
+ const page = await this.scan({ ...options, ...(after === undefined ? {} : { after }) });
134
+ yield* page.items;
135
+ if (page.next === undefined) {
136
+ return;
137
+ }
138
+ after = page.next;
139
+ }
140
+ }
141
+ /**
142
+ * Writes an object, returning once it is durable: whatever the key held is
143
+ * replaced at the commit, whole, and an upload that does not commit leaves
144
+ * nothing. A Blob, a file among them, gives its size and its type.
145
+ */
146
+ async put(key, body, options) {
147
+ const source = sourceOf(body, options?.size);
148
+ const fields = {
149
+ ...writeFields(options),
150
+ contentType: options?.contentType ?? source.contentType,
151
+ };
152
+ return this.#link.run('write', async (connection) => {
153
+ const request = await this.#call(connection, { key, size: source.size, ...fields });
154
+ return upload(connection, request, source, options?.signal);
155
+ }, options?.signal);
156
+ }
157
+ /**
158
+ * Reads an object, undefined when the key holds none: what it is at once,
159
+ * and its bytes as its body is read. A range, from offset and length bytes
160
+ * long, is not checked against the object's hash.
161
+ */
162
+ async get(key, options) {
163
+ return this.#link.run('read', async (connection) => {
164
+ const request = await this.#call(connection, {
165
+ key,
166
+ offset: options?.offset,
167
+ length: options?.length,
168
+ });
169
+ const stream = await connection.session.open(methods['blobs.get'], request, true);
170
+ const unwatch = watch(options?.signal, stream);
171
+ const head = await stream.next().catch(err => {
172
+ unwatch();
173
+ throw err;
174
+ });
175
+ const o = BlobsObject.decode(head.body);
176
+ if (head.end || o.found !== true) {
177
+ unwatch();
178
+ return undefined;
179
+ }
180
+ return downloadOf(objectOf(o), stream, unwatch);
181
+ }, options?.signal);
182
+ }
183
+ }
184
+ function sourceOf(body, size) {
185
+ if (typeof body === 'string') {
186
+ body = new TextEncoder().encode(body);
187
+ }
188
+ if (body instanceof ArrayBuffer) {
189
+ body = new Uint8Array(body);
190
+ }
191
+ if (body instanceof Uint8Array) {
192
+ const bytes = body;
193
+ return {
194
+ size: size ?? bytes.length,
195
+ contentType: undefined,
196
+ replayable: true,
197
+ chunks: () => sliced(bytes),
198
+ };
199
+ }
200
+ if (body instanceof Blob) {
201
+ const blob = body;
202
+ const contentType = blob.type === '' ? undefined : blob.type;
203
+ return {
204
+ size: size ?? blob.size,
205
+ contentType,
206
+ replayable: true,
207
+ chunks: () => rechunked(blob.stream()),
208
+ };
209
+ }
210
+ const stream = body;
211
+ return { size, contentType: undefined, replayable: false, chunks: () => rechunked(stream) };
212
+ }
213
+ async function* sliced(bytes) {
214
+ for (let at = 0; at < bytes.length; at += chunk) {
215
+ yield bytes.subarray(at, at + chunk);
216
+ }
217
+ }
218
+ async function* rechunked(stream) {
219
+ for await (const piece of stream) {
220
+ yield* sliced(piece);
221
+ }
222
+ }
223
+ /**
224
+ * Sends a put's REQUEST, its bytes as DATA and the DATA that ends them, and
225
+ * waits for the object the commit wrote. A connection lost before that last
226
+ * DATA has left aborted the upload, which left nothing; lost after it, the
227
+ * commit's outcome is unknown.
228
+ */
229
+ async function upload(connection, request, source, signal) {
230
+ const stream = await connection.session.open(methods['blobs.put'], request, false);
231
+ const unwatch = watch(signal, stream);
232
+ let ended = false;
233
+ try {
234
+ let last;
235
+ for await (const piece of source.chunks()) {
236
+ if (piece.length === 0) {
237
+ continue;
238
+ }
239
+ if (last !== undefined) {
240
+ await stream.send(last, false);
241
+ }
242
+ last = piece;
243
+ }
244
+ ended = true;
245
+ await stream.send(last ?? new Uint8Array(0), true);
246
+ const answer = await stream.next();
247
+ return objectOf(BlobsObject.decode(answer.body));
248
+ }
249
+ catch (err) {
250
+ if (err instanceof LostError) {
251
+ if (ended) {
252
+ throw new OutcomeUnknownError(`the connection was lost as the upload committed: ${err.message}`);
253
+ }
254
+ if (!source.replayable) {
255
+ throw new ClosedError(`the connection was lost during the upload, which left nothing: ${err.message}`);
256
+ }
257
+ // the server aborted what it had of it, so the whole body goes again
258
+ throw new LostError(err.message, false);
259
+ }
260
+ stream.cancel();
261
+ throw err;
262
+ }
263
+ finally {
264
+ unwatch();
265
+ }
266
+ }
267
+ function downloadOf(object, stream, unwatch) {
268
+ const body = new ReadableStream({
269
+ async pull(controller) {
270
+ try {
271
+ const event = await stream.next();
272
+ stream.consumed(event.body.length);
273
+ if (event.body.length > 0) {
274
+ controller.enqueue(event.body);
275
+ }
276
+ if (event.end) {
277
+ unwatch();
278
+ controller.close();
279
+ }
280
+ }
281
+ catch (err) {
282
+ unwatch();
283
+ controller.error(err);
284
+ }
285
+ },
286
+ cancel() {
287
+ unwatch();
288
+ stream.cancel();
289
+ },
290
+ });
291
+ const bytes = async () => new Uint8Array(await new Response(body).arrayBuffer());
292
+ return {
293
+ ...object,
294
+ body,
295
+ bytes,
296
+ text: async () => new TextDecoder().decode(await bytes()),
297
+ json: async () => JSON.parse(new TextDecoder().decode(await bytes())),
298
+ };
299
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Runs fn under a signal: every call it makes, a kv get, a statement, a
3
+ * scan, rejects once the signal aborts, its stream cancelled on the wire. A
4
+ * call given a signal of its own, as work and put take one, keeps that one.
5
+ *
6
+ * ```ts
7
+ * await withSignal(AbortSignal.timeout(2000), async () => {
8
+ * const notes = await app.all`select * from notes`
9
+ * })
10
+ * ```
11
+ */
12
+ export declare function withSignal<T>(signal: AbortSignal, fn: () => T): T;
13
+ /** The signal the caller runs under, from withSignal. */
14
+ export declare function currentSignal(): AbortSignal | undefined;
package/dist/cancel.js ADDED
@@ -0,0 +1,22 @@
1
+ // The signal a call runs under, as a Go call carries its context: every call
2
+ // made inside withSignal, and inside what it awaits, ends when it aborts.
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+ const carried = new AsyncLocalStorage();
5
+ /**
6
+ * Runs fn under a signal: every call it makes, a kv get, a statement, a
7
+ * scan, rejects once the signal aborts, its stream cancelled on the wire. A
8
+ * call given a signal of its own, as work and put take one, keeps that one.
9
+ *
10
+ * ```ts
11
+ * await withSignal(AbortSignal.timeout(2000), async () => {
12
+ * const notes = await app.all`select * from notes`
13
+ * })
14
+ * ```
15
+ */
16
+ export function withSignal(signal, fn) {
17
+ return carried.run(signal, fn);
18
+ }
19
+ /** The signal the caller runs under, from withSignal. */
20
+ export function currentSignal() {
21
+ return carried.getStore();
22
+ }
@@ -0,0 +1,21 @@
1
+ import type { Link } from './connection.ts';
2
+ import { type Duration, type Time } from './time.ts';
3
+ /**
4
+ * The clock of a store opened with `{ private: true, clock }`. Moving it
5
+ * forward expires keys, makes jobs due and ages records at once, as Go's
6
+ * tinystore.Options.Clock does; a store on the system's time refuses it with
7
+ * InvalidError.
8
+ *
9
+ * await using store = await open(dir, { private: true, clock: new Date('2026-10-03T09:00:00Z') })
10
+ * await store.clock.advance('1h')
11
+ */
12
+ export declare class Clock {
13
+ #private;
14
+ constructor(link: Link);
15
+ /** The time the server's clock reads. */
16
+ now(): Promise<Date>;
17
+ /** Moves the clock forward by a while, and gives the time it then reads. */
18
+ advance(by: Duration): Promise<Date>;
19
+ /** Sets the clock to a time, which may not be before its own, and gives it. */
20
+ set(to: Time): Promise<Date>;
21
+ }
package/dist/clock.js ADDED
@@ -0,0 +1,35 @@
1
+ // A test's clock: the time a private server opened with `clock` runs on, which
2
+ // a test moves forward rather than waits for.
3
+ import { ms, unixMs } from './time.js';
4
+ import { Clock as ClockMessage, methods } from './wire/messages.js';
5
+ /**
6
+ * The clock of a store opened with `{ private: true, clock }`. Moving it
7
+ * forward expires keys, makes jobs due and ages records at once, as Go's
8
+ * tinystore.Options.Clock does; a store on the system's time refuses it with
9
+ * InvalidError.
10
+ *
11
+ * await using store = await open(dir, { private: true, clock: new Date('2026-10-03T09:00:00Z') })
12
+ * await store.clock.advance('1h')
13
+ */
14
+ export class Clock {
15
+ #link;
16
+ constructor(link) {
17
+ this.#link = link;
18
+ }
19
+ /** The time the server's clock reads. */
20
+ now() {
21
+ return this.#move({});
22
+ }
23
+ /** Moves the clock forward by a while, and gives the time it then reads. */
24
+ advance(by) {
25
+ return this.#move({ advance: ms(by) });
26
+ }
27
+ /** Sets the clock to a time, which may not be before its own, and gives it. */
28
+ set(to) {
29
+ return this.#move({ at: unixMs(to) });
30
+ }
31
+ async #move(fields) {
32
+ const body = await this.#link.run('write', connection => connection.session.call(methods['server.clock'], ClockMessage.encode(fields)));
33
+ return new Date(Number(ClockMessage.decode(body).at ?? 0));
34
+ }
35
+ }
@@ -0,0 +1,60 @@
1
+ import type { Link } from './connection.ts';
2
+ import { type StandardSchemaV1 } from './schema.ts';
3
+ /** A value of T with any of its fields, at any depth, left out. */
4
+ export type DeepPartial<T> = {
5
+ [K in keyof T]?: T[K] extends readonly unknown[] ? T[K] : T[K] extends object ? DeepPartial<T[K]> : T[K];
6
+ };
7
+ export interface ConfigOptions<T> {
8
+ /** a file's values over the defaults, as Bun reads YAML, JSON or TOML: `import file from './config.yaml'` */
9
+ file?: DeepPartial<T>;
10
+ /** the variables' prefix: 'APP' reads APP_PORT; none when absent */
11
+ prefix?: string;
12
+ /** a field's own variable, by its path: `{ dbUrl: 'DATABASE_URL' }`; false reads none */
13
+ env?: Record<string, string> | false;
14
+ /** paths set by the defaults, the file or the environment alone: never kept, shown as *** */
15
+ secret?: readonly string[];
16
+ /** checks the config each time it is made: zod's, valibot's or another Standard Schema */
17
+ schema?: StandardSchemaV1<unknown, T>;
18
+ }
19
+ /** Where a field's value came from. */
20
+ export interface Source {
21
+ path: string;
22
+ /** its JSON, or *** for a secret */
23
+ value: string;
24
+ /** 'default', 'file', 'env NAME' or 'kept' */
25
+ from: string;
26
+ /** why a kept value is left out, when it is */
27
+ ignored?: string;
28
+ }
29
+ /**
30
+ * A field's variable: the prefix and its path in upper snake case, as Go's and
31
+ * Python's configs name it.
32
+ *
33
+ * 'APP', 'limits.maxRps' → APP_LIMITS_MAX_RPS
34
+ */
35
+ export declare function envName(prefix: string, path: string): string;
36
+ /** A config: open it with `store.kv.config(name, defaults, options)`. */
37
+ export declare class Config<T extends object> {
38
+ #private;
39
+ readonly name: string;
40
+ /** Configs come from `store.kv.config`, which waits for the first state. */
41
+ constructor(link: Link, name: string, defaults: T, options: ConfigOptions<T>);
42
+ /** The config now, frozen: update changes it. */
43
+ get value(): T;
44
+ /**
45
+ * Changes the fields change names, at any depth; each one that changed is
46
+ * checked, kept, and seen by every store watching the config. A change the
47
+ * schema refuses, or one of a secret, is InvalidError and keeps nothing.
48
+ */
49
+ update(change: DeepPartial<T>): Promise<void>;
50
+ /** Forgets what update kept for paths, each a field or a group of them; all of it without paths. */
51
+ reset(...paths: string[]): Promise<void>;
52
+ /** Calls fn with the config now and after each change, whoever made it; the function it returns stops that. */
53
+ watch(fn: (value: T) => void): () => void;
54
+ /** Where each field's value came from, and why a kept value is left out. */
55
+ sources(): Source[];
56
+ /** Follows the config's changes until the store closes; resolves once the first state is read. */
57
+ start(): Promise<void>;
58
+ /** Stops following the config, as the store does when it closes. */
59
+ stop(): void;
60
+ }