@tracken/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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tracken Technologies OÜ
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,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # @tracken/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed TypeScript client for Tracken Accounts' public API, generated from its public document.
4
+ Every v1 operation is a method on its resource, named the way the `tracken` CLI names its commands;
5
+ inputs and answers are typed from the document, and every call shares the CLI's transport: the token,
6
+ retries, an automatic `Idempotency-Key` and the 303 download of a rendition.
7
+
8
+ Published on npm as `@tracken/sdk` (`npm i @tracken/sdk`, Node.js 22 or later); the API it calls is still a
9
+ draft, so a release may break a client; the `@tracken/cli` package's `CHANGELOG.md` lists every change.
10
+ MIT license (`LICENSE`).
11
+
12
+ ```ts
13
+ import { Tracken, isApiError } from "@tracken/sdk";
14
+
15
+ const tracken = new Tracken({
16
+ environment: "dev", // or "prod" (the default)
17
+ auth: { clientId: process.env.TRACKEN_CLIENT_ID!, clientSecret: process.env.TRACKEN_CLIENT_SECRET! },
18
+ });
19
+
20
+ // Lists: one page, or every record across pages.
21
+ const page = await tracken.salesInvoices.list({ query: { status: ["draft"], limit: 50 } });
22
+ for await (const invoice of tracken.paginate("listSalesInvoices", { query: { status: ["draft"] } })) {
23
+ // Actions after the colon are methods: POST /sales-invoices/{id}:issue
24
+ try {
25
+ await tracken.salesInvoices.issue({ path: { id: invoice.id } }, { idempotencyKey: `issue-${invoice.id}` });
26
+ } catch (error) {
27
+ if (isApiError(error, "INVOICE_NOT_DRAFT")) continue;
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ // A rendition: the file's bytes.
33
+ const pdf = await tracken.salesInvoices.get({ path: { id }, query: { format: "pdf" } });
34
+
35
+ // Concurrency: send the ETag of the version you read.
36
+ const contact = await tracken.contacts.get({ path: { id } });
37
+ await tracken.contacts.update({ path: { id }, body: { data: { name: "Acme AS" } } }, { ifMatch: contact });
38
+ ```
39
+
40
+ ## Conventions
41
+
42
+ - **Bodies** are the document's: the record inside `{"data": …}`, with operation options such as
43
+ `on_conflict` beside it. `body` of an upload is a `FormData` or an object of its fields (`Blob`s for files).
44
+ - **Money, prices and quantities are decimal strings** (`"1234.50"`), never numbers. The types say
45
+ `string`, and a JavaScript number where the document expects a decimal is refused before the request
46
+ is sent. `isDecimal`, `toMinorUnits` and `fromMinorUnits` (exact, with `bigint`) help with arithmetic.
47
+ - **Answers** are `{ body, status, headers, requestId, etag, location, dryRun }`; `body` is the
48
+ parsed JSON, the file's bytes for a rendition, and `undefined` for a `204`.
49
+ - **Errors** are `TrackenApiError`s, of the subclass the status names (`TrackenValidationError`,
50
+ `TrackenConflictError`, `TrackenPreconditionFailedError`, `TrackenRateLimitedError`, …), with the
51
+ stable `code`, every field problem in `details`, `existingId`, `context` and `requestId`.
52
+ `isApiError(error, "CODE")` narrows to one code. The client retries `429` (after `Retry-After`),
53
+ gateway errors and network failures; requests it refuses to send throw `TrackenUsageError`.
54
+ - **Idempotency**: every POST carries an `Idempotency-Key`, reused on the client's own retries; pass
55
+ `idempotencyKey` to make your own retries safe too.
56
+ - **Jobs**: an operation that answers `202` returns the job; `tracken.waitForJob(response)` polls it.
57
+ - **Sync**: read changes with `updated_since` (and `sort: "updated_at"`); each answer's `nextSince`
58
+ is where the next pass starts.
59
+ - **A 401 is never masked**: the client renews once (a fresh client-credentials token, or your
60
+ `Credentials.renew`) and retries; a second 401, or a renewal Tracken ID refuses, is thrown as the
61
+ API's own `TrackenUnauthenticatedError`, with the refusal as `renewalError`.
62
+ - **Tracken-Agent**: every request names the program acting (`tracken-sdk/<version>` by default;
63
+ pass `agent: agentLabel("acme-sync", "2.1")`), which Accounts records in its audit log.
64
+ - **Any operation** by id: `tracken.call("issueSalesInvoice", { path: { id } })`; raw requests through
65
+ `tracken.client.send(…)`, and the typed openapi-fetch client as `tracken.http`.
66
+
67
+ Auth: `{ clientId, clientSecret, scope? }` for a machine credential (exchanged at Tracken ID with the
68
+ client-credentials grant and renewed as it nears expiry), `{ accessToken }` for a token you obtained
69
+ yourself, or any `Credentials` object. A person's token acts in one organization: pass
70
+ `organizationId`.
71
+
72
+ `DOCUMENT` names the public document (and its commit) this version was generated from.
package/SOURCE.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "repository": "Tracken-Technologies/tracken_accounts",
3
+ "path": "accounting-api/public_api/openapi.yaml",
4
+ "commit": "a2e2b6432ee189975da076b98c9979b2bdb95012",
5
+ "ref": "a2e2b6432",
6
+ "dirty": false,
7
+ "document_version": "2026-11-09",
8
+ "sha256": "f56551f5802179bf061a9de5ca9cd197b05a3674c267c036327b1b98a1f2ec68",
9
+ "synced_at": "2026-11-14T18:47:05Z"
10
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The transport every Tracken client shares (the SDK's typed methods, the CLI and its MCP server):
3
+ * requests go through openapi-fetch with the credential's bearer token, the organization header for a
4
+ * person, a User-Agent and `Tracken-Agent`, an automatic Idempotency-Key on every POST (the same key
5
+ * on the client's own retries), `Retry-After` on 429 and backoff on a gateway error. A rendition's 303
6
+ * is followed to its pre-signed link without any of those credentials.
7
+ *
8
+ * A 401 is never masked: the client renews once (a person's refresh, or a fresh client-credentials
9
+ * token) and retries; a second 401, or a renewal Tracken ID refuses, is thrown as the API's own 401
10
+ * (`TrackenUnauthenticatedError`, with the refusal as `renewalError`). The credentials a client is
11
+ * built with are the only ones it ever uses.
12
+ */
13
+ import { type Client } from "openapi-fetch";
14
+ import type { Credentials } from "./credentials.js";
15
+ import type { paths } from "./generated/schema.js";
16
+ import { type ApiRequest } from "./request.js";
17
+ import { type Clock, type Fetch } from "./runtime.js";
18
+ export interface ApiResponse {
19
+ status: number;
20
+ headers: Headers;
21
+ /** Parsed JSON; a `Uint8Array` for other content (a PDF, a KMD file); `undefined` for 204. */
22
+ body: unknown;
23
+ contentType: string;
24
+ binary: boolean;
25
+ requestId: string | undefined;
26
+ /** The API confirmed nothing was stored (`Tracken-Dry-Run: true`). */
27
+ dryRun: boolean;
28
+ }
29
+ export interface ClientOptions {
30
+ /** The API base including the major version (`https://accounts-api.tracken.ee/v1`). */
31
+ baseUrl: string;
32
+ credentials: Credentials;
33
+ /** The organization a person's requests act in (`X-Organization-ID`); a machine token names its own. */
34
+ organizationId?: string | undefined;
35
+ fetch?: Fetch;
36
+ clock?: Clock;
37
+ /** `et` or `en`: the language of error messages. */
38
+ language?: string | undefined;
39
+ /** Retries after 429, gateway errors and network failures (default 3). */
40
+ maxRetries?: number;
41
+ /** Sent as `User-Agent` (default `tracken-sdk/<version> (…)`). */
42
+ userAgent?: string;
43
+ /**
44
+ * Sent as `Tracken-Agent` (default `tracken-sdk/<version>`): the program acting with the token,
45
+ * which Accounts records in the audit log. Make it acceptable with `agentLabel(name, version)`.
46
+ */
47
+ agent?: string | undefined;
48
+ /**
49
+ * Whether an error `Credentials.renew` threw means Tracken ID refused the session or credential
50
+ * (the 401 is then thrown as the API's own); other errors propagate. Default: `TrackenAuthError`.
51
+ */
52
+ isRenewalRefusal?: (error: unknown) => boolean;
53
+ /** The message when a person's request needs an organization and none is set. */
54
+ missingOrganizationMessage?: string;
55
+ debug?: ((line: string) => void) | undefined;
56
+ }
57
+ /** The organization header is credentials, never a parameter: a person's token always names one. */
58
+ export declare const ORGANIZATION_HEADER = "X-Organization-ID";
59
+ /** A fresh `Idempotency-Key`: a random UUID, from the platform's Web Crypto. */
60
+ export declare function newIdempotencyKey(): string;
61
+ export declare class TrackenClient {
62
+ private readonly options;
63
+ /**
64
+ * The typed openapi-fetch client, for callers that know their operation at compile time: it adds
65
+ * the token, User-Agent and organization header, but neither retries nor renews; `send` does both.
66
+ */
67
+ readonly http: Client<paths>;
68
+ /** `send`'s own client: no middleware, since `send` sets every header itself per attempt. */
69
+ private readonly transport;
70
+ private readonly maxRetries;
71
+ private readonly clock;
72
+ private readonly userAgent;
73
+ private readonly agent;
74
+ constructor(options: ClientOptions);
75
+ get credentials(): Credentials;
76
+ get baseUrl(): string;
77
+ /** For `http` users: the token, User-Agent and organization header on every request. */
78
+ private authMiddleware;
79
+ private organizationFor;
80
+ private retryable;
81
+ private backoff;
82
+ /**
83
+ * Sends a request and answers its success, or throws a `TrackenApiError` for a non-2xx answer once
84
+ * retries are spent. `organization: null` leaves the organization header off.
85
+ */
86
+ send(request: ApiRequest): Promise<ApiResponse>;
87
+ /**
88
+ * A rendition (`format=pdf`) answers 303 with a short-lived pre-signed link to the file. The link
89
+ * carries its own signature, so it is fetched with neither the token nor the organization header
90
+ * (a storage service refuses a second credential, and the token must not leave the API). The link
91
+ * is itself a credential while it lives: messages name its origin only.
92
+ */
93
+ private download;
94
+ }
package/dist/client.js ADDED
@@ -0,0 +1,258 @@
1
+ /**
2
+ * The transport every Tracken client shares (the SDK's typed methods, the CLI and its MCP server):
3
+ * requests go through openapi-fetch with the credential's bearer token, the organization header for a
4
+ * person, a User-Agent and `Tracken-Agent`, an automatic Idempotency-Key on every POST (the same key
5
+ * on the client's own retries), `Retry-After` on 429 and backoff on a gateway error. A rendition's 303
6
+ * is followed to its pre-signed link without any of those credentials.
7
+ *
8
+ * A 401 is never masked: the client renews once (a person's refresh, or a fresh client-credentials
9
+ * token) and retries; a second 401, or a renewal Tracken ID refuses, is thrown as the API's own 401
10
+ * (`TrackenUnauthenticatedError`, with the refusal as `renewalError`). The credentials a client is
11
+ * built with are the only ones it ever uses.
12
+ */
13
+ import createClient, {} from "openapi-fetch";
14
+ import { apiError, TrackenAuthError, TrackenError, TrackenNetworkError, TrackenUsageError } from "./errors.js";
15
+ import { serializeQuery } from "./request.js";
16
+ import { AGENT_HEADER, systemClock, userAgent } from "./runtime.js";
17
+ import { SDK_VERSION } from "./version.js";
18
+ /** A 429 asking for longer than this is reported rather than slept through. */
19
+ const MAX_RETRY_AFTER_S = 120;
20
+ const GATEWAY_ERRORS = new Set([502, 503, 504]);
21
+ /** The organization header is credentials, never a parameter: a person's token always names one. */
22
+ export const ORGANIZATION_HEADER = "X-Organization-ID";
23
+ function parseRetryAfter(value, now) {
24
+ if (!value)
25
+ return undefined;
26
+ const seconds = Number(value);
27
+ if (Number.isFinite(seconds))
28
+ return Math.max(0, seconds);
29
+ const date = Date.parse(value);
30
+ return Number.isNaN(date) ? undefined : Math.max(0, (date - now) / 1000);
31
+ }
32
+ const hasHeader = (headers, name) => Object.keys(headers).some((key) => key.toLowerCase() === name.toLowerCase());
33
+ /** A fresh `Idempotency-Key`: a random UUID, from the platform's Web Crypto. */
34
+ export function newIdempotencyKey() {
35
+ return globalThis.crypto.randomUUID();
36
+ }
37
+ export class TrackenClient {
38
+ options;
39
+ /**
40
+ * The typed openapi-fetch client, for callers that know their operation at compile time: it adds
41
+ * the token, User-Agent and organization header, but neither retries nor renews; `send` does both.
42
+ */
43
+ http;
44
+ /** `send`'s own client: no middleware, since `send` sets every header itself per attempt. */
45
+ transport;
46
+ maxRetries;
47
+ clock;
48
+ userAgent;
49
+ agent;
50
+ constructor(options) {
51
+ this.options = options;
52
+ const fetchFn = (request) => (options.fetch ?? fetch)(request);
53
+ this.http = createClient({ baseUrl: options.baseUrl, fetch: fetchFn });
54
+ this.http.use(this.authMiddleware());
55
+ this.transport = createClient({ baseUrl: options.baseUrl, fetch: fetchFn });
56
+ this.maxRetries = options.maxRetries ?? 3;
57
+ this.clock = options.clock ?? systemClock;
58
+ this.userAgent = options.userAgent ?? userAgent();
59
+ this.agent = options.agent ?? `tracken-sdk/${SDK_VERSION}`;
60
+ }
61
+ get credentials() {
62
+ return this.options.credentials;
63
+ }
64
+ get baseUrl() {
65
+ return this.options.baseUrl;
66
+ }
67
+ /** For `http` users: the token, User-Agent and organization header on every request. */
68
+ authMiddleware() {
69
+ return {
70
+ onRequest: async ({ request }) => {
71
+ request.headers.set("Authorization", `Bearer ${await this.options.credentials.accessToken()}`);
72
+ request.headers.set("User-Agent", this.userAgent);
73
+ if (!request.headers.has(AGENT_HEADER))
74
+ request.headers.set(AGENT_HEADER, this.agent);
75
+ if (this.options.language && !request.headers.has("Accept-Language"))
76
+ request.headers.set("Accept-Language", this.options.language);
77
+ if (this.options.credentials.kind === "user" && this.options.organizationId && !request.headers.has(ORGANIZATION_HEADER)) {
78
+ request.headers.set(ORGANIZATION_HEADER, this.options.organizationId);
79
+ }
80
+ return request;
81
+ },
82
+ };
83
+ }
84
+ organizationFor(request) {
85
+ if (this.options.credentials.kind !== "user")
86
+ return undefined;
87
+ if (request.organization === null)
88
+ return undefined;
89
+ const organization = request.organization ?? this.options.organizationId;
90
+ if (!organization && request.operation?.organization) {
91
+ throw new TrackenUsageError(this.options.missingOrganizationMessage ??
92
+ `${request.operation.operationId} acts in one organization: set organizationId (sent as ${ORGANIZATION_HEADER}) for a person's token.`);
93
+ }
94
+ return organization;
95
+ }
96
+ retryable(method, headers) {
97
+ return method === "GET" || method === "PUT" || method === "DELETE" || hasHeader(headers, "Idempotency-Key");
98
+ }
99
+ backoff(attempt) {
100
+ return Math.min(8000, 500 * 2 ** (attempt - 1));
101
+ }
102
+ /**
103
+ * Sends a request and answers its success, or throws a `TrackenApiError` for a non-2xx answer once
104
+ * retries are spent. `organization: null` leaves the organization header off.
105
+ */
106
+ async send(request) {
107
+ const method = request.method.toUpperCase();
108
+ const headers = { ...request.headers };
109
+ if (method === "POST" && !hasHeader(headers, "Idempotency-Key"))
110
+ headers["Idempotency-Key"] = newIdempotencyKey();
111
+ const organization = this.organizationFor(request);
112
+ const call = this.transport.request;
113
+ const query = serializeQuery(request.query);
114
+ let renewed = false;
115
+ let attempt = 0;
116
+ for (;;) {
117
+ request.signal?.throwIfAborted();
118
+ const token = await this.options.credentials.accessToken();
119
+ const sent = { ...headers, Authorization: `Bearer ${token}`, "User-Agent": this.userAgent };
120
+ if (!hasHeader(sent, AGENT_HEADER))
121
+ sent[AGENT_HEADER] = this.agent;
122
+ if (organization)
123
+ sent[ORGANIZATION_HEADER] = organization;
124
+ if (this.options.language && !hasHeader(sent, "Accept-Language"))
125
+ sent["Accept-Language"] = this.options.language;
126
+ const started = this.clock.now();
127
+ this.options.debug?.(`→ ${method} ${this.options.baseUrl}${request.path}${query ? `?${query}` : ""}`);
128
+ let result;
129
+ try {
130
+ const init = {
131
+ params: { path: request.pathParams },
132
+ headers: sent,
133
+ body: request.body,
134
+ querySerializer: () => query,
135
+ bodySerializer: (body) => (body instanceof FormData ? body : JSON.stringify(body)),
136
+ parseAs: "arrayBuffer",
137
+ // A redirect is never followed with the token: see `download`.
138
+ redirect: "manual",
139
+ };
140
+ if (request.signal)
141
+ init.signal = request.signal;
142
+ result = await call(method, request.path, init);
143
+ }
144
+ catch (error) {
145
+ if (error instanceof TrackenError)
146
+ throw error;
147
+ request.signal?.throwIfAborted();
148
+ if (attempt < this.maxRetries && this.retryable(method, headers)) {
149
+ attempt++;
150
+ await this.clock.sleep(this.backoff(attempt));
151
+ continue;
152
+ }
153
+ throw new TrackenNetworkError(`Could not reach ${new URL(this.options.baseUrl).origin}: ${error.message}`, error);
154
+ }
155
+ const { response } = result;
156
+ const requestId = response.headers.get("x-request-id") ?? undefined;
157
+ this.options.debug?.(`← ${response.status} in ${this.clock.now() - started} ms${requestId ? ` (${requestId})` : ""}`);
158
+ if (response.status === 401) {
159
+ const refused = apiError(401, result.error, response.headers);
160
+ if (renewed)
161
+ throw refused;
162
+ renewed = true;
163
+ this.options.debug?.(` 401: renewing the ${this.options.credentials.kind === "machine" ? "client-credentials token" : "session (refresh)"} once`);
164
+ try {
165
+ await this.options.credentials.renew(token);
166
+ }
167
+ catch (error) {
168
+ // Tracken ID refused the renewal: the session ended or the credential is gone. Network
169
+ // failures and other errors keep their own type.
170
+ if (!(this.options.isRenewalRefusal ?? ((value) => value instanceof TrackenAuthError))(error))
171
+ throw error;
172
+ this.options.debug?.(` renewal refused: ${error.message}`);
173
+ refused.renewalError = error;
174
+ throw refused;
175
+ }
176
+ continue;
177
+ }
178
+ if (response.status === 429 && attempt < this.maxRetries) {
179
+ const wait = parseRetryAfter(response.headers.get("retry-after"), this.clock.now()) ?? this.backoff(attempt + 1) / 1000;
180
+ if (wait <= MAX_RETRY_AFTER_S) {
181
+ attempt++;
182
+ this.options.debug?.(` rate limited; retrying in ${wait} s`);
183
+ await this.clock.sleep(wait * 1000);
184
+ continue;
185
+ }
186
+ }
187
+ if (GATEWAY_ERRORS.has(response.status) && attempt < this.maxRetries && this.retryable(method, headers)) {
188
+ attempt++;
189
+ await this.clock.sleep(this.backoff(attempt));
190
+ continue;
191
+ }
192
+ if (response.status === 303)
193
+ return await this.download(response, requestId, request.signal);
194
+ if (!response.ok)
195
+ throw apiError(response.status, result.error, response.headers);
196
+ return answer(response.status, response.headers, result.data instanceof ArrayBuffer ? new Uint8Array(result.data) : undefined, requestId);
197
+ }
198
+ }
199
+ /**
200
+ * A rendition (`format=pdf`) answers 303 with a short-lived pre-signed link to the file. The link
201
+ * carries its own signature, so it is fetched with neither the token nor the organization header
202
+ * (a storage service refuses a second credential, and the token must not leave the API). The link
203
+ * is itself a credential while it lives: messages name its origin only.
204
+ */
205
+ async download(redirect, requestId, signal) {
206
+ const location = redirect.headers.get("location");
207
+ let url;
208
+ try {
209
+ url = location ? new URL(location, redirect.url || this.options.baseUrl) : undefined;
210
+ }
211
+ catch {
212
+ url = undefined;
213
+ }
214
+ if (!url || (url.protocol !== "https:" && url.protocol !== "http:")) {
215
+ throw new TrackenError(`The API answered 303 without a usable Location${requestId ? ` (request id ${requestId})` : ""}.`);
216
+ }
217
+ this.options.debug?.(`→ GET ${url.origin}${url.pathname} (pre-signed link)`);
218
+ let file;
219
+ try {
220
+ const init = { headers: { "User-Agent": this.userAgent } };
221
+ if (signal)
222
+ init.signal = signal;
223
+ file = await (this.options.fetch ?? fetch)(url.href, init);
224
+ }
225
+ catch (error) {
226
+ signal?.throwIfAborted();
227
+ throw new TrackenNetworkError(`Could not download the file from ${url.origin}: ${error.message}`, error);
228
+ }
229
+ if (!file.ok) {
230
+ throw new TrackenError(`Downloading the file from ${url.origin} failed with ${file.status}; the link may have expired, so run the request again.`);
231
+ }
232
+ return answer(file.status, file.headers, new Uint8Array(await file.arrayBuffer()), requestId);
233
+ }
234
+ }
235
+ /** A success: JSON parsed, other content (a PDF, a KMD file) kept as bytes. */
236
+ function answer(status, headers, bytes, requestId) {
237
+ const contentType = headers.get("content-type") ?? "";
238
+ const isJson = /\bjson\b/i.test(contentType);
239
+ let body = bytes;
240
+ if (bytes && (isJson || bytes.length === 0)) {
241
+ const text = new TextDecoder().decode(bytes);
242
+ try {
243
+ body = text ? JSON.parse(text) : undefined;
244
+ }
245
+ catch {
246
+ body = text;
247
+ }
248
+ }
249
+ return {
250
+ status,
251
+ headers,
252
+ body,
253
+ contentType,
254
+ binary: bytes !== undefined && !isJson && bytes.length > 0,
255
+ requestId,
256
+ dryRun: headers.get("tracken-dry-run")?.toLowerCase() === "true",
257
+ };
258
+ }
@@ -0,0 +1,60 @@
1
+ import { type Clock, type Fetch } from "./runtime.js";
2
+ export interface Credentials {
3
+ /** A person acts in the organization the client names; a machine token carries its own. */
4
+ readonly kind: "user" | "machine";
5
+ /** A token valid for at least the next minute. */
6
+ accessToken(): Promise<string>;
7
+ /** After the API answered 401 to `rejected`: obtain a new token, or throw. */
8
+ renew(rejected: string): Promise<void>;
9
+ }
10
+ /**
11
+ * A token the caller manages (a person's access token, or one minted elsewhere). It is never
12
+ * renewed, so a 401 surfaces as `TrackenUnauthenticatedError`. Pass a function to read the current
13
+ * token on every request.
14
+ */
15
+ export declare function staticToken(token: string | (() => string | Promise<string>), kind?: Credentials["kind"]): Credentials;
16
+ export interface TokenResponse {
17
+ access_token: string;
18
+ token_type: string;
19
+ expires_in?: number;
20
+ refresh_token?: string;
21
+ scope?: string;
22
+ id_token?: string;
23
+ }
24
+ /** A JWT's claims, unverified: only to know when it lapses, never to trust. */
25
+ export declare function jwtClaims(token: string): Record<string, unknown>;
26
+ /** When a JWT access token lapses (epoch ms), from its `exp` claim. */
27
+ export declare function jwtExpiry(token: string): number | undefined;
28
+ /** Renew this long before the access token lapses, so a request never leaves with a dying token. */
29
+ export declare const EXPIRY_SKEW_MS = 60000;
30
+ /** When `tokens` lapse (epoch ms): the sooner of `expires_in` and the token's own `exp`. */
31
+ export declare function tokenExpiry(tokens: TokenResponse, now: number): number;
32
+ export interface ClientCredentialsOptions {
33
+ /** Tracken ID (`https://id.tracken.ee`). */
34
+ issuer: string;
35
+ /** The resource the token is for: the API's integration audience. */
36
+ audience: string;
37
+ clientId: string;
38
+ clientSecret: string;
39
+ /** Space-separated scopes; absent asks for everything the credential holds. */
40
+ scope?: string | undefined;
41
+ fetch?: Fetch;
42
+ clock?: Clock;
43
+ userAgent?: string;
44
+ }
45
+ /** A machine credential: client-credentials tokens from Tracken ID, in memory only. */
46
+ export declare class ClientCredentials implements Credentials {
47
+ private readonly options;
48
+ readonly kind = "machine";
49
+ private token;
50
+ private expires;
51
+ private pending;
52
+ constructor(options: ClientCredentialsOptions);
53
+ get clientId(): string;
54
+ private now;
55
+ /** One token request at a time: concurrent callers share it rather than each minting their own. */
56
+ private issue;
57
+ private request;
58
+ accessToken(): Promise<string>;
59
+ renew(rejected: string): Promise<void>;
60
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Who a client acts as. A machine credential (an API key created in Accounts under Settings → API
3
+ * access) is exchanged at Tracken ID for a short-lived token (OAuth 2.0 client credentials), kept in
4
+ * memory and renewed as it nears expiry; a person's token is obtained elsewhere (Tracken ID sign-in,
5
+ * the CLI's device flow) and handed in as is.
6
+ */
7
+ import { TrackenAuthError, TrackenNetworkError } from "./errors.js";
8
+ import { systemClock, userAgent } from "./runtime.js";
9
+ /**
10
+ * A token the caller manages (a person's access token, or one minted elsewhere). It is never
11
+ * renewed, so a 401 surfaces as `TrackenUnauthenticatedError`. Pass a function to read the current
12
+ * token on every request.
13
+ */
14
+ export function staticToken(token, kind = "machine") {
15
+ return {
16
+ kind,
17
+ accessToken: async () => (typeof token === "function" ? await token() : token),
18
+ renew: async () => { },
19
+ };
20
+ }
21
+ /** A JWT's claims, unverified: only to know when it lapses, never to trust. */
22
+ export function jwtClaims(token) {
23
+ const payload = token.split(".")[1];
24
+ if (!payload)
25
+ return {};
26
+ try {
27
+ const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
28
+ const bytes = Uint8Array.from(atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=")), (char) => char.charCodeAt(0));
29
+ const claims = JSON.parse(new TextDecoder().decode(bytes));
30
+ return typeof claims === "object" && claims !== null ? claims : {};
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ }
36
+ /** When a JWT access token lapses (epoch ms), from its `exp` claim. */
37
+ export function jwtExpiry(token) {
38
+ const exp = jwtClaims(token).exp;
39
+ return typeof exp === "number" ? exp * 1000 : undefined;
40
+ }
41
+ /** Renew this long before the access token lapses, so a request never leaves with a dying token. */
42
+ export const EXPIRY_SKEW_MS = 60_000;
43
+ /** Tracken ID's access tokens for Accounts last 15 minutes; used when a response names no lifetime. */
44
+ const DEFAULT_LIFETIME_MS = 15 * 60_000;
45
+ /** When `tokens` lapse (epoch ms): the sooner of `expires_in` and the token's own `exp`. */
46
+ export function tokenExpiry(tokens, now) {
47
+ const fromResponse = typeof tokens.expires_in === "number" ? now + tokens.expires_in * 1000 : undefined;
48
+ const fromToken = jwtExpiry(tokens.access_token);
49
+ const known = [fromResponse, fromToken].filter((value) => value !== undefined);
50
+ return known.length > 0 ? Math.min(...known) : now + DEFAULT_LIFETIME_MS;
51
+ }
52
+ /** A machine credential: client-credentials tokens from Tracken ID, in memory only. */
53
+ export class ClientCredentials {
54
+ options;
55
+ kind = "machine";
56
+ token;
57
+ expires = 0;
58
+ pending;
59
+ constructor(options) {
60
+ this.options = options;
61
+ }
62
+ get clientId() {
63
+ return this.options.clientId;
64
+ }
65
+ now() {
66
+ return (this.options.clock ?? systemClock).now();
67
+ }
68
+ /** One token request at a time: concurrent callers share it rather than each minting their own. */
69
+ issue() {
70
+ this.pending ??= this.request().finally(() => {
71
+ this.pending = undefined;
72
+ });
73
+ return this.pending;
74
+ }
75
+ async request() {
76
+ const { issuer, audience, clientId, clientSecret, scope } = this.options;
77
+ const url = `${issuer.replace(/\/+$/, "")}/token`;
78
+ const form = { grant_type: "client_credentials", resource: audience };
79
+ if (scope)
80
+ form.scope = scope;
81
+ // RFC 6749 §2.3.1: the id and secret are form-encoded before the Basic encoding.
82
+ const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;
83
+ const headers = {
84
+ "content-type": "application/x-www-form-urlencoded",
85
+ accept: "application/json",
86
+ "user-agent": this.options.userAgent ?? userAgent(),
87
+ authorization: `Basic ${btoa(pair)}`,
88
+ };
89
+ let response;
90
+ try {
91
+ response = await (this.options.fetch ?? fetch)(url, { method: "POST", headers, body: new URLSearchParams(form) });
92
+ }
93
+ catch (error) {
94
+ throw new TrackenNetworkError(`Could not reach Tracken ID at ${new URL(url).origin}: ${error.message}`, error);
95
+ }
96
+ const text = await response.text();
97
+ let body;
98
+ try {
99
+ body = text ? JSON.parse(text) : {};
100
+ }
101
+ catch {
102
+ body = { error: "invalid_response", error_description: `HTTP ${response.status} from ${new URL(url).pathname}: ${text.slice(0, 200)}` };
103
+ }
104
+ if (response.status !== 200 || typeof body.access_token !== "string") {
105
+ const code = typeof body.error === "string" ? body.error : `http_${response.status}`;
106
+ throw new TrackenAuthError(code, typeof body.error_description === "string" ? body.error_description : undefined, response.status);
107
+ }
108
+ const tokens = body;
109
+ this.token = tokens.access_token;
110
+ this.expires = tokenExpiry(tokens, this.now());
111
+ return this.token;
112
+ }
113
+ async accessToken() {
114
+ if (this.token && this.now() < this.expires - EXPIRY_SKEW_MS)
115
+ return this.token;
116
+ return this.issue();
117
+ }
118
+ async renew(rejected) {
119
+ if (this.token === rejected || this.token === undefined)
120
+ await this.issue();
121
+ }
122
+ }
@@ -0,0 +1,20 @@
1
+ import { DECIMAL_PATTERNS } from "./generated/operations.js";
2
+ /**
3
+ * The document's decimal schemas: `MoneyAmount` (2 places), `UnitPrice` and `Quantity` (4), a billing
4
+ * run's `VariableDecimal` (6), `LineDecimal` (10) and the positive `ExchangeRate` (10).
5
+ */
6
+ export type DecimalFormat = keyof typeof DECIMAL_PATTERNS;
7
+ /** Whether `value` is a decimal string the API accepts as `format` (default `MoneyAmount`). */
8
+ export declare function isDecimal(value: unknown, format?: DecimalFormat): value is string;
9
+ /**
10
+ * Integer minor units of a decimal string: `toMinorUnits("1234.50")` is `123450n`. Refuses a value
11
+ * with more fraction digits than `scale` rather than rounding it.
12
+ */
13
+ export declare function toMinorUnits(value: string, scale?: number): bigint;
14
+ /** The decimal string of integer minor units: `fromMinorUnits(123450n)` is `"1234.50"`. */
15
+ export declare function fromMinorUnits(minor: bigint | number, scale?: number): string;
16
+ /**
17
+ * Throws `TrackenUsageError` when the body holds a number at any of the operation's decimal
18
+ * pointers (such as `/data/lines/<any index>/unit_price`).
19
+ */
20
+ export declare function assertDecimalStrings(body: unknown, pointers: readonly string[], operationId: string): void;