@sdeck/plugin 0.3.1 → 0.4.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/src/fields.ts ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Short, typed ways to write settings. They return the same plain fields as writing them by hand,
3
+ * so both can be mixed.
4
+ */
5
+ import type {
6
+ BooleanField,
7
+ ColorField,
8
+ GroupsField,
9
+ ImageField,
10
+ NumberField,
11
+ PageField,
12
+ SecretField,
13
+ SelectField,
14
+ SelectOption,
15
+ SlotsField,
16
+ TextField,
17
+ } from "./settings.ts";
18
+
19
+ type Options<F> = Omit<F, "type" | "label">;
20
+
21
+ /** Choices as `{ value: "What people read" }`, or a list where their order matters. */
22
+ export type Choices<V extends string> =
23
+ | Readonly<Record<V, string>>
24
+ | readonly { readonly value: V; readonly label: string }[];
25
+
26
+ /** A select whose value is one of `V`. */
27
+ export interface ChoiceField<V extends string> extends Omit<SelectField, "options" | "source"> {
28
+ options: readonly { readonly value: V; readonly label: string }[];
29
+ }
30
+
31
+ /** One of a plugin's option sources: its name, or what `plugin.source()` returned. */
32
+ export type SourceRef = string | { readonly id: string };
33
+
34
+ const sourceId = (source: SourceRef) => (typeof source === "string" ? source : source.id);
35
+
36
+ function optionList<V extends string>(choices: Choices<V>) {
37
+ if (Array.isArray(choices)) return choices as readonly { value: V; label: string }[];
38
+ return Object.entries(choices).map(([value, label]) => ({
39
+ value: value as V,
40
+ label: label as string,
41
+ }));
42
+ }
43
+
44
+ /**
45
+ * Builds settings:
46
+ *
47
+ * ```ts
48
+ * settings: {
49
+ * room: setting.text("Room", { default: "Office", required: true }),
50
+ * mode: setting.select("Mode", { set: "Set a level", mute: "Mute" }),
51
+ * level: setting.number("Level", { min: 0, max: 100, visibleIf: { mode: "set" } }),
52
+ * }
53
+ * ```
54
+ */
55
+ export const setting = {
56
+ text(label: string, options?: Options<TextField>): TextField {
57
+ return { ...options, type: "text", label };
58
+ },
59
+ number(label: string, options?: Options<NumberField>): NumberField {
60
+ return { ...options, type: "number", label };
61
+ },
62
+ boolean(label: string, options?: Options<BooleanField>): BooleanField {
63
+ return { ...options, type: "boolean", label };
64
+ },
65
+ /** A `#rrggbb` colour. */
66
+ color(label: string, options?: Options<ColorField>): ColorField {
67
+ return { ...options, type: "color", label };
68
+ },
69
+ /** One of a few fixed choices; its value has their exact type. */
70
+ select<const V extends string>(
71
+ label: string,
72
+ choices: Choices<V>,
73
+ options?: Omit<Options<ChoiceField<V>>, "options" | "default"> & { default?: NoInfer<V> },
74
+ ): ChoiceField<V> {
75
+ return { ...options, type: "select", label, options: optionList(choices) };
76
+ },
77
+ /** A choice from what one of the plugin's option sources returns when the form opens. */
78
+ pick(
79
+ label: string,
80
+ source: SourceRef,
81
+ options?: Omit<Options<SelectField>, "options" | "source"> & {
82
+ /** Choices shown before the fetched ones (`{ "": "The one in use" }`). */
83
+ first?: Readonly<Record<string, string>> | readonly SelectOption[];
84
+ },
85
+ ): SelectField & { source: string } {
86
+ const { first = [], ...rest } = options ?? {};
87
+ return { ...rest, type: "select", label, options: optionList(first), source: sourceId(source) };
88
+ },
89
+ /** One of the user's pages. */
90
+ page(label: string, options?: Options<PageField>): PageField {
91
+ return { ...options, type: "page", label };
92
+ },
93
+ /** Keys, touch sensors and the window. */
94
+ slots(label: string, options?: Options<SlotsField>): SlotsField {
95
+ return { ...options, type: "slots", label };
96
+ },
97
+ image(label: string, options?: Options<ImageField>): ImageField {
98
+ return { ...options, type: "image", label };
99
+ },
100
+ /** Named sets of options. Only for a plugin's own settings. */
101
+ groups(
102
+ label: string,
103
+ source: SourceRef,
104
+ options?: Omit<Options<GroupsField>, "source">,
105
+ ): GroupsField {
106
+ return { ...options, type: "groups", label, source: sourceId(source) };
107
+ },
108
+ /** A password or token, kept out of the config. Only for a plugin's own settings. */
109
+ secret(label: string, options?: Options<SecretField>): SecretField {
110
+ return { ...options, type: "secret", label };
111
+ },
112
+ } as const;
package/src/index.ts CHANGED
@@ -21,6 +21,16 @@ export {
21
21
  ManagedConnection,
22
22
  PermanentError,
23
23
  } from "./connection.ts";
24
+ export {
25
+ createPlugin,
26
+ type PluginBase,
27
+ type PluginBuilder,
28
+ type PluginParts,
29
+ type Source,
30
+ type StateHandle,
31
+ type TypedContext,
32
+ } from "./create.ts";
33
+ export { type ChoiceField, type Choices, type SourceRef, setting } from "./fields.ts";
24
34
  export {
25
35
  HOST_MODULES,
26
36
  type ManifestResult,
@@ -34,6 +44,7 @@ export {
34
44
  PERMISSIONS,
35
45
  type Permission,
36
46
  PermissionError,
47
+ Permissions,
37
48
  type PermissionText,
38
49
  } from "./permissions.ts";
39
50
  export {
@@ -51,6 +62,7 @@ export {
51
62
  type OptionSource,
52
63
  type Overlay,
53
64
  type OverlayProps,
65
+ onSettingsChange,
54
66
  PLUGIN_API_VERSION,
55
67
  type PluginCommand,
56
68
  type PluginContext,
@@ -95,7 +107,7 @@ export {
95
107
  slotList,
96
108
  type TextField,
97
109
  } from "./settings.ts";
98
- export { Shared } from "./shared.ts";
110
+ export { following, Shared, useShared } from "./shared.ts";
99
111
  export {
100
112
  fitText,
101
113
  layoutText,
@@ -103,3 +115,4 @@ export {
103
115
  type TextLayoutOptions,
104
116
  type TextRow,
105
117
  } from "./text.ts";
118
+ export { checkSettings, type StandardSchema, type Validator } from "./validate.ts";
package/src/manifest.ts CHANGED
@@ -9,7 +9,7 @@ import { PLUGIN_API_VERSION } from "./plugin.ts";
9
9
  * "version": "1.0.0",
10
10
  * "type": "module",
11
11
  * "keywords": ["sdeck-plugin"],
12
- * "sdeck": { "apiVersion": 2, "entry": "./dist/index.js" }
12
+ * "sdeck": { "apiVersion": 3, "entry": "./dist/index.js" }
13
13
  * }
14
14
  * ```
15
15
  *
@@ -43,10 +43,10 @@ export const HOST_MODULES = [
43
43
  ] as const;
44
44
 
45
45
  /**
46
- * Plugin APIs this host loads. Version 1 plugins (actions that draw themselves) are a subset of
47
- * version 2 and run unchanged.
46
+ * Plugin APIs this host loads. Each one only adds to the one before, so older plugins run
47
+ * unchanged: 2 added actions without a component, 3 `createPlugin` and the helpers for looks.
48
48
  */
49
- export const SUPPORTED_API_VERSIONS: readonly number[] = [1, PLUGIN_API_VERSION];
49
+ export const SUPPORTED_API_VERSIONS: readonly number[] = [1, 2, PLUGIN_API_VERSION];
50
50
 
51
51
  export type ManifestResult = { ok: true; manifest: PluginManifest } | { ok: false; error: string };
52
52
 
@@ -63,7 +63,10 @@ export function parseManifest(pkg: unknown): ManifestResult {
63
63
  if (typeof apiVersion !== "number" || !SUPPORTED_API_VERSIONS.includes(apiVersion)) {
64
64
  return {
65
65
  ok: false,
66
- error: `${p.name} targets plugin API ${String(apiVersion)}, this host supports ${SUPPORTED_API_VERSIONS.join(" and ")}`,
66
+ error:
67
+ typeof apiVersion === "number" && apiVersion > PLUGIN_API_VERSION
68
+ ? `${p.name} needs a newer version of sdeck (plugin API ${apiVersion})`
69
+ : `${p.name} targets plugin API ${String(apiVersion)}, this host supports ${SUPPORTED_API_VERSIONS.join(", ")}`,
67
70
  };
68
71
  }
69
72
  const entry =
@@ -17,6 +17,23 @@ export type Permission =
17
17
  | "overlay"
18
18
  | "native";
19
19
 
20
+ /** Every permission by name, for `permissions: [Permissions.network]`. */
21
+ export const Permissions = {
22
+ network: "network",
23
+ filesystem: "filesystem",
24
+ process: "process",
25
+ shell: "shell",
26
+ input: "input",
27
+ clipboard: "clipboard",
28
+ audio: "audio",
29
+ environment: "environment",
30
+ variables: "variables",
31
+ state: "state",
32
+ actions: "actions",
33
+ overlay: "overlay",
34
+ native: "native",
35
+ } as const satisfies { [P in Permission]: P };
36
+
20
37
  /** A permission as the user reads it. */
21
38
  export interface PermissionText {
22
39
  name: string;
package/src/plugin.ts CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  import type { TextRow } from "./text.ts";
13
13
 
14
14
  /** Bumped when the plugin contract changes incompatibly. Hosts refuse plugins built for another. */
15
- export const PLUGIN_API_VERSION = 2;
15
+ export const PLUGIN_API_VERSION = 3;
16
16
 
17
17
  /** Where an action can be placed. */
18
18
  export type SlotKind = "key" | "sensor" | "window";
@@ -102,7 +102,7 @@ export interface OverlayProps {
102
102
  export type StatusLevel = "ok" | "info" | "error";
103
103
 
104
104
  /** Something the user can run from the plugin's settings (sign in, reconnect). */
105
- export interface PluginCommand {
105
+ export interface PluginCommand<C = PluginContext, P extends Permission = Permission> {
106
106
  /** Unique within the plugin. */
107
107
  id: string;
108
108
  name: string;
@@ -111,9 +111,9 @@ export interface PluginCommand {
111
111
  * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
112
112
  * Without them it is refused.
113
113
  */
114
- permissions?: readonly Permission[];
114
+ permissions?: readonly P[];
115
115
  /** What it returns, if a string, is opened in the user's browser. Throw to fail. */
116
- run(context: PluginContext): unknown | Promise<unknown>;
116
+ run(context: C): unknown | Promise<unknown>;
117
117
  }
118
118
 
119
119
  /**
@@ -167,21 +167,21 @@ export interface Onboarding {
167
167
  }
168
168
 
169
169
  /** Props of an action's component. */
170
- export interface ActionProps<S extends SettingsSchema = SettingsSchema> {
170
+ export interface ActionProps<S extends SettingsSchema = SettingsSchema, C = PluginContext> {
171
171
  /** This placement's settings, resolved against the schema (always complete and typed). */
172
172
  settings: InferSettings<S>;
173
173
  /** Saves changed settings for this placement (persisted and shown in the UI). */
174
174
  setSettings(patch: Partial<InferSettings<S>>): void;
175
175
  /** Where the action is drawn. */
176
176
  slot: SlotInfo;
177
- plugin: PluginContext;
177
+ plugin: C;
178
178
  }
179
179
 
180
180
  /** Given to an action's `run`. */
181
- export interface RunContext<S extends SettingsSchema = SettingsSchema> {
181
+ export interface RunContext<S extends SettingsSchema = SettingsSchema, C = PluginContext> {
182
182
  /** Settings with `{{templates}}` already resolved, then checked against the schema. */
183
183
  settings: InferSettings<S>;
184
- plugin: PluginContext;
184
+ plugin: C;
185
185
  /** What started the run (a key, a trigger, a workflow…). */
186
186
  source: ExecSource;
187
187
  /** Aborted when the execution is cancelled. Long work should stop. */
@@ -215,7 +215,11 @@ export interface RunOutcome {
215
215
 
216
216
  export type RunResult = RunOutcome | undefined;
217
217
 
218
- export interface ActionDef<S extends SettingsSchema = SettingsSchema> {
218
+ export interface ActionDef<
219
+ S extends SettingsSchema = SettingsSchema,
220
+ C = PluginContext,
221
+ P extends Permission = Permission,
222
+ > {
219
223
  /** Unique within the plugin, e.g. `"clock"`. */
220
224
  id: string;
221
225
  name: string;
@@ -235,7 +239,7 @@ export interface ActionDef<S extends SettingsSchema = SettingsSchema> {
235
239
  * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
236
240
  * Without them it cannot run or draw itself.
237
241
  */
238
- permissions?: readonly Permission[];
242
+ permissions?: readonly P[];
239
243
  /**
240
244
  * It only shows something. It is offered for buttons, but not as a step of a workflow or
241
245
  * gesture, and needs no `run`.
@@ -246,15 +250,18 @@ export interface ActionDef<S extends SettingsSchema = SettingsSchema> {
246
250
  * Throw to fail. An action needs `run`, `component`, or both, unless it is `display`.
247
251
  */
248
252
  // biome-ignore lint/suspicious/noConfusingVoidType: lets `run` simply not return anything.
249
- run?(context: RunContext<S>): RunResult | void | Promise<RunResult | void>;
253
+ run?(context: RunContext<S, C>): RunResult | void | Promise<RunResult | void>;
250
254
  /**
251
255
  * Draws the action itself (it then handles its own input). It runs inside the deck's React
252
256
  * tree, so the `@sdeck/app` hooks and components work as in any app. Without it, the host
253
257
  * draws the button's look and runs `run` on press.
254
258
  */
255
- component?: ComponentType<ActionProps<S>>;
256
- /** The look a new button with this action starts with (default: its name on a dark key). */
257
- look?(settings: InferSettings<S>): Look;
259
+ component?: ComponentType<ActionProps<S, C>>;
260
+ /**
261
+ * The look a new button with this action starts with (default: its name on a dark key). `slot` is
262
+ * where it is drawn: the window is much wider than a key, and a touch sensor shows no text.
263
+ */
264
+ look?(settings: InferSettings<S>, slot: SlotKind): Look;
258
265
  }
259
266
 
260
267
  export type RunFn = (context: RunContext) => RunResult | undefined | Promise<RunResult | undefined>;
@@ -272,7 +279,7 @@ export interface Action {
272
279
  readonly display?: boolean;
273
280
  readonly run?: RunFn;
274
281
  readonly component?: ComponentType<ActionProps>;
275
- readonly look?: (settings: Record<string, unknown>) => Look;
282
+ readonly look?: (settings: Record<string, unknown>, slot: SlotKind) => Look;
276
283
  }
277
284
 
278
285
  /** A live value the plugin publishes as `<namespace>.<id>`. */
@@ -296,14 +303,18 @@ export interface StateDef {
296
303
  }
297
304
 
298
305
  /** Given to a trigger's `subscribe`. */
299
- export interface TriggerContext<S extends SettingsSchema = SettingsSchema> {
306
+ export interface TriggerContext<S extends SettingsSchema = SettingsSchema, C = PluginContext> {
300
307
  settings: InferSettings<S>;
301
- plugin: PluginContext;
308
+ plugin: C;
302
309
  /** Starts the trigger's workflow; `event` becomes `event` in its expressions. */
303
310
  fire(event?: unknown): void;
304
311
  }
305
312
 
306
- export interface TriggerDef<S extends SettingsSchema = SettingsSchema> {
313
+ export interface TriggerDef<
314
+ S extends SettingsSchema = SettingsSchema,
315
+ C = PluginContext,
316
+ P extends Permission = Permission,
317
+ > {
307
318
  /** Unique within the plugin; the trigger type is `<plugin id>:<id>`. */
308
319
  id: string;
309
320
  name: string;
@@ -313,10 +324,10 @@ export interface TriggerDef<S extends SettingsSchema = SettingsSchema> {
313
324
  * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
314
325
  * Without them it never fires.
315
326
  */
316
- permissions?: readonly Permission[];
327
+ permissions?: readonly P[];
317
328
  /** Starts watching; returns a function that stops. */
318
329
  // biome-ignore lint/suspicious/noConfusingVoidType: lets `subscribe` simply not return anything.
319
- subscribe(context: TriggerContext<S>): (() => void) | void;
330
+ subscribe(context: TriggerContext<S, C>): (() => void) | void;
320
331
  }
321
332
 
322
333
  export interface Trigger {
@@ -616,3 +627,17 @@ function checkOnboarding(def: Partial<PluginDef>): string[] {
616
627
  }
617
628
  return problems;
618
629
  }
630
+
631
+ /**
632
+ * Calls `listener` when the plugin's settings have other values than before, such as to connect
633
+ * again. `onSettings` also tells of saves that changed nothing. Returns a function that stops.
634
+ */
635
+ export function onSettingsChange(context: PluginContext, listener: () => void): () => void {
636
+ let before = JSON.stringify(context.settings());
637
+ return context.onSettings(() => {
638
+ const now = JSON.stringify(context.settings());
639
+ if (now === before) return;
640
+ before = now;
641
+ listener();
642
+ });
643
+ }
package/src/settings.ts CHANGED
@@ -2,10 +2,11 @@
2
2
  * Action settings are described by a plain-data schema. The host turns it into a form in the
3
3
  * configuration UI, and `resolveSettings` turns whatever is stored into well-typed values.
4
4
  */
5
+ import type { Validator } from "./validate.ts";
5
6
 
6
7
  type Primitive = string | number | boolean;
7
8
 
8
- interface FieldBase {
9
+ interface FieldBase<T = unknown> {
9
10
  /** Label shown in the configuration UI. */
10
11
  label: string;
11
12
  /** Help text under the field. */
@@ -15,6 +16,14 @@ interface FieldBase {
15
16
  * workflow or gesture, where nothing is drawn.
16
17
  */
17
18
  appearance?: boolean;
19
+ /** It cannot be left empty: the action does not run until it is filled in. */
20
+ required?: boolean;
21
+ /**
22
+ * Checks what was entered: a function that returns what is wrong (`"must be a URL"`), or a
23
+ * schema from zod, valibot or another Standard Schema library. The form shows it, and the action
24
+ * does not run until it is fixed. Values with `{{templates}}` are checked when it runs.
25
+ */
26
+ validate?: Validator<T>;
18
27
  /**
19
28
  * Shown only while other fields have these values: `{ to: "page" }` or
20
29
  * `{ mode: ["a", "b"] }`. Hidden fields keep their value.
@@ -22,7 +31,7 @@ interface FieldBase {
22
31
  visibleIf?: Readonly<Record<string, Primitive | readonly Primitive[]>>;
23
32
  }
24
33
 
25
- export interface TextField extends FieldBase {
34
+ export interface TextField extends FieldBase<string> {
26
35
  type: "text";
27
36
  default?: string;
28
37
  placeholder?: string;
@@ -38,7 +47,7 @@ export interface TextField extends FieldBase {
38
47
  live?: boolean;
39
48
  }
40
49
 
41
- export interface NumberField extends FieldBase {
50
+ export interface NumberField extends FieldBase<number> {
42
51
  type: "number";
43
52
  default?: number;
44
53
  min?: number;
@@ -46,7 +55,7 @@ export interface NumberField extends FieldBase {
46
55
  step?: number;
47
56
  }
48
57
 
49
- export interface BooleanField extends FieldBase {
58
+ export interface BooleanField extends FieldBase<boolean> {
50
59
  type: "boolean";
51
60
  default?: boolean;
52
61
  }
@@ -55,14 +64,14 @@ export interface BooleanField extends FieldBase {
55
64
  * A password or token, only for a plugin's own settings. It is kept in the host's secrets file
56
65
  * (never in the config, so it is safe to share or commit) and the UI never reads it back.
57
66
  */
58
- export interface SecretField extends FieldBase {
67
+ export interface SecretField extends FieldBase<string> {
59
68
  type: "secret";
60
69
  default?: string;
61
70
  placeholder?: string;
62
71
  }
63
72
 
64
73
  /** A `#rrggbb` colour. */
65
- export interface ColorField extends FieldBase {
74
+ export interface ColorField extends FieldBase<string> {
66
75
  type: "color";
67
76
  default?: string;
68
77
  }
@@ -72,7 +81,7 @@ export interface SelectOption {
72
81
  label: string;
73
82
  }
74
83
 
75
- export interface SelectField extends FieldBase {
84
+ export interface SelectField extends FieldBase<string> {
76
85
  type: "select";
77
86
  /** Fixed options. With `source`, shown before the fetched ones. */
78
87
  options: readonly SelectOption[];
@@ -90,7 +99,7 @@ export interface SelectField extends FieldBase {
90
99
  }
91
100
 
92
101
  /** The name of one of the user's pages (the UI shows a page picker). */
93
- export interface PageField extends FieldBase {
102
+ export interface PageField extends FieldBase<string> {
94
103
  type: "page";
95
104
  default?: string;
96
105
  /** Offers choosing no page (an empty value), under this name: `Every page`. */
@@ -101,13 +110,13 @@ export interface PageField extends FieldBase {
101
110
  * Keys, touch sensors and the window, picked on a picture of the deck: `key:0`, `sensor:1`,
102
111
  * `window`. An empty list stands for the entire deck.
103
112
  */
104
- export interface SlotsField extends FieldBase {
113
+ export interface SlotsField extends FieldBase<readonly string[]> {
105
114
  type: "slots";
106
115
  default?: readonly string[];
107
116
  }
108
117
 
109
118
  /** An image: an `http(s)` URL or a `data:` URI (the UI accepts a URL or a file). */
110
- export interface ImageField extends FieldBase {
119
+ export interface ImageField extends FieldBase<string> {
111
120
  type: "image";
112
121
  default?: string;
113
122
  /** As on a text field: `{{spotify.art}}` reaches `run` as written. */
@@ -124,7 +133,7 @@ export interface OptionGroup {
124
133
  }
125
134
 
126
135
  /** Named sets of options the user puts together (rooms of lights), only for a plugin's own settings. */
127
- export interface GroupsField extends FieldBase {
136
+ export interface GroupsField extends FieldBase<readonly OptionGroup[]> {
128
137
  type: "groups";
129
138
  /** The plugin's `optionSources` entry that lists what a group can contain. */
130
139
  source: string;
@@ -323,6 +332,10 @@ export function checkSchema(
323
332
  for (const other of ("dependsOn" in field && field.dependsOn) || []) {
324
333
  if (!(other in schema)) problems.push(`setting "${key}" depends on unknown "${other}"`);
325
334
  }
335
+ const { validate } = field;
336
+ if (validate !== undefined && typeof validate !== "function" && !("~standard" in validate)) {
337
+ problems.push(`setting "${key}": validate must be a function or a Standard Schema`);
338
+ }
326
339
  if (field.visibleIf !== undefined) {
327
340
  for (const other of Object.keys(field.visibleIf)) {
328
341
  if (!(other in schema)) problems.push(`setting "${key}" depends on unknown "${other}"`);
package/src/shared.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { useCallback, useSyncExternalStore } from "react";
2
+
1
3
  /** A source started on the first listener and stopped after the last one leaves. */
2
4
  export class Shared<T> {
3
5
  readonly #listeners = new Set<(value: T) => void>();
@@ -32,3 +34,34 @@ export class Shared<T> {
32
34
  };
33
35
  }
34
36
  }
37
+
38
+ /** The latest value of a {@link Shared} in a component, which keeps it started meanwhile. */
39
+ export function useShared<T>(shared: Shared<T>): T | undefined {
40
+ return useSyncExternalStore(
41
+ useCallback((changed) => shared.listen(changed), [shared]),
42
+ () => shared.last,
43
+ );
44
+ }
45
+
46
+ /**
47
+ * A live value read from a {@link Shared}, for the `start` of a state. `undefined` while the source
48
+ * has nothing.
49
+ *
50
+ * ```ts
51
+ * plugin.state.string("track", "Track", { start: following(player, (p) => p.track) });
52
+ * ```
53
+ */
54
+ export const following =
55
+ <T, V>(shared: Shared<T>, pick: (value: NonNullable<T>) => V | undefined) =>
56
+ (set: (value: V | undefined) => void): (() => void) => {
57
+ const update = (value: T | undefined) =>
58
+ set(value === undefined || value === null ? undefined : pick(value as NonNullable<T>));
59
+ let heard = false;
60
+ const stop = shared.listen((value) => {
61
+ heard = true;
62
+ update(value);
63
+ });
64
+ // Something else may have started it already.
65
+ if (!heard && shared.last !== undefined) update(shared.last);
66
+ return stop;
67
+ };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Checking what the user entered. Fields say what is wrong in a sentence, or leave it to a schema
3
+ * from any library that follows Standard Schema (zod, valibot, arktype), without depending on one.
4
+ */
5
+ import { isFieldVisible, type SettingField, type SettingsSchema } from "./settings.ts";
6
+
7
+ /** The part of https://standardschema.dev that checking a value needs. */
8
+ export interface StandardSchema {
9
+ readonly "~standard": {
10
+ readonly version: 1;
11
+ readonly vendor: string;
12
+ validate(value: unknown): StandardResult | Promise<StandardResult>;
13
+ };
14
+ }
15
+
16
+ type StandardResult =
17
+ | { readonly value: unknown; readonly issues?: undefined }
18
+ | { readonly issues: readonly { readonly message: string }[] };
19
+
20
+ /**
21
+ * Says what is wrong with a value, or nothing when it is fine. A schema only checks: what it would
22
+ * turn the value into is not used.
23
+ */
24
+ export type Validator<T> =
25
+ // biome-ignore lint/suspicious/noConfusingVoidType: lets a validator simply not return anything.
26
+ ((value: T) => string | undefined | void | Promise<string | undefined | void>) | StandardSchema;
27
+
28
+ const isSchema = (v: object): v is StandardSchema => "~standard" in v;
29
+
30
+ async function problem(field: SettingField, value: unknown): Promise<string | undefined> {
31
+ const empty = Array.isArray(value) ? value.length === 0 : String(value ?? "").trim() === "";
32
+ if (empty) return field.required ? "this is required" : undefined;
33
+ const validate = field.validate as Validator<unknown> | undefined;
34
+ // What a template gives is only known when it runs, and is checked then.
35
+ if (!validate || (typeof value === "string" && value.includes("{{"))) return undefined;
36
+ if (!isSchema(validate)) return (await validate(value)) || undefined;
37
+ const { issues } = await validate["~standard"].validate(value);
38
+ return issues?.[0]?.message;
39
+ }
40
+
41
+ /**
42
+ * What is wrong with `settings` (as `resolveSettings` gives them), by field. Fields that are not
43
+ * shown, and empty ones that are not `required`, are fine.
44
+ */
45
+ export async function checkSettings(
46
+ schema: SettingsSchema,
47
+ settings: Readonly<Record<string, unknown>>,
48
+ ): Promise<Record<string, string>> {
49
+ const found: Record<string, string> = {};
50
+ for (const [key, field] of Object.entries(schema)) {
51
+ if (!field.required && !field.validate) continue;
52
+ if (!isFieldVisible(field, settings)) continue;
53
+ try {
54
+ const text = await problem(field, settings[key]);
55
+ if (text) found[key] = text;
56
+ } catch (error) {
57
+ found[key] = error instanceof Error ? error.message : String(error);
58
+ }
59
+ }
60
+ return found;
61
+ }