@tinyshed/tinystore 0.5.0 → 0.6.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.
package/dist/config.d.ts CHANGED
@@ -28,6 +28,12 @@ interface Described extends Rules {
28
28
  required?: boolean;
29
29
  live?: boolean;
30
30
  secret?: boolean;
31
+ /** of a map of entries, each entry's group; its kind is 'object', as an older release reads it */
32
+ entries?: Group;
33
+ /** of a chosen group, the key of the setting beside it whose value names its group */
34
+ chosenBy?: string;
35
+ /** of a chosen group, each group by the name its chooser gives it; its kind is 'object' too */
36
+ groups?: Record<string, Group>;
31
37
  }
32
38
  /**
33
39
  * A setting its declaration says more of than a default would: its rules, a
@@ -43,6 +49,23 @@ export interface Setting<V, Live extends boolean = false, Given extends boolean
43
49
  readonly '~given'?: Given;
44
50
  readonly '~secret'?: IsSecret;
45
51
  }
52
+ /**
53
+ * A map of named entries, as `entries` declares one: each entry the group
54
+ * `G`, read as its settings are.
55
+ */
56
+ export interface Entries<G> extends Setting<Readonly<Record<string, Value<G>>>> {
57
+ /** what an object in code gives each entry; nothing at run time */
58
+ readonly '~entries': G;
59
+ }
60
+ /**
61
+ * A group whose settings are those of one of `G`, the one a text setting
62
+ * beside it names, as `chosenBy` declares one: each of `G`'s groups read as
63
+ * its settings are.
64
+ */
65
+ export interface Chosen<G> extends Setting<Value<G[keyof G]>> {
66
+ /** what an object in code gives the group; nothing at run time */
67
+ readonly '~chosen': G;
68
+ }
46
69
  /** A setting's text that prints as *** wherever it goes; `reveal` gives it. */
47
70
  export declare class Secret {
48
71
  #private;
@@ -65,7 +88,7 @@ export type Changes<D> = {
65
88
  };
66
89
  /** An object in code over the declaration: any of its settings, at any depth, a secret as text. */
67
90
  export type Overlay<D> = {
68
- readonly [K in keyof D]?: D[K] extends Setting<infer V, boolean, boolean, boolean> ? V extends Secret ? string : V : D[K] extends readonly unknown[] ? Value<D[K]> : D[K] extends object ? Overlay<D[K]> : Value<D[K]>;
91
+ readonly [K in keyof D]?: D[K] extends Entries<infer G> ? Readonly<Record<string, Overlay<G>>> : D[K] extends Chosen<infer G> ? Overlay<G[keyof G]> : D[K] extends Setting<infer V, boolean, boolean, boolean> ? V extends Secret ? string : V : D[K] extends readonly unknown[] ? Value<D[K]> : D[K] extends object ? Overlay<D[K]> : Value<D[K]>;
69
92
  };
70
93
  /** A file a config reads: TOML, YAML or JSON by its extension. */
71
94
  export interface FileLayer {
@@ -182,6 +205,10 @@ export interface DurationBounds {
182
205
  min?: DurationText | undefined;
183
206
  max?: DurationText | undefined;
184
207
  }
208
+ /** The entries a map of entries' declaration gives, each as an object in code gives one. */
209
+ export interface EntriesOptions<G> {
210
+ default?: Readonly<Record<string, Overlay<G>>> | undefined;
211
+ }
185
212
  /** A list's default and how many items it holds at least and at most. */
186
213
  export interface ListOptions<V> extends Bounds {
187
214
  default?: readonly V[] | undefined;
@@ -221,6 +248,24 @@ export declare function duration(fallback: DurationText, rules?: DurationBounds)
221
248
  export declare function list<T extends Token>(item: T, options?: ListOptions<Of<T>>): Setting<readonly Of<T>[]>;
222
249
  export declare function list<V>(item: Setting<V, false, boolean>, options?: ListOptions<V>): Setting<readonly V[]>;
223
250
  export declare function list<G extends object>(item: G, options?: ListOptions<Value<G>>): Setting<readonly Value<G>[]>;
251
+ /**
252
+ * A map of named entries, each the group `item` declares, whose fields are
253
+ * settings of their own, with their own marks: a file gives an entry field
254
+ * by field, and `APP_INSTANCE_AIMEE_PASSWORD`, or its `_FILE`, one field of
255
+ * the entry `aimee` that a layer before it made. A map written as a value,
256
+ * `{}`, is one setting, given whole.
257
+ */
258
+ export declare function entries<G extends object>(item: G, options?: EntriesOptions<G>): Entries<G>;
259
+ /**
260
+ * A group whose settings are those of one of `groups`, the one the text
261
+ * setting beside it, `by`, names: `settings: chosenBy('plugin', { postgres,
262
+ * stripe })` reads an instance's settings as postgres's when its `plugin` is
263
+ * 'postgres'. Its fields are settings of their own, with their own marks; a
264
+ * field of a group not chosen is refused, and so is a `plugin` that names no
265
+ * group. A layer after the one that chose a group may choose another: then
266
+ * what the layers gave the first is dropped, and explain says so.
267
+ */
268
+ export declare function chosenBy<const G extends Readonly<Record<string, object>>>(by: string, groups: G): Chosen<G>;
224
269
  /** A file a config reads: TOML, YAML or JSON by its extension, a relative path the program's. */
225
270
  export declare function file(path: string, options?: FileOptions): FileLayer;
226
271
  /**
package/dist/config.js CHANGED
@@ -83,6 +83,7 @@ export function required(given) {
83
83
  if (inner === undefined) {
84
84
  throw new InvalidError('required takes String, Number, Boolean, or a rule without its default');
85
85
  }
86
+ refuseEntries(inner);
86
87
  if (inner.secret === true) {
87
88
  throw new InvalidError('a secret is required already: secret(String)');
88
89
  }
@@ -97,6 +98,7 @@ export function live(given) {
97
98
  throw new InvalidError('a mark goes on a setting, not on a group: mark each of its settings');
98
99
  }
99
100
  const inner = describedOf(given) ?? declaredValue(given, 'live');
101
+ refuseEntries(inner);
100
102
  if (inner.secret === true) {
101
103
  throw new InvalidError('a secret is never live');
102
104
  }
@@ -141,6 +143,7 @@ function itemOf(item) {
141
143
  }
142
144
  const inner = describedOf(item);
143
145
  if (inner !== undefined) {
146
+ refuseEntries(inner);
144
147
  if (inner.live === true || inner.secret === true) {
145
148
  throw new InvalidError("a list's items are neither live nor secret: the list is one setting");
146
149
  }
@@ -152,6 +155,57 @@ function itemOf(item) {
152
155
  }
153
156
  throw new InvalidError(`a list of ${String(item)}: of String, Number, Boolean, a rule or a group`);
154
157
  }
158
+ /**
159
+ * A map of named entries, each the group `item` declares, whose fields are
160
+ * settings of their own, with their own marks: a file gives an entry field
161
+ * by field, and `APP_INSTANCE_AIMEE_PASSWORD`, or its `_FILE`, one field of
162
+ * the entry `aimee` that a layer before it made. A map written as a value,
163
+ * `{}`, is one setting, given whole.
164
+ */
165
+ export function entries(item, options = {}) {
166
+ if (!isPlainObject(item) || describedOf(item) !== undefined || Object.keys(item).length === 0) {
167
+ throw new InvalidError('an entry is a group of settings: entries({ host: String, password: secret(String) })');
168
+ }
169
+ const described = {
170
+ kind: 'object',
171
+ default: options.default ?? {},
172
+ entries: declaredGroup(item, '*'),
173
+ };
174
+ return setting(described);
175
+ }
176
+ /**
177
+ * A group whose settings are those of one of `groups`, the one the text
178
+ * setting beside it, `by`, names: `settings: chosenBy('plugin', { postgres,
179
+ * stripe })` reads an instance's settings as postgres's when its `plugin` is
180
+ * 'postgres'. Its fields are settings of their own, with their own marks; a
181
+ * field of a group not chosen is refused, and so is a `plugin` that names no
182
+ * group. A layer after the one that chose a group may choose another: then
183
+ * what the layers gave the first is dropped, and explain says so.
184
+ */
185
+ export function chosenBy(by, groups) {
186
+ const named = Object.entries(groups);
187
+ if (typeof by !== 'string' || by === '' || !isPlainObject(groups) || named.length === 0) {
188
+ throw new InvalidError("a chosen group: chosenBy('plugin', { postgres: { host: String }, stripe: { key: secret(String) } })");
189
+ }
190
+ const declared = {};
191
+ for (const [name, group] of named) {
192
+ if (!isPlainObject(group) || describedOf(group) !== undefined) {
193
+ throw new InvalidError(`chosenBy: ${name} is a group of settings, not a setting`);
194
+ }
195
+ declared[name] = declaredGroup(group, name);
196
+ }
197
+ const described = { kind: 'object', default: {}, chosenBy: by, groups: declared };
198
+ return setting(described);
199
+ }
200
+ /** A mark around a map of entries or a chosen group, which marks none of their settings. */
201
+ function refuseEntries(inner) {
202
+ if (inner.entries !== undefined) {
203
+ throw new InvalidError('entries take no mark: each of their fields carries its own');
204
+ }
205
+ if (inner.groups !== undefined) {
206
+ throw new InvalidError('a chosen group takes no mark: each of its settings carries its own');
207
+ }
208
+ }
155
209
  /** A file a config reads: TOML, YAML or JSON by its extension, a relative path the program's. */
156
210
  export function file(path, options = {}) {
157
211
  return Object.freeze({ [layerMark]: 'file', path, optional: options.optional === true });
@@ -243,11 +297,22 @@ function plainItem(first) {
243
297
  return { kind: 'any' };
244
298
  }
245
299
  }
246
- /** Every setting's path, as the core names its variable. */
300
+ /** Every setting's path, as the core names its variable, every map of entries' and every chosen group's. */
247
301
  function paths(group, path) {
248
302
  return Object.entries(group).flatMap(([key, node]) => {
249
303
  const at = path === '' ? key : `${path}.${key}`;
250
- return 'group' in node ? paths(node.group, at) : [at];
304
+ if ('group' in node) {
305
+ return paths(node.group, at);
306
+ }
307
+ const chosen = Object.values(node.groups ?? {}).flatMap(inner => paths(inner, at));
308
+ return node.groups === undefined ? [at] : [...new Set(chosen)];
309
+ });
310
+ }
311
+ /** Every map of entries' path, whose entries' variables begin with its own. */
312
+ function entryMaps(group, path) {
313
+ return Object.entries(group).flatMap(([key, node]) => {
314
+ const at = path === '' ? key : `${path}.${key}`;
315
+ return 'group' in node ? entryMaps(node.group, at) : node.entries === undefined ? [] : [at];
251
316
  });
252
317
  }
253
318
  /**
@@ -320,11 +385,15 @@ async function envData(layer, declared) {
320
385
  const key = (name) => (windows ? name.toUpperCase() : name);
321
386
  const named = paths(declared, '').map(path => layer.vars[path] ?? envName(layer.prefix, path));
322
387
  const wanted = new Set(named.flatMap(name => [key(name), key(`${name}_FILE`)]));
323
- const start = key(`${layer.prefix}_`);
388
+ // an entry's field is named by its key, so its map's variable is what it begins with
389
+ const starts = entryMaps(declared, '').map(path => key(`${envName(layer.prefix, path)}_`));
390
+ if (layer.prefix !== '') {
391
+ starts.push(key(`${layer.prefix}_`));
392
+ }
324
393
  const variables = {};
325
394
  for (const [name, value] of Object.entries(layer.from ?? process.env)) {
326
395
  const k = key(name);
327
- if (value !== undefined && (wanted.has(k) || (layer.prefix !== '' && k.startsWith(start)))) {
396
+ if (value !== undefined && (wanted.has(k) || starts.some(start => k.startsWith(start)))) {
328
397
  variables[k] = value;
329
398
  }
330
399
  }
@@ -358,16 +427,34 @@ function fileVariables(text) {
358
427
  }
359
428
  return found;
360
429
  }
361
- /** A value as the program reads it: a duration spelled, a secret wrapped, all of it frozen. */
430
+ /**
431
+ * A value as the program reads it: a duration spelled, a secret wrapped, a
432
+ * chosen group as the group its chooser names, all of it frozen.
433
+ */
362
434
  function viewed(group, value) {
363
435
  const source = (isPlainObject(value) ? value : {});
364
436
  const out = {};
365
437
  for (const [key, node] of Object.entries(group)) {
366
- out[key] = 'group' in node ? viewed(node.group, source[key]) : viewedSetting(node, source[key]);
438
+ if ('group' in node) {
439
+ out[key] = viewed(node.group, source[key]);
440
+ }
441
+ else if (node.groups !== undefined) {
442
+ const name = source[node.chosenBy ?? ''];
443
+ const chosen = typeof name === 'string' ? node.groups[name] : undefined;
444
+ out[key] = viewed(chosen ?? {}, source[key]);
445
+ }
446
+ else {
447
+ out[key] = viewedSetting(node, source[key]);
448
+ }
367
449
  }
368
450
  return Object.freeze(out);
369
451
  }
370
452
  function viewedSetting(described, value) {
453
+ const item = described.entries;
454
+ if (item !== undefined) {
455
+ const each = Object.entries(isPlainObject(value) ? value : {});
456
+ return Object.freeze(Object.fromEntries(each.map(([key, entry]) => [key, viewed(item, entry)])));
457
+ }
371
458
  if (described.secret === true) {
372
459
  return new Secret(typeof value === 'string' ? value : '');
373
460
  }
@@ -462,7 +549,7 @@ function originOf(sent) {
462
549
  return { kind: sent.kind };
463
550
  }
464
551
  }
465
- /** The text the core's `from` says: crates/tinystore/src/kv/config/explain.rs, Origin's Display. */
552
+ /** The text the core's `from` says: crates/tinystore/src/config/explain.rs, Origin's Display. */
466
553
  function originText(origin) {
467
554
  switch (origin.kind) {
468
555
  case 'declaration':
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { Body, FileBytes, FileInfo, FileListOptions, FileOptions, FilePage,
3
3
  export { withSignal } from './cancel.ts';
4
4
  export type { Channel, EachOptions, Message as ChannelMessage, Missed, SubscribeOptions, Subscription, TxChannel, } from './channels.ts';
5
5
  export type { Clock } from './clock.ts';
6
- export { type Bounds, type Changes, type Config, type ConfigOptions, type DurationBounds, duration, type EnvLayer, type EnvOptions, type Explained, type ExplainGiven, type ExplainLine, type ExplainOrigin, env, type FileLayer, file, int, type Layer, list, live, type Overlay, oneOf, required, Secret, type Setting, secret, type UpdateOptions, type Value, type Vars, } from './config.ts';
6
+ export { type Bounds, type Changes, type Chosen, type Config, type ConfigOptions, chosenBy, type DurationBounds, duration, type Entries, type EntriesOptions, type EnvLayer, type EnvOptions, type Explained, type ExplainGiven, type ExplainLine, type ExplainOrigin, entries, env, type FileLayer, file, int, type Layer, list, live, type Overlay, oneOf, required, Secret, type Setting, secret, type UpdateOptions, type Value, type Vars, } from './config.ts';
7
7
  export type { Durability, SelfMetrics } from './connection.ts';
8
8
  export { type ConsoleFormat, type ConsoleTime, secrets } from './console.ts';
9
9
  export * from './errors.ts';
@@ -12,11 +12,11 @@ export type { Adding, AddOptions, Answer, Backoff, Concurrency, Handler, Job, Jo
12
12
  export type { Bucket, BucketOptions, Counters, CountersOptions, Entry, Page as KvPage, ValueType, WriteOptions, } from './kv.ts';
13
13
  export type { Allowance, Quota, Rate, RateLimit, RateLimitOptions, WindowUse } from './limits.ts';
14
14
  export type { HoldOptions, Lease, Lock, LockOptions, Permit, Semaphore, SemaphoreOptions, Tried, } from './locks.ts';
15
- export { type ConsoleOut, type Logger, type LoggerOptions, logger } from './logger.ts';
15
+ export { type ConsoleOut, colors, type Logger, type LoggerOptions, logger } from './logger.ts';
16
16
  export { type Aggregate, type AggregatePage, type AggregateQuery, type Bucket as MetricsBucket, type Buckets, type Condition as MetricsCondition, type Counter, type Damage as MetricsDamage, type Description as MetricsDescription, exponentialBuckets, type Gauge, type GaugeFuncOptions, type Histogram, type HistogramOptions, type InstrumentLabels, type InstrumentOptions, type LabelPage, type Labels, type LabelValue, type Metrics, type NameInfo, type NamePage, type Newest, type Op as MetricsOp, type PageOptions, type Percentile, type PercentileBucket, type Plan, type PrometheusOptions, type Query as MetricsQuery, type Series, type SeriesInput, type SeriesKind, type SeriesPage, type Timer, type TimerOptions, type Timing, type ValueBucket, type ValuePage, } from './metrics.ts';
17
17
  export type { Once, OnceOptions } from './once.ts';
18
18
  export type { ColumnType, Query, RowPage, Table, TableOptions, UpsertOptions } from './query.ts';
19
- export type { Aggregate as EventsAggregate, AllEvents, AppendOptions, Counted, Damage, Event, EventLevel, Events, EventsOptions, Fields, Level, Levels, Lines, NewEvent, Page as EventsPage, PollBatch, Query as EventsQuery, Row as EventsRow, Stats, StoreLoggerOptions, StreamInfo, TailBatch, TailQuery, Top, } from './records.ts';
19
+ export type { Aggregate as EventsAggregate, AllEvents, Appending, AppendOptions, Counted, Damage, Event, EventLevel, Events, EventsOptions, FieldInfo, Fields, Level, Levels, Lines, NameCount, NewEvent, Page as EventsPage, PollBatch, Query as EventsQuery, Row as EventsRow, Stats, StoreLoggerOptions, StreamFields, StreamInfo, TailBatch, TailQuery, Top, TxEvents, ValueKind, } from './records.ts';
20
20
  export type { StandardSchemaV1 } from './schema.ts';
21
21
  export { type Found as SearchFound, type Hit as SearchHit, type IndexDocument, type IndexInfo, type IndexOptions, type IndexStatus, type KeyboardLayout, type Match as SearchMatch, type Query as SearchQuery, SearchIndex, search, TableIndex, type TableIndexOptions, type Vector, type Where, type WhereValue, } from './search.ts';
22
22
  export { type Columns, type Database, type DatabaseOptions, type Done, type Migrations, type Row, Sql, type SqlArg, type SqlTag, type SqlTx, type SqlValue, type Statement, sql, } from './sql.ts';
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  export { withSignal } from './cancel.js';
2
- export { duration, env, file, int, list, live, oneOf, required, Secret, secret, } from './config.js';
2
+ export { chosenBy, duration, entries, env, file, int, list, live, oneOf, required, Secret, secret, } from './config.js';
3
3
  export { secrets } from './console.js';
4
4
  export * from './errors.js';
5
- export { logger } from './logger.js';
5
+ export { colors, logger } from './logger.js';
6
6
  export { exponentialBuckets, } from './metrics.js';
7
7
  export { SearchIndex, search, TableIndex, } from './search.js';
8
8
  export { Sql, sql, } from './sql.js';
package/dist/kv.js CHANGED
@@ -404,106 +404,114 @@ export const jsonValues = {
404
404
  }
405
405
  },
406
406
  };
407
+ /** A row of nothing reads as the empty string. */
408
+ const stringValues = {
409
+ encode: v => {
410
+ if (typeof v !== 'string') {
411
+ throw new InvalidError(`a ${typeof v} in a bucket of strings`);
412
+ }
413
+ return tagged(kinds.text, utf8.encode(v));
414
+ },
415
+ decode: raw => {
416
+ if (raw === null) {
417
+ return '';
418
+ }
419
+ const text = textOf(bodyOf(raw, kinds.text, 'text'));
420
+ if (text === undefined) {
421
+ throw new CorruptError('a stored value is text that is not UTF-8');
422
+ }
423
+ return text;
424
+ },
425
+ };
426
+ /** A row of nothing reads as no bytes. */
427
+ const bytesValues = {
428
+ keeps: true,
429
+ encode: v => {
430
+ if (!(v instanceof Uint8Array)) {
431
+ throw new InvalidError(`a ${typeof v} in a bucket of bytes`);
432
+ }
433
+ return tagged(kinds.bytes, v);
434
+ },
435
+ decode: raw => (raw === null ? new Uint8Array(0) : bodyOf(raw, kinds.bytes, 'bytes')),
436
+ };
437
+ const intValues = {
438
+ encode: v => {
439
+ if (typeof v !== 'number' || !Number.isSafeInteger(v)) {
440
+ throw new InvalidError(`${String(v)} is not an integer a number holds exactly; open the bucket with type 'bigint'`);
441
+ }
442
+ return BigInt(v);
443
+ },
444
+ decode: raw => {
445
+ if (typeof raw !== 'bigint') {
446
+ throw new CorruptError(`a stored value is ${describe(raw)} where an integer was written`);
447
+ }
448
+ if (raw > BigInt(Number.MAX_SAFE_INTEGER) || raw < BigInt(Number.MIN_SAFE_INTEGER)) {
449
+ throw new CorruptError(`${raw} does not fit a number exactly; open the bucket with type 'bigint'`);
450
+ }
451
+ return Number(raw);
452
+ },
453
+ };
454
+ const bigintValues = {
455
+ encode: v => {
456
+ if (typeof v !== 'bigint' && !(typeof v === 'number' && Number.isSafeInteger(v))) {
457
+ throw new InvalidError(`${String(v)} is not an integer`);
458
+ }
459
+ return BigInt(v);
460
+ },
461
+ decode: raw => {
462
+ if (typeof raw !== 'bigint') {
463
+ throw new CorruptError(`a stored value is ${describe(raw)} where an integer was written`);
464
+ }
465
+ return raw;
466
+ },
467
+ };
468
+ const floatValues = {
469
+ encode: v => {
470
+ if (typeof v !== 'number') {
471
+ throw new InvalidError(`a ${typeof v} in a bucket of floats`);
472
+ }
473
+ const bytes = new Uint8Array(8);
474
+ new DataView(bytes.buffer).setFloat64(0, v);
475
+ return tagged(kinds.float, bytes);
476
+ },
477
+ decode: raw => {
478
+ const bits = bodyOf(raw, kinds.float, 'a float');
479
+ if (bits.length !== 8) {
480
+ throw new CorruptError(`a float from ${bits.length} bytes rather than 8`);
481
+ }
482
+ return new DataView(bits.buffer, bits.byteOffset, 8).getFloat64(0);
483
+ },
484
+ };
485
+ const boolValues = {
486
+ encode: v => {
487
+ if (typeof v !== 'boolean') {
488
+ throw new InvalidError(`a ${typeof v} in a bucket of booleans`);
489
+ }
490
+ return v ? 1n : 0n;
491
+ },
492
+ decode: raw => {
493
+ if (typeof raw !== 'bigint') {
494
+ throw new CorruptError(`a stored value is ${describe(raw)} where a boolean was written`);
495
+ }
496
+ return raw !== 0n;
497
+ },
498
+ };
407
499
  export function valuesOf(type) {
408
500
  switch (type) {
409
501
  case undefined:
410
502
  return jsonValues;
411
503
  case 'string':
412
- return {
413
- encode: v => {
414
- if (typeof v !== 'string') {
415
- throw new InvalidError(`a ${typeof v} in a bucket of strings`);
416
- }
417
- return tagged(kinds.text, utf8.encode(v));
418
- },
419
- decode: raw => {
420
- if (raw === null) {
421
- return '';
422
- }
423
- const text = textOf(bodyOf(raw, kinds.text, 'text'));
424
- if (text === undefined) {
425
- throw new CorruptError('a stored value is text that is not UTF-8');
426
- }
427
- return text;
428
- },
429
- };
504
+ return stringValues;
430
505
  case 'bytes':
431
- return {
432
- keeps: true,
433
- encode: v => {
434
- if (!(v instanceof Uint8Array)) {
435
- throw new InvalidError(`a ${typeof v} in a bucket of bytes`);
436
- }
437
- return tagged(kinds.bytes, v);
438
- },
439
- decode: raw => (raw === null ? new Uint8Array(0) : bodyOf(raw, kinds.bytes, 'bytes')),
440
- };
506
+ return bytesValues;
441
507
  case 'int':
442
- return {
443
- encode: v => {
444
- if (typeof v !== 'number' || !Number.isSafeInteger(v)) {
445
- throw new InvalidError(`${String(v)} is not an integer a number holds exactly; open the bucket with type 'bigint'`);
446
- }
447
- return BigInt(v);
448
- },
449
- decode: raw => {
450
- if (typeof raw !== 'bigint') {
451
- throw new CorruptError(`a stored value is ${describe(raw)} where an integer was written`);
452
- }
453
- if (raw > BigInt(Number.MAX_SAFE_INTEGER) || raw < BigInt(Number.MIN_SAFE_INTEGER)) {
454
- throw new CorruptError(`${raw} does not fit a number exactly; open the bucket with type 'bigint'`);
455
- }
456
- return Number(raw);
457
- },
458
- };
508
+ return intValues;
459
509
  case 'bigint':
460
- return {
461
- encode: v => {
462
- if (typeof v !== 'bigint' && !(typeof v === 'number' && Number.isSafeInteger(v))) {
463
- throw new InvalidError(`${String(v)} is not an integer`);
464
- }
465
- return BigInt(v);
466
- },
467
- decode: raw => {
468
- if (typeof raw !== 'bigint') {
469
- throw new CorruptError(`a stored value is ${describe(raw)} where an integer was written`);
470
- }
471
- return raw;
472
- },
473
- };
510
+ return bigintValues;
474
511
  case 'float':
475
- return {
476
- encode: v => {
477
- if (typeof v !== 'number') {
478
- throw new InvalidError(`a ${typeof v} in a bucket of floats`);
479
- }
480
- const bytes = new Uint8Array(8);
481
- new DataView(bytes.buffer).setFloat64(0, v);
482
- return tagged(kinds.float, bytes);
483
- },
484
- decode: raw => {
485
- const bits = bodyOf(raw, kinds.float, 'a float');
486
- if (bits.length !== 8) {
487
- throw new CorruptError(`a float from ${bits.length} bytes rather than 8`);
488
- }
489
- return new DataView(bits.buffer, bits.byteOffset, 8).getFloat64(0);
490
- },
491
- };
512
+ return floatValues;
492
513
  case 'bool':
493
- return {
494
- encode: v => {
495
- if (typeof v !== 'boolean') {
496
- throw new InvalidError(`a ${typeof v} in a bucket of booleans`);
497
- }
498
- return v ? 1n : 0n;
499
- },
500
- decode: raw => {
501
- if (typeof raw !== 'bigint') {
502
- throw new CorruptError(`a stored value is ${describe(raw)} where a boolean was written`);
503
- }
504
- return raw !== 0n;
505
- },
506
- };
514
+ return boolValues;
507
515
  }
508
516
  throw new InvalidError(`a bucket's type is string, bytes, int, bigint, float or bool, not ${String(type)}`);
509
517
  }
package/dist/logger.d.ts CHANGED
@@ -103,6 +103,16 @@ type Told = Omit<LoggerOptions, 'level'> & {
103
103
  export declare function newStoreLogger(append: (lines: ConsoleLine[]) => Promise<void>, stream: string, options?: Told): [Logger, LogConfig];
104
104
  /** TinyStore's own lines, on the console of a logger of stream tinystore made when first needed. */
105
105
  export declare const sayOwn: Say;
106
+ /**
107
+ * Whether a stream shows colours, by the rule every logger keeps, in Bun,
108
+ * Python, Go and Rust, and the command line too, so that a program's own
109
+ * words and the log lines printed beside them are coloured alike: off under
110
+ * NO_COLOR or a TERM of dumb, on where FORCE_COLOR is other than 0, a pipe or
111
+ * a file too, and otherwise on a terminal alone.
112
+ *
113
+ * `const painted = colors(process.stdout)`
114
+ */
115
+ export declare function colors(stream: Pick<ConsoleOut, 'isTTY'>): boolean;
106
116
  /**
107
117
  * A logger of one stream. `info`, `warn` and the rest return at once; a line
108
118
  * goes to the console as it is logged, and becomes a record named `log`, its
package/dist/logger.js CHANGED
@@ -226,6 +226,21 @@ function forceColor() {
226
226
  const force = process.env.FORCE_COLOR;
227
227
  return force !== undefined && force !== '' && force !== '0';
228
228
  }
229
+ /**
230
+ * Whether a stream shows colours, by the rule every logger keeps, in Bun,
231
+ * Python, Go and Rust, and the command line too, so that a program's own
232
+ * words and the log lines printed beside them are coloured alike: off under
233
+ * NO_COLOR or a TERM of dumb, on where FORCE_COLOR is other than 0, a pipe or
234
+ * a file too, and otherwise on a terminal alone.
235
+ *
236
+ * `const painted = colors(process.stdout)`
237
+ */
238
+ export function colors(stream) {
239
+ if (process.env.NO_COLOR || process.env.TERM === 'dumb') {
240
+ return false;
241
+ }
242
+ return forceColor() || stream.isTTY === true;
243
+ }
229
244
  /** Whether a console told no format prints pretty lines: on a terminal, or where FORCE_COLOR asks. */
230
245
  function prettyUntold(options, out) {
231
246
  const stream = out ?? options.to ?? process.stderr;
@@ -238,17 +253,12 @@ function printer(options, out) {
238
253
  return undefined;
239
254
  }
240
255
  const stream = out ?? options.to ?? process.stderr;
241
- const forced = out === undefined && forceColor();
242
- const terminal = stream.isTTY === true;
243
256
  const pretty = options.console === 'pretty' || (options.console === undefined && prettyUntold(options, out));
244
257
  if (!pretty) {
245
258
  return line => void stream.write(jsonLine(line));
246
259
  }
247
- const color = (forced || (terminal && out === undefined)) &&
248
- !process.env.NO_COLOR &&
249
- process.env.TERM !== 'dumb';
250
260
  const look = {
251
- color,
261
+ color: out === undefined && colors(stream),
252
262
  utc: out?.utc === true,
253
263
  time: options.time,
254
264
  hideStream: options.hideStream,
package/dist/metrics.d.ts CHANGED
@@ -218,6 +218,23 @@ export declare class Metrics {
218
218
  constructor(link: Link, instruments: Instruments);
219
219
  /** Writes series and their samples, every one or none: a refused series names itself. */
220
220
  ingest(series: SeriesInput | readonly SeriesInput[]): Promise<void>;
221
+ /**
222
+ * Replaces a gauge's samples from `from` to `to`, `to` excluded, with the series' own,
223
+ * whether the store had packed them or not: a time given takes its value, a time not there
224
+ * before is added, and a time the series does not give goes. One write: a read sees the
225
+ * range as it was or as it is now, never half, and the same samples sent again write
226
+ * nothing. A counter's or a histogram's is an InvalidError.
227
+ *
228
+ * // the last three days read again from the shop's database, a refund taken off yesterday
229
+ * await store.metrics.replace(
230
+ * { name: 'revenue', kind: 'gauge', labels: { shop: 'msk' }, samples: [[day(3), 1000], [day(2), 1000], [day(1), 900]] },
231
+ * { from: day(3), to: day(0) },
232
+ * )
233
+ */
234
+ replace(series: SeriesInput, range: {
235
+ from: Time;
236
+ to: Time;
237
+ }): Promise<void>;
221
238
  /**
222
239
  * Reads the text an exporter serves, in Prometheus' format or OpenMetrics', and writes its
223
240
  * series, every one or none: a counter as a counter, a histogram's _bucket series as
package/dist/metrics.js CHANGED
@@ -9,7 +9,7 @@ import { InvalidError, OutcomeUnknownError } from './errors.js';
9
9
  import { Counter, Gauge, Histogram, labelsOf, Timer, } from './instruments.js';
10
10
  import { ConnectionLostError } from './session.js';
11
11
  import { ms, unixMs } from './time.js';
12
- import { Empty, MetricsAggregateAsked, MetricsAggregates, MetricsDamages, MetricsDeleted, MetricsDescription, MetricsExposition, MetricsIngest, MetricsLatest, MetricsNameAsked, MetricsNamePage, MetricsPageAsked, MetricsPiece, MetricsPlan, MetricsQuery, MetricsRead, MetricsSeriesNamed, MetricsTextPage, MetricsUpload, methods, } from './wire/protocol.js';
12
+ import { Empty, MetricsAggregateAsked, MetricsAggregates, MetricsDamages, MetricsDeleted, MetricsDescription, MetricsExposition, MetricsIngest, MetricsLatest, MetricsNameAsked, MetricsNamePage, MetricsPageAsked, MetricsPiece, MetricsPlan, MetricsQuery, MetricsRead, MetricsReplace, MetricsSeriesNamed, MetricsTextPage, MetricsUpload, methods, } from './wire/protocol.js';
13
13
  export { Counter, exponentialBuckets, Gauge, Histogram, Timer, Timing, } from './instruments.js';
14
14
  /**
15
15
  * A store's metrics: series by name and labels, their reads and aggregates,
@@ -31,6 +31,27 @@ export class Metrics {
31
31
  const body = MetricsIngest.encode({ series: given.map(newSeries) });
32
32
  await this.#link.run('write', connection => connection.session.call(methods['metrics.ingest'], body));
33
33
  }
34
+ /**
35
+ * Replaces a gauge's samples from `from` to `to`, `to` excluded, with the series' own,
36
+ * whether the store had packed them or not: a time given takes its value, a time not there
37
+ * before is added, and a time the series does not give goes. One write: a read sees the
38
+ * range as it was or as it is now, never half, and the same samples sent again write
39
+ * nothing. A counter's or a histogram's is an InvalidError.
40
+ *
41
+ * // the last three days read again from the shop's database, a refund taken off yesterday
42
+ * await store.metrics.replace(
43
+ * { name: 'revenue', kind: 'gauge', labels: { shop: 'msk' }, samples: [[day(3), 1000], [day(2), 1000], [day(1), 900]] },
44
+ * { from: day(3), to: day(0) },
45
+ * )
46
+ */
47
+ async replace(series, range) {
48
+ const body = MetricsReplace.encode({
49
+ series: newSeries(series),
50
+ from: unixMs(range.from),
51
+ to: unixMs(range.to),
52
+ });
53
+ await this.#link.run('write', connection => connection.session.call(methods['metrics.replace'], body));
54
+ }
34
55
  /**
35
56
  * Reads the text an exporter serves, in Prometheus' format or OpenMetrics', and writes its
36
57
  * series, every one or none: a counter as a counter, a histogram's _bucket series as