@vite-hub/choices 0.0.0 → 0.5.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.
@@ -0,0 +1,148 @@
1
+ import { AiGatewayAsk, AiGatewayAskOptions, AskModel } from "@vite-hub/gateways";
2
+ import { Diagnostic } from "nostics";
3
+ //#region src/types.d.ts
4
+ /** The value that you map back to your data. It must be unique within its group. */
5
+ type ChoiceValue = string | number;
6
+ /** One option of a group. `value` is yours, `label`, `aliases`, and `description` are what the model reads. */
7
+ interface ChoiceOption<TValue extends ChoiceValue = ChoiceValue> {
8
+ /** Other names for the option, such as codes, abbreviations, or translations. */
9
+ aliases?: readonly string[];
10
+ /** What the option is about. An `infer` group needs it to choose an option that the text does not name. */
11
+ description?: string;
12
+ /** What people call the option. */
13
+ label: string;
14
+ /** Your id for the option. It comes back in the selection. */
15
+ value: TValue;
16
+ }
17
+ type MaybePromise<T> = T | Promise<T>;
18
+ /** A set of options that belong to one decision, such as one filter. */
19
+ interface ChoiceGroup<TValue extends ChoiceValue = ChoiceValue> {
20
+ /** Tells the model how to read this group. Keep it short and specific to your data. */
21
+ hints?: string;
22
+ /**
23
+ * `false` (default): choose only an option that the text names. `true`: choose the option that fits the text best,
24
+ * also when the text does not name it, such as a project for a bug report. Needs `multiple: false`.
25
+ * An `infer` group has no "none" answer. Add an option for "anything else" if you need one.
26
+ */
27
+ infer?: boolean;
28
+ /** What people call the group, such as "Supplier". */
29
+ label: string;
30
+ /** `true` (default): any number of options, each included or excluded. `false`: at most one option. */
31
+ multiple?: boolean;
32
+ /** A list, or a function that loads the list for one request. Annotate the parameter of the function: its type is the `context` of `resolve()`. */
33
+ options: readonly ChoiceOption<TValue>[] | ((context: never) => MaybePromise<readonly ChoiceOption<TValue>[]>);
34
+ }
35
+ type ChoiceGroups = Record<string, ChoiceGroup>;
36
+ interface ChoicesLimits {
37
+ /** Most options in one group. Default 100. */
38
+ options: number;
39
+ /** Most groups. Default 40. */
40
+ groups: number;
41
+ /** Longest text in characters. Default 300. */
42
+ text: number;
43
+ /** Most options in all groups together. Default 100. */
44
+ totalOptions: number;
45
+ }
46
+ interface ChoicesThresholds {
47
+ /** The lowest probability that decides one option. Default 0.5. */
48
+ option?: number;
49
+ /** The lowest probability that the options can express the text. Default 0.6. Not asked when every group infers. */
50
+ supported?: number;
51
+ }
52
+ interface ChoicesDefinition<TGroups extends ChoiceGroups> {
53
+ /** Asks TypeSafe Jev, or any object with `ask()`: `typesafe()`, `vercel()`, or `cloudflare()` from `vite-hub/gateways`. Set `gateway` or `model`. */
54
+ gateway?: {
55
+ ask: AiGatewayAsk;
56
+ };
57
+ groups: TGroups;
58
+ /** Tells the model what the options are about. It is added to every question. */
59
+ hints?: string;
60
+ limits?: Partial<ChoicesLimits>;
61
+ /** Asks any AI SDK model instead of Jev, such as `openai("gpt-5.1-mini")`. It needs the `ai` package. Set `gateway` or `model`. */
62
+ model?: AskModel;
63
+ /** A label for logs and the CLI. It never connects anything. */
64
+ name?: string;
65
+ thresholds?: ChoicesThresholds;
66
+ }
67
+ type OptionValue<TOptions> = TOptions extends readonly ChoiceOption<infer TValue>[] ? TValue : TOptions extends ((context: never) => infer TResult) ? Awaited<TResult> extends readonly ChoiceOption<infer TValue>[] ? TValue : never : never;
68
+ type GroupValue<TGroup> = TGroup extends {
69
+ options: infer TOptions;
70
+ } ? OptionValue<TOptions> : never;
71
+ /** A group with `multiple` left as `true`: the options the text includes and excludes. */
72
+ interface MultipleSelection<TValue extends ChoiceValue = ChoiceValue> {
73
+ exclude: TValue[];
74
+ include: TValue[];
75
+ }
76
+ /** A group with `multiple: false`: the best option, or `null`, and every option by probability. */
77
+ interface SingleSelection<TValue extends ChoiceValue = ChoiceValue> {
78
+ /** The probability of `value`, from 0 to 1. It is `0` when `value` is `null`. */
79
+ confidence: number;
80
+ /** Every option, from the most to the least likely. */
81
+ ranked: {
82
+ probability: number;
83
+ value: TValue;
84
+ }[];
85
+ /** The best option when it is above `thresholds.option`, else `null`. */
86
+ value: TValue | null;
87
+ }
88
+ /** The result for each group, typed from the options that you declared. */
89
+ type ChoicesSelection<TGroups> = { [K in keyof TGroups]: TGroups[K] extends {
90
+ multiple: false;
91
+ } ? SingleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>> : MultipleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>>; };
92
+ /**
93
+ * Why `resolve()` returned no selection. Check `error.code`. `DECISIONS_R0002`: a group or option is invalid or over a
94
+ * limit. `DECISIONS_R0003`: the text is empty or too long. `DECISIONS_R0004`: the options cannot express the text.
95
+ * `DECISIONS_R0005`: the gateway request failed, with the gateway error in `cause`. `DECISIONS_R0006`: the model left a
96
+ * question without an answer. `defineChoices()` throws `DECISIONS_R0001`, so it never comes back here.
97
+ */
98
+ type ChoicesError = Diagnostic<unknown, "DECISIONS_R0002"> | Diagnostic<unknown, "DECISIONS_R0003"> | Diagnostic<unknown, "DECISIONS_R0004"> | Diagnostic<unknown, "DECISIONS_R0005"> | Diagnostic<unknown, "DECISIONS_R0006">;
99
+ type ChoicesResult<TData> = readonly [error: ChoicesError, data?: undefined] | readonly [error: undefined, data: TData];
100
+ interface ChoicesRequest<TContext> {
101
+ /** Passed to `options` functions. Put what they need here, such as the tenant. */
102
+ context: TContext;
103
+ /**
104
+ * Receives the model, provider, and token counts when the gateway reports usage.
105
+ * Jev can report usage for multiple batches in one `resolve()`. With `model`, this runs at most once.
106
+ */
107
+ onUsage?: AiGatewayAskOptions["onUsage"];
108
+ /** Cancels the request to the gateway. */
109
+ signal?: AbortSignal;
110
+ }
111
+ /** What `resolve()` would send, without sending it. */
112
+ interface ChoicesPlan {
113
+ /** The questions for `gateway.ask()`. One per option of a multiple group, one per single group, and `supported` unless every group infers. */
114
+ questions: Record<string, unknown>;
115
+ /** The state for `gateway.ask()`. */
116
+ state: {
117
+ groups: {
118
+ hints?: string;
119
+ infer?: true;
120
+ label: string;
121
+ multiple: boolean;
122
+ options: {
123
+ aliases?: readonly string[];
124
+ label: string;
125
+ value: ChoiceValue;
126
+ }[];
127
+ }[];
128
+ query: string;
129
+ };
130
+ }
131
+ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (value: TUnion) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
132
+ type OptionsContext<TGroup> = TGroup extends {
133
+ options: (context: infer TContext) => unknown;
134
+ } ? TContext : never;
135
+ /** The `context` that `resolve()` needs: the parameter types of the `options` functions of the groups. `unknown` when no group needs one. */
136
+ type GroupsContext<TGroups> = UnionToIntersection<{ [K in keyof TGroups]: OptionsContext<TGroups[K]>; }[keyof TGroups]>;
137
+ type ChoicesArgs<TContext> = unknown extends TContext ? [request?: Omit<ChoicesRequest<unknown>, "context">] : [request: ChoicesRequest<TContext> & {
138
+ context: TContext;
139
+ }];
140
+ interface Choices<TGroups extends ChoiceGroups> {
141
+ /** Shows the questions and the state that `resolve()` would send. Nothing leaves your server. */
142
+ inspect: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesPlan>>;
143
+ readonly name: string | undefined;
144
+ /** Asks the gateway which options the text names. It returns `[error, selection]` and never throws. */
145
+ resolve: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesSelection<TGroups>>>;
146
+ }
147
+ //#endregion
148
+ export { MultipleSelection as _, Choices as a, ChoicesError as c, ChoicesRequest as d, ChoicesResult as f, GroupsContext as g, GroupValue as h, ChoiceValue as i, ChoicesLimits as l, ChoicesThresholds as m, ChoiceGroups as n, ChoicesArgs as o, ChoicesSelection as p, ChoiceOption as r, ChoicesDefinition as s, ChoiceGroup as t, ChoicesPlan as u, SingleSelection as v };
package/dist/vue.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { Ref } from "vue";
2
+ //#region src/vue.d.ts
3
+ /** Any Choices object. Its `resolve()` parameters do not matter here. */
4
+ export interface ChoicesLike {
5
+ resolve: (text: never, ...args: never[]) => Promise<unknown>;
6
+ }
7
+ /** The selection that `resolve()` of a Choices object returns on success. Use it with `typeof yourChoices`. */
8
+ export type ChoicesSelectionOf<TChoices extends ChoicesLike> = Extract<Awaited<ReturnType<TChoices["resolve"]>>, readonly [undefined, unknown]>[1];
9
+ export type ChoicesStatus = "error" | "idle" | "ready" | "thinking";
10
+ export interface UseChoicesOptions<TSelection> {
11
+ /**
12
+ * Wait this many milliseconds after the last keystroke, then resolve. Leave it out to resolve only when you call
13
+ * `submit()`.
14
+ */
15
+ debounce?: number;
16
+ /** The text must be at least this long before a debounced resolve runs. Defaults to `3`. */
17
+ minLength?: number;
18
+ /** Called by `clear()`, so you can reset your own state, such as the filters that the last selection set. */
19
+ onClear?: () => void;
20
+ /** Called with each new selection. Apply it to your own state here. */
21
+ onSelect?: (selection: TSelection) => void;
22
+ /**
23
+ * Your bridge to the server: send the text, return the selection. Throw when the request fails.
24
+ * Pass `signal` to your request so a newer text can cancel an older one.
25
+ */
26
+ resolve: (text: string, context: {
27
+ signal: AbortSignal;
28
+ }) => Promise<TSelection>;
29
+ }
30
+ export interface UseChoicesResult<TSelection> {
31
+ /** Cancels the pending request and goes back to `idle`. */
32
+ abort: () => void;
33
+ /** Clears the text, the selection, and the error. */
34
+ clear: () => void;
35
+ /** The error of the last request, or `undefined`. */
36
+ error: Readonly<Ref<Error | undefined>>;
37
+ /** The latest selection, or `undefined`. A newer request keeps it until it finishes. */
38
+ selection: Readonly<Ref<TSelection | undefined>>;
39
+ status: Readonly<Ref<ChoicesStatus>>;
40
+ /** Resolves the current text now. */
41
+ submit: () => Promise<void>;
42
+ /** Bind this to your input. */
43
+ text: Ref<string>;
44
+ }
45
+ /**
46
+ * Turns the text of an input into a selection through a function that you write. It owns the status, the debounce, and
47
+ * the cancelation of older requests. It does not know your server, your store, or your UI.
48
+ *
49
+ * Give the type of your Choices as the generic, for example `useChoices<typeof forecast>({ ... })`. Import it with
50
+ * `import type`, so no server code reaches the browser.
51
+ */
52
+ export declare function useChoices<TChoices extends ChoicesLike>(options: UseChoicesOptions<ChoicesSelectionOf<TChoices>>): UseChoicesResult<ChoicesSelectionOf<TChoices>>;
53
+ export declare function useChoices<TSelection>(options: UseChoicesOptions<TSelection>): UseChoicesResult<TSelection>;
54
+ //#endregion
package/dist/vue.js ADDED
@@ -0,0 +1,79 @@
1
+ import { onScopeDispose, readonly, ref, watch } from "vue";
2
+ //#region src/vue.ts
3
+ function toError(value) {
4
+ return value instanceof Error ? value : new Error(String(value));
5
+ }
6
+ function useChoices(options) {
7
+ const text = ref("");
8
+ const status = ref("idle");
9
+ const selection = ref();
10
+ const error = ref();
11
+ const minLength = options.minLength ?? 3;
12
+ let controller;
13
+ let timer;
14
+ function cancel() {
15
+ clearTimeout(timer);
16
+ timer = void 0;
17
+ controller?.abort();
18
+ controller = void 0;
19
+ }
20
+ async function submit() {
21
+ clearTimeout(timer);
22
+ timer = void 0;
23
+ const value = text.value.trim();
24
+ controller?.abort();
25
+ if (!value) {
26
+ controller = void 0;
27
+ status.value = "idle";
28
+ return;
29
+ }
30
+ const current = new AbortController();
31
+ controller = current;
32
+ status.value = "thinking";
33
+ error.value = void 0;
34
+ try {
35
+ const result = await options.resolve(value, { signal: current.signal });
36
+ if (current.signal.aborted) return;
37
+ selection.value = result;
38
+ status.value = "ready";
39
+ options.onSelect?.(result);
40
+ } catch (cause) {
41
+ if (current.signal.aborted) return;
42
+ error.value = toError(cause);
43
+ status.value = "error";
44
+ }
45
+ }
46
+ function abort() {
47
+ cancel();
48
+ status.value = "idle";
49
+ }
50
+ function clear() {
51
+ cancel();
52
+ text.value = "";
53
+ selection.value = void 0;
54
+ error.value = void 0;
55
+ status.value = "idle";
56
+ options.onClear?.();
57
+ }
58
+ if (options.debounce !== void 0) {
59
+ const delay = options.debounce;
60
+ watch(text, (value) => {
61
+ cancel();
62
+ if (status.value === "thinking") status.value = "idle";
63
+ if (value.trim().length < minLength) return;
64
+ timer = setTimeout(() => void submit(), delay);
65
+ }, { flush: "sync" });
66
+ }
67
+ onScopeDispose(cancel);
68
+ return {
69
+ abort,
70
+ clear,
71
+ error: readonly(error),
72
+ selection: readonly(selection),
73
+ status: readonly(status),
74
+ submit,
75
+ text
76
+ };
77
+ }
78
+ //#endregion
79
+ export { useChoices };
package/package.json CHANGED
@@ -1,19 +1,89 @@
1
1
  {
2
2
  "name": "@vite-hub/choices",
3
- "version": "0.0.0",
4
- "description": "Turn text into selections over choices that a ViteHub app declares.",
3
+ "version": "0.5.0",
4
+ "description": "Turn text into choices over options that you declare: filters, search facets, command palettes, and builders on a TypeSafe Jev decision model.",
5
+ "keywords": [
6
+ "ai",
7
+ "choices",
8
+ "filters",
9
+ "jev",
10
+ "search",
11
+ "typescript",
12
+ "vitehub"
13
+ ],
14
+ "homepage": "https://vitehub.dev",
15
+ "bugs": "https://github.com/vite-hub/vitehub/issues",
5
16
  "license": "Apache-2.0",
6
17
  "author": "onmax <maximogarciamtnez@gmail.com>",
7
- "homepage": "https://vitehub.dev",
8
18
  "repository": {
9
19
  "type": "git",
10
20
  "url": "git+https://github.com/vite-hub/vitehub.git",
11
21
  "directory": "packages/choices"
12
22
  },
13
- "publishConfig": {
14
- "access": "public"
15
- },
16
23
  "files": [
17
- "README.md"
18
- ]
19
- }
24
+ "dist",
25
+ "package.json"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./cli": {
37
+ "types": "./dist/cli.d.ts",
38
+ "import": "./dist/cli.js",
39
+ "default": "./dist/cli.js"
40
+ },
41
+ "./testing": {
42
+ "types": "./dist/testing.d.ts",
43
+ "import": "./dist/testing.js",
44
+ "default": "./dist/testing.js"
45
+ },
46
+ "./vue": {
47
+ "types": "./dist/vue.d.ts",
48
+ "import": "./dist/vue.js",
49
+ "default": "./dist/vue.js"
50
+ },
51
+ "./package.json": "./package.json"
52
+ },
53
+ "dependencies": {
54
+ "@vite-hub/gateways": "0.5.0",
55
+ "nostics": "1.4.0"
56
+ },
57
+ "devDependencies": {
58
+ "@types/node": "^24.19.1",
59
+ "@vite-hub/internal": "0.0.1",
60
+ "ai": "7.0.130",
61
+ "publint": "^0.3.25",
62
+ "typescript": "^6.0.3",
63
+ "vite": "^8.2.2",
64
+ "vite-plus": "^0.3.3",
65
+ "vitest": "^4.1.11",
66
+ "vue": "3.5.44"
67
+ },
68
+ "peerDependencies": {
69
+ "vite": ">=8.0.0",
70
+ "vue": "^3.5.0"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "vite": {
74
+ "optional": true
75
+ },
76
+ "vue": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "engines": {
81
+ "node": ">=24.15.0"
82
+ },
83
+ "scripts": {
84
+ "build": "vp pack",
85
+ "dev": "vp pack --watch",
86
+ "typecheck": "vp run --cache -t @vite-hub/choices#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
87
+ "test": "vp run --cache -t @vite-hub/choices#build && vp test"
88
+ }
89
+ }