appflare 0.2.19 → 0.2.21
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/commands/index.ts +11 -5
- package/cli/generate.ts +18 -0
- package/cli/index.ts +9 -5
- package/cli/load-config.ts +2 -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/registration/modules/cron.ts +1 -5
- package/cli/templates/handlers/generators/registration/modules/realtime/routes.ts +1 -1
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +1 -1
- package/cli/templates/handlers/generators/registration/modules/storage.ts +5 -5
- package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +2 -6
- package/cli/types.ts +2 -0
- package/dist/cli/index.d.mts +2 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +173 -181
- package/dist/cli/index.mjs +173 -181
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
2
|
+
'use strict';var commander=require('commander'),oa=require('chokidar'),fs=require('fs'),path=require('path'),promises=require('fs/promises'),url=require('url'),g=require('typescript'),zod=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var oa__default=/*#__PURE__*/_interopDefault(oa);var g__namespace=/*#__PURE__*/_interopNamespace(g);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,7 +1353,7 @@ function createStorageApi(
|
|
|
1353
1353
|
},
|
|
1354
1354
|
};
|
|
1355
1355
|
}
|
|
1356
|
-
`}function
|
|
1356
|
+
`}function be(e){return `
|
|
1357
1357
|
export async function createSchedulerExecutionContext(
|
|
1358
1358
|
env: Record<string, unknown>,
|
|
1359
1359
|
options: RegisterHandlersOptions,
|
|
@@ -1451,7 +1451,7 @@ export async function createExecutionContext(
|
|
|
1451
1451
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1452
1452
|
return ctx;
|
|
1453
1453
|
}
|
|
1454
|
-
`}function
|
|
1454
|
+
`}function ye(e){return `import type { Context } from "hono";
|
|
1455
1455
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1456
1456
|
import { createAuth } from "./auth.config";
|
|
1457
1457
|
import {
|
|
@@ -1470,20 +1470,20 @@ import {
|
|
|
1470
1470
|
createQueryDb,
|
|
1471
1471
|
} from "./handlers";
|
|
1472
1472
|
|
|
1473
|
-
${de()}
|
|
1474
|
-
|
|
1475
|
-
${ue()}
|
|
1476
|
-
|
|
1477
1473
|
${pe()}
|
|
1478
1474
|
|
|
1475
|
+
${de()}
|
|
1476
|
+
|
|
1479
1477
|
${me()}
|
|
1480
1478
|
|
|
1481
1479
|
${ge()}
|
|
1482
1480
|
|
|
1483
1481
|
${fe()}
|
|
1484
1482
|
|
|
1485
|
-
${he(
|
|
1486
|
-
|
|
1483
|
+
${he()}
|
|
1484
|
+
|
|
1485
|
+
${be(e)}
|
|
1486
|
+
`}function we(){return `
|
|
1487
1487
|
export async function executeOperation(
|
|
1488
1488
|
c: Context<WorkerEnv>,
|
|
1489
1489
|
operation: RegisteredOperation<ZodRawShape, unknown>,
|
|
@@ -1509,7 +1509,7 @@ export function handleOperationError(
|
|
|
1509
1509
|
validationMessage: string,
|
|
1510
1510
|
): Response {
|
|
1511
1511
|
if (error instanceof AppflareHandledError) {
|
|
1512
|
-
return c.json(error.payload, error.status);
|
|
1512
|
+
return c.json(error.payload, error.status as any);
|
|
1513
1513
|
}
|
|
1514
1514
|
|
|
1515
1515
|
if (error instanceof ZodError) {
|
|
@@ -1519,7 +1519,7 @@ export function handleOperationError(
|
|
|
1519
1519
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1520
1520
|
}
|
|
1521
1521
|
|
|
1522
|
-
`}function
|
|
1522
|
+
`}function xe(){return `import type { Context } from "hono";
|
|
1523
1523
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1524
1524
|
import {
|
|
1525
1525
|
type AppflareContext,
|
|
@@ -1528,8 +1528,8 @@ import {
|
|
|
1528
1528
|
type WorkerEnv,
|
|
1529
1529
|
} from "./handlers";
|
|
1530
1530
|
|
|
1531
|
-
${
|
|
1532
|
-
`}function
|
|
1531
|
+
${we()}
|
|
1532
|
+
`}function ve(){return `import { betterAuth } from "better-auth";
|
|
1533
1533
|
import { auth } from "./auth.config";
|
|
1534
1534
|
import {
|
|
1535
1535
|
and,
|
|
@@ -1632,7 +1632,7 @@ export async function isStorageAllowed(
|
|
|
1632
1632
|
|
|
1633
1633
|
return false;
|
|
1634
1634
|
}
|
|
1635
|
-
`}function
|
|
1635
|
+
`}function Te(){return `type Primitive = string | number | boolean | Date;
|
|
1636
1636
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1637
1637
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1638
1638
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1888,7 +1888,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1888
1888
|
where?: WhereInput<TableModel<TName>>;
|
|
1889
1889
|
limit?: number;
|
|
1890
1890
|
};
|
|
1891
|
-
`}function
|
|
1891
|
+
`}function Re(){return `type AggregateWithInput<TName extends TableName> =
|
|
1892
1892
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1893
1893
|
|
|
1894
1894
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2020,7 +2020,7 @@ export type DbMutationEvent = {
|
|
|
2020
2020
|
export type QueryDbOptions = {
|
|
2021
2021
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2022
2022
|
};
|
|
2023
|
-
`}function
|
|
2023
|
+
`}function ke(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2024
2024
|
return typeof value === "object" && value !== null;
|
|
2025
2025
|
}
|
|
2026
2026
|
|
|
@@ -2502,11 +2502,7 @@ function hasManyToManyRelationsInWith(
|
|
|
2502
2502
|
}
|
|
2503
2503
|
|
|
2504
2504
|
const nestedWith = relationValue.with;
|
|
2505
|
-
if (
|
|
2506
|
-
hasManyToManyRelationsInWith(relationName, nestedWith) ||
|
|
2507
|
-
(manyToMany &&
|
|
2508
|
-
hasManyToManyRelationsInWith(manyToMany.targetTable, nestedWith))
|
|
2509
|
-
) {
|
|
2505
|
+
if (hasManyToManyRelationsInWith(relationName, nestedWith)) {
|
|
2510
2506
|
return true;
|
|
2511
2507
|
}
|
|
2512
2508
|
}
|
|
@@ -2598,7 +2594,7 @@ type RelationWithAggregatePlan = Record<string, RelationWithAggregatePlanEntry>;
|
|
|
2598
2594
|
|
|
2599
2595
|
function hasRelationAggregatePlanEntries(
|
|
2600
2596
|
plan: RelationWithAggregatePlan | undefined,
|
|
2601
|
-
):
|
|
2597
|
+
): plan is RelationWithAggregatePlan {
|
|
2602
2598
|
return !!plan && Object.keys(plan).length > 0;
|
|
2603
2599
|
}
|
|
2604
2600
|
|
|
@@ -3052,7 +3048,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3052
3048
|
|
|
3053
3049
|
return [];
|
|
3054
3050
|
}
|
|
3055
|
-
`}function
|
|
3051
|
+
`}function Se(){return `const mergedSchema = {
|
|
3056
3052
|
...authSchema,
|
|
3057
3053
|
...schema,
|
|
3058
3054
|
};
|
|
@@ -3295,9 +3291,9 @@ type TableFindFirstResult<
|
|
|
3295
3291
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3296
3292
|
(typeof mergedSchema)[TName]
|
|
3297
3293
|
>;
|
|
3298
|
-
`}function
|
|
3294
|
+
`}function Ae(){return [Se(),Te(),Re(),ke()].join(`
|
|
3299
3295
|
|
|
3300
|
-
`)}function
|
|
3296
|
+
`)}function Ne(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3301
3297
|
const withValue = args?.with;
|
|
3302
3298
|
const pathSegments = args?.field
|
|
3303
3299
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3468,7 +3464,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3468
3464
|
},
|
|
3469
3465
|
}) as AppflareQueryDb;
|
|
3470
3466
|
}
|
|
3471
|
-
`}function
|
|
3467
|
+
`}function $e(){return `export class AppflareHandledError extends Error {
|
|
3472
3468
|
public readonly status: number;
|
|
3473
3469
|
public readonly payload: unknown;
|
|
3474
3470
|
|
|
@@ -3478,7 +3474,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3478
3474
|
this.payload = payload;
|
|
3479
3475
|
}
|
|
3480
3476
|
}
|
|
3481
|
-
`}function
|
|
3477
|
+
`}function qe(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3482
3478
|
const where = isRecord(args?.where)
|
|
3483
3479
|
? (args?.where as Record<string, unknown>)
|
|
3484
3480
|
: undefined;
|
|
@@ -3596,7 +3592,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3596
3592
|
);
|
|
3597
3593
|
});
|
|
3598
3594
|
},
|
|
3599
|
-
`}function
|
|
3595
|
+
`}function Ie(){return `export function createQueryDb(
|
|
3600
3596
|
$db: AppflareDb,
|
|
3601
3597
|
options?: QueryDbOptions,
|
|
3602
3598
|
): AppflareQueryDb {
|
|
@@ -3638,7 +3634,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3638
3634
|
};
|
|
3639
3635
|
|
|
3640
3636
|
const tableApi = {
|
|
3641
|
-
`}function
|
|
3637
|
+
`}function Ce(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
3642
3638
|
const transaction = ($db as any).transaction;
|
|
3643
3639
|
|
|
3644
3640
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -4311,9 +4307,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4311
4307
|
);
|
|
4312
4308
|
return rows;
|
|
4313
4309
|
},
|
|
4314
|
-
`}function
|
|
4310
|
+
`}function Me(){return [Ie(),qe(),Ce(),Ne(),$e()].join(`
|
|
4315
4311
|
|
|
4316
|
-
`)}function
|
|
4312
|
+
`)}function Pe(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4317
4313
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4318
4314
|
type User = AuthSession['user']
|
|
4319
4315
|
type Session = AuthSession['session']
|
|
@@ -4376,7 +4372,7 @@ export type AppflareContext = {
|
|
|
4376
4372
|
storage: AppflareStorage;
|
|
4377
4373
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4378
4374
|
};
|
|
4379
|
-
`}function
|
|
4375
|
+
`}function Ee(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4380
4376
|
|
|
4381
4377
|
export type SchedulerEnqueueOptions = {
|
|
4382
4378
|
delaySeconds?: number;
|
|
@@ -4508,9 +4504,9 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4508
4504
|
definition,
|
|
4509
4505
|
};
|
|
4510
4506
|
}
|
|
4511
|
-
`}function De(){return [
|
|
4507
|
+
`}function De(){return [ve(),Ae(),Me(),Pe(),Ee()].join(`
|
|
4512
4508
|
|
|
4513
|
-
`)}function
|
|
4509
|
+
`)}function Fe(e){return `import type { Context } from "hono";
|
|
4514
4510
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4515
4511
|
import { drizzle } from "drizzle-orm/d1";
|
|
4516
4512
|
import { z, type ZodRawShape } from "zod";
|
|
@@ -4518,10 +4514,10 @@ import * as authSchema from "./auth.schema";
|
|
|
4518
4514
|
import * as schema from "${e}";
|
|
4519
4515
|
|
|
4520
4516
|
${De()}
|
|
4521
|
-
`}function
|
|
4522
|
-
`)}function
|
|
4523
|
-
`)}function
|
|
4524
|
-
`)}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 `
|
|
4525
4521
|
app.get(
|
|
4526
4522
|
"${t.routePath}",
|
|
4527
4523
|
sValidator("query", ${r}),
|
|
@@ -4534,7 +4530,7 @@ ${De()}
|
|
|
4534
4530
|
}
|
|
4535
4531
|
},
|
|
4536
4532
|
);`}).join(`
|
|
4537
|
-
`)}function
|
|
4533
|
+
`)}function Un(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4538
4534
|
app.post(
|
|
4539
4535
|
"${t.routePath}",
|
|
4540
4536
|
sValidator("json", ${r}),
|
|
@@ -4549,26 +4545,26 @@ ${De()}
|
|
|
4549
4545
|
}
|
|
4550
4546
|
},
|
|
4551
4547
|
);`}).join(`
|
|
4552
|
-
`)}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 `
|
|
4553
4549
|
${JSON.stringify(a)}: {
|
|
4554
4550
|
definition: ${n}.definition,
|
|
4555
4551
|
schema: ${r},
|
|
4556
4552
|
},`}).join(`
|
|
4557
|
-
`)}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 `
|
|
4558
4554
|
${JSON.stringify(a)}: {
|
|
4559
4555
|
definition: ${n}.definition,
|
|
4560
4556
|
schema: ${r},
|
|
4561
4557
|
},`}).join(`
|
|
4562
|
-
`)}function
|
|
4563
|
-
`)}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 `
|
|
4564
4560
|
{
|
|
4565
4561
|
taskName: ${JSON.stringify(r)},
|
|
4566
4562
|
cronTriggers: ${JSON.stringify(a)},
|
|
4567
4563
|
definition: ${n}.definition,
|
|
4568
4564
|
},`}).join(`
|
|
4569
|
-
`)}function
|
|
4565
|
+
`)}function Jn(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4570
4566
|
${t}.definition.handler,`).join(`
|
|
4571
|
-
`)}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=`
|
|
4572
4568
|
function getRealtimeStub(
|
|
4573
4569
|
env: Record<string, unknown>,
|
|
4574
4570
|
options: RegisterHandlersOptions,
|
|
@@ -4642,7 +4638,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
4642
4638
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4643
4639
|
return url.toString();
|
|
4644
4640
|
}
|
|
4645
|
-
`;var
|
|
4641
|
+
`;var Ve=`
|
|
4646
4642
|
export class AppflareRealtimeDurableObject {
|
|
4647
4643
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
4648
4644
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -4785,7 +4781,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
4785
4781
|
return new Response("Not found", { status: 404 });
|
|
4786
4782
|
}
|
|
4787
4783
|
}
|
|
4788
|
-
`;var
|
|
4784
|
+
`;var Be=`
|
|
4789
4785
|
async function publishMutationEvents(
|
|
4790
4786
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
4791
4787
|
options: RegisterHandlersOptions,
|
|
@@ -4886,7 +4882,7 @@ async function publishMutationEvents(
|
|
|
4886
4882
|
}
|
|
4887
4883
|
}
|
|
4888
4884
|
}
|
|
4889
|
-
`;var
|
|
4885
|
+
`;var He=`
|
|
4890
4886
|
function registerRealtimeRoutes(
|
|
4891
4887
|
app: Hono<WorkerEnv>,
|
|
4892
4888
|
options: RegisterHandlersOptions,
|
|
@@ -5019,7 +5015,7 @@ function registerRealtimeRoutes(
|
|
|
5019
5015
|
} | null;
|
|
5020
5016
|
return c.json(
|
|
5021
5017
|
{ message: payload?.message ?? "Unable to remove subscription" },
|
|
5022
|
-
response.status,
|
|
5018
|
+
response.status as any,
|
|
5023
5019
|
);
|
|
5024
5020
|
}
|
|
5025
5021
|
|
|
@@ -5049,7 +5045,7 @@ function registerRealtimeRoutes(
|
|
|
5049
5045
|
return stub.fetch(c.req.raw);
|
|
5050
5046
|
});
|
|
5051
5047
|
}
|
|
5052
|
-
`;var
|
|
5048
|
+
`;var We=`
|
|
5053
5049
|
type RealtimeSubscription = {
|
|
5054
5050
|
token: string;
|
|
5055
5051
|
signature: string;
|
|
@@ -5078,7 +5074,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5078
5074
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5079
5075
|
? string
|
|
5080
5076
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5081
|
-
`;var
|
|
5077
|
+
`;var Le=`
|
|
5082
5078
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5083
5079
|
return typeof value === "object" && value !== null;
|
|
5084
5080
|
}
|
|
@@ -5593,9 +5589,9 @@ function doesSubscriptionMatchMutation(
|
|
|
5593
5589
|
|
|
5594
5590
|
return false;
|
|
5595
5591
|
}
|
|
5596
|
-
`;var
|
|
5592
|
+
`;var ze=[We,Le,je,Be,He,Ve].join(`
|
|
5597
5593
|
|
|
5598
|
-
`);var
|
|
5594
|
+
`);var Ue=`
|
|
5599
5595
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
5600
5596
|
if (!value) {
|
|
5601
5597
|
return undefined;
|
|
@@ -5654,7 +5650,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5654
5650
|
}, 200);
|
|
5655
5651
|
} catch (error) {
|
|
5656
5652
|
if (error instanceof AppflareHandledError) {
|
|
5657
|
-
return c.json(error.payload, error.status);
|
|
5653
|
+
return c.json(error.payload, error.status as any);
|
|
5658
5654
|
}
|
|
5659
5655
|
|
|
5660
5656
|
return c.json(
|
|
@@ -5686,7 +5682,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5686
5682
|
}, 200);
|
|
5687
5683
|
} catch (error) {
|
|
5688
5684
|
if (error instanceof AppflareHandledError) {
|
|
5689
|
-
return c.json(error.payload, error.status);
|
|
5685
|
+
return c.json(error.payload, error.status as any);
|
|
5690
5686
|
}
|
|
5691
5687
|
|
|
5692
5688
|
return c.json(
|
|
@@ -5716,7 +5712,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5716
5712
|
}, 200);
|
|
5717
5713
|
} catch (error) {
|
|
5718
5714
|
if (error instanceof AppflareHandledError) {
|
|
5719
|
-
return c.json(error.payload, error.status);
|
|
5715
|
+
return c.json(error.payload, error.status as any);
|
|
5720
5716
|
}
|
|
5721
5717
|
|
|
5722
5718
|
return c.json(
|
|
@@ -5734,7 +5730,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5734
5730
|
return c.json({ ok: true, path }, 200);
|
|
5735
5731
|
} catch (error) {
|
|
5736
5732
|
if (error instanceof AppflareHandledError) {
|
|
5737
|
-
return c.json(error.payload, error.status);
|
|
5733
|
+
return c.json(error.payload, error.status as any);
|
|
5738
5734
|
}
|
|
5739
5735
|
|
|
5740
5736
|
return c.json(
|
|
@@ -5778,7 +5774,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5778
5774
|
return c.json(result, 200);
|
|
5779
5775
|
} catch (error) {
|
|
5780
5776
|
if (error instanceof AppflareHandledError) {
|
|
5781
|
-
return c.json(error.payload, error.status);
|
|
5777
|
+
return c.json(error.payload, error.status as any);
|
|
5782
5778
|
}
|
|
5783
5779
|
|
|
5784
5780
|
return c.json(
|
|
@@ -5788,7 +5784,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5788
5784
|
}
|
|
5789
5785
|
});
|
|
5790
5786
|
}
|
|
5791
|
-
`;var
|
|
5787
|
+
`;var Qe=`
|
|
5792
5788
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
5793
5789
|
? string
|
|
5794
5790
|
: keyof typeof schedulerHandlers;
|
|
@@ -5819,7 +5815,7 @@ export async function executeScheduledBatch(
|
|
|
5819
5815
|
|
|
5820
5816
|
const operation = (schedulerHandlers as Record<string, {
|
|
5821
5817
|
definition: {
|
|
5822
|
-
handler: (ctx:
|
|
5818
|
+
handler: (ctx: AppflareContext, args: unknown) => Promise<void> | void;
|
|
5823
5819
|
};
|
|
5824
5820
|
schema: z.ZodTypeAny;
|
|
5825
5821
|
}>)[task];
|
|
@@ -5843,7 +5839,7 @@ export async function executeScheduledBatch(
|
|
|
5843
5839
|
}
|
|
5844
5840
|
}
|
|
5845
5841
|
}
|
|
5846
|
-
`;var
|
|
5842
|
+
`;var _e=`
|
|
5847
5843
|
export async function executeCronTriggers(
|
|
5848
5844
|
controller: { cron: string },
|
|
5849
5845
|
env: Record<string, unknown>,
|
|
@@ -5854,14 +5850,10 @@ export async function executeCronTriggers(
|
|
|
5854
5850
|
return;
|
|
5855
5851
|
}
|
|
5856
5852
|
|
|
5857
|
-
if (cronHandlers.length === 0) {
|
|
5858
|
-
return;
|
|
5859
|
-
}
|
|
5860
|
-
|
|
5861
5853
|
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5862
5854
|
|
|
5863
5855
|
for (const cronEntry of cronHandlers) {
|
|
5864
|
-
if (!cronEntry.cronTriggers.includes(cronValue)) {
|
|
5856
|
+
if (!(cronEntry.cronTriggers as readonly string[]).includes(cronValue)) {
|
|
5865
5857
|
continue;
|
|
5866
5858
|
}
|
|
5867
5859
|
|
|
@@ -5872,7 +5864,7 @@ export async function executeCronTriggers(
|
|
|
5872
5864
|
}
|
|
5873
5865
|
}
|
|
5874
5866
|
}
|
|
5875
|
-
`;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";
|
|
5876
5868
|
import type { Hono } from "hono";
|
|
5877
5869
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
5878
5870
|
import { ZodError, z } from "zod";
|
|
@@ -5921,9 +5913,9 @@ const storageHandlers = [${c||`
|
|
|
5921
5913
|
|
|
5922
5914
|
setStorageHandlers([...storageHandlers]);
|
|
5923
5915
|
|
|
5924
|
-
${
|
|
5916
|
+
${Qe}
|
|
5925
5917
|
|
|
5926
|
-
${
|
|
5918
|
+
${ze}
|
|
5927
5919
|
|
|
5928
5920
|
export function registerGeneratedHandlers(
|
|
5929
5921
|
app: Hono<WorkerEnv>,
|
|
@@ -5936,20 +5928,20 @@ export function registerGeneratedHandlers(
|
|
|
5936
5928
|
`}
|
|
5937
5929
|
}
|
|
5938
5930
|
|
|
5939
|
-
${
|
|
5931
|
+
${Ue}
|
|
5940
5932
|
|
|
5941
|
-
${
|
|
5942
|
-
`}function H(e,t,n){let r=
|
|
5943
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
5944
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
5945
|
-
}`}function
|
|
5933
|
+
${_e}
|
|
5934
|
+
`}function H(e,t,n){let r=Fe(e),a=ye(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) => {
|
|
5946
5938
|
const auth = createAuth(
|
|
5947
|
-
${
|
|
5939
|
+
${Ge(t,n)},
|
|
5948
5940
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
5949
5941
|
);
|
|
5950
5942
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
5951
5943
|
});
|
|
5952
|
-
`}function
|
|
5944
|
+
`}function Yn(){return `export const getHeaders = (headers: Headers) => {
|
|
5953
5945
|
const newHeaders = Object.fromEntries(headers as any);
|
|
5954
5946
|
const headerObject: Record<string, any> = {};
|
|
5955
5947
|
let hasCookie = false;
|
|
@@ -5979,15 +5971,15 @@ ${Qe}
|
|
|
5979
5971
|
|
|
5980
5972
|
return headerObject as any as Headers;
|
|
5981
5973
|
};
|
|
5982
|
-
`}function
|
|
5974
|
+
`}function Xn(){return `export const getSanitizedRequest = (req: Request) => {
|
|
5983
5975
|
const newRequest = new Request(req, {
|
|
5984
5976
|
headers: getHeaders(req.headers),
|
|
5985
5977
|
});
|
|
5986
5978
|
return newRequest;
|
|
5987
5979
|
};
|
|
5988
|
-
`}function
|
|
5989
|
-
`+
|
|
5990
|
-
`+
|
|
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>();
|
|
5991
5983
|
|
|
5992
5984
|
app.use('*', cors({
|
|
5993
5985
|
origin: (origin, c) => {
|
|
@@ -6003,7 +5995,7 @@ app.use('*', cors({
|
|
|
6003
5995
|
},
|
|
6004
5996
|
credentials: true
|
|
6005
5997
|
}));
|
|
6006
|
-
`}function
|
|
5998
|
+
`}function et(){return `export { AppflareRealtimeDurableObject };
|
|
6007
5999
|
|
|
6008
6000
|
export default {
|
|
6009
6001
|
fetch: app.fetch,
|
|
@@ -6014,7 +6006,7 @@ export default {
|
|
|
6014
6006
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6015
6007
|
},
|
|
6016
6008
|
};
|
|
6017
|
-
`}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?`
|
|
6018
6010
|
kvBinding: "${t}",`:"",c=r?`
|
|
6019
6011
|
r2Binding: "${r}",`:"",f=`
|
|
6020
6012
|
realtimeBinding: "${a}",
|
|
@@ -6028,16 +6020,16 @@ export default {
|
|
|
6028
6020
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6029
6021
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6030
6022
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6031
|
-
`}function
|
|
6023
|
+
`}function nt(){return `import { createAuth } from "./auth.config";
|
|
6032
6024
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6033
6025
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6034
6026
|
import { Hono } from "hono";
|
|
6035
6027
|
import { cors } from "hono/cors";
|
|
6036
6028
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6037
|
-
`}function
|
|
6029
|
+
`}function rt(){return `type WorkerEnv = {
|
|
6038
6030
|
Bindings: Record<string, unknown>;
|
|
6039
6031
|
};
|
|
6040
|
-
`}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">
|
|
6041
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">
|
|
6042
6034
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6043
6035
|
<span class="truncate">users</span>
|
|
@@ -6049,7 +6041,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6049
6041
|
<span class="truncate">${n.tableName}</span>
|
|
6050
6042
|
</a>
|
|
6051
6043
|
</li>`).join(`
|
|
6052
|
-
`)}`}function
|
|
6044
|
+
`)}`}function ct(e){let t=e.filter(o=>o.kind==="query"),n=e.filter(o=>o.kind==="mutation"),r=t.map(o=>`
|
|
6053
6045
|
<li data-name="${o.exportName}">
|
|
6054
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">
|
|
6055
6047
|
<iconify-icon icon="solar:reorder-linear" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
@@ -6083,7 +6075,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6083
6075
|
<ul class="flex flex-col gap-0.5">${a}</ul>`:""}
|
|
6084
6076
|
</nav>
|
|
6085
6077
|
</div>
|
|
6086
|
-
`}function
|
|
6078
|
+
`}function ut(e){return e.map(t=>`
|
|
6087
6079
|
<a
|
|
6088
6080
|
href="/admin/table/${t.exportName}"
|
|
6089
6081
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6100,9 +6092,9 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6100
6092
|
</div>
|
|
6101
6093
|
</div>
|
|
6102
6094
|
</a>
|
|
6103
|
-
`.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=>`
|
|
6104
6096
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6105
|
-
`).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 `
|
|
6106
6098
|
<th>
|
|
6107
6099
|
<a href="#"
|
|
6108
6100
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6114,7 +6106,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6114
6106
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6115
6107
|
</a>
|
|
6116
6108
|
</th>
|
|
6117
|
-
`}).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"?`
|
|
6118
6110
|
<div class="form-control">
|
|
6119
6111
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6120
6112
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6197,7 +6189,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6197
6189
|
payload.${n} = raw_${n};
|
|
6198
6190
|
}
|
|
6199
6191
|
`}).join(`
|
|
6200
|
-
`)}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 bt(e,t,n,r){return t?`<td class="text-right">
|
|
6201
6193
|
<div class="drawer drawer-end">
|
|
6202
6194
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6203
6195
|
<div class="drawer-content">
|
|
@@ -6283,7 +6275,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6283
6275
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6284
6276
|
hx-target="#main-content"
|
|
6285
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" />
|
|
6286
|
-
</div>`}function
|
|
6278
|
+
</div>`}function yt(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>',y=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?`
|
|
6287
6279
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6288
6280
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6289
6281
|
<div class="text-xs text-base-content/70">
|
|
@@ -6418,7 +6410,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6418
6410
|
let countQuery = db.select({ count: sql\`count(*)\` }).from(tableSchema);
|
|
6419
6411
|
|
|
6420
6412
|
if (search) {
|
|
6421
|
-
const searchConditions = [];
|
|
6413
|
+
const searchConditions: any[] = [];
|
|
6422
6414
|
${o}
|
|
6423
6415
|
if (searchConditions.length > 0) {
|
|
6424
6416
|
query = query.where(or(...searchConditions)) as any;
|
|
@@ -6535,7 +6527,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6535
6527
|
title: "${e.tableName} - Admin Dashboard",
|
|
6536
6528
|
children: content
|
|
6537
6529
|
}));
|
|
6538
|
-
});`}function
|
|
6530
|
+
});`}function wt(e,t,n,r,a,o,i,s){let l=r==="number"?`
|
|
6539
6531
|
const parsedId = Number(rawId);
|
|
6540
6532
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
6541
6533
|
idValue = parsedId;
|
|
@@ -6615,7 +6607,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6615
6607
|
if (mode === 'all-matching') {
|
|
6616
6608
|
let deleteQuery = db.delete(tableSchema);
|
|
6617
6609
|
if (search) {
|
|
6618
|
-
const searchConditions = [];
|
|
6610
|
+
const searchConditions: any[] = [];
|
|
6619
6611
|
${o}
|
|
6620
6612
|
if (searchConditions.length > 0) {
|
|
6621
6613
|
deleteQuery = deleteQuery.where(or(...searchConditions)) as any;
|
|
@@ -6668,15 +6660,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6668
6660
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
6669
6661
|
});
|
|
6670
6662
|
${c}
|
|
6671
|
-
`}function U(e){let t=
|
|
6672
|
-
`+
|
|
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),y=n?t:r[0]||"id",w=e.columns.find(m=>m.name===t)?.type,b=bt(e,n,t,c);return yt(e,y,t,n,r,i,s,l,b,u)+`
|
|
6664
|
+
`+wt(e.exportName,y,t,w,n,i,f,d)}function xt(){return `
|
|
6673
6665
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
6674
6666
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
6675
6667
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
6676
6668
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
6677
6669
|
const search = params.search ? params.search : '';
|
|
6678
6670
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
6679
|
-
};`}function
|
|
6671
|
+
};`}function vt(){return `
|
|
6680
6672
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6681
6673
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6682
6674
|
<div class="modal">
|
|
@@ -6697,7 +6689,7 @@ ${c}
|
|
|
6697
6689
|
</div>
|
|
6698
6690
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
6699
6691
|
</div>
|
|
6700
|
-
\`}`}function
|
|
6692
|
+
\`}`}function Tt(){return `
|
|
6701
6693
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6702
6694
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6703
6695
|
<div class="modal">
|
|
@@ -6718,7 +6710,7 @@ ${c}
|
|
|
6718
6710
|
</div>
|
|
6719
6711
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
6720
6712
|
</div>
|
|
6721
|
-
\`}`}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(`
|
|
6722
6714
|
`),t=I("/admin/users");return `
|
|
6723
6715
|
const tableHtml = html\`
|
|
6724
6716
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
@@ -6787,8 +6779,8 @@ ${c}
|
|
|
6787
6779
|
</div>
|
|
6788
6780
|
</div>
|
|
6789
6781
|
</div>
|
|
6790
|
-
${xt()}
|
|
6791
6782
|
${vt()}
|
|
6783
|
+
${Tt()}
|
|
6792
6784
|
</td>
|
|
6793
6785
|
</tr>
|
|
6794
6786
|
\`)}
|
|
@@ -6804,7 +6796,7 @@ ${vt()}
|
|
|
6804
6796
|
${t}
|
|
6805
6797
|
</div>
|
|
6806
6798
|
\`;
|
|
6807
|
-
`}function
|
|
6799
|
+
`}function kt(){return `
|
|
6808
6800
|
const content = html\`
|
|
6809
6801
|
<div id="main-content">
|
|
6810
6802
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -6820,7 +6812,7 @@ ${vt()}
|
|
|
6820
6812
|
</div>
|
|
6821
6813
|
\${tableHtml}
|
|
6822
6814
|
</div>
|
|
6823
|
-
\`;`}function
|
|
6815
|
+
\`;`}function St(){let e=Rt(),t=kt();return `
|
|
6824
6816
|
adminApp.get('/users', async (c) => {
|
|
6825
6817
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
6826
6818
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -6876,7 +6868,7 @@ ${vt()}
|
|
|
6876
6868
|
title: "users - Admin Dashboard",
|
|
6877
6869
|
children: content,
|
|
6878
6870
|
}));
|
|
6879
|
-
});`}function
|
|
6871
|
+
});`}function At(){return `
|
|
6880
6872
|
adminApp.post('/users/edit', async (c) => {
|
|
6881
6873
|
const session = await requireAdminSession(c);
|
|
6882
6874
|
if (!session) {
|
|
@@ -7020,7 +7012,7 @@ ${vt()}
|
|
|
7020
7012
|
|
|
7021
7013
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7022
7014
|
});`}function Q(){return `
|
|
7023
|
-
${
|
|
7015
|
+
${xt()}
|
|
7024
7016
|
|
|
7025
7017
|
const requireAdminSession = async (c: any) => {
|
|
7026
7018
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7031,12 +7023,12 @@ ${vt()}
|
|
|
7031
7023
|
return session;
|
|
7032
7024
|
};
|
|
7033
7025
|
|
|
7034
|
-
${kt()}
|
|
7035
|
-
|
|
7036
7026
|
${St()}
|
|
7037
|
-
|
|
7027
|
+
|
|
7028
|
+
${At()}
|
|
7029
|
+
`}function Nt(e){return `${e.tables.map(t=>U(t)).join(`
|
|
7038
7030
|
`)}
|
|
7039
|
-
${Q()}`}function
|
|
7031
|
+
${Q()}`}function $t(e){return `
|
|
7040
7032
|
<div class="flex items-center justify-between">
|
|
7041
7033
|
<div class="flex items-center gap-3">
|
|
7042
7034
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7051,9 +7043,9 @@ ${Q()}`}function Nt(e){return `
|
|
|
7051
7043
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7052
7044
|
</div>
|
|
7053
7045
|
</div>
|
|
7054
|
-
`}function
|
|
7046
|
+
`}function or(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function ir(e){let t=e.args??[];return t.length===0?`
|
|
7055
7047
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7056
|
-
`: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?`
|
|
7057
7049
|
<div class="flex items-center gap-3 py-1">
|
|
7058
7050
|
<input
|
|
7059
7051
|
type="checkbox"
|
|
@@ -7082,7 +7074,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7082
7074
|
/>
|
|
7083
7075
|
</div>
|
|
7084
7076
|
`}).join(`
|
|
7085
|
-
`)}function
|
|
7077
|
+
`)}function sr(e){return `
|
|
7086
7078
|
<div class="space-y-4">
|
|
7087
7079
|
<div class="flex items-center justify-between">
|
|
7088
7080
|
<div class="flex flex-col">
|
|
@@ -7095,11 +7087,11 @@ ${Q()}`}function Nt(e){return `
|
|
|
7095
7087
|
</label>
|
|
7096
7088
|
</div>
|
|
7097
7089
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7098
|
-
${
|
|
7090
|
+
${ir(e)}
|
|
7099
7091
|
</div>
|
|
7100
7092
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7101
7093
|
</div>
|
|
7102
|
-
`}function
|
|
7094
|
+
`}function lr(){return `
|
|
7103
7095
|
<div class="space-y-4">
|
|
7104
7096
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7105
7097
|
<div class="relative group">
|
|
@@ -7116,7 +7108,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7116
7108
|
</div>
|
|
7117
7109
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7118
7110
|
</div>
|
|
7119
|
-
`}function
|
|
7111
|
+
`}function cr(){return `
|
|
7120
7112
|
<div class="space-y-4">
|
|
7121
7113
|
<div class="flex items-center justify-between">
|
|
7122
7114
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7130,7 +7122,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7130
7122
|
</div>
|
|
7131
7123
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7132
7124
|
</div>
|
|
7133
|
-
`}function
|
|
7125
|
+
`}function qt(e){return `
|
|
7134
7126
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7135
7127
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7136
7128
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7151,13 +7143,13 @@ ${Q()}`}function Nt(e){return `
|
|
|
7151
7143
|
<!-- Tab Content -->
|
|
7152
7144
|
<div class="flex-1 overflow-y-auto">
|
|
7153
7145
|
<div id="request-tab-args" class="p-5">
|
|
7154
|
-
${
|
|
7146
|
+
${sr(e)}
|
|
7155
7147
|
</div>
|
|
7156
7148
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7157
|
-
${
|
|
7149
|
+
${lr()}
|
|
7158
7150
|
</div>
|
|
7159
7151
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7160
|
-
${
|
|
7152
|
+
${cr()}
|
|
7161
7153
|
</div>
|
|
7162
7154
|
</div>
|
|
7163
7155
|
|
|
@@ -7175,7 +7167,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7175
7167
|
</form>
|
|
7176
7168
|
</div>
|
|
7177
7169
|
</div>
|
|
7178
|
-
`}function
|
|
7170
|
+
`}function It(){return `
|
|
7179
7171
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7180
7172
|
<!-- Panel Header -->
|
|
7181
7173
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7257,7 +7249,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7257
7249
|
|
|
7258
7250
|
</div>
|
|
7259
7251
|
</div>
|
|
7260
|
-
`}function
|
|
7252
|
+
`}function Ct(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7261
7253
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7262
7254
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7263
7255
|
|
|
@@ -7799,21 +7791,21 @@ ${Q()}`}function Nt(e){return `
|
|
|
7799
7791
|
_rtEnabled = false;
|
|
7800
7792
|
});
|
|
7801
7793
|
</script>
|
|
7802
|
-
`}function
|
|
7794
|
+
`}function Mt(e){return `
|
|
7803
7795
|
const content = html\`
|
|
7804
7796
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
7805
|
-
${
|
|
7797
|
+
${$t(e)}
|
|
7806
7798
|
|
|
7807
7799
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
7808
7800
|
<!-- Request Panel -->
|
|
7809
|
-
${
|
|
7801
|
+
${qt(e)}
|
|
7810
7802
|
|
|
7811
7803
|
<!-- Result Panel -->
|
|
7812
|
-
${
|
|
7804
|
+
${It()}
|
|
7813
7805
|
</div>
|
|
7814
7806
|
</div>
|
|
7815
7807
|
|
|
7816
|
-
${
|
|
7808
|
+
${Ct(e)}
|
|
7817
7809
|
\`;
|
|
7818
7810
|
|
|
7819
7811
|
if (c.req.header('hx-request')) {
|
|
@@ -7823,11 +7815,11 @@ ${Q()}`}function Nt(e){return `
|
|
|
7823
7815
|
return c.html(Layout({
|
|
7824
7816
|
title: "${e.exportName} - Functions",
|
|
7825
7817
|
children: content
|
|
7826
|
-
}));`}function
|
|
7818
|
+
}));`}function Pt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
7827
7819
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
7828
|
-
${
|
|
7820
|
+
${Mt(n)}
|
|
7829
7821
|
});`).join(`
|
|
7830
|
-
`)}function
|
|
7822
|
+
`)}function Et(){return `
|
|
7831
7823
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
7832
7824
|
const r2Binding = (options as any).r2Binding;
|
|
7833
7825
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -7899,7 +7891,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7899
7891
|
`}function Dt(){return `
|
|
7900
7892
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
7901
7893
|
const parts = prefix.split('/').filter(Boolean);
|
|
7902
|
-
const breadcrumbs = [];
|
|
7894
|
+
const breadcrumbs: any[] = [];
|
|
7903
7895
|
let currentPath = '';
|
|
7904
7896
|
const visibleObjects = listed.objects.filter((obj: any) => !obj.key.endsWith('/.keep'));
|
|
7905
7897
|
|
|
@@ -8023,7 +8015,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8023
8015
|
</div>
|
|
8024
8016
|
\`;
|
|
8025
8017
|
};
|
|
8026
|
-
`}function
|
|
8018
|
+
`}function Ft(){return `
|
|
8027
8019
|
const handleStorageListRoute = async (c: any) => {
|
|
8028
8020
|
const bucket = getStorageBucket(c);
|
|
8029
8021
|
if (!bucket) {
|
|
@@ -8045,7 +8037,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8045
8037
|
|
|
8046
8038
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8047
8039
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8048
|
-
`}function
|
|
8040
|
+
`}function Ot(){return `
|
|
8049
8041
|
adminApp.post('/storage/upload', async (c) => {
|
|
8050
8042
|
const bucket = getStorageBucket(c);
|
|
8051
8043
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8063,7 +8055,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8063
8055
|
|
|
8064
8056
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8065
8057
|
});
|
|
8066
|
-
`}function
|
|
8058
|
+
`}function jt(){return `
|
|
8067
8059
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8068
8060
|
const bucket = getStorageBucket(c);
|
|
8069
8061
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8078,7 +8070,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8078
8070
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8079
8071
|
return c.html('');
|
|
8080
8072
|
});
|
|
8081
|
-
`}function
|
|
8073
|
+
`}function Vt(){return `
|
|
8082
8074
|
adminApp.post('/storage/directory', async (c) => {
|
|
8083
8075
|
const bucket = getStorageBucket(c);
|
|
8084
8076
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8104,7 +8096,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8104
8096
|
|
|
8105
8097
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8106
8098
|
});
|
|
8107
|
-
`}function
|
|
8099
|
+
`}function Bt(){return `
|
|
8108
8100
|
adminApp.get('/storage/download', async (c) => {
|
|
8109
8101
|
const bucket = getStorageBucket(c);
|
|
8110
8102
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8124,7 +8116,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8124
8116
|
|
|
8125
8117
|
return new Response(object.body, { headers });
|
|
8126
8118
|
});
|
|
8127
|
-
`}function
|
|
8119
|
+
`}function Ht(){return `
|
|
8128
8120
|
adminApp.get('/storage/preview', async (c) => {
|
|
8129
8121
|
const bucket = getStorageBucket(c);
|
|
8130
8122
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8142,25 +8134,25 @@ ${Q()}`}function Nt(e){return `
|
|
|
8142
8134
|
|
|
8143
8135
|
return new Response(object.body, { headers });
|
|
8144
8136
|
});
|
|
8145
|
-
`}function
|
|
8146
|
-
${Vt()}
|
|
8147
|
-
|
|
8137
|
+
`}function Wt(){return `
|
|
8148
8138
|
${Bt()}
|
|
8149
8139
|
|
|
8150
|
-
${
|
|
8140
|
+
${Ht()}
|
|
8151
8141
|
|
|
8152
8142
|
${Ot()}
|
|
8153
8143
|
|
|
8154
8144
|
${jt()}
|
|
8155
8145
|
|
|
8146
|
+
${Vt()}
|
|
8147
|
+
|
|
8148
|
+
${Ft()}
|
|
8149
|
+
`}function Lt(){return `
|
|
8156
8150
|
${Et()}
|
|
8157
|
-
`}function Wt(){return `
|
|
8158
|
-
${Pt()}
|
|
8159
8151
|
|
|
8160
8152
|
${Dt()}
|
|
8161
8153
|
|
|
8162
|
-
${
|
|
8163
|
-
`}function
|
|
8154
|
+
${Wt()}
|
|
8155
|
+
`}function zt(e,t){let n=ct(t);return `
|
|
8164
8156
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8165
8157
|
return html\`<!DOCTYPE html>
|
|
8166
8158
|
<html lang="en" data-theme="light">
|
|
@@ -8535,7 +8527,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8535
8527
|
</body>
|
|
8536
8528
|
</html>\`;
|
|
8537
8529
|
}
|
|
8538
|
-
`}function
|
|
8530
|
+
`}function Ut(){return `
|
|
8539
8531
|
// Auth Middleware
|
|
8540
8532
|
adminApp.use('*', async (c, next) => {
|
|
8541
8533
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -8594,7 +8586,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8594
8586
|
}
|
|
8595
8587
|
await next();
|
|
8596
8588
|
});
|
|
8597
|
-
`}function
|
|
8589
|
+
`}function Qt(e){return `
|
|
8598
8590
|
adminApp.get('/', (c) => {
|
|
8599
8591
|
return c.html(Layout({
|
|
8600
8592
|
title: "Admin Dashboard",
|
|
@@ -8611,7 +8603,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8611
8603
|
\`
|
|
8612
8604
|
}));
|
|
8613
8605
|
});
|
|
8614
|
-
`}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";
|
|
8615
8607
|
import { html, raw } from "hono/html";
|
|
8616
8608
|
import { drizzle } from "drizzle-orm/d1";
|
|
8617
8609
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8640,8 +8632,8 @@ ${f}
|
|
|
8640
8632
|
app.route('/admin', adminApp);
|
|
8641
8633
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8642
8634
|
}
|
|
8643
|
-
`}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
|
|
8644
|
-
`}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 br(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 yr(e){br(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)}: {
|
|
8645
8637
|
targetTable: ${h(i.targetTable)},
|
|
8646
8638
|
junctionTable: ${h(i.junctionTable)},
|
|
8647
8639
|
sourceField: ${h(i.sourceField??"")},
|
|
@@ -8654,7 +8646,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8654
8646
|
${t.map(n=>` ${n}`).join(`
|
|
8655
8647
|
`)}
|
|
8656
8648
|
} as const;
|
|
8657
|
-
`}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)}: {
|
|
8658
8650
|
kind: "one",
|
|
8659
8651
|
targetTable: ${h(i.targetTable)},
|
|
8660
8652
|
sourceField: ${h(i.field??"")},
|
|
@@ -8680,7 +8672,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8680
8672
|
${t.map(n=>` ${n}`).join(`
|
|
8681
8673
|
`)}
|
|
8682
8674
|
} as const;
|
|
8683
|
-
`}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[b,m]of Object.entries(s.columns)){let x=wr(b,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(b,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(b)}_unique_idx`;c.push(` t.uniqueIndex(${h(R)}).on(table.${b})`);}if(m.index){let R=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${M(b)}_idx`;c.push(` t.index(${h(R)}).on(table.${b})`);}u.push(` ${b}: ${x},`);}c.length>0?a.push(`export const ${i} = table(
|
|
8684
8676
|
${h(l)},
|
|
8685
8677
|
{
|
|
8686
8678
|
${u.join(`
|
|
@@ -8693,7 +8685,7 @@ ${c.join(`,
|
|
|
8693
8685
|
);`):a.push(`export const ${i} = table(${h(l)}, {
|
|
8694
8686
|
${u.join(`
|
|
8695
8687
|
`)}
|
|
8696
|
-
});`);let f=Object.entries(s.relations).filter(([,b])=>b.relation==="one"),d=Object.entries(s.relations).filter(([,b])=>b.relation==="many"),y=Object.entries(s.relations).filter(([,b])=>b.relation==="manyToMany");if(f.length===0&&d.length===0&&y.length===0)continue;let w=[];for(let[b,m]of f){let x=
|
|
8688
|
+
});`);let f=Object.entries(s.relations).filter(([,b])=>b.relation==="one"),d=Object.entries(s.relations).filter(([,b])=>b.relation==="many"),y=Object.entries(s.relations).filter(([,b])=>b.relation==="manyToMany");if(f.length===0&&d.length===0&&y.length===0)continue;let w=[];for(let[b,m]of f){let x=xr(i,s,m);w.push(` ${b}: one(${m.targetTable}, {
|
|
8697
8689
|
fields: [${i}.${x.sourceField}],
|
|
8698
8690
|
references: [${m.targetTable}.${x.targetField}],
|
|
8699
8691
|
}),`);}for(let[b,m]of d)w.push(` ${b}: many(${m.targetTable}),`);for(let[b,m]of y){if(!m.junctionTable)throw new Error(`manyToMany relation '${i}.${b}' is missing junctionTable after normalization.`);w.push(` ${b}: many(${m.junctionTable}),`);}o.push(`export const ${i}Relations = relations(${i}, ({ one, many }) => ({
|
|
@@ -8702,7 +8694,7 @@ ${w.join(`
|
|
|
8702
8694
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
8703
8695
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
8704
8696
|
import { relations } from "drizzle-orm";
|
|
8705
|
-
${
|
|
8697
|
+
${vr(r)}
|
|
8706
8698
|
${a.join(`
|
|
8707
8699
|
|
|
8708
8700
|
`)}
|
|
@@ -8711,10 +8703,10 @@ ${o.join(`
|
|
|
8711
8703
|
|
|
8712
8704
|
`)}
|
|
8713
8705
|
|
|
8714
|
-
${
|
|
8706
|
+
${kr(e)}
|
|
8715
8707
|
|
|
8716
|
-
${
|
|
8717
|
-
`}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({
|
|
8718
8710
|
${o.join(`
|
|
8719
8711
|
`)}
|
|
8720
8712
|
});
|
|
@@ -8728,7 +8720,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
8728
8720
|
`);}return `import { z } from "zod";
|
|
8729
8721
|
|
|
8730
8722
|
${t.join(`
|
|
8731
|
-
`)}`}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} = {
|
|
8732
8724
|
${o.join(`
|
|
8733
8725
|
`)}
|
|
8734
8726
|
};
|
|
@@ -8739,11 +8731,11 @@ ${i.join(`
|
|
|
8739
8731
|
};`);}return `${t.join(`
|
|
8740
8732
|
|
|
8741
8733
|
`)}
|
|
8742
|
-
`}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=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=$r(l,t.exportName),c=hr(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.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(path.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 promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await rn(a));continue}r.isFile()&&Dr.has(path.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__namespace.isCallExpression(n);){let i=n.expression;if(!g__namespace.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__namespace.isStringLiteral(l)||g__namespace.isNumericLiteral(l)?a=l.text:l.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===g__namespace.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__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||n.push(Er(r.initializer,r.name.text));return n}function Or(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function an(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?an(e.expression):null}function jr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return g__namespace.isStringLiteral(n)||g__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Vr(e,t){let n=g__namespace.createSourceFile(t,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(Or(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.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=path.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(path.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 promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.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=path.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=path.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=path.resolve(t,"client"),l=A(s,a);await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let u=path.resolve(t,"server.ts"),c=path.resolve(t,"client.ts"),f=path.resolve(t,"auth.config.ts"),d=path.resolve(t,"auth.schema.ts"),y=path.resolve(t,"drizzle.config.ts"),w=path.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=path.resolve(t,"admin.routes.ts"),$n=vn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source)),qn=xn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8743
|
-
`),...qn
|
|
8744
|
-
`),Bun.write(Nn
|
|
8745
|
-
`);return}process.stdout.write(`\u2705 Generated server/client in ${
|
|
8746
|
-
`);}async function
|
|
8747
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
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=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=Ir(l,t.exportName),c=yr(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let f=Ar(c,n),d=qr(c),y=Nr(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 Mr(e){return e.replaceAll("\\","/")}function A(e,t){let n=Mr(path.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 promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await an(a));continue}r.isFile()&&Fr.has(path.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__namespace.isCallExpression(n);){let i=n.expression;if(!g__namespace.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__namespace.isStringLiteral(l)||g__namespace.isNumericLiteral(l)?a=l.text:l.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===g__namespace.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__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||n.push(Or(r.initializer,r.name.text));return n}function Vr(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function on(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?on(e.expression):null}function Br(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return g__namespace.isStringLiteral(n)||g__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Hr(e,t){let n=g__namespace.createSourceFile(t,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(Vr(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.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=path.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 y=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,b=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(path.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 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 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 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 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:_r(u)}),a=t.exec(e);}return n}async function cn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.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=path.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=path.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=path.resolve(t,"client"),l=A(s,a);await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let u=path.resolve(t,"server.ts"),c=path.resolve(t,"client.ts"),f=path.resolve(t,"auth.config.ts"),d=path.resolve(t,"auth.schema.ts"),y=path.resolve(t,"drizzle.config.ts"),w=path.resolve(n,"wrangler.json"),b=await en(e),m=await un(e,b?[b.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=b?[Jr(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,Sn=ue(kn),An=it(e,T),Nn=_t(x,m,T),$n=path.resolve(t,"admin.routes.ts"),qn=Tn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source)),In=vn.map(k=>Bun.write(path.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(y,Sn),Bun.write(w,`${JSON.stringify(An,null,2)}
|
|
8736
|
+
`),Bun.write($n,Nn)]);let O=path.relative(o,f).replace(/\\/g,"/"),Cn=O.startsWith(".")?O:`./${O}`,j=path.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=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.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=zod.z.object({binding:zod.z.string().min(1),databaseName:zod.z.string().min(1),databaseId:zod.z.string().min(1),previewDatabaseId:zod.z.string().min(1).optional(),migrationsDir:zod.z.string().min(1).optional()}).strict(),mn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),gn=zod.z.object({binding:zod.z.string().min(1),bucketName:zod.z.string().min(1),previewBucketName:zod.z.string().min(1).optional(),jurisdiction:zod.z.string().min(1).optional()}).strict(),fn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),ea=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),className:zod.z.string().min(1).optional(),objectName:zod.z.string().min(1).optional(),subscribePath:zod.z.string().min(1).optional(),websocketPath:zod.z.string().min(1).optional(),protocol:zod.z.string().min(1).optional()}).strict(),ta=zod.z.object({scanDir:zod.z.string().min(1),outDir:zod.z.string().min(1),wranglerOutDir:zod.z.string().min(1).optional(),wranglerOutPath:zod.z.string().min(1).optional(),schema:zod.z.array(zod.z.string()).min(1),schemaDsl:zod.z.object({entry:zod.z.string().min(1),exportName:zod.z.string().min(1).optional(),outFile:zod.z.string().min(1).optional(),typesOutFile:zod.z.string().min(1).optional(),zodOutFile:zod.z.string().min(1).optional(),namingStrategy:zod.z.literal("camelToSnake").optional()}).strict().optional(),database:zod.z.union([pn,zod.z.array(pn).min(1)]),kv:zod.z.union([mn,zod.z.array(mn)]).optional(),r2:zod.z.union([gn,zod.z.array(gn)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(e=>typeof e=="object"&&e!==null),clientOptions:zod.z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:fn.optional(),realtime:ea.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().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,build:e.build??true}}async function q(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,i=ta.parse(o),s=aa(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}function la(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}async function F(e,t={}){let n=await q(e);if(t.build!==void 0&&(n.config.build=t.build),await dn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
8737
|
+
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
8738
|
+
`);}async function yn(e,t={}){if(await F(e,{build:t.build}),!t.watch)return;let n=await q(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await F(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
8739
|
+
`);}finally{r=false,a&&(a=false,await o());}};oa__default.default.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8748
8740
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8749
|
-
`);}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=path.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 commander.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").option("--no-build","Skip TypeScript build step").action(async e=>{await F(e.config,{build:e.build});});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).option("--no-build","Skip TypeScript build step").action(async e=>{await yn(e.config,{watch:e.watch,build:e.build});});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);});
|