diff --git a/.gitignore b/.gitignore
index 564a52a..8bd433d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,8 +2,8 @@
node_modules/
.DS_Store
.rpt2_cache
-dist/
config*.json
.vs/
.vscode/
coverage/
+dist/
diff --git a/dist/constants.d.ts b/dist/constants.d.ts
new file mode 100644
index 0000000..28d06f2
--- /dev/null
+++ b/dist/constants.d.ts
@@ -0,0 +1,24 @@
+import { CanadianBrandEnvironment } from './constants/canada';
+import { EuropeanBrandEnvironment } from './constants/europe';
+import { ChineseBrandEnvironment } from './constants/china';
+import { AustraliaBrandEnvironment } from './constants/australia';
+import { Brand, VehicleStatusOptions } from './interfaces/common.interfaces';
+export declare const ALL_ENDPOINTS: {
+ CA: (brand: Brand) => CanadianBrandEnvironment['endpoints'];
+ EU: (brand: Brand) => EuropeanBrandEnvironment['endpoints'];
+ CN: (brand: Brand) => ChineseBrandEnvironment['endpoints'];
+ AU: (brand: Brand) => AustraliaBrandEnvironment['endpoints'];
+};
+export declare const GEN2 = 2;
+export declare const GEN1 = 1;
+export type REGION = 'US' | 'CA' | 'EU' | 'CN' | 'AU';
+export declare enum REGIONS {
+ US = "US",
+ CA = "CA",
+ EU = "EU",
+ CN = "CN",
+ AU = "AU"
+}
+export type ChargeTarget = 50 | 60 | 70 | 80 | 90 | 100;
+export declare const POSSIBLE_CHARGE_LIMIT_VALUES: number[];
+export declare const DEFAULT_VEHICLE_STATUS_OPTIONS: VehicleStatusOptions;
diff --git a/dist/constants/america.d.ts b/dist/constants/america.d.ts
new file mode 100644
index 0000000..66cf95b
--- /dev/null
+++ b/dist/constants/america.d.ts
@@ -0,0 +1,9 @@
+import { Brand } from '../interfaces/common.interfaces';
+export interface AmericaBrandEnvironment {
+ brand: Brand;
+ host: string;
+ baseUrl: string;
+ clientId: string;
+ clientSecret: string;
+}
+export declare const getBrandEnvironment: (brand: Brand) => AmericaBrandEnvironment;
diff --git a/dist/constants/australia.cfb.d.ts b/dist/constants/australia.cfb.d.ts
new file mode 100644
index 0000000..62dc427
--- /dev/null
+++ b/dist/constants/australia.cfb.d.ts
@@ -0,0 +1,3 @@
+///
+export declare const kiaCFB: Buffer;
+export declare const hyundaiCFB: Buffer;
diff --git a/dist/constants/australia.d.ts b/dist/constants/australia.d.ts
new file mode 100644
index 0000000..60c15b2
--- /dev/null
+++ b/dist/constants/australia.d.ts
@@ -0,0 +1,28 @@
+import { AustraliaBlueLinkyConfig } from '../controllers/australia.controller';
+import { Brand } from '../interfaces/common.interfaces';
+import { StampMode } from './stamps';
+export interface AustraliaBrandEnvironment {
+ brand: Brand;
+ host: string;
+ baseUrl: string;
+ clientId: string;
+ appId: string;
+ endpoints: {
+ integration: string;
+ silentSignIn: string;
+ session: string;
+ login: string;
+ language: string;
+ redirectUri: string;
+ token: string;
+ };
+ basicToken: string;
+ stamp: () => Promise;
+}
+type EnvironmentConfig = {
+ stampMode: StampMode;
+ stampsFile?: string;
+};
+type BrandEnvironmentConfig = Pick & Partial;
+export declare const getBrandEnvironment: ({ brand, stampMode, stampsFile, }: BrandEnvironmentConfig) => AustraliaBrandEnvironment;
+export {};
diff --git a/dist/constants/canada.d.ts b/dist/constants/canada.d.ts
new file mode 100644
index 0000000..908561c
--- /dev/null
+++ b/dist/constants/canada.d.ts
@@ -0,0 +1,28 @@
+import { Brand } from '../interfaces/common.interfaces';
+export interface CanadianBrandEnvironment {
+ brand: Brand;
+ host: string;
+ baseUrl: string;
+ origin: 'SPA';
+ endpoints: {
+ login: string;
+ logout: string;
+ vehicleList: string;
+ vehicleInfo: string;
+ status: string;
+ remoteStatus: string;
+ lock: string;
+ unlock: string;
+ start: string;
+ stop: string;
+ locate: string;
+ hornlight: string;
+ verifyAccountToken: string;
+ verifyPin: string;
+ verifyToken: string;
+ setChargeTarget: string;
+ stopCharge: string;
+ startCharge: string;
+ };
+}
+export declare const getBrandEnvironment: (brand: Brand) => CanadianBrandEnvironment;
diff --git a/dist/constants/china.d.ts b/dist/constants/china.d.ts
new file mode 100644
index 0000000..15771f9
--- /dev/null
+++ b/dist/constants/china.d.ts
@@ -0,0 +1,25 @@
+import { ChineseBlueLinkConfig } from '../controllers/chinese.controller';
+import { Brand } from '../interfaces/common.interfaces';
+export interface ChineseBrandEnvironment {
+ brand: Brand;
+ host: string;
+ baseUrl: string;
+ clientId: string;
+ appId: string;
+ endpoints: {
+ integration: string;
+ silentSignIn: string;
+ session: string;
+ login: string;
+ language: string;
+ redirectUri: string;
+ token: string;
+ };
+ basicToken: string;
+ GCMSenderID: string;
+ providerDeviceId: string;
+ pushRegId: string;
+}
+type BrandEnvironmentConfig = Pick;
+export declare const getBrandEnvironment: ({ brand, }: BrandEnvironmentConfig) => ChineseBrandEnvironment;
+export {};
diff --git a/dist/constants/europe.cfb.d.ts b/dist/constants/europe.cfb.d.ts
new file mode 100644
index 0000000..62dc427
--- /dev/null
+++ b/dist/constants/europe.cfb.d.ts
@@ -0,0 +1,3 @@
+///
+export declare const kiaCFB: Buffer;
+export declare const hyundaiCFB: Buffer;
diff --git a/dist/constants/europe.d.ts b/dist/constants/europe.d.ts
new file mode 100644
index 0000000..27d22ac
--- /dev/null
+++ b/dist/constants/europe.d.ts
@@ -0,0 +1,33 @@
+import { EuropeBlueLinkyConfig } from '../controllers/european.controller';
+import { Brand } from '../interfaces/common.interfaces';
+export type EULanguages = 'cs' | 'da' | 'nl' | 'en' | 'fi' | 'fr' | 'de' | 'it' | 'pl' | 'hu' | 'no' | 'sk' | 'es' | 'sv';
+export declare const EU_LANGUAGES: EULanguages[];
+export declare const DEFAULT_LANGUAGE: EULanguages;
+export interface EuropeanBrandEnvironment {
+ brand: Brand;
+ host: string;
+ baseUrl: string;
+ clientId: string;
+ appId: string;
+ endpoints: {
+ integration: string;
+ silentSignIn: string;
+ session: string;
+ login: string;
+ language: string;
+ redirectUri: string;
+ token: string;
+ };
+ basicToken: string;
+ GCMSenderID: string;
+ stamp: () => Promise;
+ brandAuthUrl: (options: {
+ language: EULanguages;
+ serviceId: string;
+ userId: string;
+ }) => string;
+}
+type EnvironmentConfig = Required> & Partial>;
+type BrandEnvironmentConfig = Pick & Partial;
+export declare const getBrandEnvironment: ({ brand, stampMode, stampsFile, }: BrandEnvironmentConfig) => EuropeanBrandEnvironment;
+export {};
diff --git a/dist/constants/stamps.d.ts b/dist/constants/stamps.d.ts
new file mode 100644
index 0000000..b1ad97d
--- /dev/null
+++ b/dist/constants/stamps.d.ts
@@ -0,0 +1,16 @@
+import { Brand } from '../interfaces/common.interfaces';
+import { REGIONS } from '../constants';
+export declare enum StampMode {
+ LOCAL = "LOCAL",
+ DISTANT = "DISTANT"
+}
+export declare const getStampFromFile: (stampFileKey: string, stampHost: string, stampsFile?: string) => () => Promise;
+export declare const getStampFromCFB: (appId: string, brand: Brand, region: REGIONS) => (() => Promise);
+export declare const getStampGenerator: ({ appId, brand, mode, region, stampHost, stampsFile, }: {
+ appId: string;
+ brand: Brand;
+ mode: StampMode;
+ region: REGIONS;
+ stampHost: string;
+ stampsFile?: string | undefined;
+}) => (() => Promise);
diff --git a/dist/controllers/american.controller.d.ts b/dist/controllers/american.controller.d.ts
new file mode 100644
index 0000000..6097151
--- /dev/null
+++ b/dist/controllers/american.controller.d.ts
@@ -0,0 +1,17 @@
+import { BlueLinkyConfig } from './../interfaces/common.interfaces';
+import { Vehicle } from '../vehicles/vehicle';
+import { SessionController } from './controller';
+import { AmericaBrandEnvironment } from '../constants/america';
+export interface AmericanBlueLinkyConfig extends BlueLinkyConfig {
+ region: 'US';
+}
+export declare class AmericanController extends SessionController {
+ private _environment;
+ constructor(userConfig: AmericanBlueLinkyConfig);
+ get environment(): AmericaBrandEnvironment;
+ private vehicles;
+ refreshAccessToken(): Promise;
+ login(): Promise;
+ logout(): Promise;
+ getVehicles(): Promise>;
+}
diff --git a/dist/controllers/australia.controller.d.ts b/dist/controllers/australia.controller.d.ts
new file mode 100644
index 0000000..8bf12b9
--- /dev/null
+++ b/dist/controllers/australia.controller.d.ts
@@ -0,0 +1,28 @@
+import { GotInstance, GotJSONFn } from 'got';
+import { Vehicle } from '../vehicles/vehicle';
+import { AustraliaBrandEnvironment } from './../constants/australia';
+import { BlueLinkyConfig, Session } from './../interfaces/common.interfaces';
+import { SessionController } from './controller';
+import { StampMode } from '../constants/stamps';
+export interface AustraliaBlueLinkyConfig extends BlueLinkyConfig {
+ region: 'AU';
+ stampMode?: StampMode;
+ stampsFile?: string;
+}
+export declare class AustraliaController extends SessionController {
+ private _environment;
+ private authStrategy;
+ constructor(userConfig: AustraliaBlueLinkyConfig);
+ get environment(): AustraliaBrandEnvironment;
+ session: Session;
+ private vehicles;
+ refreshAccessToken(): Promise;
+ enterPin(): Promise;
+ login(): Promise;
+ logout(): Promise;
+ getVehicles(): Promise>;
+ private checkControlToken;
+ getVehicleHttpService(): Promise>;
+ getApiHttpService(): Promise>;
+ private get defaultHeaders();
+}
diff --git a/dist/controllers/authStrategies/australia.authStrategy.d.ts b/dist/controllers/authStrategies/australia.authStrategy.d.ts
new file mode 100644
index 0000000..daa1d0d
--- /dev/null
+++ b/dist/controllers/authStrategies/australia.authStrategy.d.ts
@@ -0,0 +1,17 @@
+import { CookieJar } from 'tough-cookie';
+import { AuthStrategy, Code } from './authStrategy';
+import { AustraliaBrandEnvironment } from '../../constants/australia';
+export declare class AustraliaAuthStrategy implements AuthStrategy {
+ private readonly environment;
+ constructor(environment: AustraliaBrandEnvironment);
+ get name(): string;
+ login(user: {
+ username: string;
+ password: string;
+ }, options?: {
+ cookieJar: CookieJar;
+ }): Promise<{
+ code: Code;
+ cookies: CookieJar;
+ }>;
+}
diff --git a/dist/controllers/authStrategies/authStrategy.d.ts b/dist/controllers/authStrategies/authStrategy.d.ts
new file mode 100644
index 0000000..842e932
--- /dev/null
+++ b/dist/controllers/authStrategies/authStrategy.d.ts
@@ -0,0 +1,16 @@
+import { CookieJar } from 'tough-cookie';
+import { EULanguages, EuropeanBrandEnvironment } from '../../constants/europe';
+export type Code = string;
+export interface AuthStrategy {
+ readonly name: string;
+ login(user: {
+ username: string;
+ password: string;
+ }, options?: {
+ cookieJar?: CookieJar;
+ }): Promise<{
+ code: Code;
+ cookies: CookieJar;
+ }>;
+}
+export declare function initSession(environment: EuropeanBrandEnvironment, language?: EULanguages, cookies?: CookieJar): Promise;
diff --git a/dist/controllers/authStrategies/china.authStrategy.d.ts b/dist/controllers/authStrategies/china.authStrategy.d.ts
new file mode 100644
index 0000000..8e4e18e
--- /dev/null
+++ b/dist/controllers/authStrategies/china.authStrategy.d.ts
@@ -0,0 +1,16 @@
+import { CookieJar } from 'tough-cookie';
+import { ChineseBrandEnvironment } from '../../constants/china';
+export type Code = string;
+export interface AuthStrategy {
+ readonly name: string;
+ login(user: {
+ username: string;
+ password: string;
+ }, options?: {
+ cookieJar?: CookieJar;
+ }): Promise<{
+ code: Code;
+ cookies: CookieJar;
+ }>;
+}
+export declare function initSession(environment: ChineseBrandEnvironment, cookies?: CookieJar): Promise;
diff --git a/dist/controllers/authStrategies/chinese.legacyAuth.strategy.d.ts b/dist/controllers/authStrategies/chinese.legacyAuth.strategy.d.ts
new file mode 100644
index 0000000..d675804
--- /dev/null
+++ b/dist/controllers/authStrategies/chinese.legacyAuth.strategy.d.ts
@@ -0,0 +1,17 @@
+import { CookieJar } from 'tough-cookie';
+import { ChineseBrandEnvironment } from '../../constants/china';
+import { AuthStrategy, Code } from './china.authStrategy';
+export declare class ChineseLegacyAuthStrategy implements AuthStrategy {
+ private readonly environment;
+ constructor(environment: ChineseBrandEnvironment);
+ get name(): string;
+ login(user: {
+ username: string;
+ password: string;
+ }, options?: {
+ cookieJar: CookieJar;
+ }): Promise<{
+ code: Code;
+ cookies: CookieJar;
+ }>;
+}
diff --git a/dist/controllers/authStrategies/european.brandAuth.strategy.d.ts b/dist/controllers/authStrategies/european.brandAuth.strategy.d.ts
new file mode 100644
index 0000000..f564ece
--- /dev/null
+++ b/dist/controllers/authStrategies/european.brandAuth.strategy.d.ts
@@ -0,0 +1,18 @@
+import { CookieJar } from 'tough-cookie';
+import { EULanguages, EuropeanBrandEnvironment } from '../../constants/europe';
+import { AuthStrategy, Code } from './authStrategy';
+export declare class EuropeanBrandAuthStrategy implements AuthStrategy {
+ private readonly environment;
+ private readonly language;
+ constructor(environment: EuropeanBrandEnvironment, language: EULanguages);
+ get name(): string;
+ login(user: {
+ username: string;
+ password: string;
+ }, options?: {
+ cookieJar?: CookieJar;
+ }): Promise<{
+ code: Code;
+ cookies: CookieJar;
+ }>;
+}
diff --git a/dist/controllers/authStrategies/european.legacyAuth.strategy.d.ts b/dist/controllers/authStrategies/european.legacyAuth.strategy.d.ts
new file mode 100644
index 0000000..8df6ccc
--- /dev/null
+++ b/dist/controllers/authStrategies/european.legacyAuth.strategy.d.ts
@@ -0,0 +1,18 @@
+import { CookieJar } from 'tough-cookie';
+import { EULanguages, EuropeanBrandEnvironment } from '../../constants/europe';
+import { AuthStrategy, Code } from './authStrategy';
+export declare class EuropeanLegacyAuthStrategy implements AuthStrategy {
+ private readonly environment;
+ private readonly language;
+ constructor(environment: EuropeanBrandEnvironment, language: EULanguages);
+ get name(): string;
+ login(user: {
+ username: string;
+ password: string;
+ }, options?: {
+ cookieJar: CookieJar;
+ }): Promise<{
+ code: Code;
+ cookies: CookieJar;
+ }>;
+}
diff --git a/dist/controllers/canadian.controller.d.ts b/dist/controllers/canadian.controller.d.ts
new file mode 100644
index 0000000..2cd4976
--- /dev/null
+++ b/dist/controllers/canadian.controller.d.ts
@@ -0,0 +1,19 @@
+import { BlueLinkyConfig } from '../interfaces/common.interfaces';
+import { CanadianBrandEnvironment } from '../constants/canada';
+import { Vehicle } from '../vehicles/vehicle';
+import { SessionController } from './controller';
+export interface CanadianBlueLinkyConfig extends BlueLinkyConfig {
+ region: 'CA';
+}
+export declare class CanadianController extends SessionController {
+ private _environment;
+ constructor(userConfig: CanadianBlueLinkyConfig);
+ get environment(): CanadianBrandEnvironment;
+ private vehicles;
+ private timeOffset;
+ refreshAccessToken(): Promise;
+ login(): Promise;
+ logout(): Promise;
+ getVehicles(): Promise>;
+ private request;
+}
diff --git a/dist/controllers/chinese.controller.d.ts b/dist/controllers/chinese.controller.d.ts
new file mode 100644
index 0000000..2dc39ed
--- /dev/null
+++ b/dist/controllers/chinese.controller.d.ts
@@ -0,0 +1,26 @@
+import { ChineseBrandEnvironment } from '../constants/china';
+import { BlueLinkyConfig, Session } from '../interfaces/common.interfaces';
+import { GotInstance, GotJSONFn } from 'got';
+import { Vehicle } from '../vehicles/vehicle';
+import { SessionController } from './controller';
+export interface ChineseBlueLinkConfig extends BlueLinkyConfig {
+ region: 'CN';
+}
+export declare class ChineseController extends SessionController {
+ private _environment;
+ private authStrategies;
+ constructor(userConfig: ChineseBlueLinkConfig);
+ get environment(): ChineseBrandEnvironment;
+ ß: any;
+ session: Session;
+ private vehicles;
+ refreshAccessToken(): Promise;
+ enterPin(): Promise;
+ login(): Promise;
+ logout(): Promise;
+ getVehicles(): Promise>;
+ private checkControlToken;
+ getVehicleHttpService(): Promise>;
+ getApiHttpService(): Promise>;
+ private get defaultHeaders();
+}
diff --git a/dist/controllers/controller.d.ts b/dist/controllers/controller.d.ts
new file mode 100644
index 0000000..7a9ab00
--- /dev/null
+++ b/dist/controllers/controller.d.ts
@@ -0,0 +1,12 @@
+import { Vehicle } from '../vehicles/vehicle';
+import { Session } from '../interfaces/common.interfaces';
+import { BlueLinkyConfig } from '../interfaces/common.interfaces';
+export declare abstract class SessionController {
+ readonly userConfig: T;
+ abstract login(): Promise;
+ abstract logout(): Promise;
+ abstract getVehicles(): Promise>;
+ abstract refreshAccessToken(): Promise;
+ session: Session;
+ constructor(userConfig: T);
+}
diff --git a/dist/controllers/european.controller.d.ts b/dist/controllers/european.controller.d.ts
new file mode 100644
index 0000000..45e1ae5
--- /dev/null
+++ b/dist/controllers/european.controller.d.ts
@@ -0,0 +1,29 @@
+import { EuropeanBrandEnvironment, EULanguages } from './../constants/europe';
+import { BlueLinkyConfig, Session } from './../interfaces/common.interfaces';
+import { GotInstance, GotJSONFn } from 'got';
+import { Vehicle } from '../vehicles/vehicle';
+import { SessionController } from './controller';
+import { StampMode } from '../constants/stamps';
+export interface EuropeBlueLinkyConfig extends BlueLinkyConfig {
+ language?: EULanguages;
+ region: 'EU';
+ stampMode?: StampMode;
+ stampsFile?: string;
+}
+export declare class EuropeanController extends SessionController {
+ private _environment;
+ private authStrategies;
+ constructor(userConfig: EuropeBlueLinkyConfig);
+ get environment(): EuropeanBrandEnvironment;
+ session: Session;
+ private vehicles;
+ refreshAccessToken(): Promise;
+ enterPin(): Promise;
+ login(): Promise;
+ logout(): Promise;
+ getVehicles(): Promise>;
+ private checkControlToken;
+ getVehicleHttpService(): Promise>;
+ getApiHttpService(): Promise>;
+ private get defaultHeaders();
+}
diff --git a/dist/index.cjs b/dist/index.cjs
new file mode 100644
index 0000000..62e9c61
--- /dev/null
+++ b/dist/index.cjs
@@ -0,0 +1,2 @@
+/* @preserve bluelinky / MIT License / https://github.com/Hacksore/bluelinky */
+"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("got"),t=require("winston"),i=require("fs"),o=require("util"),n=require("url"),r=require("tough-cookie"),s=require("node:crypto"),a=require("undici"),d=require("events");function l(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var c=l(t);function h(e,t,i,o){return new(i||(i=Promise))((function(n,r){function s(e){try{d(o.next(e))}catch(e){r(e)}}function a(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const u=process.env.LOG_LEVEL||"info",{colorize:v,json:p,combine:g,timestamp:f,printf:m}=c.format,y=m((({level:e,message:t,timestamp:i})=>(["array","object"].includes(typeof t)&&(t=JSON.stringify(t,null,2)),`[${i}] ${e}: ${t}`))),b=g(f({format:"YYYY-MM-DD HH:mm:ss"}),v(),p(),y),C=c.createLogger({format:b,level:u,transports:[new c.transports.Console({})]}),w=e=>({login:`${e}/tods/api/lgn`,logout:`${e}/tods/api/lgout`,vehicleList:`${e}/tods/api/vhcllst`,vehicleInfo:`${e}/tods/api/sltvhcl`,status:`${e}/tods/api/lstvhclsts`,remoteStatus:`${e}/tods/api/rltmvhclsts`,lock:`${e}/tods/api/drlck`,unlock:`${e}/tods/api/drulck`,start:`${e}/tods/api/evc/rfon`,stop:`${e}/tods/api/evc/rfoff`,startCharge:`${e}/tods/api/evc/rcstrt`,stopCharge:`${e}/tods/api/evc/rcstp`,setChargeTarget:`${e}/tods/api/evc/setsoc`,locate:`${e}/tods/api/fndmcr`,hornlight:`${e}/tods/api/hornlight`,verifyAccountToken:`${e}/tods/api/vrfyacctkn`,verifyPin:`${e}/tods/api/vrfypin`,verifyToken:`${e}/tods/api/vrfytnc`}),k=e=>{const t=`https://${e}`;return{host:e,baseUrl:t,origin:"SPA",endpoints:Object.freeze(w(t))}},S=e=>{switch(e){case"hyundai":return Object.freeze(Object.assign({brand:"hyundai"},k("mybluelink.ca")));case"kia":return Object.freeze(Object.assign({brand:"hyundai"},k("kiaconnect.ca")));default:throw new Error(`Constructor ${e} is not managed.`)}},T=Buffer.from("IDbMgWBXgic4MAyMgf5PFFRAdGX5O3IyC3uvN3scCs0gDpTFDuyvBorlAH9JMM2/hys=","base64"),A=Buffer.from("V60WkEmyRQaAfrBF1623/7QL62MjLVbCHdItGzQ1g5T/hkmKmMVTaMHv4cKGzgD3kfc=","base64"),O=Buffer.from("wLTVxwidmH8CfJYBWSnHD6E0huk0ozdiuygB4hLkM5XCgzAL1Dk5sE36d/bx5PFMQeU=","base64"),$=Buffer.from("RFtoRq/vDXJmRndoZaZQyfOot7OrIqGVFj96iY2WL3yyH5Z/pUvlUhqmCxD2t+D65SQ=","base64");var D;!function(e){e.LOCAL="LOCAL",e.DISTANT="DISTANT"}(D||(D={}));const I=new Map,E=(t,n,r)=>()=>h(void 0,void 0,void 0,(function*(){var s;const{stamps:a,generated:d,frequency:l}=null!==(s=I.get(t))&&void 0!==s?s:yield((t,n,...r)=>h(void 0,[t,n,...r],void 0,(function*(t,n,r=`${n}${t}.v2.json`){if(r.startsWith("file://")){const[,e]=r.split("file://"),t=yield o.promisify(i.readFile)(e);return JSON.parse(t.toString("utf-8"))}const{body:s}=yield e(r,{json:!0});return I.set(t,s),s})))(t,n,r),c=new Date(d),u=Date.now()-c.getTime(),v=Math.floor(u/l);return v/(a.length-1)>=.9&&I.delete(t),a[Math.min(v,a.length-1)]})),L=(e,t,i)=>{const o=((e,t)=>{switch(t){case _.AU:return"kia"===e?T:A;case _.EU:return"kia"===e?O:$;default:throw new Error("Local stamp generation is only supported in Australia and Europe")}})(t,i);return()=>h(void 0,void 0,void 0,(function*(){const t=Buffer.from(`${e}:${Date.now()}`,"utf-8");return Promise.resolve(((e,t)=>{if(e.length!==t.length)throw new Error(`XOR Buffers are not the same size ${e.length} vs ${t.length}`);const i=Buffer.alloc(e.length);for(let o=0;o{switch(i){case D.LOCAL:return L(e,t,o);case D.DISTANT:default:return E(`${t}-${e}`,n,r)}},R=["cs","da","nl","en","fi","fr","de","it","pl","hu","no","sk","es","sv"],M=(e,t)=>({session:`${e}/api/v1/user/oauth2/authorize?response_type=code&state=test&client_id=${t}&redirect_uri=${e}/api/v1/user/oauth2/redirect`,login:`${e}/api/v1/user/signin`,language:`${e}/api/v1/user/language`,redirectUri:`${e}/api/v1/user/oauth2/redirect`,token:`${e}/api/v1/user/oauth2/token`,integration:`${e}/api/v1/user/integrationinfo`,silentSignIn:`${e}/api/v1/user/silentsignin`}),V=({brand:e,stampMode:t=D.DISTANT,stampsFile:i})=>{switch(e){case"hyundai":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="prd.eu-ccapi.hyundai.com:8080",o=`https://${i}`,n="6d477c38-3ca4-4cf3-9557-2a1929a94654",r="1eba27d2-9a5b-4eba-8ec7-97eb6c62fb51";return{brand:"hyundai",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(M(o,n)),basicToken:"Basic NmQ0NzdjMzgtM2NhNC00Y2YzLTk1NTctMmExOTI5YTk0NjU0OktVeTQ5WHhQekxwTHVvSzB4aEJDNzdXNlZYaG10UVI5aVFobUlGampvWTRJcHhzVg==",GCMSenderID:"414998006775",stamp:P({appId:r,brand:"hyundai",mode:e,region:_.EU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t}),brandAuthUrl:({language:e,serviceId:t,userId:i})=>`https://eu-account.hyundai.com/auth/realms/euhyundaiidm/protocol/openid-connect/auth?client_id=64621b96-0f0d-11ec-82a8-0242ac130003&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri=${o}/api/v1/user/integration/redirect/login&ui_locales=${e}&state=${t}:${i}`}})({stampMode:t,stampsFile:i}));case"kia":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="prd.eu-ccapi.kia.com:8080",o=`https://${i}`,n="fdc85c00-0a2f-4c64-bcb4-2cfb1500730a",r="a2b8469b-30a3-4361-8e13-6fceea8fbe74";return{brand:"kia",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(M(o,n)),basicToken:"Basic ZmRjODVjMDAtMGEyZi00YzY0LWJjYjQtMmNmYjE1MDA3MzBhOnNlY3JldA==",GCMSenderID:"345127537656",stamp:P({appId:r,brand:"kia",mode:e,region:_.EU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t}),brandAuthUrl:({language:e,serviceId:t,userId:i})=>`https://eu-account.kia.com/auth/realms/eukiaidm/protocol/openid-connect/auth?client_id=572e0304-5f8d-4b4c-9dd5-41aa84eed160&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri=${o}/api/v1/user/integration/redirect/login&ui_locales=${e}&state=${t}:${i}`}})({stampMode:t,stampsFile:i}));default:throw new Error(`Constructor ${e} is not managed.`)}},x=(e,t)=>({session:`${e}/api/v1/user/oauth2/authorize?response_type=code&state=test&client_id=${t}&redirect_uri=${e}:443/api/v1/user/oauth2/redirect`,login:`${e}/api/v1/user/signin`,language:`${e}/api/v1/user/language`,redirectUri:`${e}:443/api/v1/user/oauth2/redirect`,token:`${e}/api/v1/user/oauth2/token`,integration:`${e}/api/v1/user/integrationinfo`,silentSignIn:`${e}/api/v1/user/silentsignin`}),U=({brand:e})=>{switch(e){case"hyundai":return Object.freeze((()=>{const e="prd.cn-ccapi.hyundai.com",t=`https://${e}`,i="72b3d019-5bc7-443d-a437-08f307cf06e2";return{brand:"hyundai",host:e,baseUrl:t,clientId:i,appId:"ed01581a-380f-48cd-83d4-ed1490c272d0",endpoints:Object.freeze(x(t,i)),basicToken:"Basic NzJiM2QwMTktNWJjNy00NDNkLWE0MzctMDhmMzA3Y2YwNmUyOnNlY3JldA==",GCMSenderID:"414998006775",providerDeviceId:"59af09e554a9442ab8589c9500d04d2e",pushRegId:"1"}})());case"kia":return Object.freeze((()=>{const e="prd.cn-ccapi.kia.com",t=`https://${e}`,i="9d5df92a-06ae-435f-b459-8304f2efcc67";return{brand:"kia",host:e,baseUrl:t,clientId:i,appId:"eea8762c-adfc-4ee4-8d7a-6e2452ddf342",endpoints:Object.freeze(x(t,i)),basicToken:"Basic OWQ1ZGY5MmEtMDZhZS00MzVmLWI0NTktODMwNGYyZWZjYzY3OnRzWGRrVWcwOEF2MlpaelhPZ1d6Snl4VVQ2eWVTbk5OUWtYWFBSZEtXRUFOd2wxcA==",GCMSenderID:"345127537656",providerDeviceId:"32dedba78045415b92db816e805ed47b",pushRegId:"ogc+GB5gom7zDEQjPhb3lP+bjjM=DG2rQ9Zuq0otwOU7n9y08LKjYpo="}})());default:throw new Error(`Constructor ${e} is not managed.`)}},H=(e,t)=>({session:`${e}/api/v1/user/oauth2/authorize?response_type=code&client_id=${t}&redirect_uri=${encodeURIComponent(`${e}/api/v1/user/oauth2/redirect`)}&lang=en`,login:`${e}/api/v1/user/signin`,language:`${e}/api/v1/user/language`,redirectUri:`${e}/api/v1/user/oauth2/redirect`,token:`${e}/api/v1/user/oauth2/token`,integration:`${e}/api/v1/user/integrationinfo`,silentSignIn:`${e}/api/v1/user/silentsignin`}),j=({brand:e,stampMode:t=D.LOCAL,stampsFile:i})=>{switch(e){case"hyundai":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="au-apigw.ccs.hyundai.com.au:8080",o=`https://${i}`,n="855c72df-dfd7-4230-ab03-67cbf902bb1c",r="f9ccfdac-a48d-4c57-bd32-9116963c24ed";return{brand:"hyundai",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(H(o,n)),basicToken:"Basic ODU1YzcyZGYtZGZkNy00MjMwLWFiMDMtNjdjYmY5MDJiYjFjOmU2ZmJ3SE0zMllOYmhRbDBwdmlhUHAzcmY0dDNTNms5MWVjZUEzTUpMZGJkVGhDTw==",stamp:P({appId:r,brand:"hyundai",mode:e,region:_.AU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t})}})({stampMode:t,stampsFile:i}));case"kia":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="au-apigw.ccs.kia.com.au:8082",o=`https://${i}`,n="8acb778a-b918-4a8d-8624-73a0beb64289",r="4ad4dcde-be23-48a8-bc1c-91b94f5c06f8";return{brand:"hyundai",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(H(o,n)),basicToken:"Basic OGFjYjc3OGEtYjkxOC00YThkLTg2MjQtNzNhMGJlYjY0Mjg5OjdTY01NbTZmRVlYZGlFUEN4YVBhUW1nZVlkbFVyZndvaDRBZlhHT3pZSVMyQ3U5VA==",stamp:P({appId:r,brand:"kia",mode:e,region:_.AU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t})}})({stampMode:t,stampsFile:i}));default:throw new Error(`Constructor ${e} is not managed.`)}};var _;!function(e){e.US="US",e.CA="CA",e.EU="EU",e.CN="CN",e.AU="AU"}(_||(_={}));const N=[50,60,70,80,90,100],F={refresh:!1,parsed:!1};class z{constructor(e,t){this.vehicleConfig=e,this.controller=t,this._fullStatus=null,this._status=null,this._location=null,this._odometer=null,this.userConfig={username:void 0,password:void 0,region:_.EU,brand:"hyundai",autoLogin:!0,pin:void 0,vin:void 0,vehicleId:void 0},this.userConfig=t.userConfig}vin(){return this.vehicleConfig.vin}name(){return this.vehicleConfig.name}nickname(){return this.vehicleConfig.nickname}id(){return this.vehicleConfig.id}brandIndicator(){return this.vehicleConfig.brandIndicator}}class B extends z{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=_.US,C.debug(`US Vehicle ${this.vehicleConfig.regId} created`)}getDefaultHeaders(){return{access_token:this.controller.session.accessToken,client_id:this.controller.environment.clientId,Host:this.controller.environment.host,"User-Agent":"okhttp/3.12.0",registrationId:this.vehicleConfig.regId,gen:this.vehicleConfig.generation,username:this.userConfig.username,vin:this.vehicleConfig.vin,"APPCLOUD-VIN":this.vehicleConfig.vin,Language:"0",to:"ISS",encryptFlag:"false",from:"SPA",brandIndicator:this.vehicleConfig.brandIndicator,bluelinkservicepin:this.userConfig.pin,offset:"-5"}}fullStatus(){throw new Error("Method not implemented.")}odometer(){return h(this,void 0,void 0,(function*(){const e=yield this._request(`/ac/v2/enrollment/details/${this.userConfig.username}`,{method:"GET",headers:Object.assign({},this.getDefaultHeaders())});if(200!==e.statusCode)throw"Failed to get odometer reading!";const t=JSON.parse(e.body).enrolledVehicleDetails.find((e=>e.vehicleDetails.vin===this.vin()));return this._odometer={value:t.vehicleDetails.odometer,unit:0},this._odometer}))}location(){return h(this,void 0,void 0,(function*(){const e=yield this._request("/ac/v2/rcs/rfc/findMyCar",{method:"GET",headers:Object.assign({},this.getDefaultHeaders())});if(200!==e.statusCode)throw"Failed to get location!";const t=JSON.parse(e.body);return{latitude:t.coord.lat,longitude:t.coord.lon,altitude:t.coord.alt,speed:{unit:t.speed.unit,value:t.speed.value},heading:t.head}}))}start(e){return h(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},{hvac:!1,duration:10,temperature:70,defrost:!1,heatedFeatures:!1,unit:"F"}),e),i={Ims:0,airCtrl:+t.hvac,airTemp:{unit:1,value:`${t.temperature}`},defrost:t.defrost,heating1:+t.heatedFeatures,igniOnDuration:t.duration,seatHeaterVentInfo:null,username:this.userConfig.username,vin:this.vehicleConfig.vin};return 200===(yield this._request("/ac/v2/rcs/rsc/start",{method:"POST",headers:Object.assign(Object.assign({},this.getDefaultHeaders()),{offset:"-4"}),body:i,json:!0})).statusCode?"Vehicle started!":"Failed to start vehicle"}))}stop(){return h(this,void 0,void 0,(function*(){if(200===(yield this._request("/ac/v2/rcs/rsc/stop",{method:"POST",headers:Object.assign(Object.assign({},this.getDefaultHeaders()),{offset:"-4"})})).statusCode)return"Vehicle stopped";throw"Failed to stop vehicle!"}))}status(e){return h(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b;const C=Object.assign(Object.assign({},F),e),w=yield this._request("/ac/v2/rcs/rvs/vehicleStatus",{method:"GET",headers:Object.assign({REFRESH:C.refresh.toString()},this.getDefaultHeaders())}),{vehicleStatus:k}=JSON.parse(w.body),S={chassis:{hoodOpen:null==k?void 0:k.hoodOpen,trunkOpen:null==k?void 0:k.trunkOpen,locked:null==k?void 0:k.doorLock,openDoors:{frontRight:!!(null===(t=null==k?void 0:k.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==k?void 0:k.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==k?void 0:k.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==k?void 0:k.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==k?void 0:k.tirePressureLamp)||void 0===r?void 0:r.tirePressureWarningLampRearLeft),frontLeft:!!(null===(s=null==k?void 0:k.tirePressureLamp)||void 0===s?void 0:s.tirePressureWarningLampFrontLeft),frontRight:!!(null===(a=null==k?void 0:k.tirePressureLamp)||void 0===a?void 0:a.tirePressureWarningLampFrontRight),rearRight:!!(null===(d=null==k?void 0:k.tirePressureLamp)||void 0===d?void 0:d.tirePressureWarningLampRearRight),all:!!(null===(l=null==k?void 0:k.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==k?void 0:k.airCtrlOn,steeringwheelHeat:!!(null==k?void 0:k.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==k?void 0:k.sideBackWindowHeat),defrost:null==k?void 0:k.defrost,temperatureSetpoint:null===(c=null==k?void 0:k.airTemp)||void 0===c?void 0:c.value,temperatureUnit:null===(h=null==k?void 0:k.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:null==k?void 0:k.engine,accessory:null==k?void 0:k.acc,range:(null===(g=null===(p=null===(v=null===(u=null==k?void 0:k.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.totalAvailableRange)||void 0===g?void 0:g.value)||(null===(f=null==k?void 0:k.dte)||void 0===f?void 0:f.value),charging:null===(m=null==k?void 0:k.evStatus)||void 0===m?void 0:m.batteryCharge,batteryCharge12v:null===(y=null==k?void 0:k.battery)||void 0===y?void 0:y.batSoc,batteryChargeHV:null===(b=null==k?void 0:k.evStatus)||void 0===b?void 0:b.batteryStatus},lastupdate:new Date(null==k?void 0:k.dateTime)};return this._status=C.parsed?S:k,this._status}))}unlock(){return h(this,void 0,void 0,(function*(){const e=new n.URLSearchParams;e.append("userName",this.userConfig.username||""),e.append("vin",this.vehicleConfig.vin);return 200===(yield this._request("/ac/v2/rcs/rdo/on",{method:"POST",headers:Object.assign({},this.getDefaultHeaders()),body:e.toString()})).statusCode?"Unlock successful":"Something went wrong!"}))}lock(){return h(this,void 0,void 0,(function*(){const e=new n.URLSearchParams;e.append("userName",this.userConfig.username||""),e.append("vin",this.vehicleConfig.vin);return 200===(yield this._request("/ac/v2/rcs/rdo/off",{method:"POST",headers:Object.assign({},this.getDefaultHeaders()),body:e.toString()})).statusCode?"Lock successful":"Something went wrong!"}))}startCharge(){return h(this,void 0,void 0,(function*(){if(200===(yield this._request(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{method:"POST"})).statusCode)return C.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}))}stopCharge(){return h(this,void 0,void 0,(function*(){if(200===(yield e(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{method:"POST"})).statusCode)return C.debug(`Send stop charge command to vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}))}_request(t,i){return h(this,void 0,void 0,(function*(){yield this.controller.refreshAccessToken(),i.headers.access_token=this.controller.session.accessToken;const o=yield e(`${this.controller.environment.baseUrl}/${t}`,Object.assign({throwHttpErrors:!1},i));return(null==o?void 0:o.body)&&C.debug(o.body),o}))}}class J{constructor(e){this.userConfig=e,this.session={accessToken:"",refreshToken:"",controlToken:"",deviceId:"",tokenExpiresAt:0}}}class Y extends Error{constructor(e,t){super(e),this.source=t,this.name=Y.ErrorName}}Y.ErrorName="ManagedBluelinkyError";const W=(t,i)=>{var o;return t instanceof e.HTTPError?new Y(`${i?`@${i}: `:""}[${t.statusCode}] ${t.statusMessage} on [${t.method}] ${t.url} - ${JSON.stringify(t.body)}`,t):t instanceof e.ParseError?new Y(`${i?`@${i}: `:""} Parsing error on [${t.method}] ${t.url} - ${JSON.stringify(null===(o=t.response)||void 0===o?void 0:o.body)}`,t):(Error,t)},G=(e,t)=>h(void 0,void 0,void 0,(function*(){const i=[];for(let o=0;o"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}));class Z extends J{constructor(e){super(e),this.vehicles=[],this._environment=(e=>{switch(e){case"hyundai":return Object.freeze((()=>{const e="api.telematics.hyundaiusa.com";return{brand:"hyundai",host:e,baseUrl:`https://${e}`,clientId:"m66129Bb-em93-SPAHYN-bZ91-am4540zp19920",clientSecret:"v558o935-6nne-423i-baa8"}})());case"kia":return Object.freeze((()=>{const e="api.owners.kia.com";return{brand:"kia",host:e,baseUrl:`https://${e}/apigw/v1/`,clientId:"MWAMOBILE",clientSecret:"98er-w34rf-ibf3-3f6h"}})());default:throw new Error(`Constructor ${e} is not managed.`)}})(e.brand),C.debug("US Controller created")}get environment(){return this._environment}refreshAccessToken(){return h(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;try{if(this.session.refreshToken&&t){C.debug("refreshing token");const t=yield e(`${this.environment.baseUrl}/v2/ac/oauth/token/refresh`,{method:"POST",body:{refresh_token:this.session.refreshToken},headers:{"User-Agent":"PostmanRuntime/7.26.10",client_secret:this.environment.clientSecret,client_id:this.environment.clientId},json:!0});return C.debug(t.body),this.session.accessToken=t.body.access_token,this.session.refreshToken=t.body.refresh_token,this.session.tokenExpiresAt=Math.floor(+new Date/1e3+parseInt(t.body.expires_in)),C.debug("Token refreshed"),"Token refreshed"}return C.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh"}catch(e){throw W(e,"AmericanController.refreshAccessToken")}}))}login(){return h(this,void 0,void 0,(function*(){C.debug("Logging in to the API");try{const t=yield e(`${this.environment.baseUrl}/v2/ac/oauth/token`,{method:"POST",body:{username:this.userConfig.username,password:this.userConfig.password},headers:{"User-Agent":"PostmanRuntime/7.26.10",client_id:this.environment.clientId,client_secret:this.environment.clientSecret},json:!0});return C.debug(t.body),200!==t.statusCode?"login bad":(this.session.accessToken=t.body.access_token,this.session.refreshToken=t.body.refresh_token,this.session.tokenExpiresAt=Math.floor(+new Date/1e3+parseInt(t.body.expires_in)),"login good")}catch(e){throw W(e,"AmericanController.login")}}))}logout(){return h(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return h(this,void 0,void 0,(function*(){try{const t=yield e(`${this.environment.baseUrl}/ac/v2/enrollment/details/${this.userConfig.username}`,{method:"GET",headers:{access_token:this.session.accessToken,client_id:this.environment.clientId,Host:this.environment.host,"User-Agent":"okhttp/3.12.0",payloadGenerated:"20200226171938",includeNonConnectedVehicles:"Y"}}),i=JSON.parse(t.body);return void 0===i.enrolledVehicleDetails?(this.vehicles=[],this.vehicles):(this.vehicles=i.enrolledVehicleDetails.map((e=>{const t=e.vehicleDetails,i={nickname:t.nickName,name:t.nickName,vin:t.vin,regDate:t.enrollmentDate,brandIndicator:t.brandIndicator,regId:t.regid,generation:t.modelYear>2016?"2":"1"};return new B(i,this)})),this.vehicles)}catch(e){throw W(e,"AmericanController.getVehicles")}}))}}var K,Q,X;!function(e){e[e.UNPLUGED=0]="UNPLUGED",e[e.FAST=1]="FAST",e[e.PORTABLE=2]="PORTABLE",e[e.STATION=3]="STATION"}(K||(K={})),function(e){e[e.FAST=0]="FAST",e[e.SLOW=1]="SLOW"}(Q||(Q={})),function(e){e[e.CLOSED=0]="CLOSED",e[e.OPEN=1]="OPEN",e[e.VENTILATION=2]="VENTILATION"}(X||(X={}));const ee=(e,t,i)=>{const o=[];for(let n=e;n<=t;n+=i)o.push(n);return o},te={EU:{start:14,end:30,step:.5},CA:{start:16,end:32,step:.5},CN:{start:14,end:30,step:.5},AU:{start:17,end:27,step:.5}},ie=(e,t)=>{const{start:i,end:o,step:n}=te[e],r=ee(i,o,n).indexOf(t);return`${("0x"+r.toString(16).substr(-4).toUpperCase()).split("x")[1].toUpperCase()}H`.padStart(3,"0")},oe=(e,t)=>{const{start:i,end:o,step:n}=te[e];return ee(i,o,n)[parseInt(t,16)]},ne=e=>{const t=parseInt(e.substring(0,4)),i=parseInt(e.substring(4,6));if(e.length<=6)return new Date(t,i-1);const o=parseInt(e.substring(6,8));if(e.length<=8)return new Date(t,i-1,o);const n=parseInt(e.substring(8,10)),r=parseInt(e.substring(10,12)),s=parseInt(e.substring(12,14));return new Date(t,i-1,o,n,r,s)},re=(e,t)=>new Date(e.getTime()+6e4*t);var se,ae;!function(e){e[e.DAY=0]="DAY",e[e.MONTH=1]="MONTH",e[e.ALL=2]="ALL"}(se||(se={})),function(e){e[e.TOTAL=0]="TOTAL",e[e.AVERAGE=1]="AVERAGE",e[e.TODAY=2]="TODAY"}(ae||(ae={}));class de extends z{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=_.EU,this.serverRates={max:-1,current:-1},C.debug(`EU Vehicle ${this.vehicleConfig.id} created`)}start(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/temperature`,{body:{action:"start",hvacType:0,options:{defrost:e.defrost,heating1:e.heatedFeatures?1:0},tempCode:ie(_.EU,e.temperature),unit:e.unit}}));return C.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw W(e,"EuropeVehicle.start")}}))}stop(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/temperature`,{body:{action:"stop",hvacType:0,options:{defrost:!0,heating1:1},tempCode:"10H",unit:"C"}}));return C.info(`Climate stopped for vehicle ${this.vehicleConfig.id}`),t.body}catch(e){throw W(e,"EuropeVehicle.stop")}}))}lock(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"close",deviceId:this.controller.session.deviceId}})).statusCode?(C.debug(`Vehicle ${this.vehicleConfig.id} locked`),"Lock successful"):"Something went wrong!"}catch(e){throw W(e,"EuropeVehicle.lock")}}))}unlock(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"open",deviceId:this.controller.session.deviceId}})).statusCode?(C.debug(`Vehicle ${this.vehicleConfig.id} unlocked`),"Unlock successful"):"Something went wrong!"}catch(e){throw W(e,"EuropeVehicle.unlock")}}))}fullStatus(e){return h(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},F),e),i=yield this.controller.getVehicleHttpService();try{const e=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`)).body.resMsg.vehicleStatusInfo,o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/ccs2/carstatus/latest`));if(null!=o.body.resMsg.state.Vehicle&&(e.ccs2Status=o.body.resMsg),t.refresh){const t=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`));e.vehicleStatus=t.body.resMsg;const o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`));e.vehicleLocation=o.body.resMsg.gpsDetail}return this._fullStatus=e,this._fullStatus}catch(e){throw W(e,"EuropeVehicle.fullStatus")}}))}status(e){return h(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b,C,w,k,S,T,A,O,$,D,I,E,L,P,R,M,V,x,U,H,j,N,z,B,J,Y;const G=Object.assign(Object.assign({},F),e),q=yield this.controller.getVehicleHttpService();try{const e=G.refresh?"":"/latest",F=this.updateRates(yield q.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${e}`)),W=G.refresh?F.body.resMsg:F.body.resMsg.vehicleStatusInfo.vehicleStatus,Z={chassis:{hoodOpen:null==W?void 0:W.hoodOpen,trunkOpen:null==W?void 0:W.trunkOpen,locked:W.doorLock,openDoors:{frontRight:!!(null===(t=null==W?void 0:W.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==W?void 0:W.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==W?void 0:W.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==W?void 0:W.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==W?void 0:W.tirePressureLamp)||void 0===r?void 0:r.tirePressureLampRL),frontLeft:!!(null===(s=null==W?void 0:W.tirePressureLamp)||void 0===s?void 0:s.tirePressureLampFL),frontRight:!!(null===(a=null==W?void 0:W.tirePressureLamp)||void 0===a?void 0:a.tirePressureLampFR),rearRight:!!(null===(d=null==W?void 0:W.tirePressureLamp)||void 0===d?void 0:d.tirePressureLampRR),all:!!(null===(l=null==W?void 0:W.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==W?void 0:W.airCtrlOn,steeringwheelHeat:!!(null==W?void 0:W.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==W?void 0:W.sideBackWindowHeat),defrost:null==W?void 0:W.defrost,temperatureSetpoint:oe(_.EU,null===(c=null==W?void 0:W.airTemp)||void 0===c?void 0:c.value),temperatureUnit:null===(h=null==W?void 0:W.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:W.engine,accessory:null==W?void 0:W.acc,rangeGas:null!==(f=null===(g=null===(p=null===(v=null===(u=null==W?void 0:W.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.gasModeRange)||void 0===g?void 0:g.value)&&void 0!==f?f:null===(m=null==W?void 0:W.dte)||void 0===m?void 0:m.value,range:null===(w=null===(C=null===(b=null===(y=null==W?void 0:W.evStatus)||void 0===y?void 0:y.drvDistance[0])||void 0===b?void 0:b.rangeByFuel)||void 0===C?void 0:C.totalAvailableRange)||void 0===w?void 0:w.value,rangeEV:null===(A=null===(T=null===(S=null===(k=null==W?void 0:W.evStatus)||void 0===k?void 0:k.drvDistance[0])||void 0===S?void 0:S.rangeByFuel)||void 0===T?void 0:T.evModeRange)||void 0===A?void 0:A.value,plugedTo:null!==($=null===(O=null==W?void 0:W.evStatus)||void 0===O?void 0:O.batteryPlugin)&&void 0!==$?$:K.UNPLUGED,charging:null===(D=null==W?void 0:W.evStatus)||void 0===D?void 0:D.batteryCharge,estimatedCurrentChargeDuration:null===(L=null===(E=null===(I=null==W?void 0:W.evStatus)||void 0===I?void 0:I.remainTime2)||void 0===E?void 0:E.atc)||void 0===L?void 0:L.value,estimatedFastChargeDuration:null===(M=null===(R=null===(P=null==W?void 0:W.evStatus)||void 0===P?void 0:P.remainTime2)||void 0===R?void 0:R.etc1)||void 0===M?void 0:M.value,estimatedPortableChargeDuration:null===(U=null===(x=null===(V=null==W?void 0:W.evStatus)||void 0===V?void 0:V.remainTime2)||void 0===x?void 0:x.etc2)||void 0===U?void 0:U.value,estimatedStationChargeDuration:null===(N=null===(j=null===(H=null==W?void 0:W.evStatus)||void 0===H?void 0:H.remainTime2)||void 0===j?void 0:j.etc3)||void 0===N?void 0:N.value,batteryCharge12v:null===(z=null==W?void 0:W.battery)||void 0===z?void 0:z.batSoc,batteryChargeHV:null===(B=null==W?void 0:W.evStatus)||void 0===B?void 0:B.batteryStatus},lastupdate:(null==W?void 0:W.time)?ne(null==W?void 0:W.time):null};return Z.engine.range||(Z.engine.rangeEV||Z.engine.rangeGas)&&(Z.engine.range=(null!==(J=Z.engine.rangeEV)&&void 0!==J?J:0)+(null!==(Y=Z.engine.rangeGas)&&void 0!==Y?Y:0)),this._status=G.parsed?Z:W,this._status}catch(e){throw W(e,"EuropeVehicle.status")}}))}odometer(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`));return this._odometer=t.body.resMsg.vehicleStatusInfo.odometer,this._odometer}catch(e){throw W(e,"EuropeVehicle.odometer")}}))}location(){return h(this,void 0,void 0,(function*(){var e,t,i,o,n,r,s;const a=yield this.controller.getVehicleHttpService();try{const d=this.updateRates(yield a.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`)),l=null!==(t=null===(e=d.body.resMsg)||void 0===e?void 0:e.gpsDetail)&&void 0!==t?t:d.body.resMsg;return this._location={latitude:null===(i=null==l?void 0:l.coord)||void 0===i?void 0:i.lat,longitude:null===(o=null==l?void 0:l.coord)||void 0===o?void 0:o.lon,altitude:null===(n=null==l?void 0:l.coord)||void 0===n?void 0:n.alt,speed:{unit:null===(r=null==l?void 0:l.speed)||void 0===r?void 0:r.unit,value:null===(s=null==l?void 0:l.speed)||void 0===s?void 0:s.value},heading:null==l?void 0:l.head},this._location}catch(e){throw W(e,"EuropeVehicle.location")}}))}startCharge(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"start",deviceId:this.controller.session.deviceId}})).statusCode)return C.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}catch(e){throw W(e,"EuropeVehicle.startCharge")}}))}stopCharge(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"stop",deviceId:this.controller.session.deviceId}})).statusCode)return C.debug(`Send stop charge command to Vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}catch(e){throw W(e,"EuropeVehicle.stopCharge")}}))}monthlyReport(){return h(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){var t,i,o,n,r,s,a,d,l,c,h;const u=yield this.controller.getVehicleHttpService();try{const v=null===(t=this.updateRates(yield u.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:le(e)}})).body.resMsg)||void 0===t?void 0:t.monthlyReport;return v?{start:null===(i=v.ifo)||void 0===i?void 0:i.mvrMonthStart,end:null===(o=v.ifo)||void 0===o?void 0:o.mvrMonthEnd,breakdown:v.breakdown,driving:v.driving?{distance:null===(n=v.driving)||void 0===n?void 0:n.runDistance,startCount:null===(r=v.driving)||void 0===r?void 0:r.engineStartCount,durations:{idle:null===(s=v.driving)||void 0===s?void 0:s.engineIdleTime,drive:null===(a=v.driving)||void 0===a?void 0:a.engineOnTime}}:void 0,vehicleStatus:v.vehicleStatus?{tpms:(null===(d=v.vehicleStatus)||void 0===d?void 0:d.tpmsSupport)?Boolean(null===(l=v.vehicleStatus)||void 0===l?void 0:l.tpmsSupport):void 0,tirePressure:{all:"1"==(null===(h=null===(c=v.vehicleStatus)||void 0===c?void 0:c.tirePressure)||void 0===h?void 0:h.tirePressureLampAll)}}:void 0}:void 0}catch(e){throw W(e,"EuropeVehicle.monthyReports")}}))}tripInfo(){return h(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){const t=yield this.controller.getApiHttpService();try{const i=Boolean(e.day),o=this.updateRates(yield t.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/tripinfo`,{body:{setTripLatest:10,setTripMonth:i?void 0:le(e),setTripDay:i?ce(e):void 0,tripPeriodType:i?1:0}}));if(!i){const e=o.body.resMsg;return{days:Array.isArray(null==e?void 0:e.tripDayList)?null==e?void 0:e.tripDayList.map((e=>({dayRaw:e.tripDayInMonth,date:e.tripDayInMonth?ne(e.tripDayInMonth):void 0,tripsCount:e.tripCntDay}))):[],durations:{drive:null==e?void 0:e.tripDrvTime,idle:null==e?void 0:e.tripIdleTime},distance:null==e?void 0:e.tripDist,speed:{avg:null==e?void 0:e.tripAvgSpeed,max:null==e?void 0:e.tripMaxSpeed}}}{const e=o.body.resMsg.dayTripList;if(e&&Array.isArray(e))return e.map((e=>({dayRaw:e.tripDay,tripsCount:e.dayTripCnt,distance:e.tripDist,durations:{drive:e.tripDrvTime,idle:e.tripIdleTime},speed:{avg:e.tripAvgSpeed,max:e.tripMaxSpeed},trips:Array.isArray(e.tripList)?e.tripList.map((t=>{const i=ne(`${e.tripDay}${t.tripTime}`);return{timeRaw:t.tripTime,start:i,end:re(i,t.tripDrvTime),durations:{drive:t.tripDrvTime,idle:t.tripIdleTime},speed:{avg:t.tripAvgSpeed,max:t.tripMaxSpeed},distance:t.tripDist}})):[]})))}return}catch(e){throw W(e,"EuropeVehicle.history")}}))}driveHistory(){return h(this,arguments,void 0,(function*(e=se.DAY){var t,i;const o=yield this.controller.getApiHttpService();try{const n=yield o.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/drvhistory`,{body:{periodTarget:e}});return{cumulated:null===(t=n.body.resMsg.drivingInfo)||void 0===t?void 0:t.map((e=>({period:e.drivingPeriod,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo}))),history:null===(i=n.body.resMsg.drivingInfoDetail)||void 0===i?void 0:i.map((e=>({period:e.drivingPeriod,rawDate:e.drivingDate,date:e.drivingDate?ne(e.drivingDate):void 0,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo})))}}catch(e){throw W(e,"EuropeVehicle.history")}}))}getChargeTargets(){return h(this,void 0,void 0,(function*(){var e;const t=yield this.controller.getVehicleHttpService();try{const i=null===(e=this.updateRates(yield t.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`)).body.resMsg)||void 0===e?void 0:e.targetSOClist;return i&&Array.isArray(i)?i.map((e=>{var t,i;return{distance:null===(i=null===(t=e.drvDistance)||void 0===t?void 0:t.distanceType)||void 0===i?void 0:i.distanceValue,targetLevel:e.targetSOClevel,type:e.plugType}})):void 0}catch(e){throw W(e,"EuropeVehicle.getChargeTargets")}}))}setChargeTargets(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();if(!N.includes(e.fast)||!N.includes(e.slow))throw new Y(`Charge target values are limited to ${N.join(", ")}`);try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`,{body:{targetSOClist:[{plugType:Q.FAST,targetSOClevel:e.fast},{plugType:Q.SLOW,targetSOClevel:e.slow}]}}))}catch(e){throw W(e,"EuropeVehicle.setChargeTargets")}}))}setNavigation(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/routes`,{body:{deviceID:this.controller.session.deviceId,poiInfoList:e}}))}catch(e){throw W(e,"EuropeVehicle.setNavigation")}}))}updateRates(e){var t,i,o,n,r;return(null===(t=e.headers)||void 0===t?void 0:t["x-ratelimit-limit"])&&(this.serverRates.max=Number(null===(i=e.headers)||void 0===i?void 0:i["x-ratelimit-limit"]),this.serverRates.current=Number(null===(o=e.headers)||void 0===o?void 0:o["x-ratelimit-remaining"]),(null===(n=e.headers)||void 0===n?void 0:n["x-ratelimit-reset"])&&(this.serverRates.reset=new Date(Number(`${null===(r=e.headers)||void 0===r?void 0:r["x-ratelimit-reset"]}000`))),this.serverRates.updatedAt=new Date),e}}function le(e){return`${e.year}${e.month.toString().padStart(2,"0")}`}function ce(e){return e.day?`${le(e)}${e.day.toString().padStart(2,"0")}`:le(e)}function he(t){return h(this,arguments,void 0,(function*(t,i="en",o){const n=null!=o?o:new r.CookieJar;return yield e(t.endpoints.session,{cookieJar:n}),yield e(t.endpoints.language,{method:"POST",body:`{"lang":"${i}"}`,cookieJar:n}),n}))}const ue={"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0 Mobile/15B92 Safari/604.1"},ve=e=>e.catch((e=>"HTTPError"===e.name&&302===e.statusCode?e.response:Promise.reject(e)));class pe{constructor(e,t){this.environment=e,this.language=t}get name(){return"EuropeanBrandAuthStrategy"}login(t,i){return h(this,void 0,void 0,(function*(){const o=yield he(this.environment,this.language,null==i?void 0:i.cookieJar),{body:{userId:r,serviceId:s}}=yield e(this.environment.endpoints.integration,{cookieJar:o,json:!0,headers:ue}),a=this.environment.brandAuthUrl({language:this.language,userId:r,serviceId:s}),d=n.parse(a,!0),{body:l}=yield e(a,{cookieJar:o,headers:ue}),c=/action="([a-z0-9:/\-.?_=&;]*)"/gi.exec(l),h=null==c?void 0:c[1].replace(/&/g,"&");if(!h)throw new Error("@EuropeanBrandAuthStrategy.login: cannot found the auth url from the form.");const u=new n.URLSearchParams;u.append("username",t.username),u.append("password",t.password),u.append("credentialId",""),u.append("rememberMe","on");const{headers:{location:v},body:p}=yield ve(e.post(h,{cookieJar:o,body:u.toString(),headers:Object.assign({"Content-Type":"application/x-www-form-urlencoded"},ue),followRedirect:!1}));if(!v){const e=/(.+)<\/span>/gm.exec(p);if(e)throw new Error(`@EuropeanBrandAuthStrategy.login: Authentication failed with message : ${e[1]}`);throw new Error("@EuropeanBrandAuthStrategy.login: Authentication failed, cannot retrieve error message")}const g=yield e(v,{cookieJar:o,headers:ue});let f=g.url,m=g.body;if(!f)throw new Error(`@EuropeanBrandAuthStrategy.login: after login redirection got stuck : ${m}`);if(f.includes("login-actions/required-action")){const t=/action="([a-z0-9:/\-.?_=&;]*)"/gi.exec(m),i=/name="code" value="(.*)"/gi.exec(m);if(!t)throw new Error("@EuropeanBrandAuthStrategy.login: Cannot find login-actions url.");if(!i)throw new Error("@EuropeanBrandAuthStrategy.login: Cannot find login-actions code.");const r=t[1].startsWith("/")?`${d.protocol}//${d.host}${t[1]}`:t[1],s=new n.URLSearchParams;s.append("code",i[1]),s.append("accept","");const{headers:{location:a},body:l}=yield ve(e.post(r,{cookieJar:o,body:s.toString(),headers:Object.assign({"Content-Type":"application/x-www-form-urlencoded"},ue)}));if(!a){const e=/(.+)<\/span>/gm.exec(l);if(e)throw new Error(`@EuropeanBrandAuthStrategy.login: Authentication action failed with message : ${e[1]}`);throw new Error("@EuropeanBrandAuthStrategy.login: Authentication action failed, cannot retrieve error message")}const c=yield e(a,{cookieJar:o,headers:ue});f=c.url,m=c.body}const{body:y,statusCode:b}=yield e.post(this.environment.endpoints.silentSignIn,{cookieJar:o,body:{intUserId:""},json:!0,headers:Object.assign(Object.assign({},ue),{"ccsp-service-id":this.environment.clientId})});if(!y.redirectUrl)throw new Error(`@EuropeanBrandAuthStrategy.login: silent sign In didn't work, could not retrieve auth code. status: ${b}, body: ${JSON.stringify(y)}`);const{code:C}=n.parse(y.redirectUrl,!0).query;if(!C)throw new Error(`@EuropeanBrandAuthStrategy.login: Cannot find the argument code in ${y.redirectUrl}.`);return{code:C,cookies:o}}))}}class ge{constructor(e,t){this.environment=e,this.language=t}get name(){return"EuropeanLegacyAuthStrategy"}login(t,i){return h(this,void 0,void 0,(function*(){const o=yield he(this.environment,this.language,null==i?void 0:i.cookieJar),{body:r,statusCode:s}=yield e(this.environment.endpoints.login,{method:"POST",json:!0,body:{email:t.username,password:t.password},cookieJar:o});if(!r.redirectUrl)throw new Error(`@EuropeanLegacyAuthStrategy.login: sign In didn't work, could not retrieve auth code. status: ${s}, body: ${JSON.stringify(r)}`);const{code:a}=n.parse(r.redirectUrl,!0).query;if(!a)throw new Error("@EuropeanLegacyAuthStrategy.login: AuthCode was not found, you probably need to migrate your account.");return{code:a,cookies:o}}))}}class fe extends J{constructor(e){var t;if(super(e),this.session={accessToken:void 0,refreshToken:void 0,controlToken:void 0,deviceId:q(),tokenExpiresAt:0,controlTokenExpiresAt:0},this.vehicles=[],this.userConfig.language=null!==(t=e.language)&&void 0!==t?t:"en",!R.includes(this.userConfig.language))throw new Error(`The language code ${this.userConfig.language} is not managed. Only ${R.join(", ")} are.`);this.session.deviceId=q(),this._environment=V(e),this.authStrategies={main:new pe(this._environment,this.userConfig.language),fallback:new ge(this._environment,this.userConfig.language)},C.debug("EU Controller created")}get environment(){return this._environment}refreshAccessToken(){return h(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;if(!this.session.refreshToken)return C.debug("Need refresh token to refresh access token. Use login()"),"Need refresh token to refresh access token. Use login()";if(!t)return C.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh";const i=new n.URLSearchParams;i.append("grant_type","refresh_token"),i.append("redirect_uri","https://www.getpostman.com/oauth2/callback"),i.append("refresh_token",this.session.refreshToken);try{const t=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0"},body:i.toString(),throwHttpErrors:!1});if(200!==t.statusCode)return C.debug(`Refresh token failed: ${t.body}`),`Refresh token failed: ${t.body}`;const o=JSON.parse(t.body);this.session.accessToken="Bearer "+o.access_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+o.expires_in)}catch(e){throw W(e,"EuropeController.refreshAccessToken")}return C.debug("Token refreshed"),"Token refreshed"}))}enterPin(){return h(this,void 0,void 0,(function*(){if(""===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/user/pin`,{method:"PUT",headers:{Authorization:this.session.accessToken,"Content-Type":"application/json"},body:{deviceId:this.session.deviceId,pin:this.userConfig.pin},json:!0});return this.session.controlToken="Bearer "+t.body.controlToken,this.session.controlTokenExpiresAt=Math.floor(Date.now()/1e3+t.body.expiresTime),"PIN entered OK, The pin is valid for 10 minutes"}catch(e){throw W(e,"EuropeController.pin")}}))}login(){return h(this,void 0,void 0,(function*(){try{if(!this.userConfig.password||!this.userConfig.username)throw new Error("@EuropeController.login: username and password must be defined.");let t=null;try{C.debug(`@EuropeController.login: Trying to sign in with ${this.authStrategies.main.name}`),t=yield this.authStrategies.main.login({password:this.userConfig.password,username:this.userConfig.username})}catch(e){C.error(`@EuropeController.login: sign in with ${this.authStrategies.main.name} failed with error ${e.toString()}`),C.debug(`@EuropeController.login: Trying to sign in with ${this.authStrategies.fallback.name}`),t=yield this.authStrategies.fallback.login({password:this.userConfig.password,username:this.userConfig.username})}C.debug("@EuropeController.login: Authenticated properly with user and password");const i=e=>[...Array(e)].map((()=>Math.floor(16*Math.random()).toString(16))).join(""),o=yield e(`${this.environment.baseUrl}/api/v1/spa/notifications/register`,{method:"POST",headers:{"ccsp-service-id":this.environment.clientId,"Content-Type":"application/json;charset=UTF-8",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:{pushRegId:i(64),pushType:"APNS",uuid:this.session.deviceId},json:!0});o&&(this.session.deviceId=o.body.resMsg.deviceId),C.debug("@EuropeController.login: Device registered");const r=new n.URLSearchParams;r.append("grant_type","authorization_code"),r.append("redirect_uri",this.environment.endpoints.redirectUri),r.append("code",t.code);const s=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0",grant_type:"authorization_code","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:r.toString(),cookieJar:t.cookies});if(200!==s.statusCode)throw new Error(`@EuropeController.login: Could not manage to get token: ${s.body}`);if(s){const e=JSON.parse(s.body);this.session.accessToken=`Bearer ${e.access_token}`,this.session.refreshToken=e.refresh_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+e.expires_in)}return C.debug("@EuropeController.login: Session defined properly"),"Login success"}catch(e){throw W(e,"EuropeController.login")}}))}logout(){return h(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return h(this,void 0,void 0,(function*(){if(void 0===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0});this.vehicles=yield G(t.body.resMsg.vehicles,(t=>h(this,void 0,void 0,(function*(){const i=(yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles/${t.vehicleId}/profile`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})).body.resMsg,o={nickname:t.nickname,name:t.vehicleName,regDate:t.regDate,brandIndicator:"H",id:t.vehicleId,vin:i.vinInfo[0].basic.vin,generation:i.vinInfo[0].basic.modelYear};return C.debug(`@EuropeController.getVehicles: Added vehicle ${o.id}`),new de(o,this)}))))}catch(e){throw W(e,"EuropeController.getVehicles")}return this.vehicles}))}checkControlToken(){return h(this,void 0,void 0,(function*(){var e;yield this.refreshAccessToken(),void 0!==(null===(e=this.session)||void 0===e?void 0:e.controlTokenExpiresAt)&&(!this.session.controlToken||Date.now()/1e3>this.session.controlTokenExpiresAt)&&(yield this.enterPin())}))}getVehicleHttpService(){return h(this,void 0,void 0,(function*(){return yield this.checkControlToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Authorization:this.session.controlToken,Stamp:yield this.environment.stamp()}),json:!0})}))}getApiHttpService(){return h(this,void 0,void 0,(function*(){return yield this.refreshAccessToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})}))}get defaultHeaders(){return{Authorization:this.session.accessToken,offset:((new Date).getTimezoneOffset()/60).toFixed(2),"ccsp-device-id":this.session.deviceId,"ccsp-application-id":this.environment.appId,"Content-Type":"application/json"}}}class me extends z{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=_.CA,this.timeOffset=-(new Date).getTimezoneOffset()/60,this._info=null,C.debug(`CA Vehicle ${this.vehicleConfig.id} created`)}fullStatus(){throw new Error("Method not implemented.")}status(e){return h(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m;const y=Object.assign(Object.assign({},F),e);C.debug("Begin status request, polling car",y.refresh);try{let e=null;if(y.useInfo)yield this.setInfo(y.refresh),this._info&&(e=this._info.status);else{const o=y.refresh?this.controller.environment.endpoints.remoteStatus:this.controller.environment.endpoints.status,n=yield this.request(o,{});if(e=null===(t=n.result)||void 0===t?void 0:t.status,null==n?void 0:n.error)throw null===(i=null==n?void 0:n.error)||void 0===i?void 0:i.errorDesc}C.debug(e);let b=null;return e&&(b={chassis:{hoodOpen:null==e?void 0:e.hoodOpen,trunkOpen:null==e?void 0:e.trunkOpen,locked:null==e?void 0:e.doorLock,openDoors:{frontRight:!!(null===(o=null==e?void 0:e.doorOpen)||void 0===o?void 0:o.frontRight),frontLeft:!!(null===(n=null==e?void 0:e.doorOpen)||void 0===n?void 0:n.frontLeft),backLeft:!!(null===(r=null==e?void 0:e.doorOpen)||void 0===r?void 0:r.backLeft),backRight:!!(null===(s=null==e?void 0:e.doorOpen)||void 0===s?void 0:s.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(a=null==e?void 0:e.tirePressureLamp)||void 0===a?void 0:a.tirePressureWarningLampRearLeft),frontLeft:!!(null===(d=null==e?void 0:e.tirePressureLamp)||void 0===d?void 0:d.tirePressureWarningLampFrontLeft),frontRight:!!(null===(l=null==e?void 0:e.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampFrontRight),rearRight:!!(null===(c=null==e?void 0:e.tirePressureLamp)||void 0===c?void 0:c.tirePressureWarningLampRearRight),all:!!(null===(h=null==e?void 0:e.tirePressureLamp)||void 0===h?void 0:h.tirePressureWarningLampAll)}},climate:{active:null==e?void 0:e.airCtrlOn,steeringwheelHeat:!!(null==e?void 0:e.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==e?void 0:e.sideBackWindowHeat),defrost:null==e?void 0:e.defrost,temperatureSetpoint:null===(u=null==e?void 0:e.airTemp)||void 0===u?void 0:u.value,temperatureUnit:null===(v=null==e?void 0:e.airTemp)||void 0===v?void 0:v.unit},engine:{ignition:null==e?void 0:e.engine,accessory:null==e?void 0:e.acc,range:null===(p=null==e?void 0:e.dte)||void 0===p?void 0:p.value,charging:null===(g=null==e?void 0:e.evStatus)||void 0===g?void 0:g.batteryCharge,batteryCharge12v:null===(f=null==e?void 0:e.battery)||void 0===f?void 0:f.batSoc,batteryChargeHV:null===(m=null==e?void 0:e.evStatus)||void 0===m?void 0:m.batteryStatus},lastupdate:ne(null==e?void 0:e.lastStatusDate)}),this._status=y.parsed?b:e,this._status}catch(e){throw e.message}}))}lock(){return h(this,void 0,void 0,(function*(){C.debug("Begin lock request");try{const e=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.lock,{},{pAuth:e}),"Lock successful"}catch(e){throw e.message}}))}unlock(){return h(this,void 0,void 0,(function*(){C.debug("Begin unlock request");try{const e=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.unlock,{},{pAuth:e}),"Unlock successful"}catch(e){throw e.message}}))}start(e){return h(this,void 0,void 0,(function*(){var t,i,o,n,r;C.debug("Begin startClimate request");try{const s={hvacInfo:{airCtrl:null!==(t=e.hvac)&&void 0!==t&&t||null!==(i=e.defrost)&&void 0!==i&&i?1:0,defrost:null!==(o=e.defrost)&&void 0!==o&&o,heating1:e.heatedFeatures?1:0}},a=e.temperature;if(null!=a)s.hvacInfo.airTemp={value:ie(_.CA,a),unit:0,hvacTempType:1};else if(null!==(n=e.hvac)&&void 0!==n&&n||null!==(r=e.defrost)&&void 0!==r&&r)throw"air temperature should be specified";const d=yield this.getPreAuth(),l=yield this.request(this.controller.environment.endpoints.start,s,{pAuth:d});return C.debug(l),l.responseHeader&&0===l.responseHeader.responseCode?"Vehicle started!":"Failed to start vehicle"}catch(e){throw e.message}}))}stop(){return h(this,void 0,void 0,(function*(){C.debug("Begin stop request");try{const e=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.stop,{pAuth:e})}catch(e){throw"error: "+e}}))}lights(){return h(this,arguments,void 0,(function*(e=!1){C.debug("Begin lights request with horn "+e);try{const t=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.hornlight,{horn:e},{pAuth:t})}catch(e){throw"error: "+e}}))}stopCharge(){return h(this,void 0,void 0,(function*(){C.debug("Begin stopCharge");const{stopCharge:e}=this.controller.environment.endpoints;try{const t=yield this.getPreAuth();return yield this.request(e,{pin:this.controller.userConfig.pin,pAuth:t})}catch(e){throw"error: "+e}}))}startCharge(){return h(this,void 0,void 0,(function*(){C.debug("Begin startCharge");const{startCharge:e}=this.controller.environment.endpoints;try{const t=yield this.getPreAuth();return yield this.request(e,{pin:this.controller.userConfig.pin,pAuth:t})}catch(e){throw"error: "+e}}))}setChargeTargets(e){return h(this,void 0,void 0,(function*(){if(C.debug("Begin setChargeTarget"),!N.includes(e.fast)||!N.includes(e.slow))throw new Y(`Charge target values are limited to ${N.join(", ")}`);const{setChargeTarget:t}=this.controller.environment.endpoints;try{const i=yield this.getPreAuth();return yield this.request(t,{pin:this.controller.userConfig.pin,pAuth:i,tsoc:[{plugType:Q.FAST,level:e.fast},{plugType:Q.SLOW,level:e.slow}]})}catch(e){throw"error: "+e}}))}odometer(){return h(this,void 0,void 0,(function*(){try{if(yield this.setInfo(),this._info)return{unit:this._info.vehicle.odometer,value:this._info.vehicle.odometerUnit};throw"error: no info"}catch(e){throw"error: "+e}}))}location(){return h(this,void 0,void 0,(function*(){C.debug("Begin locate request");try{const e=yield this.getPreAuth(),t=yield this.request(this.controller.environment.endpoints.locate,{},{pAuth:e});return this._location=t.result,this._location}catch(e){throw"error: "+e}}))}getPreAuth(){return h(this,void 0,void 0,(function*(){C.info("Begin pre-authentication");try{return(yield this.request(this.controller.environment.endpoints.verifyPin,{})).result.pAuth}catch(e){throw"error: "+e}}))}request(t,i){return h(this,arguments,void 0,(function*(t,i,o={}){C.debug(`[${t}] ${JSON.stringify(o)} ${JSON.stringify(i)}`),yield this.controller.refreshAccessToken();const[n,,]=process.versions.node.split(".").map(Number);if(n>=21){i=Object.assign({pin:this.userConfig.pin},i),process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",C.debug("Node version >= 21, using fetch instead of got");const e={method:"POST",body:JSON.stringify(i),headers:Object.assign({from:this.controller.environment.origin,language:0,offset:this.timeOffset,accessToken:this.controller.session.accessToken,Origin:"https://kiaconnect.ca",Referer:"https://kiaconnect.ca/login","Content-Type":"application/json",vehicleId:this.vehicleConfig.id},o),dispatcher:new a.Agent({connect:{rejectUnauthorized:!1,secureOptions:s.constants.SSL_OP_LEGACY_SERVER_CONNECT}})};try{const i=yield a.fetch(t,e);return yield i.json()}catch(e){return void C.error(e)}}const r={method:"POST",json:!0,throwHttpErrors:!1,headers:Object.assign({from:this.controller.environment.origin,language:1,offset:this.timeOffset,accessToken:this.controller.session.accessToken,vehicleId:this.vehicleConfig.id},o),body:Object.assign({pin:this.userConfig.pin},i)};try{const i=yield e(t,r);return 0!=i.body.responseHeader.responseCode?i.body.responseHeader.responseDesc:i.body}catch(e){throw"error: "+e}}))}setInfo(){return h(this,arguments,void 0,(function*(e=!1){if(null===this._info||e)try{const e=yield this.getPreAuth(),t=yield this.request(this.controller.environment.endpoints.vehicleInfo,{},{pAuth:e});this._info=t.result}catch(e){throw"error: "+e}}))}}class ye extends J{constructor(e){super(e),this.vehicles=[],this.timeOffset=-(new Date).getTimezoneOffset()/60,C.debug("CA Controller created"),this._environment=S(e.brand)}get environment(){return this._environment}refreshAccessToken(){return h(this,void 0,void 0,(function*(){const e=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;return C.debug("shouldRefreshToken: "+e.toString()),this.session.refreshToken&&e?(yield this.login(),C.debug("Token refreshed"),"Token refreshed"):(C.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh")}))}login(){return h(this,void 0,void 0,(function*(){C.info("Begin login request");try{const e=yield this.request(this.environment.endpoints.login,{loginId:this.userConfig.username,password:this.userConfig.password});return C.debug(e.result),this.session.accessToken=e.result.accessToken,this.session.refreshToken=e.result.refreshToken,this.session.tokenExpiresAt=Math.floor(+new Date/1e3+e.result.expireIn),"login good"}catch(e){return"error: "+e}}))}logout(){return h(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return h(this,void 0,void 0,(function*(){C.info("Begin getVehicleList request");try{const e=(yield this.request(this.environment.endpoints.vehicleList,{})).result;return void 0===e.vehicles?(this.vehicles=[],this.vehicles):(e.vehicles.forEach((e=>{const t={nickname:e.nickName,name:e.nickName,vin:e.vin,regDate:e.enrollmentDate,brandIndicator:e.brandIndicator,regId:e.regid,id:e.vehicleId,generation:e.genType};this.vehicles.push(new me(t,this))})),this.vehicles)}catch(e){return C.debug(e),this.vehicles}}))}request(t,i){return h(this,arguments,void 0,(function*(t,i,o={}){C.debug(`[${t}] ${JSON.stringify(o)} ${JSON.stringify(i)}`);const[n,,]=process.versions.node.split(".").map(Number);if(n>=21){process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",C.debug("Node version >= 21, using fetch instead of got");const e={method:"POST",body:JSON.stringify(i),headers:Object.assign({from:this.environment.origin,language:0,offset:this.timeOffset,accessToken:this.session.accessToken,Origin:"https://kiaconnect.ca",Referer:"https://kiaconnect.ca/login","Content-Type":"application/json"},o),dispatcher:new a.Agent({connect:{rejectUnauthorized:!1,secureOptions:s.constants.SSL_OP_LEGACY_SERVER_CONNECT}})};try{const i=yield a.fetch(t,e);return yield i.json()}catch(e){return void C.error(e)}}try{const n=yield e(t,{method:"POST",json:!0,headers:Object.assign({from:this.environment.origin,language:1,offset:this.timeOffset,accessToken:this.session.accessToken},o),body:Object.assign({},i)});if(0!=n.body.responseHeader.responseCode)throw n.body.responseHeader.responseDesc;return n.body}catch(e){throw W(e,"CanadianController")}}))}}var be,Ce;!function(e){e[e.DAY=0]="DAY",e[e.MONTH=1]="MONTH",e[e.ALL=2]="ALL"}(be||(be={})),function(e){e[e.TOTAL=0]="TOTAL",e[e.AVERAGE=1]="AVERAGE",e[e.TODAY=2]="TODAY"}(Ce||(Ce={}));class we extends z{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=_.CN,this.serverRates={max:-1,current:-1},C.debug(`CN Vehicle ${this.vehicleConfig.id} created`)}start(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"start",hvacType:1,options:{defrost:e.defrost,heating1:e.heatedFeatures?1:0},tempCode:ie(_.CN,e.temperature),unit:e.unit}}));return C.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw W(e,"ChinaVehicle.start")}}))}stop(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"stop",hvacType:0,options:{defrost:!0,heating1:1},tempCode:"10H",unit:"C"}}));return C.info(`Climate stopped for vehicle ${this.vehicleConfig.id}`),t.body}catch(e){throw W(e,"ChinaVehicle.stop")}}))}lock(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"close",deviceId:this.controller.session.deviceId}})).statusCode?(C.debug(`Vehicle ${this.vehicleConfig.id} locked`),"Lock successful"):"Something went wrong!"}catch(e){throw W(e,"ChinaVehicle.lock")}}))}unlock(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"open",deviceId:this.controller.session.deviceId}})).statusCode?(C.debug(`Vehicle ${this.vehicleConfig.id} unlocked`),"Unlock successful"):"Something went wrong!"}catch(e){throw W(e,"ChinaVehicle.unlock")}}))}fullStatus(e){return h(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},F),e),i=yield this.controller.getVehicleHttpService();try{const e=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`)).body.resMsg.status;if(t.refresh){const t=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`));e.vehicleStatus=t.body.resMsg.status;const o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`));e.vehicleLocation=o.body.resMsg.coord}return this._fullStatus=e,this._fullStatus}catch(e){throw W(e,"ChinaVehicle.fullStatus")}}))}status(e){return h(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b,C,w,k,S,T,A,O,$,D,I,E,L,P,R,M,V,x,U,H,j,N,z,B,J,Y;const G=Object.assign(Object.assign({},F),e),q=yield this.controller.getVehicleHttpService();try{const e=G.refresh?"":"/latest",F=this.updateRates(yield q.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${e}`)).body.resMsg.status,W={chassis:{hoodOpen:null==F?void 0:F.hoodOpen,trunkOpen:null==F?void 0:F.trunkOpen,locked:F.doorLock,openDoors:{frontRight:!!(null===(t=null==F?void 0:F.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==F?void 0:F.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==F?void 0:F.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==F?void 0:F.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==F?void 0:F.tirePressureLamp)||void 0===r?void 0:r.tirePressureLampRL),frontLeft:!!(null===(s=null==F?void 0:F.tirePressureLamp)||void 0===s?void 0:s.tirePressureLampFL),frontRight:!!(null===(a=null==F?void 0:F.tirePressureLamp)||void 0===a?void 0:a.tirePressureLampFR),rearRight:!!(null===(d=null==F?void 0:F.tirePressureLamp)||void 0===d?void 0:d.tirePressureLampRR),all:!!(null===(l=null==F?void 0:F.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==F?void 0:F.airCtrlOn,steeringwheelHeat:!!(null==F?void 0:F.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==F?void 0:F.sideBackWindowHeat),defrost:null==F?void 0:F.defrost,temperatureSetpoint:oe(_.EU,null===(c=null==F?void 0:F.airTemp)||void 0===c?void 0:c.value),temperatureUnit:null===(h=null==F?void 0:F.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:F.engine,accessory:null==F?void 0:F.acc,rangeGas:null!==(f=null===(g=null===(p=null===(v=null===(u=null==F?void 0:F.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.gasModeRange)||void 0===g?void 0:g.value)&&void 0!==f?f:null===(m=null==F?void 0:F.dte)||void 0===m?void 0:m.value,range:null===(w=null===(C=null===(b=null===(y=null==F?void 0:F.evStatus)||void 0===y?void 0:y.drvDistance[0])||void 0===b?void 0:b.rangeByFuel)||void 0===C?void 0:C.totalAvailableRange)||void 0===w?void 0:w.value,rangeEV:null===(A=null===(T=null===(S=null===(k=null==F?void 0:F.evStatus)||void 0===k?void 0:k.drvDistance[0])||void 0===S?void 0:S.rangeByFuel)||void 0===T?void 0:T.evModeRange)||void 0===A?void 0:A.value,plugedTo:null!==($=null===(O=null==F?void 0:F.evStatus)||void 0===O?void 0:O.batteryPlugin)&&void 0!==$?$:K.UNPLUGED,charging:null===(D=null==F?void 0:F.evStatus)||void 0===D?void 0:D.batteryCharge,estimatedCurrentChargeDuration:null===(L=null===(E=null===(I=null==F?void 0:F.evStatus)||void 0===I?void 0:I.remainTime2)||void 0===E?void 0:E.atc)||void 0===L?void 0:L.value,estimatedFastChargeDuration:null===(M=null===(R=null===(P=null==F?void 0:F.evStatus)||void 0===P?void 0:P.remainTime2)||void 0===R?void 0:R.etc1)||void 0===M?void 0:M.value,estimatedPortableChargeDuration:null===(U=null===(x=null===(V=null==F?void 0:F.evStatus)||void 0===V?void 0:V.remainTime2)||void 0===x?void 0:x.etc2)||void 0===U?void 0:U.value,estimatedStationChargeDuration:null===(N=null===(j=null===(H=null==F?void 0:F.evStatus)||void 0===H?void 0:H.remainTime2)||void 0===j?void 0:j.etc3)||void 0===N?void 0:N.value,batteryCharge12v:null===(z=null==F?void 0:F.battery)||void 0===z?void 0:z.batSoc,batteryChargeHV:null===(B=null==F?void 0:F.evStatus)||void 0===B?void 0:B.batteryStatus},lastupdate:(null==F?void 0:F.time)?ne(null==F?void 0:F.time):null};return W.engine.range||(W.engine.rangeEV||W.engine.rangeGas)&&(W.engine.range=(null!==(J=W.engine.rangeEV)&&void 0!==J?J:0)+(null!==(Y=W.engine.rangeGas)&&void 0!==Y?Y:0)),this._status=G.parsed?W:F,this._status}catch(e){throw W(e,"ChinaVehicle.status")}}))}odometer(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`));return this._odometer=t.body.resMsg.status.odometer,this._odometer}catch(e){throw W(e,"ChinaVehicle.odometer")}}))}location(){return h(this,void 0,void 0,(function*(){var e,t,i,o,n,r,s;const a=yield this.controller.getVehicleHttpService();try{const d=this.updateRates(yield a.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`)),l=null!==(t=null===(e=d.body.resMsg)||void 0===e?void 0:e.gpsDetail)&&void 0!==t?t:d.body.resMsg;return this._location={latitude:null===(i=null==l?void 0:l.coord)||void 0===i?void 0:i.lat,longitude:null===(o=null==l?void 0:l.coord)||void 0===o?void 0:o.lon,altitude:null===(n=null==l?void 0:l.coord)||void 0===n?void 0:n.alt,speed:{unit:null===(r=null==l?void 0:l.speed)||void 0===r?void 0:r.unit,value:null===(s=null==l?void 0:l.speed)||void 0===s?void 0:s.value},heading:null==l?void 0:l.head},this._location}catch(e){throw W(e,"ChinaVehicle.location")}}))}startCharge(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"start",deviceId:this.controller.session.deviceId}})).statusCode)return C.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}catch(e){throw W(e,"ChinaVehicle.startCharge")}}))}stopCharge(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"stop",deviceId:this.controller.session.deviceId}})).statusCode)return C.debug(`Send stop charge command to Vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}catch(e){throw W(e,"ChinaVehicle.stopCharge")}}))}monthlyReport(){return h(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){var t,i,o,n,r,s,a,d,l,c,h;const u=yield this.controller.getVehicleHttpService();try{const v=null===(t=this.updateRates(yield u.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:ke(e)}})).body.resMsg)||void 0===t?void 0:t.monthlyReport;return v?{start:null===(i=v.ifo)||void 0===i?void 0:i.mvrMonthStart,end:null===(o=v.ifo)||void 0===o?void 0:o.mvrMonthEnd,breakdown:v.breakdown,driving:v.driving?{distance:null===(n=v.driving)||void 0===n?void 0:n.runDistance,startCount:null===(r=v.driving)||void 0===r?void 0:r.engineStartCount,durations:{idle:null===(s=v.driving)||void 0===s?void 0:s.engineIdleTime,drive:null===(a=v.driving)||void 0===a?void 0:a.engineOnTime}}:void 0,vehicleStatus:v.vehicleStatus?{tpms:(null===(d=v.vehicleStatus)||void 0===d?void 0:d.tpmsSupport)?Boolean(null===(l=v.vehicleStatus)||void 0===l?void 0:l.tpmsSupport):void 0,tirePressure:{all:"1"==(null===(h=null===(c=v.vehicleStatus)||void 0===c?void 0:c.tirePressure)||void 0===h?void 0:h.tirePressureLampAll)}}:void 0}:void 0}catch(e){throw W(e,"ChinaVehicle.monthyReports")}}))}tripInfo(){return h(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){const t=yield this.controller.getApiHttpService();try{const i=Boolean(e.day),o=this.updateRates(yield t.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/tripinfo`,{body:{setTripLatest:10,setTripMonth:i?void 0:ke(e),setTripDay:i?Se(e):void 0,tripPeriodType:i?1:0}}));if(!i){const e=o.body.resMsg;return{days:Array.isArray(null==e?void 0:e.tripDayList)?null==e?void 0:e.tripDayList.map((e=>({dayRaw:e.tripDayInMonth,date:e.tripDayInMonth?ne(e.tripDayInMonth):void 0,tripsCount:e.tripCntDay}))):[],durations:{drive:null==e?void 0:e.tripDrvTime,idle:null==e?void 0:e.tripIdleTime},distance:null==e?void 0:e.tripDist,speed:{avg:null==e?void 0:e.tripAvgSpeed,max:null==e?void 0:e.tripMaxSpeed}}}{const e=o.body.resMsg.dayTripList;if(e&&Array.isArray(e))return e.map((e=>({dayRaw:e.tripDay,tripsCount:e.dayTripCnt,distance:e.tripDist,durations:{drive:e.tripDrvTime,idle:e.tripIdleTime},speed:{avg:e.tripAvgSpeed,max:e.tripMaxSpeed},trips:Array.isArray(e.tripList)?e.tripList.map((t=>{const i=ne(`${e.tripDay}${t.tripTime}`);return{timeRaw:t.tripTime,start:i,end:re(i,t.tripDrvTime),durations:{drive:t.tripDrvTime,idle:t.tripIdleTime},speed:{avg:t.tripAvgSpeed,max:t.tripMaxSpeed},distance:t.tripDist}})):[]})))}return}catch(e){throw W(e,"ChinaVehicle.history")}}))}driveHistory(){return h(this,arguments,void 0,(function*(e=be.DAY){var t,i;const o=yield this.controller.getApiHttpService();try{const n=yield o.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/drvhistory`,{body:{periodTarget:e}});return{cumulated:null===(t=n.body.resMsg.drivingInfo)||void 0===t?void 0:t.map((e=>({period:e.drivingPeriod,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo}))),history:null===(i=n.body.resMsg.drivingInfoDetail)||void 0===i?void 0:i.map((e=>({period:e.drivingPeriod,rawDate:e.drivingDate,date:e.drivingDate?ne(e.drivingDate):void 0,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo})))}}catch(e){throw W(e,"ChinaVehicle.history")}}))}getChargeTargets(){return h(this,void 0,void 0,(function*(){var e;const t=yield this.controller.getVehicleHttpService();try{const i=null===(e=this.updateRates(yield t.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`)).body.resMsg)||void 0===e?void 0:e.targetSOClist;return i&&Array.isArray(i)?i.map((e=>{var t,i;return{distance:null===(i=null===(t=e.drvDistance)||void 0===t?void 0:t.distanceType)||void 0===i?void 0:i.distanceValue,targetLevel:e.targetSOClevel,type:e.plugType}})):void 0}catch(e){throw W(e,"ChinaVehicle.getChargeTargets")}}))}setChargeTargets(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();if(!N.includes(e.fast)||!N.includes(e.slow))throw new Y(`Charge target values are limited to ${N.join(", ")}`);try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`,{body:{targetSOClist:[{plugType:Q.FAST,targetSOClevel:e.fast},{plugType:Q.SLOW,targetSOClevel:e.slow}]}}))}catch(e){throw W(e,"ChinaVehicle.setChargeTargets")}}))}setNavigation(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/routes`,{body:{deviceID:this.controller.session.deviceId,poiInfoList:e}}))}catch(e){throw W(e,"ChinaVehicle.setNavigation")}}))}updateRates(e){var t,i,o,n,r;return(null===(t=e.headers)||void 0===t?void 0:t["x-ratelimit-limit"])&&(this.serverRates.max=Number(null===(i=e.headers)||void 0===i?void 0:i["x-ratelimit-limit"]),this.serverRates.current=Number(null===(o=e.headers)||void 0===o?void 0:o["x-ratelimit-remaining"]),(null===(n=e.headers)||void 0===n?void 0:n["x-ratelimit-reset"])&&(this.serverRates.reset=new Date(Number(`${null===(r=e.headers)||void 0===r?void 0:r["x-ratelimit-reset"]}000`))),this.serverRates.updatedAt=new Date),e}}function ke(e){return`${e.year}${e.month.toString().padStart(2,"0")}`}function Se(e){return e.day?`${ke(e)}${e.day.toString().padStart(2,"0")}`:ke(e)}class Te{constructor(e){this.environment=e}get name(){return"ChineseLegacyAuthStrategy"}login(t,i){return h(this,void 0,void 0,(function*(){const o=yield function(t,i){return h(this,void 0,void 0,(function*(){const o=null!=i?i:new r.CookieJar;return yield e(t.endpoints.session,{cookieJar:o}),yield e(t.endpoints.language,{method:"POST",body:'{"lang":"zh"}',cookieJar:o}),o}))}(this.environment,null==i?void 0:i.cookieJar),{body:s,statusCode:a}=yield e(this.environment.endpoints.login,{method:"POST",json:!0,body:{email:t.username,password:t.password},cookieJar:o});if(!s.redirectUrl)throw new Error(`@ChineseLegacyAuthStrategy.login: sign In didn't work, could not retrieve auth code. status: ${a}, body: ${JSON.stringify(s)}`);const{code:d}=n.parse(s.redirectUrl,!0).query;if(!d)throw new Error("@ChineseLegacyAuthStrategy.login: AuthCode was not found, you probably need to migrate your account.");return{code:d,cookies:o}}))}}class Ae extends J{constructor(e){super(e),this.session={accessToken:void 0,refreshToken:void 0,controlToken:void 0,deviceId:q(),tokenExpiresAt:0,controlTokenExpiresAt:0},this.vehicles=[],this.session.deviceId=q(),this._environment=U(e),this.authStrategies={main:new Te(this._environment)},C.debug("CN Controller created")}get environment(){return this._environment}refreshAccessToken(){return h(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;if(!this.session.refreshToken)return C.debug("Need refresh token to refresh access token. Use login()"),"Need refresh token to refresh access token. Use login()";if(!t)return C.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh";const i=new n.URLSearchParams;i.append("grant_type","refresh_token"),i.append("redirect_uri","https://www.getpostman.com/oauth2/callback"),i.append("refresh_token",this.session.refreshToken);try{const t=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0"},body:i.toString(),throwHttpErrors:!1});if(200!==t.statusCode)return C.debug(`Refresh token failed: ${t.body}`),`Refresh token failed: ${t.body}`;const o=JSON.parse(t.body);this.session.accessToken="Bearer "+o.access_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+o.expires_in)}catch(e){throw W(e,"ChinaController.refreshAccessToken")}return C.debug("Token refreshed"),"Token refreshed"}))}enterPin(){return h(this,void 0,void 0,(function*(){if(""===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/user/pin?token=`,{method:"PUT",headers:{Authorization:this.session.accessToken,"Content-Type":"application/json"},body:{deviceId:this.session.deviceId,pin:this.userConfig.pin},json:!0});return this.session.controlToken="Bearer "+t.body.controlToken,C.debug(`controlToken is : ${this.session.controlToken}`),this.session.controlTokenExpiresAt=Math.floor(Date.now()/1e3+t.body.expiresTime),"PIN entered OK, The pin is valid for 10 minutes"}catch(e){throw W(e,"ChinaController.pin")}}))}login(){return h(this,void 0,void 0,(function*(){try{if(!this.userConfig.password||!this.userConfig.username)throw new Error("@ChinaController.login: username and password must be defined.");let t=null;try{C.debug(`@ChinaController.login: Trying to sign in with ${this.authStrategies.main.name}`),t=yield this.authStrategies.main.login({password:this.userConfig.password,username:this.userConfig.username})}catch(e){C.error(`@ChinaController.login: sign in with ${this.authStrategies.main.name} failed with error ${e.toString()}`),C.debug(`@ChinaController.login: Trying to sign in with ${this.authStrategies.main.name}`),t=yield this.authStrategies.main.login({password:this.userConfig.password,username:this.userConfig.username})}C.debug("@ChinaController.login: Authenticated properly with user and password");const i=yield e(`${this.environment.baseUrl}/api/v1/spa/notifications/register`,{method:"POST",headers:{"ccsp-service-id":this.environment.clientId,"Content-Type":"application/json;charset=UTF-8",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0","ccsp-application-id":this.environment.appId},body:{pushRegId:this.environment.pushRegId,providerDeviceId:this.environment.providerDeviceId,pushType:"GCM",uuid:q()},json:!0});i&&(this.session.deviceId=i.body.resMsg.deviceId),C.debug("@ChinaController.login: Device registered");const o=new n.URLSearchParams;o.append("grant_type","authorization_code"),o.append("redirect_uri",this.environment.endpoints.redirectUri),o.append("code",t.code);const r=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0",grant_type:"authorization_code"},body:o.toString(),cookieJar:t.cookies});if(200!==r.statusCode)throw new Error(`@ChinaController.login: Could not manage to get token: ${r.body}`);if(r){const e=JSON.parse(r.body);this.session.accessToken=`Bearer ${e.access_token}`,this.session.refreshToken=e.refresh_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+e.expires_in)}return C.debug("@ChinaController.login: Session defined properly"),C.debug(`accessToken is ${this.session.accessToken}\n refreshToken is ${this.session.refreshToken}\n tokenExpiresAt : ${this.session.tokenExpiresAt}`),"Login success"}catch(e){throw W(e,"ChinaController.login")}}))}logout(){return h(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return h(this,void 0,void 0,(function*(){if(void 0===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles`,{method:"GET",headers:Object.assign({},this.defaultHeaders),json:!0});this.vehicles=yield G(t.body.resMsg.vehicles,(t=>h(this,void 0,void 0,(function*(){const i=(yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles/${t.vehicleId}/profile`,{method:"GET",headers:Object.assign({},this.defaultHeaders),json:!0})).body.resMsg,o={nickname:t.nickname,name:t.vehicleName,regDate:t.regDate,brandIndicator:"H",id:t.vehicleId,vin:i.vinInfo[0].basic.vin,generation:i.vinInfo[0].basic.modelYear};return C.debug(`@ChineseController.getVehicles: Added vehicle ${o.id}`),new we(o,this)}))))}catch(e){throw W(e,"EuropeController.getVehicles")}return this.vehicles}))}checkControlToken(){return h(this,void 0,void 0,(function*(){var e;yield this.refreshAccessToken(),void 0!==(null===(e=this.session)||void 0===e?void 0:e.controlTokenExpiresAt)&&(!this.session.controlToken||Date.now()/1e3>this.session.controlTokenExpiresAt)&&(yield this.enterPin())}))}getVehicleHttpService(){return h(this,void 0,void 0,(function*(){return yield this.checkControlToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Authorization:this.session.controlToken,AuthorizationCCSP:this.session.controlToken,"ccsp-device-id":"2e062595-28e0-4bcb-a75a-1b395cde337c"}),json:!0})}))}getApiHttpService(){return h(this,void 0,void 0,(function*(){return yield this.refreshAccessToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign({},this.defaultHeaders),json:!0})}))}get defaultHeaders(){return{Authorization:this.session.accessToken,offset:((new Date).getTimezoneOffset()/60).toFixed(0),"ccsp-device-id":"2e062595-28e0-4bcb-a75a-1b395cde337c","ccsp-application-id":this.environment.appId,"Content-Type":"application/json","User-Agent":"okhttp/4.4.0"}}}class Oe extends z{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=_.AU,this.serverRates={max:-1,current:-1},C.debug(`AU Vehicle ${this.vehicleConfig.id} created`)}start(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"start",hvacType:0,options:{defrost:e.defrost,heating1:e.heatedFeatures?1:0},tempCode:ie(_.AU,e.temperature),unit:e.unit}}));return C.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw W(e,"AustraliaVehicle.start")}}))}stop(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"stop",hvacType:0,options:{defrost:!0,heating1:1},tempCode:"10H",unit:"C"}}));return C.info(`Climate stopped for vehicle ${this.vehicleConfig.id}`),t.body}catch(e){throw W(e,"AustraliaVehicle.stop")}}))}lock(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"close",deviceId:this.controller.session.deviceId}})).statusCode?(C.debug(`Vehicle ${this.vehicleConfig.id} locked`),"Lock successful"):"Something went wrong!"}catch(e){throw W(e,"AustraliaVehicle.lock")}}))}unlock(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"open",deviceId:this.controller.session.deviceId}})).statusCode?(C.debug(`Vehicle ${this.vehicleConfig.id} unlocked`),"Unlock successful"):"Something went wrong!"}catch(e){throw W(e,"AustraliaVehicle.unlock")}}))}setWindows(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/windowcurtain`,{body:e}));return C.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw W(e,"AustraliaVehicle.start")}}))}fullStatus(e){return h(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},F),e),i=yield this.controller.getVehicleHttpService();try{const e=this.updateRates(t.refresh?yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`):yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`)),o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/park`)),n=yield this.odometer();return n?(this._fullStatus={vehicleLocation:o.body.resMsg.gpsDetail,odometer:n,vehicleStatus:e.body.resMsg},this._fullStatus):null}catch(e){throw W(e,"AustraliaVehicle.fullStatus")}}))}status(e){return h(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b,C,w,k,S,T,A,O,$,D,I,E,L,P,R,M,V,x,U,H,j,N,z,B,J,Y;const G=Object.assign(Object.assign({},F),e),q=yield this.controller.getVehicleHttpService();try{const e=G.refresh?"":"/latest",F=this.updateRates(yield q.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${e}`)).body.resMsg,W={chassis:{hoodOpen:null==F?void 0:F.hoodOpen,trunkOpen:null==F?void 0:F.trunkOpen,locked:F.doorLock,openDoors:{frontRight:!!(null===(t=null==F?void 0:F.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==F?void 0:F.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==F?void 0:F.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==F?void 0:F.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==F?void 0:F.tirePressureLamp)||void 0===r?void 0:r.tirePressureLampRL),frontLeft:!!(null===(s=null==F?void 0:F.tirePressureLamp)||void 0===s?void 0:s.tirePressureLampFL),frontRight:!!(null===(a=null==F?void 0:F.tirePressureLamp)||void 0===a?void 0:a.tirePressureLampFR),rearRight:!!(null===(d=null==F?void 0:F.tirePressureLamp)||void 0===d?void 0:d.tirePressureLampRR),all:!!(null===(l=null==F?void 0:F.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==F?void 0:F.airCtrlOn,steeringwheelHeat:!!(null==F?void 0:F.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==F?void 0:F.sideBackWindowHeat),defrost:null==F?void 0:F.defrost,temperatureSetpoint:oe(_.AU,null===(c=null==F?void 0:F.airTemp)||void 0===c?void 0:c.value),temperatureUnit:null===(h=null==F?void 0:F.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:F.engine,accessory:null==F?void 0:F.acc,rangeGas:null!==(f=null===(g=null===(p=null===(v=null===(u=null==F?void 0:F.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.gasModeRange)||void 0===g?void 0:g.value)&&void 0!==f?f:null===(m=null==F?void 0:F.dte)||void 0===m?void 0:m.value,range:null===(w=null===(C=null===(b=null===(y=null==F?void 0:F.evStatus)||void 0===y?void 0:y.drvDistance[0])||void 0===b?void 0:b.rangeByFuel)||void 0===C?void 0:C.totalAvailableRange)||void 0===w?void 0:w.value,rangeEV:null===(A=null===(T=null===(S=null===(k=null==F?void 0:F.evStatus)||void 0===k?void 0:k.drvDistance[0])||void 0===S?void 0:S.rangeByFuel)||void 0===T?void 0:T.evModeRange)||void 0===A?void 0:A.value,plugedTo:null!==($=null===(O=null==F?void 0:F.evStatus)||void 0===O?void 0:O.batteryPlugin)&&void 0!==$?$:K.UNPLUGED,charging:null===(D=null==F?void 0:F.evStatus)||void 0===D?void 0:D.batteryCharge,estimatedCurrentChargeDuration:null===(L=null===(E=null===(I=null==F?void 0:F.evStatus)||void 0===I?void 0:I.remainTime2)||void 0===E?void 0:E.atc)||void 0===L?void 0:L.value,estimatedFastChargeDuration:null===(M=null===(R=null===(P=null==F?void 0:F.evStatus)||void 0===P?void 0:P.remainTime2)||void 0===R?void 0:R.etc1)||void 0===M?void 0:M.value,estimatedPortableChargeDuration:null===(U=null===(x=null===(V=null==F?void 0:F.evStatus)||void 0===V?void 0:V.remainTime2)||void 0===x?void 0:x.etc2)||void 0===U?void 0:U.value,estimatedStationChargeDuration:null===(N=null===(j=null===(H=null==F?void 0:F.evStatus)||void 0===H?void 0:H.remainTime2)||void 0===j?void 0:j.etc3)||void 0===N?void 0:N.value,batteryCharge12v:null===(z=null==F?void 0:F.battery)||void 0===z?void 0:z.batSoc,batteryChargeHV:null===(B=null==F?void 0:F.evStatus)||void 0===B?void 0:B.batteryStatus},lastupdate:(null==F?void 0:F.time)?ne(null==F?void 0:F.time):null};return W.engine.range||(W.engine.rangeEV||W.engine.rangeGas)&&(W.engine.range=(null!==(J=W.engine.rangeEV)&&void 0!==J?J:0)+(null!==(Y=W.engine.rangeGas)&&void 0!==Y?Y:0)),this._status=G.parsed?W:F,this._status}catch(e){throw W(e,"AustraliaVehicle.status")}}))}odometer(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:$e({year:(new Date).getFullYear(),month:(new Date).getMonth()+1})}}));return this._odometer={unit:0,value:t.body.resMsg.odometer},this._odometer}catch(e){throw W(e,"AustraliaVehicle.odometer")}}))}location(){return h(this,void 0,void 0,(function*(){var e,t,i,o,n,r;const s=yield this.controller.getVehicleHttpService();try{const a=null===(e=this.updateRates(yield s.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/park`)).body.resMsg)||void 0===e?void 0:e.gpsDetail;return this._location={latitude:null===(t=null==a?void 0:a.coord)||void 0===t?void 0:t.lat,longitude:null===(i=null==a?void 0:a.coord)||void 0===i?void 0:i.lon,altitude:null===(o=null==a?void 0:a.coord)||void 0===o?void 0:o.alt,speed:{unit:null===(n=null==a?void 0:a.speed)||void 0===n?void 0:n.unit,value:null===(r=null==a?void 0:a.speed)||void 0===r?void 0:r.value},heading:null==a?void 0:a.head},this._location}catch(e){throw W(e,"AustraliaVehicle.location")}}))}startCharge(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"start",deviceId:this.controller.session.deviceId}})).statusCode)return C.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}catch(e){throw W(e,"AustraliaVehicle.startCharge")}}))}stopCharge(){return h(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"stop",deviceId:this.controller.session.deviceId}})).statusCode)return C.debug(`Send stop charge command to Vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}catch(e){throw W(e,"AustraliaVehicle.stopCharge")}}))}monthlyReport(){return h(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){var t,i,o,n,r,s,a,d,l,c,h;const u=yield this.controller.getVehicleHttpService();try{const v=null===(t=this.updateRates(yield u.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:$e(e)}})).body.resMsg)||void 0===t?void 0:t.monthlyReport;return v?{start:null===(i=v.ifo)||void 0===i?void 0:i.mvrMonthStart,end:null===(o=v.ifo)||void 0===o?void 0:o.mvrMonthEnd,breakdown:v.breakdown,driving:v.driving?{distance:null===(n=v.driving)||void 0===n?void 0:n.runDistance,startCount:null===(r=v.driving)||void 0===r?void 0:r.engineStartCount,durations:{idle:null===(s=v.driving)||void 0===s?void 0:s.engineIdleTime,drive:null===(a=v.driving)||void 0===a?void 0:a.engineOnTime}}:void 0,vehicleStatus:v.vehicleStatus?{tpms:(null===(d=v.vehicleStatus)||void 0===d?void 0:d.tpmsSupport)?Boolean(null===(l=v.vehicleStatus)||void 0===l?void 0:l.tpmsSupport):void 0,tirePressure:{all:"1"==(null===(h=null===(c=v.vehicleStatus)||void 0===c?void 0:c.tirePressure)||void 0===h?void 0:h.tirePressureLampAll)}}:void 0}:void 0}catch(e){throw W(e,"AustraliaVehicle.monthyReports")}}))}tripInfo(){return h(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){const t=yield this.controller.getApiHttpService();try{const i=Boolean(e.day),o=this.updateRates(yield t.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/tripinfo`,{body:{setTripLatest:10,setTripMonth:i?void 0:$e(e),setTripDay:i?De(e):void 0,tripPeriodType:i?1:0}}));if(!i){const e=o.body.resMsg;return{days:Array.isArray(null==e?void 0:e.tripDayList)?null==e?void 0:e.tripDayList.map((e=>({dayRaw:e.tripDayInMonth,date:e.tripDayInMonth?ne(e.tripDayInMonth):void 0,tripsCount:e.tripCntDay}))):[],durations:{drive:null==e?void 0:e.tripDrvTime,idle:null==e?void 0:e.tripIdleTime},distance:null==e?void 0:e.tripDist,speed:{avg:null==e?void 0:e.tripAvgSpeed,max:null==e?void 0:e.tripMaxSpeed}}}{const e=o.body.resMsg.dayTripList;if(e&&Array.isArray(e))return e.map((e=>({dayRaw:e.tripDay,tripsCount:e.dayTripCnt,distance:e.tripDist,durations:{drive:e.tripDrvTime,idle:e.tripIdleTime},speed:{avg:e.tripAvgSpeed,max:e.tripMaxSpeed},trips:Array.isArray(e.tripList)?e.tripList.map((t=>{const i=ne(`${e.tripDay}${t.tripTime}`);return{timeRaw:t.tripTime,start:i,end:re(i,t.tripDrvTime),durations:{drive:t.tripDrvTime,idle:t.tripIdleTime},speed:{avg:t.tripAvgSpeed,max:t.tripMaxSpeed},distance:t.tripDist}})):[]})))}return}catch(e){throw W(e,"AustraliaVehicle.history")}}))}driveHistory(){return h(this,arguments,void 0,(function*(e=se.DAY){var t,i;const o=yield this.controller.getApiHttpService();try{const n=yield o.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/drvhistory`,{body:{periodTarget:e}});return{cumulated:null===(t=n.body.resMsg.drivingInfo)||void 0===t?void 0:t.map((e=>({period:e.drivingPeriod,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo}))),history:null===(i=n.body.resMsg.drivingInfoDetail)||void 0===i?void 0:i.map((e=>({period:e.drivingPeriod,rawDate:e.drivingDate,date:e.drivingDate?ne(e.drivingDate):void 0,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo})))}}catch(e){throw W(e,"AustraliaVehicle.history")}}))}getChargeTargets(){return h(this,void 0,void 0,(function*(){var e;const t=yield this.controller.getVehicleHttpService();try{const i=null===(e=this.updateRates(yield t.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`)).body.resMsg)||void 0===e?void 0:e.targetSOClist;return i&&Array.isArray(i)?i.map((e=>{var t,i;return{distance:null===(i=null===(t=e.drvDistance)||void 0===t?void 0:t.distanceType)||void 0===i?void 0:i.distanceValue,targetLevel:e.targetSOClevel,type:e.plugType}})):void 0}catch(e){throw W(e,"AustraliaVehicle.getChargeTargets")}}))}setChargeTargets(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();if(!N.includes(e.fast)||!N.includes(e.slow))throw new Y(`Charge target values are limited to ${N.join(", ")}`);try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`,{body:{targetSOClist:[{plugType:Q.FAST,targetSOClevel:e.fast},{plugType:Q.SLOW,targetSOClevel:e.slow}]}}))}catch(e){throw W(e,"AustraliaVehicle.setChargeTargets")}}))}setNavigation(e){return h(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/routes`,{body:{deviceID:this.controller.session.deviceId,poiInfoList:e}}))}catch(e){throw W(e,"AustraliaVehicle.setNavigation")}}))}updateRates(e){var t,i,o,n,r;return(null===(t=e.headers)||void 0===t?void 0:t["x-ratelimit-limit"])&&(this.serverRates.max=Number(null===(i=e.headers)||void 0===i?void 0:i["x-ratelimit-limit"]),this.serverRates.current=Number(null===(o=e.headers)||void 0===o?void 0:o["x-ratelimit-remaining"]),(null===(n=e.headers)||void 0===n?void 0:n["x-ratelimit-reset"])&&(this.serverRates.reset=new Date(Number(`${null===(r=e.headers)||void 0===r?void 0:r["x-ratelimit-reset"]}000`))),this.serverRates.updatedAt=new Date),e}}function $e(e){return`${e.year}${e.month.toString().padStart(2,"0")}`}function De(e){return e.day?`${$e(e)}${e.day.toString().padStart(2,"0")}`:$e(e)}class Ie{constructor(e){this.environment=e}get name(){return"AustraliaAuthStrategy"}login(t,i){return h(this,void 0,void 0,(function*(){var o;const s=null!==(o=null==i?void 0:i.cookieJar)&&void 0!==o?o:new r.CookieJar;yield e(this.environment.endpoints.session,{cookieJar:s});const{body:a,statusCode:d}=yield e(this.environment.endpoints.login,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify({email:t.username,password:t.password,mobileNum:""}),cookieJar:s}),l=JSON.parse(a);if(!l.redirectUrl)throw new Error(`@AustraliaAuthStrategy.login: sign In didn't work, could not retrieve auth code. status: ${d}, body: ${JSON.stringify(l)}`);const{code:c}=n.parse(l.redirectUrl,!0).query;if(!c)throw new Error("@AustraliaAuthStrategy.login: AuthCode was not found, you probably need to migrate your account.");return{code:c,cookies:s}}))}}class Ee extends J{constructor(e){super(e),this.session={accessToken:void 0,refreshToken:void 0,controlToken:void 0,deviceId:q(),tokenExpiresAt:0,controlTokenExpiresAt:0},this.vehicles=[],this.session.deviceId=q(),this._environment=j(e),this.authStrategy=new Ie(this._environment),C.debug("AU Controller created")}get environment(){return this._environment}refreshAccessToken(){return h(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;if(!this.session.refreshToken)return C.debug("Need refresh token to refresh access token. Use login()"),"Need refresh token to refresh access token. Use login()";if(!t)return C.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh";const i=new n.URLSearchParams;i.append("grant_type","refresh_token"),i.append("redirect_uri","https://www.getpostman.com/oauth2/callback"),i.append("refresh_token",this.session.refreshToken);try{const t=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0"},body:i.toString(),throwHttpErrors:!1});if(200!==t.statusCode)return C.debug(`Refresh token failed: ${t.body}`),`Refresh token failed: ${t.body}`;const o=JSON.parse(t.body);this.session.accessToken="Bearer "+o.access_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+o.expires_in)}catch(e){throw W(e,"AustraliaController.refreshAccessToken")}return C.debug("Token refreshed"),"Token refreshed"}))}enterPin(){return h(this,void 0,void 0,(function*(){if(""===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/user/pin`,{method:"PUT",headers:{Authorization:this.session.accessToken,"Content-Type":"application/json"},body:{deviceId:this.session.deviceId,pin:this.userConfig.pin},json:!0});return this.session.controlToken="Bearer "+t.body.controlToken,this.session.controlTokenExpiresAt=Math.floor(Date.now()/1e3+t.body.expiresTime),"PIN entered OK, The pin is valid for 10 minutes"}catch(e){throw W(e,"AustraliaController.pin")}}))}login(){return h(this,void 0,void 0,(function*(){try{if(!this.userConfig.password||!this.userConfig.username)throw new Error("@AustraliaController.login: username and password must be defined.");let t=null;try{C.debug(`@AustraliaController.login: Trying to sign in with ${this.authStrategy.name}`),t=yield this.authStrategy.login({password:this.userConfig.password,username:this.userConfig.username})}catch(e){throw new Error(`@AustraliaController.login: sign in with ${this.authStrategy.name} failed with error ${e.toString()}`)}C.debug("@AustraliaController.login: Authenticated properly with user and password");const i=e=>[...Array(e)].map((()=>Math.floor(16*Math.random()).toString(16))).join(""),o=yield e(`${this.environment.baseUrl}/api/v1/spa/notifications/register`,{method:"POST",headers:{"ccsp-service-id":this.environment.clientId,"Content-Type":"application/json;charset=UTF-8",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:{pushRegId:i(64),pushType:"GCM",uuid:this.session.deviceId},json:!0});o&&(this.session.deviceId=o.body.resMsg.deviceId),C.debug("@AustraliaController.login: Device registered");const r=new n.URLSearchParams;r.append("grant_type","authorization_code"),r.append("redirect_uri",this.environment.endpoints.redirectUri),r.append("code",t.code);const s=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0",grant_type:"authorization_code","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:r.toString(),cookieJar:t.cookies});if(200!==s.statusCode)throw new Error(`@AustraliaController.login: Could not manage to get token: ${s.body}`);if(s){const e=JSON.parse(s.body);this.session.accessToken=`Bearer ${e.access_token}`,this.session.refreshToken=e.refresh_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+e.expires_in)}return C.debug("@AustraliaController.login: Session defined properly"),"Login success"}catch(e){throw W(e,"AustraliaController.login")}}))}logout(){return h(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return h(this,void 0,void 0,(function*(){if(void 0===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0});this.vehicles=yield G(t.body.resMsg.vehicles,(t=>h(this,void 0,void 0,(function*(){const i=(yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles/${t.vehicleId}/profile`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})).body.resMsg,o={nickname:t.nickname,name:t.vehicleName,regDate:t.regDate,brandIndicator:"H",id:t.vehicleId,vin:i.vinInfo[0].basic.vin,generation:i.vinInfo[0].basic.modelYear};return C.debug(`@AustraliaController.getVehicles: Added vehicle ${o.id}`),new Oe(o,this)}))))}catch(e){throw W(e,"AustraliaController.getVehicles")}return this.vehicles}))}checkControlToken(){return h(this,void 0,void 0,(function*(){var e;yield this.refreshAccessToken(),void 0!==(null===(e=this.session)||void 0===e?void 0:e.controlTokenExpiresAt)&&(!this.session.controlToken||Date.now()/1e3>this.session.controlTokenExpiresAt)&&(yield this.enterPin())}))}getVehicleHttpService(){return h(this,void 0,void 0,(function*(){return yield this.checkControlToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Authorization:this.session.controlToken,Stamp:yield this.environment.stamp()}),json:!0})}))}getApiHttpService(){return h(this,void 0,void 0,(function*(){return yield this.refreshAccessToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})}))}get defaultHeaders(){return{Authorization:this.session.accessToken,offset:((new Date).getTimezoneOffset()/60).toFixed(2),"ccsp-device-id":this.session.deviceId,"ccsp-application-id":this.environment.appId,"Content-Type":"application/json"}}}const Le={username:"",password:"",region:_.US,brand:"hyundai",autoLogin:!0,pin:"1234",vin:"",vehicleId:void 0};class Pe extends d.EventEmitter{constructor(e){switch(super(),this.vehicles=[],this.config=Object.assign(Object.assign({},Le),e),e.region){case _.EU:this.controller=new fe(this.config);break;case _.US:this.controller=new Z(this.config);break;case _.CA:this.controller=new ye(this.config);break;case _.CN:this.controller=new Ae(this.config);break;case _.AU:this.controller=new Ee(this.config);break;default:throw new Error("Your region is not supported yet.")}void 0===e.autoLogin&&(this.config.autoLogin=!0),this.onInit()}on(e,t){return super.on(e,t)}onInit(){this.config.autoLogin&&(C.debug("Bluelinky is logging in automatically, to disable use autoLogin: false"),this.login())}login(){return h(this,void 0,void 0,(function*(){try{const e=yield this.controller.login();return this.vehicles=yield this.getVehicles(),C.debug(`Found ${this.vehicles.length} on the account`),this.emit("ready",this.vehicles),e}catch(e){return this.emit("error",e),e.message}}))}getVehicles(){return h(this,void 0,void 0,(function*(){return(yield this.controller.getVehicles())||[]}))}getVehicle(e){try{const t=this.vehicles.find((t=>t.vin().toLowerCase()===e.toLowerCase()));if(!t&&this.vehicles.length>0)throw new Error(`Could not find vehicle with id: ${e}`);return t}catch(t){throw new Error(`Vehicle not found: ${e}!`)}}refreshAccessToken(){return h(this,void 0,void 0,(function*(){return this.controller.refreshAccessToken()}))}logout(){return h(this,void 0,void 0,(function*(){return this.controller.logout()}))}getSession(){return this.controller.session}get cachedVehicles(){var e;return null!==(e=this.vehicles)&&void 0!==e?e:[]}}exports.BlueLinky=Pe,exports.default=Pe;
diff --git a/dist/index.d.ts b/dist/index.d.ts
new file mode 100644
index 0000000..0d92772
--- /dev/null
+++ b/dist/index.d.ts
@@ -0,0 +1,38 @@
+///
+import { AmericanBlueLinkyConfig } from './controllers/american.controller';
+import { EuropeBlueLinkyConfig } from './controllers/european.controller';
+import { CanadianBlueLinkyConfig } from './controllers/canadian.controller';
+import { ChineseBlueLinkConfig } from './controllers/chinese.controller';
+import { EventEmitter } from 'events';
+import { Session } from './interfaces/common.interfaces';
+import { REGIONS } from './constants';
+import AmericanVehicle from './vehicles/american.vehicle';
+import EuropeanVehicle from './vehicles/european.vehicle';
+import CanadianVehicle from './vehicles/canadian.vehicle';
+import ChineseVehicle from './vehicles/chinese.vehicle';
+import { Vehicle } from './vehicles/vehicle';
+import { AustraliaBlueLinkyConfig } from './controllers/australia.controller';
+import AustraliaVehicle from './vehicles/australia.vehicle';
+type BluelinkyConfigRegions = AmericanBlueLinkyConfig | CanadianBlueLinkyConfig | EuropeBlueLinkyConfig | ChineseBlueLinkConfig | AustraliaBlueLinkyConfig;
+export declare class BlueLinky extends EventEmitter {
+ private controller;
+ private vehicles;
+ private config;
+ constructor(config: T);
+ on(event: 'ready', fnc: (vehicles: VEHICLE_TYPE[]) => void): this;
+ on(event: 'error', fnc: (error: any) => void): this;
+ private onInit;
+ login(): Promise;
+ getVehicles(): Promise;
+ /**
+ * Allows you to access a vehicle in your account by VIN
+ * @param input - The VIN for the vehicle
+ * @returns Vehicle
+ */
+ getVehicle(input: string): VEHICLE_TYPE | undefined;
+ refreshAccessToken(): Promise;
+ logout(): Promise;
+ getSession(): Session | null;
+ get cachedVehicles(): VEHICLE_TYPE[];
+}
+export default BlueLinky;
diff --git a/dist/index.esm.js b/dist/index.esm.js
new file mode 100644
index 0000000..34b688b
--- /dev/null
+++ b/dist/index.esm.js
@@ -0,0 +1,2 @@
+/* @preserve bluelinky / MIT License / https://github.com/Hacksore/bluelinky */
+import e,{HTTPError as t,ParseError as i}from"got";import*as o from"winston";import{readFile as n}from"fs";import{promisify as r}from"util";import s,{URLSearchParams as a}from"url";import{CookieJar as d}from"tough-cookie";import l from"node:crypto";import{Agent as c,fetch as h}from"undici";import{EventEmitter as u}from"events";function v(e,t,i,o){return new(i||(i=Promise))((function(n,r){function s(e){try{d(o.next(e))}catch(e){r(e)}}function a(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const p=process.env.LOG_LEVEL||"info",{colorize:g,json:f,combine:m,timestamp:y,printf:b}=o.format,C=b((({level:e,message:t,timestamp:i})=>(["array","object"].includes(typeof t)&&(t=JSON.stringify(t,null,2)),`[${i}] ${e}: ${t}`))),w=m(y({format:"YYYY-MM-DD HH:mm:ss"}),g(),f(),C),k=o.createLogger({format:w,level:p,transports:[new o.transports.Console({})]}),T=e=>({login:`${e}/tods/api/lgn`,logout:`${e}/tods/api/lgout`,vehicleList:`${e}/tods/api/vhcllst`,vehicleInfo:`${e}/tods/api/sltvhcl`,status:`${e}/tods/api/lstvhclsts`,remoteStatus:`${e}/tods/api/rltmvhclsts`,lock:`${e}/tods/api/drlck`,unlock:`${e}/tods/api/drulck`,start:`${e}/tods/api/evc/rfon`,stop:`${e}/tods/api/evc/rfoff`,startCharge:`${e}/tods/api/evc/rcstrt`,stopCharge:`${e}/tods/api/evc/rcstp`,setChargeTarget:`${e}/tods/api/evc/setsoc`,locate:`${e}/tods/api/fndmcr`,hornlight:`${e}/tods/api/hornlight`,verifyAccountToken:`${e}/tods/api/vrfyacctkn`,verifyPin:`${e}/tods/api/vrfypin`,verifyToken:`${e}/tods/api/vrfytnc`}),S=e=>{const t=`https://${e}`;return{host:e,baseUrl:t,origin:"SPA",endpoints:Object.freeze(T(t))}},A=e=>{switch(e){case"hyundai":return Object.freeze(Object.assign({brand:"hyundai"},S("mybluelink.ca")));case"kia":return Object.freeze(Object.assign({brand:"hyundai"},S("kiaconnect.ca")));default:throw new Error(`Constructor ${e} is not managed.`)}},O=Buffer.from("IDbMgWBXgic4MAyMgf5PFFRAdGX5O3IyC3uvN3scCs0gDpTFDuyvBorlAH9JMM2/hys=","base64"),$=Buffer.from("V60WkEmyRQaAfrBF1623/7QL62MjLVbCHdItGzQ1g5T/hkmKmMVTaMHv4cKGzgD3kfc=","base64"),D=Buffer.from("wLTVxwidmH8CfJYBWSnHD6E0huk0ozdiuygB4hLkM5XCgzAL1Dk5sE36d/bx5PFMQeU=","base64"),I=Buffer.from("RFtoRq/vDXJmRndoZaZQyfOot7OrIqGVFj96iY2WL3yyH5Z/pUvlUhqmCxD2t+D65SQ=","base64");var E;!function(e){e.LOCAL="LOCAL",e.DISTANT="DISTANT"}(E||(E={}));const L=new Map,M=(t,i,o)=>()=>v(void 0,void 0,void 0,(function*(){var s;const{stamps:a,generated:d,frequency:l}=null!==(s=L.get(t))&&void 0!==s?s:yield((t,i,...o)=>v(void 0,[t,i,...o],void 0,(function*(t,i,o=`${i}${t}.v2.json`){if(o.startsWith("file://")){const[,e]=o.split("file://"),t=yield r(n)(e);return JSON.parse(t.toString("utf-8"))}const{body:s}=yield e(o,{json:!0});return L.set(t,s),s})))(t,i,o),c=new Date(d),h=Date.now()-c.getTime(),u=Math.floor(h/l);return u/(a.length-1)>=.9&&L.delete(t),a[Math.min(u,a.length-1)]})),P=(e,t,i)=>{const o=((e,t)=>{switch(t){case F.AU:return"kia"===e?O:$;case F.EU:return"kia"===e?D:I;default:throw new Error("Local stamp generation is only supported in Australia and Europe")}})(t,i);return()=>v(void 0,void 0,void 0,(function*(){const t=Buffer.from(`${e}:${Date.now()}`,"utf-8");return Promise.resolve(((e,t)=>{if(e.length!==t.length)throw new Error(`XOR Buffers are not the same size ${e.length} vs ${t.length}`);const i=Buffer.alloc(e.length);for(let o=0;o{switch(i){case E.LOCAL:return P(e,t,o);case E.DISTANT:default:return M(`${t}-${e}`,n,r)}},V=["cs","da","nl","en","fi","fr","de","it","pl","hu","no","sk","es","sv"],x=(e,t)=>({session:`${e}/api/v1/user/oauth2/authorize?response_type=code&state=test&client_id=${t}&redirect_uri=${e}/api/v1/user/oauth2/redirect`,login:`${e}/api/v1/user/signin`,language:`${e}/api/v1/user/language`,redirectUri:`${e}/api/v1/user/oauth2/redirect`,token:`${e}/api/v1/user/oauth2/token`,integration:`${e}/api/v1/user/integrationinfo`,silentSignIn:`${e}/api/v1/user/silentsignin`}),H=({brand:e,stampMode:t=E.DISTANT,stampsFile:i})=>{switch(e){case"hyundai":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="prd.eu-ccapi.hyundai.com:8080",o=`https://${i}`,n="6d477c38-3ca4-4cf3-9557-2a1929a94654",r="1eba27d2-9a5b-4eba-8ec7-97eb6c62fb51";return{brand:"hyundai",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(x(o,n)),basicToken:"Basic NmQ0NzdjMzgtM2NhNC00Y2YzLTk1NTctMmExOTI5YTk0NjU0OktVeTQ5WHhQekxwTHVvSzB4aEJDNzdXNlZYaG10UVI5aVFobUlGampvWTRJcHhzVg==",GCMSenderID:"414998006775",stamp:R({appId:r,brand:"hyundai",mode:e,region:F.EU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t}),brandAuthUrl:({language:e,serviceId:t,userId:i})=>`https://eu-account.hyundai.com/auth/realms/euhyundaiidm/protocol/openid-connect/auth?client_id=64621b96-0f0d-11ec-82a8-0242ac130003&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri=${o}/api/v1/user/integration/redirect/login&ui_locales=${e}&state=${t}:${i}`}})({stampMode:t,stampsFile:i}));case"kia":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="prd.eu-ccapi.kia.com:8080",o=`https://${i}`,n="fdc85c00-0a2f-4c64-bcb4-2cfb1500730a",r="a2b8469b-30a3-4361-8e13-6fceea8fbe74";return{brand:"kia",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(x(o,n)),basicToken:"Basic ZmRjODVjMDAtMGEyZi00YzY0LWJjYjQtMmNmYjE1MDA3MzBhOnNlY3JldA==",GCMSenderID:"345127537656",stamp:R({appId:r,brand:"kia",mode:e,region:F.EU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t}),brandAuthUrl:({language:e,serviceId:t,userId:i})=>`https://eu-account.kia.com/auth/realms/eukiaidm/protocol/openid-connect/auth?client_id=572e0304-5f8d-4b4c-9dd5-41aa84eed160&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri=${o}/api/v1/user/integration/redirect/login&ui_locales=${e}&state=${t}:${i}`}})({stampMode:t,stampsFile:i}));default:throw new Error(`Constructor ${e} is not managed.`)}},U=(e,t)=>({session:`${e}/api/v1/user/oauth2/authorize?response_type=code&state=test&client_id=${t}&redirect_uri=${e}:443/api/v1/user/oauth2/redirect`,login:`${e}/api/v1/user/signin`,language:`${e}/api/v1/user/language`,redirectUri:`${e}:443/api/v1/user/oauth2/redirect`,token:`${e}/api/v1/user/oauth2/token`,integration:`${e}/api/v1/user/integrationinfo`,silentSignIn:`${e}/api/v1/user/silentsignin`}),_=({brand:e})=>{switch(e){case"hyundai":return Object.freeze((()=>{const e="prd.cn-ccapi.hyundai.com",t=`https://${e}`,i="72b3d019-5bc7-443d-a437-08f307cf06e2";return{brand:"hyundai",host:e,baseUrl:t,clientId:i,appId:"ed01581a-380f-48cd-83d4-ed1490c272d0",endpoints:Object.freeze(U(t,i)),basicToken:"Basic NzJiM2QwMTktNWJjNy00NDNkLWE0MzctMDhmMzA3Y2YwNmUyOnNlY3JldA==",GCMSenderID:"414998006775",providerDeviceId:"59af09e554a9442ab8589c9500d04d2e",pushRegId:"1"}})());case"kia":return Object.freeze((()=>{const e="prd.cn-ccapi.kia.com",t=`https://${e}`,i="9d5df92a-06ae-435f-b459-8304f2efcc67";return{brand:"kia",host:e,baseUrl:t,clientId:i,appId:"eea8762c-adfc-4ee4-8d7a-6e2452ddf342",endpoints:Object.freeze(U(t,i)),basicToken:"Basic OWQ1ZGY5MmEtMDZhZS00MzVmLWI0NTktODMwNGYyZWZjYzY3OnRzWGRrVWcwOEF2MlpaelhPZ1d6Snl4VVQ2eWVTbk5OUWtYWFBSZEtXRUFOd2wxcA==",GCMSenderID:"345127537656",providerDeviceId:"32dedba78045415b92db816e805ed47b",pushRegId:"ogc+GB5gom7zDEQjPhb3lP+bjjM=DG2rQ9Zuq0otwOU7n9y08LKjYpo="}})());default:throw new Error(`Constructor ${e} is not managed.`)}},j=(e,t)=>({session:`${e}/api/v1/user/oauth2/authorize?response_type=code&client_id=${t}&redirect_uri=${encodeURIComponent(`${e}/api/v1/user/oauth2/redirect`)}&lang=en`,login:`${e}/api/v1/user/signin`,language:`${e}/api/v1/user/language`,redirectUri:`${e}/api/v1/user/oauth2/redirect`,token:`${e}/api/v1/user/oauth2/token`,integration:`${e}/api/v1/user/integrationinfo`,silentSignIn:`${e}/api/v1/user/silentsignin`}),N=({brand:e,stampMode:t=E.LOCAL,stampsFile:i})=>{switch(e){case"hyundai":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="au-apigw.ccs.hyundai.com.au:8080",o=`https://${i}`,n="855c72df-dfd7-4230-ab03-67cbf902bb1c",r="f9ccfdac-a48d-4c57-bd32-9116963c24ed";return{brand:"hyundai",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(j(o,n)),basicToken:"Basic ODU1YzcyZGYtZGZkNy00MjMwLWFiMDMtNjdjYmY5MDJiYjFjOmU2ZmJ3SE0zMllOYmhRbDBwdmlhUHAzcmY0dDNTNms5MWVjZUEzTUpMZGJkVGhDTw==",stamp:R({appId:r,brand:"hyundai",mode:e,region:F.AU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t})}})({stampMode:t,stampsFile:i}));case"kia":return Object.freeze((({stampMode:e,stampsFile:t})=>{const i="au-apigw.ccs.kia.com.au:8082",o=`https://${i}`,n="8acb778a-b918-4a8d-8624-73a0beb64289",r="4ad4dcde-be23-48a8-bc1c-91b94f5c06f8";return{brand:"hyundai",host:i,baseUrl:o,clientId:n,appId:r,endpoints:Object.freeze(j(o,n)),basicToken:"Basic OGFjYjc3OGEtYjkxOC00YThkLTg2MjQtNzNhMGJlYjY0Mjg5OjdTY01NbTZmRVlYZGlFUEN4YVBhUW1nZVlkbFVyZndvaDRBZlhHT3pZSVMyQ3U5VA==",stamp:R({appId:r,brand:"kia",mode:e,region:F.AU,stampHost:"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/",stampsFile:t})}})({stampMode:t,stampsFile:i}));default:throw new Error(`Constructor ${e} is not managed.`)}};var F;!function(e){e.US="US",e.CA="CA",e.EU="EU",e.CN="CN",e.AU="AU"}(F||(F={}));const z=[50,60,70,80,90,100],B={refresh:!1,parsed:!1};class Y{constructor(e,t){this.vehicleConfig=e,this.controller=t,this._fullStatus=null,this._status=null,this._location=null,this._odometer=null,this.userConfig={username:void 0,password:void 0,region:F.EU,brand:"hyundai",autoLogin:!0,pin:void 0,vin:void 0,vehicleId:void 0},this.userConfig=t.userConfig}vin(){return this.vehicleConfig.vin}name(){return this.vehicleConfig.name}nickname(){return this.vehicleConfig.nickname}id(){return this.vehicleConfig.id}brandIndicator(){return this.vehicleConfig.brandIndicator}}class J extends Y{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=F.US,k.debug(`US Vehicle ${this.vehicleConfig.regId} created`)}getDefaultHeaders(){return{access_token:this.controller.session.accessToken,client_id:this.controller.environment.clientId,Host:this.controller.environment.host,"User-Agent":"okhttp/3.12.0",registrationId:this.vehicleConfig.regId,gen:this.vehicleConfig.generation,username:this.userConfig.username,vin:this.vehicleConfig.vin,"APPCLOUD-VIN":this.vehicleConfig.vin,Language:"0",to:"ISS",encryptFlag:"false",from:"SPA",brandIndicator:this.vehicleConfig.brandIndicator,bluelinkservicepin:this.userConfig.pin,offset:"-5"}}fullStatus(){throw new Error("Method not implemented.")}odometer(){return v(this,void 0,void 0,(function*(){const e=yield this._request(`/ac/v2/enrollment/details/${this.userConfig.username}`,{method:"GET",headers:Object.assign({},this.getDefaultHeaders())});if(200!==e.statusCode)throw"Failed to get odometer reading!";const t=JSON.parse(e.body).enrolledVehicleDetails.find((e=>e.vehicleDetails.vin===this.vin()));return this._odometer={value:t.vehicleDetails.odometer,unit:0},this._odometer}))}location(){return v(this,void 0,void 0,(function*(){const e=yield this._request("/ac/v2/rcs/rfc/findMyCar",{method:"GET",headers:Object.assign({},this.getDefaultHeaders())});if(200!==e.statusCode)throw"Failed to get location!";const t=JSON.parse(e.body);return{latitude:t.coord.lat,longitude:t.coord.lon,altitude:t.coord.alt,speed:{unit:t.speed.unit,value:t.speed.value},heading:t.head}}))}start(e){return v(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},{hvac:!1,duration:10,temperature:70,defrost:!1,heatedFeatures:!1,unit:"F"}),e),i={Ims:0,airCtrl:+t.hvac,airTemp:{unit:1,value:`${t.temperature}`},defrost:t.defrost,heating1:+t.heatedFeatures,igniOnDuration:t.duration,seatHeaterVentInfo:null,username:this.userConfig.username,vin:this.vehicleConfig.vin};return 200===(yield this._request("/ac/v2/rcs/rsc/start",{method:"POST",headers:Object.assign(Object.assign({},this.getDefaultHeaders()),{offset:"-4"}),body:i,json:!0})).statusCode?"Vehicle started!":"Failed to start vehicle"}))}stop(){return v(this,void 0,void 0,(function*(){if(200===(yield this._request("/ac/v2/rcs/rsc/stop",{method:"POST",headers:Object.assign(Object.assign({},this.getDefaultHeaders()),{offset:"-4"})})).statusCode)return"Vehicle stopped";throw"Failed to stop vehicle!"}))}status(e){return v(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b;const C=Object.assign(Object.assign({},B),e),w=yield this._request("/ac/v2/rcs/rvs/vehicleStatus",{method:"GET",headers:Object.assign({REFRESH:C.refresh.toString()},this.getDefaultHeaders())}),{vehicleStatus:k}=JSON.parse(w.body),T={chassis:{hoodOpen:null==k?void 0:k.hoodOpen,trunkOpen:null==k?void 0:k.trunkOpen,locked:null==k?void 0:k.doorLock,openDoors:{frontRight:!!(null===(t=null==k?void 0:k.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==k?void 0:k.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==k?void 0:k.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==k?void 0:k.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==k?void 0:k.tirePressureLamp)||void 0===r?void 0:r.tirePressureWarningLampRearLeft),frontLeft:!!(null===(s=null==k?void 0:k.tirePressureLamp)||void 0===s?void 0:s.tirePressureWarningLampFrontLeft),frontRight:!!(null===(a=null==k?void 0:k.tirePressureLamp)||void 0===a?void 0:a.tirePressureWarningLampFrontRight),rearRight:!!(null===(d=null==k?void 0:k.tirePressureLamp)||void 0===d?void 0:d.tirePressureWarningLampRearRight),all:!!(null===(l=null==k?void 0:k.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==k?void 0:k.airCtrlOn,steeringwheelHeat:!!(null==k?void 0:k.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==k?void 0:k.sideBackWindowHeat),defrost:null==k?void 0:k.defrost,temperatureSetpoint:null===(c=null==k?void 0:k.airTemp)||void 0===c?void 0:c.value,temperatureUnit:null===(h=null==k?void 0:k.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:null==k?void 0:k.engine,accessory:null==k?void 0:k.acc,range:(null===(g=null===(p=null===(v=null===(u=null==k?void 0:k.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.totalAvailableRange)||void 0===g?void 0:g.value)||(null===(f=null==k?void 0:k.dte)||void 0===f?void 0:f.value),charging:null===(m=null==k?void 0:k.evStatus)||void 0===m?void 0:m.batteryCharge,batteryCharge12v:null===(y=null==k?void 0:k.battery)||void 0===y?void 0:y.batSoc,batteryChargeHV:null===(b=null==k?void 0:k.evStatus)||void 0===b?void 0:b.batteryStatus},lastupdate:new Date(null==k?void 0:k.dateTime)};return this._status=C.parsed?T:k,this._status}))}unlock(){return v(this,void 0,void 0,(function*(){const e=new a;e.append("userName",this.userConfig.username||""),e.append("vin",this.vehicleConfig.vin);return 200===(yield this._request("/ac/v2/rcs/rdo/on",{method:"POST",headers:Object.assign({},this.getDefaultHeaders()),body:e.toString()})).statusCode?"Unlock successful":"Something went wrong!"}))}lock(){return v(this,void 0,void 0,(function*(){const e=new a;e.append("userName",this.userConfig.username||""),e.append("vin",this.vehicleConfig.vin);return 200===(yield this._request("/ac/v2/rcs/rdo/off",{method:"POST",headers:Object.assign({},this.getDefaultHeaders()),body:e.toString()})).statusCode?"Lock successful":"Something went wrong!"}))}startCharge(){return v(this,void 0,void 0,(function*(){if(200===(yield this._request(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{method:"POST"})).statusCode)return k.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}))}stopCharge(){return v(this,void 0,void 0,(function*(){if(200===(yield e(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{method:"POST"})).statusCode)return k.debug(`Send stop charge command to vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}))}_request(t,i){return v(this,void 0,void 0,(function*(){yield this.controller.refreshAccessToken(),i.headers.access_token=this.controller.session.accessToken;const o=yield e(`${this.controller.environment.baseUrl}/${t}`,Object.assign({throwHttpErrors:!1},i));return(null==o?void 0:o.body)&&k.debug(o.body),o}))}}class W{constructor(e){this.userConfig=e,this.session={accessToken:"",refreshToken:"",controlToken:"",deviceId:"",tokenExpiresAt:0}}}class G extends Error{constructor(e,t){super(e),this.source=t,this.name=G.ErrorName}}G.ErrorName="ManagedBluelinkyError";const q=(e,o)=>{var n;return e instanceof t?new G(`${o?`@${o}: `:""}[${e.statusCode}] ${e.statusMessage} on [${e.method}] ${e.url} - ${JSON.stringify(e.body)}`,e):e instanceof i?new G(`${o?`@${o}: `:""} Parsing error on [${e.method}] ${e.url} - ${JSON.stringify(null===(n=e.response)||void 0===n?void 0:n.body)}`,e):(Error,e)},Z=(e,t)=>v(void 0,void 0,void 0,(function*(){const i=[];for(let o=0;o"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}));class Q extends W{constructor(e){super(e),this.vehicles=[],this._environment=(e=>{switch(e){case"hyundai":return Object.freeze((()=>{const e="api.telematics.hyundaiusa.com";return{brand:"hyundai",host:e,baseUrl:`https://${e}`,clientId:"m66129Bb-em93-SPAHYN-bZ91-am4540zp19920",clientSecret:"v558o935-6nne-423i-baa8"}})());case"kia":return Object.freeze((()=>{const e="api.owners.kia.com";return{brand:"kia",host:e,baseUrl:`https://${e}/apigw/v1/`,clientId:"MWAMOBILE",clientSecret:"98er-w34rf-ibf3-3f6h"}})());default:throw new Error(`Constructor ${e} is not managed.`)}})(e.brand),k.debug("US Controller created")}get environment(){return this._environment}refreshAccessToken(){return v(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;try{if(this.session.refreshToken&&t){k.debug("refreshing token");const t=yield e(`${this.environment.baseUrl}/v2/ac/oauth/token/refresh`,{method:"POST",body:{refresh_token:this.session.refreshToken},headers:{"User-Agent":"PostmanRuntime/7.26.10",client_secret:this.environment.clientSecret,client_id:this.environment.clientId},json:!0});return k.debug(t.body),this.session.accessToken=t.body.access_token,this.session.refreshToken=t.body.refresh_token,this.session.tokenExpiresAt=Math.floor(+new Date/1e3+parseInt(t.body.expires_in)),k.debug("Token refreshed"),"Token refreshed"}return k.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh"}catch(e){throw q(e,"AmericanController.refreshAccessToken")}}))}login(){return v(this,void 0,void 0,(function*(){k.debug("Logging in to the API");try{const t=yield e(`${this.environment.baseUrl}/v2/ac/oauth/token`,{method:"POST",body:{username:this.userConfig.username,password:this.userConfig.password},headers:{"User-Agent":"PostmanRuntime/7.26.10",client_id:this.environment.clientId,client_secret:this.environment.clientSecret},json:!0});return k.debug(t.body),200!==t.statusCode?"login bad":(this.session.accessToken=t.body.access_token,this.session.refreshToken=t.body.refresh_token,this.session.tokenExpiresAt=Math.floor(+new Date/1e3+parseInt(t.body.expires_in)),"login good")}catch(e){throw q(e,"AmericanController.login")}}))}logout(){return v(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return v(this,void 0,void 0,(function*(){try{const t=yield e(`${this.environment.baseUrl}/ac/v2/enrollment/details/${this.userConfig.username}`,{method:"GET",headers:{access_token:this.session.accessToken,client_id:this.environment.clientId,Host:this.environment.host,"User-Agent":"okhttp/3.12.0",payloadGenerated:"20200226171938",includeNonConnectedVehicles:"Y"}}),i=JSON.parse(t.body);return void 0===i.enrolledVehicleDetails?(this.vehicles=[],this.vehicles):(this.vehicles=i.enrolledVehicleDetails.map((e=>{const t=e.vehicleDetails,i={nickname:t.nickName,name:t.nickName,vin:t.vin,regDate:t.enrollmentDate,brandIndicator:t.brandIndicator,regId:t.regid,generation:t.modelYear>2016?"2":"1"};return new J(i,this)})),this.vehicles)}catch(e){throw q(e,"AmericanController.getVehicles")}}))}}var X,ee,te;!function(e){e[e.UNPLUGED=0]="UNPLUGED",e[e.FAST=1]="FAST",e[e.PORTABLE=2]="PORTABLE",e[e.STATION=3]="STATION"}(X||(X={})),function(e){e[e.FAST=0]="FAST",e[e.SLOW=1]="SLOW"}(ee||(ee={})),function(e){e[e.CLOSED=0]="CLOSED",e[e.OPEN=1]="OPEN",e[e.VENTILATION=2]="VENTILATION"}(te||(te={}));const ie=(e,t,i)=>{const o=[];for(let n=e;n<=t;n+=i)o.push(n);return o},oe={EU:{start:14,end:30,step:.5},CA:{start:16,end:32,step:.5},CN:{start:14,end:30,step:.5},AU:{start:17,end:27,step:.5}},ne=(e,t)=>{const{start:i,end:o,step:n}=oe[e],r=ie(i,o,n).indexOf(t);return`${("0x"+r.toString(16).substr(-4).toUpperCase()).split("x")[1].toUpperCase()}H`.padStart(3,"0")},re=(e,t)=>{const{start:i,end:o,step:n}=oe[e];return ie(i,o,n)[parseInt(t,16)]},se=e=>{const t=parseInt(e.substring(0,4)),i=parseInt(e.substring(4,6));if(e.length<=6)return new Date(t,i-1);const o=parseInt(e.substring(6,8));if(e.length<=8)return new Date(t,i-1,o);const n=parseInt(e.substring(8,10)),r=parseInt(e.substring(10,12)),s=parseInt(e.substring(12,14));return new Date(t,i-1,o,n,r,s)},ae=(e,t)=>new Date(e.getTime()+6e4*t);var de,le;!function(e){e[e.DAY=0]="DAY",e[e.MONTH=1]="MONTH",e[e.ALL=2]="ALL"}(de||(de={})),function(e){e[e.TOTAL=0]="TOTAL",e[e.AVERAGE=1]="AVERAGE",e[e.TODAY=2]="TODAY"}(le||(le={}));class ce extends Y{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=F.EU,this.serverRates={max:-1,current:-1},k.debug(`EU Vehicle ${this.vehicleConfig.id} created`)}start(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/temperature`,{body:{action:"start",hvacType:0,options:{defrost:e.defrost,heating1:e.heatedFeatures?1:0},tempCode:ne(F.EU,e.temperature),unit:e.unit}}));return k.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw q(e,"EuropeVehicle.start")}}))}stop(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/temperature`,{body:{action:"stop",hvacType:0,options:{defrost:!0,heating1:1},tempCode:"10H",unit:"C"}}));return k.info(`Climate stopped for vehicle ${this.vehicleConfig.id}`),t.body}catch(e){throw q(e,"EuropeVehicle.stop")}}))}lock(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"close",deviceId:this.controller.session.deviceId}})).statusCode?(k.debug(`Vehicle ${this.vehicleConfig.id} locked`),"Lock successful"):"Something went wrong!"}catch(e){throw q(e,"EuropeVehicle.lock")}}))}unlock(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"open",deviceId:this.controller.session.deviceId}})).statusCode?(k.debug(`Vehicle ${this.vehicleConfig.id} unlocked`),"Unlock successful"):"Something went wrong!"}catch(e){throw q(e,"EuropeVehicle.unlock")}}))}fullStatus(e){return v(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},B),e),i=yield this.controller.getVehicleHttpService();try{const e=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`)).body.resMsg.vehicleStatusInfo,o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/ccs2/carstatus/latest`));if(null!=o.body.resMsg.state.Vehicle&&(e.ccs2Status=o.body.resMsg),t.refresh){const t=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`));e.vehicleStatus=t.body.resMsg;const o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`));e.vehicleLocation=o.body.resMsg.gpsDetail}return this._fullStatus=e,this._fullStatus}catch(e){throw q(e,"EuropeVehicle.fullStatus")}}))}status(e){return v(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b,C,w,k,T,S,A,O,$,D,I,E,L,M,P,R,V,x,H,U,_,j,N,z,Y,J;const W=Object.assign(Object.assign({},B),e),G=yield this.controller.getVehicleHttpService();try{const e=W.refresh?"":"/latest",B=this.updateRates(yield G.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${e}`)),q=W.refresh?B.body.resMsg:B.body.resMsg.vehicleStatusInfo.vehicleStatus,Z={chassis:{hoodOpen:null==q?void 0:q.hoodOpen,trunkOpen:null==q?void 0:q.trunkOpen,locked:q.doorLock,openDoors:{frontRight:!!(null===(t=null==q?void 0:q.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==q?void 0:q.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==q?void 0:q.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==q?void 0:q.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==q?void 0:q.tirePressureLamp)||void 0===r?void 0:r.tirePressureLampRL),frontLeft:!!(null===(s=null==q?void 0:q.tirePressureLamp)||void 0===s?void 0:s.tirePressureLampFL),frontRight:!!(null===(a=null==q?void 0:q.tirePressureLamp)||void 0===a?void 0:a.tirePressureLampFR),rearRight:!!(null===(d=null==q?void 0:q.tirePressureLamp)||void 0===d?void 0:d.tirePressureLampRR),all:!!(null===(l=null==q?void 0:q.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==q?void 0:q.airCtrlOn,steeringwheelHeat:!!(null==q?void 0:q.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==q?void 0:q.sideBackWindowHeat),defrost:null==q?void 0:q.defrost,temperatureSetpoint:re(F.EU,null===(c=null==q?void 0:q.airTemp)||void 0===c?void 0:c.value),temperatureUnit:null===(h=null==q?void 0:q.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:q.engine,accessory:null==q?void 0:q.acc,rangeGas:null!==(f=null===(g=null===(p=null===(v=null===(u=null==q?void 0:q.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.gasModeRange)||void 0===g?void 0:g.value)&&void 0!==f?f:null===(m=null==q?void 0:q.dte)||void 0===m?void 0:m.value,range:null===(w=null===(C=null===(b=null===(y=null==q?void 0:q.evStatus)||void 0===y?void 0:y.drvDistance[0])||void 0===b?void 0:b.rangeByFuel)||void 0===C?void 0:C.totalAvailableRange)||void 0===w?void 0:w.value,rangeEV:null===(A=null===(S=null===(T=null===(k=null==q?void 0:q.evStatus)||void 0===k?void 0:k.drvDistance[0])||void 0===T?void 0:T.rangeByFuel)||void 0===S?void 0:S.evModeRange)||void 0===A?void 0:A.value,plugedTo:null!==($=null===(O=null==q?void 0:q.evStatus)||void 0===O?void 0:O.batteryPlugin)&&void 0!==$?$:X.UNPLUGED,charging:null===(D=null==q?void 0:q.evStatus)||void 0===D?void 0:D.batteryCharge,estimatedCurrentChargeDuration:null===(L=null===(E=null===(I=null==q?void 0:q.evStatus)||void 0===I?void 0:I.remainTime2)||void 0===E?void 0:E.atc)||void 0===L?void 0:L.value,estimatedFastChargeDuration:null===(R=null===(P=null===(M=null==q?void 0:q.evStatus)||void 0===M?void 0:M.remainTime2)||void 0===P?void 0:P.etc1)||void 0===R?void 0:R.value,estimatedPortableChargeDuration:null===(H=null===(x=null===(V=null==q?void 0:q.evStatus)||void 0===V?void 0:V.remainTime2)||void 0===x?void 0:x.etc2)||void 0===H?void 0:H.value,estimatedStationChargeDuration:null===(j=null===(_=null===(U=null==q?void 0:q.evStatus)||void 0===U?void 0:U.remainTime2)||void 0===_?void 0:_.etc3)||void 0===j?void 0:j.value,batteryCharge12v:null===(N=null==q?void 0:q.battery)||void 0===N?void 0:N.batSoc,batteryChargeHV:null===(z=null==q?void 0:q.evStatus)||void 0===z?void 0:z.batteryStatus},lastupdate:(null==q?void 0:q.time)?se(null==q?void 0:q.time):null};return Z.engine.range||(Z.engine.rangeEV||Z.engine.rangeGas)&&(Z.engine.range=(null!==(Y=Z.engine.rangeEV)&&void 0!==Y?Y:0)+(null!==(J=Z.engine.rangeGas)&&void 0!==J?J:0)),this._status=W.parsed?Z:q,this._status}catch(e){throw q(e,"EuropeVehicle.status")}}))}odometer(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`));return this._odometer=t.body.resMsg.vehicleStatusInfo.odometer,this._odometer}catch(e){throw q(e,"EuropeVehicle.odometer")}}))}location(){return v(this,void 0,void 0,(function*(){var e,t,i,o,n,r,s;const a=yield this.controller.getVehicleHttpService();try{const d=this.updateRates(yield a.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`)),l=null!==(t=null===(e=d.body.resMsg)||void 0===e?void 0:e.gpsDetail)&&void 0!==t?t:d.body.resMsg;return this._location={latitude:null===(i=null==l?void 0:l.coord)||void 0===i?void 0:i.lat,longitude:null===(o=null==l?void 0:l.coord)||void 0===o?void 0:o.lon,altitude:null===(n=null==l?void 0:l.coord)||void 0===n?void 0:n.alt,speed:{unit:null===(r=null==l?void 0:l.speed)||void 0===r?void 0:r.unit,value:null===(s=null==l?void 0:l.speed)||void 0===s?void 0:s.value},heading:null==l?void 0:l.head},this._location}catch(e){throw q(e,"EuropeVehicle.location")}}))}startCharge(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"start",deviceId:this.controller.session.deviceId}})).statusCode)return k.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}catch(e){throw q(e,"EuropeVehicle.startCharge")}}))}stopCharge(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"stop",deviceId:this.controller.session.deviceId}})).statusCode)return k.debug(`Send stop charge command to Vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}catch(e){throw q(e,"EuropeVehicle.stopCharge")}}))}monthlyReport(){return v(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){var t,i,o,n,r,s,a,d,l,c,h;const u=yield this.controller.getVehicleHttpService();try{const v=null===(t=this.updateRates(yield u.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:he(e)}})).body.resMsg)||void 0===t?void 0:t.monthlyReport;return v?{start:null===(i=v.ifo)||void 0===i?void 0:i.mvrMonthStart,end:null===(o=v.ifo)||void 0===o?void 0:o.mvrMonthEnd,breakdown:v.breakdown,driving:v.driving?{distance:null===(n=v.driving)||void 0===n?void 0:n.runDistance,startCount:null===(r=v.driving)||void 0===r?void 0:r.engineStartCount,durations:{idle:null===(s=v.driving)||void 0===s?void 0:s.engineIdleTime,drive:null===(a=v.driving)||void 0===a?void 0:a.engineOnTime}}:void 0,vehicleStatus:v.vehicleStatus?{tpms:(null===(d=v.vehicleStatus)||void 0===d?void 0:d.tpmsSupport)?Boolean(null===(l=v.vehicleStatus)||void 0===l?void 0:l.tpmsSupport):void 0,tirePressure:{all:"1"==(null===(h=null===(c=v.vehicleStatus)||void 0===c?void 0:c.tirePressure)||void 0===h?void 0:h.tirePressureLampAll)}}:void 0}:void 0}catch(e){throw q(e,"EuropeVehicle.monthyReports")}}))}tripInfo(){return v(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){const t=yield this.controller.getApiHttpService();try{const i=Boolean(e.day),o=this.updateRates(yield t.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/tripinfo`,{body:{setTripLatest:10,setTripMonth:i?void 0:he(e),setTripDay:i?ue(e):void 0,tripPeriodType:i?1:0}}));if(!i){const e=o.body.resMsg;return{days:Array.isArray(null==e?void 0:e.tripDayList)?null==e?void 0:e.tripDayList.map((e=>({dayRaw:e.tripDayInMonth,date:e.tripDayInMonth?se(e.tripDayInMonth):void 0,tripsCount:e.tripCntDay}))):[],durations:{drive:null==e?void 0:e.tripDrvTime,idle:null==e?void 0:e.tripIdleTime},distance:null==e?void 0:e.tripDist,speed:{avg:null==e?void 0:e.tripAvgSpeed,max:null==e?void 0:e.tripMaxSpeed}}}{const e=o.body.resMsg.dayTripList;if(e&&Array.isArray(e))return e.map((e=>({dayRaw:e.tripDay,tripsCount:e.dayTripCnt,distance:e.tripDist,durations:{drive:e.tripDrvTime,idle:e.tripIdleTime},speed:{avg:e.tripAvgSpeed,max:e.tripMaxSpeed},trips:Array.isArray(e.tripList)?e.tripList.map((t=>{const i=se(`${e.tripDay}${t.tripTime}`);return{timeRaw:t.tripTime,start:i,end:ae(i,t.tripDrvTime),durations:{drive:t.tripDrvTime,idle:t.tripIdleTime},speed:{avg:t.tripAvgSpeed,max:t.tripMaxSpeed},distance:t.tripDist}})):[]})))}return}catch(e){throw q(e,"EuropeVehicle.history")}}))}driveHistory(){return v(this,arguments,void 0,(function*(e=de.DAY){var t,i;const o=yield this.controller.getApiHttpService();try{const n=yield o.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/drvhistory`,{body:{periodTarget:e}});return{cumulated:null===(t=n.body.resMsg.drivingInfo)||void 0===t?void 0:t.map((e=>({period:e.drivingPeriod,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo}))),history:null===(i=n.body.resMsg.drivingInfoDetail)||void 0===i?void 0:i.map((e=>({period:e.drivingPeriod,rawDate:e.drivingDate,date:e.drivingDate?se(e.drivingDate):void 0,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo})))}}catch(e){throw q(e,"EuropeVehicle.history")}}))}getChargeTargets(){return v(this,void 0,void 0,(function*(){var e;const t=yield this.controller.getVehicleHttpService();try{const i=null===(e=this.updateRates(yield t.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`)).body.resMsg)||void 0===e?void 0:e.targetSOClist;return i&&Array.isArray(i)?i.map((e=>{var t,i;return{distance:null===(i=null===(t=e.drvDistance)||void 0===t?void 0:t.distanceType)||void 0===i?void 0:i.distanceValue,targetLevel:e.targetSOClevel,type:e.plugType}})):void 0}catch(e){throw q(e,"EuropeVehicle.getChargeTargets")}}))}setChargeTargets(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();if(!z.includes(e.fast)||!z.includes(e.slow))throw new G(`Charge target values are limited to ${z.join(", ")}`);try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`,{body:{targetSOClist:[{plugType:ee.FAST,targetSOClevel:e.fast},{plugType:ee.SLOW,targetSOClevel:e.slow}]}}))}catch(e){throw q(e,"EuropeVehicle.setChargeTargets")}}))}setNavigation(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/routes`,{body:{deviceID:this.controller.session.deviceId,poiInfoList:e}}))}catch(e){throw q(e,"EuropeVehicle.setNavigation")}}))}updateRates(e){var t,i,o,n,r;return(null===(t=e.headers)||void 0===t?void 0:t["x-ratelimit-limit"])&&(this.serverRates.max=Number(null===(i=e.headers)||void 0===i?void 0:i["x-ratelimit-limit"]),this.serverRates.current=Number(null===(o=e.headers)||void 0===o?void 0:o["x-ratelimit-remaining"]),(null===(n=e.headers)||void 0===n?void 0:n["x-ratelimit-reset"])&&(this.serverRates.reset=new Date(Number(`${null===(r=e.headers)||void 0===r?void 0:r["x-ratelimit-reset"]}000`))),this.serverRates.updatedAt=new Date),e}}function he(e){return`${e.year}${e.month.toString().padStart(2,"0")}`}function ue(e){return e.day?`${he(e)}${e.day.toString().padStart(2,"0")}`:he(e)}function ve(t){return v(this,arguments,void 0,(function*(t,i="en",o){const n=null!=o?o:new d;return yield e(t.endpoints.session,{cookieJar:n}),yield e(t.endpoints.language,{method:"POST",body:`{"lang":"${i}"}`,cookieJar:n}),n}))}const pe={"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0 Mobile/15B92 Safari/604.1"},ge=e=>e.catch((e=>"HTTPError"===e.name&&302===e.statusCode?e.response:Promise.reject(e)));class fe{constructor(e,t){this.environment=e,this.language=t}get name(){return"EuropeanBrandAuthStrategy"}login(t,i){return v(this,void 0,void 0,(function*(){const o=yield ve(this.environment,this.language,null==i?void 0:i.cookieJar),{body:{userId:n,serviceId:r}}=yield e(this.environment.endpoints.integration,{cookieJar:o,json:!0,headers:pe}),d=this.environment.brandAuthUrl({language:this.language,userId:n,serviceId:r}),l=s.parse(d,!0),{body:c}=yield e(d,{cookieJar:o,headers:pe}),h=/action="([a-z0-9:/\-.?_=&;]*)"/gi.exec(c),u=null==h?void 0:h[1].replace(/&/g,"&");if(!u)throw new Error("@EuropeanBrandAuthStrategy.login: cannot found the auth url from the form.");const v=new a;v.append("username",t.username),v.append("password",t.password),v.append("credentialId",""),v.append("rememberMe","on");const{headers:{location:p},body:g}=yield ge(e.post(u,{cookieJar:o,body:v.toString(),headers:Object.assign({"Content-Type":"application/x-www-form-urlencoded"},pe),followRedirect:!1}));if(!p){const e=/(.+)<\/span>/gm.exec(g);if(e)throw new Error(`@EuropeanBrandAuthStrategy.login: Authentication failed with message : ${e[1]}`);throw new Error("@EuropeanBrandAuthStrategy.login: Authentication failed, cannot retrieve error message")}const f=yield e(p,{cookieJar:o,headers:pe});let m=f.url,y=f.body;if(!m)throw new Error(`@EuropeanBrandAuthStrategy.login: after login redirection got stuck : ${y}`);if(m.includes("login-actions/required-action")){const t=/action="([a-z0-9:/\-.?_=&;]*)"/gi.exec(y),i=/name="code" value="(.*)"/gi.exec(y);if(!t)throw new Error("@EuropeanBrandAuthStrategy.login: Cannot find login-actions url.");if(!i)throw new Error("@EuropeanBrandAuthStrategy.login: Cannot find login-actions code.");const n=t[1].startsWith("/")?`${l.protocol}//${l.host}${t[1]}`:t[1],r=new a;r.append("code",i[1]),r.append("accept","");const{headers:{location:s},body:d}=yield ge(e.post(n,{cookieJar:o,body:r.toString(),headers:Object.assign({"Content-Type":"application/x-www-form-urlencoded"},pe)}));if(!s){const e=/(.+)<\/span>/gm.exec(d);if(e)throw new Error(`@EuropeanBrandAuthStrategy.login: Authentication action failed with message : ${e[1]}`);throw new Error("@EuropeanBrandAuthStrategy.login: Authentication action failed, cannot retrieve error message")}const c=yield e(s,{cookieJar:o,headers:pe});m=c.url,y=c.body}const{body:b,statusCode:C}=yield e.post(this.environment.endpoints.silentSignIn,{cookieJar:o,body:{intUserId:""},json:!0,headers:Object.assign(Object.assign({},pe),{"ccsp-service-id":this.environment.clientId})});if(!b.redirectUrl)throw new Error(`@EuropeanBrandAuthStrategy.login: silent sign In didn't work, could not retrieve auth code. status: ${C}, body: ${JSON.stringify(b)}`);const{code:w}=s.parse(b.redirectUrl,!0).query;if(!w)throw new Error(`@EuropeanBrandAuthStrategy.login: Cannot find the argument code in ${b.redirectUrl}.`);return{code:w,cookies:o}}))}}class me{constructor(e,t){this.environment=e,this.language=t}get name(){return"EuropeanLegacyAuthStrategy"}login(t,i){return v(this,void 0,void 0,(function*(){const o=yield ve(this.environment,this.language,null==i?void 0:i.cookieJar),{body:n,statusCode:r}=yield e(this.environment.endpoints.login,{method:"POST",json:!0,body:{email:t.username,password:t.password},cookieJar:o});if(!n.redirectUrl)throw new Error(`@EuropeanLegacyAuthStrategy.login: sign In didn't work, could not retrieve auth code. status: ${r}, body: ${JSON.stringify(n)}`);const{code:a}=s.parse(n.redirectUrl,!0).query;if(!a)throw new Error("@EuropeanLegacyAuthStrategy.login: AuthCode was not found, you probably need to migrate your account.");return{code:a,cookies:o}}))}}class ye extends W{constructor(e){var t;if(super(e),this.session={accessToken:void 0,refreshToken:void 0,controlToken:void 0,deviceId:K(),tokenExpiresAt:0,controlTokenExpiresAt:0},this.vehicles=[],this.userConfig.language=null!==(t=e.language)&&void 0!==t?t:"en",!V.includes(this.userConfig.language))throw new Error(`The language code ${this.userConfig.language} is not managed. Only ${V.join(", ")} are.`);this.session.deviceId=K(),this._environment=H(e),this.authStrategies={main:new fe(this._environment,this.userConfig.language),fallback:new me(this._environment,this.userConfig.language)},k.debug("EU Controller created")}get environment(){return this._environment}refreshAccessToken(){return v(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;if(!this.session.refreshToken)return k.debug("Need refresh token to refresh access token. Use login()"),"Need refresh token to refresh access token. Use login()";if(!t)return k.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh";const i=new a;i.append("grant_type","refresh_token"),i.append("redirect_uri","https://www.getpostman.com/oauth2/callback"),i.append("refresh_token",this.session.refreshToken);try{const t=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0"},body:i.toString(),throwHttpErrors:!1});if(200!==t.statusCode)return k.debug(`Refresh token failed: ${t.body}`),`Refresh token failed: ${t.body}`;const o=JSON.parse(t.body);this.session.accessToken="Bearer "+o.access_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+o.expires_in)}catch(e){throw q(e,"EuropeController.refreshAccessToken")}return k.debug("Token refreshed"),"Token refreshed"}))}enterPin(){return v(this,void 0,void 0,(function*(){if(""===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/user/pin`,{method:"PUT",headers:{Authorization:this.session.accessToken,"Content-Type":"application/json"},body:{deviceId:this.session.deviceId,pin:this.userConfig.pin},json:!0});return this.session.controlToken="Bearer "+t.body.controlToken,this.session.controlTokenExpiresAt=Math.floor(Date.now()/1e3+t.body.expiresTime),"PIN entered OK, The pin is valid for 10 minutes"}catch(e){throw q(e,"EuropeController.pin")}}))}login(){return v(this,void 0,void 0,(function*(){try{if(!this.userConfig.password||!this.userConfig.username)throw new Error("@EuropeController.login: username and password must be defined.");let t=null;try{k.debug(`@EuropeController.login: Trying to sign in with ${this.authStrategies.main.name}`),t=yield this.authStrategies.main.login({password:this.userConfig.password,username:this.userConfig.username})}catch(e){k.error(`@EuropeController.login: sign in with ${this.authStrategies.main.name} failed with error ${e.toString()}`),k.debug(`@EuropeController.login: Trying to sign in with ${this.authStrategies.fallback.name}`),t=yield this.authStrategies.fallback.login({password:this.userConfig.password,username:this.userConfig.username})}k.debug("@EuropeController.login: Authenticated properly with user and password");const i=e=>[...Array(e)].map((()=>Math.floor(16*Math.random()).toString(16))).join(""),o=yield e(`${this.environment.baseUrl}/api/v1/spa/notifications/register`,{method:"POST",headers:{"ccsp-service-id":this.environment.clientId,"Content-Type":"application/json;charset=UTF-8",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:{pushRegId:i(64),pushType:"APNS",uuid:this.session.deviceId},json:!0});o&&(this.session.deviceId=o.body.resMsg.deviceId),k.debug("@EuropeController.login: Device registered");const n=new a;n.append("grant_type","authorization_code"),n.append("redirect_uri",this.environment.endpoints.redirectUri),n.append("code",t.code);const r=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0",grant_type:"authorization_code","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:n.toString(),cookieJar:t.cookies});if(200!==r.statusCode)throw new Error(`@EuropeController.login: Could not manage to get token: ${r.body}`);if(r){const e=JSON.parse(r.body);this.session.accessToken=`Bearer ${e.access_token}`,this.session.refreshToken=e.refresh_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+e.expires_in)}return k.debug("@EuropeController.login: Session defined properly"),"Login success"}catch(e){throw q(e,"EuropeController.login")}}))}logout(){return v(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return v(this,void 0,void 0,(function*(){if(void 0===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0});this.vehicles=yield Z(t.body.resMsg.vehicles,(t=>v(this,void 0,void 0,(function*(){const i=(yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles/${t.vehicleId}/profile`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})).body.resMsg,o={nickname:t.nickname,name:t.vehicleName,regDate:t.regDate,brandIndicator:"H",id:t.vehicleId,vin:i.vinInfo[0].basic.vin,generation:i.vinInfo[0].basic.modelYear};return k.debug(`@EuropeController.getVehicles: Added vehicle ${o.id}`),new ce(o,this)}))))}catch(e){throw q(e,"EuropeController.getVehicles")}return this.vehicles}))}checkControlToken(){return v(this,void 0,void 0,(function*(){var e;yield this.refreshAccessToken(),void 0!==(null===(e=this.session)||void 0===e?void 0:e.controlTokenExpiresAt)&&(!this.session.controlToken||Date.now()/1e3>this.session.controlTokenExpiresAt)&&(yield this.enterPin())}))}getVehicleHttpService(){return v(this,void 0,void 0,(function*(){return yield this.checkControlToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Authorization:this.session.controlToken,Stamp:yield this.environment.stamp()}),json:!0})}))}getApiHttpService(){return v(this,void 0,void 0,(function*(){return yield this.refreshAccessToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})}))}get defaultHeaders(){return{Authorization:this.session.accessToken,offset:((new Date).getTimezoneOffset()/60).toFixed(2),"ccsp-device-id":this.session.deviceId,"ccsp-application-id":this.environment.appId,"Content-Type":"application/json"}}}class be extends Y{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=F.CA,this.timeOffset=-(new Date).getTimezoneOffset()/60,this._info=null,k.debug(`CA Vehicle ${this.vehicleConfig.id} created`)}fullStatus(){throw new Error("Method not implemented.")}status(e){return v(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m;const y=Object.assign(Object.assign({},B),e);k.debug("Begin status request, polling car",y.refresh);try{let e=null;if(y.useInfo)yield this.setInfo(y.refresh),this._info&&(e=this._info.status);else{const o=y.refresh?this.controller.environment.endpoints.remoteStatus:this.controller.environment.endpoints.status,n=yield this.request(o,{});if(e=null===(t=n.result)||void 0===t?void 0:t.status,null==n?void 0:n.error)throw null===(i=null==n?void 0:n.error)||void 0===i?void 0:i.errorDesc}k.debug(e);let b=null;return e&&(b={chassis:{hoodOpen:null==e?void 0:e.hoodOpen,trunkOpen:null==e?void 0:e.trunkOpen,locked:null==e?void 0:e.doorLock,openDoors:{frontRight:!!(null===(o=null==e?void 0:e.doorOpen)||void 0===o?void 0:o.frontRight),frontLeft:!!(null===(n=null==e?void 0:e.doorOpen)||void 0===n?void 0:n.frontLeft),backLeft:!!(null===(r=null==e?void 0:e.doorOpen)||void 0===r?void 0:r.backLeft),backRight:!!(null===(s=null==e?void 0:e.doorOpen)||void 0===s?void 0:s.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(a=null==e?void 0:e.tirePressureLamp)||void 0===a?void 0:a.tirePressureWarningLampRearLeft),frontLeft:!!(null===(d=null==e?void 0:e.tirePressureLamp)||void 0===d?void 0:d.tirePressureWarningLampFrontLeft),frontRight:!!(null===(l=null==e?void 0:e.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampFrontRight),rearRight:!!(null===(c=null==e?void 0:e.tirePressureLamp)||void 0===c?void 0:c.tirePressureWarningLampRearRight),all:!!(null===(h=null==e?void 0:e.tirePressureLamp)||void 0===h?void 0:h.tirePressureWarningLampAll)}},climate:{active:null==e?void 0:e.airCtrlOn,steeringwheelHeat:!!(null==e?void 0:e.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==e?void 0:e.sideBackWindowHeat),defrost:null==e?void 0:e.defrost,temperatureSetpoint:null===(u=null==e?void 0:e.airTemp)||void 0===u?void 0:u.value,temperatureUnit:null===(v=null==e?void 0:e.airTemp)||void 0===v?void 0:v.unit},engine:{ignition:null==e?void 0:e.engine,accessory:null==e?void 0:e.acc,range:null===(p=null==e?void 0:e.dte)||void 0===p?void 0:p.value,charging:null===(g=null==e?void 0:e.evStatus)||void 0===g?void 0:g.batteryCharge,batteryCharge12v:null===(f=null==e?void 0:e.battery)||void 0===f?void 0:f.batSoc,batteryChargeHV:null===(m=null==e?void 0:e.evStatus)||void 0===m?void 0:m.batteryStatus},lastupdate:se(null==e?void 0:e.lastStatusDate)}),this._status=y.parsed?b:e,this._status}catch(e){throw e.message}}))}lock(){return v(this,void 0,void 0,(function*(){k.debug("Begin lock request");try{const e=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.lock,{},{pAuth:e}),"Lock successful"}catch(e){throw e.message}}))}unlock(){return v(this,void 0,void 0,(function*(){k.debug("Begin unlock request");try{const e=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.unlock,{},{pAuth:e}),"Unlock successful"}catch(e){throw e.message}}))}start(e){return v(this,void 0,void 0,(function*(){var t,i,o,n,r;k.debug("Begin startClimate request");try{const s={hvacInfo:{airCtrl:null!==(t=e.hvac)&&void 0!==t&&t||null!==(i=e.defrost)&&void 0!==i&&i?1:0,defrost:null!==(o=e.defrost)&&void 0!==o&&o,heating1:e.heatedFeatures?1:0}},a=e.temperature;if(null!=a)s.hvacInfo.airTemp={value:ne(F.CA,a),unit:0,hvacTempType:1};else if(null!==(n=e.hvac)&&void 0!==n&&n||null!==(r=e.defrost)&&void 0!==r&&r)throw"air temperature should be specified";const d=yield this.getPreAuth(),l=yield this.request(this.controller.environment.endpoints.start,s,{pAuth:d});return k.debug(l),l.responseHeader&&0===l.responseHeader.responseCode?"Vehicle started!":"Failed to start vehicle"}catch(e){throw e.message}}))}stop(){return v(this,void 0,void 0,(function*(){k.debug("Begin stop request");try{const e=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.stop,{pAuth:e})}catch(e){throw"error: "+e}}))}lights(){return v(this,arguments,void 0,(function*(e=!1){k.debug("Begin lights request with horn "+e);try{const t=yield this.getPreAuth();return yield this.request(this.controller.environment.endpoints.hornlight,{horn:e},{pAuth:t})}catch(e){throw"error: "+e}}))}stopCharge(){return v(this,void 0,void 0,(function*(){k.debug("Begin stopCharge");const{stopCharge:e}=this.controller.environment.endpoints;try{const t=yield this.getPreAuth();return yield this.request(e,{pin:this.controller.userConfig.pin,pAuth:t})}catch(e){throw"error: "+e}}))}startCharge(){return v(this,void 0,void 0,(function*(){k.debug("Begin startCharge");const{startCharge:e}=this.controller.environment.endpoints;try{const t=yield this.getPreAuth();return yield this.request(e,{pin:this.controller.userConfig.pin,pAuth:t})}catch(e){throw"error: "+e}}))}setChargeTargets(e){return v(this,void 0,void 0,(function*(){if(k.debug("Begin setChargeTarget"),!z.includes(e.fast)||!z.includes(e.slow))throw new G(`Charge target values are limited to ${z.join(", ")}`);const{setChargeTarget:t}=this.controller.environment.endpoints;try{const i=yield this.getPreAuth();return yield this.request(t,{pin:this.controller.userConfig.pin,pAuth:i,tsoc:[{plugType:ee.FAST,level:e.fast},{plugType:ee.SLOW,level:e.slow}]})}catch(e){throw"error: "+e}}))}odometer(){return v(this,void 0,void 0,(function*(){try{if(yield this.setInfo(),this._info)return{unit:this._info.vehicle.odometer,value:this._info.vehicle.odometerUnit};throw"error: no info"}catch(e){throw"error: "+e}}))}location(){return v(this,void 0,void 0,(function*(){k.debug("Begin locate request");try{const e=yield this.getPreAuth(),t=yield this.request(this.controller.environment.endpoints.locate,{},{pAuth:e});return this._location=t.result,this._location}catch(e){throw"error: "+e}}))}getPreAuth(){return v(this,void 0,void 0,(function*(){k.info("Begin pre-authentication");try{return(yield this.request(this.controller.environment.endpoints.verifyPin,{})).result.pAuth}catch(e){throw"error: "+e}}))}request(t,i){return v(this,arguments,void 0,(function*(t,i,o={}){k.debug(`[${t}] ${JSON.stringify(o)} ${JSON.stringify(i)}`),yield this.controller.refreshAccessToken();const[n,,]=process.versions.node.split(".").map(Number);if(n>=21){i=Object.assign({pin:this.userConfig.pin},i),process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",k.debug("Node version >= 21, using fetch instead of got");const e={method:"POST",body:JSON.stringify(i),headers:Object.assign({from:this.controller.environment.origin,language:0,offset:this.timeOffset,accessToken:this.controller.session.accessToken,Origin:"https://kiaconnect.ca",Referer:"https://kiaconnect.ca/login","Content-Type":"application/json",vehicleId:this.vehicleConfig.id},o),dispatcher:new c({connect:{rejectUnauthorized:!1,secureOptions:l.constants.SSL_OP_LEGACY_SERVER_CONNECT}})};try{const i=yield h(t,e);return yield i.json()}catch(e){return void k.error(e)}}const r={method:"POST",json:!0,throwHttpErrors:!1,headers:Object.assign({from:this.controller.environment.origin,language:1,offset:this.timeOffset,accessToken:this.controller.session.accessToken,vehicleId:this.vehicleConfig.id},o),body:Object.assign({pin:this.userConfig.pin},i)};try{const i=yield e(t,r);return 0!=i.body.responseHeader.responseCode?i.body.responseHeader.responseDesc:i.body}catch(e){throw"error: "+e}}))}setInfo(){return v(this,arguments,void 0,(function*(e=!1){if(null===this._info||e)try{const e=yield this.getPreAuth(),t=yield this.request(this.controller.environment.endpoints.vehicleInfo,{},{pAuth:e});this._info=t.result}catch(e){throw"error: "+e}}))}}class Ce extends W{constructor(e){super(e),this.vehicles=[],this.timeOffset=-(new Date).getTimezoneOffset()/60,k.debug("CA Controller created"),this._environment=A(e.brand)}get environment(){return this._environment}refreshAccessToken(){return v(this,void 0,void 0,(function*(){const e=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;return k.debug("shouldRefreshToken: "+e.toString()),this.session.refreshToken&&e?(yield this.login(),k.debug("Token refreshed"),"Token refreshed"):(k.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh")}))}login(){return v(this,void 0,void 0,(function*(){k.info("Begin login request");try{const e=yield this.request(this.environment.endpoints.login,{loginId:this.userConfig.username,password:this.userConfig.password});return k.debug(e.result),this.session.accessToken=e.result.accessToken,this.session.refreshToken=e.result.refreshToken,this.session.tokenExpiresAt=Math.floor(+new Date/1e3+e.result.expireIn),"login good"}catch(e){return"error: "+e}}))}logout(){return v(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return v(this,void 0,void 0,(function*(){k.info("Begin getVehicleList request");try{const e=(yield this.request(this.environment.endpoints.vehicleList,{})).result;return void 0===e.vehicles?(this.vehicles=[],this.vehicles):(e.vehicles.forEach((e=>{const t={nickname:e.nickName,name:e.nickName,vin:e.vin,regDate:e.enrollmentDate,brandIndicator:e.brandIndicator,regId:e.regid,id:e.vehicleId,generation:e.genType};this.vehicles.push(new be(t,this))})),this.vehicles)}catch(e){return k.debug(e),this.vehicles}}))}request(t,i){return v(this,arguments,void 0,(function*(t,i,o={}){k.debug(`[${t}] ${JSON.stringify(o)} ${JSON.stringify(i)}`);const[n,,]=process.versions.node.split(".").map(Number);if(n>=21){process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",k.debug("Node version >= 21, using fetch instead of got");const e={method:"POST",body:JSON.stringify(i),headers:Object.assign({from:this.environment.origin,language:0,offset:this.timeOffset,accessToken:this.session.accessToken,Origin:"https://kiaconnect.ca",Referer:"https://kiaconnect.ca/login","Content-Type":"application/json"},o),dispatcher:new c({connect:{rejectUnauthorized:!1,secureOptions:l.constants.SSL_OP_LEGACY_SERVER_CONNECT}})};try{const i=yield h(t,e);return yield i.json()}catch(e){return void k.error(e)}}try{const n=yield e(t,{method:"POST",json:!0,headers:Object.assign({from:this.environment.origin,language:1,offset:this.timeOffset,accessToken:this.session.accessToken},o),body:Object.assign({},i)});if(0!=n.body.responseHeader.responseCode)throw n.body.responseHeader.responseDesc;return n.body}catch(e){throw q(e,"CanadianController")}}))}}var we,ke;!function(e){e[e.DAY=0]="DAY",e[e.MONTH=1]="MONTH",e[e.ALL=2]="ALL"}(we||(we={})),function(e){e[e.TOTAL=0]="TOTAL",e[e.AVERAGE=1]="AVERAGE",e[e.TODAY=2]="TODAY"}(ke||(ke={}));class Te extends Y{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=F.CN,this.serverRates={max:-1,current:-1},k.debug(`CN Vehicle ${this.vehicleConfig.id} created`)}start(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"start",hvacType:1,options:{defrost:e.defrost,heating1:e.heatedFeatures?1:0},tempCode:ne(F.CN,e.temperature),unit:e.unit}}));return k.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw q(e,"ChinaVehicle.start")}}))}stop(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"stop",hvacType:0,options:{defrost:!0,heating1:1},tempCode:"10H",unit:"C"}}));return k.info(`Climate stopped for vehicle ${this.vehicleConfig.id}`),t.body}catch(e){throw q(e,"ChinaVehicle.stop")}}))}lock(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"close",deviceId:this.controller.session.deviceId}})).statusCode?(k.debug(`Vehicle ${this.vehicleConfig.id} locked`),"Lock successful"):"Something went wrong!"}catch(e){throw q(e,"ChinaVehicle.lock")}}))}unlock(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"open",deviceId:this.controller.session.deviceId}})).statusCode?(k.debug(`Vehicle ${this.vehicleConfig.id} unlocked`),"Unlock successful"):"Something went wrong!"}catch(e){throw q(e,"ChinaVehicle.unlock")}}))}fullStatus(e){return v(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},B),e),i=yield this.controller.getVehicleHttpService();try{const e=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`)).body.resMsg.status;if(t.refresh){const t=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`));e.vehicleStatus=t.body.resMsg.status;const o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`));e.vehicleLocation=o.body.resMsg.coord}return this._fullStatus=e,this._fullStatus}catch(e){throw q(e,"ChinaVehicle.fullStatus")}}))}status(e){return v(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b,C,w,k,T,S,A,O,$,D,I,E,L,M,P,R,V,x,H,U,_,j,N,z,Y,J;const W=Object.assign(Object.assign({},B),e),G=yield this.controller.getVehicleHttpService();try{const e=W.refresh?"":"/latest",B=this.updateRates(yield G.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${e}`)).body.resMsg.status,q={chassis:{hoodOpen:null==B?void 0:B.hoodOpen,trunkOpen:null==B?void 0:B.trunkOpen,locked:B.doorLock,openDoors:{frontRight:!!(null===(t=null==B?void 0:B.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==B?void 0:B.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==B?void 0:B.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==B?void 0:B.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==B?void 0:B.tirePressureLamp)||void 0===r?void 0:r.tirePressureLampRL),frontLeft:!!(null===(s=null==B?void 0:B.tirePressureLamp)||void 0===s?void 0:s.tirePressureLampFL),frontRight:!!(null===(a=null==B?void 0:B.tirePressureLamp)||void 0===a?void 0:a.tirePressureLampFR),rearRight:!!(null===(d=null==B?void 0:B.tirePressureLamp)||void 0===d?void 0:d.tirePressureLampRR),all:!!(null===(l=null==B?void 0:B.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==B?void 0:B.airCtrlOn,steeringwheelHeat:!!(null==B?void 0:B.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==B?void 0:B.sideBackWindowHeat),defrost:null==B?void 0:B.defrost,temperatureSetpoint:re(F.EU,null===(c=null==B?void 0:B.airTemp)||void 0===c?void 0:c.value),temperatureUnit:null===(h=null==B?void 0:B.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:B.engine,accessory:null==B?void 0:B.acc,rangeGas:null!==(f=null===(g=null===(p=null===(v=null===(u=null==B?void 0:B.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.gasModeRange)||void 0===g?void 0:g.value)&&void 0!==f?f:null===(m=null==B?void 0:B.dte)||void 0===m?void 0:m.value,range:null===(w=null===(C=null===(b=null===(y=null==B?void 0:B.evStatus)||void 0===y?void 0:y.drvDistance[0])||void 0===b?void 0:b.rangeByFuel)||void 0===C?void 0:C.totalAvailableRange)||void 0===w?void 0:w.value,rangeEV:null===(A=null===(S=null===(T=null===(k=null==B?void 0:B.evStatus)||void 0===k?void 0:k.drvDistance[0])||void 0===T?void 0:T.rangeByFuel)||void 0===S?void 0:S.evModeRange)||void 0===A?void 0:A.value,plugedTo:null!==($=null===(O=null==B?void 0:B.evStatus)||void 0===O?void 0:O.batteryPlugin)&&void 0!==$?$:X.UNPLUGED,charging:null===(D=null==B?void 0:B.evStatus)||void 0===D?void 0:D.batteryCharge,estimatedCurrentChargeDuration:null===(L=null===(E=null===(I=null==B?void 0:B.evStatus)||void 0===I?void 0:I.remainTime2)||void 0===E?void 0:E.atc)||void 0===L?void 0:L.value,estimatedFastChargeDuration:null===(R=null===(P=null===(M=null==B?void 0:B.evStatus)||void 0===M?void 0:M.remainTime2)||void 0===P?void 0:P.etc1)||void 0===R?void 0:R.value,estimatedPortableChargeDuration:null===(H=null===(x=null===(V=null==B?void 0:B.evStatus)||void 0===V?void 0:V.remainTime2)||void 0===x?void 0:x.etc2)||void 0===H?void 0:H.value,estimatedStationChargeDuration:null===(j=null===(_=null===(U=null==B?void 0:B.evStatus)||void 0===U?void 0:U.remainTime2)||void 0===_?void 0:_.etc3)||void 0===j?void 0:j.value,batteryCharge12v:null===(N=null==B?void 0:B.battery)||void 0===N?void 0:N.batSoc,batteryChargeHV:null===(z=null==B?void 0:B.evStatus)||void 0===z?void 0:z.batteryStatus},lastupdate:(null==B?void 0:B.time)?se(null==B?void 0:B.time):null};return q.engine.range||(q.engine.rangeEV||q.engine.rangeGas)&&(q.engine.range=(null!==(Y=q.engine.rangeEV)&&void 0!==Y?Y:0)+(null!==(J=q.engine.rangeGas)&&void 0!==J?J:0)),this._status=W.parsed?q:B,this._status}catch(e){throw q(e,"ChinaVehicle.status")}}))}odometer(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`));return this._odometer=t.body.resMsg.status.odometer,this._odometer}catch(e){throw q(e,"ChinaVehicle.odometer")}}))}location(){return v(this,void 0,void 0,(function*(){var e,t,i,o,n,r,s;const a=yield this.controller.getVehicleHttpService();try{const d=this.updateRates(yield a.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`)),l=null!==(t=null===(e=d.body.resMsg)||void 0===e?void 0:e.gpsDetail)&&void 0!==t?t:d.body.resMsg;return this._location={latitude:null===(i=null==l?void 0:l.coord)||void 0===i?void 0:i.lat,longitude:null===(o=null==l?void 0:l.coord)||void 0===o?void 0:o.lon,altitude:null===(n=null==l?void 0:l.coord)||void 0===n?void 0:n.alt,speed:{unit:null===(r=null==l?void 0:l.speed)||void 0===r?void 0:r.unit,value:null===(s=null==l?void 0:l.speed)||void 0===s?void 0:s.value},heading:null==l?void 0:l.head},this._location}catch(e){throw q(e,"ChinaVehicle.location")}}))}startCharge(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"start",deviceId:this.controller.session.deviceId}})).statusCode)return k.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}catch(e){throw q(e,"ChinaVehicle.startCharge")}}))}stopCharge(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"stop",deviceId:this.controller.session.deviceId}})).statusCode)return k.debug(`Send stop charge command to Vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}catch(e){throw q(e,"ChinaVehicle.stopCharge")}}))}monthlyReport(){return v(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){var t,i,o,n,r,s,a,d,l,c,h;const u=yield this.controller.getVehicleHttpService();try{const v=null===(t=this.updateRates(yield u.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:Se(e)}})).body.resMsg)||void 0===t?void 0:t.monthlyReport;return v?{start:null===(i=v.ifo)||void 0===i?void 0:i.mvrMonthStart,end:null===(o=v.ifo)||void 0===o?void 0:o.mvrMonthEnd,breakdown:v.breakdown,driving:v.driving?{distance:null===(n=v.driving)||void 0===n?void 0:n.runDistance,startCount:null===(r=v.driving)||void 0===r?void 0:r.engineStartCount,durations:{idle:null===(s=v.driving)||void 0===s?void 0:s.engineIdleTime,drive:null===(a=v.driving)||void 0===a?void 0:a.engineOnTime}}:void 0,vehicleStatus:v.vehicleStatus?{tpms:(null===(d=v.vehicleStatus)||void 0===d?void 0:d.tpmsSupport)?Boolean(null===(l=v.vehicleStatus)||void 0===l?void 0:l.tpmsSupport):void 0,tirePressure:{all:"1"==(null===(h=null===(c=v.vehicleStatus)||void 0===c?void 0:c.tirePressure)||void 0===h?void 0:h.tirePressureLampAll)}}:void 0}:void 0}catch(e){throw q(e,"ChinaVehicle.monthyReports")}}))}tripInfo(){return v(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){const t=yield this.controller.getApiHttpService();try{const i=Boolean(e.day),o=this.updateRates(yield t.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/tripinfo`,{body:{setTripLatest:10,setTripMonth:i?void 0:Se(e),setTripDay:i?Ae(e):void 0,tripPeriodType:i?1:0}}));if(!i){const e=o.body.resMsg;return{days:Array.isArray(null==e?void 0:e.tripDayList)?null==e?void 0:e.tripDayList.map((e=>({dayRaw:e.tripDayInMonth,date:e.tripDayInMonth?se(e.tripDayInMonth):void 0,tripsCount:e.tripCntDay}))):[],durations:{drive:null==e?void 0:e.tripDrvTime,idle:null==e?void 0:e.tripIdleTime},distance:null==e?void 0:e.tripDist,speed:{avg:null==e?void 0:e.tripAvgSpeed,max:null==e?void 0:e.tripMaxSpeed}}}{const e=o.body.resMsg.dayTripList;if(e&&Array.isArray(e))return e.map((e=>({dayRaw:e.tripDay,tripsCount:e.dayTripCnt,distance:e.tripDist,durations:{drive:e.tripDrvTime,idle:e.tripIdleTime},speed:{avg:e.tripAvgSpeed,max:e.tripMaxSpeed},trips:Array.isArray(e.tripList)?e.tripList.map((t=>{const i=se(`${e.tripDay}${t.tripTime}`);return{timeRaw:t.tripTime,start:i,end:ae(i,t.tripDrvTime),durations:{drive:t.tripDrvTime,idle:t.tripIdleTime},speed:{avg:t.tripAvgSpeed,max:t.tripMaxSpeed},distance:t.tripDist}})):[]})))}return}catch(e){throw q(e,"ChinaVehicle.history")}}))}driveHistory(){return v(this,arguments,void 0,(function*(e=we.DAY){var t,i;const o=yield this.controller.getApiHttpService();try{const n=yield o.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/drvhistory`,{body:{periodTarget:e}});return{cumulated:null===(t=n.body.resMsg.drivingInfo)||void 0===t?void 0:t.map((e=>({period:e.drivingPeriod,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo}))),history:null===(i=n.body.resMsg.drivingInfoDetail)||void 0===i?void 0:i.map((e=>({period:e.drivingPeriod,rawDate:e.drivingDate,date:e.drivingDate?se(e.drivingDate):void 0,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo})))}}catch(e){throw q(e,"ChinaVehicle.history")}}))}getChargeTargets(){return v(this,void 0,void 0,(function*(){var e;const t=yield this.controller.getVehicleHttpService();try{const i=null===(e=this.updateRates(yield t.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`)).body.resMsg)||void 0===e?void 0:e.targetSOClist;return i&&Array.isArray(i)?i.map((e=>{var t,i;return{distance:null===(i=null===(t=e.drvDistance)||void 0===t?void 0:t.distanceType)||void 0===i?void 0:i.distanceValue,targetLevel:e.targetSOClevel,type:e.plugType}})):void 0}catch(e){throw q(e,"ChinaVehicle.getChargeTargets")}}))}setChargeTargets(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();if(!z.includes(e.fast)||!z.includes(e.slow))throw new G(`Charge target values are limited to ${z.join(", ")}`);try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`,{body:{targetSOClist:[{plugType:ee.FAST,targetSOClevel:e.fast},{plugType:ee.SLOW,targetSOClevel:e.slow}]}}))}catch(e){throw q(e,"ChinaVehicle.setChargeTargets")}}))}setNavigation(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/routes`,{body:{deviceID:this.controller.session.deviceId,poiInfoList:e}}))}catch(e){throw q(e,"ChinaVehicle.setNavigation")}}))}updateRates(e){var t,i,o,n,r;return(null===(t=e.headers)||void 0===t?void 0:t["x-ratelimit-limit"])&&(this.serverRates.max=Number(null===(i=e.headers)||void 0===i?void 0:i["x-ratelimit-limit"]),this.serverRates.current=Number(null===(o=e.headers)||void 0===o?void 0:o["x-ratelimit-remaining"]),(null===(n=e.headers)||void 0===n?void 0:n["x-ratelimit-reset"])&&(this.serverRates.reset=new Date(Number(`${null===(r=e.headers)||void 0===r?void 0:r["x-ratelimit-reset"]}000`))),this.serverRates.updatedAt=new Date),e}}function Se(e){return`${e.year}${e.month.toString().padStart(2,"0")}`}function Ae(e){return e.day?`${Se(e)}${e.day.toString().padStart(2,"0")}`:Se(e)}class Oe{constructor(e){this.environment=e}get name(){return"ChineseLegacyAuthStrategy"}login(t,i){return v(this,void 0,void 0,(function*(){const o=yield function(t,i){return v(this,void 0,void 0,(function*(){const o=null!=i?i:new d;return yield e(t.endpoints.session,{cookieJar:o}),yield e(t.endpoints.language,{method:"POST",body:'{"lang":"zh"}',cookieJar:o}),o}))}(this.environment,null==i?void 0:i.cookieJar),{body:n,statusCode:r}=yield e(this.environment.endpoints.login,{method:"POST",json:!0,body:{email:t.username,password:t.password},cookieJar:o});if(!n.redirectUrl)throw new Error(`@ChineseLegacyAuthStrategy.login: sign In didn't work, could not retrieve auth code. status: ${r}, body: ${JSON.stringify(n)}`);const{code:a}=s.parse(n.redirectUrl,!0).query;if(!a)throw new Error("@ChineseLegacyAuthStrategy.login: AuthCode was not found, you probably need to migrate your account.");return{code:a,cookies:o}}))}}class $e extends W{constructor(e){super(e),this.session={accessToken:void 0,refreshToken:void 0,controlToken:void 0,deviceId:K(),tokenExpiresAt:0,controlTokenExpiresAt:0},this.vehicles=[],this.session.deviceId=K(),this._environment=_(e),this.authStrategies={main:new Oe(this._environment)},k.debug("CN Controller created")}get environment(){return this._environment}refreshAccessToken(){return v(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;if(!this.session.refreshToken)return k.debug("Need refresh token to refresh access token. Use login()"),"Need refresh token to refresh access token. Use login()";if(!t)return k.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh";const i=new a;i.append("grant_type","refresh_token"),i.append("redirect_uri","https://www.getpostman.com/oauth2/callback"),i.append("refresh_token",this.session.refreshToken);try{const t=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0"},body:i.toString(),throwHttpErrors:!1});if(200!==t.statusCode)return k.debug(`Refresh token failed: ${t.body}`),`Refresh token failed: ${t.body}`;const o=JSON.parse(t.body);this.session.accessToken="Bearer "+o.access_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+o.expires_in)}catch(e){throw q(e,"ChinaController.refreshAccessToken")}return k.debug("Token refreshed"),"Token refreshed"}))}enterPin(){return v(this,void 0,void 0,(function*(){if(""===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/user/pin?token=`,{method:"PUT",headers:{Authorization:this.session.accessToken,"Content-Type":"application/json"},body:{deviceId:this.session.deviceId,pin:this.userConfig.pin},json:!0});return this.session.controlToken="Bearer "+t.body.controlToken,k.debug(`controlToken is : ${this.session.controlToken}`),this.session.controlTokenExpiresAt=Math.floor(Date.now()/1e3+t.body.expiresTime),"PIN entered OK, The pin is valid for 10 minutes"}catch(e){throw q(e,"ChinaController.pin")}}))}login(){return v(this,void 0,void 0,(function*(){try{if(!this.userConfig.password||!this.userConfig.username)throw new Error("@ChinaController.login: username and password must be defined.");let t=null;try{k.debug(`@ChinaController.login: Trying to sign in with ${this.authStrategies.main.name}`),t=yield this.authStrategies.main.login({password:this.userConfig.password,username:this.userConfig.username})}catch(e){k.error(`@ChinaController.login: sign in with ${this.authStrategies.main.name} failed with error ${e.toString()}`),k.debug(`@ChinaController.login: Trying to sign in with ${this.authStrategies.main.name}`),t=yield this.authStrategies.main.login({password:this.userConfig.password,username:this.userConfig.username})}k.debug("@ChinaController.login: Authenticated properly with user and password");const i=yield e(`${this.environment.baseUrl}/api/v1/spa/notifications/register`,{method:"POST",headers:{"ccsp-service-id":this.environment.clientId,"Content-Type":"application/json;charset=UTF-8",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0","ccsp-application-id":this.environment.appId},body:{pushRegId:this.environment.pushRegId,providerDeviceId:this.environment.providerDeviceId,pushType:"GCM",uuid:K()},json:!0});i&&(this.session.deviceId=i.body.resMsg.deviceId),k.debug("@ChinaController.login: Device registered");const o=new a;o.append("grant_type","authorization_code"),o.append("redirect_uri",this.environment.endpoints.redirectUri),o.append("code",t.code);const n=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0",grant_type:"authorization_code"},body:o.toString(),cookieJar:t.cookies});if(200!==n.statusCode)throw new Error(`@ChinaController.login: Could not manage to get token: ${n.body}`);if(n){const e=JSON.parse(n.body);this.session.accessToken=`Bearer ${e.access_token}`,this.session.refreshToken=e.refresh_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+e.expires_in)}return k.debug("@ChinaController.login: Session defined properly"),k.debug(`accessToken is ${this.session.accessToken}\n refreshToken is ${this.session.refreshToken}\n tokenExpiresAt : ${this.session.tokenExpiresAt}`),"Login success"}catch(e){throw q(e,"ChinaController.login")}}))}logout(){return v(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return v(this,void 0,void 0,(function*(){if(void 0===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles`,{method:"GET",headers:Object.assign({},this.defaultHeaders),json:!0});this.vehicles=yield Z(t.body.resMsg.vehicles,(t=>v(this,void 0,void 0,(function*(){const i=(yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles/${t.vehicleId}/profile`,{method:"GET",headers:Object.assign({},this.defaultHeaders),json:!0})).body.resMsg,o={nickname:t.nickname,name:t.vehicleName,regDate:t.regDate,brandIndicator:"H",id:t.vehicleId,vin:i.vinInfo[0].basic.vin,generation:i.vinInfo[0].basic.modelYear};return k.debug(`@ChineseController.getVehicles: Added vehicle ${o.id}`),new Te(o,this)}))))}catch(e){throw q(e,"EuropeController.getVehicles")}return this.vehicles}))}checkControlToken(){return v(this,void 0,void 0,(function*(){var e;yield this.refreshAccessToken(),void 0!==(null===(e=this.session)||void 0===e?void 0:e.controlTokenExpiresAt)&&(!this.session.controlToken||Date.now()/1e3>this.session.controlTokenExpiresAt)&&(yield this.enterPin())}))}getVehicleHttpService(){return v(this,void 0,void 0,(function*(){return yield this.checkControlToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Authorization:this.session.controlToken,AuthorizationCCSP:this.session.controlToken,"ccsp-device-id":"2e062595-28e0-4bcb-a75a-1b395cde337c"}),json:!0})}))}getApiHttpService(){return v(this,void 0,void 0,(function*(){return yield this.refreshAccessToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign({},this.defaultHeaders),json:!0})}))}get defaultHeaders(){return{Authorization:this.session.accessToken,offset:((new Date).getTimezoneOffset()/60).toFixed(0),"ccsp-device-id":"2e062595-28e0-4bcb-a75a-1b395cde337c","ccsp-application-id":this.environment.appId,"Content-Type":"application/json","User-Agent":"okhttp/4.4.0"}}}class De extends Y{constructor(e,t){super(e,t),this.vehicleConfig=e,this.controller=t,this.region=F.AU,this.serverRates={max:-1,current:-1},k.debug(`AU Vehicle ${this.vehicleConfig.id} created`)}start(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"start",hvacType:0,options:{defrost:e.defrost,heating1:e.heatedFeatures?1:0},tempCode:ne(F.AU,e.temperature),unit:e.unit}}));return k.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw q(e,"AustraliaVehicle.start")}}))}stop(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/engine`,{body:{action:"stop",hvacType:0,options:{defrost:!0,heating1:1},tempCode:"10H",unit:"C"}}));return k.info(`Climate stopped for vehicle ${this.vehicleConfig.id}`),t.body}catch(e){throw q(e,"AustraliaVehicle.stop")}}))}lock(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"close",deviceId:this.controller.session.deviceId}})).statusCode?(k.debug(`Vehicle ${this.vehicleConfig.id} locked`),"Lock successful"):"Something went wrong!"}catch(e){throw q(e,"AustraliaVehicle.lock")}}))}unlock(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{return 200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/door`,{body:{action:"open",deviceId:this.controller.session.deviceId}})).statusCode?(k.debug(`Vehicle ${this.vehicleConfig.id} unlocked`),"Unlock successful"):"Something went wrong!"}catch(e){throw q(e,"AustraliaVehicle.unlock")}}))}setWindows(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{const i=this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/windowcurtain`,{body:e}));return k.info(`Climate started for vehicle ${this.vehicleConfig.id}`),i.body}catch(e){throw q(e,"AustraliaVehicle.start")}}))}fullStatus(e){return v(this,void 0,void 0,(function*(){const t=Object.assign(Object.assign({},B),e),i=yield this.controller.getVehicleHttpService();try{const e=this.updateRates(t.refresh?yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status/latest`):yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`)),o=this.updateRates(yield i.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/park`)),n=yield this.odometer();return n?(this._fullStatus={vehicleLocation:o.body.resMsg.gpsDetail,odometer:n,vehicleStatus:e.body.resMsg},this._fullStatus):null}catch(e){throw q(e,"AustraliaVehicle.fullStatus")}}))}status(e){return v(this,void 0,void 0,(function*(){var t,i,o,n,r,s,a,d,l,c,h,u,v,p,g,f,m,y,b,C,w,k,T,S,A,O,$,D,I,E,L,M,P,R,V,x,H,U,_,j,N,z,Y,J;const W=Object.assign(Object.assign({},B),e),G=yield this.controller.getVehicleHttpService();try{const e=W.refresh?"":"/latest",B=this.updateRates(yield G.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${e}`)).body.resMsg,q={chassis:{hoodOpen:null==B?void 0:B.hoodOpen,trunkOpen:null==B?void 0:B.trunkOpen,locked:B.doorLock,openDoors:{frontRight:!!(null===(t=null==B?void 0:B.doorOpen)||void 0===t?void 0:t.frontRight),frontLeft:!!(null===(i=null==B?void 0:B.doorOpen)||void 0===i?void 0:i.frontLeft),backLeft:!!(null===(o=null==B?void 0:B.doorOpen)||void 0===o?void 0:o.backLeft),backRight:!!(null===(n=null==B?void 0:B.doorOpen)||void 0===n?void 0:n.backRight)},tirePressureWarningLamp:{rearLeft:!!(null===(r=null==B?void 0:B.tirePressureLamp)||void 0===r?void 0:r.tirePressureLampRL),frontLeft:!!(null===(s=null==B?void 0:B.tirePressureLamp)||void 0===s?void 0:s.tirePressureLampFL),frontRight:!!(null===(a=null==B?void 0:B.tirePressureLamp)||void 0===a?void 0:a.tirePressureLampFR),rearRight:!!(null===(d=null==B?void 0:B.tirePressureLamp)||void 0===d?void 0:d.tirePressureLampRR),all:!!(null===(l=null==B?void 0:B.tirePressureLamp)||void 0===l?void 0:l.tirePressureWarningLampAll)}},climate:{active:null==B?void 0:B.airCtrlOn,steeringwheelHeat:!!(null==B?void 0:B.steerWheelHeat),sideMirrorHeat:!1,rearWindowHeat:!!(null==B?void 0:B.sideBackWindowHeat),defrost:null==B?void 0:B.defrost,temperatureSetpoint:re(F.AU,null===(c=null==B?void 0:B.airTemp)||void 0===c?void 0:c.value),temperatureUnit:null===(h=null==B?void 0:B.airTemp)||void 0===h?void 0:h.unit},engine:{ignition:B.engine,accessory:null==B?void 0:B.acc,rangeGas:null!==(f=null===(g=null===(p=null===(v=null===(u=null==B?void 0:B.evStatus)||void 0===u?void 0:u.drvDistance[0])||void 0===v?void 0:v.rangeByFuel)||void 0===p?void 0:p.gasModeRange)||void 0===g?void 0:g.value)&&void 0!==f?f:null===(m=null==B?void 0:B.dte)||void 0===m?void 0:m.value,range:null===(w=null===(C=null===(b=null===(y=null==B?void 0:B.evStatus)||void 0===y?void 0:y.drvDistance[0])||void 0===b?void 0:b.rangeByFuel)||void 0===C?void 0:C.totalAvailableRange)||void 0===w?void 0:w.value,rangeEV:null===(A=null===(S=null===(T=null===(k=null==B?void 0:B.evStatus)||void 0===k?void 0:k.drvDistance[0])||void 0===T?void 0:T.rangeByFuel)||void 0===S?void 0:S.evModeRange)||void 0===A?void 0:A.value,plugedTo:null!==($=null===(O=null==B?void 0:B.evStatus)||void 0===O?void 0:O.batteryPlugin)&&void 0!==$?$:X.UNPLUGED,charging:null===(D=null==B?void 0:B.evStatus)||void 0===D?void 0:D.batteryCharge,estimatedCurrentChargeDuration:null===(L=null===(E=null===(I=null==B?void 0:B.evStatus)||void 0===I?void 0:I.remainTime2)||void 0===E?void 0:E.atc)||void 0===L?void 0:L.value,estimatedFastChargeDuration:null===(R=null===(P=null===(M=null==B?void 0:B.evStatus)||void 0===M?void 0:M.remainTime2)||void 0===P?void 0:P.etc1)||void 0===R?void 0:R.value,estimatedPortableChargeDuration:null===(H=null===(x=null===(V=null==B?void 0:B.evStatus)||void 0===V?void 0:V.remainTime2)||void 0===x?void 0:x.etc2)||void 0===H?void 0:H.value,estimatedStationChargeDuration:null===(j=null===(_=null===(U=null==B?void 0:B.evStatus)||void 0===U?void 0:U.remainTime2)||void 0===_?void 0:_.etc3)||void 0===j?void 0:j.value,batteryCharge12v:null===(N=null==B?void 0:B.battery)||void 0===N?void 0:N.batSoc,batteryChargeHV:null===(z=null==B?void 0:B.evStatus)||void 0===z?void 0:z.batteryStatus},lastupdate:(null==B?void 0:B.time)?se(null==B?void 0:B.time):null};return q.engine.range||(q.engine.rangeEV||q.engine.rangeGas)&&(q.engine.range=(null!==(Y=q.engine.rangeEV)&&void 0!==Y?Y:0)+(null!==(J=q.engine.rangeGas)&&void 0!==J?J:0)),this._status=W.parsed?q:B,this._status}catch(e){throw q(e,"AustraliaVehicle.status")}}))}odometer(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{const t=this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:Ie({year:(new Date).getFullYear(),month:(new Date).getMonth()+1})}}));return this._odometer={unit:0,value:t.body.resMsg.odometer},this._odometer}catch(e){throw q(e,"AustraliaVehicle.odometer")}}))}location(){return v(this,void 0,void 0,(function*(){var e,t,i,o,n,r;const s=yield this.controller.getVehicleHttpService();try{const a=null===(e=this.updateRates(yield s.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/park`)).body.resMsg)||void 0===e?void 0:e.gpsDetail;return this._location={latitude:null===(t=null==a?void 0:a.coord)||void 0===t?void 0:t.lat,longitude:null===(i=null==a?void 0:a.coord)||void 0===i?void 0:i.lon,altitude:null===(o=null==a?void 0:a.coord)||void 0===o?void 0:o.alt,speed:{unit:null===(n=null==a?void 0:a.speed)||void 0===n?void 0:n.unit,value:null===(r=null==a?void 0:a.speed)||void 0===r?void 0:r.value},heading:null==a?void 0:a.head},this._location}catch(e){throw q(e,"AustraliaVehicle.location")}}))}startCharge(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"start",deviceId:this.controller.session.deviceId}})).statusCode)return k.debug(`Send start charge command to Vehicle ${this.vehicleConfig.id}`),"Start charge successful";throw"Something went wrong!"}catch(e){throw q(e,"AustraliaVehicle.startCharge")}}))}stopCharge(){return v(this,void 0,void 0,(function*(){const e=yield this.controller.getVehicleHttpService();try{if(200===this.updateRates(yield e.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/control/charge`,{body:{action:"stop",deviceId:this.controller.session.deviceId}})).statusCode)return k.debug(`Send stop charge command to Vehicle ${this.vehicleConfig.id}`),"Stop charge successful";throw"Something went wrong!"}catch(e){throw q(e,"AustraliaVehicle.stopCharge")}}))}monthlyReport(){return v(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){var t,i,o,n,r,s,a,d,l,c,h;const u=yield this.controller.getVehicleHttpService();try{const v=null===(t=this.updateRates(yield u.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/monthlyreport`,{body:{setRptMonth:Ie(e)}})).body.resMsg)||void 0===t?void 0:t.monthlyReport;return v?{start:null===(i=v.ifo)||void 0===i?void 0:i.mvrMonthStart,end:null===(o=v.ifo)||void 0===o?void 0:o.mvrMonthEnd,breakdown:v.breakdown,driving:v.driving?{distance:null===(n=v.driving)||void 0===n?void 0:n.runDistance,startCount:null===(r=v.driving)||void 0===r?void 0:r.engineStartCount,durations:{idle:null===(s=v.driving)||void 0===s?void 0:s.engineIdleTime,drive:null===(a=v.driving)||void 0===a?void 0:a.engineOnTime}}:void 0,vehicleStatus:v.vehicleStatus?{tpms:(null===(d=v.vehicleStatus)||void 0===d?void 0:d.tpmsSupport)?Boolean(null===(l=v.vehicleStatus)||void 0===l?void 0:l.tpmsSupport):void 0,tirePressure:{all:"1"==(null===(h=null===(c=v.vehicleStatus)||void 0===c?void 0:c.tirePressure)||void 0===h?void 0:h.tirePressureLampAll)}}:void 0}:void 0}catch(e){throw q(e,"AustraliaVehicle.monthyReports")}}))}tripInfo(){return v(this,arguments,void 0,(function*(e={year:(new Date).getFullYear(),month:(new Date).getMonth()+1}){const t=yield this.controller.getApiHttpService();try{const i=Boolean(e.day),o=this.updateRates(yield t.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/tripinfo`,{body:{setTripLatest:10,setTripMonth:i?void 0:Ie(e),setTripDay:i?Ee(e):void 0,tripPeriodType:i?1:0}}));if(!i){const e=o.body.resMsg;return{days:Array.isArray(null==e?void 0:e.tripDayList)?null==e?void 0:e.tripDayList.map((e=>({dayRaw:e.tripDayInMonth,date:e.tripDayInMonth?se(e.tripDayInMonth):void 0,tripsCount:e.tripCntDay}))):[],durations:{drive:null==e?void 0:e.tripDrvTime,idle:null==e?void 0:e.tripIdleTime},distance:null==e?void 0:e.tripDist,speed:{avg:null==e?void 0:e.tripAvgSpeed,max:null==e?void 0:e.tripMaxSpeed}}}{const e=o.body.resMsg.dayTripList;if(e&&Array.isArray(e))return e.map((e=>({dayRaw:e.tripDay,tripsCount:e.dayTripCnt,distance:e.tripDist,durations:{drive:e.tripDrvTime,idle:e.tripIdleTime},speed:{avg:e.tripAvgSpeed,max:e.tripMaxSpeed},trips:Array.isArray(e.tripList)?e.tripList.map((t=>{const i=se(`${e.tripDay}${t.tripTime}`);return{timeRaw:t.tripTime,start:i,end:ae(i,t.tripDrvTime),durations:{drive:t.tripDrvTime,idle:t.tripIdleTime},speed:{avg:t.tripAvgSpeed,max:t.tripMaxSpeed},distance:t.tripDist}})):[]})))}return}catch(e){throw q(e,"AustraliaVehicle.history")}}))}driveHistory(){return v(this,arguments,void 0,(function*(e=de.DAY){var t,i;const o=yield this.controller.getApiHttpService();try{const n=yield o.post(`/api/v1/spa/vehicles/${this.vehicleConfig.id}/drvhistory`,{body:{periodTarget:e}});return{cumulated:null===(t=n.body.resMsg.drivingInfo)||void 0===t?void 0:t.map((e=>({period:e.drivingPeriod,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo}))),history:null===(i=n.body.resMsg.drivingInfoDetail)||void 0===i?void 0:i.map((e=>({period:e.drivingPeriod,rawDate:e.drivingDate,date:e.drivingDate?se(e.drivingDate):void 0,consumption:{total:e.totalPwrCsp,engine:e.motorPwrCsp,climate:e.climatePwrCsp,devices:e.eDPwrCsp,battery:e.batteryMgPwrCsp},regen:e.regenPwr,distance:e.calculativeOdo})))}}catch(e){throw q(e,"AustraliaVehicle.history")}}))}getChargeTargets(){return v(this,void 0,void 0,(function*(){var e;const t=yield this.controller.getVehicleHttpService();try{const i=null===(e=this.updateRates(yield t.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`)).body.resMsg)||void 0===e?void 0:e.targetSOClist;return i&&Array.isArray(i)?i.map((e=>{var t,i;return{distance:null===(i=null===(t=e.drvDistance)||void 0===t?void 0:t.distanceType)||void 0===i?void 0:i.distanceValue,targetLevel:e.targetSOClevel,type:e.plugType}})):void 0}catch(e){throw q(e,"AustraliaVehicle.getChargeTargets")}}))}setChargeTargets(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();if(!z.includes(e.fast)||!z.includes(e.slow))throw new G(`Charge target values are limited to ${z.join(", ")}`);try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/charge/target`,{body:{targetSOClist:[{plugType:ee.FAST,targetSOClevel:e.fast},{plugType:ee.SLOW,targetSOClevel:e.slow}]}}))}catch(e){throw q(e,"AustraliaVehicle.setChargeTargets")}}))}setNavigation(e){return v(this,void 0,void 0,(function*(){const t=yield this.controller.getVehicleHttpService();try{this.updateRates(yield t.post(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location/routes`,{body:{deviceID:this.controller.session.deviceId,poiInfoList:e}}))}catch(e){throw q(e,"AustraliaVehicle.setNavigation")}}))}updateRates(e){var t,i,o,n,r;return(null===(t=e.headers)||void 0===t?void 0:t["x-ratelimit-limit"])&&(this.serverRates.max=Number(null===(i=e.headers)||void 0===i?void 0:i["x-ratelimit-limit"]),this.serverRates.current=Number(null===(o=e.headers)||void 0===o?void 0:o["x-ratelimit-remaining"]),(null===(n=e.headers)||void 0===n?void 0:n["x-ratelimit-reset"])&&(this.serverRates.reset=new Date(Number(`${null===(r=e.headers)||void 0===r?void 0:r["x-ratelimit-reset"]}000`))),this.serverRates.updatedAt=new Date),e}}function Ie(e){return`${e.year}${e.month.toString().padStart(2,"0")}`}function Ee(e){return e.day?`${Ie(e)}${e.day.toString().padStart(2,"0")}`:Ie(e)}class Le{constructor(e){this.environment=e}get name(){return"AustraliaAuthStrategy"}login(t,i){return v(this,void 0,void 0,(function*(){var o;const n=null!==(o=null==i?void 0:i.cookieJar)&&void 0!==o?o:new d;yield e(this.environment.endpoints.session,{cookieJar:n});const{body:r,statusCode:a}=yield e(this.environment.endpoints.login,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify({email:t.username,password:t.password,mobileNum:""}),cookieJar:n}),l=JSON.parse(r);if(!l.redirectUrl)throw new Error(`@AustraliaAuthStrategy.login: sign In didn't work, could not retrieve auth code. status: ${a}, body: ${JSON.stringify(l)}`);const{code:c}=s.parse(l.redirectUrl,!0).query;if(!c)throw new Error("@AustraliaAuthStrategy.login: AuthCode was not found, you probably need to migrate your account.");return{code:c,cookies:n}}))}}class Me extends W{constructor(e){super(e),this.session={accessToken:void 0,refreshToken:void 0,controlToken:void 0,deviceId:K(),tokenExpiresAt:0,controlTokenExpiresAt:0},this.vehicles=[],this.session.deviceId=K(),this._environment=N(e),this.authStrategy=new Le(this._environment),k.debug("AU Controller created")}get environment(){return this._environment}refreshAccessToken(){return v(this,void 0,void 0,(function*(){const t=Math.floor(Date.now()/1e3-this.session.tokenExpiresAt)>=-10;if(!this.session.refreshToken)return k.debug("Need refresh token to refresh access token. Use login()"),"Need refresh token to refresh access token. Use login()";if(!t)return k.debug("Token not expired, no need to refresh"),"Token not expired, no need to refresh";const i=new a;i.append("grant_type","refresh_token"),i.append("redirect_uri","https://www.getpostman.com/oauth2/callback"),i.append("refresh_token",this.session.refreshToken);try{const t=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0"},body:i.toString(),throwHttpErrors:!1});if(200!==t.statusCode)return k.debug(`Refresh token failed: ${t.body}`),`Refresh token failed: ${t.body}`;const o=JSON.parse(t.body);this.session.accessToken="Bearer "+o.access_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+o.expires_in)}catch(e){throw q(e,"AustraliaController.refreshAccessToken")}return k.debug("Token refreshed"),"Token refreshed"}))}enterPin(){return v(this,void 0,void 0,(function*(){if(""===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/user/pin`,{method:"PUT",headers:{Authorization:this.session.accessToken,"Content-Type":"application/json"},body:{deviceId:this.session.deviceId,pin:this.userConfig.pin},json:!0});return this.session.controlToken="Bearer "+t.body.controlToken,this.session.controlTokenExpiresAt=Math.floor(Date.now()/1e3+t.body.expiresTime),"PIN entered OK, The pin is valid for 10 minutes"}catch(e){throw q(e,"AustraliaController.pin")}}))}login(){return v(this,void 0,void 0,(function*(){try{if(!this.userConfig.password||!this.userConfig.username)throw new Error("@AustraliaController.login: username and password must be defined.");let t=null;try{k.debug(`@AustraliaController.login: Trying to sign in with ${this.authStrategy.name}`),t=yield this.authStrategy.login({password:this.userConfig.password,username:this.userConfig.username})}catch(e){throw new Error(`@AustraliaController.login: sign in with ${this.authStrategy.name} failed with error ${e.toString()}`)}k.debug("@AustraliaController.login: Authenticated properly with user and password");const i=e=>[...Array(e)].map((()=>Math.floor(16*Math.random()).toString(16))).join(""),o=yield e(`${this.environment.baseUrl}/api/v1/spa/notifications/register`,{method:"POST",headers:{"ccsp-service-id":this.environment.clientId,"Content-Type":"application/json;charset=UTF-8",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:{pushRegId:i(64),pushType:"GCM",uuid:this.session.deviceId},json:!0});o&&(this.session.deviceId=o.body.resMsg.deviceId),k.debug("@AustraliaController.login: Device registered");const n=new a;n.append("grant_type","authorization_code"),n.append("redirect_uri",this.environment.endpoints.redirectUri),n.append("code",t.code);const r=yield e(this.environment.endpoints.token,{method:"POST",headers:{Authorization:this.environment.basicToken,"Content-Type":"application/x-www-form-urlencoded",Host:this.environment.host,Connection:"Keep-Alive","Accept-Encoding":"gzip","User-Agent":"okhttp/3.10.0",grant_type:"authorization_code","ccsp-application-id":this.environment.appId,Stamp:yield this.environment.stamp()},body:n.toString(),cookieJar:t.cookies});if(200!==r.statusCode)throw new Error(`@AustraliaController.login: Could not manage to get token: ${r.body}`);if(r){const e=JSON.parse(r.body);this.session.accessToken=`Bearer ${e.access_token}`,this.session.refreshToken=e.refresh_token,this.session.tokenExpiresAt=Math.floor(Date.now()/1e3+e.expires_in)}return k.debug("@AustraliaController.login: Session defined properly"),"Login success"}catch(e){throw q(e,"AustraliaController.login")}}))}logout(){return v(this,void 0,void 0,(function*(){return"OK"}))}getVehicles(){return v(this,void 0,void 0,(function*(){if(void 0===this.session.accessToken)throw"Token not set";try{const t=yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0});this.vehicles=yield Z(t.body.resMsg.vehicles,(t=>v(this,void 0,void 0,(function*(){const i=(yield e(`${this.environment.baseUrl}/api/v1/spa/vehicles/${t.vehicleId}/profile`,{method:"GET",headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})).body.resMsg,o={nickname:t.nickname,name:t.vehicleName,regDate:t.regDate,brandIndicator:"H",id:t.vehicleId,vin:i.vinInfo[0].basic.vin,generation:i.vinInfo[0].basic.modelYear};return k.debug(`@AustraliaController.getVehicles: Added vehicle ${o.id}`),new De(o,this)}))))}catch(e){throw q(e,"AustraliaController.getVehicles")}return this.vehicles}))}checkControlToken(){return v(this,void 0,void 0,(function*(){var e;yield this.refreshAccessToken(),void 0!==(null===(e=this.session)||void 0===e?void 0:e.controlTokenExpiresAt)&&(!this.session.controlToken||Date.now()/1e3>this.session.controlTokenExpiresAt)&&(yield this.enterPin())}))}getVehicleHttpService(){return v(this,void 0,void 0,(function*(){return yield this.checkControlToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Authorization:this.session.controlToken,Stamp:yield this.environment.stamp()}),json:!0})}))}getApiHttpService(){return v(this,void 0,void 0,(function*(){return yield this.refreshAccessToken(),e.extend({baseUrl:this.environment.baseUrl,headers:Object.assign(Object.assign({},this.defaultHeaders),{Stamp:yield this.environment.stamp()}),json:!0})}))}get defaultHeaders(){return{Authorization:this.session.accessToken,offset:((new Date).getTimezoneOffset()/60).toFixed(2),"ccsp-device-id":this.session.deviceId,"ccsp-application-id":this.environment.appId,"Content-Type":"application/json"}}}const Pe={username:"",password:"",region:F.US,brand:"hyundai",autoLogin:!0,pin:"1234",vin:"",vehicleId:void 0};class Re extends u{constructor(e){switch(super(),this.vehicles=[],this.config=Object.assign(Object.assign({},Pe),e),e.region){case F.EU:this.controller=new ye(this.config);break;case F.US:this.controller=new Q(this.config);break;case F.CA:this.controller=new Ce(this.config);break;case F.CN:this.controller=new $e(this.config);break;case F.AU:this.controller=new Me(this.config);break;default:throw new Error("Your region is not supported yet.")}void 0===e.autoLogin&&(this.config.autoLogin=!0),this.onInit()}on(e,t){return super.on(e,t)}onInit(){this.config.autoLogin&&(k.debug("Bluelinky is logging in automatically, to disable use autoLogin: false"),this.login())}login(){return v(this,void 0,void 0,(function*(){try{const e=yield this.controller.login();return this.vehicles=yield this.getVehicles(),k.debug(`Found ${this.vehicles.length} on the account`),this.emit("ready",this.vehicles),e}catch(e){return this.emit("error",e),e.message}}))}getVehicles(){return v(this,void 0,void 0,(function*(){return(yield this.controller.getVehicles())||[]}))}getVehicle(e){try{const t=this.vehicles.find((t=>t.vin().toLowerCase()===e.toLowerCase()));if(!t&&this.vehicles.length>0)throw new Error(`Could not find vehicle with id: ${e}`);return t}catch(t){throw new Error(`Vehicle not found: ${e}!`)}}refreshAccessToken(){return v(this,void 0,void 0,(function*(){return this.controller.refreshAccessToken()}))}logout(){return v(this,void 0,void 0,(function*(){return this.controller.logout()}))}getSession(){return this.controller.session}get cachedVehicles(){var e;return null!==(e=this.vehicles)&&void 0!==e?e:[]}}export{Re as BlueLinky,Re as default};
diff --git a/dist/interfaces/american.interfaces.d.ts b/dist/interfaces/american.interfaces.d.ts
new file mode 100644
index 0000000..0719e66
--- /dev/null
+++ b/dist/interfaces/american.interfaces.d.ts
@@ -0,0 +1,49 @@
+import BlueLinky from '../index';
+export interface HyundaiResponse {
+ status: string;
+ result: any;
+ errorMessage: string;
+}
+export interface TokenResponse {
+ access_token: string;
+ refresh_token: string;
+ expires_in: string;
+ username: string;
+}
+export interface VehicleConfig {
+ vin: string | null;
+ pin: string | null;
+ token: string | null;
+ bluelinky: BlueLinky;
+}
+export interface AmericanEndpoints {
+ getToken: string;
+ validateToken: string;
+ auth: string;
+ remoteAction: string;
+ usageStats: string;
+ health: string;
+ messageCenter: string;
+ myAccount: string;
+ status: string;
+ enrollmentStatus: string;
+ subscriptions: string;
+}
+export interface RequestHeaders {
+ 'access_token': string | undefined;
+ 'client_id': string;
+ 'Host': string;
+ 'User-Agent': string;
+ 'registrationId': string;
+ 'gen': string;
+ 'username': string | undefined;
+ 'vin': string;
+ 'APPCLOUD-VIN': string;
+ 'Language': string;
+ 'to': string;
+ 'encryptFlag': string;
+ 'from': string;
+ 'brandIndicator': string;
+ 'bluelinkservicepin': string | undefined;
+ 'offset': string;
+}
diff --git a/dist/interfaces/chinese.interfaces.d.ts b/dist/interfaces/chinese.interfaces.d.ts
new file mode 100644
index 0000000..d1717c1
--- /dev/null
+++ b/dist/interfaces/chinese.interfaces.d.ts
@@ -0,0 +1,49 @@
+export interface ChineseEndpoints {
+ session: string;
+ login: string;
+ redirect_uri: string;
+ token: string;
+}
+export interface CNPOIInformation {
+ phone: string;
+ waypointID: number;
+ lang: 1;
+ src: 'HERE';
+ coord: {
+ lat: number;
+ alt: number;
+ lon: number;
+ type: 0;
+ };
+ addr: string;
+ zip: string;
+ placeid: string;
+ name: string;
+}
+export declare enum historyDrivingPeriod {
+ DAY = 0,
+ MONTH = 1,
+ ALL = 2
+}
+export declare enum historyCumulatedTypes {
+ TOTAL = 0,
+ AVERAGE = 1,
+ TODAY = 2
+}
+export interface CNDriveHistory {
+ period: historyCumulatedTypes;
+ consumption: {
+ total: number;
+ engine: number;
+ climate: number;
+ devices: number;
+ battery: number;
+ };
+ regen: number;
+ distance: number;
+}
+export interface CNDatedDriveHistory extends Omit {
+ period: historyDrivingPeriod;
+ rawDate: string;
+ date: Date;
+}
diff --git a/dist/interfaces/common.interfaces.d.ts b/dist/interfaces/common.interfaces.d.ts
new file mode 100644
index 0000000..5670162
--- /dev/null
+++ b/dist/interfaces/common.interfaces.d.ts
@@ -0,0 +1,447 @@
+import { REGION } from '../constants';
+export type Brand = 'kia' | 'hyundai';
+export interface BlueLinkyConfig {
+ username: string | undefined;
+ password: string | undefined;
+ region: REGION | undefined;
+ brand: Brand;
+ autoLogin?: boolean;
+ pin: string | undefined;
+ vin?: string | undefined;
+ vehicleId?: string | undefined;
+}
+export interface BluelinkVehicle {
+ name: string;
+ vin: string;
+ type: string;
+}
+export interface Session {
+ accessToken?: string;
+ refreshToken?: string;
+ controlToken?: string;
+ deviceId?: string;
+ tokenExpiresAt: number;
+ controlTokenExpiresAt?: number;
+}
+export declare enum EVPlugTypes {
+ UNPLUGED = 0,
+ FAST = 1,
+ PORTABLE = 2,
+ STATION = 3
+}
+export declare enum EVChargeModeTypes {
+ FAST = 0,
+ SLOW = 1
+}
+export interface VehicleStatus {
+ engine: {
+ ignition: boolean;
+ batteryCharge?: number;
+ charging?: boolean;
+ timeToFullCharge?: unknown;
+ range: number;
+ rangeGas?: number;
+ rangeEV?: number;
+ plugedTo?: EVPlugTypes;
+ estimatedCurrentChargeDuration?: number;
+ estimatedFastChargeDuration?: number;
+ estimatedPortableChargeDuration?: number;
+ estimatedStationChargeDuration?: number;
+ batteryCharge12v?: number;
+ batteryChargeHV?: number;
+ accessory: boolean;
+ };
+ climate: {
+ active: boolean;
+ steeringwheelHeat: boolean;
+ sideMirrorHeat: boolean;
+ rearWindowHeat: boolean;
+ temperatureSetpoint: number | string;
+ temperatureUnit: number;
+ defrost: boolean;
+ };
+ chassis: {
+ hoodOpen: boolean;
+ trunkOpen: boolean;
+ locked: boolean;
+ openDoors: {
+ frontRight: boolean;
+ frontLeft: boolean;
+ backLeft: boolean;
+ backRight: boolean;
+ };
+ tirePressureWarningLamp: {
+ rearLeft: boolean;
+ frontLeft: boolean;
+ frontRight: boolean;
+ rearRight: boolean;
+ all: boolean;
+ };
+ };
+ lastupdate: Date | null;
+}
+export interface FullVehicleStatus {
+ vehicleLocation: {
+ coord: {
+ lat: number;
+ lon: number;
+ alt: number;
+ type: number;
+ };
+ head: number;
+ speed: {
+ value: number;
+ unit: number;
+ };
+ accuracy: {
+ hdop: number;
+ pdop: number;
+ };
+ time: string;
+ };
+ odometer: {
+ value: number;
+ unit: number;
+ };
+ vehicleStatus: {
+ time: string;
+ airCtrlOn: boolean;
+ engine: boolean;
+ doorLock: boolean;
+ doorOpen: {
+ frontRight: number;
+ frontLeft: number;
+ backLeft: number;
+ backRight: number;
+ };
+ trunkOpen: boolean;
+ airTemp: {
+ unit: number;
+ hvacTempType: number;
+ value: string;
+ };
+ defrost: boolean;
+ acc: boolean;
+ ign3: boolean;
+ hoodOpen: boolean;
+ transCond: boolean;
+ steerWheelHeat: number;
+ sideBackWindowHeat: number;
+ tirePressureLamp: {
+ tirePressureWarningLampAll: number;
+ tirePressureWarningLampFL: number;
+ tirePressureWarningLampFR: number;
+ tirePressureWarningLampRL: number;
+ tirePressureWarningLampRR: number;
+ };
+ battery: {
+ batSoc: number;
+ batState: number;
+ };
+ evStatus: {
+ batteryCharge: boolean;
+ batteryStatus: number;
+ batteryPlugin: number;
+ remainTime2: {
+ etc1: {
+ value: number;
+ unit: number;
+ };
+ etc2: {
+ value: number;
+ unit: number;
+ };
+ etc3: {
+ value: number;
+ unit: number;
+ };
+ atc: {
+ value: number;
+ unit: number;
+ };
+ };
+ drvDistance: [
+ {
+ rangeByFuel: {
+ gasModeRange: {
+ value: number;
+ unit: number;
+ };
+ evModeRange: {
+ value: number;
+ unit: number;
+ };
+ totalAvailableRange: {
+ value: number;
+ unit: number;
+ };
+ };
+ type: number;
+ }
+ ];
+ };
+ };
+}
+export interface RawVehicleStatus {
+ lastStatusDate: string;
+ dateTime: string;
+ acc: boolean;
+ trunkOpen: boolean;
+ doorLock: boolean;
+ defrostStatus: string;
+ transCond: boolean;
+ doorLockStatus: string;
+ doorOpen: {
+ frontRight: number;
+ frontLeft: number;
+ backLeft: number;
+ backRight: number;
+ };
+ airCtrlOn: boolean;
+ airTempUnit: string;
+ airTemp: {
+ unit: number;
+ hvacTempType: number;
+ value: string;
+ };
+ battery: {
+ batSignalReferenceValue: unknown;
+ batSoc: number;
+ batState: number;
+ sjbDeliveryMode: number;
+ };
+ ign3: boolean;
+ ignitionStatus: string;
+ lowFuelLight: boolean;
+ sideBackWindowHeat: number;
+ dte: {
+ unit: number;
+ value: number;
+ };
+ engine: boolean;
+ defrost: boolean;
+ hoodOpen: boolean;
+ airConditionStatus: string;
+ steerWheelHeat: number;
+ tirePressureLamp: {
+ tirePressureWarningLampRearLeft: number;
+ tirePressureWarningLampFrontLeft: number;
+ tirePressureWarningLampFrontRight: number;
+ tirePressureWarningLampAll: number;
+ tirePressureWarningLampRearRight: number;
+ };
+ trunkOpenStatus: string;
+ evStatus: {
+ batteryCharge: boolean;
+ batteryStatus: number;
+ batteryPlugin: number;
+ remainTime2: {
+ etc1: {
+ value: number;
+ unit: number;
+ };
+ etc2: {
+ value: number;
+ unit: number;
+ };
+ etc3: {
+ value: number;
+ unit: number;
+ };
+ atc: {
+ value: number;
+ unit: number;
+ };
+ };
+ drvDistance: [
+ {
+ rangeByFuel: {
+ gasModeRange: {
+ value: number;
+ unit: number;
+ };
+ evModeRange: {
+ value: number;
+ unit: number;
+ };
+ totalAvailableRange: {
+ value: number;
+ unit: number;
+ };
+ };
+ type: number;
+ }
+ ];
+ };
+ remoteIgnition: boolean;
+ seatHeaterVentInfo: unknown;
+ sleepModeCheck: boolean;
+ lampWireStatus: {
+ headLamp: unknown;
+ stopLamp: unknown;
+ turnSignalLamp: unknown;
+ };
+ windowOpen: unknown;
+ engineRuntime: unknown;
+}
+export interface VehicleInfo {
+ vehicleId: string;
+ nickName: string;
+ modelCode: string;
+ modelName: string;
+ modelYear: string;
+ fuelKindCode: string;
+ trim: string;
+ engine: string;
+ exteriorColor: string;
+ dtcCount: number;
+ subscriptionStatus: string;
+ subscriptionEndDate: string;
+ overviewMessage: string;
+ odometer: number;
+ odometerUnit: number;
+ defaultVehicle: boolean;
+ enrollmentStatus: string;
+ genType: string;
+ transmissionType: string;
+ vin: string;
+}
+export interface VehicleFeatureEntry {
+ category: string;
+ features: [
+ {
+ featureName: string;
+ features: [
+ {
+ subFeatureName: string;
+ subFeatureValue: string;
+ }
+ ];
+ }
+ ];
+}
+export interface VehicleLocation {
+ latitude: number;
+ longitude: number;
+ altitude: number;
+ speed: {
+ unit: number;
+ value: number;
+ };
+ heading: number;
+}
+export interface VehicleOdometer {
+ unit: number;
+ value: number;
+}
+export interface VehicleStatusOptions {
+ refresh: boolean;
+ parsed: boolean;
+ useInfo?: boolean;
+}
+export interface VehicleCommandResponse {
+ responseCode: number;
+ responseDesc: string;
+}
+export interface VehicleStartOptions {
+ hvac: boolean | string;
+ duration: number;
+ temperature: number;
+ defrost: boolean | string;
+ heatedFeatures: boolean | string;
+ unit?: 'C' | 'F';
+}
+export declare enum VehicleWindowState {
+ CLOSED = 0,
+ OPEN = 1,
+ VENTILATION = 2
+}
+export interface VehicleWindowsOptions {
+ backLeft: VehicleWindowState;
+ backRight: VehicleWindowState;
+ frontLeft: VehicleWindowState;
+ frontRight: VehicleWindowState;
+}
+export interface VehicleRegisterOptions {
+ nickname: string;
+ name: string;
+ vin: string;
+ regDate: string;
+ brandIndicator: string;
+ regId: string;
+ id: string;
+ generation: string;
+}
+export type DeepPartial = {
+ [P in keyof T]?: DeepPartial;
+};
+export interface VehicleMonthlyReport {
+ start: string;
+ end: string;
+ driving: {
+ distance: number;
+ startCount: number;
+ durations: {
+ drive: number;
+ idle: number;
+ };
+ };
+ breakdown: {
+ ecuIdx: string;
+ ecuStatus: string;
+ }[];
+ vehicleStatus: {
+ tpms: boolean;
+ tirePressure: {
+ all: boolean;
+ };
+ };
+}
+export interface VehicleTargetSOC {
+ type: EVChargeModeTypes;
+ distance: number;
+ targetLevel: number;
+}
+export interface VehicleMonthTrip {
+ days: Array<{
+ dayRaw: string;
+ date?: Date;
+ tripsCount: number;
+ }>;
+ durations: {
+ drive: number;
+ idle: number;
+ };
+ speed: {
+ avg: number;
+ max: number;
+ };
+ distance: number;
+}
+export interface VehicleDayTrip {
+ dayRaw: string;
+ tripsCount: number;
+ distance: number;
+ durations: {
+ drive: number;
+ idle: number;
+ };
+ speed: {
+ avg: number;
+ max: number;
+ };
+ trips: {
+ timeRaw: string;
+ start: Date;
+ end: Date;
+ durations: {
+ drive: number;
+ idle: number;
+ };
+ speed: {
+ avg: number;
+ max: number;
+ };
+ distance: number;
+ }[];
+}
diff --git a/dist/interfaces/european.interfaces.d.ts b/dist/interfaces/european.interfaces.d.ts
new file mode 100644
index 0000000..dc97952
--- /dev/null
+++ b/dist/interfaces/european.interfaces.d.ts
@@ -0,0 +1,49 @@
+export interface EuropeanEndpoints {
+ session: string;
+ login: string;
+ redirect_uri: string;
+ token: string;
+}
+export interface EUPOIInformation {
+ phone: string;
+ waypointID: number;
+ lang: 1;
+ src: 'HERE';
+ coord: {
+ lat: number;
+ alt: number;
+ lon: number;
+ type: 0;
+ };
+ addr: string;
+ zip: string;
+ placeid: string;
+ name: string;
+}
+export declare enum historyDrivingPeriod {
+ DAY = 0,
+ MONTH = 1,
+ ALL = 2
+}
+export declare enum historyCumulatedTypes {
+ TOTAL = 0,
+ AVERAGE = 1,
+ TODAY = 2
+}
+export interface EUDriveHistory {
+ period: historyCumulatedTypes;
+ consumption: {
+ total: number;
+ engine: number;
+ climate: number;
+ devices: number;
+ battery: number;
+ };
+ regen: number;
+ distance: number;
+}
+export interface EUDatedDriveHistory extends Omit {
+ period: historyDrivingPeriod;
+ rawDate: string;
+ date: Date;
+}
diff --git a/dist/logger.d.ts b/dist/logger.d.ts
new file mode 100644
index 0000000..1f1e62e
--- /dev/null
+++ b/dist/logger.d.ts
@@ -0,0 +1,3 @@
+import * as winston from 'winston';
+declare const logger: winston.Logger;
+export default logger;
diff --git a/dist/tools/common.tools.d.ts b/dist/tools/common.tools.d.ts
new file mode 100644
index 0000000..9603817
--- /dev/null
+++ b/dist/tools/common.tools.d.ts
@@ -0,0 +1,11 @@
+export declare class ManagedBluelinkyError extends Error {
+ readonly source?: Error | undefined;
+ static ErrorName: string;
+ constructor(message: string, source?: Error | undefined);
+}
+export interface Stringifiable {
+ toString(): string;
+}
+export declare const manageBluelinkyError: (err: unknown, context?: string) => unknown | Error | ManagedBluelinkyError;
+export declare const asyncMap: (array: T[], callback: (item: T, i: number, items: T[]) => Promise) => Promise;
+export declare const uuidV4: () => string;
diff --git a/dist/util.d.ts b/dist/util.d.ts
new file mode 100644
index 0000000..c3f41fd
--- /dev/null
+++ b/dist/util.d.ts
@@ -0,0 +1,16 @@
+import { REGION } from './constants';
+export declare const celciusToTempCode: (region: REGION, temperature: number) => string;
+export declare const tempCodeToCelsius: (region: REGION, code: string) => number;
+/**
+ * Parses an API date string
+ * @param str the date in yyyyMMdd or yyyyMMddHHmmss format
+ * @returns The parsed date
+ */
+export declare const parseDate: (str: string) => Date;
+/**
+ * Adds a certain amount of minutes to a date
+ * @param date The date to adds minutes to
+ * @param minutes The number of minutes to add
+ * @returns The updated date
+ */
+export declare const addMinutes: (date: Date, minutes: number) => Date;
diff --git a/dist/vehicles/american.vehicle.d.ts b/dist/vehicles/american.vehicle.d.ts
new file mode 100644
index 0000000..f97ceb8
--- /dev/null
+++ b/dist/vehicles/american.vehicle.d.ts
@@ -0,0 +1,25 @@
+import { REGIONS } from '../constants';
+import { VehicleStartOptions, VehicleStatus, VehicleLocation, VehicleRegisterOptions, VehicleOdometer, RawVehicleStatus, VehicleStatusOptions, FullVehicleStatus } from '../interfaces/common.interfaces';
+import { Vehicle } from './vehicle';
+import { AmericanController } from '../controllers/american.controller';
+export default class AmericanVehicle extends Vehicle {
+ vehicleConfig: VehicleRegisterOptions;
+ controller: AmericanController;
+ region: REGIONS;
+ constructor(vehicleConfig: VehicleRegisterOptions, controller: AmericanController);
+ private getDefaultHeaders;
+ fullStatus(): Promise;
+ odometer(): Promise;
+ /**
+ * This is seems to always poll the modem directly, no caching
+ */
+ location(): Promise;
+ start(startConfig: VehicleStartOptions): Promise;
+ stop(): Promise;
+ status(input: VehicleStatusOptions): Promise;
+ unlock(): Promise;
+ lock(): Promise;
+ startCharge(): Promise;
+ stopCharge(): Promise;
+ private _request;
+}
diff --git a/dist/vehicles/australia.vehicle.d.ts b/dist/vehicles/australia.vehicle.d.ts
new file mode 100644
index 0000000..4ce8f99
--- /dev/null
+++ b/dist/vehicles/australia.vehicle.d.ts
@@ -0,0 +1,68 @@
+import { ChargeTarget, REGIONS } from '../constants';
+import { DeepPartial, FullVehicleStatus, RawVehicleStatus, VehicleDayTrip, VehicleLocation, VehicleMonthTrip, VehicleMonthlyReport, VehicleOdometer, VehicleRegisterOptions, VehicleStartOptions, VehicleStatus, VehicleStatusOptions, VehicleTargetSOC, VehicleWindowsOptions } from '../interfaces/common.interfaces';
+import { AustraliaController } from '../controllers/australia.controller';
+import { EUDatedDriveHistory, EUDriveHistory, EUPOIInformation, historyDrivingPeriod } from '../interfaces/european.interfaces';
+import { Vehicle } from './vehicle';
+export default class AustraliaVehicle extends Vehicle {
+ vehicleConfig: VehicleRegisterOptions;
+ controller: AustraliaController;
+ region: REGIONS;
+ serverRates: {
+ max: number;
+ current: number;
+ reset?: Date;
+ updatedAt?: Date;
+ };
+ constructor(vehicleConfig: VehicleRegisterOptions, controller: AustraliaController);
+ /**
+ *
+ * @param config - Vehicle start configuration for the request
+ * @returns Promise
+ * @remarks - not sure if this supports starting ICE vehicles
+ */
+ start(config: VehicleStartOptions): Promise;
+ stop(): Promise;
+ lock(): Promise;
+ unlock(): Promise;
+ setWindows(config: VehicleWindowsOptions): Promise;
+ fullStatus(input: VehicleStatusOptions): Promise;
+ status(input: VehicleStatusOptions): Promise;
+ odometer(): Promise;
+ location(): Promise;
+ startCharge(): Promise;
+ stopCharge(): Promise;
+ monthlyReport(month?: {
+ year: number;
+ month: number;
+ }): Promise | undefined>;
+ tripInfo(date: {
+ year: number;
+ month: number;
+ day: number;
+ }): Promise[] | undefined>;
+ tripInfo(date?: {
+ year: number;
+ month: number;
+ }): Promise | undefined>;
+ driveHistory(period?: historyDrivingPeriod): Promise>;
+ /**
+ * Warning: Only works on EV
+ */
+ getChargeTargets(): Promise[] | undefined>;
+ /**
+ * Warning: Only works on EV
+ */
+ setChargeTargets(limits: {
+ fast: ChargeTarget;
+ slow: ChargeTarget;
+ }): Promise;
+ /**
+ * Define a navigation route
+ * @param poiInformations The list of POIs and waypoint to go through
+ */
+ setNavigation(poiInformations: EUPOIInformation[]): Promise;
+ private updateRates;
+}
diff --git a/dist/vehicles/canadian.vehicle.d.ts b/dist/vehicles/canadian.vehicle.d.ts
new file mode 100644
index 0000000..fb81c74
--- /dev/null
+++ b/dist/vehicles/canadian.vehicle.d.ts
@@ -0,0 +1,61 @@
+import { REGIONS, ChargeTarget } from '../constants';
+import { VehicleStartOptions, VehicleLocation, VehicleRegisterOptions, VehicleStatus, VehicleOdometer, VehicleStatusOptions, RawVehicleStatus, FullVehicleStatus, VehicleInfo, VehicleFeatureEntry } from '../interfaces/common.interfaces';
+import { Vehicle } from './vehicle';
+import { CanadianController } from '../controllers/canadian.controller';
+export interface CanadianInfo {
+ vehicle: VehicleInfo;
+ features: {
+ seatHeatVent: {
+ drvSeatHeatOption: number;
+ astSeatHeatOption: number;
+ rlSeatHeatOption: number;
+ rrSeatHeatOption: number;
+ };
+ hvacTempType: number;
+ targetMinSoc: number;
+ strgWhlHeatingOption: number;
+ };
+ featuresModel: {
+ features: [VehicleFeatureEntry];
+ };
+ status: RawVehicleStatus;
+}
+export default class CanadianVehicle extends Vehicle {
+ vehicleConfig: VehicleRegisterOptions;
+ controller: CanadianController;
+ region: REGIONS;
+ private timeOffset;
+ private _info;
+ constructor(vehicleConfig: VehicleRegisterOptions, controller: CanadianController);
+ fullStatus(): Promise;
+ status(input: VehicleStatusOptions): Promise;
+ lock(): Promise;
+ unlock(): Promise;
+ start(startConfig: VehicleStartOptions): Promise;
+ stop(): Promise;
+ lights(withHorn?: boolean): Promise;
+ /**
+ * Warning only works on EV vehicles
+ * @returns
+ */
+ stopCharge(): Promise;
+ /**
+ * Warning only works on EV vehicles
+ * @returns
+ */
+ startCharge(): Promise;
+ /**
+ * Warning only works on EV vehicles
+ * @param limits
+ * @returns Promise
+ */
+ setChargeTargets(limits: {
+ fast: ChargeTarget;
+ slow: ChargeTarget;
+ }): Promise;
+ odometer(): Promise;
+ location(): Promise;
+ private getPreAuth;
+ private request;
+ private setInfo;
+}
diff --git a/dist/vehicles/chinese.vehicle.d.ts b/dist/vehicles/chinese.vehicle.d.ts
new file mode 100644
index 0000000..4146d59
--- /dev/null
+++ b/dist/vehicles/chinese.vehicle.d.ts
@@ -0,0 +1,67 @@
+import { REGIONS, ChargeTarget } from '../constants';
+import { VehicleStatus, FullVehicleStatus, VehicleOdometer, VehicleLocation, VehicleRegisterOptions, VehicleStatusOptions, RawVehicleStatus, VehicleMonthlyReport, DeepPartial, VehicleTargetSOC, VehicleDayTrip, VehicleMonthTrip, VehicleStartOptions } from '../interfaces/common.interfaces';
+import { Vehicle } from './vehicle';
+import { ChineseController } from '../controllers/chinese.controller';
+import { CNDatedDriveHistory, CNDriveHistory, CNPOIInformation, historyDrivingPeriod } from '../interfaces/chinese.interfaces';
+export default class ChineseVehicle extends Vehicle {
+ vehicleConfig: VehicleRegisterOptions;
+ controller: ChineseController;
+ region: REGIONS;
+ serverRates: {
+ max: number;
+ current: number;
+ reset?: Date;
+ updatedAt?: Date;
+ };
+ constructor(vehicleConfig: VehicleRegisterOptions, controller: ChineseController);
+ /**
+ *
+ * @param config - Vehicle start configuration for the request
+ * @returns Promise
+ * @remarks - not sure if this supports starting ICE vehicles
+ */
+ start(config: VehicleStartOptions): Promise;
+ stop(): Promise;
+ lock(): Promise;
+ unlock(): Promise;
+ fullStatus(input: VehicleStatusOptions): Promise;
+ status(input: VehicleStatusOptions): Promise;
+ odometer(): Promise;
+ location(): Promise;
+ startCharge(): Promise;
+ stopCharge(): Promise;
+ monthlyReport(month?: {
+ year: number;
+ month: number;
+ }): Promise | undefined>;
+ tripInfo(date: {
+ year: number;
+ month: number;
+ day: number;
+ }): Promise[] | undefined>;
+ tripInfo(date?: {
+ year: number;
+ month: number;
+ }): Promise | undefined>;
+ driveHistory(period?: historyDrivingPeriod): Promise>;
+ /**
+ * Warning: Only works on EV
+ */
+ getChargeTargets(): Promise[] | undefined>;
+ /**
+ * Warning: Only works on EV
+ */
+ setChargeTargets(limits: {
+ fast: ChargeTarget;
+ slow: ChargeTarget;
+ }): Promise;
+ /**
+ * Define a navigation route
+ * @param poiInformations The list of POIs and waypoint to go through
+ */
+ setNavigation(poiInformations: CNPOIInformation[]): Promise;
+ private updateRates;
+}
diff --git a/dist/vehicles/european.vehicle.d.ts b/dist/vehicles/european.vehicle.d.ts
new file mode 100644
index 0000000..3f4eade
--- /dev/null
+++ b/dist/vehicles/european.vehicle.d.ts
@@ -0,0 +1,67 @@
+import { REGIONS, ChargeTarget } from '../constants';
+import { VehicleStatus, FullVehicleStatus, VehicleOdometer, VehicleLocation, VehicleRegisterOptions, VehicleStatusOptions, RawVehicleStatus, VehicleMonthlyReport, DeepPartial, VehicleTargetSOC, VehicleDayTrip, VehicleMonthTrip, VehicleStartOptions } from '../interfaces/common.interfaces';
+import { Vehicle } from './vehicle';
+import { EuropeanController } from '../controllers/european.controller';
+import { EUDatedDriveHistory, EUDriveHistory, EUPOIInformation, historyDrivingPeriod } from '../interfaces/european.interfaces';
+export default class EuropeanVehicle extends Vehicle {
+ vehicleConfig: VehicleRegisterOptions;
+ controller: EuropeanController;
+ region: REGIONS;
+ serverRates: {
+ max: number;
+ current: number;
+ reset?: Date;
+ updatedAt?: Date;
+ };
+ constructor(vehicleConfig: VehicleRegisterOptions, controller: EuropeanController);
+ /**
+ *
+ * @param config - Vehicle start configuration for the request
+ * @returns Promise
+ * @remarks - not sure if this supports starting ICE vehicles
+ */
+ start(config: VehicleStartOptions): Promise;
+ stop(): Promise;
+ lock(): Promise;
+ unlock(): Promise;
+ fullStatus(input: VehicleStatusOptions): Promise;
+ status(input: VehicleStatusOptions): Promise;
+ odometer(): Promise;
+ location(): Promise;
+ startCharge(): Promise;
+ stopCharge(): Promise;
+ monthlyReport(month?: {
+ year: number;
+ month: number;
+ }): Promise | undefined>;
+ tripInfo(date: {
+ year: number;
+ month: number;
+ day: number;
+ }): Promise[] | undefined>;
+ tripInfo(date?: {
+ year: number;
+ month: number;
+ }): Promise | undefined>;
+ driveHistory(period?: historyDrivingPeriod): Promise>;
+ /**
+ * Warning: Only works on EV
+ */
+ getChargeTargets(): Promise[] | undefined>;
+ /**
+ * Warning: Only works on EV
+ */
+ setChargeTargets(limits: {
+ fast: ChargeTarget;
+ slow: ChargeTarget;
+ }): Promise;
+ /**
+ * Define a navigation route
+ * @param poiInformations The list of POIs and waypoint to go through
+ */
+ setNavigation(poiInformations: EUPOIInformation[]): Promise;
+ private updateRates;
+}
diff --git a/dist/vehicles/vehicle.d.ts b/dist/vehicles/vehicle.d.ts
new file mode 100644
index 0000000..17d0cb8
--- /dev/null
+++ b/dist/vehicles/vehicle.d.ts
@@ -0,0 +1,26 @@
+import { VehicleStatus, FullVehicleStatus, VehicleLocation, VehicleOdometer, VehicleRegisterOptions } from '../interfaces/common.interfaces';
+import { VehicleStartOptions, BlueLinkyConfig, RawVehicleStatus, VehicleStatusOptions } from '../interfaces/common.interfaces';
+import { SessionController } from '../controllers/controller';
+export declare abstract class Vehicle {
+ vehicleConfig: VehicleRegisterOptions;
+ controller: SessionController;
+ abstract status(input: VehicleStatusOptions): Promise;
+ abstract fullStatus(input: VehicleStatusOptions): Promise;
+ abstract unlock(): Promise;
+ abstract lock(): Promise;
+ abstract start(config: VehicleStartOptions): Promise;
+ abstract stop(): Promise;
+ abstract location(): Promise;
+ abstract odometer(): Promise;
+ _fullStatus: FullVehicleStatus | null;
+ _status: VehicleStatus | RawVehicleStatus | null;
+ _location: VehicleLocation | null;
+ _odometer: VehicleOdometer | null;
+ userConfig: BlueLinkyConfig;
+ constructor(vehicleConfig: VehicleRegisterOptions, controller: SessionController);
+ vin(): string;
+ name(): string;
+ nickname(): string;
+ id(): string;
+ brandIndicator(): string;
+}
diff --git a/src/vehicles/european.vehicle.ts b/src/vehicles/european.vehicle.ts
index d1f9ca4..d8689eb 100644
--- a/src/vehicles/european.vehicle.ts
+++ b/src/vehicles/european.vehicle.ts
@@ -165,6 +165,14 @@ export default class EuropeanVehicle extends Vehicle {
const fullStatus = cachedResponse.body.resMsg.vehicleStatusInfo;
+ const ccs2Response = this.updateRates(
+ await http.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/ccs2/carstatus/latest`)
+ );
+
+ if (ccs2Response.body.resMsg.state.Vehicle != null) {
+ fullStatus.ccs2Status = ccs2Response.body.resMsg;
+ }
+
if (statusConfig.refresh) {
const statusResponse = this.updateRates(
await http.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status`)
@@ -174,7 +182,7 @@ export default class EuropeanVehicle extends Vehicle {
const locationResponse = this.updateRates(
await http.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/location`)
);
- fullStatus.vehicleLocation = locationResponse.body.resMsg.gpsDetail;
+ fullStatus.vehicleLocation = locationResponse.body.resMsg.gpsDetail;
}
this._fullStatus = fullStatus;
@@ -200,11 +208,9 @@ export default class EuropeanVehicle extends Vehicle {
const response = this.updateRates(
await http.get(`/api/v2/spa/vehicles/${this.vehicleConfig.id}/status${cacheString}`)
);
-
+
// handles refreshing data
- const vehicleStatus = statusConfig.refresh
- ? response.body.resMsg
- : response.body.resMsg.vehicleStatusInfo.vehicleStatus;
+ const vehicleStatus = statusConfig.refresh ? response.body.resMsg : response.body.resMsg.vehicleStatusInfo.vehicleStatus;
const parsedStatus: VehicleStatus = {
chassis: {
@@ -257,13 +263,12 @@ export default class EuropeanVehicle extends Vehicle {
if (!parsedStatus.engine.range) {
if (parsedStatus.engine.rangeEV || parsedStatus.engine.rangeGas) {
- parsedStatus.engine.range =
- (parsedStatus.engine.rangeEV ?? 0) + (parsedStatus.engine.rangeGas ?? 0);
+ parsedStatus.engine.range = (parsedStatus.engine.rangeEV ?? 0) + (parsedStatus.engine.rangeGas ?? 0);
}
}
this._status = statusConfig.parsed ? parsedStatus : vehicleStatus;
-
+
return this._status;
} catch (err) {
throw manageBluelinkyError(err, 'EuropeVehicle.status');