@tamr/api 0.0.0-stage → 1.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.
@@ -0,0 +1,16 @@
1
+ import { type CallOptions, type ExternalIdsPutRequest, type ExternalIdsPutResponse, type NutritionPutRequest, type NutritionPutResponse, type SdkEraseUserResponse, type SdkLaunchCodesRequest, type SdkLaunchCodesResponse, type SdkOrdersRequest, type SdkOrdersResponse, type SdkTreatRedeemRequest, type SdkTreatRedeemResponse, type Transport } from "./api.g.js";
2
+ /** The Server API: a secret key, server to server only. */
3
+ export declare function serverOperations(transport: Transport): {
4
+ /** Mint a one-time launch code for one of your users */
5
+ sdkLaunchCodes: (body: SdkLaunchCodesRequest, options?: CallOptions) => Promise<SdkLaunchCodesResponse>;
6
+ /** Erase what Tamr holds for one of your users */
7
+ sdkEraseUser: (externalUserId: string, options?: CallOptions) => Promise<SdkEraseUserResponse>;
8
+ /** Send an order your own checkout placed */
9
+ sdkOrders: (body: SdkOrdersRequest, options?: CallOptions) => Promise<SdkOrdersResponse>;
10
+ /** Redeem a treat your checkout gave at zero */
11
+ sdkTreatRedeem: (treatId: string, body: SdkTreatRedeemRequest, options?: CallOptions) => Promise<SdkTreatRedeemResponse>;
12
+ /** Set your ids for the restaurant's dishes, sizes and options */
13
+ externalIdsPut: (body: ExternalIdsPutRequest, options?: CallOptions) => Promise<ExternalIdsPutResponse>;
14
+ /** Set your own nutrition figures for the restaurant's dishes */
15
+ nutritionPut: (body: NutritionPutRequest, options?: CallOptions) => Promise<NutritionPutResponse>;
16
+ };
@@ -0,0 +1,67 @@
1
+ // Generated from packages/sdk-contract by `pnpm sdk:generate`. Do not edit.
2
+ // `@tamr/api/server`'s operations, apart from the browser entry (#448).
3
+ import { decodeExternalIdsPutResponse, decodeNutritionPutResponse, decodeSdkEraseUserResponse, decodeSdkLaunchCodesResponse, decodeSdkOrdersResponse, decodeSdkTreatRedeemResponse, } from "./api.g.js";
4
+ /** The Server API: a secret key, server to server only. */
5
+ export function serverOperations(transport) {
6
+ return {
7
+ /** Mint a one-time launch code for one of your users */
8
+ sdkLaunchCodes: async (body, options = {}) => {
9
+ const value = await transport.request({
10
+ method: "POST",
11
+ path: "/v1/sdk/launch-codes",
12
+ body,
13
+ ...(options.signal ? { signal: options.signal } : {}),
14
+ });
15
+ return decodeSdkLaunchCodesResponse(value, "SdkLaunchCodes");
16
+ },
17
+ /** Erase what Tamr holds for one of your users */
18
+ sdkEraseUser: async (externalUserId, options = {}) => {
19
+ const value = await transport.request({
20
+ method: "DELETE",
21
+ path: `/v1/sdk/users/${encodeURIComponent(externalUserId)}`,
22
+ ...(options.signal ? { signal: options.signal } : {}),
23
+ });
24
+ return decodeSdkEraseUserResponse(value, "SdkEraseUser");
25
+ },
26
+ /** Send an order your own checkout placed */
27
+ sdkOrders: async (body, options = {}) => {
28
+ const value = await transport.request({
29
+ method: "POST",
30
+ path: "/v1/sdk/orders",
31
+ body,
32
+ ...(options.signal ? { signal: options.signal } : {}),
33
+ });
34
+ return decodeSdkOrdersResponse(value, "SdkOrders");
35
+ },
36
+ /** Redeem a treat your checkout gave at zero */
37
+ sdkTreatRedeem: async (treatId, body, options = {}) => {
38
+ const value = await transport.request({
39
+ method: "POST",
40
+ path: `/v1/sdk/treats/${encodeURIComponent(treatId)}/redeem`,
41
+ body,
42
+ ...(options.signal ? { signal: options.signal } : {}),
43
+ });
44
+ return decodeSdkTreatRedeemResponse(value, "SdkTreatRedeem");
45
+ },
46
+ /** Set your ids for the restaurant's dishes, sizes and options */
47
+ externalIdsPut: async (body, options = {}) => {
48
+ const value = await transport.request({
49
+ method: "PUT",
50
+ path: "/v1/catalog/external-ids",
51
+ body,
52
+ ...(options.signal ? { signal: options.signal } : {}),
53
+ });
54
+ return decodeExternalIdsPutResponse(value, "ExternalIdsPut");
55
+ },
56
+ /** Set your own nutrition figures for the restaurant's dishes */
57
+ nutritionPut: async (body, options = {}) => {
58
+ const value = await transport.request({
59
+ method: "PUT",
60
+ path: "/v1/catalog/nutrition",
61
+ body,
62
+ ...(options.signal ? { signal: options.signal } : {}),
63
+ });
64
+ return decodeNutritionPutResponse(value, "NutritionPut");
65
+ },
66
+ };
67
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@tamr/api`: the Client API, for an app that draws its own waiter UI. The
3
+ * Server API is `@tamr/api/server`. Guide: `docs/sdk/api.md`.
4
+ */
5
+ export { type ClientOptions, createClient, type Launch, TAMR_API, type TamrClient, } from "./client.js";
6
+ export * from "./generated/api.g.js";
7
+ export { TamrApiError } from "./transport.js";
8
+ export { SDK_VERSION } from "./version.js";
package/lib/index.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@tamr/api`: the Client API, for an app that draws its own waiter UI. The
3
+ * Server API is `@tamr/api/server`. Guide: `docs/sdk/api.md`.
4
+ */
5
+ export { createClient, TAMR_API, } from "./client.js";
6
+ export * from "./generated/api.g.js";
7
+ export { TamrApiError } from "./transport.js";
8
+ export { SDK_VERSION } from "./version.js";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The Server API (`docs/sdk/api.md`): your backend, with a secret key.
3
+ * Launch codes, your catalog's ids, your orders and erasing a user.
4
+ */
5
+ export interface ServerClientOptions {
6
+ /** A secret API key. Never ship it to a browser or an app. */
7
+ secretKey: string;
8
+ /** Defaults to Tamr's API. */
9
+ baseUrl?: string;
10
+ fetch?: typeof fetch;
11
+ }
12
+ export declare function createServerClient(options: ServerClientOptions): {
13
+ sdkLaunchCodes: (body: import("./generated/api.g.js").SdkLaunchCodesRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").SdkLaunchCodesResponse>;
14
+ sdkEraseUser: (externalUserId: string, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").SdkEraseUserResponse>;
15
+ sdkOrders: (body: import("./generated/api.g.js").SdkOrdersRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").SdkOrdersResponse>;
16
+ sdkTreatRedeem: (treatId: string, body: import("./generated/api.g.js").SdkTreatRedeemRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").SdkTreatRedeemResponse>;
17
+ externalIdsPut: (body: import("./generated/api.g.js").ExternalIdsPutRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ExternalIdsPutResponse>;
18
+ nutritionPut: (body: import("./generated/api.g.js").NutritionPutRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").NutritionPutResponse>;
19
+ };
20
+ export type TamrServerClient = ReturnType<typeof createServerClient>;
21
+ export * from "./generated/api.g.js";
22
+ export { TamrApiError } from "./transport.js";
package/lib/server.js ADDED
@@ -0,0 +1,16 @@
1
+ import { serverOperations } from "./generated/server.g.js";
2
+ import { createTransport } from "./transport.js";
3
+ export function createServerClient(options) {
4
+ // A secret key in a web bundle is a leaked key: refuse before it is ever sent.
5
+ if (typeof window !== "undefined") {
6
+ throw new Error("createServerClient runs on your server only: a secret key must never reach a browser. Use createClient with your publishable key there.");
7
+ }
8
+ return serverOperations(createTransport({
9
+ baseUrl: options.baseUrl ?? "https://tamr.link/api",
10
+ fetch: options.fetch ??
11
+ ((...args) => fetch(...args)),
12
+ headers: () => ({ authorization: `Bearer ${options.secretKey}` }),
13
+ }));
14
+ }
15
+ export * from "./generated/api.g.js";
16
+ export { TamrApiError } from "./transport.js";
@@ -0,0 +1,42 @@
1
+ import { type Transport } from "./generated/api.g.js";
2
+ /**
3
+ * How `@tamr/api` reaches Tamr: one `fetch` per call, the error body read
4
+ * into a `TamrApiError`, and the chat's server-sent events read into typed
5
+ * events. Shared by the Client API and the Server API.
6
+ */
7
+ /** Tamr refused a call. `code` is the stable lower-case reason (`docs/sdk/api.md`, Errors). */
8
+ export declare class TamrApiError extends Error {
9
+ readonly status: number;
10
+ /** The stable reason, such as `rate_limited` or `session_expired`; `network` when Tamr wasn't reached. */
11
+ readonly code: string;
12
+ /** Give it to Tamr's support with the time. */
13
+ readonly requestId: string | null;
14
+ /** Seconds to wait before trying again, when Tamr says. */
15
+ readonly retryAfter: number | null;
16
+ /** The error's `data`, with any extra fields its code carries. */
17
+ readonly data: Record<string, unknown>;
18
+ readonly name = "TamrApiError";
19
+ constructor(status: number,
20
+ /** The stable reason, such as `rate_limited` or `session_expired`; `network` when Tamr wasn't reached. */
21
+ code: string, message: string,
22
+ /** Give it to Tamr's support with the time. */
23
+ requestId: string | null,
24
+ /** Seconds to wait before trying again, when Tamr says. */
25
+ retryAfter: number | null,
26
+ /** The error's `data`, with any extra fields its code carries. */
27
+ data: Record<string, unknown>);
28
+ }
29
+ export interface TransportOptions {
30
+ baseUrl: string;
31
+ fetch: typeof fetch;
32
+ /** The headers every call carries (the key, the device, the session). */
33
+ headers: () => Record<string, string>;
34
+ /** Called once when a call answers 401; true sends it again, once. */
35
+ renew?: (error: TamrApiError) => Promise<boolean>;
36
+ }
37
+ export declare function createTransport(options: TransportOptions): Transport;
38
+ /** Server-sent events (the WHATWG format): `event:` and `data:` lines, a blank line ends one. */
39
+ export declare function serverSentEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<{
40
+ event: string;
41
+ data: string;
42
+ }>;
@@ -0,0 +1,181 @@
1
+ import { ContractError } from "./generated/api.g.js";
2
+ /**
3
+ * How `@tamr/api` reaches Tamr: one `fetch` per call, the error body read
4
+ * into a `TamrApiError`, and the chat's server-sent events read into typed
5
+ * events. Shared by the Client API and the Server API.
6
+ */
7
+ /** Tamr refused a call. `code` is the stable lower-case reason (`docs/sdk/api.md`, Errors). */
8
+ export class TamrApiError extends Error {
9
+ status;
10
+ code;
11
+ requestId;
12
+ retryAfter;
13
+ data;
14
+ name = "TamrApiError";
15
+ constructor(status,
16
+ /** The stable reason, such as `rate_limited` or `session_expired`; `network` when Tamr wasn't reached. */
17
+ code, message,
18
+ /** Give it to Tamr's support with the time. */
19
+ requestId,
20
+ /** Seconds to wait before trying again, when Tamr says. */
21
+ retryAfter,
22
+ /** The error's `data`, with any extra fields its code carries. */
23
+ data) {
24
+ super(message);
25
+ this.status = status;
26
+ this.code = code;
27
+ this.requestId = requestId;
28
+ this.retryAfter = retryAfter;
29
+ this.data = data;
30
+ }
31
+ }
32
+ export function createTransport(options) {
33
+ async function send(call, accept) {
34
+ const attempt = async () => {
35
+ const init = {
36
+ method: call.method,
37
+ headers: { accept, ...options.headers() },
38
+ ...(call.signal ? { signal: call.signal } : {}),
39
+ };
40
+ if (call.body instanceof FormData) {
41
+ init.body = call.body;
42
+ }
43
+ else if (call.body !== undefined) {
44
+ init.body = JSON.stringify(call.body);
45
+ init.headers = {
46
+ ...init.headers,
47
+ "content-type": "application/json",
48
+ };
49
+ }
50
+ let response;
51
+ try {
52
+ response = await options.fetch(url(options.baseUrl, call), init);
53
+ }
54
+ catch (cause) {
55
+ // A stopped call is the platform's AbortError, as when it is
56
+ // stopped mid-stream: never "Tamr couldn't be reached".
57
+ if (call.signal?.aborted) {
58
+ throw cause;
59
+ }
60
+ throw new TamrApiError(0, "network", cause instanceof Error
61
+ ? cause.message
62
+ : "Tamr couldn't be reached", null, null, {});
63
+ }
64
+ return response.ok
65
+ ? response
66
+ : Promise.reject(await apiError(response));
67
+ };
68
+ try {
69
+ return await attempt();
70
+ }
71
+ catch (error) {
72
+ if (error instanceof TamrApiError &&
73
+ error.status === 401 &&
74
+ options.renew &&
75
+ (await options.renew(error))) {
76
+ return attempt();
77
+ }
78
+ throw error;
79
+ }
80
+ }
81
+ return {
82
+ async request(call) {
83
+ const response = await send(call, "application/json");
84
+ const text = await response.text();
85
+ return text ? parse(text, call.path) : undefined;
86
+ },
87
+ async *stream(call, decode) {
88
+ const response = await send(call, "text/event-stream");
89
+ if (!response.body) {
90
+ return;
91
+ }
92
+ for await (const { event, data } of serverSentEvents(response.body)) {
93
+ yield decode(event, data === "" ? null : parse(data, `${call.path} ${event}`));
94
+ }
95
+ },
96
+ };
97
+ }
98
+ /** JSON from Tamr; anything else is a `ContractError`, as a body that doesn't match the spec is. */
99
+ function parse(text, where) {
100
+ try {
101
+ return JSON.parse(text);
102
+ }
103
+ catch {
104
+ throw new ContractError(`${where}: expected JSON`);
105
+ }
106
+ }
107
+ function url(base, call) {
108
+ const query = new URLSearchParams();
109
+ for (const [key, value] of Object.entries(call.query ?? {})) {
110
+ if (value !== undefined) {
111
+ query.set(key, String(value));
112
+ }
113
+ }
114
+ const search = query.toString();
115
+ return `${base.replace(/\/$/, "")}${call.path}${search ? `?${search}` : ""}`;
116
+ }
117
+ /** Tamr's error body: oRPC's `{ code, status, message, data: { code, requestId, … } }`. */
118
+ async function apiError(response) {
119
+ const body = (await response.json().catch(() => null));
120
+ const data = typeof body?.data === "object" && body.data !== null
121
+ ? body.data
122
+ : {};
123
+ const header = Number(response.headers.get("retry-after"));
124
+ const retryAfter = typeof data["retryAfter"] === "number"
125
+ ? data["retryAfter"]
126
+ : Number.isFinite(header) && header > 0
127
+ ? header
128
+ : null;
129
+ return new TamrApiError(response.status, typeof data["code"] === "string" ? data["code"] : "other", typeof body?.message === "string" ? body.message : response.statusText, typeof data["requestId"] === "string"
130
+ ? data["requestId"]
131
+ : response.headers.get("x-request-id"), retryAfter, data);
132
+ }
133
+ /** Server-sent events (the WHATWG format): `event:` and `data:` lines, a blank line ends one. */
134
+ export async function* serverSentEvents(body) {
135
+ const reader = body.getReader();
136
+ const decoder = new TextDecoder();
137
+ let buffer = "";
138
+ let event = "";
139
+ let data = [];
140
+ try {
141
+ for (;;) {
142
+ const { done, value } = await reader.read();
143
+ buffer += done
144
+ ? decoder.decode()
145
+ : decoder.decode(value, { stream: true });
146
+ // A `\r` at the end may be the first half of a `\r\n` the next chunk ends: hold it back.
147
+ const held = !done && buffer.endsWith("\r") ? "\r" : "";
148
+ const lines = (held ? buffer.slice(0, -1) : buffer).split(/\r\n|\r|\n/);
149
+ buffer = done ? "" : (lines.pop() ?? "") + held;
150
+ for (const line of lines) {
151
+ if (line === "") {
152
+ if (data.length > 0) {
153
+ yield {
154
+ event: event || "message",
155
+ data: data.join("\n"),
156
+ };
157
+ }
158
+ event = "";
159
+ data = [];
160
+ }
161
+ else if (line.startsWith("event:")) {
162
+ event = line.slice(6).trim();
163
+ }
164
+ else if (line.startsWith("data:")) {
165
+ data.push(line.slice(5).replace(/^ /, ""));
166
+ }
167
+ }
168
+ if (done) {
169
+ if (data.length > 0) {
170
+ yield { event: event || "message", data: data.join("\n") };
171
+ }
172
+ return;
173
+ }
174
+ }
175
+ }
176
+ finally {
177
+ // Stopped early (a `break`, a stop button): stop the download, so Tamr stops the turn too.
178
+ await reader.cancel().catch(() => undefined);
179
+ reader.releaseLock();
180
+ }
181
+ }
@@ -0,0 +1,2 @@
1
+ /** This package's version. */
2
+ export declare const SDK_VERSION = "1.1.0";
package/lib/version.js ADDED
@@ -0,0 +1,2 @@
1
+ /** This package's version. */
2
+ export const SDK_VERSION = "1.1.0";
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
- "name": "@tamr/api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@tamr/api",
3
+ "version": "1.1.0",
4
+ "description": "A typed client for Tamr's API: the Client API for apps that draw their own waiter UI, and the Server API for their backends.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/abiroot/tamr.git",
9
+ "directory": "sdks/api/tamr-api"
10
+ },
11
+ "type": "module",
12
+ "main": "lib/index.js",
13
+ "types": "lib/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./lib/index.d.ts",
17
+ "import": "./lib/index.js"
18
+ },
19
+ "./server": {
20
+ "types": "./lib/server.d.ts",
21
+ "import": "./lib/server.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "files": [
30
+ "lib",
31
+ "README.md",
32
+ "CHANGELOG.md"
33
+ ],
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.build.json",
36
+ "test": "vitest run",
37
+ "type-check": "tsc --noEmit -p tsconfig.json"
38
+ },
39
+ "devDependencies": {
40
+ "typescript": "7.0.2",
41
+ "vitest": "5.0.5"
42
+ }
43
+ }