@dontcode2/backend 0.2.0 → 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 +99 -2
- package/dist/auth-device.d.ts +43 -0
- package/dist/auth.d.ts +102 -0
- package/dist/cache.d.ts +36 -0
- package/dist/chunk-6DFTM26Y.js +448 -0
- package/dist/chunk-6DFTM26Y.js.map +1 -0
- package/dist/chunk-LBN4R3GH.js +716 -0
- package/dist/chunk-LBN4R3GH.js.map +1 -0
- package/dist/cli.cjs +1206 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/{mock/cli.d.cts → cli.d.ts} +1 -0
- package/dist/cli.js +95 -0
- package/dist/cli.js.map +1 -0
- package/dist/client.d.ts +40 -0
- package/dist/cookies.d.ts +36 -0
- package/dist/credentials.d.ts +36 -0
- package/dist/db.d.ts +48 -0
- package/dist/errors.d.ts +38 -0
- package/dist/http.d.ts +52 -0
- package/dist/index.cjs +164 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +15 -588
- package/dist/index.js +26 -536
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.cjs +1116 -0
- package/dist/mcp/index.cjs.map +1 -0
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mock/cli.d.ts +1 -0
- package/dist/mock/db-query.d.ts +67 -0
- package/dist/mock/index.d.ts +17 -36
- package/dist/mock/{index.d.cts → server.d.ts} +3 -5
- package/dist/node.cjs +1160 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.ts +8 -0
- package/dist/node.js +28 -0
- package/dist/node.js.map +1 -0
- package/dist/realtime.d.ts +29 -0
- package/dist/session.d.ts +115 -0
- package/dist/storage.d.ts +46 -0
- package/dist/types.d.ts +184 -0
- package/package.json +19 -2
- package/dist/index.d.cts +0 -588
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
// src/cookies.ts
|
|
2
|
+
var DEFAULT_SESSION_COOKIE_NAME = "dc_access_token";
|
|
3
|
+
var DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
|
|
4
|
+
function serialize(name, value, options, maxAge) {
|
|
5
|
+
const sameSite = options.sameSite ?? "lax";
|
|
6
|
+
const secure = sameSite === "none" ? true : options.secure ?? true;
|
|
7
|
+
const httpOnly = options.httpOnly ?? true;
|
|
8
|
+
const path = options.path ?? "/";
|
|
9
|
+
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `Max-Age=${maxAge}`];
|
|
10
|
+
if (options.domain) parts.push(`Domain=${options.domain}`);
|
|
11
|
+
parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);
|
|
12
|
+
if (httpOnly) parts.push("HttpOnly");
|
|
13
|
+
if (secure) parts.push("Secure");
|
|
14
|
+
return parts.join("; ");
|
|
15
|
+
}
|
|
16
|
+
function serializeSessionCookie(token, options = {}) {
|
|
17
|
+
const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME;
|
|
18
|
+
const maxAge = options.maxAge ?? DEFAULT_MAX_AGE_SECONDS;
|
|
19
|
+
return serialize(name, token, options, maxAge);
|
|
20
|
+
}
|
|
21
|
+
function clearSessionCookie(options = {}) {
|
|
22
|
+
const name = options.name ?? DEFAULT_SESSION_COOKIE_NAME;
|
|
23
|
+
return serialize(name, "", options, 0);
|
|
24
|
+
}
|
|
25
|
+
function readSessionToken(cookieHeader, name = DEFAULT_SESSION_COOKIE_NAME) {
|
|
26
|
+
if (!cookieHeader) return null;
|
|
27
|
+
for (const pair of cookieHeader.split(";")) {
|
|
28
|
+
const eq = pair.indexOf("=");
|
|
29
|
+
if (eq === -1) continue;
|
|
30
|
+
if (pair.slice(0, eq).trim() !== name) continue;
|
|
31
|
+
const raw = pair.slice(eq + 1).trim();
|
|
32
|
+
if (!raw) return null;
|
|
33
|
+
try {
|
|
34
|
+
return decodeURIComponent(raw);
|
|
35
|
+
} catch {
|
|
36
|
+
return raw;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/errors.ts
|
|
43
|
+
var DontCodeError = class extends Error {
|
|
44
|
+
constructor(status, body) {
|
|
45
|
+
const message = typeof body?.error === "string" && body.error.length > 0 ? body.error : `DontCode request failed with status ${status}`;
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "DontCodeError";
|
|
48
|
+
this.status = status;
|
|
49
|
+
this.code = typeof body?.code === "string" ? body.code : void 0;
|
|
50
|
+
this.body = body ?? {};
|
|
51
|
+
}
|
|
52
|
+
/** True when the request was rejected by the per-key rate limiter. */
|
|
53
|
+
get rateLimited() {
|
|
54
|
+
return this.status === 429;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
function isDontCodeError(err) {
|
|
58
|
+
if (err instanceof DontCodeError) return true;
|
|
59
|
+
return typeof err === "object" && err !== null && err.name === "DontCodeError";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/session.ts
|
|
63
|
+
var DEFAULT_TTL_MS = 6e4;
|
|
64
|
+
var DEFAULT_VERIFY_TIMEOUT_MS = 5e3;
|
|
65
|
+
var InMemorySessionCache = class {
|
|
66
|
+
constructor() {
|
|
67
|
+
this.store = /* @__PURE__ */ new Map();
|
|
68
|
+
}
|
|
69
|
+
get(token) {
|
|
70
|
+
const hit = this.store.get(token);
|
|
71
|
+
if (!hit) return void 0;
|
|
72
|
+
if (Date.now() >= hit.expiresAtMs) {
|
|
73
|
+
this.store.delete(token);
|
|
74
|
+
return void 0;
|
|
75
|
+
}
|
|
76
|
+
return hit.value;
|
|
77
|
+
}
|
|
78
|
+
set(token, value, ttlMs) {
|
|
79
|
+
this.store.set(token, { value, expiresAtMs: Date.now() + ttlMs });
|
|
80
|
+
}
|
|
81
|
+
delete(token) {
|
|
82
|
+
this.store.delete(token);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
function base64UrlDecode(segment) {
|
|
86
|
+
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
87
|
+
const padded = base64.length % 4 === 0 ? base64 : base64 + "=".repeat(4 - base64.length % 4);
|
|
88
|
+
if (typeof atob === "function") {
|
|
89
|
+
const binary = atob(padded);
|
|
90
|
+
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
91
|
+
return new TextDecoder().decode(bytes);
|
|
92
|
+
}
|
|
93
|
+
return Buffer.from(padded, "base64").toString("utf8");
|
|
94
|
+
}
|
|
95
|
+
function decodeAccessToken(token) {
|
|
96
|
+
if (!token || typeof token !== "string") return null;
|
|
97
|
+
const parts = token.split(".");
|
|
98
|
+
if (parts.length < 2) return null;
|
|
99
|
+
try {
|
|
100
|
+
const payload = JSON.parse(base64UrlDecode(parts[1]));
|
|
101
|
+
if (!payload || typeof payload.sub !== "string") return null;
|
|
102
|
+
return payload;
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function isSessionExpired(input, opts = {}) {
|
|
108
|
+
const decoded = typeof input === "string" ? decodeAccessToken(input) : input;
|
|
109
|
+
if (!decoded || typeof decoded.exp !== "number") return false;
|
|
110
|
+
const nowSeconds = Date.now() / 1e3;
|
|
111
|
+
return nowSeconds >= decoded.exp - (opts.skewSeconds ?? 0);
|
|
112
|
+
}
|
|
113
|
+
function userFromClaims(decoded) {
|
|
114
|
+
return {
|
|
115
|
+
id: decoded.sub,
|
|
116
|
+
email: typeof decoded.email === "string" ? decoded.email : "",
|
|
117
|
+
role: decoded.role,
|
|
118
|
+
claims: decoded.claims
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
var SessionVerifier = class {
|
|
122
|
+
constructor(auth, options = {}) {
|
|
123
|
+
this.auth = auth;
|
|
124
|
+
this.cache = options.cache ?? new InMemorySessionCache();
|
|
125
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
126
|
+
this.verifyTimeoutMs = options.verifyTimeoutMs ?? DEFAULT_VERIFY_TIMEOUT_MS;
|
|
127
|
+
}
|
|
128
|
+
async getSession({ accessToken, mode = "optimistic" }) {
|
|
129
|
+
const decoded = decodeAccessToken(accessToken);
|
|
130
|
+
if (!decoded) return { status: "anonymous", user: null, verified: false };
|
|
131
|
+
if (isSessionExpired(decoded)) {
|
|
132
|
+
return { status: "expired", user: null, verified: false, expiresAt: decoded.exp };
|
|
133
|
+
}
|
|
134
|
+
const optimistic = {
|
|
135
|
+
status: "active",
|
|
136
|
+
user: userFromClaims(decoded),
|
|
137
|
+
verified: false,
|
|
138
|
+
expiresAt: decoded.exp
|
|
139
|
+
};
|
|
140
|
+
if (mode === "optimistic") return optimistic;
|
|
141
|
+
const cached = this.cache.get(accessToken);
|
|
142
|
+
if (cached) return cached;
|
|
143
|
+
try {
|
|
144
|
+
const { user } = await this.auth.me({
|
|
145
|
+
accessToken,
|
|
146
|
+
timeoutMs: this.verifyTimeoutMs
|
|
147
|
+
});
|
|
148
|
+
const result = user ? { status: "active", user, verified: true, expiresAt: decoded.exp } : { status: "anonymous", user: null, verified: true };
|
|
149
|
+
this.cache.set(accessToken, result, this.ttlMs);
|
|
150
|
+
return result;
|
|
151
|
+
} catch (err) {
|
|
152
|
+
if (isDontCodeError(err) && err.status === 401) {
|
|
153
|
+
return { status: "anonymous", user: null, verified: true };
|
|
154
|
+
}
|
|
155
|
+
return { ...optimistic, status: "unavailable" };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// src/auth.ts
|
|
161
|
+
var AUTH_BASE = "/api/v1/auth";
|
|
162
|
+
var MfaApi = class {
|
|
163
|
+
constructor(transport) {
|
|
164
|
+
this.transport = transport;
|
|
165
|
+
}
|
|
166
|
+
/** Complete an MFA login. Pass the `challenge_token` from `login`, plus
|
|
167
|
+
* either the authenticator `code` or a `recoveryCode`. */
|
|
168
|
+
challenge(input) {
|
|
169
|
+
return this.transport.json(`${AUTH_BASE}/mfa/challenge`, {
|
|
170
|
+
challenge_token: input.challengeToken,
|
|
171
|
+
code: input.code,
|
|
172
|
+
recovery_code: input.recoveryCode
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/** Begin enrollment. Render the returned `otpauth_url` as a QR code.
|
|
176
|
+
* Enrollment stays pending until `enrollConfirm`. */
|
|
177
|
+
enroll(input) {
|
|
178
|
+
return this.transport.json(
|
|
179
|
+
`${AUTH_BASE}/mfa/enroll`,
|
|
180
|
+
{},
|
|
181
|
+
{ accessToken: input.accessToken }
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
/** Confirm enrollment with the first authenticator code. The returned
|
|
185
|
+
* `recovery_codes` are shown once and never again. */
|
|
186
|
+
enrollConfirm(input) {
|
|
187
|
+
return this.transport.json(
|
|
188
|
+
`${AUTH_BASE}/mfa/enroll/confirm`,
|
|
189
|
+
{ code: input.code },
|
|
190
|
+
{ accessToken: input.accessToken }
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
/** Turn MFA off. Proves possession of the second factor via `code` or
|
|
194
|
+
* `recoveryCode`. */
|
|
195
|
+
disable(input) {
|
|
196
|
+
return this.transport.json(
|
|
197
|
+
`${AUTH_BASE}/mfa/disable`,
|
|
198
|
+
{ code: input.code, recovery_code: input.recoveryCode },
|
|
199
|
+
{ accessToken: input.accessToken }
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
var AuthApi = class {
|
|
204
|
+
constructor(transport, sessionOptions) {
|
|
205
|
+
this.transport = transport;
|
|
206
|
+
this.mfa = new MfaApi(transport);
|
|
207
|
+
this.sessions = new SessionVerifier(this, sessionOptions);
|
|
208
|
+
}
|
|
209
|
+
/** Create an account. If the project requires email verification the
|
|
210
|
+
* response has `verification_required: true` and NO tokens; collect a
|
|
211
|
+
* code and call `verifyEmail`, then `login`. */
|
|
212
|
+
signup(input) {
|
|
213
|
+
return this.transport.json(`${AUTH_BASE}/signup`, {
|
|
214
|
+
email: input.email,
|
|
215
|
+
password: input.password,
|
|
216
|
+
name: input.name,
|
|
217
|
+
role: input.role
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/** Authenticate. Branch on `mfa_required`: when true you hold only a
|
|
221
|
+
* challenge (finish via `mfa.challenge`); otherwise `tokens` is your
|
|
222
|
+
* session. A 403 `EmailNotVerified` means the email step isn't done. */
|
|
223
|
+
login(input) {
|
|
224
|
+
return this.transport.json(`${AUTH_BASE}/login`, {
|
|
225
|
+
email: input.email,
|
|
226
|
+
password: input.password
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Validate the current credential (API key or device token) and report the
|
|
230
|
+
* project, the caller's role, and which capabilities that role grants.
|
|
231
|
+
* Backs the MCP "is my session still good" check. */
|
|
232
|
+
info() {
|
|
233
|
+
return this.transport.get("/api/v1/info");
|
|
234
|
+
}
|
|
235
|
+
/** Resolve the signed-in user from their access token, or `{ user: null }`.
|
|
236
|
+
* This is a network round-trip; for a per-navigation guard prefer
|
|
237
|
+
* `getSession`, which can answer offline and caches verified results. */
|
|
238
|
+
me(input) {
|
|
239
|
+
return this.transport.json(
|
|
240
|
+
`${AUTH_BASE}/me`,
|
|
241
|
+
{},
|
|
242
|
+
{ accessToken: input.accessToken, timeoutMs: input.timeoutMs }
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Resolve an access token into a session for a route guard, the one call
|
|
247
|
+
* that replaces "hit `me` on every navigation". Two modes:
|
|
248
|
+
*
|
|
249
|
+
* - `'optimistic'` (default): decode the token locally and trust its
|
|
250
|
+
* claims. Zero network, zero stall. The right default for gating page
|
|
251
|
+
* loads. It does NOT verify the signature and will not notice a
|
|
252
|
+
* server-side revocation until the token's own `exp`.
|
|
253
|
+
* - `'verified'`: confirm against the gateway's `me`, cached for a short
|
|
254
|
+
* TTL with a hard timeout. Use it before sensitive actions. On a
|
|
255
|
+
* timeout/outage it returns `status: 'unavailable'` with the optimistic
|
|
256
|
+
* user, so you choose whether to fail open rather than the SDK guessing.
|
|
257
|
+
*
|
|
258
|
+
* See the BYOC docs ("Sessions") for the full reasoning and best practices.
|
|
259
|
+
*/
|
|
260
|
+
getSession(input) {
|
|
261
|
+
return this.sessions.getSession(input);
|
|
262
|
+
}
|
|
263
|
+
/** Read the access token from a `Cookie` request header and resolve it, in
|
|
264
|
+
* one call. `name` defaults to `dc_access_token`. Returns the anonymous
|
|
265
|
+
* session when no cookie is present. */
|
|
266
|
+
sessionFromCookies(cookieHeader, options = {}) {
|
|
267
|
+
const token = readSessionToken(cookieHeader, options.cookieName);
|
|
268
|
+
if (!token) return Promise.resolve({ status: "anonymous", user: null, verified: false });
|
|
269
|
+
return this.sessions.getSession({ accessToken: token, mode: options.mode });
|
|
270
|
+
}
|
|
271
|
+
/** Decode an access token's claims locally without a network call or any
|
|
272
|
+
* signature check. Convenience re-export of `decodeAccessToken`. */
|
|
273
|
+
decodeToken(token) {
|
|
274
|
+
return decodeAccessToken(token);
|
|
275
|
+
}
|
|
276
|
+
/** Confirm the 6-digit code emailed at signup. */
|
|
277
|
+
verifyEmail(input) {
|
|
278
|
+
return this.transport.json(`${AUTH_BASE}/verify-email`, {
|
|
279
|
+
code: input.code,
|
|
280
|
+
email: input.email
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
forgotPassword(input) {
|
|
284
|
+
return this.transport.json(`${AUTH_BASE}/forgot-password`, {
|
|
285
|
+
email: input.email
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
resetPassword(input) {
|
|
289
|
+
return this.transport.json(`${AUTH_BASE}/reset-password`, {
|
|
290
|
+
code: input.code,
|
|
291
|
+
password: input.password,
|
|
292
|
+
email: input.email
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
};
|
|
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
|
+
|
|
387
|
+
// src/db.ts
|
|
388
|
+
var DB_PATH = "/api/v1/db";
|
|
389
|
+
var MIGRATE_PATH = "/api/v1/db/migrate";
|
|
390
|
+
var TableQuery = class {
|
|
391
|
+
constructor(transport, tableName) {
|
|
392
|
+
this.transport = transport;
|
|
393
|
+
this.tableName = tableName;
|
|
394
|
+
}
|
|
395
|
+
async run(operation, options) {
|
|
396
|
+
const res = await this.transport.json(DB_PATH, {
|
|
397
|
+
operation,
|
|
398
|
+
tableName: this.tableName,
|
|
399
|
+
options
|
|
400
|
+
});
|
|
401
|
+
return res.data;
|
|
402
|
+
}
|
|
403
|
+
/** Rows matching the query (max 1000 per call). */
|
|
404
|
+
find(options = {}) {
|
|
405
|
+
return this.run("find", options);
|
|
406
|
+
}
|
|
407
|
+
/** Alias of `find`. */
|
|
408
|
+
findMany(options = {}) {
|
|
409
|
+
return this.run("findMany", options);
|
|
410
|
+
}
|
|
411
|
+
/** The first matching row, or `null`. */
|
|
412
|
+
findFirst(options = {}) {
|
|
413
|
+
return this.run("findFirst", options);
|
|
414
|
+
}
|
|
415
|
+
/** Alias of `findFirst`. */
|
|
416
|
+
findOne(options = {}) {
|
|
417
|
+
return this.run("findOne", options);
|
|
418
|
+
}
|
|
419
|
+
/** Insert one row. Returns `{ id }`. Unique/FK conflicts throw a 409
|
|
420
|
+
* DontCodeError, the supported idempotency signal. */
|
|
421
|
+
insert(data) {
|
|
422
|
+
return this.run("insert", { data });
|
|
423
|
+
}
|
|
424
|
+
/** Update rows matching `where`. Returns `{ count }`. */
|
|
425
|
+
update(input) {
|
|
426
|
+
return this.run("update", { where: input.where, data: input.data });
|
|
427
|
+
}
|
|
428
|
+
/** Delete rows matching `where`. Returns `{ count }`. */
|
|
429
|
+
delete(input) {
|
|
430
|
+
return this.run("delete", { where: input.where });
|
|
431
|
+
}
|
|
432
|
+
/** Count matching rows. */
|
|
433
|
+
count(options = {}) {
|
|
434
|
+
return this.run("count", options);
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
function createDb(transport) {
|
|
438
|
+
const table = (tableName) => new TableQuery(transport, tableName);
|
|
439
|
+
const migrate = (input) => transport.json(MIGRATE_PATH, { sql: input.sql });
|
|
440
|
+
return new Proxy(table, {
|
|
441
|
+
get(target, prop, receiver) {
|
|
442
|
+
if (prop === "migrate") return migrate;
|
|
443
|
+
if (typeof prop !== "string" || prop === "then" || prop in target) {
|
|
444
|
+
return Reflect.get(target, prop, receiver);
|
|
445
|
+
}
|
|
446
|
+
return new TableQuery(transport, prop);
|
|
447
|
+
},
|
|
448
|
+
apply(_target, _thisArg, args) {
|
|
449
|
+
return table(args[0]);
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|
|
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
|
+
|
|
488
|
+
// src/storage.ts
|
|
489
|
+
var STORAGE_PATH = "/api/v1/storage";
|
|
490
|
+
var DEFAULT_CONTENT_TYPE = "application/octet-stream";
|
|
491
|
+
function toBlob(body, contentType) {
|
|
492
|
+
if (body instanceof Blob) return body;
|
|
493
|
+
if (typeof body === "string") return new Blob([body], { type: contentType });
|
|
494
|
+
if (body instanceof ArrayBuffer) return new Blob([body], { type: contentType });
|
|
495
|
+
if (ArrayBuffer.isView(body)) {
|
|
496
|
+
return new Blob([body], { type: contentType });
|
|
497
|
+
}
|
|
498
|
+
throw new TypeError("upload expects a Blob, ArrayBuffer, typed array, or string");
|
|
499
|
+
}
|
|
500
|
+
function fileName(path) {
|
|
501
|
+
return path.split("/").filter(Boolean).pop() ?? path;
|
|
502
|
+
}
|
|
503
|
+
var BucketClient = class {
|
|
504
|
+
constructor(transport, bucket) {
|
|
505
|
+
this.transport = transport;
|
|
506
|
+
this.bucket = bucket;
|
|
507
|
+
}
|
|
508
|
+
op(operation, params = {}) {
|
|
509
|
+
return this.transport.json(STORAGE_PATH, { operation, bucket: this.bucket, ...params });
|
|
510
|
+
}
|
|
511
|
+
/** List objects under `prefix`. */
|
|
512
|
+
list(prefix) {
|
|
513
|
+
return this.op("list", { prefix });
|
|
514
|
+
}
|
|
515
|
+
/** Delete one or more objects. Returns `{ deleted }`. */
|
|
516
|
+
remove(paths) {
|
|
517
|
+
return this.op("remove", { paths });
|
|
518
|
+
}
|
|
519
|
+
/** Move/rename an object within the bucket. */
|
|
520
|
+
move(from, to) {
|
|
521
|
+
return this.op("move", { from, to });
|
|
522
|
+
}
|
|
523
|
+
createFolder(path) {
|
|
524
|
+
return this.op("createFolder", { path });
|
|
525
|
+
}
|
|
526
|
+
/** Download an object inline (≤ 8 MB). Use `getTemporaryUrl` for larger files. */
|
|
527
|
+
download(path) {
|
|
528
|
+
return this.op("download", { path });
|
|
529
|
+
}
|
|
530
|
+
/** A short-lived signed URL (default 300s, max 7 days). */
|
|
531
|
+
getTemporaryUrl(path, expiresIn) {
|
|
532
|
+
return this.op("getTemporaryUrl", { path, expiresIn });
|
|
533
|
+
}
|
|
534
|
+
/** A presigned PUT URL for direct, large uploads (≤ no inline limit). */
|
|
535
|
+
presignUpload(path, contentType) {
|
|
536
|
+
return this.op("presignUpload", { path, contentType });
|
|
537
|
+
}
|
|
538
|
+
/** Upload bytes directly (≤ 100 MB). For larger files, `presignUpload`
|
|
539
|
+
* then PUT to the returned URL yourself. */
|
|
540
|
+
upload(path, body, contentType = DEFAULT_CONTENT_TYPE) {
|
|
541
|
+
const form = new FormData();
|
|
542
|
+
form.append("file", toBlob(body, contentType), fileName(path));
|
|
543
|
+
form.append("bucket", this.bucket);
|
|
544
|
+
form.append("path", path);
|
|
545
|
+
form.append("contentType", contentType);
|
|
546
|
+
return this.transport.multipart(STORAGE_PATH, form);
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
var PublicBucketClient = class extends BucketClient {
|
|
550
|
+
constructor(transport) {
|
|
551
|
+
super(transport, "public");
|
|
552
|
+
}
|
|
553
|
+
/** The permanent public URL for an object. */
|
|
554
|
+
getUrl(path) {
|
|
555
|
+
return this.op("getUrl", { path });
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
function createStorage(transport) {
|
|
559
|
+
return {
|
|
560
|
+
public: new PublicBucketClient(transport),
|
|
561
|
+
private: new BucketClient(transport, "private")
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// src/http.ts
|
|
566
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
567
|
+
var Transport = class {
|
|
568
|
+
constructor(config) {
|
|
569
|
+
this.config = config;
|
|
570
|
+
}
|
|
571
|
+
headers(opts) {
|
|
572
|
+
const headers = {};
|
|
573
|
+
if (this.config.apiKey) headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
574
|
+
if (opts?.accessToken) headers["X-Access-Token"] = opts.accessToken;
|
|
575
|
+
return headers;
|
|
576
|
+
}
|
|
577
|
+
url(path) {
|
|
578
|
+
return `${this.config.baseUrl}${path}`;
|
|
579
|
+
}
|
|
580
|
+
timeout(opts) {
|
|
581
|
+
const value = opts?.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
582
|
+
return value > 0 ? value : 0;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* One fetch, with a timeout that turns "hung socket" into a fast, typed
|
|
586
|
+
* failure. A timeout surfaces as `DontCodeError` with status 408 / code
|
|
587
|
+
* `Timeout`; any other transport failure (DNS, refused, offline) as status
|
|
588
|
+
* 0 / code `NetworkError`. Both are distinct from a real `401`, so an auth
|
|
589
|
+
* guard can tell "backend is down" apart from "user is signed out".
|
|
590
|
+
*/
|
|
591
|
+
async send(path, init, opts) {
|
|
592
|
+
const timeoutMs = this.timeout(opts);
|
|
593
|
+
const controller = timeoutMs > 0 ? new AbortController() : void 0;
|
|
594
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
|
|
595
|
+
try {
|
|
596
|
+
return await fetch(this.url(path), { ...init, signal: controller?.signal });
|
|
597
|
+
} catch (err) {
|
|
598
|
+
if (controller?.signal.aborted) {
|
|
599
|
+
throw new DontCodeError(408, {
|
|
600
|
+
error: `Request to ${path} timed out after ${timeoutMs}ms`,
|
|
601
|
+
code: "Timeout"
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
throw new DontCodeError(0, {
|
|
605
|
+
error: err instanceof Error ? err.message : "Network request failed",
|
|
606
|
+
code: "NetworkError"
|
|
607
|
+
});
|
|
608
|
+
} finally {
|
|
609
|
+
if (timer) clearTimeout(timer);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
/** GET and parse the JSON response. */
|
|
613
|
+
async get(path, opts) {
|
|
614
|
+
const res = await this.send(path, { method: "GET", headers: this.headers(opts) }, opts);
|
|
615
|
+
return this.parse(res);
|
|
616
|
+
}
|
|
617
|
+
/** POST a JSON body and parse the JSON response. */
|
|
618
|
+
async json(path, body, opts) {
|
|
619
|
+
const res = await this.send(
|
|
620
|
+
path,
|
|
621
|
+
{
|
|
622
|
+
method: "POST",
|
|
623
|
+
headers: { ...this.headers(opts), "Content-Type": "application/json" },
|
|
624
|
+
body: JSON.stringify(body ?? {})
|
|
625
|
+
},
|
|
626
|
+
opts
|
|
627
|
+
);
|
|
628
|
+
return this.parse(res);
|
|
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
|
+
}
|
|
648
|
+
/** PUT a multipart form (file uploads). The runtime sets the boundary. */
|
|
649
|
+
async multipart(path, form, opts) {
|
|
650
|
+
const res = await this.send(path, { method: "PUT", headers: this.headers(opts), body: form }, opts);
|
|
651
|
+
return this.parse(res);
|
|
652
|
+
}
|
|
653
|
+
async parse(res) {
|
|
654
|
+
const raw = await res.text();
|
|
655
|
+
let data = null;
|
|
656
|
+
if (raw) {
|
|
657
|
+
try {
|
|
658
|
+
data = JSON.parse(raw);
|
|
659
|
+
} catch {
|
|
660
|
+
data = { error: raw };
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (!res.ok) {
|
|
664
|
+
const body = data && typeof data === "object" ? data : { error: res.statusText || "Request failed" };
|
|
665
|
+
throw new DontCodeError(res.status, body);
|
|
666
|
+
}
|
|
667
|
+
return data;
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
// src/client.ts
|
|
672
|
+
var DEFAULT_BASE_URL = "https://backend.dontcode.co";
|
|
673
|
+
function fromEnv(name) {
|
|
674
|
+
if (typeof process === "undefined" || !process.env) return void 0;
|
|
675
|
+
return process.env[name];
|
|
676
|
+
}
|
|
677
|
+
function dontcode(options = {}) {
|
|
678
|
+
const apiKey = options.apiKey ?? fromEnv("DONTCODE_API_KEY");
|
|
679
|
+
const baseUrl = (options.baseUrl ?? fromEnv("DONTCODE_API_URL") ?? DEFAULT_BASE_URL).replace(
|
|
680
|
+
/\/+$/,
|
|
681
|
+
""
|
|
682
|
+
);
|
|
683
|
+
const transport = new Transport({ apiKey, baseUrl, timeoutMs: options.timeoutMs });
|
|
684
|
+
return {
|
|
685
|
+
auth: new AuthApi(transport, options.session),
|
|
686
|
+
db: createDb(transport),
|
|
687
|
+
storage: createStorage(transport),
|
|
688
|
+
cache: createCache(transport),
|
|
689
|
+
realtime: createRealtime(transport)
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
export {
|
|
694
|
+
DEFAULT_SESSION_COOKIE_NAME,
|
|
695
|
+
serializeSessionCookie,
|
|
696
|
+
clearSessionCookie,
|
|
697
|
+
readSessionToken,
|
|
698
|
+
DontCodeError,
|
|
699
|
+
isDontCodeError,
|
|
700
|
+
InMemorySessionCache,
|
|
701
|
+
decodeAccessToken,
|
|
702
|
+
isSessionExpired,
|
|
703
|
+
MfaApi,
|
|
704
|
+
AuthApi,
|
|
705
|
+
CacheClient,
|
|
706
|
+
createCache,
|
|
707
|
+
TableQuery,
|
|
708
|
+
Transport,
|
|
709
|
+
RealtimeApi,
|
|
710
|
+
createRealtime,
|
|
711
|
+
BucketClient,
|
|
712
|
+
PublicBucketClient,
|
|
713
|
+
createStorage,
|
|
714
|
+
dontcode
|
|
715
|
+
};
|
|
716
|
+
//# sourceMappingURL=chunk-LBN4R3GH.js.map
|