@evobug_com/safe-ts-vue 0.1.0 → 0.3.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @evobug_com/safe-ts-vue
2
2
 
3
- SAFE-TS helpers for Vue 3.5+: <Match> for enum values in templates, async tasks without races, template refs typed by where the element is, listeners and intervals tied to the component, required injections, safe URLs for :href.
3
+ SAFE-TS helpers for Vue 3.5+: <Match> for enum values in templates, async tasks without races, template refs typed by where the element is, listeners and intervals tied to the component, typed props without casts, required injections, safe URLs for :href.
4
4
 
5
5
  **Documentation: [safe-ts.evobug-pages.com/vue](https://safe-ts.evobug-pages.com/vue/)**
6
6
 
@@ -11,4 +11,6 @@ npm install @evobug_com/safe-ts-vue
11
11
  Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
12
12
  guides, a page per rule, and a playground that runs the checker in your browser.
13
13
 
14
+ Changes in each version: [CHANGELOG.md](https://git.evobug.com/Evobug/Safe-Ts/src/branch/main/CHANGELOG.md).
15
+
14
16
  Source: https://git.evobug.com/Evobug/Safe-Ts. Licensed under MIT OR Apache-2.0.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  export { useElement, useElements, useOptionalElement } from "./element.js";
2
- export { injectRequired, type MissingInjection } from "./inject.js";
2
+ export { injectRequired, type MissingInjection, MissingInjectionError, withInjection } from "./inject.js";
3
3
  export { type Stop, useInterval, useListener } from "./listen.js";
4
4
  export { Match, type MatchSlots } from "./match.js";
5
+ export { type DefaultedProp, oneOf, type OptionalProp, prop, type PropConstructorOf, type PropDefault, type PropTypeOf, type PropValidator, type RequiredProp, } from "./prop.js";
5
6
  export { AsyncState } from "./state.js";
6
7
  export { type Task, useTask } from "./task.js";
7
8
  export { safeHref, safeUrl, type UnsafeUrl } from "./url.js";
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // @evobug_com/safe-ts-vue: optional helpers for Vue 3.5+. Each is also importable on its own
2
2
  // (`@evobug_com/safe-ts-vue/task`, ...).
3
3
  export { useElement, useElements, useOptionalElement } from "./element.js";
4
- export { injectRequired } from "./inject.js";
4
+ export { injectRequired, MissingInjectionError, withInjection } from "./inject.js";
5
5
  export { useInterval, useListener } from "./listen.js";
6
6
  export { Match } from "./match.js";
7
+ export { oneOf, prop, } from "./prop.js";
7
8
  export { AsyncState } from "./state.js";
8
9
  export { useTask } from "./task.js";
9
10
  export { safeHref, safeUrl } from "./url.js";
package/dist/inject.d.ts CHANGED
@@ -28,3 +28,33 @@ export type MissingInjection = {
28
28
  * Inside an injection context, a missing value is also warned about by Vue in development.
29
29
  */
30
30
  export declare function injectRequired<T>(key: InjectionKey<T>): Result<T, MissingInjection>;
31
+ /**
32
+ * What `withInjection` reports when nothing was provided: to `app.config.errorHandler` if the app
33
+ * has one, otherwise to `console.error`. It is reported, not thrown.
34
+ */
35
+ export declare class MissingInjectionError extends Error {
36
+ readonly missing: MissingInjection;
37
+ constructor(missing: MissingInjection);
38
+ }
39
+ /**
40
+ * Setup for a component that can't work without an injected value: `setup` gets the value and
41
+ * returns the render function.
42
+ *
43
+ * ```ts
44
+ * export const CartBadge = defineComponent({
45
+ * setup() {
46
+ * return withInjection(CartKey, (cart) => () => h("p", `${cart.count.value} items`));
47
+ * },
48
+ * });
49
+ * ```
50
+ *
51
+ * A missing provider is a mistake in how the app is put together, not something a component can
52
+ * recover from. So instead of an `if` in every component, `withInjection` reports it (a
53
+ * `MissingInjectionError` to `app.config.errorHandler`, or `console.error`) and the component
54
+ * renders nothing. Nothing is thrown: Vue calls `setup` with nothing of yours around it, the same
55
+ * as an event handler. To show something else instead, use `injectRequired` and check it.
56
+ *
57
+ * `setup` runs right away, inside the component's setup, so `ref`, `computed`, `watch` and
58
+ * `onMounted` work in it as usual.
59
+ */
60
+ export declare function withInjection<T, R>(key: InjectionKey<T>, setup: (value: T) => () => R): () => R | undefined;
package/dist/inject.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // `inject()` that says when nothing was provided, instead of handing back `undefined` typed as T.
2
- import { err } from "@evobug_com/safe-ts-std/result";
3
- import { hasInjectionContext, inject } from "vue";
2
+ import { err, isErr } from "@evobug_com/safe-ts-std/result";
3
+ import { getCurrentInstance, hasInjectionContext, inject } from "vue";
4
4
  /**
5
5
  * The value provided for `key`, or an `Err` saying it is missing:
6
6
  *
@@ -23,3 +23,50 @@ export function injectRequired(key) {
23
23
  return err({ key: name, reason: "NotProvided" });
24
24
  return value;
25
25
  }
26
+ /**
27
+ * What `withInjection` reports when nothing was provided: to `app.config.errorHandler` if the app
28
+ * has one, otherwise to `console.error`. It is reported, not thrown.
29
+ */
30
+ export class MissingInjectionError extends Error {
31
+ missing;
32
+ constructor(missing) {
33
+ const why = missing.reason === "NotProvided" ? "nothing provides it" : "called outside setup()";
34
+ super(`inject "${missing.key}": ${why}`);
35
+ this.name = "MissingInjectionError";
36
+ this.missing = missing;
37
+ }
38
+ }
39
+ /**
40
+ * Setup for a component that can't work without an injected value: `setup` gets the value and
41
+ * returns the render function.
42
+ *
43
+ * ```ts
44
+ * export const CartBadge = defineComponent({
45
+ * setup() {
46
+ * return withInjection(CartKey, (cart) => () => h("p", `${cart.count.value} items`));
47
+ * },
48
+ * });
49
+ * ```
50
+ *
51
+ * A missing provider is a mistake in how the app is put together, not something a component can
52
+ * recover from. So instead of an `if` in every component, `withInjection` reports it (a
53
+ * `MissingInjectionError` to `app.config.errorHandler`, or `console.error`) and the component
54
+ * renders nothing. Nothing is thrown: Vue calls `setup` with nothing of yours around it, the same
55
+ * as an event handler. To show something else instead, use `injectRequired` and check it.
56
+ *
57
+ * `setup` runs right away, inside the component's setup, so `ref`, `computed`, `watch` and
58
+ * `onMounted` work in it as usual.
59
+ */
60
+ export function withInjection(key, setup) {
61
+ const value = injectRequired(key);
62
+ if (!isErr(value))
63
+ return setup(value);
64
+ const error = new MissingInjectionError(value.error);
65
+ const instance = getCurrentInstance();
66
+ const handler = instance?.appContext.config.errorHandler;
67
+ if (handler === undefined || instance === null)
68
+ console.error(error);
69
+ else
70
+ handler(error, instance.proxy, "setup function");
71
+ return () => undefined;
72
+ }
@@ -0,0 +1 @@
1
+ export { Fragment, type JSX, jsx, jsxDEV, jsxs } from "./jsx-runtime.js";
@@ -0,0 +1,2 @@
1
+ // The development entry of the JSX runtime (`jsx: "react-jsxdev"`): the same functions.
2
+ export { Fragment, jsx, jsxDEV, jsxs } from "./jsx-runtime.js";
@@ -0,0 +1,11 @@
1
+ import { Fragment, type VNode, type VNodeTypes } from "vue";
2
+ export { Fragment };
3
+ /** The JSX namespace TypeScript checks the elements against: Vue's own. */
4
+ export type { JSX } from "vue/jsx-runtime";
5
+ /** What JSX hands the runtime: the attributes, and the children under `children`. */
6
+ export type JsxProps = Readonly<Record<string, unknown>> & {
7
+ readonly children?: unknown;
8
+ };
9
+ /** The vnode of one JSX element (`key` is the `key` attribute, which JSX passes apart). */
10
+ export declare function jsx(type: VNodeTypes, props: JsxProps | undefined, key?: PropertyKey): VNode;
11
+ export { jsx as jsxs, jsx as jsxDEV };
@@ -0,0 +1,43 @@
1
+ // @safe-ts std: one call into Vue's untyped vnode factory, for JSX of any element or component.
2
+ // A JSX runtime for Vue TSX: `"jsxImportSource": "@evobug_com/safe-ts-vue"` in tsconfig.json (and
3
+ // in the bundler's JSX options) compiles `<Panel title="Cart">…</Panel>` to calls of `jsx` here.
4
+ //
5
+ // Vue's own `vue/jsx-runtime` is its `h`, which hands a component its JSX children as a plain
6
+ // array: Vue then turns them into a default slot on every render and, in development, warns each
7
+ // time ("Non-function value encountered for default slot"). Here the children of a component
8
+ // become a default slot function, as Vue's Babel JSX plugin does at compile time. Elements,
9
+ // fragments and `Teleport` keep their children as they are, and an explicit slot object
10
+ // (`{{ default: () => …, actions: () => … }}`) or a slot function passes through.
11
+ import { createVNode, Fragment, isVNode, setBlockTracking } from "vue";
12
+ export { Fragment };
13
+ function isComponent(type) {
14
+ if (typeof type === "function")
15
+ return true;
16
+ return typeof type === "object" && type !== null && !("__isTeleport" in type && Boolean(type.__isTeleport));
17
+ }
18
+ function isSlotObject(children) {
19
+ return typeof children === "object" && children !== null && !Array.isArray(children) && !isVNode(children);
20
+ }
21
+ /** What `h(type, props, children)` does with a props object, without its per-kind overloads. */
22
+ function vnode(type, props, children) {
23
+ setBlockTracking(-1);
24
+ try {
25
+ return createVNode(type, props, isVNode(children) ? [children] : children);
26
+ }
27
+ finally {
28
+ setBlockTracking(1);
29
+ }
30
+ }
31
+ /** The vnode of one JSX element (`key` is the `key` attribute, which JSX passes apart). */
32
+ export function jsx(type, props, key) {
33
+ const { children, ...rest } = { ...props };
34
+ if (key !== undefined)
35
+ rest["key"] = key;
36
+ if (children === undefined)
37
+ return vnode(type, rest, undefined);
38
+ if (isComponent(type) && typeof children !== "function" && !isSlotObject(children)) {
39
+ return vnode(type, rest, { default: () => children });
40
+ }
41
+ return vnode(type, rest, children);
42
+ }
43
+ export { jsx as jsxs, jsx as jsxDEV };
package/dist/match.d.ts CHANGED
@@ -31,6 +31,9 @@ export type MatchSlots<E extends Tagged> = {
31
31
  * transform can't rewrite (`:on="find(id)"`, slot props with defaults), and tests or tools that
32
32
  * run without it.
33
33
  *
34
+ * The value can't be missing: unlike `match(...)`, there is no `#undefined` slot. Put `<Match>`
35
+ * under `v-if="value"`, with `v-else` for the missing case.
36
+ *
34
37
  * Pass the value, not a Ref: the template unwraps refs only at the top level, so a task's state
35
38
  * is `:on="task.state.value"` (or destructure it: `const { state } = useTask(...)`).
36
39
  */
package/dist/match.js CHANGED
@@ -19,6 +19,9 @@ import { defineComponent } from "vue";
19
19
  * transform can't rewrite (`:on="find(id)"`, slot props with defaults), and tests or tools that
20
20
  * run without it.
21
21
  *
22
+ * The value can't be missing: unlike `match(...)`, there is no `#undefined` slot. Put `<Match>`
23
+ * under `v-if="value"`, with `v-else` for the missing case.
24
+ *
22
25
  * Pass the value, not a Ref: the template unwraps refs only at the top level, so a task's state
23
26
  * is `:on="task.state.value"` (or destructure it: `const { state } = useTask(...)`).
24
27
  */
package/dist/prop.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ import type { PropType } from "vue";
2
+ /**
3
+ * The runtime constructor Vue checks a prop of type `T` against: `String` for strings and string
4
+ * literals, `Number`, `Boolean`, `Array` for arrays and tuples, `Function`, and `Object` for
5
+ * other objects. A union of kinds (`string | number`) takes an array: `[String, Number]`.
6
+ */
7
+ export type PropConstructorOf<T> = T extends string ? StringConstructor : T extends number ? NumberConstructor : T extends boolean ? BooleanConstructor : T extends readonly unknown[] ? ArrayConstructor : T extends (...args: never[]) => unknown ? FunctionConstructor : T extends object ? ObjectConstructor : never;
8
+ /**
9
+ * What `prop<T>()` hands to Vue. For `boolean` it says `BooleanConstructor`, which is how Vue's
10
+ * types know that a missing boolean prop is `false`, not `undefined`.
11
+ */
12
+ export type PropTypeOf<T> = [T] extends [boolean] ? BooleanConstructor : PropType<T>;
13
+ /**
14
+ * A default for a prop of type `T`. Objects and arrays need a factory, so instances don't share
15
+ * one; a function prop's default is the function itself (Vue doesn't call it).
16
+ */
17
+ export type PropDefault<T> = [T] extends [(...args: never[]) => unknown] ? T : [T] extends [object] ? () => T : T;
18
+ /**
19
+ * Called by Vue in development builds, after the constructor check passed. `false` makes Vue
20
+ * warn about the prop.
21
+ */
22
+ export type PropValidator = (value: unknown) => boolean;
23
+ /** A prop the parent may leave out: `T | undefined` in the component (`false` for `boolean`). */
24
+ export type OptionalProp<T> = {
25
+ readonly type: PropTypeOf<T>;
26
+ readonly validator?: PropValidator;
27
+ };
28
+ /** A prop the parent must pass: `T` in the component. */
29
+ export type RequiredProp<T> = OptionalProp<T> & {
30
+ readonly required: true;
31
+ };
32
+ /** A prop the parent may leave out, with a default: `T` in the component. */
33
+ export type DefaultedProp<T> = OptionalProp<T> & {
34
+ readonly default: PropDefault<T>;
35
+ };
36
+ type Constructors<T> = PropConstructorOf<T> | readonly PropConstructorOf<T>[];
37
+ /**
38
+ * A typed prop declaration for `defineComponent`'s `props` option, without a cast:
39
+ *
40
+ * ```ts
41
+ * export const Panel = defineComponent({
42
+ * props: {
43
+ * title: prop<string>(String, { required: true }),
44
+ * side: prop<"left" | "right">(String, { default: "left" }),
45
+ * items: prop<readonly Item[]>(Array, { default: () => [] }),
46
+ * collapsed: prop<boolean>(Boolean),
47
+ * },
48
+ * setup(props) { ... }, // props.side: "left" | "right", props.collapsed: boolean
49
+ * });
50
+ * ```
51
+ *
52
+ * The constructor must fit `T` (`prop<number>(String)` doesn't compile). It is the runtime part
53
+ * Vue keeps: Boolean casting (a missing `Boolean` prop is `false`, `<Panel collapsed />` is
54
+ * `true`), defaults, and in development a warning when the value has the wrong constructor or
55
+ * `validator` returns `false`. That check can't tell `"left"` from any other string; `oneOf`
56
+ * checks the exact values.
57
+ */
58
+ export declare function prop<T>(type: Constructors<T>, options: {
59
+ readonly required: true;
60
+ readonly validator?: PropValidator;
61
+ }): RequiredProp<T>;
62
+ export declare function prop<T>(type: Constructors<T>, options: {
63
+ readonly default: PropDefault<T>;
64
+ readonly validator?: PropValidator;
65
+ }): DefaultedProp<T>;
66
+ export declare function prop<T>(type: Constructors<T>, options?: {
67
+ readonly validator?: PropValidator;
68
+ }): OptionalProp<T>;
69
+ type Literals = readonly [string, ...string[]] | readonly [number, ...number[]];
70
+ /**
71
+ * A prop that is one of a fixed list of strings (or numbers). Its type is the union of the
72
+ * values, and the runtime check (in development) is the same list, so the two can't disagree:
73
+ *
74
+ * ```ts
75
+ * props: {
76
+ * side: oneOf(["left", "right"], { default: "left" }), // "left" | "right"
77
+ * size: oneOf([1, 2, 3]), // 1 | 2 | 3 | undefined
78
+ * }
79
+ * ```
80
+ */
81
+ export declare function oneOf<const V extends Literals>(values: V, options: {
82
+ readonly required: true;
83
+ }): RequiredProp<V[number]>;
84
+ export declare function oneOf<const V extends Literals>(values: V, options: {
85
+ readonly default: V[number];
86
+ }): DefaultedProp<V[number]>;
87
+ export declare function oneOf<const V extends Literals>(values: V): OptionalProp<V[number]>;
88
+ export {};
package/dist/prop.js ADDED
@@ -0,0 +1,12 @@
1
+ export function prop(type, options = {}) {
2
+ // The one cast: Vue reads the prop's type from `type`, and `T` is what the caller says it holds.
3
+ // The parent's code is type-checked against `T`; the constructor check backs it up at runtime.
4
+ return { ...options, type: type };
5
+ }
6
+ export function oneOf(values, options = {}) {
7
+ const validator = (value) => values.some((allowed) => allowed === value);
8
+ const runtime = typeof values[0] === "number" ? Number : String;
9
+ // Through `unknown`: TypeScript can't see that `PropTypeOf` of strings or numbers is never the
10
+ // boolean case. The type is the values' union, and `validator` checks exactly those values.
11
+ return { ...options, type: runtime, validator };
12
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@evobug_com/safe-ts-vue",
3
- "version": "0.1.0",
4
- "description": "SAFE-TS helpers for Vue 3.5+: <Match> for enum values in templates, async tasks without races, template refs typed by where the element is, listeners and intervals tied to the component, required injections, safe URLs for :href.",
3
+ "version": "0.3.0",
4
+ "description": "SAFE-TS helpers for Vue 3.5+: <Match> for enum values in templates, async tasks without races, template refs typed by where the element is, listeners and intervals tied to the component, typed props without casts, required injections, safe URLs for :href.",
5
5
  "keywords": [
6
6
  "safe-ts",
7
7
  "typescript",
@@ -52,9 +52,21 @@
52
52
  "types": "./dist/inject.d.ts",
53
53
  "default": "./dist/inject.js"
54
54
  },
55
+ "./prop": {
56
+ "types": "./dist/prop.d.ts",
57
+ "default": "./dist/prop.js"
58
+ },
55
59
  "./url": {
56
60
  "types": "./dist/url.d.ts",
57
61
  "default": "./dist/url.js"
62
+ },
63
+ "./jsx-runtime": {
64
+ "types": "./dist/jsx-runtime.d.ts",
65
+ "default": "./dist/jsx-runtime.js"
66
+ },
67
+ "./jsx-dev-runtime": {
68
+ "types": "./dist/jsx-dev-runtime.d.ts",
69
+ "default": "./dist/jsx-dev-runtime.js"
58
70
  }
59
71
  },
60
72
  "files": [
@@ -63,7 +75,7 @@
63
75
  "LICENSE-APACHE"
64
76
  ],
65
77
  "peerDependencies": {
66
- "@evobug_com/safe-ts-std": "^0.1.0",
78
+ "@evobug_com/safe-ts-std": "^0.3.0",
67
79
  "vue": "^3.5.0"
68
80
  },
69
81
  "publishConfig": {