appflare 0.2.18 → 0.2.20
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/cli/generate.ts +18 -0
- package/cli/templates/dashboard/builders/storage/runtime/storage-page.ts +1 -1
- package/cli/templates/dashboard/builders/table-routes/table/get-route.ts +1 -1
- package/cli/templates/dashboard/builders/table-routes/table/post-routes.ts +1 -1
- package/cli/templates/handlers/execution.ts +1 -1
- package/cli/templates/handlers/generators/context/context-creation.ts +20 -2
- package/cli/templates/handlers/generators/registration/modules/cron.ts +2 -6
- package/cli/templates/handlers/generators/registration/modules/realtime/routes.ts +1 -1
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +2 -2
- package/cli/templates/handlers/generators/registration/modules/storage.ts +5 -5
- package/cli/templates/handlers/generators/types/context.ts +2 -0
- package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +2 -6
- package/dist/cli/index.js +196 -184
- package/dist/cli/index.mjs +196 -184
- package/package.json +1 -1
package/dist/cli/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import {Command}from'commander';import
|
|
2
|
+
import {Command}from'commander';import oa from'chokidar';import {existsSync}from'fs';import {resolve,isAbsolute,dirname,relative,extname}from'path';import {mkdir,readdir}from'fs/promises';import {pathToFileURL}from'url';import*as g from'typescript';import {z as z$1}from'zod';function ne(e){return `import { betterAuth } from "better-auth";
|
|
3
3
|
import { withCloudflare } from "better-auth-cloudflare";
|
|
4
4
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
5
5
|
import { drizzle } from "drizzle-orm/d1";
|
|
@@ -55,7 +55,7 @@ export const createAuth = (
|
|
|
55
55
|
});
|
|
56
56
|
};
|
|
57
57
|
export const auth = createAuth();
|
|
58
|
-
`}function
|
|
58
|
+
`}function re(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
59
59
|
import type {
|
|
60
60
|
AppflareAuth,
|
|
61
61
|
AppflareAuthTokenResolver,
|
|
@@ -164,8 +164,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
164
164
|
): Appflare<Options> {
|
|
165
165
|
return new Appflare(options);
|
|
166
166
|
}
|
|
167
|
-
`}function
|
|
168
|
-
`)}function
|
|
167
|
+
`}function En(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function ae(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Dn(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function oe(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function V(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${Dn(i)}: ${V(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
168
|
+
`)}function Fn(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length===0)return null;let r=En(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${ae(e.kind)}${ae(n.join("_"))}`}}function On(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
169
169
|
runtime: RequestRuntime,
|
|
170
170
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
171
171
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -351,15 +351,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
351
351
|
schema: ${r},
|
|
352
352
|
run,
|
|
353
353
|
};
|
|
354
|
-
};`}function B(e){let t=e.map((u,c)=>
|
|
354
|
+
};`}function B(e){let t=e.map((u,c)=>Fn(u,c)).filter(u=>u!==null),n=t.filter(u=>u.kind==="query"),r=t.filter(u=>u.kind==="mutation"),a=t.map(u=>`import { ${u.exportName} as ${u.alias} } from "${u.importPath}";`).join(`
|
|
355
355
|
`),o=t.map(u=>{let c=`${u.typeBase}Input`,f=`${u.typeBase}Output`,d=`${u.typeBase}Schema`;return `const ${u.schemaConst} = z.object(${u.alias}.definition.args);
|
|
356
356
|
export type ${c} = z.input<typeof ${u.schemaConst}>;
|
|
357
357
|
export type ${f} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
358
358
|
export const ${d} = ${u.schemaConst};`}).join(`
|
|
359
359
|
|
|
360
|
-
`),i=t.map(u=>
|
|
360
|
+
`),i=t.map(u=>On(u)).join(`
|
|
361
361
|
|
|
362
|
-
`),s=V(
|
|
362
|
+
`),s=V(oe(n)),l=V(oe(r));return `import betterFetch from "better-fetch";
|
|
363
363
|
import { z } from "zod";
|
|
364
364
|
import type {
|
|
365
365
|
AppflareErrorMode,
|
|
@@ -736,11 +736,11 @@ export function createMutationsClient(
|
|
|
736
736
|
|
|
737
737
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
738
738
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
739
|
-
`}function
|
|
739
|
+
`}function ie(){return `export * from "./types";
|
|
740
740
|
export * from "./appflare";
|
|
741
741
|
export * from "./storage";
|
|
742
742
|
export * from "./handlers";
|
|
743
|
-
`}function
|
|
743
|
+
`}function se(){return `import type { StorageClient, StorageSignedUrlResponse, StorageListResponse } from "./types";
|
|
744
744
|
|
|
745
745
|
type AuthTokenResolver = (() => string | Promise<string>) | undefined;
|
|
746
746
|
|
|
@@ -917,7 +917,7 @@ export function createStorageClient(
|
|
|
917
917
|
},
|
|
918
918
|
};
|
|
919
919
|
}
|
|
920
|
-
`}function
|
|
920
|
+
`}function le(e){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
921
921
|
import type appflareConfig from "${e}";
|
|
922
922
|
|
|
923
923
|
export type AppflareConfig = typeof appflareConfig;
|
|
@@ -1098,7 +1098,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1098
1098
|
};
|
|
1099
1099
|
};
|
|
1100
1100
|
};
|
|
1101
|
-
`}function
|
|
1101
|
+
`}function ce(e,t){return [{relativePath:"client/index.ts",source:ie()},{relativePath:"client/types.ts",source:le(e)},{relativePath:"client/storage.ts",source:se()},{relativePath:"client/handlers.ts",source:B(t)},{relativePath:"client/appflare.ts",source:re()}]}function ue(e){return `import { defineConfig } from "drizzle-kit";
|
|
1102
1102
|
|
|
1103
1103
|
export default defineConfig({
|
|
1104
1104
|
dialect: "sqlite",
|
|
@@ -1110,7 +1110,7 @@ export default defineConfig({
|
|
|
1110
1110
|
token: "token",
|
|
1111
1111
|
},
|
|
1112
1112
|
});
|
|
1113
|
-
`}function
|
|
1113
|
+
`}function de(){return `
|
|
1114
1114
|
|
|
1115
1115
|
import { getHeaders } from "./server";
|
|
1116
1116
|
export async function resolveSession(
|
|
@@ -1144,7 +1144,7 @@ export async function resolveSession(
|
|
|
1144
1144
|
}
|
|
1145
1145
|
}
|
|
1146
1146
|
|
|
1147
|
-
`}function
|
|
1147
|
+
`}function pe(){return `
|
|
1148
1148
|
type SchedulerQueueBinding = {
|
|
1149
1149
|
send: (body: unknown, options?: SchedulerEnqueueOptions) => Promise<void>;
|
|
1150
1150
|
};
|
|
@@ -1159,7 +1159,7 @@ type R2BucketBinding = {
|
|
|
1159
1159
|
options?: { expiresIn?: number },
|
|
1160
1160
|
) => Promise<URL>;
|
|
1161
1161
|
};
|
|
1162
|
-
`}function
|
|
1162
|
+
`}function me(){return `
|
|
1163
1163
|
export function createScheduler(
|
|
1164
1164
|
queue?: SchedulerQueueBinding,
|
|
1165
1165
|
): Scheduler {
|
|
@@ -1180,7 +1180,7 @@ export function createScheduler(
|
|
|
1180
1180
|
},
|
|
1181
1181
|
};
|
|
1182
1182
|
}
|
|
1183
|
-
`}function
|
|
1183
|
+
`}function ge(){return `
|
|
1184
1184
|
function createContextErrorHelpers() {
|
|
1185
1185
|
return {
|
|
1186
1186
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1188,7 +1188,7 @@ function createContextErrorHelpers() {
|
|
|
1188
1188
|
},
|
|
1189
1189
|
};
|
|
1190
1190
|
}
|
|
1191
|
-
`}function
|
|
1191
|
+
`}function fe(){return `
|
|
1192
1192
|
function normalizeStoragePath(path: string): string {
|
|
1193
1193
|
const trimmed = path.trim();
|
|
1194
1194
|
if (trimmed.length === 0) {
|
|
@@ -1244,7 +1244,7 @@ function buildSignedRequest(
|
|
|
1244
1244
|
headers,
|
|
1245
1245
|
});
|
|
1246
1246
|
}
|
|
1247
|
-
`}function
|
|
1247
|
+
`}function he(){return `
|
|
1248
1248
|
function createStorageApi(
|
|
1249
1249
|
ctx: AppflareContext,
|
|
1250
1250
|
bucket: R2BucketBinding | undefined,
|
|
@@ -1353,11 +1353,11 @@ function createStorageApi(
|
|
|
1353
1353
|
},
|
|
1354
1354
|
};
|
|
1355
1355
|
}
|
|
1356
|
-
`}function
|
|
1357
|
-
export function createSchedulerExecutionContext(
|
|
1356
|
+
`}function ye(e){return `
|
|
1357
|
+
export async function createSchedulerExecutionContext(
|
|
1358
1358
|
env: Record<string, unknown>,
|
|
1359
1359
|
options: RegisterHandlersOptions,
|
|
1360
|
-
): AppflareContext {
|
|
1360
|
+
): Promise<AppflareContext> {
|
|
1361
1361
|
const database = env[options.databaseBinding] as D1Database;
|
|
1362
1362
|
const r2Binding = options.r2Binding ?? ${JSON.stringify(e??"")};
|
|
1363
1363
|
const storageBucket = r2Binding
|
|
@@ -1365,9 +1365,17 @@ export function createSchedulerExecutionContext(
|
|
|
1365
1365
|
: undefined;
|
|
1366
1366
|
const db = createDb(database);
|
|
1367
1367
|
const mutationEvents = [] as AppflareContext["mutationEvents"];
|
|
1368
|
+
const kvNamespace = options.kvBinding
|
|
1369
|
+
? (env[options.kvBinding] as KVNamespace)
|
|
1370
|
+
: undefined;
|
|
1368
1371
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
1369
1372
|
const schedulerQueue = env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
1370
1373
|
const helpers = createContextErrorHelpers();
|
|
1374
|
+
const auth = createAuth({
|
|
1375
|
+
DATABASE: database,
|
|
1376
|
+
KV: kvNamespace,
|
|
1377
|
+
});
|
|
1378
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
1371
1379
|
const schedulerContext = {
|
|
1372
1380
|
env: env as WorkerEnv["Bindings"],
|
|
1373
1381
|
} as unknown as Context<WorkerEnv>;
|
|
@@ -1381,6 +1389,7 @@ export function createSchedulerExecutionContext(
|
|
|
1381
1389
|
mutationEvents,
|
|
1382
1390
|
user: null as never,
|
|
1383
1391
|
session: null as never,
|
|
1392
|
+
auth: authAdapter,
|
|
1384
1393
|
context: schedulerContext,
|
|
1385
1394
|
scheduler: createScheduler(schedulerQueue),
|
|
1386
1395
|
storage: null as never,
|
|
@@ -1414,6 +1423,14 @@ export async function createExecutionContext(
|
|
|
1414
1423
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
1415
1424
|
const schedulerQueue = c.env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
1416
1425
|
const helpers = createContextErrorHelpers();
|
|
1426
|
+
const auth = createAuth(
|
|
1427
|
+
{
|
|
1428
|
+
DATABASE: database,
|
|
1429
|
+
KV: kvNamespace,
|
|
1430
|
+
},
|
|
1431
|
+
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
1432
|
+
);
|
|
1433
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
1417
1434
|
const ctx = {
|
|
1418
1435
|
$db: db,
|
|
1419
1436
|
db: createQueryDb(db, {
|
|
@@ -1424,6 +1441,7 @@ export async function createExecutionContext(
|
|
|
1424
1441
|
mutationEvents,
|
|
1425
1442
|
user,
|
|
1426
1443
|
session,
|
|
1444
|
+
auth: authAdapter,
|
|
1427
1445
|
context: c,
|
|
1428
1446
|
scheduler: createScheduler(schedulerQueue),
|
|
1429
1447
|
storage: null as never,
|
|
@@ -1452,20 +1470,20 @@ import {
|
|
|
1452
1470
|
createQueryDb,
|
|
1453
1471
|
} from "./handlers";
|
|
1454
1472
|
|
|
1455
|
-
${de()}
|
|
1456
|
-
|
|
1457
|
-
${ue()}
|
|
1458
|
-
|
|
1459
1473
|
${pe()}
|
|
1460
1474
|
|
|
1475
|
+
${de()}
|
|
1476
|
+
|
|
1461
1477
|
${me()}
|
|
1462
1478
|
|
|
1463
1479
|
${ge()}
|
|
1464
1480
|
|
|
1465
1481
|
${fe()}
|
|
1466
1482
|
|
|
1467
|
-
${he(
|
|
1468
|
-
|
|
1483
|
+
${he()}
|
|
1484
|
+
|
|
1485
|
+
${ye(e)}
|
|
1486
|
+
`}function we(){return `
|
|
1469
1487
|
export async function executeOperation(
|
|
1470
1488
|
c: Context<WorkerEnv>,
|
|
1471
1489
|
operation: RegisteredOperation<ZodRawShape, unknown>,
|
|
@@ -1491,7 +1509,7 @@ export function handleOperationError(
|
|
|
1491
1509
|
validationMessage: string,
|
|
1492
1510
|
): Response {
|
|
1493
1511
|
if (error instanceof AppflareHandledError) {
|
|
1494
|
-
return c.json(error.payload, error.status);
|
|
1512
|
+
return c.json(error.payload, error.status as any);
|
|
1495
1513
|
}
|
|
1496
1514
|
|
|
1497
1515
|
if (error instanceof ZodError) {
|
|
@@ -1501,7 +1519,7 @@ export function handleOperationError(
|
|
|
1501
1519
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1502
1520
|
}
|
|
1503
1521
|
|
|
1504
|
-
`}function
|
|
1522
|
+
`}function xe(){return `import type { Context } from "hono";
|
|
1505
1523
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1506
1524
|
import {
|
|
1507
1525
|
type AppflareContext,
|
|
@@ -1510,8 +1528,8 @@ import {
|
|
|
1510
1528
|
type WorkerEnv,
|
|
1511
1529
|
} from "./handlers";
|
|
1512
1530
|
|
|
1513
|
-
${
|
|
1514
|
-
`}function
|
|
1531
|
+
${we()}
|
|
1532
|
+
`}function ve(){return `import { betterAuth } from "better-auth";
|
|
1515
1533
|
import { auth } from "./auth.config";
|
|
1516
1534
|
import {
|
|
1517
1535
|
and,
|
|
@@ -1614,7 +1632,7 @@ export async function isStorageAllowed(
|
|
|
1614
1632
|
|
|
1615
1633
|
return false;
|
|
1616
1634
|
}
|
|
1617
|
-
`}function
|
|
1635
|
+
`}function Te(){return `type Primitive = string | number | boolean | Date;
|
|
1618
1636
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1619
1637
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1620
1638
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1870,7 +1888,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1870
1888
|
where?: WhereInput<TableModel<TName>>;
|
|
1871
1889
|
limit?: number;
|
|
1872
1890
|
};
|
|
1873
|
-
`}function
|
|
1891
|
+
`}function Re(){return `type AggregateWithInput<TName extends TableName> =
|
|
1874
1892
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1875
1893
|
|
|
1876
1894
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2002,7 +2020,7 @@ export type DbMutationEvent = {
|
|
|
2002
2020
|
export type QueryDbOptions = {
|
|
2003
2021
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2004
2022
|
};
|
|
2005
|
-
`}function
|
|
2023
|
+
`}function ke(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2006
2024
|
return typeof value === "object" && value !== null;
|
|
2007
2025
|
}
|
|
2008
2026
|
|
|
@@ -2484,11 +2502,7 @@ function hasManyToManyRelationsInWith(
|
|
|
2484
2502
|
}
|
|
2485
2503
|
|
|
2486
2504
|
const nestedWith = relationValue.with;
|
|
2487
|
-
if (
|
|
2488
|
-
hasManyToManyRelationsInWith(relationName, nestedWith) ||
|
|
2489
|
-
(manyToMany &&
|
|
2490
|
-
hasManyToManyRelationsInWith(manyToMany.targetTable, nestedWith))
|
|
2491
|
-
) {
|
|
2505
|
+
if (hasManyToManyRelationsInWith(relationName, nestedWith)) {
|
|
2492
2506
|
return true;
|
|
2493
2507
|
}
|
|
2494
2508
|
}
|
|
@@ -2580,7 +2594,7 @@ type RelationWithAggregatePlan = Record<string, RelationWithAggregatePlanEntry>;
|
|
|
2580
2594
|
|
|
2581
2595
|
function hasRelationAggregatePlanEntries(
|
|
2582
2596
|
plan: RelationWithAggregatePlan | undefined,
|
|
2583
|
-
):
|
|
2597
|
+
): plan is RelationWithAggregatePlan {
|
|
2584
2598
|
return !!plan && Object.keys(plan).length > 0;
|
|
2585
2599
|
}
|
|
2586
2600
|
|
|
@@ -3034,7 +3048,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3034
3048
|
|
|
3035
3049
|
return [];
|
|
3036
3050
|
}
|
|
3037
|
-
`}function
|
|
3051
|
+
`}function Se(){return `const mergedSchema = {
|
|
3038
3052
|
...authSchema,
|
|
3039
3053
|
...schema,
|
|
3040
3054
|
};
|
|
@@ -3277,9 +3291,9 @@ type TableFindFirstResult<
|
|
|
3277
3291
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3278
3292
|
(typeof mergedSchema)[TName]
|
|
3279
3293
|
>;
|
|
3280
|
-
`}function
|
|
3294
|
+
`}function Ae(){return [Se(),Te(),Re(),ke()].join(`
|
|
3281
3295
|
|
|
3282
|
-
`)}function
|
|
3296
|
+
`)}function Ne(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3283
3297
|
const withValue = args?.with;
|
|
3284
3298
|
const pathSegments = args?.field
|
|
3285
3299
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3450,7 +3464,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3450
3464
|
},
|
|
3451
3465
|
}) as AppflareQueryDb;
|
|
3452
3466
|
}
|
|
3453
|
-
`}function
|
|
3467
|
+
`}function $e(){return `export class AppflareHandledError extends Error {
|
|
3454
3468
|
public readonly status: number;
|
|
3455
3469
|
public readonly payload: unknown;
|
|
3456
3470
|
|
|
@@ -3460,7 +3474,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3460
3474
|
this.payload = payload;
|
|
3461
3475
|
}
|
|
3462
3476
|
}
|
|
3463
|
-
`}function
|
|
3477
|
+
`}function qe(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3464
3478
|
const where = isRecord(args?.where)
|
|
3465
3479
|
? (args?.where as Record<string, unknown>)
|
|
3466
3480
|
: undefined;
|
|
@@ -3578,7 +3592,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3578
3592
|
);
|
|
3579
3593
|
});
|
|
3580
3594
|
},
|
|
3581
|
-
`}function
|
|
3595
|
+
`}function Ie(){return `export function createQueryDb(
|
|
3582
3596
|
$db: AppflareDb,
|
|
3583
3597
|
options?: QueryDbOptions,
|
|
3584
3598
|
): AppflareQueryDb {
|
|
@@ -3620,7 +3634,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3620
3634
|
};
|
|
3621
3635
|
|
|
3622
3636
|
const tableApi = {
|
|
3623
|
-
`}function
|
|
3637
|
+
`}function Ce(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
3624
3638
|
const transaction = ($db as any).transaction;
|
|
3625
3639
|
|
|
3626
3640
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -4293,9 +4307,10 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4293
4307
|
);
|
|
4294
4308
|
return rows;
|
|
4295
4309
|
},
|
|
4296
|
-
`}function
|
|
4310
|
+
`}function Me(){return [Ie(),qe(),Ce(),Ne(),$e()].join(`
|
|
4297
4311
|
|
|
4298
|
-
`)}function
|
|
4312
|
+
`)}function Pe(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4313
|
+
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4299
4314
|
type User = AuthSession['user']
|
|
4300
4315
|
type Session = AuthSession['session']
|
|
4301
4316
|
|
|
@@ -4351,12 +4366,13 @@ export type AppflareContext = {
|
|
|
4351
4366
|
mutationEvents: DbMutationEvent[];
|
|
4352
4367
|
user: User;
|
|
4353
4368
|
session: Session;
|
|
4369
|
+
auth: AuthAdapter;
|
|
4354
4370
|
context: Context<WorkerEnv>;
|
|
4355
4371
|
scheduler: Scheduler;
|
|
4356
4372
|
storage: AppflareStorage;
|
|
4357
4373
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4358
4374
|
};
|
|
4359
|
-
`}function
|
|
4375
|
+
`}function Ee(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4360
4376
|
|
|
4361
4377
|
export type SchedulerEnqueueOptions = {
|
|
4362
4378
|
delaySeconds?: number;
|
|
@@ -4488,9 +4504,9 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4488
4504
|
definition,
|
|
4489
4505
|
};
|
|
4490
4506
|
}
|
|
4491
|
-
`}function De(){return [
|
|
4507
|
+
`}function De(){return [ve(),Ae(),Me(),Pe(),Ee()].join(`
|
|
4492
4508
|
|
|
4493
|
-
`)}function
|
|
4509
|
+
`)}function Fe(e){return `import type { Context } from "hono";
|
|
4494
4510
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4495
4511
|
import { drizzle } from "drizzle-orm/d1";
|
|
4496
4512
|
import { z, type ZodRawShape } from "zod";
|
|
@@ -4498,10 +4514,10 @@ import * as authSchema from "./auth.schema";
|
|
|
4498
4514
|
import * as schema from "${e}";
|
|
4499
4515
|
|
|
4500
4516
|
${De()}
|
|
4501
|
-
`}function
|
|
4502
|
-
`)}function
|
|
4503
|
-
`)}function
|
|
4504
|
-
`)}function
|
|
4517
|
+
`}function jn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function Vn(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return jn(`op_${t}_${n}`)}function Bn(e){return e.map((t,n)=>({operation:t,index:n,alias:Vn(t,n)}))}function Hn(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
4518
|
+
`)}function Wn(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
4519
|
+
`)}function Ln(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({alias:t})=>`const ${`${t}SchedulerSchema`} = ${t}.definition.args ? z.object(${t}.definition.args) : z.undefined();`).join(`
|
|
4520
|
+
`)}function zn(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4505
4521
|
app.get(
|
|
4506
4522
|
"${t.routePath}",
|
|
4507
4523
|
sValidator("query", ${r}),
|
|
@@ -4514,7 +4530,7 @@ ${De()}
|
|
|
4514
4530
|
}
|
|
4515
4531
|
},
|
|
4516
4532
|
);`}).join(`
|
|
4517
|
-
`)}function
|
|
4533
|
+
`)}function Un(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4518
4534
|
app.post(
|
|
4519
4535
|
"${t.routePath}",
|
|
4520
4536
|
sValidator("json", ${r}),
|
|
@@ -4529,26 +4545,26 @@ ${De()}
|
|
|
4529
4545
|
}
|
|
4530
4546
|
},
|
|
4531
4547
|
);`}).join(`
|
|
4532
|
-
`)}function
|
|
4548
|
+
`)}function Qn(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
4533
4549
|
${JSON.stringify(a)}: {
|
|
4534
4550
|
definition: ${n}.definition,
|
|
4535
4551
|
schema: ${r},
|
|
4536
4552
|
},`}).join(`
|
|
4537
|
-
`)}function
|
|
4553
|
+
`)}function _n(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
4538
4554
|
${JSON.stringify(a)}: {
|
|
4539
4555
|
definition: ${n}.definition,
|
|
4540
4556
|
schema: ${r},
|
|
4541
4557
|
},`}).join(`
|
|
4542
|
-
`)}function
|
|
4543
|
-
`)}function
|
|
4558
|
+
`)}function Kn(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${n}.definition.handler>[1];`}).join(`
|
|
4559
|
+
`)}function Gn(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
4544
4560
|
{
|
|
4545
4561
|
taskName: ${JSON.stringify(r)},
|
|
4546
4562
|
cronTriggers: ${JSON.stringify(a)},
|
|
4547
4563
|
definition: ${n}.definition,
|
|
4548
4564
|
},`}).join(`
|
|
4549
|
-
`)}function
|
|
4565
|
+
`)}function Jn(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4550
4566
|
${t}.definition.handler,`).join(`
|
|
4551
|
-
`)}function
|
|
4567
|
+
`)}function Oe(e){let t=Bn(e);return {imports:Hn(t),operationSchemas:Wn(t),schedulerSchemas:Ln(t),queryRoutes:zn(t),mutationRoutes:Un(t),queryRegistryEntries:Qn(t),schedulerEntries:_n(t),schedulerPayloadMapEntries:Kn(t),cronEntries:Gn(t),storageHandlersEntries:Jn(t)}}var je=`
|
|
4552
4568
|
function getRealtimeStub(
|
|
4553
4569
|
env: Record<string, unknown>,
|
|
4554
4570
|
options: RegisterHandlersOptions,
|
|
@@ -4622,7 +4638,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
4622
4638
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4623
4639
|
return url.toString();
|
|
4624
4640
|
}
|
|
4625
|
-
`;var
|
|
4641
|
+
`;var Ve=`
|
|
4626
4642
|
export class AppflareRealtimeDurableObject {
|
|
4627
4643
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
4628
4644
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -4765,7 +4781,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
4765
4781
|
return new Response("Not found", { status: 404 });
|
|
4766
4782
|
}
|
|
4767
4783
|
}
|
|
4768
|
-
`;var
|
|
4784
|
+
`;var Be=`
|
|
4769
4785
|
async function publishMutationEvents(
|
|
4770
4786
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
4771
4787
|
options: RegisterHandlersOptions,
|
|
@@ -4866,7 +4882,7 @@ async function publishMutationEvents(
|
|
|
4866
4882
|
}
|
|
4867
4883
|
}
|
|
4868
4884
|
}
|
|
4869
|
-
`;var
|
|
4885
|
+
`;var He=`
|
|
4870
4886
|
function registerRealtimeRoutes(
|
|
4871
4887
|
app: Hono<WorkerEnv>,
|
|
4872
4888
|
options: RegisterHandlersOptions,
|
|
@@ -4999,7 +5015,7 @@ function registerRealtimeRoutes(
|
|
|
4999
5015
|
} | null;
|
|
5000
5016
|
return c.json(
|
|
5001
5017
|
{ message: payload?.message ?? "Unable to remove subscription" },
|
|
5002
|
-
response.status,
|
|
5018
|
+
response.status as any,
|
|
5003
5019
|
);
|
|
5004
5020
|
}
|
|
5005
5021
|
|
|
@@ -5029,7 +5045,7 @@ function registerRealtimeRoutes(
|
|
|
5029
5045
|
return stub.fetch(c.req.raw);
|
|
5030
5046
|
});
|
|
5031
5047
|
}
|
|
5032
|
-
`;var
|
|
5048
|
+
`;var We=`
|
|
5033
5049
|
type RealtimeSubscription = {
|
|
5034
5050
|
token: string;
|
|
5035
5051
|
signature: string;
|
|
@@ -5058,7 +5074,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5058
5074
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5059
5075
|
? string
|
|
5060
5076
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5061
|
-
`;var
|
|
5077
|
+
`;var Le=`
|
|
5062
5078
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5063
5079
|
return typeof value === "object" && value !== null;
|
|
5064
5080
|
}
|
|
@@ -5573,9 +5589,9 @@ function doesSubscriptionMatchMutation(
|
|
|
5573
5589
|
|
|
5574
5590
|
return false;
|
|
5575
5591
|
}
|
|
5576
|
-
`;var
|
|
5592
|
+
`;var ze=[We,Le,je,Be,He,Ve].join(`
|
|
5577
5593
|
|
|
5578
|
-
`);var
|
|
5594
|
+
`);var Ue=`
|
|
5579
5595
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
5580
5596
|
if (!value) {
|
|
5581
5597
|
return undefined;
|
|
@@ -5634,7 +5650,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5634
5650
|
}, 200);
|
|
5635
5651
|
} catch (error) {
|
|
5636
5652
|
if (error instanceof AppflareHandledError) {
|
|
5637
|
-
return c.json(error.payload, error.status);
|
|
5653
|
+
return c.json(error.payload, error.status as any);
|
|
5638
5654
|
}
|
|
5639
5655
|
|
|
5640
5656
|
return c.json(
|
|
@@ -5666,7 +5682,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5666
5682
|
}, 200);
|
|
5667
5683
|
} catch (error) {
|
|
5668
5684
|
if (error instanceof AppflareHandledError) {
|
|
5669
|
-
return c.json(error.payload, error.status);
|
|
5685
|
+
return c.json(error.payload, error.status as any);
|
|
5670
5686
|
}
|
|
5671
5687
|
|
|
5672
5688
|
return c.json(
|
|
@@ -5696,7 +5712,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5696
5712
|
}, 200);
|
|
5697
5713
|
} catch (error) {
|
|
5698
5714
|
if (error instanceof AppflareHandledError) {
|
|
5699
|
-
return c.json(error.payload, error.status);
|
|
5715
|
+
return c.json(error.payload, error.status as any);
|
|
5700
5716
|
}
|
|
5701
5717
|
|
|
5702
5718
|
return c.json(
|
|
@@ -5714,7 +5730,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5714
5730
|
return c.json({ ok: true, path }, 200);
|
|
5715
5731
|
} catch (error) {
|
|
5716
5732
|
if (error instanceof AppflareHandledError) {
|
|
5717
|
-
return c.json(error.payload, error.status);
|
|
5733
|
+
return c.json(error.payload, error.status as any);
|
|
5718
5734
|
}
|
|
5719
5735
|
|
|
5720
5736
|
return c.json(
|
|
@@ -5758,7 +5774,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5758
5774
|
return c.json(result, 200);
|
|
5759
5775
|
} catch (error) {
|
|
5760
5776
|
if (error instanceof AppflareHandledError) {
|
|
5761
|
-
return c.json(error.payload, error.status);
|
|
5777
|
+
return c.json(error.payload, error.status as any);
|
|
5762
5778
|
}
|
|
5763
5779
|
|
|
5764
5780
|
return c.json(
|
|
@@ -5768,7 +5784,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5768
5784
|
}
|
|
5769
5785
|
});
|
|
5770
5786
|
}
|
|
5771
|
-
`;var
|
|
5787
|
+
`;var Qe=`
|
|
5772
5788
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
5773
5789
|
? string
|
|
5774
5790
|
: keyof typeof schedulerHandlers;
|
|
@@ -5787,7 +5803,7 @@ export async function executeScheduledBatch(
|
|
|
5787
5803
|
return;
|
|
5788
5804
|
}
|
|
5789
5805
|
|
|
5790
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
5806
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5791
5807
|
|
|
5792
5808
|
for (const message of batch.messages) {
|
|
5793
5809
|
const body = (message?.body ?? {}) as QueueMessageBody;
|
|
@@ -5799,7 +5815,7 @@ export async function executeScheduledBatch(
|
|
|
5799
5815
|
|
|
5800
5816
|
const operation = (schedulerHandlers as Record<string, {
|
|
5801
5817
|
definition: {
|
|
5802
|
-
handler: (ctx:
|
|
5818
|
+
handler: (ctx: AppflareContext, args: unknown) => Promise<void> | void;
|
|
5803
5819
|
};
|
|
5804
5820
|
schema: z.ZodTypeAny;
|
|
5805
5821
|
}>)[task];
|
|
@@ -5823,7 +5839,7 @@ export async function executeScheduledBatch(
|
|
|
5823
5839
|
}
|
|
5824
5840
|
}
|
|
5825
5841
|
}
|
|
5826
|
-
`;var
|
|
5842
|
+
`;var _e=`
|
|
5827
5843
|
export async function executeCronTriggers(
|
|
5828
5844
|
controller: { cron: string },
|
|
5829
5845
|
env: Record<string, unknown>,
|
|
@@ -5834,14 +5850,10 @@ export async function executeCronTriggers(
|
|
|
5834
5850
|
return;
|
|
5835
5851
|
}
|
|
5836
5852
|
|
|
5837
|
-
|
|
5838
|
-
return;
|
|
5839
|
-
}
|
|
5840
|
-
|
|
5841
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
5853
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5842
5854
|
|
|
5843
5855
|
for (const cronEntry of cronHandlers) {
|
|
5844
|
-
if (!cronEntry.cronTriggers.includes(cronValue)) {
|
|
5856
|
+
if (!(cronEntry.cronTriggers as readonly string[]).includes(cronValue)) {
|
|
5845
5857
|
continue;
|
|
5846
5858
|
}
|
|
5847
5859
|
|
|
@@ -5852,7 +5864,7 @@ export async function executeCronTriggers(
|
|
|
5852
5864
|
}
|
|
5853
5865
|
}
|
|
5854
5866
|
}
|
|
5855
|
-
`;function
|
|
5867
|
+
`;function Ke(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:u,storageHandlersEntries:c}=Oe(e);return `import { sValidator } from "@hono/standard-validator";
|
|
5856
5868
|
import type { Hono } from "hono";
|
|
5857
5869
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
5858
5870
|
import { ZodError, z } from "zod";
|
|
@@ -5901,9 +5913,9 @@ const storageHandlers = [${c||`
|
|
|
5901
5913
|
|
|
5902
5914
|
setStorageHandlers([...storageHandlers]);
|
|
5903
5915
|
|
|
5904
|
-
${
|
|
5916
|
+
${Qe}
|
|
5905
5917
|
|
|
5906
|
-
${
|
|
5918
|
+
${ze}
|
|
5907
5919
|
|
|
5908
5920
|
export function registerGeneratedHandlers(
|
|
5909
5921
|
app: Hono<WorkerEnv>,
|
|
@@ -5916,20 +5928,20 @@ export function registerGeneratedHandlers(
|
|
|
5916
5928
|
`}
|
|
5917
5929
|
}
|
|
5918
5930
|
|
|
5919
|
-
${
|
|
5931
|
+
${Ue}
|
|
5920
5932
|
|
|
5921
|
-
${
|
|
5922
|
-
`}function H(e,t,n){let r=
|
|
5923
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
5924
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
5925
|
-
}`}function
|
|
5933
|
+
${_e}
|
|
5934
|
+
`}function H(e,t,n){let r=Fe(e),a=be(n),o=xe(),i=Ke(t);return [{relativePath:"handlers.ts",source:r},{relativePath:"handlers.context.ts",source:a},{relativePath:"handlers.execution.ts",source:o},{relativePath:"handlers.routes.ts",source:i}]}function Zn(e){return e?`,
|
|
5935
|
+
KV: c.env["${e}"] as KVNamespace`:""}function Ge(e,t){return `{
|
|
5936
|
+
DATABASE: c.env["${e}"] as D1Database${Zn(t)}
|
|
5937
|
+
}`}function Je(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
5926
5938
|
const auth = createAuth(
|
|
5927
|
-
${
|
|
5939
|
+
${Ge(t,n)},
|
|
5928
5940
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
5929
5941
|
);
|
|
5930
5942
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
5931
5943
|
});
|
|
5932
|
-
`}function
|
|
5944
|
+
`}function Yn(){return `export const getHeaders = (headers: Headers) => {
|
|
5933
5945
|
const newHeaders = Object.fromEntries(headers as any);
|
|
5934
5946
|
const headerObject: Record<string, any> = {};
|
|
5935
5947
|
let hasCookie = false;
|
|
@@ -5959,15 +5971,15 @@ ${Qe}
|
|
|
5959
5971
|
|
|
5960
5972
|
return headerObject as any as Headers;
|
|
5961
5973
|
};
|
|
5962
|
-
`}function
|
|
5974
|
+
`}function Xn(){return `export const getSanitizedRequest = (req: Request) => {
|
|
5963
5975
|
const newRequest = new Request(req, {
|
|
5964
5976
|
headers: getHeaders(req.headers),
|
|
5965
5977
|
});
|
|
5966
5978
|
return newRequest;
|
|
5967
5979
|
};
|
|
5968
|
-
`}function
|
|
5969
|
-
`+
|
|
5970
|
-
`+
|
|
5980
|
+
`}function Ze(){return Yn()+`
|
|
5981
|
+
`+Xn()}function Ye(e,t,n){return Je(e,t,n)+`
|
|
5982
|
+
`+Ze()}function Xe(){return `const app = new Hono<WorkerEnv>();
|
|
5971
5983
|
|
|
5972
5984
|
app.use('*', cors({
|
|
5973
5985
|
origin: (origin, c) => {
|
|
@@ -5983,7 +5995,7 @@ app.use('*', cors({
|
|
|
5983
5995
|
},
|
|
5984
5996
|
credentials: true
|
|
5985
5997
|
}));
|
|
5986
|
-
`}function
|
|
5998
|
+
`}function et(){return `export { AppflareRealtimeDurableObject };
|
|
5987
5999
|
|
|
5988
6000
|
export default {
|
|
5989
6001
|
fetch: app.fetch,
|
|
@@ -5994,7 +6006,7 @@ export default {
|
|
|
5994
6006
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
5995
6007
|
},
|
|
5996
6008
|
};
|
|
5997
|
-
`}function
|
|
6009
|
+
`}function tt(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",l="appflare.realtime.v1"){let u=t?`
|
|
5998
6010
|
kvBinding: "${t}",`:"",c=r?`
|
|
5999
6011
|
r2Binding: "${r}",`:"",f=`
|
|
6000
6012
|
realtimeBinding: "${a}",
|
|
@@ -6008,16 +6020,16 @@ export default {
|
|
|
6008
6020
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6009
6021
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6010
6022
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6011
|
-
`}function
|
|
6023
|
+
`}function nt(){return `import { createAuth } from "./auth.config";
|
|
6012
6024
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6013
6025
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6014
6026
|
import { Hono } from "hono";
|
|
6015
6027
|
import { cors } from "hono/cors";
|
|
6016
6028
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6017
|
-
`}function
|
|
6029
|
+
`}function rt(){return `type WorkerEnv = {
|
|
6018
6030
|
Bindings: Record<string, unknown>;
|
|
6019
6031
|
};
|
|
6020
|
-
`}function
|
|
6032
|
+
`}function at(e,t,n,r,a,o,i,s,l,u){return nt()+rt()+Xe()+tt(t,n,r,a,o,i,s,l,u)+Ye(e,t,n)+et()}function ot(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function W(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(ot(o)&&ot(a)){n[r]=W(o,a);continue}n[r]=a;}return n}function er(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function it(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=er(t.filter(d=>d.kind==="cron").flatMap(d=>d.cronTriggers??[])),a=e.config.scheduler.enabled&&n.length>0,o=e.config.realtime.enabled,s=(typeof e.config.wranglerOverrides?.name=="string"?e.config.wranglerOverrides.name:void 0)??"appflare-worker",l=e.config.scheduler.queue??`${s}-scheduler`,u={name:s,main:"./src/index.ts",d1_databases:e.config.database.map(d=>({binding:d.binding,database_name:d.databaseName,database_id:d.databaseId,preview_database_id:d.previewDatabaseId??d.databaseId,...d.migrationsDir?{migrations_dir:d.migrationsDir}:{}})),kv_namespaces:e.config.kv.map(d=>({binding:d.binding,id:d.id,...d.previewId?{preview_id:d.previewId}:{}})),r2_buckets:e.config.r2.map(d=>({binding:d.binding,bucket_name:d.bucketName,...d.previewBucketName?{preview_bucket_name:d.previewBucketName}:{},...d.jurisdiction?{jurisdiction:d.jurisdiction}:{}})),...a?{queues:{producers:[{binding:e.config.scheduler.binding,queue:l}],consumers:[{queue:l}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:e.config.realtime.binding,class_name:e.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[e.config.realtime.className]}]}:{}};if(!e.config.wranglerOverrides)return u;let{scheduler:c,...f}=e.config.wranglerOverrides;return W(u,f)}function st(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function lt(e){return `<li data-name="users">
|
|
6021
6033
|
<a href="/admin/users" hx-get="/admin/users" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">
|
|
6022
6034
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6023
6035
|
<span class="truncate">users</span>
|
|
@@ -6029,7 +6041,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6029
6041
|
<span class="truncate">${n.tableName}</span>
|
|
6030
6042
|
</a>
|
|
6031
6043
|
</li>`).join(`
|
|
6032
|
-
`)}`}function
|
|
6044
|
+
`)}`}function ct(e){let t=e.filter(o=>o.kind==="query"),n=e.filter(o=>o.kind==="mutation"),r=t.map(o=>`
|
|
6033
6045
|
<li data-name="${o.exportName}">
|
|
6034
6046
|
<a href="/admin/functions${o.routePath}" hx-get="/admin/functions${o.routePath}" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">
|
|
6035
6047
|
<iconify-icon icon="solar:reorder-linear" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
@@ -6063,7 +6075,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6063
6075
|
<ul class="flex flex-col gap-0.5">${a}</ul>`:""}
|
|
6064
6076
|
</nav>
|
|
6065
6077
|
</div>
|
|
6066
|
-
`}function
|
|
6078
|
+
`}function ut(e){return e.map(t=>`
|
|
6067
6079
|
<a
|
|
6068
6080
|
href="/admin/table/${t.exportName}"
|
|
6069
6081
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6080,9 +6092,9 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6080
6092
|
</div>
|
|
6081
6093
|
</div>
|
|
6082
6094
|
</a>
|
|
6083
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
6095
|
+
`.replace(/\n/g,"\\n")).join("")}function dt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6084
6096
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6085
|
-
`).join("")}function
|
|
6097
|
+
`).join("")}function tr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";default:return "mdi:format-text"}}function pt(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?tr(r.type):"mdi:format-text";return `
|
|
6086
6098
|
<th>
|
|
6087
6099
|
<a href="#"
|
|
6088
6100
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6094,7 +6106,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6094
6106
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6095
6107
|
</a>
|
|
6096
6108
|
</th>
|
|
6097
|
-
`}).join("")}function
|
|
6109
|
+
`}).join("")}function mt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function L(e,t,n){let r=e.columns.find(i=>i.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
6098
6110
|
<div class="form-control">
|
|
6099
6111
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6100
6112
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6177,7 +6189,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6177
6189
|
payload.${n} = raw_${n};
|
|
6178
6190
|
}
|
|
6179
6191
|
`}).join(`
|
|
6180
|
-
`)}function
|
|
6192
|
+
`)}function gt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function ft(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function ht(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function yt(e,t,n,r){return t?`<td class="text-right">
|
|
6181
6193
|
<div class="drawer drawer-end">
|
|
6182
6194
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6183
6195
|
<div class="drawer-content">
|
|
@@ -6263,7 +6275,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6263
6275
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6264
6276
|
hx-target="#main-content"
|
|
6265
6277
|
class="input input-sm md:input-md input-bordered pl-9 w-full md:w-72 bg-base-200/50 border-base-200 focus:bg-base-100 focus:border-primary transition-all text-sm" />
|
|
6266
|
-
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=I(`/admin/table/${e.exportName}`),f=C(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',
|
|
6278
|
+
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=I(`/admin/table/${e.exportName}`),f=C(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',b=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',w=r?`
|
|
6267
6279
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6268
6280
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6269
6281
|
<div class="text-xs text-base-content/70">
|
|
@@ -6398,7 +6410,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6398
6410
|
let countQuery = db.select({ count: sql\`count(*)\` }).from(tableSchema);
|
|
6399
6411
|
|
|
6400
6412
|
if (search) {
|
|
6401
|
-
const searchConditions = [];
|
|
6413
|
+
const searchConditions: any[] = [];
|
|
6402
6414
|
${o}
|
|
6403
6415
|
if (searchConditions.length > 0) {
|
|
6404
6416
|
query = query.where(or(...searchConditions)) as any;
|
|
@@ -6431,7 +6443,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6431
6443
|
<tbody>
|
|
6432
6444
|
\${data.map((row, rowIndex) => html\`
|
|
6433
6445
|
<tr class="hover:bg-base-200/30 transition-colors">
|
|
6434
|
-
${
|
|
6446
|
+
${b}
|
|
6435
6447
|
${s}
|
|
6436
6448
|
${l}
|
|
6437
6449
|
</tr>
|
|
@@ -6515,7 +6527,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6515
6527
|
title: "${e.tableName} - Admin Dashboard",
|
|
6516
6528
|
children: content
|
|
6517
6529
|
}));
|
|
6518
|
-
});`}function
|
|
6530
|
+
});`}function wt(e,t,n,r,a,o,i,s){let l=r==="number"?`
|
|
6519
6531
|
const parsedId = Number(rawId);
|
|
6520
6532
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
6521
6533
|
idValue = parsedId;
|
|
@@ -6595,7 +6607,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6595
6607
|
if (mode === 'all-matching') {
|
|
6596
6608
|
let deleteQuery = db.delete(tableSchema);
|
|
6597
6609
|
if (search) {
|
|
6598
|
-
const searchConditions = [];
|
|
6610
|
+
const searchConditions: any[] = [];
|
|
6599
6611
|
${o}
|
|
6600
6612
|
if (searchConditions.length > 0) {
|
|
6601
6613
|
deleteQuery = deleteQuery.where(or(...searchConditions)) as any;
|
|
@@ -6648,15 +6660,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6648
6660
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
6649
6661
|
});
|
|
6650
6662
|
${c}
|
|
6651
|
-
`}function U(e){let t=
|
|
6652
|
-
`+
|
|
6663
|
+
`}function U(e){let t=gt(e),n=!!t,r=e.columns.map(m=>m.name),a=r.filter(m=>ft(e,m)),o=r.filter(m=>ht(e,m)),i=dt(e),s=pt(e,r),l=mt(r,t),u=a.map(m=>L(e,m,"create")).join(""),c=o.map(m=>L(e,m,"edit")).join(""),f=z(e,a),d=z(e,o),b=n?t:r[0]||"id",w=e.columns.find(m=>m.name===t)?.type,y=yt(e,n,t,c);return bt(e,b,t,n,r,i,s,l,y,u)+`
|
|
6664
|
+
`+wt(e.exportName,b,t,w,n,i,f,d)}function xt(){return `
|
|
6653
6665
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
6654
6666
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
6655
6667
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
6656
6668
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
6657
6669
|
const search = params.search ? params.search : '';
|
|
6658
6670
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
6659
|
-
};`}function
|
|
6671
|
+
};`}function vt(){return `
|
|
6660
6672
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6661
6673
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6662
6674
|
<div class="modal">
|
|
@@ -6677,7 +6689,7 @@ ${c}
|
|
|
6677
6689
|
</div>
|
|
6678
6690
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
6679
6691
|
</div>
|
|
6680
|
-
\`}`}function
|
|
6692
|
+
\`}`}function Tt(){return `
|
|
6681
6693
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6682
6694
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6683
6695
|
<div class="modal">
|
|
@@ -6698,7 +6710,7 @@ ${c}
|
|
|
6698
6710
|
</div>
|
|
6699
6711
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
6700
6712
|
</div>
|
|
6701
|
-
\`}`}var
|
|
6713
|
+
\`}`}var nr=["id","name","email","role","createdAt","banned"],rr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function ar(e){let t=rr[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function Rt(){let e=nr.map(ar).join(`
|
|
6702
6714
|
`),t=I("/admin/users");return `
|
|
6703
6715
|
const tableHtml = html\`
|
|
6704
6716
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
@@ -6767,8 +6779,8 @@ ${c}
|
|
|
6767
6779
|
</div>
|
|
6768
6780
|
</div>
|
|
6769
6781
|
</div>
|
|
6770
|
-
${xt()}
|
|
6771
6782
|
${vt()}
|
|
6783
|
+
${Tt()}
|
|
6772
6784
|
</td>
|
|
6773
6785
|
</tr>
|
|
6774
6786
|
\`)}
|
|
@@ -6784,7 +6796,7 @@ ${vt()}
|
|
|
6784
6796
|
${t}
|
|
6785
6797
|
</div>
|
|
6786
6798
|
\`;
|
|
6787
|
-
`}function
|
|
6799
|
+
`}function kt(){return `
|
|
6788
6800
|
const content = html\`
|
|
6789
6801
|
<div id="main-content">
|
|
6790
6802
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -6800,7 +6812,7 @@ ${vt()}
|
|
|
6800
6812
|
</div>
|
|
6801
6813
|
\${tableHtml}
|
|
6802
6814
|
</div>
|
|
6803
|
-
\`;`}function
|
|
6815
|
+
\`;`}function St(){let e=Rt(),t=kt();return `
|
|
6804
6816
|
adminApp.get('/users', async (c) => {
|
|
6805
6817
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
6806
6818
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -6856,7 +6868,7 @@ ${vt()}
|
|
|
6856
6868
|
title: "users - Admin Dashboard",
|
|
6857
6869
|
children: content,
|
|
6858
6870
|
}));
|
|
6859
|
-
});`}function
|
|
6871
|
+
});`}function At(){return `
|
|
6860
6872
|
adminApp.post('/users/edit', async (c) => {
|
|
6861
6873
|
const session = await requireAdminSession(c);
|
|
6862
6874
|
if (!session) {
|
|
@@ -7000,7 +7012,7 @@ ${vt()}
|
|
|
7000
7012
|
|
|
7001
7013
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7002
7014
|
});`}function Q(){return `
|
|
7003
|
-
${
|
|
7015
|
+
${xt()}
|
|
7004
7016
|
|
|
7005
7017
|
const requireAdminSession = async (c: any) => {
|
|
7006
7018
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7011,12 +7023,12 @@ ${vt()}
|
|
|
7011
7023
|
return session;
|
|
7012
7024
|
};
|
|
7013
7025
|
|
|
7014
|
-
${kt()}
|
|
7015
|
-
|
|
7016
7026
|
${St()}
|
|
7017
|
-
|
|
7027
|
+
|
|
7028
|
+
${At()}
|
|
7029
|
+
`}function Nt(e){return `${e.tables.map(t=>U(t)).join(`
|
|
7018
7030
|
`)}
|
|
7019
|
-
${Q()}`}function
|
|
7031
|
+
${Q()}`}function $t(e){return `
|
|
7020
7032
|
<div class="flex items-center justify-between">
|
|
7021
7033
|
<div class="flex items-center gap-3">
|
|
7022
7034
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7031,9 +7043,9 @@ ${Q()}`}function Nt(e){return `
|
|
|
7031
7043
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7032
7044
|
</div>
|
|
7033
7045
|
</div>
|
|
7034
|
-
`}function
|
|
7046
|
+
`}function or(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function ir(e){let t=e.args??[];return t.length===0?`
|
|
7035
7047
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7036
|
-
`:t.map(n=>{let r=
|
|
7048
|
+
`:t.map(n=>{let r=or(n.type),a=r==="checkbox",o=`${n.name}${n.optional?"":" *"}`,i=n.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${n.type}</span>`:"";return a?`
|
|
7037
7049
|
<div class="flex items-center gap-3 py-1">
|
|
7038
7050
|
<input
|
|
7039
7051
|
type="checkbox"
|
|
@@ -7062,7 +7074,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7062
7074
|
/>
|
|
7063
7075
|
</div>
|
|
7064
7076
|
`}).join(`
|
|
7065
|
-
`)}function
|
|
7077
|
+
`)}function sr(e){return `
|
|
7066
7078
|
<div class="space-y-4">
|
|
7067
7079
|
<div class="flex items-center justify-between">
|
|
7068
7080
|
<div class="flex flex-col">
|
|
@@ -7075,11 +7087,11 @@ ${Q()}`}function Nt(e){return `
|
|
|
7075
7087
|
</label>
|
|
7076
7088
|
</div>
|
|
7077
7089
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7078
|
-
${
|
|
7090
|
+
${ir(e)}
|
|
7079
7091
|
</div>
|
|
7080
7092
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7081
7093
|
</div>
|
|
7082
|
-
`}function
|
|
7094
|
+
`}function lr(){return `
|
|
7083
7095
|
<div class="space-y-4">
|
|
7084
7096
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7085
7097
|
<div class="relative group">
|
|
@@ -7096,7 +7108,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7096
7108
|
</div>
|
|
7097
7109
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7098
7110
|
</div>
|
|
7099
|
-
`}function
|
|
7111
|
+
`}function cr(){return `
|
|
7100
7112
|
<div class="space-y-4">
|
|
7101
7113
|
<div class="flex items-center justify-between">
|
|
7102
7114
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7110,7 +7122,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7110
7122
|
</div>
|
|
7111
7123
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7112
7124
|
</div>
|
|
7113
|
-
`}function
|
|
7125
|
+
`}function qt(e){return `
|
|
7114
7126
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7115
7127
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7116
7128
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7131,13 +7143,13 @@ ${Q()}`}function Nt(e){return `
|
|
|
7131
7143
|
<!-- Tab Content -->
|
|
7132
7144
|
<div class="flex-1 overflow-y-auto">
|
|
7133
7145
|
<div id="request-tab-args" class="p-5">
|
|
7134
|
-
${
|
|
7146
|
+
${sr(e)}
|
|
7135
7147
|
</div>
|
|
7136
7148
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7137
|
-
${
|
|
7149
|
+
${lr()}
|
|
7138
7150
|
</div>
|
|
7139
7151
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7140
|
-
${
|
|
7152
|
+
${cr()}
|
|
7141
7153
|
</div>
|
|
7142
7154
|
</div>
|
|
7143
7155
|
|
|
@@ -7155,7 +7167,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7155
7167
|
</form>
|
|
7156
7168
|
</div>
|
|
7157
7169
|
</div>
|
|
7158
|
-
`}function
|
|
7170
|
+
`}function It(){return `
|
|
7159
7171
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7160
7172
|
<!-- Panel Header -->
|
|
7161
7173
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7237,7 +7249,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7237
7249
|
|
|
7238
7250
|
</div>
|
|
7239
7251
|
</div>
|
|
7240
|
-
`}function
|
|
7252
|
+
`}function Ct(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7241
7253
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7242
7254
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7243
7255
|
|
|
@@ -7779,21 +7791,21 @@ ${Q()}`}function Nt(e){return `
|
|
|
7779
7791
|
_rtEnabled = false;
|
|
7780
7792
|
});
|
|
7781
7793
|
</script>
|
|
7782
|
-
`}function
|
|
7794
|
+
`}function Mt(e){return `
|
|
7783
7795
|
const content = html\`
|
|
7784
7796
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
7785
|
-
${
|
|
7797
|
+
${$t(e)}
|
|
7786
7798
|
|
|
7787
7799
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
7788
7800
|
<!-- Request Panel -->
|
|
7789
|
-
${
|
|
7801
|
+
${qt(e)}
|
|
7790
7802
|
|
|
7791
7803
|
<!-- Result Panel -->
|
|
7792
|
-
${
|
|
7804
|
+
${It()}
|
|
7793
7805
|
</div>
|
|
7794
7806
|
</div>
|
|
7795
7807
|
|
|
7796
|
-
${
|
|
7808
|
+
${Ct(e)}
|
|
7797
7809
|
\`;
|
|
7798
7810
|
|
|
7799
7811
|
if (c.req.header('hx-request')) {
|
|
@@ -7803,11 +7815,11 @@ ${Q()}`}function Nt(e){return `
|
|
|
7803
7815
|
return c.html(Layout({
|
|
7804
7816
|
title: "${e.exportName} - Functions",
|
|
7805
7817
|
children: content
|
|
7806
|
-
}));`}function
|
|
7818
|
+
}));`}function Pt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
7807
7819
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
7808
|
-
${
|
|
7820
|
+
${Mt(n)}
|
|
7809
7821
|
});`).join(`
|
|
7810
|
-
`)}function
|
|
7822
|
+
`)}function Et(){return `
|
|
7811
7823
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
7812
7824
|
const r2Binding = (options as any).r2Binding;
|
|
7813
7825
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -7879,7 +7891,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7879
7891
|
`}function Dt(){return `
|
|
7880
7892
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
7881
7893
|
const parts = prefix.split('/').filter(Boolean);
|
|
7882
|
-
const breadcrumbs = [];
|
|
7894
|
+
const breadcrumbs: any[] = [];
|
|
7883
7895
|
let currentPath = '';
|
|
7884
7896
|
const visibleObjects = listed.objects.filter((obj: any) => !obj.key.endsWith('/.keep'));
|
|
7885
7897
|
|
|
@@ -8003,7 +8015,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8003
8015
|
</div>
|
|
8004
8016
|
\`;
|
|
8005
8017
|
};
|
|
8006
|
-
`}function
|
|
8018
|
+
`}function Ft(){return `
|
|
8007
8019
|
const handleStorageListRoute = async (c: any) => {
|
|
8008
8020
|
const bucket = getStorageBucket(c);
|
|
8009
8021
|
if (!bucket) {
|
|
@@ -8025,7 +8037,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8025
8037
|
|
|
8026
8038
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8027
8039
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8028
|
-
`}function
|
|
8040
|
+
`}function Ot(){return `
|
|
8029
8041
|
adminApp.post('/storage/upload', async (c) => {
|
|
8030
8042
|
const bucket = getStorageBucket(c);
|
|
8031
8043
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8043,7 +8055,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8043
8055
|
|
|
8044
8056
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8045
8057
|
});
|
|
8046
|
-
`}function
|
|
8058
|
+
`}function jt(){return `
|
|
8047
8059
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8048
8060
|
const bucket = getStorageBucket(c);
|
|
8049
8061
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8058,7 +8070,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8058
8070
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8059
8071
|
return c.html('');
|
|
8060
8072
|
});
|
|
8061
|
-
`}function
|
|
8073
|
+
`}function Vt(){return `
|
|
8062
8074
|
adminApp.post('/storage/directory', async (c) => {
|
|
8063
8075
|
const bucket = getStorageBucket(c);
|
|
8064
8076
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8084,7 +8096,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8084
8096
|
|
|
8085
8097
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8086
8098
|
});
|
|
8087
|
-
`}function
|
|
8099
|
+
`}function Bt(){return `
|
|
8088
8100
|
adminApp.get('/storage/download', async (c) => {
|
|
8089
8101
|
const bucket = getStorageBucket(c);
|
|
8090
8102
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8104,7 +8116,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8104
8116
|
|
|
8105
8117
|
return new Response(object.body, { headers });
|
|
8106
8118
|
});
|
|
8107
|
-
`}function
|
|
8119
|
+
`}function Ht(){return `
|
|
8108
8120
|
adminApp.get('/storage/preview', async (c) => {
|
|
8109
8121
|
const bucket = getStorageBucket(c);
|
|
8110
8122
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8122,25 +8134,25 @@ ${Q()}`}function Nt(e){return `
|
|
|
8122
8134
|
|
|
8123
8135
|
return new Response(object.body, { headers });
|
|
8124
8136
|
});
|
|
8125
|
-
`}function
|
|
8126
|
-
${Vt()}
|
|
8127
|
-
|
|
8137
|
+
`}function Wt(){return `
|
|
8128
8138
|
${Bt()}
|
|
8129
8139
|
|
|
8130
|
-
${
|
|
8140
|
+
${Ht()}
|
|
8131
8141
|
|
|
8132
8142
|
${Ot()}
|
|
8133
8143
|
|
|
8134
8144
|
${jt()}
|
|
8135
8145
|
|
|
8146
|
+
${Vt()}
|
|
8147
|
+
|
|
8148
|
+
${Ft()}
|
|
8149
|
+
`}function Lt(){return `
|
|
8136
8150
|
${Et()}
|
|
8137
|
-
`}function Wt(){return `
|
|
8138
|
-
${Pt()}
|
|
8139
8151
|
|
|
8140
8152
|
${Dt()}
|
|
8141
8153
|
|
|
8142
|
-
${
|
|
8143
|
-
`}function
|
|
8154
|
+
${Wt()}
|
|
8155
|
+
`}function zt(e,t){let n=ct(t);return `
|
|
8144
8156
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8145
8157
|
return html\`<!DOCTYPE html>
|
|
8146
8158
|
<html lang="en" data-theme="light">
|
|
@@ -8515,7 +8527,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8515
8527
|
</body>
|
|
8516
8528
|
</html>\`;
|
|
8517
8529
|
}
|
|
8518
|
-
`}function
|
|
8530
|
+
`}function Ut(){return `
|
|
8519
8531
|
// Auth Middleware
|
|
8520
8532
|
adminApp.use('*', async (c, next) => {
|
|
8521
8533
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -8574,7 +8586,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8574
8586
|
}
|
|
8575
8587
|
await next();
|
|
8576
8588
|
});
|
|
8577
|
-
`}function
|
|
8589
|
+
`}function Qt(e){return `
|
|
8578
8590
|
adminApp.get('/', (c) => {
|
|
8579
8591
|
return c.html(Layout({
|
|
8580
8592
|
title: "Admin Dashboard",
|
|
@@ -8591,7 +8603,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8591
8603
|
\`
|
|
8592
8604
|
}));
|
|
8593
8605
|
});
|
|
8594
|
-
`}function
|
|
8606
|
+
`}function _t(e,t,n){let r=st(t),a=lt(r),o=ut(r),i=Nt(t),s=Pt(n),l=Lt(),u=zt(a,n),c=Ut(),f=Qt(o);return `import { Hono } from "hono";
|
|
8595
8607
|
import { html, raw } from "hono/html";
|
|
8596
8608
|
import { drizzle } from "drizzle-orm/d1";
|
|
8597
8609
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8620,8 +8632,8 @@ ${f}
|
|
|
8620
8632
|
app.route('/admin', adminApp);
|
|
8621
8633
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8622
8634
|
}
|
|
8623
|
-
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function M(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function
|
|
8624
|
-
`}function
|
|
8635
|
+
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function M(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function E(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function J(e){return e.endsWith("ies")?`${e.slice(0,-3)}y`:e.endsWith("ses")?e.slice(0,-2):e.endsWith("s")&&e.length>1?e.slice(0,-1):e}function h(e){return JSON.stringify(e)}function dr(e){if(typeof e=="string")return h(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return h(e.toISOString());throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, or Date.`)}function pr(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([t,n])=>[t,{kind:"table",sqlName:n.sqlName,columns:Object.fromEntries(Object.entries(n.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(n.relations).map(([r,a])=>[r,{...a}]))}]))}}function P(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function Kt(e,t,n,r,a,o,i){let s=t.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);t.columns[n]={...s,notNull:s.notNull??(s.nullable===true?false:o.notNull),nullable:s.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:s.references?.onDelete??o.onDelete,onUpdate:s.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??i,sqlName:o.sqlName,notNull:o.notNull??true,nullable:o.notNull===false?true:void 0,references:{table:r,column:a,onDelete:o.onDelete,onUpdate:o.onUpdate}};}function Gt(e,t,n){if(t.notNull===true&&t.nullable===true)throw new Error(`Invalid nullable configuration on '${e}': cannot set both notNull and nullable to true.`);return t.notNull===true?true:t.nullable===true||t.notNull===false?false:n}function Jt(e,t){return `${e}:${t}`}function mr(e,t,n,r){let a=Jt(e,t),o=Jt(n,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:t,rightTable:n,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:n,leftReferenceField:r,rightTable:e,rightReferenceField:t,sourceIsLeft:false}}function gr(e,t){return `${e}${E(t)}Links`}function Zt(e,t,n){let r=J(e),a=J(t);return r===a?`${n}${E(r)}Id`:`${r}Id`}function fr(e,t,n){if(e.junctionTable!==t.junctionTable)throw new Error(`manyToMany pair '${n}' has conflicting junctionTable values ('${e.junctionTable}' vs '${t.junctionTable}').`);if(e.leftField!==t.leftField)throw new Error(`manyToMany pair '${n}' has conflicting left field values ('${e.leftField}' vs '${t.leftField}').`);if(e.rightField!==t.rightField)throw new Error(`manyToMany pair '${n}' has conflicting right field values ('${e.rightField}' vs '${t.rightField}').`);if(e.leftSqlName!==t.leftSqlName)throw new Error(`manyToMany pair '${n}' has conflicting left sql name values ('${e.leftSqlName}' vs '${t.leftSqlName}').`);if(e.rightSqlName!==t.rightSqlName)throw new Error(`manyToMany pair '${n}' has conflicting right sql name values ('${e.rightSqlName}' vs '${t.rightSqlName}').`);if(e.onDelete!==t.onDelete)throw new Error(`manyToMany pair '${n}' has conflicting onDelete values ('${e.onDelete}' vs '${t.onDelete}').`);if(e.onUpdate!==t.onUpdate)throw new Error(`manyToMany pair '${n}' has conflicting onUpdate values ('${e.onUpdate}' vs '${t.onUpdate}').`);return e}function hr(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",i=a.targetReferenceField??"id",s=mr(n,o,a.targetTable,i),l=Zt(s.leftTable,s.rightTable,"source"),u=Zt(s.rightTable,s.leftTable,"target"),c={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??gr(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??l:a.targetField??l,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(c.leftField===c.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${c.leftField}'. Set sourceField/targetField explicitly.`);let f=t.get(s.key);f?fr(f,c,s.key):t.set(s.key,c),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=c.junctionTable,a.sourceField=s.sourceIsLeft?c.leftField:c.rightField,a.targetField=s.sourceIsLeft?c.rightField:c.leftField,a.sourceSqlName=s.sourceIsLeft?c.leftSqlName:c.rightSqlName,a.targetSqlName=s.sourceIsLeft?c.rightSqlName:c.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=P(e,n.leftTable,n.leftReferenceField)??"string",a=P(e,n.rightTable,n.rightReferenceField)??"string";e.tables[n.junctionTable]={kind:"table",columns:{[n.leftField]:{kind:"column",type:r,sqlName:n.leftSqlName,notNull:true,nullable:false,references:{table:n.leftTable,column:n.leftReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true},[n.rightField]:{kind:"column",type:a,sqlName:n.rightSqlName,notNull:true,nullable:false,references:{table:n.rightTable,column:n.rightReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true}},relations:{[n.leftTable]:{kind:"relation",relation:"one",targetTable:n.leftTable,field:n.leftField,referenceField:n.leftReferenceField},[n.rightTable]:{kind:"relation",relation:"one",targetTable:n.rightTable,field:n.rightField,referenceField:n.rightReferenceField}}};}}function yr(e){for(let[t,n]of Object.entries(e.tables)){for(let[r,a]of Object.entries(n.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(n.relations))if(a.relation!=="manyToMany"&&a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`)}}function br(e){yr(e);let t=pr(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let l=P(t,o.targetTable,i)??o.fkType??"string";Kt(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:Gt(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${J(n)}Id`;a.field=s;let l=P(t,n,i)??a.fkType??"string";Kt(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:Gt(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return hr(t),t}function Xt(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function $(e){return e.notNull!==true}function wr(e,t,n){let r=t.sqlName??M(e),a=r!==e;return t.type==="int"?a?`t.int(${h(r)})`:"t.int()":t.type==="string"?t.length!==void 0?a?`t.text(${h(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${h(r)})`:"t.text()":t.type==="boolean"?a?`t.int(${h(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })':t.type==="date"?a?`t.int(${h(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })':n==="camelToSnake"&&a?`t.text(${h(r)})`:"t.text()"}function xr(e,t,n){let r=n.field,a=n.referenceField??"id";if(!r)throw new Error(`Relation on '${e}' targeting '${n.targetTable}' is missing a local field.`);if(!(r in t.columns))throw new Error(`Relation '${e}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function vr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
8636
|
+
`}function Tr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Rr(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function kr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${h(o)}: {
|
|
8625
8637
|
targetTable: ${h(i.targetTable)},
|
|
8626
8638
|
junctionTable: ${h(i.junctionTable)},
|
|
8627
8639
|
sourceField: ${h(i.sourceField??"")},
|
|
@@ -8634,7 +8646,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8634
8646
|
${t.map(n=>` ${n}`).join(`
|
|
8635
8647
|
`)}
|
|
8636
8648
|
} as const;
|
|
8637
|
-
`}function
|
|
8649
|
+
`}function Sr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations)){if(i.relation==="one"){a.push(`${h(o)}: {
|
|
8638
8650
|
kind: "one",
|
|
8639
8651
|
targetTable: ${h(i.targetTable)},
|
|
8640
8652
|
sourceField: ${h(i.field??"")},
|
|
@@ -8660,7 +8672,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8660
8672
|
${t.map(n=>` ${n}`).join(`
|
|
8661
8673
|
`)}
|
|
8662
8674
|
} as const;
|
|
8663
|
-
`}function
|
|
8675
|
+
`}function Ar(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of Tr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??M(i),u=[],c=[];for(let[y,m]of Object.entries(s.columns)){let x=wr(y,m,t);m.uuidPrimaryKey&&(x+=".$defaultFn(() => crypto.randomUUID())"),m.primaryKey&&(x+=m.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),m.notNull&&(x+=".notNull()"),m.sqlDefault!==void 0&&(x+=`.default(${dr(m.sqlDefault)})`);let T=Rr(y,m,s);if(T)if(m.references?.onDelete||m.references?.onUpdate){let R=[];m.references.onDelete&&R.push(`onDelete: ${h(m.references.onDelete)}`),m.references.onUpdate&&R.push(`onUpdate: ${h(m.references.onUpdate)}`),x+=`.references(() => ${T.tableName}.${T.fieldName}, { ${R.join(", ")} })`;}else x+=`.references(() => ${T.tableName}.${T.fieldName})`;if(m.unique){let R=typeof m.unique=="object"&&m.unique.name?m.unique.name:`${l}_${M(y)}_unique_idx`;c.push(` t.uniqueIndex(${h(R)}).on(table.${y})`);}if(m.index){let R=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${M(y)}_idx`;c.push(` t.index(${h(R)}).on(table.${y})`);}u.push(` ${y}: ${x},`);}c.length>0?a.push(`export const ${i} = table(
|
|
8664
8676
|
${h(l)},
|
|
8665
8677
|
{
|
|
8666
8678
|
${u.join(`
|
|
@@ -8673,16 +8685,16 @@ ${c.join(`,
|
|
|
8673
8685
|
);`):a.push(`export const ${i} = table(${h(l)}, {
|
|
8674
8686
|
${u.join(`
|
|
8675
8687
|
`)}
|
|
8676
|
-
});`);let f=Object.entries(s.relations).filter(([,
|
|
8688
|
+
});`);let f=Object.entries(s.relations).filter(([,y])=>y.relation==="one"),d=Object.entries(s.relations).filter(([,y])=>y.relation==="many"),b=Object.entries(s.relations).filter(([,y])=>y.relation==="manyToMany");if(f.length===0&&d.length===0&&b.length===0)continue;let w=[];for(let[y,m]of f){let x=xr(i,s,m);w.push(` ${y}: one(${m.targetTable}, {
|
|
8677
8689
|
fields: [${i}.${x.sourceField}],
|
|
8678
8690
|
references: [${m.targetTable}.${x.targetField}],
|
|
8679
|
-
}),`);}for(let[
|
|
8691
|
+
}),`);}for(let[y,m]of d)w.push(` ${y}: many(${m.targetTable}),`);for(let[y,m]of b){if(!m.junctionTable)throw new Error(`manyToMany relation '${i}.${y}' is missing junctionTable after normalization.`);w.push(` ${y}: many(${m.junctionTable}),`);}o.push(`export const ${i}Relations = relations(${i}, ({ one, many }) => ({
|
|
8680
8692
|
${w.join(`
|
|
8681
8693
|
`)}
|
|
8682
8694
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
8683
8695
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
8684
8696
|
import { relations } from "drizzle-orm";
|
|
8685
|
-
${
|
|
8697
|
+
${vr(r)}
|
|
8686
8698
|
${a.join(`
|
|
8687
8699
|
|
|
8688
8700
|
`)}
|
|
@@ -8691,10 +8703,10 @@ ${o.join(`
|
|
|
8691
8703
|
|
|
8692
8704
|
`)}
|
|
8693
8705
|
|
|
8694
|
-
${
|
|
8706
|
+
${kr(e)}
|
|
8695
8707
|
|
|
8696
|
-
${
|
|
8697
|
-
`}function
|
|
8708
|
+
${Sr(e)}
|
|
8709
|
+
`}function Yt(e,t,n){let r="z.unknown()";return e.type==="int"?r="z.number().int()":e.type==="string"?(r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`)):e.type==="boolean"?r="z.boolean()":e.type==="date"&&(r="z.date()"),t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Nr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=E(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns))o.push(` ${s}: ${Yt(l,Xt(l),$(l))},`),i.push(` ${s}: ${Yt(l,$(l),$(l))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
8698
8710
|
${o.join(`
|
|
8699
8711
|
`)}
|
|
8700
8712
|
});
|
|
@@ -8708,7 +8720,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
8708
8720
|
`);}return `import { z } from "zod";
|
|
8709
8721
|
|
|
8710
8722
|
${t.join(`
|
|
8711
|
-
`)}`}function
|
|
8723
|
+
`)}`}function $r(e){return e.type==="int"?"number":e.type==="string"?"string":e.type==="boolean"?"boolean":e.type==="date"?"Date":"unknown"}function qr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=E(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns)){let u=$r(l),c=$(l)?" | null":"";o.push(` ${s}${$(l)?"?":""}: ${u}${c};`),i.push(` ${s}${Xt(l)?"?":""}: ${u}${c};`);}t.push(`export type ${a} = {
|
|
8712
8724
|
${o.join(`
|
|
8713
8725
|
`)}
|
|
8714
8726
|
};
|
|
@@ -8719,11 +8731,11 @@ ${i.join(`
|
|
|
8719
8731
|
};`);}return `${t.join(`
|
|
8720
8732
|
|
|
8721
8733
|
`)}
|
|
8722
|
-
`}function $r(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Xt(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=$r(l,t.exportName),c=hr(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=kr(c,n),d=Nr(c),y=Sr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=new Set([".ts",".tsx",".mts",".cts"]);async function rn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await rn(a));continue}r.isFile()&&Dr.has(extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Er(e,t){let n=e,r=false,a,o="unknown";for(;g.isCallExpression(n);){let i=n.expression;if(!g.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function Fr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Er(r.initializer,r.name.text));return n}function Or(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function an(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?an(e.expression):null}function jr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Vr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Or(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.isCallExpression(o.initializer))continue;let i=an(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?jr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Fr(o.initializer.arguments[0]):[]});}return r}function en(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Br(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function tn(e,t){let n=e.replace(/\\/g,"/"),a=Z(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function on(e){let t=[],n=await rn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),l=Vr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Br(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?tn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?tn(f,d.exportName):void 0,b=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?en("queries",f,d.exportName):c.kind==="mutation"?en("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:y,clientSegments:b,taskName:w,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function Wr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Lr(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return l}}return -1}function zr(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function Ur(e){let t=Wr(e),n=[];for(let r of t){let a=Lr(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:zr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Qr(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(f){f=false;continue}if(y==="\\"){f=true;continue}if(!u&&!c&&y==="'"){l=!l;continue}if(!l&&!c&&y==='"'){u=!u;continue}if(!l&&!u&&y==="`"){c=!c;continue}if(!(l||u||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:Ur(u)}),a=t.exec(e);}return n}async function ln(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await ln(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function cn(e,t=[]){let n=await ln(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),l=Qr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function _r(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function un(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),y=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),b=await Xt(e),m=await cn(e,b?[b.schemaPath]:[]),x=A(t,m.schemaPath),v=await on(e),R=rt(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),xn=le(l,v),vn=H(x,v,r.r2[0]?.binding),Tn=te(i),Rn=b?[_r(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,kn=ce(Rn),Sn=ot(e,v),An=Qt(x,m,v),Nn=resolve(t,"admin.routes.ts"),$n=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),qn=xn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8723
|
-
`),...qn
|
|
8724
|
-
`),Bun.write(Nn
|
|
8734
|
+
`}function Ir(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function en(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=Ir(l,t.exportName),c=br(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=Ar(c,n),d=qr(c),b=Nr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,b)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Mr(e){return e.replaceAll("\\","/")}function A(e,t){let n=Mr(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Fr=new Set([".ts",".tsx",".mts",".cts"]);async function an(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await an(a));continue}r.isFile()&&Fr.has(extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Or(e,t){let n=e,r=false,a,o="unknown";for(;g.isCallExpression(n);){let i=n.expression;if(!g.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function jr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Or(r.initializer,r.name.text));return n}function Vr(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function on(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?on(e.expression):null}function Br(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Hr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Vr(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.isCallExpression(o.initializer))continue;let i=on(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?Br(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?jr(o.initializer.arguments[0]):[]});}return r}function tn(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Wr(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function nn(e,t){let n=e.replace(/\\/g,"/"),a=Z(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function sn(e){let t=[],n=await an(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),l=Hr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Wr(s,c.kindDirectory);for(let d of c.exports){let b=c.kind==="query"||c.kind==="mutation"?nn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?nn(f,d.exportName):void 0,y=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?tn("queries",f,d.exportName):c.kind==="mutation"?tn("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:b,clientSegments:y,taskName:w,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function zr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let b=n.trim();b.length>0&&t.push(b),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Ur(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return l}}return -1}function Qr(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function _r(e){let t=zr(e),n=[];for(let r of t){let a=Ur(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:Qr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Kr(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let b=o[d];if(f){f=false;continue}if(b==="\\"){f=true;continue}if(!u&&!c&&b==="'"){l=!l;continue}if(!l&&!c&&b==='"'){u=!u;continue}if(!l&&!u&&b==="`"){c=!c;continue}if(!(l||u||c)){if(b==="{"){s+=1;continue}if(b==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:_r(u)}),a=t.exec(e);}return n}async function cn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await cn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function un(e,t=[]){let n=await cn(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),l=Kr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Jr(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function dn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),b=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),y=await en(e),m=await un(e,y?[y.schemaPath]:[]),x=A(t,m.schemaPath),T=await sn(e),R=at(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),vn=ce(l,T),Tn=H(x,T,r.r2[0]?.binding),Rn=ne(i),kn=y?[Jr(o,y.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,Sn=ue(kn),An=it(e,T),Nn=_t(x,m,T),$n=resolve(t,"admin.routes.ts"),qn=Tn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),In=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8735
|
+
`),...In,...qn,Bun.write(f,Rn),Bun.write(d,""),Bun.write(b,Sn),Bun.write(w,`${JSON.stringify(An,null,2)}
|
|
8736
|
+
`),Bun.write($n,Nn)]);let O=relative(o,f).replace(/\\/g,"/"),Cn=O.startsWith(".")?O:`./${O}`,j=relative(o,d).replace(/\\/g,"/"),Mn=j.startsWith(".")?j:`./${j}`,ee=await Bun.spawn(["npx","@better-auth/cli","generate","--config",Cn,"--output",Mn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ee!==0)throw new Error(`better-auth generation failed with exit code ${ee}`);let Pn=resolve(o,"tsconfig.json");if(existsSync(Pn)){let k=process.platform==="win32"?"npx.cmd":"npx",te=await Bun.spawn([k,"tsc","--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(te!==0)throw new Error(`TypeScript build failed with exit code ${te}`)}}var pn=z$1.object({binding:z$1.string().min(1),databaseName:z$1.string().min(1),databaseId:z$1.string().min(1),previewDatabaseId:z$1.string().min(1).optional(),migrationsDir:z$1.string().min(1).optional()}).strict(),mn=z$1.object({binding:z$1.string().min(1),id:z$1.string().min(1),previewId:z$1.string().min(1).optional()}).strict(),gn=z$1.object({binding:z$1.string().min(1),bucketName:z$1.string().min(1),previewBucketName:z$1.string().min(1).optional(),jurisdiction:z$1.string().min(1).optional()}).strict(),fn=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),queue:z$1.string().min(1).optional()}).strict(),ea=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),className:z$1.string().min(1).optional(),objectName:z$1.string().min(1).optional(),subscribePath:z$1.string().min(1).optional(),websocketPath:z$1.string().min(1).optional(),protocol:z$1.string().min(1).optional()}).strict(),ta=z$1.object({scanDir:z$1.string().min(1),outDir:z$1.string().min(1),wranglerOutDir:z$1.string().min(1).optional(),wranglerOutPath:z$1.string().min(1).optional(),schema:z$1.array(z$1.string()).min(1),schemaDsl:z$1.object({entry:z$1.string().min(1),exportName:z$1.string().min(1).optional(),outFile:z$1.string().min(1).optional(),typesOutFile:z$1.string().min(1).optional(),zodOutFile:z$1.string().min(1).optional(),namingStrategy:z$1.literal("camelToSnake").optional()}).strict().optional(),database:z$1.union([pn,z$1.array(pn).min(1)]),kv:z$1.union([mn,z$1.array(mn)]).optional(),r2:z$1.union([gn,z$1.array(gn)]).optional(),auth:z$1.object({enabled:z$1.boolean(),basePath:z$1.string().min(1),options:z$1.custom(e=>typeof e=="object"&&e!==null),clientOptions:z$1.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:fn.optional(),realtime:ea.optional(),wranglerOverrides:z$1.record(z$1.string(),z$1.unknown()).optional()}).strict();function hn(e){return typeof e=="object"&&e!==null}function na(e){let t=hn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=fn.safeParse(t);return n.success?n.data:{}}function ra(e){if(!hn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function aa(e){let n={...na(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:ra(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir}}async function q(e){let t=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=ta.parse(o),s=aa(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function la(e){let t=e;for(;;){if(existsSync(resolve(t,"package.json")))return t;let n=dirname(t);if(n===t)return e;t=n;}}async function F(e){let t=await q(e);if(await dn(t),t.wranglerOutDirAbs===t.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${t.outDirAbs}
|
|
8725
8737
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${t.outDirAbs} and wrangler.json in ${t.wranglerOutDirAbs}
|
|
8726
8738
|
`);}async function bn(e,t=false){if(await F(e),!t)return;let n=await q(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await F(e);}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
8727
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
8739
|
+
`);}finally{r=false,a&&(a=false,await o());}};oa.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8728
8740
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8729
|
-
`);}async function
|
|
8741
|
+
`);}async function wn(e,t={}){let n=await q(e),r=la(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=resolve(n.outDirAbs,"drizzle.config.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function xn(e,t={name:"",email:"",password:""}){let n=await q(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").action(async e=>{await F(e.config);});N.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).action(async e=>{await bn(e.config,e.watch);});N.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await wn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});N.command("add-admin").description("Add an admin user to the database").requiredOption("-n, --name <name>","Admin's display name").requiredOption("-e, --email <email>","Admin's email address").requiredOption("-p, --password <password>","Admin's password").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute command against a local DB for use with wrangler dev",false).option("--remote","Execute command against a remote DB for use with wrangler dev --remote",false).action(async e=>{await xn(e.config,{name:e.name,email:e.email,password:e.password,local:e.local,remote:e.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await N.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|