openbyd 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,374 @@
1
+ "use strict";
2
+ /**
3
+ * The client: pyBYD's `BydClient` with a Rust core.
4
+ *
5
+ * ```ts
6
+ * import { Client } from "openbyd";
7
+ *
8
+ * const client = new Client({ username: "user@example.com", password: "secret", controlPin: "123456" });
9
+ * try {
10
+ * await client.login();
11
+ * for (const vehicle of await client.getVehicles()) {
12
+ * const realtime = await client.getVehicleRealtime(vehicle.vin);
13
+ * console.log(vehicle.vin, realtime.elec_percent);
14
+ * }
15
+ * } finally {
16
+ * client.close();
17
+ * }
18
+ * ```
19
+ *
20
+ * Methods are pyBYD's, in camelCase. What they return is exactly pyBYD's
21
+ * `model_dump(mode="json")`, so fields keep pyBYD's snake_case names; what
22
+ * you pass (the config, options, parameter objects) is camelCase. Failures
23
+ * are thrown as pyBYD's exception classes (`BydApiError` and its subclasses,
24
+ * with `code` and `endpoint`).
25
+ *
26
+ * Every client in a process shares one HTTP connection pool and one Rust
27
+ * runtime, so a client is cheap: thousands can be created.
28
+ *
29
+ * Callbacks always run on JavaScript's thread. One that throws is reported
30
+ * to `onCallbackError` (by default as a process warning) and does not affect
31
+ * the client.
32
+ */
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.Client = exports.Car = exports.TEST_TLS = void 0;
35
+ const methods_js_1 = require("./generated/methods.js");
36
+ const shapes_js_1 = require("./generated/shapes.js");
37
+ const native_js_1 = require("./native.js");
38
+ const wire_js_1 = require("./wire.js");
39
+ /**
40
+ * Makes a client trust the certificate of the MQTT test broker. For tests,
41
+ * with an add-on built with the feature `testing`: `{ ...options, [TEST_TLS]: true }`.
42
+ *
43
+ * @internal
44
+ */
45
+ exports.TEST_TLS = Symbol.for("openbyd.testTls");
46
+ /** How long the timer that keeps a listening client's process alive sleeps: the longest Node allows. */
47
+ const KEEP_ALIVE_MS = 0x7fffffff;
48
+ /** A client's connection to the core: calls out, events in. */
49
+ class Core {
50
+ #native;
51
+ #options;
52
+ #listens;
53
+ /** The state listener of each car, by VIN. */
54
+ stateListeners = new Map();
55
+ #keepAlive;
56
+ #pending = 0;
57
+ constructor(options) {
58
+ this.#options = options;
59
+ const events = [];
60
+ if (options.onVehicleInfo)
61
+ events.push("vehicle_info");
62
+ if (options.onMqttEvent)
63
+ events.push("mqtt_event");
64
+ if (options.onCommandAck)
65
+ events.push("command_ack");
66
+ if (options.onCommandLifecycle)
67
+ events.push("command_lifecycle");
68
+ if (options.onMqttConnect)
69
+ events.push("mqtt_connect");
70
+ this.#listens = events.length > 0;
71
+ if (options.requestObserver)
72
+ events.push("request");
73
+ const hostOptions = {
74
+ events,
75
+ command_ack_ttl_seconds: options.commandAckTtlSeconds,
76
+ command_retries: options.commandRetries,
77
+ gate_policy: typeof options.gatePolicy === "function" ? "host" : options.gatePolicy,
78
+ pin_resolver: options.pinResolver ? "host" : undefined,
79
+ relogin: typeof options.relogin === "function" ? "host" : options.relogin,
80
+ test_tls: options[exports.TEST_TLS] === true ? true : undefined,
81
+ };
82
+ // The add-on keeps this function for as long as its client lives, so it
83
+ // must not hold the client: a client nobody refers to is collected, and
84
+ // the add-on's client with it.
85
+ let target;
86
+ const onEvent = (name, payload) => target?.deref()?.dispatch(name, payload);
87
+ try {
88
+ this.#native = new native_js_1.native.NativeClient((0, wire_js_1.encode)((0, methods_js_1.encodeBydConfig)(options)), (0, wire_js_1.encode)(hostOptions), onEvent);
89
+ }
90
+ catch (error) {
91
+ throw (0, wire_js_1.translate)(error);
92
+ }
93
+ target = new WeakRef(this);
94
+ }
95
+ call(method, args, shape) {
96
+ this.#pending += 1;
97
+ // The call's promise refers to this client until it settles, so a client
98
+ // is not collected while it has a call in flight (its callbacks may be needed).
99
+ return this.#native.call(method, (0, wire_js_1.encode)(args)).then((text) => {
100
+ this.#pending -= 1;
101
+ return (0, wire_js_1.decode)(text, shape);
102
+ }, (error) => {
103
+ this.#pending -= 1;
104
+ throw (0, wire_js_1.translate)(error);
105
+ });
106
+ }
107
+ callSync(method, args, shape) {
108
+ try {
109
+ return (0, wire_js_1.decode)(this.#native.callSync(method, (0, wire_js_1.encode)(args)), shape);
110
+ }
111
+ catch (error) {
112
+ throw (0, wire_js_1.translate)(error);
113
+ }
114
+ }
115
+ /** The invoker of the car numbered `car`: every call names it. */
116
+ forCar(car) {
117
+ return {
118
+ call: (method, args, shape) => this.call(method, { ...args, car }, shape),
119
+ callSync: (method, args, shape) => this.callSync(method, { ...args, car }, shape),
120
+ };
121
+ }
122
+ /** Calls in flight. */
123
+ get pending() {
124
+ return this.#pending;
125
+ }
126
+ start() {
127
+ this.callSync("start", {}, null);
128
+ if (this.#listens)
129
+ this.hold();
130
+ }
131
+ close() {
132
+ this.stateListeners.clear();
133
+ this.release();
134
+ this.callSync("close", {}, null);
135
+ }
136
+ /**
137
+ * Keeps the process alive until {@link release}, as an open socket would:
138
+ * a client with push listeners is waiting for pushes. The timer also
139
+ * refers to the client, so it is not collected while it listens.
140
+ */
141
+ hold() {
142
+ this.#keepAlive ??= setInterval(() => void this, KEEP_ALIVE_MS);
143
+ }
144
+ release() {
145
+ clearInterval(this.#keepAlive);
146
+ this.#keepAlive = undefined;
147
+ }
148
+ dispatch(name, payload) {
149
+ const options = this.#options;
150
+ const data = JSON.parse(payload);
151
+ if ((0, wire_js_1.mayHoldNonFinite)(payload))
152
+ (0, wire_js_1.reviveFields)(data, shapes_js_1.EVENT_SHAPES[name]);
153
+ switch (name) {
154
+ case "vehicle_info":
155
+ this.#notify("onVehicleInfo", () => options.onVehicleInfo?.(data.vin, data.data));
156
+ break;
157
+ case "mqtt_event":
158
+ this.#notify("onMqttEvent", () => options.onMqttEvent?.(data.event, data.vin, data.data));
159
+ break;
160
+ case "command_ack":
161
+ this.#notify("onCommandAck", () => options.onCommandAck?.(data.ack));
162
+ break;
163
+ case "command_lifecycle":
164
+ this.#notify("onCommandLifecycle", () => options.onCommandLifecycle?.(data.event));
165
+ break;
166
+ case "mqtt_connect":
167
+ this.#notify("onMqttConnect", () => options.onMqttConnect?.());
168
+ break;
169
+ case "request":
170
+ this.#notify("requestObserver", () => options.requestObserver?.(data.record));
171
+ break;
172
+ case "state_changed": {
173
+ const vin = data.vin;
174
+ this.#notify("onStateChanged", () => this.stateListeners.get(vin)?.(vin, data.state));
175
+ break;
176
+ }
177
+ case "gate_policy": {
178
+ const policy = options.gatePolicy;
179
+ if (typeof policy !== "function")
180
+ break;
181
+ this.#answer(data.request, "gatePolicy", true, () => policy(data.vin, data.verdict));
182
+ break;
183
+ }
184
+ case "pin_resolver": {
185
+ const resolver = options.pinResolver;
186
+ if (resolver === undefined)
187
+ break;
188
+ this.#answer(data.request, "pinResolver", true, () => resolver(data.command_pwd, data.control_pin));
189
+ break;
190
+ }
191
+ case "relogin": {
192
+ const relogin = options.relogin;
193
+ if (typeof relogin !== "function")
194
+ break;
195
+ // What it throws is the failure of the call that needed the session, not a stray error.
196
+ this.#answer(data.request, "relogin", false, relogin);
197
+ break;
198
+ }
199
+ default:
200
+ // An event of a newer core.
201
+ break;
202
+ }
203
+ }
204
+ /** Runs a notification callback; what it throws, now or later, is reported. */
205
+ #notify(name, run) {
206
+ try {
207
+ const result = run();
208
+ if (result instanceof Promise)
209
+ result.catch((error) => this.#report(name, error));
210
+ }
211
+ catch (error) {
212
+ this.#report(name, error);
213
+ }
214
+ }
215
+ /** Runs a callback the core waits for, and hands its answer or its failure back. */
216
+ #answer(request, name, report, run) {
217
+ Promise.resolve()
218
+ .then(run)
219
+ .then((value) => this.#resolve({ request, value }), (error) => {
220
+ if (report)
221
+ this.#report(name, error);
222
+ this.#resolve({ request, error: (0, wire_js_1.errorToJson)(error) });
223
+ });
224
+ }
225
+ #resolve(answer) {
226
+ try {
227
+ this.#native.callSync("resolve", (0, wire_js_1.encode)(answer));
228
+ }
229
+ catch {
230
+ // The question is no longer waiting.
231
+ }
232
+ }
233
+ #report(name, error) {
234
+ const handler = this.#options.onCallbackError;
235
+ if (handler !== undefined) {
236
+ try {
237
+ handler(name, error);
238
+ }
239
+ catch {
240
+ // A failing error handler has nowhere to report to.
241
+ }
242
+ return;
243
+ }
244
+ const message = error instanceof Error ? error.message : String(error);
245
+ const warning = new Error(`the ${name} callback threw: ${message}`, { cause: error });
246
+ warning.name = "OpenBydCallbackWarning";
247
+ process.emitWarning(warning);
248
+ }
249
+ }
250
+ /**
251
+ * One vehicle: pyBYD's `BydCar`. Get one from {@link Client.getCar}.
252
+ *
253
+ * It holds the vehicle's merged state and offers its commands by feature:
254
+ *
255
+ * ```ts
256
+ * const car = await client.getCar(vin);
257
+ * await car.updateRealtime();
258
+ * await car.lock.lock();
259
+ * await car.hvac.start({ temperature: 21, duration: 20 });
260
+ * car.state.realtime?.left_front_door_lock; // 2 (locked), projected
261
+ * ```
262
+ *
263
+ * A command lays the state it expects over the current state at once (a
264
+ * projection) and rolls it back when it fails; the next push or update that
265
+ * agrees confirms it. Each feature tells whether the car supports it; a
266
+ * command the car does not support throws `BydEndpointNotSupportedError`
267
+ * without sending anything. A car whose client is closed fails its calls
268
+ * with `BydError`.
269
+ */
270
+ class Car extends methods_js_1.CarMethods {
271
+ /** The vehicle identification number. */
272
+ vin;
273
+ /** @internal */
274
+ constructor(invoker, vin) {
275
+ super(invoker);
276
+ this.vin = vin;
277
+ }
278
+ }
279
+ exports.Car = Car;
280
+ /** The async client for the BYD API: pyBYD's `BydClient`. See the module's documentation. */
281
+ class Client extends methods_js_1.ClientMethods {
282
+ #core;
283
+ #cars = new Map();
284
+ #closed = false;
285
+ /**
286
+ * A client for an account, ready to use. A bad config value throws
287
+ * `ValidationError`.
288
+ *
289
+ * A client with push listeners (`onVehicleInfo`, `onMqttEvent`,
290
+ * `onCommandAck`, `onCommandLifecycle`, `onMqttConnect`, or a car's
291
+ * `onStateChanged`) keeps the process alive until {@link close}, as an
292
+ * open socket would.
293
+ */
294
+ constructor(options) {
295
+ const core = new Core(options);
296
+ super(core);
297
+ this.#core = core;
298
+ core.start();
299
+ }
300
+ /**
301
+ * A client that resumes a session from {@link exportSession}, without a
302
+ * password login. Without a `password` it never logs in by itself
303
+ * (`relogin` defaults to `"never"`): when the session expires, calls throw
304
+ * `BydSessionExpiredError` until the application imports a new one.
305
+ */
306
+ static async fromSession(session, options) {
307
+ const password = options.password ?? "";
308
+ const client = new Client({
309
+ ...options,
310
+ password,
311
+ relogin: options.relogin ?? (password === "" ? "never" : "password"),
312
+ });
313
+ try {
314
+ await client.importSession(session);
315
+ }
316
+ catch (error) {
317
+ client.close();
318
+ throw error;
319
+ }
320
+ return client;
321
+ }
322
+ /** Whether {@link close} was called and {@link start} was not called since. */
323
+ get closed() {
324
+ return this.#closed;
325
+ }
326
+ /** Opens the client again after {@link close} (pyBYD's `async_start`). A new client is open already. */
327
+ start() {
328
+ this.#core.start();
329
+ this.#closed = false;
330
+ }
331
+ /**
332
+ * Closes the cars, stops MQTT and makes later calls fail with `BydError`
333
+ * (pyBYD's `async_close`). Calls already in flight finish; one waiting
334
+ * for an MQTT push stops waiting with `CancelledError`.
335
+ */
336
+ close() {
337
+ this.#cars.clear();
338
+ this.#core.close();
339
+ this.#closed = true;
340
+ }
341
+ /** Closes the client: `using client = new Client(...)`. */
342
+ [Symbol.dispose]() {
343
+ this.close();
344
+ }
345
+ /**
346
+ * The {@link Car} of a vehicle, built once and kept.
347
+ *
348
+ * As pyBYD: a kept car is returned as it is, whatever the options.
349
+ * Otherwise the vehicle list is fetched unless `vehicle` is given, then
350
+ * the capabilities.
351
+ *
352
+ * @param vin - The vehicle identification number.
353
+ */
354
+ async getCar(vin, options = {}) {
355
+ const listener = options.onStateChanged;
356
+ const built = await this.#core.call("get_car", {
357
+ vin,
358
+ vehicle: options.vehicle,
359
+ projection_ttl: options.projectionTtl,
360
+ state_events: listener !== undefined,
361
+ }, null);
362
+ let car = this.#cars.get(built.car);
363
+ if (car === undefined) {
364
+ car = new Car(this.#core.forCar(built.car), built.vin);
365
+ this.#cars.set(built.car, car);
366
+ if (listener !== undefined) {
367
+ this.#core.stateListeners.set(built.vin, listener);
368
+ this.#core.hold();
369
+ }
370
+ }
371
+ return car;
372
+ }
373
+ }
374
+ exports.Client = Client;
@@ -0,0 +1,32 @@
1
+ /** What needs no client: the envelope cipher, pyBYD's models by name, the runtime's settings. */
2
+ import type { JsonObject, Models } from "./generated/models.js";
3
+ /** The version of openbyd's core. */
4
+ export declare function version(): string;
5
+ /** Wraps plaintext (text, or bytes) in a Bangcle envelope, as BYD's app does with every request. */
6
+ export declare function encodeEnvelope(plaintext: string | Uint8Array): string;
7
+ /** Opens a Bangcle envelope and returns the plaintext bytes. Throws `BangcleError` for a bad envelope. */
8
+ export declare function decodeEnvelope(envelope: string): Uint8Array;
9
+ /**
10
+ * Parses a raw payload (a reply's `respondData`, an MQTT event's data) as
11
+ * one of pyBYD's reply models: `Model.model_validate(raw).model_dump(mode="json")`.
12
+ * Throws `ValidationError` when it does not validate.
13
+ *
14
+ * @param context - pyBYD's validation context, for the models that take one.
15
+ */
16
+ export declare function parseModel<Name extends keyof Models>(name: Name, raw: JsonObject, context?: JsonObject): Models[Name];
17
+ /** The state of the Rust runtime every client shares. */
18
+ export interface RuntimeInfo {
19
+ /** The runtime's worker threads. */
20
+ readonly worker_threads: number;
21
+ /** Whether the runtime has started: after the first client or call. */
22
+ readonly started: boolean;
23
+ }
24
+ /** The state of the Rust runtime every client shares. */
25
+ export declare function runtimeInfo(): RuntimeInfo;
26
+ /**
27
+ * Sets the worker threads of the Rust runtime (2 by default). Only before
28
+ * the runtime starts, which the first client does.
29
+ */
30
+ export declare function configureRuntime(options: {
31
+ workerThreads: number;
32
+ }): void;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ /** What needs no client: the envelope cipher, pyBYD's models by name, the runtime's settings. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.version = version;
5
+ exports.encodeEnvelope = encodeEnvelope;
6
+ exports.decodeEnvelope = decodeEnvelope;
7
+ exports.parseModel = parseModel;
8
+ exports.runtimeInfo = runtimeInfo;
9
+ exports.configureRuntime = configureRuntime;
10
+ const shapes_js_1 = require("./generated/shapes.js");
11
+ const wire_js_1 = require("./wire.js");
12
+ /** The version of openbyd's core. */
13
+ function version() {
14
+ return (0, wire_js_1.callFunction)("version");
15
+ }
16
+ /** Wraps plaintext (text, or bytes) in a Bangcle envelope, as BYD's app does with every request. */
17
+ function encodeEnvelope(plaintext) {
18
+ if (typeof plaintext === "string")
19
+ return (0, wire_js_1.callFunction)("encode_envelope", { text: plaintext });
20
+ return (0, wire_js_1.callFunction)("encode_envelope", { hex: Buffer.from(plaintext).toString("hex") });
21
+ }
22
+ /** Opens a Bangcle envelope and returns the plaintext bytes. Throws `BangcleError` for a bad envelope. */
23
+ function decodeEnvelope(envelope) {
24
+ const { hex } = (0, wire_js_1.callFunction)("decode_envelope", { envelope });
25
+ return Buffer.from(hex, "hex");
26
+ }
27
+ /**
28
+ * Parses a raw payload (a reply's `respondData`, an MQTT event's data) as
29
+ * one of pyBYD's reply models: `Model.model_validate(raw).model_dump(mode="json")`.
30
+ * Throws `ValidationError` when it does not validate.
31
+ *
32
+ * @param context - pyBYD's validation context, for the models that take one.
33
+ */
34
+ function parseModel(name, raw, context) {
35
+ const parsed = (0, wire_js_1.callFunction)("parse_model", { name: shapes_js_1.MODEL_CALLS[name], raw, context });
36
+ return (0, wire_js_1.revive)(parsed.dump, ["struct", name]);
37
+ }
38
+ /** The state of the Rust runtime every client shares. */
39
+ function runtimeInfo() {
40
+ return (0, wire_js_1.callFunction)("runtime");
41
+ }
42
+ /**
43
+ * Sets the worker threads of the Rust runtime (2 by default). Only before
44
+ * the runtime starts, which the first client does.
45
+ */
46
+ function configureRuntime(options) {
47
+ (0, wire_js_1.callFunction)("configure", { worker_threads: options.workerThreads });
48
+ }
@@ -0,0 +1,114 @@
1
+ /** What an error is built from: its fields, whichever its class carries. */
2
+ export interface ErrorDetails {
3
+ readonly kind: string;
4
+ readonly statusCode?: number | null | undefined;
5
+ readonly endpoint?: string | null | undefined;
6
+ readonly code?: string | null | undefined;
7
+ readonly errorType?: string | null | undefined;
8
+ readonly loc?: string[] | null | undefined;
9
+ }
10
+ /**
11
+ * Base of every error openbyd raises. `kind` is the name of the Python exception class pyBYD
12
+ * raises for the same failure.
13
+ */
14
+ export declare class OpenBydError extends Error {
15
+ readonly name: string;
16
+ /** The name of the Python exception class pyBYD raises. */
17
+ readonly kind: string;
18
+ constructor(message: string, details: ErrorDetails);
19
+ }
20
+ /** Base of pyBYD's errors. */
21
+ export declare class BydError extends OpenBydError {
22
+ readonly name: string;
23
+ }
24
+ /** Encryption or decryption failed. */
25
+ export declare class BydCryptoError extends BydError {
26
+ readonly name: string;
27
+ }
28
+ /** A Bangcle envelope could not be encoded or decoded. */
29
+ export declare class BangcleError extends BydCryptoError {
30
+ readonly name: string;
31
+ }
32
+ /** The Bangcle lookup tables could not be loaded. */
33
+ export declare class BangcleTableLoadError extends BangcleError {
34
+ readonly name: string;
35
+ }
36
+ /** HTTP-level failure: the network, a status other than 200, a body that is not JSON. */
37
+ export declare class BydTransportError extends BydError {
38
+ readonly name: string;
39
+ /** The HTTP status, when the server answered. */
40
+ readonly statusCode: number | null;
41
+ /** The endpoint that failed. */
42
+ readonly endpoint: string;
43
+ constructor(message: string, details: ErrorDetails);
44
+ }
45
+ /** The API answered with a code other than 0. */
46
+ export declare class BydApiError extends BydError {
47
+ readonly name: string;
48
+ /** The API's code, such as `1005`. */
49
+ readonly code: string;
50
+ /** The endpoint that failed. */
51
+ readonly endpoint: string;
52
+ constructor(message: string, details: ErrorDetails);
53
+ }
54
+ /** Login failed or the session expired. */
55
+ export declare class BydAuthenticationError extends BydApiError {
56
+ readonly name: string;
57
+ }
58
+ /** The server rejected the session token (for example code `1005`). */
59
+ export declare class BydSessionExpiredError extends BydAuthenticationError {
60
+ readonly name: string;
61
+ }
62
+ /** A remote control command failed after the cloud accepted it. */
63
+ export declare class BydRemoteControlError extends BydApiError {
64
+ readonly name: string;
65
+ }
66
+ /**
67
+ * A remote control command was rejected for an invalid or locked operation password (codes
68
+ * `5005`, `5006`, `5011`).
69
+ */
70
+ export declare class BydControlPasswordError extends BydApiError {
71
+ readonly name: string;
72
+ }
73
+ /** The endpoint is not supported for this vehicle or region (for example code `1001`). */
74
+ export declare class BydEndpointNotSupportedError extends BydApiError {
75
+ readonly name: string;
76
+ }
77
+ /** The vehicle cannot provide the data right now (for example GPS code `6051`). */
78
+ export declare class BydDataUnavailableError extends BydApiError {
79
+ readonly name: string;
80
+ }
81
+ /** A previous command is still in progress (code `6024`). */
82
+ export declare class BydRateLimitError extends BydApiError {
83
+ readonly name: string;
84
+ }
85
+ /** The backend is busy (code `1008`); keep the last data and back off. */
86
+ export declare class BydServiceBusyError extends BydApiError {
87
+ readonly name: string;
88
+ }
89
+ /**
90
+ * A value could not be used: an argument, or a reply that is not what it should be. `kind`
91
+ * names the Python built-in exception pyBYD lets through (`ValueError`, `TypeError`,
92
+ * `JSONDecodeError`, ...).
93
+ */
94
+ export declare class DataError extends OpenBydError {
95
+ readonly name: string;
96
+ }
97
+ /** A reply or a parameter did not validate, where pyBYD raises pydantic's `ValidationError`. */
98
+ export declare class ValidationError extends DataError {
99
+ readonly name: string;
100
+ /** pydantic's error type, such as `int_parsing`. */
101
+ readonly errorType: string;
102
+ /** Where the bad value was, outermost first. */
103
+ readonly loc: string[];
104
+ constructor(message: string, details: ErrorDetails);
105
+ }
106
+ /**
107
+ * A wait for an MQTT push was cut short because the client stopped its MQTT channel, for
108
+ * example when it was closed.
109
+ */
110
+ export declare class CancelledError extends OpenBydError {
111
+ readonly name: string;
112
+ }
113
+ /** The error class for each Python exception class the core reports. */
114
+ export declare const ERROR_CLASSES: Readonly<Record<string, new (message: string, details: ErrorDetails) => OpenBydError>>;