-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathbridge-handler.ts
More file actions
1656 lines (1513 loc) · 50.8 KB
/
Copy pathbridge-handler.ts
File metadata and controls
1656 lines (1513 loc) · 50.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Bridge Handler
*
* Handles bridge calls from sandboxed plugin workers.
* Used in two contexts:
* - Dev mode: as a miniflare outboundService function (Request -> Response)
* - Production: called from the backing service HTTP handler
*
* Each handler is scoped to a specific plugin with its capabilities.
* Capability enforcement happens here, not in the plugin.
*
* This implementation maintains behavioral parity with the Cloudflare
* PluginBridge (packages/cloudflare/src/sandbox/bridge.ts). Same inputs
* must produce same outputs, same return shapes, same error messages.
*/
import {
ContentRepository,
createHttpAccess,
createSandboxRouteErrorEnvelope,
createUnrestrictedHttpAccess,
normalizeCapabilities,
PluginStorageRepository,
resolveContentCreateLocale,
} from "emdash";
import type { Database, I18nConfig, SandboxEmailSendCallback } from "emdash";
import type { Kysely } from "kysely";
/**
* Schema view of a content table (ec_${collection}) for kysely. The standard
* system columns are typed; user-defined fields are addressed via the open
* `[key: string]` index. Each kysely call resolves the table name dynamically
* via `asContentDb()`.
*/
interface ContentTableRow {
id: string;
slug: string | null;
status: string;
author_id: string | null;
created_at: string;
updated_at: string;
published_at: string | null;
scheduled_at: string | null;
deleted_at: string | null;
version: number;
live_revision_id: string | null;
draft_revision_id: string | null;
locale: string;
translation_group: string | null;
// User-defined fields. kysely.set()/values() accept these because they're
// typed as unknown rather than never.
[key: string]: unknown;
}
type ContentSchema = { [tableName: string]: ContentTableRow };
/**
* View the host db as a content schema where any `ec_*` table is addressable.
* Centralizes the one unavoidable narrowing for dynamic content tables (whose
* names are computed from user-defined collection slugs and so cannot appear
* in the static `Database` interface). The runtime SQL is identical; only the
* type lens changes.
*/
function asContentDb(db: Kysely<Database>): Kysely<ContentSchema> {
// eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- ec_* content tables are created at runtime by SchemaRegistry and cannot be expressed in the static Database interface. ContentSchema is a structural view of any ec_* table.
return db as unknown as Kysely<ContentSchema>;
}
/** Validates collection/field names to prevent SQL injection */
const COLLECTION_NAME_RE = /^[a-z][a-z0-9_]*$/;
/** System columns that plugins cannot directly write to */
const SYSTEM_COLUMNS = new Set([
"id",
"slug",
"status",
"author_id",
"created_at",
"updated_at",
"published_at",
"scheduled_at",
"deleted_at",
"version",
"live_revision_id",
"draft_revision_id",
"locale",
"translation_group",
]);
/** Minimal storage interface for media uploads and deletes */
export interface BridgeStorage {
upload(options: { key: string; body: Uint8Array; contentType: string }): Promise<unknown>;
delete(key: string): Promise<unknown>;
}
/** Per-collection storage config (matches manifest.storage entries) */
export interface BridgeStorageCollectionConfig {
indexes?: Array<string | string[]>;
uniqueIndexes?: Array<string | string[]>;
}
export interface BridgeHandlerOptions {
pluginId: string;
version: string;
capabilities: string[];
allowedHosts: string[];
/** Storage collection names declared by the plugin */
storageCollections: string[];
/** Full storage config (with indexes) for proper query/count delegation */
storageConfig?: Record<string, BridgeStorageCollectionConfig>;
i18nConfig?: I18nConfig | null;
db: Kysely<Database>;
beforeContentWrite?: () => Promise<void>;
emailSend: () => SandboxEmailSendCallback | null;
/** Storage for media uploads. Optional; media/upload throws if not provided. */
storage?: BridgeStorage | null;
}
/**
* Create a bridge handler function scoped to a specific plugin.
* Returns an async function that takes a Request and returns a Response.
*/
export function createBridgeHandler(
opts: BridgeHandlerOptions,
): (request: Request) => Promise<Response> {
// Capability arrays may contain legacy aliases from older manifests;
// everything below compares against current names only.
const resolved: BridgeHandlerOptions = {
...opts,
capabilities: normalizeCapabilities(opts.capabilities),
};
return async (request: Request): Promise<Response> => {
try {
const url = new URL(request.url);
const method = url.pathname.slice(1);
let body: Record<string, unknown> = {};
if (request.method === "POST") {
const text = await request.text();
if (text) {
const parsed: unknown = JSON.parse(text);
if (!isRecord(parsed)) {
throw new Error("Bridge request body must be a JSON object");
}
body = parsed;
}
}
const result = await dispatch(resolved, method, body);
return Response.json({ result });
} catch (error) {
const sandboxRouteError = createSandboxRouteErrorEnvelope(error);
if (sandboxRouteError) {
return Response.json(
{ error: sandboxRouteError.error },
{ status: sandboxRouteError.error.status },
);
}
const message = error instanceof Error ? error.message : "Internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
};
}
// ── Dispatch ─────────────────────────────────────────────────────────────
async function dispatch(
opts: BridgeHandlerOptions,
method: string,
body: Record<string, unknown>,
): Promise<unknown> {
const { db, pluginId } = opts;
switch (method) {
// ── KV (stored in _plugin_storage with collection='__kv') ────────
case "kv/get":
return kvGet(db, pluginId, requireString(body, "key"));
case "kv/set":
return kvSet(db, pluginId, requireString(body, "key"), body.value);
case "kv/delete":
return kvDelete(db, pluginId, requireString(body, "key"));
case "kv/list":
return kvList(db, pluginId, optionalString(body, "prefix") ?? "");
// ── Content ─────────────────────────────────────────────────────
case "content/get":
requireCapability(opts, "content:read");
return contentGet(db, requireString(body, "collection"), requireString(body, "id"));
case "content/list":
requireCapability(opts, "content:read");
return contentList(db, requireString(body, "collection"), body);
case "content/create":
requireCapability(opts, "content:write");
const createOptions = optionalRecord(body, "options");
const locale = resolveContentCreateLocale(
createOptions ? optionalString(createOptions, "locale") : undefined,
opts.i18nConfig ?? null,
);
await opts.beforeContentWrite?.();
return contentCreate(
db,
requireString(body, "collection"),
requireRecord(body, "data"),
locale,
);
case "content/update":
requireCapability(opts, "content:write");
await opts.beforeContentWrite?.();
return contentUpdate(
db,
requireString(body, "collection"),
requireString(body, "id"),
requireRecord(body, "data"),
);
case "content/delete":
requireCapability(opts, "content:write");
await opts.beforeContentWrite?.();
return contentDelete(db, requireString(body, "collection"), requireString(body, "id"));
case "content/createMany":
requireCapability(opts, "content:write");
const createManyLocale = resolveContentCreateLocale(undefined, opts.i18nConfig ?? null);
await opts.beforeContentWrite?.();
return contentCreateMany(
db,
requireString(body, "collection"),
requireRecordArray(body, "items"),
createManyLocale,
);
case "content/updateMany":
requireCapability(opts, "content:write");
await opts.beforeContentWrite?.();
return contentUpdateMany(
db,
requireString(body, "collection"),
requireUpdateManyItems(body, "items"),
);
case "content/deleteMany":
requireCapability(opts, "content:write");
await opts.beforeContentWrite?.();
return contentDeleteMany(
db,
requireString(body, "collection"),
requireStringArray(body, "ids"),
);
// ── Taxonomies (read-only) ──────────────────────────────────────
// `taxonomies:read` is a post-rename capability: it has no legacy
// alias, so the canonical name is checked directly.
case "taxonomy/list":
requireCapability(opts, "taxonomies:read");
return taxonomyList(db, optionalString(body, "locale"));
case "taxonomy/terms":
requireCapability(opts, "taxonomies:read");
return taxonomyTerms(db, requireString(body, "taxonomy"), optionalString(body, "locale"));
case "taxonomy/entryTerms":
requireCapability(opts, "taxonomies:read");
return taxonomyEntryTerms(
db,
requireString(body, "collection"),
requireString(body, "entryId"),
optionalString(body, "taxonomy"),
optionalString(body, "locale"),
);
// ── Media ───────────────────────────────────────────────────────
case "media/get":
requireCapability(opts, "media:read");
return mediaGet(db, requireString(body, "id"));
case "media/list":
requireCapability(opts, "media:read");
return mediaList(db, body);
case "media/upload":
requireCapability(opts, "media:write");
return mediaUpload(
db,
requireString(body, "filename"),
requireString(body, "contentType"),
requireMediaBytes(body, "bytes"),
optionalString(body, "encoding"),
opts.storage,
);
case "media/delete":
requireCapability(opts, "media:write");
return mediaDelete(db, requireString(body, "id"), opts.storage);
// ── HTTP ────────────────────────────────────────────────────────
case "http/fetch":
requireCapability(opts, "network:request");
return httpFetch(requireString(body, "url"), body.init, opts);
// ── Email ───────────────────────────────────────────────────────
case "email/send": {
requireCapability(opts, "email:send");
const message = requireEmailMessage(body, "message");
const emailSend = opts.emailSend();
if (!emailSend) throw new Error("Email is not configured. No email provider is available.");
await emailSend(message, pluginId);
return null;
}
// ── Users ───────────────────────────────────────────────────────
case "users/get":
requireCapability(opts, "users:read");
return userGet(db, requireString(body, "id"));
case "users/getByEmail":
requireCapability(opts, "users:read");
return userGetByEmail(db, requireString(body, "email"));
case "users/list":
requireCapability(opts, "users:read");
return userList(db, body);
// ── Storage (document store, scoped to declared collections) ────
case "storage/get":
validateStorageCollection(opts, requireString(body, "collection"));
return storageGet(opts, requireString(body, "collection"), requireString(body, "id"));
case "storage/put":
validateStorageCollection(opts, requireString(body, "collection"));
return storagePut(
opts,
requireString(body, "collection"),
requireString(body, "id"),
body.data,
);
case "storage/delete":
validateStorageCollection(opts, requireString(body, "collection"));
return storageDelete(opts, requireString(body, "collection"), requireString(body, "id"));
case "storage/query":
validateStorageCollection(opts, requireString(body, "collection"));
return storageQuery(opts, requireString(body, "collection"), body);
case "storage/count":
validateStorageCollection(opts, requireString(body, "collection"));
return storageCount(opts, requireString(body, "collection"), optionalRecord(body, "where"));
case "storage/getMany":
validateStorageCollection(opts, requireString(body, "collection"));
return storageGetMany(
opts,
requireString(body, "collection"),
requireStringArray(body, "ids"),
);
case "storage/putMany":
validateStorageCollection(opts, requireString(body, "collection"));
return storagePutMany(
opts,
requireString(body, "collection"),
requireStorageItems(body, "items"),
);
case "storage/deleteMany":
validateStorageCollection(opts, requireString(body, "collection"));
return storageDeleteMany(
opts,
requireString(body, "collection"),
requireStringArray(body, "ids"),
);
// ── Logging ─────────────────────────────────────────────────────
case "log": {
const level = requireLogLevel(body, "level");
const msg = requireString(body, "msg");
console[level](`[plugin:${pluginId}]`, msg, body.data ?? "");
return null;
}
default:
// All outbound fetch() from sandboxed plugins is routed to the
// backing service via workerd's globalOutbound config. If a plugin
// calls plain fetch("https://anywhere.com/path") instead of
// ctx.http.fetch(), we land here. This is intentional: plugins
// must use ctx.http.fetch (which goes through the http/fetch
// bridge with capability + host enforcement) to reach the network.
throw new Error(`Unknown bridge method: ${method}`);
}
}
// ── Validation ───────────────────────────────────────────────────────────
//
// Bridge call bodies are JSON-RPC-style payloads constructed by the workerd
// plugin wrapper (see ./wrapper.ts) and consumed here. We control both ends
// of the protocol, so these assertions exist to catch buggy or malicious
// plugins rather than to parse an open API surface — that's why they throw
// rather than return tagged errors. The bridge top-level catch turns thrown
// errors into JSON error responses the plugin sees as bridge call failures.
//
// Each `require*` helper is backed by a narrowing predicate so the returned
// value is typed via flow analysis rather than via a `as T` assertion. This
// keeps the @typescript-eslint/no-unsafe-type-assertion rule clean.
type EmailMessage = { to: string; subject: string; text: string; html?: string };
type LogLevel = "debug" | "info" | "warn" | "error";
type UpdateManyItem = { id: string; data: Record<string, unknown> };
type StorageItem = { id: string; data: unknown };
const LOG_LEVELS = new Set<string>(["debug", "info", "warn", "error"]);
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((v) => typeof v === "string");
}
function isRecordArray(value: unknown): value is Array<Record<string, unknown>> {
return Array.isArray(value) && value.every(isRecord);
}
function isUpdateManyItem(value: unknown): value is UpdateManyItem {
if (!isRecord(value)) return false;
return typeof value.id === "string" && isRecord(value.data);
}
function isUpdateManyItemArray(value: unknown): value is UpdateManyItem[] {
return Array.isArray(value) && value.every(isUpdateManyItem);
}
function isStorageItem(value: unknown): value is StorageItem {
if (!isRecord(value)) return false;
return typeof value.id === "string";
}
function isStorageItemArray(value: unknown): value is StorageItem[] {
return Array.isArray(value) && value.every(isStorageItem);
}
function isNumberArray(value: unknown): value is number[] {
return Array.isArray(value) && value.every((v) => typeof v === "number");
}
function isEmailMessage(value: unknown): value is EmailMessage {
if (!isRecord(value)) return false;
if (typeof value.to !== "string") return false;
if (typeof value.subject !== "string") return false;
if (typeof value.text !== "string") return false;
if (value.html !== undefined && typeof value.html !== "string") return false;
return true;
}
function isLogLevel(value: unknown): value is LogLevel {
return typeof value === "string" && LOG_LEVELS.has(value);
}
function isOrderBy(value: unknown): value is Record<string, "asc" | "desc"> {
if (!isRecord(value)) return false;
for (const dir of Object.values(value)) {
if (dir !== "asc" && dir !== "desc") return false;
}
return true;
}
function requireString(body: Record<string, unknown>, key: string): string {
const value = body[key];
if (typeof value !== "string") throw new Error(`Missing required string parameter: ${key}`);
return value;
}
function optionalString(body: Record<string, unknown>, key: string): string | undefined {
const value = body[key];
if (value === undefined) return undefined;
if (typeof value !== "string") throw new Error(`Parameter ${key} must be a string when provided`);
return value;
}
function requireRecord(body: Record<string, unknown>, key: string): Record<string, unknown> {
const value = body[key];
if (!isRecord(value)) throw new Error(`Missing required object parameter: ${key}`);
return value;
}
function optionalRecord(
body: Record<string, unknown>,
key: string,
): Record<string, unknown> | undefined {
const value = body[key];
if (value === undefined) return undefined;
if (!isRecord(value)) throw new Error(`Parameter ${key} must be an object when provided`);
return value;
}
function requireStringArray(body: Record<string, unknown>, key: string): string[] {
const value = body[key];
if (!isStringArray(value)) throw new Error(`Parameter ${key} must be an array of strings`);
return value;
}
function requireRecordArray(
body: Record<string, unknown>,
key: string,
): Array<Record<string, unknown>> {
const value = body[key];
if (!isRecordArray(value)) throw new Error(`Parameter ${key} must be an array of objects`);
return value;
}
function requireUpdateManyItems(body: Record<string, unknown>, key: string): UpdateManyItem[] {
const value = body[key];
if (!isUpdateManyItemArray(value)) {
throw new Error(`Parameter ${key} must be an array of { id: string, data: object } items`);
}
return value;
}
function requireStorageItems(body: Record<string, unknown>, key: string): StorageItem[] {
const value = body[key];
if (!isStorageItemArray(value)) {
throw new Error(`Parameter ${key} must be an array of { id: string, data } items`);
}
return value;
}
function requireMediaBytes(body: Record<string, unknown>, key: string): string | number[] {
const value = body[key];
if (typeof value === "string") return value;
if (isNumberArray(value)) return value;
throw new Error(`Parameter ${key} must be a string or array of numbers`);
}
function requireEmailMessage(body: Record<string, unknown>, key: string): EmailMessage {
const value = body[key];
if (!isEmailMessage(value)) {
throw new Error("email/send requires message with to, subject, and text");
}
return value;
}
function requireLogLevel(body: Record<string, unknown>, key: string): LogLevel {
const value = body[key];
if (!isLogLevel(value)) {
throw new Error(`Parameter ${key} must be one of: debug, info, warn, error`);
}
return value;
}
function requireOrderBy(
body: Record<string, unknown>,
key: string,
): Record<string, "asc" | "desc"> | undefined {
const value = body[key];
if (value === undefined) return undefined;
if (!isOrderBy(value)) {
throw new Error(`Parameter ${key} must be an object mapping field to "asc"|"desc"`);
}
return value;
}
function requireCapability(opts: BridgeHandlerOptions, capability: string): void {
// Strict capability check matching the Cloudflare PluginBridge.
// We do NOT imply write → read here: a plugin that declares only
// content:write cannot call ctx.content.get/list. The plugin must
// declare content:read explicitly. This matches the Cloudflare bridge
// behavior and ensures sandboxed plugins behave the same on both runners.
//
// Note: the in-process PluginContextFactory in core does build the read
// API onto the write object, so a trusted plugin can read with only
// content:write. The sandbox bridges are stricter on purpose — they
// enforce the manifest as written.
//
// The one exception: network:request:unrestricted is documented as a
// strict superset of network:request, so the broader capability
// satisfies it.
if (
capability === "network:request" &&
opts.capabilities.includes("network:request:unrestricted")
) {
return;
}
if (!opts.capabilities.includes(capability)) {
// Error message matches Cloudflare PluginBridge format
throw new Error(`Missing capability: ${capability}`);
}
}
function validateStorageCollection(opts: BridgeHandlerOptions, collection: string): void {
if (!opts.storageCollections.includes(collection)) {
// Error message matches Cloudflare PluginBridge format
throw new Error(`Storage collection not declared: ${collection}`);
}
}
function validateCollectionName(collection: string): void {
if (!COLLECTION_NAME_RE.test(collection)) {
throw new Error(`Invalid collection name: ${collection}`);
}
}
// ── Value serialization (matches Cloudflare bridge) ──────────────────────
function serializeValue(value: unknown): unknown {
if (value === null || value === undefined) return null;
if (typeof value === "boolean") return value ? 1 : 0;
if (typeof value === "object") return JSON.stringify(value);
return value;
}
/**
* Transform a raw DB row into the content item shape returned to plugins.
* Matches the Cloudflare bridge's rowToContentItem.
*/
function rowToContentItem(
collection: string,
row: Record<string, unknown>,
): {
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
} {
const data: Record<string, unknown> = {};
for (const [key, value] of Object.entries(row)) {
if (!SYSTEM_COLUMNS.has(key)) {
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
try {
data[key] = JSON.parse(value);
} catch {
data[key] = value;
}
} else if (value !== null) {
data[key] = value;
}
}
}
return {
id: typeof row.id === "string" ? row.id : String(row.id),
type: collection,
data,
createdAt: typeof row.created_at === "string" ? row.created_at : new Date().toISOString(),
updatedAt: typeof row.updated_at === "string" ? row.updated_at : new Date().toISOString(),
locale: typeof row.locale === "string" ? row.locale : "en",
};
}
// ── KV Operations ────────────────────────────────────────────────────────
// Uses _plugin_storage with collection='__kv' (matching Cloudflare bridge)
async function kvGet(db: Kysely<Database>, pluginId: string, key: string): Promise<unknown> {
const row = await db
.selectFrom("_plugin_storage")
.where("plugin_id", "=", pluginId)
.where("collection", "=", "__kv")
.where("id", "=", key)
.select("data")
.executeTakeFirst();
if (!row) return null;
try {
return JSON.parse(row.data);
} catch {
return row.data;
}
}
async function kvSet(
db: Kysely<Database>,
pluginId: string,
key: string,
value: unknown,
): Promise<void> {
const serialized = JSON.stringify(value);
const now = new Date().toISOString();
await db
.insertInto("_plugin_storage")
.values({
plugin_id: pluginId,
collection: "__kv",
id: key,
data: serialized,
created_at: now,
updated_at: now,
})
.onConflict((oc) =>
oc.columns(["plugin_id", "collection", "id"]).doUpdateSet({
data: serialized,
updated_at: now,
}),
)
.execute();
}
async function kvDelete(db: Kysely<Database>, pluginId: string, key: string): Promise<boolean> {
const result = await db
.deleteFrom("_plugin_storage")
.where("plugin_id", "=", pluginId)
.where("collection", "=", "__kv")
.where("id", "=", key)
.executeTakeFirst();
return BigInt(result.numDeletedRows) > 0n;
}
async function kvList(
db: Kysely<Database>,
pluginId: string,
prefix: string,
): Promise<Array<{ key: string; value: unknown }>> {
const rows = await db
.selectFrom("_plugin_storage")
.where("plugin_id", "=", pluginId)
.where("collection", "=", "__kv")
.where("id", "like", `${prefix}%`)
.select(["id", "data"])
.execute();
return rows.map((r) => ({
key: r.id,
value: JSON.parse(r.data),
}));
}
// ── Content Operations ───────────────────────────────────────────────────
async function contentGet(
db: Kysely<Database>,
collection: string,
id: string,
): Promise<{
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
} | null> {
validateCollectionName(collection);
const table = `ec_${collection}`;
try {
const row = await asContentDb(db)
.selectFrom(table)
.where("id", "=", id)
.where("deleted_at", "is", null)
.selectAll()
.executeTakeFirst();
if (!row) return null;
return rowToContentItem(collection, row);
} catch {
return null;
}
}
async function contentList(
db: Kysely<Database>,
collection: string,
opts: Record<string, unknown>,
): Promise<{
items: Array<{
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
}>;
cursor?: string;
hasMore: boolean;
}> {
validateCollectionName(collection);
const table = `ec_${collection}`;
const limit = Math.max(1, Math.min(Number(opts.limit) || 50, 100));
try {
let query = asContentDb(db)
.selectFrom(table)
.where("deleted_at", "is", null)
.selectAll()
.orderBy("id", "desc");
if (typeof opts.cursor === "string") {
query = query.where("id", "<", opts.cursor);
}
const rows = await query.limit(limit + 1).execute();
const pageRows = rows.slice(0, limit);
const items = pageRows.map((row) => rowToContentItem(collection, row));
const hasMore = rows.length > limit;
return {
items,
cursor: hasMore && items.length > 0 ? items.at(-1)!.id : undefined,
hasMore,
};
} catch {
return { items: [], hasMore: false };
}
}
async function contentCreate(
db: Kysely<Database>,
collection: string,
data: Record<string, unknown>,
locale?: string,
): Promise<{
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
}> {
validateCollectionName(collection);
const table = `ec_${collection}`;
// Generate ULID for the new content item
const { ulid } = await import("ulidx");
const id = ulid();
const now = new Date().toISOString();
// Build insert values: system columns + user data columns
const values: Record<string, unknown> = {
id,
slug: typeof data.slug === "string" ? data.slug : null,
status: typeof data.status === "string" ? data.status : "draft",
author_id: typeof data.author_id === "string" ? data.author_id : null,
created_at: now,
updated_at: now,
version: 1,
translation_group: id,
};
if (locale !== undefined) values.locale = locale;
// Add user data fields (skip system columns, validate names)
for (const [key, value] of Object.entries(data)) {
if (!SYSTEM_COLUMNS.has(key) && COLLECTION_NAME_RE.test(key)) {
values[key] = serializeValue(value);
}
}
const cdb = asContentDb(db);
await cdb.insertInto(table).values(values).execute();
// Re-read the created row
const created = await cdb
.selectFrom(table)
.where("id", "=", id)
.where("deleted_at", "is", null)
.selectAll()
.executeTakeFirst();
if (!created) {
return {
id,
type: collection,
data: {},
createdAt: now,
updatedAt: now,
locale: locale ?? "en",
};
}
return rowToContentItem(collection, created);
}
async function contentUpdate(
db: Kysely<Database>,
collection: string,
id: string,
data: Record<string, unknown>,
): Promise<{
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
}> {
validateCollectionName(collection);
const updated = await new ContentRepository(db).updateDraftAware(collection, id, {
data,
status: typeof data.status === "string" ? data.status : undefined,
slug: data.slug === undefined ? undefined : typeof data.slug === "string" ? data.slug : null,
});
return {
id: updated.id,
type: updated.type,
data: updated.data,
createdAt: updated.createdAt,
updatedAt: updated.updatedAt,
locale: updated.locale ?? "en",
};
}
async function contentDelete(
db: Kysely<Database>,
collection: string,
id: string,
): Promise<boolean> {
validateCollectionName(collection);
const table = `ec_${collection}`;
// Soft-delete: set deleted_at timestamp (matching Cloudflare bridge)
const now = new Date().toISOString();
const result = await asContentDb(db)
.updateTable(table)
.set({ deleted_at: now, updated_at: now })
.where("id", "=", id)
.where("deleted_at", "is", null)
.executeTakeFirst();
return BigInt(result.numUpdatedRows) > 0n;
}
// ── Batch Content Operations ─────────────────────────────────────────────
const MAX_BATCH_SIZE = 100;
async function contentCreateMany(
db: Kysely<Database>,
collection: string,
items: Array<Record<string, unknown>>,
locale: string,
): Promise<
Array<{
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
}>
> {
if (items.length > MAX_BATCH_SIZE) {
throw new Error(`Batch size ${items.length} exceeds maximum of ${MAX_BATCH_SIZE}`);
}
return db.transaction().execute(async (trx) => {
const results = [];
for (const data of items) {
results.push(await contentCreate(trx, collection, data, locale));
}
return results;
});
}
async function contentUpdateMany(
db: Kysely<Database>,
collection: string,
items: Array<{ id: string; data: Record<string, unknown> }>,
): Promise<
Array<{
id: string;
type: string;
data: Record<string, unknown>;
createdAt: string;
updatedAt: string;
locale: string;
}>
> {
if (items.length > MAX_BATCH_SIZE) {
throw new Error(`Batch size ${items.length} exceeds maximum of ${MAX_BATCH_SIZE}`);
}
return db.transaction().execute(async (trx) => {
const results = [];
for (const item of items) {
results.push(await contentUpdate(trx, collection, item.id, item.data));
}
return results;
});
}
async function contentDeleteMany(
db: Kysely<Database>,
collection: string,
ids: string[],
): Promise<number> {
if (ids.length > MAX_BATCH_SIZE) {
throw new Error(`Batch size ${ids.length} exceeds maximum of ${MAX_BATCH_SIZE}`);
}
return db.transaction().execute(async (trx) => {
let count = 0;
for (const id of ids) {
const deleted = await contentDelete(trx, collection, id);
if (deleted) count++;
}
return count;
});
}
// ── Taxonomy Operations (read-only) ──────────────────────────────────────
/** Type guard for plain JSON objects. */
function isJsonObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** Parse the `collections` JSON column into a string array (`[]` on anything else). */
function parseCollectionsColumn(value: string | null): string[] {
if (!value) return [];
try {
const parsed: unknown = JSON.parse(value);
return Array.isArray(parsed)
? parsed.filter((item): item is string => typeof item === "string")
: [];
} catch {
return [];
}
}
/**
* Convert a `taxonomies` row to the term shape exposed over the bridge.
* Matches the Cloudflare PluginBridge and core's TaxonomyTermInfo.
*/
function rowToTaxonomyTerm(row: {