sveltekit-discriminated-fields 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 +21 -0
- package/README.md +172 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +25 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024
|
|
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
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# sveltekit-discriminated-fields
|
|
2
|
+
|
|
3
|
+
Type-safe discriminated union support for SvelteKit form fields.
|
|
4
|
+
|
|
5
|
+
## The Problem
|
|
6
|
+
|
|
7
|
+
When using SvelteKit's `form()` with discriminated union schemas (e.g., Zod's `z.discriminatedUnion`), the generated `fields` object is a **union of field objects**. TypeScript only allows access to properties that exist on ALL variants - meaning variant-specific fields are completely inaccessible.
|
|
8
|
+
|
|
9
|
+
Given a typical SvelteKit setup:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
// data.remote.ts
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { form } from "$app/server/remote";
|
|
15
|
+
|
|
16
|
+
const shapeSchema = z.discriminatedUnion("kind", [
|
|
17
|
+
z.object({ kind: z.literal("circle"), radius: z.number() }),
|
|
18
|
+
z.object({
|
|
19
|
+
kind: z.literal("rectangle"),
|
|
20
|
+
width: z.number(),
|
|
21
|
+
height: z.number(),
|
|
22
|
+
}),
|
|
23
|
+
z.object({ kind: z.literal("point") }),
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
export const shapeForm = form(shapeSchema, async (data) => {
|
|
27
|
+
// handle form submission
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```svelte
|
|
32
|
+
<!-- +page.svelte (without this library) -->
|
|
33
|
+
<script lang="ts">
|
|
34
|
+
import { shapeForm } from './data.remote.ts';
|
|
35
|
+
|
|
36
|
+
const form = shapeForm();
|
|
37
|
+
const shape = form.fields;
|
|
38
|
+
</script>
|
|
39
|
+
|
|
40
|
+
<select {...shape.kind.as('select')}>
|
|
41
|
+
<option value="circle">Circle</option>
|
|
42
|
+
<option value="rectangle">Rectangle</option>
|
|
43
|
+
<option value="point">Point</option>
|
|
44
|
+
</select>
|
|
45
|
+
|
|
46
|
+
{#if shape.kind.value() === 'circle'}
|
|
47
|
+
<!-- ERROR: Property 'radius' does not exist on type 'ShapeFields' -->
|
|
48
|
+
<input {...shape.radius.as('number')} />
|
|
49
|
+
{:else if shape.kind.value() === 'rectangle'}
|
|
50
|
+
<!-- ERROR: Property 'width' does not exist on type 'ShapeFields' -->
|
|
51
|
+
<input {...shape.width.as('number')} />
|
|
52
|
+
{/if}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The issue: `shape.kind.value() === 'circle'` doesn't narrow the type because method calls don't provide TypeScript control flow analysis. You're stuck - variant-specific fields are inaccessible, and there's no way to narrow to access them.
|
|
56
|
+
|
|
57
|
+
## The Solution
|
|
58
|
+
|
|
59
|
+
This library wraps your discriminated union fields to:
|
|
60
|
+
|
|
61
|
+
1. Make all variant fields accessible
|
|
62
|
+
2. Add a `${key}Value` property that enables TypeScript narrowing
|
|
63
|
+
|
|
64
|
+
```svelte
|
|
65
|
+
<!-- +page.svelte (with this library) -->
|
|
66
|
+
<script lang="ts">
|
|
67
|
+
import { shapeForm } from './data.remote.ts';
|
|
68
|
+
import { discriminatedFields } from 'sveltekit-discriminated-fields'; // +
|
|
69
|
+
|
|
70
|
+
const form = shapeForm();
|
|
71
|
+
const shape = discriminatedFields('kind', form.fields); // changed
|
|
72
|
+
</script>
|
|
73
|
+
|
|
74
|
+
<select {...shape.kind.as('select')}>
|
|
75
|
+
<option value="circle">Circle</option>
|
|
76
|
+
<option value="rectangle">Rectangle</option>
|
|
77
|
+
<option value="point">Point</option>
|
|
78
|
+
</select>
|
|
79
|
+
|
|
80
|
+
{#if shape.kindValue === 'circle'}<!-- changed -->
|
|
81
|
+
<input {...shape.radius.as('number')} /><!-- now works! -->
|
|
82
|
+
{:else if shape.kindValue === 'rectangle'}<!-- changed -->
|
|
83
|
+
<input {...shape.width.as('number')} /><!-- now works! -->
|
|
84
|
+
<input {...shape.height.as('number')} />
|
|
85
|
+
<!-- ERROR: Property 'radius' does not exist - correctly rejected -->
|
|
86
|
+
<input {...shape.radius.as('number')} />
|
|
87
|
+
{/if}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The changes:
|
|
91
|
+
|
|
92
|
+
1. Import `discriminatedFields` from this library
|
|
93
|
+
2. Wrap `form.fields` with `discriminatedFields('kind', ...)`
|
|
94
|
+
3. Use `shape.kindValue` instead of `shape.kind.value()` for narrowing
|
|
95
|
+
|
|
96
|
+
## Installation
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
npm install sveltekit-discriminated-fields
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Usage
|
|
103
|
+
|
|
104
|
+
```svelte
|
|
105
|
+
<script lang="ts">
|
|
106
|
+
import { paymentForm } from './data.remote.ts';
|
|
107
|
+
import { discriminatedFields } from 'sveltekit-discriminated-fields';
|
|
108
|
+
|
|
109
|
+
const form = paymentForm();
|
|
110
|
+
|
|
111
|
+
// Wrap fields with $derived for reactivity
|
|
112
|
+
// The first argument is your discriminator key (e.g., 'type', 'kind', 'channel')
|
|
113
|
+
const payment = $derived(discriminatedFields('type', form.fields));
|
|
114
|
+
|
|
115
|
+
function setCardDefaults() {
|
|
116
|
+
// set() is type-safe - TypeScript enforces correct fields for each variant
|
|
117
|
+
payment.set({ type: 'card', cardNumber: '', cvv: '' });
|
|
118
|
+
}
|
|
119
|
+
</script>
|
|
120
|
+
|
|
121
|
+
<!-- typeValue is undefined until form is initialized -->
|
|
122
|
+
{#if payment.typeValue === undefined}
|
|
123
|
+
<p>Loading...</p>
|
|
124
|
+
{:else}
|
|
125
|
+
<select {...payment.type.as('select')}>
|
|
126
|
+
<option value="card">Card</option>
|
|
127
|
+
<option value="bank">Bank Transfer</option>
|
|
128
|
+
</select>
|
|
129
|
+
|
|
130
|
+
<!-- Use typeValue (not type.value()) for type narrowing -->
|
|
131
|
+
{#if payment.typeValue === 'card'}
|
|
132
|
+
<input {...payment.cardNumber.as('string')} />
|
|
133
|
+
<input {...payment.cvv.as('string')} />
|
|
134
|
+
{:else if payment.typeValue === 'bank'}
|
|
135
|
+
<input {...payment.accountNumber.as('string')} />
|
|
136
|
+
<input {...payment.sortCode.as('string')} />
|
|
137
|
+
{/if}
|
|
138
|
+
{/if}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## API
|
|
142
|
+
|
|
143
|
+
### `discriminatedFields(key, fields)`
|
|
144
|
+
|
|
145
|
+
Wraps discriminated union form fields for type-safe narrowing.
|
|
146
|
+
|
|
147
|
+
**Parameters:**
|
|
148
|
+
|
|
149
|
+
- `key` - The discriminator key (e.g., `'type'`, `'kind'`, `'channel'`)
|
|
150
|
+
- `fields` - Form fields from a discriminated union schema
|
|
151
|
+
|
|
152
|
+
**Returns:** A proxy object with:
|
|
153
|
+
|
|
154
|
+
- All original fields passed through unchanged
|
|
155
|
+
- `${key}Value` - The current discriminator value (for narrowing)
|
|
156
|
+
- `set()` - Type-safe setter that infers variant from discriminator
|
|
157
|
+
|
|
158
|
+
### `DiscriminatedData<T>`
|
|
159
|
+
|
|
160
|
+
Type helper that extracts the underlying data type from wrapped fields:
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
const payment = discriminatedFields('type', form.fields);
|
|
164
|
+
type Payment = DiscriminatedData<typeof payment>;
|
|
165
|
+
// { type: 'card'; cardNumber: string; cvv: string } | { type: 'bank'; accountNumber: string; sortCode: string }
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Useful when you need to reference the data type elsewhere, such as defining default values or passing data to other functions.
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export type DiscriminatedData<T> = T extends {
|
|
2
|
+
set: (v: infer D) => unknown;
|
|
3
|
+
} ? D : never;
|
|
4
|
+
type Setter<K extends string, T, D = DiscriminatedData<T>> = {
|
|
5
|
+
set: <V extends D[K & keyof D]>(data: Extract<D, {
|
|
6
|
+
[P in K]: V;
|
|
7
|
+
}>) => void;
|
|
8
|
+
};
|
|
9
|
+
type Keys<T> = T extends unknown ? keyof T : never;
|
|
10
|
+
type KeyValue<K extends string, V> = {
|
|
11
|
+
[P in `${K}Value`]: V;
|
|
12
|
+
};
|
|
13
|
+
type Fields<T> = {
|
|
14
|
+
[P in Keys<T>]: T extends Record<P, infer V> ? V : never;
|
|
15
|
+
};
|
|
16
|
+
type Variant<K extends string, T, V> = KeyValue<K, V> & Fields<T>;
|
|
17
|
+
type Narrowed<K extends string, T> = T extends {
|
|
18
|
+
[P in K]: {
|
|
19
|
+
value(): infer V;
|
|
20
|
+
};
|
|
21
|
+
} ? Variant<K, T, V> : never;
|
|
22
|
+
type Union<K extends string, T> = Narrowed<K, T> | Variant<K, T, undefined>;
|
|
23
|
+
type DiscriminatedFields<K extends string, T> = Setter<K, T> & Union<K, T>;
|
|
24
|
+
/**
|
|
25
|
+
* Wraps discriminated union form fields, adding ${key}Value for type narrowing.
|
|
26
|
+
* - All original fields pass through unchanged (type, issues, allIssues, etc.)
|
|
27
|
+
* - `set` is overridden with type-safe version
|
|
28
|
+
* - `${key}Value` is added for discriminator value (e.g., `reward.typeValue`)
|
|
29
|
+
*
|
|
30
|
+
* @param key - Discriminator key (e.g. 'type')
|
|
31
|
+
* @param fields - Form fields from a discriminated union schema
|
|
32
|
+
* @returns Passthrough object with type-safe set() and ${key}Value for narrowing
|
|
33
|
+
*/
|
|
34
|
+
export declare function discriminatedFields<K extends string, T extends {
|
|
35
|
+
set: (v: never) => unknown;
|
|
36
|
+
} & Record<K, {
|
|
37
|
+
value(): unknown;
|
|
38
|
+
}>>(key: K, fields: T): DiscriminatedFields<K, T>;
|
|
39
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wraps discriminated union form fields, adding ${key}Value for type narrowing.
|
|
3
|
+
* - All original fields pass through unchanged (type, issues, allIssues, etc.)
|
|
4
|
+
* - `set` is overridden with type-safe version
|
|
5
|
+
* - `${key}Value` is added for discriminator value (e.g., `reward.typeValue`)
|
|
6
|
+
*
|
|
7
|
+
* @param key - Discriminator key (e.g. 'type')
|
|
8
|
+
* @param fields - Form fields from a discriminated union schema
|
|
9
|
+
* @returns Passthrough object with type-safe set() and ${key}Value for narrowing
|
|
10
|
+
*/
|
|
11
|
+
export function discriminatedFields(key, fields) {
|
|
12
|
+
const proxy = new Proxy(fields, {
|
|
13
|
+
get(target, prop) {
|
|
14
|
+
if (prop === `${key}Value`)
|
|
15
|
+
return target[key].value();
|
|
16
|
+
if (prop === 'set')
|
|
17
|
+
return (data) => target.set(data);
|
|
18
|
+
return Reflect.get(target, prop);
|
|
19
|
+
},
|
|
20
|
+
has(target, prop) {
|
|
21
|
+
return prop === `${key}Value` || prop in target;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
return proxy;
|
|
25
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sveltekit-discriminated-fields",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Type-safe discriminated union support for SvelteKit form fields",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.build.json",
|
|
17
|
+
"check": "tsc --noEmit",
|
|
18
|
+
"test:types": "tsc -p test/types/tsconfig.json",
|
|
19
|
+
"test": "npm run test:types",
|
|
20
|
+
"prepublishOnly": "npm run test && npm run build"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"svelte",
|
|
24
|
+
"sveltekit",
|
|
25
|
+
"forms",
|
|
26
|
+
"discriminated-union",
|
|
27
|
+
"typescript"
|
|
28
|
+
],
|
|
29
|
+
"author": "robertadamsonsmith",
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "https://github.com/robertadamsonsmith/sveltekit-discriminated-fields"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"typescript": "^5.0.0"
|
|
37
|
+
}
|
|
38
|
+
}
|