@gepetto/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/dist/index.js ADDED
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Official TypeScript / JavaScript SDK of the Gepetto API v2: real estate photo editing.
3
+ * Docs: https://docs.gepettoapp.com
4
+ *
5
+ * Methods and fields have the names of the API: what the docs say of an endpoint is true of the method.
6
+ */
7
+ export const VERSION = '0.1.0';
8
+ const DEFAULT_BASE_URL = 'https://europe-west1-gepettoai.cloudfunctions.net/v2';
9
+ /** A render is stopped by the API after 450 s: 10 minutes covers it, retries included. */
10
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
11
+ const DEFAULT_MAX_RETRIES = 2;
12
+ const POLL_INTERVAL_MS = 2500;
13
+ /**
14
+ * Every failure: an invalid request, a failed render (not charged), a network problem. `message` says what to do
15
+ * next; `code` is stable, for your code.
16
+ */
17
+ export class GepettoError extends Error {
18
+ code;
19
+ /** HTTP status, or null when the API was not reached. */
20
+ status;
21
+ /** The request field at fault, when there is one. */
22
+ param;
23
+ /** The job, when the error concerns a render (it can be followed with `getJob`). */
24
+ jobId;
25
+ job;
26
+ constructor(init) {
27
+ super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
28
+ this.name = 'GepettoError';
29
+ this.code = init.code;
30
+ this.status = init.status ?? null;
31
+ if (init.param)
32
+ this.param = init.param;
33
+ if (init.jobId)
34
+ this.jobId = init.jobId;
35
+ if (init.job)
36
+ this.job = init.job;
37
+ }
38
+ }
39
+ const env = (name) => globalThis.process?.env?.[name] || undefined;
40
+ export class Gepetto {
41
+ baseUrl;
42
+ timeout;
43
+ maxRetries;
44
+ #apiKey;
45
+ #fetch;
46
+ /**
47
+ * ```ts
48
+ * const gepetto = new Gepetto(); // reads GEPETTO_API_KEY
49
+ * const gepetto = new Gepetto('test_...');
50
+ * const gepetto = new Gepetto({ apiKey, timeout: 120_000 });
51
+ * ```
52
+ */
53
+ constructor(apiKeyOrOptions, options = {}) {
54
+ const opts = typeof apiKeyOrOptions === 'string' ? { ...options, apiKey: apiKeyOrOptions } : { ...apiKeyOrOptions };
55
+ const apiKey = (opts.apiKey ?? env('GEPETTO_API_KEY'))?.trim();
56
+ if (!apiKey) {
57
+ throw new GepettoError({
58
+ code: 'missing_api_key',
59
+ message: 'No API key: pass it to new Gepetto(...) or set GEPETTO_API_KEY. Get a free test key with `npx @gepetto/cli login` then `npx @gepetto/cli init`.',
60
+ });
61
+ }
62
+ if (typeof globalThis.window !== 'undefined' && typeof globalThis.document !== 'undefined' && !opts.dangerouslyAllowBrowser) {
63
+ throw new GepettoError({
64
+ code: 'invalid_parameter',
65
+ message: 'The Gepetto SDK runs on a server: in a web page, the API key would be readable by anyone. Call your own backend from the page.',
66
+ });
67
+ }
68
+ const f = opts.fetch ?? globalThis.fetch;
69
+ if (typeof f !== 'function') {
70
+ throw new GepettoError({ code: 'invalid_parameter', message: 'No global fetch: use Node 20 or later, or pass `fetch` in the options.' });
71
+ }
72
+ this.#apiKey = apiKey;
73
+ this.#fetch = f;
74
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
75
+ this.timeout = opts.timeout ?? DEFAULT_TIMEOUT_MS;
76
+ this.maxRetries = Math.max(0, opts.maxRetries ?? DEFAULT_MAX_RETRIES);
77
+ }
78
+ /** True with a test key: renders are free (200 per account) and `priceCents` is 0. */
79
+ get isTest() {
80
+ return this.#apiKey.startsWith('test_');
81
+ }
82
+ declutter(params, options) {
83
+ return this.#render('/declutter', params, options);
84
+ }
85
+ furnish(params, options) {
86
+ return this.#render('/furnish', params, options);
87
+ }
88
+ sunshine(params, options) {
89
+ return this.#render('/sunshine', params, options);
90
+ }
91
+ creativeRedesign(params, options) {
92
+ return this.#render('/creative-redesign', params, options);
93
+ }
94
+ surfaces(params, options) {
95
+ return this.#render('/surfaces', params, options);
96
+ }
97
+ enhance(params, options) {
98
+ return this.#render('/enhance', params, options);
99
+ }
100
+ upscale(params, options) {
101
+ return this.#render('/upscale', params, options);
102
+ }
103
+ // --- Jobs
104
+ /** A job as it is now. */
105
+ async getJob(id, options = {}) {
106
+ return this.#json(await this.#send('GET', `/job/${encodeURIComponent(id)}`, { signal: options.signal }));
107
+ }
108
+ /** Waits until the job is finished. Resolves with it, or throws a GepettoError if the render failed. */
109
+ async waitForJob(id, options = {}) {
110
+ const deadline = Date.now() + (options.timeout ?? this.timeout);
111
+ const job = await this.#poll(id, deadline, options.signal, options.interval ?? POLL_INTERVAL_MS);
112
+ return this.#finished(job);
113
+ }
114
+ /** The latest jobs of the key's type (test or live), newest first. `status: 'error'` for the failures. */
115
+ async listJobs(params = {}) {
116
+ const query = new URLSearchParams();
117
+ if (params.status)
118
+ query.set('status', params.status);
119
+ if (params.limit)
120
+ query.set('limit', String(params.limit));
121
+ const qs = query.toString();
122
+ return this.#json(await this.#send('GET', `/jobs${qs ? `?${qs}` : ''}`, {}));
123
+ }
124
+ // --- Lists: the valid ids of the parameters (the editor suggests the known ones)
125
+ listRooms() {
126
+ return this.#get('/rooms');
127
+ }
128
+ listStyles() {
129
+ return this.#get('/styles');
130
+ }
131
+ listFurnitures() {
132
+ return this.#get('/furnitures');
133
+ }
134
+ listSkies() {
135
+ return this.#get('/skies');
136
+ }
137
+ /** Wall colours, floors and finishes, for `surfaces`. */
138
+ listSurfaces() {
139
+ return this.#get('/surfaces');
140
+ }
141
+ // --- Account
142
+ /** The account of the key, its test renders, the subscription, and the webhook secret of this key type. */
143
+ account() {
144
+ return this.#get('/account');
145
+ }
146
+ /** Renders and consumption of the current period. */
147
+ usage() {
148
+ return this.#get('/usage');
149
+ }
150
+ /** The payment link of the subscription (100 € excl. tax per month including 100 € of renders). A test key is
151
+ * enough; once paid, the live key is on https://app.gepettoapp.com/easy/account/api. */
152
+ async subscribe() {
153
+ return this.#json(await this.#send('POST', '/subscribe', { body: {}, idempotencyKey: uniqueId() }));
154
+ }
155
+ // --- Internals
156
+ async #get(path) {
157
+ return this.#json(await this.#send('GET', path, {}));
158
+ }
159
+ /** Sends a render, then waits for it unless a webhook was given. */
160
+ async #render(path, params, options = {}) {
161
+ const body = {};
162
+ for (const [k, v] of Object.entries(params)) {
163
+ if (v === undefined)
164
+ continue;
165
+ body[k] = v instanceof URL ? v.toString() : v;
166
+ }
167
+ const deadline = Date.now() + (options.timeout ?? this.timeout);
168
+ const idempotencyKey = options.idempotencyKey ?? uniqueId();
169
+ // The same key on every attempt: a retry answers the job already created, never a second render. It also covers
170
+ // a connection dropped while the render runs (Node closes a response that sends no headers for 300 s): the
171
+ // retry gets the running job, which is then followed with GET /job/{id}.
172
+ const sent = await this.#send('POST', path, { body, idempotencyKey, signal: options.signal, deadline, retryConnection: true });
173
+ if (sent.status === 502 && sent.data?.id) {
174
+ throw apiError(sent, { jobId: sent.data.id });
175
+ }
176
+ const job = this.#json(sent);
177
+ if (body.webhook)
178
+ return job;
179
+ const done = job.status === 'pending' || job.status === 'processing'
180
+ ? await this.#poll(job.id, deadline, options.signal, POLL_INTERVAL_MS)
181
+ : job;
182
+ return this.#finished(done);
183
+ }
184
+ #finished(job) {
185
+ if (job.status === 'success' && job.output)
186
+ return job;
187
+ throw new GepettoError({
188
+ code: job.error?.code ?? 'render_failed',
189
+ message: job.error?.message ?? 'The render failed. You were not charged. Try again.',
190
+ jobId: job.id,
191
+ job,
192
+ });
193
+ }
194
+ async #poll(id, deadline, signal, interval) {
195
+ for (;;) {
196
+ const job = this.#json(await this.#send('GET', `/job/${encodeURIComponent(id)}`, { signal, deadline }));
197
+ if (job.status === 'success' || job.status === 'error')
198
+ return job;
199
+ if (Date.now() + interval >= deadline) {
200
+ throw new GepettoError({
201
+ code: 'timeout',
202
+ message: `Job ${id} is still ${job.status}: stopped waiting (timeout). It goes on: follow it with getJob('${id}') or waitForJob('${id}').`,
203
+ jobId: id,
204
+ job,
205
+ });
206
+ }
207
+ await sleep(interval, signal);
208
+ }
209
+ }
210
+ /** The body of a 2xx answer, else a GepettoError. */
211
+ #json(sent) {
212
+ if (sent.status >= 200 && sent.status < 300) {
213
+ if (sent.data === undefined) {
214
+ throw new GepettoError({ code: 'invalid_response', status: sent.status, message: 'The API answered something that is not JSON.' });
215
+ }
216
+ return sent.data;
217
+ }
218
+ throw apiError(sent);
219
+ }
220
+ /** One request, retried on a network error, a 429 or a 5xx other than a failed render (502). */
221
+ async #send(method, path, init) {
222
+ const deadline = init.deadline ?? Date.now() + this.timeout;
223
+ // GET is safe to repeat; a POST only with an idempotency key
224
+ const retryable = method === 'GET' || !!init.idempotencyKey;
225
+ const headers = {
226
+ Authorization: `Bearer ${this.#apiKey}`,
227
+ Accept: 'application/json',
228
+ 'User-Agent': `gepetto-sdk/${VERSION}`,
229
+ };
230
+ if (init.body !== undefined)
231
+ headers['Content-Type'] = 'application/json';
232
+ if (init.idempotencyKey)
233
+ headers['Idempotency-Key'] = init.idempotencyKey;
234
+ for (let attempt = 0;; attempt++) {
235
+ throwIfAborted(init.signal);
236
+ const remaining = deadline - Date.now();
237
+ if (remaining <= 0)
238
+ throw timeoutError();
239
+ const controller = new AbortController();
240
+ let timedOut = false;
241
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, remaining);
242
+ const onAbort = () => controller.abort();
243
+ init.signal?.addEventListener('abort', onAbort, { once: true });
244
+ try {
245
+ const res = await this.#fetch(`${this.baseUrl}${path}`, {
246
+ method,
247
+ headers,
248
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
249
+ signal: controller.signal,
250
+ });
251
+ const text = await res.text();
252
+ let data;
253
+ try {
254
+ data = text ? JSON.parse(text) : null;
255
+ }
256
+ catch {
257
+ data = undefined;
258
+ }
259
+ const transient = res.status === 429 || (res.status >= 500 && res.status !== 502);
260
+ if (transient && retryable && attempt < this.maxRetries && Date.now() < deadline) {
261
+ await sleep(backoff(attempt), init.signal);
262
+ continue;
263
+ }
264
+ return { status: res.status, data };
265
+ }
266
+ catch (e) {
267
+ if (e instanceof GepettoError)
268
+ throw e;
269
+ throwIfAborted(init.signal);
270
+ if (timedOut)
271
+ throw timeoutError();
272
+ const maxAttempts = init.retryConnection ? Math.max(this.maxRetries, 2) : this.maxRetries;
273
+ if (retryable && attempt < maxAttempts && Date.now() < deadline) {
274
+ await sleep(backoff(attempt), init.signal);
275
+ continue;
276
+ }
277
+ throw new GepettoError({
278
+ code: 'connection_error',
279
+ message: `Could not reach the Gepetto API (${String(e?.cause?.code ?? e?.message ?? e)}).${init.idempotencyKey ? ` Retry with the same idempotencyKey (${init.idempotencyKey}): a render already started is not run twice.` : ''}`,
280
+ cause: e,
281
+ });
282
+ }
283
+ finally {
284
+ clearTimeout(timer);
285
+ init.signal?.removeEventListener('abort', onAbort);
286
+ }
287
+ }
288
+ }
289
+ }
290
+ export default Gepetto;
291
+ /**
292
+ * Checks that a webhook comes from Gepetto, and returns its job. Throws a GepettoError `invalid_signature` otherwise.
293
+ *
294
+ * ```ts
295
+ * app.post('/gepetto-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
296
+ * const job = await verifyWebhook({ body: req.body, signature: req.get('Gepetto-Signature') });
297
+ * res.sendStatus(200);
298
+ * });
299
+ * ```
300
+ */
301
+ export async function verifyWebhook(params) {
302
+ const secret = params.secret ?? env('GEPETTO_WEBHOOK_SECRET');
303
+ if (!secret) {
304
+ throw new GepettoError({ code: 'invalid_parameter', message: 'No webhook secret: pass `secret` (webhook_secret of account()) or set GEPETTO_WEBHOOK_SECRET.' });
305
+ }
306
+ const invalid = (why) => new GepettoError({ code: 'invalid_signature', status: null, message: `Invalid webhook signature: ${why}.` });
307
+ if (!params.signature)
308
+ throw invalid('no Gepetto-Signature header');
309
+ const parts = Object.fromEntries(params.signature.split(',').map((p) => {
310
+ const i = p.indexOf('=');
311
+ return [p.slice(0, i).trim(), p.slice(i + 1).trim()];
312
+ }));
313
+ const t = Number(parts.t);
314
+ if (!parts.t || !Number.isFinite(t) || !parts.v1)
315
+ throw invalid('malformed header');
316
+ if (Math.abs(Date.now() / 1000 - t) > (params.tolerance ?? 300))
317
+ throw invalid('timestamp too old');
318
+ const raw = typeof params.body === 'string' ? params.body : new TextDecoder().decode(params.body);
319
+ const subtle = globalThis.crypto?.subtle;
320
+ if (!subtle)
321
+ throw new GepettoError({ code: 'invalid_parameter', message: 'Web Crypto is missing: use Node 20 or later.' });
322
+ const enc = new TextEncoder();
323
+ const key = await subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
324
+ const mac = new Uint8Array(await subtle.sign('HMAC', key, enc.encode(`${parts.t}.${raw}`)));
325
+ const expected = Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
326
+ if (!timingSafeEqual(expected, parts.v1))
327
+ throw invalid('signature mismatch (wrong secret, or the body was modified)');
328
+ try {
329
+ return JSON.parse(raw);
330
+ }
331
+ catch {
332
+ throw invalid('the body is not JSON');
333
+ }
334
+ }
335
+ // --- Helpers -------------------------------------------------------------------------------------------------------
336
+ function apiError(sent, extra = {}) {
337
+ const d = sent.data && typeof sent.data === 'object' ? sent.data : {};
338
+ return new GepettoError({
339
+ code: d.code ?? (sent.status === 429 ? 'rate_limited' : 'invalid_response'),
340
+ message: d.message ?? `The API answered HTTP ${sent.status}.`,
341
+ status: sent.status,
342
+ param: d.param,
343
+ jobId: extra.jobId ?? d.id,
344
+ });
345
+ }
346
+ function timeoutError() {
347
+ return new GepettoError({ code: 'timeout', message: 'The call took longer than its timeout. A render already started goes on: find it with listJobs().' });
348
+ }
349
+ function throwIfAborted(signal) {
350
+ if (signal?.aborted)
351
+ throw new GepettoError({ code: 'aborted', message: 'Aborted by the signal.', cause: signal.reason });
352
+ }
353
+ function sleep(ms, signal) {
354
+ return new Promise((resolve, reject) => {
355
+ if (signal?.aborted)
356
+ return reject(new GepettoError({ code: 'aborted', message: 'Aborted by the signal.', cause: signal.reason }));
357
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
358
+ const onAbort = () => { clearTimeout(timer); reject(new GepettoError({ code: 'aborted', message: 'Aborted by the signal.', cause: signal?.reason })); };
359
+ signal?.addEventListener('abort', onAbort, { once: true });
360
+ });
361
+ }
362
+ /** 1 s, 2 s, 4 s... with a little jitter. */
363
+ function backoff(attempt) {
364
+ return Math.min(8000, 1000 * 2 ** attempt) * (0.8 + Math.random() * 0.4);
365
+ }
366
+ function uniqueId() {
367
+ const c = globalThis.crypto;
368
+ if (c?.randomUUID)
369
+ return c.randomUUID();
370
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
371
+ }
372
+ function timingSafeEqual(a, b) {
373
+ if (a.length !== b.length)
374
+ return false;
375
+ let diff = 0;
376
+ for (let i = 0; i < a.length; i++)
377
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
378
+ return diff === 0;
379
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@gepetto/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Official TypeScript / JavaScript SDK of the Gepetto API v2: real estate photo editing (enhance, declutter, furnish, sky, restyle, walls and floors, upscale).",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "./package.json": "./package.json"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md"
25
+ ],
26
+ "sideEffects": false,
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "scripts": {
31
+ "build": "node scripts/build.mjs",
32
+ "ids": "node scripts/generate-ids.mjs",
33
+ "prepublishOnly": "npm run build"
34
+ },
35
+ "devDependencies": {
36
+ "typescript": "5.6.3"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "keywords": [
42
+ "gepetto",
43
+ "real-estate",
44
+ "virtual-staging",
45
+ "photo-editing",
46
+ "image-enhancement",
47
+ "api",
48
+ "sdk"
49
+ ],
50
+ "homepage": "https://docs.gepettoapp.com",
51
+ "license": "UNLICENSED"
52
+ }