@evobug_com/safe-ts-vue 0.0.0-stage → 0.1.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/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evobug
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @evobug_com/safe-ts-vue
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
5
+ **Documentation: [safe-ts.evobug-pages.com/vue](https://safe-ts.evobug-pages.com/vue/)**
6
+
7
+ ```sh
8
+ npm install @evobug_com/safe-ts-vue
9
+ ```
10
+
11
+ Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
12
+ guides, a page per rule, and a playground that runs the checker in your browser.
13
+
14
+ Source: https://git.evobug.com/Evobug/Safe-Ts. Licensed under MIT OR Apache-2.0.
@@ -0,0 +1,25 @@
1
+ import type { Option } from "@evobug_com/safe-ts-std/result";
2
+ import { type ComputedRef, type ShallowRef } from "vue";
3
+ /**
4
+ * The element with `ref="name"`, for one that is always rendered: not under `v-if`, `v-for`
5
+ * or another component's slot. Typed `T`, not `T | null`:
6
+ *
7
+ * ```ts
8
+ * const input = useElement<HTMLInputElement>("input");
9
+ * onMounted(() => input.value.focus());
10
+ * ```
11
+ *
12
+ * The element exists from mount to unmount, so read it in `onMounted` / `onUpdated` or in an
13
+ * event handler (before any `await`). safe-ts checks both: that the template always renders
14
+ * the element, and that it isn't read during setup, in `onBeforeMount`, in a `computed` or
15
+ * after an `await`. If the element is missing after all (a `<KeepAlive>` branch, a template
16
+ * the checker can't read), this logs an error when the component mounts.
17
+ */
18
+ export declare function useElement<T = HTMLElement>(name: string): Readonly<ShallowRef<T>>;
19
+ /**
20
+ * The element with `ref="name"` when it may be missing (under `v-if`, in a slot): `undefined`
21
+ * while it isn't rendered, so TypeScript makes you check it.
22
+ */
23
+ export declare function useOptionalElement<T = HTMLElement>(name: string): ComputedRef<Option<T>>;
24
+ /** The elements with `ref="name"` inside `v-for`: empty until mounted. */
25
+ export declare function useElements<T = HTMLElement>(name: string): ComputedRef<readonly T[]>;
@@ -0,0 +1,38 @@
1
+ import { computed, onMounted, useTemplateRef } from "vue";
2
+ /**
3
+ * The element with `ref="name"`, for one that is always rendered: not under `v-if`, `v-for`
4
+ * or another component's slot. Typed `T`, not `T | null`:
5
+ *
6
+ * ```ts
7
+ * const input = useElement<HTMLInputElement>("input");
8
+ * onMounted(() => input.value.focus());
9
+ * ```
10
+ *
11
+ * The element exists from mount to unmount, so read it in `onMounted` / `onUpdated` or in an
12
+ * event handler (before any `await`). safe-ts checks both: that the template always renders
13
+ * the element, and that it isn't read during setup, in `onBeforeMount`, in a `computed` or
14
+ * after an `await`. If the element is missing after all (a `<KeepAlive>` branch, a template
15
+ * the checker can't read), this logs an error when the component mounts.
16
+ */
17
+ export function useElement(name) {
18
+ const element = useTemplateRef(name);
19
+ onMounted(() => {
20
+ if (element.value === null) {
21
+ console.error(`useElement("${name}"): no element with ref="${name}" was rendered; use useOptionalElement for one that may be missing`);
22
+ }
23
+ });
24
+ return element;
25
+ }
26
+ /**
27
+ * The element with `ref="name"` when it may be missing (under `v-if`, in a slot): `undefined`
28
+ * while it isn't rendered, so TypeScript makes you check it.
29
+ */
30
+ export function useOptionalElement(name) {
31
+ const element = useTemplateRef(name);
32
+ return computed(() => element.value ?? undefined);
33
+ }
34
+ /** The elements with `ref="name"` inside `v-for`: empty until mounted. */
35
+ export function useElements(name) {
36
+ const elements = useTemplateRef(name);
37
+ return computed(() => elements.value ?? []);
38
+ }
@@ -0,0 +1,7 @@
1
+ export { useElement, useElements, useOptionalElement } from "./element.js";
2
+ export { injectRequired, type MissingInjection } from "./inject.js";
3
+ export { type Stop, useInterval, useListener } from "./listen.js";
4
+ export { Match, type MatchSlots } from "./match.js";
5
+ export { AsyncState } from "./state.js";
6
+ export { type Task, useTask } from "./task.js";
7
+ export { safeHref, safeUrl, type UnsafeUrl } from "./url.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // @evobug_com/safe-ts-vue: optional helpers for Vue 3.5+. Each is also importable on its own
2
+ // (`@evobug_com/safe-ts-vue/task`, ...).
3
+ export { useElement, useElements, useOptionalElement } from "./element.js";
4
+ export { injectRequired } from "./inject.js";
5
+ export { useInterval, useListener } from "./listen.js";
6
+ export { Match } from "./match.js";
7
+ export { AsyncState } from "./state.js";
8
+ export { useTask } from "./task.js";
9
+ export { safeHref, safeUrl } from "./url.js";
@@ -0,0 +1,30 @@
1
+ import { type Result } from "@evobug_com/safe-ts-std/result";
2
+ import { type InjectionKey } from "vue";
3
+ /**
4
+ * Why `injectRequired` found nothing:
5
+ *
6
+ * - `NotProvided`: no ancestor component (and not the app) provided `key`, or it provided
7
+ * `undefined`;
8
+ * - `OutsideSetup`: called outside `setup()` / a functional component / `app.runWithContext`,
9
+ * where `inject` can't look anything up.
10
+ *
11
+ * `key` is the key's description (`Symbol("theme")` gives `"theme"`).
12
+ */
13
+ export type MissingInjection = {
14
+ readonly key: string;
15
+ readonly reason: "NotProvided" | "OutsideSetup";
16
+ };
17
+ /**
18
+ * The value provided for `key`, or an `Err` saying it is missing:
19
+ *
20
+ * ```ts
21
+ * export const ThemeKey: InjectionKey<Theme> = Symbol("theme");
22
+ *
23
+ * const theme = injectRequired(ThemeKey);
24
+ * if (isErr(theme)) console.error(`no ${theme.error.key}: wrap the app in <ThemeProvider>`);
25
+ * const colors = isErr(theme) ? defaultColors : theme.colors;
26
+ * ```
27
+ *
28
+ * Inside an injection context, a missing value is also warned about by Vue in development.
29
+ */
30
+ export declare function injectRequired<T>(key: InjectionKey<T>): Result<T, MissingInjection>;
package/dist/inject.js ADDED
@@ -0,0 +1,25 @@
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";
4
+ /**
5
+ * The value provided for `key`, or an `Err` saying it is missing:
6
+ *
7
+ * ```ts
8
+ * export const ThemeKey: InjectionKey<Theme> = Symbol("theme");
9
+ *
10
+ * const theme = injectRequired(ThemeKey);
11
+ * if (isErr(theme)) console.error(`no ${theme.error.key}: wrap the app in <ThemeProvider>`);
12
+ * const colors = isErr(theme) ? defaultColors : theme.colors;
13
+ * ```
14
+ *
15
+ * Inside an injection context, a missing value is also warned about by Vue in development.
16
+ */
17
+ export function injectRequired(key) {
18
+ const name = key.description ?? key.toString();
19
+ if (!hasInjectionContext())
20
+ return err({ key: name, reason: "OutsideSetup" });
21
+ const value = inject(key);
22
+ if (value === undefined)
23
+ return err({ key: name, reason: "NotProvided" });
24
+ return value;
25
+ }
@@ -0,0 +1,33 @@
1
+ /** Stops a listener or interval. Calling it again does nothing. */
2
+ export type Stop = () => void;
3
+ /**
4
+ * `target.addEventListener(type, handler, options)` until the component unmounts:
5
+ *
6
+ * ```ts
7
+ * useListener<KeyboardEvent>(window, "keydown", (event) => {
8
+ * if (event.key === "Escape") emit("close");
9
+ * });
10
+ * ```
11
+ *
12
+ * The listener is registered with an `AbortController`'s signal, aborted when the current
13
+ * effect scope is disposed (a component's scope ends when it unmounts), or earlier by calling
14
+ * the returned `Stop`. Outside a scope nothing removes it automatically: keep the `Stop`.
15
+ * A `signal` in `options` still works and removes the listener too.
16
+ *
17
+ * For elements in your own template, use `@keydown` there; this is for targets the template
18
+ * can't reach: `window`, `document`, a `MediaQueryList`, a `WebSocket`, ...
19
+ *
20
+ * `E` is not checked against `type`: name the event type that `type` really dispatches.
21
+ */
22
+ export declare function useListener<E extends Event>(target: EventTarget, type: string, handler: (event: E) => void, options?: AddEventListenerOptions): Stop;
23
+ /**
24
+ * `setInterval(fn, ms)` until the component unmounts (or the returned `Stop` is called):
25
+ *
26
+ * ```ts
27
+ * const now = shallowRef(Date.now());
28
+ * useInterval(() => (now.value = Date.now()), 1_000);
29
+ * ```
30
+ *
31
+ * `fn` runs from a timer, outside any `try` of yours: handle its failures inside it.
32
+ */
33
+ export declare function useInterval(fn: () => void, ms: number): Stop;
package/dist/listen.js ADDED
@@ -0,0 +1,55 @@
1
+ // Listeners and intervals that live as long as the component (or effect scope) that made them.
2
+ //
3
+ // `using sub = listen(...)` from @evobug_com/safe-ts-std/events removes the listener when its block
4
+ // ends, and in `<script setup>` the block ends as soon as setup returns, before the component
5
+ // is even shown. These remove theirs when the component unmounts instead.
6
+ import { listen } from "@evobug_com/safe-ts-std/events";
7
+ import { getCurrentScope, onScopeDispose } from "vue";
8
+ /**
9
+ * `target.addEventListener(type, handler, options)` until the component unmounts:
10
+ *
11
+ * ```ts
12
+ * useListener<KeyboardEvent>(window, "keydown", (event) => {
13
+ * if (event.key === "Escape") emit("close");
14
+ * });
15
+ * ```
16
+ *
17
+ * The listener is registered with an `AbortController`'s signal, aborted when the current
18
+ * effect scope is disposed (a component's scope ends when it unmounts), or earlier by calling
19
+ * the returned `Stop`. Outside a scope nothing removes it automatically: keep the `Stop`.
20
+ * A `signal` in `options` still works and removes the listener too.
21
+ *
22
+ * For elements in your own template, use `@keydown` there; this is for targets the template
23
+ * can't reach: `window`, `document`, a `MediaQueryList`, a `WebSocket`, ...
24
+ *
25
+ * `E` is not checked against `type`: name the event type that `type` really dispatches.
26
+ */
27
+ export function useListener(target, type, handler, options) {
28
+ const controller = new AbortController();
29
+ const signal = options?.signal === undefined ? controller.signal : AbortSignal.any([options.signal, controller.signal]);
30
+ listen(target, type, handler, { ...options, signal });
31
+ const stop = () => controller.abort();
32
+ stopWithScope(stop);
33
+ return stop;
34
+ }
35
+ /**
36
+ * `setInterval(fn, ms)` until the component unmounts (or the returned `Stop` is called):
37
+ *
38
+ * ```ts
39
+ * const now = shallowRef(Date.now());
40
+ * useInterval(() => (now.value = Date.now()), 1_000);
41
+ * ```
42
+ *
43
+ * `fn` runs from a timer, outside any `try` of yours: handle its failures inside it.
44
+ */
45
+ export function useInterval(fn, ms) {
46
+ const id = setInterval(fn, ms);
47
+ const stop = () => clearInterval(id);
48
+ stopWithScope(stop);
49
+ return stop;
50
+ }
51
+ /** Run `stop` when the current effect scope is disposed, if there is one. */
52
+ function stopWithScope(stop) {
53
+ if (getCurrentScope() !== undefined)
54
+ onScopeDispose(stop);
55
+ }
@@ -0,0 +1,65 @@
1
+ import { type EmitsOptions, type SlotsType, type VNode } from "vue";
2
+ type Tagged = {
3
+ readonly tag: string;
4
+ };
5
+ /**
6
+ * The slots of `<Match :on="value">`: one per variant, given that variant (so `#Ready="{ value }"`
7
+ * reads its fields), and `_` for the variants without a slot of their own.
8
+ */
9
+ export type MatchSlots<E extends Tagged> = {
10
+ readonly [K in E["tag"]]?: (variant: Extract<E, {
11
+ readonly tag: K;
12
+ }>) => VNode[];
13
+ } & {
14
+ readonly _?: (value: E) => VNode[];
15
+ };
16
+ /**
17
+ * Show an enum value variant by variant, like `match(value, { ... })` in a template:
18
+ *
19
+ * ```vue
20
+ * <Match :on="user">
21
+ * <template #Loading>…</template>
22
+ * <template #Ready="{ value }">{{ value.name }}</template>
23
+ * <template #Failed="{ error }">{{ error.message }}</template>
24
+ * <template #_>Not loaded yet</template>
25
+ * </Match>
26
+ * ```
27
+ *
28
+ * safe-ts checks that every variant has a slot (or that `#_` is there), and that each slot names
29
+ * a variant. With the build transform (`safeTs()` before `vue()` in Vite), `<Match>` is compiled
30
+ * into a `v-if` chain on `value.tag` and this component isn't used at all; it renders what the
31
+ * transform can't rewrite (`:on="find(id)"`, slot props with defaults), and tests or tools that
32
+ * run without it.
33
+ *
34
+ * Pass the value, not a Ref: the template unwraps refs only at the top level, so a task's state
35
+ * is `:on="task.state.value"` (or destructure it: `const { state } = useTask(...)`).
36
+ */
37
+ export declare const Match: new <E extends Tagged>(props: ({
38
+ readonly on: E;
39
+ } & ({
40
+ [x: `on${Capitalize<string>}`]: ((...args: any[]) => any) | undefined;
41
+ } | {
42
+ [x: `on${Capitalize<string>}`]: ((...args: never) => any) | undefined;
43
+ })) & import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps) => import("vue").CreateComponentPublicInstanceWithMixins<{
44
+ readonly on: E;
45
+ } & ({
46
+ [x: `on${Capitalize<string>}`]: ((...args: any[]) => any) | undefined;
47
+ } | {
48
+ [x: `on${Capitalize<string>}`]: ((...args: never) => any) | undefined;
49
+ }), {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, EmitsOptions, import("vue").PublicProps, {}, false, {}, SlotsType<MatchSlots<E>>, {}, {}, string, {}, any, import("vue").ComponentProvideOptions, {
50
+ P: {};
51
+ B: {};
52
+ D: {};
53
+ C: {};
54
+ M: {};
55
+ Defaults: {};
56
+ }, ({
57
+ readonly on: E;
58
+ } & {
59
+ [x: `on${Capitalize<string>}`]: ((...args: any[]) => any) | undefined;
60
+ }) | ({
61
+ readonly on: E;
62
+ } & {
63
+ [x: `on${Capitalize<string>}`]: ((...args: never) => any) | undefined;
64
+ }), {}, {}, {}, {}, {}>;
65
+ export {};
package/dist/match.js ADDED
@@ -0,0 +1,30 @@
1
+ // @safe-ts std: picking the slot by the value's tag needs one cast (see `Match`).
2
+ // `<Match :on="value">`: an enum value in a template, one slot per variant.
3
+ import { defineComponent } from "vue";
4
+ /**
5
+ * Show an enum value variant by variant, like `match(value, { ... })` in a template:
6
+ *
7
+ * ```vue
8
+ * <Match :on="user">
9
+ * <template #Loading>…</template>
10
+ * <template #Ready="{ value }">{{ value.name }}</template>
11
+ * <template #Failed="{ error }">{{ error.message }}</template>
12
+ * <template #_>Not loaded yet</template>
13
+ * </Match>
14
+ * ```
15
+ *
16
+ * safe-ts checks that every variant has a slot (or that `#_` is there), and that each slot names
17
+ * a variant. With the build transform (`safeTs()` before `vue()` in Vite), `<Match>` is compiled
18
+ * into a `v-if` chain on `value.tag` and this component isn't used at all; it renders what the
19
+ * transform can't rewrite (`:on="find(id)"`, slot props with defaults), and tests or tools that
20
+ * run without it.
21
+ *
22
+ * Pass the value, not a Ref: the template unwraps refs only at the top level, so a task's state
23
+ * is `:on="task.state.value"` (or destructure it: `const { state } = useTask(...)`).
24
+ */
25
+ export const Match = defineComponent((props, { slots }) => () => {
26
+ // A slot per tag: TypeScript can't tie `slots[tag]` to the variant with that tag, which
27
+ // is what `MatchSlots` says it is.
28
+ const byTag = slots;
29
+ return (byTag[props.on.tag] ?? slots._)?.(props.on);
30
+ }, { name: "Match", props: ["on"] });
@@ -0,0 +1 @@
1
+ export { AsyncState } from "@evobug_com/safe-ts-std/async-state";
package/dist/state.js ADDED
@@ -0,0 +1,3 @@
1
+ // The state of async work a component shows: nothing yet, in progress, done, or failed.
2
+ // Defined in @evobug_com/safe-ts-std/async-state, so Vue and React code share one type.
3
+ export { AsyncState } from "@evobug_com/safe-ts-std/async-state";
package/dist/task.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { type Result } from "@evobug_com/safe-ts-std/result";
2
+ import { type ShallowRef } from "vue";
3
+ import { AsyncState } from "./state.js";
4
+ /** What `useTask` returns. */
5
+ export type Task<A extends readonly unknown[], T, E> = {
6
+ /** Where the latest run stands. Read-only: only the task changes it. */
7
+ readonly state: Readonly<ShallowRef<AsyncState<T, E>>>;
8
+ /**
9
+ * Start a run, aborting the one in progress. Resolves when this run is over (or was
10
+ * superseded). Rejects only when `run` itself rejected or threw: a bug, see `useTask`.
11
+ */
12
+ readonly run: (...args: A) => Promise<void>;
13
+ /** Abort the run in progress, if any; `state` goes back to `Idle`. */
14
+ readonly abort: () => void;
15
+ };
16
+ /**
17
+ * Run async work and keep its outcome in a reactive `state`, with at most one run at a time:
18
+ *
19
+ * ```ts
20
+ * const user = useTask((signal, id: string) => fetchUser(id, signal));
21
+ * watch(() => props.id, (id) => user.run(id), { immediate: true });
22
+ * // template: <p v-if="user.state.value.tag === 'Ready'">{{ user.state.value.value.name }}</p>
23
+ * ```
24
+ *
25
+ * - Every `run(...)` aborts the previous run's `signal` and starts a new one. Only the latest
26
+ * run writes `state`: an earlier one that finishes later (the response for the previous
27
+ * `id` arriving last) is discarded, whatever it resolved or rejected with.
28
+ * - `run` reports expected failures by returning an `Err`; that becomes `Failed`.
29
+ * - Called inside a component's `setup` (or any effect scope), the task is aborted when the
30
+ * component unmounts, and `run(...)` does nothing afterwards. Outside a scope, call
31
+ * `abort()` yourself.
32
+ *
33
+ * When `run` rejects (or throws) instead of returning an `Err`, that is a bug: the failures
34
+ * you expect belong in the `Result`. It is not turned into `Failed`, because `Failed` holds an
35
+ * `E` and the rejection reason is `unknown`, and it is not swallowed either: `state` goes back
36
+ * to `Idle` (no endless spinner) and the promise returned by `task.run(...)` rejects with the
37
+ * same reason. Vue reports a promise rejected from a template event handler, a lifecycle hook
38
+ * or a `watch` callback to `app.config.errorHandler`, so `@click="save.run()"` surfaces it.
39
+ * A rejection after the run was aborted (`fetch`'s `AbortError`) is expected and dropped.
40
+ */
41
+ export declare function useTask<T, E, A extends readonly unknown[] = []>(run: (signal: AbortSignal, ...args: A) => Promise<Result<T, E>>): Task<A, T, E>;
package/dist/task.js ADDED
@@ -0,0 +1,74 @@
1
+ // Async work for a component, without the "async race": a slow earlier request can't
2
+ // overwrite the result of a later one.
3
+ import { isErr } from "@evobug_com/safe-ts-std/result";
4
+ import { getCurrentScope, onScopeDispose, shallowReadonly, shallowRef } from "vue";
5
+ import { AsyncState } from "./state.js";
6
+ /**
7
+ * Run async work and keep its outcome in a reactive `state`, with at most one run at a time:
8
+ *
9
+ * ```ts
10
+ * const user = useTask((signal, id: string) => fetchUser(id, signal));
11
+ * watch(() => props.id, (id) => user.run(id), { immediate: true });
12
+ * // template: <p v-if="user.state.value.tag === 'Ready'">{{ user.state.value.value.name }}</p>
13
+ * ```
14
+ *
15
+ * - Every `run(...)` aborts the previous run's `signal` and starts a new one. Only the latest
16
+ * run writes `state`: an earlier one that finishes later (the response for the previous
17
+ * `id` arriving last) is discarded, whatever it resolved or rejected with.
18
+ * - `run` reports expected failures by returning an `Err`; that becomes `Failed`.
19
+ * - Called inside a component's `setup` (or any effect scope), the task is aborted when the
20
+ * component unmounts, and `run(...)` does nothing afterwards. Outside a scope, call
21
+ * `abort()` yourself.
22
+ *
23
+ * When `run` rejects (or throws) instead of returning an `Err`, that is a bug: the failures
24
+ * you expect belong in the `Result`. It is not turned into `Failed`, because `Failed` holds an
25
+ * `E` and the rejection reason is `unknown`, and it is not swallowed either: `state` goes back
26
+ * to `Idle` (no endless spinner) and the promise returned by `task.run(...)` rejects with the
27
+ * same reason. Vue reports a promise rejected from a template event handler, a lifecycle hook
28
+ * or a `watch` callback to `app.config.errorHandler`, so `@click="save.run()"` surfaces it.
29
+ * A rejection after the run was aborted (`fetch`'s `AbortError`) is expected and dropped.
30
+ */
31
+ export function useTask(run) {
32
+ const state = shallowRef(AsyncState.Idle());
33
+ // The run in progress: the only one allowed to write `state`.
34
+ let current = undefined;
35
+ let disposed = false;
36
+ const abort = () => {
37
+ if (current === undefined)
38
+ return;
39
+ current.abort();
40
+ current = undefined;
41
+ state.value = AsyncState.Idle();
42
+ };
43
+ const start = async (...args) => {
44
+ if (disposed)
45
+ return;
46
+ current?.abort();
47
+ const controller = new AbortController();
48
+ current = controller;
49
+ state.value = AsyncState.Loading();
50
+ let result;
51
+ try {
52
+ result = await run(controller.signal, ...args);
53
+ }
54
+ catch (reason) {
55
+ // Aborted (by a newer run, `abort()` or unmounting): expected, and no longer ours to report.
56
+ if (controller.signal.aborted)
57
+ return;
58
+ current = undefined;
59
+ state.value = AsyncState.Idle();
60
+ return Promise.reject(reason);
61
+ }
62
+ if (controller.signal.aborted)
63
+ return;
64
+ current = undefined;
65
+ state.value = isErr(result) ? AsyncState.Failed({ error: result.error }) : AsyncState.Ready({ value: result });
66
+ };
67
+ if (getCurrentScope() !== undefined) {
68
+ onScopeDispose(() => {
69
+ disposed = true;
70
+ abort();
71
+ });
72
+ }
73
+ return { state: shallowReadonly(state), run: start, abort };
74
+ }
package/dist/url.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { safeHref, safeUrl, type UnsafeUrl } from "@evobug_com/safe-ts-std/url";
package/dist/url.js ADDED
@@ -0,0 +1,3 @@
1
+ // URLs that are safe to bind to `:href`, `:src` (iframe), `:action`, `:formaction`.
2
+ // Defined in @evobug_com/safe-ts-std/url, which doesn't depend on Vue.
3
+ export { safeHref, safeUrl } from "@evobug_com/safe-ts-std/url";
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@evobug_com/safe-ts-vue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
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.",
5
+ "keywords": [
6
+ "safe-ts",
7
+ "typescript",
8
+ "type-safety",
9
+ "vue",
10
+ "vue3",
11
+ "composables",
12
+ "async",
13
+ "result",
14
+ "pattern-matching"
15
+ ],
16
+ "license": "MIT OR Apache-2.0",
17
+ "homepage": "https://safe-ts.evobug-pages.com/vue/",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://git.evobug.com/Evobug/Safe-Ts.git",
21
+ "directory": "packages/safe-ts-vue"
22
+ },
23
+ "bugs": "https://git.evobug.com/Evobug/Safe-Ts/issues",
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./match": {
32
+ "types": "./dist/match.d.ts",
33
+ "default": "./dist/match.js"
34
+ },
35
+ "./state": {
36
+ "types": "./dist/state.d.ts",
37
+ "default": "./dist/state.js"
38
+ },
39
+ "./task": {
40
+ "types": "./dist/task.d.ts",
41
+ "default": "./dist/task.js"
42
+ },
43
+ "./element": {
44
+ "types": "./dist/element.d.ts",
45
+ "default": "./dist/element.js"
46
+ },
47
+ "./listen": {
48
+ "types": "./dist/listen.d.ts",
49
+ "default": "./dist/listen.js"
50
+ },
51
+ "./inject": {
52
+ "types": "./dist/inject.d.ts",
53
+ "default": "./dist/inject.js"
54
+ },
55
+ "./url": {
56
+ "types": "./dist/url.d.ts",
57
+ "default": "./dist/url.js"
58
+ }
59
+ },
60
+ "files": [
61
+ "dist",
62
+ "LICENSE-MIT",
63
+ "LICENSE-APACHE"
64
+ ],
65
+ "peerDependencies": {
66
+ "@evobug_com/safe-ts-std": "^0.1.0",
67
+ "vue": "^3.5.0"
68
+ },
69
+ "publishConfig": {
70
+ "access": "public"
71
+ }
72
+ }