@diephp/vue-apix 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 +223 -0
- package/dist/apix.d.ts +49 -0
- package/dist/client.d.ts +27 -0
- package/dist/index.d.ts +7 -0
- package/dist/model.d.ts +112 -0
- package/dist/types.d.ts +100 -0
- package/dist/utils.d.ts +19 -0
- package/dist/vue-apix.cjs +1 -0
- package/dist/vue-apix.js +485 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 astapov (DiePHP)
|
|
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,223 @@
|
|
|
1
|
+
# @diephp/vue-apix
|
|
2
|
+
|
|
3
|
+
Tiny form / model / api toolkit for Vue 3. Fetch data, edit it, send it back — with reactive
|
|
4
|
+
`processing`, Laravel-style validation errors and auto-refetch on change. No axios, zero
|
|
5
|
+
runtime dependencies, only Vue 3 as a peer.
|
|
6
|
+
|
|
7
|
+
The closest relative is Inertia's `useForm`, but vue-apix works with any JSON API and also
|
|
8
|
+
covers "load → edit → submit" and "filters + pagination" flows.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm i @diephp/vue-apix
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Setup
|
|
15
|
+
|
|
16
|
+
Create your own configured instance (e.g. `src/api.ts`) and import it everywhere:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import apix from '@diephp/vue-apix';
|
|
20
|
+
|
|
21
|
+
apix.setBaseUrl('https://api.domain.com/v1'); // all request URLs then start with /
|
|
22
|
+
apix.setHeader({
|
|
23
|
+
'x-auth-token': () => localStorage.getItem('token'), // lazy: resolved on every request
|
|
24
|
+
'x-app': 'admin', // static
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
apix.onProcessing((active) => progressBar.toggle(active)); // any request in flight
|
|
28
|
+
apix.onError((error, ctx) => { // any failed request
|
|
29
|
+
if (error instanceof ApixError && error.status === 401) redirectToLogin();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// onError may RETURN an Error to replace the original one — the replacement goes
|
|
33
|
+
// to the next hooks, to model.errors/message and to the rejected promise.
|
|
34
|
+
// Handy for normalizing non-Laravel validation formats:
|
|
35
|
+
apix.onError((error) => {
|
|
36
|
+
if (error instanceof ApixError && error.status === 400 && error.body?.details) {
|
|
37
|
+
return new ApixError(422, { message: error.body.error_text, errors: error.body.details });
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Global body transformer: applied to EVERY parsed response body (success and
|
|
42
|
+
// error statuses) before it is used anywhere — ApixError.message/errors included.
|
|
43
|
+
// Return a new body, or mutate in place and return nothing.
|
|
44
|
+
apix.transformResponse((body) => {
|
|
45
|
+
if (body?.messages?.[0]?.message) body.message = body.messages[0].message;
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
export default apix;
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or create isolated instances: `const other = createApix({ baseUrl, headers, credentials: 'include' })`.
|
|
52
|
+
|
|
53
|
+
## Plain requests (Promise, no model)
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
apix.get('/users', { filters: { name: 'x' }, page: 2 }); // → /users?filters[name]=x&page=2
|
|
57
|
+
apix.post('/users', { name: 'a' });
|
|
58
|
+
apix.put('/users/1', { name: 'b' });
|
|
59
|
+
apix.patch('/users/1', { name: 'c' });
|
|
60
|
+
apix.delete('/users', { ids: [1, 2] }); // DELETE with a body is allowed
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Query params are serialized PHP-style (`filters[name]=x`), booleans become `1/0`,
|
|
64
|
+
`null`/`undefined` are skipped. Non-2xx responses reject with `ApixError`
|
|
65
|
+
(`status`, `body`, `errors`, `isValidationError`).
|
|
66
|
+
|
|
67
|
+
## Forms
|
|
68
|
+
|
|
69
|
+
### From scratch
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
const model = apix.form({ name: null, description: null });
|
|
73
|
+
model.name = 'tosic'; // magic prop ≡ model.data.name, fully reactive
|
|
74
|
+
model.post('/api/attribute').then(({ message }) => alert(message));
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Filled from the API
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
interface AttrDto { id: number | null; name: string | null; description: string | null }
|
|
81
|
+
|
|
82
|
+
// response: {data: {item: {...}}} → model.data = item
|
|
83
|
+
const model = apix.getForm<AttrDto>('/api/attribute/123', 'item');
|
|
84
|
+
|
|
85
|
+
// full options:
|
|
86
|
+
const model = apix.getForm<AttrDto>('/api/attribute/123', {
|
|
87
|
+
path: 'item', // dot-path inside body.data (or body if no data wrapper)
|
|
88
|
+
default: () => ({ id: null, name: null, description: null }), // used while loading
|
|
89
|
+
immediate: true, // default; false = wait for reload()/watch trigger
|
|
90
|
+
params: { with: 'labels' }, // extra query params for every fill request
|
|
91
|
+
onSuccess: (response, model) => {}, // every successful fill (initial, reload, watch)
|
|
92
|
+
onError: (error, model) => {},
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
While the request is in flight `model.processing === true` and `model.data` is
|
|
97
|
+
`default()` (or `null` without a default). `apix.postForm(url, options)` is the same,
|
|
98
|
+
but fills via POST (complex search endpoints).
|
|
99
|
+
|
|
100
|
+
### In a component
|
|
101
|
+
|
|
102
|
+
```vue
|
|
103
|
+
<script setup lang="ts">
|
|
104
|
+
const model = apix.getForm<AttrDto>('/api/attribute/1', { path: 'item', default: () => ({ name: null, description: null }) });
|
|
105
|
+
|
|
106
|
+
// NOTE: wrap in a function! `model.put(...)` directly in setup would fire immediately.
|
|
107
|
+
const submit = () => model.put('/api/attribute/1').then(({ message }) => alert(message));
|
|
108
|
+
</script>
|
|
109
|
+
|
|
110
|
+
<template>
|
|
111
|
+
<form v-loading="model.processing" @submit.prevent="submit">
|
|
112
|
+
<input v-model="model.name" />
|
|
113
|
+
<span v-if="model.errors.name">{{ model.errors.name }}</span>
|
|
114
|
+
|
|
115
|
+
<input v-model="model.data.description" />
|
|
116
|
+
<span v-if="model.error('description')">{{ model.error('description') }}</span>
|
|
117
|
+
|
|
118
|
+
<button type="submit" :disabled="model.processing">Save</button>
|
|
119
|
+
<button type="button" @click="model.reset()">Reset</button>
|
|
120
|
+
</form>
|
|
121
|
+
</template>
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Model API
|
|
125
|
+
|
|
126
|
+
| Member | Description |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `model.data` | `T \| null` — the payload (object or array; arrays: `model.data.map(...)`) |
|
|
129
|
+
| `model.<key>` | magic prop ≡ `model.data.<key>` (objects only, reserved names win — see below) |
|
|
130
|
+
| `model.processing` | reactive boolean, true while any model request is in flight |
|
|
131
|
+
| `model.message` | `message` from the last response (success or validation error) |
|
|
132
|
+
| `model.errors` | flat map, Laravel keys: `errors['name.en.label']` → first message string |
|
|
133
|
+
| `model.error(key)` | first error for key; falls back to `key.*` sub-errors (`error('name')` finds `name.en.label`) |
|
|
134
|
+
| `model.hasErrors` / `model.isDirty` | reactive booleans |
|
|
135
|
+
| `model.get(path)` | value by dot-path; objects come back as detached deep clones |
|
|
136
|
+
| `model.setData(data)` | replace data entirely (object or array) |
|
|
137
|
+
| `model.setErrors(errors)` / `model.clearErrors(keys?)` | manage errors manually |
|
|
138
|
+
| `model.reset(keys?)` | restore the snapshot: first server response, else `default()`; `reset(['name'])` for specific paths |
|
|
139
|
+
| `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
|
|
140
|
+
| `model.reload(url?)` | re-run the fill request |
|
|
141
|
+
| `model.watch(paths?, opts?)` / `model.unwatch()` | auto-refetch on change, see below |
|
|
142
|
+
|
|
143
|
+
Submitting clears previous errors; any **4xx** response carrying an `errors` object in the
|
|
144
|
+
body (Laravel's 422, or any backend using the same shape on 400-499) fills `model.errors`
|
|
145
|
+
and `model.message` and rejects the promise, so `catch` is still yours. 5xx bodies are never
|
|
146
|
+
treated as validation errors — only `model.message` is surfaced.
|
|
147
|
+
|
|
148
|
+
**Reserved names.** These model members always win over data keys:
|
|
149
|
+
`data, errors, message, processing, hasErrors, isDirty, get, error, setData, setErrors,
|
|
150
|
+
clearErrors, reset, post, put, patch, delete, reload, watch, unwatch, transformRequest,
|
|
151
|
+
transformResponse`. A data field with such a name is still there — via `model.data.<key>`.
|
|
152
|
+
|
|
153
|
+
## Model transformers — reshape server data
|
|
154
|
+
|
|
155
|
+
When the API shape is awkward (nested, legacy), unwrap it into a comfortable model
|
|
156
|
+
shape and wrap it back on submit:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
// server: {attr: {name: {value: 'x'}}} ↔ model: {name: 'x'}
|
|
160
|
+
const model = apix
|
|
161
|
+
.getForm<{ name: string | null }>('/api/attribute/1', 'item')
|
|
162
|
+
.transformResponse((data) => ({ name: data?.attr?.name?.value ?? null }))
|
|
163
|
+
.transformRequest((data) => ({ attr: { name: { value: data.name } } }));
|
|
164
|
+
|
|
165
|
+
model.name = 'edited';
|
|
166
|
+
model.put(); // body: {attr: {name: {value: 'edited'}}}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
- `transformResponse(data, response)` runs on every fill (initial, `reload()`, watch) after
|
|
170
|
+
`path` extraction and **before** the reactive data is touched — no false watch triggers.
|
|
171
|
+
The `reset()` snapshot stores the transformed shape.
|
|
172
|
+
- `transformRequest(data)` runs on the payload of `post/put/patch/delete` (skipped when you
|
|
173
|
+
pass an explicit `opts.data`) and on watch payloads. It receives a detached clone —
|
|
174
|
+
mutations never touch the model.
|
|
175
|
+
- Both are also accepted as `getForm`/`postForm`/`form` options.
|
|
176
|
+
|
|
177
|
+
## watch() — filters, pagination, live search
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
interface PageDto {
|
|
181
|
+
items: ItemDto[];
|
|
182
|
+
filters: { name: string | null };
|
|
183
|
+
paginator: { page: number; total: number; per_page: number };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const table = apix
|
|
187
|
+
.getForm<PageDto>('/api/fetch/data', {
|
|
188
|
+
default: () => ({ items: [], filters: { name: null }, paginator: { page: 1, total: 0, per_page: 15 } }),
|
|
189
|
+
})
|
|
190
|
+
.watch(['filters', 'paginator.page'], { debounce: 300 });
|
|
191
|
+
|
|
192
|
+
// template: v-model="table.filters.name", @click="table.paginator.page++" — the table refetches itself
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
How it behaves:
|
|
196
|
+
|
|
197
|
+
- **Only the watched paths are sent** — GET → PHP-style query (`filters[name]=x&paginator[page]=2`),
|
|
198
|
+
postForm → JSON body. Override with `payload: [...]`.
|
|
199
|
+
- **The response updates everything except the watched paths**, so a slow response never
|
|
200
|
+
clobbers what the user is typing. Opt out with `refreshWatched: true`.
|
|
201
|
+
- **A new trigger aborts the previous in-flight request** (AbortController) — the last change wins.
|
|
202
|
+
- **Debounce** (`debounce: 300`) collapses fast typing into one request.
|
|
203
|
+
- `reset()` restores the first-response snapshot; if that actually changes watched data,
|
|
204
|
+
the request is re-sent — reset filters, table refreshes.
|
|
205
|
+
- Watch server-owned fields precisely: `['filters', 'paginator.page']`, not `['paginator']` —
|
|
206
|
+
otherwise `paginator.total` from the response would be preserved away too.
|
|
207
|
+
- Created inside `setup()`, the watcher is bound to the component scope and stops on unmount.
|
|
208
|
+
Module-level models live until `model.unwatch()`.
|
|
209
|
+
|
|
210
|
+
## TypeScript
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
const model = apix.getForm<AttrDto>('/api/attribute/1', 'item');
|
|
214
|
+
model.name; // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
|
|
215
|
+
model.data?.description; // full escape hatch
|
|
216
|
+
|
|
217
|
+
const list = apix.getForm<ItemDto[]>('/api/attribute', 'items');
|
|
218
|
+
list.data?.map((item) => item.name); // arrays: no magic props, use .data
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## License
|
|
222
|
+
|
|
223
|
+
MIT
|
package/dist/apix.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { ApixConfig, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, Model, ProcessingHook, RequestOptions } from './types';
|
|
2
|
+
export declare class Apix {
|
|
3
|
+
private baseUrl;
|
|
4
|
+
private headers;
|
|
5
|
+
private credentials?;
|
|
6
|
+
private processingHooks;
|
|
7
|
+
private errorHooks;
|
|
8
|
+
private bodyTransformer;
|
|
9
|
+
private active;
|
|
10
|
+
constructor(config?: ApixConfig);
|
|
11
|
+
setBaseUrl(url: string): this;
|
|
12
|
+
setHeader(headers: Record<string, HeaderValue>): this;
|
|
13
|
+
setCredentials(credentials: RequestCredentials): this;
|
|
14
|
+
/** Global hook: fires with true when the first request starts, false when the last one ends. */
|
|
15
|
+
onProcessing(hook: ProcessingHook): () => void;
|
|
16
|
+
/**
|
|
17
|
+
* Global hook: fires on every failed request (aborted requests are ignored).
|
|
18
|
+
* A hook may RETURN an Error to replace the original one — the replacement
|
|
19
|
+
* goes to the next hooks, to model.errors/message and to the rejected promise.
|
|
20
|
+
*/
|
|
21
|
+
onError(hook: ErrorHook): () => void;
|
|
22
|
+
/**
|
|
23
|
+
* Global transformer for every parsed response body (success and error statuses),
|
|
24
|
+
* applied before the body is used anywhere — ApixError.message/errors included.
|
|
25
|
+
* Return the new body, or mutate in place and return nothing. Pass null to remove.
|
|
26
|
+
* Example: `apix.transformResponse((body) => ({ ...body, message: body.messages?.[0]?.message ?? body.message }))`
|
|
27
|
+
*/
|
|
28
|
+
transformResponse(transformer: BodyTransformer | null): this;
|
|
29
|
+
request<T = any>(method: HttpMethod, url: string, options?: RequestOptions): Promise<T>;
|
|
30
|
+
get<T = any>(url: string, params?: Record<string, unknown>, options?: RequestOptions): Promise<T>;
|
|
31
|
+
post<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
32
|
+
put<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
33
|
+
patch<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
34
|
+
/** DELETE with an optional body. */
|
|
35
|
+
delete<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
36
|
+
/** Create a form model without any request (like Inertia's useForm). */
|
|
37
|
+
form<T extends object>(defaults: T | (() => T), options?: Omit<FormOptions<T>, 'default'>): Model<T>;
|
|
38
|
+
/** Create a form model and fill it with a GET request. */
|
|
39
|
+
getForm<T = any>(url: string, pathOrOptions?: string | FormOptions<T>): Model<T>;
|
|
40
|
+
/** Same as getForm, but the fill request is a POST (complex search endpoints etc.). */
|
|
41
|
+
postForm<T = any>(url: string, pathOrOptions?: string | FormOptions<T>): Model<T>;
|
|
42
|
+
private createFormModel;
|
|
43
|
+
private trackStart;
|
|
44
|
+
private trackEnd;
|
|
45
|
+
private emitProcessing;
|
|
46
|
+
/** Runs the hooks; a hook returning an Error replaces it for the rest of the chain. */
|
|
47
|
+
private emitError;
|
|
48
|
+
}
|
|
49
|
+
export declare function createApix(config?: ApixConfig): Apix;
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export declare class ApixError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
/** Parsed response body (JSON object, text string or null). */
|
|
4
|
+
readonly body: any;
|
|
5
|
+
/**
|
|
6
|
+
* Raw validation errors: `{field: [messages]}` (or `{field: message}`).
|
|
7
|
+
* Empty object otherwise. `message` (inherited from Error) is `body.message` when present.
|
|
8
|
+
*/
|
|
9
|
+
readonly errors: Record<string, string[] | string>;
|
|
10
|
+
/** Absent when the error was constructed manually (e.g. inside an onError hook). */
|
|
11
|
+
readonly response?: Response;
|
|
12
|
+
constructor(status: number, body: any, response?: Response);
|
|
13
|
+
/**
|
|
14
|
+
* True for any 4xx response whose body carries an `errors` object
|
|
15
|
+
* (Laravel's 422 and any backend following the same shape on 400-499).
|
|
16
|
+
* 5xx responses never count — their bodies are not trusted as validation payloads.
|
|
17
|
+
*/
|
|
18
|
+
get isValidationError(): boolean;
|
|
19
|
+
}
|
|
20
|
+
export declare function isAbortError(error: unknown): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* PHP-style query string: `{filters: {name: 'x'}, page: 2}` → `filters[name]=x&page=2`.
|
|
23
|
+
* Arrays use indexes (`ids[0]=1`), booleans become 1/0 (Laravel `boolean` rule friendly),
|
|
24
|
+
* null/undefined values are skipped.
|
|
25
|
+
*/
|
|
26
|
+
export declare function buildQuery(params: Record<string, unknown>): string;
|
|
27
|
+
export declare function parseBody(response: Response): Promise<any>;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { Apix, createApix } from './apix';
|
|
2
|
+
export { ApixError } from './client';
|
|
3
|
+
export { ApixModel } from './model';
|
|
4
|
+
export type { ApixConfig, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, Model, ProcessingHook, RequestContext, RequestOptions, SubmitOptions, WatchOptions, } from './types';
|
|
5
|
+
/** Shared default instance — configure it once (e.g. in your api.ts) and import everywhere. */
|
|
6
|
+
export declare const apix: import('./apix').Apix;
|
|
7
|
+
export default apix;
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Apix } from './apix';
|
|
2
|
+
import { FillSource, FormOptions, Model, SubmitOptions, WatchOptions } from './types';
|
|
3
|
+
interface ModelState {
|
|
4
|
+
data: any;
|
|
5
|
+
errors: Record<string, string>;
|
|
6
|
+
message: string | null;
|
|
7
|
+
processing: boolean;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Reactive form model. Create via `apix.form()` / `apix.getForm()` / `apix.postForm()` —
|
|
11
|
+
* they wrap the instance in a Proxy so data keys are exposed directly
|
|
12
|
+
* (`model.name` ≡ `model.data.name`).
|
|
13
|
+
*
|
|
14
|
+
* Reserved members (always win over data keys, use `model.data.<key>` for those):
|
|
15
|
+
* data, errors, message, processing, hasErrors, isDirty,
|
|
16
|
+
* get, error, setData, setErrors, clearErrors, reset,
|
|
17
|
+
* post, put, patch, delete, reload, watch, unwatch,
|
|
18
|
+
* transformRequest, transformResponse.
|
|
19
|
+
*/
|
|
20
|
+
export declare class ApixModel<T = any> {
|
|
21
|
+
/** @internal */ _apix: Apix;
|
|
22
|
+
/** @internal */ _options: FormOptions<T>;
|
|
23
|
+
/** @internal */ _state: ModelState;
|
|
24
|
+
/** @internal */ _source: FillSource | null;
|
|
25
|
+
/** @internal */ _snapshot: any;
|
|
26
|
+
/** @internal */ _snapshotLocked: boolean;
|
|
27
|
+
/** @internal */ _proxy: Model<T>;
|
|
28
|
+
/** @internal */ _stopWatch: (() => void) | null;
|
|
29
|
+
/** @internal */ _debounceTimer: ReturnType<typeof setTimeout> | null;
|
|
30
|
+
/** @internal */ _watched: string[] | null;
|
|
31
|
+
/** @internal */ _watchOptions: WatchOptions;
|
|
32
|
+
/** @internal */ _lastSent: string | null;
|
|
33
|
+
/** @internal */ _fillAbort: AbortController | null;
|
|
34
|
+
/** @internal */ _transformResponse: ((data: any, response: any) => any) | null;
|
|
35
|
+
/** @internal */ _transformRequest: ((data: any) => any) | null;
|
|
36
|
+
constructor(apix: Apix, options?: FormOptions<T>, source?: FillSource | null);
|
|
37
|
+
get data(): T | null;
|
|
38
|
+
set data(value: T | null);
|
|
39
|
+
/** Flat error map, Laravel-style keys: `errors['name.en.label']` → first message. */
|
|
40
|
+
get errors(): Record<string, string>;
|
|
41
|
+
/** `message` from the last response (success or validation error). */
|
|
42
|
+
get message(): string | null;
|
|
43
|
+
get processing(): boolean;
|
|
44
|
+
get hasErrors(): boolean;
|
|
45
|
+
/** True when data differs from the reset() snapshot. */
|
|
46
|
+
get isDirty(): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Read one value by dot-path. Objects/arrays are returned as detached
|
|
49
|
+
* deep clones — mutating them never touches the model.
|
|
50
|
+
*/
|
|
51
|
+
get(path: string): any;
|
|
52
|
+
/** Replace data entirely (object or array). A detached clone is stored. */
|
|
53
|
+
setData(data: T): Model<T>;
|
|
54
|
+
/**
|
|
55
|
+
* First error for the key. Falls back to the first `key.*` sub-error,
|
|
56
|
+
* so `error('name')` also surfaces `name.en.label` messages.
|
|
57
|
+
*/
|
|
58
|
+
error(key: string): string | undefined;
|
|
59
|
+
setErrors(errors: Record<string, string | string[]>): Model<T>;
|
|
60
|
+
/** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
|
|
61
|
+
clearErrors(keys?: string[]): Model<T>;
|
|
62
|
+
/**
|
|
63
|
+
* Restore data to the snapshot: the first server response, or `default()`
|
|
64
|
+
* if nothing was loaded yet. Pass keys to reset only those dot-paths.
|
|
65
|
+
* An active watch() reacts to the change as usual (the request is re-sent).
|
|
66
|
+
*/
|
|
67
|
+
reset(keys?: string | string[]): Model<T>;
|
|
68
|
+
post(url?: string, options?: SubmitOptions): Promise<any>;
|
|
69
|
+
put(url?: string, options?: SubmitOptions): Promise<any>;
|
|
70
|
+
patch(url?: string, options?: SubmitOptions): Promise<any>;
|
|
71
|
+
delete(url?: string, options?: SubmitOptions): Promise<any>;
|
|
72
|
+
/** Re-run the fill request (or set a new source URL and run it). */
|
|
73
|
+
reload(url?: string): Promise<any>;
|
|
74
|
+
/**
|
|
75
|
+
* Map server data into the model shape. Runs on every fill (initial, reload,
|
|
76
|
+
* watch) AFTER path extraction and BEFORE the reactive data is touched — so it
|
|
77
|
+
* never causes a false watch trigger. The snapshot for reset() stores the
|
|
78
|
+
* transformed shape. Return the new data (or mutate in place and return nothing).
|
|
79
|
+
*/
|
|
80
|
+
transformResponse(transformer: ((data: any, response: any) => any) | null): Model<T>;
|
|
81
|
+
/**
|
|
82
|
+
* Map model data back into the server shape. Runs on the payload of
|
|
83
|
+
* post/put/patch/delete (unless an explicit `data` option is passed) and on
|
|
84
|
+
* watch payloads. Receives a detached clone — mutations never touch the model.
|
|
85
|
+
*/
|
|
86
|
+
transformRequest(transformer: ((data: any) => any) | null): Model<T>;
|
|
87
|
+
/**
|
|
88
|
+
* Re-send the fill request whenever data changes.
|
|
89
|
+
* `paths` limits both what is observed and what is sent
|
|
90
|
+
* (GET → PHP-style query params, POST → JSON body).
|
|
91
|
+
* The response updates everything except the watched paths (see WatchOptions).
|
|
92
|
+
* A new trigger aborts the previous in-flight watch request.
|
|
93
|
+
*/
|
|
94
|
+
watch(paths?: string[] | WatchOptions, options?: WatchOptions): Model<T>;
|
|
95
|
+
unwatch(): Model<T>;
|
|
96
|
+
/** @internal */
|
|
97
|
+
_fill(extra?: {
|
|
98
|
+
params?: Record<string, unknown>;
|
|
99
|
+
data?: unknown;
|
|
100
|
+
preserve?: string[] | null;
|
|
101
|
+
}): Promise<any>;
|
|
102
|
+
private _applyFill;
|
|
103
|
+
private _applyError;
|
|
104
|
+
private _submit;
|
|
105
|
+
private _onWatchTrigger;
|
|
106
|
+
private _sendWatchRequest;
|
|
107
|
+
private _payloadJson;
|
|
108
|
+
private _syncLastSent;
|
|
109
|
+
}
|
|
110
|
+
/** @internal Factory: wraps the model in the magic Proxy and fires the initial fill. */
|
|
111
|
+
export declare function createModel<T>(apix: Apix, options?: FormOptions<T>, source?: FillSource | null): Model<T>;
|
|
112
|
+
export {};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { ApixModel } from './model';
|
|
2
|
+
/** Header value: a plain string or a lazy callback resolved on every request. */
|
|
3
|
+
export type HeaderValue = string | null | undefined | (() => string | null | undefined);
|
|
4
|
+
export interface ApixConfig {
|
|
5
|
+
/** Base URL prepended to every relative request URL, e.g. `https://api.domain.com/v1`. */
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
/** Default headers. Values may be lazy callbacks resolved per request. */
|
|
8
|
+
headers?: Record<string, HeaderValue>;
|
|
9
|
+
/** Passed to fetch as-is, e.g. `'include'` for Laravel Sanctum cookies. */
|
|
10
|
+
credentials?: RequestCredentials;
|
|
11
|
+
}
|
|
12
|
+
export type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
|
|
13
|
+
export interface RequestOptions {
|
|
14
|
+
/** Query parameters, serialized PHP-style: `{filters: {name: 'x'}}` → `filters[name]=x`. */
|
|
15
|
+
params?: Record<string, unknown>;
|
|
16
|
+
/** Request body. Objects are sent as JSON, FormData is sent as-is. */
|
|
17
|
+
data?: unknown;
|
|
18
|
+
/** Extra headers for this request only. */
|
|
19
|
+
headers?: Record<string, string>;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
export interface RequestContext {
|
|
23
|
+
method: HttpMethod;
|
|
24
|
+
url: string;
|
|
25
|
+
options: RequestOptions;
|
|
26
|
+
}
|
|
27
|
+
export type ProcessingHook = (processing: boolean) => void;
|
|
28
|
+
/**
|
|
29
|
+
* Global error hook. Return an Error to REPLACE the original one — the
|
|
30
|
+
* replacement is passed to the next hooks, fills model.errors/message and
|
|
31
|
+
* rejects the promise. Return nothing to just observe.
|
|
32
|
+
* Exceptions thrown inside a hook are swallowed (a hook must never break requests).
|
|
33
|
+
*/
|
|
34
|
+
export type ErrorHook = (error: unknown, context: RequestContext) => Error | void;
|
|
35
|
+
/**
|
|
36
|
+
* Global response-body transformer. Receives every parsed body (success AND
|
|
37
|
+
* error statuses) before it is used anywhere — so ApixError.message/errors are
|
|
38
|
+
* built from the transformed body too. Return the new body, or mutate the
|
|
39
|
+
* given one in place and return nothing.
|
|
40
|
+
*/
|
|
41
|
+
export type BodyTransformer = (body: any, context: RequestContext) => any;
|
|
42
|
+
export interface FormOptions<T = any> {
|
|
43
|
+
/**
|
|
44
|
+
* Dot-path to the payload inside the response. Resolved against `body.data`
|
|
45
|
+
* when it exists, otherwise against the body itself.
|
|
46
|
+
* No path → `body.data ?? body`.
|
|
47
|
+
*/
|
|
48
|
+
path?: string;
|
|
49
|
+
/** Factory for the initial data used while the request is in flight (and as reset() fallback). */
|
|
50
|
+
default?: () => T;
|
|
51
|
+
/** Send the fill request immediately (default: true). */
|
|
52
|
+
immediate?: boolean;
|
|
53
|
+
/** Extra query params sent with every fill request (initial, reload, watch). */
|
|
54
|
+
params?: Record<string, unknown>;
|
|
55
|
+
/** Body for `postForm` fill requests. */
|
|
56
|
+
data?: unknown;
|
|
57
|
+
/** Called after every successful fill request (initial, reload(), watch-triggered). */
|
|
58
|
+
onSuccess?: (response: any, model: Model<T>) => void;
|
|
59
|
+
/** Called after every failed fill request. Aborted (superseded) requests are ignored. */
|
|
60
|
+
onError?: (error: unknown, model: Model<T>) => void;
|
|
61
|
+
/** See model.transformResponse(). */
|
|
62
|
+
transformResponse?: (data: any, response: any) => any;
|
|
63
|
+
/** See model.transformRequest(). */
|
|
64
|
+
transformRequest?: (data: any) => any;
|
|
65
|
+
}
|
|
66
|
+
export interface WatchOptions {
|
|
67
|
+
/** Deep-watch the observed paths (default: true). */
|
|
68
|
+
deep?: boolean;
|
|
69
|
+
/** Debounce in milliseconds before sending the request (default: 0). */
|
|
70
|
+
debounce?: number;
|
|
71
|
+
/**
|
|
72
|
+
* By default the response updates everything EXCEPT the watched paths,
|
|
73
|
+
* so user input is never clobbered by a stale response.
|
|
74
|
+
* Set true to let the response overwrite watched paths too.
|
|
75
|
+
*/
|
|
76
|
+
refreshWatched?: boolean;
|
|
77
|
+
/** Dot-paths of `data` to send instead of the watched paths. */
|
|
78
|
+
payload?: string[];
|
|
79
|
+
}
|
|
80
|
+
export interface SubmitOptions {
|
|
81
|
+
/** Explicit body; overrides model data. */
|
|
82
|
+
data?: unknown;
|
|
83
|
+
/** Send only these dot-paths of model data. */
|
|
84
|
+
only?: string[];
|
|
85
|
+
params?: Record<string, unknown>;
|
|
86
|
+
headers?: Record<string, string>;
|
|
87
|
+
}
|
|
88
|
+
/** @internal Where a form model loads its data from. */
|
|
89
|
+
export interface FillSource {
|
|
90
|
+
url: string;
|
|
91
|
+
method: 'get' | 'post';
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Magic data properties: every key of T is exposed directly on the model
|
|
95
|
+
* (`model.name` ≡ `model.data.name`) unless it collides with a reserved
|
|
96
|
+
* model member — those stay reachable via `model.data.<key>`.
|
|
97
|
+
* Arrays get no magic props — iterate `model.data` directly.
|
|
98
|
+
*/
|
|
99
|
+
export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof ApixModel> : {};
|
|
100
|
+
export type Model<T = any> = ApixModel<T> & MagicData<T>;
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deep clone that unwraps Vue reactive proxies on every level.
|
|
3
|
+
* Plain objects, arrays and Dates are cloned; anything else
|
|
4
|
+
* (File, Blob, class instances) is kept by reference.
|
|
5
|
+
*/
|
|
6
|
+
export declare function deepClone<T>(value: T): T;
|
|
7
|
+
export declare function pathGet(target: any, path: string): any;
|
|
8
|
+
export declare function pathSet(target: any, path: string, value: any): void;
|
|
9
|
+
/** Build a plain object holding deep clones of the given dot-paths. */
|
|
10
|
+
export declare function pick(source: any, paths: string[]): any;
|
|
11
|
+
/** Laravel sends `{field: [messages]}`; keep the first message per field. */
|
|
12
|
+
export declare function flattenErrors(errors: Record<string, unknown>): Record<string, string>;
|
|
13
|
+
export declare function extractMessage(body: unknown): string | null;
|
|
14
|
+
/**
|
|
15
|
+
* Pull the payload out of a response body.
|
|
16
|
+
* Root is `body.data` when present (Laravel resources), otherwise the body itself;
|
|
17
|
+
* `path` is a dot-path inside that root.
|
|
18
|
+
*/
|
|
19
|
+
export declare function extractData(body: any, path?: string): any;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("vue");function c(o){const t=p.toRaw(o);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function f(o,t){if(o==null)return;let e=o;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(o,t,e){const s=t.split(".");let r=o;for(let i=0;i<s.length-1;i++){const a=s[i];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function b(o,t){const e={};for(const s of t){const r=f(o,s);r!==void 0&&m(e,s,c(r))}return e}function w(o){const t={};for(const[e,s]of Object.entries(o??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function d(o){return o&&typeof o=="object"&&typeof o.message=="string"?o.message:null}function q(o,t){const e=o&&typeof o=="object"&&!Array.isArray(o)&&"data"in o?o.data:o;return t?f(e,t):e}class y extends Error{constructor(t,e,s){super(d(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function A(o){return o instanceof Error&&o.name==="AbortError"}function S(o){const t=[],e=(r,i)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`)},s=(r,i)=>{if(r!=null){if(typeof r=="boolean")return e(i,r?"1":"0");if(r instanceof Date)return e(i,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${i}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${i}[${a}]`);return}e(i,String(r))}};for(const[r,i]of Object.entries(o))s(i,r);return t.join("&")}async function O(o){if(o.status===204)return null;const t=await o.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class j{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._stopWatch=null,this._debounceTimer=null,this._watched=null,this._watchOptions={},this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;this._state=p.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r)}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=w(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)m(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}watch(t,e){let s=null,r;Array.isArray(t)?(s=t,r=e??{}):r=t??e??{},this._source||console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."),this.unwatch(),this._watched=s,this._watchOptions=r,this._syncLastSent();const i=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=p.watch(i,()=>this._onWatchTrigger(),{deep:r.deep??!0}),this._proxy}unwatch(){var t;return(t=this._stopWatch)==null||t.call(this),this._stopWatch=null,this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._proxy}async _fill(t={}){var i,a,n,h,l;const e=this._source;(i=this._fillAbort)==null||i.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const u=await this._apix.request(e.method,e.url,r);let _=q(u,this._options.path);if(this._transformResponse){const g=c(_);_=this._transformResponse(g,u)??g}return this._applyFill(_,t.preserve??null),this._state.message=d(u),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,u,this._proxy),u}catch(u){throw A(u)||(this._applyError(u),(l=(h=this._options).onError)==null||l.call(h,u,this._proxy)),u}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){const s=c(t);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const r of e){const i=f(this._state.data,r);i!==void 0&&m(s,r,c(i))}this._state.data=s,this._snapshotLocked||(this._snapshot=c(t),this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=d(t.body)??t.message,t.isValidationError&&(this._state.errors=w(t.errors)))}async _submit(t,e,s={}){var a;const r=e??((a=this._source)==null?void 0:a.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let i=s.data!==void 0?s.data:s.only?b(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&i!==void 0){const n=c(i);i=this._transformRequest(n)??n}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const n=await this._apix.request(t,r,{data:i,params:s.params,headers:s.headers});return this._state.message=d(n),n}catch(n){throw this._applyError(n),n}finally{this._state.processing=!1}}_onWatchTrigger(){if(this._payloadJson()===this._lastSent)return;this._debounceTimer&&clearTimeout(this._debounceTimer);const t=this._watchOptions.debounce??0;t>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),t):this._sendWatchRequest()}_sendWatchRequest(){if(this._debounceTimer=null,!this._source)return;const t=this._watched,e=this._watchOptions.payload??t;let s=e&&e.length?b(this._state.data,e):c(this._state.data);this._transformRequest&&(s=this._transformRequest(s)??s),this._lastSent=this._payloadJson();const r=this._watchOptions.refreshWatched?null:t,i=this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r};this._fill(i).catch(()=>{})}_payloadJson(){const t=this._watched,e=t&&t.length?t.map(s=>f(this._state.data,s)):this._state.data;return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function x(o,t={},e=null){const s=new j(o,t,e),r=new Proxy(s,{get(i,a){if(typeof a=="symbol"||a in i)return Reflect.get(i,a);const n=i._state.data;if(n&&typeof n=="object")return n[a]},set(i,a,n){if(typeof a=="symbol"||a in i)return Reflect.set(i,a,n);const h=i._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(i._state.data={[a]:n},!0)},has(i,a){if(a in i)return!0;const n=i._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class R{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=S(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const i={Accept:"application/json","X-Requested-With":"XMLHttpRequest"};for(const[h,l]of Object.entries(this.headers)){const u=typeof l=="function"?l():l;u!=null&&(i[h]=u)}Object.assign(i,s.headers);const a={method:t.toUpperCase(),headers:i,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?a.body=s.data:(i["Content-Type"]="application/json",a.body=JSON.stringify(s.data)));const n={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,a);let l=await O(h);if(this.bodyTransformer&&(l=this.bodyTransformer(l,n)??l),!h.ok)throw new y(h.status,l,h);return l}catch(h){throw A(h)?h:this.emitError(h,n)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return x(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return x(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const i=r(s,e);i instanceof Error&&(s=i)}catch{}return s}}function v(o={}){return new R(o)}const E=v();exports.Apix=R;exports.ApixError=y;exports.ApixModel=j;exports.apix=E;exports.createApix=v;exports.default=E;
|
package/dist/vue-apix.js
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { toRaw as R, reactive as j, watch as A } from "vue";
|
|
2
|
+
function c(o) {
|
|
3
|
+
const t = R(o);
|
|
4
|
+
if (t === null || typeof t != "object") return t;
|
|
5
|
+
if (Array.isArray(t)) return t.map((e) => c(e));
|
|
6
|
+
if (t instanceof Date) return new Date(t.getTime());
|
|
7
|
+
const s = Object.getPrototypeOf(t);
|
|
8
|
+
if (s === Object.prototype || s === null) {
|
|
9
|
+
const e = {};
|
|
10
|
+
for (const r of Object.keys(t)) e[r] = c(t[r]);
|
|
11
|
+
return e;
|
|
12
|
+
}
|
|
13
|
+
return t;
|
|
14
|
+
}
|
|
15
|
+
function f(o, t) {
|
|
16
|
+
if (o == null) return;
|
|
17
|
+
let s = o;
|
|
18
|
+
for (const e of t.split(".")) {
|
|
19
|
+
if (s == null) return;
|
|
20
|
+
s = s[e];
|
|
21
|
+
}
|
|
22
|
+
return s;
|
|
23
|
+
}
|
|
24
|
+
function p(o, t, s) {
|
|
25
|
+
const e = t.split(".");
|
|
26
|
+
let r = o;
|
|
27
|
+
for (let i = 0; i < e.length - 1; i++) {
|
|
28
|
+
const a = e[i];
|
|
29
|
+
(r[a] === null || typeof r[a] != "object") && (r[a] = {}), r = r[a];
|
|
30
|
+
}
|
|
31
|
+
r[e[e.length - 1]] = s;
|
|
32
|
+
}
|
|
33
|
+
function y(o, t) {
|
|
34
|
+
const s = {};
|
|
35
|
+
for (const e of t) {
|
|
36
|
+
const r = f(o, e);
|
|
37
|
+
r !== void 0 && p(s, e, c(r));
|
|
38
|
+
}
|
|
39
|
+
return s;
|
|
40
|
+
}
|
|
41
|
+
function g(o) {
|
|
42
|
+
const t = {};
|
|
43
|
+
for (const [s, e] of Object.entries(o ?? {}))
|
|
44
|
+
e != null && (t[s] = Array.isArray(e) ? String(e[0]) : String(e));
|
|
45
|
+
return t;
|
|
46
|
+
}
|
|
47
|
+
function d(o) {
|
|
48
|
+
return o && typeof o == "object" && typeof o.message == "string" ? o.message : null;
|
|
49
|
+
}
|
|
50
|
+
function E(o, t) {
|
|
51
|
+
const s = o && typeof o == "object" && !Array.isArray(o) && "data" in o ? o.data : o;
|
|
52
|
+
return t ? f(s, t) : s;
|
|
53
|
+
}
|
|
54
|
+
class w extends Error {
|
|
55
|
+
constructor(t, s, e) {
|
|
56
|
+
super(d(s) ?? `Request failed with status ${t}`), this.name = "ApixError", this.status = t, this.body = s, this.response = e, this.errors = s && typeof s == "object" && s.errors && typeof s.errors == "object" ? s.errors : {};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* True for any 4xx response whose body carries an `errors` object
|
|
60
|
+
* (Laravel's 422 and any backend following the same shape on 400-499).
|
|
61
|
+
* 5xx responses never count — their bodies are not trusted as validation payloads.
|
|
62
|
+
*/
|
|
63
|
+
get isValidationError() {
|
|
64
|
+
return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function x(o) {
|
|
68
|
+
return o instanceof Error && o.name === "AbortError";
|
|
69
|
+
}
|
|
70
|
+
function q(o) {
|
|
71
|
+
const t = [], s = (r, i) => {
|
|
72
|
+
t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);
|
|
73
|
+
}, e = (r, i) => {
|
|
74
|
+
if (r != null) {
|
|
75
|
+
if (typeof r == "boolean") return s(i, r ? "1" : "0");
|
|
76
|
+
if (r instanceof Date) return s(i, r.toISOString());
|
|
77
|
+
if (Array.isArray(r)) {
|
|
78
|
+
r.forEach((a, n) => e(a, `${i}[${n}]`));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (typeof r == "object") {
|
|
82
|
+
for (const [a, n] of Object.entries(r)) e(n, `${i}[${a}]`);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
s(i, String(r));
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
for (const [r, i] of Object.entries(o)) e(i, r);
|
|
89
|
+
return t.join("&");
|
|
90
|
+
}
|
|
91
|
+
async function v(o) {
|
|
92
|
+
if (o.status === 204) return null;
|
|
93
|
+
const t = await o.text();
|
|
94
|
+
if (!t) return null;
|
|
95
|
+
try {
|
|
96
|
+
return JSON.parse(t);
|
|
97
|
+
} catch {
|
|
98
|
+
return t;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
class O {
|
|
102
|
+
constructor(t, s = {}, e = null) {
|
|
103
|
+
this._snapshot = null, this._snapshotLocked = !1, this._stopWatch = null, this._debounceTimer = null, this._watched = null, this._watchOptions = {}, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = s, this._source = e, this._transformResponse = s.transformResponse ?? null, this._transformRequest = s.transformRequest ?? null;
|
|
104
|
+
const r = s.default ? s.default() : null;
|
|
105
|
+
this._state = j({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
|
|
106
|
+
}
|
|
107
|
+
// --- reactive state ---------------------------------------------------------
|
|
108
|
+
get data() {
|
|
109
|
+
return this._state.data;
|
|
110
|
+
}
|
|
111
|
+
set data(t) {
|
|
112
|
+
this._state.data = t;
|
|
113
|
+
}
|
|
114
|
+
/** Flat error map, Laravel-style keys: `errors['name.en.label']` → first message. */
|
|
115
|
+
get errors() {
|
|
116
|
+
return this._state.errors;
|
|
117
|
+
}
|
|
118
|
+
/** `message` from the last response (success or validation error). */
|
|
119
|
+
get message() {
|
|
120
|
+
return this._state.message;
|
|
121
|
+
}
|
|
122
|
+
get processing() {
|
|
123
|
+
return this._state.processing;
|
|
124
|
+
}
|
|
125
|
+
get hasErrors() {
|
|
126
|
+
return Object.keys(this._state.errors).length > 0;
|
|
127
|
+
}
|
|
128
|
+
/** True when data differs from the reset() snapshot. */
|
|
129
|
+
get isDirty() {
|
|
130
|
+
return JSON.stringify(this._state.data) !== JSON.stringify(this._snapshot);
|
|
131
|
+
}
|
|
132
|
+
// --- data access --------------------------------------------------------------
|
|
133
|
+
/**
|
|
134
|
+
* Read one value by dot-path. Objects/arrays are returned as detached
|
|
135
|
+
* deep clones — mutating them never touches the model.
|
|
136
|
+
*/
|
|
137
|
+
get(t) {
|
|
138
|
+
return c(f(this._state.data, t));
|
|
139
|
+
}
|
|
140
|
+
/** Replace data entirely (object or array). A detached clone is stored. */
|
|
141
|
+
setData(t) {
|
|
142
|
+
return this._state.data = c(t), this._proxy;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* First error for the key. Falls back to the first `key.*` sub-error,
|
|
146
|
+
* so `error('name')` also surfaces `name.en.label` messages.
|
|
147
|
+
*/
|
|
148
|
+
error(t) {
|
|
149
|
+
const s = this._state.errors;
|
|
150
|
+
if (s[t] !== void 0) return s[t];
|
|
151
|
+
const e = `${t}.`;
|
|
152
|
+
for (const r of Object.keys(s))
|
|
153
|
+
if (r.startsWith(e)) return s[r];
|
|
154
|
+
}
|
|
155
|
+
setErrors(t) {
|
|
156
|
+
return this._state.errors = g(t), this._proxy;
|
|
157
|
+
}
|
|
158
|
+
/** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
|
|
159
|
+
clearErrors(t) {
|
|
160
|
+
if (!t)
|
|
161
|
+
return this._state.errors = {}, this._proxy;
|
|
162
|
+
for (const s of t) {
|
|
163
|
+
const e = `${s}.`;
|
|
164
|
+
for (const r of Object.keys(this._state.errors))
|
|
165
|
+
(r === s || r.startsWith(e)) && delete this._state.errors[r];
|
|
166
|
+
}
|
|
167
|
+
return this._proxy;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Restore data to the snapshot: the first server response, or `default()`
|
|
171
|
+
* if nothing was loaded yet. Pass keys to reset only those dot-paths.
|
|
172
|
+
* An active watch() reacts to the change as usual (the request is re-sent).
|
|
173
|
+
*/
|
|
174
|
+
reset(t) {
|
|
175
|
+
if (t === void 0 || Array.isArray(t) && t.length === 0)
|
|
176
|
+
return this._state.data = c(this._snapshot), this._state.errors = {}, this._state.message = null, this._proxy;
|
|
177
|
+
const s = Array.isArray(t) ? t : [t];
|
|
178
|
+
if (this._state.data && typeof this._state.data == "object")
|
|
179
|
+
for (const e of s)
|
|
180
|
+
p(this._state.data, e, c(f(this._snapshot, e)));
|
|
181
|
+
return this.clearErrors(s), this._proxy;
|
|
182
|
+
}
|
|
183
|
+
// --- HTTP ------------------------------------------------------------------------
|
|
184
|
+
post(t, s) {
|
|
185
|
+
return this._submit("post", t, s);
|
|
186
|
+
}
|
|
187
|
+
put(t, s) {
|
|
188
|
+
return this._submit("put", t, s);
|
|
189
|
+
}
|
|
190
|
+
patch(t, s) {
|
|
191
|
+
return this._submit("patch", t, s);
|
|
192
|
+
}
|
|
193
|
+
delete(t, s) {
|
|
194
|
+
return this._submit("delete", t, s);
|
|
195
|
+
}
|
|
196
|
+
/** Re-run the fill request (or set a new source URL and run it). */
|
|
197
|
+
reload(t) {
|
|
198
|
+
var s;
|
|
199
|
+
return t && (this._source = { url: t, method: ((s = this._source) == null ? void 0 : s.method) ?? "get" }), this._source ? this._fill() : Promise.reject(
|
|
200
|
+
new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
// --- transformers -------------------------------------------------------------------
|
|
204
|
+
/**
|
|
205
|
+
* Map server data into the model shape. Runs on every fill (initial, reload,
|
|
206
|
+
* watch) AFTER path extraction and BEFORE the reactive data is touched — so it
|
|
207
|
+
* never causes a false watch trigger. The snapshot for reset() stores the
|
|
208
|
+
* transformed shape. Return the new data (or mutate in place and return nothing).
|
|
209
|
+
*/
|
|
210
|
+
transformResponse(t) {
|
|
211
|
+
return this._transformResponse = t, this._proxy;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Map model data back into the server shape. Runs on the payload of
|
|
215
|
+
* post/put/patch/delete (unless an explicit `data` option is passed) and on
|
|
216
|
+
* watch payloads. Receives a detached clone — mutations never touch the model.
|
|
217
|
+
*/
|
|
218
|
+
transformRequest(t) {
|
|
219
|
+
return this._transformRequest = t, this._proxy;
|
|
220
|
+
}
|
|
221
|
+
// --- watch ------------------------------------------------------------------------
|
|
222
|
+
/**
|
|
223
|
+
* Re-send the fill request whenever data changes.
|
|
224
|
+
* `paths` limits both what is observed and what is sent
|
|
225
|
+
* (GET → PHP-style query params, POST → JSON body).
|
|
226
|
+
* The response updates everything except the watched paths (see WatchOptions).
|
|
227
|
+
* A new trigger aborts the previous in-flight watch request.
|
|
228
|
+
*/
|
|
229
|
+
watch(t, s) {
|
|
230
|
+
let e = null, r;
|
|
231
|
+
Array.isArray(t) ? (e = t, r = s ?? {}) : r = t ?? s ?? {}, this._source || console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."), this.unwatch(), this._watched = e, this._watchOptions = r, this._syncLastSent();
|
|
232
|
+
const i = e && e.length ? e.map((a) => () => f(this._state.data, a)) : () => this._state.data;
|
|
233
|
+
return this._stopWatch = A(i, () => this._onWatchTrigger(), {
|
|
234
|
+
deep: r.deep ?? !0
|
|
235
|
+
}), this._proxy;
|
|
236
|
+
}
|
|
237
|
+
unwatch() {
|
|
238
|
+
var t;
|
|
239
|
+
return (t = this._stopWatch) == null || t.call(this), this._stopWatch = null, this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null), this._proxy;
|
|
240
|
+
}
|
|
241
|
+
// --- internals ----------------------------------------------------------------------
|
|
242
|
+
/** @internal */
|
|
243
|
+
async _fill(t = {}) {
|
|
244
|
+
var i, a, n, h, l;
|
|
245
|
+
const s = this._source;
|
|
246
|
+
(i = this._fillAbort) == null || i.abort();
|
|
247
|
+
const e = new AbortController();
|
|
248
|
+
this._fillAbort = e, this._state.processing = !0;
|
|
249
|
+
const r = { signal: e.signal };
|
|
250
|
+
s.method === "get" ? r.params = { ...this._options.params, ...t.params } : (r.params = this._options.params, r.data = t.data !== void 0 ? t.data : this._options.data);
|
|
251
|
+
try {
|
|
252
|
+
const u = await this._apix.request(s.method, s.url, r);
|
|
253
|
+
let _ = E(u, this._options.path);
|
|
254
|
+
if (this._transformResponse) {
|
|
255
|
+
const m = c(_);
|
|
256
|
+
_ = this._transformResponse(m, u) ?? m;
|
|
257
|
+
}
|
|
258
|
+
return this._applyFill(_, t.preserve ?? null), this._state.message = d(u), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, u, this._proxy), u;
|
|
259
|
+
} catch (u) {
|
|
260
|
+
throw x(u) || (this._applyError(u), (l = (h = this._options).onError) == null || l.call(h, u, this._proxy)), u;
|
|
261
|
+
} finally {
|
|
262
|
+
this._fillAbort === e && (this._fillAbort = null, this._state.processing = !1);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
_applyFill(t, s) {
|
|
266
|
+
const e = c(t);
|
|
267
|
+
if (s && s.length && e && typeof e == "object" && this._state.data && typeof this._state.data == "object")
|
|
268
|
+
for (const r of s) {
|
|
269
|
+
const i = f(this._state.data, r);
|
|
270
|
+
i !== void 0 && p(e, r, c(i));
|
|
271
|
+
}
|
|
272
|
+
this._state.data = e, this._snapshotLocked || (this._snapshot = c(t), this._snapshotLocked = !0), this._syncLastSent();
|
|
273
|
+
}
|
|
274
|
+
_applyError(t) {
|
|
275
|
+
t instanceof w && (this._state.message = d(t.body) ?? t.message, t.isValidationError && (this._state.errors = g(t.errors)));
|
|
276
|
+
}
|
|
277
|
+
async _submit(t, s, e = {}) {
|
|
278
|
+
var a;
|
|
279
|
+
const r = s ?? ((a = this._source) == null ? void 0 : a.url);
|
|
280
|
+
if (!r)
|
|
281
|
+
throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
|
|
282
|
+
let i = e.data !== void 0 ? e.data : e.only ? y(this._state.data, e.only) : this._state.data ?? void 0;
|
|
283
|
+
if (e.data === void 0 && this._transformRequest && i !== void 0) {
|
|
284
|
+
const n = c(i);
|
|
285
|
+
i = this._transformRequest(n) ?? n;
|
|
286
|
+
}
|
|
287
|
+
this._state.processing = !0, this._state.errors = {}, this._state.message = null;
|
|
288
|
+
try {
|
|
289
|
+
const n = await this._apix.request(t, r, {
|
|
290
|
+
data: i,
|
|
291
|
+
params: e.params,
|
|
292
|
+
headers: e.headers
|
|
293
|
+
});
|
|
294
|
+
return this._state.message = d(n), n;
|
|
295
|
+
} catch (n) {
|
|
296
|
+
throw this._applyError(n), n;
|
|
297
|
+
} finally {
|
|
298
|
+
this._state.processing = !1;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
_onWatchTrigger() {
|
|
302
|
+
if (this._payloadJson() === this._lastSent) return;
|
|
303
|
+
this._debounceTimer && clearTimeout(this._debounceTimer);
|
|
304
|
+
const t = this._watchOptions.debounce ?? 0;
|
|
305
|
+
t > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), t) : this._sendWatchRequest();
|
|
306
|
+
}
|
|
307
|
+
_sendWatchRequest() {
|
|
308
|
+
if (this._debounceTimer = null, !this._source) return;
|
|
309
|
+
const t = this._watched, s = this._watchOptions.payload ?? t;
|
|
310
|
+
let e = s && s.length ? y(this._state.data, s) : c(this._state.data);
|
|
311
|
+
this._transformRequest && (e = this._transformRequest(e) ?? e), this._lastSent = this._payloadJson();
|
|
312
|
+
const r = this._watchOptions.refreshWatched ? null : t, i = this._source.method === "get" ? { params: e, preserve: r } : { data: e, preserve: r };
|
|
313
|
+
this._fill(i).catch(() => {
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
_payloadJson() {
|
|
317
|
+
const t = this._watched, s = t && t.length ? t.map((e) => f(this._state.data, e)) : this._state.data;
|
|
318
|
+
return JSON.stringify(s) ?? "undefined";
|
|
319
|
+
}
|
|
320
|
+
_syncLastSent() {
|
|
321
|
+
this._lastSent = this._payloadJson();
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function b(o, t = {}, s = null) {
|
|
325
|
+
const e = new O(o, t, s), r = new Proxy(e, {
|
|
326
|
+
get(i, a) {
|
|
327
|
+
if (typeof a == "symbol" || a in i) return Reflect.get(i, a);
|
|
328
|
+
const n = i._state.data;
|
|
329
|
+
if (n && typeof n == "object") return n[a];
|
|
330
|
+
},
|
|
331
|
+
set(i, a, n) {
|
|
332
|
+
if (typeof a == "symbol" || a in i) return Reflect.set(i, a, n);
|
|
333
|
+
const h = i._state.data;
|
|
334
|
+
return h && typeof h == "object" ? (h[a] = n, !0) : (i._state.data = { [a]: n }, !0);
|
|
335
|
+
},
|
|
336
|
+
has(i, a) {
|
|
337
|
+
if (a in i) return !0;
|
|
338
|
+
const n = i._state.data;
|
|
339
|
+
return !!n && typeof n == "object" && a in n;
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
return e._proxy = r, s && t.immediate !== !1 && r.reload().catch(() => {
|
|
343
|
+
}), r;
|
|
344
|
+
}
|
|
345
|
+
class S {
|
|
346
|
+
constructor(t = {}) {
|
|
347
|
+
this.baseUrl = "", this.headers = {}, this.processingHooks = [], this.errorHooks = [], this.bodyTransformer = null, this.active = 0, t.baseUrl && this.setBaseUrl(t.baseUrl), t.headers && this.setHeader(t.headers), t.credentials && (this.credentials = t.credentials);
|
|
348
|
+
}
|
|
349
|
+
// --- configuration -------------------------------------------------------
|
|
350
|
+
setBaseUrl(t) {
|
|
351
|
+
return this.baseUrl = t.replace(/\/+$/, ""), this;
|
|
352
|
+
}
|
|
353
|
+
setHeader(t) {
|
|
354
|
+
return Object.assign(this.headers, t), this;
|
|
355
|
+
}
|
|
356
|
+
setCredentials(t) {
|
|
357
|
+
return this.credentials = t, this;
|
|
358
|
+
}
|
|
359
|
+
/** Global hook: fires with true when the first request starts, false when the last one ends. */
|
|
360
|
+
onProcessing(t) {
|
|
361
|
+
return this.processingHooks.push(t), () => {
|
|
362
|
+
this.processingHooks = this.processingHooks.filter((s) => s !== t);
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Global hook: fires on every failed request (aborted requests are ignored).
|
|
367
|
+
* A hook may RETURN an Error to replace the original one — the replacement
|
|
368
|
+
* goes to the next hooks, to model.errors/message and to the rejected promise.
|
|
369
|
+
*/
|
|
370
|
+
onError(t) {
|
|
371
|
+
return this.errorHooks.push(t), () => {
|
|
372
|
+
this.errorHooks = this.errorHooks.filter((s) => s !== t);
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Global transformer for every parsed response body (success and error statuses),
|
|
377
|
+
* applied before the body is used anywhere — ApixError.message/errors included.
|
|
378
|
+
* Return the new body, or mutate in place and return nothing. Pass null to remove.
|
|
379
|
+
* Example: `apix.transformResponse((body) => ({ ...body, message: body.messages?.[0]?.message ?? body.message }))`
|
|
380
|
+
*/
|
|
381
|
+
transformResponse(t) {
|
|
382
|
+
return this.bodyTransformer = t, this;
|
|
383
|
+
}
|
|
384
|
+
// --- plain requests (Promise, no model) -----------------------------------
|
|
385
|
+
async request(t, s, e = {}) {
|
|
386
|
+
let r = /^https?:\/\//i.test(s) ? s : this.baseUrl + s;
|
|
387
|
+
if (e.params) {
|
|
388
|
+
const h = q(e.params);
|
|
389
|
+
h && (r += (r.includes("?") ? "&" : "?") + h);
|
|
390
|
+
}
|
|
391
|
+
const i = {
|
|
392
|
+
Accept: "application/json",
|
|
393
|
+
"X-Requested-With": "XMLHttpRequest"
|
|
394
|
+
};
|
|
395
|
+
for (const [h, l] of Object.entries(this.headers)) {
|
|
396
|
+
const u = typeof l == "function" ? l() : l;
|
|
397
|
+
u != null && (i[h] = u);
|
|
398
|
+
}
|
|
399
|
+
Object.assign(i, e.headers);
|
|
400
|
+
const a = { method: t.toUpperCase(), headers: i, signal: e.signal };
|
|
401
|
+
this.credentials && (a.credentials = this.credentials), e.data !== void 0 && t !== "get" && (typeof FormData < "u" && e.data instanceof FormData ? a.body = e.data : (i["Content-Type"] = "application/json", a.body = JSON.stringify(e.data)));
|
|
402
|
+
const n = { method: t, url: r, options: e };
|
|
403
|
+
this.trackStart();
|
|
404
|
+
try {
|
|
405
|
+
const h = await fetch(r, a);
|
|
406
|
+
let l = await v(h);
|
|
407
|
+
if (this.bodyTransformer && (l = this.bodyTransformer(l, n) ?? l), !h.ok) throw new w(h.status, l, h);
|
|
408
|
+
return l;
|
|
409
|
+
} catch (h) {
|
|
410
|
+
throw x(h) ? h : this.emitError(h, n);
|
|
411
|
+
} finally {
|
|
412
|
+
this.trackEnd();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
get(t, s, e = {}) {
|
|
416
|
+
return this.request("get", t, s ? { ...e, params: s } : e);
|
|
417
|
+
}
|
|
418
|
+
post(t, s, e = {}) {
|
|
419
|
+
return this.request("post", t, s !== void 0 ? { ...e, data: s } : e);
|
|
420
|
+
}
|
|
421
|
+
put(t, s, e = {}) {
|
|
422
|
+
return this.request("put", t, s !== void 0 ? { ...e, data: s } : e);
|
|
423
|
+
}
|
|
424
|
+
patch(t, s, e = {}) {
|
|
425
|
+
return this.request("patch", t, s !== void 0 ? { ...e, data: s } : e);
|
|
426
|
+
}
|
|
427
|
+
/** DELETE with an optional body. */
|
|
428
|
+
delete(t, s, e = {}) {
|
|
429
|
+
return this.request("delete", t, s !== void 0 ? { ...e, data: s } : e);
|
|
430
|
+
}
|
|
431
|
+
// --- form models -----------------------------------------------------------
|
|
432
|
+
/** Create a form model without any request (like Inertia's useForm). */
|
|
433
|
+
form(t, s = {}) {
|
|
434
|
+
return b(this, { ...s, default: typeof t == "function" ? t : () => c(t) });
|
|
435
|
+
}
|
|
436
|
+
/** Create a form model and fill it with a GET request. */
|
|
437
|
+
getForm(t, s) {
|
|
438
|
+
return this.createFormModel("get", t, s);
|
|
439
|
+
}
|
|
440
|
+
/** Same as getForm, but the fill request is a POST (complex search endpoints etc.). */
|
|
441
|
+
postForm(t, s) {
|
|
442
|
+
return this.createFormModel("post", t, s);
|
|
443
|
+
}
|
|
444
|
+
createFormModel(t, s, e) {
|
|
445
|
+
const r = typeof e == "string" ? { path: e } : { ...e ?? {} };
|
|
446
|
+
return b(this, r, { url: s, method: t });
|
|
447
|
+
}
|
|
448
|
+
// --- internals --------------------------------------------------------------
|
|
449
|
+
trackStart() {
|
|
450
|
+
++this.active === 1 && this.emitProcessing(!0);
|
|
451
|
+
}
|
|
452
|
+
trackEnd() {
|
|
453
|
+
--this.active === 0 && this.emitProcessing(!1);
|
|
454
|
+
}
|
|
455
|
+
emitProcessing(t) {
|
|
456
|
+
for (const s of this.processingHooks)
|
|
457
|
+
try {
|
|
458
|
+
s(t);
|
|
459
|
+
} catch {
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
/** Runs the hooks; a hook returning an Error replaces it for the rest of the chain. */
|
|
463
|
+
emitError(t, s) {
|
|
464
|
+
let e = t;
|
|
465
|
+
for (const r of this.errorHooks)
|
|
466
|
+
try {
|
|
467
|
+
const i = r(e, s);
|
|
468
|
+
i instanceof Error && (e = i);
|
|
469
|
+
} catch {
|
|
470
|
+
}
|
|
471
|
+
return e;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
function T(o = {}) {
|
|
475
|
+
return new S(o);
|
|
476
|
+
}
|
|
477
|
+
const U = T();
|
|
478
|
+
export {
|
|
479
|
+
S as Apix,
|
|
480
|
+
w as ApixError,
|
|
481
|
+
O as ApixModel,
|
|
482
|
+
U as apix,
|
|
483
|
+
T as createApix,
|
|
484
|
+
U as default
|
|
485
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@diephp/vue-apix",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Tiny form/model/api toolkit for Vue 3 — fetch-based, Laravel-friendly, zero dependencies",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "diephp",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"vue",
|
|
10
|
+
"vue3",
|
|
11
|
+
"form",
|
|
12
|
+
"api",
|
|
13
|
+
"model",
|
|
14
|
+
"fetch",
|
|
15
|
+
"laravel",
|
|
16
|
+
"useForm"
|
|
17
|
+
],
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"main": "./dist/vue-apix.cjs",
|
|
22
|
+
"module": "./dist/vue-apix.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/vue-apix.js",
|
|
28
|
+
"require": "./dist/vue-apix.cjs"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"dev": "vite playground --open",
|
|
40
|
+
"build": "vite build",
|
|
41
|
+
"test": "vitest run",
|
|
42
|
+
"test:watch": "vitest",
|
|
43
|
+
"typecheck": "tsc --noEmit",
|
|
44
|
+
"prepublishOnly": "npm run typecheck && npm run test && npm run build"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"vue": "^3.3.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@vitejs/plugin-vue": "^6.0.8",
|
|
51
|
+
"prettier": "^3.3.1",
|
|
52
|
+
"typescript": "^5.2.2",
|
|
53
|
+
"vite": "^5.2.0",
|
|
54
|
+
"vite-plugin-dts": "^5.0.3",
|
|
55
|
+
"vitest": "^3.2.7",
|
|
56
|
+
"vue": "^3.5.40"
|
|
57
|
+
}
|
|
58
|
+
}
|