@templr/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +234 -2
- package/dist/client.d.ts +47 -0
- package/dist/client.js +47 -0
- package/dist/errors.d.ts +94 -0
- package/dist/errors.js +107 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +17 -0
- package/dist/resources/assets.d.ts +65 -0
- package/dist/resources/assets.js +68 -0
- package/dist/resources/templates.d.ts +83 -0
- package/dist/resources/templates.js +85 -0
- package/dist/schemas.d.ts +172 -0
- package/dist/schemas.js +68 -0
- package/dist/transport.d.ts +76 -0
- package/dist/transport.js +160 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +49 -4
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP plumbing of the client: builds requests, sends them with `fetch`,
|
|
3
|
+
* validates responses and maps errors. Internal; not exported by the package.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, UnexpectedResponseError, UploadError, } from './errors.js';
|
|
8
|
+
import { errorBodySchema } from './schemas.js';
|
|
9
|
+
import { VERSION } from './version.js';
|
|
10
|
+
/** The header that carries the workspace API key. */
|
|
11
|
+
export const API_KEY_HEADER = 'x-api-key';
|
|
12
|
+
/** Milliseconds to wait for each request by default. */
|
|
13
|
+
export const DEFAULT_TIMEOUT_MS = 30_000;
|
|
14
|
+
/** Formats an id for a URL path, escaping anything that is not a plain path segment. */
|
|
15
|
+
export function pathId(id) {
|
|
16
|
+
return encodeURIComponent(id);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Validates the base URL of a Templr instance and strips its trailing slashes.
|
|
20
|
+
*
|
|
21
|
+
* @throws TypeError when the URL is not an absolute `http` or `https` URL.
|
|
22
|
+
*/
|
|
23
|
+
export function normalizeBaseUrl(baseUrl) {
|
|
24
|
+
const url = URL.canParse(baseUrl) ? new URL(baseUrl) : null;
|
|
25
|
+
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:'))
|
|
26
|
+
throw new TypeError(`baseUrl must be an absolute http(s) URL, got ${JSON.stringify(baseUrl)}`);
|
|
27
|
+
return baseUrl.replace(/\/+$/, '');
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Rejects an empty API key.
|
|
31
|
+
*
|
|
32
|
+
* @throws TypeError when the API key is empty.
|
|
33
|
+
*/
|
|
34
|
+
export function validateApiKey(apiKey) {
|
|
35
|
+
if (apiKey.trim() === '')
|
|
36
|
+
throw new TypeError('apiKey must not be empty');
|
|
37
|
+
return apiKey;
|
|
38
|
+
}
|
|
39
|
+
function retryAfter(response) {
|
|
40
|
+
const value = response.headers.get('retry-after');
|
|
41
|
+
return value !== null && /^\d+$/.test(value) ? Number(value) : null;
|
|
42
|
+
}
|
|
43
|
+
function parseJson(text) {
|
|
44
|
+
try {
|
|
45
|
+
return { ok: true, value: JSON.parse(text) }; // JSON.parse returns untyped data; Zod validates it right after.
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return { ok: false };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Builds the {@link APIError} subclass that matches an error response. */
|
|
52
|
+
export function errorFromResponse(response, text) {
|
|
53
|
+
const json = parseJson(text);
|
|
54
|
+
const parsed = json.ok ? errorBodySchema.safeParse(json.value) : null;
|
|
55
|
+
const details = parsed?.success
|
|
56
|
+
? { code: parsed.data.error.code, issues: parsed.data.error.issues, message: parsed.data.error.message, status: response.status }
|
|
57
|
+
: { code: 'unknown_error', issues: [], message: `HTTP ${response.status} response without a Templr error body.`, status: response.status };
|
|
58
|
+
switch (response.status) {
|
|
59
|
+
case 400:
|
|
60
|
+
return new BadRequestError(details);
|
|
61
|
+
case 401:
|
|
62
|
+
return new AuthenticationError(details);
|
|
63
|
+
case 403:
|
|
64
|
+
return new PermissionDeniedError(details);
|
|
65
|
+
case 404:
|
|
66
|
+
return new NotFoundError(details);
|
|
67
|
+
case 409:
|
|
68
|
+
return new ConflictError(details);
|
|
69
|
+
case 413:
|
|
70
|
+
return new PayloadTooLargeError(details);
|
|
71
|
+
case 429:
|
|
72
|
+
return new RateLimitError(details, retryAfter(response));
|
|
73
|
+
default:
|
|
74
|
+
return response.status >= 500 ? new InternalServerError(details) : new APIError(details);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Sends requests with `fetch` and validates their responses. */
|
|
78
|
+
export class Transport {
|
|
79
|
+
#baseUrl;
|
|
80
|
+
#fetch;
|
|
81
|
+
#headers;
|
|
82
|
+
#timeoutMs;
|
|
83
|
+
#userAgent = `templr-typescript/${VERSION}`;
|
|
84
|
+
constructor(options) {
|
|
85
|
+
this.#baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
86
|
+
this.#fetch = options.fetch;
|
|
87
|
+
this.#headers = { accept: 'application/json', 'user-agent': this.#userAgent, [API_KEY_HEADER]: validateApiKey(options.apiKey) };
|
|
88
|
+
this.#timeoutMs = options.timeoutMs;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Sends a request and returns its body, validated by `schema`.
|
|
92
|
+
*
|
|
93
|
+
* @throws APIError when the API answers with an error status.
|
|
94
|
+
* @throws APIConnectionError when the server cannot be reached, or {@link APITimeoutError} on timeout.
|
|
95
|
+
* @throws UnexpectedResponseError when the body does not match `schema`.
|
|
96
|
+
*/
|
|
97
|
+
async send(request, schema) {
|
|
98
|
+
const url = new URL(`${this.#baseUrl}${request.path}`);
|
|
99
|
+
for (const [name, value] of Object.entries(request.query ?? {}))
|
|
100
|
+
if (value !== undefined)
|
|
101
|
+
url.searchParams.set(name, String(value));
|
|
102
|
+
const hasBody = request.body !== undefined;
|
|
103
|
+
let response;
|
|
104
|
+
let text;
|
|
105
|
+
try {
|
|
106
|
+
response = await this.#fetch(url, {
|
|
107
|
+
headers: hasBody ? { ...this.#headers, 'content-type': 'application/json' } : this.#headers,
|
|
108
|
+
method: request.method,
|
|
109
|
+
signal: AbortSignal.timeout(this.#timeoutMs),
|
|
110
|
+
...(hasBody ? { body: JSON.stringify(request.body) } : {}),
|
|
111
|
+
});
|
|
112
|
+
text = await response.text();
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (error instanceof Error && error.name === 'TimeoutError')
|
|
116
|
+
throw new APITimeoutError({ cause: error });
|
|
117
|
+
throw new APIConnectionError(`Could not connect to the Templr API: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
118
|
+
}
|
|
119
|
+
if (!response.ok)
|
|
120
|
+
throw errorFromResponse(response, text);
|
|
121
|
+
const json = parseJson(text);
|
|
122
|
+
const parsed = json.ok ? schema.safeParse(json.value) : null;
|
|
123
|
+
if (!parsed?.success) {
|
|
124
|
+
const reason = parsed ? parsed.error.message : 'the body is not JSON';
|
|
125
|
+
throw new UnexpectedResponseError(`The API response does not match the expected shape: ${reason}`, response.status, text, parsed ? { cause: parsed.error } : undefined);
|
|
126
|
+
}
|
|
127
|
+
return parsed.data;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Sends a file to a presigned storage form: the fields, then the file as the
|
|
131
|
+
* last field. The form is for the bucket, not the API, so it never carries the API key.
|
|
132
|
+
*
|
|
133
|
+
* @throws UploadError when the bucket rejects the file.
|
|
134
|
+
* @throws APIConnectionError when the bucket cannot be reached, or {@link APITimeoutError} on timeout.
|
|
135
|
+
*/
|
|
136
|
+
async upload(upload) {
|
|
137
|
+
const form = new FormData();
|
|
138
|
+
for (const [name, value] of Object.entries(upload.fields))
|
|
139
|
+
form.append(name, value);
|
|
140
|
+
form.append('file', new Blob([upload.file], { type: upload.contentType }), 'file');
|
|
141
|
+
let response;
|
|
142
|
+
let text;
|
|
143
|
+
try {
|
|
144
|
+
response = await this.#fetch(new URL(upload.url), {
|
|
145
|
+
body: form,
|
|
146
|
+
headers: { 'user-agent': this.#userAgent },
|
|
147
|
+
method: 'POST',
|
|
148
|
+
signal: AbortSignal.timeout(this.#timeoutMs),
|
|
149
|
+
});
|
|
150
|
+
text = await response.text();
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (error instanceof Error && error.name === 'TimeoutError')
|
|
154
|
+
throw new APITimeoutError({ cause: error });
|
|
155
|
+
throw new APIConnectionError(`Could not connect to the storage bucket: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
156
|
+
}
|
|
157
|
+
if (!response.ok)
|
|
158
|
+
throw new UploadError(response.status, text);
|
|
159
|
+
}
|
|
160
|
+
}
|
package/dist/version.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@templr/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Official TypeScript SDK for the Templr REST API.",
|
|
5
|
+
"keywords": ["templr", "email", "email-templates", "react-email", "sdk", "api-client"],
|
|
6
|
+
"homepage": "https://github.com/SebastianUrdaneguiBisalaya/templr/tree/main/sdks/typescript#readme",
|
|
7
|
+
"bugs": "https://github.com/SebastianUrdaneguiBisalaya/templr/issues",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/SebastianUrdaneguiBisalaya/templr.git",
|
|
11
|
+
"directory": "sdks/typescript"
|
|
12
|
+
},
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Sebastian Marat Urdanegui Bisalaya",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"type": "module",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"files": ["dist", "CHANGELOG.md"],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
29
|
+
"check": "biome check . && tsc -p tsconfig.json && bun test",
|
|
30
|
+
"lint": "biome check .",
|
|
31
|
+
"prepack": "bun run build",
|
|
32
|
+
"test": "bun test",
|
|
33
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"zod": "^4.6.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@biomejs/biome": "2.6.9",
|
|
40
|
+
"@types/bun": "1.4.5",
|
|
41
|
+
"ajv": "8.20.0",
|
|
42
|
+
"ajv-formats": "3.0.1",
|
|
43
|
+
"typescript": "7.0.2"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=20.19"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
}
|
|
51
|
+
}
|