@timbereye/sdk 0.0.0-stage → 0.2.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/CHANGELOG.md +123 -0
- package/LICENSE +202 -0
- package/README.md +346 -2
- package/dist/cjs/case.d.ts +23 -0
- package/dist/cjs/case.js +54 -0
- package/dist/cjs/client.d.ts +98 -0
- package/dist/cjs/client.js +132 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +107 -0
- package/dist/cjs/generated/schema.d.ts +14862 -0
- package/dist/cjs/generated/schema.js +6 -0
- package/dist/cjs/http.d.ts +104 -0
- package/dist/cjs/http.js +253 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.js +29 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +31 -0
- package/dist/cjs/pagination.js +52 -0
- package/dist/cjs/resources.d.ts +11195 -0
- package/dist/cjs/resources.js +506 -0
- package/dist/cjs/runtime.d.ts +20 -0
- package/dist/cjs/runtime.js +74 -0
- package/dist/cjs/types.d.ts +649 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/units.d.ts +26 -0
- package/dist/cjs/units.js +45 -0
- package/dist/cjs/webhooks.d.ts +67 -0
- package/dist/cjs/webhooks.js +213 -0
- package/dist/esm/case.d.ts +23 -0
- package/dist/esm/case.js +47 -0
- package/dist/esm/client.d.ts +98 -0
- package/dist/esm/client.js +128 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +93 -0
- package/dist/esm/generated/schema.d.ts +14862 -0
- package/dist/esm/generated/schema.js +5 -0
- package/dist/esm/http.d.ts +104 -0
- package/dist/esm/http.js +247 -0
- package/dist/esm/index.d.ts +14 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/pagination.d.ts +31 -0
- package/dist/esm/pagination.js +49 -0
- package/dist/esm/resources.d.ts +11195 -0
- package/dist/esm/resources.js +503 -0
- package/dist/esm/runtime.d.ts +20 -0
- package/dist/esm/runtime.js +46 -0
- package/dist/esm/types.d.ts +649 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/units.d.ts +26 -0
- package/dist/esm/units.js +38 -0
- package/dist/esm/webhooks.d.ts +67 -0
- package/dist/esm/webhooks.js +208 -0
- package/package.json +51 -5
package/README.md
CHANGED
|
@@ -1,3 +1,347 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @timbereye/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript SDK for the Timbereye API: counts, measurements and tallies of forest products (sawlogs today) as
|
|
4
|
+
versioned data, grouped the way you group wood (containers, truck loads, stacks), bound to an origin place.
|
|
5
|
+
Apache-2.0.
|
|
6
|
+
|
|
7
|
+
Status: version 0.2.0, written from the OpenAPI document (https://www.timbereye.com/docs/openapi.yaml, one method
|
|
8
|
+
per operation) and exercised end to end against the real server. The contract may still change. An environment
|
|
9
|
+
that has no image storage configured answers uploads with `503 storage_unavailable`, and one whose storage does not
|
|
10
|
+
hold the on-device detector yet answers `models.retrieveDetector` with `503 model_unavailable`.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
npm install @timbereye/sdk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Supported runtimes: Node 18 or later, current browsers, and edge runtimes (Cloudflare Workers, Deno,
|
|
19
|
+
Vercel Edge, Bun) that provide `fetch` and Web Crypto. ESM and CommonJS builds with bundled types (`import Timbereye from "@timbereye/sdk"`, or
|
|
20
|
+
`const { Timbereye } = require("@timbereye/sdk")`; under `require` the default export is `.default`). No runtime dependencies, and no Node-only imports in the main entry. On Node 18,
|
|
21
|
+
which has no global `crypto`, the SDK loads `node:crypto`'s Web Crypto lazily when it first needs it.
|
|
22
|
+
|
|
23
|
+
Never put a secret key (`te_live_sk_...`, `te_test_sk_...`) or a restricted key in a browser or app. The
|
|
24
|
+
client refuses to start with one there. Apps use a publishable key or a capture token that your server
|
|
25
|
+
mints ([Keys](https://www.timbereye.com/docs/keys/)).
|
|
26
|
+
|
|
27
|
+
## Quickstart
|
|
28
|
+
|
|
29
|
+
The three steps of an integration, **Create → Scan → Sync**, in test mode, as in
|
|
30
|
+
[the docs' quickstart](https://www.timbereye.com/docs/quickstart/). Set your test secret key and the endpoint's signing
|
|
31
|
+
secret where your server reads them:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
export TIMBEREYE_SECRET_KEY=te_test_sk_...
|
|
35
|
+
export TIMBEREYE_WEBHOOK_SECRET=whsec_... # from creating the webhook endpoint
|
|
36
|
+
export TIMBEREYE_API_URL=http://localhost:8080/v1 # optional: another Timbereye API; unset means the hosted one
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`new Timbereye()` reads all three where the runtime has an environment (`process.env`); in a browser or an edge
|
|
40
|
+
runtime without one, pass them as options. An option you pass (`apiKey`, `webhookSecret`, `baseUrl`) wins.
|
|
41
|
+
|
|
42
|
+
### 1. Create
|
|
43
|
+
|
|
44
|
+
When your backend creates its record for a container, it creates the Timbereye group and keeps the group's id.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import Timbereye from "@timbereye/sdk"
|
|
48
|
+
|
|
49
|
+
const timbereye = new Timbereye() // reads TIMBEREYE_SECRET_KEY
|
|
50
|
+
const group = await timbereye.groups.create({
|
|
51
|
+
kind: "container",
|
|
52
|
+
externalRef: "ctr_4821", // your record's id
|
|
53
|
+
name: "MSKU1234567",
|
|
54
|
+
defaults: { species: "PINE_TAEDA", length: { valueM: 5.8 } },
|
|
55
|
+
})
|
|
56
|
+
await db.containers.update("ctr_4821", { timbereyeGroupId: group.id }) // "grp_7QxV3m"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`db.containers.update` stands for your own database.
|
|
60
|
+
|
|
61
|
+
### 2. Scan
|
|
62
|
+
|
|
63
|
+
In production a worker scans the logs with a phone and the server refines them. In test mode the simulator does
|
|
64
|
+
both: 35 synthetic logs, refined at once.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
await timbereye.testMode.simulateScan({ groupId: group.id, logs: 35, refine: true })
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 3. Sync
|
|
71
|
+
|
|
72
|
+
Once its logs are measured the group sends `group.measured` with its tally to your webhook endpoint. The handler updates your record:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import express from "express"
|
|
76
|
+
|
|
77
|
+
const app = express()
|
|
78
|
+
const onEvent = timbereye.webhooks.handler(async (event) => {
|
|
79
|
+
if (event.type === "group.measured") {
|
|
80
|
+
const tally = event.data.object
|
|
81
|
+
await db.containers.update(tally.externalRef, {
|
|
82
|
+
pieces: tally.pieces,
|
|
83
|
+
volumeM3: tally.volume?.m3,
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), onEvent)
|
|
88
|
+
app.listen(3000)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
For a lumber or panel bundle the same event has no sawlog `volume` (it is `null`): its figures are in `totals`, so
|
|
92
|
+
`tally.totals?.m3 ?? tally.volume?.m3` reads both.
|
|
93
|
+
|
|
94
|
+
`handler` verifies the signature with `TIMBEREYE_WEBHOOK_SECRET` and answers `200`; a request Timbereye did not
|
|
95
|
+
sign gets `400`. Register the endpoint once with
|
|
96
|
+
`timbereye.webhookEndpoints.create({ url, enabledEvents: ["group.measured"] })`; its `secret` is returned only
|
|
97
|
+
then. With no public URL yet, read the same event from the feed:
|
|
98
|
+
`(await timbereye.events.list({ type: "group.measured", limit: 1 })).data[0]`.
|
|
99
|
+
|
|
100
|
+
Every log stays readable afterwards:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
for await (const item of timbereye.groups.items.list(group.id)) {
|
|
104
|
+
console.log(item.tag?.payload, item.measurement?.effectiveShortM)
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Conventions
|
|
109
|
+
|
|
110
|
+
**Names.** Methods follow the API's resources: `te.groups.create / open / lookup / retrieve / update / list /
|
|
111
|
+
setWeight / volume / origin / listImages`, `te.groups.items.add / remove / bulkUpdate / list`,
|
|
112
|
+
`te.items.list / retrieve / update / remove / listMeasurements / createMeasurement / volume /
|
|
113
|
+
listGroups / listImages`, `te.scans.create / list / retrieve / addItems / addObservations / submit /
|
|
114
|
+
uploadImage`, `te.images.createUploadSession / createSession / retrieve / complete`, `te.places.create / list /
|
|
115
|
+
retrieve / update / validate`, `te.species.list / create / update`, `te.volumeRules.list`,
|
|
116
|
+
`te.events.list / retrieve`, `te.webhookEndpoints.create / list / retrieve / update / delete / test /
|
|
117
|
+
rollSecret`, `te.captureTokens.create`, `te.usage.retrieve / listRecords`, and
|
|
118
|
+
`te.models.retrieveDetector({ platform })`, and `te.account.retrieve` (`GET /account`: name, mode, `displayUnits`,
|
|
119
|
+
`defaultVolumeRule`). There is one method per operation in the OpenAPI document.
|
|
120
|
+
|
|
121
|
+
**camelCase in, camelCase out.** The REST API is snake_case; the SDK takes and returns camelCase
|
|
122
|
+
(`externalRef`, `originPlaceId`, `densityKgM3`). The mapping is mechanical and applies to keys only.
|
|
123
|
+
`metadata` is yours: its keys and values are sent and returned exactly as written. Query parameters
|
|
124
|
+
follow the same rule, and `expand: ["origin_place"]` becomes `expand[]=origin_place`. Error `param`
|
|
125
|
+
values and event type strings are wire names and are not converted.
|
|
126
|
+
|
|
127
|
+
**Units.** Responses carry SI values named in the field (`lengthM`, `netKg`, `m3`). Inputs also accept
|
|
128
|
+
`{ value, unit }` for lengths (`m`, `cm`, `ft`, `in`) and weights (`kg`, `lb`, `t`, `short_ton`); the
|
|
129
|
+
value as entered is echoed back in `entered`. A bare `ton` is rejected. Lengths take one shape everywhere:
|
|
130
|
+
`{ value, unit }` or `{ valueM }`.
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
await te.groups.setWeight(group.id, { gross: 52480, tare: 14120, unit: "lb", ticketRef: "WT-88213" })
|
|
134
|
+
await te.groups.items.bulkUpdate(group.id, {
|
|
135
|
+
selector: { scanId: "scn_2Pq8" },
|
|
136
|
+
patch: { length: { valueM: 5.8 } },
|
|
137
|
+
})
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Display units
|
|
141
|
+
|
|
142
|
+
An account's `displayUnits` is `metric` or `imperial`. The formatters show SI values that way and take
|
|
143
|
+
either the string or the account object; they never affect requests.
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import { formatLength, formatDiameter, formatWeight, formatVolume } from "@timbereye/sdk"
|
|
147
|
+
|
|
148
|
+
const account = await te.account.retrieve()
|
|
149
|
+
formatLength(11.8, account) // follows account.displayUnits
|
|
150
|
+
|
|
151
|
+
formatLength(11.8, "imperial") // "38.71 ft"
|
|
152
|
+
formatDiameter(0.2315, "metric") // "23.2 cm"
|
|
153
|
+
formatWeight(21400, "metric") // "21.4 t"
|
|
154
|
+
formatVolume(21.384, "imperial") // "755.169 ft³"
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Board-foot rule outputs are available as `volume.native`; they are not converted.
|
|
158
|
+
|
|
159
|
+
## Errors
|
|
160
|
+
|
|
161
|
+
Failures throw subclasses of `TimbereyeError`, chosen by the API's error `type`:
|
|
162
|
+
`InvalidRequestError` (400, 404, 409, 412, 413, 422), `AuthenticationError` (401), `PermissionError`
|
|
163
|
+
(403), `RateLimitError` (429, with `retryAfterSeconds`) and `ApiError` (5xx). Each carries `code`,
|
|
164
|
+
`param`, `requestId`, `status`, `type` and `docUrl`. Network failures throw `ConnectionError`, an
|
|
165
|
+
elapsed timeout `TimeoutError`, and your own abort `AbortError`.
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { InvalidRequestError } from "@timbereye/sdk"
|
|
169
|
+
|
|
170
|
+
try {
|
|
171
|
+
await te.groups.update(id, { name: "North stack" }, { ifMatch: group.version })
|
|
172
|
+
} catch (e) {
|
|
173
|
+
if (e instanceof InvalidRequestError && e.code === "version_mismatch") {
|
|
174
|
+
// someone else changed the group: re-read and retry
|
|
175
|
+
} else {
|
|
176
|
+
throw e // quote e.requestId to support
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`code` is a string. Codes in use include `resource_missing`, `parameter_invalid`, `parameter_unknown`,
|
|
182
|
+
`invalid_cursor`, `idempotency_key_reused`, `idempotency_key_missing`, `idempotency_request_in_progress`,
|
|
183
|
+
`version_mismatch`, `payload_too_large`, `group_not_empty`, `scope_missing`, `secret_key_required`,
|
|
184
|
+
`capture_token_not_allowed`, `key_mode_mismatch`, `rate_limited`, the 422 codes `unit_ambiguous`,
|
|
185
|
+
`group_cycle`, `group_depth_exceeded`, `weight_inconsistent` and `area_ha_not_allowed`, `not_implemented` and
|
|
186
|
+
`service_unavailable`; the YAML lists them all. New codes may appear within v1; treat unknown ones as the
|
|
187
|
+
generic case.
|
|
188
|
+
|
|
189
|
+
## Retries, timeouts and cancellation
|
|
190
|
+
|
|
191
|
+
The client retries network errors and timeouts, `409 idempotency_request_in_progress`, `429` (waiting
|
|
192
|
+
for `Retry-After` when sent, up to 60 s) and `5xx` other than `501 not_implemented`, with exponential backoff (500 ms doubling to 8 s,
|
|
193
|
+
jittered). It never retries any other 4xx. Defaults are `maxRetries: 2` and `timeoutMs: 60000` per
|
|
194
|
+
attempt. Where a person is waiting for the answer, set `maxRetryWaitMs`: a `429` or `503` that asks for a longer
|
|
195
|
+
wait (an hourly or daily limit) is then thrown at once, with `retryAfterSeconds`, instead of being waited out.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const te = new Timbereye(key, { maxRetries: 4, timeoutMs: 10_000 })
|
|
199
|
+
|
|
200
|
+
const ac = new AbortController()
|
|
201
|
+
await te.groups.retrieve(id, undefined, { timeoutMs: 2000, signal: ac.signal })
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Idempotency
|
|
205
|
+
|
|
206
|
+
Every state-changing `POST` gets an `Idempotency-Key` (a UUID) automatically. One key is generated per
|
|
207
|
+
call and reused by every retry of it, so a retry cannot create a duplicate. Supply your own to make a
|
|
208
|
+
whole workflow step safe to repeat, and on `PATCH`, `PUT` and `DELETE`, where it is optional:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
await te.groups.create({ externalRef: "MSKU1234567" }, { idempotencyKey: "booking-BK-2231-group" })
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`POST /places/validate` only computes, so no key is sent. Keys are remembered for 24 hours; the same
|
|
215
|
+
key with a different body fails with `409 idempotency_key_reused`.
|
|
216
|
+
|
|
217
|
+
## Pagination
|
|
218
|
+
|
|
219
|
+
List methods return a promise of one page (`data`, `hasMore`, `nextCursor`) that is also an async
|
|
220
|
+
iterator over every item:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
const page = await te.groups.list({ status: "open", limit: 50 })
|
|
224
|
+
|
|
225
|
+
for await (const group of te.groups.list({ status: "open" })) {
|
|
226
|
+
console.log(group.id)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const first200 = await te.groups.list().autoPagingToArray({ limit: 200 })
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
The awaited page is itself iterable, so a list returned from an `async` function keeps paging (the extra members are
|
|
233
|
+
not enumerable, so the page still serialises as a plain `{ object, data, hasMore, nextCursor }`):
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
const firstPage = await findGroups() // an async function that returns te.groups.list(...)
|
|
237
|
+
for await (const group of firstPage) console.log(group.id) // this page, then every later one
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Find groups by your own metadata with a `metadata` map: `te.groups.list({ metadata: { booking: "B123" } })` sends
|
|
241
|
+
`metadata[booking]=B123` (up to five keys, all must match). `originPlaceId`, `createdAfter` and `createdBefore` filter
|
|
242
|
+
too.
|
|
243
|
+
|
|
244
|
+
## Response headers
|
|
245
|
+
|
|
246
|
+
Every call takes `onResponse`, called with the status, `requestId`, `idempotentReplayed`, `rateLimit` (`limit`,
|
|
247
|
+
`remaining`), all headers (lower-cased) and the idempotency key the call sent, for each response it receives (also the
|
|
248
|
+
attempts that are retried):
|
|
249
|
+
|
|
250
|
+
```ts
|
|
251
|
+
await te.groups.update(
|
|
252
|
+
"grp_1",
|
|
253
|
+
{ name: "MSKU1234567" },
|
|
254
|
+
{ onResponse: (r) => console.log(r.requestId, r.rateLimit.remaining) },
|
|
255
|
+
)
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Test mode simulator
|
|
259
|
+
|
|
260
|
+
With a `te_test_` key, `te.testMode.simulateScan({ groupId, logs: 12, species: "PINE_TAEDA", length: { valueM: 5.8 }, seed: 7 })`
|
|
261
|
+
creates a scan of synthetic, tagged logs and completes it, and `te.testMode.runRefinements()` resolves the pending
|
|
262
|
+
refinements now. The numbers are simulated (`provenance.simulated` is `true`), never billed, and a live key is refused
|
|
263
|
+
with `403 test_mode_only`.
|
|
264
|
+
|
|
265
|
+
## Lumber and panels
|
|
266
|
+
|
|
267
|
+
`te.groups.createBatch({ parent, groups })`
|
|
268
|
+
creates a packing list and its bundles in one call, `te.groups.tally.submit(id, { clientId, lines })` sends a
|
|
269
|
+
bundle's tally (final when submitted), `te.groups.tally.correct` and `te.groups.tally.listRevisions` correct and audit it, and
|
|
270
|
+
`te.groups.packingList(id)` and `te.groups.tallySheet(id)` return the documents as JSON (or, with `format: "html"`, a
|
|
271
|
+
printable page). `te.groups.listParents(id)` is where a bundle has been. `te.testMode.simulatePackingList({ scenario })`
|
|
272
|
+
builds a whole tallied list. See [Lumber and panels](https://www.timbereye.com/docs/lumber-and-panels/).
|
|
273
|
+
|
|
274
|
+
## Webhooks
|
|
275
|
+
|
|
276
|
+
`te.webhooks.handler(onEvent)` is the route handler: it verifies each delivery with `TIMBEREYE_WEBHOOK_SECRET` (or
|
|
277
|
+
the `webhookSecret` option), calls `onEvent(event)` and answers `200`. A request Timbereye did not sign gets `400`
|
|
278
|
+
and never reaches `onEvent`; a setup mistake or an error from `onEvent` goes to `next` in Express (or is thrown from
|
|
279
|
+
a Fetch handler), so the delivery is retried. Express needs the raw body:
|
|
280
|
+
`app.post(path, express.raw({ type: "application/json" }), te.webhooks.handler(onEvent))`; a Fetch route handler is
|
|
281
|
+
`export const POST = te.webhooks.handler(onEvent)`.
|
|
282
|
+
|
|
283
|
+
`te.webhooks.verify(req)`, or `te.webhooks.verify(rawBody, headers, secret, { toleranceSeconds? })`, is the same
|
|
284
|
+
check for code that answers the request itself. It implements Standard Webhooks:
|
|
285
|
+
HMAC-SHA256 over `${webhook-id}.${webhook-timestamp}.${body}` with the `whsec_<base64>` secret,
|
|
286
|
+
compared in constant time, timestamps within 5 minutes by default. Pass the raw body, not parsed JSON.
|
|
287
|
+
It accepts several space-separated signatures (secret rotation), and `secret` may be an array to
|
|
288
|
+
hold old and new secrets together. It returns the event, camelCased, as a union you narrow on `type`,
|
|
289
|
+
and throws `WebhookSignatureError` (with a `code` such as `signature_mismatch` or
|
|
290
|
+
`timestamp_out_of_tolerance`) on failure. It is async, because Web Crypto is: use `await`.
|
|
291
|
+
|
|
292
|
+
`te.webhookEndpoints.rollSecret(id)` rolls a signing secret: the new `secret` is returned once, the old one
|
|
293
|
+
stays valid until `previousSecretExpiresAt` (24 hours), and until then each delivery carries two
|
|
294
|
+
space-separated signatures, either of which verifies. `te.webhookEndpoints.test(id)` sends a test
|
|
295
|
+
delivery to that endpoint only and returns a `WebhookTest` reference (it is not in `events.list`).
|
|
296
|
+
`te.webhookEndpoints.listDeliveries(id, { status, type })` is the endpoint's delivery log (30 days),
|
|
297
|
+
`retrieveDelivery(deliveryId)` gives every attempt as sent and as received, and `resendDelivery(deliveryId)` sends one
|
|
298
|
+
again now. `verifyWebhook` is also exported on its own for code that has no client.
|
|
299
|
+
|
|
300
|
+
**Testing your handler.** `te.webhooks.generateTestHeaders({ payload, secret?, id?, timestamp? })` (or
|
|
301
|
+
`generateTestWebhookHeaders` without a client) returns the headers Timbereye would send with `payload`, the raw body
|
|
302
|
+
string, signed with `secret` (default: the client's webhook secret). `verify` and `handler` accept them; an old
|
|
303
|
+
`timestamp` (Unix seconds) or another secret is refused, as a forged delivery is. `webhook-id` defaults to the
|
|
304
|
+
event's `id`, as in a real delivery.
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
const body = JSON.stringify(sampleEvent) // the delivery's raw body
|
|
308
|
+
const headers = await timbereye.webhooks.generateTestHeaders({ payload: body })
|
|
309
|
+
const res = await onEvent(
|
|
310
|
+
new Request("http://localhost/webhooks/timbereye", { method: "POST", body, headers }),
|
|
311
|
+
)
|
|
312
|
+
// res.status === 200
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
To receive real events on your machine with no tunnel, `timbereye webhooks listen --forward-to
|
|
316
|
+
http://localhost:3000/webhooks/timbereye --secret-env TIMBEREYE_WEBHOOK_SECRET` ([CLI](https://www.timbereye.com/docs/cli/)).
|
|
317
|
+
|
|
318
|
+
## Key management (dashboard sessions only)
|
|
319
|
+
|
|
320
|
+
`te.apiKeys.list/create/roll/revoke` and `te.account.createTestAccount()` are for the Timbereye dashboard: they
|
|
321
|
+
need a signed-in user's session token (`new Timbereye(sessionToken, { mode: "test" })`) and every API key or
|
|
322
|
+
capture token is refused with 403 `session_required`, so a key can never mint or list keys. `create` and `roll`
|
|
323
|
+
return the full `secret` once; show it to the person, then drop it.
|
|
324
|
+
|
|
325
|
+
`te.team.members` (list, update, remove, transferOwnership), `te.team.invitations` (list, create, revoke,
|
|
326
|
+
resend, accept) and `te.auditLog.list` are dashboard-session only too. What a session may do depends on the
|
|
327
|
+
user's role in the organisation (owner, developer, editor or viewer; see the team roles guide): a refusal is a
|
|
328
|
+
`PermissionError` with code `role_required`, and a change that would leave no owner an `InvalidRequestError`
|
|
329
|
+
with code `last_owner`. `invitations.create` and `resend` return the accept `token` once.
|
|
330
|
+
|
|
331
|
+
## Types
|
|
332
|
+
|
|
333
|
+
Types are generated from the [OpenAPI document](https://www.timbereye.com/docs/openapi.yaml) with
|
|
334
|
+
`openapi-typescript`, and a test fails when they no longer match it. The public types
|
|
335
|
+
(`Group`, `Item`, `Scan`, `Event`, and `Schemas["..."]` for the rest) are the same types with camelCase
|
|
336
|
+
keys, derived by a type-level mapping. Two lists are single pages by contract (`volumeRules.list`, `scans.addItems`); they return a `Page` with `hasMore: false`. `scans.addItems` returns one entry per input item, in input order, each with the input's `clientId` and `created`. The API ignores unknown fields and enum values in v1, so do the same.
|
|
337
|
+
|
|
338
|
+
Licensed under the Apache License 2.0. Using the hosted Timbereye service through this package is governed by the [Terms of Service](https://www.timbereye.com/terms); what the service collects is in the [Privacy Policy](https://www.timbereye.com/privacy).
|
|
339
|
+
|
|
340
|
+
### Syncing a capture queue
|
|
341
|
+
|
|
342
|
+
The mobile SDKs' offline queue ([Working offline](https://www.timbereye.com/docs/working-offline/)) uses only calls
|
|
343
|
+
that are here, so a capture queue of your own can follow the same order: `scans.list({ clientId })` finds a scan
|
|
344
|
+
again after a lost response (a capture token may call it, within its groups), `scans.create`, `scans.addItems`
|
|
345
|
+
and `scans.addObservations` are idempotent by `clientId` and tag, `images.createSession` opens a new upload
|
|
346
|
+
session, `scans.uploadImage` takes `sha256`, `width`, `height`, `location`, `region`, `sourceImageId`,
|
|
347
|
+
`itemClientId` and `detections`, and `scans.submit(id, { endedAt })` is idempotent.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Case mapping between the API (snake_case JSON) and the SDK (camelCase).
|
|
3
|
+
*
|
|
4
|
+
* The mapping is purely mechanical: it is applied to object keys only, never to values, and the
|
|
5
|
+
* contents of free-form maps are left exactly as the caller or server wrote them. Opaque keys are
|
|
6
|
+
* listed once here; a test derives the same list from the OpenAPI document so they cannot drift.
|
|
7
|
+
*/
|
|
8
|
+
/** Property names (snake_case, as on the wire) whose value is a free-form map that must not be converted. */
|
|
9
|
+
export declare const OPAQUE_KEYS: readonly string[];
|
|
10
|
+
export declare function snakeToCamel(key: string): string;
|
|
11
|
+
export declare function camelToSnake(key: string): string;
|
|
12
|
+
/** Convert a request value from the SDK's camelCase to the API's snake_case. */
|
|
13
|
+
export declare function toSnake<T = unknown>(value: unknown): T;
|
|
14
|
+
/** Convert a response value from the API's snake_case to the SDK's camelCase. */
|
|
15
|
+
export declare function toCamel<T = unknown>(value: unknown): T;
|
|
16
|
+
/** Type-level twin of `snakeToCamel`. */
|
|
17
|
+
export type CamelKey<S extends string> = S extends `${infer H}_${infer R}` ? `${H}${Capitalize<CamelKey<R>>}` : S;
|
|
18
|
+
type OpaqueKey = "by_kind" | "headers" | "layout" | "metadata" | "msf" | "rejection_gates";
|
|
19
|
+
/** Type-level twin of `toCamel`: every object key camelCased except the contents of opaque maps. */
|
|
20
|
+
export type Camel<T> = T extends readonly (infer U)[] ? Camel<U>[] : T extends object ? {
|
|
21
|
+
[K in keyof T as K extends string ? CamelKey<K> : K]: K extends OpaqueKey ? T[K] : Camel<T[K]>;
|
|
22
|
+
} : T;
|
|
23
|
+
export {};
|
package/dist/cjs/case.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Case mapping between the API (snake_case JSON) and the SDK (camelCase).
|
|
4
|
+
*
|
|
5
|
+
* The mapping is purely mechanical: it is applied to object keys only, never to values, and the
|
|
6
|
+
* contents of free-form maps are left exactly as the caller or server wrote them. Opaque keys are
|
|
7
|
+
* listed once here; a test derives the same list from the OpenAPI document so they cannot drift.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.OPAQUE_KEYS = void 0;
|
|
11
|
+
exports.snakeToCamel = snakeToCamel;
|
|
12
|
+
exports.camelToSnake = camelToSnake;
|
|
13
|
+
exports.toSnake = toSnake;
|
|
14
|
+
exports.toCamel = toCamel;
|
|
15
|
+
/** Property names (snake_case, as on the wire) whose value is a free-form map that must not be converted. */
|
|
16
|
+
exports.OPAQUE_KEYS = [
|
|
17
|
+
"by_kind",
|
|
18
|
+
"details",
|
|
19
|
+
"headers",
|
|
20
|
+
"layout",
|
|
21
|
+
"metadata",
|
|
22
|
+
"msf",
|
|
23
|
+
"rejection_gates",
|
|
24
|
+
];
|
|
25
|
+
const OPAQUE_SNAKE = new Set(exports.OPAQUE_KEYS);
|
|
26
|
+
const OPAQUE_CAMEL = new Set(exports.OPAQUE_KEYS.map(snakeToCamel));
|
|
27
|
+
function snakeToCamel(key) {
|
|
28
|
+
return key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
29
|
+
}
|
|
30
|
+
function camelToSnake(key) {
|
|
31
|
+
return key.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
|
|
32
|
+
}
|
|
33
|
+
function isPlainObject(v) {
|
|
34
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
35
|
+
}
|
|
36
|
+
function convert(value, mapKey, opaque) {
|
|
37
|
+
if (Array.isArray(value))
|
|
38
|
+
return value.map((v) => convert(v, mapKey, opaque));
|
|
39
|
+
if (!isPlainObject(value))
|
|
40
|
+
return value;
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [k, v] of Object.entries(value)) {
|
|
43
|
+
out[mapKey(k)] = opaque.has(k) ? v : convert(v, mapKey, opaque);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
/** Convert a request value from the SDK's camelCase to the API's snake_case. */
|
|
48
|
+
function toSnake(value) {
|
|
49
|
+
return convert(value, camelToSnake, OPAQUE_CAMEL);
|
|
50
|
+
}
|
|
51
|
+
/** Convert a response value from the API's snake_case to the SDK's camelCase. */
|
|
52
|
+
function toCamel(value) {
|
|
53
|
+
return convert(value, snakeToCamel, OPAQUE_SNAKE);
|
|
54
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type ClientOptions } from "./http.js";
|
|
2
|
+
import { createResources } from "./resources.js";
|
|
3
|
+
import { type TestWebhookParams, type HeadersInput, type VerifyOptions, type WebhookRequest } from "./webhooks.js";
|
|
4
|
+
import type { WebhookEvent } from "./types.js";
|
|
5
|
+
/** The client's options: the transport's, plus the webhook signing secret. */
|
|
6
|
+
export interface TimbereyeOptions extends ClientOptions {
|
|
7
|
+
/** The API key; default `TIMBEREYE_SECRET_KEY` from the environment. */
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/**
|
|
10
|
+
* The webhook endpoint's signing secret (`whsec_…`) that `webhooks.verify(req)` uses; default
|
|
11
|
+
* `TIMBEREYE_WEBHOOK_SECRET` from the environment, read when `verify` is called.
|
|
12
|
+
*/
|
|
13
|
+
webhookSecret?: string | string[];
|
|
14
|
+
}
|
|
15
|
+
/** The webhook helpers on a client. */
|
|
16
|
+
export interface WebhookHelpers {
|
|
17
|
+
/**
|
|
18
|
+
* Verifies a delivery from the request it arrived on, with the client's webhook secret
|
|
19
|
+
* (`webhookSecret`, else `TIMBEREYE_WEBHOOK_SECRET`). The request must still carry the raw body: a
|
|
20
|
+
* Fetch `Request`, or a Node request behind `express.raw({ type: "application/json" })` (or one no
|
|
21
|
+
* middleware has read). A body that was already parsed is refused with `raw_body_required`.
|
|
22
|
+
*/
|
|
23
|
+
verify(req: WebhookRequest, options?: VerifyOptions): Promise<WebhookEvent>;
|
|
24
|
+
/** Verifies a delivery from its raw body, headers and the secret (or secrets, while rolling one). */
|
|
25
|
+
verify(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersInput, secret: string | string[], options?: VerifyOptions): Promise<WebhookEvent>;
|
|
26
|
+
/**
|
|
27
|
+
* A route handler that verifies each delivery, calls `onEvent` with the event, and answers `200`. A
|
|
28
|
+
* request Timbereye did not sign (bad or missing signature, stale timestamp, not JSON) is answered `400`
|
|
29
|
+
* and `onEvent` is not called. A mistake in your setup (no secret, a body already parsed) and an error
|
|
30
|
+
* thrown by `onEvent` are not hidden: they go to `next` in Express (or are thrown), so Timbereye retries
|
|
31
|
+
* the delivery once you fix it.
|
|
32
|
+
*
|
|
33
|
+
* Express: `app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), te.webhooks.handler(fn))`.
|
|
34
|
+
* Fetch (Next.js, Hono, Workers): `export const POST = te.webhooks.handler(fn)`.
|
|
35
|
+
*/
|
|
36
|
+
handler(onEvent: (event: WebhookEvent) => unknown, options?: VerifyOptions): WebhookRouteHandler;
|
|
37
|
+
/**
|
|
38
|
+
* For tests: the headers Timbereye would send with `payload`, signed with `secret` (default: the client's
|
|
39
|
+
* webhook secret, else `TIMBEREYE_WEBHOOK_SECRET`). `verify` and `handler` accept them. It signs; it never
|
|
40
|
+
* checks a request.
|
|
41
|
+
*/
|
|
42
|
+
generateTestHeaders(params: Omit<TestWebhookParams, "secret"> & {
|
|
43
|
+
secret?: string;
|
|
44
|
+
}): Promise<Record<string, string>>;
|
|
45
|
+
}
|
|
46
|
+
/** What `webhooks.handler` returns: a Fetch handler, or a Node/Express one. */
|
|
47
|
+
export interface WebhookRouteHandler {
|
|
48
|
+
(req: Request): Promise<Response>;
|
|
49
|
+
(req: WebhookRequest, res: WebhookResponse, next?: (error?: unknown) => void): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/** The part of a Node `ServerResponse` the handler uses. */
|
|
52
|
+
export interface WebhookResponse {
|
|
53
|
+
statusCode: number;
|
|
54
|
+
headersSent?: boolean;
|
|
55
|
+
setHeader(name: string, value: string): unknown;
|
|
56
|
+
end(body?: string): unknown;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* ```ts
|
|
60
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
61
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
62
|
+
* ```
|
|
63
|
+
*
|
|
64
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, baseUrl, ... })` also work; an
|
|
65
|
+
* explicit key, secret or `baseUrl` wins over the environment (`TIMBEREYE_SECRET_KEY`, `TIMBEREYE_WEBHOOK_SECRET`,
|
|
66
|
+
* `TIMBEREYE_API_URL`).
|
|
67
|
+
*/
|
|
68
|
+
export declare class Timbereye {
|
|
69
|
+
/** Test mode only: a simulated scan and refinement, so the loop can run with no device and no model. */
|
|
70
|
+
readonly testMode: ReturnType<typeof createResources>["testMode"];
|
|
71
|
+
readonly groups: ReturnType<typeof createResources>["groups"];
|
|
72
|
+
readonly items: ReturnType<typeof createResources>["items"];
|
|
73
|
+
readonly scans: ReturnType<typeof createResources>["scans"];
|
|
74
|
+
readonly images: ReturnType<typeof createResources>["images"];
|
|
75
|
+
readonly places: ReturnType<typeof createResources>["places"];
|
|
76
|
+
/** Tag printing: label designs for the 62 mm QR tags. */
|
|
77
|
+
readonly labelTemplates: ReturnType<typeof createResources>["labelTemplates"];
|
|
78
|
+
/** Tag printing: batches of tags and their ZPL or PDF print files. */
|
|
79
|
+
readonly tagBatches: ReturnType<typeof createResources>["tagBatches"];
|
|
80
|
+
readonly species: ReturnType<typeof createResources>["species"];
|
|
81
|
+
readonly volumeRules: ReturnType<typeof createResources>["volumeRules"];
|
|
82
|
+
readonly events: ReturnType<typeof createResources>["events"];
|
|
83
|
+
readonly webhookEndpoints: ReturnType<typeof createResources>["webhookEndpoints"];
|
|
84
|
+
readonly captureTokens: ReturnType<typeof createResources>["captureTokens"];
|
|
85
|
+
/** Key management: dashboard sessions only (an API key is refused with 403 `session_required`). */
|
|
86
|
+
readonly apiKeys: ReturnType<typeof createResources>["apiKeys"];
|
|
87
|
+
readonly team: ReturnType<typeof createResources>["team"];
|
|
88
|
+
readonly auditLog: ReturnType<typeof createResources>["auditLog"];
|
|
89
|
+
readonly usage: ReturnType<typeof createResources>["usage"];
|
|
90
|
+
/** The organisation's billing (dashboard sessions only). */
|
|
91
|
+
readonly billing: ReturnType<typeof createResources>["billing"];
|
|
92
|
+
readonly models: ReturnType<typeof createResources>["models"];
|
|
93
|
+
readonly account: ReturnType<typeof createResources>["account"];
|
|
94
|
+
/** The developer console's bootstrap and onboarding: dashboard sessions only. */
|
|
95
|
+
readonly console: ReturnType<typeof createResources>["console"];
|
|
96
|
+
readonly webhooks: WebhookHelpers;
|
|
97
|
+
constructor(apiKeyOrOptions?: string | TimbereyeOptions, options?: TimbereyeOptions);
|
|
98
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Timbereye = void 0;
|
|
4
|
+
const errors_js_1 = require("./errors.js");
|
|
5
|
+
const http_js_1 = require("./http.js");
|
|
6
|
+
const resources_js_1 = require("./resources.js");
|
|
7
|
+
const runtime_js_1 = require("./runtime.js");
|
|
8
|
+
const webhooks_js_1 = require("./webhooks.js");
|
|
9
|
+
/** Verification failures that mean "not from Timbereye": answered 400. Everything else is a setup mistake. */
|
|
10
|
+
const FORGED_CODES = new Set([
|
|
11
|
+
"missing_headers",
|
|
12
|
+
"invalid_timestamp",
|
|
13
|
+
"timestamp_out_of_tolerance",
|
|
14
|
+
"signature_mismatch",
|
|
15
|
+
"invalid_payload",
|
|
16
|
+
]);
|
|
17
|
+
/**
|
|
18
|
+
* ```ts
|
|
19
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
20
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, baseUrl, ... })` also work; an
|
|
24
|
+
* explicit key, secret or `baseUrl` wins over the environment (`TIMBEREYE_SECRET_KEY`, `TIMBEREYE_WEBHOOK_SECRET`,
|
|
25
|
+
* `TIMBEREYE_API_URL`).
|
|
26
|
+
*/
|
|
27
|
+
class Timbereye {
|
|
28
|
+
constructor(apiKeyOrOptions, options = {}) {
|
|
29
|
+
const merged = typeof apiKeyOrOptions === "object" && apiKeyOrOptions !== null
|
|
30
|
+
? apiKeyOrOptions
|
|
31
|
+
: { ...options, apiKey: apiKeyOrOptions ?? options.apiKey };
|
|
32
|
+
const { apiKey: explicitKey, webhookSecret, ...transportOptions } = merged;
|
|
33
|
+
const apiKey = explicitKey ?? (0, runtime_js_1.readEnv)("TIMBEREYE_SECRET_KEY");
|
|
34
|
+
if (apiKey === undefined) {
|
|
35
|
+
throw new errors_js_1.TimbereyeError({
|
|
36
|
+
message: "No Timbereye API key: set TIMBEREYE_SECRET_KEY in the environment, or pass the key: " +
|
|
37
|
+
'new Timbereye("te_test_sk_…").',
|
|
38
|
+
type: "client_error",
|
|
39
|
+
code: "api_key_missing",
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
this.webhooks = {
|
|
43
|
+
verify: ((first, ...rest) => {
|
|
44
|
+
if (typeof first === "string" ||
|
|
45
|
+
first instanceof Uint8Array ||
|
|
46
|
+
first instanceof ArrayBuffer) {
|
|
47
|
+
const [headers, secret, verifyOptions] = rest;
|
|
48
|
+
return (0, webhooks_js_1.verifyWebhook)(first, headers, secret, verifyOptions);
|
|
49
|
+
}
|
|
50
|
+
return verifyRequest(first, webhookSecret, rest[0]);
|
|
51
|
+
}),
|
|
52
|
+
handler: (onEvent, verifyOptions) => webhookHandler(webhookSecret, onEvent, verifyOptions),
|
|
53
|
+
generateTestHeaders: async (params) => {
|
|
54
|
+
const configured = Array.isArray(webhookSecret) ? webhookSecret[0] : webhookSecret;
|
|
55
|
+
const secret = params.secret ?? configured ?? (0, runtime_js_1.readEnv)("TIMBEREYE_WEBHOOK_SECRET");
|
|
56
|
+
if (secret === undefined)
|
|
57
|
+
throw new errors_js_1.WebhookSignatureError("webhook_secret_missing", "No webhook secret: pass { secret }, set TIMBEREYE_WEBHOOK_SECRET, or new Timbereye({ webhookSecret }).");
|
|
58
|
+
return (0, webhooks_js_1.generateTestWebhookHeaders)({ ...params, secret });
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
// An explicit baseUrl, else TIMBEREYE_API_URL where the runtime has an environment, else production.
|
|
62
|
+
const baseUrl = transportOptions.baseUrl ?? (0, runtime_js_1.readEnv)("TIMBEREYE_API_URL");
|
|
63
|
+
const r = (0, resources_js_1.createResources)(new http_js_1.Transport(apiKey, baseUrl === undefined ? transportOptions : { ...transportOptions, baseUrl }));
|
|
64
|
+
this.testMode = r.testMode;
|
|
65
|
+
this.groups = r.groups;
|
|
66
|
+
this.items = r.items;
|
|
67
|
+
this.scans = r.scans;
|
|
68
|
+
this.images = r.images;
|
|
69
|
+
this.places = r.places;
|
|
70
|
+
this.labelTemplates = r.labelTemplates;
|
|
71
|
+
this.tagBatches = r.tagBatches;
|
|
72
|
+
this.species = r.species;
|
|
73
|
+
this.volumeRules = r.volumeRules;
|
|
74
|
+
this.events = r.events;
|
|
75
|
+
this.webhookEndpoints = r.webhookEndpoints;
|
|
76
|
+
this.captureTokens = r.captureTokens;
|
|
77
|
+
this.apiKeys = r.apiKeys;
|
|
78
|
+
this.team = r.team;
|
|
79
|
+
this.auditLog = r.auditLog;
|
|
80
|
+
this.usage = r.usage;
|
|
81
|
+
this.billing = r.billing;
|
|
82
|
+
this.models = r.models;
|
|
83
|
+
this.account = r.account;
|
|
84
|
+
this.console = r.console;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
exports.Timbereye = Timbereye;
|
|
88
|
+
async function verifyRequest(req, configured, options) {
|
|
89
|
+
const secret = configured ?? (0, runtime_js_1.readEnv)("TIMBEREYE_WEBHOOK_SECRET");
|
|
90
|
+
if (secret === undefined || (Array.isArray(secret) && secret.length === 0)) {
|
|
91
|
+
throw new errors_js_1.WebhookSignatureError("webhook_secret_missing", "No webhook secret: set TIMBEREYE_WEBHOOK_SECRET (the endpoint's whsec_… secret) in the environment, " +
|
|
92
|
+
"or pass it: new Timbereye({ webhookSecret }).");
|
|
93
|
+
}
|
|
94
|
+
const { body, headers } = await (0, webhooks_js_1.readWebhookRequest)(req);
|
|
95
|
+
return (0, webhooks_js_1.verifyWebhook)(body, headers, secret, options);
|
|
96
|
+
}
|
|
97
|
+
function webhookHandler(configured, onEvent, options) {
|
|
98
|
+
return (async (req, res, next) => {
|
|
99
|
+
const answer = (status, body) => {
|
|
100
|
+
if (res === undefined)
|
|
101
|
+
return new Response(body, { status, headers: { "content-type": "application/json" } });
|
|
102
|
+
if (res.headersSent !== true) {
|
|
103
|
+
res.statusCode = status;
|
|
104
|
+
res.setHeader("content-type", "application/json");
|
|
105
|
+
res.end(body);
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
};
|
|
109
|
+
try {
|
|
110
|
+
let event;
|
|
111
|
+
try {
|
|
112
|
+
event = await verifyRequest(req, configured, options);
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (error instanceof errors_js_1.WebhookSignatureError &&
|
|
116
|
+
error.code !== null &&
|
|
117
|
+
FORGED_CODES.has(error.code))
|
|
118
|
+
return answer(400, JSON.stringify({ error: { code: error.code, message: error.message } }));
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
await onEvent(event);
|
|
122
|
+
return answer(200, "{}");
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (res === undefined)
|
|
126
|
+
throw error;
|
|
127
|
+
if (next !== undefined)
|
|
128
|
+
return next(error);
|
|
129
|
+
answer(500, JSON.stringify({ error: { code: "handler_error" } }));
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|