@trulyfinal/sdk 0.0.0-stage → 1.0.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 +5 -0
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/dist/index.d.ts +596 -0
- package/dist/index.js +196 -0
- package/dist/schema.d.ts +5694 -0
- package/dist/schema.js +1 -0
- package/package.json +57 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/** Every failed call: the HTTP status, the API's error code and its message. */
|
|
2
|
+
export class TrulyFinalError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
constructor(status, code, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "TrulyFinalError";
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
const toBlob = (b, type) => (b instanceof Blob ? b : new Blob([b], type ? { type } : undefined));
|
|
13
|
+
const enc = encodeURIComponent;
|
|
14
|
+
export class TrulyFinal {
|
|
15
|
+
baseUrl;
|
|
16
|
+
#key;
|
|
17
|
+
#fetch;
|
|
18
|
+
#retries;
|
|
19
|
+
constructor(opts) {
|
|
20
|
+
if (!opts?.apiKey)
|
|
21
|
+
throw new Error("Pass your API key: new TrulyFinal({ apiKey: \"tf_…\" })");
|
|
22
|
+
this.#key = opts.apiKey;
|
|
23
|
+
this.baseUrl = (opts.baseUrl ?? "https://app.trulyfinal.com/api").replace(/\/+$/, "");
|
|
24
|
+
this.#fetch = opts.fetch ?? ((...a) => fetch(...a));
|
|
25
|
+
this.#retries = opts.maxRetries ?? 2;
|
|
26
|
+
}
|
|
27
|
+
/** Any endpoint, for what the helpers below don't cover. `path` starts with /v1/. */
|
|
28
|
+
async request(method, path, opts = {}) {
|
|
29
|
+
const url = new URL(this.baseUrl + path);
|
|
30
|
+
for (const [k, v] of Object.entries(opts.query ?? {}))
|
|
31
|
+
if (v !== undefined && v !== null)
|
|
32
|
+
url.searchParams.set(k, String(v));
|
|
33
|
+
const headers = { authorization: `Bearer ${this.#key}`, accept: "application/json" };
|
|
34
|
+
let body;
|
|
35
|
+
if (opts.bytes) {
|
|
36
|
+
headers["content-type"] = opts.bytes.contentType;
|
|
37
|
+
body = opts.bytes.data;
|
|
38
|
+
}
|
|
39
|
+
else if (opts.body !== undefined) {
|
|
40
|
+
headers["content-type"] = "application/json";
|
|
41
|
+
body = JSON.stringify(opts.body);
|
|
42
|
+
}
|
|
43
|
+
for (let attempt = 0;; attempt++) {
|
|
44
|
+
const res = await this.#fetch(url, { method: method.toUpperCase(), headers, body });
|
|
45
|
+
if (res.status === 429 && attempt < this.#retries) {
|
|
46
|
+
const wait = Math.min(Number(res.headers.get("retry-after")) || 1, 60);
|
|
47
|
+
await new Promise((r) => setTimeout(r, wait * 1000));
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (!res.ok) {
|
|
51
|
+
const err = (await res.json().catch(() => null));
|
|
52
|
+
throw new TrulyFinalError(res.status, err?.error?.code ?? "server_error", err?.error?.message ?? `HTTP ${res.status}`);
|
|
53
|
+
}
|
|
54
|
+
if (opts.raw)
|
|
55
|
+
return res;
|
|
56
|
+
return (await res.json());
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Every item of a paged list, fetching pages as you go. */
|
|
60
|
+
async *paginate(path, query = {}) {
|
|
61
|
+
let cursor;
|
|
62
|
+
do {
|
|
63
|
+
const page = await this.request("get", path, { query: { ...query, cursor } });
|
|
64
|
+
yield* page.data;
|
|
65
|
+
cursor = page.nextCursor ?? undefined;
|
|
66
|
+
} while (cursor);
|
|
67
|
+
}
|
|
68
|
+
/** The key and its studio (and, for an app someone connected, the person). */
|
|
69
|
+
me = () => this.request("get", "/v1/me");
|
|
70
|
+
members = {
|
|
71
|
+
list: (q) => this.request("get", "/v1/members", { query: q }),
|
|
72
|
+
all: () => this.paginate("/v1/members"),
|
|
73
|
+
setRole: (userId, role) => this.request("patch", `/v1/members/${enc(userId)}`, { body: { role } }),
|
|
74
|
+
/** Their projects go to `transferTo`, or to the first owner. */
|
|
75
|
+
remove: (userId, opts = {}) => this.request("delete", `/v1/members/${enc(userId)}`, { query: opts }),
|
|
76
|
+
invite: (body) => this.request("post", "/v1/members/invitations", { body }),
|
|
77
|
+
invitations: () => this.request("get", "/v1/members/invitations"),
|
|
78
|
+
cancelInvitation: (id) => this.request("delete", `/v1/members/invitations/${enc(id)}`),
|
|
79
|
+
};
|
|
80
|
+
clients = {
|
|
81
|
+
list: (q) => this.request("get", "/v1/clients", { query: q }),
|
|
82
|
+
all: () => this.paginate("/v1/clients"),
|
|
83
|
+
create: (body) => this.request("post", "/v1/clients", { body }),
|
|
84
|
+
};
|
|
85
|
+
projects = {
|
|
86
|
+
list: (q) => this.request("get", "/v1/projects", { query: q }),
|
|
87
|
+
all: (q) => this.paginate("/v1/projects", q),
|
|
88
|
+
get: (id) => this.request("get", `/v1/projects/${enc(id)}`),
|
|
89
|
+
create: (body) => this.request("post", "/v1/projects", { body }),
|
|
90
|
+
update: (id, body) => this.request("patch", `/v1/projects/${enc(id)}`, { body }),
|
|
91
|
+
/** To Recently deleted, restorable in the app for 30 days. */
|
|
92
|
+
delete: (id) => this.request("delete", `/v1/projects/${enc(id)}`),
|
|
93
|
+
sections: (id) => this.request("get", `/v1/projects/${enc(id)}/sections`),
|
|
94
|
+
setSections: (id, body) => this.request("put", `/v1/projects/${enc(id)}/sections`, { body }),
|
|
95
|
+
steps: (id) => this.request("get", `/v1/projects/${enc(id)}/steps`),
|
|
96
|
+
setSteps: (id, body) => this.request("put", `/v1/projects/${enc(id)}/steps`, { body }),
|
|
97
|
+
/** Adds reviewers to the client stage (emailing each their link) and, with `fileIds`, sends those files. */
|
|
98
|
+
inviteReviewers: (id, body) => this.request("post", `/v1/projects/${enc(id)}/reviewers`, { body }),
|
|
99
|
+
removeReviewer: (id, reviewerId) => this.request("delete", `/v1/projects/${enc(id)}/reviewers/${enc(reviewerId)}`),
|
|
100
|
+
/** Downloads, password, invited-only and expiry of the project's review link. */
|
|
101
|
+
updateLink: (id, body) => this.request("patch", `/v1/projects/${enc(id)}/link`, { body }),
|
|
102
|
+
files: (id, q) => this.request("get", `/v1/projects/${enc(id)}/files`, { query: q }),
|
|
103
|
+
allFiles: (id) => this.paginate(`/v1/projects/${enc(id)}/files`),
|
|
104
|
+
};
|
|
105
|
+
files = {
|
|
106
|
+
get: (id) => this.request("get", `/v1/files/${enc(id)}`),
|
|
107
|
+
/** Files whose `externalId` (your own id) matches, across projects. */
|
|
108
|
+
findByExternalId: (externalId) => this.paginate("/v1/files", { externalId }),
|
|
109
|
+
update: (id, body) => this.request("patch", `/v1/files/${enc(id)}`, { body }),
|
|
110
|
+
delete: (id) => this.request("delete", `/v1/files/${enc(id)}`),
|
|
111
|
+
/**
|
|
112
|
+
* A new file in a project, or with `fileId` a new version of that file. Up to 100 MB in one call;
|
|
113
|
+
* bigger files go up in parts automatically.
|
|
114
|
+
*/
|
|
115
|
+
upload: async (projectId, input) => {
|
|
116
|
+
const blob = toBlob(input.file, input.mime);
|
|
117
|
+
const mime = input.mime || blob.type || "application/octet-stream";
|
|
118
|
+
const meta = { filename: input.filename, fileId: input.fileId, externalId: input.externalId, note: input.note };
|
|
119
|
+
if (blob.size <= 100 * 1024 ** 2)
|
|
120
|
+
return this.request("post", `/v1/projects/${enc(projectId)}/files`, { query: meta, bytes: { data: blob, contentType: mime } });
|
|
121
|
+
const start = await this.request("post", `/v1/projects/${enc(projectId)}/uploads`, { body: { ...meta, size: blob.size, mime } });
|
|
122
|
+
const parts = [];
|
|
123
|
+
for (let n = 1; n <= start.parts; n++) {
|
|
124
|
+
const chunk = blob.slice((n - 1) * start.partSize, n * start.partSize);
|
|
125
|
+
parts.push(await this.request("put", `/v1/uploads/${enc(start.versionId)}/parts/${n}`, { query: { uploadId: start.uploadId }, bytes: { data: chunk, contentType: "application/octet-stream" } }));
|
|
126
|
+
}
|
|
127
|
+
return this.request("post", `/v1/uploads/${enc(start.versionId)}/complete`, { body: { uploadId: start.uploadId, parts } });
|
|
128
|
+
},
|
|
129
|
+
/** TrulyFinal downloads the file from a public URL. */
|
|
130
|
+
uploadFromUrl: (projectId, input) => this.request("post", `/v1/projects/${enc(projectId)}/files`, { body: input }),
|
|
131
|
+
};
|
|
132
|
+
versions = {
|
|
133
|
+
/** The original file, as uploaded. */
|
|
134
|
+
download: (id) => this.request("get", `/v1/versions/${enc(id)}/download`, { raw: true }),
|
|
135
|
+
reviews: (id) => this.request("get", `/v1/versions/${enc(id)}/reviews`),
|
|
136
|
+
/** To the first stage, or with `stepId` straight to that stage. */
|
|
137
|
+
sendForReview: (id, body = {}) => this.request("post", `/v1/versions/${enc(id)}/reviews`, { body }),
|
|
138
|
+
comments: (id, q) => this.request("get", `/v1/versions/${enc(id)}/comments`, { query: q }),
|
|
139
|
+
allComments: (id) => this.paginate(`/v1/versions/${enc(id)}/comments`),
|
|
140
|
+
};
|
|
141
|
+
reviews = {
|
|
142
|
+
setDueDate: (id, dueAt) => this.request("patch", `/v1/reviews/${enc(id)}`, { body: { dueAt } }),
|
|
143
|
+
/** A decision the client made outside TrulyFinal, recorded with how and why. */
|
|
144
|
+
recordDecision: (id, body) => this.request("post", `/v1/reviews/${enc(id)}/decision`, { body }),
|
|
145
|
+
};
|
|
146
|
+
comments = {
|
|
147
|
+
/** Team-only unless `internal: false`. Attach files uploaded with `attach` first. */
|
|
148
|
+
create: (versionId, body) => this.request("post", `/v1/versions/${enc(versionId)}/comments`, { body }),
|
|
149
|
+
update: (id, body) => this.request("patch", `/v1/comments/${enc(id)}`, { body }),
|
|
150
|
+
resolve: (id) => this.request("patch", `/v1/comments/${enc(id)}`, { body: { status: "resolved" } }),
|
|
151
|
+
reopen: (id) => this.request("patch", `/v1/comments/${enc(id)}`, { body: { status: "open" } }),
|
|
152
|
+
delete: (id) => this.request("delete", `/v1/comments/${enc(id)}`),
|
|
153
|
+
/** Upload a file to attach to a comment on this version (up to 25 MB); returns its id. */
|
|
154
|
+
attach: (versionId, input) => {
|
|
155
|
+
const blob = toBlob(input.file, input.mime);
|
|
156
|
+
return this.request("post", `/v1/versions/${enc(versionId)}/attachments`, { query: { filename: input.filename }, bytes: { data: blob, contentType: input.mime || blob.type || "application/octet-stream" } });
|
|
157
|
+
},
|
|
158
|
+
downloadAttachment: (id) => this.request("get", `/v1/attachments/${enc(id)}`, { raw: true }),
|
|
159
|
+
/** Share team comments with the client's review of the same version. */
|
|
160
|
+
copyToClient: (versionId, commentIds) => this.request("post", `/v1/versions/${enc(versionId)}/comments/copy`, { body: { commentIds } }),
|
|
161
|
+
};
|
|
162
|
+
templates = {
|
|
163
|
+
list: () => this.request("get", "/v1/templates"),
|
|
164
|
+
create: (body) => this.request("post", "/v1/templates", { body }),
|
|
165
|
+
delete: (id) => this.request("delete", `/v1/templates/${enc(id)}`),
|
|
166
|
+
};
|
|
167
|
+
webhooks = {
|
|
168
|
+
events: () => this.request("get", "/v1/events"),
|
|
169
|
+
list: () => this.request("get", "/v1/webhooks"),
|
|
170
|
+
/** Keep `secret` to check each delivery with verifyWebhook(). */
|
|
171
|
+
create: (body) => this.request("post", "/v1/webhooks", { body }),
|
|
172
|
+
delete: (id) => this.request("delete", `/v1/webhooks/${enc(id)}`),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
176
|
+
/**
|
|
177
|
+
* Checks a webhook delivery: `TrulyFinal-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "t.body">`.
|
|
178
|
+
* Pass the raw body exactly as received. Deliveries older than `toleranceSec` (5 minutes) are refused,
|
|
179
|
+
* so a captured one can't be replayed later.
|
|
180
|
+
*/
|
|
181
|
+
export async function verifyWebhook(secret, rawBody, signatureHeader, opts = {}) {
|
|
182
|
+
const parts = Object.fromEntries((signatureHeader ?? "").split(",").map((kv) => kv.trim().split("=")));
|
|
183
|
+
const t = Number(parts.t);
|
|
184
|
+
if (!t || !parts.v1)
|
|
185
|
+
return false;
|
|
186
|
+
if (Math.abs((opts.now ?? Date.now()) / 1000 - t) > (opts.toleranceSec ?? 300))
|
|
187
|
+
return false;
|
|
188
|
+
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
189
|
+
const expected = hex(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${t}.${rawBody}`)));
|
|
190
|
+
if (expected.length !== parts.v1.length)
|
|
191
|
+
return false;
|
|
192
|
+
let diff = 0;
|
|
193
|
+
for (let i = 0; i < expected.length; i++)
|
|
194
|
+
diff |= expected.charCodeAt(i) ^ parts.v1.charCodeAt(i);
|
|
195
|
+
return diff === 0;
|
|
196
|
+
}
|