@trakit/sync 0.0.51 → 0.0.53

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.
@@ -1,4 +1,4 @@
1
- import { Payload, RepAssetAdvancedGet, RepAssetAdvancedListByCompany, RepAssetBatchMerge, RepAssetDelete, RepAssetDispatchMerge, RepAssetGeneralGet, RepAssetGeneralListByCompany, RepAssetGet, RepAssetListByCompany, RepAssetMerge, RepAssetMessageBatchMerge, RepAssetMessageDelete, RepAssetMessageGet, RepAssetMessageListByAsset, RepAssetMessageListByCompany, RepAssetMessageMerge, RepAssetSuspend, RepBehaviourBatchMerge, RepBehaviourDelete, RepBehaviourGet, RepBehaviourListByCompany, RepBehaviourLogBatchDeleteByAsset, RepBehaviourLogBatchDeleteByBehaviour, RepBehaviourLogBatchDeleteByScript, RepBehaviourLogListByAsset, RepBehaviourLogListByBehaviour, RepBehaviourLogListByScript, RepBehaviourMerge, RepBehaviourScriptDelete, RepBehaviourScriptGet, RepBehaviourScriptListByCompany, RepBehaviourScriptMerge, RepCompanyDelete, RepCompanyDirectoryGet, RepCompanyDirectoryListByCompany, RepCompanyGeneralGet, RepCompanyGeneralListByCompany, RepCompanyGet, RepCompanyMerge, RepCompanyPolicyGet, RepCompanyPolicyListByCompany, RepCompanyResellerDelete, RepCompanyResellerGet, RepCompanyResellerMerge, RepCompanyStyleGet, RepCompanyStyleListByCompany, RepContactBatchDelete, RepContactBatchMerge, RepContactDelete, RepContactGet, RepContactListByCompany, RepContactMerge, RepDashcamGet, RepDashcamListByCompany, RepDashcamLiveListByCompany, RepDispatchJobBatchMerge, RepDispatchJobDelete, RepDispatchJobGet, RepDispatchJobListByAsset, RepDispatchJobListByCompany, RepDispatchJobMerge, RepDispatchTaskBatchMerge, RepDispatchTaskDelete, RepDispatchTaskGet, RepDispatchTaskListByAsset, RepDispatchTaskListByCompany, RepDispatchTaskMerge, RepDocumentDelete, RepDocumentGet, RepDocumentListByCompany, RepDocumentMerge, RepFormResultBatchMerge, RepFormResultDelete, RepFormResultGet, RepFormResultListByCompany, RepFormResultMerge, RepFormTemplateDelete, RepFormTemplateGet, RepFormTemplateListByCompany, RepFormTemplateMerge, RepIconDelete, RepIconGet, RepIconListByCompany, RepIconMerge, Reply, RepMachineDelete, RepMachineGet, RepMachineListByCompany, RepMachineMerge, RepMaintenanceJobDelete, RepMaintenanceJobGet, RepMaintenanceJobListByCompany, RepMaintenanceJobMerge, RepMaintenanceScheduleDelete, RepMaintenanceScheduleGet, RepMaintenanceScheduleListByCompany, RepMaintenanceScheduleMerge, RepPictureDelete, RepPictureGet, RepPictureListByCompany, RepPictureMerge, RepPlaceDelete, RepPlaceGet, RepPlaceListByCompany, RepPlaceMerge, RepProviderAdvancedGet, RepProviderAdvancedListByCompany, RepProviderBatchDelete, RepProviderBatchMerge, RepProviderConfigBatchMerge, RepProviderConfigDelete, RepProviderConfigGet, RepProviderConfigListByCompany, RepProviderConfigMerge, RepProviderConfigurationBatchMerge, RepProviderConfigurationDelete, RepProviderConfigurationGet, RepProviderConfigurationListByCompany, RepProviderConfigurationMerge, RepProviderControlGet, RepProviderControlListByCompany, RepProviderDelete, RepProviderGeneralGet, RepProviderGeneralListByCompany, RepProviderGet, RepProviderListByCompany, RepProviderMerge, RepProviderRegistrationDelete, RepProviderRegistrationGet, RepProviderRegistrationListByCompany, RepProviderRegistrationMerge, RepProviderScriptDelete, RepProviderScriptGet, RepProviderScriptListByCompany, RepProviderScriptMerge, RepReportResultDelete, RepReportResultGet, RepReportResultListByCompany, RepReportResultMerge, RepReportScheduleDelete, RepReportScheduleGet, RepReportScheduleListByCompany, RepReportScheduleMerge, RepReportTemplateDelete, RepReportTemplateGet, RepReportTemplateListByCompany, RepReportTemplateMerge, RepSelfContact, RepSelfGet, RepSelfLogout, RepSelfPassword, RepSelfPreferences, RepSessionDelete, RepSessionListByCompany, RepSessionListByUser, RepUserAdvancedGet, RepUserAdvancedListByCompany, RepUserDelete, RepUserGeneralGet, RepUserGeneralListByCompany, RepUserGet, RepUserGroupDelete, RepUserGroupGet, RepUserGroupListByCompany, RepUserGroupMerge, RepUserListByCompany, RepUserMerge } from '@trakit/commands';
1
+ import { Payload, RepAssetAdvancedGet, RepAssetAdvancedListByCompany, RepAssetBatchMerge, RepAssetDelete, RepAssetDispatchMerge, RepAssetGeneralGet, RepAssetGeneralListByCompany, RepAssetGet, RepAssetListByCompany, RepAssetMerge, RepAssetMessageBatchMerge, RepAssetMessageDelete, RepAssetMessageGet, RepAssetMessageListByAsset, RepAssetMessageListByCompany, RepAssetMessageMerge, RepAssetSuspend, RepBehaviourBatchMerge, RepBehaviourDelete, RepBehaviourGet, RepBehaviourListByCompany, RepBehaviourLogBatchDeleteByAsset, RepBehaviourLogBatchDeleteByBehaviour, RepBehaviourLogBatchDeleteByScript, RepBehaviourLogListByAsset, RepBehaviourLogListByBehaviour, RepBehaviourLogListByScript, RepBehaviourMerge, RepBehaviourScriptDelete, RepBehaviourScriptGet, RepBehaviourScriptListByCompany, RepBehaviourScriptMerge, RepCompanyDelete, RepCompanyDirectoryGet, RepCompanyDirectoryListByCompany, RepCompanyGeneralGet, RepCompanyGeneralListByCompany, RepCompanyGet, RepCompanyMerge, RepCompanyPolicyGet, RepCompanyPolicyListByCompany, RepCompanyResellerDelete, RepCompanyResellerGet, RepCompanyResellerMerge, RepCompanyStyleGet, RepCompanyStyleListByCompany, RepContactBatchDelete, RepContactBatchMerge, RepContactDelete, RepContactGet, RepContactListByCompany, RepContactMerge, RepDashcamGet, RepDashcamListByCompany, RepDashcamLiveListByCompany, RepDispatchJobBatchMerge, RepDispatchJobDelete, RepDispatchJobGet, RepDispatchJobListByAsset, RepDispatchJobListByCompany, RepDispatchJobMerge, RepDispatchTaskBatchMerge, RepDispatchTaskDelete, RepDispatchTaskGet, RepDispatchTaskListByAsset, RepDispatchTaskListByCompany, RepDispatchTaskMerge, RepDocumentDelete, RepDocumentGet, RepDocumentListByCompany, RepDocumentMerge, RepFormResultBatchMerge, RepFormResultDelete, RepFormResultGet, RepFormResultListByCompany, RepFormResultMerge, RepFormTemplateDelete, RepFormTemplateGet, RepFormTemplateListByCompany, RepFormTemplateMerge, RepIconDelete, RepIconGet, RepIconListByCompany, RepIconMerge, Reply, RepMachineDelete, RepMachineGet, RepMachineListByCompany, RepMachineMerge, RepMaintenanceJobDelete, RepMaintenanceJobGet, RepMaintenanceJobListByCompany, RepMaintenanceJobMerge, RepMaintenanceScheduleDelete, RepMaintenanceScheduleGet, RepMaintenanceScheduleListByCompany, RepMaintenanceScheduleMerge, RepPictureDelete, RepPictureGet, RepPictureListByCompany, RepPictureMerge, RepPlaceDelete, RepPlaceGet, RepPlaceListByCompany, RepPlaceMerge, RepProviderAdvancedGet, RepProviderAdvancedListByCompany, RepProviderBatchDelete, RepProviderBatchMerge, RepProviderConfigBatchMerge, RepProviderConfigDelete, RepProviderConfigGet, RepProviderConfigListByCompany, RepProviderConfigMerge, RepProviderConfigurationBatchMerge, RepProviderConfigurationDelete, RepProviderConfigurationGet, RepProviderConfigurationListByCompany, RepProviderConfigurationMerge, RepProviderControlGet, RepProviderControlListByCompany, RepProviderDelete, RepProviderGeneralGet, RepProviderGeneralListByCompany, RepProviderGet, RepProviderListByCompany, RepProviderMerge, RepProviderRegistrationDelete, RepProviderRegistrationGet, RepProviderRegistrationListByCompany, RepProviderRegistrationMerge, RepProviderScriptDelete, RepProviderScriptGet, RepProviderScriptListByCompany, RepProviderScriptMerge, RepReportResultDelete, RepReportResultGet, RepReportResultListByCompany, RepReportResultMerge, RepReportScheduleDelete, RepReportScheduleGet, RepReportScheduleListByCompany, RepReportScheduleMerge, RepReportTemplateDelete, RepReportTemplateGet, RepReportTemplateListByCompany, RepReportTemplateMerge, RepSelfGet, RepSelfLogout, RepSelfPassword, RepSessionDelete, RepSessionListByCompany, RepSessionListByUser, RepUserAdvancedGet, RepUserAdvancedListByCompany, RepUserDelete, RepUserGeneralGet, RepUserGeneralListByCompany, RepUserGet, RepUserGroupDelete, RepUserGroupGet, RepUserGroupListByCompany, RepUserGroupMerge, RepUserListByCompany, RepUserMerge } from '@trakit/commands';
2
2
  import { codified, email, expression, guid, int, IRequestable, JsonObject, nothing, SyncName, SystemsOfUnits, Timezone, ulong, url, UserNotifications } from '@trakit/objects';
3
3
  import { TrakitEvent, TrakitEventHandler } from './Events';
4
4
  import { TrakitBaseCommander } from './TrakitBaseCommander';
@@ -95,7 +95,7 @@ export declare abstract class TrakitObjectCommander<TRequest> extends TrakitBase
95
95
  * @param pictures A list of {@link Picture.id}s to associate with your {@link Contact}.
96
96
  * @returns The reply from the update contact command.
97
97
  */
98
- updateContact(name?: string, notes?: string, otherNames?: Map<string, string | null>, emails?: Map<string, string | null>, phones?: Map<string, ulong | null>, addresses?: Map<string, string | null>, urls?: Map<string, url | null>, dates?: Map<string, Date | null>, options?: Map<string, string | null>, roles?: string[], pictures?: ulong[]): Promise<RepSelfContact>;
98
+ updateContact(name?: string, notes?: string, otherNames?: Map<string, string | null>, emails?: Map<string, string | null>, phones?: Map<string, ulong | null>, addresses?: Map<string, string | null>, urls?: Map<string, url | null>, dates?: Map<string, Date | null>, options?: Map<string, string | null>, roles?: string[], pictures?: ulong[]): Promise<Reply>;
99
99
  /**
100
100
  * Allows a session {@link User} to change their own password.
101
101
  * @param oldPassword Your current password, as verification that you are the account owner.
@@ -110,10 +110,15 @@ export declare abstract class TrakitObjectCommander<TRequest> extends TrakitBase
110
110
  * @param notify Notification preferences.
111
111
  * @param formats Format templates for dates, times, etc...
112
112
  * @param measurements Measurement system preferences.
113
- * @param options Saved JSON data used by client applications.
114
- * @returns The reply from the update preferences command.
113
+ * @returns The reply from the update preferences command.
114
+ */
115
+ updatePreferences(language?: codified, timezone?: Timezone | string, notify?: UserNotifications[] | JsonObject[], formats?: Map<string, string> | JsonObject, measurements?: Map<string, SystemsOfUnits> | JsonObject): Promise<Reply>;
116
+ /**
117
+ * Allows a {@link User} to change their own state flags.
118
+ * @param options Saved JSON data used by client applications.
119
+ * @returns The reply from the update state command.
115
120
  */
116
- updatePreferences(language?: codified, timezone?: Timezone | string, notify?: UserNotifications[] | JsonObject[], formats?: Map<string, string> | JsonObject, measurements?: Map<string, SystemsOfUnits> | JsonObject, options?: Map<string, string> | JsonObject): Promise<RepSelfPreferences>;
121
+ updateState(options?: Map<string, string> | JsonObject): Promise<Reply>;
117
122
  /**
118
123
  * Retrieves a given {@link Company} from the server by its {@link Company.id}.
119
124
  * @param id
package/index.d.ts CHANGED
@@ -19,7 +19,7 @@ import { TrakitSocketCommander, TrakitSocketStatus } from "./WebSocket/TrakitSoc
19
19
  /**
20
20
  * Version number for this release.
21
21
  */
22
- export declare const version = "0.0.51";
22
+ export declare const version = "0.0.53";
23
23
  /**
24
24
  * API exports
25
25
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@trakit/sync",
3
3
  "type": "module",
4
- "version": "0.0.51",
4
+ "version": "0.0.53",
5
5
  "main": "./trakit-sync.min.js",
6
6
  "types": "./index.d.ts",
7
7
  "scripts": {
@@ -35,7 +35,7 @@
35
35
  "vitest": "^4.0.7"
36
36
  },
37
37
  "dependencies": {
38
- "@trakit/commands": "^0.0.26",
39
- "@trakit/objects": "^0.0.28"
38
+ "@trakit/commands": "^0.0.27",
39
+ "@trakit/objects": "^0.0.29"
40
40
  }
41
41
  }
@@ -1,7 +1,7 @@
1
- function e(e,t){return{errorCode:h.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=rr.capitalize(e)))e="CompanyStyle";else e=rr.singularize(e);return e}async function s(t){try{return await(await fetch(t)).json()}catch(t){throw e(t)}}function r(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(yr)].map((e=>rr.pluralize(e.toLowerCase()))).join("/"),!n.batch){switch(e.getKey&&(s+="/"+e.getKey()),n.kind){case"Get":break;case"List":switch(n.filter){case"Asset":s=n.object in wr?wr[n.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${s}`;break;case"BillingProfile":s=n.object in gr?gr[n.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${s}`;break;case"Company":s=n.object in mr?mr[n.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${s}`;break;case"User":s=`users/${encodeURIComponent(e.user.login)}/${s}`}if(rr.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),rr.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),rr.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),rr.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]}async function n(e,t,s="GET",r=null,n=null){const i=new Map(n),o={method:s,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==s&&(o.body=r),e.machine?i.set("Authorization",e.machine.secret?.length?"HMAC256 "+btoa(e.machine.key+":"+await e.machine.createHmacSignature(t,s,o.body?.length??0,new Date)):"Machine "+btoa(e.machine.key)):e.ghostId&&i.set("Authorization","Bearer "+e.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(t,o)}function i(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"+rr.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function o(e){return e.reduce(((e,t)=>e.concat(br[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function a(e){const t=[];for(const[s,r]of Object.entries(Br)){const n=r.map((e=>br[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Br[t])),[]);for(const[r,n]of Object.entries(br))!s.includes(r)&&n.some((t=>e.includes(t)))&&t.push(r);return t}import*as c from"@trakit/commands";import{ErrorCode as h,RepSelfGet as u,ReplySync as d,ReplySyncList as p,ReplySyncGet as l,ReplySyncDelete as m,ReplySyncBatchDelete as w,PaySelfGet as g,PaySelfLogin as y,PaySelfLogout as v,PaySelfContact as f,PaySelfPassword as b,PaySelfPreferences as C,PayCompanyGet as P,PayCompanyMerge as S,PayCompanyDelete as R,PayCompanyRestore as k,PayCompanyGeneralListByCompany as A,PayCompanyGeneralGet as M,PayCompanyPolicyListByCompany as D,PayCompanyPolicyGet as I,PayCompanyStyleListByCompany as T,PayCompanyStyleGet as G,PayCompanyDirectoryListByCompany as U,PayCompanyDirectoryGet as B,PayCompanyResellerGet as J,PayCompanyResellerMerge as E,PayCompanyResellerDelete as L,PayCompanyResellerRestore as x,PayContactListByCompany as N,PayContactGet as O,PayContactMerge as _,PayContactDelete as F,PayContactRestore as H,PayContactBatchMerge as q,PayContactBatchDelete as $,PayUserListByCompany as W,PayUserGet as j,PayUserMerge as z,PayUserDelete as K,PayUserRestore as Z,PayUserGeneralListByCompany as Q,PayUserGeneralGet as V,PayUserAdvancedListByCompany as X,PayUserAdvancedGet as Y,PayUserGroupListByCompany as ee,PayUserGroupGet as te,PayUserGroupMerge as se,PayUserGroupDelete as re,PayUserGroupRestore as ne,PayMachineListByCompany as ie,PayMachineGet as oe,PayMachineMerge as ae,PayMachineDelete as ce,PayMachineRestore as he,PaySessionListByCompany as ue,PaySessionListByUser as de,PaySessionDelete as pe,PayIconListByCompany as le,PayIconGet as me,PayIconMerge as we,PayIconDelete as ge,PayIconRestore as ye,PayPictureListByCompany as ve,PayPictureGet as fe,PayPictureMerge as be,PayPictureDelete as Ce,PayPictureRestore as Pe,PayDocumentListByCompany as Se,PayDocumentGet as Re,PayDocumentMerge as ke,PayDocumentDelete as Ae,PayDocumentRestore as Me,PayFormTemplateListByCompany as De,PayFormTemplateGet as Ie,PayFormTemplateMerge as Te,PayFormTemplateDelete as Ge,PayFormTemplateRestore as Ue,PayFormResultListByCompany as Be,PayFormResultGet as Je,PayFormResultMerge as Ee,PayFormResultBatchMerge as Le,PayFormResultDelete as xe,PayFormResultRestore as Ne,PayDashcamListByCompany as Oe,PayDashcamGet as _e,PayDashcamLiveListByCompany as Fe,PayAssetListByCompany as He,PayAssetGet as qe,PayAssetMerge as $e,PayAssetBatchMerge as We,PayAssetDelete as je,PayAssetRestore as ze,PayAssetSuspend as Ke,PayAssetReactivate as Ze,PayAssetGeneralListByCompany as Qe,PayAssetGeneralGet as Ve,PayAssetAdvancedListByCompany as Xe,PayAssetAdvancedGet as Ye,PayAssetDispatchMerge as et,PayDispatchTaskListByCompany as tt,PayDispatchTaskListByAsset as st,PayDispatchTaskGet as rt,PayDispatchTaskMerge as nt,PayDispatchTaskBatchMerge as it,PayDispatchTaskDelete as ot,PayDispatchTaskRestore as at,PayDispatchJobListByCompany as ct,PayDispatchJobListByAsset as ht,PayDispatchJobGet as ut,PayDispatchJobMerge as dt,PayDispatchJobBatchMerge as pt,PayDispatchJobDelete as lt,PayDispatchJobRestore as mt,PayDispatchJobChange as wt,PayDispatchJobCancel as gt,PayAssetMessageListByCompany as yt,PayAssetMessageListByAsset as vt,PayAssetMessageGet as ft,PayAssetMessageMerge as bt,PayAssetMessageBatchMerge as Ct,PayAssetMessageDelete as Pt,PayAssetMessageRestore as St,PayPlaceListByCompany as Rt,PayPlaceGet as kt,PayPlaceMerge as At,PayPlaceDelete as Mt,PayPlaceRestore as Dt,PayProviderListByCompany as It,PayProviderGet as Tt,PayProviderMerge as Gt,PayProviderBatchMerge as Ut,PayProviderBatchDelete as Bt,PayProviderDelete as Jt,PayProviderRestore as Et,PayProviderGeneralListByCompany as Lt,PayProviderGeneralGet as xt,PayProviderAdvancedListByCompany as Nt,PayProviderAdvancedGet as Ot,PayProviderControlListByCompany as _t,PayProviderControlGet as Ft,PayProviderScriptListByCompany as Ht,PayProviderScriptGet as qt,PayProviderScriptMerge as $t,PayProviderScriptDelete as Wt,PayProviderScriptRestore as jt,PayProviderConfigListByCompany as zt,PayProviderConfigGet as Kt,PayProviderConfigMerge as Zt,PayProviderConfigBatchMerge as Qt,PayProviderConfigDelete as Vt,PayProviderConfigRestore as Xt,PayProviderConfigurationListByCompany as Yt,PayProviderConfigurationGet as es,PayProviderConfigurationMerge as ts,PayProviderConfigurationBatchMerge as ss,PayProviderConfigurationDelete as rs,PayProviderConfigurationRestore as ns,PayProviderRegistrationListByCompany as is,PayProviderRegistrationGet as os,PayProviderRegistrationMerge as as,PayProviderRegistrationDelete as cs,PayBehaviourListByCompany as hs,PayBehaviourGet as us,PayBehaviourMerge as ds,PayBehaviourBatchMerge as ps,PayBehaviourDelete as ls,PayBehaviourRestore as ms,PayBehaviourScriptListByCompany as ws,PayBehaviourScriptGet as gs,PayBehaviourScriptMerge as ys,PayBehaviourScriptDelete as vs,PayBehaviourScriptRestore as fs,PayBehaviourLogListByAsset as bs,PayBehaviourLogBatchDeleteByAsset as Cs,PayBehaviourLogListByBehaviour as Ps,PayBehaviourLogBatchDeleteByBehaviour as Ss,PayBehaviourLogListByScript as Rs,PayBehaviourLogBatchDeleteByScript as ks,PayReportTemplateListByCompany as As,PayReportTemplateGet as Ms,PayReportTemplateMerge as Ds,PayReportTemplateDelete as Is,PayReportTemplateRestore as Ts,PayReportScheduleListByCompany as Gs,PayReportScheduleGet as Us,PayReportScheduleMerge as Bs,PayReportScheduleDelete as Js,PayReportScheduleRestore as Es,PayReportResultListByCompany as Ls,PayReportResultGet as xs,PayReportResultMerge as Ns,PayReportResultDelete as Os,PayReportResultRestore as _s,PayMaintenanceScheduleListByCompany as Fs,PayMaintenanceScheduleGet as Hs,PayMaintenanceScheduleMerge as qs,PayMaintenanceScheduleDelete as $s,PayMaintenanceScheduleRestore as Ws,PayMaintenanceJobListByCompany as js,PayMaintenanceJobGet as zs,PayMaintenanceJobMerge as Ks,PayMaintenanceJobDelete as Zs,PayMaintenanceJobRestore as Qs,SubscriptionType as Vs,Reply as Xs,PaySubscriptionMerge as Ys,RepSubscription as er,PaySubscriptionDelete as tr,PaySubscriptionList as sr}from"@trakit/commands";import{utility as rr,Machine as nr,serialization as ir}from"@trakit/objects";class or{type;constructor(e){this.type=e}}class ar extends or{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class cr extends or{account;constructor(e,t){super(e),this.account=t}}class hr extends ar{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class ur extends ar{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class dr extends ar{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}class pr{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 u?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof nr||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new u({errorCode:h.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new u)}t=new Map;command(t){const s=t.constructor.name+JSON.stringify(t.toJSON());let r=this.t.get(s);return r||this.t.set(s,r=new Promise((async(r,n)=>{let i=null,o=null,a=null;try{i=await this.requestCreate(t)}catch(t){o=e(t)}try{o=o??await this.requestRelay(i)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===h.success?r:n)(a),this.t.delete(s)}))),r}}class lr extends pr{i=new Map;o(e){this.setAuth(e??new u({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 cr("account",this.account)))}h(e,t,s){this.fire("list",(()=>new hr("list",e,t,s)))}u(e,t,s){this.fire("update",(()=>new ur("update",e,t,s)))}p(e,t,s){this.fire("delete",(()=>new dr("delete",e,t,s)))}on(e,t){let s=this.i.get(e);s||this.i.set(e,s=[]);const r=s.includes(t);return r||s.push(t),!r}off(e,t){const s=this.i.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.i.get(e)?.slice();if(s?.length){const e=t();s.forEach((t=>t.call(this,e)),this)}}handles(e,t){return this.i.get(e)?.includes(t)??!1}dispose(){for(const e of[...this.i.keys()])this.off(e)}async command(e){const t=await super.command(e);if(t instanceof d&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof p?s.filter?t.getList().forEach((e=>this.u(s.object,r,e))):this.h(s.object,r,t.getList()):t instanceof l?this.u(s.object,r,t.getObject()):t instanceof m?this.p(s.object,r,t.getKey()):t instanceof w&&t.getResults().forEach((e=>this.p(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new g);return this.o(e),e}async login(e,t,s){const r=await this.command(new y({username:e,password:t,userAgent:s??null}));return this.o(r),r}logout(){const e=this.command(new v);return this.o(new u),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new f({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 b({current:e,password:t}))}updatePreferences(e,t,s,r,n,i){return this.command(new C({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?ir.fromMap(r):r??null,measurements:n instanceof Map?ir.fromMap(n):n??null,options:i instanceof Map?ir.fromMap(i):i??null}))}getCompany(e){return this.command(new P({company:{id:e}}))}mergeCompany(e){return this.command(new S({company:e}))}removeCompany(e){return this.command(new R({company:{id:e}}))}restoreCompany(e){return this.command(new k({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new A({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new M({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new D({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new I({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new T({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new G({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new U({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new B({company:{id:e}}))}getReseller(e){return this.command(new J({company:{id:e}}))}mergeReseller(e){return this.command(new E({company:e}))}removeReseller(e){return this.command(new L({company:{id:e}}))}restoreReseller(e){return this.command(new x({company:{id:e}}))}listContacts(e,t){return this.command(new N({...t,company:{id:e}}))}getContact(e){return this.command(new O({contact:{id:e}}))}mergeContact(e){return this.command(new _({contact:e}))}removeContact(e){return this.command(new F({contact:{id:e}}))}restoreContact(e){return this.command(new H({contact:{id:e}}))}multiMergeContact(e){return this.command(new q({contacts:e}))}multiRemoveContact(e){return this.command(new $({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new W({...t,company:{id:e}}))}getUser(e){return this.command(new j({user:{login:e}}))}mergeUser(e){return this.command(new z({user:e}))}removeUser(e){return this.command(new K({user:{login:e}}))}restoreUser(e){return this.command(new Z({user:{login:e}}))}listUserGenerals(e,t){return this.command(new Q({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new V({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new X({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new Y({user:{login:e}}))}listUserGroups(e,t){return this.command(new ee({...t,company:{id:e}}))}getUserGroup(e){return this.command(new te({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new se({userGroup:e}))}removeUserGroup(e){return this.command(new re({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new ne({userGroup:{id:e}}))}listMachines(e,t){return this.command(new ie({...t,company:{id:e}}))}getMachine(e){return this.command(new oe({machine:{id:e}}))}mergeMachine(e){return this.command(new ae({machine:e}))}removeMachine(e){return this.command(new ce({machine:{id:e}}))}restoreMachine(e){return this.command(new he({machine:{id:e}}))}listSessions(e,t){return this.command(new ue({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new de({...t,user:{login:e}}))}killSession(e){return this.command(new pe({session:{handle:e}}))}listIcons(e,t){return this.command(new le({...t,company:{id:e}}))}getIcon(e){return this.command(new me({icon:{id:e}}))}mergeIcon(e){return this.command(new we({icon:e}))}removeIcon(e){return this.command(new ge({icon:{id:e}}))}restoreIcon(e){return this.command(new ye({icon:{id:e}}))}listPictures(e,t){return this.command(new ve({...t,company:{id:e}}))}getPicture(e){return this.command(new fe({picture:{id:e}}))}mergePicture(e){return this.command(new be({picture:e}))}removePicture(e){return this.command(new Ce({picture:{id:e}}))}restorePicture(e){return this.command(new Pe({picture:{id:e}}))}listDocuments(e,t){return this.command(new Se({...t,company:{id:e}}))}getDocument(e){return this.command(new Re({document:{id:e}}))}mergeDocument(e){return this.command(new ke({document:e}))}removeDocument(e){return this.command(new Ae({document:{id:e}}))}restoreDocument(e){return this.command(new Me({document:{id:e}}))}listFormTemplates(e,t){return this.command(new De({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Ie({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Te({formTemplate:e}))}removeFormTemplate(e){return this.command(new Ge({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Ue({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Be({...t,company:{id:e}}))}getFormResult(e){return this.command(new Je({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ee({formResult:e}))}multiMergeFormResult(e){return this.command(new Le({formResult:{id:e}}))}removeFormResult(e){return this.command(new xe({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Ne({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new Oe({...t,company:{id:e}}))}getDashcamData(e){return this.command(new _e({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new Fe({...t,company:{id:e}}))}listAssets(e,t){return this.command(new He({...t,company:{id:e}}))}getAsset(e){return this.command(new qe({asset:{id:e}}))}mergeAsset(e){return this.command(new $e({asset:e}))}multiMergeAsset(e){return this.command(new We({assets:e}))}removeAsset(e){return this.command(new je({asset:{id:e}}))}restoreAsset(e){return this.command(new ze({asset:{id:e}}))}suspendAsset(e){return this.command(new Ke({asset:{id:e}}))}reviveAsset(e){return this.command(new Ze({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new Qe({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new Ve({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new Xe({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new Ye({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new et({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new tt({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new st({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new rt({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new nt({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new it({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new ot({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new at({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new ct({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new ht({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new ut({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new dt({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new pt({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new lt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new mt({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new wt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new gt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new yt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new vt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new ft({message:{id:e}}))}mergeAssetMessage(e){return this.command(new bt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new Ct({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new Pt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new St({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new Rt({...t,company:{id:e}}))}getPlace(e){return this.command(new kt({place:{id:e}}))}mergePlace(e){return this.command(new At({place:e}))}removePlace(e){return this.command(new Mt({place:{id:e}}))}restorePlace(e){return this.command(new Dt({place:{id:e}}))}listProviders(e,t){return this.command(new It({...t,company:{id:e}}))}getProvider(e){return this.command(new Tt({provider:{id:e}}))}mergeProvider(e){return this.command(new Gt({provider:e}))}multiMergeProvider(e){return this.command(new Ut({providers:e}))}multiRemoveProvider(e){return this.command(new Bt({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Jt({provider:{id:e}}))}restoreProvider(e){return this.command(new Et({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Lt({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new xt({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Nt({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Ot({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new _t({...t,company:{id:e}}))}getProviderControl(e){return this.command(new Ft({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new Ht({...t,company:{id:e}}))}getProviderScript(e){return this.command(new qt({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new $t({providerScript:e}))}removeProviderScript(e){return this.command(new Wt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new jt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new zt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Kt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new Zt({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new Qt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new Vt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new Xt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new Yt({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new es({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new ts({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new ss({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new rs({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new ns({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new is({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new os({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new as({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new cs({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new hs({...t,company:{id:e}}))}getBehaviour(e){return this.command(new us({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new ds({behaviour:e}))}multiMergeBehaviour(e){return this.command(new ps({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new ls({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new ms({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ws({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new gs({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new ys({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new vs({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new fs({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new bs({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new Cs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new Ps({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new Ss({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new Rs({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new ks({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new As({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Ms({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Ds({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Is({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Ts({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Gs({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Us({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Bs({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Js({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Es({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Ls({...t,company:{id:e}}))}getReportResult(e){return this.command(new xs({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Ns({reportResult:e}))}removeReportResult(e){return this.command(new Os({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new _s({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new Fs({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new Hs({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new qs({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new $s({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Ws({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new js({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new zs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Ks({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new Zs({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new Qs({maintenanceJob:{id:e}}))}}const mr={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",UserAuthentication:"/companies/{companyId}/users/authentications",UserState:"/companies/{companyId}/users/states",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:""},wr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},gr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},yr=/[A-Z][a-z]+/;class vr extends lr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??vr.URI_PROD)}requestCreate(e){const[t,s]=r(e);return n(this.account,this.createBaseUrl(s),t,"GET"===t?null:JSON.stringify(e.toJSON()),this.headers)}requestRelay(e){return s(e)}}const fr=/^(.+?)(Merged|Deleted|Suspended)$/,br={Company:[Vs.companyGeneral,Vs.companyLabels,Vs.companyPolicies],CompanyGeneral:[Vs.companyGeneral],CompanyDirectory:[],CompanyStyle:[Vs.companyLabels],CompanyPolicy:[Vs.companyPolicies],CompanyReseller:[Vs.companyReseller],Contact:[Vs.contact],Machine:[Vs.machine],User:[Vs.userGeneral,Vs.userAdvanced,Vs.userAuthentication],UserGeneral:[Vs.userGeneral],UserAdvanced:[Vs.userAdvanced],UserAuthentication:[Vs.userAuthentication],UserState:[Vs.userState],UserGroup:[Vs.userGroup],Session:[],Dashcam:[],Icon:[Vs.icon],Picture:[Vs.picture],Document:[Vs.document],FormTemplate:[Vs.formTemplate],FormResult:[Vs.formResult],Asset:[Vs.assetGeneral,Vs.assetAdvanced,Vs.assetDispatch],AssetGeneral:[Vs.assetGeneral],AssetAdvanced:[Vs.assetAdvanced],AssetDispatch:[Vs.assetDispatch],AssetMessage:[Vs.assetMessage],AssetAlert:[],DispatchTask:[Vs.dispatchTask],DispatchJob:[Vs.dispatchJob],MaintenanceSchedule:[Vs.maintenanceSchedule],MaintenanceJob:[Vs.maintenanceJob],Place:[Vs.placeGeneral],BehaviourScript:[Vs.behaviourScript],Behaviour:[Vs.behaviour],BehaviourLog:[Vs.behaviourLog],Provider:[Vs.providerGeneral,Vs.providerAdvanced,Vs.providerControl],ProviderGeneral:[Vs.providerGeneral],ProviderAdvanced:[Vs.providerAdvanced],ProviderControl:[Vs.providerControl],ProviderConfiguration:[Vs.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[Vs.providerScript],ProviderConfig:[Vs.providerConfig],ProviderRegistration:[Vs.providerRegistration],ReportTemplate:[Vs.reportTemplate],ReportSchedule:[Vs.reportSchedule],ReportResult:[Vs.reportResult],BillingProfile:[Vs.billingProfile],BillingReport:[Vs.billingReport],BillableHostingRule:[Vs.billingHosting],BillableHostingLicense:[Vs.billingLicense]};class Cr{#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}expireRegion(e,t=!1){const s=t?0:(new Date).valueOf();return this.#t(e,new Date(s+3e5))}expireRegions(e,t=!1){return e.map((e=>this.expireRegion(e,t)))}preserveRegion(e){const t=this.#e.get(e);return this.#t(e),t||null}preserveRegions(e){return e.map((e=>this.preserveRegion(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var Pr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(Pr||(Pr={}));class Sr{static fromJson(e){switch(e?.kind){case Pr.maintenance:return new Rr(e);case Pr.upgrade:return new kr(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=rr.date(e?.serverTime),this.message=e?.message??""}}class Rr extends Sr{starting;ending;constructor(e){super(e),this.starting=rr.date(e?.starting),this.ending=rr.date(e?.ending)}}class kr extends Sr{eta;reload;constructor(e){super(e),this.eta=rr.date(e?.eta),this.reload=!!e?.reload}}class Ar extends or{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Mr extends or{reply;constructor(e,t){super(e),this.reply=t}}class Dr extends or{broadcast;constructor(e,t){super(e),this.broadcast=Sr.fromJson(t)}}const Ir="connection",Tr="dis"+Ir;var Gr;!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"}(Gr||(Gr={}));class Ur extends lr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=fr.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 Gr.opening;case WebSocket.OPEN:return this.#a?Gr.open:Gr.opening;case WebSocket.CLOSING:return Gr.closing;default:return Gr.closed}}get ready(){return this.#a&&this.#c}l(e){const t=this.i.get("open");if(t?.length){const s=new cr("open",e);t.forEach((e=>e.call(this,s)))}}m(e){const t=this.i.get("close");if(t?.length){const s=new Mr("close",e);t.forEach((e=>e.call(this,s)))}}v(e,t){const s=this.i.get("message");if(s?.length){const r=new Ar("message",e,t);s.forEach((e=>e.call(this,r)))}}C(e){const t=this.i.get("error");if(t?.length){const s=new Mr("error",e);t.forEach((e=>e.call(this,s)))}}P(e){const t=this.i.get("broadcast");if(t?.length){const s=new Dr("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.C(new Xs({errorCode:h.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:Gr.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:h.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===Tr?r:{...r,reqId:e,errorCode:h.service,errorDetails:{...s}});this.m?.(new Xs(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.v(t,s),t){case"connectionResponse":this.#f(s),this.#s=new Date(this.#r),this.#a=!0,this.#d(Ir,s),this.o(),this.l(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#f(s),this.o();break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#f(s),this.o();break;case"sessionGeneralMerged":this.#b([,"userGeneral","Merged"],this.#C(s)),this.o();break;case"sessionAdvancedMerged":this.#b([,"userAdvanced","Merged"],this.#P(s)),this.o();break;case"sessionAuthenticationMerged":this.#b([,"userAuthentication","Merged"],s),this.o();break;case"sessionStateMerged":this.#b([,"userState","Merged"],s),this.o();break;case"sessionMachineMerged":this.#b([,"machine","Merged"],this.#P(s)),this.o();break;case"broadcast":this.P(s)}if(t.endsWith("Response"))this.#d(s.reqId,s);else if(!t.startsWith("session")){const e=fr.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 u(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 c["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 o=new i({errorCode:h.success,message:e[2]+" event",[e[1]]:s});if(o.store())switch(e[2]){case"Merged":case"Suspended":this.u(r,n,o.getObject());break;case"Deleted":this.p(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 o}reconnectEnabled=!0;#m=0;#v=0;keepAliveEnabled=!1;#y=0;constructor(e,t){super(e,t??Ur.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===Gr.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(Ir,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new u({errorCode:h.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case Gr.opening:case Gr.open:this.#c=!1,this.reconnectEnabled=!1,this.#u.set(Tr,(s=>{(0===s.errorCode?e:t)(new Xs(s))})),this.#o.close(1e3,"Bye!");break;default:t(new Xs({errorCode:h.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}requestCreate(e){return Promise.resolve([i(e),e.toJSON()])}requestRelay(t){const s=t[0],r=t[1]||{};return new Promise(((n,i)=>{const o=this.state;switch(o){case Gr.open:const a=++this.#h,c=setTimeout((()=>this.#d(a,{reqId:a,errorCode:h.unknown,message:"Command timeout"})),12e4);r.reqId=a,this.#u.set(a,(e=>{clearTimeout(c),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r)),this.#i=new Date}catch(t){this.#d(a,e(t))}this.resetKeepAlive();break;case Gr.closed:this.open().then((()=>this.requestRelay(t).then(n))).catch(i);break;default:i({errorCode:h.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:o}})}}))}resetKeepAlive(){return clearTimeout(this.#y),this.#y=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.requestRelay(["noop",{}])),3e5):0,Promise.resolve(0!==this.#y)}subscribe(e,t){return t?.length?this.command(new Ys({company:{id:e},subscriptionTypes:t})):Promise.resolve(new er({errorCode:h.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new tr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new er({errorCode:h.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new sr)}}const Br={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Jr extends lr{S;R;get autoConnect(){return this.S.reconnectEnabled}set autoConnect(e){this.S.reconnectEnabled=!!e,e&&this.S.state===Gr.closed&&this.S.open()}get socketOnline(){return this.S.state===Gr.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.R.baseAddress}set restAddress(e){this.R.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.setAuth(e.account),n=e=>this.fire(e.type,(()=>e));this.R=new vr(this.account,t??vr.URI_PROD),this.R.on("account",r),this.S=new Ur(this.account,s??Ur.URI_PROD),this.S.on("account",r),this.S.on("open",(e=>this.#S(e.account))),this.S.on("close",(e=>this.#R(e.reply)));for(const e of["account","list","update","delete"])this.R.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.R.dispose(),this.S.dispose(),this.R=this.S=null}setAuth(e){super.setAuth(e),this.R?.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)}requestCreate(e){throw new Error("Method not implemented.")}requestRelay(e){throw new Error("Method not implemented.")}rest(e){return this.R.command(e)}socket(e){return this.S.command(e)}#S(e){this.#k.forEach(((e,t)=>{this.sync(t,a(e.reset()))})),this.#A()}#R(e){clearTimeout(this.#M)}isSynced(e,t){let s=this.S.state===Gr.open;if(s){const r=this.#D(e);s=o(t).every((e=>r.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#D(e),r=t?[]:s.getExpiring();return a(s.regions.filter((e=>!r.includes(e))))}async sync(t,s){const r=[],n=this.#D(t),i=o(s).filter((e=>!n.regions.includes(e)));if(i.length>0){n.preserveRegions(i);const s=await this.S.subscribe(t,i);n.expireRegions((s.denied??[]).concat(s.invalid??[]),!0),a(s.merged??[]).forEach((s=>{const n=function(e,t){return c["Pay"+e+(t??"Get")]}(s,s.startsWith("Company")?"Get":"ListByCompany");r.push(n?this.command(new n({company:{id:t}})):Promise.reject(e(new Error(`No payload class could be made for sync type ${s}`))))}))}return Promise.all(r)}desync(e,t){const s=this.#D(e),r=t.reduce(((e,t)=>e.concat(br[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));return s.expireRegions(r),r}#k=new Map;#A(){const e=[];this.S.state===Gr.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 Cr),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:h.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=nr.capitalize(e)))e="CompanyStyle";else e=nr.singularize(e);return e}async function s(t){try{return await(await fetch(t)).json()}catch(t){throw e(t)}}function r(e){const t=e.getAction();let s="GET",r=new URLSearchParams,n=[...t.object.match(vr)].map((e=>nr.pluralize(e.toLowerCase()))).join("/");switch(t.object){case"Self":"Get"==t.kind?(s="GET",n="self"):(s="POST",n="self/"+t.filter.toLowerCase());break;case"Subscription":throw new Error(t.object+" only supported by TrakitSocketCommander",{cause:t});case"DispatchJob":switch(t.filter){case"Cancel":s=t.batch?"PATCH":"POST",n+="/cancel";break;case"Change":s=t.batch?"PATCH":"PUT"}default:if(!t.batch){switch(e.getKey&&(n=nr.isCompounded(t.object)?n.replace("/","/"+e.getKey()+"/"):n+"/"+e.getKey()),t.kind){case"Get":break;case"List":switch(t.filter){case"Asset":n=t.object in gr?gr[t.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${n}`;break;case"BillingProfile":n=t.object in yr?yr[t.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${n}`;break;case"Company":n=t.object in wr?wr[t.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${n}`;break;case"User":n=`users/${encodeURIComponent(e.user.login)}/${n}`}if(nr.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),nr.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),nr.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),nr.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":s="POST";break;case"Delete":s="DELETE";break;case"Restore":s="PATCH",n+="/restore";break;case"Suspend":s="PATCH",n+="/suspend";break;case"Reactivate":s="PATCH",n+="/revive"}break}switch(s="PATCH",t.kind){case"Get":case"List":s="GET";break;case"Merge":break;case"Delete":s="DELETE";break;case"Restore":n+="/restore";break;case"Suspend":n+="/suspend";break;case"Reactivate":n+="/revive"}}return[s,r.size?n+"?"+r.toString():n]}async function n(e,t,s="GET",r=null,n=null){const i=new Map(n),o={method:s,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==s&&(o.body=r),e.machine?i.set("Authorization",e.machine.secret?.length?"HMAC256 "+btoa(e.machine.key+":"+await e.machine.createHmacSignature(t,s,o.body?.length??0,new Date)):"Machine "+btoa(e.machine.key)):e.ghostId&&i.set("Authorization","Bearer "+e.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(t,o)}function i(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"+nr.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function o(e){return e.reduce(((e,t)=>e.concat(Cr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function a(e){const t=[];for(const[s,r]of Object.entries(Jr)){const n=r.map((e=>Cr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Jr[t])),[]);for(const[r,n]of Object.entries(Cr))!s.includes(r)&&n.some((t=>e.includes(t)))&&t.push(r);return t}import*as c from"@trakit/commands";import{ErrorCode as h,RepSelfGet as u,ReplySync as d,ReplySyncList as p,ReplySyncGet as l,ReplySyncDelete as m,ReplySyncBatchDelete as w,PaySelfGet as g,PaySelfLogin as y,PaySelfLogout as v,PaySelfContact as f,PaySelfPassword as b,PaySelfPreferences as C,PaySelfState as P,PayCompanyGet as S,PayCompanyMerge as R,PayCompanyDelete as k,PayCompanyRestore as A,PayCompanyGeneralListByCompany as M,PayCompanyGeneralGet as D,PayCompanyPolicyListByCompany as I,PayCompanyPolicyGet as T,PayCompanyStyleListByCompany as G,PayCompanyStyleGet as U,PayCompanyDirectoryListByCompany as B,PayCompanyDirectoryGet as J,PayCompanyResellerGet as E,PayCompanyResellerMerge as L,PayCompanyResellerDelete as x,PayCompanyResellerRestore as N,PayContactListByCompany as O,PayContactGet as _,PayContactMerge as F,PayContactDelete as H,PayContactRestore as q,PayContactBatchMerge as $,PayContactBatchDelete as W,PayUserListByCompany as j,PayUserGet as z,PayUserMerge as K,PayUserDelete as Z,PayUserRestore as Q,PayUserGeneralListByCompany as V,PayUserGeneralGet as X,PayUserAdvancedListByCompany as Y,PayUserAdvancedGet as ee,PayUserGroupListByCompany as te,PayUserGroupGet as se,PayUserGroupMerge as re,PayUserGroupDelete as ne,PayUserGroupRestore as ie,PayMachineListByCompany as oe,PayMachineGet as ae,PayMachineMerge as ce,PayMachineDelete as he,PayMachineRestore as ue,PaySessionListByCompany as de,PaySessionListByUser as pe,PaySessionDelete as le,PayIconListByCompany as me,PayIconGet as we,PayIconMerge as ge,PayIconDelete as ye,PayIconRestore as ve,PayPictureListByCompany as fe,PayPictureGet as be,PayPictureMerge as Ce,PayPictureDelete as Pe,PayPictureRestore as Se,PayDocumentListByCompany as Re,PayDocumentGet as ke,PayDocumentMerge as Ae,PayDocumentDelete as Me,PayDocumentRestore as De,PayFormTemplateListByCompany as Ie,PayFormTemplateGet as Te,PayFormTemplateMerge as Ge,PayFormTemplateDelete as Ue,PayFormTemplateRestore as Be,PayFormResultListByCompany as Je,PayFormResultGet as Ee,PayFormResultMerge as Le,PayFormResultBatchMerge as xe,PayFormResultDelete as Ne,PayFormResultRestore as Oe,PayDashcamListByCompany as _e,PayDashcamGet as Fe,PayDashcamLiveListByCompany as He,PayAssetListByCompany as qe,PayAssetGet as $e,PayAssetMerge as We,PayAssetBatchMerge as je,PayAssetDelete as ze,PayAssetRestore as Ke,PayAssetSuspend as Ze,PayAssetReactivate as Qe,PayAssetGeneralListByCompany as Ve,PayAssetGeneralGet as Xe,PayAssetAdvancedListByCompany as Ye,PayAssetAdvancedGet as et,PayAssetDispatchMerge as tt,PayDispatchTaskListByCompany as st,PayDispatchTaskListByAsset as rt,PayDispatchTaskGet as nt,PayDispatchTaskMerge as it,PayDispatchTaskBatchMerge as ot,PayDispatchTaskDelete as at,PayDispatchTaskRestore as ct,PayDispatchJobListByCompany as ht,PayDispatchJobListByAsset as ut,PayDispatchJobGet as dt,PayDispatchJobMerge as pt,PayDispatchJobBatchMerge as lt,PayDispatchJobDelete as mt,PayDispatchJobRestore as wt,PayDispatchJobChange as gt,PayDispatchJobCancel as yt,PayAssetMessageListByCompany as vt,PayAssetMessageListByAsset as ft,PayAssetMessageGet as bt,PayAssetMessageMerge as Ct,PayAssetMessageBatchMerge as Pt,PayAssetMessageDelete as St,PayAssetMessageRestore as Rt,PayPlaceListByCompany as kt,PayPlaceGet as At,PayPlaceMerge as Mt,PayPlaceDelete as Dt,PayPlaceRestore as It,PayProviderListByCompany as Tt,PayProviderGet as Gt,PayProviderMerge as Ut,PayProviderBatchMerge as Bt,PayProviderBatchDelete as Jt,PayProviderDelete as Et,PayProviderRestore as Lt,PayProviderGeneralListByCompany as xt,PayProviderGeneralGet as Nt,PayProviderAdvancedListByCompany as Ot,PayProviderAdvancedGet as _t,PayProviderControlListByCompany as Ft,PayProviderControlGet as Ht,PayProviderScriptListByCompany as qt,PayProviderScriptGet as $t,PayProviderScriptMerge as Wt,PayProviderScriptDelete as jt,PayProviderScriptRestore as zt,PayProviderConfigListByCompany as Kt,PayProviderConfigGet as Zt,PayProviderConfigMerge as Qt,PayProviderConfigBatchMerge as Vt,PayProviderConfigDelete as Xt,PayProviderConfigRestore as Yt,PayProviderConfigurationListByCompany as es,PayProviderConfigurationGet as ts,PayProviderConfigurationMerge as ss,PayProviderConfigurationBatchMerge as rs,PayProviderConfigurationDelete as ns,PayProviderConfigurationRestore as is,PayProviderRegistrationListByCompany as os,PayProviderRegistrationGet as as,PayProviderRegistrationMerge as cs,PayProviderRegistrationDelete as hs,PayBehaviourListByCompany as us,PayBehaviourGet as ds,PayBehaviourMerge as ps,PayBehaviourBatchMerge as ls,PayBehaviourDelete as ms,PayBehaviourRestore as ws,PayBehaviourScriptListByCompany as gs,PayBehaviourScriptGet as ys,PayBehaviourScriptMerge as vs,PayBehaviourScriptDelete as fs,PayBehaviourScriptRestore as bs,PayBehaviourLogListByAsset as Cs,PayBehaviourLogBatchDeleteByAsset as Ps,PayBehaviourLogListByBehaviour as Ss,PayBehaviourLogBatchDeleteByBehaviour as Rs,PayBehaviourLogListByScript as ks,PayBehaviourLogBatchDeleteByScript as As,PayReportTemplateListByCompany as Ms,PayReportTemplateGet as Ds,PayReportTemplateMerge as Is,PayReportTemplateDelete as Ts,PayReportTemplateRestore as Gs,PayReportScheduleListByCompany as Us,PayReportScheduleGet as Bs,PayReportScheduleMerge as Js,PayReportScheduleDelete as Es,PayReportScheduleRestore as Ls,PayReportResultListByCompany as xs,PayReportResultGet as Ns,PayReportResultMerge as Os,PayReportResultDelete as _s,PayReportResultRestore as Fs,PayMaintenanceScheduleListByCompany as Hs,PayMaintenanceScheduleGet as qs,PayMaintenanceScheduleMerge as $s,PayMaintenanceScheduleDelete as Ws,PayMaintenanceScheduleRestore as js,PayMaintenanceJobListByCompany as zs,PayMaintenanceJobGet as Ks,PayMaintenanceJobMerge as Zs,PayMaintenanceJobDelete as Qs,PayMaintenanceJobRestore as Vs,SubscriptionType as Xs,Reply as Ys,PaySubscriptionMerge as er,RepSubscription as tr,PaySubscriptionDelete as sr,PaySubscriptionList as rr}from"@trakit/commands";import{utility as nr,Machine as ir,serialization as or}from"@trakit/objects";class ar{type;constructor(e){this.type=e}}class cr extends ar{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class hr extends ar{account;constructor(e,t){super(e),this.account=t}}class ur extends cr{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class dr extends cr{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class pr extends cr{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}class lr{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 u?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof ir||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new u({errorCode:h.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new u)}t=new Map;command(t){const s=t.constructor.name+JSON.stringify(t.toJSON());let r=this.t.get(s);return r||this.t.set(s,r=new Promise((async(r,n)=>{let i=null,o=null,a=null;try{i=await this.requestCreate(t)}catch(t){o=e(t)}try{o=o??await this.requestRelay(i)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===h.success?r:n)(a),this.t.delete(s)}))),r}}class mr extends lr{i=new Map;o(e){this.setAuth(e??new u({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 hr("account",this.account)))}h(e,t,s){this.fire("list",(()=>new ur("list",e,t,s)))}u(e,t,s){this.fire("update",(()=>new dr("update",e,t,s)))}p(e,t,s){this.fire("delete",(()=>new pr("delete",e,t,s)))}on(e,t){let s=this.i.get(e);s||this.i.set(e,s=[]);const r=s.includes(t);return r||s.push(t),!r}off(e,t){const s=this.i.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.i.get(e)?.slice();if(s?.length){const e=t();s.forEach((t=>t.call(this,e)),this)}}handles(e,t){return this.i.get(e)?.includes(t)??!1}dispose(){for(const e of[...this.i.keys()])this.off(e)}async command(e){const t=await super.command(e);if(t instanceof d&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof p?s.filter?t.getList().forEach((e=>this.u(s.object,r,e))):this.h(s.object,r,t.getList()):t instanceof l?this.u(s.object,r,t.getObject()):t instanceof m?this.p(s.object,r,t.getKey()):t instanceof w&&t.getResults().forEach((e=>this.p(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new g);return this.o(e),e}async login(e,t,s){const r=await this.command(new y({username:e,password:t,userAgent:s??null}));return this.o(r),r}logout(){const e=this.command(new v);return this.o(new u),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new f({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 b({current:e,password:t}))}updatePreferences(e,t,s,r,n){return this.command(new C({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?or.fromMap(r):r??null,measurements:n instanceof Map?or.fromMap(n):n??null}))}updateState(e){return this.command(new P({options:e instanceof Map?or.fromMap(e):e??null}))}getCompany(e){return this.command(new S({company:{id:e}}))}mergeCompany(e){return this.command(new R({company:e}))}removeCompany(e){return this.command(new k({company:{id:e}}))}restoreCompany(e){return this.command(new A({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new M({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new D({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new I({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new T({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new G({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new U({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new B({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new J({company:{id:e}}))}getReseller(e){return this.command(new E({company:{id:e}}))}mergeReseller(e){return this.command(new L({company:e}))}removeReseller(e){return this.command(new x({company:{id:e}}))}restoreReseller(e){return this.command(new N({company:{id:e}}))}listContacts(e,t){return this.command(new O({...t,company:{id:e}}))}getContact(e){return this.command(new _({contact:{id:e}}))}mergeContact(e){return this.command(new F({contact:e}))}removeContact(e){return this.command(new H({contact:{id:e}}))}restoreContact(e){return this.command(new q({contact:{id:e}}))}multiMergeContact(e){return this.command(new $({contacts:e}))}multiRemoveContact(e){return this.command(new W({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new j({...t,company:{id:e}}))}getUser(e){return this.command(new z({user:{login:e}}))}mergeUser(e){return this.command(new K({user:e}))}removeUser(e){return this.command(new Z({user:{login:e}}))}restoreUser(e){return this.command(new Q({user:{login:e}}))}listUserGenerals(e,t){return this.command(new V({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new X({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new Y({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new ee({user:{login:e}}))}listUserGroups(e,t){return this.command(new te({...t,company:{id:e}}))}getUserGroup(e){return this.command(new se({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new re({userGroup:e}))}removeUserGroup(e){return this.command(new ne({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new ie({userGroup:{id:e}}))}listMachines(e,t){return this.command(new oe({...t,company:{id:e}}))}getMachine(e){return this.command(new ae({machine:{id:e}}))}mergeMachine(e){return this.command(new ce({machine:e}))}removeMachine(e){return this.command(new he({machine:{id:e}}))}restoreMachine(e){return this.command(new ue({machine:{id:e}}))}listSessions(e,t){return this.command(new de({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new pe({...t,user:{login:e}}))}killSession(e){return this.command(new le({session:{handle:e}}))}listIcons(e,t){return this.command(new me({...t,company:{id:e}}))}getIcon(e){return this.command(new we({icon:{id:e}}))}mergeIcon(e){return this.command(new ge({icon:e}))}removeIcon(e){return this.command(new ye({icon:{id:e}}))}restoreIcon(e){return this.command(new ve({icon:{id:e}}))}listPictures(e,t){return this.command(new fe({...t,company:{id:e}}))}getPicture(e){return this.command(new be({picture:{id:e}}))}mergePicture(e){return this.command(new Ce({picture:e}))}removePicture(e){return this.command(new Pe({picture:{id:e}}))}restorePicture(e){return this.command(new Se({picture:{id:e}}))}listDocuments(e,t){return this.command(new Re({...t,company:{id:e}}))}getDocument(e){return this.command(new ke({document:{id:e}}))}mergeDocument(e){return this.command(new Ae({document:e}))}removeDocument(e){return this.command(new Me({document:{id:e}}))}restoreDocument(e){return this.command(new De({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Ie({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Te({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ge({formTemplate:e}))}removeFormTemplate(e){return this.command(new Ue({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Be({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Je({...t,company:{id:e}}))}getFormResult(e){return this.command(new Ee({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Le({formResult:e}))}multiMergeFormResult(e){return this.command(new xe({formResult:{id:e}}))}removeFormResult(e){return this.command(new Ne({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Oe({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new _e({...t,company:{id:e}}))}getDashcamData(e){return this.command(new Fe({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new He({...t,company:{id:e}}))}listAssets(e,t){return this.command(new qe({...t,company:{id:e}}))}getAsset(e){return this.command(new $e({asset:{id:e}}))}mergeAsset(e){return this.command(new We({asset:e}))}multiMergeAsset(e){return this.command(new je({assets:e}))}removeAsset(e){return this.command(new ze({asset:{id:e}}))}restoreAsset(e){return this.command(new Ke({asset:{id:e}}))}suspendAsset(e){return this.command(new Ze({asset:{id:e}}))}reviveAsset(e){return this.command(new Qe({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new Ve({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new Xe({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new Ye({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new et({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new tt({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new st({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new rt({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new nt({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new it({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new ot({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new at({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new ct({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new ht({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new ut({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new dt({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new pt({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new lt({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new mt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new wt({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new gt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new yt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new vt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new ft({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new bt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new Ct({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new Pt({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new St({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new Rt({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new kt({...t,company:{id:e}}))}getPlace(e){return this.command(new At({place:{id:e}}))}mergePlace(e){return this.command(new Mt({place:e}))}removePlace(e){return this.command(new Dt({place:{id:e}}))}restorePlace(e){return this.command(new It({place:{id:e}}))}listProviders(e,t){return this.command(new Tt({...t,company:{id:e}}))}getProvider(e){return this.command(new Gt({provider:{id:e}}))}mergeProvider(e){return this.command(new Ut({provider:e}))}multiMergeProvider(e){return this.command(new Bt({providers:e}))}multiRemoveProvider(e){return this.command(new Jt({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Et({provider:{id:e}}))}restoreProvider(e){return this.command(new Lt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new xt({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Nt({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Ot({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new _t({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Ft({...t,company:{id:e}}))}getProviderControl(e){return this.command(new Ht({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new qt({...t,company:{id:e}}))}getProviderScript(e){return this.command(new $t({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new Wt({providerScript:e}))}removeProviderScript(e){return this.command(new jt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new zt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Kt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Zt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new Qt({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new Vt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new Xt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new Yt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new es({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new ts({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new ss({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new rs({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new ns({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new is({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new os({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new as({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new cs({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new hs({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new us({...t,company:{id:e}}))}getBehaviour(e){return this.command(new ds({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new ps({behaviour:e}))}multiMergeBehaviour(e){return this.command(new ls({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new ms({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new ws({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new gs({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new ys({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new vs({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new fs({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new bs({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new Cs({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new Ps({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new Ss({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new Rs({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new ks({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new As({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Ms({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Ds({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Is({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Ts({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Gs({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Us({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Bs({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Js({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Es({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Ls({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new xs({...t,company:{id:e}}))}getReportResult(e){return this.command(new Ns({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Os({reportResult:e}))}removeReportResult(e){return this.command(new _s({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Fs({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new Hs({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new qs({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new $s({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new Ws({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new js({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new zs({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Ks({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Zs({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new Qs({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new Vs({maintenanceJob:{id:e}}))}}const wr={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",UserAuthentication:"/companies/{companyId}/users/authentications",UserState:"/companies/{companyId}/users/states",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:""},gr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},yr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},vr=/[A-Z][a-z]+/;class fr extends mr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??fr.URI_PROD)}requestCreate(e){const[t,s]=r(e);return n(this.account,this.createBaseUrl(s),t,"GET"===t?null:JSON.stringify(e.toJSON()),this.headers)}requestRelay(e){return s(e)}}const br=/^(.+?)(Merged|Deleted|Suspended)$/,Cr={Company:[Xs.companyGeneral,Xs.companyLabels,Xs.companyPolicies],CompanyGeneral:[Xs.companyGeneral],CompanyDirectory:[],CompanyStyle:[Xs.companyLabels],CompanyPolicy:[Xs.companyPolicies],CompanyReseller:[Xs.companyReseller],Contact:[Xs.contact],Machine:[Xs.machine],User:[Xs.userGeneral,Xs.userAdvanced,Xs.userAuthentication],UserGeneral:[Xs.userGeneral],UserAdvanced:[Xs.userAdvanced],UserAuthentication:[Xs.userAuthentication],UserState:[Xs.userState],UserGroup:[Xs.userGroup],Session:[],Dashcam:[],Icon:[Xs.icon],Picture:[Xs.picture],Document:[Xs.document],FormTemplate:[Xs.formTemplate],FormResult:[Xs.formResult],Asset:[Xs.assetGeneral,Xs.assetAdvanced,Xs.assetDispatch],AssetGeneral:[Xs.assetGeneral],AssetAdvanced:[Xs.assetAdvanced],AssetDispatch:[Xs.assetDispatch],AssetMessage:[Xs.assetMessage],AssetAlert:[],DispatchTask:[Xs.dispatchTask],DispatchJob:[Xs.dispatchJob],MaintenanceSchedule:[Xs.maintenanceSchedule],MaintenanceJob:[Xs.maintenanceJob],Place:[Xs.placeGeneral],BehaviourScript:[Xs.behaviourScript],Behaviour:[Xs.behaviour],BehaviourLog:[Xs.behaviourLog],Provider:[Xs.providerGeneral,Xs.providerAdvanced,Xs.providerControl],ProviderGeneral:[Xs.providerGeneral],ProviderAdvanced:[Xs.providerAdvanced],ProviderControl:[Xs.providerControl],ProviderConfiguration:[Xs.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[Xs.providerScript],ProviderConfig:[Xs.providerConfig],ProviderRegistration:[Xs.providerRegistration],ReportTemplate:[Xs.reportTemplate],ReportSchedule:[Xs.reportSchedule],ReportResult:[Xs.reportResult],BillingProfile:[Xs.billingProfile],BillingReport:[Xs.billingReport],BillableHostingRule:[Xs.billingHosting],BillableHostingLicense:[Xs.billingLicense]};class Pr{#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}expireRegion(e,t=!1){const s=t?0:(new Date).valueOf();return this.#t(e,new Date(s+3e5))}expireRegions(e,t=!1){return e.map((e=>this.expireRegion(e,t)))}preserveRegion(e){const t=this.#e.get(e);return this.#t(e),t||null}preserveRegions(e){return e.map((e=>this.preserveRegion(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var Sr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(Sr||(Sr={}));class Rr{static fromJson(e){switch(e?.kind){case Sr.maintenance:return new kr(e);case Sr.upgrade:return new Ar(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=nr.date(e?.serverTime),this.message=e?.message??""}}class kr extends Rr{starting;ending;constructor(e){super(e),this.starting=nr.date(e?.starting),this.ending=nr.date(e?.ending)}}class Ar extends Rr{eta;reload;constructor(e){super(e),this.eta=nr.date(e?.eta),this.reload=!!e?.reload}}class Mr extends ar{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Dr extends ar{reply;constructor(e,t){super(e),this.reply=t}}class Ir extends ar{broadcast;constructor(e,t){super(e),this.broadcast=Rr.fromJson(t)}}const Tr="connection",Gr="dis"+Tr;var Ur;!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"}(Ur||(Ur={}));class Br extends mr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=br.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 Ur.opening;case WebSocket.OPEN:return this.#a?Ur.open:Ur.opening;case WebSocket.CLOSING:return Ur.closing;default:return Ur.closed}}get ready(){return this.#a&&this.#c}l(e){const t=this.i.get("open");if(t?.length){const s=new hr("open",e);t.forEach((e=>e.call(this,s)))}}m(e){const t=this.i.get("close");if(t?.length){const s=new Dr("close",e);t.forEach((e=>e.call(this,s)))}}v(e,t){const s=this.i.get("message");if(s?.length){const r=new Mr("message",e,t);s.forEach((e=>e.call(this,r)))}}C(e){const t=this.i.get("error");if(t?.length){const s=new Dr("error",e);t.forEach((e=>e.call(this,s)))}}P(e){const t=this.i.get("broadcast");if(t?.length){const s=new Ir("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.C(new Ys({errorCode:h.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:Ur.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:h.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===Gr?r:{...r,reqId:e,errorCode:h.service,errorDetails:{...s}});this.m?.(new Ys(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.v(t,s),t){case"connectionResponse":this.#f(s),this.#s=new Date(this.#r),this.#a=!0,this.#d(Tr,s),this.o(),this.l(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#f(s),this.o();break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#f(s),this.o();break;case"sessionGeneralMerged":this.#b([,"userGeneral","Merged"],this.#C(s)),this.o();break;case"sessionAdvancedMerged":this.#b([,"userAdvanced","Merged"],this.#P(s)),this.o();break;case"sessionAuthenticationMerged":this.#b([,"userAuthentication","Merged"],s),this.o();break;case"sessionStateMerged":this.#b([,"userState","Merged"],s),this.o();break;case"sessionMachineMerged":this.#b([,"machine","Merged"],this.#P(s)),this.o();break;case"broadcast":this.P(s)}if(t.endsWith("Response"))this.#d(s.reqId,s);else if(!t.startsWith("session")){const e=br.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 u(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 c["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 o=new i({errorCode:h.success,message:e[2]+" event",[e[1]]:s});if(o.store())switch(e[2]){case"Merged":case"Suspended":this.u(r,n,o.getObject());break;case"Deleted":this.p(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 o}reconnectEnabled=!0;#m=0;#v=0;keepAliveEnabled=!1;#y=0;constructor(e,t){super(e,t??Br.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===Ur.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(Tr,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new u({errorCode:h.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case Ur.opening:case Ur.open:this.#c=!1,this.reconnectEnabled=!1,this.#u.set(Gr,(s=>{(0===s.errorCode?e:t)(new Ys(s))})),this.#o.close(1e3,"Bye!");break;default:t(new Ys({errorCode:h.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}requestCreate(e){return Promise.resolve([i(e),e.toJSON()])}requestRelay(t){const s=t[0],r=t[1]||{};return new Promise(((n,i)=>{const o=this.state;switch(o){case Ur.open:const a=++this.#h,c=setTimeout((()=>this.#d(a,{reqId:a,errorCode:h.unknown,message:"Command timeout"})),12e4);r.reqId=a,this.#u.set(a,(e=>{clearTimeout(c),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r)),this.#i=new Date}catch(t){this.#d(a,e(t))}this.resetKeepAlive();break;case Ur.closed:this.open().then((()=>this.requestRelay(t).then(n))).catch(i);break;default:i({errorCode:h.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:o}})}}))}resetKeepAlive(){return clearTimeout(this.#y),this.#y=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.requestRelay(["noop",{}])),3e5):0,Promise.resolve(0!==this.#y)}subscribe(e,t){return t?.length?this.command(new er({company:{id:e},subscriptionTypes:t})):Promise.resolve(new tr({errorCode:h.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new sr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new tr({errorCode:h.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new rr)}}const Jr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Er extends mr{S;R;get autoConnect(){return this.S.reconnectEnabled}set autoConnect(e){this.S.reconnectEnabled=!!e,e&&this.S.state===Ur.closed&&this.S.open()}get socketOnline(){return this.S.state===Ur.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.R.baseAddress}set restAddress(e){this.R.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.setAuth(e.account),n=e=>this.fire(e.type,(()=>e));this.R=new fr(this.account,t??fr.URI_PROD),this.R.on("account",r),this.S=new Br(this.account,s??Br.URI_PROD),this.S.on("account",r),this.S.on("open",(e=>this.#S(e.account))),this.S.on("close",(e=>this.#R(e.reply)));for(const e of["account","list","update","delete"])this.R.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.R.dispose(),this.S.dispose(),this.R=this.S=null}setAuth(e){super.setAuth(e),this.R?.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)}requestCreate(e){throw new Error("Method not implemented.")}requestRelay(e){throw new Error("Method not implemented.")}rest(e){return this.R.command(e)}socket(e){return this.S.command(e)}#S(e){this.#k.forEach(((e,t)=>{this.sync(t,a(e.reset()))})),this.#A()}#R(e){clearTimeout(this.#M)}isSynced(e,t){let s=this.S.state===Ur.open;if(s){const r=this.#D(e);s=o(t).every((e=>r.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#D(e),r=t?[]:s.getExpiring();return a(s.regions.filter((e=>!r.includes(e))))}async sync(t,s){const r=[],n=this.#D(t),i=o(s).filter((e=>!n.regions.includes(e)));if(i.length>0){n.preserveRegions(i);const s=await this.S.subscribe(t,i);n.expireRegions((s.denied??[]).concat(s.invalid??[]),!0),a(s.merged??[]).forEach((s=>{const n=function(e,t){return c["Pay"+e+(t??"Get")]}(s,s.startsWith("Company")?"Get":"ListByCompany");r.push(n?this.command(new n({company:{id:t}})):Promise.reject(e(new Error(`No payload class could be made for sync type ${s}`))))}))}return Promise.all(r)}desync(e,t){const s=this.#D(e),r=t.reduce(((e,t)=>e.concat(Cr[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));return s.expireRegions(r),r}#k=new Map;#A(){const e=[];this.S.state===Ur.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 Pr),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 Er="0.0.51";export{Cr as SubscribedRegions,pr as TrakitBaseCommander,or as TrakitEvent,cr as TrakitEventAccount,dr as TrakitEventDelete,hr as TrakitEventList,Mr as TrakitEventSocketClose,Ar as TrakitEventSocketMessage,ar as TrakitEventSync,ur as TrakitEventUpdate,lr as TrakitObjectCommander,vr as TrakitRestfulCommander,Ur as TrakitSocketCommander,Gr as TrakitSocketStatus,Jr as TrakitSyncCommander,e as createClientErrorResponse,n as createCorsRequest,s as fetchJsonObject,i as payloadToCommandName,r as payloadToVerbRoute,Er as version};
7
+ */const Lr="0.0.53";export{Pr as SubscribedRegions,lr as TrakitBaseCommander,ar as TrakitEvent,hr as TrakitEventAccount,pr as TrakitEventDelete,ur as TrakitEventList,Dr as TrakitEventSocketClose,Mr as TrakitEventSocketMessage,cr as TrakitEventSync,dr as TrakitEventUpdate,mr as TrakitObjectCommander,fr as TrakitRestfulCommander,Br as TrakitSocketCommander,Ur as TrakitSocketStatus,Er as TrakitSyncCommander,e as createClientErrorResponse,n as createCorsRequest,s as fetchJsonObject,i as payloadToCommandName,r as payloadToVerbRoute,Lr as version};