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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * A fake BYD server and an MQTT test broker, for tests: `import { FakeServer } from "openbyd/testing"`.
3
+ *
4
+ * They need an add-on built with the feature `testing` (`npm run
5
+ * build:native -- --testing`); released add-ons do not have it, and
6
+ * {@link hasTesting} tells which one is loaded.
7
+ *
8
+ * ```ts
9
+ * using server = new FakeServer([{ username: "user@example.com", password: "secret" }]);
10
+ * server.reply("/control/getStatusNow", { data: { acSwitch: 1 } });
11
+ * const client = new Client({ username: "user@example.com", password: "secret", baseUrl: server.url });
12
+ * ```
13
+ */
14
+ import { TEST_TLS } from "./client.js";
15
+ import type { JsonObject, JsonValue, SessionTokens } from "./generated/models.js";
16
+ export { TEST_TLS };
17
+ /** Whether the add-on loaded has the fake server and the test broker. */
18
+ export declare const hasTesting: boolean;
19
+ /** An account the fake server knows. */
20
+ export interface Account {
21
+ username: string;
22
+ password: string;
23
+ /** The account's user ID; made up when not given. */
24
+ userId?: string | undefined;
25
+ /** The VINs the account reaches as a guest. */
26
+ guestVins?: string[] | undefined;
27
+ /** Whether the server insists on the `userType` a guest's requests carry. Default `true`. */
28
+ userTypeRule?: boolean | undefined;
29
+ }
30
+ /** What the fake server answers to one request. */
31
+ export type Reply = ({
32
+ data: JsonValue;
33
+ } | {
34
+ code: string;
35
+ message?: string | undefined;
36
+ } | {
37
+ outer: JsonValue;
38
+ } | {
39
+ status: number;
40
+ body?: string | undefined;
41
+ } | {
42
+ drop: true;
43
+ } | {
44
+ default: true;
45
+ }) & {
46
+ /** Answer after this many seconds. */
47
+ delay?: number | undefined;
48
+ /** Add this `Set-Cookie` header. */
49
+ cookie?: string | undefined;
50
+ };
51
+ /** One request the fake server received, decoded. */
52
+ export interface RecordedRequest {
53
+ readonly endpoint: string;
54
+ readonly headers: [string, string][];
55
+ readonly cookies: [string, string][];
56
+ readonly body: string;
57
+ /** The outer payload, when the envelope opened. */
58
+ readonly outer: JsonObject | null;
59
+ /** The decrypted inner payload, when it decrypted. */
60
+ readonly inner: JsonValue;
61
+ /** The account the request was verified as. */
62
+ readonly username: string | null;
63
+ /** The API code answered; null for an HTTP-level reply. */
64
+ readonly code: string | null;
65
+ /** The HTTP status answered; null when the connection was dropped. */
66
+ readonly status: number | null;
67
+ }
68
+ /** A fake BYD server on 127.0.0.1 that speaks the real wire protocol. */
69
+ export declare class FakeServer {
70
+ #private;
71
+ /** The server's base URL, for a client's `baseUrl`. */
72
+ readonly url: string;
73
+ constructor(accounts?: Account[]);
74
+ addAccount(account: Account): void;
75
+ /** Answers every request to `endpoint` with `reply`. */
76
+ reply(endpoint: string, reply: Reply): void;
77
+ /** Answers the next requests to `endpoint` with `replies`, one each. */
78
+ script(endpoint: string, replies: Reply[]): void;
79
+ /** The requests received, to one endpoint or to all. */
80
+ requests(endpoint?: string): RecordedRequest[];
81
+ clearRequests(): void;
82
+ /** Makes the server refuse every session of an account, as an expired one. */
83
+ expireSessions(username: string): void;
84
+ userId(username: string): string | null;
85
+ stop(): void;
86
+ [Symbol.dispose](): void;
87
+ }
88
+ /** A TLS MQTT broker on 127.0.0.1, which clients made with {@link TEST_TLS} trust. */
89
+ export declare class TestBroker {
90
+ #private;
91
+ /** The address as BYD's broker lookup gives it: `{ data: { emqBorker: broker.address } }`. */
92
+ readonly address: string;
93
+ readonly port: number;
94
+ constructor();
95
+ /**
96
+ * Sends `body` to the account of `session` as BYD does: on its topic,
97
+ * encrypted with the session's content key. Returns how many connections
98
+ * it reached.
99
+ */
100
+ push(session: Pick<SessionTokens, "user_id" | "encry_token">, body: JsonValue): number;
101
+ /** Connections subscribed to `topic`. */
102
+ subscribers(topic: string): number;
103
+ /** Connections still open on the broker's side. */
104
+ get open(): number;
105
+ /** How many connection attempts the broker has seen. */
106
+ get connects(): number;
107
+ /** Refuses the next `count` connection attempts. */
108
+ refuseNext(count: number): void;
109
+ /** Drops every connection. */
110
+ dropAll(): void;
111
+ stop(): void;
112
+ [Symbol.dispose](): void;
113
+ }
114
+ /** The outcome of a parity call: pyBYD's answer for the same input is recorded in the repository's vectors. */
115
+ export type ParityOutcome = {
116
+ ok: JsonValue;
117
+ } | {
118
+ error: {
119
+ kind: string;
120
+ message: string;
121
+ };
122
+ };
123
+ /**
124
+ * Runs one parity call of the core, the hook the repository's tests compare
125
+ * openbyd with pyBYD through. Not part of the public API.
126
+ */
127
+ export declare function parityCall(name: string, args: JsonValue): ParityOutcome;
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ /**
3
+ * A fake BYD server and an MQTT test broker, for tests: `import { FakeServer } from "openbyd/testing"`.
4
+ *
5
+ * They need an add-on built with the feature `testing` (`npm run
6
+ * build:native -- --testing`); released add-ons do not have it, and
7
+ * {@link hasTesting} tells which one is loaded.
8
+ *
9
+ * ```ts
10
+ * using server = new FakeServer([{ username: "user@example.com", password: "secret" }]);
11
+ * server.reply("/control/getStatusNow", { data: { acSwitch: 1 } });
12
+ * const client = new Client({ username: "user@example.com", password: "secret", baseUrl: server.url });
13
+ * ```
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.TestBroker = exports.FakeServer = exports.hasTesting = exports.TEST_TLS = void 0;
17
+ exports.parityCall = parityCall;
18
+ const client_js_1 = require("./client.js");
19
+ Object.defineProperty(exports, "TEST_TLS", { enumerable: true, get: function () { return client_js_1.TEST_TLS; } });
20
+ const native_js_1 = require("./native.js");
21
+ const wire_js_1 = require("./wire.js");
22
+ /** Whether the add-on loaded has the fake server and the test broker. */
23
+ exports.hasTesting = (0, wire_js_1.callFunction)("has_testing");
24
+ function testing(name, args = {}) {
25
+ try {
26
+ return JSON.parse(native_js_1.native.testingCall(name, (0, wire_js_1.encode)(args)));
27
+ }
28
+ catch (error) {
29
+ throw (0, wire_js_1.translate)(error);
30
+ }
31
+ }
32
+ function accountArgs(account) {
33
+ return {
34
+ username: account.username,
35
+ password: account.password,
36
+ user_id: account.userId,
37
+ guest_vins: account.guestVins,
38
+ user_type_rule: account.userTypeRule,
39
+ };
40
+ }
41
+ /** A fake BYD server on 127.0.0.1 that speaks the real wire protocol. */
42
+ class FakeServer {
43
+ #server;
44
+ /** The server's base URL, for a client's `baseUrl`. */
45
+ url;
46
+ constructor(accounts = []) {
47
+ const started = testing("server.start", {
48
+ accounts: accounts.map(accountArgs),
49
+ });
50
+ this.#server = started.server;
51
+ this.url = started.url;
52
+ }
53
+ addAccount(account) {
54
+ testing("server.add_account", { server: this.#server, ...accountArgs(account) });
55
+ }
56
+ /** Answers every request to `endpoint` with `reply`. */
57
+ reply(endpoint, reply) {
58
+ testing("server.reply", { server: this.#server, endpoint, reply });
59
+ }
60
+ /** Answers the next requests to `endpoint` with `replies`, one each. */
61
+ script(endpoint, replies) {
62
+ testing("server.script", { server: this.#server, endpoint, replies });
63
+ }
64
+ /** The requests received, to one endpoint or to all. */
65
+ requests(endpoint) {
66
+ return testing("server.requests", { server: this.#server, endpoint });
67
+ }
68
+ clearRequests() {
69
+ testing("server.clear_requests", { server: this.#server });
70
+ }
71
+ /** Makes the server refuse every session of an account, as an expired one. */
72
+ expireSessions(username) {
73
+ testing("server.expire_sessions", { server: this.#server, username });
74
+ }
75
+ userId(username) {
76
+ return testing("server.user_id", { server: this.#server, username });
77
+ }
78
+ stop() {
79
+ testing("server.stop", { server: this.#server });
80
+ }
81
+ [Symbol.dispose]() {
82
+ this.stop();
83
+ }
84
+ }
85
+ exports.FakeServer = FakeServer;
86
+ /** A TLS MQTT broker on 127.0.0.1, which clients made with {@link TEST_TLS} trust. */
87
+ class TestBroker {
88
+ #broker;
89
+ /** The address as BYD's broker lookup gives it: `{ data: { emqBorker: broker.address } }`. */
90
+ address;
91
+ port;
92
+ constructor() {
93
+ const started = testing("broker.start");
94
+ this.#broker = started.broker;
95
+ this.address = started.address;
96
+ this.port = started.port;
97
+ }
98
+ /**
99
+ * Sends `body` to the account of `session` as BYD does: on its topic,
100
+ * encrypted with the session's content key. Returns how many connections
101
+ * it reached.
102
+ */
103
+ push(session, body) {
104
+ return testing("broker.push", { broker: this.#broker, session, body });
105
+ }
106
+ /** Connections subscribed to `topic`. */
107
+ subscribers(topic) {
108
+ return testing("broker.subscribers", { broker: this.#broker, topic });
109
+ }
110
+ /** Connections still open on the broker's side. */
111
+ get open() {
112
+ return testing("broker.open", { broker: this.#broker });
113
+ }
114
+ /** How many connection attempts the broker has seen. */
115
+ get connects() {
116
+ return testing("broker.connects", { broker: this.#broker });
117
+ }
118
+ /** Refuses the next `count` connection attempts. */
119
+ refuseNext(count) {
120
+ testing("broker.refuse_next", { broker: this.#broker, count });
121
+ }
122
+ /** Drops every connection. */
123
+ dropAll() {
124
+ testing("broker.drop_all", { broker: this.#broker });
125
+ }
126
+ stop() {
127
+ testing("broker.stop", { broker: this.#broker });
128
+ }
129
+ [Symbol.dispose]() {
130
+ this.stop();
131
+ }
132
+ }
133
+ exports.TestBroker = TestBroker;
134
+ /**
135
+ * Runs one parity call of the core, the hook the repository's tests compare
136
+ * openbyd with pyBYD through. Not part of the public API.
137
+ */
138
+ function parityCall(name, args) {
139
+ return (0, wire_js_1.callFunction)("parity_call", { name, args });
140
+ }
package/dist/wire.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What crosses between TypeScript and the core: JSON text, and errors.
3
+ *
4
+ * @internal
5
+ */
6
+ import { type Shape } from "./generated/shapes.js";
7
+ /** What the add-on threw as this package's error; anything else unchanged. */
8
+ export declare function translate(thrown: unknown): unknown;
9
+ /**
10
+ * An error a callback threw, as the core takes it back: an openbyd error
11
+ * keeps its class and fields, anything else is named by its own class.
12
+ */
13
+ export declare function errorToJson(error: unknown): Record<string, unknown>;
14
+ /**
15
+ * Turns the strings JSON needs for NaN and the infinities back into numbers,
16
+ * in place, wherever `shape` says a float is.
17
+ */
18
+ export declare function revive(value: unknown, shape: Shape): unknown;
19
+ /** {@link revive} for an object whose fields have these shapes. */
20
+ export declare function reviveFields(value: Record<string, unknown>, fields: Readonly<Record<string, Shape>> | undefined): void;
21
+ /** Whether JSON text may hold a float written as a string. */
22
+ export declare function mayHoldNonFinite(text: string): boolean;
23
+ /** The core's JSON text as a value, with the floats `shape` describes read back as numbers. */
24
+ export declare function decode<T>(text: string, shape: Shape | null): T;
25
+ /**
26
+ * Arguments as JSON text. A field that is `undefined` is left out: not
27
+ * given. A number JSON cannot hold (NaN, an infinity) is refused, as pyBYD
28
+ * refuses it, instead of silently becoming "not given".
29
+ */
30
+ export declare function encode(args: Record<string, unknown>): string;
31
+ /** Runs a function of the core that needs no client. */
32
+ export declare function callFunction<T>(name: string, args?: Record<string, unknown>): T;
package/dist/wire.js ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ /**
3
+ * What crosses between TypeScript and the core: JSON text, and errors.
4
+ *
5
+ * @internal
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.translate = translate;
9
+ exports.errorToJson = errorToJson;
10
+ exports.revive = revive;
11
+ exports.reviveFields = reviveFields;
12
+ exports.mayHoldNonFinite = mayHoldNonFinite;
13
+ exports.decode = decode;
14
+ exports.encode = encode;
15
+ exports.callFunction = callFunction;
16
+ const errors_js_1 = require("./generated/errors.js");
17
+ const shapes_js_1 = require("./generated/shapes.js");
18
+ const native_js_1 = require("./native.js");
19
+ /** The error class for what the core reported: its own, or the nearest parent's this package knows. */
20
+ function errorFromJson(error) {
21
+ const known = [error.class, ...error.bases].map((name) => errors_js_1.ERROR_CLASSES[name]).find((cls) => cls !== undefined);
22
+ return new (known ?? errors_js_1.OpenBydError)(error.message, {
23
+ kind: error.class,
24
+ code: error.code,
25
+ endpoint: error.endpoint,
26
+ statusCode: error.status_code,
27
+ errorType: error.error_type,
28
+ loc: error.loc,
29
+ });
30
+ }
31
+ /** What the add-on threw as this package's error; anything else unchanged. */
32
+ function translate(thrown) {
33
+ if (thrown instanceof Error && thrown.message.startsWith(native_js_1.native.ERROR_PREFIX)) {
34
+ try {
35
+ return errorFromJson(JSON.parse(thrown.message.slice(native_js_1.native.ERROR_PREFIX.length)));
36
+ }
37
+ catch {
38
+ return thrown;
39
+ }
40
+ }
41
+ return thrown;
42
+ }
43
+ /**
44
+ * An error a callback threw, as the core takes it back: an openbyd error
45
+ * keeps its class and fields, anything else is named by its own class.
46
+ */
47
+ function errorToJson(error) {
48
+ if (error instanceof errors_js_1.OpenBydError) {
49
+ const fields = error;
50
+ return {
51
+ class: error.kind,
52
+ message: error.message,
53
+ code: fields.code,
54
+ endpoint: fields.endpoint,
55
+ status_code: fields.statusCode,
56
+ };
57
+ }
58
+ if (error instanceof Error)
59
+ return { class: error.name, message: error.message };
60
+ return { class: "Error", message: String(error) };
61
+ }
62
+ const NON_FINITE = { NaN: NaN, Infinity: Infinity, "-Infinity": -Infinity };
63
+ /**
64
+ * Turns the strings JSON needs for NaN and the infinities back into numbers,
65
+ * in place, wherever `shape` says a float is.
66
+ */
67
+ function revive(value, shape) {
68
+ if (value === null || value === undefined)
69
+ return value;
70
+ if (shape === "float") {
71
+ return typeof value === "string" ? (NON_FINITE[value] ?? value) : value;
72
+ }
73
+ const [kind, inner] = shape;
74
+ if (kind === "list") {
75
+ const items = value;
76
+ for (let index = 0; index < items.length; index++)
77
+ items[index] = revive(items[index], inner);
78
+ }
79
+ else if (kind === "map") {
80
+ const entries = value;
81
+ for (const key of Object.keys(entries))
82
+ entries[key] = revive(entries[key], inner);
83
+ }
84
+ else {
85
+ reviveFields(value, shapes_js_1.STRUCT_SHAPES[inner]);
86
+ }
87
+ return value;
88
+ }
89
+ /** {@link revive} for an object whose fields have these shapes. */
90
+ function reviveFields(value, fields) {
91
+ if (fields === undefined)
92
+ return;
93
+ for (const [field, shape] of Object.entries(fields)) {
94
+ if (field in value)
95
+ value[field] = revive(value[field], shape);
96
+ }
97
+ }
98
+ /** Whether JSON text may hold a float written as a string. */
99
+ function mayHoldNonFinite(text) {
100
+ return text.includes('"NaN"') || text.includes('Infinity"');
101
+ }
102
+ /** The core's JSON text as a value, with the floats `shape` describes read back as numbers. */
103
+ function decode(text, shape) {
104
+ const value = JSON.parse(text);
105
+ if (shape !== null && mayHoldNonFinite(text))
106
+ return revive(value, shape);
107
+ return value;
108
+ }
109
+ /**
110
+ * Arguments as JSON text. A field that is `undefined` is left out: not
111
+ * given. A number JSON cannot hold (NaN, an infinity) is refused, as pyBYD
112
+ * refuses it, instead of silently becoming "not given".
113
+ */
114
+ function encode(args) {
115
+ return JSON.stringify(args, (key, value) => {
116
+ if (typeof value === "number" && !Number.isFinite(value)) {
117
+ throw new errors_js_1.DataError(`${key} must be a finite number, not ${value}`, { kind: "ValueError" });
118
+ }
119
+ return value;
120
+ });
121
+ }
122
+ /** Runs a function of the core that needs no client. */
123
+ function callFunction(name, args = {}) {
124
+ try {
125
+ return JSON.parse(native_js_1.native.call(name, encode(args)));
126
+ }
127
+ catch (error) {
128
+ throw translate(error);
129
+ }
130
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "openbyd",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.3",
4
+ "description": "Unofficial client for the BYD overseas app API, with a Rust core",
5
+ "keywords": [
6
+ "byd",
7
+ "ev",
8
+ "vehicle",
9
+ "telemetry"
10
+ ],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/Pho3niX90/openbyd.git",
15
+ "directory": "bindings/node"
16
+ },
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./testing": {
25
+ "types": "./dist/testing.d.ts",
26
+ "default": "./dist/testing.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md"
33
+ ],
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "scripts": {
38
+ "build:native": "node scripts/build-native.mjs",
39
+ "build": "tsc -p tsconfig.json",
40
+ "test": "npm run build && tsc -p test/tsconfig.json && node --test \"build/test/*.test.js\""
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^22.0.0",
44
+ "typescript": "^5.9.0"
45
+ },
46
+ "optionalDependencies": {
47
+ "@openbyd/darwin-arm64": "0.1.3",
48
+ "@openbyd/darwin-x64": "0.1.3",
49
+ "@openbyd/linux-arm64-gnu": "0.1.3",
50
+ "@openbyd/linux-arm64-musl": "0.1.3",
51
+ "@openbyd/linux-x64-gnu": "0.1.3",
52
+ "@openbyd/linux-x64-musl": "0.1.3",
53
+ "@openbyd/win32-x64-msvc": "0.1.3"
54
+ }
55
+ }