@trakit/sync 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ import { SyncName, url } from "@trakit/objects";
2
+ /**
3
+ * The HTTP verbs supported by the Trak-iT RESTful API.
4
+ */
5
+ export type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
6
+ /**
7
+ * A mapping of RESTful service routes to get things listed by company.
8
+ */
9
+ export declare const OBJECT_LIST_BY_COMPANY: {
10
+ [key in SyncName]: url;
11
+ };
12
+ /**
13
+ * A mapping of Trak-iT RESTful routes to get things listed by asset.
14
+ */
15
+ export declare const OBJECT_LIST_BY_ASSET: {
16
+ [key: SyncName | string]: url;
17
+ };
18
+ /**
19
+ * A mapping of Trak-iT RESTful routes to get things listed by behaviour script.
20
+ */
21
+ export declare const OBJECT_LIST_BY_BEHAVIOUR_SCRIPT: {
22
+ [key: SyncName | string]: url;
23
+ };
24
+ /**
25
+ * A mapping of Trak-iT RESTful routes to get things listed by billing profile.
26
+ */
27
+ export declare const OBJECT_LIST_BY_BILLING_PROFILE: {
28
+ [key: SyncName | string]: url;
29
+ };
30
+ /**
31
+ * A mapping of Trak-iT RESTful routes to get things listed by asset.
32
+ */
33
+ export declare const OBJECT_LIST_BY_USER: {
34
+ [key: SyncName | string]: url;
35
+ };
36
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,52 @@
1
+ import { Payload, RepSelfGet } from "@trakit/commands";
2
+ import { guid, JsonObject, Machine, nothing, url } from "@trakit/objects";
3
+ import { TrakitObjectCommander } from "../API/TrakitObjectCommander";
4
+ import { HttpVerb } from "./Constants";
5
+ /**
6
+ * Uses Trak-iT's RESTful service to access and manipulate Trak-iT API objects.
7
+ */
8
+ export declare class TrakitRestfulCommander extends TrakitObjectCommander<Request> {
9
+ /**
10
+ * Production RESTful service URL.
11
+ * This service is covered by the SLA and should be used for serices and code running in your own production environment.
12
+ * Both services access the same data-set, so be careful making changes as they will be reflected in production as well.
13
+ */
14
+ static readonly URI_PROD: url;
15
+ /**
16
+ * Testing or beta RESTful service URL.
17
+ * This service is not covered by the SLA and should be used to test your own code before deployment.
18
+ * Throttling of connections and commands is tighter to help you diagnose issues before switching to production.
19
+ * Both services access the same data-set, so be careful making changes as they will be reflected in production as well.
20
+ */
21
+ static readonly URI_BETA: url;
22
+ constructor(account?: RepSelfGet | {
23
+ machine: {
24
+ key: string;
25
+ };
26
+ } | Machine | {
27
+ key: string;
28
+ } | {
29
+ ghostId: guid;
30
+ } | guid | nothing, baseAddress?: URL | url | nothing);
31
+ /**
32
+ * Gets the appropriate HTTP verb and route for the given payload.
33
+ * @param payload The payload to analyze.
34
+ * @returns A tuple containing the HTTP verb and route.
35
+ */
36
+ getVerbRoute(payload: Payload): [HttpVerb, string];
37
+ /**
38
+ * Creates a request object for the specified HTTP method and body.
39
+ * @param payload
40
+ * @returns A {@link Request} object configured with the specified parameters.
41
+ */
42
+ _createRequest(payload: Payload): Request;
43
+ /**
44
+ * Sends the given request to Trak-iT's RESTful API and awaits a result.
45
+ * @param request.path Relative path to the resource being accessed.
46
+ * @param request.verb HTTP method to use for the request.
47
+ * @param request.body Optional JSON body to send with the request.
48
+ * @returns A promise that resolves with the JSON response from the server.
49
+ */
50
+ _relayRequest(request: Request): Promise<JsonObject>;
51
+ }
52
+ //# sourceMappingURL=TrakitRestfulCommander.d.ts.map
@@ -0,0 +1,15 @@
1
+ import { SubscriptionType } from "@trakit/commands";
2
+ import { SyncName } from "@trakit/objects";
3
+ /**
4
+ *
5
+ * @param types
6
+ * @returns
7
+ */
8
+ export declare function SYNCS_TO_SUBS(types: SyncName[]): SubscriptionType[];
9
+ /**
10
+ *
11
+ * @param subscriptions
12
+ * @returns
13
+ */
14
+ export declare function SUBS_TO_SYNCS(subscriptions: SubscriptionType[]): SyncName[];
15
+ //# sourceMappingURL=Functions.d.ts.map
@@ -0,0 +1,136 @@
1
+ import { Payload, Reply, RepSelfGet, RepSubscription, RepSubscriptionList, SubscriptionType } from "@trakit/commands";
2
+ import { guid, JsonObject, Machine, nothing, SyncName, ulong, url } from '@trakit/objects';
3
+ import { TrakitObjectCommander } from "../API/TrakitObjectCommander";
4
+ /**
5
+ * This is the class which does the work in the background {@link Worker} for the {@link SyncClient}.
6
+ * It handles synchronizing regions, maintaining a connection to Trak-iT's WebSocket, and send HTTP requests to Trak-iT's RESTful service.
7
+ * This class also maintains a queue of up-going messages.
8
+ */
9
+ export declare class TrakitSyncCommander extends TrakitObjectCommander<any> {
10
+ #private;
11
+ /**
12
+ * When true, the Trak-iT WebSocket will automatically attempt to establish a connection.
13
+ * This value defaults to true if the commander is instantiated with a `ghostId`.
14
+ */
15
+ get autoConnect(): boolean;
16
+ set autoConnect(value: boolean);
17
+ /**
18
+ * Indicates whether the Trak-iT WebSocket is currently connected.
19
+ */
20
+ get online(): boolean;
21
+ /**
22
+ * Event raised when the Trak-iT WebSocket connection is opened.
23
+ */
24
+ onOpen?: ((this: TrakitSyncCommander, account: RepSelfGet) => any) | null;
25
+ /**
26
+ * Event raised when an error occurs on the Trak-iT WebSocket connection.
27
+ */
28
+ onError?: ((this: TrakitSyncCommander, account: Reply) => any) | null;
29
+ /**
30
+ * Gets invoked any time a message is received by the Trak-iT WebSocket connection.
31
+ * This is useful for logging or debugging, but you should use the {@link onUpdate}, {@link onDelete},
32
+ * and {@link onList} events to track changes to objects.
33
+ */
34
+ onMessage?: (this: TrakitSyncCommander, kind: string, content: JsonObject) => void;
35
+ /**
36
+ * Event raised when the Trak-iT WebSocket connection is closed.
37
+ */
38
+ onClose?: ((this: TrakitSyncCommander, account: Reply) => any) | null;
39
+ constructor(account?: RepSelfGet | {
40
+ machine: {
41
+ key: string;
42
+ };
43
+ } | Machine | {
44
+ key: string;
45
+ } | {
46
+ ghostId: guid;
47
+ } | guid | nothing, httpAddress?: URL | url | nothing, wssAddress?: URL | url | nothing);
48
+ /**
49
+ * Disposes of the Trak-iT WebSocket connection, and cleans up references.
50
+ */
51
+ dispose(): void;
52
+ /**
53
+ * Overridden to set the authentication for both the RESTful service and WebSocket.
54
+ * @inheritdoc
55
+ */
56
+ setAuth(account?: RepSelfGet | {
57
+ machine: {
58
+ key: string;
59
+ };
60
+ } | Machine | {
61
+ key: string;
62
+ } | {
63
+ ghostId: guid;
64
+ } | guid | nothing): void;
65
+ /**
66
+ * Overridden to route commands to either the Trak-iT WebSocket or RESTful service based on the type of action.
67
+ * @inheritdoc
68
+ */
69
+ command<TReply extends Reply>(payload: Payload): Promise<TReply>;
70
+ /**
71
+ * Overridden to throw an error if used; it shouldn't be in use because of the {@link command} override.
72
+ * @inheritdoc
73
+ */
74
+ _createRequest(payload: Payload): any;
75
+ /**
76
+ * Overridden to throw an error if used; it shouldn't be in use because of the {@link command} override.
77
+ * @inheritdoc
78
+ */
79
+ _relayRequest(request: Payload): Promise<any>;
80
+ /**
81
+ * Sends a command specifically to the Trak-iT RESTful service.
82
+ * @param payload
83
+ * @returns
84
+ */
85
+ rest<TReply extends Reply>(payload: Payload): Promise<TReply>;
86
+ /**
87
+ * Sends a command specifically to the Trak-iT WebSocket service.
88
+ * @param payload
89
+ * @returns
90
+ */
91
+ socket<TReply extends Reply>(payload: Payload): Promise<TReply>;
92
+ /**
93
+ * Checks if the given {@link types} are currently synchronized for the given {@param companyId}.
94
+ * @param companyId
95
+ * @param types
96
+ * @returns
97
+ */
98
+ isSynced(companyId: ulong, types: SyncName[]): boolean;
99
+ /**
100
+ * Begins synchronizing the given regions.
101
+ * If all regions are in-sync, the returned Promise is resolved immediately.
102
+ * Otherwise it sends a subscribe command to the Trak-iT WebSocket for any out-of-sync regions,
103
+ * and when the subscribe is resolved, it sends commands to list the objects for the requested {@param types} (except Company, which is not listed, but "getted").
104
+ * @param companyId
105
+ * @param types
106
+ */
107
+ sync(companyId: ulong, types: SyncName[]): Promise<Reply[]>;
108
+ /**
109
+ * Adds the {@param types} to the list of expiring subscriptions.
110
+ * The process is not immediate, but happens after a timeout.
111
+ * This allows the service to re-request sync on a region, like when switching sections.
112
+ * @param companyId
113
+ * @param types
114
+ */
115
+ desync(companyId: ulong, types: SyncName[]): Promise<void>;
116
+ /**
117
+ * Subscribes to the specified subscription types for the given company.
118
+ * @param companyId
119
+ * @param subscriptions
120
+ * @returns
121
+ */
122
+ subscribe(companyId: ulong, subscriptions: SubscriptionType[]): Promise<RepSubscription>;
123
+ /**
124
+ * Unsubscribes from the specified subscription types for the given company.
125
+ * @param companyId
126
+ * @param subscriptions
127
+ * @returns
128
+ */
129
+ unsubscribe(companyId: ulong, subscriptions: SubscriptionType[]): Promise<RepSubscription>;
130
+ /**
131
+ * Retrieves the list of active subscriptions for the current account.
132
+ * @returns
133
+ */
134
+ listSubscriptions(): Promise<RepSubscriptionList>;
135
+ }
136
+ //# sourceMappingURL=TrakitSyncCommander.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { SubscriptionType } from "@trakit/commands";
2
+ import { SyncName } from "@trakit/objects";
3
+ /**
4
+ * Regex parser for socket command response message names.
5
+ */
6
+ export declare const MSG_RESPONSE: RegExp;
7
+ /**
8
+ * Regex parser for socket message names (not command responses, those are handled by the {@link TrakitCommander.command} function).
9
+ */
10
+ export declare const MSG_SYNC: RegExp;
11
+ /**
12
+ * A mapping of object names to their required subscription types.
13
+ */
14
+ export declare const OBJECT_SUBSCRIPTIONS: {
15
+ [key in SyncName]: SubscriptionType[];
16
+ };
17
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,8 @@
1
+ import { Payload } from "@trakit/commands";
2
+ /**
3
+ * Returns a WebSocket command name based on the {@link Payload} type.
4
+ * @param payload
5
+ * @returns
6
+ */
7
+ export declare function makeCommandName(payload: Payload): string;
8
+ //# sourceMappingURL=Functions.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { SubscriptionType } from "@trakit/commands";
2
+ /**
3
+ * A class to contain all the subscriptions for a company.
4
+ * This class also sets the expiration dates.
5
+ * @constructor
6
+ */
7
+ export declare class SubscribedRegions {
8
+ #private;
9
+ /**
10
+ * Returns all the currently valid subscription types, even if they are marked to expire.
11
+ */
12
+ get regions(): SubscriptionType[];
13
+ /**
14
+ * Returns a list of subscription types that should be removed.
15
+ */
16
+ getExpired(): SubscriptionType[];
17
+ /**
18
+ * Returns a list of subscription types that were removed.
19
+ */
20
+ purgeExpired(): SubscriptionType[];
21
+ /**
22
+ * Returns a list of subscription types that will be removed eventually.
23
+ */
24
+ getExpiring(): SubscriptionType[];
25
+ /**
26
+ * Marks the given subscription type for expiration.
27
+ * @param region
28
+ */
29
+ addExpiry(region: SubscriptionType): Date;
30
+ /**
31
+ * Marks the given subscription types for expiration.
32
+ * @param regions
33
+ */
34
+ addExpiries(regions: SubscriptionType[]): Date[];
35
+ /**
36
+ * Clears the expiration of the given subscription type.
37
+ * @param region
38
+ */
39
+ removeExpiry(region: SubscriptionType): Date | null;
40
+ /**
41
+ * Clears the expiration of the given subscription types.
42
+ * @param regions
43
+ */
44
+ removeExpiries(regions: SubscriptionType[]): (Date | null)[];
45
+ /**
46
+ * Removes all subscription types, and returns a list of those that were not going to expire.
47
+ */
48
+ reset(): SubscriptionType[];
49
+ }
50
+ //# sourceMappingURL=SubscribedRegions.d.ts.map
@@ -0,0 +1,161 @@
1
+ import { Payload, Reply, RepSelfGet, RepSubscription, RepSubscriptionList, SubscriptionType } from "@trakit/commands";
2
+ import { guid, JsonObject, Machine, nothing, ulong, url } from '@trakit/objects';
3
+ import { TrakitObjectCommander } from "../API/TrakitObjectCommander";
4
+ /**
5
+ * Describes the state of the {@link TrakitSocketCommander}'s connection to the Trak-iT WebSocket service.
6
+ */
7
+ export declare enum TrakitSocketStatus {
8
+ /**
9
+ * A connection is being established and is awaiting the initial {@link RepSelfGet|connectionResponse} message.
10
+ */
11
+ opening,
12
+ /**
13
+ * A connection is established and the {@link RepSelfGet|connectionResponse} message has been received.
14
+ */
15
+ open,
16
+ /**
17
+ * Either the client or the server has initiated a disconnection.
18
+ */
19
+ closing,
20
+ /**
21
+ * The underlying {@link WebSocket} connection has been terminated.
22
+ */
23
+ closed
24
+ }
25
+ /**
26
+ * Uses Trak-iT's {@link WebSocket} service to access and manipulate Trak-iT API objects.
27
+ */
28
+ export declare class TrakitSocketCommander extends TrakitObjectCommander<[string, JsonObject]> {
29
+ #private;
30
+ /**
31
+ * Production RESTful service URL.
32
+ * This service is covered by the SLA and should be used for serices and code running in your own production environment.
33
+ * Both services access the same data-set, so be careful making changes as they will be reflected in production as well.
34
+ */
35
+ static readonly URI_PROD: url;
36
+ /**
37
+ * Testing or beta RESTful service URL.
38
+ * This service is not covered by the SLA and should be used to test your own code before deployment.
39
+ * Throttling of connections and commands is tighter to help you diagnose issues before switching to production.
40
+ * Both services access the same data-set, so be careful making changes as they will be reflected in production as well.
41
+ */
42
+ static readonly URI_BETA: url;
43
+ /**
44
+ * Timestamp recorded right after establishing a connection and receiving the `connectionResponse` message.
45
+ */
46
+ get lastConnected(): Date;
47
+ /**
48
+ * A timestamp from the last time we received any kind of message from the underlying WebSocket (requested or otherwise).
49
+ * Does not reset when we send a message, only on receive.
50
+ * This is used by the keep-alive process.
51
+ */
52
+ get lastReceived(): Date;
53
+ /**
54
+ * The name of the most recent message received by the underlying WebSocket.
55
+ */
56
+ get lastMessage(): string;
57
+ /**
58
+ * Timestamp recorded right after sending the most recent message.
59
+ */
60
+ get lastSent(): Date;
61
+ /**
62
+ * Returns a {@link TrakitSocketStatus} about the underlying WebSocket.
63
+ * Also takes into account a null connection, and an open connection that has not yet received the first message.
64
+ */
65
+ get state(): TrakitSocketStatus;
66
+ /**
67
+ * True when the WebSocket is ready to send and receive messages.
68
+ * This value can be false if the connection is established, but the account has not authenticated yet, or your password has expired.
69
+ */
70
+ get ready(): boolean;
71
+ /**
72
+ * Gets invoked any time the WebSocket connection is established and the `connectionResponse` message is received.
73
+ */
74
+ onOpen?: ((this: TrakitSocketCommander, account: RepSelfGet) => any) | nothing;
75
+ /**
76
+ * Gets invoked any time the WebSocket connection is closed.
77
+ */
78
+ onClose?: ((this: TrakitSocketCommander, reply: Reply) => any) | nothing;
79
+ /**
80
+ * Gets invoked any time a message is received by the Trak-iT WebSocket connection.
81
+ * This is useful for logging or debugging, but you should use the {@link onUpdate}, {@link onDelete},
82
+ * and {@link onList} events to track changes to objects.
83
+ */
84
+ onMessage?: ((this: TrakitSocketCommander, name: string, body: JsonObject) => any) | nothing;
85
+ /**
86
+ * Gets invoked any time an error occurs on the WebSocket.
87
+ */
88
+ onError?: ((this: TrakitSocketCommander, reply: Reply) => any) | nothing;
89
+ /**
90
+ * Flag set to specifically allow automatic re-connection to Trak-iT's WebSocket.
91
+ * This value is set to false in the message handler if the connectionResponse message does not have an errorCode zero.
92
+ * Conversly, it is set to true if a login or password change is successful.
93
+ */
94
+ reconnectEnabled: boolean;
95
+ /**
96
+ * Flag set to specifically send "noop" messages on a timer to ensure the firewall doesn't prematurely kill the underlying WebSocket.
97
+ */
98
+ keepAliveEnabled: boolean;
99
+ constructor(account?: RepSelfGet | {
100
+ machine: {
101
+ key: string;
102
+ };
103
+ } | Machine | {
104
+ key: string;
105
+ } | {
106
+ ghostId: guid;
107
+ } | guid | nothing, baseAddress?: URL | url | nothing);
108
+ /**
109
+ * Disconnects the underlying WebSocket, unbinds all event-handlers, and clears any circular binds.
110
+ */
111
+ dispose(): void;
112
+ /**
113
+ * Creates a new underlying WebSocket and returns a Promise that resolves when the connectionResponse message is received.
114
+ * If the underlying WebSocket is not closed (as in, any state of openning or being closed), the returned Promise will be rejected.
115
+ */
116
+ open(): Promise<RepSelfGet>;
117
+ /**
118
+ * Closes the underlying WebSocket connection, and returns a Promise that resolves when the connection is confirmed to be closed.
119
+ * If the underlying WebSocket is not open (as in, any state of openning or being closed), the returned Promise will be rejected.
120
+ */
121
+ close(): Promise<Reply>;
122
+ /**
123
+ * Creates a request object for the specified payload.
124
+ * @param payload The payload to include in the request.
125
+ * @returns A request object configured with the specified parameters.
126
+ */
127
+ _createRequest(payload: Payload): [string, JsonObject];
128
+ /**
129
+ * Sends a command and parameters to Trak-iT's WebSocket service.
130
+ * If the underlying WebSocket is not open (as in, any state of openning or being closed), the returned Promise will be rejected.
131
+ * IF the command is sent, and a response received, even an error, the Promise is resolved.
132
+ * @param command The name of the command to send.
133
+ * @param params Optional object or value for the command.
134
+ * @returns A Promise which is resolved when a response is received, otherwise it is rejected.
135
+ */
136
+ _relayRequest(request: [string, JsonObject]): Promise<JsonObject>;
137
+ /**
138
+ * Resets the keep-alive timer (to try and keep the firewall from disconnecting the underlying WebSocket).
139
+ */
140
+ resetKeepAlive(): Promise<boolean>;
141
+ /**
142
+ * Subscribes to the specified subscription types for the given company.
143
+ * @param companyId
144
+ * @param subscriptions
145
+ * @returns
146
+ */
147
+ subscribe(companyId: ulong, subscriptions: SubscriptionType[]): Promise<RepSubscription>;
148
+ /**
149
+ * Unsubscribes from the specified subscription types for the given company.
150
+ * @param companyId
151
+ * @param subscriptions
152
+ * @returns
153
+ */
154
+ unsubscribe(companyId: ulong, subscriptions: SubscriptionType[]): Promise<RepSubscription>;
155
+ /**
156
+ * Retrieves the list of active subscriptions for the current account.
157
+ * @returns
158
+ */
159
+ listSubscriptions(): Promise<RepSubscriptionList>;
160
+ }
161
+ //# sourceMappingURL=TrakitSocketCommander.d.ts.map
package/index.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Synchronization library main process.
3
+ * {@link https://github.com/trakitwireless/trakit-ts-sync|Client synchronization library.}
4
+ * Last updated on Thu Feb 27 2025 11:59:01
5
+ * @copyright Trak-iT Wireless Inc. 2025
6
+ */
7
+ import { TrakitBaseCommander } from "./API/TrakitBaseCommander";
8
+ import { TrakitObjectCommander } from "./API/TrakitObjectCommander";
9
+ import { TrakitRestfulCommander } from "./RESTful/TrakitRestfulCommander";
10
+ import { TrakitSyncCommander } from "./Synchronization/TrakitSyncCommander";
11
+ import { SubscribedRegions } from "./WebSocket/SubscribedRegions";
12
+ import { TrakitSocketCommander } from "./WebSocket/TrakitSocketCommander";
13
+ /**
14
+ * Version number for this release.
15
+ */
16
+ export declare const version = "0.0.7";
17
+ export { TrakitBaseCommander, TrakitObjectCommander };
18
+ export { TrakitRestfulCommander };
19
+ export { SubscribedRegions, TrakitSocketCommander };
20
+ export { TrakitSyncCommander };
21
+ //# sourceMappingURL=index.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@trakit/sync",
3
3
  "type": "module",
4
- "version": "0.0.5",
4
+ "version": "0.0.7",
5
5
  "main": "./trakit-sync.min.js",
6
6
  "types": "./index.d.ts",
7
7
  "scripts": {
@@ -11,6 +11,12 @@
11
11
  "type": "git",
12
12
  "url": "git+https://github.com/trakitwireless/trakit-ts-sync.git"
13
13
  },
14
+ "files": [
15
+ "LICENSE",
16
+ "README.md",
17
+ "**/*.js",
18
+ "**/*.d.ts"
19
+ ],
14
20
  "keywords": [
15
21
  "trakit"
16
22
  ],
@@ -0,0 +1,7 @@
1
+ function e(e,t){return{errorCode:i.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){const t=e.getAction(),s=new Error("no command supported for "+e.constructor.name,{cause:t});switch(t.object){case"Subscription":switch(t.kind){case"Merge":return"subscribe";case"Delete":return"unsubscribe";case"List":return"getSubscriptionsList";default:throw s}case"Self":switch(t.filter){case"Get":return"getSessionDetails";case"Login":case"Logout":return t.filter.toLowerCase();case"Contact":case"Password":case"Preferences":return"updateOwn"+t.filter;default:throw s}case"Session":switch(t.kind){case"Get":case"List":break;case"Delete":return"killSession";default:throw s}break;case"DispatchJob":switch(t.filter){case"Cancel":case"Change":return t.kind.toLocaleLowerCase()+t.object}}switch(t.kind){case"Get":case"Merge":case"Restore":case"Suspend":return t.kind.toLocaleLowerCase()+t.object;case"Delete":return"remove"+t.object;case"Reactivate":return"revive"+t.object;case"List":return"get"+Ys.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function s(e){return e.reduce(((e,t)=>e.concat(ur[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function r(e){const t=[];for(const[s,r]of Object.entries(gr)){const n=r.map((e=>ur[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}for(const[s,r]of Object.entries(ur))!gr[s]&&r.some((t=>e.includes(t)))&&t.push(s);return t}import*as n from"@trakit/commands";import{ErrorCode as i,RepSelfGet as o,ReplySync as a,ReplySyncList as c,ReplySyncGet as h,ReplySyncDelete as u,ReplySyncBatchDelete as d,PaySelfGet as p,PaySelfLogin as l,PaySelfLogout as m,PaySelfContact as w,PaySelfPassword as g,PaySelfPreferences as v,PayCompanyGet as y,PayCompanyMerge as b,PayCompanyDelete as f,PayCompanyRestore as C,PayCompanyGeneralListByCompany as P,PayCompanyGeneralGet as R,PayCompanyPolicyListByCompany as S,PayCompanyPolicyGet as k,PayCompanyStyleListByCompany as A,PayCompanyStyleGet as D,PayCompanyDirectoryListByCompany as M,PayCompanyDirectoryGet as I,PayCompanyResellerGet as T,PayCompanyResellerMerge as G,PayCompanyResellerDelete as U,PayCompanyResellerRestore as B,PayContactListByCompany as J,PayContactGet as E,PayContactMerge as L,PayContactDelete as O,PayContactRestore as F,PayContactBatchMerge as x,PayContactBatchDelete as q,PayUserListByCompany as H,PayUserGet as N,PayUserMerge as W,PayUserDelete as _,PayUserRestore as $,PayUserGeneralListByCompany as j,PayUserGeneralGet as K,PayUserAdvancedListByCompany as z,PayUserAdvancedGet as V,PayUserGroupListByCompany as Z,PayUserGroupGet as Q,PayUserGroupMerge as X,PayUserGroupDelete as Y,PayUserGroupRestore as ee,PayMachineListByCompany as te,PayMachineGet as se,PayMachineMerge as re,PayMachineDelete as ne,PayMachineRestore as ie,PaySessionListByCompany as oe,PaySessionListByUser as ae,PaySessionDelete as ce,PayIconListByCompany as he,PayIconGet as ue,PayIconMerge as de,PayIconDelete as pe,PayIconRestore as le,PayPictureListByCompany as me,PayPictureGet as we,PayPictureMerge as ge,PayPictureDelete as ve,PayPictureRestore as ye,PayDocumentListByCompany as be,PayDocumentGet as fe,PayDocumentMerge as Ce,PayDocumentDelete as Pe,PayDocumentRestore as Re,PayFormTemplateListByCompany as Se,PayFormTemplateGet as ke,PayFormTemplateMerge as Ae,PayFormTemplateDelete as De,PayFormTemplateRestore as Me,PayFormResultListByCompany as Ie,PayFormResultGet as Te,PayFormResultMerge as Ge,PayFormResultBatchMerge as Ue,PayFormResultDelete as Be,PayFormResultRestore as Je,PayDashcamListByCompany as Ee,PayDashcamGet as Le,PayDashcamLiveListByCompany as Oe,PayAssetListByCompany as Fe,PayAssetGet as xe,PayAssetMerge as qe,PayAssetBatchMerge as He,PayAssetDelete as Ne,PayAssetRestore as We,PayAssetSuspend as _e,PayAssetReactivate as $e,PayAssetGeneralListByCompany as je,PayAssetGeneralGet as Ke,PayAssetAdvancedListByCompany as ze,PayAssetAdvancedGet as Ve,PayAssetDispatchMerge as Ze,PayDispatchTaskListByCompany as Qe,PayDispatchTaskListByAsset as Xe,PayDispatchTaskGet as Ye,PayDispatchTaskMerge as et,PayDispatchTaskBatchMerge as tt,PayDispatchTaskDelete as st,PayDispatchTaskRestore as rt,PayDispatchJobListByCompany as nt,PayDispatchJobListByAsset as it,PayDispatchJobGet as ot,PayDispatchJobMerge as at,PayDispatchJobBatchMerge as ct,PayDispatchJobDelete as ht,PayDispatchJobRestore as ut,PayDispatchJobChange as dt,PayDispatchJobCancel as pt,PayAssetMessageListByCompany as lt,PayAssetMessageListByAsset as mt,PayAssetMessageGet as wt,PayAssetMessageMerge as gt,PayAssetMessageBatchMerge as vt,PayAssetMessageDelete as yt,PayAssetMessageRestore as bt,PayPlaceListByCompany as ft,PayPlaceGet as Ct,PayPlaceMerge as Pt,PayPlaceDelete as Rt,PayPlaceRestore as St,PayProviderListByCompany as kt,PayProviderGet as At,PayProviderMerge as Dt,PayProviderBatchMerge as Mt,PayProviderBatchDelete as It,PayProviderDelete as Tt,PayProviderRestore as Gt,PayProviderGeneralListByCompany as Ut,PayProviderGeneralGet as Bt,PayProviderAdvancedListByCompany as Jt,PayProviderAdvancedGet as Et,PayProviderControlListByCompany as Lt,PayProviderControlGet as Ot,PayProviderScriptListByCompany as Ft,PayProviderScriptGet as xt,PayProviderScriptMerge as qt,PayProviderScriptDelete as Ht,PayProviderScriptRestore as Nt,PayProviderConfigListByCompany as Wt,PayProviderConfigGet as _t,PayProviderConfigMerge as $t,PayProviderConfigBatchMerge as jt,PayProviderConfigDelete as Kt,PayProviderConfigRestore as zt,PayProviderConfigurationListByCompany as Vt,PayProviderConfigurationGet as Zt,PayProviderConfigurationMerge as Qt,PayProviderConfigurationBatchMerge as Xt,PayProviderConfigurationDelete as Yt,PayProviderConfigurationRestore as es,PayProviderRegistrationListByCompany as ts,PayProviderRegistrationGet as ss,PayProviderRegistrationMerge as rs,PayProviderRegistrationDelete as ns,PayBehaviourListByCompany as is,PayBehaviourGet as os,PayBehaviourMerge as as,PayBehaviourBatchMerge as cs,PayBehaviourDelete as hs,PayBehaviourRestore as us,PayBehaviourScriptListByCompany as ds,PayBehaviourScriptGet as ps,PayBehaviourScriptMerge as ls,PayBehaviourScriptDelete as ms,PayBehaviourScriptRestore as ws,PayBehaviourLogListByAsset as gs,PayBehaviourLogBatchDeleteByAsset as vs,PayBehaviourLogListByBehaviour as ys,PayBehaviourLogBatchDeleteByBehaviour as bs,PayBehaviourLogListByScript as fs,PayBehaviourLogBatchDeleteByScript as Cs,PayReportTemplateListByCompany as Ps,PayReportTemplateGet as Rs,PayReportTemplateMerge as Ss,PayReportTemplateDelete as ks,PayReportTemplateRestore as As,PayReportScheduleListByCompany as Ds,PayReportScheduleGet as Ms,PayReportScheduleMerge as Is,PayReportScheduleDelete as Ts,PayReportScheduleRestore as Gs,PayReportResultListByCompany as Us,PayReportResultGet as Bs,PayReportResultMerge as Js,PayReportResultDelete as Es,PayReportResultRestore as Ls,PayMaintenanceScheduleListByCompany as Os,PayMaintenanceScheduleGet as Fs,PayMaintenanceScheduleMerge as xs,PayMaintenanceScheduleDelete as qs,PayMaintenanceScheduleRestore as Hs,PayMaintenanceJobListByCompany as Ns,PayMaintenanceJobGet as Ws,PayMaintenanceJobMerge as _s,PayMaintenanceJobDelete as $s,PayMaintenanceJobRestore as js,SubscriptionType as Ks,Reply as zs,PaySubscriptionMerge as Vs,RepSubscription as Zs,PaySubscriptionDelete as Qs,PaySubscriptionList as Xs}from"@trakit/commands";import{utility as Ys,Machine as er,serialization as tr}from"@trakit/objects";class sr{account;baseAddress;query=new Map;headers=new Map;createBaseUrl(e){const t=this.baseAddress?new URL(e??"",this.baseAddress):new URL(e),s=new Map(this.query);for(const[e,r]of s)t.searchParams.append(e,r);return t}constructor(e,t){this.baseAddress=t?new URL(t):null,this.setAuth(e)}setAuth(e){e instanceof o?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof er||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new o({errorCode:i.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new o)}command(t){return new Promise((async(s,r)=>{let n=null,o=null,a=null;try{n=this.t(t)}catch(t){o=e(t)}try{o=o??await this.i(n)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===i.success?s:r)(a)}))}}class rr extends sr{onAccount;onList;onUpdate;onDelete;async command(e){const t=await super.command(e);if(t instanceof a&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof c?s.filter?t.getList().forEach((e=>this.onUpdate?.(s.object,r,e))):this.onList?.(s.object,r,t.getList()):t instanceof h?this.onUpdate?.(s.object,r,t.getObject()):t instanceof u?this.onDelete?.(s.object,r,t.getKey()):t instanceof d&&t.getResults().forEach((e=>this.onDelete?.(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new p);return this.setAuth(e),this.onAccount?.(e),e}async login(e,t,s){const r=await this.command(new l({username:e,password:t,userAgent:s??null}));return this.setAuth(r),this.onAccount?.(r),r}logout(){const e=this.command(new m);return this.setAuth(),this.onAccount?.(this.account),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new w({contact:{name:e??null,notes:t??null,otherNames:s??null,emails:r??null,phones:n??null,addresses:i??null,urls:o??null,dates:a??null,options:c??null,roles:h??null,pictures:u??null}}))}updatePassword(e,t){return this.command(new g({current:e,password:t}))}updatePreferences(e,t,s,r,n,i){return this.command(new v({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?tr.fromMap(r):r??null,measurements:n instanceof Map?tr.fromMap(n):n??null,options:i instanceof Map?tr.fromMap(i):i??null}))}getCompany(e){return this.command(new y({company:{id:e}}))}mergeCompany(e){return this.command(new b({company:e}))}removeCompany(e){return this.command(new f({company:{id:e}}))}restoreCompany(e){return this.command(new C({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new P({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new R({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new S({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new k({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new A({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new D({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new M({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new I({company:{id:e}}))}getReseller(e){return this.command(new T({company:{id:e}}))}mergeReseller(e){return this.command(new G({company:e}))}removeReseller(e){return this.command(new U({company:{id:e}}))}restoreReseller(e){return this.command(new B({company:{id:e}}))}listContacts(e,t){return this.command(new J({...t,company:{id:e}}))}getContact(e){return this.command(new E({contact:{id:e}}))}mergeContact(e){return this.command(new L({contact:e}))}removeContact(e){return this.command(new O({contact:{id:e}}))}restoreContact(e){return this.command(new F({contact:{id:e}}))}multiMergeContact(e){return this.command(new x({contacts:e}))}multiRemoveContact(e){return this.command(new q({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new H({...t,company:{id:e}}))}getUser(e){return this.command(new N({user:{login:e}}))}mergeUser(e){return this.command(new W({user:e}))}removeUser(e){return this.command(new _({user:{login:e}}))}restoreUser(e){return this.command(new $({user:{login:e}}))}listUserGenerals(e,t){return this.command(new j({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new K({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new z({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new V({user:{login:e}}))}listUserGroups(e,t){return this.command(new Z({...t,company:{id:e}}))}getUserGroup(e){return this.command(new Q({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new X({userGroup:e}))}removeUserGroup(e){return this.command(new Y({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new ee({userGroup:{id:e}}))}listMachines(e,t){return this.command(new te({...t,company:{id:e}}))}getMachine(e){return this.command(new se({machine:{id:e}}))}mergeMachine(e){return this.command(new re({machine:e}))}removeMachine(e){return this.command(new ne({machine:{id:e}}))}restoreMachine(e){return this.command(new ie({machine:{id:e}}))}listSessions(e,t){return this.command(new oe({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new ae({...t,user:{login:e}}))}killSession(e){return this.command(new ce({session:{handle:e}}))}listIcons(e,t){return this.command(new he({...t,company:{id:e}}))}getIcon(e){return this.command(new ue({icon:{id:e}}))}mergeIcon(e){return this.command(new de({icon:e}))}removeIcon(e){return this.command(new pe({icon:{id:e}}))}restoreIcon(e){return this.command(new le({icon:{id:e}}))}listPictures(e,t){return this.command(new me({...t,company:{id:e}}))}getPicture(e){return this.command(new we({picture:{id:e}}))}mergePicture(e){return this.command(new ge({picture:e}))}removePicture(e){return this.command(new ve({picture:{id:e}}))}restorePicture(e){return this.command(new ye({picture:{id:e}}))}listDocuments(e,t){return this.command(new be({...t,company:{id:e}}))}getDocument(e){return this.command(new fe({document:{id:e}}))}mergeDocument(e){return this.command(new Ce({document:e}))}removeDocument(e){return this.command(new Pe({document:{id:e}}))}restoreDocument(e){return this.command(new Re({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Se({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new ke({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ae({formTemplate:e}))}removeFormTemplate(e){return this.command(new De({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Me({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Ie({...t,company:{id:e}}))}getFormResult(e){return this.command(new Te({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ge({formResult:e}))}multiMergeFormResult(e){return this.command(new Ue({formResult:{id:e}}))}removeFormResult(e){return this.command(new Be({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Je({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new Ee({...t,company:{id:e}}))}getDashcamData(e){return this.command(new Le({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new Oe({...t,company:{id:e}}))}listAssets(e,t){return this.command(new Fe({...t,company:{id:e}}))}getAsset(e){return this.command(new xe({asset:{id:e}}))}mergeAsset(e){return this.command(new qe({asset:e}))}multiMergeAsset(e){return this.command(new He({assets:e}))}removeAsset(e){return this.command(new Ne({asset:{id:e}}))}restoreAsset(e){return this.command(new We({asset:{id:e}}))}suspendAsset(e){return this.command(new _e({asset:{id:e}}))}reviveAsset(e){return this.command(new $e({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new je({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new Ke({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new ze({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new Ve({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new Ze({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new Qe({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new Xe({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new Ye({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new et({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new tt({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new st({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new rt({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new nt({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new it({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new ot({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new at({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new ct({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new ht({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new ut({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new dt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new pt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new lt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new mt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new wt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new gt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new vt({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new yt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new bt({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new ft({...t,company:{id:e}}))}getPlace(e){return this.command(new Ct({place:{id:e}}))}mergePlace(e){return this.command(new Pt({place:e}))}removePlace(e){return this.command(new Rt({place:{id:e}}))}restorePlace(e){return this.command(new St({place:{id:e}}))}listProviders(e,t){return this.command(new kt({...t,company:{id:e}}))}getProvider(e){return this.command(new At({provider:{id:e}}))}mergeProvider(e){return this.command(new Dt({provider:e}))}multiMergeProvider(e){return this.command(new Mt({providers:e}))}multiRemoveProvider(e){return this.command(new It({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Tt({provider:{id:e}}))}restoreProvider(e){return this.command(new Gt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Ut({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Bt({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Jt({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Et({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Lt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new Ot({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new Ft({...t,company:{id:e}}))}getProviderScript(e){return this.command(new xt({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new qt({providerScript:e}))}removeProviderScript(e){return this.command(new Ht({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Nt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Wt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new _t({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new $t({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new jt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new Kt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new zt({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new Vt({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new Zt({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new Qt({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new Xt({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new Yt({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new es({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new ts({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new ss({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new rs({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new ns({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new is({...t,company:{id:e}}))}getBehaviour(e){return this.command(new os({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new as({behaviour:e}))}multiMergeBehaviour(e){return this.command(new cs({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new hs({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new us({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ds({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new ps({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new ls({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new ms({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new ws({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new gs({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new vs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new ys({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new bs({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new fs({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Cs({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Ps({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Rs({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Ss({reportTemplate:e}))}removeReportTemplate(e){return this.command(new ks({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new As({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Ds({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Ms({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Is({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Ts({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Gs({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Us({...t,company:{id:e}}))}getReportResult(e){return this.command(new Bs({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Js({reportResult:e}))}removeReportResult(e){return this.command(new Es({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Ls({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new Os({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new Fs({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new xs({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new qs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Hs({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Ns({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Ws({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new _s({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new $s({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new js({maintenanceJob:{id:e}}))}}const nr={Company:"/companies/generals?parent={companyId}",CompanyGeneral:"/companies/generals?parent={companyId}",CompanyDirectory:"/companies/directory?parent={companyId}",CompanyStyle:"/companies/styles?parent={companyId}",CompanyPolicy:"/companies/policies?parent={companyId}",CompanyReseller:"/companies/resellers?parent={companyId}",Contact:"/companies/{companyId}/contacts",Machine:"/companies/{companyId}/machines",User:"/companies/{companyId}/users",UserGeneral:"/companies/{companyId}/users/generals",UserAdvanced:"/companies/{companyId}/users/advanceds",UserGroup:"/companies/{companyId}/users/groups",Session:"/companies/{companyId}/users/sessions",Dashcam:"/companies/{companyId}/dashcams",DashcamLive:"/companies/{companyId}/dashcams/live",Icon:"/companies/{companyId}/icons",Picture:"/companies/{companyId}/pictures",Document:"/companies/{companyId}/documents",FormTemplate:"/companies/{companyId}/forms/templates",FormResult:"/companies/{companyId}/forms",Asset:"/companies/{companyId}/assets",AssetGeneral:"/companies/{companyId}/assets/generals",AssetAdvanced:"/companies/{companyId}/assets/advanceds",AssetDispatch:"/companies/{companyId}/assets/dispatches",AssetMessage:"/companies/{companyId}/assets/messages",AssetAlert:"/companies/{companyId}/assets/alerts",DispatchTask:"/companies/{companyId}/assets/dispatch/tasks",DispatchJob:"/companies/{companyId}/assets/dispatch/jobs",MaintenanceSchedule:"/companies/{companyId}/maintenance/schedules",MaintenanceJob:"/companies/{companyId}/maintenance/jobs",Place:"/companies/{companyId}/places",Behaviour:"/companies/{companyId}/behaviours",BehaviourScript:"/companies/{companyId}/behaviours/scripts",BehaviourLog:"",Provider:"/companies/{companyId}/providers",ProviderGeneral:"/companies/{companyId}/providers/generals",ProviderAdvanced:"/companies/{companyId}/providers/advanceds",ProviderControl:"/companies/{companyId}/providers/controls",ProviderConfiguration:"/companies/{companyId}/providers/configurations",ProviderConfigurationType:"",ProviderScript:"/companies/{companyId}/providers/scripts",ProviderConfig:"/companies/{companyId}/providers/configs",ProviderRegistration:"/companies/{companyId}/providers/registrations",ReportTemplate:"/companies/{companyId}/reports/templates",ReportSchedule:"/companies/{companyId}/reports/schedules",ReportResult:"/companies/{companyId}/reports/results",BillingProfile:"/companies/{companyId}/billing/profiles",BillingReport:"/companies/{companyId}/billing/profiles/reports",BillableHostingRule:"",BillableHostingLicense:""},ir={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},or={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},ar=/[A-Z][a-z]+/;class cr extends rr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??cr.URI_PROD),this.headers.set("Content-Type","application/json")}getVerbRoute(e){let t="GET",s="",r="";const n=e.getAction();switch(n.object){case"Self":"Get"==n.kind?(t="GET",s="self"):(t="POST",s="self/"+n.filter.toLowerCase());break;case"Subscription":throw new Error(n.object+" only supported by TrakitSocketCommander",{cause:n});case"DispatchJob":switch(n.filter){case"Cancel":t=n.batch?"PATCH":"POST",s+="/cancel";break;case"Change":t=n.batch?"PATCH":"PUT"}default:if(s=[...n.object.match(ar)].map(Ys.pluralize).join("/"),!n.batch){switch(e.getKey&&(s+="/"+e.getKey()),n.kind){case"Get":break;case"List":switch(n.filter){case"BillingProfile":case"BillingProfile":s=n.object in or?or[n.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${s}`;break;case"Company":s=n.object in nr?nr[n.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${s}`;break;case"Asset":s=n.object in ir?ir[n.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${s}`;break;case"User":s=`users/${encodeURIComponent(e.user.login)}/${s}`}Ys.isntNaN(e?.after?.valueOf())&&(r+="&after="+encodeURIComponent(e.after.toISOString())),Ys.isntNaN(e?.before?.valueOf())&&(r+="&before="+encodeURIComponent(e.before.toISOString())),Ys.isntNaN(e?.lowest)&&(r+="&lowest="+e.lowest),Ys.isntNaN(e?.highest)&&(r+="&highest="+e.highest),e?.first&&(r+="&first="+e.first),e?.last&&(r+="&last="+e.last),e?.labels?.length&&(r+="&labels="+encodeURIComponent(e.labels.join(","))),e?.references?.size&&(r+="&"+e.references.entries().map((([e,t])=>encodeURIComponent(e)+"="+encodeURIComponent(t))).toArray().join("&"));break;case"Merge":t="POST";break;case"Delete":t="DELETE";break;case"Restore":t="PATCH",s+="/restore";break;case"Suspend":t="PATCH",s+="/suspend";break;case"Reactivate":t="PATCH",s+="/revive"}break}switch(t="PATCH",n.kind){case"Get":case"List":t="GET";break;case"Merge":break;case"Delete":t="DELETE";break;case"Restore":s+="/restore";break;case"Suspend":s+="/suspend";break;case"Reactivate":s+="/revive"}}return r.length&&(s+=s.includes("?")?r:"?"+ +r.substring(1)),[t,s]}t(e){const[t,s]=this.getVerbRoute(e),r=e.toJSON(),n=this.createBaseUrl(s),i=new Map(this.headers),o={method:t,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==t&&(o.body=JSON.stringify(r)),this.account.machine?i.set("Authorization","HMAC256 "+this.account.machine.createHmacSignature(n,t,o.body?.length??0,new Date)):this.account.ghostId&&n.searchParams.set("ghostId",this.account.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(n,o)}i(t){return new Promise((async(s,r)=>{try{const e=await fetch(t);s(await e.json())}catch(t){r(e(t))}}))}}const hr=/^(.+?)(Merged|Deleted|Suspended)$/,ur={Company:[Ks.companyGeneral,Ks.companyLabels,Ks.companyPolicies],CompanyGeneral:[Ks.companyGeneral],CompanyDirectory:[],CompanyStyle:[Ks.companyLabels],CompanyPolicy:[Ks.companyPolicies],CompanyReseller:[Ks.companyReseller],Contact:[Ks.contact],Machine:[Ks.machine],User:[Ks.userGeneral,Ks.userAdvanced],UserGeneral:[Ks.userGeneral],UserAdvanced:[Ks.userAdvanced],UserGroup:[Ks.userGroup],Session:[],Dashcam:[],Icon:[Ks.icon],Picture:[Ks.picture],Document:[Ks.document],FormTemplate:[Ks.formTemplate],FormResult:[Ks.formResult],Asset:[Ks.assetGeneral,Ks.assetAdvanced,Ks.assetDispatch],AssetGeneral:[Ks.assetGeneral],AssetAdvanced:[Ks.assetAdvanced],AssetDispatch:[Ks.assetDispatch],AssetMessage:[Ks.assetMessage],AssetAlert:[],DispatchTask:[Ks.dispatchTask],DispatchJob:[Ks.dispatchJob],MaintenanceSchedule:[Ks.maintenanceSchedule],MaintenanceJob:[Ks.maintenanceJob],Place:[Ks.placeGeneral],BehaviourScript:[Ks.behaviourScript],Behaviour:[Ks.behaviour],BehaviourLog:[Ks.behaviourLog],Provider:[Ks.providerGeneral,Ks.providerAdvanced,Ks.providerControl],ProviderGeneral:[Ks.providerGeneral],ProviderAdvanced:[Ks.providerAdvanced],ProviderControl:[Ks.providerControl],ProviderConfiguration:[Ks.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[Ks.providerScript],ProviderConfig:[Ks.providerConfig],ProviderRegistration:[Ks.providerRegistration],ReportTemplate:[Ks.reportTemplate],ReportSchedule:[Ks.reportSchedule],ReportResult:[Ks.reportResult],BillingProfile:[Ks.billingProfile],BillingReport:[Ks.billingReport],BillableHostingRule:[Ks.billingHosting],BillableHostingLicense:[Ks.billingLicense]};class dr{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(let[s,r]of this.#e)r&&r<e&&t.push(s);return t}purgeExpired(){const e=this.getExpired();return e.forEach((e=>this.#e.delete(e))),e}getExpiring(){const e=[];for(let[t,s]of this.#e)s&&e.push(t);return e}#t(e,t){return t=t||null,this.#e.set(e,t),t}addExpiry(e){return this.#t(e,new Date((new Date).valueOf()+3e5))}addExpiries(e){return e.map((e=>this.addExpiry(e)))}removeExpiry(e){const t=this.#e.get(e);return this.#t(e),t||null}removeExpiries(e){return e.map((e=>this.removeExpiry(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}const pr="connection",lr="dis"+pr;var mr;!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"}(mr||(mr={}));class wr extends rr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";#s=new Date(NaN);#r=new Date(NaN);#n="";#i=new Date(NaN);get lastConnected(){return this.#s}get lastReceived(){return this.#r}get lastMessage(){return this.#n}get lastSent(){return this.#i}get state(){switch(this.#o?.readyState){case WebSocket.CONNECTING:return mr.opening;case WebSocket.OPEN:return this.#a?mr.open:mr.opening;case WebSocket.CLOSING:return mr.closing;default:return mr.closed}}get ready(){return this.#a&&this.#c}onOpen;onClose;onMessage;onError;#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.onError?.(new zs({errorCode:i.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#g(e){clearTimeout(this.#v),clearTimeout(this.#y),this.#a=!1,this.#m=this.#m?2*this.#m:this.lastReceived?(new Date).valueOf()-this.lastReceived.valueOf():5e3;const t=Math.min(this.#m,3e5),s={kind:"connection",state:mr.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:i.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#u.keys()].sort())this.#d(e,e===lr?r:{...r,reqId:e,errorCode:i.unknown,errorDetails:{...s}});this.onClose?.(new zs(r)),this.#y=this.reconnectEnabled&&this.#c?setTimeout((()=>this.open()),t,this):0,this.#o=this.#o.onopen=this.#o.onerror=this.#o.onclose=this.#o.onmessage=null}#l(e){this.#r=new Date;const t=e.data.substring(0,e.data.indexOf(" ")),s=JSON.parse(e.data.substring(t.length+1));switch(this.#n=t,"connectionResponse"!==t&&"noopResponse"!==t&&this.onMessage?.(t,s),t){case"connectionResponse":this.#b(s),this.#s=new Date(this.#r),this.#a=!0,this.#d(pr,s),this.onAccount?.(this.account),this.onOpen?.(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#b(s),this.onAccount?.(this.account);break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"sessionMachineMerged":this.account.machine?.fromJSON(s),this.onAccount?.(this.account);break;case"sessionGeneralMerged":this.account.user?.general?.fromJSON(s),this.onAccount?.(this.account);break;case"sessionAdvancedMerged":this.account.user?.advanced?.fromJSON(s),this.onAccount?.(this.account);break;case"logoutResponse":this.close();case"sessionEnded":this.#b(s),this.#c=!1,this.onAccount?.(this.account)}if(t.endsWith("Response"))this.#d(s.reqId,s);else if(!t.startsWith("session")){const e=hr.exec(t);e?.length&&this.#f(e,s)}this.resetKeepAlive()}#b(e){if(e.user){const t={...e.user};if(t.contact){const e=t.contact;this.#f([,"contact","Merged"],e),t.contact=e.id}this.#f([,"user","Merged"],t)}e.machine&&this.#f([,"machine","Merged"],e.machine),this.setAuth(new o(e)),this.#c=0===this.account.errorCode&&!this.account.user?.passwordExpired}#f(e,t){const s=function(e){e="CompanyLabels"===(e=Ys.capitalize(e))?"CompanyStyle":Ys.singularize(e);return e}(e[1]),r=t[s.startsWith("Company")?"parent":"company"],o=function(e,t){return n["Rep"+e+(t??"Get")]}(s,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(o){const n=new o({errorCode:i.success,message:e[2]+" event",[e[1]]:t});if(n.store())switch(e[2]){case"Merged":case"Suspended":const e=n.getObject?.();e&&this.onUpdate?.(s,r,e);break;case"Deleted":this.onDelete?.(s,r,function(e,t){return e[function(e){switch(e){case"User":case"UserGeneral":case"UserAdvanced":return"login";case"ProviderRegistration":return"code";case"Session":return"handle";case"Machine":return"key";case"Dashcam":return"guid";default:return"id"}}(t)]}(t,s))}return n}}reconnectEnabled=!0;#m=0;#y=0;keepAliveEnabled=!1;#v=0;constructor(e,t){super(e,t??wr.URI_PROD)}dispose(){this.#c=!1,this.close().finally((()=>{this.#o=this.#u=null}))}open(){return clearTimeout(this.#y),this.#y=0,new Promise((async(e,t)=>{const s=this.state;if(s===mr.closed){const s=this.createBaseUrl();this.account.machine?(s.searchParams.delete("shadowKey"),this.account.machine.secret?.length&&(s.searchParams.delete("shadowSig"),s.searchParams.append("shadowSig",await this.account.machine.createHmacSignature(s))),s.searchParams.append("shadowKey",this.account.machine.key)):this.account.ghostId&&s.searchParams.set("ghostId",this.account.ghostId),this.#o=new WebSocket(s),this.#o.onopen=e=>this.#p(e),this.#o.onerror=e=>this.#w(e),this.#o.onclose=e=>this.#g(e),this.#u.set(pr,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new o({errorCode:i.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))}))}close(){return new Promise(((e,t)=>{const s=this.state;switch(s){case mr.opening:case mr.open:this.reconnectEnabled=!1,this.#u.set(lr,(s=>{(0===s.errorCode?e:t)(new zs(s))})),this.#o.close(1e3,"Bye!");break;default:t(new zs({errorCode:i.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}}))}t(e){return[t(e),e.toJSON()]}i(t){const s=t[0],r=t[1]||{};return new Promise(((n,o)=>{const a=this.state;switch(a){case mr.open:const c=++this.#h,h=setTimeout((()=>this.#d(c,{reqId:c,errorCode:i.unknown,message:"Command timeout"})),12e4);r.reqId=c,this.#u.set(c,(e=>{clearTimeout(h),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r))}catch(t){this.#d(c,e(t))}this.resetKeepAlive();break;case mr.closed:this.open().then((()=>this.i(t).then(n))).catch(o);break;default:o({errorCode:i.unknown,message:"Not connected",errorDetails:{kind:"connection",connection:a}})}}))}resetKeepAlive(){return clearTimeout(this.#v),this.#v=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.i(["noop",{}])),3e5):0,Promise.resolve(0!==this.#v)}subscribe(e,t){return t?.length?this.command(new Vs({company:e,subscriptionTypes:t})):Promise.resolve(new Zs({errorCode:i.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new Qs({company:e,subscriptionTypes:t})):Promise.resolve(new Zs({errorCode:i.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new Xs)}}const gr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class vr extends rr{#o;#C;get autoConnect(){return this.#o.reconnectEnabled}set autoConnect(e){this.#o.reconnectEnabled=!!e,e&&this.#o.state===mr.closed&&this.#o.open()}get online(){return this.#o.state===mr.open}onOpen;onError;onMessage;onClose;constructor(e,t,s){super(e),this.#C=new cr(this.account,t),this.#o=new wr(this.account,s),this.#C.onAccount=this.#o.onAccount=e=>this.#P?.(e),this.#C.onList=this.#o.onList=(e,t,s)=>this.onList?.(e,t,s),this.#C.onUpdate=this.#o.onUpdate=(e,t,s)=>this.onUpdate?.(e,t,s),this.#C.onDelete=this.#o.onDelete=(e,t,s)=>this.onDelete?.(e,t,s),this.#o.onOpen=e=>this.#p(e),this.#o.onError=e=>this.#w(e),this.#o.onMessage=(e,t)=>this.#l(e,t),this.#o.onClose=e=>this.#g(e),this.autoConnect=!!this.account.ghostId}dispose(){this.#o.dispose(),this.#C=this.#o=null}setAuth(e){super.setAuth(e),e!==this.#C?.account&&this.#C?.setAuth(this.account),e!==this.#o?.account&&this.#o?.setAuth(this.account)}command(e){switch(e.getAction().object){case"Subscription":case"Self":return this.#o.command(e);default:return this.#C.command(e)}}t(e){throw new Error("Method not implemented.")}i(e){throw new Error("Method not implemented.")}rest(e){return this.#C.command(e)}socket(e){return this.#o.command(e)}#P(e){this.setAuth(e),this.onAccount?.(e)}#p(e){this.#R.forEach(((e,t)=>{this.sync(t,r(e.reset()))})),this.#S(),this.onOpen?.(e)}#g(e){clearTimeout(this.#k),this.#k=0,this.onClose?.(e)}#l(e,t){this.onMessage?.(e,t)}#w(e){this.onError?.(e)}isSynced(e,t){let r=this.#o.state===mr.open;if(r){const n=this.#A(e);r=s(t).every((e=>n.regions.includes(e)))}return r}async sync(e,t){const i=[],o=this.#A(e),a=s(t).filter((e=>!o.regions.includes(e)));if(a.length>0){const t=(await this.#o.subscribe(e,a)).merged;o.removeExpiries(a),r(t).forEach((t=>{const s=function(e,t){return n["Pay"+e+(t??"Get")]}(t,t.startsWith("Company")?"Get":"ListByCompany");s&&i.push(this.command(new s({company:{id:e}})))}))}return Promise.all(i)}async desync(e,t){const s=this.#A(e),r=t.reduce(((e,t)=>e.concat(ur[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));s.addExpiries(r)}#R=new Map;#S(){const e=[];this.#o.state===mr.open&&this.#R.forEach(((t,s)=>{const r=t.purgeExpired();r.length&&e.push(this.unsubscribe(s,r))})),Promise.allSettled(e).finally((()=>{this.#k=setTimeout((()=>this.#S()),1e4)}))}#k;#A(e){let t=this.#R.get(e);return t||this.#R.set(e,t=new dr),t}subscribe(e,t){return this.#o.subscribe(e,t)}unsubscribe(e,t){return this.#o.unsubscribe(e,t)}listSubscriptions(){return this.#o.listSubscriptions()}}
2
+ /**
3
+ * Synchronization library main process.
4
+ * {@link https://github.com/trakitwireless/trakit-ts-sync|Client synchronization library.}
5
+ * Last updated on Thu Feb 27 2025 11:59:01
6
+ * @copyright Trak-iT Wireless Inc. 2025
7
+ */const yr="0.0.7";export{dr as SubscribedRegions,sr as TrakitBaseCommander,rr as TrakitObjectCommander,cr as TrakitRestfulCommander,wr as TrakitSocketCommander,vr as TrakitSyncCommander,yr as version};