wenmar-open 0.0.1 → 0.1.0
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/LICENSE +21 -0
- package/README.md +187 -2
- package/dist/client.d.ts +84 -0
- package/dist/client.js +205 -0
- package/dist/errors.d.ts +46 -0
- package/dist/errors.js +37 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +2 -0
- package/dist/schema.d.ts +984 -0
- package/dist/schema.js +3 -0
- package/dist/types.d.ts +31 -0
- package/dist/types.js +1 -0
- package/package.json +43 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Wenmar Pro
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,5 +1,190 @@
|
|
|
1
1
|
# wenmar-open
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A typed client for the [Wenmar Open](https://open.wenmarpro.com) API: VIN decoding and a year, make, model, trim and engine catalog for auto repair shops. The API needs no key and no account.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
- No dependencies. It uses the platform's `fetch`.
|
|
6
|
+
- Runs in Node 20 and later, browsers, Cloudflare Workers, Deno and Bun.
|
|
7
|
+
- Types are generated from the API's OpenAPI description.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install wenmar-open
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Decode a VIN
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { WenmarOpen } from "wenmar-open";
|
|
17
|
+
|
|
18
|
+
const open = new WenmarOpen();
|
|
19
|
+
|
|
20
|
+
const vehicle = await open.decodeVin("KM8K2CAB4PU001140");
|
|
21
|
+
console.log(vehicle.year, vehicle.make, vehicle.model, vehicle.trim);
|
|
22
|
+
// 2023 Hyundai Kona SE
|
|
23
|
+
console.log(vehicle.engine?.label, vehicle.drivetrain, vehicle.safety?.tpms);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Spaces, dashes and lowercase letters in the VIN are accepted. A field the data does not have is left out, so every field except `vin`, `valid`, `check_digit`, `manufacturer`, `plant` and `warnings` may be `undefined`.
|
|
27
|
+
|
|
28
|
+
A wrong check digit is not an error. The decode comes back with `valid: false` and a warning, because many genuine VINs from outside North America fail the check:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { WenmarOpen } from "wenmar-open";
|
|
32
|
+
|
|
33
|
+
const vehicle = await new WenmarOpen().decodeVin("KM8K2CAB0PU001140");
|
|
34
|
+
if (!vehicle.valid) {
|
|
35
|
+
for (const warning of vehicle.warnings) {
|
|
36
|
+
console.log(warning.code, warning.message, warning.suggestions);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
If you know the model year, pass it: `open.decodeVin(vin, { year: 2023 })`.
|
|
42
|
+
|
|
43
|
+
## Errors
|
|
44
|
+
|
|
45
|
+
Every method throws a `WenmarOpenError`. It has the API's `code`, `message` and `details`, and the HTTP `status`.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { WenmarOpen, WenmarOpenError } from "wenmar-open";
|
|
49
|
+
|
|
50
|
+
const open = new WenmarOpen();
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
await open.decodeVin("KM8K2CAB4PUO01140"); // a letter O where a zero belongs
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (!(error instanceof WenmarOpenError)) throw error;
|
|
56
|
+
if (error.code === "invalid_vin") {
|
|
57
|
+
console.log(error.message); // what is wrong with it
|
|
58
|
+
console.log(error.details.suggestions); // VINs you may have meant
|
|
59
|
+
} else if (error.code === "not_found") {
|
|
60
|
+
console.log("No manufacturer is registered for this VIN.");
|
|
61
|
+
} else if (error.code === "rate_limited" || error.code === "unavailable") {
|
|
62
|
+
console.log(`Try again in ${error.retryAfter ?? 60} seconds.`);
|
|
63
|
+
} else {
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
| `code` | `status` | Meaning |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `invalid_vin` | 400 | Wrong length or characters. `details.suggestions` lists likely corrections. |
|
|
72
|
+
| `validation_failed` | 400 | A parameter is missing or wrong. `details.field` names it. |
|
|
73
|
+
| `not_found` | 404 | No manufacturer for the VIN, or no vehicle with that id. |
|
|
74
|
+
| `rate_limited` | 429 | Over 600 requests a minute from one address. `retryAfter` is in seconds. |
|
|
75
|
+
| `unavailable` | 503 | The server is busy. `retryAfter` is in seconds. |
|
|
76
|
+
| `internal_error` | 500 | Something went wrong on the server. |
|
|
77
|
+
| `timeout` | none | No complete answer within `timeoutMs`. |
|
|
78
|
+
| `aborted` | none | Your `signal` was aborted. |
|
|
79
|
+
| `network` | none | The request could not be sent. `cause` has the reason. |
|
|
80
|
+
| `bad_response` | any | Something answered, but not the API: a proxy's error page, a sign-in page. |
|
|
81
|
+
|
|
82
|
+
The API may add codes. Treat a code you do not know as a failure.
|
|
83
|
+
|
|
84
|
+
The client does not retry. If you retry, do it only for `rate_limited`, `unavailable`, `timeout` and `network`, and wait `retryAfter` seconds when it is set.
|
|
85
|
+
|
|
86
|
+
## Decode many VINs
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { WenmarOpen, isBatchError } from "wenmar-open";
|
|
90
|
+
|
|
91
|
+
const open = new WenmarOpen();
|
|
92
|
+
const vins = ["KM8K2CAB4PU001140", "1HGCM82633A004352", "NOT-A-VIN"];
|
|
93
|
+
|
|
94
|
+
const items = await open.decodeVins(vins);
|
|
95
|
+
items.forEach((item, index) => {
|
|
96
|
+
if (isBatchError(item)) {
|
|
97
|
+
console.log(vins[index], "failed:", item.error.code);
|
|
98
|
+
} else {
|
|
99
|
+
console.log(item.vin, item.year, item.make, item.model);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A batch holds at most 50 VINs (`MAX_BATCH`). The answer has one item per VIN, in the order sent. One bad VIN does not fail the batch.
|
|
105
|
+
|
|
106
|
+
## Choose a vehicle without a VIN
|
|
107
|
+
|
|
108
|
+
Each step offers only what is valid for the steps before it.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import { WenmarOpen } from "wenmar-open";
|
|
112
|
+
|
|
113
|
+
const open = new WenmarOpen();
|
|
114
|
+
|
|
115
|
+
const years = await open.years(); // newest first
|
|
116
|
+
const makes = await open.makes({ year: 2019 }); // popular makes first
|
|
117
|
+
const models = await open.models({ make: "honda", year: 2019 });
|
|
118
|
+
const trims = await open.submodels({ make: "honda", model: "civic", year: 2019 });
|
|
119
|
+
const engines = await open.engines({ make: "honda", model: "civic", year: 2019, submodel: "si" });
|
|
120
|
+
|
|
121
|
+
console.log(years[0], makes[0]?.name, models[0]?.name, trims[0]?.name, engines[0]?.label);
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`make` and `model` take a name, an alias or an id: `Chevrolet`, `chevy` and `chevrolet` are the same make. `term` filters any step by what someone has typed so far, for autocomplete: `open.makes({ term: "che" })`.
|
|
125
|
+
|
|
126
|
+
Free text works too, and every vehicle has an id you can store:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { WenmarOpen } from "wenmar-open";
|
|
130
|
+
|
|
131
|
+
const open = new WenmarOpen();
|
|
132
|
+
|
|
133
|
+
const [best] = await open.search({ q: "2019 civic si" });
|
|
134
|
+
console.log(best?.id, best?.summary);
|
|
135
|
+
|
|
136
|
+
const same = await open.vehicle("2019_honda_civic_si");
|
|
137
|
+
console.log(same.summary);
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
A decoded VIN carries the same ids in `catalog`, so a VIN can fill in a vehicle form: `vehicle.catalog?.entry.id`.
|
|
141
|
+
|
|
142
|
+
## Options
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import { WenmarOpen } from "wenmar-open";
|
|
146
|
+
|
|
147
|
+
const open = new WenmarOpen({
|
|
148
|
+
baseUrl: "http://localhost:3000", // your own server; default https://open.wenmarpro.com
|
|
149
|
+
timeoutMs: 5_000, // default 10,000; 0 for no limit
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// Per request: a time limit, and a signal to cancel with.
|
|
153
|
+
const controller = new AbortController();
|
|
154
|
+
const makes = await open.makes({ term: "ho" }, { signal: controller.signal, timeoutMs: 2_000 });
|
|
155
|
+
console.log(makes.length);
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
`fetch` replaces the platform's `fetch`, for a Workers service binding or a test:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import { WenmarOpen } from "wenmar-open";
|
|
162
|
+
import type { FetchLike } from "wenmar-open";
|
|
163
|
+
|
|
164
|
+
const logged: FetchLike = async (url, init) => {
|
|
165
|
+
console.log(init.method, url);
|
|
166
|
+
return fetch(url, init);
|
|
167
|
+
};
|
|
168
|
+
const open = new WenmarOpen({ fetch: logged });
|
|
169
|
+
console.log((await open.meta()).data_version);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## Caching and limits
|
|
173
|
+
|
|
174
|
+
Answers change only when the data does, about once a month. `open.meta()` returns the `data_version`; anything you cache can be kept until it changes. In a browser the HTTP cache already does this.
|
|
175
|
+
|
|
176
|
+
One address may make 600 requests a minute. A server that calls the API for many users shares one address, so cache catalog answers there. To decode a list of VINs, use `decodeVins`: a batch of 50 counts as one request.
|
|
177
|
+
|
|
178
|
+
## CommonJS
|
|
179
|
+
|
|
180
|
+
The package is an ES module. `require("wenmar-open")` works in Node 20.19 and later and in Node 22.12 and later. In older Node 20 releases use `await import("wenmar-open")`.
|
|
181
|
+
|
|
182
|
+
## Types
|
|
183
|
+
|
|
184
|
+
Every response type is exported: `VinDecode`, `Entry`, `Make`, `Model`, `Submodel`, `EngineOption`, `Meta`, `BatchItem`, `ErrorBody`. The generated `paths`, `operations` and `components` types are exported as well.
|
|
185
|
+
|
|
186
|
+
The API only ever adds fields and endpoints. A response may carry fields this version's types do not name; they are passed through untouched.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
MIT. Vehicle data comes from NHTSA's vPIC and is described in the repository's [NOTICE.md](https://github.com/wenmar-pro/wenmar-open/blob/main/NOTICE.md).
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { BatchItem, EngineOption, EnginesQuery, Entry, ErrorBody, Make, MakesQuery, Meta, Model, ModelsQuery, SearchQuery, Submodel, SubmodelsQuery, VinDecode, YearsQuery } from "./types.js";
|
|
2
|
+
/** The hosted API. */
|
|
3
|
+
export declare const DEFAULT_BASE_URL = "https://open.wenmarpro.com";
|
|
4
|
+
/** How long a request may take before it fails with `timeout`. */
|
|
5
|
+
export declare const DEFAULT_TIMEOUT_MS = 10000;
|
|
6
|
+
/** The most VINs the API decodes in one batch. */
|
|
7
|
+
export declare const MAX_BATCH = 50;
|
|
8
|
+
/** What the client asks of a `fetch`: the part of the standard it uses. */
|
|
9
|
+
export interface FetchInit {
|
|
10
|
+
method: string;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
body?: string;
|
|
13
|
+
signal: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
/** What the client reads of a response. */
|
|
16
|
+
export interface FetchResponse {
|
|
17
|
+
readonly status: number;
|
|
18
|
+
readonly headers: {
|
|
19
|
+
get(name: string): string | null;
|
|
20
|
+
};
|
|
21
|
+
text(): Promise<string>;
|
|
22
|
+
}
|
|
23
|
+
/** A `fetch`. The platform's own fits; so does a Workers service binding's. */
|
|
24
|
+
export type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponse>;
|
|
25
|
+
export interface ClientOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Where the API is. Default `https://open.wenmarpro.com`. A path is kept,
|
|
28
|
+
* so `https://example.com/open` reaches `https://example.com/open/v1/...`.
|
|
29
|
+
*/
|
|
30
|
+
baseUrl?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Milliseconds a request may take, the body included. Default 10,000.
|
|
33
|
+
* `0` means no limit.
|
|
34
|
+
*/
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
/** Used instead of the platform's `fetch`. */
|
|
37
|
+
fetch?: FetchLike;
|
|
38
|
+
}
|
|
39
|
+
/** What every method accepts last. */
|
|
40
|
+
export interface RequestOptions {
|
|
41
|
+
/** Aborting it fails the request with the code `aborted`. */
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
/** Overrides the client's `timeoutMs` for this request. */
|
|
44
|
+
timeoutMs?: number;
|
|
45
|
+
}
|
|
46
|
+
export interface DecodeOptions extends RequestOptions {
|
|
47
|
+
/** Use this model year instead of working it out from the VIN. */
|
|
48
|
+
year?: number;
|
|
49
|
+
}
|
|
50
|
+
/** Whether an item of a batch is the error for its VIN and not a decode. */
|
|
51
|
+
export declare function isBatchError(item: BatchItem): item is ErrorBody;
|
|
52
|
+
/** A client for the Wenmar Open API. It keeps no state between requests. */
|
|
53
|
+
export declare class WenmarOpen {
|
|
54
|
+
#private;
|
|
55
|
+
readonly baseUrl: string;
|
|
56
|
+
readonly timeoutMs: number;
|
|
57
|
+
constructor(options?: ClientOptions);
|
|
58
|
+
/** Decode one VIN. Spaces, dashes and lowercase are accepted. */
|
|
59
|
+
decodeVin(vin: string, options?: DecodeOptions): Promise<VinDecode>;
|
|
60
|
+
/**
|
|
61
|
+
* Decode up to 50 VINs. The answer has one item per VIN, in order: a
|
|
62
|
+
* decode, or the error a single request for that VIN would have given.
|
|
63
|
+
* Tell them apart with `isBatchError`.
|
|
64
|
+
*/
|
|
65
|
+
decodeVins(vins: readonly string[], options?: RequestOptions): Promise<BatchItem[]>;
|
|
66
|
+
/** Model years, newest first. */
|
|
67
|
+
years(query?: YearsQuery, options?: RequestOptions): Promise<number[]>;
|
|
68
|
+
/** Makes, popular ones first and the rest by name. */
|
|
69
|
+
makes(query?: MakesQuery, options?: RequestOptions): Promise<Make[]>;
|
|
70
|
+
/** Models of a make, by name. An unknown make has no models. */
|
|
71
|
+
models(query: ModelsQuery, options?: RequestOptions): Promise<Model[]>;
|
|
72
|
+
/** Submodels of a model year: trims, or series where there are no trims. */
|
|
73
|
+
submodels(query: SubmodelsQuery, options?: RequestOptions): Promise<Submodel[]>;
|
|
74
|
+
/** The same as `submodels`, under the name most people use. */
|
|
75
|
+
trims(query: SubmodelsQuery, options?: RequestOptions): Promise<Submodel[]>;
|
|
76
|
+
/** Engines of a model year, in short form. */
|
|
77
|
+
engines(query: EnginesQuery, options?: RequestOptions): Promise<EngineOption[]>;
|
|
78
|
+
/** Catalog entries for free text such as `2019 civic si`, best first. */
|
|
79
|
+
search(query: SearchQuery, options?: RequestOptions): Promise<Entry[]>;
|
|
80
|
+
/** One catalog entry by its id, such as `2019_honda_civic_si`. */
|
|
81
|
+
vehicle(id: string, options?: RequestOptions): Promise<Entry>;
|
|
82
|
+
/** The data version, the vPIC release it came from, and the build time. */
|
|
83
|
+
meta(options?: RequestOptions): Promise<Meta>;
|
|
84
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { WenmarOpenError, parseRetryAfter } from "./errors.js";
|
|
2
|
+
/** The hosted API. */
|
|
3
|
+
export const DEFAULT_BASE_URL = "https://open.wenmarpro.com";
|
|
4
|
+
/** How long a request may take before it fails with `timeout`. */
|
|
5
|
+
export const DEFAULT_TIMEOUT_MS = 10_000;
|
|
6
|
+
/** The most VINs the API decodes in one batch. */
|
|
7
|
+
export const MAX_BATCH = 50;
|
|
8
|
+
function queryString(query) {
|
|
9
|
+
const params = new URLSearchParams();
|
|
10
|
+
for (const [name, value] of Object.entries((query ?? {}))) {
|
|
11
|
+
if (value === undefined || value === null || value === "")
|
|
12
|
+
continue;
|
|
13
|
+
params.append(name, String(value));
|
|
14
|
+
}
|
|
15
|
+
const text = params.toString();
|
|
16
|
+
return text === "" ? "" : `?${text}`;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* One path segment. A URL treats `.` and `..` as directions, not names, even
|
|
20
|
+
* when they are percent-encoded, so they are refused here: sent, they would
|
|
21
|
+
* reach a different address than the one meant.
|
|
22
|
+
*/
|
|
23
|
+
function segment(field, value) {
|
|
24
|
+
const text = String(value).trim();
|
|
25
|
+
if (text === "" || text === "." || text === "..") {
|
|
26
|
+
throw new WenmarOpenError({
|
|
27
|
+
code: "validation_failed",
|
|
28
|
+
message: `${field} is required`,
|
|
29
|
+
details: { field },
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return encodeURIComponent(text);
|
|
33
|
+
}
|
|
34
|
+
function isRecord(value) {
|
|
35
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
/** Whether an item of a batch is the error for its VIN and not a decode. */
|
|
38
|
+
export function isBatchError(item) {
|
|
39
|
+
return isRecord(item.error);
|
|
40
|
+
}
|
|
41
|
+
/** A client for the Wenmar Open API. It keeps no state between requests. */
|
|
42
|
+
export class WenmarOpen {
|
|
43
|
+
baseUrl;
|
|
44
|
+
timeoutMs;
|
|
45
|
+
#fetch;
|
|
46
|
+
constructor(options = {}) {
|
|
47
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
48
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
49
|
+
// The platform's fetch is looked up at each call, not kept.
|
|
50
|
+
this.#fetch = options.fetch ?? ((url, init) => fetch(url, init));
|
|
51
|
+
}
|
|
52
|
+
/** Decode one VIN. Spaces, dashes and lowercase are accepted. */
|
|
53
|
+
async decodeVin(vin, options = {}) {
|
|
54
|
+
const path = `/v1/vin/${segment("vin", vin)}${queryString({ year: options.year })}`;
|
|
55
|
+
return this.#request("GET", path, undefined, options);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Decode up to 50 VINs. The answer has one item per VIN, in order: a
|
|
59
|
+
* decode, or the error a single request for that VIN would have given.
|
|
60
|
+
* Tell them apart with `isBatchError`.
|
|
61
|
+
*/
|
|
62
|
+
async decodeVins(vins, options = {}) {
|
|
63
|
+
if (vins.length > MAX_BATCH) {
|
|
64
|
+
throw new WenmarOpenError({
|
|
65
|
+
code: "validation_failed",
|
|
66
|
+
message: `a batch holds at most ${MAX_BATCH} VINs`,
|
|
67
|
+
details: { field: "vins", max: MAX_BATCH, received: vins.length },
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return this.#request("POST", "/v1/vin/batch", { vins }, options);
|
|
71
|
+
}
|
|
72
|
+
/** Model years, newest first. */
|
|
73
|
+
async years(query = {}, options = {}) {
|
|
74
|
+
return this.#request("GET", `/v1/vehicles/years${queryString(query)}`, undefined, options);
|
|
75
|
+
}
|
|
76
|
+
/** Makes, popular ones first and the rest by name. */
|
|
77
|
+
async makes(query = {}, options = {}) {
|
|
78
|
+
return this.#request("GET", `/v1/vehicles/makes${queryString(query)}`, undefined, options);
|
|
79
|
+
}
|
|
80
|
+
/** Models of a make, by name. An unknown make has no models. */
|
|
81
|
+
async models(query, options = {}) {
|
|
82
|
+
return this.#request("GET", `/v1/vehicles/models${queryString(query)}`, undefined, options);
|
|
83
|
+
}
|
|
84
|
+
/** Submodels of a model year: trims, or series where there are no trims. */
|
|
85
|
+
async submodels(query, options = {}) {
|
|
86
|
+
return this.#request("GET", `/v1/vehicles/submodels${queryString(query)}`, undefined, options);
|
|
87
|
+
}
|
|
88
|
+
/** The same as `submodels`, under the name most people use. */
|
|
89
|
+
async trims(query, options = {}) {
|
|
90
|
+
return this.#request("GET", `/v1/vehicles/trims${queryString(query)}`, undefined, options);
|
|
91
|
+
}
|
|
92
|
+
/** Engines of a model year, in short form. */
|
|
93
|
+
async engines(query, options = {}) {
|
|
94
|
+
return this.#request("GET", `/v1/vehicles/engines${queryString(query)}`, undefined, options);
|
|
95
|
+
}
|
|
96
|
+
/** Catalog entries for free text such as `2019 civic si`, best first. */
|
|
97
|
+
async search(query, options = {}) {
|
|
98
|
+
return this.#request("GET", `/v1/vehicles/search${queryString(query)}`, undefined, options);
|
|
99
|
+
}
|
|
100
|
+
/** One catalog entry by its id, such as `2019_honda_civic_si`. */
|
|
101
|
+
async vehicle(id, options = {}) {
|
|
102
|
+
return this.#request("GET", `/v1/vehicles/${segment("id", id)}`, undefined, options);
|
|
103
|
+
}
|
|
104
|
+
/** The data version, the vPIC release it came from, and the build time. */
|
|
105
|
+
async meta(options = {}) {
|
|
106
|
+
return this.#request("GET", "/v1/meta", undefined, options);
|
|
107
|
+
}
|
|
108
|
+
async #request(method, path, body, options) {
|
|
109
|
+
const caller = options.signal;
|
|
110
|
+
if (caller?.aborted) {
|
|
111
|
+
throw new WenmarOpenError({ code: "aborted", message: "The request was aborted.", cause: caller.reason });
|
|
112
|
+
}
|
|
113
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
let timedOut = false;
|
|
116
|
+
const timer = timeoutMs > 0
|
|
117
|
+
? setTimeout(() => {
|
|
118
|
+
timedOut = true;
|
|
119
|
+
controller.abort();
|
|
120
|
+
}, timeoutMs)
|
|
121
|
+
: undefined;
|
|
122
|
+
const onAbort = () => controller.abort();
|
|
123
|
+
caller?.addEventListener("abort", onAbort, { once: true });
|
|
124
|
+
const headers = { Accept: "application/json" };
|
|
125
|
+
const init = { method, headers, signal: controller.signal };
|
|
126
|
+
if (body !== undefined) {
|
|
127
|
+
headers["Content-Type"] = "application/json";
|
|
128
|
+
init.body = JSON.stringify(body);
|
|
129
|
+
}
|
|
130
|
+
let status;
|
|
131
|
+
let retryAfter;
|
|
132
|
+
let text;
|
|
133
|
+
try {
|
|
134
|
+
// Called as a plain function, never as a method of this object: some
|
|
135
|
+
// runtimes refuse a `fetch` whose `this` is not the global object.
|
|
136
|
+
const send = this.#fetch;
|
|
137
|
+
const response = await send(`${this.baseUrl}${path}`, init);
|
|
138
|
+
status = response.status;
|
|
139
|
+
retryAfter = parseRetryAfter(response.headers.get("retry-after"));
|
|
140
|
+
// The time limit covers the body: it is read before the timer stops.
|
|
141
|
+
text = await response.text();
|
|
142
|
+
}
|
|
143
|
+
catch (cause) {
|
|
144
|
+
if (timedOut) {
|
|
145
|
+
throw new WenmarOpenError({
|
|
146
|
+
code: "timeout",
|
|
147
|
+
message: `No answer within ${timeoutMs} ms.`,
|
|
148
|
+
details: { timeout_ms: timeoutMs },
|
|
149
|
+
cause,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
if (caller?.aborted) {
|
|
153
|
+
throw new WenmarOpenError({ code: "aborted", message: "The request was aborted.", cause });
|
|
154
|
+
}
|
|
155
|
+
throw new WenmarOpenError({
|
|
156
|
+
code: "network",
|
|
157
|
+
message: `The API at ${this.baseUrl} could not be reached.`,
|
|
158
|
+
cause,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
if (timer !== undefined)
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
caller?.removeEventListener("abort", onAbort);
|
|
165
|
+
}
|
|
166
|
+
let parsed;
|
|
167
|
+
let isJson = true;
|
|
168
|
+
try {
|
|
169
|
+
parsed = JSON.parse(text);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
isJson = false;
|
|
173
|
+
}
|
|
174
|
+
if (status >= 200 && status < 300) {
|
|
175
|
+
if (!isJson) {
|
|
176
|
+
throw new WenmarOpenError({
|
|
177
|
+
code: "bad_response",
|
|
178
|
+
message: `The answer from ${this.baseUrl} is not JSON. Something other than the API may have answered.`,
|
|
179
|
+
status,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
return parsed;
|
|
183
|
+
}
|
|
184
|
+
const error = isRecord(parsed) ? parsed["error"] : undefined;
|
|
185
|
+
if (isRecord(error) && typeof error["code"] === "string" && typeof error["message"] === "string") {
|
|
186
|
+
const details = isRecord(error["details"]) ? error["details"] : {};
|
|
187
|
+
// The header is what the API promises. The body's copy is used when a
|
|
188
|
+
// proxy in between dropped the header.
|
|
189
|
+
const inBody = details["retry_after"];
|
|
190
|
+
throw new WenmarOpenError({
|
|
191
|
+
code: error["code"],
|
|
192
|
+
message: error["message"],
|
|
193
|
+
details,
|
|
194
|
+
status,
|
|
195
|
+
retryAfter: retryAfter ?? (typeof inBody === "number" ? inBody : undefined),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
throw new WenmarOpenError({
|
|
199
|
+
code: "bad_response",
|
|
200
|
+
message: `The server answered ${status} without the API's error body. A proxy in front of the API may have answered.`,
|
|
201
|
+
status,
|
|
202
|
+
retryAfter,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The codes the API answers with. */
|
|
2
|
+
export type ApiErrorCode = "invalid_vin" | "validation_failed" | "not_found" | "method_not_allowed" | "payload_too_large" | "uri_too_long" | "rate_limited" | "unavailable" | "internal_error";
|
|
3
|
+
/**
|
|
4
|
+
* The codes this client adds for failures that never reached the API or
|
|
5
|
+
* did not come from it.
|
|
6
|
+
*
|
|
7
|
+
* - `network`: the request could not be sent or the answer could not be read.
|
|
8
|
+
* - `timeout`: no complete answer within `timeoutMs`.
|
|
9
|
+
* - `aborted`: the caller's `signal` was aborted.
|
|
10
|
+
* - `bad_response`: something answered, but not with the API's JSON. A proxy's
|
|
11
|
+
* error page and a sign-in page from a captive portal both end up here.
|
|
12
|
+
*/
|
|
13
|
+
export type ClientErrorCode = "network" | "timeout" | "aborted" | "bad_response";
|
|
14
|
+
/**
|
|
15
|
+
* Every code known when this version was published. The API may add codes,
|
|
16
|
+
* so `code` is typed to accept any string while still completing these.
|
|
17
|
+
*/
|
|
18
|
+
export type ErrorCode = ApiErrorCode | ClientErrorCode | (string & {});
|
|
19
|
+
export interface WenmarOpenErrorInit {
|
|
20
|
+
code: ErrorCode;
|
|
21
|
+
message: string;
|
|
22
|
+
details?: Record<string, unknown> | undefined;
|
|
23
|
+
status?: number | undefined;
|
|
24
|
+
retryAfter?: number | undefined;
|
|
25
|
+
cause?: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** The one error every method of the client throws. */
|
|
28
|
+
export declare class WenmarOpenError extends Error {
|
|
29
|
+
/** A stable code to branch on. */
|
|
30
|
+
readonly code: ErrorCode;
|
|
31
|
+
/** The HTTP status, or `undefined` when there was no HTTP answer. */
|
|
32
|
+
readonly status: number | undefined;
|
|
33
|
+
/** More about the error, as the API sent it. Empty when there is nothing. */
|
|
34
|
+
readonly details: Record<string, unknown>;
|
|
35
|
+
/**
|
|
36
|
+
* Seconds to wait before trying again, from the `Retry-After` header of a
|
|
37
|
+
* `429` or `503`. `undefined` when the answer did not say.
|
|
38
|
+
*/
|
|
39
|
+
readonly retryAfter: number | undefined;
|
|
40
|
+
constructor(init: WenmarOpenErrorInit);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Reads a `Retry-After` header: a number of seconds, or an HTTP date.
|
|
44
|
+
* Returns whole seconds, never negative, or `undefined` if it is neither.
|
|
45
|
+
*/
|
|
46
|
+
export declare function parseRetryAfter(header: string | null, now?: number): number | undefined;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The one error every method of the client throws. */
|
|
2
|
+
export class WenmarOpenError extends Error {
|
|
3
|
+
/** A stable code to branch on. */
|
|
4
|
+
code;
|
|
5
|
+
/** The HTTP status, or `undefined` when there was no HTTP answer. */
|
|
6
|
+
status;
|
|
7
|
+
/** More about the error, as the API sent it. Empty when there is nothing. */
|
|
8
|
+
details;
|
|
9
|
+
/**
|
|
10
|
+
* Seconds to wait before trying again, from the `Retry-After` header of a
|
|
11
|
+
* `429` or `503`. `undefined` when the answer did not say.
|
|
12
|
+
*/
|
|
13
|
+
retryAfter;
|
|
14
|
+
constructor(init) {
|
|
15
|
+
super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
|
|
16
|
+
this.name = "WenmarOpenError";
|
|
17
|
+
this.code = init.code;
|
|
18
|
+
this.status = init.status;
|
|
19
|
+
this.details = init.details ?? {};
|
|
20
|
+
this.retryAfter = init.retryAfter;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Reads a `Retry-After` header: a number of seconds, or an HTTP date.
|
|
25
|
+
* Returns whole seconds, never negative, or `undefined` if it is neither.
|
|
26
|
+
*/
|
|
27
|
+
export function parseRetryAfter(header, now = Date.now()) {
|
|
28
|
+
if (header === null)
|
|
29
|
+
return undefined;
|
|
30
|
+
const text = header.trim();
|
|
31
|
+
if (/^\d+$/.test(text))
|
|
32
|
+
return Number(text);
|
|
33
|
+
const date = Date.parse(text);
|
|
34
|
+
if (Number.isNaN(date))
|
|
35
|
+
return undefined;
|
|
36
|
+
return Math.max(0, Math.ceil((date - now) / 1000));
|
|
37
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, MAX_BATCH, WenmarOpen, isBatchError, } from "./client.js";
|
|
2
|
+
export type { ClientOptions, DecodeOptions, FetchInit, FetchLike, FetchResponse, RequestOptions, } from "./client.js";
|
|
3
|
+
export { WenmarOpenError } from "./errors.js";
|
|
4
|
+
export type { ApiErrorCode, ClientErrorCode, ErrorCode, WenmarOpenErrorInit } from "./errors.js";
|
|
5
|
+
export type { BatchItem, CheckDigit, Engine, EngineOption, EnginesQuery, Entry, ErrorBody, Make, MakesQuery, Manufacturer, Meta, Model, ModelsQuery, Plant, Safety, SearchQuery, Selection, Submodel, SubmodelsQuery, VinDecode, Warning, YearsQuery, } from "./types.js";
|
|
6
|
+
export type { components, operations, paths } from "./schema.js";
|
package/dist/index.js
ADDED