@tinyshed/tinystore 0.5.1 → 0.7.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,13 +88,14 @@ 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 {
72
95
  readonly [layerMark]: 'file';
73
96
  readonly path: string;
74
97
  readonly optional: boolean;
98
+ readonly secrets: boolean;
75
99
  }
76
100
  /** The environment a config reads. */
77
101
  export interface EnvLayer {
@@ -87,6 +111,12 @@ export type Layer<D> = FileLayer | EnvLayer | Overlay<D> | false | null | undefi
87
111
  export interface FileOptions {
88
112
  /** a file that may be absent: then it declares nothing, and explain says so */
89
113
  optional?: boolean | undefined;
114
+ /**
115
+ * false refuses a secret the file gives, for a file committed beside the
116
+ * code: its secrets come from the environment, and the error names the
117
+ * variable and its _FILE that give one, never the file
118
+ */
119
+ secrets?: boolean | undefined;
90
120
  }
91
121
  /** Settings' own variables by their paths: `{ port: 'PORT', db: { url: 'DATABASE_URL' } }`. */
92
122
  export interface Vars {
@@ -117,7 +147,7 @@ export interface UpdateOptions {
117
147
  /** A setting's line of explain. */
118
148
  export interface ExplainLine {
119
149
  readonly path: string;
120
- /** as JSON, a duration spelled, a secret as *** */
150
+ /** as JSON, a duration spelled, a secret as ***, unset for none */
121
151
  readonly value: string;
122
152
  /** the layer that gave it: APP_PORT, app.yaml, layer 2, the declaration, a change */
123
153
  readonly from: string;
@@ -133,7 +163,7 @@ export interface ExplainLine {
133
163
  }
134
164
  /** A value a setting was given, and where it came from. */
135
165
  export interface ExplainGiven {
136
- /** as JSON, a duration spelled, a secret as *** */
166
+ /** as JSON, a duration spelled, a secret as ***, unset for none */
137
167
  readonly value: string;
138
168
  readonly from: ExplainOrigin;
139
169
  }
@@ -182,6 +212,10 @@ export interface DurationBounds {
182
212
  min?: DurationText | undefined;
183
213
  max?: DurationText | undefined;
184
214
  }
215
+ /** The entries a map of entries' declaration gives, each as an object in code gives one. */
216
+ export interface EntriesOptions<G> {
217
+ default?: Readonly<Record<string, Overlay<G>>> | undefined;
218
+ }
185
219
  /** A list's default and how many items it holds at least and at most. */
186
220
  export interface ListOptions<V> extends Bounds {
187
221
  default?: readonly V[] | undefined;
@@ -194,6 +228,13 @@ export declare function secret(given: StringConstructor | string): Setting<Secre
194
228
  /** A setting with no default: a layer must give it, or the config does not open. */
195
229
  export declare function required<T extends Token>(type: T): Setting<Of<T>>;
196
230
  export declare function required<V>(rule: Setting<V, false, false>): Setting<V>;
231
+ /**
232
+ * A setting with no value until a layer gives one: `optional(String)` reads as
233
+ * `string | null`, `optional(secret(String))` as `Secret | null`, and
234
+ * `optional(int({ min: 1 }))` as `number | null`. explain says it is unset.
235
+ */
236
+ export declare function optional<T extends Token>(type: T): Setting<Of<T> | null>;
237
+ export declare function optional<V, S extends boolean>(rule: Setting<V, false, boolean, S>): Setting<V | null, false, true, S>;
197
238
  /**
198
239
  * A setting that may change while the program runs: its change is kept in
199
240
  * the store, goes over every layer until it is reset, and reaches every
@@ -221,7 +262,29 @@ export declare function duration(fallback: DurationText, rules?: DurationBounds)
221
262
  export declare function list<T extends Token>(item: T, options?: ListOptions<Of<T>>): Setting<readonly Of<T>[]>;
222
263
  export declare function list<V>(item: Setting<V, false, boolean>, options?: ListOptions<V>): Setting<readonly V[]>;
223
264
  export declare function list<G extends object>(item: G, options?: ListOptions<Value<G>>): Setting<readonly Value<G>[]>;
224
- /** A file a config reads: TOML, YAML or JSON by its extension, a relative path the program's. */
265
+ /**
266
+ * A map of named entries, each the group `item` declares, whose fields are
267
+ * settings of their own, with their own marks: a file gives an entry field
268
+ * by field, and `APP_INSTANCE_AIMEE_PASSWORD`, or its `_FILE`, one field of
269
+ * the entry `aimee` that a layer before it made. A map written as a value,
270
+ * `{}`, is one setting, given whole.
271
+ */
272
+ export declare function entries<G extends object>(item: G, options?: EntriesOptions<G>): Entries<G>;
273
+ /**
274
+ * A group whose settings are those of one of `groups`, the one the text
275
+ * setting beside it, `by`, names: `settings: chosenBy('plugin', { postgres,
276
+ * stripe })` reads an instance's settings as postgres's when its `plugin` is
277
+ * 'postgres'. Its fields are settings of their own, with their own marks; a
278
+ * field of a group not chosen is refused, and so is a `plugin` that names no
279
+ * group. A layer after the one that chose a group may choose another: then
280
+ * what the layers gave the first is dropped, and explain says so.
281
+ */
282
+ export declare function chosenBy<const G extends Readonly<Record<string, object>>>(by: string, groups: G): Chosen<G>;
283
+ /**
284
+ * A file a config reads: TOML, YAML or JSON by its extension, a relative path
285
+ * the program's. `file('dashbin.toml', { secrets: false })` refuses a secret it
286
+ * gives.
287
+ */
225
288
  export declare function file(path: string, options?: FileOptions): FileLayer;
226
289
  /**
227
290
  * The environment a config reads: `env('APP')` reads APP_ and each setting's
package/dist/config.js CHANGED
@@ -55,6 +55,10 @@ function layerOf(value) {
55
55
  function kindOf(token) {
56
56
  return token === String ? 'text' : token === Number ? 'number' : 'boolean';
57
57
  }
58
+ /** What `required` and `optional` mark: a type, `String`, or a rule. */
59
+ function ruleOf(given) {
60
+ return typeof given === 'function' ? { kind: kindOf(given) } : describedOf(given);
61
+ }
58
62
  function bounds(rules) {
59
63
  const out = {};
60
64
  if (rules?.min !== undefined) {
@@ -79,10 +83,11 @@ export function secret(given) {
79
83
  return setting({ kind: 'text', secret: true, default: given });
80
84
  }
81
85
  export function required(given) {
82
- const inner = typeof given === 'function' ? { kind: kindOf(given) } : describedOf(given);
86
+ const inner = ruleOf(given);
83
87
  if (inner === undefined) {
84
88
  throw new InvalidError('required takes String, Number, Boolean, or a rule without its default');
85
89
  }
90
+ refuseEntries(inner);
86
91
  if (inner.secret === true) {
87
92
  throw new InvalidError('a secret is required already: secret(String)');
88
93
  }
@@ -92,11 +97,24 @@ export function required(given) {
92
97
  const { default: _default, ...rest } = inner;
93
98
  return setting({ ...rest, required: true });
94
99
  }
100
+ export function optional(given) {
101
+ const inner = ruleOf(given);
102
+ if (inner?.live === true) {
103
+ throw new InvalidError('live is the outermost mark: live(optional(…))');
104
+ }
105
+ if (inner === undefined || inner.default !== undefined) {
106
+ throw new InvalidError('optional takes String, Number, Boolean, secret(String) or a rule without its default');
107
+ }
108
+ refuseEntries(inner);
109
+ const { required: _required, ...rest } = inner;
110
+ return setting({ ...rest, default: null });
111
+ }
95
112
  export function live(given) {
96
113
  if (isPlainObject(given) && describedOf(given) === undefined && Object.keys(given).length > 0) {
97
114
  throw new InvalidError('a mark goes on a setting, not on a group: mark each of its settings');
98
115
  }
99
116
  const inner = describedOf(given) ?? declaredValue(given, 'live');
117
+ refuseEntries(inner);
100
118
  if (inner.secret === true) {
101
119
  throw new InvalidError('a secret is never live');
102
120
  }
@@ -141,6 +159,7 @@ function itemOf(item) {
141
159
  }
142
160
  const inner = describedOf(item);
143
161
  if (inner !== undefined) {
162
+ refuseEntries(inner);
144
163
  if (inner.live === true || inner.secret === true) {
145
164
  throw new InvalidError("a list's items are neither live nor secret: the list is one setting");
146
165
  }
@@ -152,9 +171,69 @@ function itemOf(item) {
152
171
  }
153
172
  throw new InvalidError(`a list of ${String(item)}: of String, Number, Boolean, a rule or a group`);
154
173
  }
155
- /** A file a config reads: TOML, YAML or JSON by its extension, a relative path the program's. */
174
+ /**
175
+ * A map of named entries, each the group `item` declares, whose fields are
176
+ * settings of their own, with their own marks: a file gives an entry field
177
+ * by field, and `APP_INSTANCE_AIMEE_PASSWORD`, or its `_FILE`, one field of
178
+ * the entry `aimee` that a layer before it made. A map written as a value,
179
+ * `{}`, is one setting, given whole.
180
+ */
181
+ export function entries(item, options = {}) {
182
+ if (!isPlainObject(item) || describedOf(item) !== undefined || Object.keys(item).length === 0) {
183
+ throw new InvalidError('an entry is a group of settings: entries({ host: String, password: secret(String) })');
184
+ }
185
+ const described = {
186
+ kind: 'object',
187
+ default: options.default ?? {},
188
+ entries: declaredGroup(item, '*'),
189
+ };
190
+ return setting(described);
191
+ }
192
+ /**
193
+ * A group whose settings are those of one of `groups`, the one the text
194
+ * setting beside it, `by`, names: `settings: chosenBy('plugin', { postgres,
195
+ * stripe })` reads an instance's settings as postgres's when its `plugin` is
196
+ * 'postgres'. Its fields are settings of their own, with their own marks; a
197
+ * field of a group not chosen is refused, and so is a `plugin` that names no
198
+ * group. A layer after the one that chose a group may choose another: then
199
+ * what the layers gave the first is dropped, and explain says so.
200
+ */
201
+ export function chosenBy(by, groups) {
202
+ const named = Object.entries(groups);
203
+ if (typeof by !== 'string' || by === '' || !isPlainObject(groups) || named.length === 0) {
204
+ throw new InvalidError("a chosen group: chosenBy('plugin', { postgres: { host: String }, stripe: { key: secret(String) } })");
205
+ }
206
+ const declared = {};
207
+ for (const [name, group] of named) {
208
+ if (!isPlainObject(group) || describedOf(group) !== undefined) {
209
+ throw new InvalidError(`chosenBy: ${name} is a group of settings, not a setting`);
210
+ }
211
+ declared[name] = declaredGroup(group, name);
212
+ }
213
+ const described = { kind: 'object', default: {}, chosenBy: by, groups: declared };
214
+ return setting(described);
215
+ }
216
+ /** A mark around a map of entries or a chosen group, which marks none of their settings. */
217
+ function refuseEntries(inner) {
218
+ if (inner.entries !== undefined) {
219
+ throw new InvalidError('entries take no mark: each of their fields carries its own');
220
+ }
221
+ if (inner.groups !== undefined) {
222
+ throw new InvalidError('a chosen group takes no mark: each of its settings carries its own');
223
+ }
224
+ }
225
+ /**
226
+ * A file a config reads: TOML, YAML or JSON by its extension, a relative path
227
+ * the program's. `file('dashbin.toml', { secrets: false })` refuses a secret it
228
+ * gives.
229
+ */
156
230
  export function file(path, options = {}) {
157
- return Object.freeze({ [layerMark]: 'file', path, optional: options.optional === true });
231
+ return Object.freeze({
232
+ [layerMark]: 'file',
233
+ path,
234
+ optional: options.optional === true,
235
+ secrets: options.secrets !== false,
236
+ });
158
237
  }
159
238
  /**
160
239
  * The environment a config reads: `env('APP')` reads APP_ and each setting's
@@ -243,11 +322,22 @@ function plainItem(first) {
243
322
  return { kind: 'any' };
244
323
  }
245
324
  }
246
- /** Every setting's path, as the core names its variable. */
325
+ /** Every setting's path, as the core names its variable, every map of entries' and every chosen group's. */
247
326
  function paths(group, path) {
248
327
  return Object.entries(group).flatMap(([key, node]) => {
249
328
  const at = path === '' ? key : `${path}.${key}`;
250
- return 'group' in node ? paths(node.group, at) : [at];
329
+ if ('group' in node) {
330
+ return paths(node.group, at);
331
+ }
332
+ const chosen = Object.values(node.groups ?? {}).flatMap(inner => paths(inner, at));
333
+ return node.groups === undefined ? [at] : [...new Set(chosen)];
334
+ });
335
+ }
336
+ /** Every map of entries' path, whose entries' variables begin with its own. */
337
+ function entryMaps(group, path) {
338
+ return Object.entries(group).flatMap(([key, node]) => {
339
+ const at = path === '' ? key : `${path}.${key}`;
340
+ return 'group' in node ? entryMaps(node.group, at) : node.entries === undefined ? [] : [at];
251
341
  });
252
342
  }
253
343
  /**
@@ -298,9 +388,10 @@ async function layerData(layer, place, declared) {
298
388
  }
299
389
  const kind = layerOf(layer);
300
390
  if (kind === 'file') {
301
- const { path, optional } = layer;
391
+ const { path, optional, secrets } = layer;
302
392
  const text = await readText(path);
303
- return { file: { name: path, optional, ...(text === undefined ? {} : { text }) } };
393
+ const refused = secrets ? {} : { secrets: false };
394
+ return { file: { name: path, optional, ...refused, ...(text === undefined ? {} : { text }) } };
304
395
  }
305
396
  if (kind === 'env') {
306
397
  return { env: await envData(layer, declared) };
@@ -320,11 +411,15 @@ async function envData(layer, declared) {
320
411
  const key = (name) => (windows ? name.toUpperCase() : name);
321
412
  const named = paths(declared, '').map(path => layer.vars[path] ?? envName(layer.prefix, path));
322
413
  const wanted = new Set(named.flatMap(name => [key(name), key(`${name}_FILE`)]));
323
- const start = key(`${layer.prefix}_`);
414
+ // an entry's field is named by its key, so its map's variable is what it begins with
415
+ const starts = entryMaps(declared, '').map(path => key(`${envName(layer.prefix, path)}_`));
416
+ if (layer.prefix !== '') {
417
+ starts.push(key(`${layer.prefix}_`));
418
+ }
324
419
  const variables = {};
325
420
  for (const [name, value] of Object.entries(layer.from ?? process.env)) {
326
421
  const k = key(name);
327
- if (value !== undefined && (wanted.has(k) || (layer.prefix !== '' && k.startsWith(start)))) {
422
+ if (value !== undefined && (wanted.has(k) || starts.some(start => k.startsWith(start)))) {
328
423
  variables[k] = value;
329
424
  }
330
425
  }
@@ -358,18 +453,37 @@ function fileVariables(text) {
358
453
  }
359
454
  return found;
360
455
  }
361
- /** A value as the program reads it: a duration spelled, a secret wrapped, all of it frozen. */
456
+ /**
457
+ * A value as the program reads it: a duration spelled, a secret wrapped, a
458
+ * chosen group as the group its chooser names, all of it frozen.
459
+ */
362
460
  function viewed(group, value) {
363
461
  const source = (isPlainObject(value) ? value : {});
364
462
  const out = {};
365
463
  for (const [key, node] of Object.entries(group)) {
366
- out[key] = 'group' in node ? viewed(node.group, source[key]) : viewedSetting(node, source[key]);
464
+ if ('group' in node) {
465
+ out[key] = viewed(node.group, source[key]);
466
+ }
467
+ else if (node.groups !== undefined) {
468
+ const name = source[node.chosenBy ?? ''];
469
+ const chosen = typeof name === 'string' ? node.groups[name] : undefined;
470
+ out[key] = viewed(chosen ?? {}, source[key]);
471
+ }
472
+ else {
473
+ out[key] = viewedSetting(node, source[key]);
474
+ }
367
475
  }
368
476
  return Object.freeze(out);
369
477
  }
370
478
  function viewedSetting(described, value) {
479
+ const item = described.entries;
480
+ if (item !== undefined) {
481
+ const each = Object.entries(isPlainObject(value) ? value : {});
482
+ return Object.freeze(Object.fromEntries(each.map(([key, entry]) => [key, viewed(item, entry)])));
483
+ }
371
484
  if (described.secret === true) {
372
- return new Secret(typeof value === 'string' ? value : '');
485
+ // one declared optional is null until a layer gives it
486
+ return value === null ? null : new Secret(typeof value === 'string' ? value : '');
373
487
  }
374
488
  return viewedKind(described.kind, value);
375
489
  }
@@ -462,7 +576,7 @@ function originOf(sent) {
462
576
  return { kind: sent.kind };
463
577
  }
464
578
  }
465
- /** The text the core's `from` says: crates/tinystore/src/kv/config/explain.rs, Origin's Display. */
579
+ /** The text the core's `from` says: crates/tinystore/src/config/explain.rs, Origin's Display. */
466
580
  function originText(origin) {
467
581
  switch (origin.kind) {
468
582
  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, optional, 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, optional, 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/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