@diephp/vue-apix 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -114,15 +114,17 @@ interface AttrDto {
114
114
  }
115
115
 
116
116
  // response: {data: {item: {...}}} → model.data = item
117
- const model = apix.getForm<AttrDto>('/api/attribute/123', 'item');
117
+ const model = apix.getForm<AttrDto>('/api/attribute/123', 'data.item');
118
118
  ```
119
119
 
120
120
  Full options:
121
121
 
122
122
  ```ts
123
123
  const model = apix.getForm<AttrDto>('/api/attribute/123', {
124
- // dot-path inside body.data (or inside body when there is no data wrapper)
125
- path: 'item',
124
+ // dot-path against the RAW response body — there is no implicit body.data
125
+ // unwrapping, include `data` yourself when the API wraps its payload
126
+ // (see "Laravel pagination" below)
127
+ path: 'data.item',
126
128
  // used while the request is in flight, and as the reset() fallback
127
129
  default: () => ({ id: null, name: null, description: null }),
128
130
  // default is true; false = no request until reload() or a watch trigger
@@ -164,6 +166,38 @@ default has an object falls back to the default object, explicit scalar `null`s
164
166
  response are respected, and arrays are always replaced — never merged. The `reset()`
165
167
  snapshot stores the merged state. Opt out with `mergeDefaults: false`.
166
168
 
169
+ ### Laravel pagination — `data` + `links` + `meta`
170
+
171
+ There is no implicit `body.data` unwrapping — `path` is always a dot-path against the
172
+ **raw** response body, and without a `path` the whole body is used as-is. This matters for
173
+ a Laravel paginated collection, which wraps an **array** in `data` with `links`/`meta` as
174
+ siblings:
175
+
176
+ ```json
177
+ { "data": [{ "id": 1 }, { "id": 2 }], "links": { "next": "/?page=2" }, "meta": { "total": 42 } }
178
+ ```
179
+
180
+ Since nothing is auto-unwrapped, `links`/`meta` are never at risk of being silently dropped —
181
+ you decide exactly how much of the body ends up in `model.data`:
182
+
183
+ ```ts
184
+ interface PageDto {
185
+ data: Array<{ id: number; name: string }>;
186
+ links: { next: string | null };
187
+ meta: { current_page: number; total: number };
188
+ }
189
+
190
+ // no `path` at all — model.data becomes the whole body
191
+ const table = apix.getForm<PageDto>('/api/attribute');
192
+
193
+ table.data.data; // the items array
194
+ table.data.meta.total; // pagination meta, fully reachable
195
+ ```
196
+
197
+ If you don't need `links`/`meta` and just want the items array as `model.data`, ask for it
198
+ explicitly: `path: 'data'`. And for the common single-resource convention `{data: {...}}}`,
199
+ include `data` in the path too: `path: 'data.item'` reads `body.data.item`.
200
+
167
201
  ### Edit form — full component
168
202
 
169
203
  ```vue
@@ -177,7 +211,7 @@ interface AttrDto {
177
211
  }
178
212
 
179
213
  const model = apix.getForm<AttrDto>('/api/attribute/1', {
180
- path: 'item',
214
+ path: 'data.item',
181
215
  default: () => ({ id: null, name: null, description: null }),
182
216
  });
183
217
 
@@ -228,7 +262,8 @@ const submit = () =>
228
262
  | `model.setErrors(errors)` / `model.clearErrors(keys?)` | manage errors manually |
229
263
  | `model.reset(keys?)` | restore the snapshot: first server response, else `default()`; `reset(['name'])` for specific paths |
230
264
  | `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
231
- | `model.reload(url?)` | re-run the fill request |
265
+ | `model.reload(url?)` | re-run the fill request as configured (fresh load — ignores watch payload) |
266
+ | `model.refresh()` | re-send the fill request with the CURRENT state — a manual watch trigger for a "Search" button |
232
267
  | `model.watch(paths?, opts?)` / `model.unwatch()` | auto-refetch on change, see below |
233
268
  | `model.transformResponse(fn)` / `model.transformRequest(fn)` | reshape server data ↔ model data, see below |
234
269
 
@@ -239,8 +274,42 @@ treated as validation errors — only `model.message` is surfaced.
239
274
 
240
275
  **Reserved names.** These model members always win over data keys:
241
276
  `data, errors, message, processing, hasErrors, isDirty, get, error, setData, setErrors,
242
- clearErrors, reset, post, put, patch, delete, reload, watch, unwatch, transformRequest,
243
- transformResponse`. A data field with such a name is still there — via `model.data.<key>`.
277
+ clearErrors, reset, post, put, patch, delete, reload, refresh, watch, unwatch,
278
+ transformRequest, transformResponse`. A data field with such a name is still there —
279
+ via `model.data.<key>`.
280
+
281
+ ## Passing a model to a child component
282
+
283
+ A model is a plain object reference — hand it to a child and every mutation stays shared
284
+ and reactive. Two equivalent ways:
285
+
286
+ ```ts
287
+ // ChildForm.vue — via defineModel (parent: <ChildForm v-model="model" />)
288
+ import type { ApixModel } from '@diephp/vue-apix';
289
+
290
+ // type it through the macro GENERIC — not a cast on the left side,
291
+ // otherwise .value loses the model members (errors, processing, data…)
292
+ const form = defineModel<ApixModel<AttrDto>>({ required: true });
293
+ ```
294
+
295
+ ```ts
296
+ // ChildForm.vue — via a plain prop (parent: <ChildForm :form="model" />)
297
+ import type { ApixModel } from '@diephp/vue-apix';
298
+
299
+ const props = defineProps<{ form: ApixModel<AttrDto> }>();
300
+ ```
301
+
302
+ ```html
303
+ <!-- child template is identical either way -->
304
+ <el-form-item label="Name" :error="form.errors.name">
305
+ <el-input v-model="form.name" clearable />
306
+ </el-form-item>
307
+ ```
308
+
309
+ One rule with `defineModel`: never REPLACE the model from the child
310
+ (`form.value = ...`) — mutate it instead (`form.value.setData(...)`, `form.value.reset()`).
311
+ The child mutates the same model instance the parent owns, so a separate `:errors` prop
312
+ is unnecessary — `form.errors` is already reactive inside the child.
244
313
 
245
314
  ## watch() — filters, pagination, live search
246
315
 
@@ -265,6 +334,9 @@ interface PageDto {
265
334
 
266
335
  const table = apix
267
336
  .getForm<PageDto>('/api/attribute', {
337
+ // the API wraps its payload in `data` (see the JSON below) — spell it out,
338
+ // there is no implicit body.data unwrapping
339
+ path: 'data',
268
340
  default: () => ({
269
341
  items: [],
270
342
  filters: { name: null, status: null },
@@ -335,6 +407,9 @@ How `watch()` behaves:
335
407
  - **Debounce** (`debounce: 300`) collapses fast typing into one request.
336
408
  - `reset()` restores the first-response snapshot; if that actually changes watched data,
337
409
  the request is re-sent — reset filters, the table refreshes itself.
410
+ - **A "Search" button is `model.refresh()`** — it re-sends the request with the current
411
+ watched values (and cancels a pending debounce). `model.reload()` is different: it
412
+ re-runs the ORIGINAL fill request without the watch payload, i.e. it resets the view.
338
413
  - **Watch server-owned fields precisely**: `['filters', 'paginator.page']`, not
339
414
  `['paginator']` — a watched path is preserved from responses, so watching the whole
340
415
  `paginator` would freeze `paginator.total` at its first value.
@@ -392,9 +467,9 @@ When the API shape is awkward (nested, legacy), unwrap it into a comfortable mod
392
467
  shape and wrap it back on submit:
393
468
 
394
469
  ```ts
395
- // server shape: {attr: {name: {value: 'x'}}} ↔ model shape: {name: 'x'}
470
+ // response: {data: {item: {attr: {name: {value: 'x'}}}}} ↔ model shape: {name: 'x'}
396
471
  const model = apix
397
- .getForm<{ name: string | null }>('/api/attribute/1', 'item')
472
+ .getForm<{ name: string | null }>('/api/attribute/1', 'data.item')
398
473
  .transformResponse((data) => ({ name: data?.attr?.name?.value ?? null }))
399
474
  .transformRequest((data) => ({ attr: { name: { value: data.name } } }));
400
475
 
@@ -415,15 +490,15 @@ model.put();
415
490
  ## TypeScript
416
491
 
417
492
  ```ts
418
- const model = apix.getForm<AttrDto>('/api/attribute/1', 'item');
493
+ const model = apix.getForm<AttrDto>('/api/attribute/1', 'data.item');
419
494
 
420
- // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
495
+ // typed via magic props: ApixModel<AttrDto> = ApixFormModel<AttrDto> & AttrDto
421
496
  model.name;
422
497
 
423
498
  // full escape hatch
424
499
  model.data?.description;
425
500
 
426
- const list = apix.getForm<ItemDto[]>('/api/attribute', 'items');
501
+ const list = apix.getForm<ItemDto[]>('/api/attribute', 'data.items');
427
502
 
428
503
  // arrays: no magic props, iterate .data directly
429
504
  list.data?.map((item) => item.name);
package/dist/apix.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApixConfig, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, Model, ProcessingHook, RequestOptions } from './types';
1
+ import { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, ProcessingHook, RequestOptions } from './types';
2
2
  export declare class Apix {
3
3
  private baseUrl;
4
4
  private headers;
@@ -34,11 +34,11 @@ export declare class Apix {
34
34
  /** DELETE with an optional body. */
35
35
  delete<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
36
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>;
37
+ form<T extends object>(defaults: T | (() => T), options?: Omit<FormOptions<T>, 'default'>): ApixModel<T>;
38
38
  /** Create a form model and fill it with a GET request. */
39
- getForm<T = any>(url: string, pathOrOptions?: string | FormOptions<T>): Model<T>;
39
+ getForm<T = any>(url: string, options?: string | FormOptions<T>): ApixModel<T>;
40
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>;
41
+ postForm<T = any>(url: string, options?: string | FormOptions<T>): ApixModel<T>;
42
42
  private createFormModel;
43
43
  private trackStart;
44
44
  private trackEnd;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  export { Apix, createApix } from './apix';
2
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';
3
+ /** The underlying model class (advanced use, e.g. `instanceof` checks). Prefer the `ApixModel<T>` type for annotations. */
4
+ export { ApixFormModel } from './model';
5
+ export type { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, ProcessingHook, RequestContext, RequestOptions, SubmitOptions, WatchOptions, } from './types';
5
6
  /** Shared default instance — configure it once (e.g. in your api.ts) and import everywhere. */
6
7
  export declare const apix: import('./apix').Apix;
7
8
  export default apix;
package/dist/model.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Apix } from './apix';
2
- import { FillSource, FormOptions, Model, SubmitOptions, WatchOptions } from './types';
2
+ import { ApixModel, FillSource, FormOptions, SubmitOptions, WatchOptions } from './types';
3
3
  interface ModelState {
4
4
  data: any;
5
5
  errors: Record<string, string>;
@@ -14,17 +14,17 @@ interface ModelState {
14
14
  * Reserved members (always win over data keys, use `model.data.<key>` for those):
15
15
  * data, errors, message, processing, hasErrors, isDirty,
16
16
  * get, error, setData, setErrors, clearErrors, reset,
17
- * post, put, patch, delete, reload, watch, unwatch,
17
+ * post, put, patch, delete, reload, refresh, watch, unwatch,
18
18
  * transformRequest, transformResponse.
19
19
  */
20
- export declare class ApixModel<T = any> {
20
+ export declare class ApixFormModel<T = any> {
21
21
  /** @internal */ _apix: Apix;
22
22
  /** @internal */ _options: FormOptions<T>;
23
23
  /** @internal */ _state: ModelState;
24
24
  /** @internal */ _source: FillSource | null;
25
25
  /** @internal */ _snapshot: any;
26
26
  /** @internal */ _snapshotLocked: boolean;
27
- /** @internal */ _proxy: Model<T>;
27
+ /** @internal */ _proxy: ApixModel<T>;
28
28
  /** @internal */ _stopWatch: (() => void) | null;
29
29
  /** @internal */ _debounceTimer: ReturnType<typeof setTimeout> | null;
30
30
  /** @internal */ _watched: string[] | null;
@@ -50,40 +50,47 @@ export declare class ApixModel<T = any> {
50
50
  */
51
51
  get(path: string): any;
52
52
  /** Replace data entirely (object or array). A detached clone is stored. */
53
- setData(data: T): Model<T>;
53
+ setData(data: T): ApixModel<T>;
54
54
  /**
55
55
  * First error for the key. Falls back to the first `key.*` sub-error,
56
56
  * so `error('name')` also surfaces `name.en.label` messages.
57
57
  */
58
58
  error(key: string): string | undefined;
59
- setErrors(errors: Record<string, string | string[]>): Model<T>;
59
+ setErrors(errors: Record<string, string | string[]>): ApixModel<T>;
60
60
  /** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
61
- clearErrors(keys?: string[]): Model<T>;
61
+ clearErrors(keys?: string[]): ApixModel<T>;
62
62
  /**
63
63
  * Restore data to the snapshot: the first server response, or `default()`
64
64
  * if nothing was loaded yet. Pass keys to reset only those dot-paths.
65
65
  * An active watch() reacts to the change as usual (the request is re-sent).
66
66
  */
67
- reset(keys?: string | string[]): Model<T>;
67
+ reset(keys?: string | string[]): ApixModel<T>;
68
68
  post(url?: string, options?: SubmitOptions): Promise<any>;
69
69
  put(url?: string, options?: SubmitOptions): Promise<any>;
70
70
  patch(url?: string, options?: SubmitOptions): Promise<any>;
71
71
  delete(url?: string, options?: SubmitOptions): Promise<any>;
72
72
  /** Re-run the fill request (or set a new source URL and run it). */
73
73
  reload(url?: string): Promise<any>;
74
+ /**
75
+ * Re-send the fill request with the CURRENT state — a manual watch trigger
76
+ * (a "Search" button next to filters). Sends the watched paths as payload and
77
+ * preserves them in the response, exactly like a watch-triggered request; any
78
+ * pending debounce is cancelled. Without an active watch() it equals reload().
79
+ */
80
+ refresh(): Promise<any>;
74
81
  /**
75
82
  * Map server data into the model shape. Runs on every fill (initial, reload,
76
83
  * watch) AFTER path extraction and BEFORE the reactive data is touched — so it
77
84
  * never causes a false watch trigger. The snapshot for reset() stores the
78
85
  * transformed shape. Return the new data (or mutate in place and return nothing).
79
86
  */
80
- transformResponse(transformer: ((data: any, response: any) => any) | null): Model<T>;
87
+ transformResponse(transformer: ((data: any, response: any) => any) | null): ApixModel<T>;
81
88
  /**
82
89
  * Map model data back into the server shape. Runs on the payload of
83
90
  * post/put/patch/delete (unless an explicit `data` option is passed) and on
84
91
  * watch payloads. Receives a detached clone — mutations never touch the model.
85
92
  */
86
- transformRequest(transformer: ((data: any) => any) | null): Model<T>;
93
+ transformRequest(transformer: ((data: any) => any) | null): ApixModel<T>;
87
94
  /**
88
95
  * Re-send the fill request whenever data changes.
89
96
  * `paths` limits both what is observed and what is sent
@@ -91,8 +98,8 @@ export declare class ApixModel<T = any> {
91
98
  * The response updates everything except the watched paths (see WatchOptions).
92
99
  * A new trigger aborts the previous in-flight watch request.
93
100
  */
94
- watch(paths?: string[] | WatchOptions, options?: WatchOptions): Model<T>;
95
- unwatch(): Model<T>;
101
+ watch(paths?: string[] | WatchOptions, options?: WatchOptions): ApixModel<T>;
102
+ unwatch(): ApixModel<T>;
96
103
  /** @internal */
97
104
  _fill(extra?: {
98
105
  params?: Record<string, unknown>;
@@ -104,9 +111,11 @@ export declare class ApixModel<T = any> {
104
111
  private _submit;
105
112
  private _onWatchTrigger;
106
113
  private _sendWatchRequest;
114
+ /** Build the fill() extra for a watch-shaped request from the current state. */
115
+ private _watchExtra;
107
116
  private _payloadJson;
108
117
  private _syncLastSent;
109
118
  }
110
119
  /** @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>;
120
+ export declare function createModel<T>(apix: Apix, options?: FormOptions<T>, source?: FillSource | null): ApixModel<T>;
112
121
  export {};
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ApixModel } from './model';
1
+ import { ApixFormModel } from './model';
2
2
  /** Header value: a plain string or a lazy callback resolved on every request. */
3
3
  export type HeaderValue = string | null | undefined | (() => string | null | undefined);
4
4
  export interface ApixConfig {
@@ -41,9 +41,12 @@ export type ErrorHook = (error: unknown, context: RequestContext) => Error | voi
41
41
  export type BodyTransformer = (body: any, context: RequestContext) => any;
42
42
  export interface FormOptions<T = any> {
43
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`.
44
+ * Dot-path to the payload, resolved against the RAW response body — there is
45
+ * no implicit `body.data` unwrapping. Include `data` yourself when the API
46
+ * wraps its payload: `path: 'data.item'` for `{data: {item: {...}}}`,
47
+ * `path: 'data'` for a paginated collection. No path → the whole body, so a
48
+ * Laravel paginator's `links`/`meta` (`{data: [...], links, meta}`) are
49
+ * always reachable, e.g. via `model.data.meta`.
47
50
  */
48
51
  path?: string;
49
52
  /** Factory for the initial data used while the request is in flight (and as reset() fallback). */
@@ -63,9 +66,9 @@ export interface FormOptions<T = any> {
63
66
  /** Body for `postForm` fill requests. */
64
67
  data?: unknown;
65
68
  /** Called after every successful fill request (initial, reload(), watch-triggered). */
66
- onSuccess?: (response: any, model: Model<T>) => void;
69
+ onSuccess?: (response: any, model: ApixModel<T>) => void;
67
70
  /** Called after every failed fill request. Aborted (superseded) requests are ignored. */
68
- onError?: (error: unknown, model: Model<T>) => void;
71
+ onError?: (error: unknown, model: ApixModel<T>) => void;
69
72
  /** See model.transformResponse(). */
70
73
  transformResponse?: (data: any, response: any) => any;
71
74
  /** See model.transformRequest(). */
@@ -104,5 +107,6 @@ export interface FillSource {
104
107
  * model member — those stay reachable via `model.data.<key>`.
105
108
  * Arrays get no magic props — iterate `model.data` directly.
106
109
  */
107
- export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof ApixModel> : {};
108
- export type Model<T = any> = ApixModel<T> & MagicData<T>;
110
+ export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof ApixFormModel> : {};
111
+ /** Public type of a vue-apix model: `apix.form()` / `apix.getForm()` / `apix.postForm()` all return this. */
112
+ export type ApixModel<T = any> = ApixFormModel<T> & MagicData<T>;
package/dist/utils.d.ts CHANGED
@@ -24,7 +24,11 @@ export declare function flattenErrors(errors: Record<string, unknown>): Record<s
24
24
  export declare function extractMessage(body: unknown): string | null;
25
25
  /**
26
26
  * Pull the payload out of a response body.
27
- * Root is `body.data` when present (Laravel resources), otherwise the body itself;
28
- * `path` is a dot-path inside that root.
27
+ *
28
+ * There is no implicit `body.data` unwrapping — `path` is a dot-path against
29
+ * the RAW body, and you include `data` in it yourself when the API wraps its
30
+ * payload: `path: 'data.item'` for `{data: {item: {...}}}`, `path: 'data'` for
31
+ * a paginated collection. Without a `path`, the whole body is returned as-is,
32
+ * so a Laravel paginator's `links`/`meta` are never silently dropped.
29
33
  */
30
34
  export declare function extractData(body: any, path?: string): any;
package/dist/vue-apix.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const _=require("vue");function c(i){const t=_.toRaw(i);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 b(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function A(i,t){if(!b(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!b(i))return i;for(const e of Object.keys(t))i[e]=e in i?A(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function y(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const a=s[o];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function w(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&y(e,s,c(r))}return e}function x(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function p(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function S(i,t){const e=i&&typeof i=="object"&&!Array.isArray(i)&&"data"in i?i.data:i;return t?f(e,t):e}class m extends Error{constructor(t,e,s){super(p(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 R(i){return i instanceof Error&&i.name==="AbortError"}function k(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${o}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${o}[${a}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function T(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class v{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=_.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=x(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)y(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 o=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=_.watch(o,()=>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 o,a,n,h,u;const e=this._source;(o=this._fillAbort)==null||o.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 l=await this._apix.request(e.method,e.url,r);let d=S(l,this._options.path);if(this._transformResponse){const g=c(d);d=this._transformResponse(g,l)??g}return this._applyFill(d,t.preserve??null),this._state.message=p(l),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,l,this._proxy),l}catch(l){throw R(l)||(this._applyError(l),(u=(h=this._options).onError)==null||u.call(h,l,this._proxy)),l}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=A(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&y(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof m&&(this._state.message=p(t.body)??t.message,t.isValidationError&&(this._state.errors=x(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 o=s.data!==void 0?s.data:s.only?w(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const n=c(o);o=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:o,params:s.params,headers:s.headers});return this._state.message=p(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?w(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,o=this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r};this._fill(o).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 j(i,t={},e=null){const s=new v(i,t,e),r=new Proxy(s,{get(o,a){if(typeof a=="symbol"||a in o)return Reflect.get(o,a);const n=o._state.data;if(n&&typeof n=="object")return n[a]},set(o,a,n){if(typeof a=="symbol"||a in o)return Reflect.set(o,a,n);const h=o._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(o._state.data={[a]:n},!0)},has(o,a){if(a in o)return!0;const n=o._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class E{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=k(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,u]of Object.entries(this.headers)){const l=typeof u=="function"?u():u;l!=null&&(o[h.toLowerCase()]=l)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const a={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],a.body=s.data):(o["content-type"]??(o["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 u=await T(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,n)??u),!h.ok)throw new m(h.status,u,h);return u}catch(h){throw R(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 j(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 j(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 o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function O(i={}){return new E(i)}const q=O();exports.Apix=E;exports.ApixError=m;exports.ApixModel=v;exports.apix=q;exports.createApix=O;exports.default=q;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("vue");function c(i){const t=d.toRaw(i);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 g(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function O(i,t){if(!g(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!g(i))return i;for(const e of Object.keys(t))i[e]=e in i?O(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const a=s[o];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function w(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&m(e,s,c(r))}return e}function x(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function T(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class y extends Error{constructor(t,e,s){super(_(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 E(i){return i instanceof Error&&i.name==="AbortError"}function S(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${o}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${o}[${a}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function k(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class R{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=d.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=x(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)."))}refresh(){return this._source?this._stopWatch?(this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._lastSent=this._payloadJson(),this._fill(this._watchExtra())):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 o=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=d.watch(o,()=>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 o,a,n,h,u;const e=this._source;(o=this._fillAbort)==null||o.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 l=await this._apix.request(e.method,e.url,r);let p=T(l,this._options.path);if(this._transformResponse){const b=c(p);p=this._transformResponse(b,l)??b}return this._applyFill(p,t.preserve??null),this._state.message=_(l),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,l,this._proxy),l}catch(l){throw E(l)||(this._applyError(l),(u=(h=this._options).onError)==null||u.call(h,l,this._proxy)),l}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=O(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&m(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=_(t.body)??t.message,t.isValidationError&&(this._state.errors=x(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 o=s.data!==void 0?s.data:s.only?w(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const n=c(o);o=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:o,params:s.params,headers:s.headers});return this._state.message=_(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(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._watchExtra()).catch(()=>{}))}_watchExtra(){const t=this._watched,e=this._watchOptions.payload??t;let s=e&&e.length?w(this._state.data,e):c(this._state.data);this._transformRequest&&(s=this._transformRequest(s)??s);const r=this._watchOptions.refreshWatched?null:t;return this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r}}_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 j(i,t={},e=null){const s=new R(i,t,e),r=new Proxy(s,{get(o,a){if(typeof a=="symbol"||a in o)return Reflect.get(o,a);const n=o._state.data;if(n&&typeof n=="object")return n[a]},set(o,a,n){if(typeof a=="symbol"||a in o)return Reflect.set(o,a,n);const h=o._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(o._state.data={[a]:n},!0)},has(o,a){if(a in o)return!0;const n=o._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class v{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 o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,u]of Object.entries(this.headers)){const l=typeof u=="function"?u():u;l!=null&&(o[h.toLowerCase()]=l)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const a={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],a.body=s.data):(o["content-type"]??(o["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 u=await k(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,n)??u),!h.ok)throw new y(h.status,u,h);return u}catch(h){throw E(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 j(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 j(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 o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function A(i={}){return new v(i)}const q=A();exports.Apix=v;exports.ApixError=y;exports.ApixFormModel=R;exports.apix=q;exports.createApix=A;exports.default=q;
package/dist/vue-apix.js CHANGED
@@ -1,6 +1,6 @@
1
- import { toRaw as A, reactive as v, watch as E } from "vue";
2
- function c(o) {
3
- const t = A(o);
1
+ import { toRaw as R, reactive as E, watch as v } from "vue";
2
+ function c(i) {
3
+ const t = R(i);
4
4
  if (t === null || typeof t != "object") return t;
5
5
  if (Array.isArray(t)) return t.map((s) => c(s));
6
6
  if (t instanceof Date) return new Date(t.getTime());
@@ -12,62 +12,61 @@ function c(o) {
12
12
  }
13
13
  return t;
14
14
  }
15
- function y(o) {
16
- if (o === null || typeof o != "object") return !1;
17
- const t = Object.getPrototypeOf(o);
15
+ function y(i) {
16
+ if (i === null || typeof i != "object") return !1;
17
+ const t = Object.getPrototypeOf(i);
18
18
  return t === Object.prototype || t === null;
19
19
  }
20
- function x(o, t) {
20
+ function x(i, t) {
21
21
  if (!y(t))
22
- return o === void 0 ? c(t) : o;
23
- if (o == null) return c(t);
24
- if (!y(o)) return o;
22
+ return i === void 0 ? c(t) : i;
23
+ if (i == null) return c(t);
24
+ if (!y(i)) return i;
25
25
  for (const e of Object.keys(t))
26
- o[e] = e in o ? x(o[e], t[e]) : c(t[e]);
27
- return o;
26
+ i[e] = e in i ? x(i[e], t[e]) : c(t[e]);
27
+ return i;
28
28
  }
29
- function f(o, t) {
30
- if (o == null) return;
31
- let e = o;
29
+ function f(i, t) {
30
+ if (i == null) return;
31
+ let e = i;
32
32
  for (const s of t.split(".")) {
33
33
  if (e == null) return;
34
34
  e = e[s];
35
35
  }
36
36
  return e;
37
37
  }
38
- function d(o, t, e) {
38
+ function d(i, t, e) {
39
39
  const s = t.split(".");
40
- let r = o;
41
- for (let i = 0; i < s.length - 1; i++) {
42
- const a = s[i];
40
+ let r = i;
41
+ for (let o = 0; o < s.length - 1; o++) {
42
+ const a = s[o];
43
43
  (r[a] === null || typeof r[a] != "object") && (r[a] = {}), r = r[a];
44
44
  }
45
45
  r[s[s.length - 1]] = e;
46
46
  }
47
- function g(o, t) {
47
+ function b(i, t) {
48
48
  const e = {};
49
49
  for (const s of t) {
50
- const r = f(o, s);
50
+ const r = f(i, s);
51
51
  r !== void 0 && d(e, s, c(r));
52
52
  }
53
53
  return e;
54
54
  }
55
- function b(o) {
55
+ function g(i) {
56
56
  const t = {};
57
- for (const [e, s] of Object.entries(o ?? {}))
57
+ for (const [e, s] of Object.entries(i ?? {}))
58
58
  s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
59
59
  return t;
60
60
  }
61
- function p(o) {
62
- return o && typeof o == "object" && typeof o.message == "string" ? o.message : null;
61
+ function _(i) {
62
+ return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
63
63
  }
64
- function O(o, t) {
65
- const e = o && typeof o == "object" && !Array.isArray(o) && "data" in o ? o.data : o;
66
- return t ? f(e, t) : e;
64
+ function q(i, t) {
65
+ return t && i && typeof i == "object" ? f(i, t) : i;
67
66
  }
68
67
  class j extends Error {
69
68
  constructor(t, e, s) {
70
- super(p(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 : {};
69
+ super(_(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 : {};
71
70
  }
72
71
  /**
73
72
  * True for any 4xx response whose body carries an `errors` object
@@ -78,33 +77,33 @@ class j extends Error {
78
77
  return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
79
78
  }
80
79
  }
81
- function R(o) {
82
- return o instanceof Error && o.name === "AbortError";
80
+ function O(i) {
81
+ return i instanceof Error && i.name === "AbortError";
83
82
  }
84
- function q(o) {
85
- const t = [], e = (r, i) => {
86
- t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);
87
- }, s = (r, i) => {
83
+ function A(i) {
84
+ const t = [], e = (r, o) => {
85
+ t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`);
86
+ }, s = (r, o) => {
88
87
  if (r != null) {
89
- if (typeof r == "boolean") return e(i, r ? "1" : "0");
90
- if (r instanceof Date) return e(i, r.toISOString());
88
+ if (typeof r == "boolean") return e(o, r ? "1" : "0");
89
+ if (r instanceof Date) return e(o, r.toISOString());
91
90
  if (Array.isArray(r)) {
92
- r.forEach((a, n) => s(a, `${i}[${n}]`));
91
+ r.forEach((a, n) => s(a, `${o}[${n}]`));
93
92
  return;
94
93
  }
95
94
  if (typeof r == "object") {
96
- for (const [a, n] of Object.entries(r)) s(n, `${i}[${a}]`);
95
+ for (const [a, n] of Object.entries(r)) s(n, `${o}[${a}]`);
97
96
  return;
98
97
  }
99
- e(i, String(r));
98
+ e(o, String(r));
100
99
  }
101
100
  };
102
- for (const [r, i] of Object.entries(o)) s(i, r);
101
+ for (const [r, o] of Object.entries(i)) s(o, r);
103
102
  return t.join("&");
104
103
  }
105
- async function k(o) {
106
- if (o.status === 204) return null;
107
- const t = await o.text();
104
+ async function T(i) {
105
+ if (i.status === 204) return null;
106
+ const t = await i.text();
108
107
  if (!t) return null;
109
108
  try {
110
109
  return JSON.parse(t);
@@ -116,7 +115,7 @@ class S {
116
115
  constructor(t, e = {}, s = null) {
117
116
  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;
118
117
  const r = e.default ? e.default() : null;
119
- this._state = v({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
118
+ this._state = E({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
120
119
  }
121
120
  // --- reactive state ---------------------------------------------------------
122
121
  get data() {
@@ -167,7 +166,7 @@ class S {
167
166
  if (r.startsWith(s)) return e[r];
168
167
  }
169
168
  setErrors(t) {
170
- return this._state.errors = b(t), this._proxy;
169
+ return this._state.errors = g(t), this._proxy;
171
170
  }
172
171
  /** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
173
172
  clearErrors(t) {
@@ -214,6 +213,17 @@ class S {
214
213
  new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
215
214
  );
216
215
  }
216
+ /**
217
+ * Re-send the fill request with the CURRENT state — a manual watch trigger
218
+ * (a "Search" button next to filters). Sends the watched paths as payload and
219
+ * preserves them in the response, exactly like a watch-triggered request; any
220
+ * pending debounce is cancelled. Without an active watch() it equals reload().
221
+ */
222
+ refresh() {
223
+ return this._source ? this._stopWatch ? (this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null), this._lastSent = this._payloadJson(), this._fill(this._watchExtra())) : this._fill() : Promise.reject(
224
+ new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url).")
225
+ );
226
+ }
217
227
  // --- transformers -------------------------------------------------------------------
218
228
  /**
219
229
  * Map server data into the model shape. Runs on every fill (initial, reload,
@@ -243,8 +253,8 @@ class S {
243
253
  watch(t, e) {
244
254
  let s = null, r;
245
255
  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();
246
- const i = s && s.length ? s.map((a) => () => f(this._state.data, a)) : () => this._state.data;
247
- return this._stopWatch = E(i, () => this._onWatchTrigger(), {
256
+ const o = s && s.length ? s.map((a) => () => f(this._state.data, a)) : () => this._state.data;
257
+ return this._stopWatch = v(o, () => this._onWatchTrigger(), {
248
258
  deep: r.deep ?? !0
249
259
  }), this._proxy;
250
260
  }
@@ -255,23 +265,23 @@ class S {
255
265
  // --- internals ----------------------------------------------------------------------
256
266
  /** @internal */
257
267
  async _fill(t = {}) {
258
- var i, a, n, h, u;
268
+ var o, a, n, h, u;
259
269
  const e = this._source;
260
- (i = this._fillAbort) == null || i.abort();
270
+ (o = this._fillAbort) == null || o.abort();
261
271
  const s = new AbortController();
262
272
  this._fillAbort = s, this._state.processing = !0;
263
273
  const r = { signal: s.signal };
264
274
  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);
265
275
  try {
266
276
  const l = await this._apix.request(e.method, e.url, r);
267
- let _ = O(l, this._options.path);
277
+ let p = q(l, this._options.path);
268
278
  if (this._transformResponse) {
269
- const m = c(_);
270
- _ = this._transformResponse(m, l) ?? m;
279
+ const m = c(p);
280
+ p = this._transformResponse(m, l) ?? m;
271
281
  }
272
- return this._applyFill(_, t.preserve ?? null), this._state.message = p(l), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, l, this._proxy), l;
282
+ return this._applyFill(p, t.preserve ?? null), this._state.message = _(l), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, l, this._proxy), l;
273
283
  } catch (l) {
274
- throw R(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
284
+ throw O(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
275
285
  } finally {
276
286
  this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
277
287
  }
@@ -281,33 +291,33 @@ class S {
281
291
  this._options.mergeDefaults !== !1 && this._options.default && (s = x(s, this._options.default()));
282
292
  const r = this._snapshotLocked ? null : c(s);
283
293
  if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
284
- for (const i of e) {
285
- const a = f(this._state.data, i);
286
- a !== void 0 && d(s, i, c(a));
294
+ for (const o of e) {
295
+ const a = f(this._state.data, o);
296
+ a !== void 0 && d(s, o, c(a));
287
297
  }
288
298
  this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
289
299
  }
290
300
  _applyError(t) {
291
- t instanceof j && (this._state.message = p(t.body) ?? t.message, t.isValidationError && (this._state.errors = b(t.errors)));
301
+ t instanceof j && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors = g(t.errors)));
292
302
  }
293
303
  async _submit(t, e, s = {}) {
294
304
  var a;
295
305
  const r = e ?? ((a = this._source) == null ? void 0 : a.url);
296
306
  if (!r)
297
307
  throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
298
- let i = s.data !== void 0 ? s.data : s.only ? g(this._state.data, s.only) : this._state.data ?? void 0;
299
- if (s.data === void 0 && this._transformRequest && i !== void 0) {
300
- const n = c(i);
301
- i = this._transformRequest(n) ?? n;
308
+ let o = s.data !== void 0 ? s.data : s.only ? b(this._state.data, s.only) : this._state.data ?? void 0;
309
+ if (s.data === void 0 && this._transformRequest && o !== void 0) {
310
+ const n = c(o);
311
+ o = this._transformRequest(n) ?? n;
302
312
  }
303
313
  this._state.processing = !0, this._state.errors = {}, this._state.message = null;
304
314
  try {
305
315
  const n = await this._apix.request(t, r, {
306
- data: i,
316
+ data: o,
307
317
  params: s.params,
308
318
  headers: s.headers
309
319
  });
310
- return this._state.message = p(n), n;
320
+ return this._state.message = _(n), n;
311
321
  } catch (n) {
312
322
  throw this._applyError(n), n;
313
323
  } finally {
@@ -321,13 +331,16 @@ class S {
321
331
  t > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), t) : this._sendWatchRequest();
322
332
  }
323
333
  _sendWatchRequest() {
324
- if (this._debounceTimer = null, !this._source) return;
334
+ this._debounceTimer = null, this._source && (this._lastSent = this._payloadJson(), this._fill(this._watchExtra()).catch(() => {
335
+ }));
336
+ }
337
+ /** Build the fill() extra for a watch-shaped request from the current state. */
338
+ _watchExtra() {
325
339
  const t = this._watched, e = this._watchOptions.payload ?? t;
326
- let s = e && e.length ? g(this._state.data, e) : c(this._state.data);
327
- this._transformRequest && (s = this._transformRequest(s) ?? s), this._lastSent = this._payloadJson();
328
- const r = this._watchOptions.refreshWatched ? null : t, i = this._source.method === "get" ? { params: s, preserve: r } : { data: s, preserve: r };
329
- this._fill(i).catch(() => {
330
- });
340
+ let s = e && e.length ? b(this._state.data, e) : c(this._state.data);
341
+ this._transformRequest && (s = this._transformRequest(s) ?? s);
342
+ const r = this._watchOptions.refreshWatched ? null : t;
343
+ return this._source.method === "get" ? { params: s, preserve: r } : { data: s, preserve: r };
331
344
  }
332
345
  _payloadJson() {
333
346
  const t = this._watched, e = t && t.length ? t.map((s) => f(this._state.data, s)) : this._state.data;
@@ -337,28 +350,28 @@ class S {
337
350
  this._lastSent = this._payloadJson();
338
351
  }
339
352
  }
340
- function w(o, t = {}, e = null) {
341
- const s = new S(o, t, e), r = new Proxy(s, {
342
- get(i, a) {
343
- if (typeof a == "symbol" || a in i) return Reflect.get(i, a);
344
- const n = i._state.data;
353
+ function w(i, t = {}, e = null) {
354
+ const s = new S(i, t, e), r = new Proxy(s, {
355
+ get(o, a) {
356
+ if (typeof a == "symbol" || a in o) return Reflect.get(o, a);
357
+ const n = o._state.data;
345
358
  if (n && typeof n == "object") return n[a];
346
359
  },
347
- set(i, a, n) {
348
- if (typeof a == "symbol" || a in i) return Reflect.set(i, a, n);
349
- const h = i._state.data;
350
- return h && typeof h == "object" ? (h[a] = n, !0) : (i._state.data = { [a]: n }, !0);
360
+ set(o, a, n) {
361
+ if (typeof a == "symbol" || a in o) return Reflect.set(o, a, n);
362
+ const h = o._state.data;
363
+ return h && typeof h == "object" ? (h[a] = n, !0) : (o._state.data = { [a]: n }, !0);
351
364
  },
352
- has(i, a) {
353
- if (a in i) return !0;
354
- const n = i._state.data;
365
+ has(o, a) {
366
+ if (a in o) return !0;
367
+ const n = o._state.data;
355
368
  return !!n && typeof n == "object" && a in n;
356
369
  }
357
370
  });
358
371
  return s._proxy = r, e && t.immediate !== !1 && r.reload().catch(() => {
359
372
  }), r;
360
373
  }
361
- class T {
374
+ class k {
362
375
  constructor(t = {}) {
363
376
  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);
364
377
  }
@@ -401,30 +414,30 @@ class T {
401
414
  async request(t, e, s = {}) {
402
415
  let r = /^https?:\/\//i.test(e) ? e : this.baseUrl + e;
403
416
  if (s.params) {
404
- const h = q(s.params);
417
+ const h = A(s.params);
405
418
  h && (r += (r.includes("?") ? "&" : "?") + h);
406
419
  }
407
- const i = {
420
+ const o = {
408
421
  accept: "application/json",
409
422
  "x-requested-with": "XMLHttpRequest"
410
423
  };
411
424
  for (const [h, u] of Object.entries(this.headers)) {
412
425
  const l = typeof u == "function" ? u() : u;
413
- l != null && (i[h.toLowerCase()] = l);
426
+ l != null && (o[h.toLowerCase()] = l);
414
427
  }
415
428
  for (const [h, u] of Object.entries(s.headers ?? {}))
416
- i[h.toLowerCase()] = u;
417
- const a = { method: t.toUpperCase(), headers: i, signal: s.signal };
418
- this.credentials && (a.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete i["content-type"], a.body = s.data) : (i["content-type"] ?? (i["content-type"] = "application/json"), a.body = JSON.stringify(s.data)));
429
+ o[h.toLowerCase()] = u;
430
+ const a = { method: t.toUpperCase(), headers: o, signal: s.signal };
431
+ this.credentials && (a.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete o["content-type"], a.body = s.data) : (o["content-type"] ?? (o["content-type"] = "application/json"), a.body = JSON.stringify(s.data)));
419
432
  const n = { method: t, url: r, options: s };
420
433
  this.trackStart();
421
434
  try {
422
435
  const h = await fetch(r, a);
423
- let u = await k(h);
436
+ let u = await T(h);
424
437
  if (this.bodyTransformer && (u = this.bodyTransformer(u, n) ?? u), !h.ok) throw new j(h.status, u, h);
425
438
  return u;
426
439
  } catch (h) {
427
- throw R(h) ? h : this.emitError(h, n);
440
+ throw O(h) ? h : this.emitError(h, n);
428
441
  } finally {
429
442
  this.trackEnd();
430
443
  }
@@ -481,21 +494,21 @@ class T {
481
494
  let s = t;
482
495
  for (const r of this.errorHooks)
483
496
  try {
484
- const i = r(s, e);
485
- i instanceof Error && (s = i);
497
+ const o = r(s, e);
498
+ o instanceof Error && (s = o);
486
499
  } catch {
487
500
  }
488
501
  return s;
489
502
  }
490
503
  }
491
- function U(o = {}) {
492
- return new T(o);
504
+ function U(i = {}) {
505
+ return new k(i);
493
506
  }
494
507
  const L = U();
495
508
  export {
496
- T as Apix,
509
+ k as Apix,
497
510
  j as ApixError,
498
- S as ApixModel,
511
+ S as ApixFormModel,
499
512
  L as apix,
500
513
  U as createApix,
501
514
  L as default
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Tiny form/model/api toolkit for Vue 3 — fetch-based, Laravel-friendly, zero dependencies",
5
5
  "type": "module",
6
6
  "license": "MIT",