@edge-base/server 0.2.9 → 0.3.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/admin-build/_app/immutable/chunks/BENT96gS.js +1 -0
- package/admin-build/_app/immutable/chunks/{BfhqI0W8.js → BR-X1vqg.js} +1 -1
- package/admin-build/_app/immutable/chunks/{DncT8xH5.js → BYTXdmFz.js} +1 -1
- package/admin-build/_app/immutable/chunks/{YGUb3X-Q.js → C-_7bS5w.js} +1 -1
- package/admin-build/_app/immutable/chunks/{DUhE3Ynq.js → CCB6XzFZ.js} +1 -1
- package/admin-build/_app/immutable/chunks/{39YMyjjq.js → CWTeyOdB.js} +1 -1
- package/admin-build/_app/immutable/chunks/{DllVADtt.js → CX5CmbTG.js} +1 -1
- package/admin-build/_app/immutable/chunks/{0M5txo3l.js → CdgSuiqt.js} +3 -3
- package/admin-build/_app/immutable/chunks/{BN-pHKcH.js → Cuny2nPU.js} +1 -1
- package/admin-build/_app/immutable/chunks/{CPLcjNR9.js → D15DP4DQ.js} +1 -1
- package/admin-build/_app/immutable/chunks/{DBkor_jM.js → DAzRCtch.js} +1 -1
- package/admin-build/_app/immutable/chunks/DYF4byEY.js +1 -0
- package/admin-build/_app/immutable/chunks/{DBniE7GN.js → Dcey5WNo.js} +1 -1
- package/admin-build/_app/immutable/chunks/{C5nMidnK.js → HK54RDdv.js} +1 -1
- package/admin-build/_app/immutable/chunks/{CI1lKBjB.js → gUtOgqgM.js} +1 -1
- package/admin-build/_app/immutable/chunks/{_xa30BOD.js → pnqPwnFK.js} +1 -1
- package/admin-build/_app/immutable/entry/{app.BW-Ac3jY.js → app.DwslmBQo.js} +2 -2
- package/admin-build/_app/immutable/entry/start.Bi51W3Uj.js +1 -0
- package/admin-build/_app/immutable/nodes/{0.CRSQPtos.js → 0.SSaZIC3t.js} +1 -1
- package/admin-build/_app/immutable/nodes/{1.HmStNbZP.js → 1.CqSv9lq5.js} +1 -1
- package/admin-build/_app/immutable/nodes/{10.BVlz13nr.js → 10.BoQz_717.js} +1 -1
- package/admin-build/_app/immutable/nodes/{11.VwQdbWwH.js → 11.B-yS_gft.js} +1 -1
- package/admin-build/_app/immutable/nodes/{12.BFAAgi1f.js → 12.WsVtLoVx.js} +1 -1
- package/admin-build/_app/immutable/nodes/{13.DDdauC84.js → 13.TbqRQJKh.js} +1 -1
- package/admin-build/_app/immutable/nodes/{14.D_rXaafJ.js → 14.cldePwj3.js} +1 -1
- package/admin-build/_app/immutable/nodes/{15.rfFjjiZc.js → 15.Bec037-f.js} +1 -1
- package/admin-build/_app/immutable/nodes/{16.DDEpGJ4Z.js → 16.Dd0yTYhN.js} +1 -1
- package/admin-build/_app/immutable/nodes/{17.ChQWNtRN.js → 17.CoiqH0lF.js} +1 -1
- package/admin-build/_app/immutable/nodes/{18.Rir_JwlF.js → 18.BDXxM1Qi.js} +1 -1
- package/admin-build/_app/immutable/nodes/{19.CF76nxk1.js → 19.lo9mTPiR.js} +1 -1
- package/admin-build/_app/immutable/nodes/{20.JQer3KPM.js → 20.B7kbGqh_.js} +1 -1
- package/admin-build/_app/immutable/nodes/21.BGm1TcfO.js +1 -0
- package/admin-build/_app/immutable/nodes/{22.DUw7X6z_.js → 22.VOtCuTkf.js} +1 -1
- package/admin-build/_app/immutable/nodes/{23.DS3svA-a.js → 23.C2Uxx-kO.js} +1 -1
- package/admin-build/_app/immutable/nodes/{24.BYOsQM6B.js → 24.BxdEwsS3.js} +1 -1
- package/admin-build/_app/immutable/nodes/{25.n0pyDBRv.js → 25.CVu2qoCv.js} +1 -1
- package/admin-build/_app/immutable/nodes/{26.C-Oo8sYK.js → 26.DqYlpX7Z.js} +1 -1
- package/admin-build/_app/immutable/nodes/{27.BfxbFNkk.js → 27.emgbpP8y.js} +1 -1
- package/admin-build/_app/immutable/nodes/{28.DyHSN1q7.js → 28.BVPSPK68.js} +1 -1
- package/admin-build/_app/immutable/nodes/{29.CUAmZbCc.js → 29.BsDQQ16z.js} +1 -1
- package/admin-build/_app/immutable/nodes/{3.KQm4VJJg.js → 3.uc8joqGb.js} +1 -1
- package/admin-build/_app/immutable/nodes/{30.CQdPre5F.js → 30.D4CYqQrE.js} +1 -1
- package/admin-build/_app/immutable/nodes/{31.BP6raetq.js → 31.DvUuXrVU.js} +1 -1
- package/admin-build/_app/immutable/nodes/{4.Glf2jJHB.js → 4.BqTZ0Uoq.js} +1 -1
- package/admin-build/_app/immutable/nodes/{5.BdFtj_-X.js → 5.DAO3--6W.js} +1 -1
- package/admin-build/_app/immutable/nodes/{6.JfnwWq8s.js → 6.CBbGl_Wo.js} +1 -1
- package/admin-build/_app/immutable/nodes/{7.C-rw9qDh.js → 7.s-I8cKAh.js} +1 -1
- package/admin-build/_app/immutable/nodes/{8.CA7r1Sjs.js → 8.Ct6B-y3f.js} +1 -1
- package/admin-build/_app/immutable/nodes/{9.B2jgJDkH.js → 9.Dok_ZoeZ.js} +1 -1
- package/admin-build/_app/version.json +1 -1
- package/admin-build/index.html +7 -7
- package/openapi.json +498 -3
- package/package.json +3 -3
- package/src/__tests__/auth-token.test.ts +142 -0
- package/src/__tests__/email-provider.test.ts +82 -0
- package/src/__tests__/error-format.test.ts +21 -0
- package/src/__tests__/functions-context.test.ts +87 -0
- package/src/__tests__/functions-d1-proxy.test.ts +70 -0
- package/src/__tests__/functions-route.test.ts +15 -0
- package/src/__tests__/postgres-api-consistency.test.ts +240 -0
- package/src/__tests__/postgres-batch-compat.test.ts +33 -27
- package/src/__tests__/postgres-batch.test.ts +394 -0
- package/src/__tests__/postgres-field-ops-compat.test.ts +2 -1
- package/src/__tests__/postgres-transact.test.ts +148 -0
- package/src/__tests__/room-access-policy.test.ts +26 -0
- package/src/__tests__/room-handler-context.test.ts +2 -0
- package/src/__tests__/smoke-skip-report.test.ts +1 -1
- package/src/durable-objects/database-do.ts +455 -15
- package/src/durable-objects/room-runtime-base.ts +16 -5
- package/src/durable-objects/rooms-do.ts +4 -1
- package/src/lib/auth-d1-service.ts +37 -7
- package/src/lib/auth-token.ts +66 -0
- package/src/lib/d1-handler.ts +416 -50
- package/src/lib/email-provider.ts +115 -5
- package/src/lib/errors.ts +8 -4
- package/src/lib/functions.ts +91 -1
- package/src/lib/internal-transport.ts +25 -1
- package/src/lib/jwt.ts +2 -0
- package/src/lib/postgres-handler.ts +562 -84
- package/src/routes/admin.ts +8 -1
- package/src/routes/auth.ts +169 -65
- package/src/routes/room.ts +36 -2
- package/src/routes/storage.ts +446 -62
- package/src/routes/tables.ts +140 -0
- package/src/types.ts +10 -0
- package/admin-build/_app/immutable/chunks/B0zJ5_Wk.js +0 -1
- package/admin-build/_app/immutable/chunks/DZo4s3wn.js +0 -1
- package/admin-build/_app/immutable/entry/start.Bcf0SjPV.js +0 -1
- package/admin-build/_app/immutable/nodes/21.CzGYxjpu.js +0 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Workers cannot use SMTP directly. Instead, we use HTTP REST API-based
|
|
5
5
|
* external email services via a common interface.
|
|
6
6
|
*
|
|
7
|
-
* Supported: Resend (default), SendGrid, Mailgun, AWS SES
|
|
7
|
+
* Supported: Resend (default), SendGrid, Mailgun, AWS SES, Cloudflare Email Service
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
// ─── Interface ───
|
|
@@ -26,6 +26,24 @@ export interface EmailProvider {
|
|
|
26
26
|
|
|
27
27
|
interface EmailProviderEnv {
|
|
28
28
|
EDGEBASE_EMAIL_API_URL?: string;
|
|
29
|
+
EDGEBASE_EMAIL_CLOUDFLARE_API_TOKEN?: string;
|
|
30
|
+
EDGEBASE_EMAIL_CLOUDFLARE_ACCOUNT_ID?: string;
|
|
31
|
+
EDGEBASE_EMAIL_CLOUDFLARE_BINDING?: string;
|
|
32
|
+
EMAIL?: CloudflareSendEmailBinding;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface CloudflareSendEmailBinding {
|
|
36
|
+
send(message: {
|
|
37
|
+
to: string;
|
|
38
|
+
from: string;
|
|
39
|
+
subject: string;
|
|
40
|
+
html?: string;
|
|
41
|
+
text?: string;
|
|
42
|
+
}): Promise<{ messageId?: string }>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isCloudflareSendEmailBinding(value: unknown): value is CloudflareSendEmailBinding {
|
|
46
|
+
return !!value && typeof value === 'object' && typeof (value as { send?: unknown }).send === 'function';
|
|
29
47
|
}
|
|
30
48
|
|
|
31
49
|
const encoder = new TextEncoder();
|
|
@@ -331,14 +349,83 @@ export class SESProvider implements EmailProvider {
|
|
|
331
349
|
}
|
|
332
350
|
}
|
|
333
351
|
|
|
352
|
+
// ─── Cloudflare Email Service Provider ───
|
|
353
|
+
|
|
354
|
+
export class CloudflareEmailProvider implements EmailProvider {
|
|
355
|
+
private apiBaseUrl: string;
|
|
356
|
+
|
|
357
|
+
constructor(
|
|
358
|
+
private options: {
|
|
359
|
+
from: string;
|
|
360
|
+
apiKey?: string;
|
|
361
|
+
accountId?: string;
|
|
362
|
+
binding?: CloudflareSendEmailBinding;
|
|
363
|
+
apiBaseUrl?: string;
|
|
364
|
+
},
|
|
365
|
+
) {
|
|
366
|
+
this.apiBaseUrl = options.apiBaseUrl?.replace(/\/$/, '') ?? 'https://api.cloudflare.com/client/v4';
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async send(options: EmailSendOptions): Promise<EmailSendResult> {
|
|
370
|
+
if (this.options.binding) {
|
|
371
|
+
try {
|
|
372
|
+
const result = await this.options.binding.send({
|
|
373
|
+
to: options.to,
|
|
374
|
+
from: this.options.from,
|
|
375
|
+
subject: options.subject,
|
|
376
|
+
html: options.html,
|
|
377
|
+
});
|
|
378
|
+
return { success: true, messageId: result.messageId };
|
|
379
|
+
} catch (err) {
|
|
380
|
+
console.error('[EmailProvider:Cloudflare] Workers binding failed:', err);
|
|
381
|
+
return { success: false };
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (!this.options.apiKey || !this.options.accountId) {
|
|
386
|
+
console.error(
|
|
387
|
+
'[EmailProvider:Cloudflare] accountId and apiKey are required when a Workers send_email binding is not available.',
|
|
388
|
+
);
|
|
389
|
+
return { success: false };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const resp = await fetch(
|
|
393
|
+
`${this.apiBaseUrl}/accounts/${encodeURIComponent(this.options.accountId)}/email/sending/send`,
|
|
394
|
+
{
|
|
395
|
+
method: 'POST',
|
|
396
|
+
headers: {
|
|
397
|
+
Authorization: `Bearer ${this.options.apiKey}`,
|
|
398
|
+
'Content-Type': 'application/json',
|
|
399
|
+
},
|
|
400
|
+
body: JSON.stringify({
|
|
401
|
+
to: options.to,
|
|
402
|
+
from: this.options.from,
|
|
403
|
+
subject: options.subject,
|
|
404
|
+
html: options.html,
|
|
405
|
+
}),
|
|
406
|
+
},
|
|
407
|
+
);
|
|
408
|
+
|
|
409
|
+
if (!resp.ok) {
|
|
410
|
+
const text = await resp.text();
|
|
411
|
+
console.error('[EmailProvider:Cloudflare] Failed:', resp.status, text);
|
|
412
|
+
return { success: false };
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return { success: true };
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
334
419
|
// ─── Factory ───
|
|
335
420
|
|
|
336
421
|
export interface EmailConfig {
|
|
337
|
-
provider: 'resend' | 'sendgrid' | 'mailgun' | 'ses';
|
|
338
|
-
apiKey
|
|
422
|
+
provider: 'resend' | 'sendgrid' | 'mailgun' | 'ses' | 'cloudflare';
|
|
423
|
+
apiKey?: string; // SES uses accessKeyId:secretAccessKey[:sessionToken]
|
|
339
424
|
from: string;
|
|
340
425
|
domain?: string; // Mailgun domain
|
|
341
426
|
region?: string; // SES region
|
|
427
|
+
accountId?: string; // Cloudflare REST API account ID
|
|
428
|
+
binding?: string; // Cloudflare Workers send_email binding name
|
|
342
429
|
}
|
|
343
430
|
|
|
344
431
|
/**
|
|
@@ -358,22 +445,45 @@ export function createEmailProvider(
|
|
|
358
445
|
return null;
|
|
359
446
|
}
|
|
360
447
|
|
|
361
|
-
if (!config.
|
|
362
|
-
console.warn('[EmailProvider]
|
|
448
|
+
if (!config.from) {
|
|
449
|
+
console.warn('[EmailProvider] from is required. Email features disabled.');
|
|
363
450
|
return null;
|
|
364
451
|
}
|
|
365
452
|
|
|
366
453
|
switch (config.provider) {
|
|
454
|
+
case 'cloudflare': {
|
|
455
|
+
const bindingName = config.binding
|
|
456
|
+
?? env?.EDGEBASE_EMAIL_CLOUDFLARE_BINDING?.trim()
|
|
457
|
+
?? 'EMAIL';
|
|
458
|
+
const envRecord = env as Record<string, unknown> | undefined;
|
|
459
|
+
const bindingCandidate = envRecord?.[bindingName];
|
|
460
|
+
const binding = isCloudflareSendEmailBinding(bindingCandidate)
|
|
461
|
+
? bindingCandidate
|
|
462
|
+
: undefined;
|
|
463
|
+
return new CloudflareEmailProvider({
|
|
464
|
+
from: config.from,
|
|
465
|
+
apiKey: config.apiKey ?? env?.EDGEBASE_EMAIL_CLOUDFLARE_API_TOKEN,
|
|
466
|
+
accountId: config.accountId ?? env?.EDGEBASE_EMAIL_CLOUDFLARE_ACCOUNT_ID,
|
|
467
|
+
binding,
|
|
468
|
+
});
|
|
469
|
+
}
|
|
367
470
|
case 'resend':
|
|
471
|
+
if (!config.apiKey) break;
|
|
368
472
|
return new ResendProvider(config.apiKey, config.from);
|
|
369
473
|
case 'sendgrid':
|
|
474
|
+
if (!config.apiKey) break;
|
|
370
475
|
return new SendGridProvider(config.apiKey, config.from);
|
|
371
476
|
case 'mailgun':
|
|
477
|
+
if (!config.apiKey) break;
|
|
372
478
|
return new MailgunProvider(config.apiKey, config.from, config.domain);
|
|
373
479
|
case 'ses':
|
|
480
|
+
if (!config.apiKey) break;
|
|
374
481
|
return new SESProvider(config.apiKey, config.from, config.region);
|
|
375
482
|
default:
|
|
376
483
|
console.warn(`[EmailProvider] Unknown provider: ${config.provider}. Email features disabled.`);
|
|
377
484
|
return null;
|
|
378
485
|
}
|
|
486
|
+
|
|
487
|
+
console.warn('[EmailProvider] apiKey and from are required. Email features disabled.');
|
|
488
|
+
return null;
|
|
379
489
|
}
|
package/src/lib/errors.ts
CHANGED
|
@@ -119,8 +119,9 @@ export function normalizeDatabaseError(error: unknown): EdgeBaseError | null {
|
|
|
119
119
|
|
|
120
120
|
const haystack = `${message}\n${causeMessage}`.trim();
|
|
121
121
|
|
|
122
|
-
|
|
123
|
-
|
|
122
|
+
// Matches both SQLite/D1 ("FOREIGN KEY constraint failed: table.column") and
|
|
123
|
+
// PostgreSQL ('... violates foreign key constraint "table_col_fkey"') phrasings.
|
|
124
|
+
if (/foreign key constraint failed|violates foreign key constraint/i.test(haystack)) {
|
|
124
125
|
const colMatch = haystack.match(/foreign key constraint failed[:\s]*(?:\w+\.)?(\w+)/i);
|
|
125
126
|
const detail = colMatch?.[1]
|
|
126
127
|
? `Referenced record does not exist (column: '${colMatch[1]}').`
|
|
@@ -137,8 +138,11 @@ export function normalizeDatabaseError(error: unknown): EdgeBaseError | null {
|
|
|
137
138
|
return new EdgeBaseError(409, detail, undefined, 'record-already-exists');
|
|
138
139
|
}
|
|
139
140
|
|
|
140
|
-
|
|
141
|
-
|
|
141
|
+
// Matches SQLite/D1 ("NOT NULL constraint failed: table.column") and
|
|
142
|
+
// PostgreSQL ('null value in column "col" ... violates not-null constraint').
|
|
143
|
+
if (/not null constraint failed|check constraint failed|null value in column .* violates not-null constraint/i.test(haystack)) {
|
|
144
|
+
const colMatch = haystack.match(/(?:not null|check) constraint failed[:\s]*(?:\w+\.)?(\w+)/i)
|
|
145
|
+
?? haystack.match(/null value in column "?(\w+)"?/i);
|
|
142
146
|
const detail = colMatch?.[1]
|
|
143
147
|
? `Database constraint violated (column: '${colMatch[1]}'). Ensure all required fields are provided.`
|
|
144
148
|
: 'Request violates a database constraint. Ensure all required fields are provided.';
|
package/src/lib/functions.ts
CHANGED
|
@@ -41,6 +41,7 @@ import { generateId } from './uuid.js';
|
|
|
41
41
|
import { DbRef, TableRef, DefaultDbApi, HttpClient, ContextManager } from '@edge-base/core';
|
|
42
42
|
import { InternalHttpTransport } from './internal-transport.js';
|
|
43
43
|
import { executeProviderAwareSql } from './provider-aware-sql.js';
|
|
44
|
+
import { createEmailProvider } from './email-provider.js';
|
|
44
45
|
|
|
45
46
|
// ─── Function Context Types ───
|
|
46
47
|
|
|
@@ -69,6 +70,15 @@ export interface AdminAuthContext {
|
|
|
69
70
|
revokeAllSessions(userId: string): Promise<void>;
|
|
70
71
|
}
|
|
71
72
|
|
|
73
|
+
export interface FunctionEmailProxy {
|
|
74
|
+
send(options: {
|
|
75
|
+
to: string;
|
|
76
|
+
subject: string;
|
|
77
|
+
html?: string;
|
|
78
|
+
text?: string;
|
|
79
|
+
}): Promise<{ success: boolean; messageId?: string }>;
|
|
80
|
+
}
|
|
81
|
+
|
|
72
82
|
/**
|
|
73
83
|
* AdminEdgeBase-shaped context object injected as context.admin.
|
|
74
84
|
*
|
|
@@ -186,6 +196,8 @@ export interface FunctionPushProxy {
|
|
|
186
196
|
|
|
187
197
|
/** Storage proxy for App Functions — wraps R2Bucket with convenience methods. */
|
|
188
198
|
export interface FunctionStorageProxy {
|
|
199
|
+
/** Return a proxy scoped to a named storage bucket. */
|
|
200
|
+
bucket(bucket: string): FunctionStorageProxy;
|
|
189
201
|
put(
|
|
190
202
|
key: string,
|
|
191
203
|
value: ReadableStream | ArrayBuffer | string,
|
|
@@ -199,6 +211,10 @@ export interface FunctionStorageProxy {
|
|
|
199
211
|
} | null>;
|
|
200
212
|
delete(key: string): Promise<void>;
|
|
201
213
|
getSignedUrl(key: string, options?: { expiresIn?: number }): Promise<string>;
|
|
214
|
+
getSignedUploadUrl(
|
|
215
|
+
key: string,
|
|
216
|
+
options?: { expiresIn?: number; maxBytes?: number | null },
|
|
217
|
+
): Promise<{ url: string; expiresAt: string; maxBytes: number | null }>;
|
|
202
218
|
list(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<{
|
|
203
219
|
keys: Array<{ key: string; size: number; contentType: string }>;
|
|
204
220
|
cursor?: string;
|
|
@@ -357,12 +373,29 @@ export interface FunctionContext {
|
|
|
357
373
|
data?: { before?: Record<string, unknown>; after?: Record<string, unknown> };
|
|
358
374
|
before?: Record<string, unknown>;
|
|
359
375
|
after?: Record<string, unknown>;
|
|
376
|
+
/** Configured server-side email sender, when an EdgeBase email provider is available. */
|
|
377
|
+
email?: FunctionEmailProxy;
|
|
378
|
+
/** Environment variables, secrets, and bindings available to the Worker. */
|
|
379
|
+
env?: Record<string, unknown>;
|
|
360
380
|
storage?: FunctionStorageProxy; // Available when R2 binding present
|
|
361
381
|
analytics?: unknown; // AnalyticsAdapter when ANALYTICS_APP binding present
|
|
362
382
|
/** Plugin-specific config from edgebase.config.ts plugins section. */
|
|
363
383
|
pluginConfig?: Record<string, unknown>;
|
|
364
384
|
}
|
|
365
385
|
|
|
386
|
+
function escapeEmailHtml(value: string): string {
|
|
387
|
+
return value
|
|
388
|
+
.replace(/&/g, '&')
|
|
389
|
+
.replace(/</g, '<')
|
|
390
|
+
.replace(/>/g, '>')
|
|
391
|
+
.replace(/"/g, '"')
|
|
392
|
+
.replace(/'/g, ''');
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function textEmailToHtml(text: string): string {
|
|
396
|
+
return `<pre style="font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; white-space: pre-wrap;">${escapeEmailHtml(text)}</pre>`;
|
|
397
|
+
}
|
|
398
|
+
|
|
366
399
|
// ─── Function Registry ───
|
|
367
400
|
|
|
368
401
|
/**
|
|
@@ -693,6 +726,19 @@ export function wrapMethodExport(
|
|
|
693
726
|
method: string,
|
|
694
727
|
runtimeTrigger?: { path?: string },
|
|
695
728
|
): FunctionDefinition {
|
|
729
|
+
if (
|
|
730
|
+
method === '*' &&
|
|
731
|
+
handler &&
|
|
732
|
+
typeof handler === 'object' &&
|
|
733
|
+
'handler' in handler &&
|
|
734
|
+
'trigger' in handler &&
|
|
735
|
+
handler.trigger &&
|
|
736
|
+
typeof handler.trigger === 'object' &&
|
|
737
|
+
'type' in handler.trigger
|
|
738
|
+
) {
|
|
739
|
+
return handler as FunctionDefinition;
|
|
740
|
+
}
|
|
741
|
+
|
|
696
742
|
// handler can be: raw function, or { handler, captcha? } from defineFunction()
|
|
697
743
|
let fn: (ctx: unknown) => Promise<unknown>;
|
|
698
744
|
let captcha: boolean | undefined;
|
|
@@ -1096,6 +1142,19 @@ export function buildFunctionContext(options: BuildFunctionContextOptions): Func
|
|
|
1096
1142
|
executionCtx: options.executionCtx,
|
|
1097
1143
|
preferDirectDo: options.preferDirectDoDb,
|
|
1098
1144
|
});
|
|
1145
|
+
const emailProvider = createEmailProvider(options.config.email, options.env);
|
|
1146
|
+
const email: FunctionEmailProxy | undefined = emailProvider
|
|
1147
|
+
? {
|
|
1148
|
+
async send(message) {
|
|
1149
|
+
const to = message.to.trim();
|
|
1150
|
+
const subject = message.subject.trim();
|
|
1151
|
+
if (!to) throw new Error('email.send() requires a recipient.');
|
|
1152
|
+
if (!subject) throw new Error('email.send() requires a subject.');
|
|
1153
|
+
const html = message.html ?? textEmailToHtml(message.text ?? '');
|
|
1154
|
+
return emailProvider.send({ to, subject, html });
|
|
1155
|
+
},
|
|
1156
|
+
}
|
|
1157
|
+
: undefined;
|
|
1099
1158
|
const sqlProviderAware = (
|
|
1100
1159
|
namespace: string,
|
|
1101
1160
|
id: string | undefined,
|
|
@@ -1282,6 +1341,8 @@ export function buildFunctionContext(options: BuildFunctionContextOptions): Func
|
|
|
1282
1341
|
auth: options.auth,
|
|
1283
1342
|
db: admin.db,
|
|
1284
1343
|
admin,
|
|
1344
|
+
...(options.env ? { env: options.env as unknown as Record<string, unknown> } : {}),
|
|
1345
|
+
...(email ? { email } : {}),
|
|
1285
1346
|
params: options.params ?? {},
|
|
1286
1347
|
};
|
|
1287
1348
|
|
|
@@ -1826,6 +1887,10 @@ export function buildFunctionStorageProxy(
|
|
|
1826
1887
|
const prefix = (key: string) => `${bucket}/${key}`;
|
|
1827
1888
|
|
|
1828
1889
|
return {
|
|
1890
|
+
bucket(name) {
|
|
1891
|
+
return buildFunctionStorageProxy(r2, name, env, workerUrl);
|
|
1892
|
+
},
|
|
1893
|
+
|
|
1829
1894
|
async put(key, value, options) {
|
|
1830
1895
|
const httpMeta: R2PutOptions = {};
|
|
1831
1896
|
if (options?.contentType) httpMeta.httpMetadata = { contentType: options.contentType };
|
|
@@ -1853,11 +1918,36 @@ export function buildFunctionStorageProxy(
|
|
|
1853
1918
|
if (!secret) throw new Error('Signed URLs require JWT_USER_SECRET to be configured.');
|
|
1854
1919
|
const expiresIn = options?.expiresIn ?? 3600;
|
|
1855
1920
|
const expiresAt = Date.now() + expiresIn * 1000;
|
|
1856
|
-
const
|
|
1921
|
+
const obj = await r2.head(prefix(key));
|
|
1922
|
+
const token = await createSignedToken(key, bucket, expiresAt, secret, obj ? {
|
|
1923
|
+
file: {
|
|
1924
|
+
size: obj.size,
|
|
1925
|
+
contentType: obj.httpMetadata?.contentType || 'application/octet-stream',
|
|
1926
|
+
etag: obj.etag,
|
|
1927
|
+
uploadedAt: obj.uploaded?.toISOString(),
|
|
1928
|
+
},
|
|
1929
|
+
} : undefined);
|
|
1857
1930
|
const base = workerUrl ?? 'http://localhost:8787';
|
|
1858
1931
|
return `${base}/api/storage/${encodeURIComponent(bucket)}/${key}?token=${token}`;
|
|
1859
1932
|
},
|
|
1860
1933
|
|
|
1934
|
+
async getSignedUploadUrl(key, options) {
|
|
1935
|
+
const secret = (env as unknown as Record<string, string>).JWT_USER_SECRET;
|
|
1936
|
+
if (!secret) throw new Error('Signed upload URLs require JWT_USER_SECRET to be configured.');
|
|
1937
|
+
const expiresIn = options?.expiresIn ?? 1800;
|
|
1938
|
+
const expiresAt = Date.now() + expiresIn * 1000;
|
|
1939
|
+
const maxBytes = typeof options?.maxBytes === 'number' && Number.isFinite(options.maxBytes)
|
|
1940
|
+
? Math.max(0, Math.trunc(options.maxBytes))
|
|
1941
|
+
: null;
|
|
1942
|
+
const token = await createSignedToken(key, bucket, expiresAt, secret, maxBytes);
|
|
1943
|
+
const base = workerUrl ?? 'http://localhost:8787';
|
|
1944
|
+
return {
|
|
1945
|
+
url: `${base}/api/storage/${encodeURIComponent(bucket)}/upload?token=${token}&key=${encodeURIComponent(key)}`,
|
|
1946
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
1947
|
+
maxBytes,
|
|
1948
|
+
};
|
|
1949
|
+
},
|
|
1950
|
+
|
|
1861
1951
|
async list(options) {
|
|
1862
1952
|
const r2Options: R2ListOptions = {};
|
|
1863
1953
|
if (options?.prefix) r2Options.prefix = prefix(options.prefix);
|
|
@@ -11,6 +11,7 @@ import type { EdgeBaseConfig } from '@edge-base/shared';
|
|
|
11
11
|
import {
|
|
12
12
|
callDO,
|
|
13
13
|
formatDbTargetValidationIssue,
|
|
14
|
+
getD1BindingName,
|
|
14
15
|
getDbDoName,
|
|
15
16
|
resolveDbTarget,
|
|
16
17
|
shouldRouteToD1,
|
|
@@ -76,6 +77,16 @@ function parsePath(
|
|
|
76
77
|
} else {
|
|
77
78
|
// Heuristic fallback: find first 'tables' keyword
|
|
78
79
|
tablesIdx = segments.indexOf('tables', 1);
|
|
80
|
+
if (tablesIdx < 0) tablesIdx = segments.indexOf('transact', 1);
|
|
81
|
+
}
|
|
82
|
+
// DB-level transact path has no table segment: /{ns}/transact or /{ns}/{id}/transact
|
|
83
|
+
if (segments[tablesIdx] === 'transact' && tablesIdx === segments.length - 1) {
|
|
84
|
+
return {
|
|
85
|
+
namespace: segments[0],
|
|
86
|
+
instanceId: tablesIdx === 2 ? segments[1] : undefined,
|
|
87
|
+
tableName: '',
|
|
88
|
+
directPath: '/transact',
|
|
89
|
+
};
|
|
79
90
|
}
|
|
80
91
|
if (tablesIdx < 0 || segments[tablesIdx] !== 'tables') {
|
|
81
92
|
throw new Error(`Invalid DB path: missing 'tables' segment in ${path}`);
|
|
@@ -94,6 +105,12 @@ function parsePath(
|
|
|
94
105
|
return { namespace, instanceId, tableName, directPath };
|
|
95
106
|
}
|
|
96
107
|
|
|
108
|
+
function hasD1Binding(env: Env | undefined, namespace: string): boolean {
|
|
109
|
+
if (!env) return false;
|
|
110
|
+
const bindingName = getD1BindingName(namespace);
|
|
111
|
+
return Boolean((env as unknown as Record<string, unknown>)[bindingName]);
|
|
112
|
+
}
|
|
113
|
+
|
|
97
114
|
export class InternalHttpTransport implements HttpTransport {
|
|
98
115
|
private readonly databaseNamespace: DurableObjectNamespace;
|
|
99
116
|
private readonly config: EdgeBaseConfig;
|
|
@@ -196,7 +213,14 @@ export class InternalHttpTransport implements HttpTransport {
|
|
|
196
213
|
const httpMethod = method === 'PUT' ? 'PATCH' : method; // normalize PUT → PATCH
|
|
197
214
|
|
|
198
215
|
// 1. D1 route
|
|
199
|
-
|
|
216
|
+
const shouldUseD1 =
|
|
217
|
+
!this.preferDirectDo
|
|
218
|
+
&& !dynamic
|
|
219
|
+
&& shouldRouteToD1(namespace, this.config)
|
|
220
|
+
&& this.env
|
|
221
|
+
&& (provider === 'd1' || hasD1Binding(this.env, namespace));
|
|
222
|
+
|
|
223
|
+
if (shouldUseD1) {
|
|
200
224
|
return this.requestViaD1Handler(httpMethod, namespace, normalizedInstanceId, tableName, directPath, headers, query, body);
|
|
201
225
|
}
|
|
202
226
|
|
package/src/lib/jwt.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface RefreshTokenPayload {
|
|
|
22
22
|
sub: string; // userId
|
|
23
23
|
type: 'refresh';
|
|
24
24
|
jti?: string; // unique session ID for token uniqueness
|
|
25
|
+
nonce?: string; // per-token randomness while preserving session jti
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
export interface AdminTokenPayload {
|
|
@@ -106,6 +107,7 @@ export async function signRefreshToken(
|
|
|
106
107
|
): Promise<string> {
|
|
107
108
|
const builder = new SignJWT({
|
|
108
109
|
type: 'refresh',
|
|
110
|
+
nonce: payload.nonce ?? crypto.randomUUID(),
|
|
109
111
|
})
|
|
110
112
|
.setProtectedHeader({ alg: ALGORITHM })
|
|
111
113
|
.setIssuedAt()
|