@diephp/vue-apix 0.3.4 → 0.4.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
@@ -272,7 +272,7 @@ const submit = () =>
272
272
  | `model.reset(keys?)` | restore the snapshot: first server response, else `default()`; `reset(['name'])` for specific paths |
273
273
  | `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
274
274
  | `model.reload(url?)` | re-run the fill request as configured — a fresh load, no `ignore`/`lock` applied |
275
- | `model.refresh(opts?)` | re-send with the CURRENT state — a manual trigger for a "Search" button, see `watch` below |
275
+ | `model.refresh(opts?)` | re-send with the CURRENT state — a manual trigger for a "Search" button; `opts` overrides form options for this call (`params`, `data`, `path`, …), see `watch` below |
276
276
  | `model.transformResponse(fn)` / `model.transformRequest(fn)` | reshape server data ↔ model data, see below |
277
277
 
278
278
  Submitting clears previous errors; any **4xx** response carrying an `errors` object in the
@@ -508,6 +508,23 @@ model.refresh({ ignore: ['paginator.page'], lock: ['trackingNumber'] });
508
508
  - `options.ignore`/`options.lock` **extend** the form-level lists for this call only —
509
509
  handy for "Search resets to page 1": omit `paginator.page` for just this click so the
510
510
  server defaults to page 1, without changing the form's permanent configuration.
511
+ - **Any other form option can be overridden for one call** — `params`, `data`, `path`,
512
+ `mergeDefaults`, `transformResponse`, `transformRequest`, `onSuccess`, `onError`,
513
+ `onFinish`. Nothing persists past the call:
514
+
515
+ | option | combines with the form-level value by… |
516
+ | --- | --- |
517
+ | `ignore`, `lock` | extending the lists |
518
+ | `params` | merging over form-level `params` and the field payload (the call wins on a clash), GET and POST alike |
519
+ | `onSuccess`, `onError`, `onFinish` | running **in addition** to the form-level callbacks, after them |
520
+ | `path`, `mergeDefaults`, `transformResponse`, `transformRequest`, `data` | replacing them (`data` is the `postForm` body, sent as-is without `transformRequest`; a GET form ignores it) |
521
+
522
+ ```ts
523
+ // a dependent dropdown: re-fetch the options for the newly picked conveyor
524
+ watch(() => form.conveyor_id, (id) => {
525
+ rulesOptions.refresh({ params: { conveyor_id: id, with_inactive: 1 } });
526
+ });
527
+ ```
511
528
  - `model.reload()` is different: it re-runs the *original* fill request with no
512
529
  field-derived payload and no `lock` at all — it resets the view rather than searching
513
530
  with the current state.
package/dist/model.d.ts CHANGED
@@ -87,10 +87,12 @@ export declare class ApixFormModel<T = any> {
87
87
  * "Search" button. Sends every field except `ignore` (with or without
88
88
  * `watch` configured), and protects `lock` fields from being overwritten by
89
89
  * the response, exactly like an auto watch-triggered request; any pending
90
- * debounce is cancelled. `options.ignore`/`options.lock` extend the
91
- * form-level lists for this one call only.
90
+ * debounce is cancelled. `options` overrides a subset of the form options
91
+ * for this one call only (see RefreshOptions): `ignore`/`lock` extend the
92
+ * form-level lists, `params` is merged over the request params, the rest
93
+ * replace their form-level value.
92
94
  */
93
- refresh(options?: RefreshOptions): Promise<any>;
95
+ refresh(options?: RefreshOptions<T>): Promise<any>;
94
96
  /**
95
97
  * Map server data into the model shape. Runs on every fill (initial, reload,
96
98
  * watch) AFTER path extraction and BEFORE the reactive data is touched — so it
@@ -109,6 +111,7 @@ export declare class ApixFormModel<T = any> {
109
111
  params?: Record<string, unknown>;
110
112
  data?: unknown;
111
113
  preserve?: string[] | null;
114
+ overrides?: RefreshOptions<T>;
112
115
  }): Promise<any>;
113
116
  private _applyFill;
114
117
  private _applyError;
package/dist/types.d.ts CHANGED
@@ -122,11 +122,21 @@ export interface WatchConfig {
122
122
  */
123
123
  deep?: boolean;
124
124
  }
125
- export interface RefreshOptions {
126
- /** Merged with the form-level `ignore` for this call only (not persisted). */
127
- ignore?: string[];
128
- /** Merged with the form-level `lock` for this call only (not persisted). */
129
- lock?: string[];
125
+ /**
126
+ * Per-call overrides for `model.refresh()` — a subset of FormOptions, applied
127
+ * to this one request only (never persisted, never touching the form-level
128
+ * options). How each one combines with its form-level counterpart:
129
+ * - `ignore`, `lock`: EXTEND the form-level lists.
130
+ * - `params`: MERGED over the form-level `params` AND the field payload
131
+ * (the call wins on a key clash) — GET and POST alike.
132
+ * - `onSuccess`, `onError`, `onFinish`: called IN ADDITION to the form-level
133
+ * callbacks, after them.
134
+ * - `path`, `mergeDefaults`, `transformResponse`, `transformRequest`, `data`:
135
+ * REPLACE the form-level value for this call.
136
+ * `data` only matters for `postForm` (the explicit body is sent as-is, not
137
+ * passed through `transformRequest`); a GET form has no body and ignores it.
138
+ */
139
+ export interface RefreshOptions<T = any> extends Pick<FormOptions<T>, 'ignore' | 'lock' | 'params' | 'data' | 'path' | 'mergeDefaults' | 'transformResponse' | 'transformRequest' | 'onSuccess' | 'onError' | 'onFinish'> {
130
140
  }
131
141
  export interface SubmitOptions {
132
142
  /** Explicit body; overrides model data. */
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 y(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function F(i,t){if(!y(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!y(i))return i;for(const e of Object.keys(t))i[e]=e in i?F(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 g(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const n=s[o];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function k(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&g(e,s,c(r))}return e}function E(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 A(i,t){return t.some(e=>e===i||i.startsWith(`${e}.`))}function b(i,t,e=""){if(e&&A(e,t))return[];if(y(i)){const s=[];for(const r of Object.keys(i))s.push(...b(i[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(i)||!e?[]:[e]}function U(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class x 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 S(i){return i instanceof Error&&i.name==="AbortError"}function W(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((n,a)=>s(n,`${o}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${o}[${n}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function L(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._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._deferredWatchSetup=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;if(this._state=_.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],this._sendFields=b(r??{},this._ignore),e.watch){const o=e.watch;if(!this._source)console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");else if(e.immediate===!1)this._setupWatch(o,r);else{const n=_.getCurrentScope();this._deferredWatchSetup=()=>{n?n.run(()=>this._setupWatch(o,r)):this._setupWatch(o,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=E(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)g(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(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill(e)}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var o,n,a,h,u,d,j;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 m=U(l,this._options.path);if(this._transformResponse){const w=c(m);m=this._transformResponse(w,l)??w}return this._applyFill(m,t.preserve??null),this._state.message=p(l),this._state.errors={},(a=(n=this._options).onSuccess)==null||a.call(n,l,this._proxy),l}catch(l){throw S(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,(j=(d=this._options).onFinish)==null||j.call(d,this._proxy))}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=F(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 n=f(this._state.data,o);n!==void 0&&g(s,o,c(n))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof x&&(this._state.message=p(t.body)??t.message,t.isValidationError&&(this._state.errors=E(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.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?k(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const a=c(o);o=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=p(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){const s=t===!0?{}:t,r=s.fields,o=r??this._sendFields??b(e??{},this._ignore);this._triggerFields=o,this._debounce=s.debounce??0,this._syncLastSent();const n=o.map(h=>()=>f(this._state.data,h)),a=r?s.deep??!1:!0;_.watch(n,()=>this._onWatchTrigger(),{deep:a})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(o=>!A(o,t.ignore)):this._sendFields??[];let r=k(this._state.data,s);return this._transformRequest&&(r=this._transformRequest(r)??r),this._source.method==="get"?{params:r,preserve:e}:{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function R(i,t={},e=null){const s=new v(i,t,e),r=new Proxy(s,{get(o,n){if(typeof n=="symbol"||n in o)return Reflect.get(o,n);const a=o._state.data;if(a&&typeof a=="object")return a[n]},set(o,n,a){if(typeof n=="symbol"||n in o)return Reflect.set(o,n,a);const h=o._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(o._state.data={[n]:a},!0)},has(o,n){if(n in o)return!0;const a=o._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().finally(()=>{var o;(o=s._deferredWatchSetup)==null||o.call(s),s._deferredWatchSetup=null}).catch(()=>{}),r}class O{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=W(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 d=typeof u=="function"?u():u;d!=null&&(o[h.toLowerCase()]=d)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const n={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],n.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let u=await L(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,a)??u),!h.ok)throw new x(h.status,u,h);return u}catch(h){throw S(h)?h:this.emitError(h,a)}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 R(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 R(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 q(i={}){return new O(i)}const T=q();exports.Apix=O;exports.ApixError=x;exports.ApixFormModel=v;exports.apix=T;exports.createApix=q;exports.default=T;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const _=require("vue");function c(o){const t=_.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 g(o){if(o===null||typeof o!="object")return!1;const t=Object.getPrototypeOf(o);return t===Object.prototype||t===null}function v(o,t){if(!g(t))return o===void 0?c(t):o;if(o==null)return c(t);if(!g(o))return o;for(const e of Object.keys(t))o[e]=e in o?v(o[e],t[e]):c(t[e]);return o}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 b(o,t,e){const s=t.split(".");let r=o;for(let i=0;i<s.length-1;i++){const n=s[i];(r[n]===null||typeof r[n]!="object")&&(r[n]={}),r=r[n]}r[s[s.length-1]]=e}function y(o,t){const e={};for(const s of t){const r=f(o,s);r!==void 0&&b(e,s,c(r))}return e}function A(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 p(o){return o&&typeof o=="object"&&typeof o.message=="string"?o.message:null}function T(o,t){return t.some(e=>e===o||o.startsWith(`${e}.`))}function j(o,t,e=""){if(e&&T(e,t))return[];if(g(o)){const s=[];for(const r of Object.keys(o))s.push(...j(o[r],t,e?`${e}.${r}`:r));return s}return Array.isArray(o)||!e?[]:[e]}function H(o,t){return t&&o&&typeof o=="object"?f(o,t):o}class x 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 U(o){return o instanceof Error&&o.name==="AbortError"}function D(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((n,a)=>s(n,`${i}[${a}]`));return}if(typeof r=="object"){for(const[n,a]of Object.entries(r))s(a,`${i}[${n}]`);return}e(i,String(r))}};for(const[r,i]of Object.entries(o))s(i,r);return t.join("&")}async function C(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 W{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._ignore=[],this._lock=[],this._triggerFields=null,this._sendFields=null,this._debounce=0,this._debounceTimer=null,this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._deferredWatchSetup=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;if(this._state=_.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r),this._ignore=e.ignore??[],this._lock=e.lock??[],this._sendFields=j(r??{},this._ignore),e.watch){const i=e.watch;if(!this._source)console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");else if(e.immediate===!1)this._setupWatch(i,r);else{const n=_.getCurrentScope();this._deferredWatchSetup=()=>{n?n.run(()=>this._setupWatch(i,r)):this._setupWatch(i,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=A(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)b(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(t={}){if(!this._source)return Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."));this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null);const e=this._buildFillExtra(t);return this._lastSent=this._payloadJson(),this._fill({...e,overrides:t})}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}async _fill(t={}){var n,a,h,u,d,R,w,E,k,F;const e=this._source,s=t.overrides??{};(n=this._fillAbort)==null||n.abort();const r=new AbortController;this._fillAbort=r,this._state.processing=!0;const i={signal:r.signal};e.method==="get"?i.params={...this._options.params,...t.params,...s.params}:(i.params=s.params?{...this._options.params,...s.params}:this._options.params,i.data=t.data!==void 0?t.data:this._options.data);try{const l=await this._apix.request(e.method,e.url,i);let m=H(l,s.path??this._options.path);const q=s.transformResponse??this._transformResponse;if(q){const S=c(m);m=q(S,l)??S}return this._applyFill(m,t.preserve??null,s.mergeDefaults??this._options.mergeDefaults),this._state.message=p(l),this._state.errors={},(h=(a=this._options).onSuccess)==null||h.call(a,l,this._proxy),(u=s.onSuccess)==null||u.call(s,l,this._proxy),l}catch(l){throw U(l)||(this._applyError(l),(R=(d=this._options).onError)==null||R.call(d,l,this._proxy),(w=s.onError)==null||w.call(s,l,this._proxy)),l}finally{this._fillAbort===r&&(this._fillAbort=null,this._state.processing=!1,(k=(E=this._options).onFinish)==null||k.call(E,this._proxy),(F=s.onFinish)==null||F.call(s,this._proxy))}}_applyFill(t,e,s){let r=c(t);s!==!1&&this._options.default&&(r=v(r,this._options.default()));const i=this._snapshotLocked?null:c(r);if(e&&e.length&&r&&typeof r=="object"&&this._state.data&&typeof this._state.data=="object")for(const n of e){const a=f(this._state.data,n);a!==void 0&&b(r,n,c(a))}this._state.data=r,this._snapshotLocked||(this._snapshot=i,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof x&&(this._state.message=p(t.body)??t.message,t.isValidationError&&(this._state.errors=A(t.errors)))}async _submit(t,e,s={}){var n;const r=e??((n=this._source)==null?void 0:n.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?y(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&i!==void 0){const a=c(i);i=this._transformRequest(a)??a}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const a=await this._apix.request(t,r,{data:i,params:s.params,headers:s.headers});return this._state.message=p(a),a}catch(a){throw this._applyError(a),a}finally{this._state.processing=!1}}_setupWatch(t,e){const s=t===!0?{}:t,r=s.fields,i=r??this._sendFields??j(e??{},this._ignore);this._triggerFields=i,this._debounce=s.debounce??0,this._syncLastSent();const n=i.map(h=>()=>f(this._state.data,h)),a=r?s.deep??!1:!0;_.watch(n,()=>this._onWatchTrigger(),{deep:a})}_onWatchTrigger(){this._payloadJson()!==this._lastSent&&(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounce>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),this._debounce):this._sendWatchRequest())}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._buildFillExtra()).catch(()=>{}))}_buildFillExtra(t={}){const e=t.lock?[...this._lock,...t.lock]:this._lock,s=t.ignore?(this._sendFields??[]).filter(n=>!T(n,t.ignore)):this._sendFields??[];if(this._source.method==="get"){let n=y(this._state.data,s);const a=t.transformRequest??this._transformRequest;return a&&(n=a(n)??n),{params:n,preserve:e}}if(t.data!==void 0)return{data:t.data,preserve:e};let r=y(this._state.data,s);const i=t.transformRequest??this._transformRequest;return i&&(r=i(r)??r),{data:r,preserve:e}}_payloadJson(){const e=(this._triggerFields??[]).map(s=>f(this._state.data,s));return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function O(o,t={},e=null){const s=new W(o,t,e),r=new Proxy(s,{get(i,n){if(typeof n=="symbol"||n in i)return Reflect.get(i,n);const a=i._state.data;if(a&&typeof a=="object")return a[n]},set(i,n,a){if(typeof n=="symbol"||n in i)return Reflect.set(i,n,a);const h=i._state.data;return h&&typeof h=="object"?(h[n]=a,!0):(i._state.data={[n]:a},!0)},has(i,n){if(n in i)return!0;const a=i._state.data;return!!a&&typeof a=="object"&&n in a}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().finally(()=>{var i;(i=s._deferredWatchSetup)==null||i.call(s),s._deferredWatchSetup=null}).catch(()=>{}),r}class L{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=D(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const i={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,u]of Object.entries(this.headers)){const d=typeof u=="function"?u():u;d!=null&&(i[h.toLowerCase()]=d)}for(const[h,u]of Object.entries(s.headers??{}))i[h.toLowerCase()]=u;const n={method:t.toUpperCase(),headers:i,signal:s.signal};this.credentials&&(n.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete i["content-type"],n.body=s.data):(i["content-type"]??(i["content-type"]="application/json"),n.body=JSON.stringify(s.data)));const a={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,n);let u=await C(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,a)??u),!h.ok)throw new x(h.status,u,h);return u}catch(h){throw U(h)?h:this.emitError(h,a)}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 O(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 O(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 P(o={}){return new L(o)}const $=P();exports.Apix=L;exports.ApixError=x;exports.ApixFormModel=W;exports.apix=$;exports.createApix=P;exports.default=$;
package/dist/vue-apix.js CHANGED
@@ -1,6 +1,6 @@
1
- import { toRaw as S, reactive as q, getCurrentScope as v, watch as A } from "vue";
2
- function c(i) {
3
- const t = S(i);
1
+ import { toRaw as U, reactive as W, getCurrentScope as L, watch as H } from "vue";
2
+ function c(o) {
3
+ const t = U(o);
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,72 +12,72 @@ function c(i) {
12
12
  }
13
13
  return t;
14
14
  }
15
- function m(i) {
16
- if (i === null || typeof i != "object") return !1;
17
- const t = Object.getPrototypeOf(i);
15
+ function y(o) {
16
+ if (o === null || typeof o != "object") return !1;
17
+ const t = Object.getPrototypeOf(o);
18
18
  return t === Object.prototype || t === null;
19
19
  }
20
- function R(i, t) {
21
- if (!m(t))
22
- return i === void 0 ? c(t) : i;
23
- if (i == null) return c(t);
24
- if (!m(i)) return i;
20
+ function O(o, t) {
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;
25
25
  for (const e of Object.keys(t))
26
- i[e] = e in i ? R(i[e], t[e]) : c(t[e]);
27
- return i;
26
+ o[e] = e in o ? O(o[e], t[e]) : c(t[e]);
27
+ return o;
28
28
  }
29
- function f(i, t) {
30
- if (i == null) return;
31
- let e = i;
29
+ function f(o, t) {
30
+ if (o == null) return;
31
+ let e = o;
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 y(i, t, e) {
38
+ function g(o, t, e) {
39
39
  const s = t.split(".");
40
- let r = i;
41
- for (let o = 0; o < s.length - 1; o++) {
42
- const n = s[o];
40
+ let r = o;
41
+ for (let i = 0; i < s.length - 1; i++) {
42
+ const n = s[i];
43
43
  (r[n] === null || typeof r[n] != "object") && (r[n] = {}), r = r[n];
44
44
  }
45
45
  r[s[s.length - 1]] = e;
46
46
  }
47
- function x(i, t) {
47
+ function m(o, t) {
48
48
  const e = {};
49
49
  for (const s of t) {
50
- const r = f(i, s);
51
- r !== void 0 && y(e, s, c(r));
50
+ const r = f(o, s);
51
+ r !== void 0 && g(e, s, c(r));
52
52
  }
53
53
  return e;
54
54
  }
55
- function w(i) {
55
+ function q(o) {
56
56
  const t = {};
57
- for (const [e, s] of Object.entries(i ?? {}))
57
+ for (const [e, s] of Object.entries(o ?? {}))
58
58
  s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
59
59
  return t;
60
60
  }
61
- function _(i) {
62
- return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
61
+ function _(o) {
62
+ return o && typeof o == "object" && typeof o.message == "string" ? o.message : null;
63
63
  }
64
- function E(i, t) {
65
- return t.some((e) => e === i || i.startsWith(`${e}.`));
64
+ function A(o, t) {
65
+ return t.some((e) => e === o || o.startsWith(`${e}.`));
66
66
  }
67
- function g(i, t, e = "") {
68
- if (e && E(e, t)) return [];
69
- if (m(i)) {
67
+ function b(o, t, e = "") {
68
+ if (e && A(e, t)) return [];
69
+ if (y(o)) {
70
70
  const s = [];
71
- for (const r of Object.keys(i))
72
- s.push(...g(i[r], t, e ? `${e}.${r}` : r));
71
+ for (const r of Object.keys(o))
72
+ s.push(...b(o[r], t, e ? `${e}.${r}` : r));
73
73
  return s;
74
74
  }
75
- return Array.isArray(i) || !e ? [] : [e];
75
+ return Array.isArray(o) || !e ? [] : [e];
76
76
  }
77
- function T(i, t) {
78
- return t && i && typeof i == "object" ? f(i, t) : i;
77
+ function P(o, t) {
78
+ return t && o && typeof o == "object" ? f(o, t) : o;
79
79
  }
80
- class F extends Error {
80
+ class v extends Error {
81
81
  constructor(t, e, s) {
82
82
  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 : {};
83
83
  }
@@ -90,33 +90,33 @@ class F extends Error {
90
90
  return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
91
91
  }
92
92
  }
93
- function O(i) {
94
- return i instanceof Error && i.name === "AbortError";
93
+ function T(o) {
94
+ return o instanceof Error && o.name === "AbortError";
95
95
  }
96
- function U(i) {
97
- const t = [], e = (r, o) => {
98
- t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`);
99
- }, s = (r, o) => {
96
+ function $(o) {
97
+ const t = [], e = (r, i) => {
98
+ t.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);
99
+ }, s = (r, i) => {
100
100
  if (r != null) {
101
- if (typeof r == "boolean") return e(o, r ? "1" : "0");
102
- if (r instanceof Date) return e(o, r.toISOString());
101
+ if (typeof r == "boolean") return e(i, r ? "1" : "0");
102
+ if (r instanceof Date) return e(i, r.toISOString());
103
103
  if (Array.isArray(r)) {
104
- r.forEach((n, a) => s(n, `${o}[${a}]`));
104
+ r.forEach((n, a) => s(n, `${i}[${a}]`));
105
105
  return;
106
106
  }
107
107
  if (typeof r == "object") {
108
- for (const [n, a] of Object.entries(r)) s(a, `${o}[${n}]`);
108
+ for (const [n, a] of Object.entries(r)) s(a, `${i}[${n}]`);
109
109
  return;
110
110
  }
111
- e(o, String(r));
111
+ e(i, String(r));
112
112
  }
113
113
  };
114
- for (const [r, o] of Object.entries(i)) s(o, r);
114
+ for (const [r, i] of Object.entries(o)) s(i, r);
115
115
  return t.join("&");
116
116
  }
117
- async function W(i) {
118
- if (i.status === 204) return null;
119
- const t = await i.text();
117
+ async function D(o) {
118
+ if (o.status === 204) return null;
119
+ const t = await o.text();
120
120
  if (!t) return null;
121
121
  try {
122
122
  return JSON.parse(t);
@@ -124,20 +124,20 @@ async function W(i) {
124
124
  return t;
125
125
  }
126
126
  }
127
- class L {
127
+ class C {
128
128
  constructor(t, e = {}, s = null) {
129
129
  this._snapshot = null, this._snapshotLocked = !1, this._ignore = [], this._lock = [], this._triggerFields = null, this._sendFields = null, this._debounce = 0, this._debounceTimer = null, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._deferredWatchSetup = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
130
130
  const r = e.default ? e.default() : null;
131
- if (this._state = q({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], this._sendFields = g(r ?? {}, this._ignore), e.watch) {
132
- const o = e.watch;
131
+ if (this._state = W({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r), this._ignore = e.ignore ?? [], this._lock = e.lock ?? [], this._sendFields = b(r ?? {}, this._ignore), e.watch) {
132
+ const i = e.watch;
133
133
  if (!this._source)
134
134
  console.warn("[vue-apix] `watch` has no effect without a source URL (use apix.getForm/postForm).");
135
135
  else if (e.immediate === !1)
136
- this._setupWatch(o, r);
136
+ this._setupWatch(i, r);
137
137
  else {
138
- const n = v();
138
+ const n = L();
139
139
  this._deferredWatchSetup = () => {
140
- n ? n.run(() => this._setupWatch(o, r)) : this._setupWatch(o, r);
140
+ n ? n.run(() => this._setupWatch(i, r)) : this._setupWatch(i, r);
141
141
  };
142
142
  }
143
143
  }
@@ -191,7 +191,7 @@ class L {
191
191
  if (r.startsWith(s)) return e[r];
192
192
  }
193
193
  setErrors(t) {
194
- return this._state.errors = w(t), this._proxy;
194
+ return this._state.errors = q(t), this._proxy;
195
195
  }
196
196
  /** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
197
197
  clearErrors(t) {
@@ -215,7 +215,7 @@ class L {
215
215
  const e = Array.isArray(t) ? t : [t];
216
216
  if (this._state.data && typeof this._state.data == "object")
217
217
  for (const s of e)
218
- y(this._state.data, s, c(f(this._snapshot, s)));
218
+ g(this._state.data, s, c(f(this._snapshot, s)));
219
219
  return this.clearErrors(e), this._proxy;
220
220
  }
221
221
  // --- HTTP ------------------------------------------------------------------------
@@ -243,8 +243,10 @@ class L {
243
243
  * "Search" button. Sends every field except `ignore` (with or without
244
244
  * `watch` configured), and protects `lock` fields from being overwritten by
245
245
  * the response, exactly like an auto watch-triggered request; any pending
246
- * debounce is cancelled. `options.ignore`/`options.lock` extend the
247
- * form-level lists for this one call only.
246
+ * debounce is cancelled. `options` overrides a subset of the form options
247
+ * for this one call only (see RefreshOptions): `ignore`/`lock` extend the
248
+ * form-level lists, `params` is merged over the request params, the rest
249
+ * replace their form-level value.
248
250
  */
249
251
  refresh(t = {}) {
250
252
  if (!this._source)
@@ -253,7 +255,7 @@ class L {
253
255
  );
254
256
  this._debounceTimer && (clearTimeout(this._debounceTimer), this._debounceTimer = null);
255
257
  const e = this._buildFillExtra(t);
256
- return this._lastSent = this._payloadJson(), this._fill(e);
258
+ return this._lastSent = this._payloadJson(), this._fill({ ...e, overrides: t });
257
259
  }
258
260
  // --- transformers -------------------------------------------------------------------
259
261
  /**
@@ -276,55 +278,56 @@ class L {
276
278
  // --- internals ----------------------------------------------------------------------
277
279
  /** @internal */
278
280
  async _fill(t = {}) {
279
- var o, n, a, h, u, d, b;
280
- const e = this._source;
281
- (o = this._fillAbort) == null || o.abort();
282
- const s = new AbortController();
283
- this._fillAbort = s, this._state.processing = !0;
284
- const r = { signal: s.signal };
285
- 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);
281
+ var n, a, h, u, d, j, R, x, w, k;
282
+ const e = this._source, s = t.overrides ?? {};
283
+ (n = this._fillAbort) == null || n.abort();
284
+ const r = new AbortController();
285
+ this._fillAbort = r, this._state.processing = !0;
286
+ const i = { signal: r.signal };
287
+ e.method === "get" ? i.params = { ...this._options.params, ...t.params, ...s.params } : (i.params = s.params ? { ...this._options.params, ...s.params } : this._options.params, i.data = t.data !== void 0 ? t.data : this._options.data);
286
288
  try {
287
- const l = await this._apix.request(e.method, e.url, r);
288
- let p = T(l, this._options.path);
289
- if (this._transformResponse) {
290
- const j = c(p);
291
- p = this._transformResponse(j, l) ?? j;
289
+ const l = await this._apix.request(e.method, e.url, i);
290
+ let p = P(l, s.path ?? this._options.path);
291
+ const E = s.transformResponse ?? this._transformResponse;
292
+ if (E) {
293
+ const F = c(p);
294
+ p = E(F, l) ?? F;
292
295
  }
293
- return this._applyFill(p, t.preserve ?? null), this._state.message = _(l), this._state.errors = {}, (a = (n = this._options).onSuccess) == null || a.call(n, l, this._proxy), l;
296
+ return this._applyFill(p, t.preserve ?? null, s.mergeDefaults ?? this._options.mergeDefaults), this._state.message = _(l), this._state.errors = {}, (h = (a = this._options).onSuccess) == null || h.call(a, l, this._proxy), (u = s.onSuccess) == null || u.call(s, l, this._proxy), l;
294
297
  } catch (l) {
295
- throw O(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
298
+ throw T(l) || (this._applyError(l), (j = (d = this._options).onError) == null || j.call(d, l, this._proxy), (R = s.onError) == null || R.call(s, l, this._proxy)), l;
296
299
  } finally {
297
- this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1, (b = (d = this._options).onFinish) == null || b.call(d, this._proxy));
300
+ this._fillAbort === r && (this._fillAbort = null, this._state.processing = !1, (w = (x = this._options).onFinish) == null || w.call(x, this._proxy), (k = s.onFinish) == null || k.call(s, this._proxy));
298
301
  }
299
302
  }
300
- _applyFill(t, e) {
301
- let s = c(t);
302
- this._options.mergeDefaults !== !1 && this._options.default && (s = R(s, this._options.default()));
303
- const r = this._snapshotLocked ? null : c(s);
304
- if (e && e.length && s && typeof s == "object" && this._state.data && typeof this._state.data == "object")
305
- for (const o of e) {
306
- const n = f(this._state.data, o);
307
- n !== void 0 && y(s, o, c(n));
303
+ _applyFill(t, e, s) {
304
+ let r = c(t);
305
+ s !== !1 && this._options.default && (r = O(r, this._options.default()));
306
+ const i = this._snapshotLocked ? null : c(r);
307
+ if (e && e.length && r && typeof r == "object" && this._state.data && typeof this._state.data == "object")
308
+ for (const n of e) {
309
+ const a = f(this._state.data, n);
310
+ a !== void 0 && g(r, n, c(a));
308
311
  }
309
- this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
312
+ this._state.data = r, this._snapshotLocked || (this._snapshot = i, this._snapshotLocked = !0), this._syncLastSent();
310
313
  }
311
314
  _applyError(t) {
312
- t instanceof F && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors = w(t.errors)));
315
+ t instanceof v && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors = q(t.errors)));
313
316
  }
314
317
  async _submit(t, e, s = {}) {
315
318
  var n;
316
319
  const r = e ?? ((n = this._source) == null ? void 0 : n.url);
317
320
  if (!r)
318
321
  throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
319
- let o = s.data !== void 0 ? s.data : s.only ? x(this._state.data, s.only) : this._state.data ?? void 0;
320
- if (s.data === void 0 && this._transformRequest && o !== void 0) {
321
- const a = c(o);
322
- o = this._transformRequest(a) ?? a;
322
+ let i = s.data !== void 0 ? s.data : s.only ? m(this._state.data, s.only) : this._state.data ?? void 0;
323
+ if (s.data === void 0 && this._transformRequest && i !== void 0) {
324
+ const a = c(i);
325
+ i = this._transformRequest(a) ?? a;
323
326
  }
324
327
  this._state.processing = !0, this._state.errors = {}, this._state.message = null;
325
328
  try {
326
329
  const a = await this._apix.request(t, r, {
327
- data: o,
330
+ data: i,
328
331
  params: s.params,
329
332
  headers: s.headers
330
333
  });
@@ -343,10 +346,10 @@ class L {
343
346
  * that's what determines which fields exist, regardless of timing.
344
347
  */
345
348
  _setupWatch(t, e) {
346
- const s = t === !0 ? {} : t, r = s.fields, o = r ?? this._sendFields ?? g(e ?? {}, this._ignore);
347
- this._triggerFields = o, this._debounce = s.debounce ?? 0, this._syncLastSent();
348
- const n = o.map((h) => () => f(this._state.data, h)), a = r ? s.deep ?? !1 : !0;
349
- A(n, () => this._onWatchTrigger(), { deep: a });
349
+ const s = t === !0 ? {} : t, r = s.fields, i = r ?? this._sendFields ?? b(e ?? {}, this._ignore);
350
+ this._triggerFields = i, this._debounce = s.debounce ?? 0, this._syncLastSent();
351
+ const n = i.map((h) => () => f(this._state.data, h)), a = r ? s.deep ?? !1 : !0;
352
+ H(n, () => this._onWatchTrigger(), { deep: a });
350
353
  }
351
354
  _onWatchTrigger() {
352
355
  this._payloadJson() !== this._lastSent && (this._debounceTimer && clearTimeout(this._debounceTimer), this._debounce > 0 ? this._debounceTimer = setTimeout(() => this._sendWatchRequest(), this._debounce) : this._sendWatchRequest());
@@ -357,9 +360,16 @@ class L {
357
360
  }
358
361
  /** Build the fill() extra for a watch/refresh request from the current state. */
359
362
  _buildFillExtra(t = {}) {
360
- const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((o) => !E(o, t.ignore)) : this._sendFields ?? [];
361
- let r = x(this._state.data, s);
362
- return this._transformRequest && (r = this._transformRequest(r) ?? r), this._source.method === "get" ? { params: r, preserve: e } : { data: r, preserve: e };
363
+ const e = t.lock ? [...this._lock, ...t.lock] : this._lock, s = t.ignore ? (this._sendFields ?? []).filter((n) => !A(n, t.ignore)) : this._sendFields ?? [];
364
+ if (this._source.method === "get") {
365
+ let n = m(this._state.data, s);
366
+ const a = t.transformRequest ?? this._transformRequest;
367
+ return a && (n = a(n) ?? n), { params: n, preserve: e };
368
+ }
369
+ if (t.data !== void 0) return { data: t.data, preserve: e };
370
+ let r = m(this._state.data, s);
371
+ const i = t.transformRequest ?? this._transformRequest;
372
+ return i && (r = i(r) ?? r), { data: r, preserve: e };
363
373
  }
364
374
  _payloadJson() {
365
375
  const e = (this._triggerFields ?? []).map((s) => f(this._state.data, s));
@@ -369,31 +379,31 @@ class L {
369
379
  this._lastSent = this._payloadJson();
370
380
  }
371
381
  }
372
- function k(i, t = {}, e = null) {
373
- const s = new L(i, t, e), r = new Proxy(s, {
374
- get(o, n) {
375
- if (typeof n == "symbol" || n in o) return Reflect.get(o, n);
376
- const a = o._state.data;
382
+ function S(o, t = {}, e = null) {
383
+ const s = new C(o, t, e), r = new Proxy(s, {
384
+ get(i, n) {
385
+ if (typeof n == "symbol" || n in i) return Reflect.get(i, n);
386
+ const a = i._state.data;
377
387
  if (a && typeof a == "object") return a[n];
378
388
  },
379
- set(o, n, a) {
380
- if (typeof n == "symbol" || n in o) return Reflect.set(o, n, a);
381
- const h = o._state.data;
382
- return h && typeof h == "object" ? (h[n] = a, !0) : (o._state.data = { [n]: a }, !0);
389
+ set(i, n, a) {
390
+ if (typeof n == "symbol" || n in i) return Reflect.set(i, n, a);
391
+ const h = i._state.data;
392
+ return h && typeof h == "object" ? (h[n] = a, !0) : (i._state.data = { [n]: a }, !0);
383
393
  },
384
- has(o, n) {
385
- if (n in o) return !0;
386
- const a = o._state.data;
394
+ has(i, n) {
395
+ if (n in i) return !0;
396
+ const a = i._state.data;
387
397
  return !!a && typeof a == "object" && n in a;
388
398
  }
389
399
  });
390
400
  return s._proxy = r, e && t.immediate !== !1 && r.reload().finally(() => {
391
- var o;
392
- (o = s._deferredWatchSetup) == null || o.call(s), s._deferredWatchSetup = null;
401
+ var i;
402
+ (i = s._deferredWatchSetup) == null || i.call(s), s._deferredWatchSetup = null;
393
403
  }).catch(() => {
394
404
  }), r;
395
405
  }
396
- class H {
406
+ class J {
397
407
  constructor(t = {}) {
398
408
  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);
399
409
  }
@@ -436,30 +446,30 @@ class H {
436
446
  async request(t, e, s = {}) {
437
447
  let r = /^https?:\/\//i.test(e) ? e : this.baseUrl + e;
438
448
  if (s.params) {
439
- const h = U(s.params);
449
+ const h = $(s.params);
440
450
  h && (r += (r.includes("?") ? "&" : "?") + h);
441
451
  }
442
- const o = {
452
+ const i = {
443
453
  accept: "application/json",
444
454
  "x-requested-with": "XMLHttpRequest"
445
455
  };
446
456
  for (const [h, u] of Object.entries(this.headers)) {
447
457
  const d = typeof u == "function" ? u() : u;
448
- d != null && (o[h.toLowerCase()] = d);
458
+ d != null && (i[h.toLowerCase()] = d);
449
459
  }
450
460
  for (const [h, u] of Object.entries(s.headers ?? {}))
451
- o[h.toLowerCase()] = u;
452
- const n = { method: t.toUpperCase(), headers: o, signal: s.signal };
453
- this.credentials && (n.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete o["content-type"], n.body = s.data) : (o["content-type"] ?? (o["content-type"] = "application/json"), n.body = JSON.stringify(s.data)));
461
+ i[h.toLowerCase()] = u;
462
+ const n = { method: t.toUpperCase(), headers: i, signal: s.signal };
463
+ this.credentials && (n.credentials = this.credentials), s.data !== void 0 && t !== "get" && (typeof FormData < "u" && s.data instanceof FormData ? (delete i["content-type"], n.body = s.data) : (i["content-type"] ?? (i["content-type"] = "application/json"), n.body = JSON.stringify(s.data)));
454
464
  const a = { method: t, url: r, options: s };
455
465
  this.trackStart();
456
466
  try {
457
467
  const h = await fetch(r, n);
458
- let u = await W(h);
459
- if (this.bodyTransformer && (u = this.bodyTransformer(u, a) ?? u), !h.ok) throw new F(h.status, u, h);
468
+ let u = await D(h);
469
+ if (this.bodyTransformer && (u = this.bodyTransformer(u, a) ?? u), !h.ok) throw new v(h.status, u, h);
460
470
  return u;
461
471
  } catch (h) {
462
- throw O(h) ? h : this.emitError(h, a);
472
+ throw T(h) ? h : this.emitError(h, a);
463
473
  } finally {
464
474
  this.trackEnd();
465
475
  }
@@ -483,7 +493,7 @@ class H {
483
493
  // --- form models -----------------------------------------------------------
484
494
  /** Create a form model without any request (like Inertia's useForm). */
485
495
  form(t, e = {}) {
486
- return k(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
496
+ return S(this, { ...e, default: typeof t == "function" ? t : () => c(t) });
487
497
  }
488
498
  /** Create a form model and fill it with a GET request. */
489
499
  getForm(t, e) {
@@ -495,7 +505,7 @@ class H {
495
505
  }
496
506
  createFormModel(t, e, s) {
497
507
  const r = typeof s == "string" ? { path: s } : { ...s ?? {} };
498
- return k(this, r, { url: e, method: t });
508
+ return S(this, r, { url: e, method: t });
499
509
  }
500
510
  // --- internals --------------------------------------------------------------
501
511
  trackStart() {
@@ -516,22 +526,22 @@ class H {
516
526
  let s = t;
517
527
  for (const r of this.errorHooks)
518
528
  try {
519
- const o = r(s, e);
520
- o instanceof Error && (s = o);
529
+ const i = r(s, e);
530
+ i instanceof Error && (s = i);
521
531
  } catch {
522
532
  }
523
533
  return s;
524
534
  }
525
535
  }
526
- function P(i = {}) {
527
- return new H(i);
536
+ function M(o = {}) {
537
+ return new J(o);
528
538
  }
529
- const C = P();
539
+ const I = M();
530
540
  export {
531
- H as Apix,
532
- F as ApixError,
533
- L as ApixFormModel,
534
- C as apix,
535
- P as createApix,
536
- C as default
541
+ J as Apix,
542
+ v as ApixError,
543
+ C as ApixFormModel,
544
+ I as apix,
545
+ M as createApix,
546
+ I as default
537
547
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.3.4",
3
+ "version": "0.4.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",