@trakit/sync 0.0.20 → 0.0.21
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 +21 -21
- package/Synchronization/TrakitSyncCommander.d.ts +1 -1
- package/WebSocket/Broadcast.d.ts +58 -0
- package/WebSocket/Events.d.ts +8 -0
- package/WebSocket/TrakitSocketCommander.d.ts +4 -0
- package/index.d.ts +1 -1
- package/package.json +40 -40
- package/trakit-sync.min.js +2 -2
package/README.md
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
# Trak-iT API Synchronization
|
|
2
|
-
|
|
3
|
-
This library provides a full suite of tools to keep a local copy of objects from Trak-iT's APIs in-sync. Other Trak-iT API libraries are available on GitHub. https://github.com/trakitwireless
|
|
4
|
-
|
|
5
|
-
### Prerequisites
|
|
6
|
-
|
|
7
|
-
The `@trakit/objects` and `@trakit/commands` packages are required since they contain the definitions for all the commands required to manipulate the objects.
|
|
8
|
-
|
|
9
|
-
In order to build this project, you need to install the RollupJS, and plugins for TypeScript and Minifying.
|
|
10
|
-
```
|
|
11
|
-
npm i rollup rollup-plugin-typescript2 @rollup/plugin-terser
|
|
12
|
-
```
|
|
13
|
-
After those have been installed, build the project normally.
|
|
14
|
-
```
|
|
15
|
-
rollup --config rollup.config.js
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
## Questions and Feedback
|
|
19
|
-
|
|
20
|
-
If you have any questions, please start for the project on GitHub
|
|
21
|
-
https://github.com/trakitwireless/trakit-ts-sync/issues
|
|
1
|
+
# Trak-iT API Synchronization
|
|
2
|
+
|
|
3
|
+
This library provides a full suite of tools to keep a local copy of objects from Trak-iT's APIs in-sync. Other Trak-iT API libraries are available on GitHub. https://github.com/trakitwireless
|
|
4
|
+
|
|
5
|
+
### Prerequisites
|
|
6
|
+
|
|
7
|
+
The `@trakit/objects` and `@trakit/commands` packages are required since they contain the definitions for all the commands required to manipulate the objects.
|
|
8
|
+
|
|
9
|
+
In order to build this project, you need to install the RollupJS, and plugins for TypeScript and Minifying.
|
|
10
|
+
```
|
|
11
|
+
npm i rollup rollup-plugin-typescript2 @rollup/plugin-terser
|
|
12
|
+
```
|
|
13
|
+
After those have been installed, build the project normally.
|
|
14
|
+
```
|
|
15
|
+
rollup --config rollup.config.js
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Questions and Feedback
|
|
19
|
+
|
|
20
|
+
If you have any questions, please start for the project on GitHub
|
|
21
|
+
https://github.com/trakitwireless/trakit-ts-sync/issues
|
|
@@ -124,7 +124,7 @@ export declare class TrakitSyncCommander extends TrakitObjectCommander<any> {
|
|
|
124
124
|
* @param companyId
|
|
125
125
|
* @param types
|
|
126
126
|
*/
|
|
127
|
-
desync(companyId: ulong, types: SyncName[]):
|
|
127
|
+
desync(companyId: ulong, types: SyncName[]): SubscriptionType[];
|
|
128
128
|
/**
|
|
129
129
|
* Subscribes to the specified subscription types for the given company.
|
|
130
130
|
* @param companyId
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { JsonObject } from "@trakit/objects";
|
|
2
|
+
/**
|
|
3
|
+
* The kinds of broadcast messages sent to all connected clients.
|
|
4
|
+
*/
|
|
5
|
+
export declare enum BroadcastType {
|
|
6
|
+
maintenance = "maintenance",
|
|
7
|
+
upgrade = "upgrade"
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A message sent to all connected clients regardless of authentication about the Trak-iT WebSocket.
|
|
11
|
+
* Broadcast messages are used to notify clients of upcoming maintenance or upgrades to the Trak-iT service.
|
|
12
|
+
* The message contains information about the type of broadcast, the server time when the broadcast was sent, and a message describing the broadcast.
|
|
13
|
+
*/
|
|
14
|
+
export declare class Broadcast {
|
|
15
|
+
/**
|
|
16
|
+
* The type of broadcast message, used to identify the kind of broadcast received.
|
|
17
|
+
*/
|
|
18
|
+
kind: BroadcastType;
|
|
19
|
+
/**
|
|
20
|
+
* The UTC date/time of the server hosting the connection.
|
|
21
|
+
*/
|
|
22
|
+
serverTime: Date;
|
|
23
|
+
/**
|
|
24
|
+
* Human readable message describing the broadcast.
|
|
25
|
+
*/
|
|
26
|
+
message: string;
|
|
27
|
+
constructor(json: JsonObject);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Notification to clients of a scheduled maintenance window.
|
|
31
|
+
* During a maintenance window, the service may go down and come back online repeatedly until the window ends.
|
|
32
|
+
*/
|
|
33
|
+
export declare class BroadcastMaintenance extends Broadcast {
|
|
34
|
+
/**
|
|
35
|
+
* Timestamp of when the maintenance window begins.
|
|
36
|
+
*/
|
|
37
|
+
starting: Date;
|
|
38
|
+
/**
|
|
39
|
+
* Timestamp of when the maintenance window ends.
|
|
40
|
+
*/
|
|
41
|
+
ending: Date;
|
|
42
|
+
constructor(json: JsonObject);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Notification to clients that an upgrade will take place (with optional requirement of reloading all resources).
|
|
46
|
+
*/
|
|
47
|
+
export declare class BroadcastUpgrade extends Broadcast {
|
|
48
|
+
/**
|
|
49
|
+
* Timestamp of when the upgrade will be ready.
|
|
50
|
+
*/
|
|
51
|
+
eta: Date;
|
|
52
|
+
/**
|
|
53
|
+
* Indicates whether a reload of all resources is required for the upgrade.
|
|
54
|
+
*/
|
|
55
|
+
reload: boolean;
|
|
56
|
+
constructor(json: JsonObject);
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=Broadcast.d.ts.map
|
package/WebSocket/Events.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Reply } from '@trakit/commands';
|
|
2
2
|
import { JsonObject } from "@trakit/objects";
|
|
3
3
|
import { TrakitEvent } from "../API/Events";
|
|
4
|
+
import { Broadcast } from "./Broadcast";
|
|
4
5
|
/**
|
|
5
6
|
* Represents a message event received from the Trak-iT WebSocket.
|
|
6
7
|
*/
|
|
@@ -25,4 +26,11 @@ export declare class TrakitEventSocketClose extends TrakitEvent {
|
|
|
25
26
|
readonly reply: Reply;
|
|
26
27
|
constructor(type: string, reply: Reply);
|
|
27
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
*
|
|
31
|
+
*/
|
|
32
|
+
export declare class TrakitEventSocketBroadcast extends TrakitEvent {
|
|
33
|
+
broadcast: Broadcast;
|
|
34
|
+
constructor(json: JsonObject);
|
|
35
|
+
}
|
|
28
36
|
//# sourceMappingURL=Events.d.ts.map
|
|
@@ -86,6 +86,10 @@ export declare class TrakitSocketCommander extends TrakitObjectCommander<[string
|
|
|
86
86
|
* Gets invoked any time an error occurs on the WebSocket.
|
|
87
87
|
*/
|
|
88
88
|
_handleError(this: TrakitSocketCommander, reply: Reply): void;
|
|
89
|
+
/**
|
|
90
|
+
* Gets invoked any time a broadcast message is received on the WebSocket.
|
|
91
|
+
*/
|
|
92
|
+
_handleBroadcast(this: TrakitSocketCommander, json: JsonObject): void;
|
|
89
93
|
/**
|
|
90
94
|
* Flag set to specifically allow automatic re-connection to Trak-iT's WebSocket.
|
|
91
95
|
* This value is set to false in the message handler if the connectionResponse message does not have an errorCode zero.
|
package/index.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@trakit/sync",
|
|
3
|
-
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
5
|
-
"main": "./trakit-sync.min.js",
|
|
6
|
-
"types": "./index.d.ts",
|
|
7
|
-
"scripts": {
|
|
8
|
-
"test": "echo \"Error: no test specified\" && exit 1"
|
|
9
|
-
},
|
|
10
|
-
"repository": {
|
|
11
|
-
"type": "git",
|
|
12
|
-
"url": "git+https://github.com/trakitwireless/trakit-ts-sync.git"
|
|
13
|
-
},
|
|
14
|
-
"files": [
|
|
15
|
-
"LICENSE",
|
|
16
|
-
"README.md",
|
|
17
|
-
"**/*.js",
|
|
18
|
-
"**/*.d.ts"
|
|
19
|
-
],
|
|
20
|
-
"keywords": [
|
|
21
|
-
"trakit"
|
|
22
|
-
],
|
|
23
|
-
"author": "Alex Lein",
|
|
24
|
-
"license": "AGPL-3.0-only",
|
|
25
|
-
"bugs": {
|
|
26
|
-
"url": "https://github.com/trakitwireless/trakit-ts-sync/issues"
|
|
27
|
-
},
|
|
28
|
-
"homepage": "https://github.com/trakitwireless/trakit-ts-sync#readme",
|
|
29
|
-
"description": "Trak-iT uses these object definitions to interact with all our APIs.",
|
|
30
|
-
"devDependencies": {
|
|
31
|
-
"@rollup/plugin-terser": "^0.4.4",
|
|
32
|
-
"rollup": "^4.35.0",
|
|
33
|
-
"rollup-plugin-typescript2": "^0.36.0",
|
|
34
|
-
"tsx": "^4.21.0",
|
|
35
|
-
"vitest": "^4.0.7"
|
|
36
|
-
},
|
|
37
|
-
"dependencies": {
|
|
38
|
-
"@trakit/commands": "^0.0.14",
|
|
39
|
-
"@trakit/objects": "^0.0.16"
|
|
40
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@trakit/sync",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.21",
|
|
5
|
+
"main": "./trakit-sync.min.js",
|
|
6
|
+
"types": "./index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/trakitwireless/trakit-ts-sync.git"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"README.md",
|
|
17
|
+
"**/*.js",
|
|
18
|
+
"**/*.d.ts"
|
|
19
|
+
],
|
|
20
|
+
"keywords": [
|
|
21
|
+
"trakit"
|
|
22
|
+
],
|
|
23
|
+
"author": "Alex Lein",
|
|
24
|
+
"license": "AGPL-3.0-only",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/trakitwireless/trakit-ts-sync/issues"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://github.com/trakitwireless/trakit-ts-sync#readme",
|
|
29
|
+
"description": "Trak-iT uses these object definitions to interact with all our APIs.",
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
32
|
+
"rollup": "^4.35.0",
|
|
33
|
+
"rollup-plugin-typescript2": "^0.36.0",
|
|
34
|
+
"tsx": "^4.21.0",
|
|
35
|
+
"vitest": "^4.0.7"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@trakit/commands": "^0.0.14",
|
|
39
|
+
"@trakit/objects": "^0.0.16"
|
|
40
|
+
}
|
|
41
41
|
}
|
package/trakit-sync.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
function e(e,t){return{errorCode:i.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){const t=e.getAction(),s=new Error("no command supported for "+e.constructor.name,{cause:t});switch(t.object){case"Subscription":switch(t.kind){case"Merge":return"subscribe";case"Delete":return"unsubscribe";case"List":return"getSubscriptionsList";default:throw s}case"Self":switch(t.filter){case"Get":return"getSessionDetails";case"Login":case"Logout":return t.filter.toLowerCase();case"Contact":case"Password":case"Preferences":return"updateOwn"+t.filter;default:throw s}case"Session":switch(t.kind){case"Get":case"List":break;case"Delete":return"killSession";default:throw s}break;case"DispatchJob":switch(t.filter){case"Cancel":case"Change":return t.kind.toLocaleLowerCase()+t.object}}switch(t.kind){case"Get":case"Merge":case"Restore":case"Suspend":return t.kind.toLocaleLowerCase()+t.object;case"Delete":return"remove"+t.object;case"Reactivate":return"revive"+t.object;case"List":return"get"+Ys.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function s(e){return e.reduce(((e,t)=>e.concat(gr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function r(e){const t=[];for(const[s,r]of Object.entries(Sr)){const n=r.map((e=>gr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}for(const[s,r]of Object.entries(gr))!Sr[s]&&r.some((t=>e.includes(t)))&&t.push(s);return t}import*as n from"@trakit/commands";import{ErrorCode as i,RepSelfGet as o,ReplySync as a,ReplySyncList as c,ReplySyncGet as h,ReplySyncDelete as u,ReplySyncBatchDelete as d,PaySelfGet as p,PaySelfLogin as l,PaySelfLogout as m,PaySelfContact as w,PaySelfPassword as g,PaySelfPreferences as v,PayCompanyGet as y,PayCompanyMerge as f,PayCompanyDelete as b,PayCompanyRestore as C,PayCompanyGeneralListByCompany as R,PayCompanyGeneralGet as P,PayCompanyPolicyListByCompany as S,PayCompanyPolicyGet as k,PayCompanyStyleListByCompany as A,PayCompanyStyleGet as M,PayCompanyDirectoryListByCompany as D,PayCompanyDirectoryGet as I,PayCompanyResellerGet as T,PayCompanyResellerMerge as G,PayCompanyResellerDelete as U,PayCompanyResellerRestore as B,PayContactListByCompany as J,PayContactGet as E,PayContactMerge as L,PayContactDelete as x,PayContactRestore as _,PayContactBatchMerge as O,PayContactBatchDelete as F,PayUserListByCompany as H,PayUserGet as N,PayUserMerge as q,PayUserDelete as W,PayUserRestore as j,PayUserGeneralListByCompany as $,PayUserGeneralGet as z,PayUserAdvancedListByCompany as K,PayUserAdvancedGet as V,PayUserGroupListByCompany as Z,PayUserGroupGet as Q,PayUserGroupMerge as X,PayUserGroupDelete as Y,PayUserGroupRestore as ee,PayMachineListByCompany as te,PayMachineGet as se,PayMachineMerge as re,PayMachineDelete as ne,PayMachineRestore as ie,PaySessionListByCompany as oe,PaySessionListByUser as ae,PaySessionDelete as ce,PayIconListByCompany as he,PayIconGet as ue,PayIconMerge as de,PayIconDelete as pe,PayIconRestore as le,PayPictureListByCompany as me,PayPictureGet as we,PayPictureMerge as ge,PayPictureDelete as ve,PayPictureRestore as ye,PayDocumentListByCompany as fe,PayDocumentGet as be,PayDocumentMerge as Ce,PayDocumentDelete as Re,PayDocumentRestore as Pe,PayFormTemplateListByCompany as Se,PayFormTemplateGet as ke,PayFormTemplateMerge as Ae,PayFormTemplateDelete as Me,PayFormTemplateRestore as De,PayFormResultListByCompany as Ie,PayFormResultGet as Te,PayFormResultMerge as Ge,PayFormResultBatchMerge as Ue,PayFormResultDelete as Be,PayFormResultRestore as Je,PayDashcamListByCompany as Ee,PayDashcamGet as Le,PayDashcamLiveListByCompany as xe,PayAssetListByCompany as _e,PayAssetGet as Oe,PayAssetMerge as Fe,PayAssetBatchMerge as He,PayAssetDelete as Ne,PayAssetRestore as qe,PayAssetSuspend as We,PayAssetReactivate as je,PayAssetGeneralListByCompany as $e,PayAssetGeneralGet as ze,PayAssetAdvancedListByCompany as Ke,PayAssetAdvancedGet as Ve,PayAssetDispatchMerge as Ze,PayDispatchTaskListByCompany as Qe,PayDispatchTaskListByAsset as Xe,PayDispatchTaskGet as Ye,PayDispatchTaskMerge as et,PayDispatchTaskBatchMerge as tt,PayDispatchTaskDelete as st,PayDispatchTaskRestore as rt,PayDispatchJobListByCompany as nt,PayDispatchJobListByAsset as it,PayDispatchJobGet as ot,PayDispatchJobMerge as at,PayDispatchJobBatchMerge as ct,PayDispatchJobDelete as ht,PayDispatchJobRestore as ut,PayDispatchJobChange as dt,PayDispatchJobCancel as pt,PayAssetMessageListByCompany as lt,PayAssetMessageListByAsset as mt,PayAssetMessageGet as wt,PayAssetMessageMerge as gt,PayAssetMessageBatchMerge as vt,PayAssetMessageDelete as yt,PayAssetMessageRestore as ft,PayPlaceListByCompany as bt,PayPlaceGet as Ct,PayPlaceMerge as Rt,PayPlaceDelete as Pt,PayPlaceRestore as St,PayProviderListByCompany as kt,PayProviderGet as At,PayProviderMerge as Mt,PayProviderBatchMerge as Dt,PayProviderBatchDelete as It,PayProviderDelete as Tt,PayProviderRestore as Gt,PayProviderGeneralListByCompany as Ut,PayProviderGeneralGet as Bt,PayProviderAdvancedListByCompany as Jt,PayProviderAdvancedGet as Et,PayProviderControlListByCompany as Lt,PayProviderControlGet as xt,PayProviderScriptListByCompany as _t,PayProviderScriptGet as Ot,PayProviderScriptMerge as Ft,PayProviderScriptDelete as Ht,PayProviderScriptRestore as Nt,PayProviderConfigListByCompany as qt,PayProviderConfigGet as Wt,PayProviderConfigMerge as jt,PayProviderConfigBatchMerge as $t,PayProviderConfigDelete as zt,PayProviderConfigRestore as Kt,PayProviderConfigurationListByCompany as Vt,PayProviderConfigurationGet as Zt,PayProviderConfigurationMerge as Qt,PayProviderConfigurationBatchMerge as Xt,PayProviderConfigurationDelete as Yt,PayProviderConfigurationRestore as es,PayProviderRegistrationListByCompany as ts,PayProviderRegistrationGet as ss,PayProviderRegistrationMerge as rs,PayProviderRegistrationDelete as ns,PayBehaviourListByCompany as is,PayBehaviourGet as os,PayBehaviourMerge as as,PayBehaviourBatchMerge as cs,PayBehaviourDelete as hs,PayBehaviourRestore as us,PayBehaviourScriptListByCompany as ds,PayBehaviourScriptGet as ps,PayBehaviourScriptMerge as ls,PayBehaviourScriptDelete as ms,PayBehaviourScriptRestore as ws,PayBehaviourLogListByAsset as gs,PayBehaviourLogBatchDeleteByAsset as vs,PayBehaviourLogListByBehaviour as ys,PayBehaviourLogBatchDeleteByBehaviour as fs,PayBehaviourLogListByScript as bs,PayBehaviourLogBatchDeleteByScript as Cs,PayReportTemplateListByCompany as Rs,PayReportTemplateGet as Ps,PayReportTemplateMerge as Ss,PayReportTemplateDelete as ks,PayReportTemplateRestore as As,PayReportScheduleListByCompany as Ms,PayReportScheduleGet as Ds,PayReportScheduleMerge as Is,PayReportScheduleDelete as Ts,PayReportScheduleRestore as Gs,PayReportResultListByCompany as Us,PayReportResultGet as Bs,PayReportResultMerge as Js,PayReportResultDelete as Es,PayReportResultRestore as Ls,PayMaintenanceScheduleListByCompany as xs,PayMaintenanceScheduleGet as _s,PayMaintenanceScheduleMerge as Os,PayMaintenanceScheduleDelete as Fs,PayMaintenanceScheduleRestore as Hs,PayMaintenanceJobListByCompany as Ns,PayMaintenanceJobGet as qs,PayMaintenanceJobMerge as Ws,PayMaintenanceJobDelete as js,PayMaintenanceJobRestore as $s,SubscriptionType as zs,Reply as Ks,PaySubscriptionMerge as Vs,RepSubscription as Zs,PaySubscriptionDelete as Qs,PaySubscriptionList as Xs}from"@trakit/commands";import{utility as Ys,Machine as er,serialization as tr}from"@trakit/objects";class sr{type;constructor(e){this.type=e}}class rr extends sr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class nr extends sr{account;constructor(e){super("account"),this.account=e}}class ir extends rr{objects;constructor(e,t,s){super("list",e,t),this.objects=s}}class or extends rr{object;constructor(e,t,s){super("update",e,t),this.object=s}}class ar extends rr{key;constructor(e,t,s){super("delete",e,t),this.key=s}}class cr{account;baseAddress;query=new Map;headers=new Map;createBaseUrl(e){const t=this.baseAddress?new URL(e??"",this.baseAddress):new URL(e),s=new Map(this.query);for(const[e,r]of s)t.searchParams.append(e,r);return t}constructor(e,t){this.baseAddress=t?new URL(t):null,this.setAuth(e)}setAuth(e){e instanceof o?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof er||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new o({errorCode:i.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new o)}command(t){return new Promise((async(s,r)=>{let n=null,o=null,a=null;try{n=this.t(t)}catch(t){o=e(t)}try{o=o??await this.i(n)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===i.success?s:r)(a)}))}}class hr extends cr{o=new Map;h(e){this.fire("account",(()=>new nr(e)))}u(e,t,s){this.fire("list",(()=>new ir(e,t,s)))}p(e,t,s){this.fire("update",(()=>new or(e,t,s)))}l(e,t,s){this.fire("delete",(()=>new ar(e,t,s)))}on(e,t){let s=this.o.get(e);s||this.o.set(e,s=[]);const r=s.includes(t);return r||s.push(t),!r}off(e,t){const s=this.o.get(e);if(s?.length){if(t){const e=s.indexOf(t);return!!(e>-1&&s.splice(e,1))}return!(s.length=0)}return!1}fire(e,t){const s=this.o.get(e);if(s?.length){const e=t();s.forEach((t=>t.call(this,e)),this)}}handles(e,t){return this.o.get(e)?.includes(t)??!1}dispose(){for(const e of[...this.o.keys()])this.off(e)}async command(e){const t=await super.command(e);if(t instanceof a&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof c?s.filter?t.getList().forEach((e=>this.p(s.object,r,e))):this.u(s.object,r,t.getList()):t instanceof h?this.p(s.object,r,t.getObject()):t instanceof u?this.l(s.object,r,t.getKey()):t instanceof d&&t.getResults().forEach((e=>this.l(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new p);return this.setAuth(e),this.h(e),e}async login(e,t,s){const r=await this.command(new l({username:e,password:t,userAgent:s??null}));return this.setAuth(r),this.h(r),r}logout(){const e=this.command(new m);return this.setAuth(),this.h(this.account),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new w({contact:{name:e??null,notes:t??null,otherNames:s??null,emails:r??null,phones:n??null,addresses:i??null,urls:o??null,dates:a??null,options:c??null,roles:h??null,pictures:u??null}}))}updatePassword(e,t){return this.command(new g({current:e,password:t}))}updatePreferences(e,t,s,r,n,i){return this.command(new v({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?tr.fromMap(r):r??null,measurements:n instanceof Map?tr.fromMap(n):n??null,options:i instanceof Map?tr.fromMap(i):i??null}))}getCompany(e){return this.command(new y({company:{id:e}}))}mergeCompany(e){return this.command(new f({company:e}))}removeCompany(e){return this.command(new b({company:{id:e}}))}restoreCompany(e){return this.command(new C({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new R({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new P({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new S({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new k({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new A({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new M({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new D({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new I({company:{id:e}}))}getReseller(e){return this.command(new T({company:{id:e}}))}mergeReseller(e){return this.command(new G({company:e}))}removeReseller(e){return this.command(new U({company:{id:e}}))}restoreReseller(e){return this.command(new B({company:{id:e}}))}listContacts(e,t){return this.command(new J({...t,company:{id:e}}))}getContact(e){return this.command(new E({contact:{id:e}}))}mergeContact(e){return this.command(new L({contact:e}))}removeContact(e){return this.command(new x({contact:{id:e}}))}restoreContact(e){return this.command(new _({contact:{id:e}}))}multiMergeContact(e){return this.command(new O({contacts:e}))}multiRemoveContact(e){return this.command(new F({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new H({...t,company:{id:e}}))}getUser(e){return this.command(new N({user:{login:e}}))}mergeUser(e){return this.command(new q({user:e}))}removeUser(e){return this.command(new W({user:{login:e}}))}restoreUser(e){return this.command(new j({user:{login:e}}))}listUserGenerals(e,t){return this.command(new $({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new z({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new K({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new V({user:{login:e}}))}listUserGroups(e,t){return this.command(new Z({...t,company:{id:e}}))}getUserGroup(e){return this.command(new Q({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new X({userGroup:e}))}removeUserGroup(e){return this.command(new Y({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new ee({userGroup:{id:e}}))}listMachines(e,t){return this.command(new te({...t,company:{id:e}}))}getMachine(e){return this.command(new se({machine:{id:e}}))}mergeMachine(e){return this.command(new re({machine:e}))}removeMachine(e){return this.command(new ne({machine:{id:e}}))}restoreMachine(e){return this.command(new ie({machine:{id:e}}))}listSessions(e,t){return this.command(new oe({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new ae({...t,user:{login:e}}))}killSession(e){return this.command(new ce({session:{handle:e}}))}listIcons(e,t){return this.command(new he({...t,company:{id:e}}))}getIcon(e){return this.command(new ue({icon:{id:e}}))}mergeIcon(e){return this.command(new de({icon:e}))}removeIcon(e){return this.command(new pe({icon:{id:e}}))}restoreIcon(e){return this.command(new le({icon:{id:e}}))}listPictures(e,t){return this.command(new me({...t,company:{id:e}}))}getPicture(e){return this.command(new we({picture:{id:e}}))}mergePicture(e){return this.command(new ge({picture:e}))}removePicture(e){return this.command(new ve({picture:{id:e}}))}restorePicture(e){return this.command(new ye({picture:{id:e}}))}listDocuments(e,t){return this.command(new fe({...t,company:{id:e}}))}getDocument(e){return this.command(new be({document:{id:e}}))}mergeDocument(e){return this.command(new Ce({document:e}))}removeDocument(e){return this.command(new Re({document:{id:e}}))}restoreDocument(e){return this.command(new Pe({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Se({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new ke({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ae({formTemplate:e}))}removeFormTemplate(e){return this.command(new Me({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new De({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Ie({...t,company:{id:e}}))}getFormResult(e){return this.command(new Te({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ge({formResult:e}))}multiMergeFormResult(e){return this.command(new Ue({formResult:{id:e}}))}removeFormResult(e){return this.command(new Be({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Je({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new Ee({...t,company:{id:e}}))}getDashcamData(e){return this.command(new Le({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new xe({...t,company:{id:e}}))}listAssets(e,t){return this.command(new _e({...t,company:{id:e}}))}getAsset(e){return this.command(new Oe({asset:{id:e}}))}mergeAsset(e){return this.command(new Fe({asset:e}))}multiMergeAsset(e){return this.command(new He({assets:e}))}removeAsset(e){return this.command(new Ne({asset:{id:e}}))}restoreAsset(e){return this.command(new qe({asset:{id:e}}))}suspendAsset(e){return this.command(new We({asset:{id:e}}))}reviveAsset(e){return this.command(new je({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new $e({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new ze({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new Ke({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new Ve({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new Ze({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new Qe({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new Xe({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new Ye({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new et({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new tt({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new st({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new rt({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new nt({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new it({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new ot({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new at({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new ct({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new ht({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new ut({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new dt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new pt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new lt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new mt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new wt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new gt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new vt({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new yt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new ft({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new bt({...t,company:{id:e}}))}getPlace(e){return this.command(new Ct({place:{id:e}}))}mergePlace(e){return this.command(new Rt({place:e}))}removePlace(e){return this.command(new Pt({place:{id:e}}))}restorePlace(e){return this.command(new St({place:{id:e}}))}listProviders(e,t){return this.command(new kt({...t,company:{id:e}}))}getProvider(e){return this.command(new At({provider:{id:e}}))}mergeProvider(e){return this.command(new Mt({provider:e}))}multiMergeProvider(e){return this.command(new Dt({providers:e}))}multiRemoveProvider(e){return this.command(new It({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Tt({provider:{id:e}}))}restoreProvider(e){return this.command(new Gt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Ut({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Bt({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Jt({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Et({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Lt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new xt({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new _t({...t,company:{id:e}}))}getProviderScript(e){return this.command(new Ot({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new Ft({providerScript:e}))}removeProviderScript(e){return this.command(new Ht({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Nt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new qt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Wt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new jt({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new $t({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new zt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new Kt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new Vt({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new Zt({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new Qt({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new Xt({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new Yt({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new es({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new ts({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new ss({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new rs({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new ns({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new is({...t,company:{id:e}}))}getBehaviour(e){return this.command(new os({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new as({behaviour:e}))}multiMergeBehaviour(e){return this.command(new cs({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new hs({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new us({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ds({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new ps({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new ls({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new ms({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new ws({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new gs({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new vs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new ys({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new fs({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new bs({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Cs({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Rs({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Ps({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Ss({reportTemplate:e}))}removeReportTemplate(e){return this.command(new ks({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new As({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Ms({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Ds({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Is({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Ts({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Gs({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Us({...t,company:{id:e}}))}getReportResult(e){return this.command(new Bs({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Js({reportResult:e}))}removeReportResult(e){return this.command(new Es({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Ls({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new xs({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new _s({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new Os({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new Fs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Hs({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Ns({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new qs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Ws({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new js({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new $s({maintenanceJob:{id:e}}))}}const ur={Company:"/companies/generals?parent={companyId}",CompanyGeneral:"/companies/generals?parent={companyId}",CompanyDirectory:"/companies/directory?parent={companyId}",CompanyStyle:"/companies/styles?parent={companyId}",CompanyPolicy:"/companies/policies?parent={companyId}",CompanyReseller:"/companies/resellers?parent={companyId}",Contact:"/companies/{companyId}/contacts",Machine:"/companies/{companyId}/machines",User:"/companies/{companyId}/users",UserGeneral:"/companies/{companyId}/users/generals",UserAdvanced:"/companies/{companyId}/users/advanceds",UserGroup:"/companies/{companyId}/users/groups",Session:"/companies/{companyId}/users/sessions",Dashcam:"/companies/{companyId}/dashcams",DashcamLive:"/companies/{companyId}/dashcams/live",Icon:"/companies/{companyId}/icons",Picture:"/companies/{companyId}/pictures",Document:"/companies/{companyId}/documents",FormTemplate:"/companies/{companyId}/forms/templates",FormResult:"/companies/{companyId}/forms",Asset:"/companies/{companyId}/assets",AssetGeneral:"/companies/{companyId}/assets/generals",AssetAdvanced:"/companies/{companyId}/assets/advanceds",AssetDispatch:"/companies/{companyId}/assets/dispatches",AssetMessage:"/companies/{companyId}/assets/messages",AssetAlert:"/companies/{companyId}/assets/alerts",DispatchTask:"/companies/{companyId}/assets/dispatch/tasks",DispatchJob:"/companies/{companyId}/assets/dispatch/jobs",MaintenanceSchedule:"/companies/{companyId}/maintenance/schedules",MaintenanceJob:"/companies/{companyId}/maintenance/jobs",Place:"/companies/{companyId}/places",Behaviour:"/companies/{companyId}/behaviours",BehaviourScript:"/companies/{companyId}/behaviours/scripts",BehaviourLog:"",Provider:"/companies/{companyId}/providers",ProviderGeneral:"/companies/{companyId}/providers/generals",ProviderAdvanced:"/companies/{companyId}/providers/advanceds",ProviderControl:"/companies/{companyId}/providers/controls",ProviderConfiguration:"/companies/{companyId}/providers/configurations",ProviderConfigurationType:"",ProviderScript:"/companies/{companyId}/providers/scripts",ProviderConfig:"/companies/{companyId}/providers/configs",ProviderRegistration:"/companies/{companyId}/providers/registrations",ReportTemplate:"/companies/{companyId}/reports/templates",ReportSchedule:"/companies/{companyId}/reports/schedules",ReportResult:"/companies/{companyId}/reports/results",BillingProfile:"/companies/{companyId}/billing/profiles",BillingReport:"/companies/{companyId}/billing/profiles/reports",BillableHostingRule:"",BillableHostingLicense:""},dr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},pr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},lr=/[A-Z][a-z]+/;class mr extends hr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??mr.URI_PROD),this.headers.set("Content-Type","application/json")}getVerbRoute(e){let t="GET",s="",r="";const n=e.getAction();switch(n.object){case"Self":"Get"==n.kind?(t="GET",s="self"):(t="POST",s="self/"+n.filter.toLowerCase());break;case"Subscription":throw new Error(n.object+" only supported by TrakitSocketCommander",{cause:n});case"DispatchJob":switch(n.filter){case"Cancel":t=n.batch?"PATCH":"POST",s+="/cancel";break;case"Change":t=n.batch?"PATCH":"PUT"}default:if(s=[...n.object.match(lr)].map(Ys.pluralize).join("/"),!n.batch){switch(e.getKey&&(s+="/"+e.getKey()),n.kind){case"Get":break;case"List":switch(n.filter){case"BillingProfile":case"BillingProfile":s=n.object in pr?pr[n.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${s}`;break;case"Company":s=n.object in ur?ur[n.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${s}`;break;case"Asset":s=n.object in dr?dr[n.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${s}`;break;case"User":s=`users/${encodeURIComponent(e.user.login)}/${s}`}Ys.isntNaN(e?.after?.valueOf())&&(r+="&after="+encodeURIComponent(e.after.toISOString())),Ys.isntNaN(e?.before?.valueOf())&&(r+="&before="+encodeURIComponent(e.before.toISOString())),Ys.isntNaN(e?.lowest)&&(r+="&lowest="+e.lowest),Ys.isntNaN(e?.highest)&&(r+="&highest="+e.highest),e?.first&&(r+="&first="+e.first),e?.last&&(r+="&last="+e.last),e?.labels?.length&&(r+="&labels="+encodeURIComponent(e.labels.join(","))),e?.references?.size&&(r+="&"+e.references.entries().map((([e,t])=>encodeURIComponent(e)+"="+encodeURIComponent(t))).toArray().join("&"));break;case"Merge":t="POST";break;case"Delete":t="DELETE";break;case"Restore":t="PATCH",s+="/restore";break;case"Suspend":t="PATCH",s+="/suspend";break;case"Reactivate":t="PATCH",s+="/revive"}break}switch(t="PATCH",n.kind){case"Get":case"List":t="GET";break;case"Merge":break;case"Delete":t="DELETE";break;case"Restore":s+="/restore";break;case"Suspend":s+="/suspend";break;case"Reactivate":s+="/revive"}}return r.length&&(s+=s.includes("?")?r:"?"+ +r.substring(1)),[t,s]}t(e){const[t,s]=this.getVerbRoute(e),r=e.toJSON(),n=this.createBaseUrl(s),i=new Map(this.headers),o={method:t,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==t&&(o.body=JSON.stringify(r)),this.account.machine?i.set("Authorization","HMAC256 "+this.account.machine.createHmacSignature(n,t,o.body?.length??0,new Date)):this.account.ghostId&&n.searchParams.set("ghostId",this.account.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(n,o)}i(t){return new Promise((async(s,r)=>{try{const e=await fetch(t);s(await e.json())}catch(t){r(e(t))}}))}}const wr=/^(.+?)(Merged|Deleted|Suspended)$/,gr={Company:[zs.companyGeneral,zs.companyLabels,zs.companyPolicies],CompanyGeneral:[zs.companyGeneral],CompanyDirectory:[],CompanyStyle:[zs.companyLabels],CompanyPolicy:[zs.companyPolicies],CompanyReseller:[zs.companyReseller],Contact:[zs.contact],Machine:[zs.machine],User:[zs.userGeneral,zs.userAdvanced],UserGeneral:[zs.userGeneral],UserAdvanced:[zs.userAdvanced],UserGroup:[zs.userGroup],Session:[],Dashcam:[],Icon:[zs.icon],Picture:[zs.picture],Document:[zs.document],FormTemplate:[zs.formTemplate],FormResult:[zs.formResult],Asset:[zs.assetGeneral,zs.assetAdvanced,zs.assetDispatch],AssetGeneral:[zs.assetGeneral],AssetAdvanced:[zs.assetAdvanced],AssetDispatch:[zs.assetDispatch],AssetMessage:[zs.assetMessage],AssetAlert:[],DispatchTask:[zs.dispatchTask],DispatchJob:[zs.dispatchJob],MaintenanceSchedule:[zs.maintenanceSchedule],MaintenanceJob:[zs.maintenanceJob],Place:[zs.placeGeneral],BehaviourScript:[zs.behaviourScript],Behaviour:[zs.behaviour],BehaviourLog:[zs.behaviourLog],Provider:[zs.providerGeneral,zs.providerAdvanced,zs.providerControl],ProviderGeneral:[zs.providerGeneral],ProviderAdvanced:[zs.providerAdvanced],ProviderControl:[zs.providerControl],ProviderConfiguration:[zs.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[zs.providerScript],ProviderConfig:[zs.providerConfig],ProviderRegistration:[zs.providerRegistration],ReportTemplate:[zs.reportTemplate],ReportSchedule:[zs.reportSchedule],ReportResult:[zs.reportResult],BillingProfile:[zs.billingProfile],BillingReport:[zs.billingReport],BillableHostingRule:[zs.billingHosting],BillableHostingLicense:[zs.billingLicense]};class vr{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(let[s,r]of this.#e)r&&r<e&&t.push(s);return t}purgeExpired(){const e=this.getExpired();return e.forEach((e=>this.#e.delete(e))),e}getExpiring(){const e=[];for(let[t,s]of this.#e)s&&e.push(t);return e}#t(e,t){return t=t||null,this.#e.set(e,t),t}addExpiry(e){return this.#t(e,new Date((new Date).valueOf()+3e5))}addExpiries(e){return e.map((e=>this.addExpiry(e)))}removeExpiry(e){const t=this.#e.get(e);return this.#t(e),t||null}removeExpiries(e){return e.map((e=>this.removeExpiry(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}class yr extends sr{name;body;constructor(e,t){super("message"),this.name=e,this.body=t}}class fr extends sr{reply;constructor(e,t){super(e),this.reply=t}}const br="connection",Cr="dis"+br;var Rr;!function(e){e[e.opening=WebSocket.CONNECTING]="opening",e[e.open=WebSocket.OPEN]="open",e[e.closing=WebSocket.CLOSING]="closing",e[e.closed=WebSocket.CLOSED]="closed"}(Rr||(Rr={}));class Pr extends hr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";#s=new Date(NaN);#r=new Date(NaN);#n="";#i=new Date(NaN);get lastConnected(){return this.#s}get lastReceived(){return this.#r}get lastMessage(){return this.#n}get lastSent(){return this.#i}get state(){switch(this.#o?.readyState){case WebSocket.CONNECTING:return Rr.opening;case WebSocket.OPEN:return this.#a?Rr.open:Rr.opening;case WebSocket.CLOSING:return Rr.closing;default:return Rr.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new nr(e);t.forEach((e=>e.call(this,s)))}}v(e){const t=this.o.get("close");if(t?.length){const s=new fr("close",e);t.forEach((e=>e.call(this,s)))}}C(e,t){const s=this.o.get("message");if(s?.length){const r=new yr(e,t);s.forEach((e=>e.call(this,r)))}}R(e){const t=this.o.get("error");if(t?.length){const s=new fr("error",e);t.forEach((e=>e.call(this,s)))}}#h=0;#u=new Map;#d(e,t){return this.#u.get(e)?.(t),this.#u.delete(e)}#o;#a=!1;#c=!0;#p(e){this.#o.onopen=null,this.#o.onmessage=e=>this.#l(e),this.#m=0}#w(e){this.R(new Ks({errorCode:i.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#g(e){clearTimeout(this.#v),clearTimeout(this.#y),this.#a=!1,this.#m=this.#m?2*this.#m:this.lastReceived?(new Date).valueOf()-this.lastReceived.valueOf():5e3;const t=Math.min(this.#m,3e5),s={kind:"connection",state:Rr.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:i.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===Cr?r:{...r,reqId:e,errorCode:i.service,errorDetails:{...s}});this.v?.(new Ks(r)),this.#y=this.reconnectEnabled&&this.#c?setTimeout((()=>this.open()),t,this):0,this.#o=this.#o.onopen=this.#o.onerror=this.#o.onclose=this.#o.onmessage=null}#l(e){this.#r=new Date;const t=e.data.substring(0,e.data.indexOf(" ")),s=JSON.parse(e.data.substring(t.length+1));switch(this.#n=t,"connectionResponse"!==t&&"noopResponse"!==t&&this.C(t,s),t){case"connectionResponse":this.#f(s),this.#s=new Date(this.#r),this.#a=!0,this.#d(br,s),this.h(this.account),this.m(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#f(s),this.h(this.account);break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"sessionGeneralMerged":this.#b([,"userGeneral","Merged"],this.#C(s)),this.h(this.account);break;case"sessionAdvancedMerged":this.#b([,"userAdvanced","Merged"],this.#R(s)),this.h(this.account);break;case"sessionMachineMerged":this.#b([,"machine","Merged"],this.#R(s)),this.h(this.account);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#f(s),this.h(this.account)}if(t.endsWith("Response"))this.#d(s.reqId,s);else if(!t.startsWith("session")){const e=wr.exec(t);e?.length&&this.#b(e,s)}this.resetKeepAlive()}#f(e){e.user&&this.#b([,"user","Merged"],this.#R(this.#C(e.user))),e.machine&&this.#b([,"machine","Merged"],this.#R(e.machine)),this.setAuth(new o(e)),this.#c=0===this.account.errorCode&&!this.account.user?.passwordExpired}#C(e){if(e?.contact){const t=e.contact;return this.#b([,"contact","Merged"],t),{...e,contact:t.id}}return e}#R(e){return e?.groups?.length?{...e,groups:e.groups.map((e=>(this.#b([,"userGroup","Merged"],e),e.id)))}:e}#b(e,t){const s=function(e){e="CompanyLabels"===(e=Ys.capitalize(e))?"CompanyStyle":Ys.singularize(e);return e}(e[1]),r=t[s.startsWith("Company")?"parent":"company"],o=function(e,t){return n["Rep"+e+(t??"Get")]}(s,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(o){const n=new o({errorCode:i.success,message:e[2]+" event",[e[1]]:t});if(n.store())switch(e[2]){case"Merged":case"Suspended":const e=n.getObject?.();e&&this.p(s,r,e);break;case"Deleted":this.l(s,r,function(e,t){return e[function(e){switch(e){case"User":case"UserGeneral":case"UserAdvanced":return"login";case"ProviderRegistration":return"code";case"Session":return"handle";case"Machine":return"key";case"Dashcam":return"guid";default:return"id"}}(t)]}(t,s))}return n}}reconnectEnabled=!0;#m=0;#y=0;keepAliveEnabled=!1;#v=0;constructor(e,t){super(e,t??Pr.URI_PROD)}dispose(){this.close().finally((()=>{super.dispose(),this.#o=this.#u=null}))}open(){return clearTimeout(this.#y),new Promise((async(e,t)=>{const s=this.state;if(s===Rr.closed){const s=this.createBaseUrl();this.#o=new WebSocket(s,this.account.machine?(this.account.machine.secret?.length?"HMAC256#"+btoa(this.account.machine.key+":"+await this.account.machine.createHmacSignature(s)):"MACHINE#"+btoa(this.account.machine.key)).replaceAll("/","|").replace(/=*$/,""):this.account.ghostId||void 0),this.#o.onopen=e=>this.#p(e),this.#o.onerror=e=>this.#w(e),this.#o.onclose=e=>this.#g(e),this.#u.set(br,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new o({errorCode:i.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case Rr.opening:case Rr.open:this.#c=!1,this.reconnectEnabled=!1,this.#u.set(Cr,(s=>{(0===s.errorCode?e:t)(new Ks(s))})),this.#o.close(1e3,"Bye!");break;default:t(new Ks({errorCode:i.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}t(e){return[t(e),e.toJSON()]}i(t){const s=t[0],r=t[1]||{};return new Promise(((n,o)=>{const a=this.state;switch(a){case Rr.open:const c=++this.#h,h=setTimeout((()=>this.#d(c,{reqId:c,errorCode:i.unknown,message:"Command timeout"})),12e4);r.reqId=c,this.#u.set(c,(e=>{clearTimeout(h),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r)),this.#i=new Date}catch(t){this.#d(c,e(t))}this.resetKeepAlive();break;case Rr.closed:this.open().then((()=>this.i(t).then(n))).catch(o);break;default:o({errorCode:i.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:a}})}}))}resetKeepAlive(){return clearTimeout(this.#v),this.#v=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.i(["noop",{}])),3e5):0,Promise.resolve(0!==this.#v)}subscribe(e,t){return t?.length?this.command(new Vs({company:e,subscriptionTypes:t})):Promise.resolve(new Zs({errorCode:i.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new Qs({company:e,subscriptionTypes:t})):Promise.resolve(new Zs({errorCode:i.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new Xs)}}const Sr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class kr extends hr{P;S;get autoConnect(){return this.P.reconnectEnabled}set autoConnect(e){this.P.reconnectEnabled=!!e,e&&this.P.state===Rr.closed&&this.P.open()}get socketOnline(){return this.P.state===Rr.open}get socketDetails(){return{state:this.P.state,ready:this.P.ready,lastConnected:this.P.lastConnected,lastSent:this.P.lastSent,lastReceived:this.P.lastReceived,lastMessage:this.P.lastMessage}}get socketAddress(){return this.P.baseAddress}set socketAddress(e){this.P.baseAddress=e}get restAddress(){return this.S.baseAddress}set restAddress(e){this.S.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.setAuth(e.account),n=e=>this.fire(e.type,(()=>e));this.S=new mr(this.account,t??mr.URI_PROD),this.S.on("account",r),this.P=new Pr(this.account,s??Pr.URI_PROD),this.P.on("account",r),this.P.on("open",(e=>this.#P(e.account))),this.P.on("close",(e=>this.#S(e.reply)));for(const e of["account","open","close","list","update","delete"])this.S.on(e,n),this.P.on(e,n);this.autoConnect=!(!this.account.ghostId&&!this.account.machine?.key)}dispose(){this.S.dispose(),this.P.dispose(),this.S=this.P=null}setAuth(e){super.setAuth(e),this.S?.setAuth(this.account),this.P?.setAuth(this.account)}command(e){const t=e.getAction().object;return"Subscription"===t||"Self"===t&&this.socketOnline?this.socket(e):this.rest(e)}t(e){throw new Error("Method not implemented.")}i(e){throw new Error("Method not implemented.")}rest(e){return this.S.command(e)}socket(e){return this.P.command(e)}#P(e){this.#k.forEach(((e,t)=>{this.sync(t,r(e.reset()))})),this.#A()}#S(e){clearTimeout(this.#M)}isSynced(e,t){let r=this.P.state===Rr.open;if(r){const n=this.#D(e);r=s(t).every((e=>n.regions.includes(e)))}return r}async sync(e,t){const i=[],o=this.#D(e),a=s(t).filter((e=>!o.regions.includes(e)));if(a.length>0){const t=(await this.P.subscribe(e,a)).merged;o.removeExpiries(a),r(t).forEach((t=>{const s=function(e,t){return n["Pay"+e+(t??"Get")]}(t,t.startsWith("Company")?"Get":"ListByCompany");s&&i.push(this.command(new s({company:{id:e}})))}))}return Promise.all(i)}async desync(e,t){const s=this.#D(e),r=t.reduce(((e,t)=>e.concat(gr[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));s.addExpiries(r)}#k=new Map;#A(){const e=[];this.P.state===Rr.open&&this.#k.forEach(((t,s)=>{const r=t.purgeExpired();r.length&&e.push(this.unsubscribe(s,r))})),Promise.allSettled(e).finally((()=>{this.#M=setTimeout((()=>this.#A()),1e4)}))}#M;#D(e){let t=this.#k.get(e);return t||this.#k.set(e,t=new vr),t}subscribe(e,t){return this.P.subscribe(e,t)}unsubscribe(e,t){return this.P.unsubscribe(e,t)}listSubscriptions(){return this.P.listSubscriptions()}}
|
|
1
|
+
function e(e,t){return{errorCode:i.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){const t=e.getAction(),s=new Error("no command supported for "+e.constructor.name,{cause:t});switch(t.object){case"Subscription":switch(t.kind){case"Merge":return"subscribe";case"Delete":return"unsubscribe";case"List":return"getSubscriptionsList";default:throw s}case"Self":switch(t.filter){case"Get":return"getSessionDetails";case"Login":case"Logout":return t.filter.toLowerCase();case"Contact":case"Password":case"Preferences":return"updateOwn"+t.filter;default:throw s}case"Session":switch(t.kind){case"Get":case"List":break;case"Delete":return"killSession";default:throw s}break;case"DispatchJob":switch(t.filter){case"Cancel":case"Change":return t.kind.toLocaleLowerCase()+t.object}}switch(t.kind){case"Get":case"Merge":case"Restore":case"Suspend":return t.kind.toLocaleLowerCase()+t.object;case"Delete":return"remove"+t.object;case"Reactivate":return"revive"+t.object;case"List":return"get"+Ys.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function s(e){return e.reduce(((e,t)=>e.concat(gr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function r(e){const t=[];for(const[s,r]of Object.entries(Mr)){const n=r.map((e=>gr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}for(const[s,r]of Object.entries(gr))!Mr[s]&&r.some((t=>e.includes(t)))&&t.push(s);return t}import*as n from"@trakit/commands";import{ErrorCode as i,RepSelfGet as o,ReplySync as a,ReplySyncList as c,ReplySyncGet as h,ReplySyncDelete as u,ReplySyncBatchDelete as d,PaySelfGet as p,PaySelfLogin as l,PaySelfLogout as m,PaySelfContact as w,PaySelfPassword as g,PaySelfPreferences as v,PayCompanyGet as y,PayCompanyMerge as f,PayCompanyDelete as b,PayCompanyRestore as C,PayCompanyGeneralListByCompany as R,PayCompanyGeneralGet as P,PayCompanyPolicyListByCompany as S,PayCompanyPolicyGet as k,PayCompanyStyleListByCompany as A,PayCompanyStyleGet as M,PayCompanyDirectoryListByCompany as D,PayCompanyDirectoryGet as I,PayCompanyResellerGet as T,PayCompanyResellerMerge as G,PayCompanyResellerDelete as B,PayCompanyResellerRestore as U,PayContactListByCompany as J,PayContactGet as E,PayContactMerge as L,PayContactDelete as x,PayContactRestore as _,PayContactBatchMerge as O,PayContactBatchDelete as F,PayUserListByCompany as N,PayUserGet as H,PayUserMerge as q,PayUserDelete as W,PayUserRestore as $,PayUserGeneralListByCompany as j,PayUserGeneralGet as z,PayUserAdvancedListByCompany as K,PayUserAdvancedGet as V,PayUserGroupListByCompany as Z,PayUserGroupGet as Q,PayUserGroupMerge as X,PayUserGroupDelete as Y,PayUserGroupRestore as ee,PayMachineListByCompany as te,PayMachineGet as se,PayMachineMerge as re,PayMachineDelete as ne,PayMachineRestore as ie,PaySessionListByCompany as oe,PaySessionListByUser as ae,PaySessionDelete as ce,PayIconListByCompany as he,PayIconGet as ue,PayIconMerge as de,PayIconDelete as pe,PayIconRestore as le,PayPictureListByCompany as me,PayPictureGet as we,PayPictureMerge as ge,PayPictureDelete as ve,PayPictureRestore as ye,PayDocumentListByCompany as fe,PayDocumentGet as be,PayDocumentMerge as Ce,PayDocumentDelete as Re,PayDocumentRestore as Pe,PayFormTemplateListByCompany as Se,PayFormTemplateGet as ke,PayFormTemplateMerge as Ae,PayFormTemplateDelete as Me,PayFormTemplateRestore as De,PayFormResultListByCompany as Ie,PayFormResultGet as Te,PayFormResultMerge as Ge,PayFormResultBatchMerge as Be,PayFormResultDelete as Ue,PayFormResultRestore as Je,PayDashcamListByCompany as Ee,PayDashcamGet as Le,PayDashcamLiveListByCompany as xe,PayAssetListByCompany as _e,PayAssetGet as Oe,PayAssetMerge as Fe,PayAssetBatchMerge as Ne,PayAssetDelete as He,PayAssetRestore as qe,PayAssetSuspend as We,PayAssetReactivate as $e,PayAssetGeneralListByCompany as je,PayAssetGeneralGet as ze,PayAssetAdvancedListByCompany as Ke,PayAssetAdvancedGet as Ve,PayAssetDispatchMerge as Ze,PayDispatchTaskListByCompany as Qe,PayDispatchTaskListByAsset as Xe,PayDispatchTaskGet as Ye,PayDispatchTaskMerge as et,PayDispatchTaskBatchMerge as tt,PayDispatchTaskDelete as st,PayDispatchTaskRestore as rt,PayDispatchJobListByCompany as nt,PayDispatchJobListByAsset as it,PayDispatchJobGet as ot,PayDispatchJobMerge as at,PayDispatchJobBatchMerge as ct,PayDispatchJobDelete as ht,PayDispatchJobRestore as ut,PayDispatchJobChange as dt,PayDispatchJobCancel as pt,PayAssetMessageListByCompany as lt,PayAssetMessageListByAsset as mt,PayAssetMessageGet as wt,PayAssetMessageMerge as gt,PayAssetMessageBatchMerge as vt,PayAssetMessageDelete as yt,PayAssetMessageRestore as ft,PayPlaceListByCompany as bt,PayPlaceGet as Ct,PayPlaceMerge as Rt,PayPlaceDelete as Pt,PayPlaceRestore as St,PayProviderListByCompany as kt,PayProviderGet as At,PayProviderMerge as Mt,PayProviderBatchMerge as Dt,PayProviderBatchDelete as It,PayProviderDelete as Tt,PayProviderRestore as Gt,PayProviderGeneralListByCompany as Bt,PayProviderGeneralGet as Ut,PayProviderAdvancedListByCompany as Jt,PayProviderAdvancedGet as Et,PayProviderControlListByCompany as Lt,PayProviderControlGet as xt,PayProviderScriptListByCompany as _t,PayProviderScriptGet as Ot,PayProviderScriptMerge as Ft,PayProviderScriptDelete as Nt,PayProviderScriptRestore as Ht,PayProviderConfigListByCompany as qt,PayProviderConfigGet as Wt,PayProviderConfigMerge as $t,PayProviderConfigBatchMerge as jt,PayProviderConfigDelete as zt,PayProviderConfigRestore as Kt,PayProviderConfigurationListByCompany as Vt,PayProviderConfigurationGet as Zt,PayProviderConfigurationMerge as Qt,PayProviderConfigurationBatchMerge as Xt,PayProviderConfigurationDelete as Yt,PayProviderConfigurationRestore as es,PayProviderRegistrationListByCompany as ts,PayProviderRegistrationGet as ss,PayProviderRegistrationMerge as rs,PayProviderRegistrationDelete as ns,PayBehaviourListByCompany as is,PayBehaviourGet as os,PayBehaviourMerge as as,PayBehaviourBatchMerge as cs,PayBehaviourDelete as hs,PayBehaviourRestore as us,PayBehaviourScriptListByCompany as ds,PayBehaviourScriptGet as ps,PayBehaviourScriptMerge as ls,PayBehaviourScriptDelete as ms,PayBehaviourScriptRestore as ws,PayBehaviourLogListByAsset as gs,PayBehaviourLogBatchDeleteByAsset as vs,PayBehaviourLogListByBehaviour as ys,PayBehaviourLogBatchDeleteByBehaviour as fs,PayBehaviourLogListByScript as bs,PayBehaviourLogBatchDeleteByScript as Cs,PayReportTemplateListByCompany as Rs,PayReportTemplateGet as Ps,PayReportTemplateMerge as Ss,PayReportTemplateDelete as ks,PayReportTemplateRestore as As,PayReportScheduleListByCompany as Ms,PayReportScheduleGet as Ds,PayReportScheduleMerge as Is,PayReportScheduleDelete as Ts,PayReportScheduleRestore as Gs,PayReportResultListByCompany as Bs,PayReportResultGet as Us,PayReportResultMerge as Js,PayReportResultDelete as Es,PayReportResultRestore as Ls,PayMaintenanceScheduleListByCompany as xs,PayMaintenanceScheduleGet as _s,PayMaintenanceScheduleMerge as Os,PayMaintenanceScheduleDelete as Fs,PayMaintenanceScheduleRestore as Ns,PayMaintenanceJobListByCompany as Hs,PayMaintenanceJobGet as qs,PayMaintenanceJobMerge as Ws,PayMaintenanceJobDelete as $s,PayMaintenanceJobRestore as js,SubscriptionType as zs,Reply as Ks,PaySubscriptionMerge as Vs,RepSubscription as Zs,PaySubscriptionDelete as Qs,PaySubscriptionList as Xs}from"@trakit/commands";import{utility as Ys,Machine as er,serialization as tr}from"@trakit/objects";class sr{type;constructor(e){this.type=e}}class rr extends sr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class nr extends sr{account;constructor(e){super("account"),this.account=e}}class ir extends rr{objects;constructor(e,t,s){super("list",e,t),this.objects=s}}class or extends rr{object;constructor(e,t,s){super("update",e,t),this.object=s}}class ar extends rr{key;constructor(e,t,s){super("delete",e,t),this.key=s}}class cr{account;baseAddress;query=new Map;headers=new Map;createBaseUrl(e){const t=this.baseAddress?new URL(e??"",this.baseAddress):new URL(e),s=new Map(this.query);for(const[e,r]of s)t.searchParams.append(e,r);return t}constructor(e,t){this.baseAddress=t?new URL(t):null,this.setAuth(e)}setAuth(e){e instanceof o?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof er||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new o({errorCode:i.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new o)}command(t){return new Promise((async(s,r)=>{let n=null,o=null,a=null;try{n=this.t(t)}catch(t){o=e(t)}try{o=o??await this.i(n)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===i.success?s:r)(a)}))}}class hr extends cr{o=new Map;h(e){this.fire("account",(()=>new nr(e)))}u(e,t,s){this.fire("list",(()=>new ir(e,t,s)))}p(e,t,s){this.fire("update",(()=>new or(e,t,s)))}l(e,t,s){this.fire("delete",(()=>new ar(e,t,s)))}on(e,t){let s=this.o.get(e);s||this.o.set(e,s=[]);const r=s.includes(t);return r||s.push(t),!r}off(e,t){const s=this.o.get(e);if(s?.length){if(t){const e=s.indexOf(t);return!!(e>-1&&s.splice(e,1))}return!(s.length=0)}return!1}fire(e,t){const s=this.o.get(e);if(s?.length){const e=t();s.forEach((t=>t.call(this,e)),this)}}handles(e,t){return this.o.get(e)?.includes(t)??!1}dispose(){for(const e of[...this.o.keys()])this.off(e)}async command(e){const t=await super.command(e);if(t instanceof a&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof c?s.filter?t.getList().forEach((e=>this.p(s.object,r,e))):this.u(s.object,r,t.getList()):t instanceof h?this.p(s.object,r,t.getObject()):t instanceof u?this.l(s.object,r,t.getKey()):t instanceof d&&t.getResults().forEach((e=>this.l(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new p);return this.setAuth(e),this.h(e),e}async login(e,t,s){const r=await this.command(new l({username:e,password:t,userAgent:s??null}));return this.setAuth(r),this.h(r),r}logout(){const e=this.command(new m);return this.setAuth(),this.h(this.account),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new w({contact:{name:e??null,notes:t??null,otherNames:s??null,emails:r??null,phones:n??null,addresses:i??null,urls:o??null,dates:a??null,options:c??null,roles:h??null,pictures:u??null}}))}updatePassword(e,t){return this.command(new g({current:e,password:t}))}updatePreferences(e,t,s,r,n,i){return this.command(new v({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?tr.fromMap(r):r??null,measurements:n instanceof Map?tr.fromMap(n):n??null,options:i instanceof Map?tr.fromMap(i):i??null}))}getCompany(e){return this.command(new y({company:{id:e}}))}mergeCompany(e){return this.command(new f({company:e}))}removeCompany(e){return this.command(new b({company:{id:e}}))}restoreCompany(e){return this.command(new C({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new R({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new P({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new S({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new k({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new A({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new M({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new D({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new I({company:{id:e}}))}getReseller(e){return this.command(new T({company:{id:e}}))}mergeReseller(e){return this.command(new G({company:e}))}removeReseller(e){return this.command(new B({company:{id:e}}))}restoreReseller(e){return this.command(new U({company:{id:e}}))}listContacts(e,t){return this.command(new J({...t,company:{id:e}}))}getContact(e){return this.command(new E({contact:{id:e}}))}mergeContact(e){return this.command(new L({contact:e}))}removeContact(e){return this.command(new x({contact:{id:e}}))}restoreContact(e){return this.command(new _({contact:{id:e}}))}multiMergeContact(e){return this.command(new O({contacts:e}))}multiRemoveContact(e){return this.command(new F({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new N({...t,company:{id:e}}))}getUser(e){return this.command(new H({user:{login:e}}))}mergeUser(e){return this.command(new q({user:e}))}removeUser(e){return this.command(new W({user:{login:e}}))}restoreUser(e){return this.command(new $({user:{login:e}}))}listUserGenerals(e,t){return this.command(new j({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new z({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new K({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new V({user:{login:e}}))}listUserGroups(e,t){return this.command(new Z({...t,company:{id:e}}))}getUserGroup(e){return this.command(new Q({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new X({userGroup:e}))}removeUserGroup(e){return this.command(new Y({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new ee({userGroup:{id:e}}))}listMachines(e,t){return this.command(new te({...t,company:{id:e}}))}getMachine(e){return this.command(new se({machine:{id:e}}))}mergeMachine(e){return this.command(new re({machine:e}))}removeMachine(e){return this.command(new ne({machine:{id:e}}))}restoreMachine(e){return this.command(new ie({machine:{id:e}}))}listSessions(e,t){return this.command(new oe({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new ae({...t,user:{login:e}}))}killSession(e){return this.command(new ce({session:{handle:e}}))}listIcons(e,t){return this.command(new he({...t,company:{id:e}}))}getIcon(e){return this.command(new ue({icon:{id:e}}))}mergeIcon(e){return this.command(new de({icon:e}))}removeIcon(e){return this.command(new pe({icon:{id:e}}))}restoreIcon(e){return this.command(new le({icon:{id:e}}))}listPictures(e,t){return this.command(new me({...t,company:{id:e}}))}getPicture(e){return this.command(new we({picture:{id:e}}))}mergePicture(e){return this.command(new ge({picture:e}))}removePicture(e){return this.command(new ve({picture:{id:e}}))}restorePicture(e){return this.command(new ye({picture:{id:e}}))}listDocuments(e,t){return this.command(new fe({...t,company:{id:e}}))}getDocument(e){return this.command(new be({document:{id:e}}))}mergeDocument(e){return this.command(new Ce({document:e}))}removeDocument(e){return this.command(new Re({document:{id:e}}))}restoreDocument(e){return this.command(new Pe({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Se({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new ke({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ae({formTemplate:e}))}removeFormTemplate(e){return this.command(new Me({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new De({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Ie({...t,company:{id:e}}))}getFormResult(e){return this.command(new Te({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ge({formResult:e}))}multiMergeFormResult(e){return this.command(new Be({formResult:{id:e}}))}removeFormResult(e){return this.command(new Ue({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Je({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new Ee({...t,company:{id:e}}))}getDashcamData(e){return this.command(new Le({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new xe({...t,company:{id:e}}))}listAssets(e,t){return this.command(new _e({...t,company:{id:e}}))}getAsset(e){return this.command(new Oe({asset:{id:e}}))}mergeAsset(e){return this.command(new Fe({asset:e}))}multiMergeAsset(e){return this.command(new Ne({assets:e}))}removeAsset(e){return this.command(new He({asset:{id:e}}))}restoreAsset(e){return this.command(new qe({asset:{id:e}}))}suspendAsset(e){return this.command(new We({asset:{id:e}}))}reviveAsset(e){return this.command(new $e({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new je({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new ze({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new Ke({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new Ve({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new Ze({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new Qe({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new Xe({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new Ye({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new et({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new tt({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new st({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new rt({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new nt({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new it({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new ot({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new at({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new ct({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new ht({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new ut({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new dt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new pt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new lt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new mt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new wt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new gt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new vt({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new yt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new ft({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new bt({...t,company:{id:e}}))}getPlace(e){return this.command(new Ct({place:{id:e}}))}mergePlace(e){return this.command(new Rt({place:e}))}removePlace(e){return this.command(new Pt({place:{id:e}}))}restorePlace(e){return this.command(new St({place:{id:e}}))}listProviders(e,t){return this.command(new kt({...t,company:{id:e}}))}getProvider(e){return this.command(new At({provider:{id:e}}))}mergeProvider(e){return this.command(new Mt({provider:e}))}multiMergeProvider(e){return this.command(new Dt({providers:e}))}multiRemoveProvider(e){return this.command(new It({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Tt({provider:{id:e}}))}restoreProvider(e){return this.command(new Gt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Bt({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Ut({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Jt({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Et({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Lt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new xt({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new _t({...t,company:{id:e}}))}getProviderScript(e){return this.command(new Ot({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new Ft({providerScript:e}))}removeProviderScript(e){return this.command(new Nt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Ht({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new qt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Wt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new $t({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new jt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new zt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new Kt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new Vt({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new Zt({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new Qt({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new Xt({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new Yt({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new es({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new ts({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new ss({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new rs({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new ns({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new is({...t,company:{id:e}}))}getBehaviour(e){return this.command(new os({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new as({behaviour:e}))}multiMergeBehaviour(e){return this.command(new cs({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new hs({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new us({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ds({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new ps({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new ls({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new ms({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new ws({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new gs({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new vs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new ys({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new fs({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new bs({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Cs({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Rs({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Ps({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Ss({reportTemplate:e}))}removeReportTemplate(e){return this.command(new ks({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new As({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Ms({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Ds({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Is({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Ts({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Gs({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Bs({...t,company:{id:e}}))}getReportResult(e){return this.command(new Us({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Js({reportResult:e}))}removeReportResult(e){return this.command(new Es({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Ls({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new xs({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new _s({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new Os({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new Fs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Ns({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Hs({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new qs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Ws({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new $s({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new js({maintenanceJob:{id:e}}))}}const ur={Company:"/companies/generals?parent={companyId}",CompanyGeneral:"/companies/generals?parent={companyId}",CompanyDirectory:"/companies/directory?parent={companyId}",CompanyStyle:"/companies/styles?parent={companyId}",CompanyPolicy:"/companies/policies?parent={companyId}",CompanyReseller:"/companies/resellers?parent={companyId}",Contact:"/companies/{companyId}/contacts",Machine:"/companies/{companyId}/machines",User:"/companies/{companyId}/users",UserGeneral:"/companies/{companyId}/users/generals",UserAdvanced:"/companies/{companyId}/users/advanceds",UserGroup:"/companies/{companyId}/users/groups",Session:"/companies/{companyId}/users/sessions",Dashcam:"/companies/{companyId}/dashcams",DashcamLive:"/companies/{companyId}/dashcams/live",Icon:"/companies/{companyId}/icons",Picture:"/companies/{companyId}/pictures",Document:"/companies/{companyId}/documents",FormTemplate:"/companies/{companyId}/forms/templates",FormResult:"/companies/{companyId}/forms",Asset:"/companies/{companyId}/assets",AssetGeneral:"/companies/{companyId}/assets/generals",AssetAdvanced:"/companies/{companyId}/assets/advanceds",AssetDispatch:"/companies/{companyId}/assets/dispatches",AssetMessage:"/companies/{companyId}/assets/messages",AssetAlert:"/companies/{companyId}/assets/alerts",DispatchTask:"/companies/{companyId}/assets/dispatch/tasks",DispatchJob:"/companies/{companyId}/assets/dispatch/jobs",MaintenanceSchedule:"/companies/{companyId}/maintenance/schedules",MaintenanceJob:"/companies/{companyId}/maintenance/jobs",Place:"/companies/{companyId}/places",Behaviour:"/companies/{companyId}/behaviours",BehaviourScript:"/companies/{companyId}/behaviours/scripts",BehaviourLog:"",Provider:"/companies/{companyId}/providers",ProviderGeneral:"/companies/{companyId}/providers/generals",ProviderAdvanced:"/companies/{companyId}/providers/advanceds",ProviderControl:"/companies/{companyId}/providers/controls",ProviderConfiguration:"/companies/{companyId}/providers/configurations",ProviderConfigurationType:"",ProviderScript:"/companies/{companyId}/providers/scripts",ProviderConfig:"/companies/{companyId}/providers/configs",ProviderRegistration:"/companies/{companyId}/providers/registrations",ReportTemplate:"/companies/{companyId}/reports/templates",ReportSchedule:"/companies/{companyId}/reports/schedules",ReportResult:"/companies/{companyId}/reports/results",BillingProfile:"/companies/{companyId}/billing/profiles",BillingReport:"/companies/{companyId}/billing/profiles/reports",BillableHostingRule:"",BillableHostingLicense:""},dr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},pr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},lr=/[A-Z][a-z]+/;class mr extends hr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??mr.URI_PROD),this.headers.set("Content-Type","application/json")}getVerbRoute(e){let t="GET",s="",r="";const n=e.getAction();switch(n.object){case"Self":"Get"==n.kind?(t="GET",s="self"):(t="POST",s="self/"+n.filter.toLowerCase());break;case"Subscription":throw new Error(n.object+" only supported by TrakitSocketCommander",{cause:n});case"DispatchJob":switch(n.filter){case"Cancel":t=n.batch?"PATCH":"POST",s+="/cancel";break;case"Change":t=n.batch?"PATCH":"PUT"}default:if(s=[...n.object.match(lr)].map(Ys.pluralize).join("/"),!n.batch){switch(e.getKey&&(s+="/"+e.getKey()),n.kind){case"Get":break;case"List":switch(n.filter){case"BillingProfile":case"BillingProfile":s=n.object in pr?pr[n.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${s}`;break;case"Company":s=n.object in ur?ur[n.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${s}`;break;case"Asset":s=n.object in dr?dr[n.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${s}`;break;case"User":s=`users/${encodeURIComponent(e.user.login)}/${s}`}Ys.isntNaN(e?.after?.valueOf())&&(r+="&after="+encodeURIComponent(e.after.toISOString())),Ys.isntNaN(e?.before?.valueOf())&&(r+="&before="+encodeURIComponent(e.before.toISOString())),Ys.isntNaN(e?.lowest)&&(r+="&lowest="+e.lowest),Ys.isntNaN(e?.highest)&&(r+="&highest="+e.highest),e?.first&&(r+="&first="+e.first),e?.last&&(r+="&last="+e.last),e?.labels?.length&&(r+="&labels="+encodeURIComponent(e.labels.join(","))),e?.references?.size&&(r+="&"+e.references.entries().map((([e,t])=>encodeURIComponent(e)+"="+encodeURIComponent(t))).toArray().join("&"));break;case"Merge":t="POST";break;case"Delete":t="DELETE";break;case"Restore":t="PATCH",s+="/restore";break;case"Suspend":t="PATCH",s+="/suspend";break;case"Reactivate":t="PATCH",s+="/revive"}break}switch(t="PATCH",n.kind){case"Get":case"List":t="GET";break;case"Merge":break;case"Delete":t="DELETE";break;case"Restore":s+="/restore";break;case"Suspend":s+="/suspend";break;case"Reactivate":s+="/revive"}}return r.length&&(s+=s.includes("?")?r:"?"+ +r.substring(1)),[t,s]}t(e){const[t,s]=this.getVerbRoute(e),r=e.toJSON(),n=this.createBaseUrl(s),i=new Map(this.headers),o={method:t,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==t&&(o.body=JSON.stringify(r)),this.account.machine?i.set("Authorization","HMAC256 "+this.account.machine.createHmacSignature(n,t,o.body?.length??0,new Date)):this.account.ghostId&&n.searchParams.set("ghostId",this.account.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(n,o)}i(t){return new Promise((async(s,r)=>{try{const e=await fetch(t);s(await e.json())}catch(t){r(e(t))}}))}}const wr=/^(.+?)(Merged|Deleted|Suspended)$/,gr={Company:[zs.companyGeneral,zs.companyLabels,zs.companyPolicies],CompanyGeneral:[zs.companyGeneral],CompanyDirectory:[],CompanyStyle:[zs.companyLabels],CompanyPolicy:[zs.companyPolicies],CompanyReseller:[zs.companyReseller],Contact:[zs.contact],Machine:[zs.machine],User:[zs.userGeneral,zs.userAdvanced],UserGeneral:[zs.userGeneral],UserAdvanced:[zs.userAdvanced],UserGroup:[zs.userGroup],Session:[],Dashcam:[],Icon:[zs.icon],Picture:[zs.picture],Document:[zs.document],FormTemplate:[zs.formTemplate],FormResult:[zs.formResult],Asset:[zs.assetGeneral,zs.assetAdvanced,zs.assetDispatch],AssetGeneral:[zs.assetGeneral],AssetAdvanced:[zs.assetAdvanced],AssetDispatch:[zs.assetDispatch],AssetMessage:[zs.assetMessage],AssetAlert:[],DispatchTask:[zs.dispatchTask],DispatchJob:[zs.dispatchJob],MaintenanceSchedule:[zs.maintenanceSchedule],MaintenanceJob:[zs.maintenanceJob],Place:[zs.placeGeneral],BehaviourScript:[zs.behaviourScript],Behaviour:[zs.behaviour],BehaviourLog:[zs.behaviourLog],Provider:[zs.providerGeneral,zs.providerAdvanced,zs.providerControl],ProviderGeneral:[zs.providerGeneral],ProviderAdvanced:[zs.providerAdvanced],ProviderControl:[zs.providerControl],ProviderConfiguration:[zs.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[zs.providerScript],ProviderConfig:[zs.providerConfig],ProviderRegistration:[zs.providerRegistration],ReportTemplate:[zs.reportTemplate],ReportSchedule:[zs.reportSchedule],ReportResult:[zs.reportResult],BillingProfile:[zs.billingProfile],BillingReport:[zs.billingReport],BillableHostingRule:[zs.billingHosting],BillableHostingLicense:[zs.billingLicense]};class vr{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(let[s,r]of this.#e)r&&r<e&&t.push(s);return t}purgeExpired(){const e=this.getExpired();return e.forEach((e=>this.#e.delete(e))),e}getExpiring(){const e=[];for(let[t,s]of this.#e)s&&e.push(t);return e}#t(e,t){return t=t||null,this.#e.set(e,t),t}addExpiry(e){return this.#t(e,new Date((new Date).valueOf()+3e5))}addExpiries(e){return e.map((e=>this.addExpiry(e)))}removeExpiry(e){const t=this.#e.get(e);return this.#t(e),t||null}removeExpiries(e){return e.map((e=>this.removeExpiry(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var yr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(yr||(yr={}));class fr{kind;serverTime;message;constructor(e){const{kind:t,serverTime:s,message:r}=e;this.kind=t,this.serverTime=Ys.date(s),this.message=r}}class br extends sr{name;body;constructor(e,t){super("message"),this.name=e,this.body=t}}class Cr extends sr{reply;constructor(e,t){super(e),this.reply=t}}class Rr extends sr{broadcast;constructor(e){super("broadcast"),this.broadcast=new fr(e)}}const Pr="connection",Sr="dis"+Pr;var kr;!function(e){e[e.opening=WebSocket.CONNECTING]="opening",e[e.open=WebSocket.OPEN]="open",e[e.closing=WebSocket.CLOSING]="closing",e[e.closed=WebSocket.CLOSED]="closed"}(kr||(kr={}));class Ar extends hr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";#s=new Date(NaN);#r=new Date(NaN);#n="";#i=new Date(NaN);get lastConnected(){return this.#s}get lastReceived(){return this.#r}get lastMessage(){return this.#n}get lastSent(){return this.#i}get state(){switch(this.#o?.readyState){case WebSocket.CONNECTING:return kr.opening;case WebSocket.OPEN:return this.#a?kr.open:kr.opening;case WebSocket.CLOSING:return kr.closing;default:return kr.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new nr(e);t.forEach((e=>e.call(this,s)))}}v(e){const t=this.o.get("close");if(t?.length){const s=new Cr("close",e);t.forEach((e=>e.call(this,s)))}}C(e,t){const s=this.o.get("message");if(s?.length){const r=new br(e,t);s.forEach((e=>e.call(this,r)))}}R(e){const t=this.o.get("error");if(t?.length){const s=new Cr("error",e);t.forEach((e=>e.call(this,s)))}}P(e){const t=this.o.get("broadcast");if(t?.length){const s=new Rr(e);t.forEach((e=>e.call(this,s)))}}#h=0;#u=new Map;#d(e,t){return this.#u.get(e)?.(t),this.#u.delete(e)}#o;#a=!1;#c=!0;#p(e){this.#o.onopen=null,this.#o.onmessage=e=>this.#l(e),this.#m=0}#w(e){this.R(new Ks({errorCode:i.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#g(e){clearTimeout(this.#v),clearTimeout(this.#y),this.#a=!1,this.#m=this.#m?2*this.#m:this.lastReceived?(new Date).valueOf()-this.lastReceived.valueOf():5e3;const t=Math.min(this.#m,3e5),s={kind:"connection",state:kr.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:i.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===Sr?r:{...r,reqId:e,errorCode:i.service,errorDetails:{...s}});this.v?.(new Ks(r)),this.#y=this.reconnectEnabled&&this.#c?setTimeout((()=>this.open()),t,this):0,this.#o=this.#o.onopen=this.#o.onerror=this.#o.onclose=this.#o.onmessage=null}#l(e){this.#r=new Date;const t=e.data.substring(0,e.data.indexOf(" ")),s=JSON.parse(e.data.substring(t.length+1));switch(this.#n=t,"connectionResponse"!==t&&"noopResponse"!==t&&this.C(t,s),t){case"connectionResponse":this.#f(s),this.#s=new Date(this.#r),this.#a=!0,this.#d(Pr,s),this.h(this.account),this.m(this.account),this.#d(s.reqId,s);break;case"loginResponse":case"getSessionDetailsResponse":this.#f(s),this.h(this.account),this.#d(s.reqId,s);break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode),this.#d(s.reqId,s);break;case"logoutResponse":this.#d(s.reqId,s),this.close();case"sessionEnded":this.#c=!1,this.#f(s),this.h(this.account);break;case"sessionGeneralMerged":this.#b([,"userGeneral","Merged"],this.#C(s)),this.h(this.account);break;case"sessionAdvancedMerged":this.#b([,"userAdvanced","Merged"],this.#R(s)),this.h(this.account);break;case"sessionMachineMerged":this.#b([,"machine","Merged"],this.#R(s)),this.h(this.account);break;case"broadcast":this.P(s);break;default:if(t.endsWith("Response"))this.#d(s.reqId,s);else{const e=wr.exec(t);e?.length&&this.#b(e,s)}}this.resetKeepAlive()}#f(e){e.user&&this.#b([,"user","Merged"],this.#R(this.#C(e.user))),e.machine&&this.#b([,"machine","Merged"],this.#R(e.machine)),this.setAuth(new o(e)),this.#c=0===this.account.errorCode&&!this.account.user?.passwordExpired}#C(e){if(e?.contact){const t=e.contact;return this.#b([,"contact","Merged"],t),{...e,contact:t.id}}return e}#R(e){return e?.groups?.length?{...e,groups:e.groups.map((e=>(this.#b([,"userGroup","Merged"],e),e.id)))}:e}#b(e,t){const s=function(e){e="CompanyLabels"===(e=Ys.capitalize(e))?"CompanyStyle":Ys.singularize(e);return e}(e[1]),r=t[s.startsWith("Company")?"parent":"company"],o=function(e,t){return n["Rep"+e+(t??"Get")]}(s,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(!o)throw new Error("No Reply class found for "+s+" and action "+e[2]);const a=new o({errorCode:i.success,message:e[2]+" event",[e[1]]:t});if(a.store())switch(e[2]){case"Merged":case"Suspended":this.p(s,r,a.getObject());break;case"Deleted":this.l(s,r,function(e,t){return e[function(e){switch(e){case"User":case"UserGeneral":case"UserAdvanced":return"login";case"ProviderRegistration":return"code";case"Session":return"handle";case"Machine":return"key";case"Dashcam":return"guid";default:return"id"}}(t)]}(t,s))}return a}reconnectEnabled=!0;#m=0;#y=0;keepAliveEnabled=!1;#v=0;constructor(e,t){super(e,t??Ar.URI_PROD)}dispose(){this.close().finally((()=>{super.dispose(),this.#o=this.#u=null}))}open(){return clearTimeout(this.#y),new Promise((async(e,t)=>{const s=this.state;if(s===kr.closed){const s=this.createBaseUrl();this.#o=new WebSocket(s,this.account.machine?(this.account.machine.secret?.length?"HMAC256#"+btoa(this.account.machine.key+":"+await this.account.machine.createHmacSignature(s)):"MACHINE#"+btoa(this.account.machine.key)).replaceAll("/","|").replace(/=*$/,""):this.account.ghostId||void 0),this.#o.onopen=e=>this.#p(e),this.#o.onerror=e=>this.#w(e),this.#o.onclose=e=>this.#g(e),this.#u.set(Pr,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new o({errorCode:i.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case kr.opening:case kr.open:this.#c=!1,this.reconnectEnabled=!1,this.#u.set(Sr,(s=>{(0===s.errorCode?e:t)(new Ks(s))})),this.#o.close(1e3,"Bye!");break;default:t(new Ks({errorCode:i.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}t(e){return[t(e),e.toJSON()]}i(t){const s=t[0],r=t[1]||{};return new Promise(((n,o)=>{const a=this.state;switch(a){case kr.open:const c=++this.#h,h=setTimeout((()=>this.#d(c,{reqId:c,errorCode:i.unknown,message:"Command timeout"})),12e4);r.reqId=c,this.#u.set(c,(e=>{clearTimeout(h),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r)),this.#i=new Date}catch(t){this.#d(c,e(t))}this.resetKeepAlive();break;case kr.closed:this.open().then((()=>this.i(t).then(n))).catch(o);break;default:o({errorCode:i.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:a}})}}))}resetKeepAlive(){return clearTimeout(this.#v),this.#v=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.i(["noop",{}])),3e5):0,Promise.resolve(0!==this.#v)}subscribe(e,t){return t?.length?this.command(new Vs({company:e,subscriptionTypes:t})):Promise.resolve(new Zs({errorCode:i.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new Qs({company:e,subscriptionTypes:t})):Promise.resolve(new Zs({errorCode:i.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new Xs)}}const Mr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Dr extends hr{S;k;get autoConnect(){return this.S.reconnectEnabled}set autoConnect(e){this.S.reconnectEnabled=!!e,e&&this.S.state===kr.closed&&this.S.open()}get socketOnline(){return this.S.state===kr.open}get socketDetails(){return{state:this.S.state,ready:this.S.ready,lastConnected:this.S.lastConnected,lastSent:this.S.lastSent,lastReceived:this.S.lastReceived,lastMessage:this.S.lastMessage}}get socketAddress(){return this.S.baseAddress}set socketAddress(e){this.S.baseAddress=e}get restAddress(){return this.k.baseAddress}set restAddress(e){this.k.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.setAuth(e.account),n=e=>this.fire(e.type,(()=>e));this.k=new mr(this.account,t??mr.URI_PROD),this.k.on("account",r),this.S=new Ar(this.account,s??Ar.URI_PROD),this.S.on("account",r),this.S.on("open",(e=>this.#P(e.account))),this.S.on("close",(e=>this.#S(e.reply)));for(const e of["account","list","update","delete"])this.k.on(e,n),this.S.on(e,n);for(const e of["open","close","broadcast"])this.S.on(e,n);this.autoConnect=!(!this.account.ghostId&&!this.account.machine?.key)}dispose(){this.k.dispose(),this.S.dispose(),this.k=this.S=null}setAuth(e){super.setAuth(e),this.k?.setAuth(this.account),this.S?.setAuth(this.account)}command(e){const t=e.getAction().object;return"Subscription"===t||"Self"===t&&this.socketOnline?this.socket(e):this.rest(e)}t(e){throw new Error("Method not implemented.")}i(e){throw new Error("Method not implemented.")}rest(e){return this.k.command(e)}socket(e){return this.S.command(e)}#P(e){this.#k.forEach(((e,t)=>{this.sync(t,r(e.reset()))})),this.#A()}#S(e){clearTimeout(this.#M)}isSynced(e,t){let r=this.S.state===kr.open;if(r){const n=this.#D(e);r=s(t).every((e=>n.regions.includes(e)))}return r}async sync(e,t){const i=[],o=this.#D(e),a=s(t).filter((e=>!o.regions.includes(e)));if(a.length>0){const t=(await this.S.subscribe(e,a)).merged;o.removeExpiries(a),r(t).forEach((t=>{const s=function(e,t){return n["Pay"+e+(t??"Get")]}(t,t.startsWith("Company")?"Get":"ListByCompany");if(!s)throw new Error(`No payload class could be made for sync type ${t}`);i.push(this.command(new s({company:{id:e}})))}))}return Promise.all(i)}desync(e,t){const s=this.#D(e),r=t.reduce(((e,t)=>e.concat(gr[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));return s.addExpiries(r),r}#k=new Map;#A(){const e=[];this.S.state===kr.open&&this.#k.forEach(((t,s)=>{const r=t.purgeExpired();r.length&&e.push(this.unsubscribe(s,r))})),Promise.allSettled(e).finally((()=>{this.#M=setTimeout((()=>this.#A()),1e4)}))}#M;#D(e){let t=this.#k.get(e);return t||this.#k.set(e,t=new vr),t}subscribe(e,t){return this.S.subscribe(e,t)}unsubscribe(e,t){return this.S.unsubscribe(e,t)}listSubscriptions(){return this.S.listSubscriptions()}}
|
|
2
2
|
/**
|
|
3
3
|
* Synchronization library main process.
|
|
4
4
|
* {@link https://github.com/trakitwireless/trakit-ts-sync|Client synchronization library.}
|
|
5
5
|
* Last updated on Thu Feb 27 2025 11:59:01
|
|
6
6
|
* @copyright Trak-iT Wireless Inc. 2025
|
|
7
|
-
*/const
|
|
7
|
+
*/const Ir="0.0.21";export{vr as SubscribedRegions,cr as TrakitBaseCommander,sr as TrakitEvent,nr as TrakitEventAccount,ar as TrakitEventDelete,ir as TrakitEventList,Cr as TrakitEventSocketClose,br as TrakitEventSocketMessage,rr as TrakitEventSync,or as TrakitEventUpdate,hr as TrakitObjectCommander,mr as TrakitRestfulCommander,Ar as TrakitSocketCommander,Dr as TrakitSyncCommander,Ir as version};
|