@trakit/sync 0.0.38 → 0.0.39

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.
@@ -0,0 +1,9 @@
1
+ import { Payload } from "@trakit/commands";
2
+ import { HttpVerb } from "./Constants";
3
+ /**
4
+ * Gets the appropriate HTTP verb and route for the given payload.
5
+ * @param payload The payload being sent.
6
+ * @returns A tuple containing the HTTP verb and route.
7
+ */
8
+ export declare function payloadToVerbRoute(payload: Payload): [HttpVerb, string];
9
+ //# sourceMappingURL=Functions.d.ts.map
@@ -1,7 +1,6 @@
1
1
  import { Payload, RepSelfGet } from "@trakit/commands";
2
2
  import { guid, JsonObject, Machine, nothing, url } from "@trakit/objects";
3
3
  import { TrakitObjectCommander } from "../API/TrakitObjectCommander";
4
- import { HttpVerb } from "./Constants";
5
4
  /**
6
5
  * Uses Trak-iT's RESTful service to access and manipulate Trak-iT API objects.
7
6
  */
@@ -28,12 +27,6 @@ export declare class TrakitRestfulCommander extends TrakitObjectCommander<Reques
28
27
  } | {
29
28
  ghostId: guid;
30
29
  } | guid | nothing, baseAddress?: URL | url | nothing);
31
- /**
32
- * Gets the appropriate HTTP verb and route for the given payload.
33
- * @param payload The payload to analyze.
34
- * @returns A tuple containing the HTTP verb and route.
35
- */
36
- getVerbRoute(payload: Payload): [HttpVerb, string];
37
30
  /**
38
31
  * Creates a request object for the specified HTTP method and body.
39
32
  * @param payload
@@ -1,8 +1,8 @@
1
1
  import { Payload } from "@trakit/commands";
2
2
  /**
3
3
  * Returns a WebSocket command name based on the {@link Payload} type.
4
- * @param payload
5
- * @returns
4
+ * @param payload The payload being sent.
5
+ * @returns The corresponding WebSocket command name.
6
6
  */
7
- export declare function makeCommandName(payload: Payload): string;
7
+ export declare function payloadToCommandName(payload: Payload): string;
8
8
  //# sourceMappingURL=Functions.d.ts.map
package/index.d.ts CHANGED
@@ -7,15 +7,17 @@
7
7
  import { TrakitEvent, TrakitEventAccount, TrakitEventDelete, TrakitEventList, TrakitEventSync, TrakitEventUpdate } from "./API/Events";
8
8
  import { TrakitBaseCommander } from "./API/TrakitBaseCommander";
9
9
  import { TrakitObjectCommander } from "./API/TrakitObjectCommander";
10
+ import { payloadToVerbRoute } from "./RESTful/Functions";
10
11
  import { TrakitRestfulCommander } from "./RESTful/TrakitRestfulCommander";
11
12
  import { TrakitSyncCommander } from "./Synchronization/TrakitSyncCommander";
12
13
  import { TrakitEventSocketClose, TrakitEventSocketMessage } from "./WebSocket/Events";
14
+ import { payloadToCommandName } from "./WebSocket/Functions";
13
15
  import { SubscribedRegions } from "./WebSocket/SubscribedRegions";
14
- import { TrakitSocketCommander } from "./WebSocket/TrakitSocketCommander";
16
+ import { TrakitSocketCommander, TrakitSocketStatus } from "./WebSocket/TrakitSocketCommander";
15
17
  /**
16
18
  * Version number for this release.
17
19
  */
18
- export declare const version = "0.0.38";
20
+ export declare const version = "0.0.39";
19
21
  /**
20
22
  * API exports
21
23
  */
@@ -23,11 +25,11 @@ export { TrakitBaseCommander, TrakitEvent, TrakitEventAccount, TrakitEventDelete
23
25
  /**
24
26
  * RESTful API exports
25
27
  */
26
- export { TrakitRestfulCommander };
28
+ export { payloadToVerbRoute, TrakitRestfulCommander };
27
29
  /**
28
30
  * WebSocket API exports
29
31
  */
30
- export { SubscribedRegions, TrakitSocketCommander };
32
+ export { payloadToCommandName, SubscribedRegions, TrakitSocketCommander, TrakitSocketStatus };
31
33
  /**
32
34
  * Synchronization exports
33
35
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@trakit/sync",
3
3
  "type": "module",
4
- "version": "0.0.38",
4
+ "version": "0.0.39",
5
5
  "main": "./trakit-sync.min.js",
6
6
  "types": "./index.d.ts",
7
7
  "scripts": {
@@ -1,7 +1,7 @@
1
- function e(e,t){return{errorCode:o.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){if("CompanyLabels"===(e=er.capitalize(e)))e="CompanyStyle";else e=er.singularize(e);return e}function s(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"+er.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function r(e){return e.reduce(((e,t)=>e.concat(yr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function n(e){const t=[];for(const[s,r]of Object.entries(Tr)){const n=r.map((e=>yr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Tr[t])),[]);for(const[r,n]of Object.entries(yr))!s.includes(r)&&n.some((t=>e.includes(t)))&&t.push(r);return t}import*as i from"@trakit/commands";import{ErrorCode as o,RepSelfGet as a,ReplySync as c,ReplySyncList as h,ReplySyncGet as u,ReplySyncDelete as d,ReplySyncBatchDelete as p,PaySelfGet as l,PaySelfLogin as m,PaySelfLogout as w,PaySelfContact as g,PaySelfPassword as y,PaySelfPreferences as v,PayCompanyGet as f,PayCompanyMerge as b,PayCompanyDelete as C,PayCompanyRestore as P,PayCompanyGeneralListByCompany as R,PayCompanyGeneralGet as S,PayCompanyPolicyListByCompany as k,PayCompanyPolicyGet as A,PayCompanyStyleListByCompany as M,PayCompanyStyleGet as D,PayCompanyDirectoryListByCompany as I,PayCompanyDirectoryGet as T,PayCompanyResellerGet as G,PayCompanyResellerMerge as B,PayCompanyResellerDelete as U,PayCompanyResellerRestore as J,PayContactListByCompany as E,PayContactGet as L,PayContactMerge as x,PayContactDelete as _,PayContactRestore as N,PayContactBatchMerge as O,PayContactBatchDelete as F,PayUserListByCompany as H,PayUserGet as q,PayUserMerge as $,PayUserDelete as W,PayUserRestore as j,PayUserGeneralListByCompany as z,PayUserGeneralGet as K,PayUserAdvancedListByCompany as V,PayUserAdvancedGet as Z,PayUserGroupListByCompany as Q,PayUserGroupGet as X,PayUserGroupMerge as Y,PayUserGroupDelete as ee,PayUserGroupRestore as te,PayMachineListByCompany as se,PayMachineGet as re,PayMachineMerge as ne,PayMachineDelete as ie,PayMachineRestore as oe,PaySessionListByCompany as ae,PaySessionListByUser as ce,PaySessionDelete as he,PayIconListByCompany as ue,PayIconGet as de,PayIconMerge as pe,PayIconDelete as le,PayIconRestore as me,PayPictureListByCompany as we,PayPictureGet as ge,PayPictureMerge as ye,PayPictureDelete as ve,PayPictureRestore as fe,PayDocumentListByCompany as be,PayDocumentGet as Ce,PayDocumentMerge as Pe,PayDocumentDelete as Re,PayDocumentRestore as Se,PayFormTemplateListByCompany as ke,PayFormTemplateGet as Ae,PayFormTemplateMerge as Me,PayFormTemplateDelete as De,PayFormTemplateRestore as Ie,PayFormResultListByCompany as Te,PayFormResultGet as Ge,PayFormResultMerge as Be,PayFormResultBatchMerge as Ue,PayFormResultDelete as Je,PayFormResultRestore as Ee,PayDashcamListByCompany as Le,PayDashcamGet as xe,PayDashcamLiveListByCompany as _e,PayAssetListByCompany as Ne,PayAssetGet as Oe,PayAssetMerge as Fe,PayAssetBatchMerge as He,PayAssetDelete as qe,PayAssetRestore as $e,PayAssetSuspend as We,PayAssetReactivate as je,PayAssetGeneralListByCompany as ze,PayAssetGeneralGet as Ke,PayAssetAdvancedListByCompany as Ve,PayAssetAdvancedGet as Ze,PayAssetDispatchMerge as Qe,PayDispatchTaskListByCompany as Xe,PayDispatchTaskListByAsset as Ye,PayDispatchTaskGet as et,PayDispatchTaskMerge as tt,PayDispatchTaskBatchMerge as st,PayDispatchTaskDelete as rt,PayDispatchTaskRestore as nt,PayDispatchJobListByCompany as it,PayDispatchJobListByAsset as ot,PayDispatchJobGet as at,PayDispatchJobMerge as ct,PayDispatchJobBatchMerge as ht,PayDispatchJobDelete as ut,PayDispatchJobRestore as dt,PayDispatchJobChange as pt,PayDispatchJobCancel as lt,PayAssetMessageListByCompany as mt,PayAssetMessageListByAsset as wt,PayAssetMessageGet as gt,PayAssetMessageMerge as yt,PayAssetMessageBatchMerge as vt,PayAssetMessageDelete as ft,PayAssetMessageRestore as bt,PayPlaceListByCompany as Ct,PayPlaceGet as Pt,PayPlaceMerge as Rt,PayPlaceDelete as St,PayPlaceRestore as kt,PayProviderListByCompany as At,PayProviderGet as Mt,PayProviderMerge as Dt,PayProviderBatchMerge as It,PayProviderBatchDelete as Tt,PayProviderDelete as Gt,PayProviderRestore as Bt,PayProviderGeneralListByCompany as Ut,PayProviderGeneralGet as Jt,PayProviderAdvancedListByCompany as Et,PayProviderAdvancedGet as Lt,PayProviderControlListByCompany as xt,PayProviderControlGet as _t,PayProviderScriptListByCompany as Nt,PayProviderScriptGet as Ot,PayProviderScriptMerge as Ft,PayProviderScriptDelete as Ht,PayProviderScriptRestore as qt,PayProviderConfigListByCompany as $t,PayProviderConfigGet as Wt,PayProviderConfigMerge as jt,PayProviderConfigBatchMerge as zt,PayProviderConfigDelete as Kt,PayProviderConfigRestore as Vt,PayProviderConfigurationListByCompany as Zt,PayProviderConfigurationGet as Qt,PayProviderConfigurationMerge as Xt,PayProviderConfigurationBatchMerge as Yt,PayProviderConfigurationDelete as es,PayProviderConfigurationRestore as ts,PayProviderRegistrationListByCompany as ss,PayProviderRegistrationGet as rs,PayProviderRegistrationMerge as ns,PayProviderRegistrationDelete as is,PayBehaviourListByCompany as os,PayBehaviourGet as as,PayBehaviourMerge as cs,PayBehaviourBatchMerge as hs,PayBehaviourDelete as us,PayBehaviourRestore as ds,PayBehaviourScriptListByCompany as ps,PayBehaviourScriptGet as ls,PayBehaviourScriptMerge as ms,PayBehaviourScriptDelete as ws,PayBehaviourScriptRestore as gs,PayBehaviourLogListByAsset as ys,PayBehaviourLogBatchDeleteByAsset as vs,PayBehaviourLogListByBehaviour as fs,PayBehaviourLogBatchDeleteByBehaviour as bs,PayBehaviourLogListByScript as Cs,PayBehaviourLogBatchDeleteByScript as Ps,PayReportTemplateListByCompany as Rs,PayReportTemplateGet as Ss,PayReportTemplateMerge as ks,PayReportTemplateDelete as As,PayReportTemplateRestore as Ms,PayReportScheduleListByCompany as Ds,PayReportScheduleGet as Is,PayReportScheduleMerge as Ts,PayReportScheduleDelete as Gs,PayReportScheduleRestore as Bs,PayReportResultListByCompany as Us,PayReportResultGet as Js,PayReportResultMerge as Es,PayReportResultDelete as Ls,PayReportResultRestore as xs,PayMaintenanceScheduleListByCompany as _s,PayMaintenanceScheduleGet as Ns,PayMaintenanceScheduleMerge as Os,PayMaintenanceScheduleDelete as Fs,PayMaintenanceScheduleRestore as Hs,PayMaintenanceJobListByCompany as qs,PayMaintenanceJobGet as $s,PayMaintenanceJobMerge as Ws,PayMaintenanceJobDelete as js,PayMaintenanceJobRestore as zs,SubscriptionType as Ks,Reply as Vs,PaySubscriptionMerge as Zs,RepSubscription as Qs,PaySubscriptionDelete as Xs,PaySubscriptionList as Ys}from"@trakit/commands";import{utility as er,Machine as tr,serialization as sr}from"@trakit/objects";class rr{type;constructor(e){this.type=e}}class nr extends rr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class ir extends rr{account;constructor(e,t){super(e),this.account=t}}class or extends nr{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class ar extends nr{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class cr extends nr{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}class hr{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 a?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof tr||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new a({errorCode:o.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new a)}command(t){return new Promise((async(s,r)=>{let n=null,i=null,a=null;try{n=await this.t(t)}catch(t){i=e(t)}try{i=i??await this.i(n)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(i)}catch(s){a=t.createReply(e(s,i))}(a.errorCode===o.success?s:r)(a)}))}}class ur extends hr{o=new Map;h(e){e&&this.setAuth(new a({serverTime:this.account.serverTime?.toISOString()??null,ghostId:this.account.ghostId??null,expiry:this.account.expiry?.toISOString()??null,user:this.account.userLogin?{login:this.account.userLogin}:null,machine:this.account.machineKey?{key:this.account.machineKey}:null,sessionPolicy:this.account.sessionPolicy?.toJSON()??null,passwordPolicy:this.account.passwordPolicy?.toJSON()??null})),this.fire("account",(()=>new ir("account",this.account)))}u(e,t,s){this.fire("list",(()=>new or("list",e,t,s)))}p(e,t,s){this.fire("update",(()=>new ar("update",e,t,s)))}l(e,t,s){this.fire("delete",(()=>new cr("delete",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)?.slice();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 c&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof h?s.filter?t.getList().forEach((e=>this.p(s.object,r,e))):this.u(s.object,r,t.getList()):t instanceof u?this.p(s.object,r,t.getObject()):t instanceof d?this.l(s.object,r,t.getKey()):t instanceof p&&t.getResults().forEach((e=>this.l(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new l);return this.setAuth(e),this.h(),e}async login(e,t,s){const r=await this.command(new m({username:e,password:t,userAgent:s??null}));return this.setAuth(r),this.h(),r}logout(){const e=this.command(new w);return this.setAuth(),this.h(),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new g({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 y({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?sr.fromMap(r):r??null,measurements:n instanceof Map?sr.fromMap(n):n??null,options:i instanceof Map?sr.fromMap(i):i??null}))}getCompany(e){return this.command(new f({company:{id:e}}))}mergeCompany(e){return this.command(new b({company:e}))}removeCompany(e){return this.command(new C({company:{id:e}}))}restoreCompany(e){return this.command(new P({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new R({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new S({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new k({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new A({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new M({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new D({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new I({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new T({company:{id:e}}))}getReseller(e){return this.command(new G({company:{id:e}}))}mergeReseller(e){return this.command(new B({company:e}))}removeReseller(e){return this.command(new U({company:{id:e}}))}restoreReseller(e){return this.command(new J({company:{id:e}}))}listContacts(e,t){return this.command(new E({...t,company:{id:e}}))}getContact(e){return this.command(new L({contact:{id:e}}))}mergeContact(e){return this.command(new x({contact:e}))}removeContact(e){return this.command(new _({contact:{id:e}}))}restoreContact(e){return this.command(new N({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 q({user:{login:e}}))}mergeUser(e){return this.command(new $({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 z({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new K({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new V({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new Z({user:{login:e}}))}listUserGroups(e,t){return this.command(new Q({...t,company:{id:e}}))}getUserGroup(e){return this.command(new X({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new Y({userGroup:e}))}removeUserGroup(e){return this.command(new ee({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new te({userGroup:{id:e}}))}listMachines(e,t){return this.command(new se({...t,company:{id:e}}))}getMachine(e){return this.command(new re({machine:{id:e}}))}mergeMachine(e){return this.command(new ne({machine:e}))}removeMachine(e){return this.command(new ie({machine:{id:e}}))}restoreMachine(e){return this.command(new oe({machine:{id:e}}))}listSessions(e,t){return this.command(new ae({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new ce({...t,user:{login:e}}))}killSession(e){return this.command(new he({session:{handle:e}}))}listIcons(e,t){return this.command(new ue({...t,company:{id:e}}))}getIcon(e){return this.command(new de({icon:{id:e}}))}mergeIcon(e){return this.command(new pe({icon:e}))}removeIcon(e){return this.command(new le({icon:{id:e}}))}restoreIcon(e){return this.command(new me({icon:{id:e}}))}listPictures(e,t){return this.command(new we({...t,company:{id:e}}))}getPicture(e){return this.command(new ge({picture:{id:e}}))}mergePicture(e){return this.command(new ye({picture:e}))}removePicture(e){return this.command(new ve({picture:{id:e}}))}restorePicture(e){return this.command(new fe({picture:{id:e}}))}listDocuments(e,t){return this.command(new be({...t,company:{id:e}}))}getDocument(e){return this.command(new Ce({document:{id:e}}))}mergeDocument(e){return this.command(new Pe({document:e}))}removeDocument(e){return this.command(new Re({document:{id:e}}))}restoreDocument(e){return this.command(new Se({document:{id:e}}))}listFormTemplates(e,t){return this.command(new ke({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Ae({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Me({formTemplate:e}))}removeFormTemplate(e){return this.command(new De({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Ie({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Te({...t,company:{id:e}}))}getFormResult(e){return this.command(new Ge({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Be({formResult:e}))}multiMergeFormResult(e){return this.command(new Ue({formResult:{id:e}}))}removeFormResult(e){return this.command(new Je({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Ee({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new Le({...t,company:{id:e}}))}getDashcamData(e){return this.command(new xe({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new _e({...t,company:{id:e}}))}listAssets(e,t){return this.command(new Ne({...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 qe({asset:{id:e}}))}restoreAsset(e){return this.command(new $e({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 ze({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new Ke({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new Ve({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new Ze({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new Qe({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new Xe({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new Ye({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new et({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new tt({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new st({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new rt({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new nt({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new it({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new ot({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new at({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new ct({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new ht({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new ut({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new dt({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new pt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new lt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new mt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new wt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new gt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new yt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new vt({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new ft({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new bt({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new Ct({...t,company:{id:e}}))}getPlace(e){return this.command(new Pt({place:{id:e}}))}mergePlace(e){return this.command(new Rt({place:e}))}removePlace(e){return this.command(new St({place:{id:e}}))}restorePlace(e){return this.command(new kt({place:{id:e}}))}listProviders(e,t){return this.command(new At({...t,company:{id:e}}))}getProvider(e){return this.command(new Mt({provider:{id:e}}))}mergeProvider(e){return this.command(new Dt({provider:e}))}multiMergeProvider(e){return this.command(new It({providers:e}))}multiRemoveProvider(e){return this.command(new Tt({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Gt({provider:{id:e}}))}restoreProvider(e){return this.command(new Bt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Ut({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Jt({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Et({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Lt({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new xt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new _t({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new Nt({...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 qt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new $t({...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 zt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new Kt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new Vt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new Zt({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new Qt({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new Xt({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new Yt({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new es({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new ts({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new ss({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new rs({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new ns({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new is({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new os({...t,company:{id:e}}))}getBehaviour(e){return this.command(new as({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new cs({behaviour:e}))}multiMergeBehaviour(e){return this.command(new hs({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new us({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new ds({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ps({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new ls({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new ms({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new ws({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new gs({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new ys({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new vs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new fs({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new bs({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new Cs({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Ps({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Rs({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Ss({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new ks({reportTemplate:e}))}removeReportTemplate(e){return this.command(new As({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Ms({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Ds({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Is({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Ts({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Gs({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Bs({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Us({...t,company:{id:e}}))}getReportResult(e){return this.command(new Js({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Es({reportResult:e}))}removeReportResult(e){return this.command(new Ls({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new xs({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new _s({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new Ns({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 qs({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new $s({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 zs({maintenanceJob:{id:e}}))}}const dr={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:""},pr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},lr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},mr=/[A-Z][a-z]+/;class wr extends ur{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??wr.URI_PROD)}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(mr)].map((e=>er.pluralize(e.toLowerCase()))).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 lr?lr[n.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${s}`;break;case"Company":s=n.object in dr?dr[n.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${s}`;break;case"Asset":s=n.object in pr?pr[n.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${s}`;break;case"User":s=`users/${encodeURIComponent(e.user.login)}/${s}`}er.isntNaN(e?.after?.valueOf())&&(r+="&after="+encodeURIComponent(e.after.toISOString())),er.isntNaN(e?.before?.valueOf())&&(r+="&before="+encodeURIComponent(e.before.toISOString())),er.isntNaN(e?.lowest)&&(r+="&lowest="+e.lowest),er.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]}async 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",this.account.machine.secret?.length?"HMAC256 "+btoa(this.account.machine.key+":"+await this.account.machine.createHmacSignature(n,t,o.body?.length??0,new Date)):"Machine "+btoa(this.account.machine.key)):this.account.ghostId&&i.set("Authorization","Bearer "+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 gr=/^(.+?)(Merged|Deleted|Suspended)$/,yr={Company:[Ks.companyGeneral,Ks.companyLabels,Ks.companyPolicies],CompanyGeneral:[Ks.companyGeneral],CompanyDirectory:[],CompanyStyle:[Ks.companyLabels],CompanyPolicy:[Ks.companyPolicies],CompanyReseller:[Ks.companyReseller],Contact:[Ks.contact],Machine:[Ks.machine],User:[Ks.userGeneral,Ks.userAdvanced],UserGeneral:[Ks.userGeneral],UserAdvanced:[Ks.userAdvanced],UserGroup:[Ks.userGroup],Session:[],Dashcam:[],Icon:[Ks.icon],Picture:[Ks.picture],Document:[Ks.document],FormTemplate:[Ks.formTemplate],FormResult:[Ks.formResult],Asset:[Ks.assetGeneral,Ks.assetAdvanced,Ks.assetDispatch],AssetGeneral:[Ks.assetGeneral],AssetAdvanced:[Ks.assetAdvanced],AssetDispatch:[Ks.assetDispatch],AssetMessage:[Ks.assetMessage],AssetAlert:[],DispatchTask:[Ks.dispatchTask],DispatchJob:[Ks.dispatchJob],MaintenanceSchedule:[Ks.maintenanceSchedule],MaintenanceJob:[Ks.maintenanceJob],Place:[Ks.placeGeneral],BehaviourScript:[Ks.behaviourScript],Behaviour:[Ks.behaviour],BehaviourLog:[Ks.behaviourLog],Provider:[Ks.providerGeneral,Ks.providerAdvanced,Ks.providerControl],ProviderGeneral:[Ks.providerGeneral],ProviderAdvanced:[Ks.providerAdvanced],ProviderControl:[Ks.providerControl],ProviderConfiguration:[Ks.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[Ks.providerScript],ProviderConfig:[Ks.providerConfig],ProviderRegistration:[Ks.providerRegistration],ReportTemplate:[Ks.reportTemplate],ReportSchedule:[Ks.reportSchedule],ReportResult:[Ks.reportResult],BillingProfile:[Ks.billingProfile],BillingReport:[Ks.billingReport],BillableHostingRule:[Ks.billingHosting],BillableHostingLicense:[Ks.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 fr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(fr||(fr={}));class br{static fromJson(e){switch(e?.kind){case fr.maintenance:return new Cr(e);case fr.upgrade:return new Pr(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=er.date(e?.serverTime),this.message=e?.message??""}}class Cr extends br{starting;ending;constructor(e){super(e),this.starting=er.date(e?.starting),this.ending=er.date(e?.ending)}}class Pr extends br{eta;reload;constructor(e){super(e),this.eta=er.date(e?.eta),this.reload=!!e?.reload}}class Rr extends rr{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Sr extends rr{reply;constructor(e,t){super(e),this.reply=t}}class kr extends rr{broadcast;constructor(e,t){super(e),this.broadcast=br.fromJson(t)}}const Ar="connection",Mr="dis"+Ar;var Dr;!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"}(Dr||(Dr={}));class Ir extends ur{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=gr.exec(e);return 3===s?.length?t(s[1])||null:void 0}#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 Dr.opening;case WebSocket.OPEN:return this.#a?Dr.open:Dr.opening;case WebSocket.CLOSING:return Dr.closing;default:return Dr.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new ir("open",e);t.forEach((e=>e.call(this,s)))}}v(e){const t=this.o.get("close");if(t?.length){const s=new Sr("close",e);t.forEach((e=>e.call(this,s)))}}C(e,t){const s=this.o.get("message");if(s?.length){const r=new Rr("message",e,t);s.forEach((e=>e.call(this,r)))}}P(e){const t=this.o.get("error");if(t?.length){const s=new Sr("error",e);t.forEach((e=>e.call(this,s)))}}R(e){const t=this.o.get("broadcast");if(t?.length){const s=new kr("broadcast",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.P(new Vs({errorCode:o.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#g(e){clearTimeout(this.#y),clearTimeout(this.#v),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:Dr.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:o.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===Mr?r:{...r,reqId:e,errorCode:o.service,errorDetails:{...s}});this.v?.(new Vs(r)),this.#v=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(Ar,s),this.h(),this.m(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#f(s),this.h();break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#f(s),this.h();break;case"sessionGeneralMerged":this.#b([,"userGeneral","Merged"],this.#C(s)),this.h(!0);break;case"sessionAdvancedMerged":this.#b([,"userAdvanced","Merged"],this.#P(s)),this.h(!0);break;case"sessionMachineMerged":this.#b([,"machine","Merged"],this.#P(s)),this.h(!0);break;case"broadcast":this.R(s)}if(t.endsWith("Response"))this.#d(s.reqId,s);else if(!t.startsWith("session")){const e=gr.exec(t);e?.length&&this.#b(e,s)}this.resetKeepAlive()}#f(e){e.user&&this.#b([,"user","Merged"],this.#P(this.#C(e.user))),e.machine&&this.#b([,"machine","Merged"],this.#P(e.machine)),this.setAuth(new a(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}#P(e){return e?.groups?.length?{...e,groups:e.groups.map((e=>(this.#b([,"userGroup","Merged"],e),e.id)))}:e}#b(e,s){const r=t(e[1]),n=s[r.startsWith("Company")?"parent":"company"],a=function(e,t){return i["Rep"+e+(t??"Get")]}(r,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(!a)throw new Error("No Reply class found for "+r+" and action "+e[2]);const c=new a({errorCode:o.success,message:e[2]+" event",[e[1]]:s});if(c.store())switch(e[2]){case"Merged":case"Suspended":this.p(r,n,c.getObject());break;case"Deleted":this.l(r,n,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)]}(s,r))}return c}reconnectEnabled=!0;#m=0;#v=0;keepAliveEnabled=!1;#y=0;constructor(e,t){super(e,t??Ir.URI_PROD)}dispose(){this.close().finally((()=>{super.dispose(),this.#o=this.#u=null}))}open(){return clearTimeout(this.#v),new Promise((async(e,t)=>{const s=this.state;if(s===Dr.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(Ar,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new a({errorCode:o.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case Dr.opening:case Dr.open:this.#c=!1,this.reconnectEnabled=!1,this.#u.set(Mr,(s=>{(0===s.errorCode?e:t)(new Vs(s))})),this.#o.close(1e3,"Bye!");break;default:t(new Vs({errorCode:o.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}t(e){return Promise.resolve([s(e),e.toJSON()])}i(t){const s=t[0],r=t[1]||{};return new Promise(((n,i)=>{const a=this.state;switch(a){case Dr.open:const c=++this.#h,h=setTimeout((()=>this.#d(c,{reqId:c,errorCode:o.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 Dr.closed:this.open().then((()=>this.i(t).then(n))).catch(i);break;default:i({errorCode:o.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:a}})}}))}resetKeepAlive(){return clearTimeout(this.#y),this.#y=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.i(["noop",{}])),3e5):0,Promise.resolve(0!==this.#y)}subscribe(e,t){return t?.length?this.command(new Zs({company:{id:e},subscriptionTypes:t})):Promise.resolve(new Qs({errorCode:o.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new Xs({company:{id:e},subscriptionTypes:t})):Promise.resolve(new Qs({errorCode:o.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new Ys)}}const Tr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Gr extends ur{S;k;get autoConnect(){return this.S.reconnectEnabled}set autoConnect(e){this.S.reconnectEnabled=!!e,e&&this.S.state===Dr.closed&&this.S.open()}get socketOnline(){return this.S.state===Dr.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 wr(this.account,t??wr.URI_PROD),this.k.on("account",r),this.S=new Ir(this.account,s??Ir.URI_PROD),this.S.on("account",r),this.S.on("open",(e=>this.#R(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(){super.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)}#R(e){this.#k.forEach(((e,t)=>{this.sync(t,n(e.reset()))})),this.#A()}#S(e){clearTimeout(this.#M)}isSynced(e,t){let s=this.S.state===Dr.open;if(s){const n=this.#D(e);s=r(t).every((e=>n.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#D(e),r=t?[]:s.getExpiring();return n(s.regions.filter((e=>!r.includes(e))))}async sync(e,t){const s=[],o=this.#D(e),a=r(t).filter((e=>!o.regions.includes(e)));if(a.length>0){const t=(await this.S.subscribe(e,a)).merged;o.removeExpiries(a),n(t).forEach((t=>{const r=function(e,t){return i["Pay"+e+(t??"Get")]}(t,t.startsWith("Company")?"Get":"ListByCompany");if(!r)throw new Error(`No payload class could be made for sync type ${t}`);s.push(this.command(new r({company:{id:e}})))}))}return Promise.all(s)}desync(e,t){const s=this.#D(e),r=t.reduce(((e,t)=>e.concat(yr[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===Dr.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()}}
1
+ function e(e,t){return{errorCode:a.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){if("CompanyLabels"===(e=tr.capitalize(e)))e="CompanyStyle";else e=tr.singularize(e);return e}function s(e){let t="GET",s="",r=new URLSearchParams;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(wr)].map((e=>tr.pluralize(e.toLowerCase()))).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 mr?mr[n.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${s}`;break;case"Company":s=n.object in pr?pr[n.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${s}`;break;case"Asset":s=n.object in lr?lr[n.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${s}`;break;case"User":s=`users/${encodeURIComponent(e.user.login)}/${s}`}if(tr.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),tr.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),tr.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),tr.isntNaN(e?.highest)&&r.set("highest",e.highest),e?.first&&r.set("first",e.first),e?.last&&r.set("last",e.last),e?.labels?.length&&r.set("labels",e.labels.join(",")),e?.references?.size)for(const[t,s]of e.references.entries())r.set(t,s);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[t,r.size?s+"?"+r.toString():s]}function r(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"+tr.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function n(e){return e.reduce(((e,t)=>e.concat(vr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function i(e){const t=[];for(const[s,r]of Object.entries(Gr)){const n=r.map((e=>vr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Gr[t])),[]);for(const[r,n]of Object.entries(vr))!s.includes(r)&&n.some((t=>e.includes(t)))&&t.push(r);return t}import*as o from"@trakit/commands";import{ErrorCode as a,RepSelfGet as c,ReplySync as h,ReplySyncList as u,ReplySyncGet as d,ReplySyncDelete as p,ReplySyncBatchDelete as l,PaySelfGet as m,PaySelfLogin as w,PaySelfLogout as g,PaySelfContact as y,PaySelfPassword as v,PaySelfPreferences as f,PayCompanyGet as b,PayCompanyMerge as C,PayCompanyDelete as P,PayCompanyRestore as R,PayCompanyGeneralListByCompany as S,PayCompanyGeneralGet as k,PayCompanyPolicyListByCompany as A,PayCompanyPolicyGet as M,PayCompanyStyleListByCompany as D,PayCompanyStyleGet as I,PayCompanyDirectoryListByCompany as T,PayCompanyDirectoryGet as G,PayCompanyResellerGet as B,PayCompanyResellerMerge as U,PayCompanyResellerDelete as J,PayCompanyResellerRestore as E,PayContactListByCompany as L,PayContactGet as x,PayContactMerge as _,PayContactDelete as N,PayContactRestore as O,PayContactBatchMerge as F,PayContactBatchDelete as H,PayUserListByCompany as q,PayUserGet as $,PayUserMerge as W,PayUserDelete as j,PayUserRestore as z,PayUserGeneralListByCompany as K,PayUserGeneralGet as Z,PayUserAdvancedListByCompany as Q,PayUserAdvancedGet as V,PayUserGroupListByCompany as X,PayUserGroupGet as Y,PayUserGroupMerge as ee,PayUserGroupDelete as te,PayUserGroupRestore as se,PayMachineListByCompany as re,PayMachineGet as ne,PayMachineMerge as ie,PayMachineDelete as oe,PayMachineRestore as ae,PaySessionListByCompany as ce,PaySessionListByUser as he,PaySessionDelete as ue,PayIconListByCompany as de,PayIconGet as pe,PayIconMerge as le,PayIconDelete as me,PayIconRestore as we,PayPictureListByCompany as ge,PayPictureGet as ye,PayPictureMerge as ve,PayPictureDelete as fe,PayPictureRestore as be,PayDocumentListByCompany as Ce,PayDocumentGet as Pe,PayDocumentMerge as Re,PayDocumentDelete as Se,PayDocumentRestore as ke,PayFormTemplateListByCompany as Ae,PayFormTemplateGet as Me,PayFormTemplateMerge as De,PayFormTemplateDelete as Ie,PayFormTemplateRestore as Te,PayFormResultListByCompany as Ge,PayFormResultGet as Be,PayFormResultMerge as Ue,PayFormResultBatchMerge as Je,PayFormResultDelete as Ee,PayFormResultRestore as Le,PayDashcamListByCompany as xe,PayDashcamGet as _e,PayDashcamLiveListByCompany as Ne,PayAssetListByCompany as Oe,PayAssetGet as Fe,PayAssetMerge as He,PayAssetBatchMerge as qe,PayAssetDelete as $e,PayAssetRestore as We,PayAssetSuspend as je,PayAssetReactivate as ze,PayAssetGeneralListByCompany as Ke,PayAssetGeneralGet as Ze,PayAssetAdvancedListByCompany as Qe,PayAssetAdvancedGet as Ve,PayAssetDispatchMerge as Xe,PayDispatchTaskListByCompany as Ye,PayDispatchTaskListByAsset as et,PayDispatchTaskGet as tt,PayDispatchTaskMerge as st,PayDispatchTaskBatchMerge as rt,PayDispatchTaskDelete as nt,PayDispatchTaskRestore as it,PayDispatchJobListByCompany as ot,PayDispatchJobListByAsset as at,PayDispatchJobGet as ct,PayDispatchJobMerge as ht,PayDispatchJobBatchMerge as ut,PayDispatchJobDelete as dt,PayDispatchJobRestore as pt,PayDispatchJobChange as lt,PayDispatchJobCancel as mt,PayAssetMessageListByCompany as wt,PayAssetMessageListByAsset as gt,PayAssetMessageGet as yt,PayAssetMessageMerge as vt,PayAssetMessageBatchMerge as ft,PayAssetMessageDelete as bt,PayAssetMessageRestore as Ct,PayPlaceListByCompany as Pt,PayPlaceGet as Rt,PayPlaceMerge as St,PayPlaceDelete as kt,PayPlaceRestore as At,PayProviderListByCompany as Mt,PayProviderGet as Dt,PayProviderMerge as It,PayProviderBatchMerge as Tt,PayProviderBatchDelete as Gt,PayProviderDelete as Bt,PayProviderRestore as Ut,PayProviderGeneralListByCompany as Jt,PayProviderGeneralGet as Et,PayProviderAdvancedListByCompany as Lt,PayProviderAdvancedGet as xt,PayProviderControlListByCompany as _t,PayProviderControlGet as Nt,PayProviderScriptListByCompany as Ot,PayProviderScriptGet as Ft,PayProviderScriptMerge as Ht,PayProviderScriptDelete as qt,PayProviderScriptRestore as $t,PayProviderConfigListByCompany as Wt,PayProviderConfigGet as jt,PayProviderConfigMerge as zt,PayProviderConfigBatchMerge as Kt,PayProviderConfigDelete as Zt,PayProviderConfigRestore as Qt,PayProviderConfigurationListByCompany as Vt,PayProviderConfigurationGet as Xt,PayProviderConfigurationMerge as Yt,PayProviderConfigurationBatchMerge as es,PayProviderConfigurationDelete as ts,PayProviderConfigurationRestore as ss,PayProviderRegistrationListByCompany as rs,PayProviderRegistrationGet as ns,PayProviderRegistrationMerge as is,PayProviderRegistrationDelete as os,PayBehaviourListByCompany as as,PayBehaviourGet as cs,PayBehaviourMerge as hs,PayBehaviourBatchMerge as us,PayBehaviourDelete as ds,PayBehaviourRestore as ps,PayBehaviourScriptListByCompany as ls,PayBehaviourScriptGet as ms,PayBehaviourScriptMerge as ws,PayBehaviourScriptDelete as gs,PayBehaviourScriptRestore as ys,PayBehaviourLogListByAsset as vs,PayBehaviourLogBatchDeleteByAsset as fs,PayBehaviourLogListByBehaviour as bs,PayBehaviourLogBatchDeleteByBehaviour as Cs,PayBehaviourLogListByScript as Ps,PayBehaviourLogBatchDeleteByScript as Rs,PayReportTemplateListByCompany as Ss,PayReportTemplateGet as ks,PayReportTemplateMerge as As,PayReportTemplateDelete as Ms,PayReportTemplateRestore as Ds,PayReportScheduleListByCompany as Is,PayReportScheduleGet as Ts,PayReportScheduleMerge as Gs,PayReportScheduleDelete as Bs,PayReportScheduleRestore as Us,PayReportResultListByCompany as Js,PayReportResultGet as Es,PayReportResultMerge as Ls,PayReportResultDelete as xs,PayReportResultRestore as _s,PayMaintenanceScheduleListByCompany as Ns,PayMaintenanceScheduleGet as Os,PayMaintenanceScheduleMerge as Fs,PayMaintenanceScheduleDelete as Hs,PayMaintenanceScheduleRestore as qs,PayMaintenanceJobListByCompany as $s,PayMaintenanceJobGet as Ws,PayMaintenanceJobMerge as js,PayMaintenanceJobDelete as zs,PayMaintenanceJobRestore as Ks,SubscriptionType as Zs,Reply as Qs,PaySubscriptionMerge as Vs,RepSubscription as Xs,PaySubscriptionDelete as Ys,PaySubscriptionList as er}from"@trakit/commands";import{utility as tr,Machine as sr,serialization as rr}from"@trakit/objects";class nr{type;constructor(e){this.type=e}}class ir extends nr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class or extends nr{account;constructor(e,t){super(e),this.account=t}}class ar extends ir{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class cr extends ir{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class hr extends ir{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}class ur{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 c?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof sr||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new c({errorCode:a.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new c)}command(t){return new Promise((async(s,r)=>{let n=null,i=null,o=null;try{n=await this.t(t)}catch(t){i=e(t)}try{i=i??await this.i(n)}catch(s){o=t.createReply(s instanceof Error?e(s):s)}try{o=o??t.createReply(i)}catch(s){o=t.createReply(e(s,i))}(o.errorCode===a.success?s:r)(o)}))}}class dr extends ur{o=new Map;h(e){e&&this.setAuth(new c({serverTime:this.account.serverTime?.toISOString()??null,ghostId:this.account.ghostId??null,expiry:this.account.expiry?.toISOString()??null,user:this.account.userLogin?{login:this.account.userLogin}:null,machine:this.account.machineKey?{key:this.account.machineKey}:null,sessionPolicy:this.account.sessionPolicy?.toJSON()??null,passwordPolicy:this.account.passwordPolicy?.toJSON()??null})),this.fire("account",(()=>new or("account",this.account)))}u(e,t,s){this.fire("list",(()=>new ar("list",e,t,s)))}p(e,t,s){this.fire("update",(()=>new cr("update",e,t,s)))}l(e,t,s){this.fire("delete",(()=>new hr("delete",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)?.slice();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 h&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof u?s.filter?t.getList().forEach((e=>this.p(s.object,r,e))):this.u(s.object,r,t.getList()):t instanceof d?this.p(s.object,r,t.getObject()):t instanceof p?this.l(s.object,r,t.getKey()):t instanceof l&&t.getResults().forEach((e=>this.l(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new m);return this.setAuth(e),this.h(),e}async login(e,t,s){const r=await this.command(new w({username:e,password:t,userAgent:s??null}));return this.setAuth(r),this.h(),r}logout(){const e=this.command(new g);return this.setAuth(),this.h(),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new y({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 v({current:e,password:t}))}updatePreferences(e,t,s,r,n,i){return this.command(new f({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?rr.fromMap(r):r??null,measurements:n instanceof Map?rr.fromMap(n):n??null,options:i instanceof Map?rr.fromMap(i):i??null}))}getCompany(e){return this.command(new b({company:{id:e}}))}mergeCompany(e){return this.command(new C({company:e}))}removeCompany(e){return this.command(new P({company:{id:e}}))}restoreCompany(e){return this.command(new R({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new S({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new k({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new A({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new M({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new D({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new I({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new T({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new G({company:{id:e}}))}getReseller(e){return this.command(new B({company:{id:e}}))}mergeReseller(e){return this.command(new U({company:e}))}removeReseller(e){return this.command(new J({company:{id:e}}))}restoreReseller(e){return this.command(new E({company:{id:e}}))}listContacts(e,t){return this.command(new L({...t,company:{id:e}}))}getContact(e){return this.command(new x({contact:{id:e}}))}mergeContact(e){return this.command(new _({contact:e}))}removeContact(e){return this.command(new N({contact:{id:e}}))}restoreContact(e){return this.command(new O({contact:{id:e}}))}multiMergeContact(e){return this.command(new F({contacts:e}))}multiRemoveContact(e){return this.command(new H({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new q({...t,company:{id:e}}))}getUser(e){return this.command(new $({user:{login:e}}))}mergeUser(e){return this.command(new W({user:e}))}removeUser(e){return this.command(new j({user:{login:e}}))}restoreUser(e){return this.command(new z({user:{login:e}}))}listUserGenerals(e,t){return this.command(new K({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new Z({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new Q({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new V({user:{login:e}}))}listUserGroups(e,t){return this.command(new X({...t,company:{id:e}}))}getUserGroup(e){return this.command(new Y({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new ee({userGroup:e}))}removeUserGroup(e){return this.command(new te({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new se({userGroup:{id:e}}))}listMachines(e,t){return this.command(new re({...t,company:{id:e}}))}getMachine(e){return this.command(new ne({machine:{id:e}}))}mergeMachine(e){return this.command(new ie({machine:e}))}removeMachine(e){return this.command(new oe({machine:{id:e}}))}restoreMachine(e){return this.command(new ae({machine:{id:e}}))}listSessions(e,t){return this.command(new ce({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new he({...t,user:{login:e}}))}killSession(e){return this.command(new ue({session:{handle:e}}))}listIcons(e,t){return this.command(new de({...t,company:{id:e}}))}getIcon(e){return this.command(new pe({icon:{id:e}}))}mergeIcon(e){return this.command(new le({icon:e}))}removeIcon(e){return this.command(new me({icon:{id:e}}))}restoreIcon(e){return this.command(new we({icon:{id:e}}))}listPictures(e,t){return this.command(new ge({...t,company:{id:e}}))}getPicture(e){return this.command(new ye({picture:{id:e}}))}mergePicture(e){return this.command(new ve({picture:e}))}removePicture(e){return this.command(new fe({picture:{id:e}}))}restorePicture(e){return this.command(new be({picture:{id:e}}))}listDocuments(e,t){return this.command(new Ce({...t,company:{id:e}}))}getDocument(e){return this.command(new Pe({document:{id:e}}))}mergeDocument(e){return this.command(new Re({document:e}))}removeDocument(e){return this.command(new Se({document:{id:e}}))}restoreDocument(e){return this.command(new ke({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Ae({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Me({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new De({formTemplate:e}))}removeFormTemplate(e){return this.command(new Ie({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Te({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Ge({...t,company:{id:e}}))}getFormResult(e){return this.command(new Be({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ue({formResult:e}))}multiMergeFormResult(e){return this.command(new Je({formResult:{id:e}}))}removeFormResult(e){return this.command(new Ee({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Le({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new xe({...t,company:{id:e}}))}getDashcamData(e){return this.command(new _e({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new Ne({...t,company:{id:e}}))}listAssets(e,t){return this.command(new Oe({...t,company:{id:e}}))}getAsset(e){return this.command(new Fe({asset:{id:e}}))}mergeAsset(e){return this.command(new He({asset:e}))}multiMergeAsset(e){return this.command(new qe({assets:e}))}removeAsset(e){return this.command(new $e({asset:{id:e}}))}restoreAsset(e){return this.command(new We({asset:{id:e}}))}suspendAsset(e){return this.command(new je({asset:{id:e}}))}reviveAsset(e){return this.command(new ze({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new Ke({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new Ze({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new Qe({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new Ve({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new Xe({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new Ye({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new et({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new tt({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new st({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new rt({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new nt({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new it({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new ot({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new at({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new ct({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new ht({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new ut({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new dt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new pt({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new lt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new mt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new wt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new gt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new yt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new vt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new ft({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new bt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new Ct({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new Pt({...t,company:{id:e}}))}getPlace(e){return this.command(new Rt({place:{id:e}}))}mergePlace(e){return this.command(new St({place:e}))}removePlace(e){return this.command(new kt({place:{id:e}}))}restorePlace(e){return this.command(new At({place:{id:e}}))}listProviders(e,t){return this.command(new Mt({...t,company:{id:e}}))}getProvider(e){return this.command(new Dt({provider:{id:e}}))}mergeProvider(e){return this.command(new It({provider:e}))}multiMergeProvider(e){return this.command(new Tt({providers:e}))}multiRemoveProvider(e){return this.command(new Gt({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Bt({provider:{id:e}}))}restoreProvider(e){return this.command(new Ut({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Jt({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Et({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Lt({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new xt({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new _t({...t,company:{id:e}}))}getProviderControl(e){return this.command(new Nt({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new Ot({...t,company:{id:e}}))}getProviderScript(e){return this.command(new Ft({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new Ht({providerScript:e}))}removeProviderScript(e){return this.command(new qt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new $t({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Wt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new jt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new zt({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new Kt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new Zt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new Qt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new Vt({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new Xt({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new Yt({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new es({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new ts({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new ss({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new rs({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new ns({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new is({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new os({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new as({...t,company:{id:e}}))}getBehaviour(e){return this.command(new cs({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new hs({behaviour:e}))}multiMergeBehaviour(e){return this.command(new us({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new ds({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new ps({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ls({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new ms({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new ws({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new gs({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new ys({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new vs({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new fs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new bs({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new Cs({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new Ps({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Rs({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Ss({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new ks({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new As({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Ms({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Ds({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Is({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Ts({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Gs({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Bs({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Us({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Js({...t,company:{id:e}}))}getReportResult(e){return this.command(new Es({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Ls({reportResult:e}))}removeReportResult(e){return this.command(new xs({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new _s({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new Ns({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new Os({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new Fs({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new Hs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new qs({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new $s({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Ws({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new js({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new zs({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new Ks({maintenanceJob:{id:e}}))}}const pr={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:""},lr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},mr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},wr=/[A-Z][a-z]+/;class gr extends dr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??gr.URI_PROD)}async t(e){const[t,r]=s(e),n=e.toJSON(),i=this.createBaseUrl(r),o=new Map(this.headers),a={method:t,cache:"no-store",mode:"cors",credentials:"omit"};return n&&"GET"!==t&&(a.body=JSON.stringify(n)),this.account.machine?o.set("Authorization",this.account.machine.secret?.length?"HMAC256 "+btoa(this.account.machine.key+":"+await this.account.machine.createHmacSignature(i,t,a.body?.length??0,new Date)):"Machine "+btoa(this.account.machine.key)):this.account.ghostId&&o.set("Authorization","Bearer "+this.account.ghostId),o.size>0&&(a.headers=new Headers([...o.entries()])),new Request(i,a)}i(t){return new Promise((async(s,r)=>{try{const e=await fetch(t);s(await e.json())}catch(t){r(e(t))}}))}}const yr=/^(.+?)(Merged|Deleted|Suspended)$/,vr={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 fr{#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 br;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(br||(br={}));class Cr{static fromJson(e){switch(e?.kind){case br.maintenance:return new Pr(e);case br.upgrade:return new Rr(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=tr.date(e?.serverTime),this.message=e?.message??""}}class Pr extends Cr{starting;ending;constructor(e){super(e),this.starting=tr.date(e?.starting),this.ending=tr.date(e?.ending)}}class Rr extends Cr{eta;reload;constructor(e){super(e),this.eta=tr.date(e?.eta),this.reload=!!e?.reload}}class Sr extends nr{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class kr extends nr{reply;constructor(e,t){super(e),this.reply=t}}class Ar extends nr{broadcast;constructor(e,t){super(e),this.broadcast=Cr.fromJson(t)}}const Mr="connection",Dr="dis"+Mr;var Ir;!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"}(Ir||(Ir={}));class Tr extends dr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=yr.exec(e);return 3===s?.length?t(s[1])||null:void 0}#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 Ir.opening;case WebSocket.OPEN:return this.#a?Ir.open:Ir.opening;case WebSocket.CLOSING:return Ir.closing;default:return Ir.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new or("open",e);t.forEach((e=>e.call(this,s)))}}v(e){const t=this.o.get("close");if(t?.length){const s=new kr("close",e);t.forEach((e=>e.call(this,s)))}}C(e,t){const s=this.o.get("message");if(s?.length){const r=new Sr("message",e,t);s.forEach((e=>e.call(this,r)))}}P(e){const t=this.o.get("error");if(t?.length){const s=new kr("error",e);t.forEach((e=>e.call(this,s)))}}R(e){const t=this.o.get("broadcast");if(t?.length){const s=new Ar("broadcast",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.P(new Qs({errorCode:a.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#g(e){clearTimeout(this.#y),clearTimeout(this.#v),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:Ir.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:a.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===Dr?r:{...r,reqId:e,errorCode:a.service,errorDetails:{...s}});this.v?.(new Qs(r)),this.#v=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(Mr,s),this.h(),this.m(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#f(s),this.h();break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#f(s),this.h();break;case"sessionGeneralMerged":this.#b([,"userGeneral","Merged"],this.#C(s)),this.h(!0);break;case"sessionAdvancedMerged":this.#b([,"userAdvanced","Merged"],this.#P(s)),this.h(!0);break;case"sessionMachineMerged":this.#b([,"machine","Merged"],this.#P(s)),this.h(!0);break;case"broadcast":this.R(s)}if(t.endsWith("Response"))this.#d(s.reqId,s);else if(!t.startsWith("session")){const e=yr.exec(t);e?.length&&this.#b(e,s)}this.resetKeepAlive()}#f(e){e.user&&this.#b([,"user","Merged"],this.#P(this.#C(e.user))),e.machine&&this.#b([,"machine","Merged"],this.#P(e.machine)),this.setAuth(new c(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}#P(e){return e?.groups?.length?{...e,groups:e.groups.map((e=>(this.#b([,"userGroup","Merged"],e),e.id)))}:e}#b(e,s){const r=t(e[1]),n=s[r.startsWith("Company")?"parent":"company"],i=function(e,t){return o["Rep"+e+(t??"Get")]}(r,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(!i)throw new Error("No Reply class found for "+r+" and action "+e[2]);const c=new i({errorCode:a.success,message:e[2]+" event",[e[1]]:s});if(c.store())switch(e[2]){case"Merged":case"Suspended":this.p(r,n,c.getObject());break;case"Deleted":this.l(r,n,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)]}(s,r))}return c}reconnectEnabled=!0;#m=0;#v=0;keepAliveEnabled=!1;#y=0;constructor(e,t){super(e,t??Tr.URI_PROD)}dispose(){this.close().finally((()=>{super.dispose(),this.#o=this.#u=null}))}open(){return clearTimeout(this.#v),new Promise((async(e,t)=>{const s=this.state;if(s===Ir.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(Mr,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new c({errorCode:a.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case Ir.opening:case Ir.open:this.#c=!1,this.reconnectEnabled=!1,this.#u.set(Dr,(s=>{(0===s.errorCode?e:t)(new Qs(s))})),this.#o.close(1e3,"Bye!");break;default:t(new Qs({errorCode:a.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}t(e){return Promise.resolve([r(e),e.toJSON()])}i(t){const s=t[0],r=t[1]||{};return new Promise(((n,i)=>{const o=this.state;switch(o){case Ir.open:const c=++this.#h,h=setTimeout((()=>this.#d(c,{reqId:c,errorCode:a.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 Ir.closed:this.open().then((()=>this.i(t).then(n))).catch(i);break;default:i({errorCode:a.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:o}})}}))}resetKeepAlive(){return clearTimeout(this.#y),this.#y=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.i(["noop",{}])),3e5):0,Promise.resolve(0!==this.#y)}subscribe(e,t){return t?.length?this.command(new Vs({company:{id:e},subscriptionTypes:t})):Promise.resolve(new Xs({errorCode:a.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new Ys({company:{id:e},subscriptionTypes:t})):Promise.resolve(new Xs({errorCode:a.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new er)}}const Gr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Br extends dr{S;k;get autoConnect(){return this.S.reconnectEnabled}set autoConnect(e){this.S.reconnectEnabled=!!e,e&&this.S.state===Ir.closed&&this.S.open()}get socketOnline(){return this.S.state===Ir.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 gr(this.account,t??gr.URI_PROD),this.k.on("account",r),this.S=new Tr(this.account,s??Tr.URI_PROD),this.S.on("account",r),this.S.on("open",(e=>this.#R(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(){super.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)}#R(e){this.#k.forEach(((e,t)=>{this.sync(t,i(e.reset()))})),this.#A()}#S(e){clearTimeout(this.#M)}isSynced(e,t){let s=this.S.state===Ir.open;if(s){const r=this.#D(e);s=n(t).every((e=>r.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#D(e),r=t?[]:s.getExpiring();return i(s.regions.filter((e=>!r.includes(e))))}async sync(e,t){const s=[],r=this.#D(e),a=n(t).filter((e=>!r.regions.includes(e)));if(a.length>0){const t=(await this.S.subscribe(e,a)).merged;r.removeExpiries(a),i(t).forEach((t=>{const r=function(e,t){return o["Pay"+e+(t??"Get")]}(t,t.startsWith("Company")?"Get":"ListByCompany");if(!r)throw new Error(`No payload class could be made for sync type ${t}`);s.push(this.command(new r({company:{id:e}})))}))}return Promise.all(s)}desync(e,t){const s=this.#D(e),r=t.reduce(((e,t)=>e.concat(vr[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===Ir.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 fr),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 Br="0.0.38";export{vr as SubscribedRegions,hr as TrakitBaseCommander,rr as TrakitEvent,ir as TrakitEventAccount,cr as TrakitEventDelete,or as TrakitEventList,Sr as TrakitEventSocketClose,Rr as TrakitEventSocketMessage,nr as TrakitEventSync,ar as TrakitEventUpdate,ur as TrakitObjectCommander,wr as TrakitRestfulCommander,Ir as TrakitSocketCommander,Gr as TrakitSyncCommander,Br as version};
7
+ */const Ur="0.0.39";export{fr as SubscribedRegions,ur as TrakitBaseCommander,nr as TrakitEvent,or as TrakitEventAccount,hr as TrakitEventDelete,ar as TrakitEventList,kr as TrakitEventSocketClose,Sr as TrakitEventSocketMessage,ir as TrakitEventSync,cr as TrakitEventUpdate,dr as TrakitObjectCommander,gr as TrakitRestfulCommander,Tr as TrakitSocketCommander,Ir as TrakitSocketStatus,Br as TrakitSyncCommander,r as payloadToCommandName,s as payloadToVerbRoute,Ur as version};