@dontcode2/backend 0.2.1 → 0.2.2

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/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @dontcode2/backend
2
2
 
3
3
  The public SDK for the [DontCode](https://www.dontcode.co) backend: a thin, typed
4
- proxy over the v1 HTTP gateway. Auth, database, and file storage for an app you host
5
- yourself ("bring your own code"), behind a single project API key.
4
+ proxy over the v1 HTTP gateway. Auth, database, file storage, a key-value cache, and
5
+ realtime pub/sub for an app you host yourself ("bring your own code"), behind a single
6
+ project API key.
6
7
 
7
8
  It speaks the exact wire protocol of the gateway, so you can move between the SDK and
8
9
  raw HTTP at any time without platform-side changes.
@@ -228,6 +229,61 @@ await priv.move('a.pdf', 'archive/a.pdf')
228
229
  const { url: putUrl } = await priv.presignUpload('big.zip', 'application/zip')
229
230
  ```
230
231
 
232
+ ## Cache
233
+
234
+ A key-value cache for ephemeral, high-churn, or session-scoped state, with optional TTL
235
+ expiry. Keys are scoped to your project automatically. This is a cache, not a database:
236
+ values may be evicted and are not durable, so keep your system of record in `db`.
237
+
238
+ ```ts
239
+ const c = client.cache
240
+
241
+ await c.set('session:42', { step: 2 }, { ttl: 3600 }) // ttl in seconds
242
+ const session = await c.get<{ step: number }>('session:42') // null on miss or expiry
243
+ await c.set('lock:job', '1', { nx: true }) // false if it already existed
244
+ await c.expire('session:42', 600) // or null to clear the TTL
245
+ await c.del('session:42')
246
+
247
+ // hashes
248
+ await c.hset('profile:9', { name: 'Zed', level: 7 })
249
+ const profile = await c.hgetAll<{ name: string; level: number }>('profile:9') // null on miss
250
+
251
+ // sets (string members)
252
+ await c.sAdd('online', 'u1', 'u2')
253
+ const online = await c.sMembers('online') // string[] ([] on miss)
254
+ await c.sRem('online', 'u1')
255
+ ```
256
+
257
+ A miss (or expiry) reads back as `null` for `get`/`hgetAll` and `[]` for `sMembers`,
258
+ not an error.
259
+
260
+ ## Realtime
261
+
262
+ Realtime pub/sub over WebSockets for live features (chat, presence, live updates). The
263
+ SDK is the **server side**: mint a connection token for a browser, publish messages, and
264
+ read presence. The browser opens the socket itself with the scoped token, so it never
265
+ holds your API key. Delivery is fire-and-forget (no history/replay), so persist anything
266
+ that needs durability to `db`.
267
+
268
+ ```ts
269
+ const rt = client.realtime
270
+
271
+ // In your token endpoint, after you've authenticated the user:
272
+ const conn = await rt.mintToken({ channels: [`room:${id}`], identity: userId })
273
+ // → send `conn` to the browser; it connects to `${conn.url}?token=${conn.token}`
274
+ // (use @dontcode/realtime's client `connect()` to handle the socket + reconnect)
275
+
276
+ // From anywhere on your backend:
277
+ const delivered = await rt.publish(`room:${id}`, { text: 'hello' })
278
+ const members = await rt.presence(`room:${id}`) // [{ id, identity? }]
279
+ ```
280
+
281
+ A browser connection may only use the channels named when its token was minted.
282
+
283
+ > The local mock gateway (`dontcode-mock`) and the MCP server currently cover auth,
284
+ > database, and storage. Cache and realtime are available on the hosted gateway; point
285
+ > `DONTCODE_API_URL` at it to use them.
286
+
231
287
  ## Errors
232
288
 
233
289
  Every non-2xx response throws a `DontCodeError`:
@@ -0,0 +1,36 @@
1
+ import { Transport } from './http';
2
+ import type { CacheSetOptions } from './types';
3
+ /**
4
+ * Key-value cache: a typed proxy over `/api/v1/cache`. Keys are namespaced to
5
+ * your project by the gateway; values are JSON. This is ephemeral storage —
6
+ * use `db` for anything that must be durable.
7
+ *
8
+ * ```ts
9
+ * await client.cache.set('session:42', { step: 2 }, { ttl: 3600 })
10
+ * const s = await client.cache.get<{ step: number }>('session:42') // null if expired
11
+ * ```
12
+ */
13
+ export declare class CacheClient {
14
+ private readonly transport;
15
+ constructor(transport: Transport);
16
+ /** Read a value. Returns `null` on a miss or expiry. */
17
+ get<T = unknown>(key: string): Promise<T | null>;
18
+ /** Set a value, optionally with a TTL (seconds) or set-if-absent (`nx`).
19
+ * Returns `false` when `nx` is set and the key already existed. */
20
+ set(key: string, value: unknown, options?: CacheSetOptions): Promise<boolean>;
21
+ /** Delete a key. Returns whether it existed. */
22
+ del(key: string): Promise<boolean>;
23
+ /** Set or clear (`null`) the TTL on an existing key. Returns `false` if absent. */
24
+ expire(key: string, ttl: number | null): Promise<boolean>;
25
+ /** Set fields on a hash. Returns the number of fields written. */
26
+ hset(key: string, fields: Record<string, unknown>): Promise<number>;
27
+ /** Read a whole hash. Returns `null` on a miss. */
28
+ hgetAll<T = Record<string, unknown>>(key: string): Promise<T | null>;
29
+ /** Add members to a set. Returns the number newly added. */
30
+ sAdd(key: string, ...members: string[]): Promise<number>;
31
+ /** List set members. Returns `[]` on a miss. */
32
+ sMembers(key: string): Promise<string[]>;
33
+ /** Remove members from a set. Returns the number removed. */
34
+ sRem(key: string, ...members: string[]): Promise<number>;
35
+ }
36
+ export declare function createCache(transport: Transport): CacheClient;
@@ -3,7 +3,7 @@ import {
3
3
  Transport,
4
4
  dontcode,
5
5
  isDontCodeError
6
- } from "./chunk-CAYYXFFZ.js";
6
+ } from "./chunk-LBN4R3GH.js";
7
7
 
8
8
  // src/credentials.ts
9
9
  import { mkdirSync, readFileSync, writeFileSync } from "fs";
@@ -445,4 +445,4 @@ export {
445
445
  createMcpServer,
446
446
  startMcpServer
447
447
  };
448
- //# sourceMappingURL=chunk-HSPHQ6OU.js.map
448
+ //# sourceMappingURL=chunk-6DFTM26Y.js.map
@@ -294,6 +294,96 @@ var AuthApi = class {
294
294
  }
295
295
  };
296
296
 
297
+ // src/cache.ts
298
+ var CACHE_PATH = "/api/v1/cache";
299
+ var enc = (key) => encodeURIComponent(key);
300
+ function asMiss(err, fallback) {
301
+ if (isDontCodeError(err) && err.status === 404) return fallback;
302
+ throw err;
303
+ }
304
+ var CacheClient = class {
305
+ constructor(transport) {
306
+ this.transport = transport;
307
+ }
308
+ /** Read a value. Returns `null` on a miss or expiry. */
309
+ async get(key) {
310
+ try {
311
+ const r = await this.transport.get(`${CACHE_PATH}/kv/${enc(key)}`);
312
+ return r.value;
313
+ } catch (err) {
314
+ return asMiss(err, null);
315
+ }
316
+ }
317
+ /** Set a value, optionally with a TTL (seconds) or set-if-absent (`nx`).
318
+ * Returns `false` when `nx` is set and the key already existed. */
319
+ async set(key, value, options = {}) {
320
+ const params = new URLSearchParams();
321
+ if (options.ttl != null) params.set("ttl", String(options.ttl));
322
+ if (options.nx) params.set("nx", "true");
323
+ const qs = params.toString() ? `?${params}` : "";
324
+ const r = await this.transport.put(`${CACHE_PATH}/kv/${enc(key)}${qs}`, value);
325
+ return r.set;
326
+ }
327
+ /** Delete a key. Returns whether it existed. */
328
+ async del(key) {
329
+ const r = await this.transport.del(`${CACHE_PATH}/kv/${enc(key)}`);
330
+ return r.deleted;
331
+ }
332
+ /** Set or clear (`null`) the TTL on an existing key. Returns `false` if absent. */
333
+ async expire(key, ttl) {
334
+ const r = await this.transport.json(`${CACHE_PATH}/expire/${enc(key)}`, {
335
+ ttl
336
+ });
337
+ return r.applied;
338
+ }
339
+ // --- hashes -------------------------------------------------------------
340
+ /** Set fields on a hash. Returns the number of fields written. */
341
+ async hset(key, fields) {
342
+ const r = await this.transport.json(`${CACHE_PATH}/hset/${enc(key)}`, {
343
+ fields
344
+ });
345
+ return r.written;
346
+ }
347
+ /** Read a whole hash. Returns `null` on a miss. */
348
+ async hgetAll(key) {
349
+ try {
350
+ const r = await this.transport.get(`${CACHE_PATH}/hgetall/${enc(key)}`);
351
+ return r.value;
352
+ } catch (err) {
353
+ return asMiss(err, null);
354
+ }
355
+ }
356
+ // --- sets ---------------------------------------------------------------
357
+ /** Add members to a set. Returns the number newly added. */
358
+ async sAdd(key, ...members) {
359
+ const r = await this.transport.json(`${CACHE_PATH}/sadd/${enc(key)}`, {
360
+ members
361
+ });
362
+ return r.added;
363
+ }
364
+ /** List set members. Returns `[]` on a miss. */
365
+ async sMembers(key) {
366
+ try {
367
+ const r = await this.transport.get(
368
+ `${CACHE_PATH}/smembers/${enc(key)}`
369
+ );
370
+ return r.value ?? [];
371
+ } catch (err) {
372
+ return asMiss(err, []);
373
+ }
374
+ }
375
+ /** Remove members from a set. Returns the number removed. */
376
+ async sRem(key, ...members) {
377
+ const r = await this.transport.json(`${CACHE_PATH}/srem/${enc(key)}`, {
378
+ members
379
+ });
380
+ return r.removed;
381
+ }
382
+ };
383
+ function createCache(transport) {
384
+ return new CacheClient(transport);
385
+ }
386
+
297
387
  // src/db.ts
298
388
  var DB_PATH = "/api/v1/db";
299
389
  var MIGRATE_PATH = "/api/v1/db/migrate";
@@ -361,6 +451,40 @@ function createDb(transport) {
361
451
  });
362
452
  }
363
453
 
454
+ // src/realtime.ts
455
+ var REALTIME_PATH = "/api/v1/realtime";
456
+ var RealtimeApi = class {
457
+ constructor(transport) {
458
+ this.transport = transport;
459
+ }
460
+ /** Mint a short-lived, channel-scoped connection token for a browser. */
461
+ mintToken(input) {
462
+ return this.transport.json(`${REALTIME_PATH}/token`, {
463
+ channels: input.channels,
464
+ identity: input.identity,
465
+ ttl: input.ttl
466
+ });
467
+ }
468
+ /** Publish a message to a channel. Returns how many subscribers it reached. */
469
+ async publish(channel, payload) {
470
+ const r = await this.transport.json(`${REALTIME_PATH}/publish`, {
471
+ channel,
472
+ payload
473
+ });
474
+ return r.delivered;
475
+ }
476
+ /** Who is currently connected to a channel. */
477
+ async presence(channel) {
478
+ const r = await this.transport.get(
479
+ `${REALTIME_PATH}/channels/${encodeURIComponent(channel)}/presence`
480
+ );
481
+ return r.presence ?? [];
482
+ }
483
+ };
484
+ function createRealtime(transport) {
485
+ return new RealtimeApi(transport);
486
+ }
487
+
364
488
  // src/storage.ts
365
489
  var STORAGE_PATH = "/api/v1/storage";
366
490
  var DEFAULT_CONTENT_TYPE = "application/octet-stream";
@@ -503,6 +627,24 @@ var Transport = class {
503
627
  );
504
628
  return this.parse(res);
505
629
  }
630
+ /** PUT a JSON body and parse the JSON response. */
631
+ async put(path, body, opts) {
632
+ const res = await this.send(
633
+ path,
634
+ {
635
+ method: "PUT",
636
+ headers: { ...this.headers(opts), "Content-Type": "application/json" },
637
+ body: JSON.stringify(body ?? null)
638
+ },
639
+ opts
640
+ );
641
+ return this.parse(res);
642
+ }
643
+ /** DELETE and parse the JSON response. */
644
+ async del(path, opts) {
645
+ const res = await this.send(path, { method: "DELETE", headers: this.headers(opts) }, opts);
646
+ return this.parse(res);
647
+ }
506
648
  /** PUT a multipart form (file uploads). The runtime sets the boundary. */
507
649
  async multipart(path, form, opts) {
508
650
  const res = await this.send(path, { method: "PUT", headers: this.headers(opts), body: form }, opts);
@@ -542,7 +684,9 @@ function dontcode(options = {}) {
542
684
  return {
543
685
  auth: new AuthApi(transport, options.session),
544
686
  db: createDb(transport),
545
- storage: createStorage(transport)
687
+ storage: createStorage(transport),
688
+ cache: createCache(transport),
689
+ realtime: createRealtime(transport)
546
690
  };
547
691
  }
548
692
 
@@ -558,11 +702,15 @@ export {
558
702
  isSessionExpired,
559
703
  MfaApi,
560
704
  AuthApi,
705
+ CacheClient,
706
+ createCache,
561
707
  TableQuery,
562
708
  Transport,
709
+ RealtimeApi,
710
+ createRealtime,
563
711
  BucketClient,
564
712
  PublicBucketClient,
565
713
  createStorage,
566
714
  dontcode
567
715
  };
568
- //# sourceMappingURL=chunk-CAYYXFFZ.js.map
716
+ //# sourceMappingURL=chunk-LBN4R3GH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cookies.ts","../src/errors.ts","../src/session.ts","../src/auth.ts","../src/cache.ts","../src/db.ts","../src/realtime.ts","../src/storage.ts","../src/http.ts","../src/client.ts"],"sourcesContent":["/**\n * Cookie helpers, framework-agnostic by design. They return strings: a\n * `Set-Cookie` header value to write, or a parsed token to read. Your framework\n * applies them (`headers.append('Set-Cookie', …)`, SvelteKit `cookies.set`, a\n * Next `Response` cookie, etc.). The SDK never owns a request or response.\n *\n * Defaults match how DontCode's own apps store the session: an httpOnly cookie\n * so JavaScript can't read the token, `Secure`, `SameSite=Lax`, path `/`, and a\n * 7-day max age. Cross-site setups (your app and the gateway on different sites)\n * need `sameSite: 'none'`, which forces `Secure` on.\n */\n\n/** Default cookie name for the end-user access token. */\nexport const DEFAULT_SESSION_COOKIE_NAME = 'dc_access_token'\n\n/** One week, in seconds. Matches the default session lifetime DontCode issues. */\nconst DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7\n\nexport interface SessionCookieOptions {\n /** Cookie name. Default `dc_access_token`. */\n name?: string\n /** Lifetime in seconds. Default one week. Pass the token's `ExpiresIn` to\n * keep the cookie and the token in lockstep. */\n maxAge?: number\n /** Default `/`. */\n path?: string\n domain?: string\n /** Default `true`. */\n secure?: boolean\n /** Default `true`. Keep the token unreadable from client JavaScript. */\n httpOnly?: boolean\n /** Default `'lax'`. Use `'none'` for cross-site (it forces `Secure`). */\n sameSite?: 'lax' | 'strict' | 'none'\n}\n\nfunction serialize(name: string, value: string, options: SessionCookieOptions, maxAge: number): string {\n const sameSite = options.sameSite ?? 'lax'\n // SameSite=None is meaningless without Secure (browsers drop it), so force\n // Secure on there; otherwise it defaults on and the caller can opt out.\n const secure = sameSite === 'none' ? true : (options.secure ?? true)\n const httpOnly = options.httpOnly ?? true\n const path = options.path ?? '/'\n\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `Max-Age=${maxAge}`]\n if (options.domain) parts.push(`Domain=${options.domain}`)\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`)\n if (httpOnly) parts.push('HttpOnly')\n if (secure) parts.push('Secure')\n return parts.join('; ')\n}\n\n/** Build a `Set-Cookie` value that stores the access token. */\nexport function serializeSessionCookie(token: string, options: SessionCookieOptions = {}): string {\n const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME\n const maxAge = options.maxAge ?? DEFAULT_MAX_AGE_SECONDS\n return serialize(name, token, options, maxAge)\n}\n\n/** Build a `Set-Cookie` value that clears the access token (logout). */\nexport function clearSessionCookie(options: SessionCookieOptions = {}): string {\n const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME\n return serialize(name, '', options, 0)\n}\n\n/** Read the access token out of a `Cookie` request header, or `null`. Pass the\n * raw header string (`name=value; name2=value2`). */\nexport function readSessionToken(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_SESSION_COOKIE_NAME\n): string | null {\n if (!cookieHeader) return null\n for (const pair of cookieHeader.split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n const raw = pair.slice(eq + 1).trim()\n if (!raw) return null\n try {\n return decodeURIComponent(raw)\n } catch {\n return raw\n }\n }\n return null\n}\n","/**\n * Every non-2xx response from the gateway surfaces as a DontCodeError. The\n * platform's error envelope is `{ error, ... }`, sometimes with a machine\n * `code` (e.g. `EmailNotVerified`, `ChallengeExpired`, `MfaNotOffered`) or\n * rate-limit fields. We preserve the whole body so callers can branch on it.\n *\n * Note: many \"one more step\" auth states (signup needing email verification,\n * login returning `mfa_required`) are 2xx successes, NOT errors; inspect the\n * resolved value for those. Errors are reserved for actual failures.\n *\n * Transport failures (no HTTP response at all) also surface as a DontCodeError\n * so callers have one error type: a timeout is status 408 / code `Timeout`, and\n * any other network failure is status 0 / code `NetworkError`. Neither is a\n * `401`, so a guard can distinguish \"backend unavailable\" from \"signed out\".\n */\nexport interface DontCodeErrorBody {\n error?: string\n /** Stable machine code, when the platform sends one. */\n code?: string\n /** Present on 429 responses. */\n rate_limit?: boolean\n /** Seconds until the rate limit resets, on 429 responses. */\n timeleft?: number\n [key: string]: unknown\n}\n\nexport class DontCodeError extends Error {\n /** HTTP status code of the failing response. */\n readonly status: number\n /** Stable machine code, when present (e.g. `EmailNotVerified`). */\n readonly code?: string\n /** The raw parsed response body. */\n readonly body: DontCodeErrorBody\n\n constructor(status: number, body: DontCodeErrorBody) {\n const message =\n typeof body?.error === 'string' && body.error.length > 0\n ? body.error\n : `DontCode request failed with status ${status}`\n super(message)\n this.name = 'DontCodeError'\n this.status = status\n this.code = typeof body?.code === 'string' ? body.code : undefined\n this.body = body ?? {}\n }\n\n /** True when the request was rejected by the per-key rate limiter. */\n get rateLimited(): boolean {\n return this.status === 429\n }\n}\n\n/** Cross-bundle-safe check; works even if two copies of the SDK are loaded. */\nexport function isDontCodeError(err: unknown): err is DontCodeError {\n if (err instanceof DontCodeError) return true\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'DontCodeError'\n )\n}\n","import { isDontCodeError } from './errors'\nimport type { AuthApi } from './auth'\nimport type { CurrentUser } from './types'\n\n/**\n * Session helpers, framework-agnostic by design. They never touch a request or\n * response object; they take a token (or a cookie header) and return plain\n * data, so they slot into any framework's guard (Next middleware, SvelteKit\n * hooks, Express, a worker) without an adapter.\n *\n * The point of the module: an auth guard must not make a network round-trip on\n * every navigation, or a slow gateway stalls the page and a swallowed timeout\n * reads as \"signed out\". So there are two modes:\n *\n * - optimistic — decode the token locally (no signature check, no network)\n * and trust its claims for routing. Instant. Used for the common gate.\n * - verified — call the gateway's `me` once, cache the result for a short\n * TTL, and hard-timeout the request. Used for sensitive actions.\n *\n * The trade-offs (no signature verification, revocation lag) are documented on\n * `getSession` and in the public BYOC docs; read them before choosing a mode.\n */\n\n/** A JWT payload decoded WITHOUT verifying its signature. Trust accordingly. */\nexport interface DecodedSession {\n /** Subject — the user id. */\n sub: string\n email?: string\n role?: string\n claims?: Record<string, unknown>\n /** Expiry, seconds since the epoch (standard JWT `exp`). */\n exp?: number\n /** Issued-at, seconds since the epoch (standard JWT `iat`). */\n iat?: number\n [key: string]: unknown\n}\n\nexport type SessionStatus =\n /** A usable session: a present, unexpired token (verified or optimistic). */\n | 'active'\n /** The token is present but past its `exp`. */\n | 'expired'\n /** No token, or an unparseable one. */\n | 'anonymous'\n /** Verified mode could not reach the gateway (timeout/network/5xx). The\n * optimistically-decoded `user` is still returned so the caller can choose\n * to fail open during an outage instead of logging everyone out. */\n | 'unavailable'\n\nexport interface SessionResult {\n status: SessionStatus\n /** The signed-in user, or `null` when anonymous/expired. In `verified` mode\n * this came from the gateway; in `optimistic` (or `unavailable`) it was\n * decoded from the token's own claims. */\n user: CurrentUser | null\n /** True only when `user` was confirmed by a gateway `me` call this request\n * (or from a fresh cache entry of one). False for optimistic decodes. */\n verified: boolean\n /** The token's `exp` (seconds since epoch), when present. */\n expiresAt?: number\n}\n\nexport interface GetSessionInput {\n accessToken: string\n /** `optimistic` (default): decode locally, zero network. `verified`: confirm\n * against the gateway with caching + a hard timeout. */\n mode?: 'optimistic' | 'verified'\n}\n\n/** A place to cache verified sessions. Swap the default in-memory store for a\n * shared one (Redis, KV) when running multiple instances. */\nexport interface SessionCache {\n get(token: string): SessionResult | undefined\n set(token: string, value: SessionResult, ttlMs: number): void\n delete?(token: string): void\n}\n\nexport interface SessionOptions {\n /** Cache for verified sessions. Defaults to a per-process `InMemorySessionCache`. */\n cache?: SessionCache\n /** How long a verified session stays cached. Default 60_000 (60s). Keep it\n * short: a cached session can outlive a server-side revocation by up to\n * this long. */\n ttlMs?: number\n /** Timeout for the `me` call made by `verified` mode (ms). Default 5_000. */\n verifyTimeoutMs?: number\n}\n\nconst DEFAULT_TTL_MS = 60_000\nconst DEFAULT_VERIFY_TIMEOUT_MS = 5_000\n\n/** Default cache: a `Map` with per-entry TTL. Lives for the life of the process\n * (and is shared across requests on a reused serverless instance). */\nexport class InMemorySessionCache implements SessionCache {\n private readonly store = new Map<string, { value: SessionResult; expiresAtMs: number }>()\n\n get(token: string): SessionResult | undefined {\n const hit = this.store.get(token)\n if (!hit) return undefined\n if (Date.now() >= hit.expiresAtMs) {\n this.store.delete(token)\n return undefined\n }\n return hit.value\n }\n\n set(token: string, value: SessionResult, ttlMs: number): void {\n this.store.set(token, { value, expiresAtMs: Date.now() + ttlMs })\n }\n\n delete(token: string): void {\n this.store.delete(token)\n }\n}\n\nfunction base64UrlDecode(segment: string): string {\n const base64 = segment.replace(/-/g, '+').replace(/_/g, '/')\n const padded = base64.length % 4 === 0 ? base64 : base64 + '='.repeat(4 - (base64.length % 4))\n if (typeof atob === 'function') {\n const binary = atob(padded)\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))\n return new TextDecoder().decode(bytes)\n }\n // Node without a global atob (older runtimes); Buffer is always present there.\n return Buffer.from(padded, 'base64').toString('utf8')\n}\n\n/**\n * Decode a JWT access token's payload WITHOUT verifying its signature, or\n * return `null` if it is not a parseable JWT. This is deliberately cheap and\n * offline; it is not proof the token is genuine. DontCode tokens are signed\n * with a secret the gateway never shares, so the only authority on a token is\n * the gateway's `me` endpoint — use `getSession({ mode: 'verified' })` when you\n * need that authority.\n */\nexport function decodeAccessToken(token: string): DecodedSession | null {\n if (!token || typeof token !== 'string') return null\n const parts = token.split('.')\n if (parts.length < 2) return null\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1])) as Record<string, unknown>\n if (!payload || typeof payload.sub !== 'string') return null\n return payload as DecodedSession\n } catch {\n return null\n }\n}\n\n/** True when a token (or already-decoded payload) is past its `exp`. A token\n * with no `exp` is treated as not expired (the caller cannot prove otherwise\n * offline). `skewSeconds` widens the window to absorb clock drift. */\nexport function isSessionExpired(\n input: string | DecodedSession | null,\n opts: { skewSeconds?: number } = {}\n): boolean {\n const decoded = typeof input === 'string' ? decodeAccessToken(input) : input\n if (!decoded || typeof decoded.exp !== 'number') return false\n const nowSeconds = Date.now() / 1000\n return nowSeconds >= decoded.exp - (opts.skewSeconds ?? 0)\n}\n\nfunction userFromClaims(decoded: DecodedSession): CurrentUser {\n return {\n id: decoded.sub,\n email: typeof decoded.email === 'string' ? decoded.email : '',\n role: decoded.role,\n claims: decoded.claims,\n }\n}\n\n/**\n * Resolves access tokens into sessions for `AuthApi`. Holds the verified-session\n * cache and timeout policy. Not exported directly; reach it via\n * `client.auth.getSession` / `client.auth.sessionFromCookies`.\n */\nexport class SessionVerifier {\n private readonly cache: SessionCache\n private readonly ttlMs: number\n private readonly verifyTimeoutMs: number\n\n constructor(\n private readonly auth: AuthApi,\n options: SessionOptions = {}\n ) {\n this.cache = options.cache ?? new InMemorySessionCache()\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS\n this.verifyTimeoutMs = options.verifyTimeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS\n }\n\n async getSession({ accessToken, mode = 'optimistic' }: GetSessionInput): Promise<SessionResult> {\n const decoded = decodeAccessToken(accessToken)\n if (!decoded) return { status: 'anonymous', user: null, verified: false }\n if (isSessionExpired(decoded)) {\n return { status: 'expired', user: null, verified: false, expiresAt: decoded.exp }\n }\n\n const optimistic: SessionResult = {\n status: 'active',\n user: userFromClaims(decoded),\n verified: false,\n expiresAt: decoded.exp,\n }\n if (mode === 'optimistic') return optimistic\n\n const cached = this.cache.get(accessToken)\n if (cached) return cached\n\n try {\n const { user } = await this.auth.me({\n accessToken,\n timeoutMs: this.verifyTimeoutMs,\n })\n const result: SessionResult = user\n ? { status: 'active', user, verified: true, expiresAt: decoded.exp }\n : { status: 'anonymous', user: null, verified: true }\n this.cache.set(accessToken, result, this.ttlMs)\n return result\n } catch (err) {\n // A real 401 means the gateway rejected the token: the user is out.\n if (isDontCodeError(err) && err.status === 401) {\n return { status: 'anonymous', user: null, verified: true }\n }\n // Timeout / network / 5xx: the backend is unreachable, not a verdict\n // on the user. Hand back the optimistic session marked unavailable so\n // the caller decides whether to fail open. Not cached.\n return { ...optimistic, status: 'unavailable' }\n }\n }\n}\n","import { Transport } from './http'\nimport { readSessionToken } from './cookies'\nimport {\n SessionVerifier,\n decodeAccessToken,\n type DecodedSession,\n type GetSessionInput,\n type SessionOptions,\n type SessionResult,\n} from './session'\nimport type {\n ForgotPasswordInput,\n LoginInput,\n LoginResult,\n MeResult,\n MfaChallengeInput,\n MfaDisableInput,\n MfaEnrollConfirmInput,\n MfaEnrollResult,\n ResetPasswordInput,\n SignupInput,\n SignupResult,\n SimpleResult,\n VerifyEmailInput,\n} from './types'\n\nconst AUTH_BASE = '/api/v1/auth'\n\n/** Shape of `GET /api/v1/info`: validates the credential and reports what it\n * can do. For device tokens, capabilities follow the signed-in user's role. */\nexport interface InfoResult {\n project: { id: string; name: string | null }\n credential: {\n type: 'api_key' | 'device'\n role: string | null\n user_id: string | null\n }\n capabilities: Record<string, boolean>\n}\n\n/**\n * MFA is per-user and opt-in. `enroll`/`enrollConfirm`/`disable` act as the\n * signed-in user, so they need the end-user access token. `challenge` does\n * not; it completes a login that returned `mfa_required`, exchanging the\n * short-lived challenge token for real session tokens.\n */\nexport class MfaApi {\n constructor(private readonly transport: Transport) {}\n\n /** Complete an MFA login. Pass the `challenge_token` from `login`, plus\n * either the authenticator `code` or a `recoveryCode`. */\n challenge(input: MfaChallengeInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/mfa/challenge`, {\n challenge_token: input.challengeToken,\n code: input.code,\n recovery_code: input.recoveryCode,\n })\n }\n\n /** Begin enrollment. Render the returned `otpauth_url` as a QR code.\n * Enrollment stays pending until `enrollConfirm`. */\n enroll(input: { accessToken: string }): Promise<MfaEnrollResult> {\n return this.transport.json<MfaEnrollResult>(\n `${AUTH_BASE}/mfa/enroll`,\n {},\n { accessToken: input.accessToken }\n )\n }\n\n /** Confirm enrollment with the first authenticator code. The returned\n * `recovery_codes` are shown once and never again. */\n enrollConfirm(input: MfaEnrollConfirmInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/enroll/confirm`,\n { code: input.code },\n { accessToken: input.accessToken }\n )\n }\n\n /** Turn MFA off. Proves possession of the second factor via `code` or\n * `recoveryCode`. */\n disable(input: MfaDisableInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(\n `${AUTH_BASE}/mfa/disable`,\n { code: input.code, recovery_code: input.recoveryCode },\n { accessToken: input.accessToken }\n )\n }\n}\n\n/**\n * Fronts DontCode Auth with the same shapes as the gateway. Two behaviours are\n * project settings (not API flags) and your code must handle both states:\n * email verification (signup may not return tokens) and MFA (login may be two\n * steps). Branch on the resolved value; never assume one round-trip.\n */\nexport class AuthApi {\n readonly mfa: MfaApi\n private readonly sessions: SessionVerifier\n\n constructor(\n private readonly transport: Transport,\n sessionOptions?: SessionOptions\n ) {\n this.mfa = new MfaApi(transport)\n this.sessions = new SessionVerifier(this, sessionOptions)\n }\n\n /** Create an account. If the project requires email verification the\n * response has `verification_required: true` and NO tokens; collect a\n * code and call `verifyEmail`, then `login`. */\n signup(input: SignupInput): Promise<SignupResult> {\n return this.transport.json<SignupResult>(`${AUTH_BASE}/signup`, {\n email: input.email,\n password: input.password,\n name: input.name,\n role: input.role,\n })\n }\n\n /** Authenticate. Branch on `mfa_required`: when true you hold only a\n * challenge (finish via `mfa.challenge`); otherwise `tokens` is your\n * session. A 403 `EmailNotVerified` means the email step isn't done. */\n login(input: LoginInput): Promise<LoginResult> {\n return this.transport.json<LoginResult>(`${AUTH_BASE}/login`, {\n email: input.email,\n password: input.password,\n })\n }\n\n /** Validate the current credential (API key or device token) and report the\n * project, the caller's role, and which capabilities that role grants.\n * Backs the MCP \"is my session still good\" check. */\n info(): Promise<InfoResult> {\n return this.transport.get<InfoResult>('/api/v1/info')\n }\n\n /** Resolve the signed-in user from their access token, or `{ user: null }`.\n * This is a network round-trip; for a per-navigation guard prefer\n * `getSession`, which can answer offline and caches verified results. */\n me(input: { accessToken: string; timeoutMs?: number }): Promise<MeResult> {\n return this.transport.json<MeResult>(\n `${AUTH_BASE}/me`,\n {},\n { accessToken: input.accessToken, timeoutMs: input.timeoutMs }\n )\n }\n\n /**\n * Resolve an access token into a session for a route guard, the one call\n * that replaces \"hit `me` on every navigation\". Two modes:\n *\n * - `'optimistic'` (default): decode the token locally and trust its\n * claims. Zero network, zero stall. The right default for gating page\n * loads. It does NOT verify the signature and will not notice a\n * server-side revocation until the token's own `exp`.\n * - `'verified'`: confirm against the gateway's `me`, cached for a short\n * TTL with a hard timeout. Use it before sensitive actions. On a\n * timeout/outage it returns `status: 'unavailable'` with the optimistic\n * user, so you choose whether to fail open rather than the SDK guessing.\n *\n * See the BYOC docs (\"Sessions\") for the full reasoning and best practices.\n */\n getSession(input: GetSessionInput): Promise<SessionResult> {\n return this.sessions.getSession(input)\n }\n\n /** Read the access token from a `Cookie` request header and resolve it, in\n * one call. `name` defaults to `dc_access_token`. Returns the anonymous\n * session when no cookie is present. */\n sessionFromCookies(\n cookieHeader: string | null | undefined,\n options: { mode?: GetSessionInput['mode']; cookieName?: string } = {}\n ): Promise<SessionResult> {\n const token = readSessionToken(cookieHeader, options.cookieName)\n if (!token) return Promise.resolve({ status: 'anonymous', user: null, verified: false })\n return this.sessions.getSession({ accessToken: token, mode: options.mode })\n }\n\n /** Decode an access token's claims locally without a network call or any\n * signature check. Convenience re-export of `decodeAccessToken`. */\n decodeToken(token: string): DecodedSession | null {\n return decodeAccessToken(token)\n }\n\n /** Confirm the 6-digit code emailed at signup. */\n verifyEmail(input: VerifyEmailInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/verify-email`, {\n code: input.code,\n email: input.email,\n })\n }\n\n forgotPassword(input: ForgotPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/forgot-password`, {\n email: input.email,\n })\n }\n\n resetPassword(input: ResetPasswordInput): Promise<SimpleResult> {\n return this.transport.json<SimpleResult>(`${AUTH_BASE}/reset-password`, {\n code: input.code,\n password: input.password,\n email: input.email,\n })\n }\n}\n","import { isDontCodeError } from './errors'\nimport { Transport } from './http'\nimport type { CacheSetOptions } from './types'\n\nconst CACHE_PATH = '/api/v1/cache'\n\nconst enc = (key: string) => encodeURIComponent(key)\n\n/** Treat a 404 from the gateway as a cache miss rather than an error. */\nfunction asMiss<T>(err: unknown, fallback: T): T {\n if (isDontCodeError(err) && err.status === 404) return fallback\n throw err\n}\n\n/**\n * Key-value cache: a typed proxy over `/api/v1/cache`. Keys are namespaced to\n * your project by the gateway; values are JSON. This is ephemeral storage —\n * use `db` for anything that must be durable.\n *\n * ```ts\n * await client.cache.set('session:42', { step: 2 }, { ttl: 3600 })\n * const s = await client.cache.get<{ step: number }>('session:42') // null if expired\n * ```\n */\nexport class CacheClient {\n constructor(private readonly transport: Transport) {}\n\n /** Read a value. Returns `null` on a miss or expiry. */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const r = await this.transport.get<{ value: T }>(`${CACHE_PATH}/kv/${enc(key)}`)\n return r.value\n } catch (err) {\n return asMiss<T | null>(err, null)\n }\n }\n\n /** Set a value, optionally with a TTL (seconds) or set-if-absent (`nx`).\n * Returns `false` when `nx` is set and the key already existed. */\n async set(key: string, value: unknown, options: CacheSetOptions = {}): Promise<boolean> {\n const params = new URLSearchParams()\n if (options.ttl != null) params.set('ttl', String(options.ttl))\n if (options.nx) params.set('nx', 'true')\n const qs = params.toString() ? `?${params}` : ''\n const r = await this.transport.put<{ set: boolean }>(`${CACHE_PATH}/kv/${enc(key)}${qs}`, value)\n return r.set\n }\n\n /** Delete a key. Returns whether it existed. */\n async del(key: string): Promise<boolean> {\n const r = await this.transport.del<{ deleted: boolean }>(`${CACHE_PATH}/kv/${enc(key)}`)\n return r.deleted\n }\n\n /** Set or clear (`null`) the TTL on an existing key. Returns `false` if absent. */\n async expire(key: string, ttl: number | null): Promise<boolean> {\n const r = await this.transport.json<{ applied: boolean }>(`${CACHE_PATH}/expire/${enc(key)}`, {\n ttl,\n })\n return r.applied\n }\n\n // --- hashes -------------------------------------------------------------\n\n /** Set fields on a hash. Returns the number of fields written. */\n async hset(key: string, fields: Record<string, unknown>): Promise<number> {\n const r = await this.transport.json<{ written: number }>(`${CACHE_PATH}/hset/${enc(key)}`, {\n fields,\n })\n return r.written\n }\n\n /** Read a whole hash. Returns `null` on a miss. */\n async hgetAll<T = Record<string, unknown>>(key: string): Promise<T | null> {\n try {\n const r = await this.transport.get<{ value: T }>(`${CACHE_PATH}/hgetall/${enc(key)}`)\n return r.value\n } catch (err) {\n return asMiss<T | null>(err, null)\n }\n }\n\n // --- sets ---------------------------------------------------------------\n\n /** Add members to a set. Returns the number newly added. */\n async sAdd(key: string, ...members: string[]): Promise<number> {\n const r = await this.transport.json<{ added: number }>(`${CACHE_PATH}/sadd/${enc(key)}`, {\n members,\n })\n return r.added\n }\n\n /** List set members. Returns `[]` on a miss. */\n async sMembers(key: string): Promise<string[]> {\n try {\n const r = await this.transport.get<{ value: string[] }>(\n `${CACHE_PATH}/smembers/${enc(key)}`\n )\n return r.value ?? []\n } catch (err) {\n return asMiss<string[]>(err, [])\n }\n }\n\n /** Remove members from a set. Returns the number removed. */\n async sRem(key: string, ...members: string[]): Promise<number> {\n const r = await this.transport.json<{ removed: number }>(`${CACHE_PATH}/srem/${enc(key)}`, {\n members,\n })\n return r.removed\n }\n}\n\nexport function createCache(transport: Transport): CacheClient {\n return new CacheClient(transport)\n}\n","import { Transport } from './http'\nimport type {\n DeleteInput,\n MigrateInput,\n MigrateResult,\n QueryOptions,\n UpdateInput,\n} from './types'\n\nconst DB_PATH = '/api/v1/db'\nconst MIGRATE_PATH = '/api/v1/db/migrate'\n\n/** The gateway wraps every DB result in `{ data }`; we unwrap it. */\ninterface DbEnvelope<T> {\n data: T\n}\n\n/**\n * A handle to one table. Structured queries only; there is no raw-SQL escape\n * hatch (schema changes go through `db.migrate`). `update` and `delete`\n * require a `where` clause server-side, so the types make it mandatory.\n */\nexport class TableQuery {\n constructor(\n private readonly transport: Transport,\n private readonly tableName: string\n ) {}\n\n private async run<T>(operation: string, options: unknown): Promise<T> {\n const res = await this.transport.json<DbEnvelope<T>>(DB_PATH, {\n operation,\n tableName: this.tableName,\n options,\n })\n return res.data\n }\n\n /** Rows matching the query (max 1000 per call). */\n find<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('find', options)\n }\n\n /** Alias of `find`. */\n findMany<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T[]> {\n return this.run<T[]>('findMany', options)\n }\n\n /** The first matching row, or `null`. */\n findFirst<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findFirst', options)\n }\n\n /** Alias of `findFirst`. */\n findOne<T = Record<string, unknown>>(options: QueryOptions = {}): Promise<T | null> {\n return this.run<T | null>('findOne', options)\n }\n\n /** Insert one row. Returns `{ id }`. Unique/FK conflicts throw a 409\n * DontCodeError, the supported idempotency signal. */\n insert(data: Record<string, unknown>): Promise<{ id: unknown }> {\n return this.run<{ id: unknown }>('insert', { data })\n }\n\n /** Update rows matching `where`. Returns `{ count }`. */\n update(input: UpdateInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('update', { where: input.where, data: input.data })\n }\n\n /** Delete rows matching `where`. Returns `{ count }`. */\n delete(input: DeleteInput): Promise<{ count: number }> {\n return this.run<{ count: number }>('delete', { where: input.where })\n }\n\n /** Count matching rows. */\n count(options: Pick<QueryOptions, 'where'> = {}): Promise<number> {\n return this.run<number>('count', options)\n }\n}\n\n/**\n * `db.users.find()` and `db('users').find()` both work; the bracket/callable\n * form is there for table names that aren't valid identifiers. `db.migrate()`\n * applies schema DDL (the one place migrations enter from outside).\n */\nexport type DbClient = {\n readonly [tableName: string]: TableQuery\n} & {\n (tableName: string): TableQuery\n migrate(input: MigrateInput): Promise<MigrateResult>\n}\n\nexport function createDb(transport: Transport): DbClient {\n const table = (tableName: string): TableQuery => new TableQuery(transport, tableName)\n const migrate = (input: MigrateInput): Promise<MigrateResult> =>\n transport.json<MigrateResult>(MIGRATE_PATH, { sql: input.sql })\n\n return new Proxy(table, {\n get(target, prop, receiver) {\n if (prop === 'migrate') return migrate\n // Don't manufacture a TableQuery for symbols or promise-unwrapping\n // probes (`then`) or the function's own members.\n if (typeof prop !== 'string' || prop === 'then' || prop in target) {\n return Reflect.get(target, prop, receiver)\n }\n return new TableQuery(transport, prop)\n },\n apply(_target, _thisArg, args: [string]) {\n return table(args[0])\n },\n }) as unknown as DbClient\n}\n","import { Transport } from './http'\nimport type { ConnectionToken, MintConnectionTokenInput, RealtimePresenceMember } from './types'\n\nconst REALTIME_PATH = '/api/v1/realtime'\n\n/**\n * Realtime control plane: a typed proxy over `/api/v1/realtime`. This is the\n * server side — mint connection tokens for browsers, publish messages, and read\n * presence. The WebSocket itself terminates at the realtime service: hand the\n * `{ token, url }` from `mintToken` to a browser and connect to\n * `${url}?token=${token}`. Channels are namespaced to your project by the gateway.\n *\n * ```ts\n * // In your token endpoint, after authenticating the user:\n * const conn = await client.realtime.mintToken({ channels: [`room:${id}`], identity: userId })\n * // → return conn to the browser, which connects to `${conn.url}?token=${conn.token}`\n *\n * // From anywhere on your backend:\n * await client.realtime.publish(`room:${id}`, { text: 'hello' })\n * ```\n */\nexport class RealtimeApi {\n constructor(private readonly transport: Transport) {}\n\n /** Mint a short-lived, channel-scoped connection token for a browser. */\n mintToken(input: MintConnectionTokenInput): Promise<ConnectionToken> {\n return this.transport.json<ConnectionToken>(`${REALTIME_PATH}/token`, {\n channels: input.channels,\n identity: input.identity,\n ttl: input.ttl,\n })\n }\n\n /** Publish a message to a channel. Returns how many subscribers it reached. */\n async publish(channel: string, payload: unknown): Promise<number> {\n const r = await this.transport.json<{ delivered: number }>(`${REALTIME_PATH}/publish`, {\n channel,\n payload,\n })\n return r.delivered\n }\n\n /** Who is currently connected to a channel. */\n async presence(channel: string): Promise<RealtimePresenceMember[]> {\n const r = await this.transport.get<{ presence: RealtimePresenceMember[] }>(\n `${REALTIME_PATH}/channels/${encodeURIComponent(channel)}/presence`\n )\n return r.presence ?? []\n }\n}\n\nexport function createRealtime(transport: Transport): RealtimeApi {\n return new RealtimeApi(transport)\n}\n","import { Transport } from './http'\nimport type {\n DownloadResult,\n ListResult,\n PresignResult,\n StorageBucket,\n StorageObject,\n TemporaryUrlResult,\n UploadBody,\n} from './types'\n\nconst STORAGE_PATH = '/api/v1/storage'\n\nconst DEFAULT_CONTENT_TYPE = 'application/octet-stream'\n\n/** Normalize whatever the caller hands us into a Blob for multipart upload. */\nfunction toBlob(body: UploadBody, contentType: string): Blob {\n if (body instanceof Blob) return body\n if (typeof body === 'string') return new Blob([body], { type: contentType })\n if (body instanceof ArrayBuffer) return new Blob([body], { type: contentType })\n if (ArrayBuffer.isView(body)) {\n return new Blob([body as unknown as BlobPart], { type: contentType })\n }\n throw new TypeError('upload expects a Blob, ArrayBuffer, typed array, or string')\n}\n\nfunction fileName(path: string): string {\n return path.split('/').filter(Boolean).pop() ?? path\n}\n\n/** Operations available on both buckets. */\nexport class BucketClient {\n constructor(\n protected readonly transport: Transport,\n protected readonly bucket: StorageBucket\n ) {}\n\n protected op<T>(operation: string, params: Record<string, unknown> = {}): Promise<T> {\n return this.transport.json<T>(STORAGE_PATH, { operation, bucket: this.bucket, ...params })\n }\n\n /** List objects under `prefix`. */\n list(prefix?: string): Promise<ListResult> {\n return this.op<ListResult>('list', { prefix })\n }\n\n /** Delete one or more objects. Returns `{ deleted }`. */\n remove(paths: string[]): Promise<{ deleted: number }> {\n return this.op<{ deleted: number }>('remove', { paths })\n }\n\n /** Move/rename an object within the bucket. */\n move(from: string, to: string): Promise<{ object: StorageObject }> {\n return this.op<{ object: StorageObject }>('move', { from, to })\n }\n\n createFolder(path: string): Promise<{ created: string }> {\n return this.op<{ created: string }>('createFolder', { path })\n }\n\n /** Download an object inline (≤ 8 MB). Use `getTemporaryUrl` for larger files. */\n download(path: string): Promise<DownloadResult> {\n return this.op<DownloadResult>('download', { path })\n }\n\n /** A short-lived signed URL (default 300s, max 7 days). */\n getTemporaryUrl(path: string, expiresIn?: number): Promise<TemporaryUrlResult> {\n return this.op<TemporaryUrlResult>('getTemporaryUrl', { path, expiresIn })\n }\n\n /** A presigned PUT URL for direct, large uploads (≤ no inline limit). */\n presignUpload(path: string, contentType?: string): Promise<PresignResult> {\n return this.op<PresignResult>('presignUpload', { path, contentType })\n }\n\n /** Upload bytes directly (≤ 100 MB). For larger files, `presignUpload`\n * then PUT to the returned URL yourself. */\n upload(\n path: string,\n body: UploadBody,\n contentType: string = DEFAULT_CONTENT_TYPE\n ): Promise<{ object: StorageObject }> {\n const form = new FormData()\n form.append('file', toBlob(body, contentType), fileName(path))\n form.append('bucket', this.bucket)\n form.append('path', path)\n form.append('contentType', contentType)\n return this.transport.multipart<{ object: StorageObject }>(STORAGE_PATH, form)\n }\n}\n\n/** The public bucket additionally exposes stable public URLs. */\nexport class PublicBucketClient extends BucketClient {\n constructor(transport: Transport) {\n super(transport, 'public')\n }\n\n /** The permanent public URL for an object. */\n getUrl(path: string): Promise<{ url: string }> {\n return this.op<{ url: string }>('getUrl', { path })\n }\n}\n\nexport interface StorageClient {\n public: PublicBucketClient\n private: BucketClient\n}\n\nexport function createStorage(transport: Transport): StorageClient {\n return {\n public: new PublicBucketClient(transport),\n private: new BucketClient(transport, 'private'),\n }\n}\n","import { DontCodeError, type DontCodeErrorBody } from './errors'\n\n/** Default per-request timeout. Without one, a slow or unreachable gateway can\n * hang a request for the platform's full socket timeout (tens of seconds),\n * which is the single worst failure mode for an auth guard on the hot path. */\nexport const DEFAULT_TIMEOUT_MS = 10_000\n\nexport interface TransportConfig {\n /** Project API key. When absent, no Authorization header is sent and the\n * gateway responds with its own \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin, already normalized (no trailing slash). */\n baseUrl: string\n /** Per-request timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`; `0` (or any\n * non-positive value) disables it. */\n timeoutMs?: number\n}\n\nexport interface RequestOptions {\n /** End-user access token, sent as `X-Access-Token` (separate from the\n * project API key). Required by signed-in auth calls. */\n accessToken?: string\n /** Override the client's timeout for this one call (ms). `0` disables it. */\n timeoutMs?: number\n}\n\n/**\n * The single place network requests are made. Everything else in the SDK is a\n * typed shape around `json()` / `multipart()`. No retries, no caching, just a\n * faithful proxy of the v1 gateway.\n */\nexport class Transport {\n constructor(private readonly config: TransportConfig) {}\n\n private headers(opts?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {}\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`\n if (opts?.accessToken) headers['X-Access-Token'] = opts.accessToken\n return headers\n }\n\n private url(path: string): string {\n return `${this.config.baseUrl}${path}`\n }\n\n private timeout(opts?: RequestOptions): number {\n const value = opts?.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n return value > 0 ? value : 0\n }\n\n /**\n * One fetch, with a timeout that turns \"hung socket\" into a fast, typed\n * failure. A timeout surfaces as `DontCodeError` with status 408 / code\n * `Timeout`; any other transport failure (DNS, refused, offline) as status\n * 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth\n * guard can tell \"backend is down\" apart from \"user is signed out\".\n */\n private async send(path: string, init: RequestInit, opts?: RequestOptions): Promise<Response> {\n const timeoutMs = this.timeout(opts)\n const controller = timeoutMs > 0 ? new AbortController() : undefined\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : undefined\n try {\n return await fetch(this.url(path), { ...init, signal: controller?.signal })\n } catch (err) {\n if (controller?.signal.aborted) {\n throw new DontCodeError(408, {\n error: `Request to ${path} timed out after ${timeoutMs}ms`,\n code: 'Timeout',\n })\n }\n throw new DontCodeError(0, {\n error: err instanceof Error ? err.message : 'Network request failed',\n code: 'NetworkError',\n })\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n /** GET and parse the JSON response. */\n async get<T>(path: string, opts?: RequestOptions): Promise<T> {\n const res = await this.send(path, { method: 'GET', headers: this.headers(opts) }, opts)\n return this.parse<T>(res)\n }\n\n /** POST a JSON body and parse the JSON response. */\n async json<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T> {\n const res = await this.send(\n path,\n {\n method: 'POST',\n headers: { ...this.headers(opts), 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n },\n opts\n )\n return this.parse<T>(res)\n }\n\n /** PUT a JSON body and parse the JSON response. */\n async put<T>(path: string, body?: unknown, opts?: RequestOptions): Promise<T> {\n const res = await this.send(\n path,\n {\n method: 'PUT',\n headers: { ...this.headers(opts), 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? null),\n },\n opts\n )\n return this.parse<T>(res)\n }\n\n /** DELETE and parse the JSON response. */\n async del<T>(path: string, opts?: RequestOptions): Promise<T> {\n const res = await this.send(path, { method: 'DELETE', headers: this.headers(opts) }, opts)\n return this.parse<T>(res)\n }\n\n /** PUT a multipart form (file uploads). The runtime sets the boundary. */\n async multipart<T>(path: string, form: FormData, opts?: RequestOptions): Promise<T> {\n const res = await this.send(path, { method: 'PUT', headers: this.headers(opts), body: form }, opts)\n return this.parse<T>(res)\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const raw = await res.text()\n let data: unknown = null\n if (raw) {\n try {\n data = JSON.parse(raw)\n } catch {\n data = { error: raw }\n }\n }\n if (!res.ok) {\n const body: DontCodeErrorBody =\n data && typeof data === 'object'\n ? (data as DontCodeErrorBody)\n : { error: res.statusText || 'Request failed' }\n throw new DontCodeError(res.status, body)\n }\n return data as T\n }\n}\n","import { AuthApi } from './auth'\nimport { CacheClient, createCache } from './cache'\nimport { createDb, type DbClient } from './db'\nimport { Transport } from './http'\nimport { createRealtime, RealtimeApi } from './realtime'\nimport type { SessionOptions } from './session'\nimport { createStorage, type StorageClient } from './storage'\n\nconst DEFAULT_BASE_URL = 'https://backend.dontcode.co'\n\nexport interface DontCodeClientOptions {\n /** Project API key (`dc_…`). Defaults to `process.env.DONTCODE_API_KEY`.\n * If neither is set, requests fail naturally with the gateway's\n * \"Missing API key\" 401. */\n apiKey?: string\n /** Gateway origin. Defaults to `process.env.DONTCODE_API_URL`, then to\n * `https://backend.dontcode.co`. */\n baseUrl?: string\n /** Per-request network timeout in ms. Defaults to 10_000; `0` disables it.\n * Without one, a slow gateway can hang a request for the full socket\n * timeout, the worst case for an auth guard. */\n timeoutMs?: number\n /** Caching + timeout policy for `auth.getSession` / `auth.sessionFromCookies`. */\n session?: SessionOptions\n}\n\nexport interface DontCodeClient {\n auth: AuthApi\n db: DbClient\n storage: StorageClient\n cache: CacheClient\n realtime: RealtimeApi\n}\n\n/** Read an env var without assuming `process` exists (e.g. in the browser). */\nfunction fromEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined\n return process.env[name]\n}\n\n/**\n * Create a DontCode backend client. A thin, typed proxy over the v1 HTTP\n * gateway: auth, database, storage, cache, and realtime. The API key scopes\n * every request to a single project; there is nothing else to configure.\n *\n * ```ts\n * import { dontcode } from '@dontcode2/backend'\n * const client = dontcode() // reads DONTCODE_API_KEY\n * await client.auth.signup({ email, password, role: 'editor' })\n * ```\n */\nexport function dontcode(options: DontCodeClientOptions = {}): DontCodeClient {\n const apiKey = options.apiKey ?? fromEnv('DONTCODE_API_KEY')\n const baseUrl = (options.baseUrl ?? fromEnv('DONTCODE_API_URL') ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n )\n\n const transport = new Transport({ apiKey, baseUrl, timeoutMs: options.timeoutMs })\n\n return {\n auth: new AuthApi(transport, options.session),\n db: createDb(transport),\n storage: createStorage(transport),\n cache: createCache(transport),\n realtime: createRealtime(transport),\n }\n}\n"],"mappings":";AAaO,IAAM,8BAA8B;AAG3C,IAAM,0BAA0B,KAAK,KAAK,KAAK;AAmB/C,SAAS,UAAU,MAAc,OAAe,SAA+B,QAAwB;AACnG,QAAM,WAAW,QAAQ,YAAY;AAGrC,QAAM,SAAS,aAAa,SAAS,OAAQ,QAAQ,UAAU;AAC/D,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,OAAO,QAAQ,QAAQ;AAE7B,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,mBAAmB,KAAK,CAAC,IAAI,QAAQ,IAAI,IAAI,WAAW,MAAM,EAAE;AAC1F,MAAI,QAAQ,OAAQ,OAAM,KAAK,UAAU,QAAQ,MAAM,EAAE;AACzD,QAAM,KAAK,YAAY,SAAS,OAAO,CAAC,EAAE,YAAY,CAAC,GAAG,SAAS,MAAM,CAAC,CAAC,EAAE;AAC7E,MAAI,SAAU,OAAM,KAAK,UAAU;AACnC,MAAI,OAAQ,OAAM,KAAK,QAAQ;AAC/B,SAAO,MAAM,KAAK,IAAI;AAC1B;AAGO,SAAS,uBAAuB,OAAe,UAAgC,CAAC,GAAW;AAC9F,QAAM,OAAO,QAAQ,QA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AAM,KAAK,GAAG,IAAI;AAClG,WAAO,KAAK,MAAS,GAAG;AAAA,EAC5B;AAAA,EAEA,MAAc,MAAS,KAA2B;AAC9C,UAAM,MAAM,MAAM,IAAI,KAAK;AAC3B,QAAI,OAAgB;AACpB,QAAI,KAAK;AACL,UAAI;AACA,eAAO,KAAK,MAAM,GAAG;AAAA,MACzB,QAAQ;AACJ,eAAO,EAAE,OAAO,IAAI;AAAA,MACxB;AAAA,IACJ;AACA,QAAI,CAAC,IAAI,IAAI;AACT,YAAM,OACF,QAAQ,OAAO,SAAS,WACjB,OACD,EAAE,OAAO,IAAI,cAAc,iBAAiB;AACtD,YAAM,IAAI,cAAc,IAAI,QAAQ,IAAI;AAAA,IAC5C;AACA,WAAO;AAAA,EACX;AACJ;;;ACxIA,IAAM,mBAAmB;AA2BzB,SAAS,QAAQ,MAAkC;AAC/C,MAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,IAAK,QAAO;AAC3D,SAAO,QAAQ,IAAI,IAAI;AAC3B;AAaO,SAAS,SAAS,UAAiC,CAAC,GAAmB;AAC1E,QAAM,SAAS,QAAQ,UAAU,QAAQ,kBAAkB;AAC3D,QAAM,WAAW,QAAQ,WAAW,QAAQ,kBAAkB,KAAK,kBAAkB;AAAA,IACjF;AAAA,IACA;AAAA,EACJ;AAEA,QAAM,YAAY,IAAI,UAAU,EAAE,QAAQ,SAAS,WAAW,QAAQ,UAAU,CAAC;AAEjF,SAAO;AAAA,IACH,MAAM,IAAI,QAAQ,WAAW,QAAQ,OAAO;AAAA,IAC5C,IAAI,SAAS,SAAS;AAAA,IACtB,SAAS,cAAc,SAAS;AAAA,IAChC,OAAO,YAAY,SAAS;AAAA,IAC5B,UAAU,eAAe,SAAS;AAAA,EACtC;AACJ;","names":[]}
package/dist/cli.cjs CHANGED
@@ -161,6 +161,24 @@ var Transport = class {
161
161
  );
162
162
  return this.parse(res);
163
163
  }
164
+ /** PUT a JSON body and parse the JSON response. */
165
+ async put(path, body, opts) {
166
+ const res = await this.send(
167
+ path,
168
+ {
169
+ method: "PUT",
170
+ headers: { ...this.headers(opts), "Content-Type": "application/json" },
171
+ body: JSON.stringify(body ?? null)
172
+ },
173
+ opts
174
+ );
175
+ return this.parse(res);
176
+ }
177
+ /** DELETE and parse the JSON response. */
178
+ async del(path, opts) {
179
+ const res = await this.send(path, { method: "DELETE", headers: this.headers(opts) }, opts);
180
+ return this.parse(res);
181
+ }
164
182
  /** PUT a multipart form (file uploads). The runtime sets the boundary. */
165
183
  async multipart(path, form, opts) {
166
184
  const res = await this.send(path, { method: "PUT", headers: this.headers(opts), body: form }, opts);
@@ -516,6 +534,96 @@ var AuthApi = class {
516
534
  }
517
535
  };
518
536
 
537
+ // src/cache.ts
538
+ var CACHE_PATH = "/api/v1/cache";
539
+ var enc = (key) => encodeURIComponent(key);
540
+ function asMiss(err, fallback) {
541
+ if (isDontCodeError(err) && err.status === 404) return fallback;
542
+ throw err;
543
+ }
544
+ var CacheClient = class {
545
+ constructor(transport) {
546
+ this.transport = transport;
547
+ }
548
+ /** Read a value. Returns `null` on a miss or expiry. */
549
+ async get(key) {
550
+ try {
551
+ const r = await this.transport.get(`${CACHE_PATH}/kv/${enc(key)}`);
552
+ return r.value;
553
+ } catch (err) {
554
+ return asMiss(err, null);
555
+ }
556
+ }
557
+ /** Set a value, optionally with a TTL (seconds) or set-if-absent (`nx`).
558
+ * Returns `false` when `nx` is set and the key already existed. */
559
+ async set(key, value, options = {}) {
560
+ const params = new URLSearchParams();
561
+ if (options.ttl != null) params.set("ttl", String(options.ttl));
562
+ if (options.nx) params.set("nx", "true");
563
+ const qs = params.toString() ? `?${params}` : "";
564
+ const r = await this.transport.put(`${CACHE_PATH}/kv/${enc(key)}${qs}`, value);
565
+ return r.set;
566
+ }
567
+ /** Delete a key. Returns whether it existed. */
568
+ async del(key) {
569
+ const r = await this.transport.del(`${CACHE_PATH}/kv/${enc(key)}`);
570
+ return r.deleted;
571
+ }
572
+ /** Set or clear (`null`) the TTL on an existing key. Returns `false` if absent. */
573
+ async expire(key, ttl) {
574
+ const r = await this.transport.json(`${CACHE_PATH}/expire/${enc(key)}`, {
575
+ ttl
576
+ });
577
+ return r.applied;
578
+ }
579
+ // --- hashes -------------------------------------------------------------
580
+ /** Set fields on a hash. Returns the number of fields written. */
581
+ async hset(key, fields) {
582
+ const r = await this.transport.json(`${CACHE_PATH}/hset/${enc(key)}`, {
583
+ fields
584
+ });
585
+ return r.written;
586
+ }
587
+ /** Read a whole hash. Returns `null` on a miss. */
588
+ async hgetAll(key) {
589
+ try {
590
+ const r = await this.transport.get(`${CACHE_PATH}/hgetall/${enc(key)}`);
591
+ return r.value;
592
+ } catch (err) {
593
+ return asMiss(err, null);
594
+ }
595
+ }
596
+ // --- sets ---------------------------------------------------------------
597
+ /** Add members to a set. Returns the number newly added. */
598
+ async sAdd(key, ...members) {
599
+ const r = await this.transport.json(`${CACHE_PATH}/sadd/${enc(key)}`, {
600
+ members
601
+ });
602
+ return r.added;
603
+ }
604
+ /** List set members. Returns `[]` on a miss. */
605
+ async sMembers(key) {
606
+ try {
607
+ const r = await this.transport.get(
608
+ `${CACHE_PATH}/smembers/${enc(key)}`
609
+ );
610
+ return r.value ?? [];
611
+ } catch (err) {
612
+ return asMiss(err, []);
613
+ }
614
+ }
615
+ /** Remove members from a set. Returns the number removed. */
616
+ async sRem(key, ...members) {
617
+ const r = await this.transport.json(`${CACHE_PATH}/srem/${enc(key)}`, {
618
+ members
619
+ });
620
+ return r.removed;
621
+ }
622
+ };
623
+ function createCache(transport) {
624
+ return new CacheClient(transport);
625
+ }
626
+
519
627
  // src/db.ts
520
628
  var DB_PATH = "/api/v1/db";
521
629
  var MIGRATE_PATH = "/api/v1/db/migrate";
@@ -583,6 +691,40 @@ function createDb(transport) {
583
691
  });
584
692
  }
585
693
 
694
+ // src/realtime.ts
695
+ var REALTIME_PATH = "/api/v1/realtime";
696
+ var RealtimeApi = class {
697
+ constructor(transport) {
698
+ this.transport = transport;
699
+ }
700
+ /** Mint a short-lived, channel-scoped connection token for a browser. */
701
+ mintToken(input) {
702
+ return this.transport.json(`${REALTIME_PATH}/token`, {
703
+ channels: input.channels,
704
+ identity: input.identity,
705
+ ttl: input.ttl
706
+ });
707
+ }
708
+ /** Publish a message to a channel. Returns how many subscribers it reached. */
709
+ async publish(channel, payload) {
710
+ const r = await this.transport.json(`${REALTIME_PATH}/publish`, {
711
+ channel,
712
+ payload
713
+ });
714
+ return r.delivered;
715
+ }
716
+ /** Who is currently connected to a channel. */
717
+ async presence(channel) {
718
+ const r = await this.transport.get(
719
+ `${REALTIME_PATH}/channels/${encodeURIComponent(channel)}/presence`
720
+ );
721
+ return r.presence ?? [];
722
+ }
723
+ };
724
+ function createRealtime(transport) {
725
+ return new RealtimeApi(transport);
726
+ }
727
+
586
728
  // src/storage.ts
587
729
  var STORAGE_PATH = "/api/v1/storage";
588
730
  var DEFAULT_CONTENT_TYPE = "application/octet-stream";
@@ -676,7 +818,9 @@ function dontcode(options = {}) {
676
818
  return {
677
819
  auth: new AuthApi(transport, options.session),
678
820
  db: createDb(transport),
679
- storage: createStorage(transport)
821
+ storage: createStorage(transport),
822
+ cache: createCache(transport),
823
+ realtime: createRealtime(transport)
680
824
  };
681
825
  }
682
826