@gemmein/sdk 0.0.1 → 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/LICENSE +21 -0
- package/README.md +272 -4
- package/REFERENCE.md +235 -0
- package/dist/index.cjs +566 -0
- package/dist/index.d.cts +337 -0
- package/dist/index.d.ts +337 -0
- package/dist/index.js +553 -0
- package/llms.txt +290 -0
- package/package.json +48 -6
- package/reaffirm.mjs +76 -0
- package/index.js +0 -6
package/dist/index.js
ADDED
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
export class GemmeinError extends Error {
|
|
2
|
+
constructor(input) {
|
|
3
|
+
super(input.message);
|
|
4
|
+
this.name = "GemmeinError";
|
|
5
|
+
this.status = input.status;
|
|
6
|
+
this.code = input.code;
|
|
7
|
+
this.resetAt = input.resetAt;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export class MemoryTokenStore {
|
|
11
|
+
get() {
|
|
12
|
+
return this.token;
|
|
13
|
+
}
|
|
14
|
+
set(token) {
|
|
15
|
+
this.token = token;
|
|
16
|
+
}
|
|
17
|
+
clear() {
|
|
18
|
+
this.token = undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
// Persists the session across page reloads — the default in browsers.
|
|
22
|
+
// Sessions are long-lived server-side; a memory-only default would log
|
|
23
|
+
// users out on every refresh. Keyed per app key so two Gemmein apps on
|
|
24
|
+
// one origin never share a token. All storage access is guarded: private
|
|
25
|
+
// modes and blocked storage degrade to "signed out", never to a crash.
|
|
26
|
+
export class BrowserTokenStore {
|
|
27
|
+
constructor(appKey) {
|
|
28
|
+
this.key = `gemmein_session_${appKey.slice(0, 20)}`;
|
|
29
|
+
}
|
|
30
|
+
get() {
|
|
31
|
+
try {
|
|
32
|
+
return window.localStorage.getItem(this.key) ?? undefined;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
set(token) {
|
|
39
|
+
try {
|
|
40
|
+
window.localStorage.setItem(this.key, token);
|
|
41
|
+
}
|
|
42
|
+
catch { /* storage blocked — session lives for this page only */ }
|
|
43
|
+
}
|
|
44
|
+
clear() {
|
|
45
|
+
try {
|
|
46
|
+
window.localStorage.removeItem(this.key);
|
|
47
|
+
}
|
|
48
|
+
catch { /* nothing to clear */ }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function defaultTokenStore(appKey) {
|
|
52
|
+
try {
|
|
53
|
+
if (typeof window !== "undefined" && window.localStorage)
|
|
54
|
+
return new BrowserTokenStore(appKey);
|
|
55
|
+
}
|
|
56
|
+
catch { /* SSR / Node / storage blocked */ }
|
|
57
|
+
return new MemoryTokenStore();
|
|
58
|
+
}
|
|
59
|
+
export class Gemmein {
|
|
60
|
+
constructor(options) {
|
|
61
|
+
if (options.appKey?.startsWith("sk_")) {
|
|
62
|
+
throw new GemmeinError({
|
|
63
|
+
status: 0,
|
|
64
|
+
code: "invalid_app_key",
|
|
65
|
+
message: "Secret keys (sk_) must not be used in the client SDK — use gemmeinServer() instead"
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
// The signpost: an AI building without a key gets routed, not stuck.
|
|
69
|
+
if (!options.appKey || !options.appKey.startsWith("pk_")) {
|
|
70
|
+
throw new GemmeinError({
|
|
71
|
+
status: 0,
|
|
72
|
+
code: "missing_app_key",
|
|
73
|
+
message: 'Gemmein needs your app key (it starts with "pk_"). Get one in 30 seconds: ' +
|
|
74
|
+
"sign in at https://app.gemmein.com with an email code (free, no card) and " +
|
|
75
|
+
'copy the key from the Setup page. Then: gemmein("pk_...")'
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const config = {
|
|
79
|
+
apiUrl: options.apiUrl ?? "https://api.gemmein.com",
|
|
80
|
+
appKey: options.appKey,
|
|
81
|
+
tokenStore: options.tokenStore ?? defaultTokenStore(options.appKey)
|
|
82
|
+
};
|
|
83
|
+
this.auth = new AuthClient(config);
|
|
84
|
+
this.storage = new StorageClient(config);
|
|
85
|
+
}
|
|
86
|
+
/** The signed-in user's subscription — `(await g.subscription())?.plan === "pro"`. */
|
|
87
|
+
subscription() {
|
|
88
|
+
return this.auth.subscription();
|
|
89
|
+
}
|
|
90
|
+
/** Send the signed-in user to Stripe checkout for a plan — `g.checkout("pro")`. Redirects in browsers. */
|
|
91
|
+
checkout(plan) {
|
|
92
|
+
return this.auth.checkout(plan);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Buy a one-off product — `g.pay("poster")`. Redirects in browsers. NOT
|
|
96
|
+
* for plans/subscriptions (that's `g.checkout`). The optional `item` note
|
|
97
|
+
* names WHAT is being bought when one product covers many things (e.g. a
|
|
98
|
+
* license tier across a catalog): `g.pay("premium license", { item: "beat_37" })`
|
|
99
|
+
* — it lands on the buyer's receipt record for the owner to fulfil.
|
|
100
|
+
*/
|
|
101
|
+
pay(product, options) {
|
|
102
|
+
return this.auth.pay(product, options);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// Factory forms — what the copied prompts teach. `gemmein("pk_...")` reads
|
|
106
|
+
// better in an AI prompt than a class instantiation, and both accept an
|
|
107
|
+
// options object when more than a key is needed.
|
|
108
|
+
// ROUND-8 FIND: `gemmein(key, { apiUrl })` is the call shape people (and
|
|
109
|
+
// AIs) write naturally — silently dropping the second argument misrouted a
|
|
110
|
+
// local app to production. Both forms are now first-class.
|
|
111
|
+
export function gemmein(appKeyOrOptions, options) {
|
|
112
|
+
return new Gemmein(typeof appKeyOrOptions === "string"
|
|
113
|
+
? { appKey: appKeyOrOptions, ...(options ?? {}) }
|
|
114
|
+
: appKeyOrOptions);
|
|
115
|
+
}
|
|
116
|
+
export function gemmeinServer(secretKeyOrOptions, options) {
|
|
117
|
+
return new GemmeinServer(typeof secretKeyOrOptions === "string"
|
|
118
|
+
? { secretKey: secretKeyOrOptions, ...(options ?? {}) }
|
|
119
|
+
: secretKeyOrOptions);
|
|
120
|
+
}
|
|
121
|
+
export class AuthClient {
|
|
122
|
+
constructor(config) {
|
|
123
|
+
this.config = config;
|
|
124
|
+
}
|
|
125
|
+
async sendEmailCode(email) {
|
|
126
|
+
await this.request("/auth/email/start", {
|
|
127
|
+
method: "POST",
|
|
128
|
+
body: JSON.stringify({ email }),
|
|
129
|
+
headers: { "content-type": "application/json" }
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async verifyEmailCode(input) {
|
|
133
|
+
const result = await this.request("/auth/email/verify", {
|
|
134
|
+
method: "POST",
|
|
135
|
+
body: JSON.stringify(input),
|
|
136
|
+
headers: { "content-type": "application/json" }
|
|
137
|
+
});
|
|
138
|
+
if (isSessionResponse(result)) {
|
|
139
|
+
await this.config.tokenStore.set(result.token);
|
|
140
|
+
return result;
|
|
141
|
+
}
|
|
142
|
+
throw new Error("Gemmein auth response did not include a session token");
|
|
143
|
+
}
|
|
144
|
+
async logout() {
|
|
145
|
+
try {
|
|
146
|
+
await this.request("/auth/logout", { method: "POST" });
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
// Even if the network call fails, the user asked to be signed out.
|
|
150
|
+
await this.config.tokenStore.clear();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async deleteAccount() {
|
|
154
|
+
const result = await this.request("/auth/delete-account", { method: "POST" });
|
|
155
|
+
await this.config.tokenStore.clear();
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
async subscription() {
|
|
159
|
+
// SUBS-1: Gemmein manages the subscription record — one per customer,
|
|
160
|
+
// created by the payment itself. Read-only: gate features with
|
|
161
|
+
// `sub?.plan === "pro"`. Null when payments are off or this user has
|
|
162
|
+
// never paid; throws GemmeinError (401) when nobody is signed in — a
|
|
163
|
+
// data route, not the never-throw current-user contract. There is no
|
|
164
|
+
// client write path, by design.
|
|
165
|
+
const result = (await this.request("/auth/subscription"));
|
|
166
|
+
return result.subscription;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* SUBS-2: start a Stripe checkout for a plan — Gemmein mints the URL with
|
|
170
|
+
* the signed-in buyer and the plan already wired in (never build checkout
|
|
171
|
+
* URLs yourself; raw emails get silently dropped by Stripe's URL rules).
|
|
172
|
+
* In a browser this redirects immediately; it also resolves with the URL
|
|
173
|
+
* (for non-browser callers or custom handling). Requires a signed-in user
|
|
174
|
+
* and a plan whose Payment Link the app owner has pasted in their
|
|
175
|
+
* dashboard; omit `plan` to buy the app's paid plan.
|
|
176
|
+
*/
|
|
177
|
+
async checkout(plan) {
|
|
178
|
+
const query = plan ? `?plan=${encodeURIComponent(plan)}` : "";
|
|
179
|
+
const result = (await this.request(`/auth/checkout${query}`));
|
|
180
|
+
if (typeof window !== "undefined" && window.location) {
|
|
181
|
+
window.location.assign(result.url);
|
|
182
|
+
}
|
|
183
|
+
return result;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* PAY-1: buy a one-off product — same contract as checkout() but for
|
|
187
|
+
* things, not plans. A completed payment writes a receipt record addressed
|
|
188
|
+
* to the buyer in the owner's receipts collection; gate downloads/fulfilment
|
|
189
|
+
* on that receipt, never on the redirect coming back.
|
|
190
|
+
*/
|
|
191
|
+
async pay(product, options) {
|
|
192
|
+
const params = new URLSearchParams({ product });
|
|
193
|
+
if (options?.item)
|
|
194
|
+
params.set("item", options.item);
|
|
195
|
+
const result = (await this.request(`/auth/pay?${params.toString()}`));
|
|
196
|
+
if (typeof window !== "undefined" && window.location) {
|
|
197
|
+
window.location.assign(result.url);
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
async currentUser() {
|
|
202
|
+
// Contract: "who am I?" never throws for session state — the server
|
|
203
|
+
// answers 200 {authenticated:false} for a token it won't honour right
|
|
204
|
+
// now, same as no token. We deliberately do NOT clear the stored token
|
|
205
|
+
// here: authenticated:false also covers a SUSPENDED user, whose session
|
|
206
|
+
// is intact and restored on unsuspend — clearing it would make a
|
|
207
|
+
// reversible suspension permanently sign them out. A genuinely expired
|
|
208
|
+
// token is harmless to keep (the next data-plane call 401s and the app
|
|
209
|
+
// re-auths); logout() and deleteAccount() are the deliberate clears.
|
|
210
|
+
return this.request("/auth/current-user");
|
|
211
|
+
}
|
|
212
|
+
async request(path, init = {}) {
|
|
213
|
+
const response = await fetch(new URL(path, this.config.apiUrl), {
|
|
214
|
+
...init,
|
|
215
|
+
headers: await runtimeHeaders(this.config, init.headers)
|
|
216
|
+
});
|
|
217
|
+
return handleResponse(response, this.config);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function isSessionResponse(value) {
|
|
221
|
+
return (typeof value === "object" &&
|
|
222
|
+
value !== null &&
|
|
223
|
+
"token" in value &&
|
|
224
|
+
typeof value.token === "string");
|
|
225
|
+
}
|
|
226
|
+
export class StorageClient {
|
|
227
|
+
constructor(config) {
|
|
228
|
+
this.config = config;
|
|
229
|
+
}
|
|
230
|
+
/** Optionally type your fields: `g.storage.collection<{ title: string }>("notes")`. */
|
|
231
|
+
collection(name) {
|
|
232
|
+
assertCollectionName(name);
|
|
233
|
+
return new CollectionClient(this.config, name);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Talks to one collection. Collections themselves are created by the app
|
|
238
|
+
* owner in their dashboard (app.gemmein.com → data) — a 404
|
|
239
|
+
* `unknown_collection` means it doesn't exist yet: ask the owner to create
|
|
240
|
+
* it there, don't retry.
|
|
241
|
+
*/
|
|
242
|
+
export class CollectionClient {
|
|
243
|
+
constructor(config, name) {
|
|
244
|
+
this.config = config;
|
|
245
|
+
this.name = name;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Create a record from your fields. The signed-in user becomes its owner.
|
|
249
|
+
*
|
|
250
|
+
* For anything two users can race for (a booking slot, a unique slug, a
|
|
251
|
+
* limited drop), pass a deterministic `key` derived from the thing that
|
|
252
|
+
* must be unique: `create(data, { key: "slot:2026-07-15T15:00" })`.
|
|
253
|
+
* The second writer gets a 409 GemmeinError `conflict` — that error IS
|
|
254
|
+
* the booking system working: catch it and tell the user it's taken.
|
|
255
|
+
* Your own retry with the same key returns the record you already made
|
|
256
|
+
* (`existing: true`) instead of a duplicate. Deleting a keyed record
|
|
257
|
+
* frees its key.
|
|
258
|
+
*
|
|
259
|
+
* On `addressed` and `direct` collections every create names its
|
|
260
|
+
* recipient: `create(data, { for: userId })` — the server stamps it,
|
|
261
|
+
* and only that user (plus the sender/owner) will ever read the record.
|
|
262
|
+
* Sending to a non-user is a 400 `invalid_audience`; a 403 `reply_only`
|
|
263
|
+
* means this collection only allows replies to people who wrote to you
|
|
264
|
+
* first — tell the user, don't retry.
|
|
265
|
+
*
|
|
266
|
+
* On the PUBLIC rules (public_read, community) pass `{ published: false }`
|
|
267
|
+
* to save a DRAFT the public can't see (the author still sees their own;
|
|
268
|
+
* the owner sees all). Publish later with
|
|
269
|
+
* `update(id, {}, { published: true })`. This is server-enforced — never
|
|
270
|
+
* fake drafts with a data field + client-side filtering: on a public
|
|
271
|
+
* collection the data still reaches everyone.
|
|
272
|
+
*/
|
|
273
|
+
async create(data, options = {}) {
|
|
274
|
+
const query = new URLSearchParams();
|
|
275
|
+
if (options.key !== undefined)
|
|
276
|
+
query.set("key", options.key);
|
|
277
|
+
if (options.for !== undefined)
|
|
278
|
+
query.set("for", options.for);
|
|
279
|
+
if (options.published !== undefined)
|
|
280
|
+
query.set("published", String(options.published));
|
|
281
|
+
const qs = query.toString();
|
|
282
|
+
return this.request(qs ? `?${qs}` : "", {
|
|
283
|
+
method: "POST",
|
|
284
|
+
body: JSON.stringify(data)
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* List records this user is allowed to see under the collection's safety
|
|
289
|
+
* rule (the app owner sees everyone's). Returns `{ records, hasMore }` —
|
|
290
|
+
* an object, not a bare array.
|
|
291
|
+
*/
|
|
292
|
+
async list(options = {}) {
|
|
293
|
+
const query = new URLSearchParams();
|
|
294
|
+
if (options.limit !== undefined)
|
|
295
|
+
query.set("limit", String(options.limit));
|
|
296
|
+
if (options.sort)
|
|
297
|
+
query.set("sort", options.sort);
|
|
298
|
+
if (options.where)
|
|
299
|
+
query.set("where", JSON.stringify(options.where));
|
|
300
|
+
if (options.cursor)
|
|
301
|
+
query.set("cursor", options.cursor);
|
|
302
|
+
if (options.search)
|
|
303
|
+
query.set("search", options.search);
|
|
304
|
+
if (options.expand && options.expand.length > 0)
|
|
305
|
+
query.set("expand", options.expand.join(","));
|
|
306
|
+
// NOT query.size — absent on Node <19.8 / older browsers, where
|
|
307
|
+
// `undefined > 0` would silently drop every filter.
|
|
308
|
+
const qs = query.toString();
|
|
309
|
+
return this.request(qs ? `?${qs}` : "");
|
|
310
|
+
}
|
|
311
|
+
async get(id, options = {}) {
|
|
312
|
+
const qs = options.expand && options.expand.length > 0 ? `?expand=${encodeURIComponent(options.expand.join(","))}` : "";
|
|
313
|
+
return this.request(`/${encodeURIComponent(id)}${qs}`);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Merge-updates `data` fields; returns the full updated record.
|
|
317
|
+
*
|
|
318
|
+
* Counters that users race for (stock, seats) must never be computed
|
|
319
|
+
* client-side — put an atomic op in value position and the server does
|
|
320
|
+
* the math on current state: `update(id, { stock: { decrement: 1,
|
|
321
|
+
* floor: 0 } })`. Breaching the floor/ceiling → 409 `conflict` ("out of
|
|
322
|
+
* stock" — the limit working, not a bug). An object is treated as an op
|
|
323
|
+
* ONLY when its keys are exactly increment|decrement (+ optional
|
|
324
|
+
* floor|ceiling), all numbers.
|
|
325
|
+
*
|
|
326
|
+
* When different people can edit the same record (CMS pages, shared
|
|
327
|
+
* docs), pass `{ ifVersion: record.version }` — a stale save gets a 409
|
|
328
|
+
* `conflict` instead of clobbering; re-read, reapply, retry.
|
|
329
|
+
*/
|
|
330
|
+
async update(id, data, options = {}) {
|
|
331
|
+
const query = new URLSearchParams();
|
|
332
|
+
if (options.ifVersion !== undefined)
|
|
333
|
+
query.set("ifVersion", String(options.ifVersion));
|
|
334
|
+
if (options.published !== undefined)
|
|
335
|
+
query.set("published", String(options.published));
|
|
336
|
+
const qs = query.toString();
|
|
337
|
+
return this.request(`/${encodeURIComponent(id)}${qs ? `?${qs}` : ""}`, {
|
|
338
|
+
method: "PATCH",
|
|
339
|
+
body: JSON.stringify(data)
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
async delete(id) {
|
|
343
|
+
await this.request(`/${encodeURIComponent(id)}`, { method: "DELETE" });
|
|
344
|
+
}
|
|
345
|
+
async upload(file, options) {
|
|
346
|
+
const name = options?.name ?? (file instanceof File ? file.name : "upload");
|
|
347
|
+
// Step 1: Get presigned upload URL
|
|
348
|
+
const presign = await this.request("/upload", {
|
|
349
|
+
method: "POST",
|
|
350
|
+
body: JSON.stringify({ name, size: file.size, contentType: file.type }),
|
|
351
|
+
});
|
|
352
|
+
// Step 2: Upload directly to S3 via presigned POST
|
|
353
|
+
const form = new FormData();
|
|
354
|
+
for (const [key, value] of Object.entries(presign.fields)) {
|
|
355
|
+
form.append(key, value);
|
|
356
|
+
}
|
|
357
|
+
form.append("file", file); // Must be last — S3 presigned POST requirement
|
|
358
|
+
const s3Response = await fetch(presign.uploadUrl, { method: "POST", body: form });
|
|
359
|
+
if (!s3Response.ok) {
|
|
360
|
+
throw new GemmeinError({
|
|
361
|
+
status: s3Response.status,
|
|
362
|
+
code: "upload_failed",
|
|
363
|
+
message: `Upload failed: ${s3Response.status}`,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
// Step 3: Confirm upload
|
|
367
|
+
const confirmed = await this.request(`/upload/${encodeURIComponent(presign.fileId)}/confirm`, {
|
|
368
|
+
method: "POST",
|
|
369
|
+
});
|
|
370
|
+
return confirmed;
|
|
371
|
+
}
|
|
372
|
+
async request(suffix, init = {}) {
|
|
373
|
+
const response = await fetch(new URL(`/storage/${encodeURIComponent(this.name)}${suffix}`, this.config.apiUrl), {
|
|
374
|
+
...init,
|
|
375
|
+
headers: await runtimeHeaders(this.config, {
|
|
376
|
+
"content-type": "application/json",
|
|
377
|
+
...init.headers
|
|
378
|
+
})
|
|
379
|
+
});
|
|
380
|
+
return handleResponse(response, this.config);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
export class GemmeinServer {
|
|
384
|
+
constructor(options) {
|
|
385
|
+
if (options.secretKey.startsWith("pk_")) {
|
|
386
|
+
throw new GemmeinError({
|
|
387
|
+
status: 0,
|
|
388
|
+
code: "invalid_secret_key",
|
|
389
|
+
message: "Public keys (pk_) must not be used with GemmeinServer — use the Gemmein client SDK instead"
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
this.apiUrl = options.apiUrl ?? "https://api.gemmein.com";
|
|
393
|
+
this.secretKey = options.secretKey;
|
|
394
|
+
}
|
|
395
|
+
collection(name) {
|
|
396
|
+
assertCollectionName(name);
|
|
397
|
+
return new ServerCollectionClient(this.apiUrl, this.secretKey, name);
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Mint a member session for a test email WITHOUT an OTP round-trip — so a CI
|
|
401
|
+
* self-test ("reaffirm") can sign in as N test users and prove your app's
|
|
402
|
+
* isolation boundaries hold (user B genuinely can't read user A's private
|
|
403
|
+
* records). DEV ENVIRONMENTS ONLY: throws `test_session_forbidden_live` on an
|
|
404
|
+
* `sk_live` key, and the server refuses it too. Never ship this in app code.
|
|
405
|
+
* Pass the returned `token` to `gemmein(pk, { tokenStore })` to act as that user.
|
|
406
|
+
*/
|
|
407
|
+
async testSession(email) {
|
|
408
|
+
if (this.secretKey.startsWith("sk_live")) {
|
|
409
|
+
throw new GemmeinError({
|
|
410
|
+
status: 0,
|
|
411
|
+
code: "test_session_forbidden_live",
|
|
412
|
+
message: "test sessions are only available in a development environment — never with a live (sk_live) key",
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
const response = await fetch(new URL("/server/test-session", this.apiUrl), {
|
|
416
|
+
method: "POST",
|
|
417
|
+
headers: { "x-app-key": this.secretKey, "content-type": "application/json" },
|
|
418
|
+
body: JSON.stringify({ email }),
|
|
419
|
+
});
|
|
420
|
+
if (!response.ok) {
|
|
421
|
+
const body = await response.json().catch(() => ({ code: "request_failed", message: `Request failed: ${response.status}` }));
|
|
422
|
+
throw new GemmeinError({
|
|
423
|
+
status: response.status,
|
|
424
|
+
code: body.code ?? "request_failed",
|
|
425
|
+
message: body.message ?? `Request failed: ${response.status}`,
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
return response.json();
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
class ServerCollectionClient {
|
|
432
|
+
constructor(apiUrl, secretKey, name) {
|
|
433
|
+
this.apiUrl = apiUrl;
|
|
434
|
+
this.secretKey = secretKey;
|
|
435
|
+
this.name = name;
|
|
436
|
+
}
|
|
437
|
+
async get(id) {
|
|
438
|
+
return this.request(`/${encodeURIComponent(id)}`);
|
|
439
|
+
}
|
|
440
|
+
async list(options = {}) {
|
|
441
|
+
const query = new URLSearchParams();
|
|
442
|
+
if (options.limit !== undefined)
|
|
443
|
+
query.set("limit", String(options.limit));
|
|
444
|
+
if (options.sort)
|
|
445
|
+
query.set("sort", options.sort);
|
|
446
|
+
if (options.where)
|
|
447
|
+
query.set("where", JSON.stringify(options.where));
|
|
448
|
+
if (options.cursor)
|
|
449
|
+
query.set("cursor", options.cursor);
|
|
450
|
+
if (options.search)
|
|
451
|
+
query.set("search", options.search);
|
|
452
|
+
if (options.expand && options.expand.length > 0)
|
|
453
|
+
query.set("expand", options.expand.join(","));
|
|
454
|
+
// NOT query.size — absent on Node <19.8 / older browsers, where
|
|
455
|
+
// `undefined > 0` would silently drop every filter.
|
|
456
|
+
const qs = query.toString();
|
|
457
|
+
return this.request(qs ? `?${qs}` : "");
|
|
458
|
+
}
|
|
459
|
+
async update(id, data) {
|
|
460
|
+
return this.request(`/${encodeURIComponent(id)}`, {
|
|
461
|
+
method: "PATCH",
|
|
462
|
+
body: JSON.stringify(data),
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
async request(suffix, init = {}) {
|
|
466
|
+
const headers = {
|
|
467
|
+
"x-app-key": this.secretKey,
|
|
468
|
+
};
|
|
469
|
+
if (init.body) {
|
|
470
|
+
headers["content-type"] = "application/json";
|
|
471
|
+
}
|
|
472
|
+
const response = await fetch(new URL(`/storage/${encodeURIComponent(this.name)}${suffix}`, this.apiUrl), { ...init, headers });
|
|
473
|
+
if (response.status === 204)
|
|
474
|
+
return undefined;
|
|
475
|
+
if (!response.ok) {
|
|
476
|
+
const body = await response.json().catch(() => ({ code: "request_failed", message: `Request failed: ${response.status}` }));
|
|
477
|
+
throw new GemmeinError({
|
|
478
|
+
status: response.status,
|
|
479
|
+
code: body.code ?? "request_failed",
|
|
480
|
+
message: body.message ?? `Request failed: ${response.status}`,
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
return response.json();
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
async function handleResponse(response, config) {
|
|
487
|
+
if (response.status === 204)
|
|
488
|
+
return undefined;
|
|
489
|
+
if (!response.ok) {
|
|
490
|
+
const errorBody = await readErrorBody(response);
|
|
491
|
+
if (errorBody.code === "auth_expired") {
|
|
492
|
+
await config.tokenStore.clear();
|
|
493
|
+
}
|
|
494
|
+
// Signpost: a wrong/revoked key routes the builder (or their AI) to
|
|
495
|
+
// where a working key comes from, instead of dead-ending.
|
|
496
|
+
if (errorBody.code === "invalid_app_key" || errorBody.code === "missing_app_key") {
|
|
497
|
+
errorBody.message += " — get your app key from the Setup page at https://app.gemmein.com (sign in with an email code, free, no card)";
|
|
498
|
+
}
|
|
499
|
+
throw new GemmeinError({
|
|
500
|
+
status: response.status,
|
|
501
|
+
code: errorBody.code,
|
|
502
|
+
message: errorBody.message,
|
|
503
|
+
resetAt: errorBody.resetAt
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
return response.json();
|
|
507
|
+
}
|
|
508
|
+
async function readErrorBody(response) {
|
|
509
|
+
try {
|
|
510
|
+
const value = await response.json();
|
|
511
|
+
if (typeof value === "object" && value !== null) {
|
|
512
|
+
const code = typeof value.code === "string"
|
|
513
|
+
? value.code
|
|
514
|
+
: typeof value.error === "string"
|
|
515
|
+
? value.error
|
|
516
|
+
: "request_failed";
|
|
517
|
+
return {
|
|
518
|
+
code,
|
|
519
|
+
message: typeof value.message === "string"
|
|
520
|
+
? value.message
|
|
521
|
+
: `Gemmein request failed: ${response.status}`,
|
|
522
|
+
resetAt: typeof value.resetAt === "string"
|
|
523
|
+
? value.resetAt
|
|
524
|
+
: undefined
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
// Fall through to a stable typed error.
|
|
530
|
+
}
|
|
531
|
+
return {
|
|
532
|
+
code: "request_failed",
|
|
533
|
+
message: `Gemmein request failed: ${response.status}`
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
async function runtimeHeaders(config, headers) {
|
|
537
|
+
const token = await config.tokenStore.get();
|
|
538
|
+
return {
|
|
539
|
+
...headers,
|
|
540
|
+
"x-app-key": config.appKey,
|
|
541
|
+
...(token ? { authorization: `Bearer ${token}` } : {})
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
const COLLECTION_NAME_RE = /^[a-z][a-z0-9_]{1,62}$/;
|
|
545
|
+
function assertCollectionName(name) {
|
|
546
|
+
if (!COLLECTION_NAME_RE.test(name)) {
|
|
547
|
+
throw new GemmeinError({
|
|
548
|
+
status: 0,
|
|
549
|
+
code: "invalid_collection_name",
|
|
550
|
+
message: `Collection name must be lowercase letters, numbers, and underscores (e.g. "tasks", "user_notes"). Got: "${name}"`
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|