@vue-modeler/model 2.1.1-beta.1 → 2.2.0-beta.1

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/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var A=(r,t,e)=>t in r?m(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var n=(r,t,e)=>A(r,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("vue");class w extends Error{constructor(t,e){super(e.cause.message),this.actionName=t,this.options=e,this.name=this.constructor.name}get cause(){return this.options.cause}throwCause(){throw this.cause}toString(){return this.options.cause.message}}class u extends Error{constructor(t,e){super(t,e),this.message=t,this.options=e,this.name=this.constructor.name}}class p extends u{constructor(t,e,o){super(`Trying to update state of ${t} from ${e} to ${o}`),this.name=this.constructor.name}}class g extends u{constructor(t,e){super(`Unexpected AbortError for the action ${t} in state ${e}`),this.name=this.constructor.name}}const y=r=>r instanceof DOMException&&r.name==="AbortError"||typeof r=="object"&&r!==null&&"message"in r&&r.message==="canceled",s=class s{constructor(t,e){n(this,"name");n(this,"_state",s.possibleState.ready);n(this,"_value",null);n(this,"_args",null);this.model=t,this.actionFunction=e;const o=e.name;if(!(o in t&&typeof t[o]=="function"))throw new u(`Model does not contain method ${o}`);if(typeof e[s.actionFlag]!="function")throw new u(`Method ${o} is not action`);this.name=o}toString(){return this.name}get possibleStates(){return Object.values(s.possibleState)}get state(){return this._state}set state(t){this._state=t,this.model.setActionState(this)}get abortController(){return this.isPending?this._value.abortController:null}get args(){return this._args||[]}get promise(){return this.isPending?this._value.promise:null}get error(){return this.isError?this._value:null}get abortReason(){return this.isAbort?this._value.abortController.signal.reason:null}get isPending(){return this.state===s.possibleState.pending}get isError(){return this.state===s.possibleState.error}get isReady(){return this.state===s.possibleState.ready}get isLock(){return this.state===s.possibleState.lock}get isAbort(){return this.state===s.possibleState.abort}is(...t){return!!t.find(e=>this.state===e)}exec(...t){if(this.is(s.possibleState.lock,s.possibleState.pending))throw new p(this.name,this.state,s.possibleState.pending);const e=[...t];let o=t.length&&t[t.length-1];o instanceof AbortController||(o=new AbortController,e.push(o)),this.state=s.possibleState.pending,this._args=t;const i=this.actionFunction[s.actionFlag].apply(this.model,e);if(!(i instanceof Promise))return this.state=s.possibleState.ready,Promise.resolve();const d=i.then(()=>{this.ready()}).catch(a=>{if(a instanceof u||a instanceof RangeError||a instanceof ReferenceError||a instanceof SyntaxError||a instanceof TypeError||a instanceof URIError||a instanceof EvalError)throw a;const S=y(a);if(S&&!this.is(s.possibleState.pending,s.possibleState.lock))throw new g(this.name,this.state);if(S&&this._value.abortController instanceof AbortController&&this._value.abortController.signal.reason===s.abortedByLock){this.state=s.possibleState.lock,this._value=null;return}if(S){this.state=s.possibleState.abort;return}this.setError(new w(this.name,{cause:a}))});return this._value={promise:d,abortController:o},d}abort(t){return this.isPending?(this._value.abortController.abort(t),this._value.promise):Promise.resolve()}lock(){return this.isPending?this.abort(s.abortedByLock):(this.state=s.possibleState.lock,this._value=null,Promise.resolve())}unlock(){if(!this.isLock)throw new p(this.name,this.state,s.possibleState.ready);return this.ready()}setError(t){if(!this.isPending)throw new p(this.name,this.state,s.possibleState.error);return this.state=s.possibleState.error,this._value=t,this}ready(){return this.state=s.possibleState.ready,this}resetError(){if(!this.error)throw new p(this.name,this.state,s.possibleState.ready);return this.ready()}};n(s,"actionFlag",Symbol("__action_original_method__")),n(s,"possibleState",{pending:"pending",error:"error",lock:"lock",ready:"ready",abort:"abort"}),n(s,"abortedByLock",Symbol("lock"));let c=s;const v=Proxy;function E(r){if(!(r instanceof b))throw new Error("ProtoModel instance is required");return new v(l.shallowReactive(r),{get(e,o,h){const i=Reflect.get(e,o,h),d=typeof i=="function";return d&&c.actionFlag in i&&typeof i[c.actionFlag]=="function"?e.action(i):d?i.bind(e):i}})}const f=class f{constructor(){n(this,"_effectScope",l.effectScope(!0));n(this,"_actions",new WeakMap);n(this,"_actionIds",new WeakMap);n(this,"_actionStates",new Map);n(this,"_actionsSize",0);n(this,"_watchStopHandlers",new Set)}static model(...t){if(this.prototype===f.prototype)throw new Error("ProtoModel is abstract class and can not be instantiated");const e=new this(...t);return f.createModel(e)}get hasPendingActions(){return!!this.getActionStatesRef(c.possibleState.pending).value}get hasActionWithError(){return!!this.getActionStatesRef(c.possibleState.error).value}watch(...t){if(t.length===0)throw new Error("watch requires at least one argument");const e=t.length===1?this._effectScope.run(()=>l.watchEffect(t[0])):this._effectScope.run(()=>l.watch(...t));if(!e)throw new Error("watchStopHandler is undefined");return this._watchStopHandlers.add(e),()=>{e(),this._watchStopHandlers.delete(e)}}computed(t,e){return this._effectScope.run(()=>l.computed(t,e))}updateBit(t,e,o){const h=o?1:0,i=~(1<<e);return t&i|h<<e}createAction(t){const e=l.shallowReactive(new c(this,t));return this._actions.set(t,e),this._actionIds.set(e,++this._actionsSize),this.setActionState(e),e}getActionStatesRef(t){const e=this._actionStates.get(t)||l.ref(0);return this._actionStates.get(t)===void 0&&this._actionStates.set(t,e),e}action(t){if(!(c.actionFlag in t&&typeof t[c.actionFlag]=="function"))throw new u("Action decorator is not applied to the method");return this._actions.get(t)||this.createAction(t)}setActionState(t){const e=this._actionIds.get(t);if(!e)throw new Error("Action not found");for(const o of t.possibleStates)o!==t.state&&(this.getActionStatesRef(o).value=this.updateBit(this.getActionStatesRef(o).value,e,!1));this.getActionStatesRef(t.state).value=this.updateBit(this.getActionStatesRef(t.state).value,e,!0)}isModelOf(t){return this instanceof t}destructor(){this._watchStopHandlers.forEach(t=>{t()}),this._watchStopHandlers=new Set,this._effectScope.stop()}};n(f,"createModel",E);let b=f;function k(r,t){if(t.static)throw new Error("Action decorator is not supported for static methods");if(t.private)throw new Error("Action decorator is not supported for private methods");const e=t.name.toString(),o={[e]:function(...h){return this.action(o[e]).exec(...h)}};return o[e][c.actionFlag]=r,o[e]}exports.ActionError=w;exports.ActionInternalError=u;exports.ActionStatusConflictError=p;exports.ActionUnexpectedAbortError=g;exports.ProtoModel=b;exports.action=k;
1
+ "use strict";var $=Object.defineProperty;var B=(r,t,e)=>t in r?$(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var n=(r,t,e)=>B(r,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("vue");class K extends Error{constructor(t,e){super(e.cause.message),this.actionName=t,this.options=e,this.name=this.constructor.name}get cause(){return this.options.cause}throwCause(){throw this.cause}toString(){return this.options.cause.message}}class u extends Error{constructor(t,e){super(t,e),this.message=t,this.options=e,this.name=this.constructor.name}}class b extends u{constructor(t,e,o){super(`Trying to update state of ${t} from ${e} to ${o}`),this.name=this.constructor.name}}class L extends u{constructor(t,e){super(`Unexpected AbortError for the action ${t} in state ${e}`),this.name=this.constructor.name}}const T=r=>r instanceof DOMException&&r.name==="AbortError"||typeof r=="object"&&r!==null&&"message"in r&&r.message==="canceled",s=class s{constructor(t,e,o){n(this,"name");n(this,"_state",s.possibleState.ready);n(this,"_value",null);n(this,"_args",null);this._model=t,this.actionFunction=e,this.modelGetter=o;const i=e.name;if(!(i in this._model&&typeof this._model[i]=="function"))throw new u(`Model does not contain method ${i}`);if(typeof e[s.actionFlag]!="function")throw new u(`Method ${i} is not action`);this.name=i}static create(t,e,o){return h.shallowReactive(new s(t,e,o))}toString(){return this.name}get owner(){return this.modelGetter()}get possibleStates(){return Object.values(s.possibleState)}get state(){return this._state}set state(t){this._state=t,this._model.setActionState(this)}get abortController(){return this.isPending?this._value.abortController:null}get args(){return this._args||[]}get promise(){return this.isPending?this._value.promise:null}get error(){return this.isError?this._value:null}get abortReason(){return this.isAbort?this._value.abortController.signal.reason:null}get isPending(){return this.state===s.possibleState.pending}get isError(){return this.state===s.possibleState.error}get isReady(){return this.state===s.possibleState.ready}get isLock(){return this.state===s.possibleState.lock}get isAbort(){return this.state===s.possibleState.abort}is(...t){return!!t.find(e=>this.state===e)}exec(...t){if(this.is(s.possibleState.lock,s.possibleState.pending))throw new b(this.name,this.state,s.possibleState.pending);const e=[...t];let o=t.length&&t[t.length-1];o instanceof AbortController||(o=new AbortController,e.push(o)),this.state=s.possibleState.pending,this._args=t;const a=this.actionFunction[s.actionFlag].apply(this._model,e);if(!(a instanceof Promise))return this.state=s.possibleState.ready,Promise.resolve();const d=a.then(()=>{this.ready()}).catch(c=>{if(c instanceof u||c instanceof RangeError||c instanceof ReferenceError||c instanceof SyntaxError||c instanceof TypeError||c instanceof URIError||c instanceof EvalError)throw c;const y=T(c);if(y&&!this.is(s.possibleState.pending,s.possibleState.lock))throw new L(this.name,this.state);if(y&&this._value.abortController instanceof AbortController&&this._value.abortController.signal.reason===s.abortedByLock){this.state=s.possibleState.lock,this._value=null;return}if(y){this.state=s.possibleState.abort;return}this.setError(new K(this.name,{cause:c}))});return this._value={promise:d,abortController:o},d}abort(t){return this.isPending?(this._value.abortController.abort(t),this._value.promise):Promise.resolve()}lock(){return this.isPending?this.abort(s.abortedByLock):(this.state=s.possibleState.lock,this._value=null,Promise.resolve())}unlock(){if(!this.isLock)throw new b(this.name,this.state,s.possibleState.ready);return this.ready()}setError(t){if(!this.isPending)throw new b(this.name,this.state,s.possibleState.error);return this.state=s.possibleState.error,this._value=t,this}ready(){return this.state=s.possibleState.ready,this}resetError(){if(!this.error)throw new b(this.name,this.state,s.possibleState.ready);return this.ready()}};n(s,"actionFlag",Symbol("__action_original_method__")),n(s,"possibleState",{pending:"pending",error:"error",lock:"lock",ready:"ready",abort:"abort"}),n(s,"abortedByLock",Symbol("lock"));let l=s;const D=Proxy;function I(r){if(!(r instanceof g))throw new Error("ProtoModel instance is required");return new D(h.shallowReactive(r),{get(e,o,i){const a=Reflect.get(e,o,i),d=typeof a=="function";return d&&l.actionFlag in a&&typeof a[l.actionFlag]=="function"?e.action(a):d?a.bind(e):a}})}const p=Symbol("scope"),S=Symbol("model"),A=Symbol("actions"),v=Symbol("actionIds"),w=Symbol("actionStates"),E=Symbol("actionsSize"),f=Symbol("watchStopHandlers");var k,M,P,R,C,x,F;F=p,x=S,C=A,R=v,P=w,M=E,k=f;const m=class m{constructor(){n(this,F,h.effectScope(!0));n(this,x,null);n(this,C,new WeakMap);n(this,R,new WeakMap);n(this,P,new Map);n(this,M,0);n(this,k,new Set)}static model(...t){if(this.prototype===m.prototype)throw new Error("ProtoModel is abstract class and can not be instantiated");const e=new this(...t),o=m.createModel(e);return e[S]=o,o}get hasPendingActions(){return!!this.getActionStatesRef(l.possibleState.pending).value}get hasActionWithError(){return!!this.getActionStatesRef(l.possibleState.error).value}watch(...t){if(t.length===0)throw new Error("watch requires at least one argument");const e=t.length===1?this[p].run(()=>h.watchEffect(t[0])):this[p].run(()=>h.watch(...t));if(!e)throw new Error("watchStopHandler is undefined");return this[f].add(e),()=>{e(),this[f].delete(e)}}computed(t,e){return this[p].run(()=>h.computed(t,e))}updateBit(t,e,o){const i=o?1:0,a=~(1<<e);return t&a|i<<e}createAction(t){const e=()=>{if(!this[S])throw new Error("Model not set");return this[S]},o=l.create(this,t,e);return this[A].set(t,o),this[v].set(o,++this[E]),this.setActionState(o),o}getActionStatesRef(t){const e=this[w].get(t)||h.ref(0);return this[w].get(t)===void 0&&this[w].set(t,e),e}action(t){if(!(l.actionFlag in t&&typeof t[l.actionFlag]=="function"))throw new u("Action decorator is not applied to the method");return this[A].get(t)||this.createAction(t)}setActionState(t){const e=this[v].get(t);if(!e)throw new Error("Action not found");for(const o of t.possibleStates)o!==t.state&&(this.getActionStatesRef(o).value=this.updateBit(this.getActionStatesRef(o).value,e,!1));this.getActionStatesRef(t.state).value=this.updateBit(this.getActionStatesRef(t.state).value,e,!0)}isModelOf(t){return this instanceof t}destructor(){this[f].forEach(t=>{t()}),this[f]=new Set,this[p].stop()}};n(m,"createModel",I);let g=m;function O(r,t){if(t.static)throw new Error("Action decorator is not supported for static methods");if(t.private)throw new Error("Action decorator is not supported for private methods");const e=t.name.toString(),o={[e]:function(...i){return this.action(o[e]).exec(...i)}};return o[e][l.actionFlag]=r,o[e]}exports.ActionError=K;exports.ActionInternalError=u;exports.ActionStatusConflictError=b;exports.ActionUnexpectedAbortError=L;exports.ProtoModel=g;exports.action=O;
package/dist/index.d.ts CHANGED
@@ -6,9 +6,42 @@ import { Ref } from 'vue';
6
6
  import { ShallowReactive } from 'vue';
7
7
  import { WatchStopHandle } from 'vue';
8
8
 
9
- declare class Action<Args extends any[] = unknown[]> {
10
- protected model: ProtoModel;
9
+ export declare type Action<T extends ProtoModel, Args extends any[] = unknown[]> = Omit<ActionInner<T, Args>, 'call'>;
10
+
11
+ export declare function action<T extends ProtoModel, Args extends unknown[]>(originalMethod: (this: T, ...args: Args) => Promise<void>, context: ClassMethodDecoratorContext<T, (this: T, ...args: Args) => Promise<void>>): OriginalMethodWrapper<Args>;
12
+
13
+ /**
14
+ * IMPORTANT: this class looks like error,
15
+ * but it is an exception in the correct terminology "errors vs exceptions".
16
+ *
17
+ * In other words, this is a class of errors that must be handled
18
+ * and displayed to the user as messages in UI layer.
19
+ */
20
+ export declare class ActionError extends Error {
21
+ protected actionName: string;
22
+ protected options: {
23
+ cause: Error;
24
+ };
25
+ constructor(actionName: string, options: {
26
+ cause: Error;
27
+ });
28
+ get cause(): Error;
29
+ throwCause(): void;
30
+ toString(): string;
31
+ }
32
+
33
+ declare const actionIdsKey: unique symbol;
34
+
35
+ /**
36
+ * We should to use here `<T extends ProtoModel>` because
37
+ * we need some methods from `ProtoModel` class which are protected in context of `Model<T>`.
38
+ * For example, `setActionState` method.
39
+ * @see `ProtoModel.setActionState`
40
+ */
41
+ declare class ActionInner<T extends ProtoModel, Args extends any[] = unknown[]> {
42
+ protected _model: T;
11
43
  protected actionFunction: OriginalMethodWrapper<Args>;
44
+ protected modelGetter: () => Model<T>;
12
45
  static readonly actionFlag: unique symbol;
13
46
  static readonly possibleState: {
14
47
  readonly pending: "pending";
@@ -22,9 +55,11 @@ declare class Action<Args extends any[] = unknown[]> {
22
55
  protected _state: ActionStateName;
23
56
  protected _value: ActionValue;
24
57
  protected _args: Args | null;
25
- constructor(model: ProtoModel, // TODO: thing about this arg, it may be potential problem
26
- actionFunction: OriginalMethodWrapper<Args>);
58
+ constructor(_model: T, // TODO: thing about this arg, it may be potential problem
59
+ actionFunction: OriginalMethodWrapper<Args>, modelGetter: () => Model<T>);
60
+ static create<T extends ProtoModel, Args extends unknown[] = unknown[]>(model: T, actionFunction: OriginalMethodWrapper<Args>, modelGetter: () => Model<T>): ActionInner<T, Args>;
27
61
  toString(): string;
62
+ get owner(): Model<T>;
28
63
  get possibleStates(): ActionStateName[];
29
64
  get state(): ActionStateName;
30
65
  protected set state(newState: ActionStateName);
@@ -51,28 +86,6 @@ declare class Action<Args extends any[] = unknown[]> {
51
86
  resetError(): this;
52
87
  }
53
88
 
54
- export declare function action<T extends ProtoModel, Args extends unknown[]>(originalMethod: (this: T, ...args: Args) => Promise<void>, context: ClassMethodDecoratorContext<T, (this: T, ...args: Args) => Promise<void>>): OriginalMethodWrapper<Args>;
55
-
56
- /**
57
- * IMPORTANT: this class looks like error,
58
- * but it is an exception in the correct terminology "errors vs exceptions".
59
- *
60
- * In other words, this is a class of errors that must be handled
61
- * and displayed to the user as messages in UI layer.
62
- */
63
- export declare class ActionError extends Error {
64
- protected actionName: string;
65
- protected options: {
66
- cause: Error;
67
- };
68
- constructor(actionName: string, options: {
69
- cause: Error;
70
- });
71
- get cause(): Error;
72
- throwCause(): void;
73
- toString(): string;
74
- }
75
-
76
89
  /**
77
90
  * IMPORTANT: this class is an error in the correct terminology "errors vs exceptions".
78
91
  *
@@ -96,9 +109,13 @@ declare interface ActionPendingValue {
96
109
  abortController: AbortController;
97
110
  }
98
111
 
99
- export declare type ActionPublic = Omit<Action, 'call'>;
112
+ declare const actionsKey: unique symbol;
113
+
114
+ declare const actionsSizeKey: unique symbol;
115
+
116
+ export declare type ActionStateName = keyof typeof ActionInner.possibleState;
100
117
 
101
- export declare type ActionStateName = keyof typeof Action.possibleState;
118
+ declare const actionStatesKey: unique symbol;
102
119
 
103
120
  export declare class ActionStatusConflictError extends ActionInternalError {
104
121
  constructor(actionName: string, currentState: ActionStateName, newState: ActionStateName);
@@ -137,8 +154,8 @@ declare type ActionValue = ActionPendingValue | ActionError | null;
137
154
  */
138
155
  declare function createModel<Target extends ProtoModel>(protoModel: Target): Model<Target>;
139
156
 
140
- export declare type Model<T> = {
141
- [K in keyof T]: T[K] extends ((...args: infer Args) => Promise<void>) ? Action<Args> : K extends ProtectedMethodInModel ? never : T[K];
157
+ export declare type Model<T extends ProtoModel> = {
158
+ [K in keyof T]: T[K] extends ((...args: infer Args) => Promise<void>) ? Action<T, Args> : K extends ProtectedMethodInModel ? never : T[K];
142
159
  };
143
160
 
144
161
  export declare type ModelAdapterProxyConstructor = new <Target extends ProtoModel>(target: Target, handler: ProxyHandler<Target>) => Model<Target>;
@@ -147,22 +164,25 @@ export declare type ModelConstructor<T extends new (...args: unknown[]) => unkno
147
164
 
148
165
  declare type ModelConstructor_2 = new (...args: any[]) => ProtoModel;
149
166
 
167
+ declare const modelKey: unique symbol;
168
+
150
169
  export declare type OriginalMethod = (...args: any[]) => Promise<void>;
151
170
 
152
- export declare interface OriginalMethodWrapper<Args extends unknown[] = unknown[]> {
171
+ export declare interface OriginalMethodWrapper<Args extends any[] = unknown[]> {
153
172
  (...args: Args): Promise<void>;
154
- [Action.actionFlag]: OriginalMethod;
173
+ [ActionInner.actionFlag]: OriginalMethod;
155
174
  }
156
175
 
157
176
  export declare type ProtectedMethodInModel = 'action' | 'setActionState';
158
177
 
159
178
  export declare abstract class ProtoModel {
160
- protected _effectScope: EffectScope;
161
- protected _actions: WeakMap<OriginalMethodWrapper<unknown[]>, ShallowReactive<ActionPublic>>;
162
- protected _actionIds: WeakMap<ShallowReactive<ActionPublic>, number>;
163
- protected _actionStates: Map<"error" | "abort" | "lock" | "pending" | "ready", Ref<number>>;
164
- protected _actionsSize: number;
165
- protected _watchStopHandlers: Set<WatchStopHandle>;
179
+ protected [scopeKey]: EffectScope;
180
+ protected [modelKey]: Model<this> | null;
181
+ protected [actionsKey]: WeakMap<OriginalMethodWrapper<unknown[]>, ShallowReactive<Action<this>>>;
182
+ protected [actionIdsKey]: WeakMap<ShallowReactive<Action<this>>, number>;
183
+ protected [actionStatesKey]: Map<"error" | "abort" | "lock" | "pending" | "ready", Ref<number>>;
184
+ protected [actionsSizeKey]: number;
185
+ protected [watchStopHandlersKey]: Set<WatchStopHandle>;
166
186
  protected static createModel: typeof createModel;
167
187
  /**
168
188
  * Creates a model instance.
@@ -233,7 +253,7 @@ export declare abstract class ProtoModel {
233
253
  protected watch(...args: unknown[]): WatchStopHandle;
234
254
  protected computed<T>(getter: ComputedGetter<T>, debugOptions?: DebuggerOptions): ComputedRef<T>;
235
255
  protected updateBit(number: number, bitPosition: number, bitValue: boolean): number;
236
- protected createAction(actionFunction: OriginalMethodWrapper): ShallowReactive<ActionPublic>;
256
+ protected createAction(actionFunction: OriginalMethodWrapper): ShallowReactive<Action<this>>;
237
257
  protected getActionStatesRef(stateName: ActionStateName): Ref<number>;
238
258
  /**
239
259
  * Gets Action instance by wrapped original method or create Action instance.
@@ -278,16 +298,20 @@ export declare abstract class ProtoModel {
278
298
  * @param originalMethod - defined as OriginalMethod or OriginalMethodWrapper.
279
299
  * @returns action
280
300
  */
281
- protected action(originalMethod: OriginalMethod | OriginalMethodWrapper): ShallowReactive<ActionPublic>;
301
+ protected action(originalMethod: OriginalMethod | OriginalMethodWrapper): ShallowReactive<Action<this>>;
282
302
  /**
283
303
  * It is public method in context ProtoModel,
284
304
  * but in Model<ProtoModel> context it is protected method
285
305
  *
286
306
  * @see type Model<T>
287
307
  */
288
- setActionState(action: Action): void;
308
+ setActionState(action: Action<this>): void;
289
309
  isModelOf(typeModel: ModelConstructor_2): boolean;
290
310
  destructor(): void;
291
311
  }
292
312
 
313
+ declare const scopeKey: unique symbol;
314
+
315
+ declare const watchStopHandlersKey: unique symbol;
316
+
293
317
  export { }
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var w = Object.defineProperty;
2
- var m = (r, t, e) => t in r ? w(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
- var n = (r, t, e) => m(r, typeof t != "symbol" ? t + "" : t, e);
4
- import { shallowReactive as S, effectScope as g, watchEffect as A, watch as y, computed as v, ref as k } from "vue";
5
- class E extends Error {
1
+ var K = Object.defineProperty;
2
+ var L = (r, t, e) => t in r ? K(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
+ var n = (r, t, e) => L(r, typeof t != "symbol" ? t + "" : t, e);
4
+ import { shallowReactive as F, effectScope as $, watchEffect as B, watch as D, computed as T, ref as H } from "vue";
5
+ class I extends Error {
6
6
  constructor(t, e) {
7
7
  super(e.cause.message), this.actionName = t, this.options = e, this.name = this.constructor.name;
8
8
  }
@@ -21,33 +21,39 @@ class l extends Error {
21
21
  super(t, e), this.message = t, this.options = e, this.name = this.constructor.name;
22
22
  }
23
23
  }
24
- class d extends l {
24
+ class b extends l {
25
25
  constructor(t, e, o) {
26
26
  super(`Trying to update state of ${t} from ${e} to ${o}`), this.name = this.constructor.name;
27
27
  }
28
28
  }
29
- class M extends l {
29
+ class O extends l {
30
30
  constructor(t, e) {
31
31
  super(`Unexpected AbortError for the action ${t} in state ${e}`), this.name = this.constructor.name;
32
32
  }
33
33
  }
34
- const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof r == "object" && r !== null && "message" in r && r.message === "canceled", s = class s {
35
- constructor(t, e) {
34
+ const j = (r) => r instanceof DOMException && r.name === "AbortError" || typeof r == "object" && r !== null && "message" in r && r.message === "canceled", s = class s {
35
+ constructor(t, e, o) {
36
36
  n(this, "name");
37
37
  n(this, "_state", s.possibleState.ready);
38
38
  n(this, "_value", null);
39
39
  n(this, "_args", null);
40
- this.model = t, this.actionFunction = e;
41
- const o = e.name;
42
- if (!(o in t && typeof t[o] == "function"))
43
- throw new l(`Model does not contain method ${o}`);
40
+ this._model = t, this.actionFunction = e, this.modelGetter = o;
41
+ const i = e.name;
42
+ if (!(i in this._model && typeof this._model[i] == "function"))
43
+ throw new l(`Model does not contain method ${i}`);
44
44
  if (typeof e[s.actionFlag] != "function")
45
- throw new l(`Method ${o} is not action`);
46
- this.name = o;
45
+ throw new l(`Method ${i} is not action`);
46
+ this.name = i;
47
+ }
48
+ static create(t, e, o) {
49
+ return F(new s(t, e, o));
47
50
  }
48
51
  toString() {
49
52
  return this.name;
50
53
  }
54
+ get owner() {
55
+ return this.modelGetter();
56
+ }
51
57
  get possibleStates() {
52
58
  return Object.values(s.possibleState);
53
59
  }
@@ -55,7 +61,7 @@ const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof
55
61
  return this._state;
56
62
  }
57
63
  set state(t) {
58
- this._state = t, this.model.setActionState(this);
64
+ this._state = t, this._model.setActionState(this);
59
65
  }
60
66
  get abortController() {
61
67
  return this.isPending ? this._value.abortController : null;
@@ -96,7 +102,7 @@ const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof
96
102
  */
97
103
  exec(...t) {
98
104
  if (this.is(s.possibleState.lock, s.possibleState.pending))
99
- throw new d(
105
+ throw new b(
100
106
  this.name,
101
107
  this.state,
102
108
  s.possibleState.pending
@@ -104,26 +110,26 @@ const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof
104
110
  const e = [...t];
105
111
  let o = t.length && t[t.length - 1];
106
112
  o instanceof AbortController || (o = new AbortController(), e.push(o)), this.state = s.possibleState.pending, this._args = t;
107
- const i = this.actionFunction[s.actionFlag].apply(this.model, e);
108
- if (!(i instanceof Promise))
113
+ const a = this.actionFunction[s.actionFlag].apply(this._model, e);
114
+ if (!(a instanceof Promise))
109
115
  return this.state = s.possibleState.ready, Promise.resolve();
110
- const u = i.then(() => {
116
+ const u = a.then(() => {
111
117
  this.ready();
112
- }).catch((a) => {
113
- if (a instanceof l || a instanceof RangeError || a instanceof ReferenceError || a instanceof SyntaxError || a instanceof TypeError || a instanceof URIError || a instanceof EvalError)
114
- throw a;
115
- const f = P(a);
116
- if (f && !this.is(s.possibleState.pending, s.possibleState.lock))
117
- throw new M(this.name, this.state);
118
- if (f && this._value.abortController instanceof AbortController && this._value.abortController.signal.reason === s.abortedByLock) {
118
+ }).catch((c) => {
119
+ if (c instanceof l || c instanceof RangeError || c instanceof ReferenceError || c instanceof SyntaxError || c instanceof TypeError || c instanceof URIError || c instanceof EvalError)
120
+ throw c;
121
+ const w = j(c);
122
+ if (w && !this.is(s.possibleState.pending, s.possibleState.lock))
123
+ throw new O(this.name, this.state);
124
+ if (w && this._value.abortController instanceof AbortController && this._value.abortController.signal.reason === s.abortedByLock) {
119
125
  this.state = s.possibleState.lock, this._value = null;
120
126
  return;
121
127
  }
122
- if (f) {
128
+ if (w) {
123
129
  this.state = s.possibleState.abort;
124
130
  return;
125
131
  }
126
- this.setError(new E(this.name, { cause: a }));
132
+ this.setError(new I(this.name, { cause: c }));
127
133
  });
128
134
  return this._value = {
129
135
  promise: u,
@@ -141,7 +147,7 @@ const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof
141
147
  }
142
148
  unlock() {
143
149
  if (!this.isLock)
144
- throw new d(
150
+ throw new b(
145
151
  this.name,
146
152
  this.state,
147
153
  s.possibleState.ready
@@ -150,7 +156,7 @@ const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof
150
156
  }
151
157
  setError(t) {
152
158
  if (!this.isPending)
153
- throw new d(
159
+ throw new b(
154
160
  this.name,
155
161
  this.state,
156
162
  s.possibleState.error
@@ -162,7 +168,7 @@ const P = (r) => r instanceof DOMException && r.name === "AbortError" || typeof
162
168
  }
163
169
  resetError() {
164
170
  if (!this.error)
165
- throw new d(
171
+ throw new b(
166
172
  this.name,
167
173
  this.state,
168
174
  s.possibleState.ready
@@ -177,33 +183,37 @@ n(s, "actionFlag", Symbol("__action_original_method__")), n(s, "possibleState",
177
183
  ready: "ready",
178
184
  abort: "abort"
179
185
  }), n(s, "abortedByLock", Symbol("lock"));
180
- let c = s;
181
- const _ = Proxy;
182
- function R(r) {
183
- if (!(r instanceof b))
186
+ let h = s;
187
+ const z = Proxy;
188
+ function G(r) {
189
+ if (!(r instanceof A))
184
190
  throw new Error("ProtoModel instance is required");
185
- return new _(
186
- S(r),
191
+ return new z(
192
+ F(r),
187
193
  {
188
- get(e, o, h) {
189
- const i = Reflect.get(e, o, h), u = typeof i == "function";
190
- return u && c.actionFlag in i && typeof i[c.actionFlag] == "function" ? e.action(i) : u ? i.bind(e) : i;
194
+ get(e, o, i) {
195
+ const a = Reflect.get(e, o, i), u = typeof a == "function";
196
+ return u && h.actionFlag in a && typeof a[h.actionFlag] == "function" ? e.action(a) : u ? a.bind(e) : a;
191
197
  }
192
198
  }
193
199
  );
194
200
  }
195
- const p = class p {
201
+ const d = Symbol("scope"), m = Symbol("model"), g = Symbol("actions"), y = Symbol("actionIds"), S = Symbol("actionStates"), v = Symbol("actionsSize"), p = Symbol("watchStopHandlers");
202
+ var k, E, M, P, R, C, x;
203
+ x = d, C = m, R = g, P = y, M = S, E = v, k = p;
204
+ const f = class f {
196
205
  constructor() {
197
206
  // each model has its own effect scope to avoid memory leaks
198
- n(this, "_effectScope", g(!0));
207
+ n(this, x, $(!0));
208
+ n(this, C, null);
199
209
  // we use WeakMap to store actions as keys to avoid memory leaks
200
- n(this, "_actions", /* @__PURE__ */ new WeakMap());
201
- n(this, "_actionIds", /* @__PURE__ */ new WeakMap());
202
- n(this, "_actionStates", /* @__PURE__ */ new Map());
210
+ n(this, R, /* @__PURE__ */ new WeakMap());
211
+ n(this, P, /* @__PURE__ */ new WeakMap());
212
+ n(this, M, /* @__PURE__ */ new Map());
203
213
  // WeakMap doesn't have a size property, so we need to store the size of the map
204
- n(this, "_actionsSize", 0);
214
+ n(this, E, 0);
205
215
  // watchers are stored in a set to avoid memory leaks
206
- n(this, "_watchStopHandlers", /* @__PURE__ */ new Set());
216
+ n(this, k, /* @__PURE__ */ new Set());
207
217
  }
208
218
  /**
209
219
  * Creates a model instance.
@@ -213,16 +223,16 @@ const p = class p {
213
223
  * @see src/create-model.ts
214
224
  */
215
225
  static model(...t) {
216
- if (this.prototype === p.prototype)
226
+ if (this.prototype === f.prototype)
217
227
  throw new Error("ProtoModel is abstract class and can not be instantiated");
218
- const e = new this(...t);
219
- return p.createModel(e);
228
+ const e = new this(...t), o = f.createModel(e);
229
+ return e[m] = o, o;
220
230
  }
221
231
  get hasPendingActions() {
222
- return !!this.getActionStatesRef(c.possibleState.pending).value;
232
+ return !!this.getActionStatesRef(h.possibleState.pending).value;
223
233
  }
224
234
  get hasActionWithError() {
225
- return !!this.getActionStatesRef(c.possibleState.error).value;
235
+ return !!this.getActionStatesRef(h.possibleState.error).value;
226
236
  }
227
237
  /**
228
238
  * Registers watcher in the model effect scope.
@@ -283,28 +293,32 @@ const p = class p {
283
293
  watch(...t) {
284
294
  if (t.length === 0)
285
295
  throw new Error("watch requires at least one argument");
286
- const e = t.length === 1 ? this._effectScope.run(() => A(t[0])) : this._effectScope.run(() => y(...t));
296
+ const e = t.length === 1 ? this[d].run(() => B(t[0])) : this[d].run(() => D(...t));
287
297
  if (!e)
288
298
  throw new Error("watchStopHandler is undefined");
289
- return this._watchStopHandlers.add(e), () => {
290
- e(), this._watchStopHandlers.delete(e);
299
+ return this[p].add(e), () => {
300
+ e(), this[p].delete(e);
291
301
  };
292
302
  }
293
303
  computed(t, e) {
294
- return this._effectScope.run(() => v(t, e));
304
+ return this[d].run(() => T(t, e));
295
305
  }
296
306
  // @see https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/bits/updateBit.js
297
307
  updateBit(t, e, o) {
298
- const h = o ? 1 : 0, i = ~(1 << e);
299
- return t & i | h << e;
308
+ const i = o ? 1 : 0, a = ~(1 << e);
309
+ return t & a | i << e;
300
310
  }
301
311
  createAction(t) {
302
- const e = S(new c(this, t));
303
- return this._actions.set(t, e), this._actionIds.set(e, ++this._actionsSize), this.setActionState(e), e;
312
+ const e = () => {
313
+ if (!this[m])
314
+ throw new Error("Model not set");
315
+ return this[m];
316
+ }, o = h.create(this, t, e);
317
+ return this[g].set(t, o), this[y].set(o, ++this[v]), this.setActionState(o), o;
304
318
  }
305
319
  getActionStatesRef(t) {
306
- const e = this._actionStates.get(t) || k(0);
307
- return this._actionStates.get(t) === void 0 && this._actionStates.set(t, e), e;
320
+ const e = this[S].get(t) || H(0);
321
+ return this[S].get(t) === void 0 && this[S].set(t, e), e;
308
322
  }
309
323
  /**
310
324
  * Gets Action instance by wrapped original method or create Action instance.
@@ -350,9 +364,9 @@ const p = class p {
350
364
  * @returns action
351
365
  */
352
366
  action(t) {
353
- if (!(c.actionFlag in t && typeof t[c.actionFlag] == "function"))
367
+ if (!(h.actionFlag in t && typeof t[h.actionFlag] == "function"))
354
368
  throw new l("Action decorator is not applied to the method");
355
- return this._actions.get(t) || this.createAction(t);
369
+ return this[g].get(t) || this.createAction(t);
356
370
  }
357
371
  /**
358
372
  * It is public method in context ProtoModel,
@@ -361,7 +375,7 @@ const p = class p {
361
375
  * @see type Model<T>
362
376
  */
363
377
  setActionState(t) {
364
- const e = this._actionIds.get(t);
378
+ const e = this[y].get(t);
365
379
  if (!e)
366
380
  throw new Error("Action not found");
367
381
  for (const o of t.possibleStates)
@@ -372,14 +386,14 @@ const p = class p {
372
386
  return this instanceof t;
373
387
  }
374
388
  destructor() {
375
- this._watchStopHandlers.forEach((t) => {
389
+ this[p].forEach((t) => {
376
390
  t();
377
- }), this._watchStopHandlers = /* @__PURE__ */ new Set(), this._effectScope.stop();
391
+ }), this[p] = /* @__PURE__ */ new Set(), this[d].stop();
378
392
  }
379
393
  };
380
- n(p, "createModel", R);
381
- let b = p;
382
- function H(r, t) {
394
+ n(f, "createModel", G);
395
+ let A = f;
396
+ function V(r, t) {
383
397
  if (t.static)
384
398
  throw new Error("Action decorator is not supported for static methods");
385
399
  if (t.private)
@@ -388,17 +402,17 @@ function H(r, t) {
388
402
  // Action constructor checks that model has method with the same name.
389
403
  // We can`t define anonymous function and change name because Function.name is readonly property.
390
404
  // So we need to create stub object to save original method name
391
- [e]: function(...h) {
392
- return this.action(o[e]).exec(...h);
405
+ [e]: function(...i) {
406
+ return this.action(o[e]).exec(...i);
393
407
  }
394
408
  };
395
- return o[e][c.actionFlag] = r, o[e];
409
+ return o[e][h.actionFlag] = r, o[e];
396
410
  }
397
411
  export {
398
- E as ActionError,
412
+ I as ActionError,
399
413
  l as ActionInternalError,
400
- d as ActionStatusConflictError,
401
- M as ActionUnexpectedAbortError,
402
- b as ProtoModel,
403
- H as action
414
+ b as ActionStatusConflictError,
415
+ O as ActionUnexpectedAbortError,
416
+ A as ProtoModel,
417
+ V as action
404
418
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@vue-modeler/model",
4
- "version": "2.1.1-beta.1",
4
+ "version": "2.2.0-beta.1",
5
5
  "description": "A state management library based on models for Vue.js",
6
6
  "author": "abratko",
7
7
  "license": "MIT",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "scripts": {
47
47
  "build": "tsc && vite build",
48
- "test": "vitest",
48
+ "test": "tsc --noEmit && vitest",
49
49
  "coverage": "vitest run --coverage",
50
50
  "semantic-release": "semantic-release"
51
51
  },